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
10 changes: 10 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ jobs:
exit 1
fi

TAG_COMMIT=$(git rev-list -n 1 "$TAG" 2>/dev/null || echo "")
HEAD_COMMIT=$(git rev-parse HEAD)

if [[ "$TAG_COMMIT" != "$HEAD_COMMIT" ]]; then
echo "❌ ERROR: Tag $TAG does not point to HEAD"
echo " Tag points to: $TAG_COMMIT"
echo " HEAD is: $HEAD_COMMIT"
exit 1
fi
Comment on lines +56 to +64

echo "✅ package.json version: $PKG_VERSION"
echo "✅ Tag $TAG exists in repo"
echo "TAG_VERSION=$TAG" >> $GITHUB_ENV
Expand Down
7 changes: 5 additions & 2 deletions .github/workflows/release-check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ jobs:
run: npm ci

- name: Audit
run: npm audit --production
run: npm audit --omit=dev

- name: Format
run: npm run format
Expand All @@ -54,6 +54,7 @@ jobs:
run: npm run build

- name: SonarCloud Scan
if: ${{ github.event.pull_request.head.repo.full_name == github.repository }}
uses: SonarSource/sonarqube-scan-action@v6
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
Expand All @@ -63,10 +64,12 @@ jobs:
-Dsonar.organization=${{ env.SONAR_ORGANIZATION }}
-Dsonar.projectKey=${{ env.SONAR_PROJECT_KEY }}
-Dsonar.sources=src
-Dsonar.tests=test
-Dsonar.tests=src
-Dsonar.test.inclusions=src/**/*.test.ts,src/**/*.test.tsx,src/**/*.spec.ts,src/__tests__/**
-Dsonar.javascript.lcov.reportPaths=coverage/lcov.info

- name: SonarCloud Quality Gate
if: ${{ github.event.pull_request.head.repo.full_name == github.repository }}
uses: SonarSource/sonarqube-quality-gate-action@v1
timeout-minutes: 10
env:
Expand Down
88 changes: 44 additions & 44 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
Expand Up @@ -86,6 +86,6 @@
"node": ">=20"
},
"dependencies": {
"axios": "^1.14.0"
"axios": "^1.15.0"
}
}
21 changes: 12 additions & 9 deletions src/api/createApiClient.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { createApiClient } from './createApiClient';
import { ApiError } from './ApiError';
import type { ApiClient } from './createApiClient.types';
Expand Down Expand Up @@ -487,16 +487,21 @@ describe('createApiClient', () => {

describe('getToken auth interceptor', () => {
it('should inject Authorization header when getToken returns a value', async () => {
const capturedHeaders: Record<string, string>[] = [];
const tokenClient = createApiClient({
baseURL: 'https://api.example.com',
getToken: () => 'my-token-123',
});
tokenClient.addRequestInterceptor((req) => {
capturedHeaders.push({ ...req.headers });
return req;
});
mockState.setResponse('get', '/secure', { data: 'secret' });

await tokenClient.get('/secure');

const requestCall = mockState.instance.get.mock.calls[0];
expect(requestCall).toBeDefined();
expect(capturedHeaders[0]).toBeDefined();
expect(capturedHeaders[0]['Authorization']).toBe('Bearer my-token-123');
});

it('should skip Authorization header when getToken returns null', async () => {
Expand Down Expand Up @@ -553,6 +558,10 @@ describe('createApiClient', () => {
// ─── AC6 + AC7 + AC8: Retry with exponential backoff ─────────────

describe('retry with exponential backoff', () => {
afterEach(() => {
vi.unstubAllGlobals();
});

it('should retry retryable status codes up to configured retry count', async () => {
let callCount = 0;
const retryClient = createApiClient({
Expand Down Expand Up @@ -604,8 +613,6 @@ describe('createApiClient', () => {
const result = await retryClient.get('/backoff');
expect(result).toEqual({ ok: true });
expect(delays).toEqual([500, 1000, 2000]);

vi.unstubAllGlobals();
});

it('should verify second delay is approximately 2x the first', async () => {
Expand Down Expand Up @@ -633,8 +640,6 @@ describe('createApiClient', () => {

await retryClient.get('/timing');
expect(delays[1]).toBe(delays[0] * 2);

vi.unstubAllGlobals();
});

it('should not retry on 400', async () => {
Expand Down Expand Up @@ -789,8 +794,6 @@ describe('createApiClient', () => {

await retryClient.get('/default-delay');
expect(delays[0]).toBe(500);

vi.unstubAllGlobals();
});
});
});
32 changes: 29 additions & 3 deletions src/api/createApiClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,39 @@ function delay(ms: number): Promise<void> {
});
}

function normalizeHeaders(headers: unknown): Record<string, string> {
if (!headers || typeof headers !== 'object') {
return {};
}

const source =
'toJSON' in headers && typeof (headers as Record<string, unknown>).toJSON === 'function'
? (headers as { toJSON(): Record<string, unknown> }).toJSON()
: headers;

if (!source || typeof source !== 'object') {
return {};
}

const normalized: Record<string, string> = {};
for (const [key, value] of Object.entries(source)) {
if (Array.isArray(value)) {
normalized[key] = value.map((item) => String(item)).join(', ');
} else if (value != null) {
Comment on lines +53 to +57
normalized[key] = String(value);
}
}
return normalized;
}
Comment on lines +39 to +62

function toInterceptedResponse(axiosRes: {
status: number;
headers: unknown;
data: unknown;
}): InterceptedResponse {
const raw = axiosRes.headers as Record<string, string> | undefined;
return {
status: axiosRes.status,
headers: raw ?? {},
headers: normalizeHeaders(axiosRes.headers),
data: axiosRes.data,
};
}
Expand Down Expand Up @@ -78,7 +102,7 @@ export function createApiClient(config: ApiClientConfig): ApiClient {
let intercepted: InterceptedRequest = {
url: axiosConfig.url ?? '',
method: (axiosConfig.method ?? 'get').toLowerCase(),
headers: (axiosConfig.headers as unknown as Record<string, string>) ?? {},
headers: normalizeHeaders(axiosConfig.headers),
params: axiosConfig.params as Record<string, unknown> | undefined,
data: axiosConfig.data as unknown,
};
Expand All @@ -104,6 +128,8 @@ export function createApiClient(config: ApiClientConfig): ApiClient {
intercepted = interceptor(intercepted);
}

axiosResponse.status = intercepted.status;
axiosResponse.headers = intercepted.headers as typeof axiosResponse.headers;
axiosResponse.data = intercepted.data;
return axiosResponse;
},
Expand Down
4 changes: 3 additions & 1 deletion src/api/createApiClient.types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { ApiError } from './ApiError';

export interface ApiClientConfig {
baseURL: string;
timeout?: number;
Expand Down Expand Up @@ -29,7 +31,7 @@ export interface InterceptedResponse {

export type RequestInterceptor = (request: InterceptedRequest) => InterceptedRequest;
export type ResponseInterceptor = (response: InterceptedResponse) => InterceptedResponse;
export type ErrorInterceptor = (error: Error) => void;
export type ErrorInterceptor = (error: ApiError) => void;

export interface ApiClient {
get<T>(url: string, config?: RequestConfig): Promise<T>;
Expand Down
Loading