@aws-amplify/analytics 7.0.1-console-preview.8d88eef.0 → 7.0.1-console-preview.b278dcb.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 (95) hide show
  1. package/lib/errors/validation.d.ts +2 -0
  2. package/lib/errors/validation.js +8 -0
  3. package/lib/index.d.ts +1 -1
  4. package/lib/index.js +2 -1
  5. package/lib/providers/pinpoint/apis/configureAutoTrack.d.ts +15 -0
  6. package/lib/providers/pinpoint/apis/configureAutoTrack.js +35 -0
  7. package/lib/providers/pinpoint/apis/index.d.ts +1 -0
  8. package/lib/providers/pinpoint/apis/index.js +3 -1
  9. package/lib/providers/pinpoint/index.d.ts +2 -2
  10. package/lib/providers/pinpoint/index.js +2 -1
  11. package/lib/providers/pinpoint/types/index.d.ts +1 -1
  12. package/lib/providers/pinpoint/types/inputs.d.ts +5 -1
  13. package/lib/trackers/EventTracker.d.ts +10 -0
  14. package/lib/trackers/EventTracker.js +104 -0
  15. package/lib/trackers/PageViewTracker.d.ts +18 -0
  16. package/lib/trackers/PageViewTracker.js +116 -0
  17. package/lib/trackers/SessionTracker.d.ts +13 -0
  18. package/lib/trackers/SessionTracker.js +73 -0
  19. package/lib/trackers/SessionTracker.native.d.ts +13 -0
  20. package/lib/trackers/SessionTracker.native.js +73 -0
  21. package/lib/trackers/index.d.ts +3 -0
  22. package/lib/trackers/index.js +11 -0
  23. package/lib/tsconfig.tsbuildinfo +1 -1
  24. package/lib/types/index.d.ts +1 -2
  25. package/lib/types/inputs.d.ts +16 -0
  26. package/lib/types/trackers.d.ts +22 -0
  27. package/lib/utils/index.d.ts +2 -0
  28. package/lib/utils/index.js +5 -1
  29. package/lib/utils/trackerConfigHelpers.d.ts +5 -0
  30. package/lib/utils/trackerConfigHelpers.js +15 -0
  31. package/lib/utils/trackerConfigHelpers.native.d.ts +5 -0
  32. package/lib/utils/trackerConfigHelpers.native.js +14 -0
  33. package/lib/utils/trackerHelpers.d.ts +9 -0
  34. package/lib/utils/trackerHelpers.js +44 -0
  35. package/lib-esm/errors/validation.d.ts +2 -0
  36. package/lib-esm/errors/validation.js +8 -0
  37. package/lib-esm/index.d.ts +1 -1
  38. package/lib-esm/index.js +1 -1
  39. package/lib-esm/providers/pinpoint/apis/configureAutoTrack.d.ts +15 -0
  40. package/lib-esm/providers/pinpoint/apis/configureAutoTrack.js +31 -0
  41. package/lib-esm/providers/pinpoint/apis/index.d.ts +1 -0
  42. package/lib-esm/providers/pinpoint/apis/index.js +1 -0
  43. package/lib-esm/providers/pinpoint/apis/record.js +1 -1
  44. package/lib-esm/providers/pinpoint/index.d.ts +2 -2
  45. package/lib-esm/providers/pinpoint/index.js +1 -1
  46. package/lib-esm/providers/pinpoint/types/index.d.ts +1 -1
  47. package/lib-esm/providers/pinpoint/types/inputs.d.ts +5 -1
  48. package/lib-esm/trackers/EventTracker.d.ts +10 -0
  49. package/lib-esm/trackers/EventTracker.js +101 -0
  50. package/lib-esm/trackers/PageViewTracker.d.ts +18 -0
  51. package/lib-esm/trackers/PageViewTracker.js +113 -0
  52. package/lib-esm/trackers/SessionTracker.d.ts +13 -0
  53. package/lib-esm/trackers/SessionTracker.js +70 -0
  54. package/lib-esm/trackers/SessionTracker.native.d.ts +13 -0
  55. package/lib-esm/trackers/SessionTracker.native.js +70 -0
  56. package/lib-esm/trackers/index.d.ts +3 -0
  57. package/lib-esm/trackers/index.js +5 -0
  58. package/lib-esm/tsconfig.tsbuildinfo +1 -1
  59. package/lib-esm/types/index.d.ts +1 -2
  60. package/lib-esm/types/inputs.d.ts +16 -0
  61. package/lib-esm/types/trackers.d.ts +22 -0
  62. package/lib-esm/utils/index.d.ts +2 -0
  63. package/lib-esm/utils/index.js +2 -0
  64. package/lib-esm/utils/trackerConfigHelpers.d.ts +5 -0
  65. package/lib-esm/utils/trackerConfigHelpers.js +11 -0
  66. package/lib-esm/utils/trackerConfigHelpers.native.d.ts +5 -0
  67. package/lib-esm/utils/trackerConfigHelpers.native.js +10 -0
  68. package/lib-esm/utils/trackerHelpers.d.ts +9 -0
  69. package/lib-esm/utils/trackerHelpers.js +40 -0
  70. package/package.json +5 -4
  71. package/src/errors/validation.ts +8 -0
  72. package/src/index.ts +3 -1
  73. package/src/providers/pinpoint/apis/configureAutoTrack.ts +49 -0
  74. package/src/providers/pinpoint/apis/index.ts +1 -0
  75. package/src/providers/pinpoint/apis/record.ts +1 -1
  76. package/src/providers/pinpoint/index.ts +6 -2
  77. package/src/providers/pinpoint/types/index.ts +5 -1
  78. package/src/providers/pinpoint/types/inputs.ts +9 -1
  79. package/src/trackers/EventTracker.ts +135 -0
  80. package/src/trackers/PageViewTracker.ts +160 -0
  81. package/src/trackers/SessionTracker.native.ts +106 -0
  82. package/src/trackers/SessionTracker.ts +106 -0
  83. package/src/trackers/index.ts +6 -0
  84. package/src/types/index.ts +4 -13
  85. package/src/types/inputs.ts +25 -0
  86. package/src/types/trackers.ts +35 -0
  87. package/src/utils/index.ts +2 -0
  88. package/src/utils/trackerConfigHelpers.native.ts +18 -0
  89. package/src/utils/trackerConfigHelpers.ts +19 -0
  90. package/src/utils/trackerHelpers.ts +57 -0
  91. package/lib/types/analytics.d.ts +0 -50
  92. package/lib-esm/types/analytics.d.ts +0 -50
  93. package/src/types/analytics.ts +0 -70
  94. /package/lib/types/{analytics.js → trackers.js} +0 -0
  95. /package/lib-esm/types/{analytics.js → trackers.js} +0 -0
