diff --git a/sdk/analytics.ts b/sdk/analytics.ts index b601cd6..a8420d6 100644 --- a/sdk/analytics.ts +++ b/sdk/analytics.ts @@ -1,6 +1,6 @@ import { pino, Logger } from 'pino'; -import { Fetch } from './types.js'; -import { FlagsmithConfig } from './types.js'; +import { Dispatcher } from 'undici-types'; +import { Fetch, FlagsmithConfig } from './types.js'; import { getUserAgent } from './utils.js'; export const ANALYTICS_ENDPOINT = './analytics/flags/'; @@ -22,6 +22,10 @@ export interface AnalyticsProcessorOptions { logger?: Logger; /** Custom {@link fetch} implementation to use for API requests. **/ fetch?: Fetch; + /** A custom {@link Dispatcher} to use for API requests. **/ + agent?: Dispatcher; + /** Custom headers to send with API requests. **/ + customHeaders?: FlagsmithConfig['customHeaders']; /** @deprecated Use {@link analyticsUrl} instead. **/ baseApiUrl?: string; @@ -45,6 +49,8 @@ export class AnalyticsProcessor { private logger: Logger; private currentFlush: ReturnType | undefined; private customFetch: Fetch; + private agent?: Dispatcher; + private customHeaders?: FlagsmithConfig['customHeaders']; constructor(data: AnalyticsProcessorOptions) { this.analyticsUrl = data.analyticsUrl || data.baseApiUrl + ANALYTICS_ENDPOINT; @@ -54,6 +60,8 @@ export class AnalyticsProcessor { this.requestTimeoutMs = data.requestTimeoutMs || this.requestTimeoutMs; this.logger = data.logger || pino(); this.customFetch = data.fetch ?? fetch; + this.agent = data.agent; + this.customHeaders = data.customHeaders; } /** * Try to flush pending collected data to the Flagsmith analytics API. @@ -64,16 +72,25 @@ export class AnalyticsProcessor { } try { - this.currentFlush = this.customFetch(this.analyticsUrl, { + const customHeaders = new Headers(this.customHeaders); + customHeaders.delete('Content-Type'); + customHeaders.delete('X-Environment-Key'); + customHeaders.delete('User-Agent'); + + // built-in RequestInit type doesn't have dispatcher/agent + const init: RequestInit & { dispatcher?: Dispatcher } = { + dispatcher: this.agent, method: 'POST', body: JSON.stringify(this.analyticsData), signal: AbortSignal.timeout(this.requestTimeoutMs), headers: { + ...Object.fromEntries(customHeaders), 'Content-Type': 'application/json', 'X-Environment-Key': this.environmentKey, 'User-Agent': getUserAgent() } - }); + }; + this.currentFlush = this.customFetch(this.analyticsUrl, init); await this.currentFlush; } catch (error) { // We don't want failing to write analytics to cause any exceptions in the main diff --git a/sdk/index.ts b/sdk/index.ts index 95ee1a6..f079e2b 100644 --- a/sdk/index.ts +++ b/sdk/index.ts @@ -183,7 +183,10 @@ export class Flagsmith { environmentKey: this.environmentKey, analyticsUrl: this.analyticsUrl, requestTimeoutMs: this.requestTimeoutMs, - logger: this.logger + logger: this.logger, + fetch: this.customFetch, + agent: this.agent, + customHeaders: this.customHeaders }); } diff --git a/tests/sdk/analytics.test.ts b/tests/sdk/analytics.test.ts index 98b6ce3..c37f965 100644 --- a/tests/sdk/analytics.test.ts +++ b/tests/sdk/analytics.test.ts @@ -1,6 +1,7 @@ import { getUserAgent } from '../../sdk/utils.js'; import { fetch } from './fetchMock.js'; -import { analyticsProcessor } from './utils.js'; +import { analyticsProcessor, apiKey, flagsmith } from './utils.js'; +import { Dispatcher } from 'undici-types'; test('test_analytics_processor_track_feature_updates_analytics_data', () => { const aP = analyticsProcessor(); @@ -38,6 +39,40 @@ test('test_analytics_processor_flush_post_request_data_match_ananlytics_data', a ); }); +const customHeaders = { + 'X-Custom-Header': 'value', + 'x-environment-key': 'wrong-key', + 'content-type': 'text/plain', + 'user-agent': 'wrong-agent' +}; + +test.each<{ format: string; headers: HeadersInit }>([ + { format: 'record', headers: customHeaders }, + { format: 'Headers', headers: new Headers(customHeaders) }, + { format: 'tuples', headers: Object.entries(customHeaders) } +])('analytics uses the client transport and $format headers', async ({ headers }) => { + const agent = {} as Dispatcher; + const customFetch = vi.fn((url, options) => fetch(url.toString(), options)); + const client = flagsmith({ + enableAnalytics: true, + fetch: customFetch, + agent, + customHeaders: headers + }); + const flags = await client.getEnvironmentFlags(); + flags.getFlag('some_feature'); + + await client['analyticsProcessor']!.flush(); + + const request = customFetch.mock.calls.find(([url]) => url.includes('analytics/flags/'))?.[1]; + expect(request?.dispatcher).toBe(agent); + const postedHeaders = new Headers(request?.headers); + expect(postedHeaders.get('x-custom-header')).toBe('value'); + expect(postedHeaders.get('x-environment-key')).toBe(apiKey()); + expect(postedHeaders.get('content-type')).toBe('application/json'); + expect(postedHeaders.get('user-agent')).toBe(getUserAgent()); +}); + vi.useFakeTimers(); test('test_analytics_processor_flush_post_request_data_match_ananlytics_data_test', async () => { const aP = analyticsProcessor();