Files
vue-chat-layer/app/lib/client.ts
Jakub Zych 5d581539b3 feat: port the chat store, realtime client and components
- realtime.ts: the page's one Centrifuge client, setRealtimeAuth, onUserEvent for user:{me} events the chat does not handle
- chatEvents, chatFormat, chatText, chatUnread, format, media, tabs ported; copy passed in localized
- useChat over useState: channels with join and leave, DMs, member list, unread and mention counts, read marks, typing, presence, polling fallback
- ChatPanel, ChatHeader, ChatMessage, ChatDmList, ChatMemberPicker, ChatMentionPopup, ChatAvatar, ChatIcon, ChatNotices
- EN and PL strings
2026-10-31 13:52:56 +01:00

265 lines
10 KiB
TypeScript

// The chat layer's HTTP client: golem15.chat (/_chat/api/v1), the host
// bootstrap ({hostApiBase}/chat) and golem15.chatchannels. Pure
// and Nuxt-free, so tests drive it with a stub fetch; useChatApi binds it to
// runtime config and the app's $chatAuth hook.
//
// Every request carries `Authorization: Bearer {auth.token()}`. A 401 on a
// request that carried a token refreshes once through auth.refresh() (one
// refresh at a time; concurrent 401s share it) and retries; a second 401, or
// a refresh that yields no token, calls auth.unauthorized(). The layer never
// stores the token.
import type {
ChatBootstrap,
ChatConversation,
ChatMember,
ChatMessage,
ChatSendBody,
} from './types'
/** The app's auth hook ($chatAuth): the user's JWT, its renewal and the signed-out callback. */
export interface ChatAuth {
token(): string | null | undefined
/** Renews the token and answers the new one, or null when the session cannot be renewed. */
refresh?(): Promise<string | null | undefined>
/** Called once a request failed with 401 and the refresh did not help. */
unauthorized?(): void
/** The caller's user id; without it the chat reads the token's numeric sub claim. */
userId?(): number | null | undefined
}
/** The API bases: same-origin paths in the browser. */
export interface ChatBases {
/** golem15.chat, e.g. /_chat/api/v1. */
chat: string
/** golem15.chatchannels, e.g. /_chatchannels/api/v1. */
channels: string
/** golem15.chatbots, e.g. /_chatbots/api/v1. */
bots: string
/** The host's bootstrap routes ({host}/chat, {host}/chat/members). */
host: string
}
export type ChatFetch = (url: string, init: { method: string; headers: Record<string, string>; body?: string | FormData }) => Promise<Response>
export interface ChatClientOptions {
bases: ChatBases
auth: ChatAuth
fetch?: ChatFetch
}
/** A refused request: the HTTP status (0 without a connection), the message and the 422 field errors. */
export class ChatApiError extends Error {
status: number
errors: Record<string, string[]>
constructor(status: number, message: string, errors: Record<string, string[]> = {}) {
super(message)
this.name = 'ChatApiError'
this.status = status
this.errors = errors
}
/** The first error of a field, or ''. */
field(name: string): string {
return this.errors[name]?.[0] ?? ''
}
}
export interface RequestOptions {
method?: string
query?: Record<string, string | number | undefined | null>
body?: unknown
}
export interface MessagePage {
limit?: number
/** Only messages older than this id. */
before?: number
}
/**
* userIdFromToken reads the numeric sub claim of a JWT without verifying it
* (the server does): the chat needs the caller's id for its user:{id}
* channel and to tell its own messages apart. null for anything else.
*/
export function userIdFromToken(token: string | null | undefined): number | null {
if (!token) return null
const part = token.split('.')[1]
if (!part) return null
try {
const b64 = part.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(part.length / 4) * 4, '=')
const claims = JSON.parse(globalThis.atob(b64)) as { sub?: unknown }
const n = typeof claims.sub === 'string' ? Number(claims.sub.trim()) : claims.sub
return typeof n === 'number' && Number.isInteger(n) && n > 0 ? n : null
} catch {
return null
}
}
function joinUrl(base: string, path: string): string {
return `${base.replace(/\/+$/, '')}${path}`
}
function withQuery(url: string, query?: RequestOptions['query']): string {
if (!query) return url
const qs = new URLSearchParams()
for (const [k, v] of Object.entries(query)) {
if (v !== undefined && v !== null && v !== '') qs.set(k, String(v))
}
const s = qs.toString()
return s ? `${url}?${s}` : url
}
function errorsOf(v: unknown): Record<string, string[]> {
if (!v || typeof v !== 'object' || Array.isArray(v)) return {}
const out: Record<string, string[]> = {}
for (const [k, list] of Object.entries(v as Record<string, unknown>)) {
if (Array.isArray(list)) out[k] = list.filter((x): x is string => typeof x === 'string')
else if (typeof list === 'string') out[k] = [list]
}
return out
}
/** toError maps an error body ({"error": msg, "errors": {field: [msg]}}) to a ChatApiError. */
export function toError(status: number, json: unknown): ChatApiError {
const j = (json && typeof json === 'object' ? json : {}) as { error?: unknown; message?: unknown; errors?: unknown }
const msg = (typeof j.error === 'string' && j.error) || (typeof j.message === 'string' && j.message) || `HTTP ${status}`
return new ChatApiError(status, msg, errorsOf(j.errors))
}
/** The payload: `data` of a wrapped body, the body itself otherwise. */
function unwrap<T>(json: unknown): T {
if (json && typeof json === 'object' && !Array.isArray(json) && 'data' in json) return (json as { data: T }).data
return json as T
}
export function createChatClient(opts: ChatClientOptions) {
const { bases, auth } = opts
const doFetch: ChatFetch = opts.fetch ?? ((url, init) => fetch(url, init))
let refreshing: Promise<string | null> | null = null
function token(): string | null {
try {
return auth.token() || null
} catch {
return null
}
}
function headers(extra: Record<string, string> = {}): Record<string, string> {
const h: Record<string, string> = { Accept: 'application/json', ...extra }
const t = token()
if (t) h.Authorization = `Bearer ${t}`
return h
}
/** One refresh at a time; concurrent 401s share it. */
function refresh(): Promise<string | null> {
if (!refreshing) {
refreshing = (async () => {
try {
return (await auth.refresh?.()) || null
} catch {
return null
} finally {
// Cleared after the awaiting callers resumed.
queueMicrotask(() => {
refreshing = null
})
}
})()
}
return refreshing
}
/** send, then one refresh-and-retry on 401 for a request that carried a token. */
async function authorized(send: () => Promise<Response>): Promise<Response> {
const used = token()
let res: Response
try {
res = await send()
} catch {
throw new ChatApiError(0, 'network error')
}
if (res.status !== 401 || !used) return res
// Another request may have refreshed the token meanwhile: just retry.
const current = token()
const renewed = current && current !== used ? current : await refresh()
if (renewed) {
try {
res = await send()
} catch {
throw new ChatApiError(0, 'network error')
}
}
if (res.status === 401) auth.unauthorized?.()
return res
}
async function parse(res: Response): Promise<unknown> {
const text = await res.text()
if (!text) return null
try {
return JSON.parse(text)
} catch {
return null
}
}
/** The parsed payload of a JSON request against a full URL. */
async function request<T>(url: string, o: RequestOptions = {}): Promise<T> {
const res = await authorized(() => {
const init: Parameters<ChatFetch>[1] = { method: o.method ?? 'GET', headers: headers() }
if (o.body !== undefined) {
init.headers['Content-Type'] = 'application/json'
init.body = JSON.stringify(o.body)
}
return doFetch(withQuery(url, o.query), init)
})
const json = await parse(res)
if (!res.ok) throw toError(res.status, json)
return unwrap<T>(json)
}
const chat = (path: string) => joinUrl(bases.chat, path)
const channels = (context: { type: string; id: number }, path: string) =>
joinUrl(bases.channels, `/contexts/${encodeURIComponent(context.type)}/${context.id}${path}`)
const host = (path: string) => {
if (!bases.host) throw new ChatApiError(0, 'public.chat.hostApiBase is not set')
return joinUrl(bases.host, path)
}
return {
request,
/** GET {host}/chat: membership, channels, DMs and limits. */
bootstrap: () => request<ChatBootstrap>(host('/chat')),
/** GET {host}/chat/members: the other members (pickers and mentions). */
members: () => request<{ members: ChatMember[] } | ChatMember[]>(host('/chat/members')).then((r) => (Array.isArray(r) ? r : (r?.members ?? []))),
/** The conversation of a context; opening a channel's makes the caller a participant. */
openConversation: (type: string, id: number) =>
request<ChatConversation>(chat(`/contexts/${encodeURIComponent(type)}/${id}/conversation`)),
/** A page of messages (thread roots and plain messages), oldest first. */
messages: (conversationId: number, { limit = 50, before }: MessagePage = {}) =>
request<ChatMessage[]>(chat(`/conversations/${conversationId}/messages`), { query: { limit, before } }),
/** 201 with the message itself. */
send: (conversationId: number, body: ChatSendBody) =>
request<ChatMessage>(chat(`/conversations/${conversationId}/messages`), { method: 'POST', body }),
/** One message (content for a created event, which carries ids only). */
message: (id: number) => request<ChatMessage>(chat(`/messages/${id}`)),
/** Marks a conversation read up to now; golem15.chat tells the other participants. */
markRead: (conversationId: number) => request<unknown>(chat(`/conversations/${conversationId}/read`), { method: 'POST' }),
/** Emits typing.chat.message on the conversation channel. */
typing: (conversationId: number) => request<unknown>(chat(`/conversations/${conversationId}/typing`), { method: 'POST' }),
/** Finds or creates the DM with a member of the context (chat-dm bucket, 10/min). */
startDm: (context: { type: string; id: number }, userId: number) =>
request<ChatConversation>(chat(`/contexts/${encodeURIComponent(context.type)}/${context.id}/dm`), { method: 'POST', body: { user_id: userId } }),
/** Joins a public channel of the context (golem15.chatchannels). */
joinChannel: (context: { type: string; id: number }, channelId: number) =>
request<unknown>(channels(context, `/channels/${channelId}/join`), { method: 'POST' }),
/** Leaves a channel; it stays listed with joined false. */
leaveChannel: (context: { type: string; id: number }, channelId: number) =>
request<unknown>(channels(context, `/channels/${channelId}/leave`), { method: 'POST' }),
}
}
export type ChatClient = ReturnType<typeof createChatClient>