@@ -1,4 +1,3 @@
1
- export { AutoTrackAttributes, AutoTrackEventOpts, AutoTrackPageViewOpts, AutoTrackSessionOpts, EventAttributes, EventMetrics, EventTrackOpts, PageViewTrackOpts, SessionTrackOpts, } from './analytics';
2
1
  export { AnalyticsServiceOptions } from './options';
3
- export { AnalyticsIdentifyUserInput } from './inputs';
2
+ export { AnalyticsConfigureAutoTrackInput, AnalyticsIdentifyUserInput, } from './inputs';
4
3
  export { KinesisStream, KinesisShard, KinesisEventData } from './kinesis';
@@ -1,5 +1,6 @@
1
1
  import { UserProfile } from '@aws-amplify/core';
2
2
  import { AnalyticsServiceOptions } from '.';
3
+ import { SessionTrackingOptions, PageViewTrackingOptions, EventTrackingOptions } from './trackers';
3
4
  /**
4
5
  * Input type for `identifyUser`.
5
6
  */
@@ -17,3 +18,18 @@ export type AnalyticsIdentifyUserInput<ServiceOptions extends AnalyticsServiceOp
17
18
  */
18
19
  options?: ServiceOptions;
19
20
  };
21
+ /**
22
+ * Input type for `configureAutoTrack`.
23
+ */
24
+ export type AnalyticsConfigureAutoTrackInput = {
25
+ enable: boolean;
26
+ } & ({
27
+ type: 'session';
28
+ options?: SessionTrackingOptions;
29
+ } | {
30
+ type: 'pageView';
31
+ options?: PageViewTrackingOptions;
32
+ } | {
33
+ type: 'event';
34
+ options?: EventTrackingOptions;
35
+ });
@@ -0,0 +1,22 @@
1
+ export type SessionTrackingOptions = {
2
+ attributes?: TrackerAttributes;
3
+ };
4
+ export type PageViewTrackingOptions = {
5
+ attributes?: TrackerAttributes;
6
+ eventName?: string;
7
+ urlProvider?: () => string;
8
+ appType?: 'multiPage' | 'singlePage';
9
+ };
10
+ export type EventTrackingOptions = {
11
+ attributes?: TrackerAttributes;
12
+ events?: DOMEvent[];
13
+ selectorPrefix?: string;
14
+ };
15
+ export type TrackerType = 'event' | 'pageView' | 'session';
16
+ export type TrackerAttributes = Record<string, string>;
17
+ export type TrackerEventRecorder = (eventName: string, attributes: TrackerAttributes) => void;
18
+ export type DOMEvent = keyof GlobalEventHandlersEventMap;
19
+ export interface TrackerInterface {
20
+ configure(eventRecorder: TrackerEventRecorder, options?: object): void;
21
+ cleanup(): void;
22
+ }
@@ -3,3 +3,5 @@ export { groupBy } from './groupBy';
3
3
  export { EventBuffer, IAnalyticsClient, EventBufferConfig, } from './eventBuffer';
