test: the SPA's chat tests on the port, client, store and link embeds

- vitest runs app/**/*.test.ts and tests/**/*.test.ts; the SPA's
  chatEvents, chatFormat, chatText, chatUnread and realtime tests sit next
  to their ports with only import paths changed
- linkEmbeds: escaping, http(s) only, rel and target, registry order
- client: every endpoint, refresh-and-retry, unauthorized, 422, upload
- store: bootstrap, anonymous and non-member starts, lazy joins, DMs,
  live messages and unread, threads, pins, reactions, slash commands,
  polling without realtime, onUserEvent, DM-only actions
This commit is contained in:
Jakub Zych
2026-11-01 19:17:42 +01:00
parent 764cb42894
commit b6d3389e46
11 changed files with 1670 additions and 5 deletions

140
app/lib/chatEvents.test.ts Normal file
View File

@@ -0,0 +1,140 @@
import { describe, expect, it } from 'vitest'
import type { ChatConversationRow, ChatMessage } from './types'
import { applyChatMessage, applyReaction, needsFetch, parsePublication } from './chatEvents'
function message(id: number, conversation = 11, sender = 2, created = '2026-10-26T10:00:00Z'): ChatMessage {
return {
id,
conversation_id: conversation,
sender_id: sender,
sender_name: '',
sender_avatar: null,
content: `m${id}`,
type: 'text',
attachments: [],
created_at: created,
created_at_human: '',
edited_at: null,
deleted_at: null,
is_mine: false,
root_id: null,
}
}
describe('parsePublication', () => {
it('rejects non-objects, unknown events and bad payloads', () => {
expect(parsePublication(null)).toBeNull()
expect(parsePublication('created.chat.message')).toBeNull()
expect(parsePublication([])).toBeNull()
expect(parsePublication({ event: 'deleted.chat.message', payload: { id: 1 } })).toBeNull()
expect(parsePublication({ event: 'reacted.chat.message', payload: { id: 1, conversation_id: 10, user_id: 2, key: '', action: 'added' } })).toBeNull()
expect(parsePublication({ event: 'reacted.chat.message', payload: { id: 1, conversation_id: 10, user_id: 2, key: 'x', action: 'toggled' } })).toBeNull()
expect(parsePublication({ event: 'created.chat.message', payload: { id: '7', conversation_id: 10, sender_id: 2 } })).toBeNull()
expect(parsePublication({ event: 'typing.chat.message', payload: { conversation_id: 10, user_id: 2, action: 'typing-stop' } })).toBeNull()
expect(parsePublication({ event: 'chat:message', payload: { conversation_id: 10, message: { id: 1 } } })).toBeNull()
expect(parsePublication({ event: 'chat:message', payload: { conversation_id: 12, message: message(1, 11) } })).toBeNull()
expect(parsePublication({ event: 'chat:unread', payload: { count: -1 } })).toBeNull()
})
it('reads the ids-only created event and never its content', () => {
const ev = parsePublication({
event: 'created.chat.message',
payload: { id: 7, conversation_id: 10, sender_id: 2, root_id: null, type: 'text', action: 'created', created_at: 'x', content: 'spoofed' },
timestamp: 1,
})
expect(ev).toEqual({ kind: 'created', id: 7, conversationId: 10, senderId: 2 })
})
it('reads chat:message, typing, read, unread and mentions', () => {
expect(parsePublication({ event: 'chat:message', payload: { conversation_id: 11, message: message(3) } })).toEqual({
kind: 'chatMessage',
conversationId: 11,
message: message(3),
})
expect(parsePublication({ event: 'typing.chat.message', payload: { conversation_id: 10, user_id: 2, action: 'typing-start' } })).toEqual({
kind: 'typing',
conversationId: 10,
userId: 2,
})
expect(parsePublication({ event: 'chat:read', payload: { conversation_id: 10, user_id: 2, read_at: 'x' } })).toEqual({ kind: 'read', conversationId: 10, userId: 2 })
expect(parsePublication({ event: 'chat:unread', payload: { count: 4 } })).toEqual({ kind: 'unread', count: 4 })
expect(parsePublication({ event: 'mentions.changed', payload: { action: 'mentions' } })).toEqual({ kind: 'mentions' })
})
})
describe('needsFetch', () => {
const created = { kind: 'created', id: 7, conversationId: 10, senderId: 2 } as const
it('asks once per id, only for a loaded conversation', () => {
expect(needsFetch(created, {})).toBe(false)
expect(needsFetch(created, { 10: [message(6, 10)] })).toBe(true)
expect(needsFetch(created, { 10: [message(6, 10), message(7, 10)] })).toBe(false)
expect(needsFetch({ kind: 'mentions' }, { 10: [] })).toBe(false)
})
})
describe('applyChatMessage', () => {
const rows: ChatConversationRow[] = [
{ id: 11, type: 'dm', other_user_id: 2, unread: 1, last_message: { id: 1, sender_id: 2, content: 'a', created_at: '2026-10-25T10:00:00Z' } },
{ id: 12, type: 'dm', other_user_id: 3, unread: 0, last_message: null },
]
it('bumps unread and the preview of a known DM', () => {
const next = applyChatMessage(rows, message(5, 11), { seen: false })
expect(next[0]).toMatchObject({ id: 11, unread: 2, last_message: { id: 5, content: 'm5' } })
expect(rows[0]?.unread).toBe(1)
// The same message twice changes nothing.
expect(applyChatMessage(next, message(5, 11), { seen: false })).toBe(next)
})
it('does not count a message the user is looking at', () => {
expect(applyChatMessage(rows, message(5, 12, 3), { seen: true })[1]).toMatchObject({ unread: 0, last_message: { id: 5 } })
})
it('adds a new DM row first', () => {
const next = applyChatMessage(rows, message(9, 20, 4), { seen: false })
expect(next).toHaveLength(3)
expect(next[0]).toMatchObject({ id: 20, type: 'dm', other_user_id: 4, unread: 1, last_message: { id: 9 } })
})
})
describe('message events (reacted, updated, deleted)', () => {
it('reads the reacted, updated and deleted payloads', () => {
expect(parsePublication({ event: 'reacted.chat.message', payload: { id: 1, conversation_id: 10, user_id: 2, key: '👍', action: 'added' } })).toEqual({
kind: 'reacted',
id: 1,
conversationId: 10,
userId: 2,
key: '👍',
added: true,
})
expect(parsePublication({ event: 'reacted.chat.message', payload: { id: 1, conversation_id: 10, user_id: 2, key: '👍', action: 'removed' } })).toMatchObject({ added: false })
expect(parsePublication({ event: 'updated.chat.message', payload: { id: 4, conversation_id: 10, action: 'updated', edited_at: '2026-01-15T12:05:00Z' } })).toEqual({
kind: 'updated',
id: 4,
conversationId: 10,
})
expect(parsePublication({ event: 'deleted.chat.message', payload: { id: 5, conversation_id: 10, action: 'deleted' } })).toEqual({ kind: 'deleted', id: 5, conversationId: 10 })
})
})
describe('applyReaction', () => {
it('adds and removes one user idempotently', () => {
const one = applyReaction(undefined, 'a', 1, true)
expect(one).toEqual([{ key: 'a', count: 1, user_ids: [1] }])
expect(applyReaction(one, 'a', 1, true)).toBe(one)
const two = applyReaction(one, 'a', 2, true)
expect(two).toEqual([{ key: 'a', count: 2, user_ids: [1, 2] }])
expect(applyReaction(two, 'a', 3, false)).toBe(two)
expect(applyReaction(two, 'a', 1, false)).toEqual([{ key: 'a', count: 1, user_ids: [2] }])
expect(applyReaction(one, 'a', 1, false)).toEqual([])
})
it('places a new key in the allowed order', () => {
const list = [
{ key: 'a', count: 1, user_ids: [1] },
{ key: 'c', count: 1, user_ids: [1] },
]
expect(applyReaction(list, 'b', 2, true, ['a', 'b', 'c']).map((r) => r.key)).toEqual(['a', 'b', 'c'])
expect(applyReaction(list, 'z', 2, true, ['a', 'b', 'c']).map((r) => r.key)).toEqual(['a', 'c', 'z'])
})
})

