@aws-amplify/analytics 7.0.1-api-v6-models.9351bcf.0 → 7.0.1-api-v6-models.891fe0d.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 (87) hide show
  1. package/lib/apis/disable.js +1 -1
  2. package/lib/apis/enable.js +1 -1
  3. package/lib/errors/AnalyticsError.js +7 -11
  4. package/lib/errors/assertValidationError.js +6 -6
  5. package/lib/errors/validation.js +10 -11
  6. package/lib/providers/kinesis/apis/flushEvents.js +20 -23
  7. package/lib/providers/kinesis/apis/record.js +24 -26
  8. package/lib/providers/kinesis/utils/getEventBuffer.js +39 -70
  9. package/lib/providers/kinesis/utils/resolveConfig.js +14 -13
  10. package/lib/providers/kinesis-firehose/apis/flushEvents.js +19 -22
  11. package/lib/providers/kinesis-firehose/apis/record.js +22 -24
  12. package/lib/providers/kinesis-firehose/utils/getEventBuffer.js +39 -68
  13. package/lib/providers/kinesis-firehose/utils/resolveConfig.js +14 -13
  14. package/lib/providers/personalize/apis/flushEvents.js +18 -21
  15. package/lib/providers/personalize/apis/record.js +55 -71
  16. package/lib/providers/personalize/utils/autoTrackMedia.js +96 -98
  17. package/lib/providers/personalize/utils/cachedSession.js +30 -42
  18. package/lib/providers/personalize/utils/getEventBuffer.js +35 -62
  19. package/lib/providers/personalize/utils/resolveConfig.js +14 -13
  20. package/lib/providers/pinpoint/apis/configureAutoTrack.js +6 -6
  21. package/lib/providers/pinpoint/apis/flushEvents.js +10 -13
  22. package/lib/providers/pinpoint/apis/identifyUser.js +18 -30
  23. package/lib/providers/pinpoint/apis/record.js +15 -16
  24. package/lib/providers/pinpoint/utils/resolveConfig.js +5 -6
  25. package/lib/providers/pinpoint/utils/resolveCredentials.js +7 -15
  26. package/lib/setupTests.js +1 -1
  27. package/lib/trackers/EventTracker.js +39 -45
  28. package/lib/trackers/PageViewTracker.js +41 -45
  29. package/lib/trackers/SessionTracker.js +25 -31
  30. package/lib/trackers/SessionTracker.native.js +25 -31
  31. package/lib/tsconfig.tsbuildinfo +1 -1
  32. package/lib/utils/eventBuffer/EventBuffer.js +34 -62
  33. package/lib/utils/groupBy.js +4 -7
  34. package/lib/utils/resolveCredentials.js +7 -15
  35. package/lib/utils/statusHelpers.js +4 -4
  36. package/lib/utils/trackerConfigHelpers.js +2 -2
  37. package/lib/utils/trackerConfigHelpers.native.js +2 -2
  38. package/lib/utils/trackerHelpers.js +5 -5
  39. package/lib/utils/userAgent.js +3 -3
  40. package/lib-esm/apis/disable.js +1 -1
  41. package/lib-esm/apis/enable.js +1 -1
  42. package/lib-esm/errors/AnalyticsError.js +6 -11
  43. package/lib-esm/errors/assertValidationError.js +4 -4
  44. package/lib-esm/errors/validation.js +10 -11
  45. package/lib-esm/providers/kinesis/apis/flushEvents.js +15 -18
  46. package/lib-esm/providers/kinesis/apis/record.js +18 -20
  47. package/lib-esm/providers/kinesis/utils/constants.js +1 -1
  48. package/lib-esm/providers/kinesis/utils/getEventBuffer.js +37 -68
  49. package/lib-esm/providers/kinesis/utils/resolveConfig.js +11 -10
  50. package/lib-esm/providers/kinesis-firehose/apis/flushEvents.js +15 -18
  51. package/lib-esm/providers/kinesis-firehose/apis/record.js +17 -19
  52. package/lib-esm/providers/kinesis-firehose/utils/constants.js +1 -1
  53. package/lib-esm/providers/kinesis-firehose/utils/getEventBuffer.js +37 -66
  54. package/lib-esm/providers/kinesis-firehose/utils/resolveConfig.js +11 -10
  55. package/lib-esm/providers/personalize/apis/flushEvents.js +14 -17
  56. package/lib-esm/providers/personalize/apis/record.js +50 -66
  57. package/lib-esm/providers/personalize/utils/autoTrackMedia.js +94 -96
  58. package/lib-esm/providers/personalize/utils/cachedSession.js +28 -40
  59. package/lib-esm/providers/personalize/utils/constants.js +4 -4
  60. package/lib-esm/providers/personalize/utils/getEventBuffer.js +33 -60
  61. package/lib-esm/providers/personalize/utils/resolveConfig.js +11 -10
  62. package/lib-esm/providers/pinpoint/apis/configureAutoTrack.js +4 -4
  63. package/lib-esm/providers/pinpoint/apis/flushEvents.js +5 -8
  64. package/lib-esm/providers/pinpoint/apis/identifyUser.js +14 -26
  65. package/lib-esm/providers/pinpoint/apis/record.js +9 -10
  66. package/lib-esm/providers/pinpoint/utils/resolveConfig.js +3 -4
  67. package/lib-esm/providers/pinpoint/utils/resolveCredentials.js +5 -13
  68. package/lib-esm/setupTests.js +1 -1
  69. package/lib-esm/trackers/EventTracker.js +37 -44
  70. package/lib-esm/trackers/PageViewTracker.js +39 -44
  71. package/lib-esm/trackers/SessionTracker.js +22 -29
  72. package/lib-esm/trackers/SessionTracker.native.js +22 -29
  73. package/lib-esm/tsconfig.tsbuildinfo +1 -1
  74. package/lib-esm/utils/eventBuffer/EventBuffer.js +33 -62
  75. package/lib-esm/utils/groupBy.js +4 -7
  76. package/lib-esm/utils/resolveCredentials.js +5 -13
  77. package/lib-esm/utils/statusHelpers.js +4 -4
  78. package/lib-esm/utils/trackerConfigHelpers.js +1 -1
  79. package/lib-esm/utils/trackerConfigHelpers.native.js +1 -1
  80. package/lib-esm/utils/trackerHelpers.js +4 -4
  81. package/lib-esm/utils/userAgent.js +2 -2
  82. package/package.json +6 -9
  83. package/src/providers/kinesis/utils/getEventBuffer.ts +6 -7
  84. package/src/providers/kinesis-firehose/utils/getEventBuffer.ts +6 -7
  85. package/src/providers/personalize/utils/getEventBuffer.ts +6 -7
  86. package/src/trackers/SessionTracker.native.ts +2 -3
  87. package/src/trackers/SessionTracker.ts +2 -3