4
4
  export { enableAnalytics, disableAnalytics, isAnalyticsEnabled, } from './statusHelpers';
5
5
  export { getAnalyticsUserAgent, getAnalyticsUserAgentString, } from './userAgent';
6
+ export { updateProviderTrackers } from './trackerHelpers';
7
+ export { validateTrackerConfiguration } from './trackerConfigHelpers';
@@ -5,3 +5,5 @@ export { groupBy } from './groupBy';
5
5
  export { EventBuffer, } from './eventBuffer';
6
6
  export { enableAnalytics, disableAnalytics, isAnalyticsEnabled, } from './statusHelpers';
7
7
  export { getAnalyticsUserAgent, getAnalyticsUserAgentString, } from './userAgent';
8
+ export { updateProviderTrackers } from './trackerHelpers';
9
+ export { validateTrackerConfiguration } from './trackerConfigHelpers';
@@ -0,0 +1,5 @@
1
+ import { AnalyticsConfigureAutoTrackInput } from '../types';
2
+ /**
3
+ * Validates tracker configuration.
4
+ */
5
+ export declare const validateTrackerConfiguration: (input: AnalyticsConfigureAutoTrackInput) => void;
@@ -0,0 +1,11 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { AnalyticsValidationErrorCode, assertValidationError } from '../errors';
4
+ /**
5
+ * Validates tracker configuration.
6
+ */
7
+ export var validateTrackerConfiguration = function (input) {
8
+ assertValidationError(input.type === 'event' ||
9
+ input.type === 'pageView' ||
10
+ input.type === 'session', AnalyticsValidationErrorCode.InvalidTracker);
11
+ };
@@ -0,0 +1,5 @@
1
+ import { AnalyticsConfigureAutoTrackInput } from '../types';
2
+ /**
3
+ * Validates tracker configuration.
4
+ */
5
+ export declare const validateTrackerConfiguration: (input: AnalyticsConfigureAutoTrackInput) => void;
@@ -0,0 +1,10 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { AnalyticsValidationErrorCode, assertValidationError } from '../errors';
4
+ /**
5
+ * Validates tracker configuration.
6
+ */
7
+ export var validateTrackerConfiguration = function (input) {
8
+ // React Native only supports session tracking
9
+ assertValidationError(input.type === 'session', AnalyticsValidationErrorCode.UnsupportedPlatform);
10
+ };
@@ -0,0 +1,9 @@
1
+ import { TrackerEventRecorder, TrackerInterface, TrackerType } from '../types/trackers';
2
+ import { ConfigureAutoTrackInput } from '../providers/pinpoint';
3
+ /**
4
+ * Updates a provider's trackers as appropriate for the provided auto-track configuration.
5
+ *
6
+ * @remark
7
+ * This utility will mutate the provider's configured trackers via `providerTrackers`.
8
+ */
9
+ export declare const updateProviderTrackers: (input: ConfigureAutoTrackInput, providerEventRecorder: TrackerEventRecorder, providerTrackers: Partial<Record<TrackerType, TrackerInterface>>) => void;
@@ -0,0 +1,40 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { EventTracker, PageViewTracker, SessionTracker } from '../trackers';
4
+ /**
5
+ * Updates a provider's trackers as appropriate for the provided auto-track configuration.
6
+ *
7
+ * @remark
8
+ * This utility will mutate the provider's configured trackers via `providerTrackers`.
9
+ */
10
+ export var updateProviderTrackers = function (input, providerEventRecorder, providerTrackers) {
11
+ var trackerInstance;
12
+ var trackerType = input.type;
13
+ var currentTracker = providerTrackers[trackerType];
14
+ // Check if the tracker was disabled & should be cleaned up
15
+ if (!input.enable) {
16
+ if (currentTracker) {
17
+ currentTracker.cleanup();
18
+ delete providerTrackers[trackerType];
19
+ }
20
+ return;
21
+ }
22
+ // Re-configure the existing tracker, or create & configure an instance if it doesn't exist yet
23
+ if (currentTracker) {
24
+ currentTracker.configure(providerEventRecorder, input.options);
25
+ return;
26
+ }
27
+ // Create a new tracker instance for the type
28
+ if (trackerType === 'event') {
29
+ trackerInstance = new EventTracker(providerEventRecorder, input.options);
30
+ }
31
+ else if (trackerType === 'pageView') {
32
+ trackerInstance = new PageViewTracker(providerEventRecorder, input.options);
33
+ }
34
+ else if (trackerType === 'session') {
35
+ trackerInstance = new SessionTracker(providerEventRecorder, input.options);
36
+ }
37
+ if (trackerInstance) {
38
+ providerTrackers[trackerType] = trackerInstance;
39
+ }
40
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aws-amplify/analytics",
3
- "version": "7.0.1-console-preview.8d88eef.0+8d88eef",
3
+ "version": "7.0.1-console-preview.b278dcb.0+b278dcb",
4
4
  "description": "Analytics category of aws-amplify",
5
5
  "main": "./lib/index.js",
6
6
  "module": "./lib-esm/index.js",
@@ -99,10 +99,11 @@
99
99
  "tslib": "^2.5.0"
100
100
  },
