@clickmax/webchat-react 0.0.0-stage → 12.5.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,3046 @@
1
+ 'use client';
2
+ import { jsx } from "react/jsx-runtime";
3
+ import { useEffect, useRef } from "react";
4
+
5
+
6
+ var __webpack_modules__ = {};
7
+ // The module cache
8
+ var __webpack_module_cache__ = {};
9
+ // The require function
10
+ function __webpack_require__(moduleId) {
11
+ // Check if module is in cache
12
+ var cachedModule = __webpack_module_cache__[moduleId];
13
+ if (cachedModule !== undefined) {
14
+ return cachedModule.exports;
15
+ }
16
+ // Create a new module (and put it into the cache)
17
+ var module = (__webpack_module_cache__[moduleId] = {
18
+ id: moduleId,
19
+ exports: {}
20
+ });
21
+ // Execute the module function
22
+ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
23
+
24
+ // Return the exports of the module
25
+ return module.exports;
26
+ }
27
+ // expose the modules object (__webpack_modules__)
28
+ __webpack_require__.m = __webpack_modules__;
29
+
30
+ // webpack/runtime/compat_get_default_export
31
+ (() => {
32
+ // getDefaultExport function for compatibility with non-ESM modules
33
+ __webpack_require__.n = (module) => {
34
+ var getter = module && module.__esModule ?
35
+ () => (module['default']) :
36
+ () => (module);
37
+ __webpack_require__.d(getter, { a: getter });
38
+ return getter;
39
+ };
40
+
41
+ })();
42
+ // webpack/runtime/define_property_getters
43
+ (() => {
44
+ __webpack_require__.d = (exports, definition) => {
45
+ for(var key in definition) {
46
+ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
47
+ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
48
+ }
49
+ }
50
+ };
51
+ })();
52
+ // webpack/runtime/esm_register_module
53
+ (() => {
54
+ __webpack_require__.add = function registerModules(modules) { Object.assign(__webpack_require__.m, modules) }
55
+
56
+ })();
57
+ // webpack/runtime/has_own_property
58
+ (() => {
59
+ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
60
+ })();
61
+ // webpack/runtime/module_chunk_loading
62
+ (() => {
63
+ __webpack_require__.b = new URL("./", import.meta.url);;
64
+
65
+ // object to store loaded and loading chunks
66
+ // undefined = chunk not loaded, null = chunk preloaded/prefetched
67
+ // [resolve, Promise] = chunk loading, 0 = chunk loaded
68
+ var installedChunks = {"410": 0,};
69
+ // no install chunk// no chunk on demand loading
70
+ // no external install chunk
71
+ // no on chunks loaded
72
+ // no HMR
73
+ // no HMR manifest
74
+
75
+ })();
76
+
77
+ __webpack_require__.add({
78
+ "./src/widget/styles/widget.scss?inline"(module, __webpack_exports__, __webpack_require__) {
79
+ __webpack_require__.d(__webpack_exports__, {
80
+ A: () => (__rspack_default_export)
81
+ });
82
+ /* import */ var _node_modules_pnpm_rsbuild_core_2_0_0_rc_0_emnapi_core_1_11_2_emnapi_runtime_1_11_3_core_js_3_49_0_node_modules_rsbuild_core_compiled_css_loader_noSourceMaps_js__rspack_import_0 = __webpack_require__("../../node_modules/.pnpm/@rsbuild+core@2.0.0-rc.0_@emnapi+core@1.11.2_@emnapi+runtime@1.11.3_core-js@3.49.0/node_modules/@rsbuild/core/compiled/css-loader/noSourceMaps.js");
83
+ /* import */ var _node_modules_pnpm_rsbuild_core_2_0_0_rc_0_emnapi_core_1_11_2_emnapi_runtime_1_11_3_core_js_3_49_0_node_modules_rsbuild_core_compiled_css_loader_noSourceMaps_js__rspack_import_0_default = /*#__PURE__*/__webpack_require__.n(_node_modules_pnpm_rsbuild_core_2_0_0_rc_0_emnapi_core_1_11_2_emnapi_runtime_1_11_3_core_js_3_49_0_node_modules_rsbuild_core_compiled_css_loader_noSourceMaps_js__rspack_import_0);
84
+ /* import */ var _node_modules_pnpm_rsbuild_core_2_0_0_rc_0_emnapi_core_1_11_2_emnapi_runtime_1_11_3_core_js_3_49_0_node_modules_rsbuild_core_compiled_css_loader_api_js__rspack_import_1 = __webpack_require__("../../node_modules/.pnpm/@rsbuild+core@2.0.0-rc.0_@emnapi+core@1.11.2_@emnapi+runtime@1.11.3_core-js@3.49.0/node_modules/@rsbuild/core/compiled/css-loader/api.js");
85
+ /* import */ var _node_modules_pnpm_rsbuild_core_2_0_0_rc_0_emnapi_core_1_11_2_emnapi_runtime_1_11_3_core_js_3_49_0_node_modules_rsbuild_core_compiled_css_loader_api_js__rspack_import_1_default = /*#__PURE__*/__webpack_require__.n(_node_modules_pnpm_rsbuild_core_2_0_0_rc_0_emnapi_core_1_11_2_emnapi_runtime_1_11_3_core_js_3_49_0_node_modules_rsbuild_core_compiled_css_loader_api_js__rspack_import_1);
86
+ /* import */ var _node_modules_pnpm_rsbuild_core_2_0_0_rc_0_emnapi_core_1_11_2_emnapi_runtime_1_11_3_core_js_3_49_0_node_modules_rsbuild_core_compiled_css_loader_getUrl_js__rspack_import_2 = __webpack_require__("../../node_modules/.pnpm/@rsbuild+core@2.0.0-rc.0_@emnapi+core@1.11.2_@emnapi+runtime@1.11.3_core-js@3.49.0/node_modules/@rsbuild/core/compiled/css-loader/getUrl.js");
87
+ /* import */ var _node_modules_pnpm_rsbuild_core_2_0_0_rc_0_emnapi_core_1_11_2_emnapi_runtime_1_11_3_core_js_3_49_0_node_modules_rsbuild_core_compiled_css_loader_getUrl_js__rspack_import_2_default = /*#__PURE__*/__webpack_require__.n(_node_modules_pnpm_rsbuild_core_2_0_0_rc_0_emnapi_core_1_11_2_emnapi_runtime_1_11_3_core_js_3_49_0_node_modules_rsbuild_core_compiled_css_loader_getUrl_js__rspack_import_2);
88
+ // Imports
89
+
90
+
91
+
92
+ var ___CSS_LOADER_URL_IMPORT_0___ = new URL(/* asset import */__webpack_require__("data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 width=%2780%27 height=%2780%27 viewBox=%270 0 80 80%27%3E%3Cg fill=%27none%27 stroke=%27%23000000%27 stroke-opacity=%270.03%27 stroke-width=%271.5%27%3E%3Ccircle cx=%2720%27 cy=%2720%27 r=%276%27/%3E%3Cpath d=%27M52 14l6 6-6 6-6-6z%27/%3E%3Cpath d=%27M12 54h10M17 49v10%27/%3E%3Ccircle cx=%2760%27 cy=%2758%27 r=%275%27/%3E%3C/g%3E%3C/svg%3E"), __webpack_require__.b);
93
+ var ___CSS_LOADER_EXPORT___ = _node_modules_pnpm_rsbuild_core_2_0_0_rc_0_emnapi_core_1_11_2_emnapi_runtime_1_11_3_core_js_3_49_0_node_modules_rsbuild_core_compiled_css_loader_api_js__rspack_import_1_default()((_node_modules_pnpm_rsbuild_core_2_0_0_rc_0_emnapi_core_1_11_2_emnapi_runtime_1_11_3_core_js_3_49_0_node_modules_rsbuild_core_compiled_css_loader_noSourceMaps_js__rspack_import_0_default()));
94
+ var ___CSS_LOADER_URL_REPLACEMENT_0___ = _node_modules_pnpm_rsbuild_core_2_0_0_rc_0_emnapi_core_1_11_2_emnapi_runtime_1_11_3_core_js_3_49_0_node_modules_rsbuild_core_compiled_css_loader_getUrl_js__rspack_import_2_default()(___CSS_LOADER_URL_IMPORT_0___);
95
+ // Module
96
+ ___CSS_LOADER_EXPORT___.push([module.id, `.cx-livechat{--cx-livechat-accent:#111827;--cx-livechat-accent-fg:#fff;--cx-livechat-bg:#fff;--cx-livechat-border:#e5e7eb;--cx-livechat-bubble-agent-bg:#f3f4f6;--cx-livechat-fg:#111827;--cx-livechat-link:#2563eb;--cx-livechat-muted:#6b7280;--cx-livechat-radius:16px;color:var(--cx-livechat-fg);z-index:2147483000;flex-direction:column;align-items:flex-end;gap:12px;font-family:Inter,system-ui,sans-serif;display:flex;position:fixed;bottom:20px;right:20px}.cx-livechat[data-cx-theme=dark]{--cx-livechat-bg:#0f172a;--cx-livechat-border:#334155;--cx-livechat-bubble-agent-bg:#1e293b;--cx-livechat-fg:#f8fafc;--cx-livechat-link:#60a5fa;--cx-livechat-muted:#94a3b8}.cx-livechat--left{align-items:flex-start;left:20px;right:auto}.cx-livechat--fullscreen{align-items:stretch;gap:0;padding:0;inset:0}.cx-livechat--fullscreen .cx-livechat__dock{display:none}.cx-livechat--embed{z-index:auto;position:absolute}.cx-livechat--embed.cx-livechat--fullscreen .cx-livechat__window{height:100%}.cx-livechat--fullscreen .cx-livechat__close{display:none}.cx-livechat--fullscreen .cx-livechat__window{box-shadow:none;background-color:#f5f2ed;background-image:url(${___CSS_LOADER_URL_REPLACEMENT_0___});border:none;border-radius:0;width:100%;max-width:none;height:100dvh}.cx-livechat--fullscreen .cx-livechat__progress,.cx-livechat--fullscreen .cx-livechat__messages,.cx-livechat--fullscreen .cx-livechat__consent,.cx-livechat--fullscreen .cx-livechat__footer{box-sizing:border-box;align-self:center;width:100%;max-width:760px}.cx-livechat--fullscreen .cx-livechat__progress{background:0 0;border-bottom:none;padding-top:14px}.cx-livechat--fullscreen .cx-livechat__bubble--agent{background:#fff;box-shadow:0 1px 1.5px #0000000d}.cx-livechat--fullscreen .cx-livechat__bubble--visitor{background:#e9f1ec;background:color-mix(in srgb, var(--cx-livechat-accent) 14%, #fff);color:var(--cx-livechat-fg)}.cx-livechat--fullscreen .cx-livechat__footer{border-top:none;padding:10px 16px 18px}.cx-livechat--fullscreen .cx-livechat__input{background:#fff;border-color:#0000;border-radius:999px;padding:12px 18px;box-shadow:0 1px 2px #0000000f}.cx-livechat--fullscreen .cx-livechat__prechat .cx-livechat__input{border-radius:14px}.cx-livechat--fullscreen .cx-livechat__send{border-radius:50%;width:46px;height:46px}.cx-livechat--fullscreen .cx-livechat__button{border-radius:999px;padding:13px}.cx-livechat--fullscreen .cx-livechat__consent{background:#fff;border-radius:12px;margin-bottom:8px;padding:12px 16px;box-shadow:0 1px 2px #0000000d}.cx-livechat__dock{flex-direction:column;align-items:flex-end;gap:10px;display:flex}.cx-livechat--left .cx-livechat__dock{align-items:flex-start}.cx-livechat__tooltip{background:var(--cx-livechat-bg);color:var(--cx-livechat-fg);border-radius:12px;max-width:220px;padding:9px 13px;font-size:.8rem;font-weight:500;position:relative;box-shadow:0 6px 20px #0000002e}.cx-livechat__tooltip:after{background:var(--cx-livechat-bg);content:"";border-radius:2px;width:10px;height:10px;position:absolute;bottom:-4px;right:16px;transform:rotate(45deg)}.cx-livechat--left .cx-livechat__tooltip:after{left:16px;right:auto}.cx-livechat__launcher-wrap{position:relative}.cx-livechat__launcher{background:var(--cx-livechat-accent);color:var(--cx-livechat-accent-fg);cursor:pointer;border:none;border-radius:50%;justify-content:center;align-items:center;width:58px;height:58px;transition:transform .15s;display:flex;box-shadow:0 8px 28px #0000004d}.cx-livechat__launcher:hover{transform:scale(1.06)}.cx-livechat__launcher--bounce{animation:2.4s .3s infinite cx-lc-bounce}.cx-livechat__launcher--pulse{animation:1.8s ease-in-out infinite cx-lc-pulse}.cx-livechat__launcher--slide{animation:3s infinite cx-lc-slide}.cx-livechat__launcher-icon{justify-content:center;align-items:center;width:45%;height:45%;display:flex}.cx-livechat__launcher-icon svg{width:100%;height:100%}.cx-livechat__badge{border:2px solid var(--cx-livechat-bg);color:#14130f;background:#d9ff00;border-radius:50%;justify-content:center;align-items:center;width:20px;height:20px;font-size:.7rem;font-weight:800;display:flex;position:absolute;top:-3px;right:-3px}.cx-livechat__window{background:var(--cx-livechat-bg);border:1px solid var(--cx-livechat-border);border-radius:var(--cx-livechat-radius);flex-direction:column;width:min(370px,100vw - 40px);height:min(560px,100dvh - 110px);display:flex;position:relative;overflow:hidden;box-shadow:0 16px 48px #00000038}.cx-livechat__window--dragover:after{background:color-mix(in srgb, var(--cx-livechat-bg) 88%, transparent);border:2px dashed var(--cx-livechat-accent);border-radius:inherit;color:var(--cx-livechat-fg);content:attr(data-drop-label);pointer-events:none;z-index:5;justify-content:center;align-items:center;font-weight:600;display:flex;position:absolute;inset:0}.cx-livechat__header{background:var(--cx-livechat-accent);color:var(--cx-livechat-accent-fg);align-items:center;gap:10px;padding:14px 16px;display:flex}.cx-livechat__avatar{object-fit:cover;border-radius:50%;width:32px;height:32px}.cx-livechat__avatar--clickable{cursor:pointer;transition:transform .12s}.cx-livechat__avatar--clickable:hover{transform:scale(1.06)}.cx-livechat__fontcontrols{align-items:center;gap:4px;display:flex}.cx-livechat__fontbtn{color:var(--cx-livechat-accent-fg);cursor:pointer;background:#ffffff29;border:none;border-radius:8px;padding:4px 8px;font-family:inherit;font-weight:700;line-height:1}.cx-livechat__fontbtn:hover{background:#ffffff4d}.cx-livechat__fontbtn--sm{font-size:.72rem}.cx-livechat__fontbtn--lg{font-size:1.02rem}.cx-livechat__progress{background:var(--cx-livechat-bg);border-bottom:1px solid var(--cx-livechat-border);align-items:center;gap:10px;padding:10px 16px;display:flex}.cx-livechat__progress-track{flex:1;gap:4px;display:flex}.cx-livechat__progress-seg{background:var(--cx-livechat-border);border-radius:999px;flex:1;height:5px;transition:background .2s,opacity .2s}.cx-livechat__progress-seg--done{background:var(--cx-livechat-accent)}.cx-livechat__progress-seg--active{background:var(--cx-livechat-accent);opacity:.5}.cx-livechat__progress-count{color:var(--cx-livechat-muted);white-space:nowrap;font-size:.8rem;font-weight:500}.cx-livechat__progress-count b{color:var(--cx-livechat-fg);font-size:1.15em;font-weight:700}.cx-livechat__consent{background:var(--cx-livechat-bg);color:var(--cx-livechat-muted);align-items:flex-start;gap:8px;padding:10px 16px;font-size:.8rem;line-height:1.4;display:flex}.cx-livechat__consent input{accent-color:var(--cx-livechat-accent);flex-shrink:0;margin:2px 0 0}.cx-livechat__consent a{color:var(--cx-livechat-accent);text-decoration:underline}.cx-livechat__consent--flash{animation:.5s cx-lc-consent-flash}.cx-livechat__lightbox{cursor:zoom-out;z-index:10;background:#000c;justify-content:center;align-items:center;padding:24px;display:flex;position:fixed;inset:0}.cx-livechat__lightbox-img{object-fit:contain;border-radius:16px;max-width:min(90vw,520px);max-height:90vh}.cx-livechat__heading{flex-direction:column;flex:1;min-width:0;display:flex}.cx-livechat__title{text-overflow:ellipsis;white-space:nowrap;font-size:.95rem;font-weight:600;overflow:hidden}.cx-livechat__subtitle{opacity:.85;text-overflow:ellipsis;white-space:nowrap;font-size:.75rem;overflow:hidden}.cx-livechat__close{color:inherit;cursor:pointer;opacity:.85;background:0 0;border:none;padding:4px;display:flex}.cx-livechat__close:hover{opacity:1}.cx-livechat__close svg{width:18px;height:18px}.cx-livechat__messages{font-size:calc(.9rem*var(--cx-livechat-font-scale,1));flex-direction:column;flex:1;gap:6px;padding:16px;display:flex;overflow-y:auto}.cx-livechat__row{gap:8px;max-width:88%;display:flex}.cx-livechat__row--agent{align-self:flex-start;align-items:flex-end}.cx-livechat__row--visitor{align-self:flex-end}.cx-livechat__row-avatar{flex-shrink:0;align-self:flex-end;width:26px;height:26px;display:none}.cx-livechat__row-avatar img{object-fit:cover;border-radius:50%;width:100%;height:100%}.cx-livechat--fullscreen .cx-livechat__row-avatar{display:block}.cx-livechat__bubble{overflow-wrap:break-word;white-space:pre-wrap;border-radius:14px;min-width:0;padding:7px 11px 5px;font-size:1em;line-height:1.4}.cx-livechat__bubble--agent{background:var(--cx-livechat-bubble-agent-bg);color:var(--cx-livechat-fg);border-bottom-left-radius:4px}.cx-livechat__bubble--visitor{background:var(--cx-livechat-accent);color:var(--cx-livechat-accent-fg);border-bottom-right-radius:4px}.cx-livechat__bubble--pending{opacity:.65}.cx-livechat__bubble--failed{opacity:.65;text-decoration:line-through}.cx-livechat__bubble-name{color:var(--cx-livechat-accent);margin-bottom:1px;font-size:.78em;font-weight:700}.cx-livechat__bubble-time{opacity:.45;text-align:right;margin-top:3px;font-size:.66em;line-height:1;display:block}.cx-livechat__note{color:var(--cx-livechat-fg);opacity:.6;text-align:center;align-self:center;max-width:88%;margin:4px 12px;font-size:.78em;line-height:1.35}.cx-livechat__funnel-continue{background:var(--cx-livechat-accent);color:var(--cx-livechat-accent-fg);cursor:pointer;border:none;border-radius:999px;align-self:center;min-width:160px;margin:8px 12px 4px;padding:11px 22px;font-family:inherit;font-size:.95em;font-weight:600}.cx-livechat__funnel-continue:hover{filter:brightness(1.08)}.cx-livechat__funnel-continue:focus-visible{outline:2px solid var(--cx-livechat-accent);outline-offset:3px}.cx-livechat__typing{background:var(--cx-livechat-bubble-agent-bg);border-radius:14px 14px 14px 4px;align-self:flex-start;gap:4px;padding:12px 14px;display:flex}.cx-livechat__typing span{background:var(--cx-livechat-fg);opacity:.4;border-radius:50%;width:7px;height:7px;animation:1.2s ease-in-out infinite cx-lc-typing}.cx-livechat__typing span:nth-child(2){animation-delay:.18s}.cx-livechat__typing span:nth-child(3){animation-delay:.36s}.cx-livechat__footer{border-top:1px solid var(--cx-livechat-border);font-size:calc(.9rem*var(--cx-livechat-font-scale,1));padding:12px}.cx-livechat__prechat{flex-direction:column;gap:8px;display:flex}.cx-livechat__options{flex-direction:column;gap:6px;display:flex}.cx-livechat__option{background:var(--cx-livechat-bg);border:1.5px solid var(--cx-livechat-accent);color:var(--cx-livechat-accent);cursor:pointer;text-align:left;border-radius:10px;padding:9px 13px;font-family:inherit;font-size:.95em;font-weight:500;transition:background .12s,color .12s}.cx-livechat__option:hover{background:var(--cx-livechat-accent);color:var(--cx-livechat-accent-fg)}.cx-livechat__input{background:var(--cx-livechat-bg);border:1px solid var(--cx-livechat-border);box-sizing:border-box;color:var(--cx-livechat-fg);border-radius:10px;outline:none;width:100%;padding:10px 12px;font-size:1em}.cx-livechat__input:focus{border-color:var(--cx-livechat-accent)}.cx-livechat__input::placeholder{color:var(--cx-livechat-muted)}.cx-livechat__error{color:#dc2626;margin:0;font-size:.8rem}.cx-livechat__button{background:var(--cx-livechat-accent);color:var(--cx-livechat-accent-fg);cursor:pointer;border:none;border-radius:10px;padding:10px 12px;font-size:.9rem;font-weight:600}.cx-livechat__button:hover{filter:brightness(1.08)}.cx-livechat__composer{align-items:center;gap:8px;display:flex}.cx-livechat__composer .cx-livechat__input{flex:1}.cx-livechat__send{background:var(--cx-livechat-accent);color:var(--cx-livechat-accent-fg);cursor:pointer;border:none;border-radius:10px;justify-content:center;align-items:center;width:44px;height:40px;display:flex}.cx-livechat__send svg{width:18px;height:18px}.cx-livechat__attach{border:1px solid var(--cx-livechat-border);color:var(--cx-livechat-muted);cursor:pointer;background:0 0;border-radius:10px;flex-shrink:0;justify-content:center;align-items:center;width:40px;height:40px;display:flex}.cx-livechat__attach:hover{border-color:var(--cx-livechat-accent);color:var(--cx-livechat-accent)}.cx-livechat__attach svg{width:18px;height:18px}.cx-livechat--fullscreen .cx-livechat__attach{background:#fff;border-color:#0000;border-radius:50%;width:46px;height:46px;box-shadow:0 1px 2px #0000000f}.cx-livechat__attachments{flex-wrap:wrap;align-items:center;gap:6px;margin-bottom:8px;display:flex}.cx-livechat__attachments:empty{display:none}.cx-livechat__chip{background:var(--cx-livechat-bubble-agent-bg);color:var(--cx-livechat-fg);border-radius:999px;align-items:center;gap:6px;max-width:100%;padding:4px 6px 4px 10px;font-size:.8em;display:inline-flex}.cx-livechat__chip--uploading{opacity:.6}.cx-livechat__thumb{background:var(--cx-livechat-bubble-agent-bg);border-radius:10px;flex-shrink:0;width:56px;height:56px;position:relative;overflow:hidden}.cx-livechat__thumb .cx-livechat__chip-remove{color:#fff;opacity:1;background:#0009;position:absolute;top:3px;right:3px}.cx-livechat__thumb.cx-livechat__chip--uploading:after{content:"";border:2px solid #ffffffe6;border-top-color:#0000;border-radius:50%;width:18px;height:18px;animation:.8s linear infinite cx-lc-spin;position:absolute;top:calc(50% - 11px);left:calc(50% - 11px)}.cx-livechat__thumb-media{object-fit:cover;width:100%;height:100%;display:block}.cx-livechat__thumb-play{color:#fff;background:#0000008c;border-radius:50%;width:18px;height:18px;padding:3px;display:flex;position:absolute;bottom:4px;left:4px}.cx-livechat__thumb-play svg{width:100%;height:100%}.cx-livechat__chip-name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.cx-livechat__chip-remove{color:inherit;cursor:pointer;opacity:.7;background:0 0;border:none;border-radius:50%;justify-content:center;align-items:center;width:18px;height:18px;padding:0;display:flex}.cx-livechat__chip-remove:hover{opacity:1}.cx-livechat__chip-remove svg{width:12px;height:12px}.cx-livechat__bubble-attachments{flex-direction:column;gap:4px;margin-top:6px;display:flex}.cx-livechat__bubble-attachment{background:#ffffff29;border-radius:8px;align-items:center;gap:6px;padding:4px 8px;font-size:.85em;display:flex}.cx-livechat__bubble-attachment svg{flex-shrink:0;width:14px;height:14px}.cx-livechat__bubble-attachment span{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.cx-livechat__bubble--agent .cx-livechat__bubble-attachment{background:#0000000f}.cx-livechat__bubble-media{display:block}.cx-livechat button.cx-livechat__bubble-media{cursor:zoom-in;background:0 0;border:none;padding:0}.cx-livechat__bubble-image,.cx-livechat__bubble-video{object-fit:cover;border-radius:8px;max-width:100%;max-height:240px;display:block}.cx-livechat__bubble-link{color:var(--cx-livechat-link);overflow-wrap:anywhere;text-decoration:underline}.cx-livechat__bubble--visitor .cx-livechat__bubble-link{color:inherit}.cx-livechat--fullscreen .cx-livechat__bubble--visitor .cx-livechat__bubble-link{color:var(--cx-livechat-link)}.cx-livechat__bubble-file{color:inherit;text-decoration:none}.cx-livechat__bubble-file:hover span{text-decoration:underline}@keyframes cx-lc-spin{to{transform:rotate(360deg)}}@keyframes cx-lc-bounce{0%,25%,to{transform:translateY(0)}10%{transform:translateY(-9px)}18%{transform:translateY(-4px)}}@keyframes cx-lc-pulse{0%,to{box-shadow:0 8px 28px #0000004d}50%{box-shadow:0 8px 28px #0000004d,0 0 0 10px #0000000f}}@keyframes cx-lc-slide{0%,70%,to{transform:translate(0)}80%{transform:translate(7px)}90%{transform:translate(0)}}@keyframes cx-lc-typing{0%,60%,to{opacity:.4;transform:translateY(0)}30%{opacity:1;transform:translateY(-4px)}}@keyframes cx-lc-consent-flash{0%,to{background:var(--cx-livechat-bg)}30%{background:#dc262624}}`, ""]);
97
+ // Exports
98
+ /* export default */ const __rspack_default_export = (___CSS_LOADER_EXPORT___.toString());
99
+
100
+
101
+ },
102
+ "data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 width=%2780%27 height=%2780%27 viewBox=%270 0 80 80%27%3E%3Cg fill=%27none%27 stroke=%27%23000000%27 stroke-opacity=%270.03%27 stroke-width=%271.5%27%3E%3Ccircle cx=%2720%27 cy=%2720%27 r=%276%27/%3E%3Cpath d=%27M52 14l6 6-6 6-6-6z%27/%3E%3Cpath d=%27M12 54h10M17 49v10%27/%3E%3Ccircle cx=%2760%27 cy=%2758%27 r=%275%27/%3E%3C/g%3E%3C/svg%3E"(module) {
103
+ module.exports = "data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 width=%2780%27 height=%2780%27 viewBox=%270 0 80 80%27%3E%3Cg fill=%27none%27 stroke=%27%23000000%27 stroke-opacity=%270.03%27 stroke-width=%271.5%27%3E%3Ccircle cx=%2720%27 cy=%2720%27 r=%276%27/%3E%3Cpath d=%27M52 14l6 6-6 6-6-6z%27/%3E%3Cpath d=%27M12 54h10M17 49v10%27/%3E%3Ccircle cx=%2760%27 cy=%2758%27 r=%275%27/%3E%3C/g%3E%3C/svg%3E";
104
+
105
+ },
106
+ "../../node_modules/.pnpm/@rsbuild+core@2.0.0-rc.0_@emnapi+core@1.11.2_@emnapi+runtime@1.11.3_core-js@3.49.0/node_modules/@rsbuild/core/compiled/css-loader/api.js"(module) {
107
+
108
+
109
+ /*
110
+ MIT License http://www.opensource.org/licenses/mit-license.php
111
+ Author Tobias Koppers @sokra
112
+ */
113
+ module.exports = function (cssWithMappingToString) {
114
+ var list = [];
115
+
116
+ // return the list of modules as css string
117
+ list.toString = function toString() {
118
+ return this.map(function (item) {
119
+ var content = "";
120
+ var needLayer = typeof item[5] !== "undefined";
121
+ if (item[4]) {
122
+ content += "@supports (".concat(item[4], ") {");
123
+ }
124
+ if (item[2]) {
125
+ content += "@media ".concat(item[2], " {");
126
+ }
127
+ if (needLayer) {
128
+ content += "@layer".concat(item[5].length > 0 ? " ".concat(item[5]) : "", " {");
129
+ }
130
+ content += cssWithMappingToString(item);
131
+ if (needLayer) {
132
+ content += "}";
133
+ }
134
+ if (item[2]) {
135
+ content += "}";
136
+ }
137
+ if (item[4]) {
138
+ content += "}";
139
+ }
140
+ return content;
141
+ }).join("");
142
+ };
143
+
144
+ // import a list of modules into the list
145
+ list.i = function i(modules, media, dedupe, supports, layer) {
146
+ if (typeof modules === "string") {
147
+ modules = [[null, modules, undefined]];
148
+ }
149
+ var alreadyImportedModules = {};
150
+ if (dedupe) {
151
+ for (var k = 0; k < this.length; k++) {
152
+ var id = this[k][0];
153
+ if (id != null) {
154
+ alreadyImportedModules[id] = true;
155
+ }
156
+ }
157
+ }
158
+ for (var _k = 0; _k < modules.length; _k++) {
159
+ var item = [].concat(modules[_k]);
160
+ if (dedupe && alreadyImportedModules[item[0]]) {
161
+ continue;
162
+ }
163
+ if (typeof layer !== "undefined") {
164
+ if (typeof item[5] === "undefined") {
165
+ item[5] = layer;
166
+ } else {
167
+ item[1] = "@layer".concat(item[5].length > 0 ? " ".concat(item[5]) : "", " {").concat(item[1], "}");
168
+ item[5] = layer;
169
+ }
170
+ }
171
+ if (media) {
172
+ if (!item[2]) {
173
+ item[2] = media;
174
+ } else {
175
+ item[1] = "@media ".concat(item[2], " {").concat(item[1], "}");
176
+ item[2] = media;
177
+ }
178
+ }
179
+ if (supports) {
180
+ if (!item[4]) {
181
+ item[4] = "".concat(supports);
182
+ } else {
183
+ item[1] = "@supports (".concat(item[4], ") {").concat(item[1], "}");
184
+ item[4] = supports;
185
+ }
186
+ }
187
+ list.push(item);
188
+ }
189
+ };
190
+ return list;
191
+ };
192
+
193
+ },
194
+ "../../node_modules/.pnpm/@rsbuild+core@2.0.0-rc.0_@emnapi+core@1.11.2_@emnapi+runtime@1.11.3_core-js@3.49.0/node_modules/@rsbuild/core/compiled/css-loader/getUrl.js"(module) {
195
+
196
+
197
+ module.exports = function (url, options) {
198
+ if (!options) {
199
+ options = {};
200
+ }
201
+ if (!url) {
202
+ return url;
203
+ }
204
+ url = String(url.__esModule ? url.default : url);
205
+
206
+ // If url is already wrapped in quotes, remove them
207
+ if (/^['"].*['"]$/.test(url)) {
208
+ url = url.slice(1, -1);
209
+ }
210
+ if (options.hash) {
211
+ url += options.hash;
212
+ }
213
+
214
+ // Should url be wrapped?
215
+ // See https://drafts.csswg.org/css-values-3/#urls
216
+ if (/["'() \t\n]|(%20)/.test(url) || options.needQuotes) {
217
+ return "\"".concat(url.replace(/"/g, '\\"').replace(/\n/g, "\\n"), "\"");
218
+ }
219
+ return url;
220
+ };
221
+
222
+ },
223
+ "../../node_modules/.pnpm/@rsbuild+core@2.0.0-rc.0_@emnapi+core@1.11.2_@emnapi+runtime@1.11.3_core-js@3.49.0/node_modules/@rsbuild/core/compiled/css-loader/noSourceMaps.js"(module) {
224
+
225
+
226
+ module.exports = function (i) {
227
+ return i[1];
228
+ };
229
+
230
+ },
231
+ });
232
+
233
+
234
+ /** Runtime guard for an attachment reference (server upload response and host `send` payload). */ function isLiveChatAttachment(value) {
235
+ if (typeof value !== 'object' || value === null) return false;
236
+ const { fileId, name, mimeType, size } = value;
237
+ return typeof fileId === 'string' && fileId.trim().length > 0 && typeof name === 'string' && name.trim().length > 0 && typeof mimeType === 'string' && typeof size === 'number' && Number.isInteger(size) && size >= 0;
238
+ }
239
+ // Endpoints públicos expostos pelo api-gateway (`/sdk/webchat/*` → hermes-api).
240
+ function baseUrl(cx, apiOverride, channelId) {
241
+ const origin = (apiOverride || cx.apiUrl).replace(/\/+$/, '');
242
+ return `${origin}/sdk/webchat/${encodeURIComponent(channelId)}`;
243
+ }
244
+ /**
245
+ * `session` (FLOWS-2457): identidade assinada do usuário logado. Vai na query (GET simples,
246
+ * sem preflight) como `visitorHash, identityName, identityEmail, identitySignature`; o servidor
247
+ * ecoa `identity` na resposta SÓ se o HMAC conferir — é esse eco que o widget usa para pular o
248
+ * `capture`, nunca o que foi enviado.
249
+ */ async function fetchLiveChatConfig(cx, channelId, apiOverride, session) {
250
+ let url = `${baseUrl(cx, apiOverride, channelId)}/config`;
251
+ if (session) {
252
+ const query = new URLSearchParams({
253
+ visitorHash: session.visitorHash,
254
+ identityName: session.identity.name,
255
+ identityEmail: session.identity.email,
256
+ identitySignature: session.identity.signature
257
+ });
258
+ url += `?${query}`;
259
+ }
260
+ const response = await fetch(url);
261
+ if (!response.ok) {
262
+ throw new Error(`LiveChat config request failed with status ${response.status}`);
263
+ }
264
+ return response.json();
265
+ }
266
+ async function sendLiveChatMessage(cx, channelId, body, apiOverride) {
267
+ const response = await fetch(`${baseUrl(cx, apiOverride, channelId)}/messages`, {
268
+ method: 'POST',
269
+ headers: {
270
+ 'Content-Type': 'application/json',
271
+ 'x-clickmax-sdk': 'browser'
272
+ },
273
+ body: JSON.stringify(body)
274
+ });
275
+ if (!response.ok) {
276
+ throw new Error(`LiveChat send request failed with status ${response.status}`);
277
+ }
278
+ return true;
279
+ }
280
+ /**
281
+ * FLOWS-2457: sobe um anexo do visitante (multipart, campo `file`) e devolve a referência que
282
+ * vai em `attachments` da próxima mensagem. Sem header customizado de propósito: `FormData`
283
+ * é content-type CORS-safelisted, então o POST sai como simple request (sem preflight), como o
284
+ * GET de polling. Tipo/tamanho são validados no servidor (10 MB, 25 MB para vídeo); o widget
285
+ * pré-checa os dois (`checkAttachmentFile`) só para não gastar o upload.
286
+ */ async function uploadLiveChatAttachment(cx, channelId, visitorHash, file, apiOverride) {
287
+ const form = new FormData();
288
+ form.append('file', file, file.name);
289
+ const query = new URLSearchParams({
290
+ visitorHash
291
+ });
292
+ const response = await fetch(`${baseUrl(cx, apiOverride, channelId)}/attachments?${query}`, {
293
+ method: 'POST',
294
+ body: form
295
+ });
296
+ if (!response.ok) {
297
+ throw new Error(`LiveChat attachment upload failed with status ${response.status}`);
298
+ }
299
+ const attachment = await response.json();
300
+ if (!isLiveChatAttachment(attachment)) {
301
+ throw new Error('LiveChat attachment upload returned an invalid response');
302
+ }
303
+ return attachment;
304
+ }
305
+ /**
306
+ * Solicita o handoff IA→atendente quando o fluxo do bot chega a um nó `handoff`
307
+ * (PM-3584). Envia o `nodeId` (o backend resolve o `assignTo` server-side a partir
308
+ * do `preChatFlow` persistido), os dados capturados pelo pré-chat (`visitor`, para
309
+ * criar o lead num fluxo só de cliques) e o `botMessages` para backfillar o
310
+ * transcript — este último APENAS quando este POST é o primeiro contato com o
311
+ * servidor (nenhuma mensagem `/messages` esvaziou o buffer antes).
312
+ */ async function requestLiveChatHandoff(cx, channelId, body, apiOverride) {
313
+ const response = await fetch(`${baseUrl(cx, apiOverride, channelId)}/handoff`, {
314
+ method: 'POST',
315
+ headers: {
316
+ 'Content-Type': 'application/json',
317
+ 'x-clickmax-sdk': 'browser'
318
+ },
319
+ body: JSON.stringify(body)
320
+ });
321
+ if (!response.ok) {
322
+ throw new Error(`LiveChat handoff request failed with status ${response.status}`);
323
+ }
324
+ return true;
325
+ }
326
+ /** Classifica a resposta livre do visitante (nó de IA) → id do ramo (ou null = fallback). */ async function classifyLiveChat(cx, channelId, body, apiOverride) {
327
+ const response = await fetch(`${baseUrl(cx, apiOverride, channelId)}/classify`, {
328
+ method: 'POST',
329
+ headers: {
330
+ 'Content-Type': 'application/json',
331
+ 'x-clickmax-sdk': 'browser'
332
+ },
333
+ body: JSON.stringify(body)
334
+ });
335
+ if (!response.ok) {
336
+ throw new Error(`LiveChat classify request failed with status ${response.status}`);
337
+ }
338
+ return response.json();
339
+ }
340
+ // GET sem headers customizados = simple request (não dispara preflight CORS).
341
+ async function pollLiveChatMessages(cx, channelId, visitorHash, since, apiOverride) {
342
+ const query = new URLSearchParams({
343
+ visitorHash
344
+ });
345
+ if (since) query.set('since', since);
346
+ const response = await fetch(`${baseUrl(cx, apiOverride, channelId)}/messages?${query}`);
347
+ if (!response.ok) {
348
+ throw new Error(`LiveChat poll request failed with status ${response.status}`);
349
+ }
350
+ return response.json();
351
+ }
352
+ /**
353
+ * Registra um evento do webchat no funil e devolve o destino do gatilho conectado (se houver).
354
+ * `funnelId`/`nodeId` vêm de `cm_funnel`/`cm_node` da URL; ausentes, o servidor resolve o nó
355
+ * pelo canal (reverse lookup). Quem chama engole a falha: o funil nunca quebra a conversa.
356
+ */ async function sendFunnelEvent(cx, channelId, body, apiOverride) {
357
+ const response = await fetch(`${baseUrl(cx, apiOverride, channelId)}/funnel-events`, {
358
+ method: 'POST',
359
+ headers: {
360
+ 'Content-Type': 'application/json',
361
+ 'x-clickmax-sdk': 'browser'
362
+ },
363
+ body: JSON.stringify(body)
364
+ });
365
+ if (!response.ok) {
366
+ throw new Error(`LiveChat funnel event request failed with status ${response.status}`);
367
+ }
368
+ return response.json();
369
+ }
370
+ /** Teto de uma remessa do roteiro; estourado, o lote volta para a próxima remessa. */ const FLOW_SESSION_TIMEOUT_MS = 10000;
371
+ /**
372
+ * Registra as etapas do roteiro por onde o visitante passou (analytics por etapa do webchat).
373
+ * Quem chama engole a falha: o registro nunca pode quebrar a conversa.
374
+ */ async function sendFlowSession(cx, channelId, body, apiOverride) {
375
+ // Remessas saem em fila: uma resposta travada seguraria todas as seguintes da conversa.
376
+ const controller = new AbortController();
377
+ const timer = setTimeout(()=>controller.abort(), FLOW_SESSION_TIMEOUT_MS);
378
+ try {
379
+ const response = await fetch(`${baseUrl(cx, apiOverride, channelId)}/flow-session`, {
380
+ method: 'POST',
381
+ headers: {
382
+ 'Content-Type': 'application/json',
383
+ 'x-clickmax-sdk': 'browser'
384
+ },
385
+ body: JSON.stringify(body),
386
+ signal: controller.signal
387
+ });
388
+ if (!response.ok) {
389
+ // Corpo de erro não é lido: cancela o stream para liberar a conexão antes de desistir.
390
+ void response.body?.cancel().catch(()=>undefined);
391
+ throw new Error(`LiveChat flow session request failed with status ${response.status}`);
392
+ }
393
+ const payload = await response.json();
394
+ const sessionId = typeof payload === 'object' && payload !== null && 'sessionId' in payload ? payload.sessionId : undefined;
395
+ if (sessionId !== null && typeof sessionId !== 'string') {
396
+ throw new Error('LiveChat flow session response without a valid sessionId');
397
+ }
398
+ return {
399
+ sessionId
400
+ };
401
+ } finally{
402
+ clearTimeout(timer);
403
+ }
404
+ }
405
+
406
+ // Copies of the browser SDK helpers the widget uses: `safeResolvedUrl` from
407
+ // `@clickmax/form-builder-core` (`src/url.ts`) and `mergeCurrentSearch` from the SDK's
408
+ // `utils/query.ts`. A public package cannot depend on workspace packages at runtime.
409
+ /** Resolves `raw` against `base` and returns it only when the result is http(s). */ function safeResolvedUrl(raw, base) {
410
+ if (!raw) return null;
411
+ const value = raw.trim();
412
+ if (!value) return null;
413
+ try {
414
+ const url = new URL(value, base);
415
+ return url.protocol === 'http:' || url.protocol === 'https:' ? url.toString() : null;
416
+ } catch {
417
+ return null;
418
+ }
419
+ }
420
+ /**
421
+ * Carries the current page's query params to `target` when it does not have the key yet, so
422
+ * attribution (`utm_*`, `gclid`...) survives the jump. `cm_*` keys are never carried: they are
423
+ * the reserved context namespace and the target is their source of truth.
424
+ */ function mergeCurrentSearch(target) {
425
+ if (typeof window === 'undefined') return;
426
+ const pageParams = new URLSearchParams(window.location.search);
427
+ for (const [k, v] of pageParams){
428
+ if (k.startsWith('cm_')) continue;
429
+ if (!target.searchParams.has(k)) {
430
+ target.searchParams.set(k, v);
431
+ }
432
+ }
433
+ }
434
+
435
+
436
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
437
+ function readFunnelContext(search) {
438
+ const params = new URLSearchParams(search);
439
+ const funnelId = params.get('cm_funnel')?.trim();
440
+ const nodeId = params.get('cm_node')?.trim();
441
+ return {
442
+ ...funnelId && UUID_RE.test(funnelId) && {
443
+ funnelId
444
+ },
445
+ ...nodeId && UUID_RE.test(nodeId) && {
446
+ nodeId
447
+ }
448
+ };
449
+ }
450
+ const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
451
+ /** Mesmo teto do schema do visitor no hermes (`name` maxLength 255). */ const PREFILL_MAX_LENGTH = 255;
452
+ function readLeadPrefill(search) {
453
+ const params = new URLSearchParams(search);
454
+ const read = (...keys)=>{
455
+ for (const key of keys){
456
+ const value = params.get(key)?.trim();
457
+ if (value) return value.slice(0, PREFILL_MAX_LENGTH);
458
+ }
459
+ return undefined;
460
+ };
461
+ const name = read('name');
462
+ const email = read('email');
463
+ const phone = read('phone', 'telephone');
464
+ return {
465
+ ...name && {
466
+ name
467
+ },
468
+ // E-mail malformado na URL não vira identidade: a captura pergunta de novo.
469
+ ...email && EMAIL_RE.test(email) && {
470
+ email
471
+ },
472
+ ...phone && {
473
+ phone
474
+ }
475
+ };
476
+ }
477
+ /**
478
+ * Destino final do gatilho, espelho do `navigateTo` do quiz: só `http(s)` (relativo resolve
479
+ * contra a página) e repassa os params com que o visitante CHEGOU (`utm_*`, `gclid`, …) sem
480
+ * sobrescrever os do destino nem levar o namespace `cm_*` (`mergeCurrentSearch`).
481
+ * `null` = destino inseguro/inválido: não navega.
482
+ */ function buildFunnelNextUrl(rawUrl) {
483
+ const safeUrl = safeResolvedUrl(rawUrl, window.location.href);
484
+ if (!safeUrl) return null;
485
+ const url = new URL(safeUrl);
486
+ mergeCurrentSearch(url);
487
+ return url.toString();
488
+ }
489
+
490
+ const messagesByLocale = {
491
+ en: {
492
+ launcherLabel: 'Open chat',
493
+ defaultTitle: 'Chat with us',
494
+ inputPlaceholder: 'Type your message…',
495
+ sendLabel: 'Send',
496
+ continueLabel: 'Continue',
497
+ startChatLabel: 'Start chat',
498
+ requiredFieldMessage: 'Fill in the required fields to continue.',
499
+ invalidEmailMessage: 'Enter a valid email to continue.',
500
+ preChatSummaryPrefix: 'My details',
501
+ nameLabel: 'Your name',
502
+ emailLabel: 'Your email',
503
+ phoneLabel: 'Your phone',
504
+ connectionErrorMessage: 'Connection failed. Try again.',
505
+ progressOf: 'of',
506
+ consentDefault: 'I agree to be contacted and to the processing of my data.',
507
+ privacyPolicy: 'Privacy Policy',
508
+ viewPhoto: 'View photo',
509
+ handoffQueued: 'You’ve been transferred to our team. Someone will pick up here shortly.',
510
+ handoffHuman: 'An agent joined the conversation.',
511
+ funnelRedirecting: 'Redirecting…',
512
+ funnelContinue: 'Continue',
513
+ attachLabel: 'Attach file',
514
+ removeAttachmentLabel: 'Remove attachment',
515
+ attachmentUploadFailed: 'Could not upload the file. Try again.',
516
+ attachmentTooLarge: 'File too large (max. 10 MB, or 25 MB for videos).',
517
+ attachmentTypeNotAllowed: 'This file type can’t be sent here.',
518
+ attachmentLimitReached: 'Up to 5 attachments per message.',
519
+ dropFilesLabel: 'Drop to attach',
520
+ signedInAs: 'Signed in as',
521
+ fileAttachmentLabel: 'Attachment ({number})',
522
+ imageAttachmentLabel: 'Image'
523
+ },
524
+ 'pt-BR': {
525
+ launcherLabel: 'Abrir chat',
526
+ defaultTitle: 'Fale com a gente',
527
+ inputPlaceholder: 'Digite sua mensagem…',
528
+ sendLabel: 'Enviar',
529
+ continueLabel: 'Continuar',
530
+ startChatLabel: 'Iniciar conversa',
531
+ requiredFieldMessage: 'Preencha os campos obrigatórios para continuar.',
532
+ invalidEmailMessage: 'Informe um email válido para continuar.',
533
+ preChatSummaryPrefix: 'Meus dados',
534
+ nameLabel: 'Seu nome',
535
+ emailLabel: 'Seu email',
536
+ phoneLabel: 'Seu telefone',
537
+ connectionErrorMessage: 'Falha de conexão. Tente novamente.',
538
+ progressOf: 'de',
539
+ consentDefault: 'Concordo em ser contatado e com o tratamento dos meus dados.',
540
+ privacyPolicy: 'Política de Privacidade',
541
+ viewPhoto: 'Ver foto',
542
+ handoffQueued: 'Você foi transferido para a nossa equipe. Em breve alguém continua por aqui.',
543
+ handoffHuman: 'Um atendente entrou na conversa.',
544
+ funnelRedirecting: 'Redirecionando…',
545
+ funnelContinue: 'Continuar',
546
+ attachLabel: 'Anexar arquivo',
547
+ removeAttachmentLabel: 'Remover anexo',
548
+ attachmentUploadFailed: 'Não foi possível enviar o arquivo. Tente novamente.',
549
+ attachmentTooLarge: 'Arquivo muito grande (máx. 10 MB, ou 25 MB para vídeo).',
550
+ attachmentTypeNotAllowed: 'Esse tipo de arquivo não pode ser enviado aqui.',
551
+ attachmentLimitReached: 'Até 5 anexos por mensagem.',
552
+ dropFilesLabel: 'Solte para anexar',
553
+ signedInAs: 'Conectado como',
554
+ fileAttachmentLabel: 'Anexo ({number})',
555
+ imageAttachmentLabel: 'Imagem'
556
+ },
557
+ es: {
558
+ launcherLabel: 'Abrir chat',
559
+ defaultTitle: 'Habla con nosotros',
560
+ inputPlaceholder: 'Escribe tu mensaje…',
561
+ sendLabel: 'Enviar',
562
+ continueLabel: 'Continuar',
563
+ startChatLabel: 'Iniciar conversación',
564
+ requiredFieldMessage: 'Completa los campos obligatorios para continuar.',
565
+ invalidEmailMessage: 'Ingresa un email válido para continuar.',
566
+ preChatSummaryPrefix: 'Mis datos',
567
+ nameLabel: 'Tu nombre',
568
+ emailLabel: 'Tu email',
569
+ phoneLabel: 'Tu teléfono',
570
+ connectionErrorMessage: 'Error de conexión. Inténtalo de nuevo.',
571
+ progressOf: 'de',
572
+ consentDefault: 'Acepto ser contactado y el tratamiento de mis datos.',
573
+ privacyPolicy: 'Política de Privacidad',
574
+ viewPhoto: 'Ver foto',
575
+ handoffQueued: 'Te transferimos a nuestro equipo. En breve alguien continúa por aquí.',
576
+ handoffHuman: 'Un agente se unió a la conversación.',
577
+ funnelRedirecting: 'Redirigiendo…',
578
+ funnelContinue: 'Continuar',
579
+ attachLabel: 'Adjuntar archivo',
580
+ removeAttachmentLabel: 'Quitar adjunto',
581
+ attachmentUploadFailed: 'No se pudo subir el archivo. Inténtalo de nuevo.',
582
+ attachmentTooLarge: 'Archivo demasiado grande (máx. 10 MB, o 25 MB para videos).',
583
+ attachmentTypeNotAllowed: 'Este tipo de archivo no se puede enviar aquí.',
584
+ attachmentLimitReached: 'Hasta 5 adjuntos por mensaje.',
585
+ dropFilesLabel: 'Suelta para adjuntar',
586
+ signedInAs: 'Conectado como',
587
+ fileAttachmentLabel: 'Adjunto ({number})',
588
+ imageAttachmentLabel: 'Imagen'
589
+ }
590
+ };
591
+ function getLiveChatMessages(locale) {
592
+ return messagesByLocale[locale || 'pt-BR'] || messagesByLocale['pt-BR'];
593
+ }
594
+
595
+ // Biblioteca de ícones do botão flutuante (espelha o handoff Claude Design —
596
+ // livechat-appearance.jsx WGT_ICONS). innerHTML de SVG com stroke/fill currentColor,
597
+ // então a cor é herdada do `color` do span que os contém.
598
+ const S = 'stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"';
599
+ const icons_open = '<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">';
600
+ const LIVECHAT_ICONS = {
601
+ chat: `${icons_open}<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" ${S}/></svg>`,
602
+ msg: `${icons_open}<path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7A8.38 8.38 0 0 1 4 12a8.5 8.5 0 0 1 4.7-7.6A8.38 8.38 0 0 1 12.5 3h.5a8.48 8.48 0 0 1 8 8v.5z" ${S}/></svg>`,
603
+ headset: `${icons_open}<path d="M3 18v-6a9 9 0 0 1 18 0v6" ${S}/><path d="M21 19a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3zM3 19a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2v-3a2 2 0 0 0-2-2H3z" ${S}/></svg>`,
604
+ help: `${icons_open}<circle cx="12" cy="12" r="10" ${S}/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3" ${S}/><line x1="12" y1="17" x2="12.01" y2="17" ${S}/></svg>`,
605
+ phone: `${icons_open}<path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07A19.5 19.5 0 0 1 4.72 9.29 19.79 19.79 0 0 1 1.6 1.5 2 2 0 0 1 3.08 0H6.27a2 2 0 0 1 2 1.72c.127.96.361 1.903.7 2.81a2 2 0 0 1-.45 2.11L7.09 8.05a16 16 0 0 0 6.29 6.29l1.37-1.37a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0 1 22 15.09z" ${S}/></svg>`,
606
+ sparkle: `${icons_open}<path d="M12 2l1.8 6.4L20 10l-6.2 1.6L12 18l-1.8-6.4L4 10l6.2-1.6L12 2z" fill="currentColor" stroke="none"/></svg>`,
607
+ robot: `${icons_open}<rect x="3" y="11" width="18" height="11" rx="2" ${S}/><path d="M12 2v4M8 15h0M16 15h0" ${S}/><circle cx="12" cy="6" r="2" ${S}/></svg>`,
608
+ bell: `${icons_open}<path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9" ${S}/><path d="M13.73 21a2 2 0 0 1-3.46 0" ${S}/></svg>`
609
+ };
610
+ const CLOSE_ICON = `${icons_open}<path d="M18 6 6 18M6 6l12 12" ${S}/></svg>`;
611
+ const SEND_ICON = `${icons_open}<path d="m22 2-7 20-4-9-9-4Z" ${S}/></svg>`;
612
+ /** Clipe de papel do botão de anexo do composer (FLOWS-2457). */ const ATTACH_ICON = `${icons_open}<path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48" ${S}/></svg>`;
613
+ /** Selo de play sobre a miniatura de vídeo na fila de anexos. */ const PLAY_ICON = `${icons_open}<path d="M8 5.5v13l10.5-6.5z" fill="currentColor" stroke="none"/></svg>`;
614
+
615
+ /**
616
+ * Signed identity → visitor the widget may act on (FLOWS-2457).
617
+ *
618
+ * The widget never trusts the identity the host handed it: name/email only count once the
619
+ * public config echoes them back, which hermes-api does solely after verifying the HMAC. The
620
+ * echo must also match what was requested (same name, email and signature) — a config carrying
621
+ * some other identity (stale cache, mixed-up frames) is not "ours" and must not skip anything.
622
+ *
623
+ * Returns the visitor info to send along with messages/handoff, or `null` when the widget has
624
+ * to behave exactly like an anonymous embed (run `capture`, trust nothing).
625
+ */ function resolveVerifiedIdentity(requested, echoed) {
626
+ if (!requested || !echoed) return null;
627
+ if (echoed.name !== requested.name || echoed.email !== requested.email || echoed.signature !== requested.signature) {
628
+ return null;
629
+ }
630
+ return {
631
+ name: echoed.name,
632
+ email: echoed.email
633
+ };
634
+ }
635
+ /**
636
+ * FLOWS-2481: `cxLiveChat.identify({ name, email, signature })` comes from the customer's page —
637
+ * untyped JS. Anything that is not three non-empty strings is dropped (anonymous embed). Values
638
+ * pass through untouched: the signature covers the exact bytes the customer signed, so any
639
+ * "cleanup" (trim, lowercase) here would turn a valid identity into a rejected one.
640
+ */ function parseIdentifyInput(value) {
641
+ if (typeof value !== 'object' || value === null) return null;
642
+ const { name, email, signature } = value;
643
+ if (typeof name !== 'string' || typeof email !== 'string' || typeof signature !== 'string' || !name || !email || !signature) {
644
+ return null;
645
+ }
646
+ return {
647
+ name,
648
+ email,
649
+ signature
650
+ };
651
+ }
652
+
653
+ // Copies of the browser SDK helpers the widget uses: `el` from `forms/form-builder/shared.ts` and
654
+ // `getPageUtmValues` from `forms/core/utm.ts`.
655
+ function el(tag, attrs = {}, children = []) {
656
+ const node = document.createElement(tag);
657
+ for (const [key, value] of Object.entries(attrs)){
658
+ if (value === undefined) continue;
659
+ if (key === 'class') node.className = value;
660
+ else node.setAttribute(key, value);
661
+ }
662
+ for (const child of children)node.append(child);
663
+ return node;
664
+ }
665
+ function getPageUtmValues() {
666
+ const searchParams = new URLSearchParams(window.location.search);
667
+ return {
668
+ utmCampaign: searchParams.get('utm_campaign') || undefined,
669
+ utmContent: searchParams.get('utm_content') || undefined,
670
+ utmMedium: searchParams.get('utm_medium') || undefined,
671
+ utmSource: searchParams.get('utm_source') || undefined,
672
+ utmTerm: searchParams.get('utm_term') || undefined
673
+ };
674
+ }
675
+
676
+
677
+
678
+ /**
679
+ * FLOWS-2457: media the attendant sends from the LiveChat to a Web Chat visitor. The message row
680
+ * carries only `contentType` + `content` (the public S3 URL of the upload) — the original file
681
+ * name is not stored anywhere (`hermes.thread_messages` has no name/caption column and the CRM
682
+ * upload key is a bare UUID), so files get a generic label.
683
+ */ /**
684
+ * Only absolute `https:` URLs become media. `content` is free text on the row (any message type
685
+ * shares the column), so without this a crafted row could turn into a `javascript:`/`data:` href
686
+ * or a tracking `http:` pixel inside the visitor's page.
687
+ */ function safeMediaUrl(content) {
688
+ const value = content.trim();
689
+ if (!value) return null;
690
+ try {
691
+ return new URL(value).protocol === 'https:' ? value : null;
692
+ } catch {
693
+ return null;
694
+ }
695
+ }
696
+ /**
697
+ * Builds the bubble body for a media message, or `null` when the message is text or the URL is
698
+ * not safe (the caller then prints `content` as plain text, which is inert).
699
+ *
700
+ * - `image` → `<img>` wrapped in a link that opens the full image (never inlined as markup, so an
701
+ * SVG/HTML upload can't run script: `<img>` renders SVG without executing it).
702
+ * - `video` → `<video controls>` (the LiveChat composer only lets mp4/3gpp through).
703
+ * - `audio`/`file` → download link. Audio is not offered by the webchat composer (recorded notes
704
+ * are normalized to ogg, which Safari does not play), but an audio FILE attached through the
705
+ * picker still arrives as `audio`, and a link opens in every browser.
706
+ */ function buildMessageMedia(contentType, content, labels) {
707
+ if (contentType !== 'image' && contentType !== 'video' && contentType !== 'audio' && contentType !== 'file') {
708
+ return null;
709
+ }
710
+ const url = safeMediaUrl(content);
711
+ if (!url) return null;
712
+ if (contentType === 'image') {
713
+ const img = el('img', {
714
+ class: 'cx-livechat__bubble-image',
715
+ src: url,
716
+ alt: labels.imageLabel,
717
+ loading: 'lazy'
718
+ });
719
+ return el('a', {
720
+ class: 'cx-livechat__bubble-media',
721
+ href: url,
722
+ target: '_blank',
723
+ rel: 'noopener noreferrer',
724
+ 'aria-label': labels.imageLabel
725
+ }, [
726
+ img
727
+ ]);
728
+ }
729
+ if (contentType === 'video') {
730
+ return el('video', {
731
+ class: 'cx-livechat__bubble-video',
732
+ src: url,
733
+ controls: '',
734
+ preload: 'metadata',
735
+ playsinline: ''
736
+ });
737
+ }
738
+ const link = el('a', {
739
+ class: 'cx-livechat__bubble-attachment cx-livechat__bubble-file',
740
+ href: url,
741
+ target: '_blank',
742
+ rel: 'noopener noreferrer',
743
+ download: ''
744
+ });
745
+ link.innerHTML = ATTACH_ICON;
746
+ const name = el('span');
747
+ name.textContent = labels.fileLabel;
748
+ link.append(name);
749
+ return link;
750
+ }
751
+ /**
752
+ * Espelho da allowlist de `uploadWebChatAttachment` (hermes-api, `WEBCHAT_ATTACHMENT_MIME_TYPES`).
753
+ * O servidor é quem decide; aqui só evita gastar o upload com um arquivo que ele vai recusar e dá
754
+ * o aviso na hora. Mudou lá, muda aqui.
755
+ */ const ATTACHMENT_MIME_TYPES = new Set([
756
+ 'image/png',
757
+ 'image/jpeg',
758
+ 'image/gif',
759
+ 'image/webp',
760
+ 'video/mp4',
761
+ 'video/webm',
762
+ 'video/quicktime',
763
+ 'application/pdf',
764
+ 'application/zip',
765
+ 'application/x-zip-compressed',
766
+ 'text/plain',
767
+ 'text/csv',
768
+ 'application/msword',
769
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
770
+ 'application/vnd.ms-excel',
771
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
772
+ ]);
773
+ /** Filtro do seletor de arquivos: tipos + extensões (o Windows às vezes não informa o tipo). */ const ATTACHMENT_ACCEPT = [
774
+ ...ATTACHMENT_MIME_TYPES,
775
+ '.pdf',
776
+ '.zip',
777
+ '.txt',
778
+ '.csv',
779
+ '.doc',
780
+ '.docx',
781
+ '.xls',
782
+ '.xlsx',
783
+ '.mov'
784
+ ].join(',');
785
+ /** Mesmos tetos de `WEBCHAT_ATTACHMENT_MAX_BYTES` / `WEBCHAT_VIDEO_ATTACHMENT_MAX_BYTES`. */ const ATTACHMENT_MAX_BYTES = 10 * 1024 * 1024;
786
+ const VIDEO_ATTACHMENT_MAX_BYTES = 25 * 1024 * 1024;
787
+ function attachmentKind(mimeType) {
788
+ if (mimeType.startsWith('image/')) return 'image';
789
+ if (mimeType.startsWith('video/')) return 'video';
790
+ return 'file';
791
+ }
792
+ /** Extensão → tipo, para arquivo que o sistema entrega sem `type` (alguns Windows, `.csv`/`.docx`). */ const MIME_BY_EXTENSION = {
793
+ png: 'image/png',
794
+ jpg: 'image/jpeg',
795
+ jpeg: 'image/jpeg',
796
+ gif: 'image/gif',
797
+ webp: 'image/webp',
798
+ mp4: 'video/mp4',
799
+ webm: 'video/webm',
800
+ mov: 'video/quicktime',
801
+ pdf: 'application/pdf',
802
+ zip: 'application/zip',
803
+ txt: 'text/plain',
804
+ csv: 'text/csv',
805
+ doc: 'application/msword',
806
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
807
+ xls: 'application/vnd.ms-excel',
808
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
809
+ };
810
+ /**
811
+ * Arquivo sem `type` sairia no multipart como `application/octet-stream` e o servidor recusaria.
812
+ * Ganha o tipo pela extensão; o servidor ainda confere a assinatura do conteúdo contra ele.
813
+ */ function withAttachmentType(file) {
814
+ if (file.type) return file;
815
+ const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
816
+ // `Object.hasOwn`: a extensão vem do nome do arquivo (`.constructor` não pode cair no protótipo).
817
+ const type = Object.hasOwn(MIME_BY_EXTENSION, ext) ? MIME_BY_EXTENSION[ext] : undefined;
818
+ return type ? new File([
819
+ file
820
+ ], file.name, {
821
+ type,
822
+ lastModified: file.lastModified
823
+ }) : file;
824
+ }
825
+ /** `null` = pode subir; senão o motivo da recusa local. Espera o arquivo de `withAttachmentType`. */ function checkAttachmentFile(file) {
826
+ if (!ATTACHMENT_MIME_TYPES.has(file.type)) return 'type';
827
+ const max = file.type.startsWith('video/') ? VIDEO_ATTACHMENT_MAX_BYTES : ATTACHMENT_MAX_BYTES;
828
+ return file.size > max ? 'size' : null;
829
+ }
830
+ /**
831
+ * Print colado (Ctrl+V) chega como `image.png` em todo navegador: vários na mesma conversa ficariam
832
+ * com o mesmo nome no Drive e no chamado. Ganha um nome com data e hora até o milissegundo, mais a
833
+ * posição na colagem (`index`), já que os arquivos de uma mesma colagem chegam no mesmo instante.
834
+ */ function namePastedFile(file, index = 0, now = new Date()) {
835
+ if (file.name && !/^image\.\w+$/i.test(file.name)) return file;
836
+ const ext = file.type.split('/')[1]?.replace('jpeg', 'jpg') ?? 'png';
837
+ const pad = (n, size = 2)=>String(n).padStart(size, '0');
838
+ const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}${pad(now.getMilliseconds(), 3)}`;
839
+ const suffix = index > 0 ? `-${index + 1}` : '';
840
+ return new File([
841
+ file
842
+ ], `image-${stamp}${suffix}.${ext}`, {
843
+ type: file.type
844
+ });
845
+ }
846
+ /**
847
+ * Mídia que o PRÓPRIO visitante acabou de anexar, desenhada a partir do arquivo local (`blob:` de
848
+ * `URL.createObjectURL`) — a cópia pública só existe depois do envio. `blob:` é criado pelo widget,
849
+ * nunca vem do servidor, por isso fica fora do `safeMediaUrl`. Imagem abre ampliada em `onZoom`.
850
+ */ function buildLocalAttachmentMedia(kind, url, name, labels) {
851
+ if (kind === 'image' && url) {
852
+ const img = el('img', {
853
+ class: 'cx-livechat__bubble-image',
854
+ src: url,
855
+ alt: name
856
+ });
857
+ const zoom = el('button', {
858
+ class: 'cx-livechat__bubble-media',
859
+ type: 'button',
860
+ 'aria-label': labels.imageLabel
861
+ }, [
862
+ img
863
+ ]);
864
+ zoom.addEventListener('click', ()=>labels.onZoom(url));
865
+ return zoom;
866
+ }
867
+ if (kind === 'video' && url) {
868
+ return el('video', {
869
+ class: 'cx-livechat__bubble-video',
870
+ src: url,
871
+ controls: '',
872
+ preload: 'metadata',
873
+ playsinline: ''
874
+ });
875
+ }
876
+ const chip = el('span', {
877
+ class: 'cx-livechat__bubble-attachment'
878
+ });
879
+ chip.innerHTML = ATTACH_ICON;
880
+ const label = el('span');
881
+ label.textContent = name;
882
+ chip.append(label);
883
+ return chip;
884
+ }
885
+ /**
886
+ * `http(s)://…` ou `www.…` até o próximo espaço. Só esses dois começos viram link, então
887
+ * `javascript:`/`data:` digitados no texto nunca chegam a um href.
888
+ */ const LINK_PATTERN = /\b(?:https?:\/\/|www\.)[^\s<>"]+/gi;
889
+ /** Pontuação colada no fim ("veja https://x.com/a.") fica fora do link. */ const TRAILING_PUNCTUATION = /[.,;:!?)\]}'"]+$/;
890
+ /**
891
+ * Preenche a bolha com o texto da mensagem, com as URLs como links clicáveis (nova aba). Monta
892
+ * nós de texto e `<a>` (nunca `innerHTML`), então o texto do visitante/atendente segue inerte.
893
+ */ function appendLinkifiedText(container, text) {
894
+ let cursor = 0;
895
+ for (const match of text.matchAll(LINK_PATTERN)){
896
+ const start = match.index ?? 0;
897
+ const raw = match[0].replace(TRAILING_PUNCTUATION, '');
898
+ if (!raw.includes('.')) continue;
899
+ if (start > cursor) container.append(text.slice(cursor, start));
900
+ const href = /^https?:\/\//i.test(raw) ? raw : `https://${raw}`;
901
+ container.append(el('a', {
902
+ class: 'cx-livechat__bubble-link',
903
+ href,
904
+ target: '_blank',
905
+ rel: 'noopener noreferrer'
906
+ }, [
907
+ raw
908
+ ]));
909
+ cursor = start + raw.length;
910
+ }
911
+ if (cursor < text.length) container.append(text.slice(cursor));
912
+ }
913
+
914
+
915
+
916
+
917
+
918
+
919
+
920
+
921
+ const LAUNCHER_SIZE = {
922
+ sm: 48,
923
+ md: 58,
924
+ lg: 70
925
+ };
926
+ const LAUNCHER_RADIUS = {
927
+ circle: '50%',
928
+ rounded: '16px',
929
+ pill: '999px'
930
+ };
931
+ const LAUNCHER_SHADOW = [
932
+ 'none',
933
+ '0 4px 14px rgba(0,0,0,.18)',
934
+ '0 8px 28px rgba(0,0,0,.30)',
935
+ '0 12px 36px rgba(0,0,0,.42)'
936
+ ];
937
+ const VISITOR_HASH_KEY = 'cx-livechat-visitor';
938
+ /** Aceite do aviso LGPD por canal — mesma vida útil da identidade do visitante. */ const CONSENT_KEY_PREFIX = 'cx-livechat-consent:';
939
+ const POLL_INTERVAL_MS = 3000;
940
+ /** Gatilho do funil com saída automática: tempo do aviso "Redirecionando…" antes de navegar. */ const FUNNEL_REDIRECT_DELAY_MS = 1500;
941
+ /** Teto de `attachments` por mensagem (`WebChatVisitorMessageSchema`, `maxItems: 5`). */ const ATTACHMENTS_PER_MESSAGE = 5;
942
+ /** Teto de espera pelo envio da última resposta antes de mandar "Webchat concluído". */ const COMPLETED_SEND_WAIT_MS = 4000;
943
+ function generateVisitorHash() {
944
+ if (typeof crypto !== 'undefined') {
945
+ if (crypto.randomUUID) return `wc_${crypto.randomUUID().replace(/-/g, '')}`;
946
+ const bytes = new Uint8Array(16);
947
+ crypto.getRandomValues(bytes);
948
+ return `wc_${Array.from(bytes, (byte)=>byte.toString(16).padStart(2, '0')).join('')}`;
949
+ }
950
+ // Browsers sem WebCrypto: aleatoriedade fraca é melhor que quebrar o widget
951
+ return `wc_${Date.now().toString(16)}${Math.random().toString(16).slice(2)}`;
952
+ }
953
+ function flowProgressKey(channelId) {
954
+ return `cx-livechat-flow:${channelId}`;
955
+ }
956
+ function readFlowProgress(channelId) {
957
+ try {
958
+ const value = localStorage.getItem(flowProgressKey(channelId));
959
+ return value === 'running' || value === 'done' ? value : null;
960
+ } catch {
961
+ // Storage bloqueado: sem memória entre cargas, vale o comportamento antigo (não refaz).
962
+ return null;
963
+ }
964
+ }
965
+ function writeFlowProgress(channelId, value) {
966
+ try {
967
+ localStorage.setItem(flowProgressKey(channelId), value);
968
+ } catch {
969
+ // Storage bloqueado: idem acima.
970
+ }
971
+ }
972
+ function getVisitorHash() {
973
+ try {
974
+ const existing = localStorage.getItem(VISITOR_HASH_KEY);
975
+ if (existing) return existing;
976
+ const hash = generateVisitorHash();
977
+ localStorage.setItem(VISITOR_HASH_KEY, hash);
978
+ return hash;
979
+ } catch {
980
+ // Storage bloqueado (iframe/3rd-party) — identidade válida só nesta pageview.
981
+ return generateVisitorHash();
982
+ }
983
+ }
984
+ /**
985
+ * Sanitiza a URL do link de consentimento (LGPD). Só libera `http(s)` e caminhos
986
+ * relativos/same-origin; bloqueia `javascript:`/`data:`/etc. que, na página
987
+ * hospedada (`/chat/:id`, origem clickmax), virariam XSS refletido a partir de
988
+ * config do dono. Retorna a URL original (preserva relativos) ou null se insegura.
989
+ */ function safeHref(url) {
990
+ const value = url.trim();
991
+ if (!value) return null;
992
+ try {
993
+ const resolved = new URL(value, document.baseURI);
994
+ return resolved.protocol === 'http:' || resolved.protocol === 'https:' ? value : null;
995
+ } catch {
996
+ return null;
997
+ }
998
+ }
999
+ /** Horário HH:MM local de uma Date (carimbo da bolha). */ function formatClock(d) {
1000
+ return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
1001
+ }
1002
+ /** Horário HH:MM local de agora (bolhas geradas no cliente pelo fluxo/bot). */ function nowTime() {
1003
+ return formatClock(new Date());
1004
+ }
1005
+ class LiveChatWidget {
1006
+ cx;
1007
+ options;
1008
+ messages;
1009
+ visitorHash;
1010
+ isPreview;
1011
+ /** Desmontado (`destroy`): cadeias async do fluxo ainda em voo param de renderizar. */ destroyed = false;
1012
+ onVisibilityChange = ()=>{
1013
+ if (!this.isOpen && !this.pollWhileClosed) return;
1014
+ if (document.hidden) this.stopPolling();
1015
+ else this.startPolling();
1016
+ };
1017
+ isOpen = false;
1018
+ bootstrapped = false;
1019
+ /** Bootstrap em voo: `open()` concorrente (tela cheia + `sendMessage`) espera o mesmo. */ bootstrapping = null;
1020
+ // ── FLOWS-2457: identidade verificada, anexos, não lidas ──
1021
+ /** Nome/e-mail que o servidor confirmou (eco da config) — `null` = anônimo. */ identityVisitor = null;
1022
+ uploads = [];
1023
+ uploadSeq = 0;
1024
+ attachmentsEl = null;
1025
+ /** Fila de upload: um corpo de arquivo por vez segura a memória num lote grande. */ uploadChain = Promise.resolve();
1026
+ /** `blob:` criados para as miniaturas; liberados no `destroy`. */ objectUrls = new Set();
1027
+ /**
1028
+ * Anexos que este widget já desenhou na bolha do visitante. A mídia volta no polling como
1029
+ * mensagem própria (URL pública com o `fileId` no caminho, `webchatAttachmentMediaKey`): sem
1030
+ * isto o visitante veria cada foto duas vezes.
1031
+ */ sentAttachmentIds = new Set();
1032
+ unreadCount = 0;
1033
+ /** Host avisou que o chat está fora da vista (modal fechado): mensagens novas contam como não lidas. */ hostHidden = false;
1034
+ /** `appearance.badge` ligado: o badge "1" de chamariz volta quando as não lidas zeram. */ badgeConfigured = false;
1035
+ /** Tela cheia ativa (via `data-cx-mode` ou `appearance.mode`) — sem launcher, abre sozinho */ fullscreen = false;
1036
+ /**
1037
+ * Modo 'embed': o shell mora dentro do marcador (`options.host`) e não vira overlay.
1038
+ * Fixado no mount — `appearance.mode` remoto só liga o visual de tela cheia
1039
+ * (idempotente), nunca tira o chat do container de volta pro `body`.
1040
+ */ embedHost;
1041
+ // ── Fase 2 (config opcional): barra de etapas / fonte a11y / consent LGPD ──
1042
+ fontControlsEl;
1043
+ progressEl;
1044
+ progressEnabled = false;
1045
+ progressTotal = 0;
1046
+ progressDone = 0;
1047
+ consentEl;
1048
+ consentCheckbox = null;
1049
+ avatarUrl = null;
1050
+ agentName = '';
1051
+ fontScale = 1;
1052
+ /** Agrupamento de bolhas (tipo WhatsApp): nome no topo do grupo, avatar na última bolha. */ lastBubbleSide = null;
1053
+ /**
1054
+ * Último estado do atendimento humano visto no polling. `undefined` = ainda não lido: o primeiro
1055
+ * valor (no bootstrap) só registra — o visitante que volta não recebe de novo o aviso de uma
1056
+ * transferência antiga. Só a MUDANÇA vira nota no chat.
1057
+ */ attendance = undefined;
1058
+ lastAgentAvatarSlot = null;
1059
+ /** Config carregada uma vez no mount (reusada no bootstrap da 1ª abertura) */ config = null;
1060
+ configLoaded = null;
1061
+ autoOpenTimer = null;
1062
+ /** webchat-react: closes the avatar lightbox while it is open. */ closeLightbox = null;
1063
+ /** Indicador de "digitando…" (3 pontinhos) ativo, se houver */ typingEl = null;
1064
+ /**
1065
+ * Última resposta digitada numa pergunta de texto, ainda não classificada. Um nó de IA logo
1066
+ * depois (só com mensagens no meio) classifica ESTA resposta na hora em vez de abrir o composer:
1067
+ * "Qual a escola?" → IA "Deixa eu verificar…" não pode esperar o visitante escrever de novo.
1068
+ * Opção clicada ou captura zeram — aí não há texto livre para a IA ler.
1069
+ */ pendingTextAnswer = null;
1070
+ container;
1071
+ windowEl;
1072
+ launcherEl;
1073
+ launcherIconEl;
1074
+ tooltipEl;
1075
+ badgeEl;
1076
+ headerTitleEl;
1077
+ headerSubtitleEl;
1078
+ headerAvatarEl;
1079
+ messagesEl;
1080
+ footerEl;
1081
+ knownMessageIds = new Set();
1082
+ lastCreatedAt;
1083
+ pollTimer = null;
1084
+ pollInFlight = false;
1085
+ /** Dados do pré-chat aguardando ir junto do próximo send */ pendingVisitorInfo = null;
1086
+ /** Bolhas automáticas do bot aguardando backfill no próximo send do visitante */ botBuffer = [];
1087
+ /**
1088
+ * PM-3584: true assim que um `send()` ao `/messages` já levou o buffer do bot ao
1089
+ * servidor. O handoff só backfilla `botMessages` quando isto é `false` (primeiro
1090
+ * contato — fluxo só de cliques que chega ao handoff sem nunca ter enviado uma
1091
+ * mensagem), evitando duplicar o transcript já enviado.
1092
+ */ messageSent = false;
1093
+ /**
1094
+ * Envio de mensagem ainda em voo. O pedido de atendente espera por ele: os dois saem quase juntos
1095
+ * (opção que leva direto ao Atendente), e o envio é quem cria o contato do visitante novo — em
1096
+ * paralelo, os dois disputariam essa criação. A thread é criada depois, pelo CRM, a partir de
1097
+ * eventos separados; essa corrida residual é a aceita em `getOrCreateThread`.
1098
+ */ inFlightSend = null;
1099
+ /**
1100
+ * Bolhas já renderizadas pelo fluxo (bot + visitante). O backend persiste o
1101
+ * transcript e o polling devolve essas mesmas mensagens — este log deduplica
1102
+ * o echo (consome uma entrada por mensagem polida com mesmo lado+conteúdo).
1103
+ */ flowEcho = [];
1104
+ /** `cm_funnel`/`cm_node` da URL (lidos uma vez no mount) — contexto do nó webchat no funil. */ funnelContext;
1105
+ /** Eventos do funil já enviados nesta carga: cada um no máximo uma vez. */ funnelEventsSent = new Set();
1106
+ /** Já mostrou "Redirecionando…"/"Continuar": o primeiro destino vence, os seguintes não empilham. */ funnelExitShown = false;
1107
+ /** `name`/`email`/`phone` repassados na URL pela página anterior do funil (`readLeadPrefill`). */ leadPrefill;
1108
+ funnelQueue = Promise.resolve();
1109
+ /**
1110
+ * Execução do roteiro em curso, para o analytics por etapa (`hermes.webchatFlowSessions`).
1111
+ * Etapas alcançadas se acumulam em `pending` e sobem numa remessa só quando o roteiro para à
1112
+ * espera do visitante (pergunta, captura, IA) ou termina: uma sequência de mensagens do bot não
1113
+ * vira uma requisição por bolha. `null` fora do roteiro e na prévia do construtor.
1114
+ */ flowSession = null;
1115
+ funnelRedirectTimer = null;
1116
+ constructor(cx, options){
1117
+ this.cx = cx;
1118
+ this.options = options;
1119
+ this.messages = getLiveChatMessages(options.locale);
1120
+ this.isPreview = options.preview !== undefined;
1121
+ this.embedHost = options.mode === 'embed' && options.host ? options.host : null;
1122
+ // Prévia: identidade descartável — não grava `cx-livechat-visitor` no storage do app.
1123
+ // Host com sessão própria (FLOWS-2457): usa o hash dele, sem tocar no storage.
1124
+ this.visitorHash = options.visitorHash ?? (this.isPreview ? generateVisitorHash() : getVisitorHash());
1125
+ this.funnelContext = this.isPreview ? {} : readFunnelContext(window.location.search);
1126
+ this.leadPrefill = this.isPreview ? {} : readLeadPrefill(window.location.search);
1127
+ // Sem etapa de captura (ou visitante recorrente), o lead da URL ainda identifica a conversa:
1128
+ // vai no 1º envio/handoff, e o hermes adota o lead que já tem esse e-mail.
1129
+ if (this.leadPrefill.name || this.leadPrefill.email) {
1130
+ this.pendingVisitorInfo = {
1131
+ ...this.leadPrefill.name && {
1132
+ name: this.leadPrefill.name
1133
+ },
1134
+ ...this.leadPrefill.email && {
1135
+ email: this.leadPrefill.email
1136
+ }
1137
+ };
1138
+ }
1139
+ this.renderShell();
1140
+ const preview = options.preview;
1141
+ if (preview) {
1142
+ // Config chega pronta do editor: aplica síncrono, sem fetch.
1143
+ this.config = preview.config;
1144
+ this.configLoaded = Promise.resolve();
1145
+ this.applyConfig(preview.config);
1146
+ if (preview.open && !this.isOpen) void this.open();
1147
+ else this.scheduleAutoOpen(preview.config.appearance?.autoOpen);
1148
+ } else {
1149
+ // Carrega a config logo no mount para estilizar o launcher fechado
1150
+ // (cor/ícone/forma/tamanho/tooltip/badge) sem esperar a 1ª abertura.
1151
+ this.configLoaded = this.loadConfig();
1152
+ }
1153
+ // Tela cheia via atributo do embed: liga de forma síncrona (antes da config
1154
+ // remota) pra não piscar o balão. `open()` aguarda `configLoaded` no bootstrap,
1155
+ // então a config já carregada é reusada (sem 2º fetch). Embeds sem o atributo
1156
+ // caem no `appearance.mode` dentro do applyConfig.
1157
+ if (this.options.mode === 'fullscreen' || this.embedHost) this.enableFullscreen();
1158
+ document.addEventListener('visibilitychange', this.onVisibilityChange);
1159
+ }
1160
+ /**
1161
+ * FLOWS-2481: `cxLiveChat.identify` chamado DEPOIS do mount (o site do cliente só sabe quem é o
1162
+ * visitante quando a sessão dele carrega, em geral depois do nosso script). Refaz a busca da
1163
+ * config com a identidade assinada; só o eco do servidor vale, então uma assinatura errada deixa
1164
+ * o widget anônimo, exatamente como se `identify` nunca tivesse sido chamado. Encadeia depois de
1165
+ * uma busca em voo para a mais recente ser a que fica. Sem efeito na prévia (não tem rede).
1166
+ */ identify(identity) {
1167
+ if (this.isPreview || this.destroyed) return;
1168
+ this.options.identity = identity;
1169
+ this.configLoaded = (this.configLoaded ?? Promise.resolve()).then(()=>this.loadConfig());
1170
+ }
1171
+ /**
1172
+ * Desmonta o widget (a prévia do construtor remonta a cada mudança de config).
1173
+ * Cadeias async em voo (bolhas com "digitando…") checam `destroyed` e param.
1174
+ */ destroy() {
1175
+ this.destroyed = true;
1176
+ this.closeLightbox?.();
1177
+ this.stopPolling();
1178
+ if (this.autoOpenTimer !== null) clearTimeout(this.autoOpenTimer);
1179
+ this.autoOpenTimer = null;
1180
+ if (this.funnelRedirectTimer !== null) clearTimeout(this.funnelRedirectTimer);
1181
+ this.funnelRedirectTimer = null;
1182
+ document.removeEventListener('visibilitychange', this.onVisibilityChange);
1183
+ for (const url of this.objectUrls)URL.revokeObjectURL(url);
1184
+ this.objectUrls.clear();
1185
+ this.container.remove();
1186
+ }
1187
+ /**
1188
+ * FLOWS-2457: envio programático do host (modal de suporte). Mesmo caminho do composer —
1189
+ * bolha otimista, `visitor` pendente, backfill do bot — mais `intent`/`context`/`attachments`.
1190
+ * Abre (e bootstrapa) o chat se ainda não aconteceu. Sem `nodeId`: é conversa, não resposta a
1191
+ * um nó do roteiro — se o roteiro estiver esperando uma resposta, ela continua esperando.
1192
+ * `true` = o servidor aceitou.
1193
+ */ async sendMessage(text, extras) {
1194
+ const trimmed = text.trim();
1195
+ if (!trimmed || this.destroyed) return false;
1196
+ if (!this.isOpen) await this.open();
1197
+ else if (this.bootstrapping) await this.bootstrapping;
1198
+ if (this.destroyed) return false;
1199
+ return this.send(trimmed, undefined, extras);
1200
+ }
1201
+ /**
1202
+ * FLOWS-2457: o host (iframe do modal) avisa se o chat está visível. Oculto, as respostas do
1203
+ * atendente viram não lidas; visível, zera. Independente do `isOpen` — no modo embed o chat
1204
+ * está sempre "aberto", o que muda é a modal por cima.
1205
+ */ setHostVisible(visible) {
1206
+ this.hostHidden = !visible;
1207
+ if (visible) this.setUnread(0);
1208
+ }
1209
+ /** Contador de não lidas → badge do balão + callback do host. Só avisa quando muda. */ setUnread(count) {
1210
+ if (count === this.unreadCount) return;
1211
+ this.unreadCount = count;
1212
+ if (count > 0) {
1213
+ this.badgeEl.textContent = count > 99 ? '99+' : String(count);
1214
+ if (!this.isOpen) this.badgeEl.style.display = '';
1215
+ } else {
1216
+ this.badgeEl.textContent = '1';
1217
+ this.badgeEl.style.display = this.badgeConfigured && !this.isOpen ? '' : 'none';
1218
+ }
1219
+ this.options.onUnreadChange?.(count);
1220
+ }
1221
+ /** Polling segue com o balão fechado só quando alguém conta as não lidas (host). */ get pollWhileClosed() {
1222
+ return this.options.onUnreadChange !== undefined;
1223
+ }
1224
+ /**
1225
+ * Na prévia do construtor o clipe aparece quando o toggle está ligado, mas nada sobe: o arquivo
1226
+ * vira miniatura e bolha locais (ver `uploadAttachment`).
1227
+ */ get attachmentsEnabled() {
1228
+ return this.options.attachments === true || this.config?.appearance?.attachments?.enabled === true;
1229
+ }
1230
+ /** Identidade assinada do host para a query do `/config` (undefined = anônimo). */ configSession() {
1231
+ return this.options.identity ? {
1232
+ visitorHash: this.visitorHash,
1233
+ identity: this.options.identity
1234
+ } : undefined;
1235
+ }
1236
+ /** Eventos do bus (pixel/analytics) — a prévia do construtor não é visita real. */ emit(name) {
1237
+ if (this.isPreview) return;
1238
+ this.cx.bus.emit(name, {
1239
+ channelId: this.options.channelId
1240
+ });
1241
+ }
1242
+ // ── Shell (launcher + janela vazia) ────────────────────────────────────────
1243
+ renderShell() {
1244
+ const themeAttrs = this.options.theme === undefined ? undefined : {
1245
+ 'data-cx-theme': this.options.theme
1246
+ };
1247
+ this.container = el('div', {
1248
+ class: 'cx-livechat',
1249
+ ...themeAttrs
1250
+ });
1251
+ // Posição explícita vale já na criação: se o config remoto falhar ou demorar, o launcher não cai no canto padrão.
1252
+ if (this.options.position === 'bottom-left') this.container.classList.add('cx-livechat--left');
1253
+ // ── Janela (chat aberto) ──
1254
+ this.headerAvatarEl = el('img', {
1255
+ class: 'cx-livechat__avatar',
1256
+ alt: ''
1257
+ });
1258
+ this.headerAvatarEl.style.display = 'none';
1259
+ // Clique/teclado no avatar abre a foto ampliada (habilitado no applyConfig se houver avatarUrl).
1260
+ const openPhoto = ()=>{
1261
+ if (this.avatarUrl) this.openAvatarLightbox(this.avatarUrl);
1262
+ };
1263
+ this.headerAvatarEl.addEventListener('click', openPhoto);
1264
+ this.headerAvatarEl.addEventListener('keydown', (event)=>{
1265
+ if (event.key === 'Enter' || event.key === ' ') {
1266
+ event.preventDefault();
1267
+ openPhoto();
1268
+ }
1269
+ });
1270
+ this.headerTitleEl = el('span', {
1271
+ class: 'cx-livechat__title'
1272
+ }, [
1273
+ this.messages.defaultTitle
1274
+ ]);
1275
+ this.headerSubtitleEl = el('span', {
1276
+ class: 'cx-livechat__subtitle'
1277
+ });
1278
+ this.headerSubtitleEl.style.display = 'none';
1279
+ const heading = el('div', {
1280
+ class: 'cx-livechat__heading'
1281
+ }, [
1282
+ this.headerTitleEl,
1283
+ this.headerSubtitleEl
1284
+ ]);
1285
+ // Controles de tamanho de fonte (a11y) — escondidos até appearance.fontControls.
1286
+ this.fontControlsEl = this.renderFontControls();
1287
+ this.fontControlsEl.style.display = 'none';
1288
+ const closeButton = el('button', {
1289
+ class: 'cx-livechat__close',
1290
+ type: 'button',
1291
+ 'aria-label': 'Close'
1292
+ });
1293
+ closeButton.innerHTML = CLOSE_ICON;
1294
+ closeButton.addEventListener('click', ()=>this.close());
1295
+ const header = el('div', {
1296
+ class: 'cx-livechat__header'
1297
+ }, [
1298
+ this.headerAvatarEl,
1299
+ heading,
1300
+ this.fontControlsEl,
1301
+ closeButton
1302
+ ]);
1303
+ // Barra de etapas "X de N" — escondida até appearance.progress + fluxo com etapas.
1304
+ this.progressEl = el('div', {
1305
+ class: 'cx-livechat__progress'
1306
+ });
1307
+ this.progressEl.style.display = 'none';
1308
+ this.messagesEl = el('div', {
1309
+ class: 'cx-livechat__messages'
1310
+ });
1311
+ // Consentimento LGPD (acima do input) — escondido até appearance.consent.
1312
+ this.consentEl = el('label', {
1313
+ class: 'cx-livechat__consent'
1314
+ });
1315
+ this.consentEl.style.display = 'none';
1316
+ this.footerEl = el('div', {
1317
+ class: 'cx-livechat__footer'
1318
+ });
1319
+ this.windowEl = el('div', {
1320
+ class: 'cx-livechat__window'
1321
+ }, [
1322
+ header,
1323
+ this.progressEl,
1324
+ this.messagesEl,
1325
+ this.consentEl,
1326
+ this.footerEl
1327
+ ]);
1328
+ this.windowEl.style.display = 'none';
1329
+ this.bindFileDrop();
1330
+ // ── Dock (launcher fechado + tooltip + badge) ──
1331
+ this.tooltipEl = el('div', {
1332
+ class: 'cx-livechat__tooltip'
1333
+ });
1334
+ this.tooltipEl.style.display = 'none';
1335
+ this.launcherIconEl = el('span', {
1336
+ class: 'cx-livechat__launcher-icon'
1337
+ });
1338
+ this.launcherIconEl.innerHTML = LIVECHAT_ICONS.chat;
1339
+ this.launcherEl = el('button', {
1340
+ class: 'cx-livechat__launcher',
1341
+ type: 'button',
1342
+ 'aria-label': this.messages.launcherLabel
1343
+ });
1344
+ this.launcherEl.append(this.launcherIconEl);
1345
+ this.launcherEl.addEventListener('click', ()=>{
1346
+ if (this.isOpen) this.close();
1347
+ else void this.open();
1348
+ });
1349
+ this.badgeEl = el('span', {
1350
+ class: 'cx-livechat__badge'
1351
+ }, [
1352
+ '1'
1353
+ ]);
1354
+ this.badgeEl.style.display = 'none';
1355
+ const launcherWrap = el('div', {
1356
+ class: 'cx-livechat__launcher-wrap'
1357
+ }, [
1358
+ this.launcherEl,
1359
+ this.badgeEl
1360
+ ]);
1361
+ const dock = el('div', {
1362
+ class: 'cx-livechat__dock'
1363
+ }, [
1364
+ this.tooltipEl,
1365
+ launcherWrap
1366
+ ]);
1367
+ this.container.append(this.windowEl, dock);
1368
+ if (this.embedHost) this.mountInHost(this.embedHost);
1369
+ else document.body.append(this.container);
1370
+ if (this.options.accentColor) {
1371
+ this.container.style.setProperty('--cx-livechat-accent', this.options.accentColor);
1372
+ }
1373
+ }
1374
+ /**
1375
+ * Modo 'embed': o chat preenche o marcador (absolute, inset 0) em vez de cobrir a
1376
+ * página. O marcador vira contexto de posicionamento se estiver `static`, e ganha
1377
+ * uma altura mínima se não tiver altura própria — o shell é absolute e não daria
1378
+ * altura nenhuma a um `<div>` vazio, que colapsaria em 0px.
1379
+ */ mountInHost(host) {
1380
+ this.container.classList.add('cx-livechat--embed');
1381
+ host.append(this.container);
1382
+ if (getComputedStyle(host).position === 'static') host.style.position = 'relative';
1383
+ if (host.clientHeight === 0) host.style.minHeight = '600px';
1384
+ }
1385
+ applyConfig(config) {
1386
+ const appearance = config.appearance ?? {};
1387
+ // Fullscreen configurado no builder (Design tab): liga mesmo sem o atributo
1388
+ // no embed. Idempotente — no-op se o atributo já ligou.
1389
+ if (appearance.mode === 'fullscreen') this.enableFullscreen();
1390
+ this.agentName = appearance.agentName || config.name || this.messages.defaultTitle;
1391
+ this.headerTitleEl.textContent = this.agentName;
1392
+ const subtitle = appearance.subtitle ?? appearance.agentTeam;
1393
+ if (subtitle) {
1394
+ this.headerSubtitleEl.textContent = subtitle;
1395
+ this.headerSubtitleEl.style.display = '';
1396
+ }
1397
+ if (config.avatarUrl) {
1398
+ this.avatarUrl = config.avatarUrl;
1399
+ this.headerAvatarEl.src = config.avatarUrl;
1400
+ this.headerAvatarEl.style.display = '';
1401
+ // Avatar vira "botão" acessível pra abrir a foto ampliada.
1402
+ this.headerAvatarEl.classList.add('cx-livechat__avatar--clickable');
1403
+ this.headerAvatarEl.setAttribute('role', 'button');
1404
+ this.headerAvatarEl.setAttribute('tabindex', '0');
1405
+ const agent = appearance.agentName || config.name || '';
1406
+ this.headerAvatarEl.setAttribute('aria-label', agent ? `${this.messages.viewPhoto} — ${agent}` : this.messages.viewPhoto);
1407
+ }
1408
+ if (config.primaryColor && !this.options.accentColor) {
1409
+ this.container.style.setProperty('--cx-livechat-accent', config.primaryColor);
1410
+ }
1411
+ this.container.classList.toggle('cx-livechat--left', (this.options.position ?? config.position) === 'bottom-left');
1412
+ // FLOWS-2457: só o eco do servidor conta. Verificada, nome/e-mail sobem no próximo envio/
1413
+ // handoff como numa captura (mesmo mecanismo do `leadPrefill`), e o nó `capture` é pulado.
1414
+ // FLOWS-2481: `identify` can run again on a live page (logout/login in an SPA). A pending
1415
+ // visitor that still carries the PREVIOUS identity's e-mail came from it, not from a capture
1416
+ // the visitor typed — replace (or drop) it so the next message is not attributed to them.
1417
+ const previousIdentity = this.identityVisitor;
1418
+ const pendingIsFromPreviousIdentity = previousIdentity !== null && this.pendingVisitorInfo?.email === previousIdentity.email;
1419
+ this.identityVisitor = resolveVerifiedIdentity(this.options.identity, config.identity);
1420
+ if (this.identityVisitor && (!this.pendingVisitorInfo || pendingIsFromPreviousIdentity)) {
1421
+ this.pendingVisitorInfo = {
1422
+ ...this.identityVisitor
1423
+ };
1424
+ } else if (!this.identityVisitor && pendingIsFromPreviousIdentity) {
1425
+ this.pendingVisitorInfo = null;
1426
+ }
1427
+ this.applyAppearance(appearance);
1428
+ this.applyExtras(appearance);
1429
+ }
1430
+ /** Estiliza o botão flutuante (forma/tamanho/ícone/cor/sombra/animação/badge/tooltip). */ applyAppearance(a) {
1431
+ const size = LAUNCHER_SIZE[a.size ?? 'md'];
1432
+ this.launcherEl.style.width = `${size}px`;
1433
+ this.launcherEl.style.height = `${size}px`;
1434
+ this.launcherEl.style.borderRadius = LAUNCHER_RADIUS[a.shape ?? 'circle'];
1435
+ this.launcherEl.style.boxShadow = LAUNCHER_SHADOW[a.shadow ?? 2] ?? '0 8px 28px rgba(0,0,0,.30)';
1436
+ if (a.iconUrl) {
1437
+ this.launcherIconEl.innerHTML = '';
1438
+ const img = el('img', {
1439
+ src: a.iconUrl,
1440
+ alt: ''
1441
+ });
1442
+ img.style.width = '55%';
1443
+ img.style.height = '55%';
1444
+ img.style.objectFit = 'contain';
1445
+ this.launcherIconEl.append(img);
1446
+ } else {
1447
+ this.launcherIconEl.innerHTML = LIVECHAT_ICONS[a.iconId ?? 'chat'];
1448
+ }
1449
+ this.launcherIconEl.style.color = a.iconColor && a.iconColor !== 'auto' ? a.iconColor : '#fff';
1450
+ // Animação de entrada (one-shot via classe)
1451
+ this.launcherEl.classList.remove('cx-livechat__launcher--bounce', 'cx-livechat__launcher--pulse', 'cx-livechat__launcher--slide');
1452
+ if (a.animation && a.animation !== 'none') {
1453
+ this.launcherEl.classList.add(`cx-livechat__launcher--${a.animation}`);
1454
+ }
1455
+ this.badgeConfigured = a.badge === true;
1456
+ if (a.badge) this.badgeEl.style.display = '';
1457
+ if (a.tooltip?.enabled && a.tooltip.text) {
1458
+ this.tooltipEl.textContent = a.tooltip.text;
1459
+ this.tooltipEl.style.display = '';
1460
+ }
1461
+ }
1462
+ // ── Fase 2: barra de etapas / fonte a11y / consent / lightbox ──────────────
1463
+ /** Liga os recursos opcionais (fonte a11y, consent LGPD, barra de etapas). */ applyExtras(a) {
1464
+ if (a.fontControls?.enabled) this.fontControlsEl.style.display = '';
1465
+ if (a.consent?.enabled) this.renderConsent(a.consent);
1466
+ // A barra de etapas só aparece quando o pré-chat vai realmente rodar (decidido
1467
+ // no bootstrap). Visitante recorrente cai direto no chat ao vivo sem etapas —
1468
+ // mostrá-la aqui deixaria um "0 de N" travado. Aqui só guardamos a intenção.
1469
+ this.progressEnabled = a.progress?.enabled ?? false;
1470
+ }
1471
+ renderFontControls() {
1472
+ const dec = el('button', {
1473
+ class: 'cx-livechat__fontbtn cx-livechat__fontbtn--sm',
1474
+ type: 'button',
1475
+ 'aria-label': 'A-'
1476
+ }, [
1477
+ 'A'
1478
+ ]);
1479
+ const inc = el('button', {
1480
+ class: 'cx-livechat__fontbtn cx-livechat__fontbtn--lg',
1481
+ type: 'button',
1482
+ 'aria-label': 'A+'
1483
+ }, [
1484
+ 'A'
1485
+ ]);
1486
+ dec.addEventListener('click', ()=>this.setFontScale(-0.1));
1487
+ inc.addEventListener('click', ()=>this.setFontScale(0.1));
1488
+ return el('div', {
1489
+ class: 'cx-livechat__fontcontrols'
1490
+ }, [
1491
+ dec,
1492
+ inc
1493
+ ]);
1494
+ }
1495
+ /** Escala a fonte da conversa via CSS var (a11y). Passos de 0.1, faixa 0.85–1.4. */ setFontScale(delta) {
1496
+ this.fontScale = Math.min(1.4, Math.max(0.85, Math.round((this.fontScale + delta) * 10) / 10));
1497
+ this.container.style.setProperty('--cx-livechat-font-scale', String(this.fontScale));
1498
+ }
1499
+ /** Conta as etapas interativas (capture/question/ai) → total da barra "X de N". */ countInteractiveSteps(flow) {
1500
+ if (!flow?.enabled) return 0;
1501
+ return flow.steps.filter((s)=>s.type === 'capture' || s.type === 'question' || s.type === 'ai').length;
1502
+ }
1503
+ renderProgress() {
1504
+ const total = this.progressTotal;
1505
+ const done = Math.min(this.progressDone, total);
1506
+ const track = el('div', {
1507
+ class: 'cx-livechat__progress-track'
1508
+ });
1509
+ for(let i = 0; i < total; i++){
1510
+ const cls = i < done ? 'cx-livechat__progress-seg cx-livechat__progress-seg--done' : i === done ? 'cx-livechat__progress-seg cx-livechat__progress-seg--active' : 'cx-livechat__progress-seg';
1511
+ track.append(el('div', {
1512
+ class: cls
1513
+ }));
1514
+ }
1515
+ const count = el('span', {
1516
+ class: 'cx-livechat__progress-count'
1517
+ });
1518
+ count.append(el('b', {}, [
1519
+ String(done)
1520
+ ]), ` ${this.messages.progressOf} ${total}`);
1521
+ this.progressEl.replaceChildren(track, count);
1522
+ }
1523
+ /** Marca mais uma etapa interativa concluída e atualiza a barra. */ advanceProgress() {
1524
+ if (this.progressTotal === 0 || this.progressDone >= this.progressTotal) return;
1525
+ this.progressDone++;
1526
+ this.renderProgress();
1527
+ }
1528
+ renderConsent(consent) {
1529
+ const checkbox = el('input', {
1530
+ type: 'checkbox'
1531
+ });
1532
+ this.consentCheckbox = checkbox;
1533
+ const text = consent.text || this.messages.consentDefault;
1534
+ const parts = [
1535
+ checkbox,
1536
+ ` ${text} `
1537
+ ];
1538
+ const privacyHref = consent.privacyUrl ? safeHref(consent.privacyUrl) : null;
1539
+ if (privacyHref) {
1540
+ parts.push(el('a', {
1541
+ href: privacyHref,
1542
+ target: '_blank',
1543
+ rel: 'noopener noreferrer'
1544
+ }, [
1545
+ this.messages.privacyPolicy
1546
+ ]));
1547
+ }
1548
+ this.consentEl.replaceChildren(...parts);
1549
+ // Aceito uma vez, o aviso sai da tela e não volta: ele fica entre as mensagens e as
1550
+ // opções de resposta, e no fullscreen (diagnóstico longo) cobria a pergunta da vez a
1551
+ // cada etapa. O `guardConsent` segue lendo o checkbox, que continua marcado mesmo oculto.
1552
+ // O aceite também sobrevive ao recarregar a página (FLOWS-2329): o visitante volta pro
1553
+ // mesmo thread (mesmo `cx-livechat-visitor`), então pedir de novo só reabria o aviso
1554
+ // por cima da pergunta e travava a resposta até remarcar. O aceite fica preso ao texto e
1555
+ // ao link exibidos: mudou um dos dois, o aviso volta desmarcado para o novo termo.
1556
+ const terms = JSON.stringify([
1557
+ text,
1558
+ privacyHref ?? ''
1559
+ ]);
1560
+ if (this.hasStoredConsent(terms)) {
1561
+ checkbox.checked = true;
1562
+ this.consentEl.style.display = 'none';
1563
+ } else {
1564
+ this.consentEl.style.display = '';
1565
+ }
1566
+ checkbox.addEventListener('change', ()=>{
1567
+ if (!checkbox.checked) return;
1568
+ this.consentEl.style.display = 'none';
1569
+ this.storeConsent(terms);
1570
+ });
1571
+ }
1572
+ consentStorageKey() {
1573
+ return `${CONSENT_KEY_PREFIX}${this.options.channelId}`;
1574
+ }
1575
+ /**
1576
+ * `terms` = texto + link exibidos no aceite. Prévia nunca lê nem grava: roda num iframe
1577
+ * same-origin com o app.
1578
+ */ hasStoredConsent(terms) {
1579
+ if (this.isPreview) return false;
1580
+ try {
1581
+ return localStorage.getItem(this.consentStorageKey()) === terms;
1582
+ } catch {
1583
+ return false;
1584
+ }
1585
+ }
1586
+ storeConsent(terms) {
1587
+ if (this.isPreview) return;
1588
+ try {
1589
+ localStorage.setItem(this.consentStorageKey(), terms);
1590
+ } catch {
1591
+ // Storage bloqueado: o aceite vale só nesta pageview (checkbox segue marcado).
1592
+ }
1593
+ }
1594
+ /** true = pode prosseguir. Consent ligado e desmarcado ⇒ sinaliza (flash) e bloqueia. */ guardConsent() {
1595
+ if (!this.consentCheckbox || this.consentCheckbox.checked) return true;
1596
+ this.consentEl.classList.remove('cx-livechat__consent--flash');
1597
+ void this.consentEl.offsetWidth; // reinicia a animação de flash
1598
+ this.consentEl.classList.add('cx-livechat__consent--flash');
1599
+ return false;
1600
+ }
1601
+ openAvatarLightbox(url) {
1602
+ const img = el('img', {
1603
+ class: 'cx-livechat__lightbox-img',
1604
+ src: url,
1605
+ alt: ''
1606
+ });
1607
+ const overlay = el('div', {
1608
+ class: 'cx-livechat__lightbox'
1609
+ }, [
1610
+ img
1611
+ ]);
1612
+ const onKey = (event)=>{
1613
+ if (event.key === 'Escape') close();
1614
+ };
1615
+ // webchat-react: `destroy` closes an open lightbox, or its `keydown` listener outlives the chat.
1616
+ const close = ()=>{
1617
+ overlay.remove();
1618
+ document.removeEventListener('keydown', onKey);
1619
+ this.closeLightbox = null;
1620
+ };
1621
+ this.closeLightbox = close;
1622
+ overlay.addEventListener('click', close);
1623
+ document.addEventListener('keydown', onKey);
1624
+ this.container.append(overlay);
1625
+ }
1626
+ /** Carrega a config uma vez e aplica a aparência ao launcher fechado + agenda auto-open. */ async loadConfig() {
1627
+ try {
1628
+ const config = await fetchLiveChatConfig(this.cx, this.options.channelId, this.options.apiOverride, this.configSession());
1629
+ // webchat-react: a config arriving after `destroy` (route left mid-fetch) is dropped, or its
1630
+ // auto open would bootstrap and poll a chat nobody sees.
1631
+ if (this.destroyed) return;
1632
+ this.config = config;
1633
+ this.applyConfig(config);
1634
+ this.scheduleAutoOpen(config.appearance?.autoOpen);
1635
+ // Depois do applyConfig: `appearance.mode` remoto também liga a tela cheia.
1636
+ this.trackFunnelEvent('view');
1637
+ } catch (error) {
1638
+ this.cx.debug('LiveChat config load failed', error);
1639
+ }
1640
+ }
1641
+ scheduleAutoOpen(autoOpen) {
1642
+ // Tela cheia já abre sozinho — não agenda timer morto.
1643
+ if (this.fullscreen || !autoOpen?.enabled || this.autoOpenTimer !== null) return;
1644
+ this.autoOpenTimer = setTimeout(()=>{
1645
+ if (!this.isOpen) void this.open();
1646
+ }, Math.max(1, autoOpen.delaySeconds) * 1000);
1647
+ }
1648
+ // ── Abertura / fechamento ──────────────────────────────────────────────────
1649
+ /**
1650
+ * Liga o modo tela cheia: o container passa a cobrir a viewport (o CSS
1651
+ * `.cx-livechat--fullscreen` esconde launcher/dock e o botão de fechar) e o
1652
+ * chat abre sozinho. Idempotente. Disparado pelo atributo do embed
1653
+ * (`data-cx-mode="fullscreen"`) ou pela config remota (`appearance.mode`).
1654
+ */ enableFullscreen() {
1655
+ if (this.fullscreen) return;
1656
+ this.fullscreen = true;
1657
+ this.container.classList.add('cx-livechat--fullscreen');
1658
+ // Sem auto-open agendado: a tela cheia já abre imediatamente.
1659
+ if (this.autoOpenTimer !== null) {
1660
+ clearTimeout(this.autoOpenTimer);
1661
+ this.autoOpenTimer = null;
1662
+ }
1663
+ if (!this.isOpen) void this.open();
1664
+ }
1665
+ async open() {
1666
+ this.isOpen = true;
1667
+ this.windowEl.style.display = '';
1668
+ this.tooltipEl.style.display = 'none';
1669
+ this.badgeEl.style.display = 'none';
1670
+ this.container.classList.add('cx-livechat--open');
1671
+ this.setUnread(0);
1672
+ this.emit('chat_opened');
1673
+ this.options.preview?.onOpenChange?.(true);
1674
+ // PM-3369: só marca bootstrapped no sucesso. Antes a flag era setada
1675
+ // antes do await, então uma falha de rede travava o widget num estado
1676
+ // degradado pro resto da sessão (reabrir não re-tentava).
1677
+ if (!this.bootstrapped) {
1678
+ // Uma só rodada por vez: `enableFullscreen` e `sendMessage` podem abrir quase juntos.
1679
+ this.bootstrapping ??= this.bootstrap().finally(()=>{
1680
+ this.bootstrapping = null;
1681
+ });
1682
+ const ok = await this.bootstrapping;
1683
+ if (ok && !this.bootstrapped) {
1684
+ this.bootstrapped = true;
1685
+ this.options.onReady?.();
1686
+ }
1687
+ }
1688
+ if (this.destroyed) return;
1689
+ this.startPolling();
1690
+ }
1691
+ close() {
1692
+ this.isOpen = false;
1693
+ this.windowEl.style.display = 'none';
1694
+ this.container.classList.remove('cx-livechat--open');
1695
+ // Com contador de não lidas o polling continua fechado (é ele que traz o que contar).
1696
+ if (!this.pollWhileClosed) this.stopPolling();
1697
+ this.emit('chat_closed');
1698
+ this.options.preview?.onOpenChange?.(false);
1699
+ }
1700
+ /**
1701
+ * Primeira abertura: reusa a config carregada no mount e busca o histórico.
1702
+ * Com thread existente, pula o pré-chat (visitante recorrente); sem thread,
1703
+ * roda o fluxo do builder. Retorna `true` no sucesso e `false` no erro —
1704
+ * `open()` usa esse retorno para deixar o flag `bootstrapped` em `false`
1705
+ * quando a 1ª tentativa falha, permitindo retry na próxima abertura.
1706
+ */ async bootstrap() {
1707
+ try {
1708
+ if (this.configLoaded) await this.configLoaded;
1709
+ const config = this.config ?? await fetchLiveChatConfig(this.cx, this.options.channelId, this.options.apiOverride, this.configSession());
1710
+ // Prévia: sempre visitante novo (sem thread) — roda o fluxo do começo.
1711
+ const view = this.isPreview ? {
1712
+ thread: null,
1713
+ messages: []
1714
+ } : await pollLiveChatMessages(this.cx, this.options.channelId, this.visitorHash, undefined, this.options.apiOverride);
1715
+ // FLOWS-2457: conversa nova com identidade verificada — uma linha de sistema no lugar da
1716
+ // bolha "Meus dados" que a captura mostraria. Histórico existente dispensa.
1717
+ if (this.identityVisitor?.name && view.messages.length === 0) {
1718
+ this.renderNote(`${this.messages.signedInAs} ${this.identityVisitor.name}`);
1719
+ }
1720
+ const preChat = config.preChatFlow;
1721
+ const hasFlow = preChat?.enabled === true && preChat.steps.length > 0;
1722
+ // Quem abandonou o roteiro no meio (a 1ª resposta já criou a thread) refaz do começo. Sem
1723
+ // isso o retorno caía no chat livre e "Webchat concluído" nunca saía — sem redirect no
1724
+ // funil. Só com o roteiro marcado `running` NESTE navegador: conversa que já terminou o
1725
+ // roteiro (IA, equipe, mesmo que o atendente tenha saído) segue com o histórico.
1726
+ const resumeAbandonedFlow = view.thread !== null && hasFlow && !view.thread.attendance && readFlowProgress(this.options.channelId) === 'running';
1727
+ const shouldRunPreChat = hasFlow && (view.thread === null || resumeAbandonedFlow);
1728
+ if (!resumeAbandonedFlow) this.appendPolledMessages(view.messages, {
1729
+ silent: true
1730
+ });
1731
+ else this.markMessagesSeen(view.messages);
1732
+ this.syncAttendance(view.thread?.attendance ?? null);
1733
+ // Barra de etapas: só no fluxo guiado (não p/ visitante recorrente que já
1734
+ // está no chat ao vivo), senão ficaria travada em "0 de N".
1735
+ if (shouldRunPreChat && this.progressEnabled) {
1736
+ this.progressTotal = this.countInteractiveSteps(preChat);
1737
+ if (this.progressTotal > 0) {
1738
+ this.progressEl.style.display = '';
1739
+ this.renderProgress();
1740
+ }
1741
+ }
1742
+ if (config.welcomeMessage && (view.messages.length === 0 || resumeAbandonedFlow)) {
1743
+ // Desmontado no meio (prévia remontou): bootstrap cancelado, não concluído.
1744
+ if (!await this.botSay(config.welcomeMessage)) return false;
1745
+ }
1746
+ if (shouldRunPreChat) {
1747
+ const first = preChat.steps[0];
1748
+ // As condições do fluxo enxergam o que a URL já trouxe (ex.: "tem e-mail?").
1749
+ if (first && preChat) {
1750
+ if (!this.isPreview) writeFlowProgress(this.options.channelId, 'running');
1751
+ this.startFlowSession();
1752
+ this.pendingTextAnswer = null;
1753
+ void this.runNode(preChat.steps, first.id, {
1754
+ ...this.leadPrefill
1755
+ }, undefined);
1756
+ } else this.renderInputRow();
1757
+ } else {
1758
+ this.renderInputRow();
1759
+ }
1760
+ return true;
1761
+ } catch (error) {
1762
+ this.cx.error(error, 'LiveChat bootstrap failed');
1763
+ this.renderBubble('agent', this.messages.connectionErrorMessage);
1764
+ this.renderInputRow();
1765
+ return false;
1766
+ }
1767
+ }
1768
+ // ── Pré-chat / bot flow (interpretador de grafo) ───────────────────────────
1769
+ /**
1770
+ * Resolve a transição de um nó, nesta ordem: (1) id de um nó existente —
1771
+ * inclusive nós cujo id é literalmente `'handoff'`/`'end'` (o editor nomeia
1772
+ * assim); (2) sentinela terminal `'handoff'`/`'end'` sem nó correspondente
1773
+ * (fluxos legados) → conclui, e o de handoff pede atendente (fila); (3) null/undefined →
1774
+ * segue o próximo nó na ordem
1775
+ * do array; sem próximo ⇒ conclui.
1776
+ */ gotoTarget(steps, target, current, answers, choice) {
1777
+ // Um id de nó explícito SEMPRE vence o sentinela terminal abaixo. O editor
1778
+ // gera o nó de transferência com id 'handoff' (e o de fim com 'end'); sem
1779
+ // esta ordem, `target === 'handoff'` caía direto no sentinela e chamava
1780
+ // finishPreChat SEM rodar o nó handoff — logo `requestHandoff` nunca
1781
+ // disparava e a conversa ficava presa em status 'bot', fora do inbox de
1782
+ // atendimento (o nó handoff é quem promove a thread via handoff.requested).
1783
+ if (target) {
1784
+ const node = steps.find((s)=>s.id === target);
1785
+ if (node) {
1786
+ void this.runNode(steps, node.id, answers, choice);
1787
+ return;
1788
+ }
1789
+ }
1790
+ // Id de etapa apagada (não é sentinela): o canvas do editor não desenha aresta para ele, então
1791
+ // a etapa aparece como fim do roteiro — conclui aqui também, em vez de cair no próximo do
1792
+ // array (que podia ser um Atendente e trocar "Webchat concluído" por handoff).
1793
+ if (target && target !== 'handoff') {
1794
+ this.finishPreChat(answers, 'completed');
1795
+ return;
1796
+ }
1797
+ if (target === 'handoff') {
1798
+ // O builder oferece "→ Falar com atendente" como destino de qualquer etapa, mas os nós que
1799
+ // ele cria têm id `step_…`: o sentinela quase nunca casa um nó. Sem este pedido a conversa
1800
+ // terminava o roteiro sem chegar à fila, escondida da equipe. Sem nó, sem `assignTo`: fila.
1801
+ this.requestHandoff(target, answers);
1802
+ this.finishPreChat(answers, 'handoff');
1803
+ return;
1804
+ }
1805
+ // Sequencial: próximo nó na ordem do array
1806
+ const index = steps.findIndex((s)=>s.id === current.id);
1807
+ const nextStep = index >= 0 ? steps[index + 1] : undefined;
1808
+ if (nextStep) void this.runNode(steps, nextStep.id, answers, choice);
1809
+ else this.finishPreChat(answers, 'completed');
1810
+ }
1811
+ /** Verdadeiro se o alvo encerra o fluxo (para rotular o botão de captura). */ isTerminalNext(steps, target, current) {
1812
+ // Espelha a resolução do gotoTarget: um id de nó existente vence o sentinela.
1813
+ // Um nó real 'handoff'/'end' é terminal pelo seu TYPE; a string literal só conta
1814
+ // como terminal quando não existe nó com esse id (fluxo legado sem nó explícito).
1815
+ if (target) {
1816
+ const node = steps.find((s)=>s.id === target);
1817
+ if (node) return node.type === 'handoff' || node.type === 'end';
1818
+ }
1819
+ if (target === 'handoff' || target === 'end') return true;
1820
+ const index = steps.findIndex((s)=>s.id === current.id);
1821
+ return index < 0 || index + 1 >= steps.length;
1822
+ }
1823
+ evalCondition(node, answers, choice) {
1824
+ const raw = node.variable === 'choice' ? choice : answers[node.variable];
1825
+ const value = (raw ?? '').toLowerCase();
1826
+ const target = (node.value ?? '').toLowerCase();
1827
+ if (node.op === 'exists') return Boolean(raw);
1828
+ if (node.op === 'equals') return value === target;
1829
+ return Boolean(value) && value.includes(target);
1830
+ }
1831
+ async runNode(steps, nodeId, answers, choice) {
1832
+ if (this.destroyed) return;
1833
+ const node = steps.find((s)=>s.id === nodeId);
1834
+ if (!node) {
1835
+ this.finishPreChat(answers, 'completed');
1836
+ return;
1837
+ }
1838
+ // Condição é invisível para o visitante: não conta como etapa alcançada.
1839
+ if (node.type !== 'condition') this.flowSession?.pending.push(node.id);
1840
+ if (node.type === 'message') {
1841
+ if (!await this.botSay(node.text)) return;
1842
+ this.gotoTarget(steps, node.next, node, answers, choice);
1843
+ return;
1844
+ }
1845
+ if (node.type === 'condition') {
1846
+ const ok = this.evalCondition(node, answers, choice);
1847
+ this.gotoTarget(steps, ok ? node.next : node.elseNext, node, answers, choice);
1848
+ return;
1849
+ }
1850
+ if (node.type === 'handoff' || node.type === 'end') {
1851
+ if (node.text && !await this.botSay(node.text)) return;
1852
+ if (node.type === 'handoff') this.requestHandoff(node.id, answers);
1853
+ this.finishPreChat(answers, node.type === 'handoff' ? 'handoff' : 'completed');
1854
+ return;
1855
+ }
1856
+ if (node.type === 'ai') {
1857
+ if (!await this.botSay(node.text)) return;
1858
+ this.flushFlowSession();
1859
+ const classify = (text, questionNodeId)=>{
1860
+ this.advanceProgress();
1861
+ // IA "pensando": mantém o indicador o tempo que a classificação levar.
1862
+ // O sucesso NÃO esconde — o próximo botSay/render do ramo cuida disso,
1863
+ // deixando os pontinhos contínuos até a próxima bolha.
1864
+ this.showTyping();
1865
+ // Prévia: o classify público usa o fluxo PUBLICADO; o rascunho é classificado pelo editor
1866
+ // (`preview.classify`). Sem ele (aba Design), segue pelo ramo padrão.
1867
+ const previewClassify = this.options.preview?.classify;
1868
+ if (this.isPreview && !previewClassify) {
1869
+ this.gotoTarget(steps, node.fallbackNext, node, answers, text);
1870
+ return;
1871
+ }
1872
+ const request = {
1873
+ nodeId: node.id,
1874
+ text,
1875
+ questionNodeId
1876
+ };
1877
+ const classified = previewClassify ? previewClassify(request) : classifyLiveChat(this.cx, this.options.channelId, {
1878
+ visitorHash: this.visitorHash,
1879
+ ...request
1880
+ }, this.options.apiOverride);
1881
+ void classified.then(({ branchId })=>{
1882
+ // Resposta que chega depois de o widget ser trocado (prévia remontou, Reiniciar) não
1883
+ // avança o fluxo novo.
1884
+ if (this.destroyed) return;
1885
+ const branch = branchId ? node.branches.find((b)=>b.id === branchId) : undefined;
1886
+ this.gotoTarget(steps, branch ? branch.next : node.fallbackNext, node, answers, text);
1887
+ }).catch((error)=>{
1888
+ this.cx.debug('LiveChat classify failed', error);
1889
+ this.hideTyping();
1890
+ this.gotoTarget(steps, node.fallbackNext, node, answers, text);
1891
+ });
1892
+ };
1893
+ // A resposta já veio na pergunta de texto anterior (e já foi enviada com o nodeId dela):
1894
+ // classifica sem pedir outra mensagem.
1895
+ const previousAnswer = this.pendingTextAnswer;
1896
+ this.pendingTextAnswer = null;
1897
+ if (previousAnswer) {
1898
+ classify(previousAnswer.text, previousAnswer.nodeId);
1899
+ return;
1900
+ }
1901
+ const form = this.buildTextComposer((text)=>{
1902
+ // Persiste como inbound (+ backfill das bolhas do bot) e ramifica via IA. O nodeId marca
1903
+ // a resposta como do roteiro: o SDR de IA do canal não responde por cima da classificação.
1904
+ void this.send(text, node.id);
1905
+ classify(text);
1906
+ });
1907
+ this.mountComposer(form);
1908
+ return;
1909
+ }
1910
+ if (node.type === 'question') {
1911
+ if (!await this.botSay(node.text)) return;
1912
+ this.flushFlowSession();
1913
+ // Modo texto: o visitante digita a resposta no composer em vez de clicar numa
1914
+ // opção. Mesmo caminho de persistência (send com nodeId → o backend grava no
1915
+ // answerField), mas a pergunta tem uma saída só (`next`) por não ter ramos.
1916
+ //
1917
+ // Zero opções cai aqui mesmo sem `answerMode` — sem isso o footer receberia uma
1918
+ // lista vazia e a conversa travava sem saída (nem o reload salva: o bootstrap
1919
+ // reroda o pre-chat enquanto não há thread). Acontece quando um widget em cache
1920
+ // roda um fluxo salvo em modo texto por uma versão mais nova do builder.
1921
+ if (node.answerMode === 'text' || node.options.length === 0) {
1922
+ const form = this.buildTextComposer((text)=>{
1923
+ void this.send(text, node.id);
1924
+ this.advanceProgress();
1925
+ this.pendingTextAnswer = {
1926
+ nodeId: node.id,
1927
+ text
1928
+ };
1929
+ this.gotoTarget(steps, node.next, node, answers, text);
1930
+ });
1931
+ this.hideTyping();
1932
+ this.mountComposer(form);
1933
+ return;
1934
+ }
1935
+ const list = el('div', {
1936
+ class: 'cx-livechat__options'
1937
+ });
1938
+ for (const option of node.options){
1939
+ const button = el('button', {
1940
+ class: 'cx-livechat__option',
1941
+ type: 'button'
1942
+ }, [
1943
+ option.label
1944
+ ]);
1945
+ button.addEventListener('click', ()=>{
1946
+ if (!this.guardConsent()) return;
1947
+ list.remove();
1948
+ // Persiste a escolha como inbound (+ backfill das bolhas do bot) e ramifica.
1949
+ // Manda o nodeId da pergunta: se ela mapeia um custom field, o backend grava a resposta no lead.
1950
+ void this.send(option.label, node.id);
1951
+ this.flowSession?.answers.push({
1952
+ stepId: node.id,
1953
+ optionId: option.id
1954
+ });
1955
+ this.advanceProgress();
1956
+ this.pendingTextAnswer = null;
1957
+ this.gotoTarget(steps, option.next, node, answers, option.label);
1958
+ });
1959
+ list.append(button);
1960
+ }
1961
+ this.hideTyping();
1962
+ this.footerEl.replaceChildren(list);
1963
+ return;
1964
+ }
1965
+ // capture
1966
+ // Zerado na entrada, não no commit: a captura por identidade verificada avança sem commitar, e
1967
+ // a resposta de texto de antes não pode chegar a um nó de IA depois desta etapa.
1968
+ this.pendingTextAnswer = null;
1969
+ // Persiste a captura JÁ NESTE ponto (em ordem, antes de avançar): vira uma mensagem inbound
1970
+ // do visitante + enriquece o lead. Antes isso ia só no finishPreChat (fim do fluxo),
1971
+ // persistindo fora de ordem.
1972
+ const commitCapture = (values)=>{
1973
+ const captured = [];
1974
+ for (const { key, value } of values){
1975
+ if (!value) continue;
1976
+ answers[key] = value;
1977
+ captured.push(value);
1978
+ }
1979
+ this.advanceProgress();
1980
+ if (captured.length > 0) {
1981
+ this.pendingVisitorInfo = {
1982
+ ...answers.name && {
1983
+ name: answers.name
1984
+ },
1985
+ ...answers.email && {
1986
+ email: answers.email
1987
+ }
1988
+ };
1989
+ // nodeId: resposta do roteiro, não conversa livre — o SDR de IA espera o fluxo acabar.
1990
+ // Gatilho "Contato capturado" só depois do envio aceito: é ele que cria/enriquece o lead.
1991
+ // Entra na fila AGORA (antes do fim do fluxo logo abaixo), esperando o envio: assim
1992
+ // "Contato capturado" sempre chega antes de "Webchat concluído" quando a captura é a
1993
+ // última etapa, e o destino que vale é o dele.
1994
+ this.trackFunnelEvent('lead_captured', this.send(`${this.messages.preChatSummaryPrefix}: ${captured.join(' · ')}`, node.id));
1995
+ }
1996
+ this.gotoTarget(steps, node.next, node, answers, choice);
1997
+ };
1998
+ // FLOWS-2457: identidade verificada pelo servidor responde a captura sozinha — sem formulário
1999
+ // e sem a bolha "Meus dados" (o usuário já está logado no app que hospeda o chat). `answers`
2000
+ // ganha nome/e-mail (as condições do fluxo enxergam) e o `visitor` sobe no próximo envio ou
2001
+ // handoff como numa captura normal (`pendingVisitorInfo`, posto no `applyConfig`). Campos
2002
+ // além de nome/e-mail (telefone) ficam sem resposta de propósito: o chat de suporte do app é
2003
+ // configurado pela própria Clickmax, e pedir dado ao usuário logado contraria o card.
2004
+ if (this.identityVisitor) {
2005
+ if (this.identityVisitor.name) answers.name = this.identityVisitor.name;
2006
+ if (this.identityVisitor.email) answers.email = this.identityVisitor.email;
2007
+ this.advanceProgress();
2008
+ this.gotoTarget(steps, node.next, node, answers, choice);
2009
+ return;
2010
+ }
2011
+ // A página anterior do funil já capturou estes dados (vieram na URL): não pergunta de novo.
2012
+ // Pula só quando TODO campo obrigatório está coberto; senão o formulário abre preenchido.
2013
+ const prefilled = (key)=>key === 'name' || key === 'email' || key === 'phone' ? this.leadPrefill[key] ?? '' : '';
2014
+ const coversRequired = node.fields.every((f)=>f.required === false || prefilled(f.key));
2015
+ // Consentimento pendente (checkbox do LGPD desmarcado) mantém o formulário: o aceite é do
2016
+ // visitante, não da página anterior. Checado sem o flash do `guardConsent`.
2017
+ const consentOk = !this.consentCheckbox || this.consentCheckbox.checked;
2018
+ if (node.fields.length > 0 && coversRequired && consentOk) {
2019
+ commitCapture(node.fields.map((f)=>({
2020
+ key: f.key,
2021
+ value: prefilled(f.key)
2022
+ })));
2023
+ return;
2024
+ }
2025
+ if (node.text && !await this.botSay(node.text)) return;
2026
+ this.hideTyping();
2027
+ this.flushFlowSession();
2028
+ const form = el('form', {
2029
+ class: 'cx-livechat__prechat'
2030
+ });
2031
+ const errorEl = el('p', {
2032
+ class: 'cx-livechat__error'
2033
+ });
2034
+ errorEl.style.display = 'none';
2035
+ const inputs = [];
2036
+ const defaultLabels = {
2037
+ name: this.messages.nameLabel,
2038
+ email: this.messages.emailLabel,
2039
+ phone: this.messages.phoneLabel
2040
+ };
2041
+ for (const field of node.fields){
2042
+ const input = el('input', {
2043
+ class: 'cx-livechat__input',
2044
+ name: field.key,
2045
+ placeholder: field.label || defaultLabels[field.key] || field.key,
2046
+ type: field.key === 'email' ? 'email' : field.key === 'phone' ? 'tel' : 'text',
2047
+ autocomplete: field.key === 'phone' ? 'tel' : field.key
2048
+ });
2049
+ input.value = prefilled(field.key);
2050
+ inputs.push({
2051
+ key: field.key,
2052
+ input,
2053
+ required: field.required !== false
2054
+ });
2055
+ form.append(input);
2056
+ }
2057
+ const submit = el('button', {
2058
+ class: 'cx-livechat__button',
2059
+ type: 'submit'
2060
+ }, [
2061
+ this.isTerminalNext(steps, node.next, node) ? this.messages.startChatLabel : this.messages.continueLabel
2062
+ ]);
2063
+ form.append(errorEl, submit);
2064
+ form.addEventListener('submit', (event)=>{
2065
+ event.preventDefault();
2066
+ if (!this.guardConsent()) return;
2067
+ const values = [];
2068
+ for (const { key, input, required } of inputs){
2069
+ const value = input.value.trim();
2070
+ if (required && !value) {
2071
+ errorEl.textContent = this.messages.requiredFieldMessage;
2072
+ errorEl.style.display = '';
2073
+ return;
2074
+ }
2075
+ if (key === 'email' && value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
2076
+ errorEl.textContent = this.messages.invalidEmailMessage;
2077
+ errorEl.style.display = '';
2078
+ return;
2079
+ }
2080
+ values.push({
2081
+ key,
2082
+ value
2083
+ });
2084
+ }
2085
+ form.remove();
2086
+ commitCapture(values);
2087
+ });
2088
+ this.footerEl.replaceChildren(form);
2089
+ inputs[0]?.input.focus();
2090
+ }
2091
+ /**
2092
+ * Fim do fluxo: cai no chat ao vivo. Os dados de captura e as respostas já
2093
+ * foram persistidos em ordem no momento de cada interação (não aqui), então
2094
+ * só resta renderizar o composer. Bolhas finais do bot ainda no buffer
2095
+ * (ex.: texto de handoff) sobem junto da próxima mensagem do visitante.
2096
+ *
2097
+ * `reason` separa o fim por Encerrar/última etapa (gatilho "Webchat concluído" do funil)
2098
+ * do fim por handoff — esse segue com a equipe e só dispara "Pediu atendente" quando o
2099
+ * pedido é aceito (`requestHandoffWithRetry`).
2100
+ */ finishPreChat(_answers, reason) {
2101
+ if (!this.isPreview) writeFlowProgress(this.options.channelId, 'done');
2102
+ this.flushFlowSession(reason);
2103
+ this.renderInputRow();
2104
+ // Espera o envio da última resposta: o redirect navega ~1,5s depois e abortaria um `send`
2105
+ // lento (resposta e custom field perdidos). Falha de envio não segura o funil.
2106
+ if (reason === 'completed') this.trackFunnelEvent('webchat_completed', this.inFlightSend === null ? undefined : Promise.race([
2107
+ this.inFlightSend.then(()=>true),
2108
+ // `fetch` sem timeout: um envio travado não pode segurar a fila do funil.
2109
+ this.sleep(COMPLETED_SEND_WAIT_MS).then(()=>true)
2110
+ ]));
2111
+ }
2112
+ /**
2113
+ * PM-3584: ao chegar a um nó `handoff`, registra a conversa no atendimento.
2114
+ * Envia o `nodeId` (o backend resolve o atendente a partir do `preChatFlow`),
2115
+ * os dados capturados pelo pré-chat (criam o lead quando o visitante chegou só
2116
+ * clicando, sem nunca digitar) e — APENAS quando nenhuma mensagem foi enviada
2117
+ * ainda (`!messageSent`) — o buffer do bot para backfill do transcript, espelhando
2118
+ * o flush feito por `send()` e evitando duplicar bolhas já enviadas.
2119
+ */ requestHandoff(nodeId, answers) {
2120
+ if (this.isPreview) return;
2121
+ const visitor = this.pendingVisitorInfo ?? (answers.name || answers.email ? {
2122
+ ...answers.name && {
2123
+ name: answers.name
2124
+ },
2125
+ ...answers.email && {
2126
+ email: answers.email
2127
+ }
2128
+ } : undefined);
2129
+ this.pendingVisitorInfo = null;
2130
+ // Primeiro contato com o servidor? Só então leva as bolhas do bot (o `send()`
2131
+ // normal já as teria enviado e esvaziado o buffer).
2132
+ const botMessages = this.messageSent ? [] : this.botBuffer;
2133
+ if (!this.messageSent) this.botBuffer = [];
2134
+ // Non-blocking: não atrasa o `finishPreChat`/UI. Tenta o POST até 3x com
2135
+ // backoff antes de desistir — sem retry, uma falha de rede deixaria a conversa
2136
+ // órfã (nunca registrada no inbox do livechat) e o visitante preso.
2137
+ void this.requestHandoffWithRetry(nodeId, visitor, botMessages);
2138
+ }
2139
+ async requestHandoffWithRetry(nodeId, visitor, botMessages) {
2140
+ const delays = [
2141
+ 500,
2142
+ 1500,
2143
+ 3000
2144
+ ];
2145
+ await this.inFlightSend;
2146
+ for(let attempt = 0; attempt <= delays.length; attempt++){
2147
+ try {
2148
+ await requestLiveChatHandoff(this.cx, this.options.channelId, {
2149
+ visitorHash: this.visitorHash,
2150
+ nodeId,
2151
+ ...visitor && {
2152
+ visitor
2153
+ },
2154
+ ...botMessages.length ? {
2155
+ botMessages
2156
+ } : {}
2157
+ }, this.options.apiOverride);
2158
+ this.trackFunnelEvent('handoff_requested');
2159
+ return;
2160
+ } catch (error) {
2161
+ const delay = delays[attempt];
2162
+ if (delay !== undefined) {
2163
+ this.cx.debug(`LiveChat handoff request failed (attempt ${attempt + 1}), retrying`, error);
2164
+ await this.sleep(delay);
2165
+ continue;
2166
+ }
2167
+ // Esgotadas as tentativas: devolve o que tentamos enviar para não perder
2168
+ // dados num `send()` posterior. As bolhas do bot só voltam ao buffer se
2169
+ // nenhuma mensagem foi enviada ainda — caso contrário o `send()` já as
2170
+ // entregou ao servidor e re-injetá-las DUPLICARIA o transcript.
2171
+ this.cx.error(error, 'LiveChat handoff request failed after retries');
2172
+ if (visitor) this.pendingVisitorInfo = visitor;
2173
+ if (!this.messageSent && botMessages.length) {
2174
+ this.botBuffer = [
2175
+ ...botMessages,
2176
+ ...this.botBuffer
2177
+ ];
2178
+ }
2179
+ return;
2180
+ }
2181
+ }
2182
+ }
2183
+ // ── Composer ───────────────────────────────────────────────────────────────
2184
+ renderInputRow() {
2185
+ this.hideTyping();
2186
+ const input = el('input', {
2187
+ class: 'cx-livechat__input',
2188
+ placeholder: this.messages.inputPlaceholder,
2189
+ type: 'text',
2190
+ autocomplete: 'off'
2191
+ });
2192
+ const send = el('button', {
2193
+ class: 'cx-livechat__send',
2194
+ type: 'submit',
2195
+ 'aria-label': this.messages.sendLabel
2196
+ });
2197
+ send.innerHTML = SEND_ICON;
2198
+ const form = el('form', {
2199
+ class: 'cx-livechat__composer'
2200
+ });
2201
+ if (this.attachmentsEnabled) {
2202
+ form.append(...this.buildAttachControl());
2203
+ // Ctrl+V / Cmd+V de print ou arquivo copiado: vai para a fila de anexos. Com texto puro na
2204
+ // área de transferência o colar segue normal: células copiadas do Excel trazem uma imagem
2205
+ // das células junto do texto, e quem colou queria o texto.
2206
+ input.addEventListener('paste', (event)=>{
2207
+ const files = Array.from(event.clipboardData?.files ?? []);
2208
+ if (files.length === 0 || event.clipboardData?.getData('text/plain').trim()) return;
2209
+ event.preventDefault();
2210
+ this.queueAttachments(files.map((file, index)=>namePastedFile(file, index)));
2211
+ });
2212
+ }
2213
+ form.append(input, send);
2214
+ form.addEventListener('submit', (event)=>{
2215
+ event.preventDefault();
2216
+ if (!this.guardConsent()) return;
2217
+ const text = input.value.trim();
2218
+ // Só os anexos já enviados vão nesta mensagem; os ainda subindo ficam para a próxima.
2219
+ const uploads = this.takeUploadedAttachments();
2220
+ if (!text && uploads.length === 0) return;
2221
+ input.value = '';
2222
+ const attachments = uploads.flatMap((u)=>u.attachment ? [
2223
+ u.attachment
2224
+ ] : []);
2225
+ // O servidor exige texto: anexo sem legenda vai com os nomes dos arquivos (só no registro —
2226
+ // a bolha do visitante mostra a mídia, sem repetir os nomes).
2227
+ void this.send(text || attachments.map((a)=>a.name).join(', '), undefined, attachments.length ? {
2228
+ attachments
2229
+ } : undefined, uploads.length ? {
2230
+ uploads,
2231
+ showText: Boolean(text)
2232
+ } : undefined);
2233
+ });
2234
+ // Fila dos anexos fica ACIMA do composer, fora do form (o CSS do composer é uma linha flex).
2235
+ this.attachmentsEl = this.attachmentsEnabled ? el('div', {
2236
+ class: 'cx-livechat__attachments'
2237
+ }) : null;
2238
+ this.footerEl.replaceChildren(...this.attachmentsEl ? [
2239
+ this.attachmentsEl
2240
+ ] : [], form);
2241
+ this.renderPendingUploads();
2242
+ input.focus();
2243
+ }
2244
+ // ── Anexos (FLOWS-2457) ────────────────────────────────────────────────────
2245
+ /** Clipe + input de arquivo oculto do composer. O upload começa na escolha, não no envio. */ buildAttachControl() {
2246
+ const fileInput = el('input', {
2247
+ class: 'cx-livechat__file',
2248
+ type: 'file',
2249
+ multiple: '',
2250
+ accept: ATTACHMENT_ACCEPT
2251
+ });
2252
+ fileInput.style.display = 'none';
2253
+ const attach = el('button', {
2254
+ class: 'cx-livechat__attach',
2255
+ type: 'button',
2256
+ 'aria-label': this.messages.attachLabel
2257
+ });
2258
+ attach.innerHTML = ATTACH_ICON;
2259
+ attach.addEventListener('click', ()=>fileInput.click());
2260
+ fileInput.addEventListener('change', ()=>{
2261
+ const files = Array.from(fileInput.files ?? []);
2262
+ // Limpa para o mesmo arquivo poder ser escolhido de novo depois de removido.
2263
+ fileInput.value = '';
2264
+ this.queueAttachments(files);
2265
+ });
2266
+ return [
2267
+ attach,
2268
+ fileInput
2269
+ ];
2270
+ }
2271
+ /**
2272
+ * Arrastar arquivos para cima da janela. Registrado uma vez no shell; só reage enquanto o
2273
+ * composer livre (com a fila de anexos) está montado — num nó do roteiro o drop é ignorado.
2274
+ */ bindFileDrop() {
2275
+ this.windowEl.setAttribute('data-drop-label', this.messages.dropFilesLabel);
2276
+ const accepts = (event)=>Boolean(this.attachmentsEl?.isConnected && event.dataTransfer?.types.includes('Files'));
2277
+ this.windowEl.addEventListener('dragover', (event)=>{
2278
+ if (!accepts(event)) return;
2279
+ event.preventDefault();
2280
+ this.windowEl.classList.add('cx-livechat__window--dragover');
2281
+ });
2282
+ this.windowEl.addEventListener('dragleave', (event)=>{
2283
+ const next = event.relatedTarget;
2284
+ if (next instanceof Node && this.windowEl.contains(next)) return;
2285
+ this.windowEl.classList.remove('cx-livechat__window--dragover');
2286
+ });
2287
+ this.windowEl.addEventListener('drop', (event)=>{
2288
+ this.windowEl.classList.remove('cx-livechat__window--dragover');
2289
+ if (!accepts(event)) return;
2290
+ event.preventDefault();
2291
+ this.queueAttachments(Array.from(event.dataTransfer?.files ?? []));
2292
+ });
2293
+ }
2294
+ /**
2295
+ * Entrada única do clipe, do colar e do arrastar: recusa na hora o que o servidor recusaria
2296
+ * (tipo, tamanho, mais de 5 na fila) e sobe o resto em sequência.
2297
+ */ queueAttachments(files) {
2298
+ const notes = new Set();
2299
+ for (const picked of files){
2300
+ const file = withAttachmentType(picked);
2301
+ if (this.uploads.length >= ATTACHMENTS_PER_MESSAGE) {
2302
+ notes.add(this.messages.attachmentLimitReached);
2303
+ break;
2304
+ }
2305
+ const problem = checkAttachmentFile(file);
2306
+ if (problem) {
2307
+ notes.add(problem === 'type' ? this.messages.attachmentTypeNotAllowed : this.messages.attachmentTooLarge);
2308
+ continue;
2309
+ }
2310
+ const kind = attachmentKind(file.type);
2311
+ const previewUrl = kind === 'file' ? null : URL.createObjectURL(file);
2312
+ if (previewUrl) this.objectUrls.add(previewUrl);
2313
+ const pending = {
2314
+ key: ++this.uploadSeq,
2315
+ name: file.name,
2316
+ kind,
2317
+ previewUrl,
2318
+ attachment: null
2319
+ };
2320
+ this.uploads.push(pending);
2321
+ this.uploadChain = this.uploadChain.then(()=>this.uploadAttachment(pending, file));
2322
+ }
2323
+ this.renderPendingUploads();
2324
+ for (const note of notes)this.renderNote(note);
2325
+ }
2326
+ async uploadAttachment(pending, file) {
2327
+ // Removido pelo visitante antes de chegar a vez dele na fila.
2328
+ if (!this.uploads.includes(pending) || this.destroyed) return;
2329
+ if (this.isPreview) {
2330
+ // Prévia do construtor: nada sobe. Uma referência local deixa o envio desenhar a bolha.
2331
+ pending.attachment = {
2332
+ fileId: `preview-${pending.key}`,
2333
+ name: file.name,
2334
+ mimeType: file.type,
2335
+ size: file.size
2336
+ };
2337
+ this.renderPendingUploads();
2338
+ return;
2339
+ }
2340
+ try {
2341
+ const attachment = await uploadLiveChatAttachment(this.cx, this.options.channelId, this.visitorHash, file, this.options.apiOverride);
2342
+ // Removido pelo visitante enquanto subia: não volta.
2343
+ if (!this.uploads.includes(pending)) return;
2344
+ pending.attachment = attachment;
2345
+ } catch (error) {
2346
+ this.cx.debug('LiveChat attachment upload failed', error);
2347
+ this.uploads = this.uploads.filter((u)=>u !== pending);
2348
+ this.releasePreview(pending);
2349
+ if (!this.destroyed) this.renderNote(this.messages.attachmentUploadFailed);
2350
+ }
2351
+ this.renderPendingUploads();
2352
+ }
2353
+ /**
2354
+ * Item que saiu da fila sem ser enviado (X ou falha no upload): a miniatura não volta. Só uma
2355
+ * bolha enviada segura a URL, até o `destroy`.
2356
+ */ releasePreview(upload) {
2357
+ if (!upload.previewUrl) return;
2358
+ URL.revokeObjectURL(upload.previewUrl);
2359
+ this.objectUrls.delete(upload.previewUrl);
2360
+ }
2361
+ /** Fila acima do composer: miniatura para foto/vídeo, chip com o nome para documento. */ renderPendingUploads() {
2362
+ if (!this.attachmentsEl) return;
2363
+ const items = this.uploads.map((upload)=>{
2364
+ const remove = el('button', {
2365
+ class: 'cx-livechat__chip-remove',
2366
+ type: 'button',
2367
+ 'aria-label': this.messages.removeAttachmentLabel
2368
+ });
2369
+ remove.innerHTML = CLOSE_ICON;
2370
+ remove.addEventListener('click', ()=>{
2371
+ this.uploads = this.uploads.filter((u)=>u !== upload);
2372
+ this.releasePreview(upload);
2373
+ this.renderPendingUploads();
2374
+ });
2375
+ const uploading = upload.attachment ? '' : ' cx-livechat__chip--uploading';
2376
+ if (upload.previewUrl) {
2377
+ const thumb = upload.kind === 'image' ? el('img', {
2378
+ class: 'cx-livechat__thumb-media',
2379
+ src: upload.previewUrl,
2380
+ alt: ''
2381
+ }) : el('video', {
2382
+ class: 'cx-livechat__thumb-media',
2383
+ src: upload.previewUrl,
2384
+ muted: '',
2385
+ preload: 'metadata',
2386
+ playsinline: ''
2387
+ });
2388
+ const tile = el('span', {
2389
+ class: `cx-livechat__thumb${uploading}`,
2390
+ title: upload.name
2391
+ }, [
2392
+ thumb
2393
+ ]);
2394
+ if (upload.kind === 'video') {
2395
+ const play = el('span', {
2396
+ class: 'cx-livechat__thumb-play'
2397
+ });
2398
+ play.innerHTML = PLAY_ICON;
2399
+ tile.append(play);
2400
+ }
2401
+ tile.append(remove);
2402
+ return tile;
2403
+ }
2404
+ const name = el('span', {
2405
+ class: 'cx-livechat__chip-name'
2406
+ });
2407
+ name.textContent = upload.name;
2408
+ return el('span', {
2409
+ class: `cx-livechat__chip${uploading}`
2410
+ }, [
2411
+ name,
2412
+ remove
2413
+ ]);
2414
+ });
2415
+ this.attachmentsEl.replaceChildren(...items);
2416
+ }
2417
+ /**
2418
+ * Tira da fila os anexos que já subiram (vão nesta mensagem, até 5); os em voo continuam na
2419
+ * fila. A miniatura (`previewUrl`) segue viva: vira a bolha do visitante.
2420
+ */ takeUploadedAttachments() {
2421
+ const ready = this.uploads.filter((u)=>u.attachment).slice(0, ATTACHMENTS_PER_MESSAGE);
2422
+ if (ready.length) {
2423
+ this.uploads = this.uploads.filter((u)=>!ready.includes(u));
2424
+ this.renderPendingUploads();
2425
+ }
2426
+ return ready;
2427
+ }
2428
+ /**
2429
+ * Bolhas do envio com anexos do composer: a legenda (se houver) e uma bolha por arquivo, na mesma
2430
+ * ordem em que a conversa grava (texto primeiro, depois cada mídia).
2431
+ */ renderLocalUploads(text, local) {
2432
+ const bubbles = [];
2433
+ if (local.showText) bubbles.push(this.renderBubble('visitor', text));
2434
+ for (const upload of local.uploads){
2435
+ if (upload.attachment) this.sentAttachmentIds.add(upload.attachment.fileId);
2436
+ const media = buildLocalAttachmentMedia(upload.kind, upload.previewUrl, upload.name, {
2437
+ fileLabel: upload.name,
2438
+ imageLabel: this.messages.imageAttachmentLabel,
2439
+ onZoom: (url)=>this.openAvatarLightbox(url)
2440
+ });
2441
+ bubbles.push(this.renderBubble('visitor', upload.name, undefined, undefined, undefined, media));
2442
+ }
2443
+ return bubbles;
2444
+ }
2445
+ /**
2446
+ * Mídia do visitante que volta no polling e este widget já desenhou (`sentAttachmentIds`).
2447
+ * O `fileId` (UUID) está no caminho da URL pública. Consome a marca: aparece uma vez só.
2448
+ */ consumeSentAttachment(content) {
2449
+ for (const fileId of this.sentAttachmentIds){
2450
+ if (content.includes(`/${fileId}/`)) {
2451
+ this.sentAttachmentIds.delete(fileId);
2452
+ return true;
2453
+ }
2454
+ }
2455
+ return false;
2456
+ }
2457
+ /** `true` = o servidor aceitou a mensagem (a prévia nunca envia: `false`). */ async send(text, nodeId, extras, /** Anexos do próprio composer: bolhas com a mídia local em vez dos chips com o nome. */ local) {
2458
+ const bubbles = local ? this.renderLocalUploads(text, local) : [
2459
+ this.renderBubble('visitor', text, undefined, extras?.attachments)
2460
+ ];
2461
+ if (this.isPreview) return false;
2462
+ this.flowEcho.push({
2463
+ side: 'visitor',
2464
+ content: text
2465
+ });
2466
+ const visitor = this.pendingVisitorInfo ?? undefined;
2467
+ this.pendingVisitorInfo = null;
2468
+ // Backfill das bolhas do bot mostradas antes desta resposta (esvazia o buffer).
2469
+ const botMessages = this.botBuffer;
2470
+ this.botBuffer = [];
2471
+ const request = sendLiveChatMessage(this.cx, this.options.channelId, {
2472
+ visitorHash: this.visitorHash,
2473
+ text,
2474
+ ...nodeId && {
2475
+ nodeId
2476
+ },
2477
+ ...visitor && {
2478
+ visitor
2479
+ },
2480
+ ...botMessages.length ? {
2481
+ botMessages
2482
+ } : {},
2483
+ ...extras?.intent && {
2484
+ intent: extras.intent
2485
+ },
2486
+ ...extras?.context && {
2487
+ context: extras.context
2488
+ },
2489
+ ...extras?.attachments?.length ? {
2490
+ attachments: extras.attachments
2491
+ } : {},
2492
+ ...this.options.identity && {
2493
+ identity: this.options.identity
2494
+ }
2495
+ }, this.options.apiOverride);
2496
+ // A falha é tratada no `catch` abaixo; quem espera só quer saber que o envio terminou.
2497
+ this.inFlightSend = request.then(()=>undefined, ()=>undefined);
2498
+ try {
2499
+ await request;
2500
+ this.messageSent = true;
2501
+ this.emit('chat_message_sent');
2502
+ return true;
2503
+ } catch (error) {
2504
+ this.cx.error(error, 'LiveChat message send failed');
2505
+ // Devolve payload do pré-chat e buffer do bot pra próxima tentativa não perder nada
2506
+ if (visitor) this.pendingVisitorInfo = visitor;
2507
+ this.botBuffer = [
2508
+ ...botMessages,
2509
+ ...this.botBuffer
2510
+ ];
2511
+ for (const bubble of bubbles)bubble.classList.add('cx-livechat__bubble--failed');
2512
+ return false;
2513
+ }
2514
+ }
2515
+ // ── Sessão do roteiro (analytics por etapa) ────────────────────────────────
2516
+ /** Abre uma execução nova do roteiro: cada início (inclusive o refazer após abandono) é uma. */ startFlowSession() {
2517
+ if (this.isPreview) return;
2518
+ this.flowSession = {
2519
+ id: null,
2520
+ pending: [],
2521
+ answers: [],
2522
+ queue: Promise.resolve()
2523
+ };
2524
+ }
2525
+ /**
2526
+ * Manda as etapas e respostas acumuladas, em fila (cada remessa precisa do id devolvido pela
2527
+ * 1ª). Com `outcome` encerra a sessão. Falha de rede é engolida (debug); se a 1ª remessa
2528
+ * falhar, as etapas voltam para a próxima, que tenta abrir a sessão de novo.
2529
+ */ flushFlowSession(outcome) {
2530
+ const session = this.flowSession;
2531
+ if (!session) return;
2532
+ if (outcome) this.flowSession = null;
2533
+ if (!outcome && session.pending.length === 0 && session.answers.length === 0) return;
2534
+ session.queue = session.queue.then(async ()=>{
2535
+ // O lote sai da fila na hora do envio, não na hora do pedido: o que uma remessa anterior
2536
+ // devolveu à fila por falha entra nesta, inclusive na final (que encerra a sessão).
2537
+ const stepIds = session.pending.splice(0);
2538
+ const answers = session.answers.splice(0);
2539
+ if (!outcome && stepIds.length === 0 && answers.length === 0) return;
2540
+ const opening = session.id === null;
2541
+ // A remessa final grava a linha do histórico do contato, e o contato nasce da resposta que
2542
+ // pode estar em voo (resposta → Encerrar logo em seguida): espera ela, como o handoff.
2543
+ if (outcome) await this.inFlightSend?.catch(()=>undefined);
2544
+ try {
2545
+ const utm = getPageUtmValues();
2546
+ const { sessionId } = await sendFlowSession(this.cx, this.options.channelId, {
2547
+ visitorHash: this.visitorHash,
2548
+ ...session.id && {
2549
+ sessionId: session.id
2550
+ },
2551
+ stepIds,
2552
+ ...answers.length > 0 && {
2553
+ answers
2554
+ },
2555
+ ...outcome && {
2556
+ outcome
2557
+ },
2558
+ ...opening && {
2559
+ utm: {
2560
+ source: utm.utmSource,
2561
+ medium: utm.utmMedium,
2562
+ campaign: utm.utmCampaign,
2563
+ term: utm.utmTerm,
2564
+ content: utm.utmContent
2565
+ }
2566
+ }
2567
+ }, this.options.apiOverride);
2568
+ session.id = sessionId ?? session.id;
2569
+ } catch (error) {
2570
+ this.cx.debug('LiveChat flow session failed', {
2571
+ op: 'flowSession',
2572
+ channelId: this.options.channelId,
2573
+ sessionId: session.id,
2574
+ outcome: outcome ?? null,
2575
+ error
2576
+ });
2577
+ // Devolve o lote para a próxima remessa: o servidor ignora etapa repetida e mescla as
2578
+ // respostas, então reenviar é seguro.
2579
+ session.pending.unshift(...stepIds);
2580
+ session.answers.unshift(...answers);
2581
+ }
2582
+ });
2583
+ }
2584
+ // ── Funil (FLOWS-2234): visita + gatilhos do nó webchat ─────────────────────
2585
+ /**
2586
+ * Envia um evento do funil — no máximo uma vez por carga — e segue o destino do gatilho
2587
+ * conectado. Só na tela cheia/embed (a página do webchat que o funil publica): o balão
2588
+ * flutuante vive em sites quaisquer do dono, e o reverse lookup por canal do servidor
2589
+ * tiraria o visitante da página dele. Nunca na prévia do construtor. Falha de rede é
2590
+ * engolida (debug): o funil nunca pode quebrar a conversa.
2591
+ */ trackFunnelEvent(event, ready) {
2592
+ if (this.isPreview || !this.fullscreen || this.funnelEventsSent.has(event)) return;
2593
+ this.funnelEventsSent.add(event);
2594
+ // Fila: eventos saem na ordem em que aconteceram, mesmo quando um deles espera outra
2595
+ // requisição (`ready`, ex.: o envio da captura). O primeiro destino seguido vence
2596
+ // (`funnelExitShown`); os seguintes só contam para o analytics.
2597
+ this.funnelQueue = this.funnelQueue.then(async ()=>{
2598
+ // Envio que pré-condiciona o evento falhou (ex.: a mensagem da captura): libera o evento
2599
+ // para uma nova tentativa nesta carga, em vez de dá-lo por enviado.
2600
+ if (ready && !await ready.catch(()=>false)) {
2601
+ this.funnelEventsSent.delete(event);
2602
+ return;
2603
+ }
2604
+ try {
2605
+ const result = await sendFunnelEvent(this.cx, this.options.channelId, {
2606
+ visitorHash: this.visitorHash,
2607
+ event,
2608
+ ...this.funnelContext
2609
+ }, this.options.apiOverride);
2610
+ if (event !== 'view') this.followFunnelExit(result);
2611
+ } catch (error) {
2612
+ this.cx.debug(`LiveChat funnel event "${event}" failed`, error);
2613
+ }
2614
+ });
2615
+ }
2616
+ /**
2617
+ * Destino do gatilho: `redirect` avisa e navega após ~1,5s; `button` anexa "Continuar" ao fim
2618
+ * da conversa. Sem `nextUrl` (gatilho desconectado) nada muda — no handoff a conversa segue
2619
+ * com a equipe normalmente.
2620
+ */ followFunnelExit(result) {
2621
+ if (this.destroyed || this.funnelExitShown || !result.nextUrl) return;
2622
+ const href = buildFunnelNextUrl(result.nextUrl);
2623
+ if (!href) return;
2624
+ this.funnelExitShown = true;
2625
+ if (result.exitMode === 'button') {
2626
+ const button = el('button', {
2627
+ class: 'cx-livechat__funnel-continue',
2628
+ type: 'button'
2629
+ }, [
2630
+ this.messages.funnelContinue
2631
+ ]);
2632
+ button.addEventListener('click', ()=>window.location.assign(href));
2633
+ this.messagesEl.append(button);
2634
+ this.messagesEl.scrollTop = this.messagesEl.scrollHeight;
2635
+ return;
2636
+ }
2637
+ this.renderNote(this.messages.funnelRedirecting);
2638
+ if (this.funnelRedirectTimer !== null) clearTimeout(this.funnelRedirectTimer);
2639
+ this.funnelRedirectTimer = setTimeout(()=>{
2640
+ this.funnelRedirectTimer = null;
2641
+ if (!this.destroyed) window.location.assign(href);
2642
+ }, FUNNEL_REDIRECT_DELAY_MS);
2643
+ }
2644
+ // ── Polling (respostas do atendente) ───────────────────────────────────────
2645
+ startPolling() {
2646
+ if (this.isPreview || this.pollTimer !== null) return;
2647
+ this.scheduleNextPoll(0);
2648
+ }
2649
+ stopPolling() {
2650
+ if (this.pollTimer !== null) {
2651
+ clearTimeout(this.pollTimer);
2652
+ this.pollTimer = null;
2653
+ }
2654
+ }
2655
+ scheduleNextPoll(delay) {
2656
+ this.pollTimer = setTimeout(()=>{
2657
+ void this.poll().finally(()=>{
2658
+ if ((this.isOpen || this.pollWhileClosed) && this.pollTimer !== null) {
2659
+ this.scheduleNextPoll(POLL_INTERVAL_MS);
2660
+ }
2661
+ });
2662
+ }, delay);
2663
+ }
2664
+ async poll() {
2665
+ if (this.pollInFlight || !this.bootstrapped) return;
2666
+ this.pollInFlight = true;
2667
+ try {
2668
+ const view = await pollLiveChatMessages(this.cx, this.options.channelId, this.visitorHash, this.lastCreatedAt, this.options.apiOverride);
2669
+ this.appendPolledMessages(view.messages, {
2670
+ silent: false
2671
+ });
2672
+ this.syncAttendance(view.thread?.attendance ?? null);
2673
+ } catch (error) {
2674
+ this.cx.debug('LiveChat poll failed', error);
2675
+ } finally{
2676
+ this.pollInFlight = false;
2677
+ }
2678
+ }
2679
+ /**
2680
+ * Avisa o visitante quando a conversa passa para a equipe ou quando um atendente entra. Sem isso
2681
+ * a transferência era invisível: o pedido de atendente, a escalada do SDR de IA e a atribuição
2682
+ * só apareciam para a equipe, e o visitante via o mesmo chat de sempre ficar em silêncio.
2683
+ */ syncAttendance(next) {
2684
+ const previous = this.attendance;
2685
+ this.attendance = next;
2686
+ if (previous === undefined || previous === next) return;
2687
+ if (next === 'queued') this.renderNote(this.messages.handoffQueued);
2688
+ if (next === 'human') this.renderNote(this.messages.handoffHuman);
2689
+ }
2690
+ /** Aviso do sistema no meio da conversa: centralizado, fora das bolhas de agente/visitante. */ renderNote(content) {
2691
+ const note = el('div', {
2692
+ class: 'cx-livechat__note',
2693
+ role: 'status'
2694
+ });
2695
+ note.textContent = content;
2696
+ this.messagesEl.append(note);
2697
+ // A próxima fala do agente abre grupo novo (nome no topo), como depois de qualquer quebra.
2698
+ this.lastBubbleSide = null;
2699
+ this.lastAgentAvatarSlot = null;
2700
+ this.messagesEl.scrollTop = this.messagesEl.scrollHeight;
2701
+ }
2702
+ /**
2703
+ * Histórico que não vai para a tela (roteiro do funil recomeçando): marca como visto para o
2704
+ * polling não despejar as bolhas antigas no meio do roteiro novo.
2705
+ */ markMessagesSeen(messages) {
2706
+ for (const message of messages){
2707
+ this.knownMessageIds.add(message.id);
2708
+ if (!this.lastCreatedAt || message.createdAt > this.lastCreatedAt) {
2709
+ this.lastCreatedAt = message.createdAt;
2710
+ }
2711
+ }
2712
+ }
2713
+ appendPolledMessages(messages, { silent }) {
2714
+ for (const message of messages){
2715
+ if (this.knownMessageIds.has(message.id)) continue;
2716
+ this.knownMessageIds.add(message.id);
2717
+ if (!this.lastCreatedAt || message.createdAt > this.lastCreatedAt) {
2718
+ this.lastCreatedAt = message.createdAt;
2719
+ }
2720
+ const side = message.direction === 'inbound' ? 'visitor' : 'agent';
2721
+ if (side === 'visitor' && message.contentType !== undefined && message.contentType !== 'text' && this.consumeSentAttachment(message.content)) {
2722
+ continue;
2723
+ }
2724
+ // Já renderizado pelo fluxo nesta sessão? Consome o echo e não duplica.
2725
+ const echoIndex = this.flowEcho.findIndex((e)=>e.side === side && e.content === message.content);
2726
+ if (echoIndex !== -1) {
2727
+ this.flowEcho.splice(echoIndex, 1);
2728
+ continue;
2729
+ }
2730
+ this.renderBubble(side, message.content, message.createdAt, message.attachments, message.contentType);
2731
+ if (side === 'agent' && !silent) {
2732
+ this.emit('chat_message_received');
2733
+ // FLOWS-2457: chegou sem ninguém olhando (balão fechado ou host com o modal fechado).
2734
+ if (!this.isOpen || this.hostHidden) this.setUnread(this.unreadCount + 1);
2735
+ }
2736
+ }
2737
+ }
2738
+ // ── Render helpers ─────────────────────────────────────────────────────────
2739
+ /**
2740
+ * Composer de resposta livre (input + botão enviar) dos nós que esperam texto do
2741
+ * visitante: `ai` (classifica o texto num ramo) e `question` no modo `text`.
2742
+ * `onText` só roda depois do guard de consentimento, com texto não-vazio e com o
2743
+ * form já removido do footer — o callback fica livre pra render o próximo nó.
2744
+ */ buildTextComposer(onText) {
2745
+ const input = el('input', {
2746
+ class: 'cx-livechat__input',
2747
+ placeholder: this.messages.inputPlaceholder,
2748
+ type: 'text',
2749
+ autocomplete: 'off'
2750
+ });
2751
+ const sendBtn = el('button', {
2752
+ class: 'cx-livechat__send',
2753
+ type: 'submit',
2754
+ 'aria-label': this.messages.sendLabel
2755
+ });
2756
+ sendBtn.innerHTML = SEND_ICON;
2757
+ const form = el('form', {
2758
+ class: 'cx-livechat__composer'
2759
+ }, [
2760
+ input,
2761
+ sendBtn
2762
+ ]);
2763
+ form.addEventListener('submit', (event)=>{
2764
+ event.preventDefault();
2765
+ if (!this.guardConsent()) return;
2766
+ const text = input.value.trim();
2767
+ if (!text) return;
2768
+ input.value = '';
2769
+ form.remove();
2770
+ onText(text);
2771
+ });
2772
+ return form;
2773
+ }
2774
+ /** Põe o composer no footer e devolve o cursor pro visitante (focus só cola depois de anexado). */ mountComposer(form) {
2775
+ this.footerEl.replaceChildren(form);
2776
+ form.querySelector('input')?.focus();
2777
+ }
2778
+ /** Indicador "digitando…" (3 pontinhos). Idempotente. */ showTyping() {
2779
+ if (this.typingEl) return;
2780
+ const dots = el('div', {
2781
+ class: 'cx-livechat__typing'
2782
+ });
2783
+ dots.innerHTML = '<span></span><span></span><span></span>';
2784
+ this.messagesEl.append(dots);
2785
+ this.messagesEl.scrollTop = this.messagesEl.scrollHeight;
2786
+ this.typingEl = dots;
2787
+ }
2788
+ hideTyping() {
2789
+ this.typingEl?.remove();
2790
+ this.typingEl = null;
2791
+ }
2792
+ sleep(ms) {
2793
+ return new Promise((resolve)=>setTimeout(resolve, ms));
2794
+ }
2795
+ /**
2796
+ * Bolha automática do bot: mostra "digitando…" antes de aparecer (mensagens
2797
+ * programadas ~600ms; no nó de IA o indicador já vem aberto desde o classify,
2798
+ * então emenda). Registra o echo (dedup do polling) e enfileira pro backfill.
2799
+ * Devolve `false` se o widget foi desmontado no meio — o chamador interrompe o fluxo.
2800
+ */ async botSay(content) {
2801
+ this.showTyping();
2802
+ await this.sleep(600);
2803
+ // Widget desmontado durante o "digitando…" (a prévia remonta a cada mudança):
2804
+ // `false` avisa o `runNode` para não seguir o fluxo com o rascunho antigo.
2805
+ if (this.destroyed) return false;
2806
+ this.hideTyping();
2807
+ this.renderBubble('agent', content);
2808
+ this.flowEcho.push({
2809
+ side: 'agent',
2810
+ content
2811
+ });
2812
+ this.botBuffer.push(content);
2813
+ return true;
2814
+ }
2815
+ renderBubble(side, content, time, attachments, contentType, /** Mídia já montada (anexo local do visitante, `renderLocalUploads`); vence `contentType`. */ localMedia) {
2816
+ const groupStart = this.lastBubbleSide !== side;
2817
+ const bubble = el('div', {
2818
+ class: `cx-livechat__bubble cx-livechat__bubble--${side}`
2819
+ });
2820
+ // Nome do atendente só na primeira bolha de um grupo (tipo WhatsApp).
2821
+ if (side === 'agent' && groupStart && this.agentName) {
2822
+ bubble.append(el('div', {
2823
+ class: 'cx-livechat__bubble-name'
2824
+ }, [
2825
+ this.agentName
2826
+ ]));
2827
+ }
2828
+ // FLOWS-2457: mídia do atendente (imagem/vídeo/arquivo) — `content` é a URL do upload.
2829
+ // URL não-https cai no texto puro (inerte), nunca vira href/src.
2830
+ // Sem nome de arquivo guardado, o link vira "Anexo (1)", "Anexo (2)"… na ordem da conversa —
2831
+ // contado no DOM, que zera junto com a lista quando a conversa troca.
2832
+ const fileNumber = this.messagesEl.querySelectorAll('.cx-livechat__bubble-file').length + 1;
2833
+ const media = localMedia ?? buildMessageMedia(contentType, content, {
2834
+ fileLabel: this.messages.fileAttachmentLabel.replace('{number}', String(fileNumber)),
2835
+ imageLabel: this.messages.imageAttachmentLabel
2836
+ });
2837
+ if (media) {
2838
+ bubble.append(media);
2839
+ } else {
2840
+ const text = el('div', {
2841
+ class: 'cx-livechat__bubble-text'
2842
+ });
2843
+ appendLinkifiedText(text, content);
2844
+ bubble.append(text);
2845
+ }
2846
+ // FLOWS-2457: anexos como chips (nome + clipe). Sem link: a rota pública não serve o
2847
+ // arquivo — quem baixa é o atendente, pelo Drive do workspace.
2848
+ if (attachments?.length) {
2849
+ const list = el('div', {
2850
+ class: 'cx-livechat__bubble-attachments'
2851
+ });
2852
+ for (const attachment of attachments){
2853
+ const chip = el('span', {
2854
+ class: 'cx-livechat__bubble-attachment'
2855
+ });
2856
+ chip.innerHTML = ATTACH_ICON;
2857
+ const name = el('span');
2858
+ name.textContent = attachment.name;
2859
+ chip.append(name);
2860
+ list.append(chip);
2861
+ }
2862
+ bubble.append(list);
2863
+ }
2864
+ // Carimbo: usa o createdAt real da mensagem (histórico vindo do polling) quando
2865
+ // fornecido; senão o horário atual (bolhas geradas localmente pelo fluxo/bot).
2866
+ const stamp = time ? formatClock(new Date(time)) : nowTime();
2867
+ bubble.append(el('span', {
2868
+ class: 'cx-livechat__bubble-time'
2869
+ }, [
2870
+ stamp
2871
+ ]));
2872
+ const row = el('div', {
2873
+ class: `cx-livechat__row cx-livechat__row--${side}`
2874
+ });
2875
+ if (side === 'agent') {
2876
+ // Avatar só na ÚLTIMA bolha do grupo: esvazia o slot da bolha anterior e
2877
+ // (re)coloca nesta. O slot vazio nas bolhas anteriores mantém o alinhamento.
2878
+ this.lastAgentAvatarSlot?.replaceChildren();
2879
+ const slot = el('span', {
2880
+ class: 'cx-livechat__row-avatar'
2881
+ });
2882
+ if (this.avatarUrl) {
2883
+ slot.append(el('img', {
2884
+ src: this.avatarUrl,
2885
+ alt: ''
2886
+ }));
2887
+ this.lastAgentAvatarSlot = slot;
2888
+ } else {
2889
+ this.lastAgentAvatarSlot = null;
2890
+ }
2891
+ row.append(slot, bubble);
2892
+ } else {
2893
+ this.lastAgentAvatarSlot = null;
2894
+ row.append(bubble);
2895
+ }
2896
+ this.messagesEl.append(row);
2897
+ this.lastBubbleSide = side;
2898
+ this.messagesEl.scrollTop = this.messagesEl.scrollHeight;
2899
+ return bubble;
2900
+ }
2901
+ }
2902
+ function createLiveChatWidget(cx, options) {
2903
+ return new LiveChatWidget(cx, options);
2904
+ }
2905
+
2906
+ const widgetinline = __webpack_require__("./src/widget/styles/widget.scss?inline");
2907
+
2908
+
2909
+
2910
+
2911
+ const STYLE_ATTRIBUTE = 'data-cx-webchat-styles';
2912
+ /** One `<style>` per document, kept after unmount: the next chat on the page reuses it. */ function injectStyles() {
2913
+ if (document.head.querySelector(`style[${STYLE_ATTRIBUTE}]`)) return;
2914
+ const style = document.createElement('style');
2915
+ style.setAttribute(STYLE_ATTRIBUTE, '');
2916
+ style.textContent = widgetinline.A;
2917
+ document.head.appendChild(style);
2918
+ }
2919
+ /** Compared by value: a new object with the same fields must not refetch the config. */ function identityKey(identity) {
2920
+ return identity ? JSON.stringify([
2921
+ identity.name,
2922
+ identity.email,
2923
+ identity.signature
2924
+ ]) : '';
2925
+ }
2926
+ /**
2927
+ * The Clickmax WebChat of a channel. Renders a `<div>` and, after hydration, the chat: a launcher
2928
+ * in a corner (or full screen, or inside the `<div>` with `mode="embed"`). Unmounting removes the
2929
+ * chat, its timers and its listeners, so render it in the routes where it should appear.
2930
+ */ function ClickmaxWebchat(props) {
2931
+ const { channelId, apiUrl, locale, theme, accentColor, position, mode, identity, onEvent, onError, ...rest } = props;
2932
+ const host = useRef(null);
2933
+ const widget = useRef(null);
2934
+ const callbacks = useRef({
2935
+ onEvent,
2936
+ onError
2937
+ });
2938
+ callbacks.current = {
2939
+ onEvent,
2940
+ onError
2941
+ };
2942
+ const identityRef = useRef(identity);
2943
+ identityRef.current = identity;
2944
+ const currentIdentity = identityKey(identity);
2945
+ const mountedIdentity = useRef('');
2946
+ useEffect(()=>{
2947
+ const node = host.current;
2948
+ if (!node || !channelId) return;
2949
+ injectStyles();
2950
+ const cx = {
2951
+ apiUrl: apiUrl || window.location.origin,
2952
+ bus: {
2953
+ emit: (type, payload)=>{
2954
+ try {
2955
+ callbacks.current.onEvent?.({
2956
+ type,
2957
+ channelId: payload.channelId
2958
+ });
2959
+ } catch (error) {
2960
+ console.error('[clickmax-webchat] onEvent threw', {
2961
+ op: 'onEvent',
2962
+ type,
2963
+ error
2964
+ });
2965
+ }
2966
+ }
2967
+ },
2968
+ debug: ()=>{},
2969
+ error: (error, message)=>{
2970
+ const log = ()=>console.error(`[clickmax-webchat] ${message}`, {
2971
+ op: 'webchat',
2972
+ channelId,
2973
+ error
2974
+ });
2975
+ if (!callbacks.current.onError) return log();
2976
+ // The widget calls this mid-recovery (restoring a failed send); a throwing host must not stop it.
2977
+ try {
2978
+ callbacks.current.onError(error, message);
2979
+ } catch (hostError) {
2980
+ console.error('[clickmax-webchat] onError threw', {
2981
+ op: 'onError',
2982
+ channelId,
2983
+ error: hostError
2984
+ });
2985
+ log();
2986
+ }
2987
+ }
2988
+ };
2989
+ // `mode="embed"` makes this div a positioned box with a minimum height; a later mode without
2990
+ // embed reuses the same div, so cleanup undoes what the widget set, and only while it is still
2991
+ // the widget's value (a `style` prop React applied since then wins).
2992
+ const before = {
2993
+ position: node.style.position,
2994
+ minHeight: node.style.minHeight
2995
+ };
2996
+ const created = createLiveChatWidget(cx, {
2997
+ channelId,
2998
+ locale,
2999
+ theme,
3000
+ accentColor,
3001
+ position,
3002
+ mode,
3003
+ host: node,
3004
+ identity: identityRef.current ?? undefined
3005
+ });
3006
+ widget.current = created;
3007
+ mountedIdentity.current = identityKey(identityRef.current);
3008
+ const set = {
3009
+ position: node.style.position,
3010
+ minHeight: node.style.minHeight
3011
+ };
3012
+ return ()=>{
3013
+ created.destroy();
3014
+ for (const key of [
3015
+ 'position',
3016
+ 'minHeight'
3017
+ ]){
3018
+ if (set[key] !== before[key] && node.style[key] === set[key]) node.style[key] = before[key];
3019
+ }
3020
+ if (widget.current === created) widget.current = null;
3021
+ };
3022
+ }, [
3023
+ channelId,
3024
+ apiUrl,
3025
+ locale,
3026
+ theme,
3027
+ accentColor,
3028
+ position,
3029
+ mode
3030
+ ]);
3031
+ useEffect(()=>{
3032
+ if (!widget.current || mountedIdentity.current === currentIdentity) return;
3033
+ mountedIdentity.current = currentIdentity;
3034
+ widget.current.identify(identityRef.current ?? undefined);
3035
+ }, [
3036
+ currentIdentity
3037
+ ]);
3038
+ return /*#__PURE__*/ jsx("div", {
3039
+ ...rest,
3040
+ ref: host
3041
+ });
3042
+ }
3043
+
3044
+
3045
+
3046
+ export { ClickmaxWebchat };