131
app/lib/chatFormat.test.ts Normal file
View File

@@ -0,0 +1,131 @@
import { describe, expect, it } from 'vitest'
import type { ChatMessage } from './types'
import { avatarIndex, dayLabel, filterMembers, fullName, groupMessages, initials, reactorsTitle, shortName } from './chatFormat'
const ola = { id: 3, name: 'Ola', surname: 'Kowalska', handle: 'ola', is_bot: false }
function msg(id: number, sender: number, at: string): ChatMessage {
return {
id,
conversation_id: 1,
sender_id: sender,
sender_name: '',
sender_avatar: null,
content: `m${id}`,
type: 'text',
attachments: [],
created_at: at,
created_at_human: '',
edited_at: null,
deleted_at: null,
is_mine: false,
root_id: null,
}
}
describe('shortName', () => {
it('is the name and the initial of the surname', () => {
expect(shortName(ola)).toBe('Ola K.')
})
it('falls back to @handle, then to the e-mail local part', () => {
expect(shortName({ name: '', surname: '', handle: 'olak' })).toBe('@olak')
expect(shortName(undefined, 'ola.k@uwr.edu.pl')).toBe('ola.k')
})
it('is the name only for a bot', () => {
expect(shortName({ name: 'Asystent', surname: 'Bot', handle: 'bot', is_bot: true })).toBe('Asystent')
})
it('gives the full name for picker rows', () => {
expect(fullName(ola)).toBe('Ola Kowalska')
})
})
describe('initials', () => {
it('takes name and surname', () => {
expect(initials(ola)).toBe('OK')
})
it('falls back to the first two letters of the handle', () => {
expect(initials({ name: '', surname: '', handle: 'łukasz' })).toBe('ŁU')
})
})
describe('avatarIndex', () => {
it('maps user ids onto the 8 palette slots', () => {
expect(avatarIndex(9)).toBe(2)
expect(avatarIndex(8)).toBe(1)
expect(avatarIndex(7)).toBe(8)
})
})
describe('dayLabel', () => {
const now = new Date('2026-10-26T12:00:00+01:00')
it('says DZIŚ and WCZORAJ', () => {
expect(dayLabel('2026-10-26T08:00:00+01:00', now)).toBe('DZIŚ')
expect(dayLabel('2026-10-25T23:30:00+01:00', now)).toBe('WCZORAJ')
})
it('uppercases older days and adds a different year', () => {
expect(dayLabel('2026-10-20T10:00:00+02:00', now)).toBe('WTOREK, 20 PAŹDZIERNIKA')
expect(dayLabel('2025-12-31T10:00:00+01:00', now)).toBe('ŚRODA, 31 GRUDNIA 2025')
})
})
describe('groupMessages', () => {
const now = new Date('2026-10-26T12:00:00+01:00')
it('collapses one author within 5 minutes and starts a new group after that', () => {
const items = groupMessages(
[
msg(1, 3, '2026-10-26T10:00:00+01:00'),
msg(2, 3, '2026-10-26T10:04:00+01:00'),
msg(3, 3, '2026-10-26T10:10:00+01:00'),
msg(4, 5, '2026-10-26T10:11:00+01:00'),
],
now,
)
expect(items.map((i) => (i.kind === 'day' ? i.label : `${i.message.id}${i.followUp ? '+' : ''}`))).toEqual([
'DZIŚ',
'1',
'2+',
'3',
'4',
])
})
it('never collapses across a day separator', () => {
const items = groupMessages([msg(1, 3, '2026-10-25T23:58:00+01:00'), msg(2, 3, '2026-10-26T00:01:00+01:00')], now)
expect(items.map((i) => (i.kind === 'day' ? i.label : `${i.message.id}${i.followUp ? '+' : ''}`))).toEqual([
'WCZORAJ',
'1',
'DZIŚ',
'2',
])
})
})
describe('filterMembers', () => {
const people = [
{ id: 1, name: 'Jakub', surname: 'Zych', handle: 'jakub', is_bot: false },
{ id: 2, name: 'Łukasz', surname: 'Nowak', handle: 'lukasz', is_bot: false },
{ id: 3, name: 'Ola', surname: 'Łuczak', handle: 'ola', is_bot: false },
{ id: 4, name: 'Michał', surname: 'Wiśniewski', handle: 'michal', is_bot: false },
]
it('folds case and diacritics (ł = l) and matches a name or surname prefix', () => {
expect(filterMembers(people, 'łu', 1).map((m) => m.id)).toEqual([2, 3])
expect(filterMembers(people, 'LU', 1).map((m) => m.id)).toEqual([2, 3])
expect(filterMembers(people, 'wisn', 1).map((m) => m.id)).toEqual([4])
expect(filterMembers(people, 'ichał', 1)).toEqual([])
})
it('excludes yourself and lists everyone else for an empty query, by name', () => {
expect(filterMembers(people, '', 1).map((m) => m.id)).toEqual([2, 4, 3])
expect(filterMembers(people, 'jak', 1)).toEqual([])
})
})
describe('reactorsTitle', () => {
const m = (id: number, name: string, surname: string) => ({ id, name, surname, handle: `${name}_${id}`, is_bot: false })
it('lists short names, at most ten, then the rest as a count', () => {
const members = new Map([1, 2, 3].map((id) => [id, m(id, 'Ola', 'Kowalska')]))
expect(reactorsTitle([1, 2], members)).toBe('Ola K., Ola K.')
const many = Array.from({ length: 13 }, (_, i) => i + 1)
const title = reactorsTitle(many, members)
expect(title.endsWith(' i 3 innych')).toBe(true)
expect(title.split(', ')).toHaveLength(10)
})
})