101
101
  "peerDependencies": {
102
- "@aws-amplify/core": "6.0.1-console-preview.8d88eef.0+8d88eef"
102
+ "@aws-amplify/core": "6.0.1-console-preview.b278dcb.0+b278dcb"
103
103
  },
104
104
  "devDependencies": {
105
- "@aws-amplify/core": "6.0.1-console-preview.8d88eef.0+8d88eef",
105
+ "@aws-amplify/core": "6.0.1-console-preview.b278dcb.0+b278dcb",
106
+ "@aws-amplify/react-native": "1.0.1-console-preview.b278dcb.0+b278dcb",
106
107
  "@aws-sdk/types": "3.398.0",
107
108
  "typescript": "5.0.2"
108
109
  },
@@ -150,5 +151,5 @@
150
151
  "<rootDir>/src/setupTests.ts"
151
152
  ]
152
153
  },
153
- "gitHead": "8d88eef4137cef4fbe03d7d3683b5bec59feb7b8"
154
+ "gitHead": "b278dcb6dd7334e53d92d22386a22fba3c4a6089"
154
155
  }
@@ -8,6 +8,8 @@ export enum AnalyticsValidationErrorCode {
8
8
  NoCredentials = 'NoCredentials',
9
9
  NoEventName = 'NoEventName',
10
10
  NoRegion = 'NoRegion',
11
+ InvalidTracker = 'InvalidTracker',
12
+ UnsupportedPlatform = 'UnsupportedPlatform',
11
13
  NoTrackingId = 'NoTrackingId',
12
14
  InvalidFlushSize = 'InvalidFlushSize',
13
15
  }
