@crimson-education/browser-logger 3.0.5 → 3.0.6-beta.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 (37) hide show
  1. package/lib/index.d.ts +12 -12
  2. package/lib/index.js +69 -69
  3. package/lib/logger/consoleTransport.d.ts +36 -36
  4. package/lib/logger/consoleTransport.js +80 -80
  5. package/lib/logger/datadogTransport.d.ts +7 -7
  6. package/lib/logger/datadogTransport.js +20 -20
  7. package/lib/logger/index.d.ts +15 -15
  8. package/lib/logger/index.js +147 -147
  9. package/lib/logger/index.test.d.ts +1 -1
  10. package/lib/logger/index.test.js +59 -59
  11. package/lib/logger/utils.d.ts +14 -14
  12. package/lib/logger/utils.js +31 -31
  13. package/lib/reporters/amplifyReporter.d.ts +85 -85
  14. package/lib/reporters/amplifyReporter.js +222 -222
  15. package/lib/reporters/amplifyReporter.js.map +1 -1
  16. package/lib/reporters/amplifyReporter.test.d.ts +1 -1
  17. package/lib/reporters/amplifyReporter.test.js +50 -50
  18. package/lib/reporters/datadogReporter.d.ts +85 -85
  19. package/lib/reporters/datadogReporter.js +124 -124
  20. package/lib/reporters/gtmReporter.d.ts +8 -8
  21. package/lib/reporters/gtmReporter.js +56 -56
  22. package/lib/reporters/index.d.ts +66 -66
  23. package/lib/reporters/index.js +212 -212
  24. package/lib/reporters/logReporter.d.ts +34 -34
  25. package/lib/reporters/logReporter.js +61 -61
  26. package/lib/types/index.d.ts +2 -2
  27. package/lib/types/index.js +18 -18
  28. package/lib/types/logger.d.ts +77 -77
  29. package/lib/types/logger.js +10 -10
  30. package/lib/types/reporter.d.ts +154 -154
  31. package/lib/types/reporter.js +2 -2
  32. package/lib/utils.d.ts +9 -9
  33. package/lib/utils.js +31 -31
  34. package/lib/utils.test.d.ts +1 -1
  35. package/lib/utils.test.js +31 -31
  36. package/package.json +1 -1
  37. package/src/reporters/amplifyReporter.ts +2 -2
