import { describe, expect, it, vi } from 'vitest' import { ChatApiError, createChatClient, type ChatFetch } from '../app/lib/client' const bases = { chat: '/_chat/api/v1', channels: '/_chatchannels/api/v1', bots: '/_chatbots/api/v1', host: '/_acme/api/v1' } function json(status: number, body: unknown): Response { return new Response(body === undefined ? '' : JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }) } describe('createChatClient', () => { it('builds the messages URL and sends the bearer token', async () => { const fetch = vi.fn(async () => json(200, { data: [] })) const client = createChatClient({ bases, auth: { token: () => 'tok' }, fetch }) await client.messages(7) const [url, init] = fetch.mock.calls[0] expect(url).toBe('/_chat/api/v1/conversations/7/messages?limit=50') expect(init.headers.Authorization).toBe('Bearer tok') }) it('reads the bootstrap and the members from the host base', async () => { const fetch = vi.fn(async (url) => url.endsWith('/members') ? json(200, { members: [{ id: 2, name: 'Ada', surname: 'H', handle: 'ada', is_bot: false }] }) : json(200, { member: false }), ) const client = createChatClient({ bases, auth: { token: () => 'tok' }, fetch }) await expect(client.bootstrap()).resolves.toEqual({ member: false }) await expect(client.members()).resolves.toHaveLength(1) expect(fetch.mock.calls.map((c) => c[0])).toEqual(['/_acme/api/v1/chat', '/_acme/api/v1/chat/members']) }) it('retries once after a refresh on 401', async () => { let current = 'old' const refresh = vi.fn(async () => (current = 'new')) const unauthorized = vi.fn() const fetch = vi .fn() .mockResolvedValueOnce(json(401, { error: 'Token expired' })) .mockResolvedValueOnce(json(201, { id: 9, conversation_id: 7 })) const client = createChatClient({ bases, auth: { token: () => current, refresh, unauthorized }, fetch }) const m = await client.send(7, { content: 'hi' }) expect(m.id).toBe(9) expect(refresh).toHaveBeenCalledOnce() expect(fetch).toHaveBeenCalledTimes(2) expect(fetch.mock.calls[1][1].headers.Authorization).toBe('Bearer new') expect(JSON.parse(String(fetch.mock.calls[1][1].body))).toEqual({ content: 'hi' }) expect(unauthorized).not.toHaveBeenCalled() }) it('calls unauthorized when the refresh does not help', async () => { const unauthorized = vi.fn() const fetch = vi.fn(async () => json(401, { error: 'Unauthorized' })) const client = createChatClient({ bases, auth: { token: () => 'tok', refresh: async () => null, unauthorized }, fetch }) await expect(client.messages(7)).rejects.toMatchObject({ status: 401 }) expect(fetch).toHaveBeenCalledOnce() expect(unauthorized).toHaveBeenCalledOnce() }) it('maps a 422 body to field errors', async () => { const fetch = vi.fn(async () => json(422, { error: 'Validation failed', errors: { content: ['Banned word'] } })) const client = createChatClient({ bases, auth: { token: () => 'tok' }, fetch }) const err = await client.send(7, { content: 'x' }).catch((e: unknown) => e) expect(err).toBeInstanceOf(ChatApiError) expect((err as ChatApiError).status).toBe(422) expect((err as ChatApiError).field('content')).toBe('Banned word') expect((err as ChatApiError).message).toBe('Validation failed') }) it('answers status 0 without a connection', async () => { const fetch = vi.fn(async () => { throw new TypeError('fetch failed') }) const client = createChatClient({ bases, auth: { token: () => null }, fetch }) await expect(client.messages(7)).rejects.toMatchObject({ status: 0 }) }) })