@@ -26,6 +28,12 @@ export const validationErrorMap: AmplifyErrorMap<AnalyticsValidationErrorCode> =
26
28
  [AnalyticsValidationErrorCode.NoRegion]: {
27
29
  message: 'Missing region.',
28
30
  },
31
+ [AnalyticsValidationErrorCode.InvalidTracker]: {
32
+ message: 'Invalid tracker type specified.',
33
+ },
34
+ [AnalyticsValidationErrorCode.UnsupportedPlatform]: {
35
+ message: 'Only session tracking is supported on React Native.',
36
+ },
29
37
  [AnalyticsValidationErrorCode.InvalidFlushSize]: {
30
38
  message: 'Invalid FlushSize, it should be smaller than BufferSize',
31
39
  },
package/src/index.ts CHANGED
@@ -4,9 +4,11 @@
4
4
  export {
5
5
  record,
6
6
  identifyUser,
7
+ configureAutoTrack,
8
+ flushEvents,
7
9
  RecordInput,
8
10
  IdentifyUserInput,
9
- flushEvents,
11
+ ConfigureAutoTrackInput,
10
12
  } from './providers/pinpoint';
11
13
  export { enable, disable } from './apis';
12
14
  export { AnalyticsError } from './errors';
@@ -0,0 +1,49 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { AnalyticsValidationErrorCode } from '../../../errors';
5
+ import {
6
+ TrackerType,
7
+ TrackerAttributes,
8
+ TrackerInterface,
9
+ } from '../../../types/trackers';
10
+ import {
11
+ updateProviderTrackers,
12
+ validateTrackerConfiguration,
13
+ } from '../../../utils';
14
+ import { ConfigureAutoTrackInput } from '../types';
15
+ import { record } from './record';
16
+
17
+ // Configured Tracker instances for Pinpoint
18
+ const configuredTrackers: Partial<Record<TrackerType, TrackerInterface>> = {};
19
+
20
+ // Callback that will emit an appropriate event to Pinpoint when required by the Tracker
21
+ const emitTrackingEvent = (
22
+ eventName: string,
23
+ attributes: TrackerAttributes
24
+ ) => {
25
+ record({
26
+ name: eventName,
27
+ attributes,
28
+ });
29
+ };
30
+
31
+ /**
32
+ * Configures automatic event tracking for Pinpoint. This API will automatically transmit an analytic event when
33
+ * configured events are detected within your application. This can include: DOM element events (via the `event`
34
+ * tracker), session events (via the `session` tracker), and page view events (via the `pageView` tracker).
35
+ *
36
+ * @remark Only session tracking is currently supported on React Native.
37
+ *
38
+ * @param {ConfigureAutoTrackInput} params The input object to configure auto track behavior.
39
+ *
40
+ * @throws service: {@link UpdateEndpointException} - Thrown when the underlying Pinpoint service returns an error.
41
+ * @throws validation: {@link AnalyticsValidationErrorCode} - Thrown when the provided parameters or library
42
+ * configuration is incorrect.
43
+ */
44
+ export const configureAutoTrack = (input: ConfigureAutoTrackInput): void => {
45
+ validateTrackerConfiguration(input);
46
+
47
+ // Initialize or update this provider's trackers
48
+ updateProviderTrackers(input, emitTrackingEvent, configuredTrackers);
49
+ };
@@ -3,4 +3,5 @@
3
3
 
4
4
  export { record } from './record';
5
5
  export { identifyUser } from './identifyUser';
6
+ export { configureAutoTrack } from './configureAutoTrack';
6
7
  export { flushEvents } from './flushEvents';
@@ -4,7 +4,7 @@
4
4
  import { Hub, ConsoleLogger } from '@aws-amplify/core';
5
5
  import {
6
6
  AMPLIFY_SYMBOL,
7
- AnalyticsAction
7
+ AnalyticsAction,
8
8
  } from '@aws-amplify/core/internals/utils';
9
9
  import { record as recordCore } from '@aws-amplify/core/internals/providers/pinpoint';