@@ -3,9 +3,8 @@
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.getEventBuffer = void 0;
6
- var tslib_1 = require("tslib");
7
- var utils_1 = require("../../../utils");
8
- var client_firehose_1 = require("@aws-sdk/client-firehose");
6
+ const utils_1 = require("../../../utils");
7
+ const client_firehose_1 = require("@aws-sdk/client-firehose");
9
8
  /**
10
9
  * These Records hold cached event buffers and AWS clients.
11
10
  * The hash key is determined by the region and session,
@@ -14,85 +13,57 @@ var client_firehose_1 = require("@aws-sdk/client-firehose");
14
13
  * Only one active session should exist at any given moment.
15
14
  * When a new session is initiated, the previous ones should be released.
16
15
  * */
17
- var eventBufferMap = {};
18
- var cachedClients = {};
19
- var createPutRecordsBatchCommand = function (streamName, events) {
20
- return new client_firehose_1.PutRecordBatchCommand({
21
- DeliveryStreamName: streamName,
22
- Records: events.map(function (event) { return ({
23
- Data: event.event,
24
- }); }),
25
- });
16
+ const eventBufferMap = {};
17
+ const cachedClients = {};
18
+ const createPutRecordsBatchCommand = (streamName, events) => new client_firehose_1.PutRecordBatchCommand({
19
+ DeliveryStreamName: streamName,
20
+ Records: events.map(event => ({
21
+ Data: event.event,
22
+ })),
23
+ });
24
+ const submitEvents = async (events, client, resendLimit) => {
25
+ const groupedByStreamName = Object.entries((0, utils_1.groupBy)(event => event.streamName, events));
26
+ const requests = groupedByStreamName
27
+ .map(([streamName, events]) => createPutRecordsBatchCommand(streamName, events))
28
+ .map(command => client.send(command));
29
+ const responses = await Promise.allSettled(requests);
30
+ const failedEvents = responses
31
+ .map((response, i) => response.status === 'rejected' ? groupedByStreamName[i][1] : [])
32
+ .flat();
33
+ return resendLimit
34
+ ? failedEvents
35
+ .filter(event => event.retryCount < resendLimit)
36
+ .map(event => ({ ...event, retryCount: event.retryCount + 1 }))
37
+ .sort((a, b) => a.timestamp - b.timestamp)
38
+ : [];
26
39
  };
27
- var submitEvents = function (events, client, resendLimit) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
28
- var groupedByStreamName, requests, responses, failedEvents;
29
- return tslib_1.__generator(this, function (_a) {
30
- switch (_a.label) {
31
- case 0:
32
- groupedByStreamName = Object.entries((0, utils_1.groupBy)(function (event) { return event.streamName; }, events));
33
- requests = groupedByStreamName
34
- .map(function (_a) {
35
- var _b = tslib_1.__read(_a, 2), streamName = _b[0], events = _b[1];
36
- return createPutRecordsBatchCommand(streamName, events);
37
- })
38
- .map(function (command) { return client.send(command); });
39
- return [4 /*yield*/, Promise.allSettled(requests)];
40
- case 1:
41
- responses = _a.sent();
42
- failedEvents = responses
43
- .map(function (response, i) {
44
- return response.status === 'rejected' ? groupedByStreamName[i][1] : [];
45
- })
46
- .flat();
47
- return [2 /*return*/, resendLimit
48
- ? failedEvents
49
- .filter(function (event) { return event.retryCount < resendLimit; })
50
- .map(function (event) { return (tslib_1.__assign(tslib_1.__assign({}, event), { retryCount: event.retryCount + 1 })); })
51
- .sort(function (a, b) { return a.timestamp - b.timestamp; })
52
- : []];
53
- }
54
- });
55
- }); };
56
- var getEventBuffer = function (_a) {
57
- var e_1, _b;
58
- var region = _a.region, credentials = _a.credentials, identityId = _a.identityId, bufferSize = _a.bufferSize, flushSize = _a.flushSize, flushInterval = _a.flushInterval, resendLimit = _a.resendLimit, userAgentValue = _a.userAgentValue;
59
- var sessionToken = credentials.sessionToken;
60
- var sessionIdentityKey = [region, sessionToken, identityId]
61
- .filter(function (id) { return !!id; })
62
- .join('-');
40
+ const getEventBuffer = ({ region, credentials, identityId, bufferSize, flushSize, flushInterval, resendLimit, userAgentValue, }) => {
41
+ const sessionIdentityKey = [region, identityId].filter(id => !!id).join('-');
63
42
  if (!eventBufferMap[sessionIdentityKey]) {
64
- var getClient = function () {
43
+ const getClient = () => {
65
44
  if (!cachedClients[sessionIdentityKey]) {
66
45
  cachedClients[sessionIdentityKey] = new client_firehose_1.FirehoseClient({
67
- region: region,
68
- credentials: credentials,
46
+ region,
47
+ credentials,
69
48
  customUserAgent: userAgentValue,
70
49
  });
71
50
  }
72
- var firehoseClient = cachedClients[sessionIdentityKey];
73
- return function (events) { return submitEvents(events, firehoseClient, resendLimit); };
51
+ const firehoseClient = cachedClients[sessionIdentityKey];
52
+ return events => submitEvents(events, firehoseClient, resendLimit);
74
53
  };
75
54
  eventBufferMap[sessionIdentityKey] =
76
55
  new utils_1.EventBuffer({
77
- bufferSize: bufferSize,
78
- flushSize: flushSize,
79
- flushInterval: flushInterval,
56
+ bufferSize,
57
+ flushSize,
58
+ flushInterval,
80
59
  }, getClient);
81
- var releaseSessionKeys = Object.keys(eventBufferMap).filter(function (key) { return key !== sessionIdentityKey; });
82
- try {
83
- for (var releaseSessionKeys_1 = tslib_1.__values(releaseSessionKeys), releaseSessionKeys_1_1 = releaseSessionKeys_1.next(); !releaseSessionKeys_1_1.done; releaseSessionKeys_1_1 = releaseSessionKeys_1.next()) {
84
- var releaseSessionKey = releaseSessionKeys_1_1.value;
60
+ const releaseSessionKeys = Object.keys(eventBufferMap).filter(key => key !== sessionIdentityKey);
61
+ for (const releaseSessionKey of releaseSessionKeys) {
62
+ eventBufferMap[releaseSessionKey].flushAll().finally(() => {
85
63
  eventBufferMap[releaseSessionKey].release();
86
64
  delete eventBufferMap[releaseSessionKey];
87
65
  delete cachedClients[releaseSessionKey];
88
- }
89
- }
90
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
91
- finally {
92
- try {
93
- if (releaseSessionKeys_1_1 && !releaseSessionKeys_1_1.done && (_b = releaseSessionKeys_1.return)) _b.call(releaseSessionKeys_1);
94
- }
95
- finally { if (e_1) throw e_1.error; }
66
+ });
96
67
  }
97
68
  }
98
69
  return eventBufferMap[sessionIdentityKey];
@@ -3,22 +3,23 @@
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.resolveConfig = void 0;
6
- var tslib_1 = require("tslib");
7
- var core_1 = require("@aws-amplify/core");
8
- var errors_1 = require("../../../errors");
9
- var constants_1 = require("./constants");
10
- var resolveConfig = function () {
11
- var _a;
12
- var config = (_a = core_1.Amplify.getConfig().Analytics) === null || _a === void 0 ? void 0 : _a.KinesisFirehose;
13
- var _b = tslib_1.__assign(tslib_1.__assign({}, constants_1.DEFAULT_KINESIS_FIREHOSE_CONFIG), config), region = _b.region, _c = _b.bufferSize, bufferSize = _c === void 0 ? constants_1.DEFAULT_KINESIS_FIREHOSE_CONFIG.bufferSize : _c, _d = _b.flushSize, flushSize = _d === void 0 ? constants_1.DEFAULT_KINESIS_FIREHOSE_CONFIG.flushSize : _d, _e = _b.flushInterval, flushInterval = _e === void 0 ? constants_1.DEFAULT_KINESIS_FIREHOSE_CONFIG.flushInterval : _e, resendLimit = _b.resendLimit;
6
+ const core_1 = require("@aws-amplify/core");
7
+ const errors_1 = require("../../../errors");
8
+ const constants_1 = require("./constants");
9
+ const resolveConfig = () => {
10
+ const config = core_1.Amplify.getConfig().Analytics?.KinesisFirehose;
11
+ const { region, bufferSize = constants_1.DEFAULT_KINESIS_FIREHOSE_CONFIG.bufferSize, flushSize = constants_1.DEFAULT_KINESIS_FIREHOSE_CONFIG.flushSize, flushInterval = constants_1.DEFAULT_KINESIS_FIREHOSE_CONFIG.flushInterval, resendLimit, } = {
12
+ ...constants_1.DEFAULT_KINESIS_FIREHOSE_CONFIG,
13
+ ...config,
14
+ };
14
15
  (0, errors_1.assertValidationError)(!!region, errors_1.AnalyticsValidationErrorCode.NoRegion);
15
16
  (0, errors_1.assertValidationError)(flushSize < bufferSize, errors_1.AnalyticsValidationErrorCode.InvalidFlushSize);
16
17
  return {
17
- region: region,
18
- bufferSize: bufferSize,
19
- flushSize: flushSize,
20
- flushInterval: flushInterval,
21
- resendLimit: resendLimit,
18
+ region,
19
+ bufferSize,
20
+ flushSize,
21
+ flushInterval,
22
+ resendLimit,
22
23
  };
23
24
  };
24
25
  exports.resolveConfig = resolveConfig;
@@ -3,11 +3,11 @@
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.flushEvents = void 0;
6
- var utils_1 = require("../utils");
7
- var utils_2 = require("../../../utils");
8
- var utils_3 = require("@aws-amplify/core/internals/utils");
9
- var core_1 = require("@aws-amplify/core");
10
- var logger = new core_1.ConsoleLogger('Personalize');
6
+ const utils_1 = require("../utils");
7
+ const utils_2 = require("../../../utils");
8
+ const utils_3 = require("@aws-amplify/core/internals/utils");
9
+ const core_1 = require("@aws-amplify/core");
10
+ const logger = new core_1.ConsoleLogger('Personalize');
11
11
  /**
12
12
  * Flushes all buffered Personalize events to the service.
13
13
  *
@@ -15,22 +15,19 @@ var logger = new core_1.ConsoleLogger('Personalize');
15
15
  * This API will make a best-effort attempt to flush events from the buffer. Events recorded immediately after invoking
16
16
  * this API may not be included in the flush.
17
17
  */
18
- var flushEvents = function () {
19
- var _a = (0, utils_1.resolveConfig)(), region = _a.region, flushSize = _a.flushSize, bufferSize = _a.bufferSize, flushInterval = _a.flushInterval;
18
+ const flushEvents = () => {
19
+ const { region, flushSize, bufferSize, flushInterval } = (0, utils_1.resolveConfig)();
20
20
  (0, utils_2.resolveCredentials)()
21
- .then(function (_a) {
22
- var credentials = _a.credentials, identityId = _a.identityId;
23
- return (0, utils_1.getEventBuffer)({
24
- region: region,
25
- flushSize: flushSize,
26
- flushInterval: flushInterval,
27
- bufferSize: bufferSize,
28
- credentials: credentials,
29
- identityId: identityId,
30
- userAgentValue: (0, utils_2.getAnalyticsUserAgentString)(utils_3.AnalyticsAction.Record),
31
- });
32
- })
33
- .then(function (eventBuffer) { return eventBuffer.flushAll(); })
34
- .catch(function (e) { return logger.warn('Failed to flush events', e); });
21
+ .then(({ credentials, identityId }) => (0, utils_1.getEventBuffer)({
22
+ region,
23
+ flushSize,
24
+ flushInterval,
25
+ bufferSize,
26
+ credentials,
27
+ identityId,
28
+ userAgentValue: (0, utils_2.getAnalyticsUserAgentString)(utils_3.AnalyticsAction.Record),
29
+ }))
30
+ .then(eventBuffer => eventBuffer.flushAll())
31
+ .catch(e => logger.warn('Failed to flush events', e));
35
32
  };
36
33
  exports.flushEvents = flushEvents;
@@ -3,84 +3,68 @@
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.record = void 0;
6
- var tslib_1 = require("tslib");
7
- var utils_1 = require("../utils");
8
- var utils_2 = require("../../../utils");
9
- var utils_3 = require("@aws-amplify/core/internals/utils");
10
- var core_1 = require("@aws-amplify/core");
11
- var constants_1 = require("../utils/constants");
12
- var logger = new core_1.ConsoleLogger('Personalize');
13
- var record = function (_a) {
14
- var userId = _a.userId, eventId = _a.eventId, eventType = _a.eventType, properties = _a.properties;
6
+ const utils_1 = require("../utils");
7
+ const utils_2 = require("../../../utils");
8
+ const utils_3 = require("@aws-amplify/core/internals/utils");
9
+ const core_1 = require("@aws-amplify/core");
10
+ const constants_1 = require("../utils/constants");
11
+ const logger = new core_1.ConsoleLogger('Personalize');
12
+ const record = ({ userId, eventId, eventType, properties, }) => {
15
13
  if (!(0, utils_2.isAnalyticsEnabled)()) {
16
14
  logger.debug('Analytics is disabled, event will not be recorded.');
17
15
  return;
18
16
  }
19
- var _b = (0, utils_1.resolveConfig)(), region = _b.region, trackingId = _b.trackingId, bufferSize = _b.bufferSize, flushSize = _b.flushSize, flushInterval = _b.flushInterval;
17
+ const { region, trackingId, bufferSize, flushSize, flushInterval } = (0, utils_1.resolveConfig)();
20
18
  (0, utils_2.resolveCredentials)()
21
- .then(function (_a) {
22
- var credentials = _a.credentials, identityId = _a.identityId;
23
- return tslib_1.__awaiter(void 0, void 0, void 0, function () {
24
- var timestamp, _b, cachedSessionId, cachedUserId, _c, updatedSessionId, updatedUserId, eventBuffer;
25
- return tslib_1.__generator(this, function (_d) {
26
- switch (_d.label) {
27
- case 0:
28
- timestamp = Date.now();
29
- return [4 /*yield*/, (0, utils_1.resolveCachedSession)()];
30
- case 1:
31
- _b = _d.sent(), cachedSessionId = _b.sessionId, cachedUserId = _b.userId;
32
- if (eventType === constants_1.IDENTIFY_EVENT_TYPE) {
33
- (0, utils_1.updateCachedSession)(typeof properties.userId === 'string' ? properties.userId : '', cachedSessionId, cachedUserId);
34
- }
35
- else if (!!userId) {
36
- (0, utils_1.updateCachedSession)(userId, cachedSessionId, cachedUserId);
37
- }
38
- return [4 /*yield*/, (0, utils_1.resolveCachedSession)()];
39
- case 2:
40
- _c = _d.sent(), updatedSessionId = _c.sessionId, updatedUserId = _c.userId;
41
- eventBuffer = (0, utils_1.getEventBuffer)({
42
- region: region,
43
- flushSize: flushSize,
44
- flushInterval: flushInterval,
45
- bufferSize: bufferSize,
46
- credentials: credentials,
47
- identityId: identityId,
48
- userAgentValue: (0, utils_2.getAnalyticsUserAgentString)(utils_3.AnalyticsAction.Record),
49
- });
50
- if (eventType === constants_1.MEDIA_AUTO_TRACK_EVENT_TYPE) {
51
- (0, utils_1.autoTrackMedia)({
52
- trackingId: trackingId,
53
- sessionId: updatedSessionId,
54
- userId: updatedUserId,
55
- event: {
56
- eventId: eventId,
57
- eventType: eventType,
58
- properties: properties,
59
- },
60
- }, eventBuffer);
61
- }
62
- else {
63
- eventBuffer.append({
64
- trackingId: trackingId,
65
- sessionId: updatedSessionId,
66
- userId: updatedUserId,
67
- event: {
68
- eventId: eventId,
69
- eventType: eventType,
70
- properties: properties,
71
- },
72
- timestamp: timestamp,
73
- });
74
- }
75
- if (eventBuffer.length >= bufferSize) {
76
- eventBuffer.flushAll();
77
- }
78
- return [2 /*return*/];
79
- }
80
- });
19
+ .then(async ({ credentials, identityId }) => {
20
+ const timestamp = Date.now();
21
+ const { sessionId: cachedSessionId, userId: cachedUserId } = await (0, utils_1.resolveCachedSession)();
22
+ if (eventType === constants_1.IDENTIFY_EVENT_TYPE) {
23
+ (0, utils_1.updateCachedSession)(typeof properties.userId === 'string' ? properties.userId : '', cachedSessionId, cachedUserId);
24
+ }
25
+ else if (!!userId) {
26
+ (0, utils_1.updateCachedSession)(userId, cachedSessionId, cachedUserId);
27
+ }
28
+ const { sessionId: updatedSessionId, userId: updatedUserId } = await (0, utils_1.resolveCachedSession)();
29
+ const eventBuffer = (0, utils_1.getEventBuffer)({
30
+ region,
31
+ flushSize,
32
+ flushInterval,
33
+ bufferSize,
34
+ credentials,
35
+ identityId,
36
+ userAgentValue: (0, utils_2.getAnalyticsUserAgentString)(utils_3.AnalyticsAction.Record),
81
37
  });
38
+ if (eventType === constants_1.MEDIA_AUTO_TRACK_EVENT_TYPE) {
39
+ (0, utils_1.autoTrackMedia)({
40
+ trackingId,
41
+ sessionId: updatedSessionId,
42
+ userId: updatedUserId,
43
+ event: {
44
+ eventId,
45
+ eventType,
46
+ properties,
47
+ },
48
+ }, eventBuffer);
49
+ }
50
+ else {
51
+ eventBuffer.append({
52
+ trackingId,
53
+ sessionId: updatedSessionId,
54
+ userId: updatedUserId,
55
+ event: {
56
+ eventId,
57
+ eventType,
58
+ properties,
59
+ },
60
+ timestamp,
61
+ });
62
+ }
63
+ if (eventBuffer.length >= bufferSize) {
64
+ eventBuffer.flushAll();
65
+ }
82
66
  })
83
- .catch(function (e) {
67
+ .catch(e => {
84
68
  logger.warn('Failed to record event.', e);
85
69
  });
86
70
  };
@@ -3,9 +3,8 @@
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.autoTrackMedia = void 0;
6
- var tslib_1 = require("tslib");
7
- var utils_1 = require("@aws-amplify/core/internals/utils");
8
- var core_1 = require("@aws-amplify/core");
6
+ const utils_1 = require("@aws-amplify/core/internals/utils");
7
+ const core_1 = require("@aws-amplify/core");
9
8
  var HTML5_MEDIA_EVENT;
10
9
  (function (HTML5_MEDIA_EVENT) {
11
10
  HTML5_MEDIA_EVENT["PLAY"] = "play";
@@ -25,43 +24,43 @@ var EVENT_TYPE;
25
24
  EVENT_TYPE["PAUSE"] = "Pause";
26
25
  EVENT_TYPE["TIME_WATCHED"] = "TimeWatched";
27
26
  })(EVENT_TYPE || (EVENT_TYPE = {}));
28
- var logger = new core_1.ConsoleLogger('MediaAutoTrack');
29
- var startIframeAutoTracking = function (element, recordEvent) {
30
- var isPlaying = false;
31
- var player;
32
- var mediaProperties = function () {
33
- var duration = Number(parseFloat(player.getDuration()).toFixed(4));
34
- var currentTime = Number(parseFloat(player.getCurrentTime()).toFixed(4));
27
+ const logger = new core_1.ConsoleLogger('MediaAutoTrack');
28
+ const startIframeAutoTracking = (element, recordEvent) => {
29
+ let isPlaying = false;
30
+ let player;
31
+ const mediaProperties = () => {
32
+ const duration = Number(parseFloat(player.getDuration()).toFixed(4));
33
+ const currentTime = Number(parseFloat(player.getCurrentTime()).toFixed(4));
35
34
  return {
36
- duration: duration,
35
+ duration,
37
36
  eventValue: Number((currentTime / duration).toFixed(4)),
38
37
  };
39
38
  };
40
- var scriptElement = document.createElement('script');
39
+ const scriptElement = document.createElement('script');
41
40
  scriptElement.type = 'text/javascript';
42
41
  scriptElement.src = 'https://www.youtube.com/iframe_api';
43
42
  document.body.append(scriptElement);
44
- var timer = setInterval(function () {
43
+ const timer = setInterval(() => {
45
44
  if (isPlaying && player) {
46
45
  recordEvent(EVENT_TYPE.TIME_WATCHED, mediaProperties());
47
46
  }
48
47
  }, 3000);
49
- element.addEventListener('unload', function () { return clearInterval(timer); });
48
+ element.addEventListener('unload', () => clearInterval(timer));
50
49
  // @ts-ignore
51
- window.onYouTubeIframeAPIReady = function () {
50
+ window.onYouTubeIframeAPIReady = () => {
52
51
  // @ts-ignore
53
52
  delete window.onYouTubeIframeAPIReady;
54
53
  // @ts-ignore
55
54
  player = new window.YT.Player(element.id, {
56
55
  events: {
57
- onStateChange: function (event) {
58
- var iframeEventMapping = {
56
+ onStateChange: (event) => {
57
+ const iframeEventMapping = {
59
58
  0: EVENT_TYPE.ENDED,
60
59
  1: EVENT_TYPE.PLAY,
61
60
  2: EVENT_TYPE.PAUSE,
62
61
  };
63
62
  // @ts-ignore
64
- var eventType = iframeEventMapping[event.data];
63
+ const eventType = iframeEventMapping[event.data];
65
64
  switch (eventType) {
66
65
  case EVENT_TYPE.ENDED:
67
66
  case EVENT_TYPE.PAUSE:
@@ -79,105 +78,104 @@ var startIframeAutoTracking = function (element, recordEvent) {
79
78
  });
80
79
  };
81
80
  };
82
- var startHTMLMediaAutoTracking = function (element, recordEvent) {
83
- var isPlaying = false;
84
- var mediaProperties = function () { return ({
81
+ const startHTMLMediaAutoTracking = (element, recordEvent) => {
82
+ let isPlaying = false;
83
+ const mediaProperties = () => ({
85
84
  duration: element.duration,
86
85
  eventValue: Number((element.currentTime / element.duration).toFixed(4)),
87
- }); };
88
- var timer = setInterval(function () {
86
+ });
87
+ const timer = setInterval(() => {
89
88
  if (isPlaying) {
90
89
  recordEvent(EVENT_TYPE.TIME_WATCHED, mediaProperties());
91
90
  }
92
91
  }, 3000);
93
- element.addEventListener('unload', function () { return clearInterval(timer); });
94
- element.addEventListener(HTML5_MEDIA_EVENT.PLAY, function () {
92
+ element.addEventListener('unload', () => clearInterval(timer));
93
+ element.addEventListener(HTML5_MEDIA_EVENT.PLAY, () => {
95
94
  isPlaying = true;
96
95
  recordEvent(EVENT_TYPE.PLAY, mediaProperties());
97
96
  });
98
- element.addEventListener(HTML5_MEDIA_EVENT.PAUSE, function () {
97
+ element.addEventListener(HTML5_MEDIA_EVENT.PAUSE, () => {
99
98
  isPlaying = false;
100
99
  recordEvent(EVENT_TYPE.PAUSE, mediaProperties());
101
100
  });
102
- element.addEventListener(HTML5_MEDIA_EVENT.ENDED, function () {
101
+ element.addEventListener(HTML5_MEDIA_EVENT.ENDED, () => {
103
102
  isPlaying = false;
104
103
  recordEvent(EVENT_TYPE.ENDED, mediaProperties());
105
104
  });
106
105
  };
107
- var checkElementLoaded = function (interval, maxTries) {
108
- var retryCount = 0;
109
- var wait = function () { return new Promise(function (r) { return setTimeout(r, interval); }); };
110
- var check = function (elementId) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
111
- var domElement;
112
- return tslib_1.__generator(this, function (_a) {
113
- switch (_a.label) {
114
- case 0:
115
- if (retryCount >= maxTries) {
116
- return [2 /*return*/, false];
117
- }
118
- domElement = document.getElementById(elementId);
119
- if (!(domElement && domElement.clientHeight)) return [3 /*break*/, 1];
120
- return [2 /*return*/, true];
121
- case 1:
122
- retryCount += 1;
123
- return [4 /*yield*/, wait()];
124
- case 2:
125
- _a.sent();
126
- return [4 /*yield*/, check(elementId)];
127
- case 3: return [2 /*return*/, _a.sent()];
128
- }
129
- });
130
- }); };
106
+ const checkElementLoaded = (interval, maxTries) => {
107
+ let retryCount = 0;
108
+ const wait = () => new Promise(r => setTimeout(r, interval));
109
+ const check = async (elementId) => {
110
+ if (retryCount >= maxTries) {
111
+ return false;
112
+ }
113
+ const domElement = document.getElementById(elementId);
114
+ if (domElement && domElement.clientHeight) {
115
+ return true;
116
+ }
117
+ else {
118
+ retryCount += 1;
119
+ await wait();
120
+ return await check(elementId);
121
+ }
122
+ };
131
123
  return check;
132
124
  };
133
- var recordEvent = function (config, eventBuffer) {
134
- return function (eventType, properties) {
135
- // override eventType and merge properties
136
- eventBuffer.append(tslib_1.__assign(tslib_1.__assign({}, config), { event: tslib_1.__assign(tslib_1.__assign({}, config.event), { eventType: eventType, properties: tslib_1.__assign(tslib_1.__assign({}, config.event.properties), properties) }), timestamp: Date.now() }));
137
- };
125
+ const recordEvent = (config, eventBuffer) => (eventType, properties) => {
126
+ // override eventType and merge properties
127
+ eventBuffer.append({
128
+ ...config,
129
+ event: {
130
+ ...config.event,
131
+ eventType,
132
+ properties: {
133
+ ...config.event.properties,
134
+ ...properties,
135
+ },
136
+ },
137
+ timestamp: Date.now(),
138
+ });
138
139
  };
139
- var autoTrackMedia = function (config, eventBuffer) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
140
- var _a, eventType, properties, domElementId, otherProperties, elementId, isElementLoaded, autoTrackConfigWithoutDomElementId, element;
141
- return tslib_1.__generator(this, function (_b) {
142
- switch (_b.label) {
143
- case 0:
144
- _a = config.event, eventType = _a.eventType, properties = _a.properties;
145
- domElementId = properties.domElementId, otherProperties = tslib_1.__rest(properties, ["domElementId"]);
146
- if (!(0, utils_1.isBrowser)()) {
147
- logger.debug("".concat(eventType, " only for browser"));
148
- return [2 /*return*/];
149
- }
150
- if (typeof domElementId === 'string' && !domElementId) {
151
- logger.debug("Missing domElementId field in 'properties' for MediaAutoTrack event type.");
152
- return [2 /*return*/];
153
- }
154
- elementId = domElementId;
155
- return [4 /*yield*/, checkElementLoaded(500, 5)(elementId)];
156
- case 1:
157
- isElementLoaded = _b.sent();
158
- if (isElementLoaded) {
159
- autoTrackConfigWithoutDomElementId = tslib_1.__assign(tslib_1.__assign({}, config), { event: tslib_1.__assign(tslib_1.__assign({}, config.event), { properties: otherProperties }) });
160
- element = document.getElementById(elementId);
161
- switch (element === null || element === void 0 ? void 0 : element.tagName) {
162
- case MEDIA_TYPE.IFRAME:
163
- startIframeAutoTracking(element, recordEvent(autoTrackConfigWithoutDomElementId, eventBuffer));
164
- break;
165
- case MEDIA_TYPE.VIDEO:
166
- case MEDIA_TYPE.AUDIO:
167
- if (element instanceof HTMLMediaElement) {
168
- startHTMLMediaAutoTracking(element, recordEvent(autoTrackConfigWithoutDomElementId, eventBuffer));
169
- }
170
- break;
171
- default:
172
- logger.debug("Unsupported DOM element tag: ".concat(element === null || element === void 0 ? void 0 : element.tagName));
173
- break;
174
- }
175
- }
176
- else {
177
- logger.debug('Cannot find the media element.');
140
+ const autoTrackMedia = async (config, eventBuffer) => {
141
+ const { eventType, properties } = config.event;
142
+ const { domElementId, ...otherProperties } = properties;
143
+ if (!(0, utils_1.isBrowser)()) {
144
+ logger.debug(`${eventType} only for browser`);
145
+ return;
146
+ }
147
+ if (typeof domElementId === 'string' && !domElementId) {
148
+ logger.debug("Missing domElementId field in 'properties' for MediaAutoTrack event type.");
149
+ return;
150
+ }
151
+ const elementId = domElementId;
152
+ const isElementLoaded = await checkElementLoaded(500, 5)(elementId);
153
+ if (isElementLoaded) {
154
+ const autoTrackConfigWithoutDomElementId = {
155
+ ...config,
156
+ event: {
157
+ ...config.event,
158
+ properties: otherProperties,
159
+ },
160
+ };
161
+ const element = document.getElementById(elementId);
162
+ switch (element?.tagName) {
163
+ case MEDIA_TYPE.IFRAME:
164
+ startIframeAutoTracking(element, recordEvent(autoTrackConfigWithoutDomElementId, eventBuffer));
165
+ break;
166
+ case MEDIA_TYPE.VIDEO:
167
+ case MEDIA_TYPE.AUDIO:
168
+ if (element instanceof HTMLMediaElement) {
169
+ startHTMLMediaAutoTracking(element, recordEvent(autoTrackConfigWithoutDomElementId, eventBuffer));
178
170
  }
179
- return [2 /*return*/];
171
+ break;
172
+ default:
173
+ logger.debug(`Unsupported DOM element tag: ${element?.tagName}`);
174
+ break;
180
175
  }
181
- });
182
- }); };
176
+ }
177
+ else {
178
+ logger.debug('Cannot find the media element.');
179
+ }
180
+ };
183
181
  exports.autoTrackMedia = autoTrackMedia;