@datadog/mobile-react-native 2.13.0 → 2.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/android/src/main/kotlin/com/datadog/reactnative/SdkVersion.kt +1 -1
  2. package/ios/Sources/DatadogSDKWrapper.swift +7 -1
  3. package/ios/Sources/DdSdk.mm +2 -0
  4. package/ios/Sources/DdSdkImplementation.swift +9 -1
  5. package/ios/Sources/DdSdkNativeInitialization.swift +6 -1
  6. package/ios/Sources/SdkVersion.swift +1 -1
  7. package/lib/commonjs/rum/DdRum.js +1 -0
  8. package/lib/commonjs/rum/DdRum.js.map +1 -1
  9. package/lib/commonjs/rum/instrumentation/resourceTracking/distributedTracing/distributedTracingHeaders.js +9 -6
  10. package/lib/commonjs/rum/instrumentation/resourceTracking/distributedTracing/distributedTracingHeaders.js.map +1 -1
  11. package/lib/commonjs/rum/instrumentation/resourceTracking/graphql/graphqlHeaders.js +5 -10
  12. package/lib/commonjs/rum/instrumentation/resourceTracking/graphql/graphqlHeaders.js.map +1 -1
  13. package/lib/commonjs/rum/instrumentation/resourceTracking/headers.js +19 -0
  14. package/lib/commonjs/rum/instrumentation/resourceTracking/headers.js.map +1 -0
  15. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/XHRProxy.js +37 -16
  16. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/XHRProxy.js.map +1 -1
  17. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/baggageHeaderUtils.js +135 -0
  18. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/baggageHeaderUtils.js.map +1 -0
  19. package/lib/commonjs/rum/sessionId/sessionIdHelper.js +5 -1
  20. package/lib/commonjs/rum/sessionId/sessionIdHelper.js.map +1 -1
  21. package/lib/commonjs/version.js +1 -1
  22. package/lib/module/rum/DdRum.js +2 -1
  23. package/lib/module/rum/DdRum.js.map +1 -1
  24. package/lib/module/rum/instrumentation/resourceTracking/distributedTracing/distributedTracingHeaders.js +9 -6
  25. package/lib/module/rum/instrumentation/resourceTracking/distributedTracing/distributedTracingHeaders.js.map +1 -1
  26. package/lib/module/rum/instrumentation/resourceTracking/graphql/graphqlHeaders.js +2 -5
  27. package/lib/module/rum/instrumentation/resourceTracking/graphql/graphqlHeaders.js.map +1 -1
  28. package/lib/module/rum/instrumentation/resourceTracking/headers.js +12 -0
  29. package/lib/module/rum/instrumentation/resourceTracking/headers.js.map +1 -0
  30. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/XHRProxy.js +39 -18
  31. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/XHRProxy.js.map +1 -1
  32. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/baggageHeaderUtils.js +130 -0
  33. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/baggageHeaderUtils.js.map +1 -0
  34. package/lib/module/rum/sessionId/sessionIdHelper.js +3 -0
  35. package/lib/module/rum/sessionId/sessionIdHelper.js.map +1 -1
  36. package/lib/module/version.js +1 -1
  37. package/lib/typescript/rum/DdRum.d.ts.map +1 -1
  38. package/lib/typescript/rum/instrumentation/resourceTracking/distributedTracing/distributedTracingHeaders.d.ts.map +1 -1
  39. package/lib/typescript/rum/instrumentation/resourceTracking/graphql/graphqlHeaders.d.ts +0 -1
  40. package/lib/typescript/rum/instrumentation/resourceTracking/graphql/graphqlHeaders.d.ts.map +1 -1
  41. package/lib/typescript/rum/instrumentation/resourceTracking/headers.d.ts +4 -0
  42. package/lib/typescript/rum/instrumentation/resourceTracking/headers.d.ts.map +1 -0
  43. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/XHRProxy.d.ts.map +1 -1
  44. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/baggageHeaderUtils.d.ts +6 -0
  45. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/baggageHeaderUtils.d.ts.map +1 -0
  46. package/lib/typescript/rum/sessionId/sessionIdHelper.d.ts +1 -0
  47. package/lib/typescript/rum/sessionId/sessionIdHelper.d.ts.map +1 -1
  48. package/lib/typescript/version.d.ts +1 -1
  49. package/package.json +2 -2
  50. package/src/rum/DdRum.ts +2 -0
  51. package/src/rum/instrumentation/resourceTracking/__tests__/headers.test.ts +14 -0
  52. package/src/rum/instrumentation/resourceTracking/distributedTracing/distributedTracingHeaders.ts +11 -6
  53. package/src/rum/instrumentation/resourceTracking/graphql/__tests__/graphqlHeaders.test.ts +2 -8
  54. package/src/rum/instrumentation/resourceTracking/graphql/graphqlHeaders.ts +2 -7
  55. package/src/rum/instrumentation/resourceTracking/headers.ts +12 -0
  56. package/src/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/XHRProxy.ts +50 -19
  57. package/src/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/__tests__/XHRProxy.test.ts +87 -0
  58. package/src/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/__tests__/baggageHeaderUtils.test.ts +117 -0
  59. package/src/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/baggageHeaderUtils.ts +172 -0
  60. package/src/rum/sessionId/sessionIdHelper.ts +4 -0
  61. package/src/version.ts +1 -1