10
10
  import {
@@ -1,5 +1,9 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- export { record, identifyUser, flushEvents } from './apis';
5
- export { RecordInput, IdentifyUserInput } from './types/inputs';
4
+ export { record, identifyUser, flushEvents, configureAutoTrack } from './apis';
5
+ export {
6
+ RecordInput,
7
+ IdentifyUserInput,
8
+ ConfigureAutoTrackInput,
9
+ } from './types/inputs';
@@ -1,5 +1,9 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- export { RecordInput, IdentifyUserInput } from './inputs';
4
+ export {
5
+ RecordInput,
6
+ IdentifyUserInput,
7
+ ConfigureAutoTrackInput,
8
+ } from './inputs';
5
9
  export { IdentifyUserOptions } from './options';
@@ -3,7 +3,10 @@
3
3
 
4
4
  import { PinpointAnalyticsEvent } from '@aws-amplify/core/internals/providers/pinpoint';
5
5
  import { IdentifyUserOptions } from '.';
6
- import { AnalyticsIdentifyUserInput } from '../../../types';
6
+ import {
7
+ AnalyticsConfigureAutoTrackInput,
8
+ AnalyticsIdentifyUserInput,
9
+ } from '../../../types';
7
10
 
8
11
  /**
9
12
  * Input type for Pinpoint record API.
@@ -14,3 +17,8 @@ export type RecordInput = PinpointAnalyticsEvent;
14
17
  * Input type for Pinpoint identifyUser API.
15
18
  */
16
19
  export type IdentifyUserInput = AnalyticsIdentifyUserInput<IdentifyUserOptions>;
20
+
21
+ /**
22
+ * Input type for Pinpoint configureAutoTrack API.
23
+ */
24
+ export type ConfigureAutoTrackInput = AnalyticsConfigureAutoTrackInput;
@@ -0,0 +1,135 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import {
5
+ EventTrackingOptions,
6
+ DOMEvent,
7
+ TrackerEventRecorder,
8
+ TrackerInterface,
9
+ } from '../types/trackers';
10
+ import { ConsoleLogger } from '@aws-amplify/core';
11
+ import { isBrowser } from '@aws-amplify/core/internals/utils';
12
+
13
+ const DEFAULT_EVENTS = ['click'] as DOMEvent[];
14
+ const DEFAULT_SELECTOR_PREFIX = 'data-amplify-analytics-';
15
+ const DEFAULT_EVENT_NAME = 'event'; // Default event name as sent to the analytics provider
16
+
17
+ const logger = new ConsoleLogger('EventTracker');
18
+
19
+ export class EventTracker implements TrackerInterface {
20
+ private trackerActive: boolean;
21
+ private options: EventTrackingOptions;
22
+ private eventRecorder: TrackerEventRecorder;
23
+
24
+ constructor(
25
+ eventRecorder: TrackerEventRecorder,
26
+ options?: EventTrackingOptions
27
+ ) {
28
+ this.options = {};
29
+ this.trackerActive = false;
30
+ this.eventRecorder = eventRecorder;
31
+ this.handleDocEvent = this.handleDocEvent.bind(this);
32
+
33
+ this.configure(eventRecorder, options);
34
+ }
35
+
36
+ public configure(
37
+ eventRecorder: TrackerEventRecorder,
38
+ options?: EventTrackingOptions
39
+ ) {
40
+ this.eventRecorder = eventRecorder;
41
+
42
+ // Clean up any existing listeners
43
+ this.cleanup();
44
+
45
+ // Apply defaults
46
+ this.options = {
47
+ attributes: options?.attributes ?? undefined,
48
+ events: options?.events ?? DEFAULT_EVENTS,
49
+ selectorPrefix: options?.selectorPrefix ?? DEFAULT_SELECTOR_PREFIX,
50
+ };
51
+
52
+ // Register event listeners
53
+ if (isBrowser()) {
54
+ this.options.events?.forEach(targetEvent => {
55
+ document.addEventListener(targetEvent, this.handleDocEvent, {
56
+ capture: true,
57
+ });
58
+ });
59
+
60
+ this.trackerActive = true;
61
+ }
62
+ }
63
+
64
+ public cleanup() {
65
+ // No-op if document listener is not active
66
+ if (!this.trackerActive) {
67
+ return;
68
+ }
69
+
70
+ // Clean up event listeners
71
+ this.options.events?.forEach(targetEvent => {
72
+ document.removeEventListener(targetEvent, this.handleDocEvent, {
73
+ capture: true,
74
+ });
75
+ });
76
+ }
77
+
78
+ private handleDocEvent(event: Event) {
79
+ /**
80
+ * Example DOM element:
81
+ *
82
+ * ```
83
+ * <button
84
+ * data-amplify-analytics-on="click"
85
+ * data-amplify-analytics-name="click"
86
+ * data-amplify-analytics-attrs="attr1:attr1_value,attr2:attr2_value"
87
+ * />
88
+ * ```
89
+ */
90
+ const triggerSelector = `[${this.options.selectorPrefix}on]`;
91
+ const attrSelector = `${this.options.selectorPrefix}attrs`;
92
+ const eventNameSelector = `${this.options.selectorPrefix}name`;
93
+ const eventSource = event.target;
94
+
95
+ // Validate that the triggering event type is being tracked
96
+ if (!this.options.events?.includes(event.type as DOMEvent)) {
97
+ return;
98
+ }
99
+
100
+ if (eventSource instanceof HTMLElement) {
101
+ const target = eventSource.closest(triggerSelector);
102
+
103
+ if (target) {
104
+ // Parse event name from the element
105
+ const eventName =
106
+ target.getAttribute(eventNameSelector) || DEFAULT_EVENT_NAME;
107
+
108
+ // Parse attributes from the element
109
+ const elementAttributes: Record<string, string> = {};
110
+ const rawElementAttributes = target.getAttribute(attrSelector);
111
+ rawElementAttributes?.split(/\s*,\s*/).forEach(attr => {
112
+ const tmp = attr.trim().split(/\s*:\s*/);
113
+ elementAttributes[tmp[0]] = tmp[1];
114
+ });
115
+
116
+ // Assemble final list of attributes
117
+ const attributes = Object.assign(
118
+ {
119
+ type: event.type,
120
+ target: `${target.localName} with id ${target.id}`,
121
+ },
122
+ this.options.attributes,
123
+ elementAttributes
124
+ );
125
+
126
+ logger.debug('Recording automatically tracked DOM event', {
127
+ eventName,
128
+ attributes,
129
+ });
130
+
131
+ this.eventRecorder(eventName, attributes);
132
+ }
133
+ }
134
+ }
135
+ }
@@ -0,0 +1,160 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import {
5
+ PageViewTrackingOptions,
6
+ TrackerEventRecorder,
7
+ TrackerInterface,
8
+ } from '../types/trackers';
9
+ import { ConsoleLogger } from '@aws-amplify/core';
10
+ import { isBrowser } from '@aws-amplify/core/internals/utils';
11
+
12
+ const logger = new ConsoleLogger('PageViewTracker');
13
+
14
+ const DEFAULT_EVENT_NAME = 'pageView';
15
+ const DEFAULT_APP_TYPE = 'singlePage';
16
+ const DEFAULT_URL_PROVIDER = () => {
17
+ return window.location.origin + window.location.pathname;
18
+ };
19
+ const PREV_URL_STORAGE_KEY = 'aws-amplify-analytics-prevUrl';
20
+
21
+ export class PageViewTracker implements TrackerInterface {
22
+ private trackerActive: boolean;
23
+ private options: PageViewTrackingOptions;
24
+ private eventRecorder: TrackerEventRecorder;
25
+
26
+ // SPA tracking helpers
27
+ private spaTrackingActive: boolean;
28
+ private pushStateProxy?: any;
29
+ private replaceStateProxy?: any;
30
+ private originalPushState: any;
31
+ private originalReplaceState: any;
32
+
33
+ constructor(
34
+ eventRecorder: TrackerEventRecorder,
35
+ options?: PageViewTrackingOptions
36
+ ) {
37
+ this.options = {};
38
+ this.trackerActive = true;
39
+ this.eventRecorder = eventRecorder;
40
+ this.spaTrackingActive = false;
41
+ this.handleLocationChange = this.handleLocationChange.bind(this);
42
+
43
+ this.configure(eventRecorder, options);
44
+ }
45
+
46
+ public configure(
47
+ eventRecorder: TrackerEventRecorder,
48
+ options?: PageViewTrackingOptions
49
+ ) {
50
+ this.eventRecorder = eventRecorder;
51
+
52
+ // Clean up any existing listeners
53
+ this.cleanup();
54
+
55
+ // Apply defaults
56
+ this.options = {
57
+ appType: options?.appType ?? DEFAULT_APP_TYPE,
58
+ attributes: options?.attributes ?? undefined,
59
+ eventName: this.options?.eventName ?? DEFAULT_EVENT_NAME,
60
+ urlProvider: this.options?.urlProvider ?? DEFAULT_URL_PROVIDER,
61
+ };
62
+
63
+ // Configure SPA or MPA page view tracking
64
+ if (isBrowser()) {
65
+ if (this.options.appType === 'singlePage') {
66
+ this.setupSPATracking();
67
+ } else {
68
+ this.setupMPATracking();
69
+ }
70
+
71
+ this.trackerActive = true;
72
+ }
73
+ }
74
+
75
+ public cleanup() {
76
+ // No-op if document listener is not active
77
+ if (!this.trackerActive) {
78
+ return;
79
+ }
80
+
81
+ // Clean up SPA page view listeners
82
+ if (this.spaTrackingActive) {
83
+ window.history.pushState = this.originalPushState;
84
+ window.history.replaceState = this.originalReplaceState;
85
+ this.pushStateProxy?.revoke();
86
+ this.replaceStateProxy?.revoke();
87
+ window.removeEventListener('popstate', this.handleLocationChange);
88
+
89
+ this.spaTrackingActive = false;
90
+ }
91
+ }
92
+
93
+ private setupSPATracking() {
94
+ if (!this.spaTrackingActive) {
95
+ // Configure proxies on History APIs
96
+ this.pushStateProxy = Proxy.revocable(window.history.pushState, {
97
+ apply: (target, thisArg, args) => {
98
+ const proxiedResult = target.apply(thisArg, args as any);
99
+
100
+ this.handleLocationChange();
101
+
102
+ return proxiedResult;
103
+ },
104
+ });
105
+ this.replaceStateProxy = Proxy.revocable(window.history.replaceState, {
106
+ apply: (target, thisArg, args) => {
107
+ const proxiedResult = target.apply(thisArg, args as any);
108
+
109
+ this.handleLocationChange();
110
+
111
+ return proxiedResult;
112
+ },
113
+ });
114
+
115
+ this.originalPushState = window.history.pushState;
116
+ this.originalReplaceState = window.history.replaceState;
117
+ window.history.pushState = this.pushStateProxy.proxy;
118
+ window.history.replaceState = this.replaceStateProxy.proxy;
119
+ window.addEventListener('popstate', this.handleLocationChange);
120
+ sessionStorage.removeItem(PREV_URL_STORAGE_KEY);
121
+
122
+ this.spaTrackingActive = true;
123
+ }
124
+ }
125
+
126
+ private setupMPATracking() {
127
+ this.handleLocationChange();
128
+ }
129
+
130
+ private handleLocationChange() {
131
+ const currentUrl = this.options.urlProvider!();
132
+ const eventName = this.options.eventName || DEFAULT_EVENT_NAME;
133
+
134
+ if (this.urlHasChanged()) {
135
+ sessionStorage.setItem(PREV_URL_STORAGE_KEY, currentUrl);
136
+
137
+ // Assemble attribute list
138
+ const attributes = Object.assign(
139
+ {
140
+ url: currentUrl,
141
+ },
142
+ this.options.attributes
143
+ );
144
+
145
+ logger.debug('Recording automatically tracked page view event', {
146
+ eventName,
147
+ attributes,
148
+ });
149
+
150
+ this.eventRecorder(eventName, attributes);
151
+ }
152
+ }
153
+
154
+ private urlHasChanged() {
155
+ const prevUrl = sessionStorage.getItem(PREV_URL_STORAGE_KEY);
156
+ const currUrl = this.options.urlProvider!();
157
+
158
+ return currUrl !== prevUrl;
159
+ }
160
+ }