Skip to content

Commit 4e4ae65

Browse files
committed
feat(utils): Introduce envelope helper functions
This patch introduces functions that create, mutate and serialize envelopes. It also adds some basic unit tests that sanity check their functionality. It builds on top of the work done in #4527. Users are expected to not directly interact with the Envelope instance, but instead use the helper functions to work with them. Essentially, we can treat the envelope instance as an opaque handle, similar to how void pointers are used in low-level languages. This was done to minimize the bundle impact of working with the envelopes, and as the set of possible envelope operations was fixed (and on the smaller end). To directly create an envelope, the `createEnvelope()` function was introduced. Users are encouraged to explicitly provide the generic type arg to this function so that add headers/items are typed accordingly. To add headers and items to envelopes, the `addHeaderToEnvelope()` and `addItemToEnvelope()` functions are exposed respectively. The reason that these functions are purely additive (or in the case of headers, can re-write existing ones), instead of allow for headers/items to be removed, is that removal functionality doesn't seem like it'll be used at all. In the interest of keeping the API surface small, we settled with these two functions, but we can come back and adjust this later on. Finally, there is `serializeEnvelope()`, which is used to serialize an envelope to a string. It does have some TypeScript complications, which is explained in detail in a code comment, but otherwise is a pretty simple implementation. You can notice the power of the tuple based envelope implementation, where it becomes easy to access headers/items. ```js const [headers, items] = envelope; ``` To illustrate how these functions will be used, another patch will be added that adds a `createClientReportEnvelope()` util, and the base transport in `@sentry/browser` will be updated to use that util.
1 parent c7416da commit 4e4ae65

File tree

4 files changed

+97
-7
lines changed

4 files changed

+97
-7
lines changed

Diff for: packages/types/src/envelope.ts

+6-7
Original file line numberDiff line numberDiff line change
@@ -25,15 +25,14 @@ type BaseEnvelopeItem<ItemHeader extends { type: string }, Payload = unknown> =
2525
Payload,
2626
];
2727

28-
type UnknownEnvelopeItem = BaseEnvelopeItem<{ type: '__unknown__' }>;
29-
30-
type BaseEnvelope<
28+
/**
29+
* 1st Item: Envelope headers
30+
* 2nd Item: Envelope items {@see BaseEnvelopeItem}
31+
*/
32+
export type BaseEnvelope<
3133
EnvelopeHeaders extends Record<string, unknown>,
3234
EnvelopeItem extends BaseEnvelopeItem<{ type: string }>,
33-
> = {
34-
headers: CommonEnvelopeHeaders & EnvelopeHeaders;
35-
items: Array<EnvelopeItem | UnknownEnvelopeItem>;
36-
};
35+
> = [CommonEnvelopeHeaders & EnvelopeHeaders & Record<string, unknown>, EnvelopeItem[]];
3736

3837
export type EventEnvelopeItem = BaseEnvelopeItem<{ type: 'event' | 'transaction' }, Event>;
3938