110
app/lib/chatText.test.ts Normal file
View File

@@ -0,0 +1,110 @@
import { describe, expect, it } from 'vitest'
import type { ChatMember } from './types'
import { insertMention, mentionQuery, mentionsHandle, renderChatText } from './chatText'
const ola: ChatMember = { id: 2, name: 'Ola', surname: 'Kowalska', handle: 'ola_k', is_bot: false }
const bot: ChatMember = { id: 9, name: 'Asystent', surname: 'Roku', handle: 'asystent', is_bot: true }
const members = new Map([ola, bot].map((m) => [m.handle, m]))
describe('renderChatText (D-13)', () => {
it('escapes everything it does not produce itself', () => {
const html = renderChatText('<script>x</script> <img src=x onerror=alert(1)> & "q"')
expect(html).not.toContain('<script')
expect(html).not.toContain('<img')
expect(html).toContain('&lt;script&gt;x&lt;/script&gt;')
expect(html).toContain('&amp; &quot;q&quot;')
})
it('renders bold, italic and code spans', () => {
expect(renderChatText('**a** _b_ `c`')).toBe('<strong>a</strong> <em>b</em> <code>c</code>')
expect(renderChatText('`<b>**x**</b>`')).toBe('<code>&lt;b&gt;**x**&lt;/b&gt;</code>')
})
it('autolinks bare http(s) URLs for a new tab, leaving trailing punctuation outside', () => {
expect(renderChatText('see https://example.org/x?y=1')).toBe(
'see <a href="https://example.org/x?y=1" target="_blank" rel="noopener noreferrer nofollow">https://example.org/x?y=1</a>',
)
expect(renderChatText('(https://example.org/a).')).toBe(
'(<a href="https://example.org/a" target="_blank" rel="noopener noreferrer nofollow">https://example.org/a</a>).',
)
expect(renderChatText('https://pl.wikipedia.org/wiki/Foo_(bar)')).toContain('href="https://pl.wikipedia.org/wiki/Foo_(bar)"')
})
it('renders [label](url) through safeUrl and a javascript: link as text', () => {
expect(renderChatText('[plan](/plan)')).toBe('<a href="/plan">plan</a>')
expect(renderChatText('[x](https://example.org)')).toBe(
'<a href="https://example.org" target="_blank" rel="noopener noreferrer nofollow">x</a>',
)
const bad = renderChatText('[x](javascript:alert(1))')
expect(bad).not.toContain('<a')
expect(bad).not.toContain('href')
expect(bad.startsWith('x')).toBe(true)
})
it('never produces headings, lists, quotes or images', () => {
const html = renderChatText('# h\n- a\n> q\n![i](https://example.org/i.png)')
for (const tag of ['<h', '<ul', '<li', '<blockquote', '<img', '<p']) expect(html).not.toContain(tag)
})
it('turns line breaks into br', () => {
expect(renderChatText('a\nb')).toBe('a<br>b')
expect(renderChatText('a\r\nb')).toBe('a<br>b')
})
it('renders a known @handle as a mention span and leaves unknown ones as text (D-12)', () => {
expect(renderChatText('@ola_k hi', members)).toBe('<span class="mention" title="@ola_k">@Ola K.</span> hi')
expect(renderChatText('@nobody hi', members)).toBe('@nobody hi')
expect(renderChatText('dzięki @ola_k.', members)).toBe('dzięki <span class="mention" title="@ola_k">@Ola K.</span>.')
expect(renderChatText('mail@ola_k', members)).toBe('mail@ola_k')
expect(renderChatText('@asystent', members)).toContain('>@Asystent</span>')
expect(renderChatText('`@ola_k`', members)).toBe('<code>@ola_k</code>')
})
it('handles empty input', () => {
expect(renderChatText('')).toBe('')
expect(renderChatText(null)).toBe('')
})
})
describe('nested code spans (WR-07)', () => {
it('renders a code span inside a link label', () => {
const html = renderChatText('[`kod`](https://x.pl)')
expect(html).toBe('<a href="https://x.pl" target="_blank" rel="noopener noreferrer nofollow"><code>kod</code></a>')
expect(html).not.toContain('\u0000')
})
it('does not link a URL that holds a code span', () => {
const bare = renderChatText('https://x.pl/`a`')
expect(bare).toBe('https://x.pl/<code>a</code>')
const link = renderChatText('[tu](https://x.pl/`a`)')
expect(link).not.toContain('<a ')
expect(link).toContain('<code>a</code>')
expect(link).not.toContain('\u0000')
})
})
describe('mention helpers', () => {
it('mentionsHandle finds a handle as its own token', () => {
expect(mentionsHandle('hi @ola_k', 'ola_k')).toBe(true)
expect(mentionsHandle('hi @ola_k.', 'ola_k')).toBe(true)
expect(mentionsHandle('hi @ola_kx', 'ola_k')).toBe(false)
expect(mentionsHandle('mail@ola_k', 'ola_k')).toBe(false)
expect(mentionsHandle('`@ola_k`', 'ola_k')).toBe(false)
expect(mentionsHandle(null, 'ola_k')).toBe(false)
expect(mentionsHandle('hi @ola_k', '')).toBe(false)
})
it('mentionQuery reads an @ at a word start before the caret', () => {
expect(mentionQuery('hej @ol', 7)).toEqual({ start: 4, query: 'ol' })
expect(mentionQuery('@', 1)).toEqual({ start: 0, query: '' })
expect(mentionQuery('hej\n@Łu', 7)).toEqual({ start: 4, query: 'Łu' })
expect(mentionQuery('mail@x', 6)).toBeNull()
expect(mentionQuery('hej @ol x', 9)).toBeNull()
expect(mentionQuery('hej @ol', 3)).toBeNull()
})
it('insertMention puts @handle and a space in place of the query', () => {
expect(insertMention('hej @ol', { start: 4, end: 7 }, 'ola_k')).toEqual({ text: 'hej @ola_k ', caret: 11 })
expect(insertMention('@ol jak tam', { start: 0, end: 3 }, 'ola_k')).toEqual({ text: '@ola_k jak tam', caret: 7 })
})
})