@@ -1,86 +1,86 @@
1
- import { IReporter, Metadata, ReporterConfigBase, ServiceInfo } from '../types';
2
- declare type AttributeMap = Record<string, string[] | string | null>;
3
- declare type AmplifyAutoTrackSource = 'pageView' | 'event' | 'session';
4
- export interface AmplifyReporterConfig extends ReporterConfigBase {
5
- /**
6
- * AWS Region for Amplify.
7
- */
8
- region: string;
9
- /**
10
- * The Identity Pool Id to use for reporting, if set to false, Auth.configure is not called.
11
- * This must be called manually for the reporter to work.
12
- */
13
- identityPoolId: string | false;
14
- /**
15
- * The Pinpoint App Id to report to.
16
- */
17
- analyticsAppId: string;
18
- /** Optional proxy URL */
19
- proxyUrl?: string;
20
- /**
21
- * The Cognito User Pool to configure in Auth.configure.
22
- * If you are using Cognito, it is better to set identityPoolId to false and configure Auth manually.
23
- */
24
- userPoolId?: string;
25
- /**
26
- * The Cognito Web Client Id to configure in Auth.configure.
27
- * If you are using Cognito, it is better to set identityPoolId to false and configure Auth manually.
28
- */
29
- userPoolWebClientId?: string;
30
- /**
31
- * If you want to track which page/url in your webapp is the most frequently viewed one, you can use this feature.
32
- * It will automatically send events containing url information when the page is visited.
33
- */
34
- autoTrackPageViews?: boolean;
35
- /**
36
- * If you want to track user interactions with elements on the page, you can use this feature.
37
- * All you need to do is attach the specified selectors to your dom element and turn on the auto tracking.
38
- */
39
- autoTrackEvents?: boolean;
40
- /**
41
- * A web session can be defined in different ways.
42
- * To keep it simple we define that the web session is active when the page is not hidden and inactive when the page is hidden.
43
- */
44
- autoTrackSessions?: boolean;
45
- /**
46
- * Optional function to run before autotracked analytics events are sent out.
47
- * The returned metadata is attached to the event.
48
- */
49
- beforeAutoTrack?(source: AmplifyAutoTrackSource): Metadata | undefined;
50
- /**
51
- * The data tag prefix to use for attributing HTML elements. Defaults to data-analytics-
52
- */
53
- selectorPrefix?: string;
54
- /**
55
- * Modify how the reporter sends events to Amplify.
56
- */
57
- buffering?: AmplifyReporterBufferingConfig;
58
- }
59
- /**
60
- * Configuration options for the buffering behavior of Pinpoint's event tracker.
61
- *
62
- * @see https://docs.amplify.aws/lib/analytics/getting-started/q/platform/js/#set-up-existing-analytics-backend
63
- */
64
- declare type AmplifyReporterBufferingConfig = {
65
- /** Number of items to buffer for sending. */
66
- bufferSize?: number;
67
- /** Number of events sent each time Pinpoint flushes. */
68
- flushSize?: number;
69
- /** Interval Pinpoint flushes analytics events. Measured in milliseconds. */
70
- flushInterval?: number;
71
- /** The maximum number of times Pinpoint will retry to send an event. */
72
- resendLimit?: number;
73
- };
74
- export declare function amplifyReporter(info: ServiceInfo, config: AmplifyReporterConfig): IReporter;
75
- /**
76
- * Pinpoint has strict attribute name and value length limits
77
- */
78
- export declare function asAttributeMap(values: Record<string, unknown>, groupValues?: boolean): AttributeMap;
79
- /**
80
- * Pinpoint expects `endpoint.attributes` and `endpoint.userAttributes` to have
81
- * values which are string arrays. This function takes in an object and ensures
82
- * all of its values are of type `string[]` to appease Pinpoint.
83
- */
84
- export declare function buildAttributeMap(values: Record<string, any>, parentKey?: string | undefined, groupValues?: boolean): AttributeMap;
85
- export {};
1
+ import { IReporter, Metadata, ReporterConfigBase, ServiceInfo } from '../types';
2
+ declare type AttributeMap = Record<string, string[] | string | null>;
3
+ declare type AmplifyAutoTrackSource = 'pageView' | 'event' | 'session';
4
+ export interface AmplifyReporterConfig extends ReporterConfigBase {
5
+ /**
6
+ * AWS Region for Amplify.
7
+ */
8
+ region: string;
9
+ /**
10
+ * The Identity Pool Id to use for reporting, if set to false, Auth.configure is not called.
11
+ * This must be called manually for the reporter to work.
12
+ */
13
+ identityPoolId: string | false;
14
+ /**
15
+ * The Pinpoint App Id to report to.
16
+ */
17
+ analyticsAppId: string;
18
+ /** Optional proxy URL */
19
+ proxyUrl?: string;
20
+ /**
21
+ * The Cognito User Pool to configure in Auth.configure.
22
+ * If you are using Cognito, it is better to set identityPoolId to false and configure Auth manually.
23
+ */
24
+ userPoolId?: string;
25
+ /**
26
+ * The Cognito Web Client Id to configure in Auth.configure.
27
+ * If you are using Cognito, it is better to set identityPoolId to false and configure Auth manually.
28
+ */
29
+ userPoolWebClientId?: string;
30
+ /**
31
+ * If you want to track which page/url in your webapp is the most frequently viewed one, you can use this feature.
32
+ * It will automatically send events containing url information when the page is visited.
33
+ */
34
+ autoTrackPageViews?: boolean;
35
+ /**
36
+ * If you want to track user interactions with elements on the page, you can use this feature.
37
+ * All you need to do is attach the specified selectors to your dom element and turn on the auto tracking.
38
+ */
39
+ autoTrackEvents?: boolean;
40
+ /**
41
+ * A web session can be defined in different ways.
42
+ * To keep it simple we define that the web session is active when the page is not hidden and inactive when the page is hidden.
43
+ */
44
+ autoTrackSessions?: boolean;
45
+ /**
46
+ * Optional function to run before autotracked analytics events are sent out.
47
+ * The returned metadata is attached to the event.
48
+ */
49
+ beforeAutoTrack?(source: AmplifyAutoTrackSource): Metadata | undefined;
50
+ /**
51
+ * The data tag prefix to use for attributing HTML elements. Defaults to data-analytics-
52
+ */
53
+ selectorPrefix?: string;
54
+ /**
55
+ * Modify how the reporter sends events to Amplify.
56
+ */
57
+ buffering?: AmplifyReporterBufferingConfig;
58
+ }
59
+ /**
60
+ * Configuration options for the buffering behavior of Pinpoint's event tracker.
61
+ *
62
+ * @see https://docs.amplify.aws/lib/analytics/getting-started/q/platform/js/#set-up-existing-analytics-backend
63
+ */
64
+ declare type AmplifyReporterBufferingConfig = {
65
+ /** Number of items to buffer for sending. */
66
+ bufferSize?: number;
67
+ /** Number of events sent each time Pinpoint flushes. */
68
+ flushSize?: number;
69
+ /** Interval Pinpoint flushes analytics events. Measured in milliseconds. */
70
+ flushInterval?: number;
71
+ /** The maximum number of times Pinpoint will retry to send an event. */
72
+ resendLimit?: number;
73
+ };
74
+ export declare function amplifyReporter(info: ServiceInfo, config: AmplifyReporterConfig): IReporter;
75
+ /**
76
+ * Pinpoint has strict attribute name and value length limits
77
+ */
78
+ export declare function asAttributeMap(values: Record<string, unknown>, groupValues?: boolean): AttributeMap;
79
+ /**
80
+ * Pinpoint expects `endpoint.attributes` and `endpoint.userAttributes` to have
81
+ * values which are string arrays. This function takes in an object and ensures
82
+ * all of its values are of type `string[]` to appease Pinpoint.
83
+ */
84
+ export declare function buildAttributeMap(values: Record<string, any>, parentKey?: string | undefined, groupValues?: boolean): AttributeMap;
85
+ export {};
86
86
  //# sourceMappingURL=amplifyReporter.d.ts.map
