@theonexai/chartsconnect-chat-widget 1.0.39 → 1.0.41

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.
@@ -1,4 +1,4 @@
1
- "use strict";const e="undefined"!=typeof process&&process.env?.REACT_APP_BACKEND_BASE_URL||"http://localhost:8012";const t="chat_session_id";class n{constructor(){this.sessionId=null,this.sessionId=this.loadSessionId()}loadSessionId(){return"undefined"!=typeof localStorage?localStorage.getItem(t):null}saveSessionId(e){this.sessionId=e,"undefined"!=typeof localStorage&&(e?localStorage.setItem(t,e):localStorage.removeItem(t))}updateSessionFromResponse(e){const t=e?.data?.session_id||e?.session_id;t&&"string"==typeof t&&this.saveSessionId(t)}getSessionId(){return this.sessionId||""}getSessionHeader(){return{"X-Session-ID":this.getSessionId()}}}let s=null;class o extends Error{constructor(e="chat_resolved"){super(e),this.reason="chat_resolved",this.name="ChatResolvedError"}}class r{constructor(e={}){this.ws=null,this.wsReconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectTimeout=null,this.pingInterval=null,this.currentChatId=null,this.currentSessionId=null,this.messageHandlers=new Set,this.connectionHandlers=new Set,this.baseUrl=e.baseUrl||"https://susy-cany-alida.ngrok-free.dev",this.wsUrl=e.wsUrl||"wss://susy-cany-alida.ngrok-free.dev",this.debug=e.debug||!1,this.sessionManager=(s||(s=new n),s)}async startSupportChat(e){try{const t={"Content-Type":"application/json",...this.sessionManager.getSessionHeader()};e&&(t["X-Session-ID"]=e);const n=await fetch(`${this.baseUrl}/api/support/chat/start`,{method:"POST",headers:t,body:JSON.stringify({})});if(!n.ok){const e=n.headers.get("content-type");let t={};if(!e||!e.includes("application/json")){await n.text();throw new Error(`API endpoint returned HTML instead of JSON. Status: ${n.status}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${this.baseUrl}/api/support/chat/start`)}try{t=await n.json()}catch{t={}}throw new Error(t.message||`HTTP error! status: ${n.status}`)}const s=n.headers.get("content-type");if(!s||!s.includes("application/json")){await n.text();throw new Error(`API endpoint returned non-JSON response. Status: ${n.status}. Content-Type: ${s||"unknown"}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${this.baseUrl}/api/support/chat/start`)}const o=await n.json();if(this.sessionManager.updateSessionFromResponse(o),o.status&&o.data)return{chat_id:o.data.chat_id,session_id:o.data.session_id};if(o.chat_id&&o.session_id)return{chat_id:o.chat_id,session_id:o.session_id};throw new Error("Invalid response format from chat start endpoint")}catch(t){throw new Error(t.message||"Failed to start support chat session")}}async requestHandoff(e,t,n,s){if(!e||"undefined"===e||"null"===e)throw new Error("Invalid chat_id. Chat must be initialized first.");try{const o={"Content-Type":"application/json",...this.sessionManager.getSessionHeader()};t?o["X-Session-ID"]=t:s&&(o["X-Session-ID"]=s);const r={};n&&(r.reason=n);const a=await fetch(`${this.baseUrl}/api/support/chat/${e}/handoff`,{method:"POST",headers:o,body:JSON.stringify(r)}),i=a.headers.get("content-type");if(400===a.status||404===a.status){let t={};if(!i||!i.includes("application/json")){await a.text();throw new Error(`API endpoint returned HTML instead of JSON. Status: ${a.status}. This usually means the chat_id is invalid or the endpoint doesn't exist. URL: ${this.baseUrl}/api/support/chat/${e}/handoff`)}try{t=await a.json()}catch{t={}}throw new Error(t.message||"Invalid chat_id. Chat may have expired.")}if(!a.ok){let t={};if(!i||!i.includes("application/json")){await a.text();throw new Error(`API endpoint returned HTML instead of JSON. Status: ${a.status}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${this.baseUrl}/api/support/chat/${e}/handoff`)}try{t=await a.json()}catch{t={}}throw new Error(t.message||`HTTP error! status: ${a.status}`)}if(!i||!i.includes("application/json")){await a.text();throw new Error(`API endpoint returned non-JSON response. Status: ${a.status}. Content-Type: ${i||"unknown"}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${this.baseUrl}/api/support/chat/${e}/handoff`)}const c=await a.json();return this.sessionManager.updateSessionFromResponse(c),c.status?{success:!0,message:c.message||c.data?.message}:{success:!0,message:c.message}}catch(o){throw o}}async sendMessageToAgent(e,t,n){try{const s={"Content-Type":"application/json",...this.sessionManager.getSessionHeader()};t&&(s["X-Session-ID"]=t);const r=await fetch(`${this.baseUrl}/api/support/chat/${e}/message`,{method:"POST",headers:s,body:JSON.stringify({content:n})}),a=r.headers.get("content-type");if(401===r.status||404===r.status){let t={};if(!a||!a.includes("application/json")){await r.text();throw new Error(`API endpoint returned HTML instead of JSON. Status: ${r.status}. This usually means the chat_id is invalid or the endpoint doesn't exist. URL: ${this.baseUrl}/api/support/chat/${e}/message`)}try{t=await r.json()}catch{t={}}throw new Error(t.message||"Chat not found or unauthorized")}if(!r.ok){let t={};if(!a||!a.includes("application/json")){await r.text();throw new Error(`API endpoint returned HTML instead of JSON. Status: ${r.status}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${this.baseUrl}/api/support/chat/${e}/message`)}try{t=await r.json()}catch{t={}}throw new Error(t.message||`HTTP error! status: ${r.status}`)}if(!a||!a.includes("application/json")){await r.text();throw new Error(`API endpoint returned non-JSON response. Status: ${r.status}. Content-Type: ${a||"unknown"}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${this.baseUrl}/api/support/chat/${e}/message`)}const i=await r.json();if(this.sessionManager.updateSessionFromResponse(i),!0===i?.ignored&&"chat_resolved"===i?.reason)throw new o;return{id:i.id,sender_type:"customer",content:n,timestamp:i.timestamp||(new Date).toISOString()}}catch(s){if(s instanceof o||"ChatResolvedError"===s?.name)throw s;throw new Error(s.message||"Failed to send message to agent")}}async ensureChatInitialized(e,t,n){return e&&"undefined"!==e&&"null"!==e&&t?{chat_id:e,session_id:t}:await this.startSupportChat(n||null)}async loadMessageHistory(e,t){try{const n={...this.sessionManager.getSessionHeader()};t&&(n["X-Session-ID"]=t);const s=await fetch(`${this.baseUrl}/api/support/chat/${e}/messages`,{method:"GET",headers:n}),o=s.headers.get("content-type");if(401===s.status||404===s.status){let t={};if(!o||!o.includes("application/json")){await s.text();throw new Error(`API endpoint returned HTML instead of JSON. Status: ${s.status}. This usually means the chat_id is invalid or the endpoint doesn't exist. URL: ${this.baseUrl}/api/support/chat/${e}/messages`)}try{t=await s.json()}catch{t={}}throw new Error(t.message||"Chat not found or unauthorized")}if(!s.ok){let t={};if(!o||!o.includes("application/json")){await s.text();throw new Error(`API endpoint returned HTML instead of JSON. Status: ${s.status}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${this.baseUrl}/api/support/chat/${e}/messages`)}try{t=await s.json()}catch{t={}}throw new Error(t.message||`HTTP error! status: ${s.status}`)}if(!o||!o.includes("application/json")){await s.text();throw new Error(`API endpoint returned non-JSON response. Status: ${s.status}. Content-Type: ${o||"unknown"}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${this.baseUrl}/api/support/chat/${e}/messages`)}const r=await s.json();return this.sessionManager.updateSessionFromResponse(r),r.messages||[]}catch(n){throw new Error(n.message||"Failed to load message history")}}connectWebSocket(e,t,n,s,o){if(this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws&&this.ws.readyState===WebSocket.OPEN)return void this.debug;this.currentChatId=e,this.currentSessionId=t,n&&this.messageHandlers.add(n),s&&this.connectionHandlers.add(s);const r=t||this.sessionManager.getSessionId()||"",a=`${this.wsUrl}/ws/support/${e}?X-Session-ID=${encodeURIComponent(r)}`;try{this.ws=new WebSocket(a),this.ws.onopen=()=>{this.debug,this.wsReconnectAttempts=0,this.connectionHandlers.forEach(e=>e(!0)),this.startPingInterval()},this.ws.onmessage=e=>{try{const t=JSON.parse(e.data);if(this.debug,t.session_id&&this.sessionManager.updateSessionFromResponse({session_id:t.session_id}),"agent_accepted"===t.type||"chat_resolved"===t.type||t.type,"pong"===t.type)return;this.debug&&t.type,this.messageHandlers.forEach(e=>e(t))}catch(t){this.debug}},this.ws.onerror=e=>{this.connectionHandlers.forEach(e=>e(!1))},this.ws.onclose=e=>{if(this.debug,this.stopPingInterval(),this.connectionHandlers.forEach(e=>e(!1)),this.ws=null,o?.(e),4e3===e.code)return this.wsReconnectAttempts=this.maxReconnectAttempts,this.currentChatId=null,void(this.currentSessionId=null);if(this.wsReconnectAttempts<this.maxReconnectAttempts&&this.currentChatId&&this.currentSessionId){this.wsReconnectAttempts++;const e=Math.min(1e3*Math.pow(2,this.wsReconnectAttempts),3e4);this.debug,this.reconnectTimeout=setTimeout(()=>{this.currentChatId&&this.currentSessionId&&this.connectWebSocket(this.currentChatId,this.currentSessionId,n,s,o)},e)}else this.debug}}catch(i){this.connectionHandlers.forEach(e=>e(!1))}}sendMessageViaWebSocket(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return!1;try{return this.ws.send(JSON.stringify({type:"message",content:e})),!0}catch(t){return!1}}sendTypingIndicator(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return!1;try{return this.ws.send(JSON.stringify({type:e})),!0}catch(t){return!1}}startPingInterval(){this.stopPingInterval(),this.pingInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify({type:"ping"}))}catch(e){}},3e4)}stopPingInterval(){this.pingInterval&&(clearInterval(this.pingInterval),this.pingInterval=null)}disconnectWebSocket(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.stopPingInterval(),this.ws&&(this.ws.close(),this.ws=null),this.messageHandlers.clear(),this.connectionHandlers.clear(),this.wsReconnectAttempts=0,this.currentChatId=null,this.currentSessionId=null}isWebSocketConnected(){return null!==this.ws&&this.ws.readyState===WebSocket.OPEN}removeMessageHandler(e){this.messageHandlers.delete(e)}removeConnectionHandler(e){this.connectionHandlers.delete(e)}}
1
+ "use strict";const e="undefined"!=typeof process&&process.env?.REACT_APP_BACKEND_BASE_URL||"http://localhost:8012";const t="chat_session_id";class n{constructor(){this.sessionId=null,this.sessionId=this.loadSessionId()}loadSessionId(){return"undefined"!=typeof localStorage?localStorage.getItem(t):null}saveSessionId(e){this.sessionId=e,"undefined"!=typeof localStorage&&(e?localStorage.setItem(t,e):localStorage.removeItem(t))}updateSessionFromResponse(e){const t=e?.data?.session_id||e?.session_id;t&&"string"==typeof t&&this.saveSessionId(t)}getSessionId(){return this.sessionId||""}getSessionHeader(){return{"X-Session-ID":this.getSessionId()}}}let s=null;class o extends Error{constructor(e="chat_resolved"){super(e),this.reason="chat_resolved",this.name="ChatResolvedError"}}class r{constructor(e={}){this.ws=null,this.wsReconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectTimeout=null,this.pingInterval=null,this.currentChatId=null,this.currentSessionId=null,this.messageHandlers=new Set,this.connectionHandlers=new Set,this.baseUrl=e.baseUrl||"https://chartconnect.blockspark.in",this.wsUrl=e.wsUrl||"wss://chartconnect.blockspark.in",this.debug=e.debug||!1,this.sessionManager=(s||(s=new n),s)}async startSupportChat(e){try{const t={"Content-Type":"application/json",...this.sessionManager.getSessionHeader()};e&&(t["X-Session-ID"]=e);const n=await fetch(`${this.baseUrl}/api/support/chat/start`,{method:"POST",headers:t,body:JSON.stringify({})});if(!n.ok){const e=n.headers.get("content-type");let t={};if(!e||!e.includes("application/json")){await n.text();throw new Error(`API endpoint returned HTML instead of JSON. Status: ${n.status}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${this.baseUrl}/api/support/chat/start`)}try{t=await n.json()}catch{t={}}throw new Error(t.message||`HTTP error! status: ${n.status}`)}const s=n.headers.get("content-type");if(!s||!s.includes("application/json")){await n.text();throw new Error(`API endpoint returned non-JSON response. Status: ${n.status}. Content-Type: ${s||"unknown"}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${this.baseUrl}/api/support/chat/start`)}const o=await n.json();if(this.sessionManager.updateSessionFromResponse(o),o.status&&o.data)return{chat_id:o.data.chat_id,session_id:o.data.session_id};if(o.chat_id&&o.session_id)return{chat_id:o.chat_id,session_id:o.session_id};throw new Error("Invalid response format from chat start endpoint")}catch(t){throw new Error(t.message||"Failed to start support chat session")}}async requestHandoff(e,t,n,s){if(!e||"undefined"===e||"null"===e)throw new Error("Invalid chat_id. Chat must be initialized first.");try{const o={"Content-Type":"application/json",...this.sessionManager.getSessionHeader()};t?o["X-Session-ID"]=t:s&&(o["X-Session-ID"]=s);const r={};n&&(r.reason=n);const a=await fetch(`${this.baseUrl}/api/support/chat/${e}/handoff`,{method:"POST",headers:o,body:JSON.stringify(r)}),i=a.headers.get("content-type");if(400===a.status||404===a.status){let t={};if(!i||!i.includes("application/json")){await a.text();throw new Error(`API endpoint returned HTML instead of JSON. Status: ${a.status}. This usually means the chat_id is invalid or the endpoint doesn't exist. URL: ${this.baseUrl}/api/support/chat/${e}/handoff`)}try{t=await a.json()}catch{t={}}throw new Error(t.message||"Invalid chat_id. Chat may have expired.")}if(!a.ok){let t={};if(!i||!i.includes("application/json")){await a.text();throw new Error(`API endpoint returned HTML instead of JSON. Status: ${a.status}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${this.baseUrl}/api/support/chat/${e}/handoff`)}try{t=await a.json()}catch{t={}}throw new Error(t.message||`HTTP error! status: ${a.status}`)}if(!i||!i.includes("application/json")){await a.text();throw new Error(`API endpoint returned non-JSON response. Status: ${a.status}. Content-Type: ${i||"unknown"}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${this.baseUrl}/api/support/chat/${e}/handoff`)}const c=await a.json();return this.sessionManager.updateSessionFromResponse(c),c.status?{success:!0,message:c.message||c.data?.message}:{success:!0,message:c.message}}catch(o){throw o}}async sendMessageToAgent(e,t,n){try{const s={"Content-Type":"application/json",...this.sessionManager.getSessionHeader()};t&&(s["X-Session-ID"]=t);const r=await fetch(`${this.baseUrl}/api/support/chat/${e}/message`,{method:"POST",headers:s,body:JSON.stringify({content:n})}),a=r.headers.get("content-type");if(401===r.status||404===r.status){let t={};if(!a||!a.includes("application/json")){await r.text();throw new Error(`API endpoint returned HTML instead of JSON. Status: ${r.status}. This usually means the chat_id is invalid or the endpoint doesn't exist. URL: ${this.baseUrl}/api/support/chat/${e}/message`)}try{t=await r.json()}catch{t={}}throw new Error(t.message||"Chat not found or unauthorized")}if(!r.ok){let t={};if(!a||!a.includes("application/json")){await r.text();throw new Error(`API endpoint returned HTML instead of JSON. Status: ${r.status}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${this.baseUrl}/api/support/chat/${e}/message`)}try{t=await r.json()}catch{t={}}throw new Error(t.message||`HTTP error! status: ${r.status}`)}if(!a||!a.includes("application/json")){await r.text();throw new Error(`API endpoint returned non-JSON response. Status: ${r.status}. Content-Type: ${a||"unknown"}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${this.baseUrl}/api/support/chat/${e}/message`)}const i=await r.json();if(this.sessionManager.updateSessionFromResponse(i),!0===i?.ignored&&"chat_resolved"===i?.reason)throw new o;return{id:i.id,sender_type:"customer",content:n,timestamp:i.timestamp||(new Date).toISOString()}}catch(s){if(s instanceof o||"ChatResolvedError"===s?.name)throw s;throw new Error(s.message||"Failed to send message to agent")}}async ensureChatInitialized(e,t,n){return e&&"undefined"!==e&&"null"!==e&&t?{chat_id:e,session_id:t}:await this.startSupportChat(n||null)}async loadMessageHistory(e,t){try{const n={...this.sessionManager.getSessionHeader()};t&&(n["X-Session-ID"]=t);const s=await fetch(`${this.baseUrl}/api/support/chat/${e}/messages`,{method:"GET",headers:n}),o=s.headers.get("content-type");if(401===s.status||404===s.status){let t={};if(!o||!o.includes("application/json")){await s.text();throw new Error(`API endpoint returned HTML instead of JSON. Status: ${s.status}. This usually means the chat_id is invalid or the endpoint doesn't exist. URL: ${this.baseUrl}/api/support/chat/${e}/messages`)}try{t=await s.json()}catch{t={}}throw new Error(t.message||"Chat not found or unauthorized")}if(!s.ok){let t={};if(!o||!o.includes("application/json")){await s.text();throw new Error(`API endpoint returned HTML instead of JSON. Status: ${s.status}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${this.baseUrl}/api/support/chat/${e}/messages`)}try{t=await s.json()}catch{t={}}throw new Error(t.message||`HTTP error! status: ${s.status}`)}if(!o||!o.includes("application/json")){await s.text();throw new Error(`API endpoint returned non-JSON response. Status: ${s.status}. Content-Type: ${o||"unknown"}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${this.baseUrl}/api/support/chat/${e}/messages`)}const r=await s.json();return this.sessionManager.updateSessionFromResponse(r),r.messages||[]}catch(n){throw new Error(n.message||"Failed to load message history")}}connectWebSocket(e,t,n,s,o){if(this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws&&this.ws.readyState===WebSocket.OPEN)return void this.debug;this.currentChatId=e,this.currentSessionId=t,n&&this.messageHandlers.add(n),s&&this.connectionHandlers.add(s);const r=t||this.sessionManager.getSessionId()||"",a=`${this.wsUrl}/ws/support/${e}?X-Session-ID=${encodeURIComponent(r)}`;try{this.ws=new WebSocket(a),this.ws.onopen=()=>{this.debug,this.wsReconnectAttempts=0,this.connectionHandlers.forEach(e=>e(!0)),this.startPingInterval()},this.ws.onmessage=e=>{try{const t=JSON.parse(e.data);if(this.debug,t.session_id&&this.sessionManager.updateSessionFromResponse({session_id:t.session_id}),"agent_accepted"===t.type||"chat_resolved"===t.type||t.type,"pong"===t.type)return;this.debug&&t.type,this.messageHandlers.forEach(e=>e(t))}catch(t){this.debug}},this.ws.onerror=e=>{this.connectionHandlers.forEach(e=>e(!1))},this.ws.onclose=e=>{if(this.debug,this.stopPingInterval(),this.connectionHandlers.forEach(e=>e(!1)),this.ws=null,o?.(e),4e3===e.code)return this.wsReconnectAttempts=this.maxReconnectAttempts,this.currentChatId=null,void(this.currentSessionId=null);if(this.wsReconnectAttempts<this.maxReconnectAttempts&&this.currentChatId&&this.currentSessionId){this.wsReconnectAttempts++;const e=Math.min(1e3*Math.pow(2,this.wsReconnectAttempts),3e4);this.debug,this.reconnectTimeout=setTimeout(()=>{this.currentChatId&&this.currentSessionId&&this.connectWebSocket(this.currentChatId,this.currentSessionId,n,s,o)},e)}else this.debug}}catch(i){this.connectionHandlers.forEach(e=>e(!1))}}sendMessageViaWebSocket(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return!1;try{return this.ws.send(JSON.stringify({type:"message",content:e})),!0}catch(t){return!1}}sendTypingIndicator(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return!1;try{return this.ws.send(JSON.stringify({type:e})),!0}catch(t){return!1}}startPingInterval(){this.stopPingInterval(),this.pingInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify({type:"ping"}))}catch(e){}},3e4)}stopPingInterval(){this.pingInterval&&(clearInterval(this.pingInterval),this.pingInterval=null)}disconnectWebSocket(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.stopPingInterval(),this.ws&&(this.ws.close(),this.ws=null),this.messageHandlers.clear(),this.connectionHandlers.clear(),this.wsReconnectAttempts=0,this.currentChatId=null,this.currentSessionId=null}isWebSocketConnected(){return null!==this.ws&&this.ws.readyState===WebSocket.OPEN}removeMessageHandler(e){this.messageHandlers.delete(e)}removeConnectionHandler(e){this.connectionHandlers.delete(e)}}
2
2
  /*! @license DOMPurify 3.3.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.1/LICENSE */