View File

@@ -0,0 +1,81 @@
import { describe, expect, it } from 'vitest'
import type { ChatMessage } from './types'
import { badgeText, dividerMessageId, mentionLabel, shouldMarkRead, typingText, unreadLabel } from './chatUnread'
function message(id: number, sender: number): ChatMessage {
return {
id,
conversation_id: 10,
sender_id: sender,
sender_name: '',
sender_avatar: null,
content: `m${id}`,
type: 'text',
attachments: [],
created_at: '2026-10-26T10:00:00Z',
created_at_human: '',
edited_at: null,
deleted_at: null,
is_mine: sender === 1,
root_id: null,
}
}
describe('shouldMarkRead (D-18)', () => {
const all = { active: true, visible: true, focused: true, atBottom: true }
it('needs the conversation active and visible, the window focused and the list at the bottom', () => {
expect(shouldMarkRead(all)).toBe(true)
expect(shouldMarkRead({ ...all, active: false })).toBe(false)
expect(shouldMarkRead({ ...all, visible: false })).toBe(false)
expect(shouldMarkRead({ ...all, focused: false })).toBe(false)
expect(shouldMarkRead({ ...all, atBottom: false })).toBe(false)
})
})
describe('badgeText', () => {
it('hides 0, shows the number, caps at 99+', () => {
expect(badgeText(0)).toBe('')
expect(badgeText(-1)).toBe('')
expect(badgeText(5)).toBe('5')
expect(badgeText(99)).toBe('99')
expect(badgeText(120)).toBe('99+')
})
})
describe('sr-only plurals', () => {
it('reads unread counts in the three Polish forms', () => {
expect(unreadLabel(1)).toBe('1 nieprzeczytana wiadomość')
expect(unreadLabel(3)).toBe('3 nieprzeczytane wiadomości')
expect(unreadLabel(5)).toBe('5 nieprzeczytanych wiadomości')
expect(unreadLabel(22)).toBe('22 nieprzeczytane wiadomości')
})
it('reads mention counts in the three Polish forms', () => {
expect(mentionLabel(1)).toBe('wzmianka o Tobie')
expect(mentionLabel(3)).toBe('3 wzmianki o Tobie')
expect(mentionLabel(5)).toBe('5 wzmianek o Tobie')
})
})
describe('dividerMessageId', () => {
const list = [message(1, 2), message(2, 1), message(3, 2), message(4, 1), message(5, 3)]
it('marks the first of the last N messages from others', () => {
expect(dividerMessageId(list, 2, 1)).toBe(3)
expect(dividerMessageId(list, 1, 1)).toBe(5)
})
it('has no divider without unread messages, and stops at the oldest loaded one', () => {
expect(dividerMessageId(list, 0, 1)).toBeNull()
expect(dividerMessageId([], 3, 1)).toBeNull()
expect(dividerMessageId(list, 9, 1)).toBe(1)
expect(dividerMessageId([message(1, 1)], 2, 1)).toBeNull()
})
})
describe('typingText (D-15)', () => {
it('reads zero, one, two and many', () => {
expect(typingText([])).toBe('')
expect(typingText(['Ola K.'])).toBe('Ola K. pisze…')
expect(typingText(['Ola K.', 'Jan N.'])).toBe('Ola K. i Jan N. piszą…')
expect(typingText(['Ola K.', 'Jan N.', 'Ewa M.'])).toBe('Kilka osób pisze…')
})
})