@@ -1,223 +1,223 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.buildAttributeMap = exports.asAttributeMap = exports.amplifyReporter = void 0;
4
- const auth_1 = require("@aws-amplify/auth");
5
- const analytics_1 = require("@aws-amplify/analytics");
6
- const protocol_http_1 = require("@aws-sdk/protocol-http");
7
- const logger_1 = require("../logger");
8
- function amplifyReporter(info, config) {
9
- var _a;
10
- if (config.identityPoolId !== false) {
11
- auth_1.Auth.configure({
12
- region: config.region,
13
- identityPoolId: config.identityPoolId,
14
- userPoolId: config.userPoolId,
15
- userPoolWebClientId: config.userPoolWebClientId,
16
- });
17
- }
18
- const wrapAutoTrackMiddleware = (source) => {
19
- const { beforeAutoTrack } = config;
20
- return typeof beforeAutoTrack === 'function' ? () => { var _a; return (_a = beforeAutoTrack(source)) !== null && _a !== void 0 ? _a : {}; } : undefined;
21
- };
22
- const allMetadata = asAttributeMap({
23
- appName: info.service,
24
- service: info.service,
25
- domain: window.location.host,
26
- environment: info.environment,
27
- version: info.version,
28
- });
29
- analytics_1.Analytics.configure({
30
- region: config.region,
31
- appId: config.analyticsAppId,
32
- endpoint: {
33
- attributes: allMetadata,
34
- },
35
- ...config.buffering,
36
- });
37
- // Session autotracking is enabled by default for backwards compatibility reasons, so we _must_
38
- // call this unconditionally to ensure we opt out of session tracking when `autoTrackSessions` isn't set
39
- // See: https://docs.amplify.aws/lib/analytics/autotrack/q/platform/js/#session-tracking
40
- analytics_1.Analytics.autoTrack('session', {
41
- enable: config.autoTrackSessions === true,
42
- attributes: wrapAutoTrackMiddleware('session'),
43
- });
44
- if (config.autoTrackPageViews) {
45
- analytics_1.Analytics.autoTrack('pageView', {
46
- enable: true,
47
- eventName: 'pageView',
48
- type: 'SPA',
49
- provider: 'AWSPinpoint',
50
- attributes: wrapAutoTrackMiddleware('pageView'),
51
- });
52
- }
53
- if (config.autoTrackEvents) {
54
- analytics_1.Analytics.autoTrack('event', {
55
- enable: true,
56
- selectorPrefix: (_a = config.selectorPrefix) !== null && _a !== void 0 ? _a : 'data-analytics-',
57
- attributes: wrapAutoTrackMiddleware('event'),
58
- });
59
- }
60
- if (config.proxyUrl) {
61
- installPinpointProxy(new URL(config.proxyUrl));
62
- }
63
- const reporter = {
64
- trackEvent: function (event) {
65
- analytics_1.Analytics.record({
66
- name: event.message,
67
- attributes: asAttributeMap({
68
- ...event.metadata,
69
- ...event.tags,
70
- }, false),
71
- metrics: event.metrics,
72
- });
73
- },
74
- addBreadcrumb: function (breadcrumb) {
75
- reporter.trackEvent({
76
- message: breadcrumb.message,
77
- metadata: {
78
- category: breadcrumb.category,
79
- ...breadcrumb.metadata,
80
- },
81
- });
82
- },
83
- addMetadata: function (metadata) {
84
- Object.assign(allMetadata, asAttributeMap(metadata, true));
85
- analytics_1.Analytics.updateEndpoint({
86
- attributes: allMetadata,
87
- }).catch(() => {
88
- // Swallow; see: https://crimsonhq.slack.com/archives/G4UN6Q4KF/p1648599302847539
89
- });
90
- },
91
- setUser: function (user) {
92
- var _a, _b;
93
- const userMetadata = user
94
- ? asAttributeMap({
95
- userId: user.id,
96
- })
97
- : {};
98
- Object.assign(allMetadata, asAttributeMap(userMetadata, true));
99
- analytics_1.Analytics.updateEndpoint({
100
- userId: (_a = user === null || user === void 0 ? void 0 : user.id) !== null && _a !== void 0 ? _a : '',
101
- attributes: allMetadata,
102
- userAttributes: user
103
- ? asAttributeMap({
104
- id: user.id,
105
- email: user.email,
106
- name: (_b = user.name) !== null && _b !== void 0 ? _b : user.email,
107
- username: user.username,
108
- })
109
- : {},
110
- }).catch(() => {
111
- // Swallow; see: https://crimsonhq.slack.com/archives/G4UN6Q4KF/p1648599302847539
112
- });
113
- },
114
- setRouteName: function (routeName) {
115
- reporter.addMetadata({ routeName });
116
- },
117
- setPageName: function (pageName) {
118
- reporter.addMetadata({ pageName });
119
- },
120
- };
121
- return reporter;
122
- }
123
- exports.amplifyReporter = amplifyReporter;
124
- /**
125
- * Pinpoint has strict attribute name and value length limits
126
- */
127
- function asAttributeMap(values, groupValues = true) {
128
- const attributeMap = buildAttributeMap(values, undefined, groupValues);
129
- const checkedEntries = Object.entries(attributeMap).map(([key, value]) => {
130
- var _a, _b;
131
- const truncatedKey = key.length > 50 ? `___${key.slice(-47)}` : key;
132
- const truncatedValue = Array.isArray(value)
133
- ? (_a = value === null || value === void 0 ? void 0 : value.map((val) => val.slice(0, 100))) !== null && _a !== void 0 ? _a : null
134
- : (_b = value === null || value === void 0 ? void 0 : value.slice(0, 100)) !== null && _b !== void 0 ? _b : null;
135
- return [truncatedKey, truncatedValue];
136
- });
137
- // Pinpoint only accepts 40 attributes
138
- if (checkedEntries.length > 40) {
139
- logger_1.logger.error(`Amplify only allows 40 attributes per event, truncating to 40 attributes`, {
140
- attributes: checkedEntries,
141
- });
142
- checkedEntries.length = 40;
143
- }
144
- return Object.fromEntries(checkedEntries);
145
- }
146
- exports.asAttributeMap = asAttributeMap;
147
- /**
148
- * Pinpoint expects `endpoint.attributes` and `endpoint.userAttributes` to have
149
- * values which are string arrays. This function takes in an object and ensures
150
- * all of its values are of type `string[]` to appease Pinpoint.
151
- */
152
- function buildAttributeMap(values, parentKey = undefined, groupValues = true) {
153
- const valuesWithStringArrays = {};
154
- Object.entries(values).forEach(([key, value]) => {
155
- const combinedKey = parentKey ? [parentKey, key].join('.') : key;
156
- if (!value) {
157
- valuesWithStringArrays[combinedKey] = null;
158
- }
159
- else if (groupValues && Array.isArray(value)) {
160
- valuesWithStringArrays[combinedKey] = value.map((element) => typeof element === 'string' ? element : JSON.stringify(element));
161
- }
162
- else if (typeof value === 'object') {
163
- const flattenedAttribute = buildAttributeMap(value, combinedKey, groupValues);
164
- Object.assign(valuesWithStringArrays, flattenedAttribute);
165
- }
166
- else {
167
- const stringValue = typeof value === 'string' ? value : JSON.stringify(value);
168
- valuesWithStringArrays[combinedKey] = groupValues ? [stringValue] : stringValue;
169
- }
170
- });
171
- return valuesWithStringArrays;
172
- }
173
- exports.buildAttributeMap = buildAttributeMap;
174
- function installPinpointProxy(proxyUrl) {
175
- // No public API for overriding where the Pinpoint client sends events to... 🤮
176
- // In theory you can pass in an `endpoint` to the Pinpoint client's constructor like any other AWS
177
- // client, but Amplify's analytics doesn't expose anything we can use to get an endpoint threaded
178
- // down to the Pinpoint client's constructor.
179
- //
180
- // The Pinpoint client _also_ isn't available synchronously because it is instantiated when events
181
- // get sent out, and then reconfigured whenever the API credentials change. We need to hook `_initClients`
182
- // to ensure that the Pinpoint client being used is always patched with our custom endpoint.
183
- const provider = analytics_1.Analytics.getPluggable('AWSPinpoint');
184
- if (!provider || typeof provider._initClients !== 'function') {
185
- logger_1.logger.error('Installation of the Pinpoint proxy failed. This likely means the internals of the @aws-amplify/analytics package have changed.');
186
- return;
187
- }
188
- const originalInitClients = provider._initClients;
189
- const requestMiddleware = (next) => async (args) => {
190
- const pinpointClient = provider.pinpointClient;
191
- if (pinpointClient && proxyUrl.pathname !== '/' && protocol_http_1.HttpRequest.isInstance(args.request)) {
192
- // Add proxyUrl.pathname to final request url if it was provided
193
- const shouldStripSlash = proxyUrl.pathname.endsWith('/');
194
- args.request.path = `${proxyUrl.pathname}${args.request.path.slice(shouldStripSlash ? 1 : 0)}`;
195
- // Wrap request body so the proxy has signing info
196
- if (typeof args.request.body === 'string') {
197
- const credentials = await pinpointClient.config.credentials();
198
- args.request.body = JSON.stringify({
199
- credentials,
200
- data: JSON.parse(args.request.body),
201
- });
202
- }
203
- }
204
- return next(args);
205
- };
206
- provider._initClients = async (credentials) => {
207
- const result = await originalInitClients.call(provider, credentials);
208
- const pinpointClient = provider.pinpointClient;
209
- if (pinpointClient) {
210
- pinpointClient.config.endpoint = () => Promise.resolve({
211
- hostname: proxyUrl.hostname,
212
- // Passing proxyUrl.pathname here doesn't work; it gets overridden
213
- path: '/',
214
- port: undefined,
215
- protocol: proxyUrl.protocol,
216
- });
217
- pinpointClient.middlewareStack.remove(requestMiddleware);
218
- pinpointClient.middlewareStack.add(requestMiddleware, { step: 'finalizeRequest' });
219
- }
220
- return result;
221
- };
222
- }
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildAttributeMap = exports.asAttributeMap = exports.amplifyReporter = void 0;
4
+ const Auth_1 = require("@aws-amplify/auth/lib/Auth");
5
+ const Analytics_1 = require("@aws-amplify/analytics/lib/Analytics");
6
+ const protocol_http_1 = require("@aws-sdk/protocol-http");
7
+ const logger_1 = require("../logger");
8
+ function amplifyReporter(info, config) {
9
+ var _a;
10
+ if (config.identityPoolId !== false) {
11
+ Auth_1.Auth.configure({
12
+ region: config.region,
13
+ identityPoolId: config.identityPoolId,
14
+ userPoolId: config.userPoolId,
15
+ userPoolWebClientId: config.userPoolWebClientId,
16
+ });
17
+ }
18
+ const wrapAutoTrackMiddleware = (source) => {
19
+ const { beforeAutoTrack } = config;
20
+ return typeof beforeAutoTrack === 'function' ? () => { var _a; return (_a = beforeAutoTrack(source)) !== null && _a !== void 0 ? _a : {}; } : undefined;
21
+ };
22
+ const allMetadata = asAttributeMap({
23
+ appName: info.service,
24
+ service: info.service,
25
+ domain: window.location.host,
26
+ environment: info.environment,
27
+ version: info.version,
28
+ });
29
+ Analytics_1.Analytics.configure({
30
+ region: config.region,
31
+ appId: config.analyticsAppId,
32
+ endpoint: {
33
+ attributes: allMetadata,
34
+ },
35
+ ...config.buffering,
36
+ });
37
+ // Session autotracking is enabled by default for backwards compatibility reasons, so we _must_
38
+ // call this unconditionally to ensure we opt out of session tracking when `autoTrackSessions` isn't set
39
+ // See: https://docs.amplify.aws/lib/analytics/autotrack/q/platform/js/#session-tracking
40
+ Analytics_1.Analytics.autoTrack('session', {
41
+ enable: config.autoTrackSessions === true,
42
+ attributes: wrapAutoTrackMiddleware('session'),
43
+ });
44
+ if (config.autoTrackPageViews) {
45
+ Analytics_1.Analytics.autoTrack('pageView', {
46
+ enable: true,
47
+ eventName: 'pageView',
48
+ type: 'SPA',
49
+ provider: 'AWSPinpoint',
50
+ attributes: wrapAutoTrackMiddleware('pageView'),
51
+ });
52
+ }
53
+ if (config.autoTrackEvents) {
54
+ Analytics_1.Analytics.autoTrack('event', {
55
+ enable: true,
56
+ selectorPrefix: (_a = config.selectorPrefix) !== null && _a !== void 0 ? _a : 'data-analytics-',
57
+ attributes: wrapAutoTrackMiddleware('event'),
58
+ });
59
+ }
60
+ if (config.proxyUrl) {
61
+ installPinpointProxy(new URL(config.proxyUrl));
62
+ }
63
+ const reporter = {
64
+ trackEvent: function (event) {
65
+ Analytics_1.Analytics.record({
66
+ name: event.message,
67
+ attributes: asAttributeMap({
68
+ ...event.metadata,
69
+ ...event.tags,
70
+ }, false),
71
+ metrics: event.metrics,
72
+ });
73
+ },
74
+ addBreadcrumb: function (breadcrumb) {
75
+ reporter.trackEvent({
76
+ message: breadcrumb.message,
77
+ metadata: {
78
+ category: breadcrumb.category,
79
+ ...breadcrumb.metadata,
80
+ },
81
+ });
82
+ },
83
+ addMetadata: function (metadata) {
84
+ Object.assign(allMetadata, asAttributeMap(metadata, true));
85
+ Analytics_1.Analytics.updateEndpoint({
86
+ attributes: allMetadata,
87
+ }).catch(() => {
88
+ // Swallow; see: https://crimsonhq.slack.com/archives/G4UN6Q4KF/p1648599302847539
89
+ });
90
+ },
91
+ setUser: function (user) {
92
+ var _a, _b;
93
+ const userMetadata = user
94
+ ? asAttributeMap({
95
+ userId: user.id,
96
+ })
97
+ : {};
98
+ Object.assign(allMetadata, asAttributeMap(userMetadata, true));
99
+ Analytics_1.Analytics.updateEndpoint({
100
+ userId: (_a = user === null || user === void 0 ? void 0 : user.id) !== null && _a !== void 0 ? _a : '',
101
+ attributes: allMetadata,
102
+ userAttributes: user
103
+ ? asAttributeMap({
104
+ id: user.id,
105
+ email: user.email,
106
+ name: (_b = user.name) !== null && _b !== void 0 ? _b : user.email,
107
+ username: user.username,
108
+ })
109
+ : {},
110
+ }).catch(() => {
111
+ // Swallow; see: https://crimsonhq.slack.com/archives/G4UN6Q4KF/p1648599302847539
112
+ });
113
+ },
114
+ setRouteName: function (routeName) {
115
+ reporter.addMetadata({ routeName });
116
+ },
117
+ setPageName: function (pageName) {
118
+ reporter.addMetadata({ pageName });
119
+ },
120
+ };
121
+ return reporter;
122
+ }
123
+ exports.amplifyReporter = amplifyReporter;
124
+ /**
125
+ * Pinpoint has strict attribute name and value length limits
126
+ */
127
+ function asAttributeMap(values, groupValues = true) {
128
+ const attributeMap = buildAttributeMap(values, undefined, groupValues);
129
+ const checkedEntries = Object.entries(attributeMap).map(([key, value]) => {
130
+ var _a, _b;
131
+ const truncatedKey = key.length > 50 ? `___${key.slice(-47)}` : key;
132
+ const truncatedValue = Array.isArray(value)
133
+ ? (_a = value === null || value === void 0 ? void 0 : value.map((val) => val.slice(0, 100))) !== null && _a !== void 0 ? _a : null
134
+ : (_b = value === null || value === void 0 ? void 0 : value.slice(0, 100)) !== null && _b !== void 0 ? _b : null;
135
+ return [truncatedKey, truncatedValue];
136
+ });
137
+ // Pinpoint only accepts 40 attributes
138
+ if (checkedEntries.length > 40) {
139
+ logger_1.logger.error(`Amplify only allows 40 attributes per event, truncating to 40 attributes`, {
140
+ attributes: checkedEntries,
141
+ });
142
+ checkedEntries.length = 40;
143
+ }
144
+ return Object.fromEntries(checkedEntries);
145
+ }
146
+ exports.asAttributeMap = asAttributeMap;
147
+ /**
148
+ * Pinpoint expects `endpoint.attributes` and `endpoint.userAttributes` to have
149
+ * values which are string arrays. This function takes in an object and ensures
150
+ * all of its values are of type `string[]` to appease Pinpoint.
151
+ */
152
+ function buildAttributeMap(values, parentKey = undefined, groupValues = true) {
153
+ const valuesWithStringArrays = {};
154
+ Object.entries(values).forEach(([key, value]) => {
155
+ const combinedKey = parentKey ? [parentKey, key].join('.') : key;
156
+ if (!value) {
157
+ valuesWithStringArrays[combinedKey] = null;
158
+ }
159
+ else if (groupValues && Array.isArray(value)) {
160
+ valuesWithStringArrays[combinedKey] = value.map((element) => typeof element === 'string' ? element : JSON.stringify(element));
161
+ }
162
+ else if (typeof value === 'object') {
163
+ const flattenedAttribute = buildAttributeMap(value, combinedKey, groupValues);
164
+ Object.assign(valuesWithStringArrays, flattenedAttribute);
165
+ }
166
+ else {
167
+ const stringValue = typeof value === 'string' ? value : JSON.stringify(value);
168
+ valuesWithStringArrays[combinedKey] = groupValues ? [stringValue] : stringValue;
169
+ }
170
+ });
171
+ return valuesWithStringArrays;
172
+ }
173
+ exports.buildAttributeMap = buildAttributeMap;
174
+ function installPinpointProxy(proxyUrl) {
175
+ // No public API for overriding where the Pinpoint client sends events to... 🤮
176
+ // In theory you can pass in an `endpoint` to the Pinpoint client's constructor like any other AWS
177
+ // client, but Amplify's analytics doesn't expose anything we can use to get an endpoint threaded
178
+ // down to the Pinpoint client's constructor.
179
+ //
180
+ // The Pinpoint client _also_ isn't available synchronously because it is instantiated when events
181
+ // get sent out, and then reconfigured whenever the API credentials change. We need to hook `_initClients`
182
+ // to ensure that the Pinpoint client being used is always patched with our custom endpoint.
183
+ const provider = Analytics_1.Analytics.getPluggable('AWSPinpoint');
184
+ if (!provider || typeof provider._initClients !== 'function') {
185
+ logger_1.logger.error('Installation of the Pinpoint proxy failed. This likely means the internals of the @aws-amplify/analytics package have changed.');
186
+ return;
187
+ }
188
+ const originalInitClients = provider._initClients;
189
+ const requestMiddleware = (next) => async (args) => {
190
+ const pinpointClient = provider.pinpointClient;
191
+ if (pinpointClient && proxyUrl.pathname !== '/' && protocol_http_1.HttpRequest.isInstance(args.request)) {
192
+ // Add proxyUrl.pathname to final request url if it was provided
193
+ const shouldStripSlash = proxyUrl.pathname.endsWith('/');
194
+ args.request.path = `${proxyUrl.pathname}${args.request.path.slice(shouldStripSlash ? 1 : 0)}`;
195
+ // Wrap request body so the proxy has signing info
196
+ if (typeof args.request.body === 'string') {
197
+ const credentials = await pinpointClient.config.credentials();
198
+ args.request.body = JSON.stringify({
199
+ credentials,
200
+ data: JSON.parse(args.request.body),
201
+ });
202
+ }
203
+ }
204
+ return next(args);
205
+ };
206
+ provider._initClients = async (credentials) => {
207
+ const result = await originalInitClients.call(provider, credentials);
208
+ const pinpointClient = provider.pinpointClient;
209
+ if (pinpointClient) {
210
+ pinpointClient.config.endpoint = () => Promise.resolve({
211
+ hostname: proxyUrl.hostname,
212
+ // Passing proxyUrl.pathname here doesn't work; it gets overridden
213
+ path: '/',
214
+ port: undefined,
215
+ protocol: proxyUrl.protocol,
216
+ });
217
+ pinpointClient.middlewareStack.remove(requestMiddleware);
218
+ pinpointClient.middlewareStack.add(requestMiddleware, { step: 'finalizeRequest' });
219
+ }
220
+ return result;
221
+ };
222
+ }
223
223
  //# sourceMappingURL=amplifyReporter.js.map