Files
ai-agent/web/lib/kefu-host-bridge.ts
T
mlogclub bd9fad68a7 refactor: update Kefu widget configuration to use dynamic user token retrieval
- Changed `userToken` property to `getUserToken` function in KefuWidgetHostConfig for dynamic token fetching.
- Introduced KefuWidgetRuntimeConfig to manage runtime-specific configurations.
- Updated readKefuWidgetConfig and setKefuWidgetConfig functions to accommodate new configuration structure.
- Enhanced cs-ai-agent-sdk.js to handle user token resolution and frame configuration.
- Added tests for dynamic user token retrieval in cs-ai-agent-sdk.test.mjs.
- Removed deprecated cs-agent-widget.js file as part of the refactor.
2026-05-06 18:19:49 +08:00

88 lines
2.3 KiB
TypeScript

import {
setKefuWidgetConfig,
type KefuWidgetRuntimeConfig,
} from "@/lib/kefu-widget-config"
type HostBridgeOptions = {
onInit?: () => void
onOpen?: () => void
onMinimize?: () => void
onMaximizedChange?: (isMaximized: boolean) => void
}
const INIT_MESSAGE_TYPE = "cs-agent:init"
const OPEN_MESSAGE_TYPE = "cs-agent:open"
const MINIMIZE_MESSAGE_TYPE = "cs-agent:minimize"
const MAXIMIZED_MESSAGE_TYPE = "cs-agent:maximized"
const READY_MESSAGE_TYPE = "cs-agent:ready"
const REQUEST_MINIMIZE_MESSAGE_TYPE = "cs-agent:request-minimize"
const REQUEST_CLOSE_MESSAGE_TYPE = "cs-agent:request-close"
const REQUEST_TOGGLE_MAXIMIZE_MESSAGE_TYPE = "cs-agent:request-toggle-maximize"
export function bindKefuHostBridge(options: HostBridgeOptions = {}) {
if (typeof window === "undefined") {
return () => undefined
}
if (window.parent && window.parent !== window) {
window.parent.postMessage({ type: READY_MESSAGE_TYPE }, "*")
}
const handleMessage = (event: MessageEvent) => {
const data = event.data as
| {
type?: string
payload?: KefuWidgetRuntimeConfig | { isMaximized?: boolean }
}
| undefined
if (!data?.type) {
return
}
if (data.type === INIT_MESSAGE_TYPE && data.payload) {
setKefuWidgetConfig(data.payload as KefuWidgetRuntimeConfig)
options.onInit?.()
return
}
if (data.type === OPEN_MESSAGE_TYPE) {
options.onOpen?.()
return
}
if (data.type === MINIMIZE_MESSAGE_TYPE) {
options.onMinimize?.()
return
}
if (data.type === MAXIMIZED_MESSAGE_TYPE) {
const payload = data.payload as { isMaximized?: boolean } | undefined
options.onMaximizedChange?.(Boolean(payload?.isMaximized))
}
}
window.addEventListener("message", handleMessage)
return () => window.removeEventListener("message", handleMessage)
}
function postToParent(type: string) {
if (typeof window === "undefined") {
return
}
if (window.parent && window.parent !== window) {
window.parent.postMessage({ type }, "*")
}
}
export function requestKefuHostMinimize() {
postToParent(REQUEST_MINIMIZE_MESSAGE_TYPE)
}
export function requestKefuHostClose() {
postToParent(REQUEST_CLOSE_MESSAGE_TYPE)
}
export function requestKefuHostToggleMaximize() {
postToParent(REQUEST_TOGGLE_MAXIMIZE_MESSAGE_TYPE)
}