105
app/lib/linkEmbeds.test.ts Normal file
View File

@@ -0,0 +1,105 @@
import { afterEach, describe, expect, it } from 'vitest'
import { embedRendererFor, linkify, messageUrls, registerEmbedRenderer } from './linkEmbeds'
import { escapeHtml } from './markdown'
const EXTERNAL = 'target="_blank" rel="noopener noreferrer nofollow"'
describe('linkify', () => {
it('links a bare https URL with target and rel set', () => {
expect(linkify('see https://summercms.io/docs now')).toBe(
`see <a href="https://summercms.io/docs" ${EXTERNAL}>https://summercms.io/docs</a> now`,
)
})
it('links http as well, and only http(s)', () => {
expect(linkify('http://a.example')).toContain('<a href="http://a.example"')
for (const s of ['javascript:alert(1)', 'ftp://a.example/x', 'mailto:a@b.example', 'data:text/html,hi', '//a.example/x']) {
expect(linkify(escapeHtml(s))).toBe(escapeHtml(s))
}
})
it('keeps trailing punctuation outside the link', () => {
expect(linkify('go to https://a.example/x.')).toBe(`go to <a href="https://a.example/x" ${EXTERNAL}>https://a.example/x</a>.`)
expect(linkify('(https://a.example/x)')).toBe(`(<a href="https://a.example/x" ${EXTERNAL}>https://a.example/x</a>)`)
expect(linkify('https://en.wikipedia.org/wiki/Go_(game)')).toContain('href="https://en.wikipedia.org/wiki/Go_(game)"')
expect(linkify('https://a.example/?q=1, then')).toContain('href="https://a.example/?q=1"')
})
it('works on escaped text and adds no markup of the input', () => {
const input = '<script>alert(1)</script> https://a.example/?a=1&b=<x>'
const out = linkify(escapeHtml(input))
expect(out).not.toContain('<script')
expect(out).toContain('&lt;script&gt;')
// The URL's & and <> stay escaped once in the href and the text.
expect(out).toContain('href="https://a.example/?a=1&amp;b=&lt;x&gt;"')
expect(out).not.toMatch(/<(?!a |\/a>)/)
})
it('cannot break out of the href attribute', () => {
const out = linkify(escapeHtml('https://a.example/"onmouseover="alert(1)'))
expect(out).not.toContain('" onmouseover')
expect(out).not.toMatch(/href="[^"]*"[^>]*onmouseover/)
})
it('leaves text without URLs alone', () => {
expect(linkify('no links here')).toBe('no links here')
expect(linkify('')).toBe('')
})
})
describe('messageUrls', () => {
it('lists distinct http(s) URLs in order', () => {
const urls = messageUrls('a https://x.example/1 b http://y.example c https://x.example/1 d https://z.example/2.')
expect(urls.map((u) => u.href)).toEqual(['https://x.example/1', 'http://y.example/', 'https://z.example/2'])
})
it('skips code spans, other schemes and empty text', () => {
expect(messageUrls('`https://code.example` and ftp://f.example and https://ok.example').map((u) => u.host)).toEqual(['ok.example'])
expect(messageUrls('')).toEqual([])
expect(messageUrls(null)).toEqual([])
expect(messageUrls(undefined)).toEqual([])
})
it('counts the URL of a [label](url) link and ignores a URL glued to a word', () => {
expect(messageUrls('[docs](https://docs.example/a)').map((u) => u.href)).toEqual(['https://docs.example/a'])
expect(messageUrls('xhttps://a.example user@https://b.example')).toEqual([])
})
it('gives the cards limits.max_embeds takes the first of', () => {
const urls = messageUrls('https://1.example https://2.example https://3.example https://4.example')
expect(urls.slice(0, 3).map((u) => u.host)).toEqual(['1.example', '2.example', '3.example'])
})
})
describe('registerEmbedRenderer', () => {
const cleanups: Array<() => void> = []
afterEach(() => {
while (cleanups.length) cleanups.pop()?.()
})
it('returns null without a matching renderer (the generic card)', () => {
expect(embedRendererFor(new URL('https://a.example/'))).toBeNull()
})
it('picks the first registered renderer that matches', () => {
const blog = { name: 'BlogCard' }
const any = { name: 'AnyCard' }
cleanups.push(registerEmbedRenderer((u) => u.pathname.startsWith('/blog/'), blog))
cleanups.push(registerEmbedRenderer(() => true, any))
expect(embedRendererFor(new URL('https://a.example/blog/post'))).toBe(blog)
expect(embedRendererFor(new URL('https://a.example/other'))).toBe(any)
})
it('removes a registration with the returned function, and a throwing matcher matches nothing', () => {
const card = { name: 'Card' }
const off = registerEmbedRenderer(() => {
throw new Error('broken matcher')
}, { name: 'Broken' })
cleanups.push(off)
const remove = registerEmbedRenderer((u) => u.host === 'a.example', card)
expect(embedRendererFor(new URL('https://a.example/'))).toBe(card)
remove()
remove()
expect(embedRendererFor(new URL('https://a.example/'))).toBeNull()
})
})

