|
| 1 | +import { describe, expect, it, vi } from 'vitest' |
| 2 | +import { SendDock } from './client.js' |
| 3 | +import { SendDockError } from './error.js' |
| 4 | + |
| 5 | +function jsonResponse(status: number, body: unknown, headers?: Record<string, string>) { |
| 6 | + return new Response(JSON.stringify(body), { |
| 7 | + status, |
| 8 | + headers: { 'Content-Type': 'application/json', ...headers }, |
| 9 | + }) |
| 10 | +} |
| 11 | + |
| 12 | +function makeClient(fetchImpl: typeof fetch, maxRetries = 0) { |
| 13 | + return new SendDock({ |
| 14 | + baseUrl: 'https://mail.example.com', |
| 15 | + apiKey: 'sk_test_123', |
| 16 | + projectId: 'proj-1', |
| 17 | + fetch: fetchImpl, |
| 18 | + maxRetries, |
| 19 | + }) |
| 20 | +} |
| 21 | + |
| 22 | +describe('constructor validation', () => { |
| 23 | + it.each([ |
| 24 | + ['baseUrl', { baseUrl: '', apiKey: 'sk', projectId: 'p' }], |
| 25 | + ['apiKey', { baseUrl: 'https://x.com', apiKey: '', projectId: 'p' }], |
| 26 | + ['projectId', { baseUrl: 'https://x.com', apiKey: 'sk', projectId: '' }], |
| 27 | + ])('throws synchronously when %s is missing', (_field, opts) => { |
| 28 | + expect(() => new SendDock(opts)).toThrow() |
| 29 | + }) |
| 30 | + |
| 31 | + it('normalizes a trailing slash in baseUrl', async () => { |
| 32 | + const fetchMock = vi.fn().mockResolvedValue(jsonResponse(200, {})) |
| 33 | + const sd = new SendDock({ |
| 34 | + baseUrl: 'https://mail.example.com///', |
| 35 | + apiKey: 'sk', |
| 36 | + projectId: 'p', |
| 37 | + fetch: fetchMock, |
| 38 | + }) |
| 39 | + await sd.stats() |
| 40 | + expect(fetchMock.mock.calls[0]![0]).toBe( |
| 41 | + 'https://mail.example.com/api/v1/projects/p/stats', |
| 42 | + ) |
| 43 | + }) |
| 44 | +}) |
| 45 | + |
| 46 | +describe('network failures', () => { |
| 47 | + it('wraps a connection failure in SendDockError instead of leaking a raw TypeError', async () => { |
| 48 | + const fetchMock = vi.fn().mockRejectedValue(new TypeError('fetch failed')) |
| 49 | + const sd = makeClient(fetchMock) |
| 50 | + |
| 51 | + const err = await sd.stats().catch((e: unknown) => e) |
| 52 | + |
| 53 | + expect(err).toBeInstanceOf(SendDockError) |
| 54 | + expect((err as SendDockError).status).toBe(0) |
| 55 | + expect((err as SendDockError).isNetworkError).toBe(true) |
| 56 | + expect((err as SendDockError).message).toContain('fetch failed') |
| 57 | + }) |
| 58 | + |
| 59 | + it('retries network failures before giving up', async () => { |
| 60 | + vi.useFakeTimers() |
| 61 | + try { |
| 62 | + const fetchMock = vi |
| 63 | + .fn() |
| 64 | + .mockRejectedValueOnce(new TypeError('fetch failed')) |
| 65 | + .mockResolvedValueOnce(jsonResponse(200, { message: 'sent' })) |
| 66 | + const sd = makeClient(fetchMock, 2) |
| 67 | + |
| 68 | + const pending = sd.send({ to: 'a@example.com', template_id: 't-1' }) |
| 69 | + await vi.advanceTimersByTimeAsync(500) |
| 70 | + |
| 71 | + expect(await pending).toEqual({ message: 'sent' }) |
| 72 | + expect(fetchMock).toHaveBeenCalledTimes(2) |
| 73 | + } finally { |
| 74 | + vi.useRealTimers() |
| 75 | + } |
| 76 | + }) |
| 77 | + |
| 78 | + it('reports a timeout as a SendDockError naming the limit', async () => { |
| 79 | + const fetchMock = vi |
| 80 | + .fn() |
| 81 | + .mockRejectedValue(new DOMException('signal timed out', 'TimeoutError')) |
| 82 | + const sd = makeClient(fetchMock) |
| 83 | + |
| 84 | + const err = await sd.stats().catch((e: unknown) => e) |
| 85 | + |
| 86 | + expect(err).toBeInstanceOf(SendDockError) |
| 87 | + expect((err as SendDockError).message).toBe('request timed out after 30000ms') |
| 88 | + }) |
| 89 | + |
| 90 | + it('passes an abort signal so hung requests cannot hang forever', async () => { |
| 91 | + const fetchMock = vi.fn().mockResolvedValue(jsonResponse(200, {})) |
| 92 | + const sd = makeClient(fetchMock) |
| 93 | + |
| 94 | + await sd.stats() |
| 95 | + |
| 96 | + const [, init] = fetchMock.mock.calls[0]! |
| 97 | + expect(init.signal).toBeInstanceOf(AbortSignal) |
| 98 | + }) |
| 99 | +}) |
| 100 | + |
| 101 | +describe('malformed server responses', () => { |
| 102 | + it('wraps invalid JSON on a 2xx instead of leaking a SyntaxError', async () => { |
| 103 | + const fetchMock = vi |
| 104 | + .fn() |
| 105 | + .mockResolvedValue(new Response('<html>gateway</html>', { status: 200 })) |
| 106 | + const sd = makeClient(fetchMock) |
| 107 | + |
| 108 | + const err = await sd.stats().catch((e: unknown) => e) |
| 109 | + |
| 110 | + expect(err).toBeInstanceOf(SendDockError) |
| 111 | + expect((err as SendDockError).message).toBe('the server returned a non-JSON response body') |
| 112 | + }) |
| 113 | + |
| 114 | + it('handles a non-JSON error body without crashing', async () => { |
| 115 | + const fetchMock = vi |
| 116 | + .fn() |
| 117 | + .mockResolvedValue(new Response('Bad Gateway', { status: 502 })) |
| 118 | + const sd = makeClient(fetchMock) |
| 119 | + |
| 120 | + const err = await sd.stats().catch((e: unknown) => e) |
| 121 | + |
| 122 | + expect(err).toBeInstanceOf(SendDockError) |
| 123 | + expect((err as SendDockError).status).toBe(502) |
| 124 | + expect((err as SendDockError).message).toBe('request failed with status 502') |
| 125 | + }) |
| 126 | + |
| 127 | + it('handles an error body whose error field is not a string', async () => { |
| 128 | + const fetchMock = vi |
| 129 | + .fn() |
| 130 | + .mockResolvedValue(jsonResponse(400, { error: { nested: true } })) |
| 131 | + const sd = makeClient(fetchMock) |
| 132 | + |
| 133 | + const err = await sd.stats().catch((e: unknown) => e) |
| 134 | + |
| 135 | + expect((err as SendDockError).message).toBe('request failed with status 400') |
| 136 | + expect((err as SendDockError).body).toEqual({ error: { nested: true } }) |
| 137 | + }) |
| 138 | +}) |
| 139 | + |
| 140 | +describe('retry exhaustion', () => { |
| 141 | + it('throws the last error after exhausting retries on 5xx', async () => { |
| 142 | + vi.useFakeTimers() |
| 143 | + try { |
| 144 | + const fetchMock = vi |
| 145 | + .fn() |
| 146 | + .mockImplementation(() => Promise.resolve(jsonResponse(503, { error: 'unavailable' }))) |
| 147 | + const sd = makeClient(fetchMock, 2) |
| 148 | + |
| 149 | + const pending = sd.stats().catch((e: unknown) => e) |
| 150 | + await vi.advanceTimersByTimeAsync(10_000) |
| 151 | + const err = await pending |
| 152 | + |
| 153 | + expect(fetchMock).toHaveBeenCalledTimes(3) |
| 154 | + expect((err as SendDockError).status).toBe(503) |
| 155 | + expect((err as SendDockError).message).toBe('unavailable') |
| 156 | + } finally { |
| 157 | + vi.useRealTimers() |
| 158 | + } |
| 159 | + }) |
| 160 | + |
| 161 | + it('caps a hostile Retry-After at 60 seconds', async () => { |
| 162 | + vi.useFakeTimers() |
| 163 | + try { |
| 164 | + const fetchMock = vi |
| 165 | + .fn() |
| 166 | + .mockResolvedValueOnce( |
| 167 | + jsonResponse(429, { error: 'slow down' }, { 'Retry-After': '86400' }), |
| 168 | + ) |
| 169 | + .mockResolvedValueOnce(jsonResponse(200, {})) |
| 170 | + const sd = makeClient(fetchMock, 1) |
| 171 | + |
| 172 | + const pending = sd.stats() |
| 173 | + await vi.advanceTimersByTimeAsync(60_000) |
| 174 | + |
| 175 | + await expect(pending).resolves.toEqual({}) |
| 176 | + expect(fetchMock).toHaveBeenCalledTimes(2) |
| 177 | + } finally { |
| 178 | + vi.useRealTimers() |
| 179 | + } |
| 180 | + }) |
| 181 | + |
| 182 | + it('never retries 4xx client errors even with retries configured', async () => { |
| 183 | + const fetchMock = vi.fn().mockResolvedValue(jsonResponse(404, { error: 'project not found' })) |
| 184 | + const sd = makeClient(fetchMock, 3) |
| 185 | + |
| 186 | + const err = await sd.stats().catch((e: unknown) => e) |
| 187 | + |
| 188 | + expect(fetchMock).toHaveBeenCalledTimes(1) |
| 189 | + expect((err as SendDockError).isNotFound).toBe(true) |
| 190 | + }) |
| 191 | +}) |
0 commit comments