@datadog/mobile-react-native 2.8.2 → 2.9.0

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 (92) hide show
  1. package/android/build.gradle +15 -4
  2. package/android/src/main/kotlin/com/datadog/reactnative/SdkVersion.kt +1 -1
  3. package/datadog-sourcemaps.gradle +101 -3
  4. package/ios/Sources/SdkVersion.swift +1 -1
  5. package/lib/commonjs/metro/debugIdResolver.js +35 -0
  6. package/lib/commonjs/metro/debugIdResolver.js.map +1 -0
  7. package/lib/commonjs/metro/metro.d.js +2 -0
  8. package/lib/commonjs/metro/metro.d.js.map +1 -0
  9. package/lib/commonjs/metro/plugin/debugIdHelper.js +244 -0
  10. package/lib/commonjs/metro/plugin/debugIdHelper.js.map +1 -0
  11. package/lib/commonjs/metro/plugin/metroConfig.js +68 -0
  12. package/lib/commonjs/metro/plugin/metroConfig.js.map +1 -0
  13. package/lib/commonjs/metro/plugin/metroSerializer.js +143 -0
  14. package/lib/commonjs/metro/plugin/metroSerializer.js.map +1 -0
  15. package/lib/commonjs/metro/plugin/types/expoTypes.js +6 -0
  16. package/lib/commonjs/metro/plugin/types/expoTypes.js.map +1 -0
  17. package/lib/commonjs/metro/plugin/types/metroTypes.js +6 -0
  18. package/lib/commonjs/metro/plugin/types/metroTypes.js.map +1 -0
  19. package/lib/commonjs/metro/plugin/utils.js +153 -0
  20. package/lib/commonjs/metro/plugin/utils.js.map +1 -0
  21. package/lib/commonjs/metro.js +19 -0
  22. package/lib/commonjs/metro.js.map +1 -0
  23. package/lib/commonjs/rum/DdRum.js +2 -1
  24. package/lib/commonjs/rum/DdRum.js.map +1 -1
  25. package/lib/commonjs/rum/instrumentation/DdRumErrorTracking.js +1 -1
  26. package/lib/commonjs/rum/instrumentation/DdRumErrorTracking.js.map +1 -1
  27. package/lib/commonjs/utils/errorUtils.js +13 -1
  28. package/lib/commonjs/utils/errorUtils.js.map +1 -1
  29. package/lib/commonjs/version.js +1 -1
  30. package/lib/module/metro/debugIdResolver.js +30 -0
  31. package/lib/module/metro/debugIdResolver.js.map +1 -0
  32. package/lib/module/metro/metro.d.js +2 -0
  33. package/lib/module/metro/metro.d.js.map +1 -0
  34. package/lib/module/metro/plugin/debugIdHelper.js +225 -0
  35. package/lib/module/metro/plugin/debugIdHelper.js.map +1 -0
  36. package/lib/module/metro/plugin/metroConfig.js +61 -0
  37. package/lib/module/metro/plugin/metroConfig.js.map +1 -0
  38. package/lib/module/metro/plugin/metroSerializer.js +131 -0
  39. package/lib/module/metro/plugin/metroSerializer.js.map +1 -0
  40. package/lib/module/metro/plugin/types/expoTypes.js +2 -0
  41. package/lib/module/metro/plugin/types/expoTypes.js.map +1 -0
  42. package/lib/module/metro/plugin/types/metroTypes.js +2 -0
  43. package/lib/module/metro/plugin/types/metroTypes.js.map +1 -0
  44. package/lib/module/metro/plugin/utils.js +139 -0
  45. package/lib/module/metro/plugin/utils.js.map +1 -0
  46. package/lib/module/metro.js +8 -0
  47. package/lib/module/metro.js.map +1 -0
  48. package/lib/module/rum/DdRum.js +2 -1
  49. package/lib/module/rum/DdRum.js.map +1 -1
  50. package/lib/module/rum/instrumentation/DdRumErrorTracking.js +2 -2
  51. package/lib/module/rum/instrumentation/DdRumErrorTracking.js.map +1 -1
  52. package/lib/module/utils/errorUtils.js +11 -0
  53. package/lib/module/utils/errorUtils.js.map +1 -1
  54. package/lib/module/version.js +1 -1
  55. package/lib/typescript/metro/debugIdResolver.d.ts +3 -0
  56. package/lib/typescript/metro/debugIdResolver.d.ts.map +1 -0
  57. package/lib/typescript/metro/plugin/debugIdHelper.d.ts +99 -0
  58. package/lib/typescript/metro/plugin/debugIdHelper.d.ts.map +1 -0
  59. package/lib/typescript/metro/plugin/metroConfig.d.ts +35 -0
  60. package/lib/typescript/metro/plugin/metroConfig.d.ts.map +1 -0
  61. package/lib/typescript/metro/plugin/metroSerializer.d.ts +29 -0
  62. package/lib/typescript/metro/plugin/metroSerializer.d.ts.map +1 -0
  63. package/lib/typescript/metro/plugin/types/expoTypes.d.ts +31 -0
  64. package/lib/typescript/metro/plugin/types/expoTypes.d.ts.map +1 -0
  65. package/lib/typescript/metro/plugin/types/metroTypes.d.ts +33 -0
  66. package/lib/typescript/metro/plugin/types/metroTypes.d.ts.map +1 -0
  67. package/lib/typescript/metro/plugin/utils.d.ts +36 -0
  68. package/lib/typescript/metro/plugin/utils.d.ts.map +1 -0
  69. package/lib/typescript/metro.d.ts +6 -0
  70. package/lib/typescript/metro.d.ts.map +1 -0
  71. package/lib/typescript/rum/DdRum.d.ts.map +1 -1
  72. package/lib/typescript/rum/instrumentation/DdRumErrorTracking.d.ts.map +1 -1
  73. package/lib/typescript/utils/errorUtils.d.ts +1 -0
  74. package/lib/typescript/utils/errorUtils.d.ts.map +1 -1
  75. package/lib/typescript/version.d.ts +1 -1
  76. package/package.json +17 -3
  77. package/scripts/copy-debug-id.js +52 -0
  78. package/src/metro/__tests__/__utils__/serializerUtils.ts +100 -0
  79. package/src/metro/__tests__/metro.test.ts +382 -0
  80. package/src/metro/debugIdResolver.ts +36 -0
  81. package/src/metro/metro.d.ts +73 -0
  82. package/src/metro/plugin/debugIdHelper.ts +279 -0
  83. package/src/metro/plugin/metroConfig.ts +97 -0
  84. package/src/metro/plugin/metroSerializer.ts +173 -0
  85. package/src/metro/plugin/types/expoTypes.ts +64 -0
  86. package/src/metro/plugin/types/metroTypes.ts +94 -0
  87. package/src/metro/plugin/utils.ts +177 -0
  88. package/src/metro.ts +14 -0
  89. package/src/rum/DdRum.ts +2 -1
  90. package/src/rum/instrumentation/DdRumErrorTracking.tsx +8 -2
  91. package/src/utils/errorUtils.ts +13 -0
  92. package/src/version.ts +1 -1
