diff --git a/packages/sdk/electron/__tests__/ElectronClient.mainProcess.test.ts b/packages/sdk/electron/__tests__/ElectronClient.mainProcess.test.ts index 5b6216173e..8b63769387 100644 --- a/packages/sdk/electron/__tests__/ElectronClient.mainProcess.test.ts +++ b/packages/sdk/electron/__tests__/ElectronClient.mainProcess.test.ts @@ -97,11 +97,23 @@ jest.mock('../src/platform/ElectronPlatform', () => ({ const clientSideId = 'client-side-id'; const DEFAULT_INITIAL_CONTEXT = { kind: 'user' as const, key: 'test-user' }; +// A client that stays open keeps its poll and flush timers, and jest cannot exit. +const openClients: { close(): Promise }[] = []; + +function closeAfterTest }>(client: T): T { + openClients.push(client); + return client; +} + beforeEach(() => { jest.clearAllMocks(); handlers.clear(); }); +afterEach(async () => { + await Promise.all(openClients.splice(0).map((client) => client.close())); +}); + describe('given an initialized ElectronClient with enableIPC: false', () => { const logger: LDLogger = { debug: jest.fn(), @@ -121,6 +133,10 @@ describe('given an initialized ElectronClient with enableIPC: false', () => { await client.start(); }); + afterAll(async () => { + await client.close(); + }); + it('does not register any IPC channels so ipcMain.on and ipcMain.handle are never called', () => { expect(mockOn).not.toHaveBeenCalled(); expect(mockHandle).not.toHaveBeenCalled(); @@ -195,12 +211,14 @@ describe('given an initialized ElectronClient with enableIPC: false and bootstra }; it('evaluates flags from bootstrap when called directly on the client', async () => { - const client = new ElectronClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { - initialConnectionMode: 'offline', - enableIPC: false, - logger, - diagnosticOptOut: true, - }); + const client = closeAfterTest( + new ElectronClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { + initialConnectionMode: 'offline', + enableIPC: false, + logger, + diagnosticOptOut: true, + }), + ); await client.start({ bootstrap: goodBootstrapData }); expect(client.variation('killswitch', false)).toBe(true); @@ -223,12 +241,14 @@ describe('enableIPC: false and close()', () => { }; it('does not register channels so close() does not remove any handlers', async () => { - const client = new ElectronClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { - initialConnectionMode: 'offline', - enableIPC: false, - logger, - diagnosticOptOut: true, - }); + const client = closeAfterTest( + new ElectronClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { + initialConnectionMode: 'offline', + enableIPC: false, + logger, + diagnosticOptOut: true, + }), + ); await client.start(); expect(mockOn).not.toHaveBeenCalled(); @@ -267,13 +287,15 @@ describe('given an initialized ElectronClient with enableIPC: false and polling' }, }); - const client = createClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { - initialConnectionMode: 'polling', - enableIPC: false, - logger, - diagnosticOptOut: true, - sendEvents: false, - }); + const client = closeAfterTest( + createClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { + initialConnectionMode: 'polling', + enableIPC: false, + logger, + diagnosticOptOut: true, + sendEvents: false, + }), + ); await client.start(); expect(client.boolVariation('on-off-flag', false)).toBe(true); @@ -319,13 +341,15 @@ describe('maxCachedContexts', () => { storage, }); - const client = createClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { - initialConnectionMode: 'polling', - enableIPC: false, - diagnosticOptOut: true, - sendEvents: false, - maxCachedContexts: 1, - }); + const client = closeAfterTest( + createClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { + initialConnectionMode: 'polling', + enableIPC: false, + diagnosticOptOut: true, + sendEvents: false, + maxCachedContexts: 1, + }), + ); await client.start(); // After start, context A's flags are cached. @@ -364,13 +388,15 @@ describe('maxCachedContexts', () => { storage, }); - const client = createClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { - initialConnectionMode: 'polling', - enableIPC: false, - diagnosticOptOut: true, - sendEvents: false, - maxCachedContexts: 0, - }); + const client = closeAfterTest( + createClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { + initialConnectionMode: 'polling', + enableIPC: false, + diagnosticOptOut: true, + sendEvents: false, + maxCachedContexts: 0, + }), + ); await client.start(); // Flags should still evaluate correctly from the network response @@ -412,13 +438,15 @@ describe('given an initialized ElectronClient with enableIPC: false and streamin }, }); - const client = createClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { - initialConnectionMode: 'streaming', - enableIPC: false, - logger, - diagnosticOptOut: true, - sendEvents: false, - }); + const client = closeAfterTest( + createClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { + initialConnectionMode: 'streaming', + enableIPC: false, + logger, + diagnosticOptOut: true, + sendEvents: false, + }), + ); await client.start(); expect(client.boolVariation('on-off-flag', false)).toBe(true); diff --git a/packages/sdk/electron/__tests__/platform/ElectronRequests.test.ts b/packages/sdk/electron/__tests__/platform/ElectronRequests.test.ts index e04792e0db..d3eaa733a3 100644 --- a/packages/sdk/electron/__tests__/platform/ElectronRequests.test.ts +++ b/packages/sdk/electron/__tests__/platform/ElectronRequests.test.ts @@ -1,6 +1,23 @@ import * as http from 'http'; import * as zlib from 'zlib'; +// electron.net isn't available outside a real Electron main process. net.fetch is a standard +// fetch over Chromium's stack, so Node's own fetch stands in for it. Both decode a compressed +// body and keep the origin's content-encoding header. +jest.mock('electron', () => ({ + app: { + isReady: jest.fn(() => true), + whenReady: jest.fn(() => Promise.resolve()), + }, + net: { + fetch: jest.fn((url: string, init: RequestInit) => globalThis.fetch(url, init)), + }, +})); + +// eslint-disable-next-line import/first +import { app as mockedElectronApp, net as mockedElectronNet } from 'electron'; + +// eslint-disable-next-line import/first import ElectronRequests from '../../src/platform/ElectronRequests'; const PORT = '3333'; @@ -52,6 +69,12 @@ beforeEach(() => { } else if ((req.url?.indexOf('404') || -1) >= 0) { res.statusCode = 404; res.end(); + } else if ((req.url?.indexOf('slow') || -1) >= 0) { + setTimeout(() => { + if (!res.destroyed) { + res.end(TEXT_RESPONSE); + } + }, 200).unref(); } else if ((req.url?.indexOf('reset') || -1) >= 0) { res.statusCode = 200; res.flushHeaders(); @@ -77,7 +100,7 @@ afterEach( }), ); -describe('given a default instance of NodeRequests', () => { +describe('given a default instance of ElectronRequests', () => { const requests = new ElectronRequests(); it('can make a basic get request', async () => { const res = await requests.fetch(`http://localhost:${PORT}`); @@ -179,9 +202,182 @@ describe('given a default instance of NodeRequests', () => { expect(serverResult.method).toEqual('GET'); expect(serverResult.body).toEqual(''); }); + + it('rejects with a timeout error and aborts the underlying request', async () => { + await expect(requests.fetch(`http://localhost:${PORT}/slow`, { timeout: 20 })).rejects.toThrow( + 'Request timed out', + ); + }); + + it('does not time out when the response arrives before the deadline', async () => { + const res = await requests.fetch(`http://localhost:${PORT}`, { timeout: 5000 }); + expect(res.status).toEqual(200); + }); + + it('does not follow redirects, omits ambient session credentials, and bypasses the shared cache', async () => { + await requests.fetch(`http://localhost:${PORT}`); + expect(mockedElectronNet.fetch).toHaveBeenLastCalledWith( + `http://localhost:${PORT}`, + expect.objectContaining({ + redirect: 'error', + credentials: 'omit', + cache: 'no-store', + }), + ); + }); +}); + +describe('given a streaming server', () => { + // A long-lived server on its own port. Restarting a server per test leaves undici's pooled + // connections pointing at the old one, which resets the next streaming request. + const STREAM_PORT = 3334; + const SSE_CHUNK = 'event: put\ndata: {"hello":"world"}\n\n'; + const requests = new ElectronRequests(); + let streamServer: http.Server; + let streamRequest: Promise; + let streamResolve: (value: TestRequestData) => void; + + beforeAll(async () => { + streamServer = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on('data', (chunk: Buffer) => chunks.push(chunk)); + req.on('end', () => { + if (req.url === '/redirect') { + res.writeHead(307, { Location: '/stream' }); + res.end(); + return; + } + streamResolve({ + method: req.method, + body: Buffer.concat(chunks).toString(), + headers: req.headers, + }); + // Holds the connection open after the first event, like an SSE stream. + res.writeHead(200, { 'Content-Type': 'text/event-stream' }); + res.write(SSE_CHUNK); + }); + }); + await new Promise((res) => { + streamServer.listen(STREAM_PORT, res); + }); + }); + + beforeEach(() => { + streamRequest = new Promise((res) => { + streamResolve = res; + }); + }); + + afterAll( + async () => + new Promise((resolveClose) => { + streamServer.close(resolveClose); + streamServer.closeAllConnections(); + }), + ); + + it('delivers body chunks before the stream ends', async () => { + const res = await requests.fetch(`http://localhost:${STREAM_PORT}/stream`, { + streaming: true, + }); + expect(res.status).toEqual(200); + expect(res.headers.get('content-type')).toEqual('text/event-stream'); + + const reader = res.body!.getReader(); + const first = await reader.read(); + expect(first.done).toBe(false); + expect(Buffer.from(first.value!).toString()).toEqual(SSE_CHUNK); + await reader.cancel?.(); + }); + + it('uses net.fetch with the method, headers, body, and signal', async () => { + const controller = new AbortController(); + const res = await requests.fetch(`http://localhost:${STREAM_PORT}/stream`, { + method: 'REPORT', + headers: { 'Sample-Header': 'Some header value' }, + body: '{"key":"user"}', + signal: controller.signal, + timeout: 1, + streaming: true, + }); + expect(mockedElectronNet.fetch).toHaveBeenLastCalledWith( + `http://localhost:${STREAM_PORT}/stream`, + { + method: 'REPORT', + headers: { 'Sample-Header': 'Some header value', 'accept-encoding': 'identity' }, + body: '{"key":"user"}', + signal: controller.signal, + redirect: 'follow', + credentials: 'omit', + cache: 'no-store', + }, + ); + const serverResult = await streamRequest; + expect(serverResult.method).toEqual('REPORT'); + expect(serverResult.body).toEqual('{"key":"user"}'); + expect(serverResult.headers['sample-header']).toEqual('Some header value'); + expect(serverResult.headers['accept-encoding']).toEqual('identity'); + controller.abort(); + await expect(res.body!.getReader().read()).rejects.toThrow('This operation was aborted'); + }); + + it('follows a redirect', async () => { + const res = await requests.fetch(`http://localhost:${STREAM_PORT}/redirect`, { + streaming: true, + }); + expect(res.status).toEqual(200); + const reader = res.body!.getReader(); + const first = await reader.read(); + expect(Buffer.from(first.value!).toString()).toEqual(SSE_CHUNK); + await reader.cancel?.(); + }); + + it('waits for whenReady() before issuing the request', async () => { + (mockedElectronNet.fetch as jest.Mock).mockClear(); + (mockedElectronApp.isReady as jest.Mock).mockReturnValueOnce(false); + let readyResolve: () => void = () => {}; + (mockedElectronApp.whenReady as jest.Mock).mockReturnValueOnce( + new Promise((res) => { + readyResolve = res; + }), + ); + + const fetchPromise = requests.fetch(`http://localhost:${STREAM_PORT}/stream`, { + streaming: true, + }); + await Promise.resolve(); + expect(mockedElectronNet.fetch).not.toHaveBeenCalled(); + + readyResolve(); + const res = await fetchPromise; + expect(res.status).toEqual(200); + await res.body!.cancel?.(); + }); + + it('delivers server-sent events through createEventSource', async () => { + const es = requests.createEventSource(`http://localhost:${STREAM_PORT}/stream`, { + headers: { authorization: 'sdk-key' }, + errorFilter: () => true, + initialRetryDelayMillis: 1000, + readTimeoutMillis: 0, + retryResetIntervalMillis: 60000, + }); + try { + const data = await new Promise((resolveEvent) => { + es.addEventListener('put', (event) => resolveEvent(event?.data)); + }); + expect(JSON.parse(data)).toEqual({ hello: 'world' }); + expect(mockedElectronNet.fetch).toHaveBeenCalled(); + const serverResult = await streamRequest; + expect(serverResult.headers.authorization).toEqual('sdk-key'); + expect(serverResult.headers.accept).toEqual('text/event-stream'); + } finally { + es.close(); + } + }); }); -describe('given an instance of NodeRequests with enableEventCompression turned on', () => { +describe('given an instance of ElectronRequests with enableEventCompression turned on', () => { const requests = new ElectronRequests(true); it('can make a basic post with compressBodyIfPossible enabled', async () => { await requests.fetch(`http://localhost:${PORT}`, { @@ -207,3 +403,41 @@ describe('given an instance of NodeRequests with enableEventCompression turned o expect(serverResult.body).toEqual('BODY TEXT'); }); }); + +describe('given the app is not ready yet', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + afterEach(() => { + (mockedElectronApp.isReady as jest.Mock).mockReturnValue(true); + }); + + it('waits for whenReady() before issuing the request, then proceeds', async () => { + (mockedElectronApp.isReady as jest.Mock).mockReturnValue(false); + let readyResolve: () => void = () => {}; + (mockedElectronApp.whenReady as jest.Mock).mockReturnValue( + new Promise((res) => { + readyResolve = res; + }), + ); + + const requests = new ElectronRequests(); + const fetchPromise = requests.fetch(`http://localhost:${PORT}`); + + expect(mockedElectronNet.fetch).not.toHaveBeenCalled(); + + readyResolve(); + const res = await fetchPromise; + + expect(res.status).toEqual(200); + expect(mockedElectronNet.fetch).toHaveBeenCalled(); + }); + + it('does not call whenReady() when the app is already ready', async () => { + const requests = new ElectronRequests(); + await requests.fetch(`http://localhost:${PORT}`); + + expect(mockedElectronApp.whenReady).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/sdk/electron/__tests__/platform/HeaderWrapper.test.ts b/packages/sdk/electron/__tests__/platform/HeaderWrapper.test.ts deleted file mode 100644 index d2c89ae6b9..0000000000 --- a/packages/sdk/electron/__tests__/platform/HeaderWrapper.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import * as http from 'http'; - -import HeaderWrapper from '../../src/platform/HeaderWrapper'; - -describe('given header values', () => { - const headers: http.IncomingHttpHeaders = { - accept: 'anything', - 'some-header': 'some-value', - 'some-array': ['a', 'b'], - }; - const wrapper = new HeaderWrapper(headers); - - it('can get a single value header', () => { - expect(wrapper.get('accept')).toEqual('anything'); - }); - - it('can get an array value header', () => { - expect(wrapper.get('some-array')).toEqual('a, b'); - }); - - it('can get the entries', () => { - const flat: Array<[string, string]> = []; - for (const entry of wrapper.entries()) { - flat.push(entry); - } - expect(flat).toEqual([ - ['accept', 'anything'], - ['some-header', 'some-value'], - ['some-array', 'a, b'], - ]); - }); - - it('can check if a value is present', () => { - expect(wrapper.has('accept')).toBeTruthy(); - expect(wrapper.has('potato')).toBeFalsy(); - }); - - it('can key the keys', () => { - const keys: string[] = []; - for (const key of wrapper.keys()) { - keys.push(key); - } - expect(keys).toEqual(['accept', 'some-header', 'some-array']); - }); - - it('can key the values', () => { - const values: string[] = []; - for (const value of wrapper.values()) { - values.push(value); - } - expect(values).toEqual(['anything', 'some-value', 'a, b']); - }); -}); diff --git a/packages/sdk/electron/package.json b/packages/sdk/electron/package.json index dd0770ba03..aa23b6898d 100644 --- a/packages/sdk/electron/package.json +++ b/packages/sdk/electron/package.json @@ -65,8 +65,8 @@ "electron": ">=34.5.6" }, "dependencies": { - "@launchdarkly/js-client-sdk-common": "workspace:^", - "launchdarkly-eventsource": "2.3.0" + "@launchdarkly/eventsource": "0.2.5", + "@launchdarkly/js-client-sdk-common": "workspace:^" }, "devDependencies": { "@types/jest": "^29.4.0", diff --git a/packages/sdk/electron/src/platform/ElectronRequests.ts b/packages/sdk/electron/src/platform/ElectronRequests.ts index 18a3fd7712..82b7156f89 100644 --- a/packages/sdk/electron/src/platform/ElectronRequests.ts +++ b/packages/sdk/electron/src/platform/ElectronRequests.ts @@ -1,15 +1,10 @@ -import * as http from 'http'; -import * as https from 'https'; -// No types for the event source. -// @ts-ignore -import { EventSource as LDEventSource } from 'launchdarkly-eventsource'; +import { app, net } from 'electron'; import { promisify } from 'util'; import * as zlib from 'zlib'; +import { createEventSource } from '@launchdarkly/eventsource'; import { EventSourceCapabilities, platform } from '@launchdarkly/js-client-sdk-common'; -import ElectronResponse from './ElectronResponse'; - const gzip = promisify(zlib.gzip); export default class ElectronRequests implements platform.Requests { @@ -19,15 +14,26 @@ export default class ElectronRequests implements platform.Requests { this._enableBodyCompression = !!enableEventCompression; } + /** + * Uses Electron's `net` module (Chromium's networking stack) for streaming, polling, + * analytics, and diagnostic requests. The `net` module is only usable once Electron's `ready` + * event has fired. This method waits for that event, so callers do not have to. + * + * https://www.electronjs.org/docs/latest/api/net + */ async fetch(url: string, options: platform.Options = {}): Promise { - const isSecure = url.startsWith('https://'); - const impl = isSecure ? https : http; + if (!app.isReady()) { + await app.whenReady(); + } + + if (options.streaming) { + return this._streamingFetch(url, options); + } const headers = { ...options.headers }; - let bodyData: string | Buffer | undefined = options.body; + let bodyData: string | Uint8Array | undefined = options.body; // For get requests we are going to automatically support compressed responses. - // Note this does not affect SSE as the event source is not using this fetch implementation. if (options.method?.toLowerCase() === 'get') { headers['accept-encoding'] = 'gzip'; } @@ -41,29 +47,67 @@ export default class ElectronRequests implements platform.Requests { options.body ) { headers['content-encoding'] = 'gzip'; - bodyData = await gzip(Buffer.from(options.body, 'utf8')); + // The net.fetch body type accepts only a view backed by an ArrayBuffer. A Buffer has + // the wider ArrayBufferLike type, so copy it into a plain Uint8Array. + bodyData = new Uint8Array(await gzip(Buffer.from(options.body, 'utf8'))); } - return new Promise((resolve, reject) => { - const req = impl.request( - url, - { - timeout: options.timeout, - headers, - method: options.method, - }, - (res) => resolve(new ElectronResponse(res)), - ); - - if (bodyData) { - req.write(bodyData); - } + // net.fetch applies no timeout. This timer limits only the wait for the response + // headers. It stops when the headers arrive, so it does not limit the body read. + const controller = new AbortController(); + let timedOut = false; + let timeoutHandle: ReturnType | undefined; + if (options.timeout && options.timeout > 0) { + timeoutHandle = setTimeout(() => { + timedOut = true; + controller.abort(); + }, options.timeout); + } - req.on('error', (err) => { - reject(err); + try { + return await net.fetch(url, { + method: options.method, + headers, + body: bodyData, + signal: controller.signal, + // A redirect fails the request, so the SDK key never follows it to another host. + // Ambient session credentials stay off. Responses never come from, or go into, + // the app's shared HTTP cache. + redirect: 'error', + credentials: 'omit', + cache: 'no-store', }); + } catch (err) { + if (timedOut) { + throw new Error('Request timed out'); + } + throw err; + } finally { + clearTimeout(timeoutHandle); + } + } - req.end(); + /** + * Sends a streaming request. `net.fetch` returns a standard response whose body + * streams, and it rejects a pending read when the signal aborts. It applies no timeout; the + * caller owns the read timeout. It asks for an uncompressed body, so that a proxy + * does not hold events back in a compression buffer. + * + * Unlike `fetch`, this follows redirects. `net.fetch` cannot hand a redirect back to the + * caller (`redirect: 'manual'` cancels the request), and the stream must survive a + * redirect. Chromium follows 301, 302, 303, 307 and 308, up to 20 hops. It keeps the + * request headers on each hop, the Authorization header included, also to another + * origin. A 303 changes the method to GET and drops the body. + */ + private _streamingFetch(url: string, options: platform.Options): Promise { + return net.fetch(url, { + method: options.method, + headers: { ...options.headers, 'accept-encoding': 'identity' }, + body: options.body, + signal: options.signal, + redirect: 'follow', + credentials: 'omit', + cache: 'no-store', }); } @@ -71,12 +115,12 @@ export default class ElectronRequests implements platform.Requests { url: string, eventSourceInitDict: platform.EventSourceInitDict, ): platform.EventSource { - const expandedOptions = { + return createEventSource(url, { ...eventSourceInitDict, maxBackoffMillis: 30 * 1000, jitterRatio: 0.5, - }; - return new LDEventSource(url, expandedOptions); + fetch: (fetchUrl, init) => this.fetch(fetchUrl, { ...init, streaming: true }), + }); } getEventSourceCapabilities(): EventSourceCapabilities { diff --git a/packages/sdk/electron/src/platform/ElectronResponse.ts b/packages/sdk/electron/src/platform/ElectronResponse.ts deleted file mode 100644 index d348d06157..0000000000 --- a/packages/sdk/electron/src/platform/ElectronResponse.ts +++ /dev/null @@ -1,76 +0,0 @@ -import * as http from 'http'; -import { pipeline, Writable } from 'stream'; -import * as zlib from 'zlib'; - -import { platform } from '@launchdarkly/js-client-sdk-common'; - -import HeaderWrapper from './HeaderWrapper'; - -export default class ElectronResponse implements platform.Response { - incomingMessage: http.IncomingMessage; - - chunks: any[] = []; - - memoryStream: Writable = new Writable({ - decodeStrings: true, - write: (chunk, _enc, next) => { - this.chunks.push(chunk); - next(); - }, - }); - - promise: Promise; - - headers: platform.Headers; - - status: number; - - listened: boolean = false; - rejection?: Error; - - constructor(res: http.IncomingMessage) { - this.headers = new HeaderWrapper(res.headers); - // Status code is optionally typed, but will always be present for this - // use case. - this.status = res.statusCode || 0; - this.incomingMessage = res; - - this.promise = new Promise((resolve, reject) => { - // Called on error or completion of the pipeline. - const pipelineCallback = (err: any) => { - if (err) { - this.rejection = err; - if (this.listened) { - reject(err); - } - } - return resolve(Buffer.concat(this.chunks).toString()); - }; - switch (res.headers['content-encoding']) { - case 'gzip': - pipeline(res, zlib.createGunzip(), this.memoryStream, pipelineCallback); - break; - default: - pipeline(res, this.memoryStream, pipelineCallback); - break; - } - }); - } - - private async _wrappedWait(): Promise { - this.listened = true; - if (this.rejection) { - throw this.rejection; - } - return this.promise; - } - - text(): Promise { - return this._wrappedWait(); - } - - async json(): Promise { - const stringValue = await this._wrappedWait(); - return JSON.parse(stringValue); - } -} diff --git a/packages/sdk/electron/src/platform/HeaderWrapper.ts b/packages/sdk/electron/src/platform/HeaderWrapper.ts deleted file mode 100644 index 9c447c2a8f..0000000000 --- a/packages/sdk/electron/src/platform/HeaderWrapper.ts +++ /dev/null @@ -1,58 +0,0 @@ -import * as http from 'http'; - -import { platform } from '@launchdarkly/js-client-sdk-common'; - -/** - * Wraps the headers to match those used by fetch APIs. - * @internal - */ -export default class HeaderWrapper implements platform.Headers { - private _headers: http.IncomingHttpHeaders; - - constructor(headers: http.IncomingHttpHeaders) { - this._headers = headers; - } - - private _headerVal(name: string) { - const val = this._headers[name]; - if (val === undefined || val === null) { - return null; - } - if (Array.isArray(val)) { - return val.join(', '); - } - return val; - } - - get(name: string): string | null { - return this._headerVal(name); - } - - keys(): Iterable { - return Object.keys(this._headers); - } - - // We want to use generators here for the simplicity of maintaining - // this interface. Also they aren't expected to be high frequency usage. - *values(): Iterable { - for (const key of this.keys()) { - const val = this.get(key); - if (val !== null) { - yield val; - } - } - } - - *entries(): Iterable<[string, string]> { - for (const key of this.keys()) { - const val = this.get(key); - if (val !== null) { - yield [key, val]; - } - } - } - - has(name: string): boolean { - return Object.prototype.hasOwnProperty.call(this._headers, name); - } -}