import { request as httpRequest } from 'node:http'; import { connect } from 'node:net'; import { afterEach, describe, expect, it } from 'vitest'; import { HttpError, HttpServer, Router, reply, type RouteDefinition } from '../src/index.js'; import { deferred, startServer, type TestServer } from './helpers.js'; let current: TestServer | undefined; async function start(routes: readonly RouteDefinition[], options = {}) { current = await startServer(routes, options); return current; } afterEach(async () => { await current?.server.close(); current = undefined; }); const get = (path: string, handler: RouteDefinition['handler']): RouteDefinition => ({ method: 'GET', path, handler, }); const post = (path: string, handler: RouteDefinition['handler']): RouteDefinition => ({ method: 'POST', path, handler, }); describe('responses', () => { it('sends objects as JSON', async () => { const { url } = await start([get('/', () => ({ hello: 'world' }))]); const res = await fetch(url); expect(res.status).toBe(200); expect(res.headers.get('content-type')).toBe('application/json; charset=utf-8'); expect(res.headers.get('content-length')).toBe('17'); expect(res.headers.get('x-content-type-options')).toBe('nosniff'); expect(await res.json()).toEqual({ hello: 'world' }); }); it('sends strings as UTF-8 text', async () => { const { url } = await start([get('/', () => 'héllo')]); const res = await fetch(url); expect(res.headers.get('content-type')).toBe('text/plain; charset=utf-8'); expect(res.headers.get('content-length')).toBe('6'); expect(await res.text()).toBe('héllo'); }); it('sends bytes as octet-stream', async () => { const { url } = await start([get('/', () => new Uint8Array([1, 2, 3]))]); const res = await fetch(url); expect(res.headers.get('content-type')).toBe('application/octet-stream'); expect(new Uint8Array(await res.arrayBuffer())).toEqual(new Uint8Array([1, 2, 3])); }); it.each([ [null, 'null'], [42, '42'], [false, 'false'], [[1, 2], '[1,2]'], ])('sends %j as JSON', async (value, expected) => { const { url } = await start([get('/', () => value)]); const res = await fetch(url); expect(res.headers.get('content-type')).toBe('application/json; charset=utf-8'); expect(await res.text()).toBe(expected); }); it('sends 204 with no body for undefined', async () => { const { url } = await start([get('/', () => undefined)]); const res = await fetch(url); expect(res.status).toBe(204); expect(res.headers.get('content-type')).toBeNull(); expect(await res.text()).toBe(''); }); it('awaits async handlers', async () => { const { url } = await start([ get('/', async () => { await new Promise((r) => setTimeout(r, 5)); return { async: true }; }), ]); expect(await (await fetch(url)).json()).toEqual({ async: true }); }); it('applies reply status and headers', async () => { const { url } = await start([ post('/users', () => reply({ id: 1 }, { status: 201, headers: { location: '/users/1' } })), get('/empty', () => reply(undefined, { status: 202 })), get('/html', () => reply('
hi
', { headers: { 'content-type': 'text/html' } })), ]); const created = await fetch(`${url}/users`, { method: 'POST' }); expect(created.status).toBe(201); expect(created.headers.get('location')).toBe('/users/1'); expect(await created.json()).toEqual({ id: 1 }); const empty = await fetch(`${url}/empty`); expect(empty.status).toBe(202); expect(await empty.text()).toBe(''); const html = await fetch(`${url}/html`); expect(html.headers.get('content-type')).toBe('text/html'); }); it('returns 404 JSON for unknown paths', async () => { const { url, logger } = await start([get('/known', () => 'ok')]); const res = await fetch(`${url}/missing`); expect(res.status).toBe(404); expect(await res.json()).toEqual({ statusCode: 404, error: 'Not Found', message: 'Not Found' }); expect(logger.error).not.toHaveBeenCalled(); }); }); describe('routing', () => { it('passes decoded params to the handler', async () => { const { url } = await start([ get('/users/:id/files/*', (ctx) => ({ path: ctx.path, params: { ...ctx.params } })), ]); const res = await fetch(`${url}/users/caf%C3%A9/files/a/b%20c.txt?x=1`); expect(await res.json()).toEqual({ path: '/users/caf%C3%A9/files/a/b%20c.txt', params: { id: 'café', '*': 'a/b c.txt' }, }); }); it('answers 405 with an Allow header', async () => { const { url, logger } = await start([get('/items', () => []), post('/items', () => ({}))]); const res = await fetch(`${url}/items`, { method: 'DELETE' }); expect(res.status).toBe(405); expect(res.headers.get('allow')).toBe('GET, HEAD, POST, OPTIONS'); expect(await res.json()).toEqual({ statusCode: 405, error: 'Method Not Allowed', message: 'Method Not Allowed', }); expect(logger.error).not.toHaveBeenCalled(); }); it('serves HEAD from GET with headers and no body', async () => { let calls = 0; const { url } = await start([ get('/items', () => { calls++; return { items: [1, 2, 3] }; }), ]); const res = await fetch(`${url}/items`, { method: 'HEAD' }); expect(res.status).toBe(200); expect(res.headers.get('content-type')).toBe('application/json; charset=utf-8'); expect(res.headers.get('content-length')).toBe(String('{"items":[1,2,3]}'.length)); expect(await res.text()).toBe(''); expect(calls).toBe(1); }); it('answers OPTIONS with 204 and Allow', async () => { const { url } = await start([get('/items/:id', () => 'x')]); const res = await fetch(`${url}/items/1`, { method: 'OPTIONS' }); expect(res.status).toBe(204); expect(res.headers.get('allow')).toBe('GET, HEAD, OPTIONS'); expect(await res.text()).toBe(''); }); it('rejects malformed percent-encoding with 400 before any handler', async () => { let called = false; const { port } = await start([ get('/*', () => { called = true; return 'x'; }), ]); const { status, body } = await new Promise<{ status?: number; body: string }>( (resolve, reject) => { const req = httpRequest({ port, host: '127.0.0.1', path: '/files/%E0%A4' }, (res) => { let body = ''; res.setEncoding('utf8'); res.on('data', (chunk: string) => (body += chunk)); res.on('end', () => { resolve({ status: res.statusCode, body }); }); }); req.on('error', reject); req.end(); }, ); expect(status).toBe(400); expect(JSON.parse(body)).toMatchObject({ message: 'Malformed URL encoding' }); expect(called).toBe(false); }); it('sends headers attached to an HttpError', async () => { const { url } = await start([ get('/limited', () => { throw new HttpError(429, 'Slow down', { headers: { 'retry-after': '30' } }); }), get('/bad-headers', () => { throw new HttpError(400, 'Bad', { headers: { 'x-ok': '1', 'x-bad': 'a\nb' } }); }), ]); const limited = await fetch(`${url}/limited`); expect(limited.status).toBe(429); expect(limited.headers.get('retry-after')).toBe('30'); const bad = await fetch(`${url}/bad-headers`); expect(bad.status).toBe(400); expect(bad.headers.get('x-ok')).toBeNull(); }); it('exposes path and query separately', async () => { const { url } = await start([ get('/search', (ctx) => ({ path: ctx.path, q: ctx.query.get('q'), tags: ctx.query.getAll('t'), })), ]); const res = await fetch(`${url}/search?q=avi&t=a&t=b`); expect(await res.json()).toEqual({ path: '/search', q: 'avi', tags: ['a', 'b'] }); }); }); describe('errors', () => { it('hides thrown errors behind a generic 500 and logs them', async () => { const error = new Error('database password is hunter2'); const { url, logger } = await start([ get('/boom', () => { throw error; }), ]); const res = await fetch(`${url}/boom`); expect(res.status).toBe(500); const body = await res.text(); expect(JSON.parse(body)).toEqual({ statusCode: 500, error: 'Internal Server Error' }); expect(body).not.toContain('hunter2'); expect(logger.error).toHaveBeenCalledWith( 'Request failed: GET /boom', error, expect.objectContaining({ method: 'GET' }), ); }); it('handles rejected promises the same way', async () => { const { url, logger } = await start([ get('/boom', () => Promise.reject(new Error('async secret'))), ]); const res = await fetch(`${url}/boom`); expect(res.status).toBe(500); expect(await res.text()).not.toContain('async secret'); expect(logger.error).toHaveBeenCalledOnce(); }); it('sends 4xx HttpError messages without logging', async () => { const { url, logger } = await start([ get('/bad', () => { throw new HttpError(422, 'Name is required'); }), ]); const res = await fetch(`${url}/bad`); expect(res.status).toBe(422); expect(await res.json()).toEqual({ statusCode: 422, error: 'Unprocessable Entity', message: 'Name is required', }); expect(logger.error).not.toHaveBeenCalled(); }); it('keeps the status but hides the message of 5xx HttpErrors', async () => { const { url, logger } = await start([ get('/down', () => { throw new HttpError(503, 'Replica db-3 is down'); }), ]); const res = await fetch(`${url}/down`); expect(res.status).toBe(503); expect(await res.json()).toEqual({ statusCode: 503, error: 'Service Unavailable' }); expect(logger.error).toHaveBeenCalledOnce(); }); it('turns serialization failures into a 500', async () => { const { url, logger } = await start([get('/', () => ({ big: 1n }))]); const res = await fetch(url); expect(res.status).toBe(500); expect(logger.error).toHaveBeenCalledOnce(); }); it('drops reply headers when writing them fails', async () => { const { url } = await start([ get('/', () => reply('x', { headers: { 'x-first': 'kept?', 'x-bad': 'a\nb' } })), ]); const res = await fetch(url); expect(res.status).toBe(500); expect(res.headers.get('x-first')).toBeNull(); }); }); describe('request body', () => { it('reads text', async () => { const { url } = await start([post('/', async (ctx) => (await ctx.text()).toUpperCase())]); const res = await fetch(url, { method: 'POST', body: 'hello' }); expect(await res.text()).toBe('HELLO'); }); it('reads the body once and caches it', async () => { const { url } = await start([ post('/', async (ctx) => [await ctx.text(), await ctx.text(), await ctx.json()]), ]); const res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{"a":1}', }); expect(await res.json()).toEqual(['{"a":1}', '{"a":1}', { a: 1 }]); }); it.each(['application/json', 'application/json; charset=utf-8', 'application/problem+json'])( 'parses JSON sent as %s', async (type) => { const { url } = await start([post('/', (ctx) => ctx.json())]); const res = await fetch(url, { method: 'POST', headers: { 'content-type': type }, body: '[1]', }); expect(await res.json()).toEqual([1]); }, ); it('rejects JSON with the wrong content type with 415', async () => { const { url } = await start([post('/', (ctx) => ctx.json())]); const res = await fetch(url, { method: 'POST', headers: { 'content-type': 'text/plain' }, body: '{}', }); expect(res.status).toBe(415); }); it('rejects malformed JSON with 400', async () => { const { url, logger } = await start([post('/', (ctx) => ctx.json())]); const res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{"a":', }); expect(res.status).toBe(400); expect(await res.json()).toMatchObject({ message: 'Malformed JSON body' }); expect(logger.error).not.toHaveBeenCalled(); }); it('accepts a body exactly at the limit', async () => { const { url } = await start([post('/', (ctx) => ctx.text())], { bodyLimit: 5 }); const res = await fetch(url, { method: 'POST', body: '12345' }); expect(await res.text()).toBe('12345'); }); it('rejects a declared length over the limit with 413', async () => { let reached = false; const { url } = await start( [ post('/', async (ctx) => { await ctx.text(); reached = true; }), ], { bodyLimit: 10 }, ); const res = await fetch(url, { method: 'POST', body: 'x'.repeat(11) }); expect(res.status).toBe(413); expect(res.headers.get('connection')).toBe('close'); expect(reached).toBe(false); }); it('rejects a streamed body over the limit with 413', async () => { const { port } = await start([post('/', (ctx) => ctx.text())], { bodyLimit: 10 }); const status = await new Promise