3
- const{entries:a,setPrototypeOf:i,isFrozen:c,getPrototypeOf:l,getOwnPropertyDescriptor:u}=Object;let{freeze:d,seal:p,create:h}=Object,{apply:m,construct:f}="undefined"!=typeof Reflect&&Reflect;d||(d=function(e){return e}),p||(p=function(e){return e}),m||(m=function(e,t){for(var n=arguments.length,s=new Array(n>2?n-2:0),o=2;o<n;o++)s[o-2]=arguments[o];return e.apply(t,s)}),f||(f=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];return new e(...n)});const g=k(Array.prototype.forEach),w=k(Array.prototype.lastIndexOf),y=k(Array.prototype.pop),T=k(Array.prototype.push),S=k(Array.prototype.splice),E=k(String.prototype.toLowerCase),A=k(String.prototype.toString),b=k(String.prototype.match),_=k(String.prototype.replace),I=k(String.prototype.indexOf),N=k(String.prototype.trim),R=k(Object.prototype.hasOwnProperty),v=k(RegExp.prototype.test),C=(O=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return f(O,t)});var O;function k(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,s=new Array(n>1?n-1:0),o=1;o<n;o++)s[o-1]=arguments[o];return m(e,t,s)}}function x(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:E;i&&i(e,null);let s=t.length;for(;s--;){let o=t[s];if("string"==typeof o){const e=n(o);e!==o&&(c(t)||(t[s]=e),o=e)}e[o]=!0}return e}function L(e){for(let t=0;t<e.length;t++){R(e,t)||(e[t]=null)}return e}function D(e){const t=h(null);for(const[n,s]of a(e)){R(e,n)&&(Array.isArray(s)?t[n]=L(s):s&&"object"==typeof s&&s.constructor===Object?t[n]=D(s):t[n]=s)}return t}function M(e,t){for(;null!==e;){const n=u(e,t);if(n){if(n.get)return k(n.get);if("function"==typeof n.value)return k(n.value)}e=l(e)}return function(){return null}}const P=d(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),U=d(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),H=d(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),$=d(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),F=d(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),z=d(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),j=d(["#text"]),W=d(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),B=d(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),G=d(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),J=d(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Y=p(/\{\{[\w\W]*|[\w\W]*\}\}/gm),X=p(/<%[\w\W]*|[\w\W]*%>/gm),q=p(/\$\{[\w\W]*/gm),K=p(/^data-[\-\w.\u00B7-\uFFFF]+$/),V=p(/^aria-[\-\w]+$/),Z=p(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Q=p(/^(?:\w+script|data):/i),ee=p(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),te=p(/^html$/i),ne=p(/^[a-z][.\w]*(-[.\w]+)+$/i);var se=Object.freeze({__proto__:null,ARIA_ATTR:V,ATTR_WHITESPACE:ee,CUSTOM_ELEMENT:ne,DATA_ATTR:K,DOCTYPE_NAME:te,ERB_EXPR:X,IS_ALLOWED_URI:Z,IS_SCRIPT_OR_DATA:Q,MUSTACHE_EXPR:Y,TMPLIT_EXPR:q});const oe=1,re=3,ae=7,ie=8,ce=9;var le=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"undefined"==typeof window?null:window;const n=t=>e(t);if(n.version="3.3.1",n.removed=[],!t||!t.document||t.document.nodeType!==ce||!t.Element)return n.isSupported=!1,n;let{document:s}=t;const o=s,r=o.currentScript,{DocumentFragment:i,HTMLTemplateElement:c,Node:l,Element:u,NodeFilter:p,NamedNodeMap:m=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:f,DOMParser:O,trustedTypes:k}=t,L=u.prototype,Y=M(L,"cloneNode"),X=M(L,"remove"),q=M(L,"nextSibling"),K=M(L,"childNodes"),V=M(L,"parentNode");if("function"==typeof c){const e=s.createElement("template");e.content&&e.content.ownerDocument&&(s=e.content.ownerDocument)}let Q,ee="";const{implementation:ne,createNodeIterator:le,createDocumentFragment:ue,getElementsByTagName:de}=s,{importNode:pe}=o;let he={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof a&&"function"==typeof V&&ne&&void 0!==ne.createHTMLDocument;const{MUSTACHE_EXPR:me,ERB_EXPR:fe,TMPLIT_EXPR:ge,DATA_ATTR:we,ARIA_ATTR:ye,IS_SCRIPT_OR_DATA:Te,ATTR_WHITESPACE:Se,CUSTOM_ELEMENT:Ee}=se;let{IS_ALLOWED_URI:Ae}=se,be=null;const _e=x({},[...P,...U,...H,...F,...j]);let Ie=null;const Ne=x({},[...W,...B,...G,...J]);let Re=Object.seal(h(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ve=null,Ce=null;const Oe=Object.seal(h(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let ke=!0,xe=!0,Le=!1,De=!0,Me=!1,Pe=!0,Ue=!1,He=!1,$e=!1,Fe=!1,ze=!1,je=!1,We=!0,Be=!1,Ge=!0,Je=!1,Ye={},Xe=null;const qe=x({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Ke=null;const Ve=x({},["audio","video","img","source","image","track"]);let Ze=null;const Qe=x({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),et="http://www.w3.org/1998/Math/MathML",tt="http://www.w3.org/2000/svg",nt="http://www.w3.org/1999/xhtml";let st=nt,ot=!1,rt=null;const at=x({},[et,tt,nt],A);let it=x({},["mi","mo","mn","ms","mtext"]),ct=x({},["annotation-xml"]);const lt=x({},["title","style","font","a","script"]);let ut=null;const dt=["application/xhtml+xml","text/html"];let pt=null,ht=null;const mt=s.createElement("form"),ft=function(e){return e instanceof RegExp||e instanceof Function},gt=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!ht||ht!==e){if(e&&"object"==typeof e||(e={}),e=D(e),ut=-1===dt.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,pt="application/xhtml+xml"===ut?A:E,be=R(e,"ALLOWED_TAGS")?x({},e.ALLOWED_TAGS,pt):_e,Ie=R(e,"ALLOWED_ATTR")?x({},e.ALLOWED_ATTR,pt):Ne,rt=R(e,"ALLOWED_NAMESPACES")?x({},e.ALLOWED_NAMESPACES,A):at,Ze=R(e,"ADD_URI_SAFE_ATTR")?x(D(Qe),e.ADD_URI_SAFE_ATTR,pt):Qe,Ke=R(e,"ADD_DATA_URI_TAGS")?x(D(Ve),e.ADD_DATA_URI_TAGS,pt):Ve,Xe=R(e,"FORBID_CONTENTS")?x({},e.FORBID_CONTENTS,pt):qe,ve=R(e,"FORBID_TAGS")?x({},e.FORBID_TAGS,pt):D({}),Ce=R(e,"FORBID_ATTR")?x({},e.FORBID_ATTR,pt):D({}),Ye=!!R(e,"USE_PROFILES")&&e.USE_PROFILES,ke=!1!==e.ALLOW_ARIA_ATTR,xe=!1!==e.ALLOW_DATA_ATTR,Le=e.ALLOW_UNKNOWN_PROTOCOLS||!1,De=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,Me=e.SAFE_FOR_TEMPLATES||!1,Pe=!1!==e.SAFE_FOR_XML,Ue=e.WHOLE_DOCUMENT||!1,Fe=e.RETURN_DOM||!1,ze=e.RETURN_DOM_FRAGMENT||!1,je=e.RETURN_TRUSTED_TYPE||!1,$e=e.FORCE_BODY||!1,We=!1!==e.SANITIZE_DOM,Be=e.SANITIZE_NAMED_PROPS||!1,Ge=!1!==e.KEEP_CONTENT,Je=e.IN_PLACE||!1,Ae=e.ALLOWED_URI_REGEXP||Z,st=e.NAMESPACE||nt,it=e.MATHML_TEXT_INTEGRATION_POINTS||it,ct=e.HTML_INTEGRATION_POINTS||ct,Re=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&ft(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Re.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&ft(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Re.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(Re.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Me&&(xe=!1),ze&&(Fe=!0),Ye&&(be=x({},j),Ie=[],!0===Ye.html&&(x(be,P),x(Ie,W)),!0===Ye.svg&&(x(be,U),x(Ie,B),x(Ie,J)),!0===Ye.svgFilters&&(x(be,H),x(Ie,B),x(Ie,J)),!0===Ye.mathMl&&(x(be,F),x(Ie,G),x(Ie,J))),e.ADD_TAGS&&("function"==typeof e.ADD_TAGS?Oe.tagCheck=e.ADD_TAGS:(be===_e&&(be=D(be)),x(be,e.ADD_TAGS,pt))),e.ADD_ATTR&&("function"==typeof e.ADD_ATTR?Oe.attributeCheck=e.ADD_ATTR:(Ie===Ne&&(Ie=D(Ie)),x(Ie,e.ADD_ATTR,pt))),e.ADD_URI_SAFE_ATTR&&x(Ze,e.ADD_URI_SAFE_ATTR,pt),e.FORBID_CONTENTS&&(Xe===qe&&(Xe=D(Xe)),x(Xe,e.FORBID_CONTENTS,pt)),e.ADD_FORBID_CONTENTS&&(Xe===qe&&(Xe=D(Xe)),x(Xe,e.ADD_FORBID_CONTENTS,pt)),Ge&&(be["#text"]=!0),Ue&&x(be,["html","head","body"]),be.table&&(x(be,["tbody"]),delete ve.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw C('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw C('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');Q=e.TRUSTED_TYPES_POLICY,ee=Q.createHTML("")}else void 0===Q&&(Q=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const s="data-tt-policy-suffix";t&&t.hasAttribute(s)&&(n=t.getAttribute(s));const o="dompurify"+(n?"#"+n:"");try{return e.createPolicy(o,{createHTML:e=>e,createScriptURL:e=>e})}catch(r){return null}}(k,r)),null!==Q&&"string"==typeof ee&&(ee=Q.createHTML(""));d&&d(e),ht=e}},wt=x({},[...U,...H,...$]),yt=x({},[...F,...z]),Tt=function(e){T(n.removed,{element:e});try{V(e).removeChild(e)}catch(t){X(e)}},St=function(e,t){try{T(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(s){T(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(Fe||ze)try{Tt(t)}catch(s){}else try{t.setAttribute(e,"")}catch(s){}},Et=function(e){let t=null,n=null;if($e)e="<remove></remove>"+e;else{const t=b(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===ut&&st===nt&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const o=Q?Q.createHTML(e):e;if(st===nt)try{t=(new O).parseFromString(o,ut)}catch(a){}if(!t||!t.documentElement){t=ne.createDocument(st,"template",null);try{t.documentElement.innerHTML=ot?ee:o}catch(a){}}const r=t.body||t.documentElement;return e&&n&&r.insertBefore(s.createTextNode(n),r.childNodes[0]||null),st===nt?de.call(t,Ue?"html":"body")[0]:Ue?t.documentElement:r},At=function(e){return le.call(e.ownerDocument||e,e,p.SHOW_ELEMENT|p.SHOW_COMMENT|p.SHOW_TEXT|p.SHOW_PROCESSING_INSTRUCTION|p.SHOW_CDATA_SECTION,null)},bt=function(e){return e instanceof f&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof m)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},_t=function(e){return"function"==typeof l&&e instanceof l};function It(e,t,s){g(e,e=>{e.call(n,t,s,ht)})}const Nt=function(e){let t=null;if(It(he.beforeSanitizeElements,e,null),bt(e))return Tt(e),!0;const s=pt(e.nodeName);if(It(he.uponSanitizeElement,e,{tagName:s,allowedTags:be}),Pe&&e.hasChildNodes()&&!_t(e.firstElementChild)&&v(/<[/\w!]/g,e.innerHTML)&&v(/<[/\w!]/g,e.textContent))return Tt(e),!0;if(e.nodeType===ae)return Tt(e),!0;if(Pe&&e.nodeType===ie&&v(/<[/\w]/g,e.data))return Tt(e),!0;if(!(Oe.tagCheck instanceof Function&&Oe.tagCheck(s))&&(!be[s]||ve[s])){if(!ve[s]&&vt(s)){if(Re.tagNameCheck instanceof RegExp&&v(Re.tagNameCheck,s))return!1;if(Re.tagNameCheck instanceof Function&&Re.tagNameCheck(s))return!1}if(Ge&&!Xe[s]){const t=V(e)||e.parentNode,n=K(e)||e.childNodes;if(n&&t){for(let s=n.length-1;s>=0;--s){const o=Y(n[s],!0);o.__removalCount=(e.__removalCount||0)+1,t.insertBefore(o,q(e))}}}return Tt(e),!0}return e instanceof u&&!function(e){let t=V(e);t&&t.tagName||(t={namespaceURI:st,tagName:"template"});const n=E(e.tagName),s=E(t.tagName);return!!rt[e.namespaceURI]&&(e.namespaceURI===tt?t.namespaceURI===nt?"svg"===n:t.namespaceURI===et?"svg"===n&&("annotation-xml"===s||it[s]):Boolean(wt[n]):e.namespaceURI===et?t.namespaceURI===nt?"math"===n:t.namespaceURI===tt?"math"===n&&ct[s]:Boolean(yt[n]):e.namespaceURI===nt?!(t.namespaceURI===tt&&!ct[s])&&!(t.namespaceURI===et&&!it[s])&&!yt[n]&&(lt[n]||!wt[n]):!("application/xhtml+xml"!==ut||!rt[e.namespaceURI]))}(e)?(Tt(e),!0):"noscript"!==s&&"noembed"!==s&&"noframes"!==s||!v(/<\/no(script|embed|frames)/i,e.innerHTML)?(Me&&e.nodeType===re&&(t=e.textContent,g([me,fe,ge],e=>{t=_(t,e," ")}),e.textContent!==t&&(T(n.removed,{element:e.cloneNode()}),e.textContent=t)),It(he.afterSanitizeElements,e,null),!1):(Tt(e),!0)},Rt=function(e,t,n){if(We&&("id"===t||"name"===t)&&(n in s||n in mt))return!1;if(xe&&!Ce[t]&&v(we,t));else if(ke&&v(ye,t));else if(Oe.attributeCheck instanceof Function&&Oe.attributeCheck(t,e));else if(!Ie[t]||Ce[t]){if(!(vt(e)&&(Re.tagNameCheck instanceof RegExp&&v(Re.tagNameCheck,e)||Re.tagNameCheck instanceof Function&&Re.tagNameCheck(e))&&(Re.attributeNameCheck instanceof RegExp&&v(Re.attributeNameCheck,t)||Re.attributeNameCheck instanceof Function&&Re.attributeNameCheck(t,e))||"is"===t&&Re.allowCustomizedBuiltInElements&&(Re.tagNameCheck instanceof RegExp&&v(Re.tagNameCheck,n)||Re.tagNameCheck instanceof Function&&Re.tagNameCheck(n))))return!1}else if(Ze[t]);else if(v(Ae,_(n,Se,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==I(n,"data:")||!Ke[e]){if(Le&&!v(Te,_(n,Se,"")));else if(n)return!1}else;return!0},vt=function(e){return"annotation-xml"!==e&&b(e,Ee)},Ct=function(e){It(he.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||bt(e))return;const s={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Ie,forceKeepAttr:void 0};let o=t.length;for(;o--;){const a=t[o],{name:i,namespaceURI:c,value:l}=a,u=pt(i),d=l;let p="value"===i?d:N(d);if(s.attrName=u,s.attrValue=p,s.keepAttr=!0,s.forceKeepAttr=void 0,It(he.uponSanitizeAttribute,e,s),p=s.attrValue,!Be||"id"!==u&&"name"!==u||(St(i,e),p="user-content-"+p),Pe&&v(/((--!?|])>)|<\/(style|title|textarea)/i,p)){St(i,e);continue}if("attributename"===u&&b(p,"href")){St(i,e);continue}if(s.forceKeepAttr)continue;if(!s.keepAttr){St(i,e);continue}if(!De&&v(/\/>/i,p)){St(i,e);continue}Me&&g([me,fe,ge],e=>{p=_(p,e," ")});const h=pt(e.nodeName);if(Rt(h,u,p)){if(Q&&"object"==typeof k&&"function"==typeof k.getAttributeType)if(c);else switch(k.getAttributeType(h,u)){case"TrustedHTML":p=Q.createHTML(p);break;case"TrustedScriptURL":p=Q.createScriptURL(p)}if(p!==d)try{c?e.setAttributeNS(c,i,p):e.setAttribute(i,p),bt(e)?Tt(e):y(n.removed)}catch(r){St(i,e)}}else St(i,e)}It(he.afterSanitizeAttributes,e,null)},Ot=function e(t){let n=null;const s=At(t);for(It(he.beforeSanitizeShadowDOM,t,null);n=s.nextNode();)It(he.uponSanitizeShadowNode,n,null),Nt(n),Ct(n),n.content instanceof i&&e(n.content);It(he.afterSanitizeShadowDOM,t,null)};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=null,r=null,a=null,c=null;if(ot=!e,ot&&(e="\x3c!--\x3e"),"string"!=typeof e&&!_t(e)){if("function"!=typeof e.toString)throw C("toString is not a function");if("string"!=typeof(e=e.toString()))throw C("dirty is not a string, aborting")}if(!n.isSupported)return e;if(He||gt(t),n.removed=[],"string"==typeof e&&(Je=!1),Je){if(e.nodeName){const t=pt(e.nodeName);if(!be[t]||ve[t])throw C("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof l)s=Et("\x3c!----\x3e"),r=s.ownerDocument.importNode(e,!0),r.nodeType===oe&&"BODY"===r.nodeName||"HTML"===r.nodeName?s=r:s.appendChild(r);else{if(!Fe&&!Me&&!Ue&&-1===e.indexOf("<"))return Q&&je?Q.createHTML(e):e;if(s=Et(e),!s)return Fe?null:je?ee:""}s&&$e&&Tt(s.firstChild);const u=At(Je?e:s);for(;a=u.nextNode();)Nt(a),Ct(a),a.content instanceof i&&Ot(a.content);if(Je)return e;if(Fe){if(ze)for(c=ue.call(s.ownerDocument);s.firstChild;)c.appendChild(s.firstChild);else c=s;return(Ie.shadowroot||Ie.shadowrootmode)&&(c=pe.call(o,c,!0)),c}let d=Ue?s.outerHTML:s.innerHTML;return Ue&&be["!doctype"]&&s.ownerDocument&&s.ownerDocument.doctype&&s.ownerDocument.doctype.name&&v(te,s.ownerDocument.doctype.name)&&(d="<!DOCTYPE "+s.ownerDocument.doctype.name+">\n"+d),Me&&g([me,fe,ge],e=>{d=_(d,e," ")}),Q&&je?Q.createHTML(d):d},n.setConfig=function(){gt(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),He=!0},n.clearConfig=function(){ht=null,He=!1},n.isValidAttribute=function(e,t,n){ht||gt({});const s=pt(e),o=pt(t);return Rt(s,o,n)},n.addHook=function(e,t){"function"==typeof t&&T(he[e],t)},n.removeHook=function(e,t){if(void 0!==t){const n=w(he[e],t);return-1===n?void 0:S(he[e],n,1)[0]}return y(he[e])},n.removeHooks=function(e){he[e]=[]},n.removeAllHooks=function(){he={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}();function ue(e){return function(e,t){const n={ALLOWED_TAGS:["a","b","strong","i","em","u","br","p","span"],ALLOWED_ATTR:["href","target","rel"],ALLOW_DATA_ATTR:!1,...t?.allowedTags&&{ALLOWED_TAGS:t.allowedTags},...t?.allowedAttributes&&{ALLOWED_ATTR:Object.keys(t.allowedAttributes).flatMap(e=>t.allowedAttributes[e])}},s=le.sanitize(e,n);return"string"==typeof s?s:String(s)}(e.replace(/(https?:\/\/[^\s]+)/g,'<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>'),{allowedTags:["a"],allowedAttributes:{a:["href","target","rel"]}})}exports.ChatResolvedError=o,exports.createChatService=function(e){return new r(e)},exports.createDialogflowSession=async function(t,n){try{const s=t.backendBaseUrl||e,o={dfProjectId:t.dfProjectId,dfLocation:t.dfLocation||"us-central1",dfAgentId:t.dfAgentId,languageCode:t.languageCode||"en"};n&&(o.sessionId=n);const r=await fetch(`${s}/api/dialogflow/session/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!r.ok){const e=r.headers.get("content-type");let t={};if(!e||!e.includes("application/json")){const e=await r.text();throw new Error(`API endpoint returned HTML instead of JSON. Status: ${r.status}. Response preview: ${e.substring(0,200)}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${s}/api/dialogflow/session/create`)}try{t=await r.json()}catch{t={}}if(400===r.status)throw new Error(t.message||"Bad request. Please check your Dialogflow configuration.");if(401===r.status)throw new Error(t.message||"Authentication failed. Please check your backend configuration.");if(403===r.status)throw new Error(t.message||"Access forbidden. Please check your permissions.");if(404===r.status)throw new Error(t.message||"Dialogflow agent not found. Please check your project ID, location, and agent ID.");if(500===r.status)throw new Error(t.message||"Internal server error. Please try again later.");throw new Error(t.message||`HTTP error! status: ${r.status}`)}const a=r.headers.get("content-type");if(!a||!a.includes("application/json")){const e=r.clone(),t=await e.text();throw new Error(`API endpoint returned non-JSON response. Status: ${r.status}. Content-Type: ${a||"unknown"}. Response body: ${t.substring(0,200)}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${s}/api/dialogflow/session/create`)}const i=await r.json();if("success"!==i.status)throw new Error(i.message||"Failed to create session. Backend returned unsuccessful status.");const c=i.data||i;return{session_id:c.session_id||i.session_id,message:c.message||"Hello! How can I help you today?",...c.richContent&&{richContent:c.richContent}}}catch(s){if(s.message?.includes("Failed to fetch")||s.message?.includes("CORS"))throw new Error("Network error. Unable to connect to backend. Please check your network connection and CORS settings.");if(s.message&&!s.message.includes("HTTP error"))throw s;throw new Error(s.message||"Failed to create Dialogflow session")}},exports.linkifyText=ue,exports.safeLinkifyText=function(e){return ue(e)},exports.sendDialogflowMessage=async function(t,n,s){try{const o=s.backendBaseUrl||e,r={message:t.trim(),dfProjectId:s.dfProjectId,dfLocation:s.dfLocation||"us-central1",dfAgentId:s.dfAgentId,languageCode:s.languageCode||"en"},a=await fetch(`${o}/api/dialogflow/session/${encodeURIComponent(n)}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!a.ok){const e=a.headers.get("content-type");let t={};if(!e||!e.includes("application/json")){const e=await a.text();throw new Error(`API endpoint returned HTML instead of JSON. Status: ${a.status}. Response preview: ${e.substring(0,200)}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${o}/api/dialogflow/session/${encodeURIComponent(n)}/message`)}try{t=await a.json()}catch{t={}}if(400===a.status)throw new Error(t.message||"Bad request. Please check your message and configuration.");if(401===a.status)throw new Error(t.message||"Authentication failed. Please check your backend configuration.");if(403===a.status)throw new Error(t.message||"Access forbidden. Please check your permissions.");if(404===a.status)throw new Error(t.message||"Dialogflow session not found. Please check your session ID.");if(500===a.status)throw new Error(t.message||"Internal server error. Please try again later.");throw new Error(t.message||`HTTP error! status: ${a.status}`)}const i=a.headers.get("content-type");if(!i||!i.includes("application/json")){const e=a.clone(),t=await e.text();throw new Error(`API endpoint returned non-JSON response. Status: ${a.status}. Content-Type: ${i||"unknown"}. Response body: ${t.substring(0,200)}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${o}/api/dialogflow/session/${encodeURIComponent(n)}/message`)}const c=await a.json();if("success"!==c.status)throw new Error(c.message||"Failed to send message. Backend returned unsuccessful status.");const l=c.data||c;return{response:l.response||l.message||"",session_id:l.session_id||c.session_id||n,source:l.source||"dialogflow",timestamp:l.timestamp||(new Date).toISOString(),...l.richContent&&{richContent:l.richContent},...void 0!==l.handoff&&{handoff:l.handoff},...l.chat_id&&{chat_id:l.chat_id},...l.support_session_id&&{support_session_id:l.support_session_id}}}catch(o){if(o.message?.includes("Failed to fetch")||o.message?.includes("CORS"))throw new Error("Network error. Unable to connect to backend. Please check your network connection and CORS settings.");if(o.message&&!o.message.includes("HTTP error"))throw o;throw new Error(o.message||"Failed to send message to Dialogflow")}};
4
- //# sourceMappingURL=sanitize-BSKgKaR-.cjs.map
3
+ const{entries:a,setPrototypeOf:i,isFrozen:c,getPrototypeOf:l,getOwnPropertyDescriptor:u}=Object;let{freeze:d,seal:p,create:h}=Object,{apply:m,construct:f}="undefined"!=typeof Reflect&&Reflect;d||(d=function(e){return e}),p||(p=function(e){return e}),m||(m=function(e,t){for(var n=arguments.length,s=new Array(n>2?n-2:0),o=2;o<n;o++)s[o-2]=arguments[o];return e.apply(t,s)}),f||(f=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];return new e(...n)});const g=k(Array.prototype.forEach),w=k(Array.prototype.lastIndexOf),y=k(Array.prototype.pop),T=k(Array.prototype.push),S=k(Array.prototype.splice),E=k(String.prototype.toLowerCase),A=k(String.prototype.toString),b=k(String.prototype.match),_=k(String.prototype.replace),I=k(String.prototype.indexOf),N=k(String.prototype.trim),R=k(Object.prototype.hasOwnProperty),C=k(RegExp.prototype.test),v=(O=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return f(O,t)});var O;function k(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,s=new Array(n>1?n-1:0),o=1;o<n;o++)s[o-1]=arguments[o];return m(e,t,s)}}function x(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:E;i&&i(e,null);let s=t.length;for(;s--;){let o=t[s];if("string"==typeof o){const e=n(o);e!==o&&(c(t)||(t[s]=e),o=e)}e[o]=!0}return e}function L(e){for(let t=0;t<e.length;t++){R(e,t)||(e[t]=null)}return e}function D(e){const t=h(null);for(const[n,s]of a(e)){R(e,n)&&(Array.isArray(s)?t[n]=L(s):s&&"object"==typeof s&&s.constructor===Object?t[n]=D(s):t[n]=s)}return t}function M(e,t){for(;null!==e;){const n=u(e,t);if(n){if(n.get)return k(n.get);if("function"==typeof n.value)return k(n.value)}e=l(e)}return function(){return null}}const P=d(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),U=d(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),H=d(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),$=d(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),F=d(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),z=d(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),j=d(["#text"]),W=d(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),B=d(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),G=d(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),J=d(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Y=p(/\{\{[\w\W]*|[\w\W]*\}\}/gm),X=p(/<%[\w\W]*|[\w\W]*%>/gm),q=p(/\$\{[\w\W]*/gm),K=p(/^data-[\-\w.\u00B7-\uFFFF]+$/),V=p(/^aria-[\-\w]+$/),Z=p(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Q=p(/^(?:\w+script|data):/i),ee=p(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),te=p(/^html$/i),ne=p(/^[a-z][.\w]*(-[.\w]+)+$/i);var se=Object.freeze({__proto__:null,ARIA_ATTR:V,ATTR_WHITESPACE:ee,CUSTOM_ELEMENT:ne,DATA_ATTR:K,DOCTYPE_NAME:te,ERB_EXPR:X,IS_ALLOWED_URI:Z,IS_SCRIPT_OR_DATA:Q,MUSTACHE_EXPR:Y,TMPLIT_EXPR:q});const oe=1,re=3,ae=7,ie=8,ce=9;var le=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"undefined"==typeof window?null:window;const n=t=>e(t);if(n.version="3.3.1",n.removed=[],!t||!t.document||t.document.nodeType!==ce||!t.Element)return n.isSupported=!1,n;let{document:s}=t;const o=s,r=o.currentScript,{DocumentFragment:i,HTMLTemplateElement:c,Node:l,Element:u,NodeFilter:p,NamedNodeMap:m=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:f,DOMParser:O,trustedTypes:k}=t,L=u.prototype,Y=M(L,"cloneNode"),X=M(L,"remove"),q=M(L,"nextSibling"),K=M(L,"childNodes"),V=M(L,"parentNode");if("function"==typeof c){const e=s.createElement("template");e.content&&e.content.ownerDocument&&(s=e.content.ownerDocument)}let Q,ee="";const{implementation:ne,createNodeIterator:le,createDocumentFragment:ue,getElementsByTagName:de}=s,{importNode:pe}=o;let he={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof a&&"function"==typeof V&&ne&&void 0!==ne.createHTMLDocument;const{MUSTACHE_EXPR:me,ERB_EXPR:fe,TMPLIT_EXPR:ge,DATA_ATTR:we,ARIA_ATTR:ye,IS_SCRIPT_OR_DATA:Te,ATTR_WHITESPACE:Se,CUSTOM_ELEMENT:Ee}=se;let{IS_ALLOWED_URI:Ae}=se,be=null;const _e=x({},[...P,...U,...H,...F,...j]);let Ie=null;const Ne=x({},[...W,...B,...G,...J]);let Re=Object.seal(h(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Ce=null,ve=null;const Oe=Object.seal(h(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let ke=!0,xe=!0,Le=!1,De=!0,Me=!1,Pe=!0,Ue=!1,He=!1,$e=!1,Fe=!1,ze=!1,je=!1,We=!0,Be=!1,Ge=!0,Je=!1,Ye={},Xe=null;const qe=x({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Ke=null;const Ve=x({},["audio","video","img","source","image","track"]);let Ze=null;const Qe=x({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),et="http://www.w3.org/1998/Math/MathML",tt="http://www.w3.org/2000/svg",nt="http://www.w3.org/1999/xhtml";let st=nt,ot=!1,rt=null;const at=x({},[et,tt,nt],A);let it=x({},["mi","mo","mn","ms","mtext"]),ct=x({},["annotation-xml"]);const lt=x({},["title","style","font","a","script"]);let ut=null;const dt=["application/xhtml+xml","text/html"];let pt=null,ht=null;const mt=s.createElement("form"),ft=function(e){return e instanceof RegExp||e instanceof Function},gt=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!ht||ht!==e){if(e&&"object"==typeof e||(e={}),e=D(e),ut=-1===dt.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,pt="application/xhtml+xml"===ut?A:E,be=R(e,"ALLOWED_TAGS")?x({},e.ALLOWED_TAGS,pt):_e,Ie=R(e,"ALLOWED_ATTR")?x({},e.ALLOWED_ATTR,pt):Ne,rt=R(e,"ALLOWED_NAMESPACES")?x({},e.ALLOWED_NAMESPACES,A):at,Ze=R(e,"ADD_URI_SAFE_ATTR")?x(D(Qe),e.ADD_URI_SAFE_ATTR,pt):Qe,Ke=R(e,"ADD_DATA_URI_TAGS")?x(D(Ve),e.ADD_DATA_URI_TAGS,pt):Ve,Xe=R(e,"FORBID_CONTENTS")?x({},e.FORBID_CONTENTS,pt):qe,Ce=R(e,"FORBID_TAGS")?x({},e.FORBID_TAGS,pt):D({}),ve=R(e,"FORBID_ATTR")?x({},e.FORBID_ATTR,pt):D({}),Ye=!!R(e,"USE_PROFILES")&&e.USE_PROFILES,ke=!1!==e.ALLOW_ARIA_ATTR,xe=!1!==e.ALLOW_DATA_ATTR,Le=e.ALLOW_UNKNOWN_PROTOCOLS||!1,De=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,Me=e.SAFE_FOR_TEMPLATES||!1,Pe=!1!==e.SAFE_FOR_XML,Ue=e.WHOLE_DOCUMENT||!1,Fe=e.RETURN_DOM||!1,ze=e.RETURN_DOM_FRAGMENT||!1,je=e.RETURN_TRUSTED_TYPE||!1,$e=e.FORCE_BODY||!1,We=!1!==e.SANITIZE_DOM,Be=e.SANITIZE_NAMED_PROPS||!1,Ge=!1!==e.KEEP_CONTENT,Je=e.IN_PLACE||!1,Ae=e.ALLOWED_URI_REGEXP||Z,st=e.NAMESPACE||nt,it=e.MATHML_TEXT_INTEGRATION_POINTS||it,ct=e.HTML_INTEGRATION_POINTS||ct,Re=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&ft(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Re.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&ft(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Re.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(Re.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Me&&(xe=!1),ze&&(Fe=!0),Ye&&(be=x({},j),Ie=[],!0===Ye.html&&(x(be,P),x(Ie,W)),!0===Ye.svg&&(x(be,U),x(Ie,B),x(Ie,J)),!0===Ye.svgFilters&&(x(be,H),x(Ie,B),x(Ie,J)),!0===Ye.mathMl&&(x(be,F),x(Ie,G),x(Ie,J))),e.ADD_TAGS&&("function"==typeof e.ADD_TAGS?Oe.tagCheck=e.ADD_TAGS:(be===_e&&(be=D(be)),x(be,e.ADD_TAGS,pt))),e.ADD_ATTR&&("function"==typeof e.ADD_ATTR?Oe.attributeCheck=e.ADD_ATTR:(Ie===Ne&&(Ie=D(Ie)),x(Ie,e.ADD_ATTR,pt))),e.ADD_URI_SAFE_ATTR&&x(Ze,e.ADD_URI_SAFE_ATTR,pt),e.FORBID_CONTENTS&&(Xe===qe&&(Xe=D(Xe)),x(Xe,e.FORBID_CONTENTS,pt)),e.ADD_FORBID_CONTENTS&&(Xe===qe&&(Xe=D(Xe)),x(Xe,e.ADD_FORBID_CONTENTS,pt)),Ge&&(be["#text"]=!0),Ue&&x(be,["html","head","body"]),be.table&&(x(be,["tbody"]),delete Ce.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw v('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw v('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');Q=e.TRUSTED_TYPES_POLICY,ee=Q.createHTML("")}else void 0===Q&&(Q=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const s="data-tt-policy-suffix";t&&t.hasAttribute(s)&&(n=t.getAttribute(s));const o="dompurify"+(n?"#"+n:"");try{return e.createPolicy(o,{createHTML:e=>e,createScriptURL:e=>e})}catch(r){return null}}(k,r)),null!==Q&&"string"==typeof ee&&(ee=Q.createHTML(""));d&&d(e),ht=e}},wt=x({},[...U,...H,...$]),yt=x({},[...F,...z]),Tt=function(e){T(n.removed,{element:e});try{V(e).removeChild(e)}catch(t){X(e)}},St=function(e,t){try{T(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(s){T(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(Fe||ze)try{Tt(t)}catch(s){}else try{t.setAttribute(e,"")}catch(s){}},Et=function(e){let t=null,n=null;if($e)e="<remove></remove>"+e;else{const t=b(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===ut&&st===nt&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const o=Q?Q.createHTML(e):e;if(st===nt)try{t=(new O).parseFromString(o,ut)}catch(a){}if(!t||!t.documentElement){t=ne.createDocument(st,"template",null);try{t.documentElement.innerHTML=ot?ee:o}catch(a){}}const r=t.body||t.documentElement;return e&&n&&r.insertBefore(s.createTextNode(n),r.childNodes[0]||null),st===nt?de.call(t,Ue?"html":"body")[0]:Ue?t.documentElement:r},At=function(e){return le.call(e.ownerDocument||e,e,p.SHOW_ELEMENT|p.SHOW_COMMENT|p.SHOW_TEXT|p.SHOW_PROCESSING_INSTRUCTION|p.SHOW_CDATA_SECTION,null)},bt=function(e){return e instanceof f&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof m)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},_t=function(e){return"function"==typeof l&&e instanceof l};function It(e,t,s){g(e,e=>{e.call(n,t,s,ht)})}const Nt=function(e){let t=null;if(It(he.beforeSanitizeElements,e,null),bt(e))return Tt(e),!0;const s=pt(e.nodeName);if(It(he.uponSanitizeElement,e,{tagName:s,allowedTags:be}),Pe&&e.hasChildNodes()&&!_t(e.firstElementChild)&&C(/<[/\w!]/g,e.innerHTML)&&C(/<[/\w!]/g,e.textContent))return Tt(e),!0;if(e.nodeType===ae)return Tt(e),!0;if(Pe&&e.nodeType===ie&&C(/<[/\w]/g,e.data))return Tt(e),!0;if(!(Oe.tagCheck instanceof Function&&Oe.tagCheck(s))&&(!be[s]||Ce[s])){if(!Ce[s]&&Ct(s)){if(Re.tagNameCheck instanceof RegExp&&C(Re.tagNameCheck,s))return!1;if(Re.tagNameCheck instanceof Function&&Re.tagNameCheck(s))return!1}if(Ge&&!Xe[s]){const t=V(e)||e.parentNode,n=K(e)||e.childNodes;if(n&&t){for(let s=n.length-1;s>=0;--s){const o=Y(n[s],!0);o.__removalCount=(e.__removalCount||0)+1,t.insertBefore(o,q(e))}}}return Tt(e),!0}return e instanceof u&&!function(e){let t=V(e);t&&t.tagName||(t={namespaceURI:st,tagName:"template"});const n=E(e.tagName),s=E(t.tagName);return!!rt[e.namespaceURI]&&(e.namespaceURI===tt?t.namespaceURI===nt?"svg"===n:t.namespaceURI===et?"svg"===n&&("annotation-xml"===s||it[s]):Boolean(wt[n]):e.namespaceURI===et?t.namespaceURI===nt?"math"===n:t.namespaceURI===tt?"math"===n&&ct[s]:Boolean(yt[n]):e.namespaceURI===nt?!(t.namespaceURI===tt&&!ct[s])&&!(t.namespaceURI===et&&!it[s])&&!yt[n]&&(lt[n]||!wt[n]):!("application/xhtml+xml"!==ut||!rt[e.namespaceURI]))}(e)?(Tt(e),!0):"noscript"!==s&&"noembed"!==s&&"noframes"!==s||!C(/<\/no(script|embed|frames)/i,e.innerHTML)?(Me&&e.nodeType===re&&(t=e.textContent,g([me,fe,ge],e=>{t=_(t,e," ")}),e.textContent!==t&&(T(n.removed,{element:e.cloneNode()}),e.textContent=t)),It(he.afterSanitizeElements,e,null),!1):(Tt(e),!0)},Rt=function(e,t,n){if(We&&("id"===t||"name"===t)&&(n in s||n in mt))return!1;if(xe&&!ve[t]&&C(we,t));else if(ke&&C(ye,t));else if(Oe.attributeCheck instanceof Function&&Oe.attributeCheck(t,e));else if(!Ie[t]||ve[t]){if(!(Ct(e)&&(Re.tagNameCheck instanceof RegExp&&C(Re.tagNameCheck,e)||Re.tagNameCheck instanceof Function&&Re.tagNameCheck(e))&&(Re.attributeNameCheck instanceof RegExp&&C(Re.attributeNameCheck,t)||Re.attributeNameCheck instanceof Function&&Re.attributeNameCheck(t,e))||"is"===t&&Re.allowCustomizedBuiltInElements&&(Re.tagNameCheck instanceof RegExp&&C(Re.tagNameCheck,n)||Re.tagNameCheck instanceof Function&&Re.tagNameCheck(n))))return!1}else if(Ze[t]);else if(C(Ae,_(n,Se,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==I(n,"data:")||!Ke[e]){if(Le&&!C(Te,_(n,Se,"")));else if(n)return!1}else;return!0},Ct=function(e){return"annotation-xml"!==e&&b(e,Ee)},vt=function(e){It(he.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||bt(e))return;const s={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Ie,forceKeepAttr:void 0};let o=t.length;for(;o--;){const a=t[o],{name:i,namespaceURI:c,value:l}=a,u=pt(i),d=l;let p="value"===i?d:N(d);if(s.attrName=u,s.attrValue=p,s.keepAttr=!0,s.forceKeepAttr=void 0,It(he.uponSanitizeAttribute,e,s),p=s.attrValue,!Be||"id"!==u&&"name"!==u||(St(i,e),p="user-content-"+p),Pe&&C(/((--!?|])>)|<\/(style|title|textarea)/i,p)){St(i,e);continue}if("attributename"===u&&b(p,"href")){St(i,e);continue}if(s.forceKeepAttr)continue;if(!s.keepAttr){St(i,e);continue}if(!De&&C(/\/>/i,p)){St(i,e);continue}Me&&g([me,fe,ge],e=>{p=_(p,e," ")});const h=pt(e.nodeName);if(Rt(h,u,p)){if(Q&&"object"==typeof k&&"function"==typeof k.getAttributeType)if(c);else switch(k.getAttributeType(h,u)){case"TrustedHTML":p=Q.createHTML(p);break;case"TrustedScriptURL":p=Q.createScriptURL(p)}if(p!==d)try{c?e.setAttributeNS(c,i,p):e.setAttribute(i,p),bt(e)?Tt(e):y(n.removed)}catch(r){St(i,e)}}else St(i,e)}It(he.afterSanitizeAttributes,e,null)},Ot=function e(t){let n=null;const s=At(t);for(It(he.beforeSanitizeShadowDOM,t,null);n=s.nextNode();)It(he.uponSanitizeShadowNode,n,null),Nt(n),vt(n),n.content instanceof i&&e(n.content);It(he.afterSanitizeShadowDOM,t,null)};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=null,r=null,a=null,c=null;if(ot=!e,ot&&(e="\x3c!--\x3e"),"string"!=typeof e&&!_t(e)){if("function"!=typeof e.toString)throw v("toString is not a function");if("string"!=typeof(e=e.toString()))throw v("dirty is not a string, aborting")}if(!n.isSupported)return e;if(He||gt(t),n.removed=[],"string"==typeof e&&(Je=!1),Je){if(e.nodeName){const t=pt(e.nodeName);if(!be[t]||Ce[t])throw v("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof l)s=Et("\x3c!----\x3e"),r=s.ownerDocument.importNode(e,!0),r.nodeType===oe&&"BODY"===r.nodeName||"HTML"===r.nodeName?s=r:s.appendChild(r);else{if(!Fe&&!Me&&!Ue&&-1===e.indexOf("<"))return Q&&je?Q.createHTML(e):e;if(s=Et(e),!s)return Fe?null:je?ee:""}s&&$e&&Tt(s.firstChild);const u=At(Je?e:s);for(;a=u.nextNode();)Nt(a),vt(a),a.content instanceof i&&Ot(a.content);if(Je)return e;if(Fe){if(ze)for(c=ue.call(s.ownerDocument);s.firstChild;)c.appendChild(s.firstChild);else c=s;return(Ie.shadowroot||Ie.shadowrootmode)&&(c=pe.call(o,c,!0)),c}let d=Ue?s.outerHTML:s.innerHTML;return Ue&&be["!doctype"]&&s.ownerDocument&&s.ownerDocument.doctype&&s.ownerDocument.doctype.name&&C(te,s.ownerDocument.doctype.name)&&(d="<!DOCTYPE "+s.ownerDocument.doctype.name+">\n"+d),Me&&g([me,fe,ge],e=>{d=_(d,e," ")}),Q&&je?Q.createHTML(d):d},n.setConfig=function(){gt(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),He=!0},n.clearConfig=function(){ht=null,He=!1},n.isValidAttribute=function(e,t,n){ht||gt({});const s=pt(e),o=pt(t);return Rt(s,o,n)},n.addHook=function(e,t){"function"==typeof t&&T(he[e],t)},n.removeHook=function(e,t){if(void 0!==t){const n=w(he[e],t);return-1===n?void 0:S(he[e],n,1)[0]}return y(he[e])},n.removeHooks=function(e){he[e]=[]},n.removeAllHooks=function(){he={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}();function ue(e){return function(e,t){const n={ALLOWED_TAGS:["a","b","strong","i","em","u","br","p","span"],ALLOWED_ATTR:["href","target","rel"],ALLOW_DATA_ATTR:!1,...t?.allowedTags&&{ALLOWED_TAGS:t.allowedTags},...t?.allowedAttributes&&{ALLOWED_ATTR:Object.keys(t.allowedAttributes).flatMap(e=>t.allowedAttributes[e])}},s=le.sanitize(e,n);return"string"==typeof s?s:String(s)}(e.replace(/(https?:\/\/[^\s]+)/g,'<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>'),{allowedTags:["a"],allowedAttributes:{a:["href","target","rel"]}})}exports.ChatResolvedError=o,exports.createChatService=function(e){return new r(e)},exports.createDialogflowSession=async function(t,n){try{const s=t.backendBaseUrl||e,o={dfProjectId:t.dfProjectId,dfLocation:t.dfLocation||"us-central1",dfAgentId:t.dfAgentId,languageCode:t.languageCode||"en"};n&&(o.sessionId=n);const r=await fetch(`${s}/api/dialogflow/session/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!r.ok){const e=r.headers.get("content-type");let t={};if(!e||!e.includes("application/json")){const e=await r.text();throw new Error(`API endpoint returned HTML instead of JSON. Status: ${r.status}. Response preview: ${e.substring(0,200)}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${s}/api/dialogflow/session/create`)}try{t=await r.json()}catch{t={}}if(400===r.status)throw new Error(t.message||"Bad request. Please check your Dialogflow configuration.");if(401===r.status)throw new Error(t.message||"Authentication failed. Please check your backend configuration.");if(403===r.status)throw new Error(t.message||"Access forbidden. Please check your permissions.");if(404===r.status)throw new Error(t.message||"Dialogflow agent not found. Please check your project ID, location, and agent ID.");if(500===r.status)throw new Error(t.message||"Internal server error. Please try again later.");throw new Error(t.message||`HTTP error! status: ${r.status}`)}const a=r.headers.get("content-type");if(!a||!a.includes("application/json")){const e=r.clone(),t=await e.text();throw new Error(`API endpoint returned non-JSON response. Status: ${r.status}. Content-Type: ${a||"unknown"}. Response body: ${t.substring(0,200)}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${s}/api/dialogflow/session/create`)}const i=await r.json();if("success"!==i.status)throw new Error(i.message||"Failed to create session. Backend returned unsuccessful status.");const c=i.data||i;return{session_id:c.session_id||i.session_id,message:c.message||"Hello! How can I help you today?",...c.richContent&&{richContent:c.richContent}}}catch(s){if(s.message?.includes("Failed to fetch")||s.message?.includes("CORS"))throw new Error("Network error. Unable to connect to backend. Please check your network connection and CORS settings.");if(s.message&&!s.message.includes("HTTP error"))throw s;throw new Error(s.message||"Failed to create Dialogflow session")}},exports.linkifyText=ue,exports.safeLinkifyText=function(e){return ue(e)},exports.sendDialogflowMessage=async function(t,n,s){try{const o=s.backendBaseUrl||e,r={message:t.trim(),dfProjectId:s.dfProjectId,dfLocation:s.dfLocation||"us-central1",dfAgentId:s.dfAgentId,languageCode:s.languageCode||"en"},a=await fetch(`${o}/api/dialogflow/session/${encodeURIComponent(n)}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!a.ok){const e=a.headers.get("content-type");let t={};if(!e||!e.includes("application/json")){const e=await a.text();throw new Error(`API endpoint returned HTML instead of JSON. Status: ${a.status}. Response preview: ${e.substring(0,200)}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${o}/api/dialogflow/session/${encodeURIComponent(n)}/message`)}try{t=await a.json()}catch{t={}}if(400===a.status)throw new Error(t.message||"Bad request. Please check your message and configuration.");if(401===a.status)throw new Error(t.message||"Authentication failed. Please check your backend configuration.");if(403===a.status)throw new Error(t.message||"Access forbidden. Please check your permissions.");if(404===a.status)throw new Error(t.message||"Dialogflow session not found. Please check your session ID.");if(500===a.status)throw new Error(t.message||"Internal server error. Please try again later.");throw new Error(t.message||`HTTP error! status: ${a.status}`)}const i=a.headers.get("content-type");if(!i||!i.includes("application/json")){const e=a.clone(),t=await e.text();throw new Error(`API endpoint returned non-JSON response. Status: ${a.status}. Content-Type: ${i||"unknown"}. Response body: ${t.substring(0,200)}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${o}/api/dialogflow/session/${encodeURIComponent(n)}/message`)}const c=await a.json();if("success"!==c.status)throw new Error(c.message||"Failed to send message. Backend returned unsuccessful status.");const l=c.data||c,u=l.chat_id??l.chatId??l.data?.chat_id??l.data?.chatId,d=l.support_session_id??l.supportSessionId??l.data?.support_session_id??l.data?.supportSessionId;return{response:l.response||l.message||"",session_id:l.session_id||c.session_id||n,source:l.source||"dialogflow",timestamp:l.timestamp||(new Date).toISOString(),...l.richContent&&{richContent:l.richContent},...void 0!==l.handoff&&{handoff:l.handoff},...u&&{chat_id:u},...d&&{support_session_id:d}}}catch(o){if(o.message?.includes("Failed to fetch")||o.message?.includes("CORS"))throw new Error("Network error. Unable to connect to backend. Please check your network connection and CORS settings.");if(o.message&&!o.message.includes("HTTP error"))throw o;throw new Error(o.message||"Failed to send message to Dialogflow")}};
4
+ //# sourceMappingURL=sanitize-BYa4jHJ0.cjs.map