Extracted from the private caelum0x/scribase monorepo's packages/scribase-js with a fresh, single-commit history (no core history leaks). The npx scribase CLI and the typed /v1 API client, unchanged except: prepublishOnly simplified (the monorepo-only tarball gitleaks gate dropped), repository/homepage/bugs fields added, and one test that cross-checked embedded template strings against the monorepo's templates/ directory removed (nothing it tested changed; that directory isn't shipped here).
451 lines
14 KiB
TypeScript
451 lines
14 KiB
TypeScript
/**
|
|
* Tests for ScribaseClient — construction, URL building, header injection,
|
|
* success/error decoding, and retry logic. All tests use an injected `fetch`
|
|
* function so no network is required.
|
|
*/
|
|
|
|
import { describe, it } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
|
|
import { ScribaseClient } from '../src/client.js';
|
|
import {
|
|
ScribaseApiError,
|
|
BadRequestError,
|
|
UnauthorizedError,
|
|
ForbiddenError,
|
|
NotFoundError,
|
|
QuotaExceededError,
|
|
ServiceUnavailableError,
|
|
NetworkError,
|
|
TimeoutError,
|
|
} from '../src/errors.js';
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Helpers
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/** Build a mock `fetch` that returns a fixed JSON body with the given status. */
|
|
function stubFetch(
|
|
status: number,
|
|
body: unknown,
|
|
headers?: Record<string, string>
|
|
): typeof fetch {
|
|
return async (_url: string | URL | Request, _init?: RequestInit): Promise<Response> => {
|
|
const bodyStr = body === undefined ? '' : JSON.stringify(body);
|
|
const responseHeaders: Record<string, string> = {
|
|
'content-type': 'application/json',
|
|
...headers,
|
|
};
|
|
return new Response(bodyStr, { status, headers: responseHeaders });
|
|
};
|
|
}
|
|
|
|
/** Build a mock fetch that throws a network error. */
|
|
function throwingFetch(message: string): typeof fetch {
|
|
return async (): Promise<Response> => {
|
|
throw new Error(message);
|
|
};
|
|
}
|
|
|
|
/** A no-op sleep for testing retry logic without actual delays. */
|
|
const noSleep = async (_ms: number): Promise<void> => {};
|
|
|
|
function makeClient(fetchFn: typeof fetch, opts?: { timeoutMs?: number; maxRetries?: number }) {
|
|
return new ScribaseClient({
|
|
baseUrl: 'https://api.example.com',
|
|
token: 'test-token',
|
|
fetch: fetchFn,
|
|
timeoutMs: opts?.timeoutMs ?? 5_000,
|
|
maxRetries: opts?.maxRetries ?? 0,
|
|
sleep: noSleep,
|
|
});
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Construction
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('ScribaseClient construction', () => {
|
|
it('accepts a valid https URL', () => {
|
|
assert.doesNotThrow(() =>
|
|
makeClient(stubFetch(200, {}))
|
|
);
|
|
});
|
|
|
|
it('accepts a valid http URL (non-TLS deployment)', () => {
|
|
assert.doesNotThrow(() =>
|
|
new ScribaseClient({
|
|
baseUrl: 'http://localhost:8080',
|
|
token: 'tok',
|
|
fetch: stubFetch(200, {}),
|
|
sleep: noSleep,
|
|
})
|
|
);
|
|
});
|
|
|
|
it('rejects an invalid URL', () => {
|
|
assert.throws(
|
|
() =>
|
|
new ScribaseClient({
|
|
baseUrl: 'not-a-url',
|
|
token: 'tok',
|
|
fetch: stubFetch(200, {}),
|
|
sleep: noSleep,
|
|
}),
|
|
TypeError
|
|
);
|
|
});
|
|
|
|
it('rejects a non-http(s) scheme', () => {
|
|
assert.throws(
|
|
() =>
|
|
new ScribaseClient({
|
|
baseUrl: 'ftp://example.com',
|
|
token: 'tok',
|
|
fetch: stubFetch(200, {}),
|
|
sleep: noSleep,
|
|
}),
|
|
TypeError
|
|
);
|
|
});
|
|
|
|
it('strips trailing slashes from baseUrl', async () => {
|
|
let capturedUrl = '';
|
|
const spy: typeof fetch = async (url, _init) => {
|
|
capturedUrl = url as string;
|
|
return new Response(JSON.stringify({ environments: [] }), {
|
|
status: 200,
|
|
headers: { 'content-type': 'application/json' },
|
|
});
|
|
};
|
|
const client = new ScribaseClient({
|
|
baseUrl: 'https://api.example.com///',
|
|
token: 'tok',
|
|
fetch: spy,
|
|
sleep: noSleep,
|
|
});
|
|
await client.environments.list({ organizationId: 'org-1' });
|
|
assert.ok(!capturedUrl.includes('///'), 'URL should not have triple slash');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Successful responses
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('ScribaseClient.send — success path', () => {
|
|
it('returns parsed JSON for a 200 response', async () => {
|
|
const payload = { environments: [{ environment_id: 'env-1' }] };
|
|
const client = makeClient(stubFetch(200, payload));
|
|
|
|
const result = await client.send<typeof payload>({ method: 'GET', path: '/v1/test' });
|
|
assert.deepEqual(result.data, payload);
|
|
assert.equal(result.status, 200);
|
|
assert.equal(result.idempotencyReplayed, false);
|
|
});
|
|
|
|
it('detects an idempotency-replayed header', async () => {
|
|
const client = makeClient(
|
|
stubFetch(200, { ok: true }, { 'idempotency-replayed': 'true' })
|
|
);
|
|
const result = await client.send<{ ok: boolean }>({ method: 'GET', path: '/v1/test' });
|
|
assert.equal(result.idempotencyReplayed, true);
|
|
});
|
|
|
|
it('handles a 204 no-content response', async () => {
|
|
const fetchFn: typeof fetch = async () =>
|
|
new Response(null, { status: 204 });
|
|
const client = makeClient(fetchFn);
|
|
const result = await client.send<undefined>({
|
|
method: 'DELETE',
|
|
path: '/v1/test',
|
|
expectNoContent: true,
|
|
});
|
|
assert.equal(result.status, 204);
|
|
assert.equal(result.data, undefined);
|
|
});
|
|
|
|
it('attaches the authorization header', async () => {
|
|
let capturedHeaders: Headers | undefined;
|
|
const spy: typeof fetch = async (_url, init) => {
|
|
capturedHeaders = new Headers(init?.headers as HeadersInit);
|
|
return new Response('{}', {
|
|
status: 200,
|
|
headers: { 'content-type': 'application/json' },
|
|
});
|
|
};
|
|
const client = new ScribaseClient({
|
|
baseUrl: 'https://api.example.com',
|
|
token: 'my-secret-token',
|
|
fetch: spy,
|
|
sleep: noSleep,
|
|
});
|
|
await client.send({ method: 'GET', path: '/v1/test' });
|
|
assert.equal(capturedHeaders?.get('authorization'), 'Bearer my-secret-token');
|
|
});
|
|
|
|
it('resolves an async token provider', async () => {
|
|
let capturedAuth = '';
|
|
const spy: typeof fetch = async (_url, init) => {
|
|
const h = new Headers(init?.headers as HeadersInit);
|
|
capturedAuth = h.get('authorization') ?? '';
|
|
return new Response('{}', {
|
|
status: 200,
|
|
headers: { 'content-type': 'application/json' },
|
|
});
|
|
};
|
|
const client = new ScribaseClient({
|
|
baseUrl: 'https://api.example.com',
|
|
token: async () => 'async-token',
|
|
fetch: spy,
|
|
sleep: noSleep,
|
|
});
|
|
await client.send({ method: 'GET', path: '/v1/test' });
|
|
assert.equal(capturedAuth, 'Bearer async-token');
|
|
});
|
|
|
|
it('serializes the request body as JSON and sets content-type', async () => {
|
|
let capturedInit: RequestInit | undefined;
|
|
const spy: typeof fetch = async (_url, init) => {
|
|
capturedInit = init;
|
|
return new Response('{}', {
|
|
status: 200,
|
|
headers: { 'content-type': 'application/json' },
|
|
});
|
|
};
|
|
const client = makeClient(spy);
|
|
await client.send({ method: 'POST', path: '/v1/test', body: { foo: 'bar' } });
|
|
assert.equal(capturedInit?.body, JSON.stringify({ foo: 'bar' }));
|
|
const h = new Headers(capturedInit?.headers as HeadersInit);
|
|
assert.equal(h.get('content-type'), 'application/json');
|
|
});
|
|
|
|
it('attaches the idempotency key header when provided', async () => {
|
|
let capturedKey = '';
|
|
const spy: typeof fetch = async (_url, init) => {
|
|
const h = new Headers(init?.headers as HeadersInit);
|
|
capturedKey = h.get('idempotency-key') ?? '';
|
|
return new Response('{}', {
|
|
status: 200,
|
|
headers: { 'content-type': 'application/json' },
|
|
});
|
|
};
|
|
const client = makeClient(spy);
|
|
await client.send({
|
|
method: 'POST',
|
|
path: '/v1/test',
|
|
body: {},
|
|
idempotencyKey: 'my-idem-key',
|
|
});
|
|
assert.equal(capturedKey, 'my-idem-key');
|
|
});
|
|
|
|
it('appends query parameters to the URL', async () => {
|
|
let capturedUrl = '';
|
|
const spy: typeof fetch = async (url) => {
|
|
capturedUrl = url as string;
|
|
return new Response('{}', {
|
|
status: 200,
|
|
headers: { 'content-type': 'application/json' },
|
|
});
|
|
};
|
|
const client = makeClient(spy);
|
|
await client.send({
|
|
method: 'GET',
|
|
path: '/v1/test',
|
|
query: { organization_id: 'org-1', limit: 10 },
|
|
});
|
|
const u = new URL(capturedUrl);
|
|
assert.equal(u.searchParams.get('organization_id'), 'org-1');
|
|
assert.equal(u.searchParams.get('limit'), '10');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Error decoding
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('ScribaseClient.send — error decoding', () => {
|
|
const problem = (status: number, code: string) => ({
|
|
type: 'about:blank',
|
|
title: 'Error',
|
|
status,
|
|
code,
|
|
});
|
|
|
|
it('throws BadRequestError for 400', async () => {
|
|
const client = makeClient(stubFetch(400, problem(400, 'bad_request')));
|
|
await assert.rejects(
|
|
() => client.send({ method: 'GET', path: '/v1/test' }),
|
|
BadRequestError
|
|
);
|
|
});
|
|
|
|
it('throws UnauthorizedError for 401', async () => {
|
|
const client = makeClient(stubFetch(401, problem(401, 'unauthorized')));
|
|
await assert.rejects(
|
|
() => client.send({ method: 'GET', path: '/v1/test' }),
|
|
UnauthorizedError
|
|
);
|
|
});
|
|
|
|
it('throws ForbiddenError for 403', async () => {
|
|
const client = makeClient(stubFetch(403, problem(403, 'forbidden')));
|
|
await assert.rejects(
|
|
() => client.send({ method: 'GET', path: '/v1/test' }),
|
|
ForbiddenError
|
|
);
|
|
});
|
|
|
|
it('throws NotFoundError for 404', async () => {
|
|
const client = makeClient(stubFetch(404, problem(404, 'not_found')));
|
|
await assert.rejects(
|
|
() => client.send({ method: 'GET', path: '/v1/test' }),
|
|
NotFoundError
|
|
);
|
|
});
|
|
|
|
it('throws QuotaExceededError for 429', async () => {
|
|
const client = makeClient(stubFetch(429, problem(429, 'quota_exceeded')));
|
|
await assert.rejects(
|
|
() => client.send({ method: 'GET', path: '/v1/test' }),
|
|
QuotaExceededError
|
|
);
|
|
});
|
|
|
|
it('throws ServiceUnavailableError for 503', async () => {
|
|
const client = makeClient(stubFetch(503, problem(503, 'service_unavailable')));
|
|
await assert.rejects(
|
|
() => client.send({ method: 'GET', path: '/v1/test' }),
|
|
ServiceUnavailableError
|
|
);
|
|
});
|
|
|
|
it('synthesizes a problem for a non-JSON error body', async () => {
|
|
const fetchFn: typeof fetch = async () =>
|
|
new Response('Internal Server Error', {
|
|
status: 500,
|
|
headers: { 'content-type': 'text/plain' },
|
|
});
|
|
const client = makeClient(fetchFn);
|
|
await assert.rejects(
|
|
() => client.send({ method: 'GET', path: '/v1/test' }),
|
|
(err: unknown) => {
|
|
assert.ok(err instanceof ScribaseApiError);
|
|
assert.equal(err.status, 500);
|
|
return true;
|
|
}
|
|
);
|
|
});
|
|
|
|
it('throws NetworkError when fetch throws a non-abort error', async () => {
|
|
const client = makeClient(throwingFetch('ECONNREFUSED'), { maxRetries: 0 });
|
|
await assert.rejects(
|
|
() => client.send({ method: 'GET', path: '/v1/test' }),
|
|
NetworkError
|
|
);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Retry
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('ScribaseClient — retry', () => {
|
|
it('retries on 503 up to maxRetries times', async () => {
|
|
let calls = 0;
|
|
const fetchFn: typeof fetch = async () => {
|
|
calls += 1;
|
|
return new Response(
|
|
JSON.stringify({ type: 'about:blank', title: 'Unavailable', status: 503, code: 'unavailable' }),
|
|
{ status: 503, headers: { 'content-type': 'application/json' } }
|
|
);
|
|
};
|
|
const client = new ScribaseClient({
|
|
baseUrl: 'https://api.example.com',
|
|
token: 'tok',
|
|
fetch: fetchFn,
|
|
maxRetries: 2,
|
|
retryBaseDelayMs: 0,
|
|
sleep: noSleep,
|
|
});
|
|
await assert.rejects(
|
|
() => client.send({ method: 'GET', path: '/v1/test' }),
|
|
ServiceUnavailableError
|
|
);
|
|
// 1 initial attempt + 2 retries
|
|
assert.equal(calls, 3);
|
|
});
|
|
|
|
it('does not retry on 404', async () => {
|
|
let calls = 0;
|
|
const fetchFn: typeof fetch = async () => {
|
|
calls += 1;
|
|
return new Response(
|
|
JSON.stringify({ type: 'about:blank', title: 'Not Found', status: 404, code: 'not_found' }),
|
|
{ status: 404, headers: { 'content-type': 'application/json' } }
|
|
);
|
|
};
|
|
const client = new ScribaseClient({
|
|
baseUrl: 'https://api.example.com',
|
|
token: 'tok',
|
|
fetch: fetchFn,
|
|
maxRetries: 3,
|
|
sleep: noSleep,
|
|
});
|
|
await assert.rejects(
|
|
() => client.send({ method: 'GET', path: '/v1/test' }),
|
|
NotFoundError
|
|
);
|
|
assert.equal(calls, 1);
|
|
});
|
|
|
|
it('retries on network errors', async () => {
|
|
let calls = 0;
|
|
const fetchFn: typeof fetch = async () => {
|
|
calls += 1;
|
|
throw new Error('ECONNRESET');
|
|
};
|
|
const client = new ScribaseClient({
|
|
baseUrl: 'https://api.example.com',
|
|
token: 'tok',
|
|
fetch: fetchFn,
|
|
maxRetries: 1,
|
|
retryBaseDelayMs: 0,
|
|
sleep: noSleep,
|
|
});
|
|
await assert.rejects(
|
|
() => client.send({ method: 'GET', path: '/v1/test' }),
|
|
NetworkError
|
|
);
|
|
assert.equal(calls, 2);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// AbortSignal / cancellation
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('ScribaseClient — cancellation', () => {
|
|
it('propagates an already-aborted signal without retrying', async () => {
|
|
let calls = 0;
|
|
// The mock fetch honours the abort signal so the client propagation logic is exercised.
|
|
const fetchFn: typeof fetch = async (_url, init) => {
|
|
calls += 1;
|
|
const signal = init?.signal;
|
|
if (signal?.aborted) {
|
|
throw signal.reason as Error;
|
|
}
|
|
return new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } });
|
|
};
|
|
const controller = new AbortController();
|
|
controller.abort(new Error('cancelled'));
|
|
const client = makeClient(fetchFn, { maxRetries: 3 });
|
|
await assert.rejects(() =>
|
|
client.send({ method: 'GET', path: '/v1/test', signal: controller.signal })
|
|
);
|
|
// The abort should propagate before any retries are attempted.
|
|
assert.ok(calls <= 1);
|
|
});
|
|
});
|