package/src/rum/DdRum.ts CHANGED
@@ -31,6 +31,7 @@ import {
31
31
  getTracingContextForPropagators
32
32
  } from './instrumentation/resourceTracking/distributedTracing/distributedTracingHeaders';
33
33
  import {
34
+ clearCachedSessionId,
34
35
  getCachedSessionId,
35
36
  setCachedSessionId
36
37
  } from './sessionId/sessionIdHelper';
@@ -295,6 +296,7 @@ class DdRumWrapper implements DdRumType {
295
296
 
296
297
  stopSession = (): Promise<void> => {
297
298
  InternalLog.log('Stopping RUM Session', SdkVerbosity.DEBUG);
299
+ clearCachedSessionId();
298
300
  return bufferVoidNativeCall(() => this.nativeRum.stopSession());
299
301
  };
300
302
 
@@ -0,0 +1,14 @@
1
+ /*
2
+ * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
3
+ * This product includes software developed at Datadog (https://www.datadoghq.com/).
4
+ * Copyright 2016-Present Datadog, Inc.
5
+ */
6
+ import { isDatadogCustomHeader } from '../headers';
7
+
8
+ describe('headers', () => {
9
+ describe('isDatadogCustomHeader', () => {
10
+ it('returns false for non-custom headers', () => {
11
+ expect(isDatadogCustomHeader('non-custom-header')).toBeFalsy();
12
+ });
13
+ });
14
+ });
@@ -48,9 +48,12 @@ export const getTracingHeadersFromAttributes = (
48
48
  if (tracingAttributes.tracingStrategy === 'DISCARD') {
49
49
  return headers;
50
50
  }
51
+
52
+ let hasDatadogOrW3CPropagator = false;
51
53
  tracingAttributes.propagatorTypes.forEach(propagator => {
52
54
  switch (propagator) {
53
55
  case PropagatorType.DATADOG: {
56
+ hasDatadogOrW3CPropagator = true;
54
57
  headers.push(
55
58
  {
56
59
  header: ORIGIN_HEADER_KEY,
@@ -82,6 +85,7 @@ export const getTracingHeadersFromAttributes = (
82
85
  break;
83
86
  }
84
87
  case PropagatorType.TRACECONTEXT: {
88
+ hasDatadogOrW3CPropagator = true;
85
89
  const isSampled =
86
90
  tracingAttributes.samplingPriorityHeader === '1';
87
91
  headers.push(
@@ -137,14 +141,15 @@ export const getTracingHeadersFromAttributes = (
137
141
  );
138
142
  }
139
143
  }
140
- if (tracingAttributes.rumSessionId) {
141
- headers.push({
142
- header: BAGGAGE_HEADER_KEY,
143
- value: `${DD_RUM_SESSION_ID_TAG}=${tracingAttributes.rumSessionId}`
144
- });
145
- }
146
144
  });
147
145
 
146
+ if (hasDatadogOrW3CPropagator && tracingAttributes.rumSessionId) {
147
+ headers.push({
148
+ header: BAGGAGE_HEADER_KEY,
149
+ value: `${DD_RUM_SESSION_ID_TAG}=${tracingAttributes.rumSessionId}`
150
+ });
151
+ }
152
+
148
153
  return headers;
149
154
  };
150
155
 
@@ -4,11 +4,11 @@
4
4
  * Copyright 2016-Present Datadog, Inc.
5
5
  */
6
6
 
7
+ import { isDatadogCustomHeader } from '../../headers';
7
8
  import {
8
9
  DATADOG_GRAPH_QL_OPERATION_NAME_HEADER,
9
10
  DATADOG_GRAPH_QL_OPERATION_TYPE_HEADER,
10
- DATADOG_GRAPH_QL_VARIABLES_HEADER,
11
- isDatadogCustomHeader
11
+ DATADOG_GRAPH_QL_VARIABLES_HEADER
12
12
  } from '../graphqlHeaders';
13
13
 
14
14
  describe('GraphQL custom headers', () => {
@@ -19,10 +19,4 @@ describe('GraphQL custom headers', () => {
19
19
  ])('%s matches the custom header pattern', header => {
20
20
  expect(isDatadogCustomHeader(header)).toBeTruthy();
21
21
  });
22
-
23
- describe('isDatadogCustomHeader', () => {
24
- it('returns false for non-custom headers', () => {
25
- expect(isDatadogCustomHeader('non-custom-header')).toBeFalsy();
26
- });
27
- });
28
22
  });
@@ -1,15 +1,10 @@
1
+ import { DATADOG_CUSTOM_HEADER_PREFIX } from '../headers';
2
+
1
3
  /*
2
4
  * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
3
5
  * This product includes software developed at Datadog (https://www.datadoghq.com/).
4
6
  * Copyright 2016-Present Datadog, Inc.
5
7
  */
6
-
7
- const DATADOG_CUSTOM_HEADER_PREFIX = '_dd-custom-header';
8
-
9
8
  export const DATADOG_GRAPH_QL_OPERATION_NAME_HEADER = `${DATADOG_CUSTOM_HEADER_PREFIX}-graph-ql-operation-name`;
10
9
  export const DATADOG_GRAPH_QL_VARIABLES_HEADER = `${DATADOG_CUSTOM_HEADER_PREFIX}-graph-ql-variables`;
11
10
  export const DATADOG_GRAPH_QL_OPERATION_TYPE_HEADER = `${DATADOG_CUSTOM_HEADER_PREFIX}-graph-ql-operation-type`;
12
-
13
- export const isDatadogCustomHeader = (header: string) => {
14
- return header.match(new RegExp(`^${DATADOG_CUSTOM_HEADER_PREFIX}`));
15
- };
@@ -0,0 +1,12 @@
1
+ /*
2
+ * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
3
+ * This product includes software developed at Datadog (https://www.datadoghq.com/).
4
+ * Copyright 2016-Present Datadog, Inc.
5
+ */
6
+
7
+ export const DATADOG_CUSTOM_HEADER_PREFIX = '_dd-custom-header';
8
+ export const DATADOG_BAGGAGE_HEADER = `${DATADOG_CUSTOM_HEADER_PREFIX}-baggage`;
9
+
10
+ export const isDatadogCustomHeader = (header: string) => {
11
+ return header.match(new RegExp(`^${DATADOG_CUSTOM_HEADER_PREFIX}`));
12
+ };
@@ -6,20 +6,24 @@
6
6
 
7
7
  import { Timer } from '../../../../../utils/Timer';
8
8
  import { getCachedSessionId } from '../../../../sessionId/sessionIdHelper';
9
- import { getTracingHeadersFromAttributes } from '../../distributedTracing/distributedTracingHeaders';
9
+ import {
10
+ BAGGAGE_HEADER_KEY,
11
+ getTracingHeadersFromAttributes
12
+ } from '../../distributedTracing/distributedTracingHeaders';
10
13
  import type { DdRumResourceTracingAttributes } from '../../distributedTracing/distributedTracing';
11
14
  import { getTracingAttributes } from '../../distributedTracing/distributedTracing';
12
15
  import {
13
16
  DATADOG_GRAPH_QL_OPERATION_NAME_HEADER,
14
17
  DATADOG_GRAPH_QL_OPERATION_TYPE_HEADER,
15
- DATADOG_GRAPH_QL_VARIABLES_HEADER,
16
- isDatadogCustomHeader
18
+ DATADOG_GRAPH_QL_VARIABLES_HEADER
17
19
  } from '../../graphql/graphqlHeaders';
20
+ import { DATADOG_BAGGAGE_HEADER, isDatadogCustomHeader } from '../../headers';
18
21
  import type { RequestProxyOptions } from '../interfaces/RequestProxy';
19
22
  import { RequestProxy } from '../interfaces/RequestProxy';
20
23
 
21
24
  import type { ResourceReporter } from './DatadogRumResource/ResourceReporter';
22
25
  import { URLHostParser } from './URLHostParser';
26
+ import { formatBaggageHeader } from './baggageHeaderUtils';
23
27
  import { calculateResponseSize } from './responseSize';
24
28
 
25
29
  const RESPONSE_START_LABEL = 'response_start';
@@ -39,6 +43,7 @@ interface DdRumXhrContext {
39
43
  reported: boolean;
40
44
  timer: Timer;
41
45
  tracingAttributes: DdRumResourceTracingAttributes;
46
+ baggageHeaderEntries: Set<string>;
42
47
  }
43
48
 
44
49
  interface XHRProxyProviders {
@@ -111,7 +116,8 @@ const proxyOpen = (
111
116
  firstPartyHostsRegexMap,
112
117
  tracingSamplingRate,
113
118
  rumSessionId: getCachedSessionId()
114
- })
119
+ }),
120
+ baggageHeaderEntries: new Set<string>()
115
121
  };
116
122
  // eslint-disable-next-line prefer-rest-params
117
123
  return originalXhrOpen.apply(this, arguments as any);
@@ -127,12 +133,22 @@ const proxySend = (providers: XHRProxyProviders): void => {
127
133
  // keep track of start time
128
134
  this._datadog_xhr.timer.start();
129
135
 
136
+ // Tracing Headers
130
137
  const tracingHeaders = getTracingHeadersFromAttributes(
131
138
  this._datadog_xhr.tracingAttributes
132
139
  );
140
+
133
141
  tracingHeaders.forEach(({ header, value }) => {
134
142
  this.setRequestHeader(header, value);
135
143
  });
144
+
145
+ // Join all baggage header entries
146
+ const baggageHeader = formatBaggageHeader(
147
+ this._datadog_xhr.baggageHeaderEntries
148
+ );
149
+ if (baggageHeader) {
150
+ this.setRequestHeader(DATADOG_BAGGAGE_HEADER, baggageHeader);
151
+ }
136
152
  }
137
153
 
138
154
  proxyOnReadyStateChange(this, providers);
@@ -211,22 +227,37 @@ const proxySetRequestHeader = (providers: XHRProxyProviders): void => {
211
227
  header: string,
212
228
  value: string
213
229
  ) {
214
- if (isDatadogCustomHeader(header)) {
215
- if (header === DATADOG_GRAPH_QL_OPERATION_NAME_HEADER) {
216
- this._datadog_xhr.graphql.operationName = value;
217
- return;
218
- }
219
- if (header === DATADOG_GRAPH_QL_OPERATION_TYPE_HEADER) {
220
- this._datadog_xhr.graphql.operationType = value;
221
- return;
222
- }
223
- if (header === DATADOG_GRAPH_QL_VARIABLES_HEADER) {
224
- this._datadog_xhr.graphql.variables = value;
225
- return;
230
+ const key = header.toLowerCase();
231
+ if (isDatadogCustomHeader(key)) {
232
+ switch (key) {
233
+ case DATADOG_GRAPH_QL_OPERATION_NAME_HEADER:
234
+ this._datadog_xhr.graphql.operationName = value;
235
+ break;
236
+ case DATADOG_GRAPH_QL_OPERATION_TYPE_HEADER:
237
+ this._datadog_xhr.graphql.operationType = value;
238
+ break;
239
+ case DATADOG_GRAPH_QL_VARIABLES_HEADER:
240
+ this._datadog_xhr.graphql.variables = value;
241
+ break;
242
+ case DATADOG_BAGGAGE_HEADER:
243
+ // Apply Baggage Header only if pre-processed by Datadog
244
+ return originalXhrSetRequestHeader.apply(this, [
245
+ BAGGAGE_HEADER_KEY,
246
+ value
247
+ ]);
248
+ default:
249
+ return originalXhrSetRequestHeader.apply(
250
+ this,
251
+ // eslint-disable-next-line prefer-rest-params
252
+ arguments as any
253
+ );
226
254
  }
255
+ } else if (key === BAGGAGE_HEADER_KEY) {
256
+ // Intercept User Baggage Header entries to apply them later
257
+ this._datadog_xhr.baggageHeaderEntries?.add(value);
258
+ } else {
259
+ // eslint-disable-next-line prefer-rest-params
260
+ return originalXhrSetRequestHeader.apply(this, arguments as any);
227
261
  }
228
-
229
- // eslint-disable-next-line prefer-rest-params
230
- return originalXhrSetRequestHeader.apply(this, arguments as any);
231
262
  };
232
263
  };
@@ -839,6 +839,93 @@ describe('XHRProxy', () => {
839
839
  // THEN
840
840
  expect(xhr.requestHeaders[BAGGAGE_HEADER_KEY]).toBeUndefined();
841
841
  });
842
+
843
+ it('does not add rum session id to baggage headers when propagator type is not datadog or w3c', async () => {
844
+ // GIVEN
845
+ const method = 'GET';
846
+ const url = 'https://example.com';
847
+ xhrProxy.onTrackingStart({
848
+ tracingSamplingRate: 100,
849
+ firstPartyHostsRegexMap: firstPartyHostsRegexMapBuilder([
850
+ {
851
+ match: 'api.example.com',
852
+ propagatorTypes: [
853
+ PropagatorType.DATADOG,
854
+ PropagatorType.TRACECONTEXT
855
+ ]
856
+ },
857
+ {
858
+ match: 'example.com', // <-- no datadog or tracecontext here
859
+ propagatorTypes: [
860
+ PropagatorType.B3,
861
+ PropagatorType.B3MULTI
862
+ ]
863
+ }
864
+ ])
865
+ });
866
+
867
+ setCachedSessionId('TEST-SESSION-ID');
868
+
869
+ // WHEN
870
+ const xhr = new XMLHttpRequestMock();
871
+ xhr.open(method, url);
872
+ xhr.send();
873
+ xhr.notifyResponseArrived();
874
+ xhr.complete(200, 'ok');
875
+ await flushPromises();
876
+
877
+ // THEN
878
+ expect(xhr.requestHeaders[BAGGAGE_HEADER_KEY]).toBeUndefined();
879
+ });
880
+
881
+ it('rum session id does not overwrite existing baggage headers', async () => {
882
+ // GIVEN
883
+ const method = 'GET';
884
+ const url = 'https://api.example.com:443/v2/user';
885
+ xhrProxy.onTrackingStart({
886
+ tracingSamplingRate: 100,
887
+ firstPartyHostsRegexMap: firstPartyHostsRegexMapBuilder([
888
+ {
889
+ match: 'api.example.com',
890
+ propagatorTypes: [
891
+ PropagatorType.DATADOG,
892
+ PropagatorType.TRACECONTEXT
893
+ ]
894
+ },
895
+ {
896
+ match: 'example.com',
897
+ propagatorTypes: [
898
+ PropagatorType.B3,
899
+ PropagatorType.B3MULTI
900
+ ]
901
+ }
902
+ ])
903
+ });
904
+
905
+ setCachedSessionId('TEST-SESSION-ID');
906
+
907
+ // WHEN
908
+ const xhr = new XMLHttpRequestMock();
909
+ xhr.open(method, url);
910
+ xhr.setRequestHeader('baggage', 'existing.key=existing-value');
911
+ xhr.send();
912
+ xhr.notifyResponseArrived();
913
+ xhr.complete(200, 'ok');
914
+ await flushPromises();
915
+
916
+ // THEN
917
+ expect(xhr.requestHeaders[BAGGAGE_HEADER_KEY]).not.toBeUndefined();
918
+ expect(xhr.requestHeaders[BAGGAGE_HEADER_KEY]).toContain(
919
+ 'existing.key=existing-value'
920
+ );
921
+
922
+ const values = xhr.requestHeaders[BAGGAGE_HEADER_KEY].split(
923
+ ','
924
+ ).sort();
925
+
926
+ expect(values[0]).toBe('existing.key=existing-value');
927
+ expect(values[1]).toBe('session.id=TEST-SESSION-ID');
928
+ });
842
929
  });
843
930
 
844
931
  describe('DdRum.startResource calls', () => {
@@ -0,0 +1,117 @@
1
+ import { InternalLog } from '../../../../../../InternalLog';
2
+ import { SdkVerbosity } from '../../../../../../SdkVerbosity';
3
+ import { formatBaggageHeader } from '../baggageHeaderUtils';
4
+
5
+ describe('formatBaggageHeader', () => {
6
+ let logSpy: jest.SpyInstance;
7
+
8
+ beforeEach(() => {
9
+ logSpy = jest.spyOn(InternalLog, 'log').mockImplementation(() => {});
10
+ });
11
+
12
+ afterEach(() => {
13
+ logSpy.mockRestore();
14
+ });
15
+
16
+ it('should format simple key=value entries correctly', () => {
17
+ const entries = new Set(['userId=alice', 'isProduction=false']);
18
+ const result = formatBaggageHeader(entries);
19
+ expect(result).toBe('userId=alice,isProduction=false');
20
+ expect(logSpy).not.toHaveBeenCalled();
21
+ });
22
+
23
+ it('should percent-encode spaces and non-ASCII characters in values', () => {
24
+ const entries = new Set(['user=Amélie', 'region=us east']);
25
+ const result = formatBaggageHeader(entries);
26
+ expect(result).toBe('user=Am%C3%A9lie,region=us%20east');
27
+ });
28
+
29
+ it('should support properties with and without values', () => {
30
+ const entries = new Set(['traceId=abc123;sampled=true;debug']);
31
+ const result = formatBaggageHeader(entries);
32
+ expect(result).toBe('traceId=abc123;sampled=true;debug');
33
+ });
34
+
35
+ it('should trim whitespace around keys, values, and properties', () => {
36
+ const entries = new Set([' foo = bar ; p1 = one ; p2 ']);
37
+ const result = formatBaggageHeader(entries);
38
+ expect(result).toBe('foo=bar;p1=one;p2');
39
+ });
40
+
41
+ it('should skip invalid entries without crashing', () => {
42
+ const entries = new Set(['valid=ok', 'invalidEntry']);
43
+ const result = formatBaggageHeader(entries);
44
+ expect(result).toBe('valid=ok');
45
+ expect(logSpy).toHaveBeenCalledWith(
46
+ expect.stringContaining('Dropped invalid baggage header entry'),
47
+ SdkVerbosity.WARN
48
+ );
49
+ });
50
+
51
+ it('should skip entries with invalid key (non-token)', () => {
52
+ const entries = new Set(['in valid=value', 'user=ok']);
53
+ const result = formatBaggageHeader(entries);
54
+ expect(result).toBe('user=ok');
55
+ expect(logSpy).toHaveBeenCalledWith(
56
+ expect.stringContaining('key not compliant'),
57
+ SdkVerbosity.WARN
58
+ );
59
+ });
60
+
61
+ it('should skip invalid properties (bad property key)', () => {
62
+ const entries = new Set(['user=ok;invalid key=value;good=yes']);
63
+ const result = formatBaggageHeader(entries);
64
+ expect(result).toBe('user=ok;good=yes');
65
+ expect(logSpy).toHaveBeenCalledWith(
66
+ expect.stringContaining('property key not compliant'),
67
+ SdkVerbosity.WARN
68
+ );
69
+ });
70
+
71
+ it('should log warning when too many members (>64)', () => {
72
+ const entries = new Set<string>();
73
+ for (let i = 0; i < 70; i++) {
74
+ entries.add(`k${i}=v${i}`);
75
+ }
76
+ const result = formatBaggageHeader(entries);
77
+ expect(result?.startsWith('k0=v0')).toBe(true);
78
+ expect(logSpy).toHaveBeenCalledWith(
79
+ expect.stringContaining('Too many baggage members'),
80
+ SdkVerbosity.WARN
81
+ );
82
+ });
83
+
84
+ it('should log warning when header exceeds byte limit', () => {
85
+ const bigValue = 'x'.repeat(9000);
86
+ const entries = new Set([`large=${bigValue}`]);
87
+ const result = formatBaggageHeader(entries);
88
+ expect(result).toContain('large=');
89
+ expect(logSpy).toHaveBeenCalledWith(
90
+ expect.stringContaining('Baggage header too large'),
91
+ SdkVerbosity.WARN
92
+ );
93
+ });
94
+
95
+ it('should return null if all entries are invalid', () => {
96
+ const entries = new Set(['badEntry', 'stillBad']);
97
+ const result = formatBaggageHeader(entries);
98
+ expect(result).toBeNull();
99
+ });
100
+
101
+ it('should preserve insertion order', () => {
102
+ const entries = new Set(['first=1', 'second=2', 'third=3']);
103
+ const result = formatBaggageHeader(entries);
104
+ expect(result).toBe('first=1,second=2,third=3');
105
+ });
106
+
107
+ it('should trim keys and values', () => {
108
+ const entries = new Set([
109
+ 'traceId=abc123;sampled=true;debug',
110
+ 'test1 = this is a test'
111
+ ]);
112
+ const result = formatBaggageHeader(entries);
113
+ expect(result).toBe(
114
+ 'traceId=abc123;sampled=true;debug,test1=this%20is%20a%20test'
115
+ );
116
+ });
117
+ });
@@ -0,0 +1,172 @@
1
+ /*
2
+ * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
3
+ * This product includes software developed at Datadog (https://www.datadoghq.com/).
4
+ * Copyright 2016-Present Datadog, Inc.
5
+ */
6
+
7
+ import { InternalLog } from '../../../../../InternalLog';
8
+ import { SdkVerbosity } from '../../../../../SdkVerbosity';
9
+
10
+ // The resulting baggage-string should contain 64 list-members or less (https://www.w3.org/TR/baggage/#limits)
11
+ const MAX_MEMBERS = 64;
12
+
13
+ // The resulting baggage-string should be of size 8192 bytes or less (https://www.w3.org/TR/baggage/#limits)
14
+ const MAX_BYTES = 8192;
15
+
16
+ // The keys must follow RFC 7230 token grammar (https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.6)
17
+ const TOKEN_REGEX = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
18
+
19
+ /**
20
+ * Lazy property for {@link getBaggageHeaderSafeChars}.
21
+ */
22
+ let baggageHeaderSafeChars: Set<string> | undefined;
23
+
24
+ /**
25
+ * Transform a Set of baggage entries (strings like "key=value;prop1=foo;prop2")
26
+ * into a compliant baggage header value per W3C Baggage spec.
27
+ */
28
+ export function formatBaggageHeader(entries: Set<string>): string | null {
29
+ const formattedParts: string[] = [];
30
+
31
+ for (const rawEntry of entries) {
32
+ if (!rawEntry.includes('=')) {
33
+ InternalLog.log(
34
+ 'XHRProxy: Dropped invalid baggage header entry - expected format "key=value".',
35
+ SdkVerbosity.WARN
36
+ );
37
+ continue;
38
+ }
39
+
40
+ // Split first key=value from properties (properties are after first ';')
41
+ const [mainPart, ...rawProperties] = rawEntry.split(';');
42
+ const idx = mainPart.indexOf('=');
43
+ if (idx <= 0) {
44
+ InternalLog.log(
45
+ "XHRProxy: Dropped invalid baggage header entry - no '=' or empty key",
46
+ SdkVerbosity.WARN
47
+ );
48
+ continue;
49
+ }
50
+
51
+ const rawKey = mainPart.slice(0, idx).trim();
52
+ const rawValue = mainPart.slice(idx + 1).trim();
53
+
54
+ if (!TOKEN_REGEX.test(rawKey)) {
55
+ InternalLog.log(
56
+ 'XHRProxy: Dropped invalid baggage header entry - key not compliant to RFC 7230 token grammar',
57
+ SdkVerbosity.WARN
58
+ );
59
+ continue;
60
+ }
61
+
62
+ const encodedValue = encodeValue(rawValue);
63
+
64
+ // Handle properties
65
+ const properties: string[] = [];
66
+ for (const rawProperty of rawProperties) {
67
+ const trimmed = rawProperty.trim();
68
+ if (!trimmed) {
69
+ continue;
70
+ }
71
+
72
+ const eqIdx = trimmed.indexOf('=');
73
+ if (eqIdx === -1) {
74
+ // Property with no value (key1=value1;prop1; ... )
75
+ const propKey = trimmed.trim();
76
+ if (!TOKEN_REGEX.test(propKey)) {
77
+ InternalLog.log(
78
+ 'XHRProxy: Dropped invalid baggage header entry - property key not compliant to RFC 7230 token grammar',
79
+ SdkVerbosity.WARN
80
+ );
81
+ continue;
82
+ }
83
+ properties.push(propKey);
84
+ } else {
85
+ // Property in key-value format (key1=value1;prop1=propValue1; ... )
86
+ const propKey = trimmed.slice(0, eqIdx).trim();
87
+ const propVal = trimmed.slice(eqIdx + 1).trim();
88
+ if (!TOKEN_REGEX.test(propKey)) {
89
+ InternalLog.log(
90
+ 'XHRProxy: Dropped invalid baggage header entry - key-value property key not compliant to RFC 7230 token grammar',
91
+ SdkVerbosity.WARN
92
+ );
93
+ continue;
94
+ }
95
+ properties.push(`${propKey}=${encodeValue(propVal)}`);
96
+ }
97
+ }
98
+
99
+ const joinedProps = properties.length ? `;${properties.join(';')}` : '';
100
+ formattedParts.push(`${rawKey}=${encodedValue}${joinedProps}`);
101
+ }
102
+
103
+ if (formattedParts.length > MAX_MEMBERS) {
104
+ InternalLog.log(
105
+ `XHRProxy: Too many baggage members: ${formattedParts.length} > ${MAX_MEMBERS} - entries may be dropped (https://www.w3.org/TR/baggage/#limits)`,
106
+ SdkVerbosity.WARN
107
+ );
108
+ } else if (formattedParts.length === 0) {
109
+ return null;
110
+ }
111
+
112
+ const headerValue = formattedParts.join(',');
113
+ const byteLength = Buffer.byteLength(headerValue, 'utf8');
114
+
115
+ if (byteLength > MAX_BYTES) {
116
+ InternalLog.log(
117
+ `Baggage header too large: ${byteLength} bytes > ${MAX_BYTES} - entries may be dropped (https://www.w3.org/TR/baggage/#limits)`,
118
+ SdkVerbosity.WARN
119
+ );
120
+ }
121
+
122
+ return headerValue;
123
+ }
124
+
125
+ /**
126
+ * Returns a set of valid baggage header characters.
127
+ */
128
+ function getBaggageHeaderSafeChars(): Set<string> {
129
+ if (baggageHeaderSafeChars) {
130
+ return baggageHeaderSafeChars;
131
+ }
132
+
133
+ const safeChars = new Set<string>();
134
+ for (let c = 0x21; c <= 0x7e; c++) {
135
+ if (
136
+ c === 0x22 ||
137
+ c === 0x2c ||
138
+ c === 0x3b ||
139
+ c === 0x5c ||
140
+ c === 0x20
141
+ ) {
142
+ continue;
143
+ }
144
+ safeChars.add(String.fromCharCode(c));
145
+ }
146
+
147
+ baggageHeaderSafeChars = safeChars;
148
+
149
+ return safeChars;
150
+ }
151
+
152
+ /*
153
+ * Percent-encode all characters outside baggage-octet range.
154
+ */
155
+ function encodeValue(raw: string): string {
156
+ const safeChars = getBaggageHeaderSafeChars();
157
+ let result = '';
158
+ for (const ch of Array.from(raw)) {
159
+ if (safeChars.has(ch)) {
160
+ result += ch;
161
+ } else {
162
+ const utf8Bytes = Buffer.from(ch, 'utf8');
163
+ for (const value of utf8Bytes) {
164
+ result += `%${value
165
+ .toString(16)
166
+ .toUpperCase()
167
+ .padStart(2, '0')}`;
168
+ }
169
+ }
170
+ }
171
+ return result;
172
+ }
@@ -12,3 +12,7 @@ export const getCachedSessionId = () => {
12
12
  export const setCachedSessionId = (sessionId: string) => {
13
13
  _cachedSessionId = sessionId;
14
14
  };
15
+
16
+ export const clearCachedSessionId = () => {
17
+ _cachedSessionId = undefined;
18
+ };
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  // generated by genversion
2
- export const version = '2.13.0';
2
+ export const version = '2.13.1';