2026-04-24 14:34:21 +08:00
|
|
|
import { createWebSocketBaseUrl } from "@/lib/api/websocket"
|
2026-04-28 19:56:27 +08:00
|
|
|
import { getCustomerSessionToken, type ImMessage } from "@/lib/api/im"
|
2026-05-30 14:00:23 +08:00
|
|
|
import { readSupportChatRuntimeConfig } from "@/lib/sdk/runtime-config"
|
2026-04-25 17:24:26 +08:00
|
|
|
import type {
|
|
|
|
|
RealtimeConversationPatch,
|
|
|
|
|
RealtimeMessageCreatedPayload,
|
|
|
|
|
} from "@/lib/im-realtime-state"
|
2026-04-24 14:34:21 +08:00
|
|
|
|
|
|
|
|
export type ImRealtimeEnvelope = {
|
|
|
|
|
type: string
|
|
|
|
|
topic?: string
|
2026-04-28 19:56:27 +08:00
|
|
|
data?: RealtimeMessageCreatedPayload<ImMessage> &
|
|
|
|
|
RealtimeConversationPatch & {
|
|
|
|
|
customerSessionToken?: string
|
|
|
|
|
expiresAt?: string
|
|
|
|
|
}
|
|
|
|
|
payload?: RealtimeMessageCreatedPayload<ImMessage> &
|
|
|
|
|
RealtimeConversationPatch & {
|
|
|
|
|
customerSessionToken?: string
|
|
|
|
|
expiresAt?: string
|
|
|
|
|
}
|
2026-04-24 14:34:21 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function createImRealtimeConnection() {
|
2026-05-30 14:00:23 +08:00
|
|
|
const config = readSupportChatRuntimeConfig()
|
2026-04-24 22:32:34 +08:00
|
|
|
const apiBaseUrl = (config.apiBaseUrl || "").trim()
|
2026-04-24 19:17:07 +08:00
|
|
|
const baseUrl = apiBaseUrl
|
|
|
|
|
? apiBaseUrl.replace(/^http/, "ws").replace(/\/$/, "")
|
|
|
|
|
: createWebSocketBaseUrl()
|
|
|
|
|
const channelId = encodeURIComponent(config.channelId || "")
|
2026-04-28 19:56:27 +08:00
|
|
|
const customerSessionToken = getCustomerSessionToken()
|
2026-04-24 14:34:21 +08:00
|
|
|
return new WebSocket(
|
2026-04-28 19:56:27 +08:00
|
|
|
`${baseUrl}/api/ws/open?channelId=${channelId}&customerSessionToken=${encodeURIComponent(customerSessionToken)}`
|
2026-04-24 14:34:21 +08:00
|
|
|
)
|
|
|
|
|
}
|