287
app/lib/realtime.test.ts Normal file
View File

@@ -0,0 +1,287 @@
// bm's src/lib/realtime.test.ts against the layer's port (./realtime), as
// the demo site runs it through its re-export. The client fetches its
// connection token from /api/realtime/token itself, so the token route is a stubbed fetch that
// answers what hoisted.request resolves (200) or the status of the ApiError
// it rejects with, instead of a mocked API client; a refusal surfaces as the
// layer's RealtimeTokenError with that status.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ApiError } from '@/api/http'
type Listener = (ctx: unknown) => void
interface FakeSub {
channel: string
state: string
subscribeCalls: number
unsubscribed: boolean
presence: ReturnType<typeof vi.fn>
emit(event: string, ctx?: unknown): void
}
interface FakeClient {
connectCalls: number
disconnectCalls: number
subs: Map<string, FakeSub>
newSubscriptionCalls: number
emit(event: string, ctx?: unknown): void
}
const hoisted = vi.hoisted(() => {
class FakeUnauthorizedError extends Error {}
return {
request: vi.fn(),
getToken: null as null | (() => Promise<string>),
FakeUnauthorizedError,
created: [] as unknown[],
presenceFn: () => vi.fn(async () => ({ clients: {} as Record<string, unknown> })),
}
})
async function tokenRoute(path: string): Promise<Response> {
try {
const body = await hoisted.request(path)
return new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' } })
} catch (e) {
return new Response(JSON.stringify({ error: String((e as Error).message) }), { status: e instanceof ApiError ? e.status : 500 })
}
}
vi.mock('centrifuge', () => {
class Emitter {
listeners = new Map<string, Listener[]>()
on(event: string, fn: Listener) {
this.listeners.set(event, [...(this.listeners.get(event) ?? []), fn])
return this
}
emit(event: string, ctx: unknown = {}) {
for (const fn of this.listeners.get(event) ?? []) fn(ctx)
}
removeAllListeners() {
this.listeners.clear()
}
}
class Subscription extends Emitter {
state = 'unsubscribed'
subscribeCalls = 0
unsubscribed = false
presence = hoisted.presenceFn()
constructor(public channel: string) {
super()
}
subscribe() {
this.subscribeCalls++
}
unsubscribe() {
this.unsubscribed = true
}
}
class Centrifuge extends Emitter {
subs = new Map<string, Subscription>()
connectCalls = 0
disconnectCalls = 0
newSubscriptionCalls = 0
constructor(_url: string, opts: { getToken: () => Promise<string> }) {
super()
hoisted.getToken = opts.getToken
hoisted.created.push(this)
}
newSubscription(channel: string) {
this.newSubscriptionCalls++
const s = new Subscription(channel)
this.subs.set(channel, s)
return s
}
getSubscription(channel: string) {
return this.subs.get(channel) ?? null
}
removeSubscription(s: Subscription | null) {
if (s) this.subs.delete(s.channel)
}
connect() {
this.connectCalls++
this.emit('state', { newState: 'connecting' })
}
disconnect() {
this.disconnectCalls++
this.emit('state', { newState: 'disconnected' })
}
}
return { Centrifuge, UnauthorizedError: hoisted.FakeUnauthorizedError }
})
import * as rt from './realtime'
function clients(): FakeClient[] {
return hoisted.created as FakeClient[]
}
function lastClient(): FakeClient {
const c = clients().at(-1)
if (!c) throw new Error('no client was created')
return c
}
function sub(channel: string): FakeSub {
const s = lastClient().subs.get(channel)
if (!s) throw new Error(`no subscription for ${channel}`)
return s
}
beforeEach(() => {
vi.stubGlobal('window', { location: { protocol: 'https:', host: 'bm.example' } })
vi.stubGlobal('fetch', (path: string) => tokenRoute(path))
hoisted.request.mockReset()
hoisted.getToken = null
hoisted.created.length = 0
})
afterEach(() => {
rt.disconnect()
vi.unstubAllGlobals()
})
describe('tokenFailureIsFinal', () => {
it('stops only on 401, 403 and 404', () => {
expect(rt.tokenFailureIsFinal(401)).toBe(true)
expect(rt.tokenFailureIsFinal(403)).toBe(true)
expect(rt.tokenFailureIsFinal(404)).toBe(true)
expect(rt.tokenFailureIsFinal(503)).toBe(false)
expect(rt.tokenFailureIsFinal(500)).toBe(false)
expect(rt.tokenFailureIsFinal(429)).toBe(false)
})
})
describe('openChannel getToken', () => {
async function tokenFn(onUnavailable: () => void) {
await rt.openChannel('presentations:remote:1.abc', { onPublication() {}, onUnavailable })
if (!hoisted.getToken) throw new Error('getToken was not passed to the client')
return hoisted.getToken
}
it('retries a 503 instead of giving up', async () => {
const onUnavailable = vi.fn()
const getToken = await tokenFn(onUnavailable)
hoisted.request.mockRejectedValueOnce(new ApiError(503, 'Service unavailable'))
const err = await getToken().catch((e: unknown) => e)
expect(err).toMatchObject({ status: 503 })
expect(err).not.toBeInstanceOf(hoisted.FakeUnauthorizedError)
expect(onUnavailable).not.toHaveBeenCalled()
hoisted.request.mockResolvedValueOnce({ token: 'tok' })
await expect(getToken()).resolves.toBe('tok')
})
it('gives up for good on a 403', async () => {
const onUnavailable = vi.fn()
const getToken = await tokenFn(onUnavailable)
hoisted.request.mockRejectedValueOnce(new ApiError(403, 'Forbidden'))
await expect(getToken()).rejects.toBeInstanceOf(hoisted.FakeUnauthorizedError)
expect(onUnavailable).toHaveBeenCalledOnce()
})
it('tells a listener added after the refusal at once', async () => {
const getToken = await tokenFn(() => {})
hoisted.request.mockRejectedValueOnce(new ApiError(404, 'Not found'))
await getToken().catch(() => {})
const late = vi.fn()
rt.onUnavailable(late)
await Promise.resolve()
expect(late).toHaveBeenCalledOnce()
})
})
describe('the shared client', () => {
it('uses one client for two channels and disconnects with the last handle', async () => {
const a = await rt.subscribe('user:1', {})
const b = await rt.subscribe('chat:conversation:10', {})
expect(clients()).toHaveLength(1)
expect(lastClient().subs.size).toBe(2)
a.close()
expect(lastClient().disconnectCalls).toBe(0)
expect(lastClient().subs.has('user:1')).toBe(false)
b.close()
expect(lastClient().disconnectCalls).toBe(1)
// The next subscribe reconnects the same client.
await rt.subscribe('user:1', {})
expect(clients()).toHaveLength(1)
expect(lastClient().connectCalls).toBe(2)
})
it('shares one Subscription per channel and fans events out to every handle', async () => {
const first = { onPublication: vi.fn(), onSubscribed: vi.fn(), onDenied: vi.fn() }
const second = { onPublication: vi.fn() }
const h1 = await rt.subscribe('chat:conversation:10', first)
const h2 = await rt.subscribe('chat:conversation:10', second)
expect(lastClient().newSubscriptionCalls).toBe(1)
const s = sub('chat:conversation:10')
expect(s.subscribeCalls).toBe(1)
s.emit('publication', { data: { event: 'x' } })
expect(first.onPublication).toHaveBeenCalledWith({ event: 'x' })
expect(second.onPublication).toHaveBeenCalledWith({ event: 'x' })
s.emit('subscribed')
expect(first.onSubscribed).toHaveBeenCalledOnce()
s.emit('unsubscribed', { code: 403 })
s.emit('unsubscribed', { code: 0 })
expect(first.onDenied).toHaveBeenCalledExactlyOnceWith(403)
h1.close()
s.emit('publication', { data: 2 })
expect(first.onPublication).toHaveBeenCalledTimes(1)
expect(second.onPublication).toHaveBeenCalledTimes(2)
expect(s.unsubscribed).toBe(false)
h2.close()
expect(s.unsubscribed).toBe(true)
})
it('hands a later handle its own subscribed on a live channel', async () => {
await rt.subscribe('chat:conversation:10', {})
sub('chat:conversation:10').state = 'subscribed'
const onSubscribed = vi.fn()
await rt.subscribe('chat:conversation:10', { onSubscribed })
await Promise.resolve()
expect(onSubscribed).toHaveBeenCalledOnce()
})
it('reports presence, joins and leaves with numeric user ids', async () => {
const onJoin = vi.fn()
const onLeave = vi.fn()
await rt.subscribe('chat:conversation:10', { onJoin, onLeave })
const s = sub('chat:conversation:10')
s.presence.mockResolvedValueOnce({ clients: { c1: { client: 'c1', user: '1' }, c2: { client: 'c2', user: '7' }, x: { client: 'x', user: '' } } })
await expect(rt.presence('chat:conversation:10')).resolves.toEqual([
{ client: 'c1', user: 1 },
{ client: 'c2', user: 7 },
])
s.emit('join', { info: { client: 'c3', user: '8' } })
s.emit('leave', { info: { client: 'c2', user: '7' } })
expect(onJoin).toHaveBeenCalledWith({ client: 'c3', user: 8 })
expect(onLeave).toHaveBeenCalledWith({ client: 'c2', user: 7 })
s.presence.mockRejectedValueOnce(new Error('not available'))
await expect(rt.presence('chat:conversation:10')).resolves.toBeNull()
await expect(rt.presence('chat:conversation:99')).resolves.toBeNull()
})
it('openChannel keeps close and resubscribe and rides the chat socket', async () => {
const chat = await rt.subscribe('user:1', {})
lastClient().emit('state', { newState: 'connected' })
const onConnection = vi.fn()
const remote = await rt.openChannel('presentations:remote:1.abc', { onPublication() {}, onConnection })
expect(clients()).toHaveLength(1)
expect(onConnection).toHaveBeenCalledWith('connected')
remote.resubscribe()
expect(sub('presentations:remote:1.abc').subscribeCalls).toBe(2)
remote.close()
expect(lastClient().disconnectCalls).toBe(0)
lastClient().emit('state', { newState: 'connecting' })
expect(onConnection).toHaveBeenCalledTimes(1)
chat.close()
expect(lastClient().disconnectCalls).toBe(1)
})
it('disconnect forgets the client so the next session gets a new one', async () => {
const h = await rt.subscribe('user:1', {})
rt.disconnect()
expect(clients()[0]?.disconnectCalls).toBe(1)
h.close()
await rt.subscribe('user:2', {})
expect(clients()).toHaveLength(2)
})
})