@blockspark/chat-widget 1.0.14 → 1.0.16
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/{ChatWidget-B6nWBTpX.js → ChatWidget-CFvb5g7s.js} +2 -2
- package/dist/{ChatWidget-B6nWBTpX.js.map → ChatWidget-CFvb5g7s.js.map} +1 -1
- package/dist/ChatWidget-CdA7TymM.cjs +2 -0
- package/dist/ChatWidget-CdA7TymM.cjs.map +1 -0
- package/dist/index.cjs.js +2 -0
- package/dist/index.cjs.js.map +1 -0
- package/dist/index.esm.js +1273 -22
- package/dist/index.esm.js.map +1 -1
- package/dist/nuxt.cjs.js +2 -0
- package/dist/nuxt.cjs.js.map +1 -0
- package/dist/nuxt.esm.js +2 -2
- package/dist/sanitize-DRKcO9o5.cjs +4 -0
- package/dist/sanitize-DRKcO9o5.cjs.map +1 -0
- package/dist/{sanitize-BpLEG5NX.js → sanitize-NEykcppO.js} +5 -4
- package/dist/{sanitize-BpLEG5NX.js.map → sanitize-NEykcppO.js.map} +1 -1
- package/dist/utils/frameworkDetector.d.ts.map +1 -1
- package/dist/utils/sanitize.d.ts.map +1 -1
- package/dist/vue.cjs.js +2 -0
- package/dist/vue.cjs.js.map +1 -0
- package/dist/vue.esm.js +2 -2
- package/package.json +86 -98
- package/dist/ChatWidget-Dfxoglek.js +0 -1181
- package/dist/ChatWidget-Dfxoglek.js.map +0 -1
- package/dist/next.esm.js +0 -9
- package/dist/next.esm.js.map +0 -1
- package/dist/react.esm.js +0 -5
- package/dist/react.esm.js.map +0 -1
- package/dist/vanilla.esm.js +0 -50
- package/dist/vanilla.esm.js.map +0 -1
- /package/dist/{style.css → styles.css} +0 -0
package/dist/index.esm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm.js","sources":["../src/utils/frameworkDetector.ts"],"sourcesContent":["/**\n * Framework Detection Utility\n * Detects which framework is available in the runtime environment\n */\n\nexport type Framework = 'react' | 'vue' | 'next' | 'nuxt' | 'vite' | 'vanilla';\n\nexport interface FrameworkInfo {\n name: Framework;\n version?: string;\n isSSR: boolean;\n}\n\n/**\n * Detects the framework in the current environment\n */\nexport function detectFramework(): FrameworkInfo {\n const isSSR = typeof window === 'undefined';\n \n // Check for Next.js\n if (typeof process !== 'undefined' && process.env?.NEXT_RUNTIME) {\n return {\n name: 'next',\n version: process.env.NEXT_VERSION,\n isSSR,\n };\n }\n \n // Check for Nuxt\n if (typeof process !== 'undefined' && (process.env?.NUXT || (globalThis as any).__NUXT__)) {\n return {\n name: 'nuxt',\n version: (process.env as any).NUXT_VERSION,\n isSSR,\n };\n }\n \n // Check for Vite (development)\n if (typeof import.meta !== 'undefined') {\n const meta = import.meta as any;\n if (meta.env?.DEV) {\n return {\n name: 'vite',\n version: meta.env?.VITE_VERSION,\n isSSR,\n };\n }\n }\n \n // Check for React\n if (detectReact()) {\n return {\n name: 'react',\n version: getReactVersion(),\n isSSR,\n };\n }\n \n // Check for Vue\n if (detectVue()) {\n return {\n name: 'vue',\n version: getVueVersion(),\n isSSR,\n };\n }\n \n // Default to vanilla\n return {\n name: 'vanilla',\n isSSR,\n };\n}\n\n/**\n * Detects if React is available\n */\nfunction detectReact(): boolean {\n // Check global React\n if (typeof window !== 'undefined') {\n if ((window as any).React || (window as any).react) {\n return true;\n }\n }\n \n // Check for React in ES modules (runtime) - try dynamic import\n if (typeof window !== 'undefined') {\n try {\n // Check if React is available via global or module system\n // In browser, React should be available as a global or via module system\n // We can't use require() in browser, so we check for global or module presence\n if (typeof module !== 'undefined' && (module as any).hot) {\n // Likely in a module environment that supports React\n return true;\n }\n } catch {\n // React not available\n }\n }\n \n return false;\n}\n\n/**\n * Gets React version if available\n */\nfunction getReactVersion(): string | undefined {\n try {\n if (typeof window !== 'undefined' && (window as any).React?.version) {\n return (window as any).React.version;\n }\n } catch {\n // Version not available\n }\n \n return undefined;\n}\n\n/**\n * Detects if Vue is available\n */\nfunction detectVue(): boolean {\n // Check global Vue\n if (typeof window !== 'undefined') {\n if ((window as any).Vue || (window as any).vue) {\n return true;\n }\n }\n \n // In browser/module environment, Vue should be available via module system\n // We can't use require() in browser, so we rely on global detection\n return false;\n}\n\n/**\n * Gets Vue version if available\n */\nfunction getVueVersion(): string | undefined {\n try {\n if (typeof window !== 'undefined' && (window as any).Vue?.version) {\n return (window as any).Vue.version;\n }\n } catch {\n // Version not available\n }\n \n return undefined;\n}\n\n/**\n * Forces a specific framework (useful for testing or explicit configuration)\n */\nlet forcedFramework: Framework | null = null;\n\nexport function setFramework(framework: Framework): void {\n forcedFramework = framework;\n}\n\nexport function getFramework(): FrameworkInfo {\n if (forcedFramework) {\n return {\n name: forcedFramework,\n isSSR: typeof window === 'undefined',\n };\n }\n return detectFramework();\n}\n"],"names":[],"mappings":";;;AAgBO,SAAS,kBAAiC;AAC/C,QAAM,QAAQ,OAAO,WAAW;AAGhC,MAAI,OAAO,YAAY,eAAe,QAAQ,KAAK,cAAc;AAC/D,WAAO;AAAA,MACL,MAAM;AAAA,MACN,SAAS,QAAQ,IAAI;AAAA,MACrB;AAAA,IAAA;AAAA,EAEJ;AAGA,MAAI,OAAO,YAAY,gBAAgB,QAAQ,KAAK,QAAS,WAAmB,WAAW;AACzF,WAAO;AAAA,MACL,MAAM;AAAA,MACN,SAAU,QAAQ,IAAY;AAAA,MAC9B;AAAA,IAAA;AAAA,EAEJ;AAGA,MAAI,OAAO,gBAAgB,aAAa;AACtC,UAAM,OAAO;AACb,QAAI,KAAK,KAAK,KAAK;AACjB,aAAO;AAAA,QACL,MAAM;AAAA,QACN,SAAS,KAAK,KAAK;AAAA,QACnB;AAAA,MAAA;AAAA,IAEJ;AAAA,EACF;AAGA,MAAI,eAAe;AACjB,WAAO;AAAA,MACL,MAAM;AAAA,MACN,SAAS,gBAAA;AAAA,MACT;AAAA,IAAA;AAAA,EAEJ;AAGA,MAAI,aAAa;AACf,WAAO;AAAA,MACL,MAAM;AAAA,MACN,SAAS,cAAA;AAAA,MACT;AAAA,IAAA;AAAA,EAEJ;AAGA,SAAO;AAAA,IACL,MAAM;AAAA,IACN;AAAA,EAAA;AAEJ;AAKA,SAAS,cAAuB;AAE9B,MAAI,OAAO,WAAW,aAAa;AACjC,QAAK,OAAe,SAAU,OAAe,OAAO;AAClD,aAAO;AAAA,IACT;AAAA,EACF;AAGA,MAAI,OAAO,WAAW,aAAa;AACjC,QAAI;AAIF,UAAI,OAAO,WAAW,eAAgB,OAAe,KAAK;AAExD,eAAO;AAAA,MACT;AAAA,IACF,QAAQ;AAAA,IAER;AAAA,EACF;AAEA,SAAO;AACT;AAKA,SAAS,kBAAsC;AAC7C,MAAI;AACF,QAAI,OAAO,WAAW,eAAgB,OAAe,OAAO,SAAS;AACnE,aAAQ,OAAe,MAAM;AAAA,IAC/B;AAAA,EACF,QAAQ;AAAA,EAER;AAEA,SAAO;AACT;AAKA,SAAS,YAAqB;AAE5B,MAAI,OAAO,WAAW,aAAa;AACjC,QAAK,OAAe,OAAQ,OAAe,KAAK;AAC9C,aAAO;AAAA,IACT;AAAA,EACF;AAIA,SAAO;AACT;AAKA,SAAS,gBAAoC;AAC3C,MAAI;AACF,QAAI,OAAO,WAAW,eAAgB,OAAe,KAAK,SAAS;AACjE,aAAQ,OAAe,IAAI;AAAA,IAC7B;AAAA,EACF,QAAQ;AAAA,EAER;AAEA,SAAO;AACT;AAKA,IAAI,kBAAoC;AAEjC,SAAS,aAAa,WAA4B;AACvD,oBAAkB;AACpB;AAEO,SAAS,eAA8B;AAC5C,MAAI,iBAAiB;AACnB,WAAO;AAAA,MACL,MAAM;AAAA,MACN,OAAO,OAAO,WAAW;AAAA,IAAA;AAAA,EAE7B;AACA,SAAO,gBAAA;AACT;"}
|
|
1
|
+
{"version":3,"file":"index.esm.js","sources":["../src/hooks/useChatMode.ts","../src/components/ChatWidget.tsx","../src/utils/frameworkDetector.ts","../node_modules/react-dom/client.js","../src/entry/vanilla.ts"],"sourcesContent":["// hooks/useChatMode.ts\nimport { useState, useEffect, useCallback } from \"react\";\nimport type { ChatResponse } from \"../services/dialogflowClient\";\n\nexport type ChatMode = \"BOT\" | \"HUMAN\";\n\nconst MODE_STORAGE_KEY = \"blockspark_chat_mode\";\nconst CHAT_ID_STORAGE_KEY = \"blockspark_chat_id\";\nconst SESSION_ID_STORAGE_KEY = \"blockspark_session_id\";\n\nexport interface UseChatModeReturn {\n currentMode: ChatMode;\n switchToHumanMode: () => void;\n switchToBotMode: () => void;\n isHandoffTriggered: (dialogflowResponse: ChatResponse) => boolean;\n chatId: string | null;\n sessionId: string | null;\n setChatId: (id: string | null) => void;\n setSessionId: (id: string | null) => void;\n}\n\n/**\n * Hook to manage chat mode (BOT or HUMAN)\n */\nexport function useChatMode(): UseChatModeReturn {\n const [currentMode, setCurrentMode] = useState<ChatMode>(() => {\n // Load from localStorage on init\n const savedMode = localStorage.getItem(MODE_STORAGE_KEY);\n return (savedMode === \"HUMAN\" ? \"HUMAN\" : \"BOT\") as ChatMode;\n });\n\n const [chatId, setChatIdState] = useState<string | null>(() => {\n return localStorage.getItem(CHAT_ID_STORAGE_KEY);\n });\n\n const [sessionId, setSessionIdState] = useState<string | null>(() => {\n return localStorage.getItem(SESSION_ID_STORAGE_KEY);\n });\n\n // Persist mode to localStorage\n useEffect(() => {\n localStorage.setItem(MODE_STORAGE_KEY, currentMode);\n }, [currentMode]);\n\n // Persist chat_id to localStorage\n const setChatId = useCallback((id: string | null) => {\n setChatIdState(id);\n if (id) {\n localStorage.setItem(CHAT_ID_STORAGE_KEY, id);\n } else {\n localStorage.removeItem(CHAT_ID_STORAGE_KEY);\n }\n }, []);\n\n // Persist session_id to localStorage\n const setSessionId = useCallback((id: string | null) => {\n setSessionIdState(id);\n if (id) {\n localStorage.setItem(SESSION_ID_STORAGE_KEY, id);\n } else {\n localStorage.removeItem(SESSION_ID_STORAGE_KEY);\n }\n }, []);\n\n const switchToHumanMode = useCallback(() => {\n setCurrentMode(\"HUMAN\");\n }, []);\n\n const switchToBotMode = useCallback(() => {\n setCurrentMode(\"BOT\");\n }, []);\n\n /**\n * Check if Dialogflow response contains handoff trigger\n * Handoff is triggered when response contains {\"handoff\": true}\n * This can be in:\n * - queryResult.parameters.handoff\n * - queryResult.responseMessages payload\n * - queryResult.intent.displayName (if configured)\n */\n const isHandoffTriggered = useCallback(\n (dialogflowResponse: ChatResponse): boolean => {\n // Check if response has handoff flag\n // This would need to be extracted from Dialogflow response\n // For now, we'll check the response text or any custom fields\n \n // The handoff flag might come from Dialogflow's custom payload\n // We need to check the actual Dialogflow response structure\n // Since ChatResponse doesn't include the full response, we'll need to\n // modify the dialogflowClient to pass through handoff information\n \n // For now, return false - this will be handled by dialogflowHandler\n return false;\n },\n []\n );\n\n return {\n currentMode,\n switchToHumanMode,\n switchToBotMode,\n isHandoffTriggered,\n chatId,\n sessionId,\n setChatId,\n setSessionId,\n };\n}\n\n","import React, { useState, useEffect, useRef, useCallback } from \"react\";\nimport {\n createDialogflowSession,\n sendDialogflowMessage,\n type DialogflowConfig,\n type SessionResponse,\n type ChatResponse,\n} from \"../services/dialogflowClient\";\nimport { useChatMode } from \"../hooks/useChatMode\";\nimport { ChatResolvedError, createChatService, type WebSocketMessage } from \"../services/chatService\";\nimport { linkifyText } from \"../utils/sanitize\";\nimport \"../styles/chatWidget.css\";\n\ninterface ChipOption {\n text: string;\n payload: string;\n}\n\ninterface RichContent {\n type?: string;\n options?: ChipOption[];\n}\n\ntype RichContentArray = RichContent | RichContent[];\n\ninterface Message {\n id: string;\n text: string;\n sender: \"user\" | \"bot\" | \"agent\";\n timestamp: Date;\n richContent?: RichContentArray[];\n}\n\nexport interface ChatWidgetProps {\n /** Custom title for the chat widget */\n title?: string;\n /** Custom subtitle for the chat widget */\n subtitle?: string;\n /** Welcome popup title */\n welcomeTitle?: string;\n /** Welcome popup message */\n welcomeMessage?: string;\n /** Welcome popup CTA text */\n welcomeCta?: string;\n /** Whether to show the welcome popup */\n showWelcomePopup?: boolean;\n /** Delay in milliseconds before showing welcome popup */\n welcomePopupDelay?: number;\n /** Fallback welcome message if API fails */\n fallbackWelcomeMessage?: string;\n /** Placeholder text for input field */\n inputPlaceholder?: string;\n /** Custom empty state message */\n emptyStateMessage?: string;\n /** Enable/disable debug logging */\n debug?: boolean;\n /** Dialogflow project ID */\n dfProjectId?: string;\n /** Dialogflow location (e.g., \"us-central1\") */\n dfLocation?: string;\n /** Dialogflow agent ID */\n dfAgentId?: string;\n /** Google Cloud service account key JSON object */\n serviceAccountKey?: any;\n /** Access token (alternative to serviceAccountKey) */\n accessToken?: string;\n /** Language code for Dialogflow */\n languageCode?: string;\n /** Backend API base URL (default: http://localhost:8012) */\n backendBaseUrl?: string;\n /** WebSocket URL (default: ws://localhost:8012) */\n backendWsUrl?: string;\n}\n\nexport default function ChatWidget({\n title = \"💬 BlockSpark AI Assistant\",\n subtitle = \"We're here to help\",\n welcomeTitle = \"👋 Welcome to Blockspark\",\n welcomeMessage = \"My name is BlockSpark AI Assistant and I'll guide you.\",\n welcomeCta = \"💬 Click here to start chatting!\",\n showWelcomePopup: enableWelcomePopup = true,\n welcomePopupDelay = 1500,\n fallbackWelcomeMessage = \"Hello! I'm BlockSpark AI Assistant. How can I help you today?\",\n inputPlaceholder = \"Type your message...\",\n emptyStateMessage = \"Hi! I'm BlockSpark AI Assistant. How can I help you today?\",\n debug = false,\n dfProjectId,\n dfLocation = \"us-central1\",\n dfAgentId,\n serviceAccountKey,\n accessToken,\n languageCode = \"en\",\n backendBaseUrl,\n backendWsUrl,\n}: ChatWidgetProps) {\n const [isOpen, setIsOpen] = useState(false);\n const [showWelcomePopup, setShowWelcomePopup] = useState(false);\n const [messages, setMessages] = useState<Message[]>([]);\n const [inputValue, setInputValue] = useState(\"\");\n const [isLoading, setIsLoading] = useState(false);\n const [sessionId, setSessionId] = useState<string | null>(null);\n const [isInitializing, setIsInitializing] = useState(false);\n const [isConnectingToAgent, setIsConnectingToAgent] = useState(false);\n const [wsConnected, setWsConnected] = useState(false);\n const [agentTyping, setAgentTyping] = useState(false);\n const [currentAgent, setCurrentAgent] = useState<{ name: string; id?: string }>({ name: \"Agent\" });\n const [collectingUserInfo, setCollectingUserInfo] = useState(false);\n const [chatResolved, setChatResolved] = useState(false);\n const [isStartingNewChat, setIsStartingNewChat] = useState(false);\n const [agentAccepted, setAgentAccepted] = useState(false);\n const [userInfoStep, setUserInfoStep] = useState<\"name\" | \"email\" | \"mobile\" | null>(null);\n const [collectedUserName, setCollectedUserName] = useState<string>(\"\");\n const [collectedUserEmail, setCollectedUserEmail] = useState<string>(\"\");\n const [collectedUserMobile, setCollectedUserMobile] = useState<string>(\"\");\n const collectedUserNameRef = useRef<string>(\"\");\n const messagesEndRef = useRef<HTMLDivElement>(null);\n const typingTimeoutRef = useRef<NodeJS.Timeout | null>(null);\n const agentTypingTimeoutRef = useRef<NodeJS.Timeout | null>(null);\n \n // Get backend URLs from props or environment variables\n const getBackendBaseUrl = () => {\n return backendBaseUrl || \n (typeof process !== 'undefined' && (process as any).env?.REACT_APP_BACKEND_BASE_URL)\n };\n \n const getBackendWsUrl = () => {\n return backendWsUrl || \n (typeof process !== 'undefined' && (process as any).env?.REACT_APP_BACKEND_WS_URL)\n };\n \n const chatServiceRef = useRef(\n createChatService({ \n baseUrl: getBackendBaseUrl(), \n wsUrl: getBackendWsUrl(),\n debug: debug\n })\n );\n const historyLoadedRef = useRef<string | null>(null);\n \n // Use chat mode hook\n const {\n currentMode,\n switchToHumanMode,\n switchToBotMode,\n chatId,\n sessionId: supportSessionId,\n setChatId,\n setSessionId: setSupportSessionId,\n } = useChatMode();\n\n const enterResolvedState = useCallback(\n (_resolvedChatId?: string | null) => {\n setChatResolved(true);\n setIsConnectingToAgent(false);\n setAgentAccepted(false);\n setAgentTyping(false);\n if (agentTypingTimeoutRef.current) {\n clearTimeout(agentTypingTimeoutRef.current);\n agentTypingTimeoutRef.current = null;\n }\n\n // Stop WS + prevent any reuse of the old chat_id\n chatServiceRef.current.disconnectWebSocket();\n setChatId(null);\n setSupportSessionId(null);\n \n // Add thank you message before reset\n const thankYouMessage: Message = {\n id: `resolved-${Date.now()}`,\n text: \"Thank you for contacting us!\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, thankYouMessage]);\n \n // Automatically reset to BOT mode after showing thank you message\n setTimeout(() => {\n switchToBotMode();\n setChatResolved(false);\n setMessages([]);\n setCollectingUserInfo(false);\n setUserInfoStep(null);\n setCollectedUserName(\"\");\n setCollectedUserEmail(\"\");\n setCollectedUserMobile(\"\");\n collectedUserNameRef.current = \"\";\n \n // Recreate Dialogflow session to start fresh\n createSession().catch(console.error);\n }, 2000); // 3 second delay to show thank you message\n },\n [setChatId, setSupportSessionId, switchToBotMode]\n );\n\n const handleStartNewChat = useCallback(async () => {\n if (isStartingNewChat) return;\n setIsStartingNewChat(true);\n try {\n const customerName = collectedUserNameRef.current || collectedUserName || null;\n const customerEmail = collectedUserEmail || null;\n const customerMobile = collectedUserMobile || null;\n\n const newSession = await chatServiceRef.current.startSupportChat(\n sessionId || null,\n customerName,\n customerEmail,\n customerMobile\n );\n\n switchToHumanMode();\n setChatId(newSession.chat_id);\n setSupportSessionId(newSession.session_id);\n setChatResolved(false);\n setInputValue(\"\");\n } catch (error: any) {\n console.error(\"Error starting new chat:\", error);\n setMessages((prev) => [\n ...prev,\n {\n id: `error-new-chat-${Date.now()}`,\n text: debug\n ? `Error: ${error?.message || \"Failed to start a new chat.\"}`\n : \"Sorry, I couldn't start a new chat. Please try again.\",\n sender: \"bot\",\n timestamp: new Date(),\n },\n ]);\n } finally {\n setIsStartingNewChat(false);\n }\n }, [\n collectedUserEmail,\n collectedUserMobile,\n collectedUserName,\n debug,\n isStartingNewChat,\n sessionId,\n setChatId,\n setSupportSessionId,\n switchToHumanMode,\n ]);\n\n // Helper function to build Dialogflow config from props\n const getDialogflowConfig = (): DialogflowConfig | undefined => {\n if (!dfProjectId || !dfAgentId) {\n return undefined;\n }\n \n return {\n dfProjectId,\n dfLocation: dfLocation || 'us-central1',\n dfAgentId,\n serviceAccountKey,\n accessToken,\n languageCode: languageCode || 'en',\n };\n };\n\n // Show welcome popup after page load\n useEffect(() => {\n if (!enableWelcomePopup) return;\n \n const timer = setTimeout(() => {\n setShowWelcomePopup(true);\n }, welcomePopupDelay);\n return () => clearTimeout(timer);\n }, [enableWelcomePopup, welcomePopupDelay]);\n\n // Auto-scroll to bottom when new messages arrive\n useEffect(() => {\n messagesEndRef.current?.scrollIntoView({ behavior: \"smooth\" });\n }, [messages]);\n\n // Handle agent changed notification\n const handleAgentChanged = useCallback((message: WebSocketMessage) => {\n if (message.to_agent) {\n setCurrentAgent({\n id: message.to_agent_id,\n name: message.to_agent,\n });\n\n // Add system message to chat\n const systemMessage: Message = {\n id: `system-${Date.now()}`,\n text: message.from_agent\n ? `Chat has been transferred from ${message.from_agent} to ${message.to_agent}`\n : `Chat has been transferred to ${message.to_agent}`,\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, systemMessage]);\n\n if (debug) {\n console.log(\"Agent changed:\", {\n from: message.from_agent,\n to: message.to_agent,\n reason: message.reason,\n });\n }\n }\n }, [debug]);\n\n // Handle WebSocket messages\n const handleWebSocketMessage = useCallback((message: WebSocketMessage) => {\n switch (message.type) {\n case \"message\":\n if (message.content) {\n // Only display messages from agent, ignore customer messages (we already added them)\n if (message.sender_type === \"agent\" || !message.sender_type) {\n const agentMessage: Message = {\n id: message.id || `agent-${Date.now()}`,\n text: message.content,\n sender: \"agent\",\n timestamp: new Date(message.timestamp || Date.now()),\n };\n setMessages((prev) => {\n // Avoid duplicate messages by checking if message ID already exists\n const existingIds = new Set(prev.map(m => m.id));\n if (existingIds.has(agentMessage.id)) {\n return prev;\n }\n return [...prev, agentMessage];\n });\n // Hide typing indicator when message received\n setAgentTyping(false);\n if (agentTypingTimeoutRef.current) {\n clearTimeout(agentTypingTimeoutRef.current);\n agentTypingTimeoutRef.current = null;\n }\n } else if (debug && message.sender_type === \"customer\") {\n console.log(\"Ignoring customer message from WebSocket (already added)\");\n }\n // If sender_type is \"customer\", ignore it - we already added the user message\n } else if (debug) {\n console.warn(\"WebSocket message received without content:\", message);\n }\n break;\n\n case \"typing_start\":\n if (message.sender_type === \"agent\") {\n setAgentTyping(true);\n // Auto-hide after 3 seconds if no message received\n if (agentTypingTimeoutRef.current) {\n clearTimeout(agentTypingTimeoutRef.current);\n }\n agentTypingTimeoutRef.current = setTimeout(() => {\n setAgentTyping(false);\n }, 3000);\n }\n break;\n\n case \"typing_stop\":\n if (message.sender_type === \"agent\") {\n setAgentTyping(false);\n if (agentTypingTimeoutRef.current) {\n clearTimeout(agentTypingTimeoutRef.current);\n agentTypingTimeoutRef.current = null;\n }\n }\n break;\n\n case \"agent_changed\":\n handleAgentChanged(message);\n break;\n\n case \"chat_info\":\n if (debug) {\n console.log(\"Chat info:\", message);\n }\n // Update connection status based on chat info\n if (message.status === \"active\") {\n setIsConnectingToAgent(false);\n setAgentAccepted(true);\n } else if (message.status === \"resolved\" || message.status === \"ended\") {\n enterResolvedState(message.chat_id || null);\n }\n // Update agent info if provided\n if (message.agent_id) {\n setCurrentAgent((prev) => ({\n ...prev,\n id: message.agent_id,\n }));\n }\n break;\n\n case \"agent_accepted\":\n // Agent has accepted the chat request\n setAgentAccepted(true);\n setIsConnectingToAgent(false);\n const acceptedMessage: Message = {\n id: message.id || `agent-accepted-${message.chat_id || Date.now()}-${Date.now()}`,\n text: \"You can chat now, the agent has accepted your request.\",\n sender: \"bot\",\n timestamp: message.timestamp ? new Date(message.timestamp) : new Date(),\n };\n setMessages((prev) => {\n // Avoid duplicate messages\n const existingIds = new Set(prev.map(m => m.id));\n if (existingIds.has(acceptedMessage.id)) {\n return prev;\n }\n return [...prev, acceptedMessage];\n });\n // Update agent info if provided\n if (message.to_agent) {\n setCurrentAgent({\n name: message.to_agent,\n id: message.to_agent_id,\n });\n }\n if (debug) {\n console.log(\"Agent accepted chat:\", message);\n }\n break;\n\n case \"chat_resolved\":\n case \"chat_ended\":\n // Chat has been resolved/ended by agent (terminal state)\n enterResolvedState(message.chat_id || null);\n if (debug) {\n console.log(\"Chat resolved/ended:\", message);\n }\n break;\n\n case \"error\":\n console.error(\"WebSocket error:\", message.error);\n const errorMessage: Message = {\n id: `error-${Date.now()}`,\n text: message.error || \"An error occurred. Please try again.\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, errorMessage]);\n break;\n\n case \"pong\":\n // Keep-alive response, no action needed\n break;\n\n default:\n if (debug) {\n console.log(\"Unknown message type:\", message.type);\n }\n }\n }, [debug, enterResolvedState, handleAgentChanged]);\n\n const handleWebSocketClose = useCallback(\n (event: CloseEvent) => {\n // Backend uses 4000 to indicate the chat is resolved, and then closes.\n if (event.code === 4000) {\n enterResolvedState(chatId);\n }\n },\n [chatId, enterResolvedState]\n );\n\n // Handle WebSocket connection changes\n const handleConnectionChange = useCallback((connected: boolean) => {\n setWsConnected(connected);\n if (connected) {\n setIsConnectingToAgent(false);\n }\n }, []);\n\n // Initialize WebSocket when switching to HUMAN mode\n useEffect(() => {\n if (currentMode === \"HUMAN\" && chatId && supportSessionId) {\n chatServiceRef.current.connectWebSocket(\n chatId,\n supportSessionId,\n handleWebSocketMessage,\n handleConnectionChange,\n handleWebSocketClose\n );\n\n return () => {\n chatServiceRef.current.disconnectWebSocket();\n };\n }\n }, [\n currentMode,\n chatId,\n supportSessionId,\n handleWebSocketMessage,\n handleConnectionChange,\n handleWebSocketClose,\n ]);\n\n // Load message history from backend\n const loadMessageHistory = useCallback(async (preserveExisting: boolean = true) => {\n if (!chatId || !supportSessionId) return;\n\n try {\n setIsLoading(true);\n const history = await chatServiceRef.current.loadMessageHistory(chatId, supportSessionId);\n \n const historyMessages: Message[] = history.map((msg) => ({\n id: msg.id || `msg-${Date.now()}-${Math.random()}`,\n text: msg.content,\n sender: msg.sender_type === \"agent\" ? \"agent\" : \"user\",\n timestamp: new Date(msg.timestamp),\n }));\n\n if (preserveExisting) {\n // Merge with existing messages, avoiding duplicates\n setMessages((prevMessages) => {\n const existingIds = new Set(prevMessages.map(m => m.id));\n const newMessages = historyMessages.filter(m => !existingIds.has(m.id));\n \n // Combine existing messages with new history messages\n // Sort by timestamp to maintain chronological order\n const combined = [...prevMessages, ...newMessages].sort((a, b) => \n a.timestamp.getTime() - b.timestamp.getTime()\n );\n \n return combined;\n });\n } else {\n // Replace all messages (only if explicitly requested)\n setMessages(historyMessages);\n }\n } catch (error: any) {\n console.error(\"Error loading message history:\", error);\n if (debug) {\n const errorMessage: Message = {\n id: `error-${Date.now()}`,\n text: `Failed to load chat history: ${error.message}`,\n sender: \"bot\",\n timestamp: new Date(),\n };\n // Only add error message, don't replace existing messages\n setMessages((prev) => [...prev, errorMessage]);\n }\n } finally {\n setIsLoading(false);\n }\n }, [chatId, supportSessionId, debug]);\n\n // Load message history when switching to HUMAN mode\n useEffect(() => {\n if (currentMode === \"HUMAN\" && chatId && supportSessionId) {\n // Only load if we haven't loaded history for this chat session yet\n const sessionKey = `${chatId}-${supportSessionId}`;\n if (historyLoadedRef.current !== sessionKey) {\n historyLoadedRef.current = sessionKey;\n // Check if we have existing messages (from bot conversation during handoff)\n // If yes, preserve them and don't load history\n // If no, load history for new chat\n // Access messages state via a ref or check in the next tick\n const checkAndLoad = () => {\n // Check messages length - if 0, load history; if > 0, preserve existing\n if (messages.length === 0) {\n // No existing messages, load history\n loadMessageHistory(false).catch(console.error);\n }\n // Has existing messages (bot conversation), keep them - don't load history\n };\n // Use setTimeout to ensure we check after state updates\n setTimeout(checkAndLoad, 0);\n }\n } else if (currentMode === \"BOT\") {\n // Reset history loaded flag when switching back to BOT mode\n historyLoadedRef.current = null;\n }\n }, [currentMode, chatId, supportSessionId, loadMessageHistory, messages.length]);\n\n // Handle handoff from Dialogflow\n const handleHandoff = async (customerName?: string, customerEmail?: string, customerMobile?: string) => {\n try {\n setIsConnectingToAgent(true);\n \n // Get Dialogflow session ID if available\n const dialogflowSessionId = sessionId;\n \n // STEP 1: Ensure chat is initialized (validates existing or creates new)\n const session = await chatServiceRef.current.ensureChatInitialized(\n chatId,\n supportSessionId,\n dialogflowSessionId || null,\n customerName || null,\n customerEmail || null,\n customerMobile || null\n );\n \n if (!session || !session.chat_id) {\n throw new Error(\"Failed to initialize chat session\");\n }\n \n const currentChatId = session.chat_id;\n const currentSupportSessionId = session.session_id;\n \n // Update state if chat was newly initialized\n if (currentChatId !== chatId) {\n setChatId(currentChatId);\n setSupportSessionId(currentSupportSessionId);\n if (debug) {\n console.log(\"✅ Chat initialized:\", { chatId: currentChatId, sessionId: currentSupportSessionId });\n }\n }\n\n // STEP 2: Request handoff with valid chat_id (include name/email/mobile to update existing chat)\n try {\n await chatServiceRef.current.requestHandoff(\n currentChatId,\n currentSupportSessionId,\n \"Customer requested human agent\",\n dialogflowSessionId || null,\n customerName || null,\n customerEmail || null,\n customerMobile || null\n );\n \n if (debug) {\n console.log(\"✅ Handoff requested successfully\");\n }\n } catch (handoffError: any) {\n // Handle 401/404 or \"chat not found\" - clear chat_id and retry (but keep session logic)\n if (handoffError.message?.includes(\"Invalid chat_id\") || \n handoffError.message?.includes(\"Chat not found\") ||\n handoffError.message?.includes(\"unauthorized\") ||\n handoffError.message?.includes(\"400\") ||\n handoffError.message?.includes(\"401\") ||\n handoffError.message?.includes(\"404\") ||\n handoffError.message?.includes(\"expired\")) {\n if (debug) {\n console.log(\"⚠️ Chat expired or not found. Re-initializing chat...\");\n }\n \n // Clear old chat_id (but keep session logic - session_id is managed by sessionManager)\n setChatId(null);\n setSupportSessionId(null);\n \n // Create new chat session (session_id will be automatically included from session manager)\n const newSession = await chatServiceRef.current.startSupportChat(\n dialogflowSessionId || null,\n customerName || null,\n customerEmail || null,\n customerMobile || null\n );\n \n if (!newSession || !newSession.chat_id) {\n throw new Error(\"Failed to re-initialize chat session\");\n }\n \n const newChatId = newSession.chat_id;\n const newSessionId = newSession.session_id;\n setChatId(newChatId);\n setSupportSessionId(newSessionId);\n \n // Retry handoff with new chat_id\n await chatServiceRef.current.requestHandoff(\n newChatId,\n newSessionId,\n \"Customer requested human agent\",\n dialogflowSessionId || null,\n customerName || null,\n customerEmail || null,\n customerMobile || null\n );\n \n if (debug) {\n console.log(\"✅ Handoff requested successfully after retry\");\n }\n \n // Update for message history loading\n const newSessionKey = `${newChatId}-${newSessionId}`;\n if (historyLoadedRef.current !== newSessionKey) {\n historyLoadedRef.current = newSessionKey;\n await loadMessageHistory(true);\n }\n } else {\n throw handoffError;\n }\n }\n\n // Switch to human mode\n switchToHumanMode();\n // Reset states for new handoff\n setChatResolved(false);\n setAgentAccepted(false);\n\n // Add connecting message (preserve existing messages)\n const connectingMessage: Message = {\n id: `connecting-${Date.now()}`,\n text: \"Connecting you to a human agent...\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, connectingMessage]);\n\n // Don't load history during handoff - preserve existing bot conversation\n // History will be loaded automatically via useEffect if needed for new sessions\n const sessionKey = `${currentChatId}-${currentSupportSessionId}`;\n historyLoadedRef.current = sessionKey;\n } catch (error: any) {\n console.error(\"Error handling handoff:\", error);\n const errorMessage: Message = {\n id: `error-${Date.now()}`,\n text: debug\n ? `Handoff error: ${error.message}`\n : \"Failed to connect to agent. Please try again.\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, errorMessage]);\n setIsConnectingToAgent(false);\n }\n };\n\n // Create new session\n const createSession = async () => {\n if (sessionId) return sessionId;\n\n try {\n setIsInitializing(true);\n const dfConfig = getDialogflowConfig();\n if (!dfConfig) {\n throw new Error('Dialogflow configuration is missing. Please provide dfProjectId, dfAgentId, and either serviceAccountKey or accessToken.');\n }\n \n const data = await createDialogflowSession(dfConfig);\n setSessionId(data.session_id);\n\n // Add welcome message from backend\n if (data.message) {\n if (debug) {\n console.log('Session response richContent:', data.richContent);\n console.log('Full session response:', data);\n }\n \n const welcomeMessage: Message = {\n id: `welcome-${Date.now()}`,\n text: data.message,\n sender: \"bot\",\n timestamp: new Date(),\n richContent: data.richContent,\n };\n setMessages([welcomeMessage]);\n }\n\n return data.session_id;\n } catch (error: any) {\n console.error(\"Error creating session:\", error);\n if (debug) {\n console.error(\"Full error details:\", {\n message: error.message,\n stack: error.stack,\n config: getDialogflowConfig(),\n });\n }\n // Show error message to user\n const errorMessage: Message = {\n id: `error-${Date.now()}`,\n text: debug \n ? `Error: ${error.message || 'Failed to create session. Please check your Dialogflow configuration.'}`\n : fallbackWelcomeMessage,\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages([errorMessage]);\n return null;\n } finally {\n setIsInitializing(false);\n }\n };\n\n // Note: Dialogflow manages conversation history internally\n // History is maintained through the session, so we don't need to load it separately\n\n // Send message to backend API\n const sendMessage = async (text: string, displayText?: string, skipUserMessage: boolean = false) => {\n if (!text.trim()) return;\n\n // Handle user info collection for handoff\n if (collectingUserInfo) {\n if (userInfoStep === \"name\") {\n // Save name and ask for email\n const name = text.trim();\n setCollectedUserName(name);\n collectedUserNameRef.current = name;\n setUserInfoStep(\"email\");\n \n // Add user message\n const userMessage: Message = {\n id: Date.now().toString(),\n text: name,\n sender: \"user\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, userMessage]);\n \n // Ask for email\n const emailPrompt: Message = {\n id: (Date.now() + 1).toString(),\n text: \"Thank you! Now please provide your email address:\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, emailPrompt]);\n setInputValue(\"\");\n return;\n } else if (userInfoStep === \"email\") {\n // Validate email format (basic validation)\n const email = text.trim();\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n \n if (!emailRegex.test(email)) {\n // Invalid email, ask again\n const invalidEmailMessage: Message = {\n id: (Date.now() + 1).toString(),\n text: \"Please provide a valid email address:\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, invalidEmailMessage]);\n setInputValue(\"\");\n return;\n }\n \n // Save email and ask for mobile\n setCollectedUserEmail(email);\n setUserInfoStep(\"mobile\");\n \n // Add user message\n const userMessage: Message = {\n id: Date.now().toString(),\n text: email,\n sender: \"user\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, userMessage]);\n \n // Ask for mobile\n const mobilePrompt: Message = {\n id: (Date.now() + 1).toString(),\n text: \"Thank you! Now please provide your mobile number:\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, mobilePrompt]);\n setInputValue(\"\");\n return;\n } else if (userInfoStep === \"mobile\") {\n // Validate mobile format (basic validation - allows +, digits, spaces, dashes)\n const mobile = text.trim();\n const mobileRegex = /^[\\+]?[(]?[0-9]{1,4}[)]?[-\\s\\.]?[(]?[0-9]{1,4}[)]?[-\\s\\.]?[0-9]{1,9}$/;\n \n if (!mobileRegex.test(mobile) || mobile.length < 10) {\n // Invalid mobile, ask again\n const invalidMobileMessage: Message = {\n id: (Date.now() + 1).toString(),\n text: \"Please provide a valid mobile number (e.g., +1234567890):\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, invalidMobileMessage]);\n setInputValue(\"\");\n return;\n }\n \n // Save mobile and proceed with handoff\n setCollectedUserMobile(mobile);\n \n // Add user message\n const userMessage: Message = {\n id: Date.now().toString(),\n text: mobile,\n sender: \"user\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, userMessage]);\n \n // Get the collected info from ref and state (avoids state timing issues)\n const userName = collectedUserNameRef.current;\n const userEmail = collectedUserEmail;\n \n // Reset collection state\n setCollectingUserInfo(false);\n setUserInfoStep(null);\n collectedUserNameRef.current = \"\";\n \n // Proceed with handoff using collected info\n await handleHandoff(userName, userEmail, mobile);\n setInputValue(\"\");\n return;\n }\n }\n\n // Handle HUMAN mode\n if (currentMode === \"HUMAN\") {\n if (!chatId || !supportSessionId) {\n const errorMessage: Message = {\n id: Date.now().toString(),\n text: \"Chat session not initialized. Please try again.\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, errorMessage]);\n return;\n }\n\n // Add user message unless skipped\n if (!skipUserMessage) {\n const userMessage: Message = {\n id: Date.now().toString(),\n text: displayText || text.trim(),\n sender: \"user\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, userMessage]);\n }\n\n // Send typing_stop before sending message\n chatServiceRef.current.sendTypingIndicator(\"typing_stop\");\n \n // Clear typing timeout\n if (typingTimeoutRef.current) {\n clearTimeout(typingTimeoutRef.current);\n typingTimeoutRef.current = null;\n }\n\n setInputValue(\"\");\n setIsLoading(true);\n\n try {\n // Try WebSocket first, fallback to REST API\n const sentViaWs = chatServiceRef.current.sendMessageViaWebSocket(text.trim());\n \n if (!sentViaWs) {\n // Fallback to REST API\n await chatServiceRef.current.sendMessageToAgent(chatId, supportSessionId, text.trim());\n }\n } catch (error: any) {\n // chat_resolved is a normal terminal success condition, not an error.\n if (\n error instanceof ChatResolvedError ||\n error?.name === \"ChatResolvedError\" ||\n error?.message === \"chat_resolved\"\n ) {\n enterResolvedState(chatId);\n return;\n }\n\n console.error(\"Error sending message to agent:\", error);\n \n // Handle 401/404 - clear chat_id and reinitialize (but keep session logic)\n if (error.message?.includes(\"Chat not found\") ||\n error.message?.includes(\"unauthorized\") ||\n error.message?.includes(\"401\") ||\n error.message?.includes(\"404\")) {\n if (debug) {\n console.log(\"⚠️ Chat expired. Re-initializing...\");\n }\n \n // Clear chat_id (session_id is managed by sessionManager)\n setChatId(null);\n setSupportSessionId(null);\n \n // Try to reinitialize chat\n try {\n const newSession = await chatServiceRef.current.startSupportChat(\n sessionId || null,\n null,\n null,\n null\n );\n setChatId(newSession.chat_id);\n setSupportSessionId(newSession.session_id);\n \n // Retry sending message\n try {\n await chatServiceRef.current.sendMessageToAgent(\n newSession.chat_id,\n newSession.session_id,\n text.trim()\n );\n } catch (retryError: any) {\n if (\n retryError instanceof ChatResolvedError ||\n retryError?.name === \"ChatResolvedError\" ||\n retryError?.message === \"chat_resolved\"\n ) {\n enterResolvedState(newSession.chat_id);\n return;\n }\n throw retryError;\n }\n return; // Success, exit early\n } catch (retryError: any) {\n if (\n retryError instanceof ChatResolvedError ||\n retryError?.name === \"ChatResolvedError\" ||\n retryError?.message === \"chat_resolved\"\n ) {\n enterResolvedState(chatId);\n return;\n }\n // If retry fails, show error\n const errorMessage: Message = {\n id: (Date.now() + 1).toString(),\n text: debug\n ? `Error: ${retryError.message || 'Failed to send message.'}`\n : \"Sorry, I'm having trouble sending your message. Please try again.\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, errorMessage]);\n }\n } else {\n const errorMessage: Message = {\n id: (Date.now() + 1).toString(),\n text: debug\n ? `Error: ${error.message || 'Failed to send message to agent.'}`\n : \"Sorry, I'm having trouble sending your message. Please try again.\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, errorMessage]);\n }\n } finally {\n setIsLoading(false);\n }\n return;\n }\n\n // Handle BOT mode (Dialogflow)\n // Ensure we have a session\n let currentSessionId = sessionId;\n if (!currentSessionId) {\n try {\n currentSessionId = await createSession();\n if (!currentSessionId) {\n const errorMessage: Message = {\n id: Date.now().toString(),\n text: debug \n ? \"Failed to create session. Please check the console for details.\"\n : \"Sorry, I'm having trouble connecting. Please try again.\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, errorMessage]);\n return;\n }\n } catch (error: any) {\n console.error(\"Error in createSession:\", error);\n const errorMessage: Message = {\n id: Date.now().toString(),\n text: debug \n ? `Connection Error: ${error.message || 'Please check your Dialogflow configuration.'}`\n : \"Sorry, I'm having trouble connecting. Please check your configuration.\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, errorMessage]);\n return;\n }\n }\n\n // Add user message unless skipped (e.g., when chip button already added it)\n if (!skipUserMessage) {\n const userMessage: Message = {\n id: Date.now().toString(),\n text: displayText || text.trim(),\n sender: \"user\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, userMessage]);\n }\n \n setInputValue(\"\");\n setIsLoading(true);\n\n try {\n const dfConfig = getDialogflowConfig();\n if (!dfConfig) {\n throw new Error('Dialogflow configuration is missing. Please provide dfProjectId, dfAgentId, and either serviceAccountKey or accessToken.');\n }\n \n const data = await sendDialogflowMessage(text.trim(), currentSessionId, dfConfig);\n\n if (debug) {\n console.log('Chat response richContent:', data.richContent);\n console.log('Full chat response:', data);\n console.log('Handoff detected:', data.handoff);\n }\n \n // Check for handoff\n if (data.handoff === true) {\n // Add bot response first\n const botMessage: Message = {\n id: (Date.now() + 1).toString(),\n text: data.response,\n sender: \"bot\",\n timestamp: new Date(data.timestamp || Date.now()),\n richContent: data.richContent,\n };\n setMessages((prev) => [...prev, botMessage]);\n \n // Start collecting user info for handoff\n setCollectingUserInfo(true);\n setUserInfoStep(\"name\");\n setCollectedUserName(\"\");\n setCollectedUserEmail(\"\");\n collectedUserNameRef.current = \"\";\n \n // Ask for name\n const namePrompt: Message = {\n id: (Date.now() + 2).toString(),\n text: \"To connect you with a human agent, I'll need some information. Please provide your name:\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, namePrompt]);\n return;\n }\n \n const botMessage: Message = {\n id: (Date.now() + 1).toString(),\n text: data.response,\n sender: \"bot\",\n timestamp: new Date(data.timestamp || Date.now()),\n richContent: data.richContent,\n };\n\n setMessages((prev) => [...prev, botMessage]);\n } catch (error: any) {\n console.error(\"Error sending message:\", error);\n if (debug) {\n console.error(\"Full error details:\", {\n message: error.message,\n stack: error.stack,\n sessionId: currentSessionId,\n config: getDialogflowConfig(),\n });\n }\n const errorMessage: Message = {\n id: (Date.now() + 1).toString(),\n text: debug\n ? `Error: ${error.message || 'Failed to send message. Please check your Dialogflow configuration.'}`\n : error.message?.includes(\"Failed to fetch\") || error.message?.includes(\"CORS\")\n ? \"Unable to connect to Dialogflow. Please check your configuration and network.\"\n : \"Sorry, I'm having trouble processing your message. Please try again.\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, errorMessage]);\n } finally {\n setIsLoading(false);\n }\n };\n\n const handleSubmit = (e: React.FormEvent) => {\n e.preventDefault();\n sendMessage(inputValue);\n };\n\n // Handle input change - send typing indicators (only in HUMAN mode)\n const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n const value = e.target.value;\n setInputValue(value);\n\n // Only send typing indicators in HUMAN mode with WebSocket connected\n if (currentMode === \"HUMAN\" && wsConnected) {\n // Send typing_start\n chatServiceRef.current.sendTypingIndicator(\"typing_start\");\n\n // Clear existing timeout\n if (typingTimeoutRef.current) {\n clearTimeout(typingTimeoutRef.current);\n }\n\n // Send typing_stop after 2 seconds of inactivity\n typingTimeoutRef.current = setTimeout(() => {\n chatServiceRef.current.sendTypingIndicator(\"typing_stop\");\n typingTimeoutRef.current = null;\n }, 2000);\n }\n };\n\n // Cleanup typing timeouts on unmount\n useEffect(() => {\n return () => {\n if (typingTimeoutRef.current) {\n clearTimeout(typingTimeoutRef.current);\n }\n if (agentTypingTimeoutRef.current) {\n clearTimeout(agentTypingTimeoutRef.current);\n }\n };\n }, []);\n\n const openChat = async () => {\n setIsOpen(true);\n setShowWelcomePopup(false);\n\n // Create session when chat opens if it doesn't exist\n if (!sessionId) {\n await createSession();\n }\n // Note: Dialogflow maintains conversation history internally through the session\n };\n\n const closeChat = () => {\n setIsOpen(false);\n // Disconnect WebSocket when closing chat\n if (currentMode === \"HUMAN\") {\n chatServiceRef.current.disconnectWebSocket();\n }\n };\n\n // Check if message is a handoff message\n const isHandoffMessage = (text: string): boolean => {\n return (\n text.includes(\"👤\") ||\n text.includes(\"being connected\") ||\n text.includes(\"live support agent\") ||\n text.includes(\"transfer your conversation\") ||\n text.includes(\"✅\") ||\n text.includes(\"🔄\")\n );\n };\n\n // Cleanup WebSocket on unmount\n useEffect(() => {\n return () => {\n chatServiceRef.current.disconnectWebSocket();\n };\n }, []);\n\n return (\n <>\n {/* Welcome Popup */}\n {showWelcomePopup && !isOpen && (\n <div className=\"custom-welcome-popup\" onClick={openChat}>\n <div className=\"custom-welcome-header\">\n <div className=\"custom-welcome-title\">{welcomeTitle}</div>\n <button\n className=\"custom-close-popup\"\n onClick={(e) => {\n e.stopPropagation();\n setShowWelcomePopup(false);\n }}\n >\n ×\n </button>\n </div>\n <div className=\"custom-welcome-message\">\n {welcomeMessage}\n </div>\n <div className=\"custom-welcome-cta\">{welcomeCta}</div>\n </div>\n )}\n\n {/* Chat Toggle Button */}\n {!isOpen && (\n <button\n className=\"custom-chat-toggle-btn\"\n onClick={openChat}\n aria-label=\"Open chat\"\n >\n <svg\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <path d=\"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z\"></path>\n </svg>\n </button>\n )}\n\n {/* Chat Window */}\n {isOpen && (\n <div className=\"custom-chat-window\">\n <div className=\"custom-chat-header\">\n <div className=\"custom-chat-header-content\">\n <div className=\"custom-chat-title\">{title}</div>\n <div className=\"custom-chat-subtitle\">\n {subtitle}\n {currentMode === \"HUMAN\" && (\n <span className=\"custom-mode-indicator\">\n {\" \"}\n • {wsConnected ? \"🟢 Connected\" : \"🟡 Connecting...\"}\n </span>\n )}\n </div>\n {currentMode === \"HUMAN\" && (\n <>\n <div className=\"custom-mode-badge\">Human Support Mode</div>\n <div className=\"custom-agent-info\">\n <span className=\"custom-agent-label\">Agent:</span>\n <span className=\"custom-agent-name\">{currentAgent.name}</span>\n </div>\n </>\n )}\n {currentMode === \"BOT\" && (\n <div className=\"custom-mode-badge\">Bot Mode</div>\n )}\n </div>\n <button\n className=\"custom-chat-close-btn\"\n onClick={closeChat}\n aria-label=\"Close chat\"\n >\n ×\n </button>\n </div>\n\n <div className=\"custom-chat-messages\">\n {isInitializing && messages.length === 0 && (\n <div className=\"custom-chat-empty\">\n <div className=\"custom-typing-indicator\">\n <span></span>\n <span></span>\n <span></span>\n </div>\n <p>Initializing chat...</p>\n </div>\n )}\n {!isInitializing && messages.length === 0 && (\n <div className=\"custom-chat-empty\">\n <div className=\"custom-chat-empty-icon\">👋</div>\n <p>{emptyStateMessage}</p>\n </div>\n )}\n {messages.map((message) => (\n <div\n key={message.id}\n className={`custom-message custom-message-${message.sender} ${\n isHandoffMessage(message.text) ? \"custom-handoff-message\" : \"\"\n }`}\n >\n <div \n className={`custom-message-content ${\n isHandoffMessage(message.text) ? \"custom-handoff-content\" : \"\"\n }`}\n dangerouslySetInnerHTML={{ \n __html: linkifyText(message.text).replace(/\\n/g, \"<br>\") \n }}\n />\n {(() => {\n // Debug: Log rich content structure\n if (debug && message.richContent) {\n console.log('Rendering message with richContent:', message.richContent);\n console.log('richContent type:', typeof message.richContent);\n console.log('richContent is array:', Array.isArray(message.richContent));\n console.log('richContent length:', message.richContent?.length);\n }\n \n // Check if richContent exists and has data\n if (message.richContent && Array.isArray(message.richContent) && message.richContent.length > 0) {\n return (\n <div className=\"custom-chips-container\">\n {message.richContent.map((contentGroup, groupIndex) => {\n if (debug) {\n console.log(`Processing contentGroup ${groupIndex}:`, contentGroup);\n }\n if (!Array.isArray(contentGroup)) {\n // Handle case where contentGroup is not an array (single RichContent object)\n const content = contentGroup as RichContent;\n if (content && content.type === \"chips\" && content.options) {\n return (\n <div key={groupIndex} className=\"custom-chips-group\">\n {content.options.map((chip: ChipOption, chipIndex: number) => (\n <button\n key={chipIndex}\n className=\"custom-chip-button\"\n onClick={() => {\n const userMessage: Message = {\n id: Date.now().toString(),\n text: chip.text,\n sender: \"user\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, userMessage]);\n // Send the chip text instead of payload for better intent matching\n // Dialogflow will match the text to the intent\n sendMessage(chip.text, chip.text, true);\n }}\n type=\"button\"\n >\n {chip.text}\n </button>\n ))}\n </div>\n );\n }\n return null;\n }\n return contentGroup.map((content: RichContent, contentIndex: number) => {\n if (debug) {\n console.log(`Processing content ${groupIndex}-${contentIndex}:`, content);\n }\n if (content && content.type === \"chips\" && content.options) {\n return (\n <div key={`${groupIndex}-${contentIndex}`} className=\"custom-chips-group\">\n {content.options.map((chip: ChipOption, chipIndex: number) => (\n <button\n key={chipIndex}\n className=\"custom-chip-button\"\n onClick={() => {\n const userMessage: Message = {\n id: Date.now().toString(),\n text: chip.text,\n sender: \"user\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, userMessage]);\n // Send the chip text instead of payload for better intent matching\n sendMessage(chip.text, chip.text, true);\n }}\n type=\"button\"\n >\n {chip.text}\n </button>\n ))}\n </div>\n );\n }\n return null;\n });\n })}\n </div>\n );\n }\n return null;\n })()}\n <div className=\"custom-message-time\">\n {message.timestamp.toLocaleTimeString([], {\n hour: \"2-digit\",\n minute: \"2-digit\",\n })}\n </div>\n </div>\n ))}\n {isLoading && (\n <div className=\"custom-message custom-message-bot\">\n <div className=\"custom-typing-indicator\">\n <span></span>\n <span></span>\n <span></span>\n </div>\n </div>\n )}\n {isConnectingToAgent && (\n <div className=\"custom-message custom-message-bot\">\n <div className=\"custom-typing-indicator\">\n <span></span>\n <span></span>\n <span></span>\n </div>\n <div className=\"custom-message-content\">\n Connecting to agent...\n </div>\n </div>\n )}\n {/* Agent Typing Indicator */}\n {currentMode === \"HUMAN\" && agentTyping && (\n <div className=\"custom-agent-typing-indicator\">\n <span className=\"custom-typing-dots\">\n <span></span>\n <span></span>\n <span></span>\n </span>\n <span className=\"custom-typing-text\">Agent is typing...</span>\n </div>\n )}\n <div ref={messagesEndRef} />\n </div>\n\n <form className=\"custom-chat-input-form\" onSubmit={handleSubmit}>\n <input\n type=\"text\"\n className=\"custom-chat-input\"\n value={inputValue}\n onChange={handleInputChange}\n placeholder={inputPlaceholder}\n disabled={isLoading || isInitializing || isStartingNewChat}\n />\n <button\n type=\"submit\"\n className=\"custom-chat-send-btn\"\n disabled={!inputValue.trim() || isLoading || isInitializing || isStartingNewChat}\n >\n <svg\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <line x1=\"22\" y1=\"2\" x2=\"11\" y2=\"13\"></line>\n <polygon points=\"22 2 15 22 11 13 2 9 22 2\"></polygon>\n </svg>\n </button>\n </form>\n </div>\n )}\n </>\n );\n} ","/**\n * Framework Detection Utility\n * Detects which framework is available in the runtime environment\n */\n\nexport type Framework = 'react' | 'vue' | 'next' | 'nuxt' | 'vite' | 'vanilla';\n\nexport interface FrameworkInfo {\n name: Framework;\n version?: string;\n isSSR: boolean;\n}\n\n/**\n * Detects the framework in the current environment\n */\nexport function detectFramework(): FrameworkInfo {\n const isSSR = typeof window === 'undefined';\n \n // Check for Next.js\n // Use safe property access to avoid bundling process.env\n if (typeof process !== 'undefined' && typeof (process as any).env !== 'undefined') {\n const env = (process as any).env;\n if (env?.NEXT_RUNTIME) {\n return {\n name: 'next',\n version: env.NEXT_VERSION,\n isSSR,\n };\n }\n }\n \n // Check for Nuxt\n if (typeof process !== 'undefined' && typeof (process as any).env !== 'undefined') {\n const env = (process as any).env;\n if (env?.NUXT || (globalThis as any).__NUXT__) {\n return {\n name: 'nuxt',\n version: env.NUXT_VERSION,\n isSSR,\n };\n }\n }\n \n // Also check for Nuxt via globalThis (SSR-safe)\n if ((globalThis as any).__NUXT__) {\n return {\n name: 'nuxt',\n version: undefined,\n isSSR,\n };\n }\n \n // Check for Vite (development)\n if (typeof import.meta !== 'undefined') {\n const meta = import.meta as any;\n if (meta.env?.DEV) {\n return {\n name: 'vite',\n version: meta.env?.VITE_VERSION,\n isSSR,\n };\n }\n }\n \n // Check for React\n if (detectReact()) {\n return {\n name: 'react',\n version: getReactVersion(),\n isSSR,\n };\n }\n \n // Check for Vue\n if (detectVue()) {\n return {\n name: 'vue',\n version: getVueVersion(),\n isSSR,\n };\n }\n \n // Default to vanilla\n return {\n name: 'vanilla',\n isSSR,\n };\n}\n\n/**\n * Detects if React is available\n */\nfunction detectReact(): boolean {\n // Check global React\n if (typeof window !== 'undefined') {\n if ((window as any).React || (window as any).react) {\n return true;\n }\n }\n \n // Note: Removed module.hot check as it's Node-specific and not available in browser ESM\n \n // For ESM environments, we can't use require.resolve\n // Instead, we check for common React indicators\n if (typeof document !== 'undefined') {\n // Check if React DevTools are present (indicates React is loaded)\n if ((window as any).__REACT_DEVTOOLS_GLOBAL_HOOK__) {\n return true;\n }\n }\n \n return false;\n}\n\n/**\n * Gets React version if available\n */\nfunction getReactVersion(): string | undefined {\n try {\n if (typeof window !== 'undefined' && (window as any).React?.version) {\n return (window as any).React.version;\n }\n \n // In ESM environments, we can't use require\n // Try to get version from React DevTools hook if available\n if (typeof window !== 'undefined' && (window as any).__REACT_DEVTOOLS_GLOBAL_HOOK__) {\n const hook = (window as any).__REACT_DEVTOOLS_GLOBAL_HOOK__;\n if (hook.renderers && hook.renderers.size > 0) {\n const renderer = Array.from(hook.renderers.values())[0] as any;\n return renderer.version;\n }\n }\n } catch {\n // Version not available\n }\n \n return undefined;\n}\n\n/**\n * Detects if Vue is available\n */\nfunction detectVue(): boolean {\n // Check global Vue\n if (typeof window !== 'undefined') {\n if ((window as any).Vue || (window as any).vue) {\n return true;\n }\n }\n \n // For ESM environments, we can't use require.resolve\n // Check for Vue DevTools or other indicators\n if (typeof window !== 'undefined') {\n // Check if Vue DevTools are present\n if ((window as any).__VUE_DEVTOOLS_GLOBAL_HOOK__) {\n return true;\n }\n }\n \n return false;\n}\n\n/**\n * Gets Vue version if available\n */\nfunction getVueVersion(): string | undefined {\n try {\n if (typeof window !== 'undefined' && (window as any).Vue?.version) {\n return (window as any).Vue.version;\n }\n \n // In ESM environments, we can't use require\n // Try to get version from Vue DevTools hook if available\n if (typeof window !== 'undefined' && (window as any).__VUE_DEVTOOLS_GLOBAL_HOOK__) {\n const hook = (window as any).__VUE_DEVTOOLS_GLOBAL_HOOK__;\n if (hook.apps && hook.apps.length > 0) {\n const app = hook.apps[0];\n return app.version;\n }\n }\n } catch {\n // Version not available\n }\n \n return undefined;\n}\n\n/**\n * Forces a specific framework (useful for testing or explicit configuration)\n */\nlet forcedFramework: Framework | null = null;\n\nexport function setFramework(framework: Framework): void {\n forcedFramework = framework;\n}\n\nexport function getFramework(): FrameworkInfo {\n if (forcedFramework) {\n return {\n name: forcedFramework,\n isSSR: typeof window === 'undefined',\n };\n }\n return detectFramework();\n}\n","'use strict';\n\nvar m = require('react-dom');\nif (process.env.NODE_ENV === 'production') {\n exports.createRoot = m.createRoot;\n exports.hydrateRoot = m.hydrateRoot;\n} else {\n var i = m.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;\n exports.createRoot = function(c, o) {\n i.usingClientEntryPoint = true;\n try {\n return m.createRoot(c, o);\n } finally {\n i.usingClientEntryPoint = false;\n }\n };\n exports.hydrateRoot = function(c, h, o) {\n i.usingClientEntryPoint = true;\n try {\n return m.hydrateRoot(c, h, o);\n } finally {\n i.usingClientEntryPoint = false;\n }\n };\n}\n","/**\n * Vanilla JavaScript Entry Point\n * Uses the original ChatWidget.tsx component via ReactDOM\n * Reuses the same component to reduce code duplication\n */\n\nimport React from 'react';\nimport { createRoot, Root } from 'react-dom/client';\nimport ChatWidgetComponent from '../components/ChatWidget';\nimport type { ChatWidgetProps } from '../components/ChatWidget';\nimport '../styles/chatWidget.css';\n\n/**\n * Vanilla JS Chat Widget\n * Renders the original React component using ReactDOM\n * This reuses the same component code, reducing duplication\n */\nexport class ChatWidget {\n private container: HTMLElement;\n private config: ChatWidgetProps;\n private root: Root | null = null;\n\n constructor(container: HTMLElement | string, config: ChatWidgetProps) {\n this.config = config;\n \n // Get container element\n if (typeof container === 'string') {\n const element = document.querySelector(container);\n if (!element) {\n throw new Error(`Container element \"${container}\" not found`);\n }\n this.container = element as HTMLElement;\n } else {\n this.container = container;\n }\n\n // Create React root and render the component\n // This reuses the same ChatWidget.tsx component\n this.root = createRoot(this.container);\n this.render();\n }\n\n private render(): void {\n // Render the original React component using ReactDOM\n // This reuses the same component code, reducing duplication\n if (this.root) {\n this.root.render(React.createElement(ChatWidgetComponent, this.config));\n }\n }\n\n /**\n * Update configuration\n */\n updateConfig(config: Partial<ChatWidgetProps>): void {\n this.config = { ...this.config, ...config };\n this.render();\n }\n\n /**\n * Destroy the widget\n */\n destroy(): void {\n if (this.root) {\n this.root.unmount();\n this.root = null;\n }\n }\n}\n\n/**\n * Factory function for easier usage\n */\nexport function createChatWidget(\n container: HTMLElement | string,\n config: ChatWidgetProps\n): ChatWidget {\n return new ChatWidget(container, config);\n}\n\nexport default ChatWidget;\n"],"names":["ChatWidget","m","welcomeMessage","botMessage","ChatWidgetComponent"],"mappings":";;;;AAMA,MAAM,mBAAmB;AACzB,MAAM,sBAAsB;AAC5B,MAAM,yBAAyB;AAgBxB,SAAS,cAAiC;AAC/C,QAAM,CAAC,aAAa,cAAc,IAAI,SAAmB,MAAM;AAE7D,UAAM,YAAY,aAAa,QAAQ,gBAAgB;AACvD,WAAQ,cAAc,UAAU,UAAU;AAAA,EAC5C,CAAC;AAED,QAAM,CAAC,QAAQ,cAAc,IAAI,SAAwB,MAAM;AAC7D,WAAO,aAAa,QAAQ,mBAAmB;AAAA,EACjD,CAAC;AAED,QAAM,CAAC,WAAW,iBAAiB,IAAI,SAAwB,MAAM;AACnE,WAAO,aAAa,QAAQ,sBAAsB;AAAA,EACpD,CAAC;AAGD,YAAU,MAAM;AACd,iBAAa,QAAQ,kBAAkB,WAAW;AAAA,EACpD,GAAG,CAAC,WAAW,CAAC;AAGhB,QAAM,YAAY,YAAY,CAAC,OAAsB;AACnD,mBAAe,EAAE;AACjB,QAAI,IAAI;AACN,mBAAa,QAAQ,qBAAqB,EAAE;AAAA,IAC9C,OAAO;AACL,mBAAa,WAAW,mBAAmB;AAAA,IAC7C;AAAA,EACF,GAAG,CAAA,CAAE;AAGL,QAAM,eAAe,YAAY,CAAC,OAAsB;AACtD,sBAAkB,EAAE;AACpB,QAAI,IAAI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I;AACmC;AACzC,eAAqB,EAAE;AACD,IAAE;AAC1B;ACWO,MAAM,WAAW;AAAA,EAKtB,YAAY,WAAiC,QAAyB;AAFtE,SAAQ,OAAoB;AAG1B,SAAK,SAAS;AAGd,QAAI,OAAO,cAAc,UAAU;AACjC,YAAM,UAAU,SAAS,cAAc,SAAS;AAChD,UAAI,CAAC,SAAS;AACZ,cAAM,IAAI,MAAM,sBAAsB,SAAS,aAAa;AAAA,MAC9D;AACA,WAAK,YAAY;AAAA,IACnB,OAAO;AACL,WAAK,YAAY;AAAA,IACnB;AAIA,SAAK,OAAO,WAAW,KAAK,SAAS;AACrC,SAAK,OAAA;AAAA,EACP;AAAA,EAEQ,SAAe;AAGrB,QAAI,KAAK,MAAM;AACb,WAAK,KAAK,OAAO,MAAM,cAAcC,cAAqB,KAAK,MAAM,CAAC;AAAA,IACxE;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,aAAa,QAAwC;AACnD,SAAK,SAAS,EAAE,GAAG,KAAK,QAAQ,GAAG,OAAA;AACnC,SAAK,OAAA;AAAA,EACP;AAAA;AAAA;AAAA;AAAA,EAKA,UAAgB;AACd,QAAI,KAAK,MAAM;AACb,WAAK,KAAK,QAAA;AACV,WAAK,OAAO;AAAA,IACd;AAAA,EACF;AACF;AAKO,SAAS,iBACd,WACA,QACY;AACZ,SAAO,IAAI,WAAW,WAAW,MAAM;AACzC;","x_google_ignoreList":[3]}
|
package/dist/nuxt.cjs.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./ChatWidget-CdA7TymM.cjs");exports.ChatWidget=e.ChatWidgetComponent,exports.WidgetStateManager=e.WidgetStateManager,exports.default=e.ChatWidgetComponent,exports.useChatWidget=e.useChatWidget;
|
|
2
|
+
//# sourceMappingURL=nuxt.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nuxt.cjs.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
|
package/dist/nuxt.esm.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as ChatWidgetComponent } from "./ChatWidget-
|
|
2
|
-
import { W, u } from "./ChatWidget-
|
|
1
|
+
import { C as ChatWidgetComponent } from "./ChatWidget-CFvb5g7s.js";
|
|
2
|
+
import { W, u } from "./ChatWidget-CFvb5g7s.js";
|
|
3
3
|
export {
|
|
4
4
|
ChatWidgetComponent as ChatWidget,
|
|
5
5
|
W as WidgetStateManager,
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
"use strict";const e=crypto,t=e=>e instanceof CryptoKey,n=new TextEncoder,r=new TextDecoder;const o=e=>(e=>{let t=e;"string"==typeof t&&(t=n.encode(t));const r=[];for(let n=0;n<t.length;n+=32768)r.push(String.fromCharCode.apply(null,t.subarray(n,n+32768)));return btoa(r.join(""))})(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),s=e=>{let t=e;t instanceof Uint8Array&&(t=r.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return(e=>{const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n})(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class a extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}a.code="ERR_JOSE_GENERIC";(class extends a{constructor(e,t,n="unspecified",r="unspecified"){super(e,{cause:{claim:n,reason:r,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=n,this.reason=r,this.payload=t}}).code="ERR_JWT_CLAIM_VALIDATION_FAILED";(class extends a{constructor(e,t,n="unspecified",r="unspecified"){super(e,{cause:{claim:n,reason:r,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=n,this.reason=r,this.payload=t}}).code="ERR_JWT_EXPIRED";(class extends a{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}).code="ERR_JOSE_ALG_NOT_ALLOWED";class i extends a{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}i.code="ERR_JOSE_NOT_SUPPORTED";(class extends a{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}).code="ERR_JWE_DECRYPTION_FAILED";(class extends a{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}).code="ERR_JWE_INVALID";class c extends a{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}c.code="ERR_JWS_INVALID";class l extends a{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}l.code="ERR_JWT_INVALID";(class extends a{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}).code="ERR_JWK_INVALID";(class extends a{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}).code="ERR_JWKS_INVALID";(class extends a{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}).code="ERR_JWKS_NO_MATCHING_KEY";(class extends a{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}).code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";(class extends a{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}).code="ERR_JWKS_TIMEOUT";function u(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function d(e,t){return e.name===t}function h(e){return parseInt(e.name.slice(4),10)}function p(e,t,...n){switch(t){case"HS256":case"HS384":case"HS512":{if(!d(e.algorithm,"HMAC"))throw u("HMAC");const n=parseInt(t.slice(2),10);if(h(e.algorithm.hash)!==n)throw u(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!d(e.algorithm,"RSASSA-PKCS1-v1_5"))throw u("RSASSA-PKCS1-v1_5");const n=parseInt(t.slice(2),10);if(h(e.algorithm.hash)!==n)throw u(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!d(e.algorithm,"RSA-PSS"))throw u("RSA-PSS");const n=parseInt(t.slice(2),10);if(h(e.algorithm.hash)!==n)throw u(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw u("Ed25519 or Ed448");break;case"Ed25519":if(!d(e.algorithm,"Ed25519"))throw u("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!d(e.algorithm,"ECDSA"))throw u("ECDSA");const n=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==n)throw u(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const n=t.pop();e+=`one of ${t.join(", ")}, or ${n}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,n)}function f(e,t,...n){if((n=n.filter(Boolean)).length>2){const t=n.pop();e+=`one of type ${n.join(", ")}, or ${t}.`}else 2===n.length?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}(class extends a{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}).code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";const m=(e,...t)=>f("Key must be ",e,...t);function g(e,t,...n){return f(`Key for the ${e} algorithm must be `,t,...n)}const y=e=>!!t(e)||"KeyObject"===e?.[Symbol.toStringTag],E=["CryptoKey"];function S(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let n=e;for(;null!==Object.getPrototypeOf(n);)n=Object.getPrototypeOf(n);return Object.getPrototypeOf(e)===n}function w(e){return S(e)&&"string"==typeof e.kty}const A=async t=>{if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:n,keyUsages:r}=function(e){let t,n;switch(e.kty){case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},n=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},n=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},n=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new i('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},n=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},n=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},n=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},n=e.d?["deriveBits"]:[];break;default:throw new i('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":t={name:"Ed25519"},n=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},n=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},n=e.d?["deriveBits"]:[];break;default:throw new i('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new i('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:n}}(t),o=[n,t.ext??!1,t.key_ops??r],s={...t};return delete s.alg,delete s.use,e.subtle.importKey("jwk",s,...o)},_=e=>s(e);let T;const b=e=>"KeyObject"===e?.[Symbol.toStringTag],R=async(e,t,n,r,o=!1)=>{let s=e.get(t);if(s?.[r])return s[r];const a=await A({...n,alg:r});return o&&Object.freeze(t),s?s[r]=a:e.set(t,{[r]:a}),a},I=(e,t)=>{if(b(e)){let n=e.export({format:"jwk"});return n.k?_(n.k):(T||(T=new WeakMap),R(T,e,n,t))}if(w(e)){if(e.k)return s(e.k);T||(T=new WeakMap);return R(T,e,e,t,!0)}return e},v=(e,t,n=0)=>{0===n&&(t.unshift(t.length),t.unshift(6));const r=e.indexOf(t[0],n);if(-1===r)return!1;const o=e.subarray(r,r+t.length);return o.length===t.length&&(o.every((e,n)=>e===t[n])||v(e,t,r+1))},C=e=>{switch(!0){case v(e,[42,134,72,206,61,3,1,7]):return"P-256";case v(e,[43,129,4,0,34]):return"P-384";case v(e,[43,129,4,0,35]):return"P-521";case v(e,[43,101,110]):return"X25519";case v(e,[43,101,111]):return"X448";case v(e,[43,101,112]):return"Ed25519";case v(e,[43,101,113]):return"Ed448";default:throw new i("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},k=(t,n,r)=>(async(t,n,r,o)=>{let s,a;const c=new Uint8Array(atob(r.replace(t,"")).split("").map(e=>e.charCodeAt(0)));switch(o){case"PS256":case"PS384":case"PS512":s={name:"RSA-PSS",hash:`SHA-${o.slice(-3)}`},a=["sign"];break;case"RS256":case"RS384":case"RS512":s={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${o.slice(-3)}`},a=["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":s={name:"RSA-OAEP",hash:`SHA-${parseInt(o.slice(-3),10)||1}`},a=["decrypt","unwrapKey"];break;case"ES256":s={name:"ECDSA",namedCurve:"P-256"},a=["sign"];break;case"ES384":s={name:"ECDSA",namedCurve:"P-384"},a=["sign"];break;case"ES512":s={name:"ECDSA",namedCurve:"P-521"},a=["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=C(c);s=e.startsWith("P-")?{name:"ECDH",namedCurve:e}:{name:e},a=["deriveBits"];break}case"Ed25519":s={name:"Ed25519"},a=["sign"];break;case"EdDSA":s={name:C(c)},a=["sign"];break;default:throw new i('Invalid or unsupported "alg" (Algorithm) value')}return e.subtle.importKey(n,c,s,!1,a)})(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",t,n);const N=e=>e?.[Symbol.toStringTag],D=(e,t,n)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(n))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${n}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},O=(e,t,n,r)=>{if(!(t instanceof Uint8Array)){if(r&&w(t)){if(function(e){return w(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&D(e,t,n))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!y(t))throw new TypeError(g(e,t,...E,"Uint8Array",r?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${N(t)} instances for symmetric algorithms must be of type "secret"`)}};function P(e,t,n,r){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?O(t,n,r,e):((e,t,n,r)=>{if(r&&w(t))switch(n){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&D(e,t,n))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&D(e,t,n))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!y(t))throw new TypeError(g(e,t,...E,r?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${N(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===n&&"public"===t.type)throw new TypeError(`${N(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===n&&"public"===t.type)throw new TypeError(`${N(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===n&&"private"===t.type)throw new TypeError(`${N(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===n&&"private"===t.type)throw new TypeError(`${N(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,n,r,e)}P.bind(void 0,!1);const x=P.bind(void 0,!0);const H=e=>Math.floor(e.getTime()/1e3),L=86400,M=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,W=e=>{const t=M.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const n=parseFloat(t[2]);let r;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":r=Math.round(n);break;case"minute":case"minutes":case"min":case"mins":case"m":r=Math.round(60*n);break;case"hour":case"hours":case"hr":case"hrs":case"h":r=Math.round(3600*n);break;case"day":case"days":case"d":r=Math.round(n*L);break;case"week":case"weeks":case"w":r=Math.round(604800*n);break;default:r=Math.round(31557600*n)}return"-"===t[1]||"ago"===t[4]?-r:r},U=async(n,r,o)=>{const s=await async function(n,r,o){if(r=await I(r,n),t(r))return p(r,n,o),r;if(r instanceof Uint8Array){if(!n.startsWith("HS"))throw new TypeError(m(r,...E));return e.subtle.importKey("raw",r,{hash:`SHA-${n.slice(-3)}`,name:"HMAC"},!1,[o])}throw new TypeError(m(r,...E,"Uint8Array","JSON Web Key"))}(n,r,"sign");((e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:n}=t.algorithm;if("number"!=typeof n||n<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}})(n,s);const a=await e.subtle.sign(function(e,t){const n=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:n,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:n,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:n,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:n,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new i(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(n,s.algorithm),s,o);return new Uint8Array(a)};class K{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new c("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!((...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let n;for(const r of t){const e=Object.keys(r);if(n&&0!==n.size)for(const t of e){if(n.has(t))return!1;n.add(t)}else n=new Set(e)}return!0})(this._protectedHeader,this._unprotectedHeader))throw new c("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...this._protectedHeader,...this._unprotectedHeader},a=function(e,t,n,r,o){if(void 0!==o.crit&&void 0===r?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!r||void 0===r.crit)return new Set;if(!Array.isArray(r.crit)||0===r.crit.length||r.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;s=void 0!==n?new Map([...Object.entries(n),...t.entries()]):t;for(const a of r.crit){if(!s.has(a))throw new i(`Extension Header Parameter "${a}" is not recognized`);if(void 0===o[a])throw new e(`Extension Header Parameter "${a}" is missing`);if(s.get(a)&&void 0===r[a])throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(r.crit)}(c,new Map([["b64",!0]]),t?.crit,this._protectedHeader,s);let l=!0;if(a.has("b64")&&(l=this._protectedHeader.b64,"boolean"!=typeof l))throw new c('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:u}=s;if("string"!=typeof u||!u)throw new c('JWS "alg" (Algorithm) Header Parameter missing or invalid');x(u,e,"sign");let d,h=this._payload;l&&(h=n.encode(o(h))),d=this._protectedHeader?n.encode(o(JSON.stringify(this._protectedHeader))):n.encode("");const p=function(...e){const t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t);let r=0;for(const o of e)n.set(o,r),r+=o.length;return n}(d,n.encode("."),h),f=await U(u,e,p),m={signature:o(f),payload:""};return l&&(m.payload=r.decode(h)),this._unprotectedHeader&&(m.header=this._unprotectedHeader),this._protectedHeader&&(m.protected=r.decode(d)),m}}class ${constructor(e){this._flattened=new K(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const n=await this._flattened.sign(e,t);if(void 0===n.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}}function j(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class F{constructor(e={}){if(!S(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:j("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:j("setNotBefore",H(e))}:this._payload={...this._payload,nbf:H(new Date)+W(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:j("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:j("setExpirationTime",H(e))}:this._payload={...this._payload,exp:H(new Date)+W(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:H(new Date)}:e instanceof Date?this._payload={...this._payload,iat:j("setIssuedAt",H(e))}:this._payload="string"==typeof e?{...this._payload,iat:j("setIssuedAt",H(new Date)+W(e))}:{...this._payload,iat:j("setIssuedAt",e)},this}}class z extends F{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new $(n.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new l("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}async function J(e){const t=Math.floor(Date.now()/1e3);let n=e.private_key;if(!n)throw new Error("Private key is missing from service account key");if(n=n.trim(),n.includes("-----BEGIN")){if(n=n.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),n.includes("BEGIN RSA PRIVATE KEY"))throw new Error("Private key is in PKCS#1 format (RSA PRIVATE KEY). Please download a new service account key from Google Cloud Console. The key should be in PKCS#8 format (PRIVATE KEY).");const e=n.match(/-----BEGIN PRIVATE KEY-----\n?([\s\S]*?)\n?-----END PRIVATE KEY-----/);if(e){const t=e[1].replace(/\s/g,"");if(!t.includes("\n")||t.length>64){n=`-----BEGIN PRIVATE KEY-----\n${t.match(/.{1,64}/g)?.join("\n")||t}\n-----END PRIVATE KEY-----`}}}else{const e=n.replace(/\s/g,"");n=`-----BEGIN PRIVATE KEY-----\n${e.match(/.{1,64}/g)?.join("\n")||e}\n-----END PRIVATE KEY-----`}try{const r=await async function(e,t){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return k(e,t)}(n,"RS256"),o=await new z({scope:"https://www.googleapis.com/auth/cloud-platform"}).setProtectedHeader({alg:"RS256"}).setIssuedAt(t).setExpirationTime(t+3600).setIssuer(e.client_email).setSubject(e.client_email).setAudience("https://oauth2.googleapis.com/token").sign(r),s=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:o})});if(!s.ok){const e=await s.json();throw new Error(e.error_description||"Failed to get access token")}return(await s.json()).access_token}catch(r){if(r.message&&r.message.includes("pkcs8"))throw new Error("Invalid private key format. The service account key must be in PKCS#8 format. Please ensure your service account key JSON file has a properly formatted private_key field. If you downloaded the key from Google Cloud Console, it should already be in the correct format.");throw r}}async function B(e){if(e.accessToken)return e.accessToken;if(!e.serviceAccountKey)throw new Error("Either serviceAccountKey or accessToken must be provided");return await J(e.serviceAccountKey)}function G(e,t,n,r){return`projects/${e}/locations/${t}/agents/${n}/sessions/${r}`}function V(e){let t=null;for(const n of e)if(n.payload){if(n.payload.richContent){t=n.payload.richContent;break}if(n.payload.fields&&n.payload.fields.richContent){const e=n.payload.fields.richContent;e.listValue&&e.listValue.values?t=e.listValue.values.map(e=>e.listValue&&e.listValue.values?e.listValue.values.map(e=>{if(e.structValue&&e.structValue.fields){const t=e.structValue.fields;if(t.type&&t.options)return{type:t.type.stringValue||t.type,options:t.options.listValue?t.options.listValue.values.map(e=>({text:e.structValue?.fields?.text?.stringValue||"",payload:e.structValue?.fields?.payload?.stringValue||""})):[]}}return e}):e):"object"!=typeof e||e.listValue||(t=e);break}}return t}const Y="chat_session_id";class q{constructor(){this.sessionId=null,this.sessionId=this.loadSessionId()}loadSessionId(){return"undefined"!=typeof localStorage?localStorage.getItem(Y):null}saveSessionId(e){this.sessionId=e,"undefined"!=typeof localStorage&&(e?localStorage.setItem(Y,e):localStorage.removeItem(Y))}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 X=null;class Z extends Error{constructor(e="chat_resolved"){super(e),this.reason="chat_resolved",this.name="ChatResolvedError"}}const Q="undefined"!=typeof process&&process.env?.REACT_APP_BACKEND_BASE_URL,ee="undefined"!=typeof process&&process.env?.REACT_APP_BACKEND_WS_URL;class te{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||Q,this.wsUrl=e.wsUrl||ee,this.debug=e.debug||!1,this.sessionManager=(X||(X=new q),X)}async startSupportChat(e,t,n,r){try{const o={"Content-Type":"application/json",...this.sessionManager.getSessionHeader()};e&&(o["X-Session-ID"]=e);const s={};t&&(s.name=t),n&&(s.email=n),r&&(s.mobile=r);const a=await fetch(`${this.baseUrl}/api/support/chat/start`,{method:"POST",headers:o,body:JSON.stringify(s)});if(!a.ok){const e=await a.json().catch(()=>({}));throw new Error(e.message||`HTTP error! status: ${a.status}`)}const i=await a.json();if(this.sessionManager.updateSessionFromResponse(i),i.status&&i.data)return{chat_id:i.data.chat_id,session_id:i.data.session_id};if(i.chat_id&&i.session_id)return{chat_id:i.chat_id,session_id:i.session_id};throw new Error("Invalid response format from chat start endpoint")}catch(o){throw new Error(o.message||"Failed to start support chat session")}}async requestHandoff(e,t,n,r,o,s,a){if(!e||"undefined"===e||"null"===e)throw new Error("Invalid chat_id. Chat must be initialized first.");try{const i={"Content-Type":"application/json",...this.sessionManager.getSessionHeader()};t?i["X-Session-ID"]=t:r&&(i["X-Session-ID"]=r);const c={};n&&(c.reason=n),o&&(c.name=o),s&&(c.email=s),a&&(c.mobile=a);const l=await fetch(`${this.baseUrl}/api/support/chat/${e}/handoff`,{method:"POST",headers:i,body:JSON.stringify(c)});if(400===l.status||404===l.status){const e=await l.json().catch(()=>({}));throw new Error(e.message||"Invalid chat_id. Chat may have expired.")}if(!l.ok){const e=await l.json().catch(()=>({}));throw new Error(e.message||`HTTP error! status: ${l.status}`)}const u=await l.json();return this.sessionManager.updateSessionFromResponse(u),u.status?{success:!0,message:u.message||u.data?.message}:{success:!0,message:u.message}}catch(i){throw i}}async sendMessageToAgent(e,t,n){try{const r={"Content-Type":"application/json",...this.sessionManager.getSessionHeader()};t&&(r["X-Session-ID"]=t);const o=await fetch(`${this.baseUrl}/api/support/chat/${e}/message`,{method:"POST",headers:r,body:JSON.stringify({content:n})});if(401===o.status||404===o.status){const e=await o.json().catch(()=>({}));throw new Error(e.message||"Chat not found or unauthorized")}if(!o.ok){const e=await o.json().catch(()=>({}));throw new Error(e.message||`HTTP error! status: ${o.status}`)}const s=await o.json();if(this.sessionManager.updateSessionFromResponse(s),!0===s?.ignored&&"chat_resolved"===s?.reason)throw new Z;return{id:s.id,sender_type:"customer",content:n,timestamp:s.timestamp||(new Date).toISOString()}}catch(r){if(r instanceof Z||"ChatResolvedError"===r?.name)throw r;throw new Error(r.message||"Failed to send message to agent")}}async ensureChatInitialized(e,t,n,r,o,s){return e&&"undefined"!==e&&"null"!==e&&t?{chat_id:e,session_id:t}:await this.startSupportChat(n||null,r||null,o||null,s||null)}async loadMessageHistory(e,t){try{const n={...this.sessionManager.getSessionHeader()};t&&(n["X-Session-ID"]=t);const r=await fetch(`${this.baseUrl}/api/support/chat/${e}/messages`,{method:"GET",headers:n});if(401===r.status||404===r.status){const e=await r.json().catch(()=>({}));throw new Error(e.message||"Chat not found or unauthorized")}if(!r.ok){const e=await r.json().catch(()=>({}));throw new Error(e.message||`HTTP error! status: ${r.status}`)}const o=await r.json();return this.sessionManager.updateSessionFromResponse(o),o.messages||[]}catch(n){throw new Error(n.message||"Failed to load message history")}}connectWebSocket(e,t,n,r,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),r&&this.connectionHandlers.add(r);const s=t||this.sessionManager.getSessionId()||"",a=`${this.wsUrl}/ws/support/${e}?X-Session-ID=${encodeURIComponent(s)}`;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,r,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
|
+
/*! @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:ne,setPrototypeOf:re,isFrozen:oe,getPrototypeOf:se,getOwnPropertyDescriptor:ae}=Object;let{freeze:ie,seal:ce,create:le}=Object,{apply:ue,construct:de}="undefined"!=typeof Reflect&&Reflect;ie||(ie=function(e){return e}),ce||(ce=function(e){return e}),ue||(ue=function(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),o=2;o<n;o++)r[o-2]=arguments[o];return e.apply(t,r)}),de||(de=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return new e(...n)});const he=ve(Array.prototype.forEach),pe=ve(Array.prototype.lastIndexOf),fe=ve(Array.prototype.pop),me=ve(Array.prototype.push),ge=ve(Array.prototype.splice),ye=ve(String.prototype.toLowerCase),Ee=ve(String.prototype.toString),Se=ve(String.prototype.match),we=ve(String.prototype.replace),Ae=ve(String.prototype.indexOf),_e=ve(String.prototype.trim),Te=ve(Object.prototype.hasOwnProperty),be=ve(RegExp.prototype.test),Re=(Ie=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return de(Ie,t)});var Ie;function ve(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return ue(e,t,r)}}function Ce(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:ye;re&&re(e,null);let r=t.length;for(;r--;){let o=t[r];if("string"==typeof o){const e=n(o);e!==o&&(oe(t)||(t[r]=e),o=e)}e[o]=!0}return e}function ke(e){for(let t=0;t<e.length;t++){Te(e,t)||(e[t]=null)}return e}function Ne(e){const t=le(null);for(const[n,r]of ne(e)){Te(e,n)&&(Array.isArray(r)?t[n]=ke(r):r&&"object"==typeof r&&r.constructor===Object?t[n]=Ne(r):t[n]=r)}return t}function De(e,t){for(;null!==e;){const n=ae(e,t);if(n){if(n.get)return ve(n.get);if("function"==typeof n.value)return ve(n.value)}e=se(e)}return function(){return null}}const Oe=ie(["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"]),Pe=ie(["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"]),xe=ie(["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"]),He=ie(["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"]),Le=ie(["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"]),Me=ie(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),We=ie(["#text"]),Ue=ie(["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"]),Ke=ie(["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"]),$e=ie(["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"]),je=ie(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Fe=ce(/\{\{[\w\W]*|[\w\W]*\}\}/gm),ze=ce(/<%[\w\W]*|[\w\W]*%>/gm),Je=ce(/\$\{[\w\W]*/gm),Be=ce(/^data-[\-\w.\u00B7-\uFFFF]+$/),Ge=ce(/^aria-[\-\w]+$/),Ve=ce(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Ye=ce(/^(?:\w+script|data):/i),qe=ce(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Xe=ce(/^html$/i),Ze=ce(/^[a-z][.\w]*(-[.\w]+)+$/i);var Qe=Object.freeze({__proto__:null,ARIA_ATTR:Ge,ATTR_WHITESPACE:qe,CUSTOM_ELEMENT:Ze,DATA_ATTR:Be,DOCTYPE_NAME:Xe,ERB_EXPR:ze,IS_ALLOWED_URI:Ve,IS_SCRIPT_OR_DATA:Ye,MUSTACHE_EXPR:Fe,TMPLIT_EXPR:Je});const et=1,tt=3,nt=7,rt=8,ot=9;var st=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!==ot||!t.Element)return n.isSupported=!1,n;let{document:r}=t;const o=r,s=o.currentScript,{DocumentFragment:a,HTMLTemplateElement:i,Node:c,Element:l,NodeFilter:u,NamedNodeMap:d=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:h,DOMParser:p,trustedTypes:f}=t,m=l.prototype,g=De(m,"cloneNode"),y=De(m,"remove"),E=De(m,"nextSibling"),S=De(m,"childNodes"),w=De(m,"parentNode");if("function"==typeof i){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let A,_="";const{implementation:T,createNodeIterator:b,createDocumentFragment:R,getElementsByTagName:I}=r,{importNode:v}=o;let C={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof ne&&"function"==typeof w&&T&&void 0!==T.createHTMLDocument;const{MUSTACHE_EXPR:k,ERB_EXPR:N,TMPLIT_EXPR:D,DATA_ATTR:O,ARIA_ATTR:P,IS_SCRIPT_OR_DATA:x,ATTR_WHITESPACE:H,CUSTOM_ELEMENT:L}=Qe;let{IS_ALLOWED_URI:M}=Qe,W=null;const U=Ce({},[...Oe,...Pe,...xe,...Le,...We]);let K=null;const $=Ce({},[...Ue,...Ke,...$e,...je]);let j=Object.seal(le(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}})),F=null,z=null;const J=Object.seal(le(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let B=!0,G=!0,V=!1,Y=!0,q=!1,X=!0,Z=!1,Q=!1,ee=!1,te=!1,re=!1,oe=!1,se=!0,ae=!1,ce=!0,ue=!1,de={},Ie=null;const ve=Ce({},["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 Fe=Ce({},["audio","video","img","source","image","track"]);let ze=null;const Je=Ce({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Be="http://www.w3.org/1998/Math/MathML",Ge="http://www.w3.org/2000/svg",Ye="http://www.w3.org/1999/xhtml";let qe=Ye,Ze=!1,st=null;const at=Ce({},[Be,Ge,Ye],Ee);let it=Ce({},["mi","mo","mn","ms","mtext"]),ct=Ce({},["annotation-xml"]);const lt=Ce({},["title","style","font","a","script"]);let ut=null;const dt=["application/xhtml+xml","text/html"];let ht=null,pt=null;const ft=r.createElement("form"),mt=function(e){return e instanceof RegExp||e instanceof Function},gt=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!pt||pt!==e){if(e&&"object"==typeof e||(e={}),e=Ne(e),ut=-1===dt.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,ht="application/xhtml+xml"===ut?Ee:ye,W=Te(e,"ALLOWED_TAGS")?Ce({},e.ALLOWED_TAGS,ht):U,K=Te(e,"ALLOWED_ATTR")?Ce({},e.ALLOWED_ATTR,ht):$,st=Te(e,"ALLOWED_NAMESPACES")?Ce({},e.ALLOWED_NAMESPACES,Ee):at,ze=Te(e,"ADD_URI_SAFE_ATTR")?Ce(Ne(Je),e.ADD_URI_SAFE_ATTR,ht):Je,ke=Te(e,"ADD_DATA_URI_TAGS")?Ce(Ne(Fe),e.ADD_DATA_URI_TAGS,ht):Fe,Ie=Te(e,"FORBID_CONTENTS")?Ce({},e.FORBID_CONTENTS,ht):ve,F=Te(e,"FORBID_TAGS")?Ce({},e.FORBID_TAGS,ht):Ne({}),z=Te(e,"FORBID_ATTR")?Ce({},e.FORBID_ATTR,ht):Ne({}),de=!!Te(e,"USE_PROFILES")&&e.USE_PROFILES,B=!1!==e.ALLOW_ARIA_ATTR,G=!1!==e.ALLOW_DATA_ATTR,V=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Y=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,q=e.SAFE_FOR_TEMPLATES||!1,X=!1!==e.SAFE_FOR_XML,Z=e.WHOLE_DOCUMENT||!1,te=e.RETURN_DOM||!1,re=e.RETURN_DOM_FRAGMENT||!1,oe=e.RETURN_TRUSTED_TYPE||!1,ee=e.FORCE_BODY||!1,se=!1!==e.SANITIZE_DOM,ae=e.SANITIZE_NAMED_PROPS||!1,ce=!1!==e.KEEP_CONTENT,ue=e.IN_PLACE||!1,M=e.ALLOWED_URI_REGEXP||Ve,qe=e.NAMESPACE||Ye,it=e.MATHML_TEXT_INTEGRATION_POINTS||it,ct=e.HTML_INTEGRATION_POINTS||ct,j=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&mt(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(j.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&mt(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(j.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(j.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),q&&(G=!1),re&&(te=!0),de&&(W=Ce({},We),K=[],!0===de.html&&(Ce(W,Oe),Ce(K,Ue)),!0===de.svg&&(Ce(W,Pe),Ce(K,Ke),Ce(K,je)),!0===de.svgFilters&&(Ce(W,xe),Ce(K,Ke),Ce(K,je)),!0===de.mathMl&&(Ce(W,Le),Ce(K,$e),Ce(K,je))),e.ADD_TAGS&&("function"==typeof e.ADD_TAGS?J.tagCheck=e.ADD_TAGS:(W===U&&(W=Ne(W)),Ce(W,e.ADD_TAGS,ht))),e.ADD_ATTR&&("function"==typeof e.ADD_ATTR?J.attributeCheck=e.ADD_ATTR:(K===$&&(K=Ne(K)),Ce(K,e.ADD_ATTR,ht))),e.ADD_URI_SAFE_ATTR&&Ce(ze,e.ADD_URI_SAFE_ATTR,ht),e.FORBID_CONTENTS&&(Ie===ve&&(Ie=Ne(Ie)),Ce(Ie,e.FORBID_CONTENTS,ht)),e.ADD_FORBID_CONTENTS&&(Ie===ve&&(Ie=Ne(Ie)),Ce(Ie,e.ADD_FORBID_CONTENTS,ht)),ce&&(W["#text"]=!0),Z&&Ce(W,["html","head","body"]),W.table&&(Ce(W,["tbody"]),delete F.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw Re('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw Re('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');A=e.TRUSTED_TYPES_POLICY,_=A.createHTML("")}else void 0===A&&(A=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(n=t.getAttribute(r));const o="dompurify"+(n?"#"+n:"");try{return e.createPolicy(o,{createHTML:e=>e,createScriptURL:e=>e})}catch(s){return null}}(f,s)),null!==A&&"string"==typeof _&&(_=A.createHTML(""));ie&&ie(e),pt=e}},yt=Ce({},[...Pe,...xe,...He]),Et=Ce({},[...Le,...Me]),St=function(e){me(n.removed,{element:e});try{w(e).removeChild(e)}catch(t){y(e)}},wt=function(e,t){try{me(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(r){me(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(te||re)try{St(t)}catch(r){}else try{t.setAttribute(e,"")}catch(r){}},At=function(e){let t=null,n=null;if(ee)e="<remove></remove>"+e;else{const t=Se(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===ut&&qe===Ye&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const o=A?A.createHTML(e):e;if(qe===Ye)try{t=(new p).parseFromString(o,ut)}catch(a){}if(!t||!t.documentElement){t=T.createDocument(qe,"template",null);try{t.documentElement.innerHTML=Ze?_:o}catch(a){}}const s=t.body||t.documentElement;return e&&n&&s.insertBefore(r.createTextNode(n),s.childNodes[0]||null),qe===Ye?I.call(t,Z?"html":"body")[0]:Z?t.documentElement:s},_t=function(e){return b.call(e.ownerDocument||e,e,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT|u.SHOW_PROCESSING_INSTRUCTION|u.SHOW_CDATA_SECTION,null)},Tt=function(e){return e instanceof h&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof d)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},bt=function(e){return"function"==typeof c&&e instanceof c};function Rt(e,t,r){he(e,e=>{e.call(n,t,r,pt)})}const It=function(e){let t=null;if(Rt(C.beforeSanitizeElements,e,null),Tt(e))return St(e),!0;const r=ht(e.nodeName);if(Rt(C.uponSanitizeElement,e,{tagName:r,allowedTags:W}),X&&e.hasChildNodes()&&!bt(e.firstElementChild)&&be(/<[/\w!]/g,e.innerHTML)&&be(/<[/\w!]/g,e.textContent))return St(e),!0;if(e.nodeType===nt)return St(e),!0;if(X&&e.nodeType===rt&&be(/<[/\w]/g,e.data))return St(e),!0;if(!(J.tagCheck instanceof Function&&J.tagCheck(r))&&(!W[r]||F[r])){if(!F[r]&&Ct(r)){if(j.tagNameCheck instanceof RegExp&&be(j.tagNameCheck,r))return!1;if(j.tagNameCheck instanceof Function&&j.tagNameCheck(r))return!1}if(ce&&!Ie[r]){const t=w(e)||e.parentNode,n=S(e)||e.childNodes;if(n&&t){for(let r=n.length-1;r>=0;--r){const o=g(n[r],!0);o.__removalCount=(e.__removalCount||0)+1,t.insertBefore(o,E(e))}}}return St(e),!0}return e instanceof l&&!function(e){let t=w(e);t&&t.tagName||(t={namespaceURI:qe,tagName:"template"});const n=ye(e.tagName),r=ye(t.tagName);return!!st[e.namespaceURI]&&(e.namespaceURI===Ge?t.namespaceURI===Ye?"svg"===n:t.namespaceURI===Be?"svg"===n&&("annotation-xml"===r||it[r]):Boolean(yt[n]):e.namespaceURI===Be?t.namespaceURI===Ye?"math"===n:t.namespaceURI===Ge?"math"===n&&ct[r]:Boolean(Et[n]):e.namespaceURI===Ye?!(t.namespaceURI===Ge&&!ct[r])&&!(t.namespaceURI===Be&&!it[r])&&!Et[n]&&(lt[n]||!yt[n]):!("application/xhtml+xml"!==ut||!st[e.namespaceURI]))}(e)?(St(e),!0):"noscript"!==r&&"noembed"!==r&&"noframes"!==r||!be(/<\/no(script|embed|frames)/i,e.innerHTML)?(q&&e.nodeType===tt&&(t=e.textContent,he([k,N,D],e=>{t=we(t,e," ")}),e.textContent!==t&&(me(n.removed,{element:e.cloneNode()}),e.textContent=t)),Rt(C.afterSanitizeElements,e,null),!1):(St(e),!0)},vt=function(e,t,n){if(se&&("id"===t||"name"===t)&&(n in r||n in ft))return!1;if(G&&!z[t]&&be(O,t));else if(B&&be(P,t));else if(J.attributeCheck instanceof Function&&J.attributeCheck(t,e));else if(!K[t]||z[t]){if(!(Ct(e)&&(j.tagNameCheck instanceof RegExp&&be(j.tagNameCheck,e)||j.tagNameCheck instanceof Function&&j.tagNameCheck(e))&&(j.attributeNameCheck instanceof RegExp&&be(j.attributeNameCheck,t)||j.attributeNameCheck instanceof Function&&j.attributeNameCheck(t,e))||"is"===t&&j.allowCustomizedBuiltInElements&&(j.tagNameCheck instanceof RegExp&&be(j.tagNameCheck,n)||j.tagNameCheck instanceof Function&&j.tagNameCheck(n))))return!1}else if(ze[t]);else if(be(M,we(n,H,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Ae(n,"data:")||!ke[e]){if(V&&!be(x,we(n,H,"")));else if(n)return!1}else;return!0},Ct=function(e){return"annotation-xml"!==e&&Se(e,L)},kt=function(e){Rt(C.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||Tt(e))return;const r={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:K,forceKeepAttr:void 0};let o=t.length;for(;o--;){const a=t[o],{name:i,namespaceURI:c,value:l}=a,u=ht(i),d=l;let h="value"===i?d:_e(d);if(r.attrName=u,r.attrValue=h,r.keepAttr=!0,r.forceKeepAttr=void 0,Rt(C.uponSanitizeAttribute,e,r),h=r.attrValue,!ae||"id"!==u&&"name"!==u||(wt(i,e),h="user-content-"+h),X&&be(/((--!?|])>)|<\/(style|title|textarea)/i,h)){wt(i,e);continue}if("attributename"===u&&Se(h,"href")){wt(i,e);continue}if(r.forceKeepAttr)continue;if(!r.keepAttr){wt(i,e);continue}if(!Y&&be(/\/>/i,h)){wt(i,e);continue}q&&he([k,N,D],e=>{h=we(h,e," ")});const p=ht(e.nodeName);if(vt(p,u,h)){if(A&&"object"==typeof f&&"function"==typeof f.getAttributeType)if(c);else switch(f.getAttributeType(p,u)){case"TrustedHTML":h=A.createHTML(h);break;case"TrustedScriptURL":h=A.createScriptURL(h)}if(h!==d)try{c?e.setAttributeNS(c,i,h):e.setAttribute(i,h),Tt(e)?St(e):fe(n.removed)}catch(s){wt(i,e)}}else wt(i,e)}Rt(C.afterSanitizeAttributes,e,null)},Nt=function e(t){let n=null;const r=_t(t);for(Rt(C.beforeSanitizeShadowDOM,t,null);n=r.nextNode();)Rt(C.uponSanitizeShadowNode,n,null),It(n),kt(n),n.content instanceof a&&e(n.content);Rt(C.afterSanitizeShadowDOM,t,null)};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,s=null,i=null,l=null;if(Ze=!e,Ze&&(e="\x3c!--\x3e"),"string"!=typeof e&&!bt(e)){if("function"!=typeof e.toString)throw Re("toString is not a function");if("string"!=typeof(e=e.toString()))throw Re("dirty is not a string, aborting")}if(!n.isSupported)return e;if(Q||gt(t),n.removed=[],"string"==typeof e&&(ue=!1),ue){if(e.nodeName){const t=ht(e.nodeName);if(!W[t]||F[t])throw Re("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof c)r=At("\x3c!----\x3e"),s=r.ownerDocument.importNode(e,!0),s.nodeType===et&&"BODY"===s.nodeName||"HTML"===s.nodeName?r=s:r.appendChild(s);else{if(!te&&!q&&!Z&&-1===e.indexOf("<"))return A&&oe?A.createHTML(e):e;if(r=At(e),!r)return te?null:oe?_:""}r&&ee&&St(r.firstChild);const u=_t(ue?e:r);for(;i=u.nextNode();)It(i),kt(i),i.content instanceof a&&Nt(i.content);if(ue)return e;if(te){if(re)for(l=R.call(r.ownerDocument);r.firstChild;)l.appendChild(r.firstChild);else l=r;return(K.shadowroot||K.shadowrootmode)&&(l=v.call(o,l,!0)),l}let d=Z?r.outerHTML:r.innerHTML;return Z&&W["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&be(Xe,r.ownerDocument.doctype.name)&&(d="<!DOCTYPE "+r.ownerDocument.doctype.name+">\n"+d),q&&he([k,N,D],e=>{d=we(d,e," ")}),A&&oe?A.createHTML(d):d},n.setConfig=function(){gt(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),Q=!0},n.clearConfig=function(){pt=null,Q=!1},n.isValidAttribute=function(e,t,n){pt||gt({});const r=ht(e),o=ht(t);return vt(r,o,n)},n.addHook=function(e,t){"function"==typeof t&&me(C[e],t)},n.removeHook=function(e,t){if(void 0!==t){const n=pe(C[e],t);return-1===n?void 0:ge(C[e],n,1)[0]}return fe(C[e])},n.removeHooks=function(e){C[e]=[]},n.removeAllHooks=function(){C={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}();function at(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])}},r=st.sanitize(e,n);return"string"==typeof r?r:String(r)}(e.replace(/(https?:\/\/[^\s]+)/g,'<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>'),{allowedTags:["a"],allowedAttributes:{a:["href","target","rel"]}})}exports.ChatResolvedError=Z,exports.createChatService=function(e){return new te(e)},exports.createDialogflowSession=async function(e){try{const t=await B(e),n=`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,r=e.dfLocation.split(" ")[0].trim(),o=`https://${r}-dialogflow.googleapis.com/v3/${G(e.dfProjectId,r,e.dfAgentId,n)}:detectIntent`,s={queryInput:{text:{text:"hello"},languageCode:e.languageCode||"en"}},a=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(s)});if(!a.ok){const e=await a.json().catch(()=>({}));throw new Error(e.error?.message||`HTTP error! status: ${a.status}`)}const i=await a.json();let c="Hello! I'm BlockSpark AI Assistant. How can I help you today?",l=null;if(i.queryResult?.responseMessages){const e=i.queryResult.responseMessages.filter(e=>e.text).map(e=>e.text.text.join(" "));e.length>0&&(c=e.join(" ")),l=V(i.queryResult.responseMessages)}else i.queryResult?.fulfillmentText&&(c=i.queryResult.fulfillmentText);return{session_id:n,message:c,...l&&{richContent:l}}}catch(t){const e=t.message||"Failed to create session";if(e.includes("401")||e.includes("Unauthorized"))throw new Error("Authentication failed. Please check your service account key or access token.");if(e.includes("403")||e.includes("Forbidden"))throw new Error("Access forbidden. Please check your Dialogflow API permissions.");if(e.includes("404")||e.includes("Not Found"))throw new Error("Dialogflow agent not found. Please check your project ID, location, and agent ID.");throw new Error(e)}},exports.linkifyText=at,exports.safeLinkifyText=function(e){return at(e)},exports.sendDialogflowMessage=async function(e,t,n){try{const r=await B(n),o=n.dfLocation.split(" ")[0].trim(),s=`https://${o}-dialogflow.googleapis.com/v3/${G(n.dfProjectId,o,n.dfAgentId,t)}:detectIntent`,a={queryInput:{text:{text:e.trim()},languageCode:n.languageCode||"en"}},i=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(a)});if(!i.ok){const e=await i.text();let t={};try{t=JSON.parse(e)}catch{t={message:e||`HTTP ${i.status}`}}const n=t.error?.message||t.message||`HTTP error! status: ${i.status}`;throw new Error(n)}const c=await i.json();let l="I'm sorry, I didn't understand that. Could you please rephrase?",u=null,d=!1;if(!0===c.queryResult?.parameters?.fields?.handoff?.boolValue)d=!0;else if(c.queryResult?.responseMessages)for(const e of c.queryResult.responseMessages)if(e.payload&&"object"==typeof e.payload){if(!0===e.payload.handoff){d=!0;break}if(!0===e.payload.fields?.handoff?.boolValue){d=!0;break}}if(!0===c.handoff&&(d=!0),c.queryResult?.responseMessages){const e=c.queryResult.responseMessages.filter(e=>e.text).map(e=>e.text.text.join(" "));e.length>0&&(l=e.join(" ")),u=V(c.queryResult.responseMessages)}else c.queryResult?.fulfillmentText&&(l=c.queryResult.fulfillmentText);return{response:l,session_id:t,source:"dialogflow",timestamp:(new Date).toISOString(),...u&&{richContent:u},...d&&{handoff:!0}}}catch(r){const e=r.message||"Failed to send message";if(e.includes("401")||e.includes("Unauthorized"))throw new Error("Authentication failed. Please check your service account key or access token.");if(e.includes("403")||e.includes("Forbidden"))throw new Error("Access forbidden. Please check your Dialogflow API permissions.");if(e.includes("404")||e.includes("Not Found"))throw new Error("Dialogflow agent not found. Please check your project ID, location, and agent ID.");if(e.includes("CORS"))throw new Error("CORS error. Dialogflow API may not allow browser requests. Consider using a backend proxy.");throw new Error(e)}};
|
|
4
|
+
//# sourceMappingURL=sanitize-DRKcO9o5.cjs.map
|