Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ jobs:
- name: Publish to npm
env:
NPM_DIST_TAG: ${{ needs.validate.outputs.dist_tag }}
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npm publish --access public --provenance --tag "$NPM_DIST_TAG"

github-release:
Expand Down
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,6 @@ npm run check
local HTTP server. Their pinned source revision and checksums are recorded in
`contracts/source.json`; no live API or Python installation is needed.

Releases run automatically on matching `v*` tags after all checks pass. See
[release setup](https://github.com/energy-tracker/api-client-typescript/blob/main/docs/releasing.md) for the one-time npm configuration and commands.
To release, update the version in `package.json` and `package-lock.json`, merge
into `main`, then push the matching `v*` tag on the merged commit. GitHub Actions
publishes to npm through OIDC after all checks pass.
2 changes: 2 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,5 @@ for local or transport failures) and `apiMessage` (the server's message array).
`TimeoutError` represents a client timeout, `NetworkError` a transport failure.
Only each endpoint's exact success status is accepted. A caller-triggered abort
rejects with the original abort reason rather than an SDK error.
An unreadable HTTP error body keeps its status-specific error class, with the
body failure in `cause`. Invalid entries in the server's message array are ignored.
49 changes: 0 additions & 49 deletions docs/releasing.md

This file was deleted.

4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@energy-tracker/api-client",
"version": "1.0.0",
"version": "1.0.1",
"description": "Typed async client for the Energy Tracker public API",
"license": "MIT",
"author": "Stefan Nebel",
Expand Down
21 changes: 14 additions & 7 deletions src/transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,17 @@ function messages(data: unknown): string[] {
if (!data || typeof data !== 'object') return [];
const value = (data as Record<string, unknown>).message;
if (typeof value === 'string') return [value];
return Array.isArray(value) ? value.map(String) : [];
return Array.isArray(value)
? value.filter((item): item is string => typeof item === 'string')
: [];
}
function httpError(response: Response, data: unknown, expected: number): EnergyTrackerAPIError {
const options = { statusCode: response.status, apiMessage: messages(data) };
function httpError(
response: Response,
data: unknown,
expected: number,
cause?: unknown,
): EnergyTrackerAPIError {
const options = { statusCode: response.status, apiMessage: messages(data), cause };
switch (response.status) {
case 400:
return new ValidationError('Bad Request', options);
Expand Down Expand Up @@ -142,12 +149,12 @@ export class Transport {
}
const response = await this.#fetch(url, init);
if (response.status !== request.status) {
const text = await response.text();
let data: unknown;
try {
data = JSON.parse(text);
} catch {
/* HTTP status takes priority over an invalid error body. */
data = JSON.parse(await response.text());
} catch (cause) {
// Keep the known HTTP error when its body is invalid or interrupted.
throw httpError(response, undefined, request.status, cause);
}
throw httpError(response, data, request.status);
}
Expand Down
183 changes: 149 additions & 34 deletions tests/client.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -103,23 +103,25 @@ test('network errors retain cause without HTTP status', async () => {
},
);
});
test('timeout covers streaming body after headers and does not retry', async (t) => {
let requests = 0;
const baseUrl = await serve(t, (req, res) => {
requests++;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write('[');
for (const status of [200, 429, 503]) {
test(`timeout covers streaming HTTP ${status} body and does not retry`, async (t) => {
let requests = 0;
const baseUrl = await serve(t, (req, res) => {
requests++;
res.writeHead(status, { 'Content-Type': 'application/json' });
res.write('[');
});
await assert.rejects(
() => client({ baseUrl, timeout: 0.2 }).devices.listStandard(),
(error) => {
assert.ok(error instanceof api.TimeoutError);
assert.equal(error.statusCode, null);
return true;
},
);
assert.equal(requests, 1);
});
await assert.rejects(
() => client({ baseUrl, timeout: 0.2 }).devices.listStandard(),
(error) => {
assert.ok(error instanceof api.TimeoutError);
assert.equal(error.statusCode, null);
return true;
},
);
assert.equal(requests, 1);
});
}
test('calculations use their own timeout', async (t) => {
const baseUrl = await serve(t, async (req, res) => {
await delay(100);
Expand All @@ -133,29 +135,142 @@ test('calculations use their own timeout', async (t) => {
[],
);
});
test('caller cancellation is preserved, including before starting a request', async (t) => {
const controller = new AbortController();
const reason = new Error('Caller cancelled');
const baseUrl = await serve(t, (req, res) => {
res.writeHead(200);
res.write('[');
controller.abort(reason);
for (const status of [200, 503]) {
test(`caller cancellation is preserved for HTTP ${status} and before requests`, async (t) => {
const controller = new AbortController();
const reason = new Error('Caller cancelled');
const baseUrl = await serve(t, (req, res) => {
res.writeHead(status);
res.write('[');
});
const apiClient = client({
baseUrl,
fetch: async (...args) => {
const response = await fetch(...args);
setImmediate(() => controller.abort(reason));
return response;
},
});
await assert.rejects(
() => apiClient.devices.listStandard({ signal: controller.signal }),
(error) => error === reason,
);
let calls = 0;
await assert.rejects(
() =>
client({
fetch: async () => {
calls++;
},
}).devices.listVirtual({ signal: controller.signal }),
(error) => error === reason,
);
assert.equal(calls, 0);
});
}

for (const [status, ErrorType] of [
[400, api.ValidationError],
[401, api.AuthenticationError],
[403, api.ForbiddenError],
[404, api.ResourceNotFoundError],
[409, api.ConflictError],
[429, api.RateLimitError],
[503, api.ServiceUnavailableError],
[500, api.EnergyTrackerAPIError],
[201, api.EnergyTrackerAPIError],
]) {
test(`HTTP ${status} survives a failed response body`, async () => {
const cause = new Error('Response stream disconnected');
const response = new Response(
new ReadableStream({
start(stream) {
stream.error(cause);
},
}),
{
status,
headers: { 'Retry-After': '20' },
},
);
await assert.rejects(
() => client({ fetch: async () => response }).devices.listStandard(),
(error) => {
assert.equal(error.constructor, ErrorType);
assert.equal(error.statusCode, status);
assert.equal(error.cause, cause);
assert.deepEqual(error.apiMessage, []);
if (status === 429) assert.equal(error.retryAfter, 20);
return true;
},
);
});
}

test('invalid message entries cannot mask HTTP status or retry-after', async (t) => {
const baseUrl = await serve(t, (req, res) =>
res
.writeHead(429, {
'Content-Type': 'application/json',
'Retry-After': '20',
})
.end(
JSON.stringify({
message: ['Rate limited', { toString: null }, null, 42, false, ['nested']],
}),
),
);
await assert.rejects(
() => client({ baseUrl }).devices.listStandard({ signal: controller.signal }),
(error) => error === reason,
() => client({ baseUrl }).devices.listStandard(),
(error) => {
assert.ok(error instanceof api.RateLimitError);
assert.equal(error.statusCode, 429);
assert.equal(error.retryAfter, 20);
assert.deepEqual(error.apiMessage, ['Rate limited']);
return true;
},
);
});

test('an interrupted success body remains a network error', async () => {
const cause = new Error('Response stream disconnected');
const response = new Response(
new ReadableStream({
start(stream) {
stream.error(cause);
},
}),
{
status: 200,
headers: { 'Content-Type': 'application/json' },
},
);
let calls = 0;
await assert.rejects(
() =>
client({
fetch: async () => {
calls++;
},
}).devices.listVirtual({ signal: controller.signal }),
(error) => error === reason,
() => client({ fetch: async () => response }).devices.listStandard(),
(error) => {
assert.ok(error instanceof api.NetworkError);
assert.equal(error.statusCode, null);
assert.equal(error.cause, cause);
return true;
},
);
});

test('a truncated HTTP error from the server keeps its status', async (t) => {
const baseUrl = await serve(t, (req, res) => {
res.writeHead(503, { 'Content-Type': 'application/json', 'Content-Length': '1000' });
res.write('{"message":');
setTimeout(() => res.destroy(), 20);
});
await assert.rejects(
() => client({ baseUrl }).devices.listStandard(),
(error) => {
assert.ok(error instanceof api.ServiceUnavailableError);
assert.equal(error.statusCode, 503);
assert.ok(error.cause instanceof Error);
return true;
},
);
assert.equal(calls, 0);
});
const point = {
date: '2026-09-01T00:00:00Z',
Expand Down