import type { MutableRefObject } from 'react'; import { NativeEventEmitter, NativeModules, Platform } from 'react-native'; import type { WebView, WebViewMessageEvent } from 'react-native-webview'; import { extractVideoCallUrl, isAudioVideoStopPayload, parseBridgeMessage } from './parser'; import { EnxBotConfig } from './types'; type QueueItem = | { kind: 'text'; text: string } | { kind: 'file'; base64: string; fileName: string; mimeType: string }; type BridgeCallbacks = { onReady?: () => void; onConnected?: () => void; onDisconnected?: () => void; onReconnecting?: () => void; onReconnected?: () => void; onReconnectFailed?: () => void; onBotInfo?: (info: Record) => void; onConversationReady?: (id: string) => void; onMessage?: (message: unknown) => void; onTyping?: (ms: number) => void; onClear?: (id?: string) => void; onError?: (message: string, type: string) => void; onMessageSentToBot?: () => void; onVideoCallRequest?: (url: string) => void; onVideoCallEnd?: () => void; }; const esc = (s: string): string => s.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t'); /** Payload sent to the chat page for multi-select — echoed back as user text; keep in sync with `sendMultiSuggestion`. */ export function formatMultiSuggestionWireText(values: string[]): string { return `[${values.map((v) => `"${v.replace(/"/g, '\\"')}"`).join(', ')}]`; } export class EnxWebViewBridge { readonly callbacks: BridgeCallbacks = {}; private isReady = false; private initialized = false; private queue: QueueItem[] = []; private ref: MutableRefObject | null = null; /** From last `botInfo` event — used for embedded video `name` query param. */ private botDisplayName?: string; /** iOS native bridge subscription handle. */ private nativeSubscription?: ReturnType; /** * True when running on iOS and the EnxChatBridge native module is available. * In this case the WKWebView is owned by the native module, not by React Native's * WebView component, and all communication goes through NativeModules.EnxChatBridge. */ readonly usesNativePath: boolean = Platform.OS === 'ios' && !!NativeModules.EnxChatBridge; constructor(private readonly config: EnxBotConfig) {} // --------------------------------------------------------------------------- // Lifecycle // --------------------------------------------------------------------------- attachWebViewRef(ref: MutableRefObject): void { this.ref = ref; } /** Call when the widget unmounts so the next mount reruns initialisation. */ resetWebViewSession(): void { this.initialized = false; this.isReady = false; this.botDisplayName = undefined; this.nativeSubscription?.remove(); this.nativeSubscription = undefined; } // --------------------------------------------------------------------------- // Android path — called from WebView's onLoadEnd // --------------------------------------------------------------------------- initializeAfterPageLoad(): void { if (this.usesNativePath) return; // handled by native module on iOS if (this.initialized) return; this.initialized = true; const cfg = JSON.stringify({ botId: this.config.botId, host: this.config.host, path: this.config.rootPath ?? '', }); // ES5-safe polling: no arrow functions or default parameters so the script // works in every WKWebView/Android WebView environment. this.inject(`(function(){window.webkit=window.webkit||{};window.webkit.messageHandlers=window.webkit.messageHandlers||{};window.webkit.messageHandlers.chatCallback={postMessage:function(d){try{var s=(typeof d==='string')?d:JSON.stringify(d);window.ReactNativeWebView&&window.ReactNativeWebView.postMessage(s);}catch(e){}}};if(typeof window.initializeEnxChat==='function'){window.initializeEnxChat(${cfg});}})();true;`); } // --------------------------------------------------------------------------- // iOS native module path — called from ChatWidget on mount // --------------------------------------------------------------------------- initializeNative(): void { if (!this.usesNativePath) return; if (this.initialized) return; this.initialized = true; const emitter = new NativeEventEmitter(NativeModules.EnxChatBridge); this.nativeSubscription = emitter.addListener('EnxChatEvent', this.handleNativeEvent); NativeModules.EnxChatBridge.initialize({ botId: this.config.botId, host: this.config.host, path: this.config.rootPath ?? '', }); } // --------------------------------------------------------------------------- // Incoming messages — WebView path (Android) // --------------------------------------------------------------------------- onMessage = (e: WebViewMessageEvent): void => { let envelope: Record; try { envelope = JSON.parse(e.nativeEvent.data) as Record; } catch { return; } const event = String(envelope.event ?? ''); const data = envelope.data; if (event.toLowerCase().replace(/_/g, '') === 'botinfo') { this.applyBotInfoPayload(envelope, data); return; } this.handleEnvelope(event, data); }; // --------------------------------------------------------------------------- // Incoming messages — native module path (iOS) // --------------------------------------------------------------------------- private handleNativeEvent = (payload: Record): void => { const event = String(payload.event ?? ''); const data = payload.data; if (event.toLowerCase().replace(/_/g, '') === 'botinfo') { this.applyBotInfoPayload(payload, data); return; } this.handleEnvelope(event, data); }; // --------------------------------------------------------------------------- // Shared event dispatcher (used by both paths) // --------------------------------------------------------------------------- private handleEnvelope(event: string, data: unknown): void { switch (event) { case 'chatReady': this.isReady = true; this.flush(); this.callbacks.onReady?.(); break; case 'connected': this.callbacks.onConnected?.(); break; case 'disconnected': this.isReady = false; this.callbacks.onDisconnected?.(); break; case 'reconnecting': this.callbacks.onReconnecting?.(); break; case 'reconnected': this.isReady = true; this.flush(); this.callbacks.onReconnected?.(); break; case 'reconnectFailed': this.callbacks.onReconnectFailed?.(); break; case 'conversationReady': { const map = data && typeof data === 'object' ? (data as Record) : {}; if (typeof map.conversationId === 'string') this.callbacks.onConversationReady?.(map.conversationId); break; } case 'message': { if (isAudioVideoStopPayload(data)) this.callbacks.onVideoCallEnd?.(); const callUrl = extractVideoCallUrl(data, this.botDisplayName); if (callUrl) this.callbacks.onVideoCallRequest?.(callUrl); parseBridgeMessage(data).forEach((m) => this.callbacks.onMessage?.(m)); break; } case 'typing': { const map = data && typeof data === 'object' ? (data as Record) : {}; const ms = Number(map.timeInMs ?? 1500); this.callbacks.onTyping?.(Number.isNaN(ms) ? 1500 : ms); break; } case 'clear': { const map = data && typeof data === 'object' ? (data as Record) : {}; this.callbacks.onClear?.(typeof map.conversationId === 'string' ? map.conversationId : undefined); break; } case 'error': { const map = data && typeof data === 'object' ? (data as Record) : {}; this.callbacks.onError?.(String(map.message ?? 'Unknown JS error'), String(map.type ?? 'unknown')); break; } default: break; } } // --------------------------------------------------------------------------- // Outgoing messages — sendText / sendFile route to native module or WebView // --------------------------------------------------------------------------- async sendText(text: string): Promise { const clean = text.trim(); if (!clean) return; if (!this.isReady) { this.queue.push({ kind: 'text', text: clean }); return; } if (this.usesNativePath) { NativeModules.EnxChatBridge.sendText(clean); } else { this.inject(`(function(){if(typeof sendMessageToBot==='function'){sendMessageToBot('${esc(clean)}',[]);}})();true;`); } this.callbacks.onMessageSentToBot?.(); } async sendSingleSuggestion(value: string): Promise { return this.sendText(value); } async sendMultiSuggestion(values: string[]): Promise { return this.sendText(formatMultiSuggestionWireText(values)); } async sendFile(base64: string, fileName: string, mimeType: string): Promise { if (!this.isReady) { this.queue.push({ kind: 'file', base64, fileName, mimeType }); return; } if (this.usesNativePath) { NativeModules.EnxChatBridge.sendFile(base64, fileName, mimeType); } else { this.inject(`(function(){if(typeof sendFileToBot==='function'){sendFileToBot('${base64}','${esc(fileName)}','${esc(mimeType)}',[]);}})();true;`); } this.callbacks.onMessageSentToBot?.(); } async resetConversation(): Promise { if (this.usesNativePath) { NativeModules.EnxChatBridge.resetConversation(); } else { this.inject(`(function(){try{if(window.chat&&typeof window.chat.resetConversation==='function'){window.chat.resetConversation();return;}if(typeof resetConversation==='function'){resetConversation();return;}if(typeof window.resetConversation==='function'){window.resetConversation();}}catch(e){}})();true;`); } } async reconnect(): Promise { if (this.usesNativePath) { NativeModules.EnxChatBridge.reconnect(); } else { this.inject('window.reconnectChat&&window.reconnectChat();true;'); } } async disconnect(): Promise { if (this.usesNativePath) { NativeModules.EnxChatBridge.disconnect(); } else { this.inject('window.disconnectChat&&window.disconnectChat();true;'); } } // --------------------------------------------------------------------------- // Bot info helper // --------------------------------------------------------------------------- /** * Resolves bot info from `data`, or from the envelope root when the widget posts * `{ event, name, showBotInfoPage, ... }` without a nested `data` object. */ private applyBotInfoPayload(envelope: Record, data: unknown): void { let rec: Record | undefined; const asRecord = (v: unknown): Record | undefined => v && typeof v === 'object' && !Array.isArray(v) ? (v as Record) : undefined; if (typeof data === 'string') { try { const parsed = JSON.parse(data) as unknown; rec = asRecord(parsed); } catch { /* ignore */ } } else { rec = asRecord(data); } const nested = rec?.botInfo; if (nested && typeof nested === 'object' && !Array.isArray(nested)) { rec = nested as Record; } if (!rec && (typeof envelope.name === 'string' || envelope.showBotInfoPage !== undefined)) { rec = { ...envelope }; delete rec.event; delete rec.data; } if (!rec) { console.log('[enx-chatbot-reactnative] botInfo: missing payload (no data object and no root-level bot fields)'); return; } const nameRaw = rec.name ?? rec.botName; if (typeof nameRaw === 'string' && nameRaw.trim()) { this.botDisplayName = nameRaw.trim(); console.log('[enx-chatbot-reactnative] botInfo name for video / display:', this.botDisplayName); } else { console.log('[enx-chatbot-reactnative] botInfo: payload has no name/botName string', JSON.stringify(rec).slice(0, 200)); } this.callbacks.onBotInfo?.(rec); } // --------------------------------------------------------------------------- // Internal // --------------------------------------------------------------------------- private flush(): void { const q = [...this.queue]; this.queue = []; q.forEach((item) => { if (item.kind === 'text') void this.sendText(item.text); else void this.sendFile(item.base64, item.fileName, item.mimeType); }); } private inject(js: string): void { this.ref?.current?.injectJavaScript(js); } }