Diff for: packages/utils/src/envelope.ts

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { Envelope } from '@sentry/types';
2+
3+
/**
4+
* Creates an envelope.
5+
* Make sure to always explicitly provide the generic to this function
6+
* so that the envelope types resolve correctly.
7+
*/
8+
export function createEnvelope<E extends Envelope>(headers: E[0], items: E[1]): E {
9+
return [headers, items] as E;
10+
}
11+
12+
/**
13+
* Add a set of key value pairs to the envelope header.
14+
* Make sure to always explicitly provide the generic to this function
15+
* so that the envelope types resolve correctly.
16+
*/
17+
export function addHeaderToEnvelope<E extends Envelope>(envelope: E, newHeaders: E[0]): E {
18+
const [headers, items] = envelope;
19+
return [{ ...headers, ...newHeaders }, items] as E;
20+
}
21+
22+
/**
23+
* Add an item to an envelope.
24+
* Make sure to always explicitly provide the generic to this function
25+
* so that the envelope types resolve correctly.
26+
*/
27+
export function addItemToEnvelope<E extends Envelope>(envelope: E, newItem: E[1][number]): E {
28+
const [headers, items] = envelope;
29+
return [headers, [...items, newItem]] as E;
30+
}
31+
32+
/**
33+
* Serializes an envelope into a string.
34+
*/
35+
export function serializeEnvelope(envelope: Envelope): string {
36+
const [headers, items] = envelope;
37+
const serializedHeaders = JSON.stringify(headers);
38+
39+
// Have to cast items to any here since Envelope is a union type
40+
// Fixed in Typescript 4.2
41+
// TODO: Remove any[] cast when we upgrade to TS 4.2
42+
// https://github.com/microsoft/TypeScript/issues/36390
43+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
44+
return (items as any[]).reduce((acc, item: typeof items[number]) => {
45+
const [itemHeaders, payload] = item;
46+
return `${acc}\n${JSON.stringify(itemHeaders)}\n${JSON.stringify(payload)}`;
47+
}, serializedHeaders);
48+
}

Diff for: packages/utils/src/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,4 @@ export * from './supports';
2121
export * from './syncpromise';
2222
export * from './time';
2323
export * from './env';
24+
export * from './envelope';

Diff for: packages/utils/test/envelope.test.ts

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { createEnvelope, addHeaderToEnvelope, addItemToEnvelope, serializeEnvelope } from '../src/envelope';
2+
import { EventEnvelope } from '@sentry/types';
3+
4+
describe('envelope', () => {
5+
describe('createEnvelope()', () => {
6+
const testTable: Array<[string, Parameters<typeof createEnvelope>[0], Parameters<typeof createEnvelope>[1]]> = [
7+
['creates an empty envelope', {}, []],
8+
['creates an envelope with a header but no items', { dsn: 'https://public@example.com/1', sdk: {} }, []],
9+
];
10+
it.each(testTable)('%s', (_: string, headers, items) => {
11+
const env = createEnvelope(headers, items);
12+
expect(env).toHaveLength(2);
13+
expect(env[0]).toStrictEqual(headers);
14+
expect(env[1]).toStrictEqual(items);
15+
});
16+
});
17+
18+
describe('addHeaderToEnvelope()', () => {
19+
it('adds a header to the envelope', () => {
20+
const env = createEnvelope({}, []);
21+
expect(serializeEnvelope(env)).toMatchInlineSnapshot(`"{}"`);
22+
const newEnv = addHeaderToEnvelope(env, { dsn: 'https://public@example.com/' });
23+
expect(serializeEnvelope(newEnv)).toMatchInlineSnapshot(`"{\\"dsn\\":\\"https://public@example.com/\\"}"`);
24+
});
25+
});
26+
27+
describe('addItemToEnvelope()', () => {
28+
const env = createEnvelope<EventEnvelope>({ event_id: 'aa3ff046696b4bc6b609ce6d28fde9e2', sent_at: '123' }, []);
29+
expect(serializeEnvelope(env)).toMatchInlineSnapshot(
30+
`"{\\"event_id\\":\\"aa3ff046696b4bc6b609ce6d28fde9e2\\",\\"sent_at\\":\\"123\\"}"`,
31+
);
32+
const newEnv = addItemToEnvelope<EventEnvelope>(env, [
33+
{ type: 'event' },
34+
{ event_id: 'aa3ff046696b4bc6b609ce6d28fde9e2' },
35+
]);
36+
expect(serializeEnvelope(newEnv)).toMatchInlineSnapshot(`
37+
"{\\"event_id\\":\\"aa3ff046696b4bc6b609ce6d28fde9e2\\",\\"sent_at\\":\\"123\\"}
38+
{\\"type\\":\\"event\\"}
39+
{\\"event_id\\":\\"aa3ff046696b4bc6b609ce6d28fde9e2\\"}"
40+
`);
41+
});
42+
});

0 commit comments

Comments
 (0)