- route /lists/:id/sent and a Sent tab on the list page - a table of posts (subject, date, sent of recipients with a progress bar, recipients, pending, failed, dropped) and an empty state; a post with no recipients shows no bar - refreshes every 5 seconds while any post has pending deliveries, and stops when none has - api.posts.list, the Post type and the fake API route; tests
204 lines
8.5 KiB
TypeScript
204 lines
8.5 KiB
TypeScript
// An in-memory stand-in for the Parsimony API, used by component tests.
|
|
import { vi } from 'vitest'
|
|
import type { Held, List, Member, Message, Post, QueueItem } from '@/lib/api'
|
|
|
|
export interface FakeState {
|
|
token: string
|
|
lists: List[]
|
|
members: Record<number, Member[]>
|
|
held: Record<number, Held[]>
|
|
archive: Record<number, Message[]>
|
|
queue: QueueItem[]
|
|
posts: Record<number, Post[]>
|
|
/** Like the server, the queue listing is capped. */
|
|
queueLimit: number
|
|
/** Content types seen on archive imports. */
|
|
importTypes: string[]
|
|
/** When set, archive imports wait for it (to look at the busy state). */
|
|
hold?: Promise<void>
|
|
nextId: number
|
|
/** Every request seen, as "METHOD /path". */
|
|
calls: string[]
|
|
/** Force the next matching request ("METHOD /path") to fail with this status. */
|
|
fail: Record<string, { status: number; error: string }>
|
|
}
|
|
|
|
export function newState(overrides: Partial<FakeState> = {}): FakeState {
|
|
return { token: 'good', lists: [], members: {}, held: {}, archive: {}, queue: [], posts: {}, queueLimit: 100, importTypes: [], nextId: 100, calls: [], fail: {}, ...overrides }
|
|
}
|
|
|
|
export function aList(over: Partial<List> = {}): List {
|
|
const name = over.name ?? 'dev'
|
|
const domain = over.domain ?? 'example.org'
|
|
return {
|
|
id: 1,
|
|
name,
|
|
domain,
|
|
title: 'Dev list',
|
|
address: `${name}@${domain}`,
|
|
post_policy: 'members',
|
|
join_policy: 'open',
|
|
archive_policy: 'private',
|
|
...over,
|
|
}
|
|
}
|
|
|
|
function json(status: number, body?: unknown) {
|
|
return new Response(body === undefined ? null : JSON.stringify(body), {
|
|
status,
|
|
headers: body === undefined ? {} : { 'Content-Type': 'application/json' },
|
|
})
|
|
}
|
|
|
|
const err = (status: number, error: string) => json(status, { error })
|
|
|
|
export function installFakeApi(state: FakeState) {
|
|
const handler = async (input: string, init: RequestInit = {}): Promise<Response> => {
|
|
const method = init.method ?? 'GET'
|
|
const url = new URL(input, 'http://x')
|
|
const path = url.pathname.replace(/^\/api\/v1/, '')
|
|
const key = `${method} ${path}`
|
|
state.calls.push(key)
|
|
|
|
const auth = (init.headers as Record<string, string> | undefined)?.Authorization
|
|
if (auth !== `Bearer ${state.token}`) return err(401, 'invalid or missing token')
|
|
if (state.fail[key]) {
|
|
const f = state.fail[key]
|
|
delete state.fail[key]
|
|
return err(f.status, f.error)
|
|
}
|
|
// Files (archive imports) are not JSON.
|
|
const body = typeof init.body === 'string' && init.body ? JSON.parse(init.body) : {}
|
|
let m: RegExpMatchArray | null
|
|
|
|
if (path === '/queue' && method === 'GET') {
|
|
const items = [...state.queue].sort((a, b) => Number(b.failed) - Number(a.failed) || b.attempts - a.attempts).slice(0, state.queueLimit)
|
|
const waiting = state.queue.filter((i) => !i.failed)
|
|
const retrying = waiting.filter((i) => i.attempts > 0).length
|
|
const failed = state.queue.length - waiting.length
|
|
const oldest = waiting.map((i) => i.created_at).sort()[0] ?? null
|
|
return json(200, { pending: waiting.length, retrying, failed, oldest, items })
|
|
}
|
|
if ((m = path.match(/^\/queue\/(\d+)$/)) && method === 'DELETE') {
|
|
const id = Number(m[1])
|
|
if (!state.queue.some((i) => i.id === id)) return err(404, 'not found')
|
|
state.queue = state.queue.filter((i) => i.id !== id)
|
|
return json(204)
|
|
}
|
|
if (path === '/lists' && method === 'GET') return json(200, state.lists)
|
|
if (path === '/lists' && method === 'POST') {
|
|
if (state.lists.some((l) => l.name === body.name && l.domain === body.domain)) return err(409, 'already exists')
|
|
if (!body.name || !body.domain) return err(400, 'name and domain are required')
|
|
const l = aList({ id: state.nextId++, name: body.name, domain: body.domain, title: body.title || body.name })
|
|
state.lists.push(l)
|
|
return json(201, l)
|
|
}
|
|
if ((m = path.match(/^\/lists\/(\d+)$/))) {
|
|
const id = Number(m[1])
|
|
const l = state.lists.find((x) => x.id === id)
|
|
if (!l) return err(404, 'not found')
|
|
if (method === 'GET') return json(200, l)
|
|
if (method === 'PATCH') {
|
|
Object.assign(l, body)
|
|
return json(200, l)
|
|
}
|
|
if (method === 'DELETE') {
|
|
state.lists = state.lists.filter((x) => x.id !== id)
|
|
return json(204)
|
|
}
|
|
}
|
|
if ((m = path.match(/^\/lists\/(\d+)\/members$/))) {
|
|
const id = Number(m[1])
|
|
const ms = (state.members[id] ??= [])
|
|
if (method === 'GET') return json(200, ms)
|
|
if (method === 'POST') {
|
|
if (!/^[^@\s]+@[^@\s]+$/.test(body.address ?? '')) return err(400, 'a valid email address is required')
|
|
const mem: Member = { address: body.address.toLowerCase(), display_name: body.display_name ?? '', disabled: false, bounce_count: 0 }
|
|
state.members[id] = [...ms.filter((x) => x.address !== mem.address), mem]
|
|
return json(201, mem)
|
|
}
|
|
}
|
|
if ((m = path.match(/^\/lists\/(\d+)\/members\/(.+)$/)) && method === 'DELETE') {
|
|
const id = Number(m[1])
|
|
const addr = decodeURIComponent(m[2])
|
|
const before = state.members[id] ?? []
|
|
if (!before.some((x) => x.address === addr)) return err(404, 'not found')
|
|
state.members[id] = before.filter((x) => x.address !== addr)
|
|
return json(204)
|
|
}
|
|
if ((m = path.match(/^\/lists\/(\d+)\/posts$/)) && method === 'GET') {
|
|
const id = Number(m[1])
|
|
if (!state.lists.some((l) => l.id === id)) return err(404, 'not found')
|
|
return json(200, state.posts[id] ?? [])
|
|
}
|
|
if ((m = path.match(/^\/lists\/(\d+)\/held$/)) && method === 'GET') return json(200, state.held[Number(m[1])] ?? [])
|
|
if ((m = path.match(/^\/held\/(\d+)(\/approve)?$/))) {
|
|
const id = Number(m[1])
|
|
for (const k of Object.keys(state.held)) {
|
|
const list = state.held[Number(k)]
|
|
if (list.some((h) => h.id === id)) {
|
|
if ((m[2] && method === 'POST') || (!m[2] && method === 'DELETE')) {
|
|
state.held[Number(k)] = list.filter((h) => h.id !== id)
|
|
return json(204)
|
|
}
|
|
}
|
|
}
|
|
return err(404, 'not found')
|
|
}
|
|
if ((m = path.match(/^\/lists\/(\d+)\/archive\/import$/)) && method === 'POST') {
|
|
const id = Number(m[1])
|
|
if (!state.lists.some((l) => l.id === id)) return err(404, 'not found')
|
|
if (state.hold) await state.hold
|
|
state.importTypes.push((init.headers as Record<string, string>)['Content-Type'] ?? '')
|
|
const text = typeof init.body === 'string' ? init.body : await (init.body as Blob).text()
|
|
const messages = text.split(/^From \S+ .*$/m).slice(1)
|
|
const archive = (state.archive[id] ??= [])
|
|
let imported = 0
|
|
let duplicates = 0
|
|
const errors: string[] = []
|
|
messages.forEach((raw, i) => {
|
|
const subject = /^Subject: (.*)$/m.exec(raw)?.[1]
|
|
const messageId = /^Message-ID: (.*)$/m.exec(raw)?.[1]
|
|
if (!subject || !messageId) {
|
|
errors.push(`message ${i + 1}: parse message: no headers`)
|
|
return
|
|
}
|
|
if (archive.some((a) => a.message_id === messageId)) {
|
|
duplicates++
|
|
return
|
|
}
|
|
const nid = state.nextId++
|
|
archive.push({ id: nid, thread_id: nid, message_id: messageId, subject, sender: 'Imported', date: '2024-01-01T00:00:00Z', size: raw.length })
|
|
imported++
|
|
})
|
|
return json(200, { imported, duplicates, failed: errors.length, errors })
|
|
}
|
|
if ((m = path.match(/^\/lists\/(\d+)\/archive$/)) && method === 'GET') {
|
|
const id = Number(m[1])
|
|
const q = (url.searchParams.get('q') ?? '').toLowerCase()
|
|
const limit = Number(url.searchParams.get('limit') ?? 50)
|
|
const offset = Number(url.searchParams.get('offset') ?? 0)
|
|
const all = (state.archive[id] ?? [])
|
|
.filter((x) => !q || x.subject.toLowerCase().includes(q) || (x.body ?? '').toLowerCase().includes(q))
|
|
.map((x) => ({ ...x, body: undefined }))
|
|
return json(200, { total: all.length, messages: all.slice(offset, offset + limit) })
|
|
}
|
|
if ((m = path.match(/^\/archive\/(\d+)$/))) {
|
|
const id = Number(m[1])
|
|
for (const k of Object.keys(state.archive)) {
|
|
const msg = state.archive[Number(k)].find((x) => x.id === id)
|
|
if (msg) {
|
|
if (method === 'GET') return json(200, msg)
|
|
if (method === 'DELETE') {
|
|
state.archive[Number(k)] = state.archive[Number(k)].filter((x) => x.id !== id)
|
|
return json(204)
|
|
}
|
|
}
|
|
}
|
|
return err(404, 'not found')
|
|
}
|
|
return err(404, 'not found')
|
|
}
|
|
vi.stubGlobal('fetch', vi.fn(handler))
|
|
return state
|
|
}
|