@@ -0,0 +1,279 @@
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
+ * Portions of this code are adapted from Sentry's Metro configuration:
7
+ * https://github.com/getsentry/sentry-react-native/blob/17c0c2e8913030e4826d055284a735efad637312/packages/core/src/js/tools/sentryMetroSerializer.ts
8
+ */
9
+
10
+ import { createHash } from 'crypto';
11
+ // eslint-disable-next-line import/no-extraneous-dependencies
12
+ import countLines from 'metro/src/lib/countLines';
13
+
14
+ import type {
15
+ Bundle,
16
+ MixedOutput,
17
+ Module,
18
+ MetroBundleWithMap,
19
+ DatadogDebugIdModule
20
+ } from './types/metroTypes';
21
+ import { createCountingSet } from './utils';
22
+
23
+ /**
24
+ * Regex to match the Debug ID comment in the bundle.
25
+ */
26
+ const DEBUG_ID_BUNDLE_REGEX = /\/\/\s?([#@])\s?debugId=([\d\-a-zA-Z]*$)/m;
27
+
28
+ /**
29
+ * Path name for the Debug ID Metro Virtual Module.
30
+ */
31
+ export const DEBUG_ID_MODULE_PATH = '__datadog_debugid__';
32
+
33
+ /**
34
+ * The initial placeholder for the injected Debug ID in the virtual module, replaced
35
+ * later by the actual Debug ID.
36
+ */
37
+ export const DEBUG_ID_PLACEHOLDER = '__datadog_debug_id_placeholder__';
38
+
39
+ /**
40
+ * A comment that can be found at the end of the JS bundle, to specify the URL of the sourcemap.
41
+ * Ref: https://tc39.es/ecma426/#sec-linking-inline
42
+ */
43
+ export const SOURCE_MAP_COMMENT = '//# sourceMappingURL=';
44
+
45
+ /**
46
+ * The comment that will be appended at the end of the JS bundle, to specify the Debug ID.
47
+ * Ref: https://github.com/tc39/ecma426/blob/main/proposals/debug-id.md
48
+ */
49
+ export const DEBUG_ID_COMMENT = '//# debugId=';
50
+
51
+ /**
52
+ * The Debug ID is injected in the virtual module as a plain string, using this prefix.
53
+ * It is later retrieved by searching it in the bundle, using the same prefix.
54
+ */
55
+ const DEBUG_ID_METADATA_PREFIX = 'datadog-debug-id-';
56
+
57
+ /**
58
+ * Creates a virtual module to embed a debug ID into the bundle.
59
+ * @param debugId - the debug ID to inject into the bundle, or a placeholder.
60
+ * @returns The Debug ID virtual module.
61
+ */
62
+ export const createDebugIdModule = (debugId: string): DatadogDebugIdModule => {
63
+ let debugIdCode = createDebugIdSnippet(debugId);
64
+
65
+ return {
66
+ setSource: (code: string) => {
67
+ debugIdCode = code;
68
+ },
69
+ dependencies: new Map(),
70
+ getSource: () => Buffer.from(debugIdCode),
71
+ inverseDependencies: createCountingSet(),
72
+ path: DEBUG_ID_MODULE_PATH,
73
+ output: [
74
+ {
75
+ type: 'js/script/virtual',
76
+ data: {
77
+ code: debugIdCode,
78
+ lineCount: countLines(debugIdCode),
79
+ map: []
80
+ }
81
+ }
82
+ ]
83
+ };
84
+ };
85
+
86
+ /**
87
+ * Injects the debug ID module into the list of pre-modules,
88
+ * ensuring that the prelude module (if present) stays at the top
89
+ * to correctly measure bundle startup time.
90
+ */
91
+ export const addDebugIdModule = (
92
+ preModules: readonly Module<MixedOutput>[],
93
+ debugIdModule: DatadogDebugIdModule
94
+ ): Module<MixedOutput>[] => {
95
+ const result = [...preModules];
96
+ const hasPrelude = result.length > 0 && result[0]?.path === '__prelude__';
97
+
98
+ if (hasPrelude) {
99
+ result.splice(1, 0, debugIdModule);
100
+ } else {
101
+ result.unshift(debugIdModule);
102
+ }
103
+
104
+ return result;
105
+ };
106
+
107
+ /**
108
+ * Creates a minified JavaScript snippet that exposes the provided Debug ID
109
+ * on the global scope at runtime.
110
+ *
111
+ * @param debugId - The Debug ID to be injected into the global scope.
112
+ * @returns A minified JavaScript string that performs the injection.
113
+ */
114
+ export const createDebugIdSnippet = (debugId: string) => {
115
+ return `var _datadogDebugIds,_datadogDebugIdMeta;void 0===_datadogDebugIds&&(_datadogDebugIds={});try{var stack=(new Error).stack;stack&&(_datadogDebugIds[stack]="${debugId}",_datadogDebugIdMeta="${DEBUG_ID_METADATA_PREFIX}${debugId}")}catch(e){}`;
116
+ };
117
+
118
+ /**
119
+ * Extracts the Debug ID from a bundle source string by locating the pattern
120
+ * "{@link DEBUG_ID_METADATA_PREFIX}`[DEBUG-ID]`"
121
+ *
122
+ * @param code - The source code of the bundle to search within.
123
+ * @returns The extracted Debug ID, or `undefined` if not found.
124
+ */
125
+ export const getDebugIdFromBundleSource = (
126
+ code: string
127
+ ): string | undefined => {
128
+ const match = code.match(
129
+ new RegExp(
130
+ `${DEBUG_ID_METADATA_PREFIX}([0-9a-fA-F]{8}\\b-(?:[0-9a-fA-F]{4}\\b-){3}[0-9a-fA-F]{12})`
131
+ )
132
+ );
133
+
134
+ return match ? match[1] : undefined;
135
+ };
136
+
137
+ /**
138
+ * Creates a unique Debug ID from the given bundle, by using the content of its modules.
139
+ * @param bundle The bundle to create the Debug ID from.
140
+ * @returns The computed Debug ID.
141
+ */
142
+ export const createDebugIdFromBundle = (bundle: Bundle): string => {
143
+ const hash = createHash('md5');
144
+ hash.update(bundle.pre);
145
+ for (const [, code] of bundle.modules) {
146
+ hash.update(code);
147
+ }
148
+
149
+ hash.update(bundle.post);
150
+
151
+ return createDebugIdFromString(hash.digest('hex'));
152
+ };
153
+
154
+ /**
155
+ * Creates a unique Debug ID from the given string.
156
+ * Ref: https://github.com/expo/expo/blob/94a124894a355ad6e24f4bac5144986380686157/packages/%40expo/metro-config/src/serializer/debugId.ts#L15
157
+ * @param str The string to create the Debug ID from.
158
+ * @returns The computed Debug ID.
159
+ */
160
+ export const createDebugIdFromString = (str: string): string => {
161
+ const md5sum = createHash('md5');
162
+ md5sum.update(str);
163
+ const md5Hash = md5sum.digest('hex');
164
+
165
+ // Position 16 is fixed to either 8, 9, a, or b in the uuid v4 spec (10xx in binary)
166
+ // RFC 4122 section 4.4
167
+ const v4variant = ['8', '9', 'a', 'b'][
168
+ md5Hash.substring(16, 17).charCodeAt(0) % 4
169
+ ] as string;
170
+
171
+ return `${md5Hash.substring(0, 8)}-${md5Hash.substring(
172
+ 8,
173
+ 12
174
+ )}-4${md5Hash.substring(13, 16)}-${v4variant}${md5Hash.substring(
175
+ 17,
176
+ 20
177
+ )}-${md5Hash.substring(20)}`.toLowerCase();
178
+ };
179
+
180
+ /**
181
+ * Injects the given debug ID in the given code, and returns the modified code.
182
+ *
183
+ * It looks for a specific placeholder defined in {@link DEBUG_ID_PLACEHOLDER}, and replaces
184
+ * all its occurences with the given Debug ID.
185
+ * @param code The code to inject the Debug ID into.
186
+ * @param debugId The Debug ID to inject.
187
+ * @returns The modified code with the injected Debug ID.
188
+ */
189
+ export const injectDebugIdInCode = (code: string, debugId: string): string => {
190
+ return code.replace(new RegExp(DEBUG_ID_PLACEHOLDER, 'g'), debugId);
191
+ };
192
+
193
+ /**
194
+ * Injects the given Debug ID in the given code (as a comment at the end of the file), and in the
195
+ * given sourcemap (as a top-level JSON property).
196
+ * @param debugId The Debug ID to inject.
197
+ * @param code The code to inject the Debug ID in.
198
+ * @param sourcemap The sourcemap to inject the Debug ID in.
199
+ * @returns The modified {@link MetroBundleWithMap} with the Debug ID
200
+ */
201
+ export const injectDebugIdInCodeAndSourceMap = (
202
+ debugId: string,
203
+ code: string,
204
+ sourcemap: string
205
+ ): MetroBundleWithMap => {
206
+ let codeWithDebugId = code;
207
+
208
+ if (_isDebugIdInBundle(debugId, code)) {
209
+ codeWithDebugId = _replaceDebugIdInBundle(debugId, code);
210
+ } else {
211
+ codeWithDebugId = _insertDebugIdCommentInBundle(debugId, code);
212
+ }
213
+
214
+ // Insert the Debug ID as a top-level property of the sourcemap
215
+ const bundleMap: Record<string, unknown> = JSON.parse(sourcemap);
216
+ bundleMap['debugId'] = debugId;
217
+ return { code: codeWithDebugId, map: JSON.stringify(bundleMap) };
218
+ };
219
+
220
+ /**
221
+ * [INTERNAL] Checks if the debug ID is in the bundle, and prints a warning if it does not match the given one.
222
+ */
223
+ export const _isDebugIdInBundle = (
224
+ debugId: string,
225
+ bundleCode: string
226
+ ): boolean => {
227
+ const match = bundleCode.match(DEBUG_ID_BUNDLE_REGEX);
228
+ if (!match || match.length < 2) {
229
+ return false;
230
+ }
231
+
232
+ if (match[2] !== debugId) {
233
+ console.warn(
234
+ '[DATADOG METRO PLUGIN] The debug ID found in the file does not match the calculated debug ID.'
235
+ );
236
+ }
237
+
238
+ return true;
239
+ };
240
+
241
+ /**
242
+ * Checks if the virtual Debug ID module exists in the given modules.
243
+ * @param modules - The list of modules in which to look for the Debug ID.
244
+ * @returns `true` if the Debug ID module exists, `false` otherwise.
245
+ */
246
+ export const checkIfDebugIdModuleExists = (
247
+ modules: readonly Module[]
248
+ ): boolean =>
249
+ modules.findIndex(module => module.path === DEBUG_ID_MODULE_PATH) !== -1;
250
+
251
+ /**
252
+ * [INTERNAL] Replaces the existing Debug ID comment in the bundle with a new one, containing the given Debug ID.
253
+ */
254
+ export const _replaceDebugIdInBundle = (
255
+ debugId: string,
256
+ bundleCode: string
257
+ ): string => {
258
+ return bundleCode.replace(
259
+ DEBUG_ID_BUNDLE_REGEX,
260
+ `${DEBUG_ID_COMMENT}${debugId}`
261
+ );
262
+ };
263
+
264
+ /**
265
+ * [INTERNAL] Inserts the Debug ID comment in the bundle in the correct position.
266
+ */
267
+ export const _insertDebugIdCommentInBundle = (
268
+ debugId: string,
269
+ bundleCode: string
270
+ ): string => {
271
+ const debugIdComment = `${DEBUG_ID_COMMENT}${debugId}`;
272
+ const indexOfSourceMapComment = bundleCode.lastIndexOf(SOURCE_MAP_COMMENT);
273
+ if (indexOfSourceMapComment === -1) {
274
+ return `${bundleCode}\n${debugIdComment}`;
275
+ }
276
+ const before = bundleCode.substring(0, indexOfSourceMapComment);
277
+ const after = bundleCode.substring(indexOfSourceMapComment);
278
+ return `${before}${debugIdComment}\n${after}`;
279
+ };
@@ -0,0 +1,97 @@
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 type { MetroConfig } from 'metro';
7
+
8
+ import {
9
+ createDatadogMetroSerializer,
10
+ unstable_beforeAssetSerializationPlugin
11
+ } from './metroSerializer';
12
+ import type {
13
+ DatadogExpoConfigOptions,
14
+ DefaultConfigOptions
15
+ } from './types/expoTypes';
16
+ import type { DatadogMetroSerializer } from './types/metroTypes';
17
+ import { getDefaultExpoConfig } from './utils';
18
+
19
+ /**
20
+ * Custom Datadog Metro Configuration.
21
+ */
22
+ export type DatadogMetroConfigOptions = {
23
+ /**
24
+ * Determines whether a Debug ID should be injected into bundles and sourcemaps.
25
+ *
26
+ * The Debug ID establishes a unique connection between a bundle and its corresponding sourcemap.
27
+ * It is highly recommended to keep this enabled unless you have a specific reason to disable it.
28
+ *
29
+ * Default: `true`
30
+ */
31
+ useDebugId?: boolean;
32
+ };
33
+
34
+ /**
35
+ * Extends the Metro bundler configuration to integrate with Datadog.
36
+ *
37
+ * *Note: If a custom serializer is used and `config.useDebugId` is set to `true` (as it is by default),
38
+ * you must manually invoke `options.datadogBundleCallback` within the serializer.*
39
+ */
40
+ export function withDatadogMetroConfig(
41
+ config: MetroConfig & DatadogMetroConfigOptions
42
+ ): MetroConfig {
43
+ let newConfig = config;
44
+
45
+ if (config.useDebugId ?? true) {
46
+ newConfig = withDatadogDebugId(config);
47
+ }
48
+
49
+ return {
50
+ ...newConfig,
51
+ transformer: {
52
+ ...newConfig.transformer
53
+ }
54
+ };
55
+ }
56
+
57
+ /**
58
+ * Extends the Expo configuration to integrate with Datadog.
59
+ * @param config
60
+ * @returns
61
+ */
62
+ export function getDatadogExpoConfig(
63
+ projectRoot: string,
64
+ options: DefaultConfigOptions & DatadogExpoConfigOptions = {}
65
+ ): DefaultConfigOptions {
66
+ const plugins = options.unstable_beforeAssetSerializationPlugins ?? [];
67
+ const datadogOptions: DefaultConfigOptions = {
68
+ ...options,
69
+ unstable_beforeAssetSerializationPlugins: [
70
+ ...plugins,
71
+ unstable_beforeAssetSerializationPlugin
72
+ ]
73
+ };
74
+
75
+ return (options.getDefaultConfig ?? getDefaultExpoConfig)(
76
+ projectRoot,
77
+ datadogOptions
78
+ );
79
+ }
80
+
81
+ /**
82
+ * Extends the Metro bundler configuration by enabling Debug ID injection.
83
+ * Ref: https://github.com/tc39/ecma426/blob/main/proposals/debug-id.md
84
+ */
85
+ export function withDatadogDebugId(config: MetroConfig): MetroConfig {
86
+ const customSerializer = createDatadogMetroSerializer(
87
+ config.serializer?.customSerializer || undefined
88
+ ) as DatadogMetroSerializer;
89
+
90
+ return {
91
+ ...config,
92
+ serializer: {
93
+ ...config.serializer,
94
+ customSerializer
95
+ }
96
+ };
97
+ }
@@ -0,0 +1,173 @@
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
+ * Portions of this code are adapted from Sentry's Metro configuration:
7
+ * https://github.com/getsentry/sentry-react-native/blob/17c0c2e8913030e4826d055284a735efad637312/packages/core/src/js/tools/sentryMetroSerializer.ts
8
+ */
9
+
10
+ // eslint-disable-next-line import/no-extraneous-dependencies
11
+ import baseJSBundle from 'metro/src/DeltaBundler/Serializers/baseJSBundle';
12
+ // eslint-disable-next-line import/no-extraneous-dependencies
13
+ import bundleToString from 'metro/src/lib/bundleToString';
14
+
15
+ import {
16
+ DEBUG_ID_PLACEHOLDER,
17
+ addDebugIdModule,
18
+ checkIfDebugIdModuleExists,
19
+ createDebugIdFromBundle,
20
+ createDebugIdModule,
21
+ getDebugIdFromBundleSource,
22
+ injectDebugIdInCode,
23
+ injectDebugIdInCodeAndSourceMap
24
+ } from './debugIdHelper';
25
+ import type {
26
+ Bundle,
27
+ DatadogDebugIdModule,
28
+ DatadogMetroSerializer,
29
+ MetroSerializer,
30
+ MixedOutput,
31
+ Module,
32
+ ReadOnlyGraph
33
+ } from './types/metroTypes';
34
+ import {
35
+ convertSerializerOutput as getMetroBundleWithMap,
36
+ getSortedModules,
37
+ metroSourceMapString
38
+ } from './utils';
39
+
40
+ /**
41
+ * Creates a Metro serializer that adds a Debug ID module to the bundle.
42
+ * This module injects the Debug ID at runtime, making it globally accessible.
43
+ *
44
+ * @param customSerializer - Optional custom {@link MetroSerializer}. If provided, you are responsible
45
+ * for invoking `options.datadogBundleCallback` within it.
46
+ */
47
+ export const createDatadogMetroSerializer = (
48
+ customSerializer?: MetroSerializer
49
+ ): DatadogMetroSerializer => {
50
+ const serializer = customSerializer || createDefaultMetroSerializer();
51
+ return async (entryPoint, preModules, graph, options) => {
52
+ // Skip for hot reload mode
53
+ if (graph.transformOptions.hot) {
54
+ return serializer(entryPoint, preModules, graph, options);
55
+ }
56
+
57
+ // Make sure we don't add the Debug ID module twice
58
+ if (checkIfDebugIdModuleExists(preModules)) {
59
+ return serializer(entryPoint, preModules, graph, options);
60
+ }
61
+
62
+ // Create a virtual module to inject the Debug ID in a globally accessible property
63
+ const debugIdModule = createDebugIdModule(DEBUG_ID_PLACEHOLDER);
64
+
65
+ // Set the datadogBundleCallback in the options, to be used later by the serializer
66
+ options.datadogBundleCallback = createDatadogBundleCallback(
67
+ debugIdModule
68
+ );
69
+
70
+ // Add the Debug ID virtual module to the pre-modules
71
+ const preModulesWithDebugId = addDebugIdModule(
72
+ preModules,
73
+ debugIdModule
74
+ );
75
+
76
+ // Run serializer
77
+ const serializerOutput = serializer(
78
+ entryPoint,
79
+ preModulesWithDebugId,
80
+ graph,
81
+ options
82
+ );
83
+
84
+ // Get serialized code and sourcemap
85
+ const { code, map } = await getMetroBundleWithMap(serializerOutput);
86
+
87
+ // Retrieve the Debug ID, previously injected as a snippet of code in a virtual module by `datadogBundleCallback`.
88
+ const debugId = getDebugIdFromBundleSource(code);
89
+ if (!debugId) {
90
+ throw new Error(
91
+ '[DATADOG METRO PLUGIN] Debug ID was not found in the bundle. Call `options.datadogBundleCallback` if you are using a custom serializer.'
92
+ );
93
+ }
94
+
95
+ // Inject the Debug ID as a comment in the bundle, and as a top-level property in the sourcemap.
96
+ const result = injectDebugIdInCodeAndSourceMap(debugId, code, map);
97
+
98
+ return result;
99
+ };
100
+ };
101
+
102
+ /**
103
+ * Creates a Metro Bundle Serializer like metro does by default, while also calling the datadogBundleCallback.
104
+ * https://github.com/facebook/metro/blob/a3d021a0d021b5706372059f472715c63019e044/packages/metro/src/Server.js#L272-L307
105
+ */
106
+ export const createDefaultMetroSerializer = (): MetroSerializer => {
107
+ return (entryPoint, preModules, graph, options) => {
108
+ // Default metro bundle
109
+ // https://github.com/facebook/metro/blob/a3d021a0d021b5706372059f472715c63019e044/packages/metro/src/DeltaBundler/Serializers/baseJSBundle.js#L25
110
+ let bundle = baseJSBundle(entryPoint, preModules, graph, options);
111
+
112
+ // Modify the bundle through the datadogBundleCallback, if we are not in hot-reload mode
113
+ if (
114
+ (options as any).datadogBundleCallback &&
115
+ !graph.transformOptions.hot
116
+ ) {
117
+ bundle = (options as any).datadogBundleCallback(bundle);
118
+ }
119
+
120
+ // Retrieves the processed code from the bundle
121
+ const { code } = bundleToString(bundle);
122
+
123
+ // If we are in hot-reload mode, we skip sourcemaps generation, and only return the code.
124
+ if (graph.transformOptions.hot) {
125
+ return code;
126
+ }
127
+
128
+ // Force generation of sourcemaps
129
+ const map = metroSourceMapString(
130
+ [...preModules, ...getSortedModules(graph, options)],
131
+ {
132
+ processModuleFilter: options.processModuleFilter,
133
+ shouldAddToIgnoreList: options.shouldAddToIgnoreList
134
+ }
135
+ );
136
+
137
+ return { code, map };
138
+ };
139
+ };
140
+
141
+ /**
142
+ * Creates a callback used to transform the given bundle by injecting the Debug ID snippet.
143
+ * @param debugIdModule - The virtual Debug ID module
144
+ * @returns The bundle callback
145
+ */
146
+ export const createDatadogBundleCallback = (
147
+ debugIdModule: DatadogDebugIdModule
148
+ ) => {
149
+ return (bundle: Bundle) => {
150
+ const debugId = createDebugIdFromBundle(bundle);
151
+ const code = debugIdModule.getSource().toString();
152
+ debugIdModule.setSource(injectDebugIdInCode(code, debugId));
153
+ bundle.pre = injectDebugIdInCode(bundle.pre, debugId);
154
+ return bundle;
155
+ };
156
+ };
157
+
158
+ /**
159
+ * Adds Debug ID module for runtime injection, used for Expo.
160
+ */
161
+ export function unstable_beforeAssetSerializationPlugin({
162
+ premodules,
163
+ debugId
164
+ }: {
165
+ graph: ReadOnlyGraph<MixedOutput>;
166
+ premodules: Module[];
167
+ debugId?: string;
168
+ }): Module[] {
169
+ if (!debugId || checkIfDebugIdModuleExists(premodules)) {
170
+ return premodules;
171
+ }
172
+ return [...addDebugIdModule(premodules, createDebugIdModule(debugId))];
173
+ }
@@ -0,0 +1,64 @@
1
+ // The MIT License (MIT)
2
+
3
+ // Copyright (c) 2015-present 650 Industries, Inc. (aka Expo)
4
+
5
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ // of this software and associated documentation files (the "Software"), to deal
7
+ // in the Software without restriction, including without limitation the rights
8
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ // copies of the Software, and to permit persons to whom the Software is
10
+ // furnished to do so, subject to the following conditions:
11
+
12
+ // The above copyright notice and this permission notice shall be included in all
13
+ // copies or substantial portions of the Software.
14
+
15
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ // SOFTWARE.
22
+
23
+ import type { MixedOutput, Module, ReadOnlyGraph } from 'metro';
24
+
25
+ // https://github.com/expo/expo/blob/15350ff92b31782543b455236966e7f67615d774/packages/%40expo/metro-config/src/ExpoMetroConfig.ts
26
+ export interface DefaultConfigOptions {
27
+ /** @deprecated */
28
+ mode?: 'exotic';
29
+ /**
30
+ * **Experimental:** Enable CSS support for Metro web, and shim on native.
31
+ *
32
+ * This is an experimental feature and may change in the future. The underlying implementation
33
+ * is subject to change, and native support for CSS Modules may be added in the future during a non-major SDK release.
34
+ */
35
+ isCSSEnabled?: boolean;
36
+
37
+ /**
38
+ * **Experimental:** Modify premodules before a code asset is serialized
39
+ *
40
+ * This is an experimental feature and may change in the future. The underlying implementation
41
+ * is subject to change.
42
+ */
43
+ unstable_beforeAssetSerializationPlugins?: ((serializationInput: {
44
+ graph: ReadOnlyGraph<MixedOutput>;
45
+ premodules: Module[];
46
+ debugId?: string;
47
+ }) => Module[])[];
48
+ }
49
+
50
+ /*
51
+ * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
52
+ * This product includes software developed at Datadog (https://www.datadoghq.com/).
53
+ * Copyright 2016-Present Datadog, Inc.
54
+ */
55
+ export interface DatadogExpoConfigOptions {
56
+ /**
57
+ * You can use this property to specify your getDefaultConfig function. By default, the
58
+ * `getDefaultConfig` function from `@expo/metro-config` will be used.
59
+ */
60
+ getDefaultConfig?: (
61
+ projectRoot: string,
62
+ options: DefaultConfigOptions
63
+ ) => DefaultConfigOptions;
64
+ }