@amplitude/analytics-core 2.62.0-codexsemantic-review-integration.0 → 2.62.0-video-analytics-8.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 (93) hide show
  1. package/lib/cjs/config.d.ts +1 -0
  2. package/lib/cjs/config.d.ts.map +1 -1
  3. package/lib/cjs/config.js +1 -0
  4. package/lib/cjs/config.js.map +1 -1
  5. package/lib/cjs/heartbeat.d.ts +23 -4
  6. package/lib/cjs/heartbeat.d.ts.map +1 -1
  7. package/lib/cjs/heartbeat.js +108 -18
  8. package/lib/cjs/heartbeat.js.map +1 -1
  9. package/lib/cjs/index.d.ts +3 -3
  10. package/lib/cjs/index.d.ts.map +1 -1
  11. package/lib/cjs/index.js +4 -3
  12. package/lib/cjs/index.js.map +1 -1
  13. package/lib/cjs/observers/video.d.ts +6 -3
  14. package/lib/cjs/observers/video.d.ts.map +1 -1
  15. package/lib/cjs/observers/video.js +41 -8
  16. package/lib/cjs/observers/video.js.map +1 -1
  17. package/lib/cjs/page-view-id.d.ts +3 -1
  18. package/lib/cjs/page-view-id.d.ts.map +1 -1
  19. package/lib/cjs/page-view-id.js +4 -2
  20. package/lib/cjs/page-view-id.js.map +1 -1
  21. package/lib/cjs/plugins/destination.d.ts +21 -1
  22. package/lib/cjs/plugins/destination.d.ts.map +1 -1
  23. package/lib/cjs/plugins/destination.js +180 -25
  24. package/lib/cjs/plugins/destination.js.map +1 -1
  25. package/lib/cjs/types/config/core-config.d.ts +5 -0
  26. package/lib/cjs/types/config/core-config.d.ts.map +1 -1
  27. package/lib/cjs/types/config/core-config.js.map +1 -1
  28. package/lib/cjs/types/event/base-event.d.ts +1 -0
  29. package/lib/cjs/types/event/base-event.d.ts.map +1 -1
  30. package/lib/cjs/types/event/base-event.js.map +1 -1
  31. package/lib/cjs/types/event/event.d.ts +4 -1
  32. package/lib/cjs/types/event/event.d.ts.map +1 -1
  33. package/lib/cjs/types/event/event.js.map +1 -1
  34. package/lib/cjs/types/page-view-tracking.d.ts +24 -0
  35. package/lib/cjs/types/page-view-tracking.d.ts.map +1 -1
  36. package/lib/cjs/types/page-view-tracking.js.map +1 -1
  37. package/lib/cjs/types/payload.d.ts +5 -0
  38. package/lib/cjs/types/payload.d.ts.map +1 -1
  39. package/lib/cjs/types/payload.js.map +1 -1
  40. package/lib/cjs/video-analytics/track-video.d.ts +1 -1
  41. package/lib/cjs/video-analytics/track-video.d.ts.map +1 -1
  42. package/lib/cjs/video-analytics/track-video.js +107 -19
  43. package/lib/cjs/video-analytics/track-video.js.map +1 -1
  44. package/lib/cjs/video-analytics/types.d.ts +6 -5
  45. package/lib/cjs/video-analytics/types.d.ts.map +1 -1
  46. package/lib/cjs/video-analytics/types.js.map +1 -1
  47. package/lib/esm/config.d.ts +1 -0
  48. package/lib/esm/config.d.ts.map +1 -1
  49. package/lib/esm/config.js +1 -0
  50. package/lib/esm/config.js.map +1 -1
  51. package/lib/esm/heartbeat.d.ts +23 -4
  52. package/lib/esm/heartbeat.d.ts.map +1 -1
  53. package/lib/esm/heartbeat.js +108 -18
  54. package/lib/esm/heartbeat.js.map +1 -1
  55. package/lib/esm/index.d.ts +3 -3
  56. package/lib/esm/index.d.ts.map +1 -1
  57. package/lib/esm/index.js +1 -1
  58. package/lib/esm/index.js.map +1 -1
  59. package/lib/esm/observers/video.d.ts +6 -3
  60. package/lib/esm/observers/video.d.ts.map +1 -1
  61. package/lib/esm/observers/video.js +41 -8
  62. package/lib/esm/observers/video.js.map +1 -1
  63. package/lib/esm/page-view-id.d.ts +3 -1
  64. package/lib/esm/page-view-id.d.ts.map +1 -1
  65. package/lib/esm/page-view-id.js +4 -2
  66. package/lib/esm/page-view-id.js.map +1 -1
  67. package/lib/esm/plugins/destination.d.ts +21 -1
  68. package/lib/esm/plugins/destination.d.ts.map +1 -1
  69. package/lib/esm/plugins/destination.js +181 -26
  70. package/lib/esm/plugins/destination.js.map +1 -1
  71. package/lib/esm/types/config/core-config.d.ts +5 -0
  72. package/lib/esm/types/config/core-config.d.ts.map +1 -1
  73. package/lib/esm/types/config/core-config.js.map +1 -1
  74. package/lib/esm/types/event/base-event.d.ts +1 -0
  75. package/lib/esm/types/event/base-event.d.ts.map +1 -1
  76. package/lib/esm/types/event/base-event.js.map +1 -1
  77. package/lib/esm/types/event/event.d.ts +4 -1
  78. package/lib/esm/types/event/event.d.ts.map +1 -1
  79. package/lib/esm/types/event/event.js.map +1 -1
  80. package/lib/esm/types/page-view-tracking.d.ts +24 -0
  81. package/lib/esm/types/page-view-tracking.d.ts.map +1 -1
  82. package/lib/esm/types/page-view-tracking.js.map +1 -1
  83. package/lib/esm/types/payload.d.ts +5 -0
  84. package/lib/esm/types/payload.d.ts.map +1 -1
  85. package/lib/esm/types/payload.js.map +1 -1
  86. package/lib/esm/video-analytics/track-video.d.ts +1 -1
  87. package/lib/esm/video-analytics/track-video.d.ts.map +1 -1
  88. package/lib/esm/video-analytics/track-video.js +107 -19
  89. package/lib/esm/video-analytics/track-video.js.map +1 -1
  90. package/lib/esm/video-analytics/types.d.ts +6 -5
  91. package/lib/esm/video-analytics/types.d.ts.map +1 -1
  92. package/lib/esm/video-analytics/types.js.map +1 -1
  93. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"video.d.ts","sourceRoot":"","sources":["../../../src/observers/video.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAEV,UAAU,EACV,mBAAmB,EACnB,UAAU,EACV,MAAM,EAEP,MAAM,0BAA0B,CAAC;AAElC,YAAY,EAAE,MAAM,EAAE,CAAC;AAEvB,KAAK,aAAa,GAAG,SAAS,GAAG,QAAQ,GAAG,OAAO,GAAG,OAAO,GAAG,SAAS,CAAC;AAE1E,MAAM,MAAM,KAAK,GAAG;IAClB,aAAa,EAAE,aAAa,CAAC;IAC7B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,UAAU,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC;IAC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EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,KAAK,CAAC,EAAE,cAAc,CAAC;CACxB,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG;IAChC,OAAO,EAAE,gBAAgB,GAAG,mBAAmB,GAAG,UAAU,CAAC;IAC7D,aAAa,EAAE,CAAC,aAAa,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,KAAK,IAAI,CAAC;IAChE,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB,CAAC;AAEF,qBAAa,aAAa;IACxB,OAAO,CAAC,KAAK,CAEX;IAEF,OAAO,CAAC,eAAe,CAA8C;IACrE,OAAO,CAAC,OAAO,CAAa;IAC5B,OAAO,CAAC,aAAa,CAAmD;IACxE,OAAO,CAAC,OAAO,CA+Bb;gBAEU,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,EAAE,UAAU,EAAE,EAAE,mBAAmB;IAS/E,OAAO,CAAC,kBAAkB;IAQ1B,OAAO,CAAC,oBAAoB;IAY5B,OAAO,CAAC,mBAAmB;IAoC3B,OAAO,CAAC,oBAAoB;IAO5B,OAAO,CAAC,UAAU;IA2BlB,OAAO,CAAC,WAAW;IAMnB,OAAO;CAIR"}
@@ -10,6 +10,7 @@ var VideoObserver = /** @class */ (function () {
10
10
  this.state = {
11
11
  playbackState: 'paused',
12
12
  };
13
+ this.waitingInterval = null;
13
14
  this.handler = {
14
15
  onPlay: function (evt) {
15
16
  _this.updatePlaybackState('playing', evt);
@@ -17,15 +18,15 @@ var VideoObserver = /** @class */ (function () {
17
18
  onPause: function (evt) {
18
19
  _this.updatePlaybackState('paused', evt);
19
20
  },
20
- onEnded: function (evt) {
21
- _this.updatePlaybackState('ended', evt);
21
+ onEnded: function (evt, cause) {
22
+ _this.updatePlaybackState('ended', evt, cause);
22
23
  },
23
24
  onSeeking: function () {
24
25
  var nextState = tslib_1.__assign(tslib_1.__assign({}, _this.state), { isSeeking: true });
25
26
  _this.updateState(nextState);
26
27
  },
27
28
  onSeeked: function (event) {
28
- var nextState = tslib_1.__assign(tslib_1.__assign({}, _this.state), { isSeeking: false, position: event.last_position });
29
+ var nextState = tslib_1.__assign(tslib_1.__assign({}, _this.state), { isSeeking: false, position: event.position });
29
30
  _this.updateState(nextState);
30
31
  },
31
32
  onError: function (errorMessage) {
@@ -52,18 +53,49 @@ var VideoObserver = /** @class */ (function () {
52
53
  }
53
54
  };
54
55
  VideoObserver.prototype.updateStateWithError = function (error) {
56
+ this.clearWaitingInterval();
55
57
  var previousState = this.state;
56
- var nextState = tslib_1.__assign(tslib_1.__assign({}, previousState), { playbackState: 'error', errorMessage: error });
58
+ var nextState = tslib_1.__assign(tslib_1.__assign({}, previousState), { playbackState: 'error', errorMessage: error, cause: undefined });
57
59
  this.updateState(nextState);
58
60
  };
59
- VideoObserver.prototype.updatePlaybackState = function (playbackState, event) {
60
- var nextState = tslib_1.__assign(tslib_1.__assign({}, this.state), { playbackState: playbackState, lastEvent: event, position: event.last_position });
61
+ VideoObserver.prototype.updatePlaybackState = function (playbackState, event, cause) {
62
+ var _this = this;
63
+ var previousPlayback = this.state.playbackState;
64
+ // Aborting a load does not emit `seeked`. A seek still open when this media
65
+ // ends, or when the replacement starts, must not stick to the next stream.
66
+ var clearSeeking = !!this.state.isSeeking &&
67
+ (playbackState === 'ended' || (playbackState === 'playing' && previousPlayback === 'ended'));
68
+ var nextState = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, this.state), { playbackState: playbackState, errorMessage: undefined, lastEvent: event, position: event.position, cause: cause }), (clearSeeking ? { isSeeking: false } : {}));
61
69
  this.updateState(nextState);
70
+ this.clearWaitingInterval();
71
+ if (playbackState !== 'playing') {
72
+ return;
73
+ }
74
+ // if it's in a playing state, but the playhead is not moving,
75
+ // then transition playback from 'playing' to 'waiting'
76
+ // (the "waiting" listener isn't reliable, so this is a fallback)
77
+ var prevPosition = this.state.position;
78
+ this.waitingInterval = setInterval(function () {
79
+ var position = _this.state.position;
80
+ if (_this.state.playbackState === 'playing' && typeof prevPosition === 'number' && prevPosition === position) {
81
+ // no new player event backs this transition, so carry the current position and metadata over
82
+ _this.updateState(tslib_1.__assign(tslib_1.__assign({}, _this.state), { playbackState: 'waiting' }));
83
+ }
84
+ prevPosition = position;
85
+ }, 1000);
86
+ };
87
+ VideoObserver.prototype.clearWaitingInterval = function () {
88
+ if (this.waitingInterval) {
89
+ clearInterval(this.waitingInterval);
90
+ this.waitingInterval = null;
91
+ }
62
92
  };
63
93
  VideoObserver.prototype.updateTime = function (event) {
64
94
  var _a, _b;
65
95
  var lastVideoEvent = this.state.lastEvent;
66
- if (!lastVideoEvent || this.state.playbackState !== 'playing') {
96
+ var isWaiting = this.state.playbackState === 'waiting';
97
+ var isPlaying = this.state.playbackState === 'playing';
98
+ if (!lastVideoEvent || (!isPlaying && !isWaiting)) {
67
99
  return;
68
100
  }
69
101
  var isSeeking = event.isSeeking || this.state.isSeeking;
@@ -74,7 +106,7 @@ var VideoObserver = /** @class */ (function () {
74
106
  return;
75
107
  }
76
108
  var timeDelta = nextPosition - lastPosition;
77
- var nextState = tslib_1.__assign(tslib_1.__assign({}, this.state), { position: nextPosition, watchTime: ((_b = this.state.watchTime) !== null && _b !== void 0 ? _b : 0) + timeDelta });
109
+ var nextState = tslib_1.__assign(tslib_1.__assign({}, this.state), { playbackState: 'playing', position: nextPosition, watchTime: ((_b = this.state.watchTime) !== null && _b !== void 0 ? _b : 0) + timeDelta });
78
110
  this.updateState(nextState);
79
111
  };
80
112
  VideoObserver.prototype.updateState = function (nextState) {
@@ -83,6 +115,7 @@ var VideoObserver = /** @class */ (function () {
83
115
  this.stateChangeHandler(previousState, nextState);
84
116
  };
85
117
  VideoObserver.prototype.destroy = function () {
118
+ this.clearWaitingInterval();
86
119
  this.untrack();
87
120
  };
88
121
  return VideoObserver;
@@ -1 +1 @@
1
- {"version":3,"file":"video.js","sourceRoot":"","sources":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YAAY,GAAG,KAAK,CAAC,QAAQ,CAAC;QACpC,IAAI,SAAS,EAAE;YACb,IAAI,CAAC,KAAK,yCACL,IAAI,CAAC,KAAK,KACb,QAAQ,EAAE,YAAY,GACvB,CAAC;YACF,OAAO;SACR;QACD,IAAM,SAAS,GAAG,YAAY,GAAG,YAAY,CAAC;QAC9C,IAAM,SAAS,yCACV,IAAI,CAAC,KAAK,KACb,QAAQ,EAAE,YAAY,EACtB,SAAS,EAAE,CAAC,MAAA,IAAI,CAAC,KAAK,CAAC,SAAS,mCAAI,CAAC,CAAC,GAAG,SAAS,GACnD,CAAC;QACF,IAAI,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC;IAC9B,CAAC;IAEO,mCAAW,GAAnB,UAAoB,SAAgB;QAClC,IAAM,aAAa,GAAG,IAAI,CAAC,KAAK,CAAC;QACjC,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC;QACvB,IAAI,CAAC,kBAAkB,CAAC,aAAa,EAAE,SAAS,CAAC,CAAC;IACpD,CAAC;IAED,+BAAO,GAAP;QACE,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;IACH,oBAAC;AAAD,CAAC,AA9GD,IA8GC;AA9GY,sCAAa","sourcesContent":["import { trackHtmlVideo, trackEmbeddedVideo } from '../video-analytics/track-video';\nimport type {\n VideoHandler,\n VideoEvent,\n EmbeddedVideoPlayer,\n MuxElement,\n Vendor,\n TimeUpdateEvent,\n} from '../video-analytics/types';\n\nexport type { Vendor };\n\ntype PlaybackState = 'playing' | 'paused' | 'ended' | 'error' | 'seeking';\n\nexport type State = {\n playbackState: PlaybackState;\n errorMessage?: string;\n lastEvent?: VideoEvent;\n watchTime?: number;\n position?: number | null;\n isSeeking?: boolean;\n};\n\nexport type VideoObserverParams = {\n videoEl: HTMLVideoElement | EmbeddedVideoPlayer | MuxElement;\n onStateChange: (previousState: State, nextState: State) => void;\n vendor?: Vendor;\n isEmbedded?: boolean;\n};\n\nexport class VideoObserver {\n private state: State = {\n playbackState: 'paused',\n };\n\n private untrack: () => void;\n private onStateChange: (previousState: State, nextState: State) => void;\n private handler: VideoHandler = {\n onPlay: (evt: VideoEvent) => {\n this.updatePlaybackState('playing', evt);\n },\n onPause: (evt: VideoEvent) => {\n this.updatePlaybackState('paused', evt);\n },\n onEnded: (evt: VideoEvent) => {\n this.updatePlaybackState('ended', evt);\n },\n onSeeking: () => {\n const nextState: State = {\n ...this.state,\n isSeeking: true,\n };\n this.updateState(nextState);\n },\n onSeeked: (event: VideoEvent) => {\n const nextState: State = {\n ...this.state,\n isSeeking: false,\n position: event.last_position,\n };\n this.updateState(nextState);\n },\n onError: (errorMessage: string) => {\n this.updateStateWithError(errorMessage);\n },\n onTimeUpdate: (evt: TimeUpdateEvent) => {\n this.updateTime(evt);\n },\n };\n\n constructor({ videoEl, onStateChange, vendor, isEmbedded }: VideoObserverParams) {\n this.onStateChange = onStateChange;\n if (isEmbedded) {\n this.untrack = trackEmbeddedVideo(videoEl as EmbeddedVideoPlayer, this.handler, vendor);\n } else {\n this.untrack = trackHtmlVideo(videoEl as HTMLVideoElement, this.handler, vendor);\n }\n }\n\n private stateChangeHandler(previousState: State, nextState: State) {\n try {\n this.onStateChange(previousState, nextState);\n } catch (_error) {\n // Swallow callback errors to keep observer state consistent.\n }\n }\n\n private updateStateWithError(error: string) {\n const previousState = this.state;\n const nextState: State = {\n ...previousState,\n playbackState: 'error',\n errorMessage: error,\n };\n this.updateState(nextState);\n }\n\n private updatePlaybackState(playbackState: PlaybackState, event: VideoEvent) {\n const nextState: State = {\n ...this.state,\n playbackState,\n lastEvent: event,\n position: event.last_position,\n };\n this.updateState(nextState);\n }\n\n private updateTime(event: TimeUpdateEvent) {\n const lastVideoEvent = this.state.lastEvent;\n if (!lastVideoEvent || this.state.playbackState !== 'playing') {\n return;\n }\n const isSeeking = event.isSeeking || this.state.isSeeking;\n const lastPosition = this.state.position ?? 0;\n const nextPosition = event.position;\n if (isSeeking) {\n this.state = {\n ...this.state,\n position: nextPosition,\n };\n return;\n }\n const timeDelta = nextPosition - lastPosition;\n const nextState: State = {\n ...this.state,\n position: nextPosition,\n watchTime: (this.state.watchTime ?? 0) + timeDelta,\n };\n this.updateState(nextState);\n }\n\n private updateState(nextState: State) {\n const previousState = this.state;\n this.state = nextState;\n this.stateChangeHandler(previousState, nextState);\n }\n\n destroy() {\n this.untrack();\n }\n}\n"]}
1
+ {"version":3,"file":"video.js","sourceRoot":"","sources":["../../../src/observers/video.ts"],"names":[],"mappings":";;;;AAAA,8DAAoF;AAgCpF;IAyCE,uBAAY,EAAmE;YAAjE,OAAO,aAAA,EAAE,aAAa,mBAAA,EAAE,MAAM,YAAA,EAAE,UAAU,gBAAA;QAAxD,iBAOC;QA/CO,UAAK,GAAU;YACrB,aAAa,EAAE,QAAQ;SACxB,CAAC;QAEM,oBAAe,GAAyC,IAAI,CAAC;QAG7D,YAAO,GAAiB;YAC9B,MAAM,EAAE,UAAC,GAAe;gBACtB,KAAI,CAAC,mBAAmB,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC;YAC3C,CAAC;YACD,OAAO,EAAE,UAAC,GAAe;gBACvB,KAAI,CAAC,mBAAmB,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;YAC1C,CAAC;YACD,OAAO,EAAE,UAAC,GAAe,EAAE,KAAsB;gBAC/C,KAAI,CAAC,mBAAmB,CAAC,OAAO,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC;YAChD,CAAC;YACD,SAAS,EAAE;gBACT,IAAM,SAAS,yCACV,KAAI,CAAC,KAAK,KACb,SAAS,EAAE,IAAI,GAChB,CAAC;gBACF,KAAI,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC;YAC9B,CAAC;YACD,QAAQ,EAAE,UAAC,KAAiB;gBAC1B,IAAM,SAAS,yCACV,KAAI,CAAC,KAAK,KACb,SAAS,EAAE,KAAK,EAChB,QAAQ,EAAE,KAAK,CAAC,QAAQ,GACzB,CAAC;gBACF,KAAI,CAAC,WAAW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AC5B,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;IACH,oBAAC;AAAD,CAAC,AAtJD,IAsJC;AAtJY,sCAAa","sourcesContent":["import { trackHtmlVideo, trackEmbeddedVideo } from '../video-analytics/track-video';\nimport type {\n VideoHandler,\n VideoEvent,\n EmbeddedVideoPlayer,\n MuxElement,\n Vendor,\n TimeUpdateEvent,\n VideoStopCause,\n} from '../video-analytics/types';\n\nexport type { Vendor };\n\ntype PlaybackState = 'playing' | 'paused' | 'ended' | 'error' | 'seeking' | 'waiting';\n\nexport type State = {\n playbackState: PlaybackState;\n errorMessage?: string;\n lastEvent?: VideoEvent;\n watchTime?: number;\n position?: number | null;\n isSeeking?: boolean;\n cause?: VideoStopCause; // the reason for the playback state change\n};\n\nexport type VideoObserverParams = {\n videoEl: HTMLMediaElement | EmbeddedVideoPlayer | MuxElement;\n onStateChange: (previousState: State, nextState: State) => void;\n vendor?: Vendor;\n isEmbedded?: boolean;\n};\n\nexport class VideoObserver {\n private state: State = {\n playbackState: 'paused',\n };\n\n private waitingInterval: ReturnType<typeof setTimeout> | null = null;\n private untrack: () => void;\n private onStateChange: (previousState: State, nextState: State) => void;\n private handler: VideoHandler = {\n onPlay: (evt: VideoEvent) => {\n this.updatePlaybackState('playing', evt);\n },\n onPause: (evt: VideoEvent) => {\n this.updatePlaybackState('paused', evt);\n },\n onEnded: (evt: VideoEvent, cause?: VideoStopCause) => {\n this.updatePlaybackState('ended', evt, cause);\n },\n onSeeking: () => {\n const nextState: State = {\n ...this.state,\n isSeeking: true,\n };\n this.updateState(nextState);\n },\n onSeeked: (event: VideoEvent) => {\n const nextState: State = {\n ...this.state,\n isSeeking: false,\n position: event.position,\n };\n this.updateState(nextState);\n },\n onError: (errorMessage: string) => {\n this.updateStateWithError(errorMessage);\n },\n onTimeUpdate: (evt: TimeUpdateEvent) => {\n this.updateTime(evt);\n },\n };\n\n constructor({ videoEl, onStateChange, vendor, isEmbedded }: VideoObserverParams) {\n this.onStateChange = onStateChange;\n if (isEmbedded) {\n this.untrack = trackEmbeddedVideo(videoEl as EmbeddedVideoPlayer, this.handler, vendor);\n } else {\n this.untrack = trackHtmlVideo(videoEl as HTMLMediaElement, this.handler, vendor);\n }\n }\n\n private stateChangeHandler(previousState: State, nextState: State) {\n try {\n this.onStateChange(previousState, nextState);\n } catch (_error) {\n // Swallow callback errors to keep observer state consistent.\n }\n }\n\n private updateStateWithError(error: string) {\n this.clearWaitingInterval();\n const previousState = this.state;\n const nextState: State = {\n ...previousState,\n playbackState: 'error',\n errorMessage: error,\n cause: undefined,\n };\n this.updateState(nextState);\n }\n\n private updatePlaybackState(playbackState: PlaybackState, event: VideoEvent, cause?: VideoStopCause) {\n const previousPlayback = this.state.playbackState;\n // Aborting a load does not emit `seeked`. A seek still open when this media\n // ends, or when the replacement starts, must not stick to the next stream.\n const clearSeeking =\n !!this.state.isSeeking &&\n (playbackState === 'ended' || (playbackState === 'playing' && previousPlayback === 'ended'));\n const nextState: State = {\n ...this.state,\n playbackState,\n errorMessage: undefined,\n lastEvent: event,\n position: event.position,\n cause,\n ...(clearSeeking ? { isSeeking: false } : {}),\n };\n this.updateState(nextState);\n\n this.clearWaitingInterval();\n if (playbackState !== 'playing') {\n return;\n }\n // if it's in a playing state, but the playhead is not moving,\n // then transition playback from 'playing' to 'waiting'\n // (the \"waiting\" listener isn't reliable, so this is a fallback)\n let prevPosition: number | null | undefined = this.state.position;\n this.waitingInterval = setInterval(() => {\n const position = this.state.position;\n if (this.state.playbackState === 'playing' && typeof prevPosition === 'number' && prevPosition === position) {\n // no new player event backs this transition, so carry the current position and metadata over\n this.updateState({ ...this.state, playbackState: 'waiting' });\n }\n prevPosition = position;\n }, 1_000);\n }\n\n private clearWaitingInterval() {\n if (this.waitingInterval) {\n clearInterval(this.waitingInterval);\n this.waitingInterval = null;\n }\n }\n\n private updateTime(event: TimeUpdateEvent) {\n const lastVideoEvent = this.state.lastEvent;\n const isWaiting = this.state.playbackState === 'waiting';\n const isPlaying = this.state.playbackState === 'playing';\n if (!lastVideoEvent || (!isPlaying && !isWaiting)) {\n return;\n }\n const isSeeking = event.isSeeking || this.state.isSeeking;\n const lastPosition = this.state.position ?? 0;\n const nextPosition = event.position;\n if (isSeeking) {\n this.state = {\n ...this.state,\n position: nextPosition,\n };\n return;\n }\n const timeDelta = nextPosition - lastPosition;\n const nextState: State = {\n ...this.state,\n playbackState: 'playing',\n position: nextPosition,\n watchTime: (this.state.watchTime ?? 0) + timeDelta,\n };\n this.updateState(nextState);\n }\n\n private updateState(nextState: State) {\n const previousState = this.state;\n this.state = nextState;\n this.stateChangeHandler(previousState, nextState);\n }\n\n destroy() {\n this.clearWaitingInterval();\n this.untrack();\n }\n}\n"]}
@@ -8,8 +8,10 @@ export declare const PAGE_VIEW_SESSION_STORAGE_KEY = "AMP_PAGE_VIEW";
8
8
  * Returns the page view id for this project and document URL.
9
9
  * Another SDK initialized with the same API key reuses the id for the current
10
10
  * page instead of overwriting the value autocapture later reads.
11
+ * Pass the previous id to renew an engagement view. If another SDK has already
12
+ * renewed it, reuse that new id so the instances stay in sync.
11
13
  */
12
- export declare const getOrCreatePageViewId: (apiKey: string | undefined, href: string) => string | undefined;
14
+ export declare const getOrCreatePageViewId: (apiKey: string | undefined, href: string, previousPageViewId?: string) => string | undefined;
13
15
  /** Reads the current page view id for a project, from memory or session storage. */
14
16
  export declare const getCurrentPageViewId: (apiKey?: string) => string | undefined;
15
17
  /** Drops in-memory page view ids. Session storage is left unchanged. */
@@ -1 +1 @@
1
- {"version":3,"file":"page-view-id.d.ts","sourceRoot":"","sources":["../../src/page-view-id.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,eAAO,MAAM,6BAA6B,kBAAkB,CAAC;AA8E7D;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,WAAY,MAAM,GAAG,SAAS,QAAQ,MAAM,KAAG,MAAM,GAAG,SAiBzF,CAAC;AAeF,oFAAoF;AACpF,eAAO,MAAM,oBAAoB,YAAa,MAAM,KAAG,MAAM,GAAG,SAM/D,CAAC;AAEF,wEAAwE;AACxE,eAAO,MAAM,kBAAkB,QAAO,IAKrC,CAAC"}
1
+ {"version":3,"file":"page-view-id.d.ts","sourceRoot":"","sources":["../../src/page-view-id.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,eAAO,MAAM,6BAA6B,kBAAkB,CAAC;AA8E7D;;;;;;GAMG;AACH,eAAO,MAAM,qBAAqB,WACxB,MAAM,GAAG,SAAS,QACpB,MAAM,uBACS,MAAM,KAC1B,MAAM,GAAG,SAiBX,CAAC;AAeF,oFAAoF;AACpF,eAAO,MAAM,oBAAoB,YAAa,MAAM,KAAG,MAAM,GAAG,SAM/D,CAAC;AAEF,wEAAwE;AACxE,eAAO,MAAM,kBAAkB,QAAO,IAKrC,CAAC"}
@@ -77,8 +77,10 @@ var persistPageViewId = function (scope, apiKey, pageViewId) {
77
77
  * Returns the page view id for this project and document URL.
78
78
  * Another SDK initialized with the same API key reuses the id for the current
79
79
  * page instead of overwriting the value autocapture later reads.
80
+ * Pass the previous id to renew an engagement view. If another SDK has already
81
+ * renewed it, reuse that new id so the instances stay in sync.
80
82
  */
81
- var getOrCreatePageViewId = function (apiKey, href) {
83
+ var getOrCreatePageViewId = function (apiKey, href, previousPageViewId) {
82
84
  var _a;
83
85
  var scope = getScope();
84
86
  if (!scope) {
@@ -87,7 +89,7 @@ var getOrCreatePageViewId = function (apiKey, href) {
87
89
  var key = storageKeyFor(apiKey);
88
90
  var state = (_a = scope[PAGE_VIEW_STATE]) !== null && _a !== void 0 ? _a : { byApiKey: {} };
89
91
  var existing = state.byApiKey[key];
90
- if (existing && existing.href === href) {
92
+ if (existing && existing.href === href && existing.pageViewId !== previousPageViewId) {
91
93
  persistPageViewId(scope, apiKey, existing.pageViewId);
92
94
  return existing.pageViewId;
93
95
  }
@@ -1 +1 @@
1
- {"version":3,"file":"page-view-id.js","sourceRoot":"","sources":["../../src/page-view-id.ts"],"names":[],"mappings":";;;;AAAA,+C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AAE,QAAQ,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,0CAAE,UAAU,CAAC;IAC1E,IAAI,QAAQ,EAAE;QACZ,OAAO,QAAQ,CAAC;KACjB;IACD,OAAO,kBAAkB,CAAC,MAAM,CAAC,CAAC;AACpC,CAAC,CAAC;AANW,QAAA,oBAAoB,wBAM/B;AAEF,wEAAwE;AACjE,IAAM,kBAAkB,GAAG;IAChC,IAAM,KAAK,GAAG,QAAQ,EAAE,CAAC;IACzB,IAAI,KAAK,EAAE;QACT,OAAO,KAAK,CAAC,eAAe,CAAC,CAAC;KAC/B;AACH,CAAC,CAAC;AALW,QAAA,kBAAkB,sBAK7B","sourcesContent":["import { getGlobalScope } from './global-scope';\nimport { UUID } from './utils/uuid';\n\n/**\n * Session storage key shared by page view tracking and autocapture.\n * `pageViewId` is the legacy single-id field. `byApiKey` keeps one id per project\n * so a second SDK cannot replace another project's id.\n */\nexport const PAGE_VIEW_SESSION_STORAGE_KEY = 'AMP_PAGE_VIEW';\n\nconst PAGE_VIEW_STATE = Symbol.for('@amplitude/page-view-state');\n\ninterface PageViewEntry {\n pageViewId: string;\n href: string;\n}\n\ninterface PageViewState {\n byApiKey: Record<string, PageViewEntry>;\n}\n\ninterface StoredPageViews {\n pageViewId?: unknown;\n byApiKey?: unknown;\n}\n\ntype PageViewScope = NonNullable<ReturnType<typeof getGlobalScope>> & Record<symbol, PageViewState | undefined>;\n\nconst storageKeyFor = (apiKey: string | undefined): string => apiKey || '';\n\nconst getScope = (): PageViewScope | undefined => getGlobalScope() as PageViewScope | undefined;\n\nconst readState = (): PageViewState | undefined => getScope()?.[PAGE_VIEW_STATE];\n\nconst readStored = (scope: PageViewScope | undefined = getScope()): StoredPageViews | undefined => {\n try {\n const raw = scope?.sessionStorage?.getItem(PAGE_VIEW_SESSION_STORAGE_KEY);\n if (!raw) {\n return undefined;\n }\n const parsed: unknown = JSON.parse(raw);\n if (!parsed || typeof parsed !== 'object') {\n return undefined;\n }\n return parsed as StoredPageViews;\n } catch {\n return undefined;\n }\n};\n\nconst copyStoredIds = (byApiKey: unknown): Record<string, string> => {\n const ids: Record<string, string> = {};\n if (!byApiKey || typeof byApiKey !== 'object') {\n return ids;\n }\n for (const [key, value] of Object.entries(byApiKey as Record<string, unknown>)) {\n if (typeof value === 'string') {\n ids[key] = value;\n }\n }\n return ids;\n};\n\nconst persistPageViewId = (scope: PageViewScope, apiKey: string | undefined, pageViewId: string): void => {\n try {\n const storage = scope.sessionStorage;\n if (!storage) {\n return;\n }\n const byApiKey = copyStoredIds(readStored(scope)?.byApiKey);\n const key = storageKeyFor(apiKey);\n if (key) {\n byApiKey[key] = pageViewId;\n }\n storage.setItem(\n PAGE_VIEW_SESSION_STORAGE_KEY,\n JSON.stringify({\n pageViewId,\n ...(Object.keys(byApiKey).length > 0 ? { byApiKey } : {}),\n }),\n );\n } catch {\n // sessionStorage can throw in sandboxed documents\n }\n};\n\n/**\n * Returns the page view id for this project and document URL.\n * Another SDK initialized with the same API key reuses the id for the current\n * page instead of overwriting the value autocapture later reads.\n */\nexport const getOrCreatePageViewId = (apiKey: string | undefined, href: string): string | undefined => {\n const scope = getScope();\n if (!scope) {\n return undefined;\n }\n const key = storageKeyFor(apiKey);\n const state = scope[PAGE_VIEW_STATE] ?? { byApiKey: {} };\n const existing = state.byApiKey[key];\n if (existing && existing.href === href) {\n persistPageViewId(scope, apiKey, existing.pageViewId);\n return existing.pageViewId;\n }\n const pageViewId = UUID();\n state.byApiKey[key] = { pageViewId, href };\n scope[PAGE_VIEW_STATE] = state;\n persistPageViewId(scope, apiKey, pageViewId);\n return pageViewId;\n};\n\nconst readScopedStoredId = (apiKey: string | undefined): string | undefined => {\n const stored = readStored();\n if (!stored) {\n return undefined;\n }\n const key = storageKeyFor(apiKey);\n if (key && stored.byApiKey && typeof stored.byApiKey === 'object') {\n const scoped = (stored.byApiKey as Record<string, unknown>)[key];\n return typeof scoped === 'string' ? scoped : undefined;\n }\n return typeof stored.pageViewId === 'string' ? stored.pageViewId : undefined;\n};\n\n/** Reads the current page view id for a project, from memory or session storage. */\nexport const getCurrentPageViewId = (apiKey?: string): string | undefined => {\n const inMemory = readState()?.byApiKey[storageKeyFor(apiKey)]?.pageViewId;\n if (inMemory) {\n return inMemory;\n }\n return readScopedStoredId(apiKey);\n};\n\n/** Drops in-memory page view ids. Session storage is left unchanged. */\nexport const clearPageViewState = (): void => {\n const scope = getScope();\n if (scope) {\n delete scope[PAGE_VIEW_STATE];\n }\n};\n"]}
1
+ {"version":3,"file":"page-view-id.js","sourceRoot":"","sources":["../../src/page-view-id.ts"],"names":[],"mappings":";;;;AAAA,+CAAgD;AAChD,qCAAoC;AAEpC;;;;GAIG;AACU,QAAA,6BAA6B,GAAG,eAAe,CAAC;AAE7D,IAAM,eAAe,GAAG,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;AAkBjE,IAAM,aAAa,GAAG,UAAC,MAA0B,IAAa,OAAA,MAAM,IAAI,EAAE,EAAZ,CAAY,CAAC;AAE3E,IAAM,QAAQ,GAAG,cAAiC,OAAA,IAAA,6BAAc,GAA+B,EAA7C,CAA6C,CAAC;AAEhG,IAAM,SAAS,GAAG,sBAAiC,OAAA,MAAA,QAAQ,EAAE,0CAAG,eAAe,CAAC,CAAA,EAAA,CAAC;AAEjF,IAAM,UAAU,GAAG,UAAC,KAA6C;;IAA7C,sBAAA,EAAA,QAAmC,QAAQ,EAAE;IAC/D,IAAI;QACF,IAAM,GAAG,GAAG,MAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,cAAc,0CAAE,OAAO,CAAC,qCAA6B,CAAC,CAAC;QAC1E,IAAI,CAAC,GAAG,EAAE;YACR,OAAO,SAAS,CAAC;SAClB;QACD,IAAM,MAAM,GAAY,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACxC,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;YACzC,OAAO,SAAS,CAAC;SAClB;QACD,OAA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AO,MAAM,CAAC,QAAQ,KAAK,QAAQ,EAAE;QACjE,IAAM,MAAM,GAAI,MAAM,CAAC,QAAoC,CAAC,GAAG,CAAC,CAAC;QACjE,OAAO,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;KACxD;IACD,OAAO,OAAO,MAAM,CAAC,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC;AAC/E,CAAC,CAAC;AAEF,oFAAoF;AAC7E,IAAM,oBAAoB,GAAG,UAAC,MAAe;;IAClD,IAAM,QAAQ,GAAG,MAAA,MAAA,SAAS,EAAE,0CAAE,QAAQ,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,0CAAE,UAAU,CAAC;IAC1E,IAAI,QAAQ,EAAE;QACZ,OAAO,QAAQ,CAAC;KACjB;IACD,OAAO,kBAAkB,CAAC,MAAM,CAAC,CAAC;AACpC,CAAC,CAAC;AANW,QAAA,oBAAoB,wBAM/B;AAEF,wEAAwE;AACjE,IAAM,kBAAkB,GAAG;IAChC,IAAM,KAAK,GAAG,QAAQ,EAAE,CAAC;IACzB,IAAI,KAAK,EAAE;QACT,OAAO,KAAK,CAAC,eAAe,CAAC,CAAC;KAC/B;AACH,CAAC,CAAC;AALW,QAAA,kBAAkB,sBAK7B","sourcesContent":["import { getGlobalScope } from './global-scope';\nimport { UUID } from './utils/uuid';\n\n/**\n * Session storage key shared by page view tracking and autocapture.\n * `pageViewId` is the legacy single-id field. `byApiKey` keeps one id per project\n * so a second SDK cannot replace another project's id.\n */\nexport const PAGE_VIEW_SESSION_STORAGE_KEY = 'AMP_PAGE_VIEW';\n\nconst PAGE_VIEW_STATE = Symbol.for('@amplitude/page-view-state');\n\ninterface PageViewEntry {\n pageViewId: string;\n href: string;\n}\n\ninterface PageViewState {\n byApiKey: Record<string, PageViewEntry>;\n}\n\ninterface StoredPageViews {\n pageViewId?: unknown;\n byApiKey?: unknown;\n}\n\ntype PageViewScope = NonNullable<ReturnType<typeof getGlobalScope>> & Record<symbol, PageViewState | undefined>;\n\nconst storageKeyFor = (apiKey: string | undefined): string => apiKey || '';\n\nconst getScope = (): PageViewScope | undefined => getGlobalScope() as PageViewScope | undefined;\n\nconst readState = (): PageViewState | undefined => getScope()?.[PAGE_VIEW_STATE];\n\nconst readStored = (scope: PageViewScope | undefined = getScope()): StoredPageViews | undefined => {\n try {\n const raw = scope?.sessionStorage?.getItem(PAGE_VIEW_SESSION_STORAGE_KEY);\n if (!raw) {\n return undefined;\n }\n const parsed: unknown = JSON.parse(raw);\n if (!parsed || typeof parsed !== 'object') {\n return undefined;\n }\n return parsed as StoredPageViews;\n } catch {\n return undefined;\n }\n};\n\nconst copyStoredIds = (byApiKey: unknown): Record<string, string> => {\n const ids: Record<string, string> = {};\n if (!byApiKey || typeof byApiKey !== 'object') {\n return ids;\n }\n for (const [key, value] of Object.entries(byApiKey as Record<string, unknown>)) {\n if (typeof value === 'string') {\n ids[key] = value;\n }\n }\n return ids;\n};\n\nconst persistPageViewId = (scope: PageViewScope, apiKey: string | undefined, pageViewId: string): void => {\n try {\n const storage = scope.sessionStorage;\n if (!storage) {\n return;\n }\n const byApiKey = copyStoredIds(readStored(scope)?.byApiKey);\n const key = storageKeyFor(apiKey);\n if (key) {\n byApiKey[key] = pageViewId;\n }\n storage.setItem(\n PAGE_VIEW_SESSION_STORAGE_KEY,\n JSON.stringify({\n pageViewId,\n ...(Object.keys(byApiKey).length > 0 ? { byApiKey } : {}),\n }),\n );\n } catch {\n // sessionStorage can throw in sandboxed documents\n }\n};\n\n/**\n * Returns the page view id for this project and document URL.\n * Another SDK initialized with the same API key reuses the id for the current\n * page instead of overwriting the value autocapture later reads.\n * Pass the previous id to renew an engagement view. If another SDK has already\n * renewed it, reuse that new id so the instances stay in sync.\n */\nexport const getOrCreatePageViewId = (\n apiKey: string | undefined,\n href: string,\n previousPageViewId?: string,\n): string | undefined => {\n const scope = getScope();\n if (!scope) {\n return undefined;\n }\n const key = storageKeyFor(apiKey);\n const state = scope[PAGE_VIEW_STATE] ?? { byApiKey: {} };\n const existing = state.byApiKey[key];\n if (existing && existing.href === href && existing.pageViewId !== previousPageViewId) {\n persistPageViewId(scope, apiKey, existing.pageViewId);\n return existing.pageViewId;\n }\n const pageViewId = UUID();\n state.byApiKey[key] = { pageViewId, href };\n scope[PAGE_VIEW_STATE] = state;\n persistPageViewId(scope, apiKey, pageViewId);\n return pageViewId;\n};\n\nconst readScopedStoredId = (apiKey: string | undefined): string | undefined => {\n const stored = readStored();\n if (!stored) {\n return undefined;\n }\n const key = storageKeyFor(apiKey);\n if (key && stored.byApiKey && typeof stored.byApiKey === 'object') {\n const scoped = (stored.byApiKey as Record<string, unknown>)[key];\n return typeof scoped === 'string' ? scoped : undefined;\n }\n return typeof stored.pageViewId === 'string' ? stored.pageViewId : undefined;\n};\n\n/** Reads the current page view id for a project, from memory or session storage. */\nexport const getCurrentPageViewId = (apiKey?: string): string | undefined => {\n const inMemory = readState()?.byApiKey[storageKeyFor(apiKey)]?.pageViewId;\n if (inMemory) {\n return inMemory;\n }\n return readScopedStoredId(apiKey);\n};\n\n/** Drops in-memory page view ids. Session storage is left unchanged. */\nexport const clearPageViewState = (): void => {\n const scope = getScope();\n if (scope) {\n delete scope[PAGE_VIEW_STATE];\n }\n};\n"]}
@@ -1,16 +1,20 @@
1
1
  import { DestinationPlugin } from '../types/plugin';
2
2
  import { Event } from '../types/event/event';
3
+ import { Delay } from '../types/event/base-event';
3
4
  import { Result } from '../types/result';
4
5
  import { Response, InvalidResponse, PayloadTooLargeResponse, RateLimitResponse, SuccessResponse } from '../types/response';
5
6
  import { IConfig } from '../types/config/core-config';
6
7
  import { EventCallback } from '../types/event-callback';
7
8
  import { IDiagnosticsClient } from '../diagnostics/diagnostics-client';
9
+ import { DelayedPayload, Payload } from '../types/payload';
8
10
  export interface Context {
9
11
  event: Event;
10
12
  attempts: number;
11
13
  callback: EventCallback;
12
14
  timeout: number;
15
+ delay?: Delay;
13
16
  }
17
+ type DelayedEventsById = Record<string, Context[]>;
14
18
  export declare function getResponseBodyString(res: Response): string;
15
19
  export declare class Destination implements DestinationPlugin {
16
20
  name: string;
@@ -24,17 +28,32 @@ export declare class Destination implements DestinationPlugin {
24
28
  flushId: ReturnType<typeof setTimeout> | null;
25
29
  queue: Context[];
26
30
  diagnosticsClient: IDiagnosticsClient | undefined;
31
+ inFlightDelayedEvents: Record<string, boolean>;
27
32
  constructor(context?: {
28
33
  diagnosticsClient: IDiagnosticsClient;
29
34
  });
30
35
  setup(config: IConfig): Promise<undefined>;
31
36
  execute(event: Event): Promise<Result>;
37
+ /**
38
+ * If a stale delayed event is sitting in the queue, and it is not in flight,
39
+ * remove it and resolve as "stale" with status code 0.
40
+ *
41
+ * If a matching delayed event is already in flight, clone `delay` onto the
42
+ * incoming event and set skipRemoval so the in-flight send does not drop the
43
+ * replacement. Earlier replacements waiting on the same send are discarded
44
+ * as stale so only the latest copy remains.
45
+ * @param incomingEvent { Event } the new event to check old events against
46
+ * @returns void
47
+ */
48
+ private removeStaleDelayedEvents;
32
49
  removeEventsExceedFlushMaxRetries(list: Context[]): Context[];
33
50
  scheduleEvents(list: Context[]): void;
34
51
  schedule(timeout: number): void;
35
52
  resetSchedule(): void;
36
53
  flush(useRetry?: boolean): Promise<void>;
37
- send(list: Context[], useRetry?: boolean): Promise<void>;
54
+ sendDelayedEvents(delayed: DelayedEventsById, useRetry: boolean): Promise<void>;
55
+ translatePayloadToDelayedPayload(payload: Payload & Partial<DelayedPayload>, list: Context[]): void;
56
+ send(list: Context[], useRetry?: boolean, delay?: boolean): Promise<void>;
38
57
  handleResponse(res: Response, list: Context[]): void;
39
58
  handleSuccessResponse(res: SuccessResponse, list: Context[]): void;
40
59
  handleInvalidResponse(res: InvalidResponse, list: Context[]): void;
@@ -55,4 +74,5 @@ export declare class Destination implements DestinationPlugin {
55
74
  */
56
75
  removeEvents(eventsToRemove: Context[]): void;
57
76
  }
77
+ export {};
58
78
  //# sourceMappingURL=destination.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"destination.d.ts","sourceRoot":"","sources":["../../../src/plugins/destination.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAC7C,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAEzC,OAAO,EACL,QAAQ,EACR,eAAe,EACf,uBAAuB,EACvB,iBAAiB,EACjB,eAAe,EAChB,MAAM,mBAAmB,CAAC;AAmB3B,OAAO,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,EAAE,kBAAkB,EAAE,MAAM,mCAAmC,CAAC;AAIvE,MAAM,WAAW,OAAO;IACtB,KAAK,EAAE,KAAK,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,aAAa,CAAC;IACxB,OAAO,EAAE,MAAM,CAAC;CACjB;AAsBD,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,QAAQ,UAUlD;AAED,qBAAa,WAAY,YAAW,iBAAiB;IACnD,IAAI,SAAe;IACnB,IAAI,gBAA0B;IAE9B,YAAY,SAAQ;IACpB,eAAe,SAAS;IACxB,UAAU,SAAM;IAIhB,MAAM,EAAE,OAAO,CAAC;IAKhB,UAAU,EAAE,UAAU,CAAC,OAAO,UAAU,CAAC,GAAG,IAAI,CAAQ;IAExD,gBAAgB,SAAK;IAGrB,OAAO,EAAE,UAAU,CAAC,OAAO,UAAU,CAAC,GAAG,IAAI,CAAQ;IACrD,KAAK,EAAE,OAAO,EAAE,CAAM;IACtB,iBAAiB,EAAE,kBAAkB,GAAG,SAAS,CAAC;gBAEtC,OAAO,CAAC,EAAE;QAAE,iBAAiB,EAAE,kBAAkB,CAAA;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30
  return String(error);
31
31
  }
32
+ function isDelayedEvent(event) {
33
+ return event.delay !== undefined && event.delay !== null;
34
+ }
32
35
  function getResponseBodyString(res) {
33
36
  var responseBodyString = '';
34
37
  try {
@@ -60,6 +63,7 @@ var Destination = /** @class */ (function () {
60
63
  // When flush resolves, set `flushId` to null
61
64
  this.flushId = null;
62
65
  this.queue = [];
66
+ this.inFlightDelayedEvents = {};
63
67
  this.diagnosticsClient = context === null || context === void 0 ? void 0 : context.diagnosticsClient;
64
68
  }
65
69
  Destination.prototype.setup = function (config) {
@@ -85,6 +89,10 @@ var Destination = /** @class */ (function () {
85
89
  };
86
90
  Destination.prototype.execute = function (event) {
87
91
  var _this = this;
92
+ // Repeated delayed events must not replay stale user-property updates.
93
+ // This also strips properties added by enrichment plugins.
94
+ if (event.delay)
95
+ delete event.user_properties;
88
96
  // Assign insert_id for dropping invalid event later
89
97
  if (!event.insert_id) {
90
98
  event.insert_id = (0, uuid_1.UUID)();
@@ -96,11 +104,63 @@ var Destination = /** @class */ (function () {
96
104
  callback: function (result) { return resolve(result); },
97
105
  timeout: 0,
98
106
  };
107
+ if (isDelayedEvent(event)) {
108
+ _this.removeStaleDelayedEvents(event);
109
+ }
99
110
  _this.queue.push(context);
100
111
  _this.schedule(_this.config.flushIntervalMillis);
101
112
  _this.saveEvents();
102
113
  });
103
114
  };
115
+ /**
116
+ * If a stale delayed event is sitting in the queue, and it is not in flight,
117
+ * remove it and resolve as "stale" with status code 0.
118
+ *
119
+ * If a matching delayed event is already in flight, clone `delay` onto the
120
+ * incoming event and set skipRemoval so the in-flight send does not drop the
121
+ * replacement. Earlier replacements waiting on the same send are discarded
122
+ * as stale so only the latest copy remains.
123
+ * @param incomingEvent { Event } the new event to check old events against
124
+ * @returns void
125
+ */
126
+ Destination.prototype.removeStaleDelayedEvents = function (incomingEvent) {
127
+ var _this = this;
128
+ try {
129
+ /* istanbul ignore next */
130
+ this.queue = this.queue.filter(function (context) {
131
+ var _a;
132
+ var targetEvent = context.event;
133
+ if (!isDelayedEvent(targetEvent)) {
134
+ return true;
135
+ }
136
+ // target event matches the incoming event if it has the same insert_id and delay id
137
+ // as the incoming event (the incoming event takes precedence)
138
+ var isMatchingEvent = targetEvent.delay.id === incomingEvent.delay.id && targetEvent.insert_id === incomingEvent.insert_id;
139
+ // do not filter out non matching events
140
+ if (!isMatchingEvent) {
141
+ return true;
142
+ }
143
+ // are there delayed events for this delay id currently in flight?
144
+ var areDelayedEventsInFlight = _this.inFlightDelayedEvents[incomingEvent.delay.id];
145
+ // if they are, then protect the target event from being removed from the queue
146
+ // after the in-flight send completes by setting skipRemoval on the incoming event
147
+ if (areDelayedEventsInFlight) {
148
+ incomingEvent.delay = tslib_1.__assign(tslib_1.__assign({}, incomingEvent.delay), { skipRemoval: true });
149
+ }
150
+ // if events are not in flight, or if the target event is marked to skipRemoval,
151
+ // then the incoming event supersedes the target event, and target event should be dropped
152
+ if (!areDelayedEventsInFlight || ((_a = targetEvent.delay) === null || _a === void 0 ? void 0 : _a.skipRemoval)) {
153
+ context.callback((0, result_builder_1.buildResult)(targetEvent, 0, 'Stale event overwritten'));
154
+ return false;
155
+ }
156
+ return true;
157
+ });
158
+ /* istanbul ignore next */
159
+ }
160
+ catch (e) {
161
+ // swallow error
162
+ }
163
+ };
104
164
  Destination.prototype.removeEventsExceedFlushMaxRetries = function (list) {
105
165
  var _this = this;
106
166
  return list.filter(function (context) {
@@ -151,7 +211,7 @@ var Destination = /** @class */ (function () {
151
211
  Destination.prototype.flush = function (useRetry) {
152
212
  if (useRetry === void 0) { useRetry = false; }
153
213
  return tslib_1.__awaiter(this, void 0, void 0, function () {
154
- var list, later, batches;
214
+ var list, delayed, later, batches, regularEventBatch, eventPromises;
155
215
  var _this = this;
156
216
  return tslib_1.__generator(this, function (_a) {
157
217
  switch (_a.label) {
@@ -170,25 +230,40 @@ var Destination = /** @class */ (function () {
170
230
  this.flushId = this.scheduleId;
171
231
  this.resetSchedule();
172
232
  list = [];
233
+ delayed = {};
173
234
  later = [];
174
- this.queue.forEach(function (context) { return (context.timeout === 0 ? list.push(context) : later.push(context)); });
235
+ this.queue.forEach(function (context) {
236
+ var _a;
237
+ if (context.timeout !== 0) {
238
+ later.push(context);
239
+ }
240
+ else if ((_a = context.event.delay) === null || _a === void 0 ? void 0 : _a.id) {
241
+ var delay = context.event.delay;
242
+ delayed[delay.id] = delayed[delay.id] || [];
243
+ delayed[delay.id].push(context);
244
+ }
245
+ else {
246
+ list.push(context);
247
+ }
248
+ });
175
249
  batches = (0, chunk_1.chunk)(list, this.config.flushQueueSize);
176
- // Promise.all() doesn't guarantee resolve order.
177
- // Sequentially resolve to make sure backend receives events in order
178
- return [4 /*yield*/, batches.reduce(function (promise, batch) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
179
- return tslib_1.__generator(this, function (_a) {
180
- switch (_a.label) {
181
- case 0: return [4 /*yield*/, promise];
182
- case 1:
183
- _a.sent();
184
- return [4 /*yield*/, this.send(batch, useRetry)];
185
- case 2: return [2 /*return*/, _a.sent()];
186
- }
187
- });
188
- }); }, Promise.resolve())];
250
+ regularEventBatch = batches.reduce(function (promise, batch) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
251
+ return tslib_1.__generator(this, function (_a) {
252
+ switch (_a.label) {
253
+ case 0: return [4 /*yield*/, promise];
254
+ case 1:
255
+ _a.sent();
256
+ return [4 /*yield*/, this.send(batch, useRetry)];
257
+ case 2: return [2 /*return*/, _a.sent()];
258
+ }
259
+ });
260
+ }); }, Promise.resolve());
261
+ eventPromises = [regularEventBatch];
262
+ if (Object.keys(delayed).length > 0) {
263
+ eventPromises.push(this.sendDelayedEvents(delayed, useRetry));
264
+ }
265
+ return [4 /*yield*/, Promise.all(eventPromises)];
189
266
  case 1:
190
- // Promise.all() doesn't guarantee resolve order.
191
- // Sequentially resolve to make sure backend receives events in order
192
267
  _a.sent();
193
268
  // Mark current flush is done
194
269
  this.flushId = null;
@@ -198,11 +273,77 @@ var Destination = /** @class */ (function () {
198
273
  });
199
274
  });
200
275
  };
201
- Destination.prototype.send = function (list, useRetry) {
276
+ Destination.prototype.sendDelayedEvents = function (delayed, useRetry) {
277
+ var e_1, _a;
278
+ var _this = this;
279
+ var eventPromises = [];
280
+ try {
281
+ var _loop_1 = function (delayId, contexts) {
282
+ this_1.inFlightDelayedEvents[delayId] = true;
283
+ var delayedEventsSend = this_1.send(contexts, useRetry, true);
284
+ eventPromises.push(delayedEventsSend);
285
+ delayedEventsSend.finally(function () {
286
+ delete _this.inFlightDelayedEvents[delayId];
287
+ });
288
+ };
289
+ var this_1 = this;
290
+ try {
291
+ for (var _b = tslib_1.__values(Object.entries(delayed)), _c = _b.next(); !_c.done; _c = _b.next()) {
292
+ var _d = tslib_1.__read(_c.value, 2), delayId = _d[0], contexts = _d[1];
293
+ _loop_1(delayId, contexts);
294
+ }
295
+ }
296
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
297
+ finally {
298
+ try {
299
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
300
+ }
301
+ finally { if (e_1) throw e_1.error; }
302
+ }
303
+ }
304
+ catch (e) {
305
+ // swallow error
306
+ }
307
+ return eventPromises.reduce(function (promise, batch) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
308
+ return tslib_1.__generator(this, function (_a) {
309
+ switch (_a.label) {
310
+ case 0: return [4 /*yield*/, promise];
311
+ case 1:
312
+ _a.sent();
313
+ return [4 /*yield*/, batch];
314
+ case 2: return [2 /*return*/, _a.sent()];
315
+ }
316
+ });
317
+ }); }, Promise.resolve());
318
+ };
319
+ Destination.prototype.translatePayloadToDelayedPayload = function (payload, list) {
320
+ var _a, _b;
321
+ var delayedEvents = [];
322
+ var instantEvents = [];
323
+ var delayedContexts = [];
324
+ var instantContexts = [];
325
+ list.forEach(function (context, index) {
326
+ if (context.event.delay.timeout) {
327
+ delayedEvents.push(payload.events[index]);
328
+ delayedContexts.push(context);
329
+ }
330
+ else {
331
+ instantEvents.push(payload.events[index]);
332
+ instantContexts.push(context);
333
+ }
334
+ });
335
+ list.splice.apply(list, tslib_1.__spreadArray(tslib_1.__spreadArray([0, list.length], tslib_1.__read(delayedContexts), false), tslib_1.__read(instantContexts), false));
336
+ /* istanbul ignore next */
337
+ payload.timeout = (_b = (_a = delayedContexts[0]) === null || _a === void 0 ? void 0 : _a.event.delay.timeout) !== null && _b !== void 0 ? _b : 0;
338
+ payload.id = list[0].event.delay.id;
339
+ payload.events = delayedEvents;
340
+ payload.instant_events = instantEvents;
341
+ };
342
+ Destination.prototype.send = function (list, useRetry, delay) {
202
343
  var _a;
203
344
  if (useRetry === void 0) { useRetry = true; }
204
345
  return tslib_1.__awaiter(this, void 0, void 0, function () {
205
- var payload, serverUrl, shouldCompressUploadBody, res, e_1, errorMessage;
346
+ var payload, serverUrl, shouldCompressUploadBody, res, e_2, errorMessage;
206
347
  return tslib_1.__generator(this, function (_b) {
207
348
  switch (_b.label) {
208
349
  case 0:
@@ -213,21 +354,28 @@ var Destination = /** @class */ (function () {
213
354
  api_key: this.config.apiKey,
214
355
  events: list.map(function (context) {
215
356
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
216
- var _a = context.event, extra = _a.extra, eventWithoutExtra = tslib_1.__rest(_a, ["extra"]);
357
+ var _a = context.event, extra = _a.extra, delay = _a.delay, eventWithoutExtra = tslib_1.__rest(_a, ["extra", "delay"]);
217
358
  return eventWithoutExtra;
218
359
  }),
219
360
  options: {
220
361
  min_id_length: this.config.minIdLength,
221
362
  },
222
363
  client_upload_time: new Date().toISOString(),
223
- request_metadata: this.config.requestMetadata,
364
+ request_metadata: delay ? undefined : this.config.requestMetadata,
224
365
  };
225
- this.config.requestMetadata = new config_1.RequestMetadata();
366
+ if (!delay) {
367
+ this.config.requestMetadata = new config_1.RequestMetadata();
368
+ }
226
369
  _b.label = 1;
227
370
  case 1:
228
371
  _b.trys.push([1, 3, , 4]);
229
372
  serverUrl = (0, config_1.createServerConfig)(this.config.serverUrl, this.config.serverZone, this.config.useBatch).serverUrl;
230
373
  shouldCompressUploadBody = shouldCompressUploadBodyForRequest(serverUrl, this.config.enableRequestBodyCompression);
374
+ if (delay) {
375
+ serverUrl = this.config.delayedEventsServerUrl || "".concat(serverUrl, "/delayed");
376
+ this.translatePayloadToDelayedPayload(payload, list);
377
+ shouldCompressUploadBody = false; // delayed events doesn't support compression
378
+ }
231
379
  return [4 /*yield*/, this.config.transportProvider.send(serverUrl, payload, shouldCompressUploadBody)];
232
380
  case 2:
233
381
  res = _b.sent();
@@ -247,8 +395,8 @@ var Destination = /** @class */ (function () {
247
395
  this.handleResponse(res, list);
248
396
  return [3 /*break*/, 4];
249
397
  case 3:
250
- e_1 = _b.sent();
251
- errorMessage = getErrorMessage(e_1);
398
+ e_2 = _b.sent();
399
+ errorMessage = getErrorMessage(e_2);
252
400
  this.config.loggerProvider.error(errorMessage);
253
401
  (_a = this.diagnosticsClient) === null || _a === void 0 ? void 0 : _a.recordEvent('analytics.events.unsuccessful.from.catch.error', {
254
402
  events: list.map(function (context) { return context.event.event_type; }),
@@ -406,9 +554,16 @@ var Destination = /** @class */ (function () {
406
554
  * This is called on response comes back for a request
407
555
  */
408
556
  Destination.prototype.removeEvents = function (eventsToRemove) {
557
+ var insertIdsBeingRemoved = new Set(eventsToRemove.map(function (context) { return context.event.insert_id; }));
409
558
  // Remove only the exact fulfilled Context instances so duplicate insert_id events remain queued.
410
559
  var toRemove = new Set(eventsToRemove);
411
- this.queue = this.queue.filter(function (queuedContext) { return !toRemove.has(queuedContext); });
560
+ this.queue = this.queue.filter(function (queuedContext) { var _a; return !toRemove.has(queuedContext) || ((_a = queuedContext.event.delay) === null || _a === void 0 ? void 0 : _a.skipRemoval); });
561
+ this.queue.forEach(function (context) {
562
+ var _a;
563
+ if (((_a = context.event.delay) === null || _a === void 0 ? void 0 : _a.skipRemoval) && insertIdsBeingRemoved.has(context.event.insert_id)) {
564
+ delete context.event.delay.skipRemoval;
565
+ }
566
+ });
412
567
  this.saveEvents();
413
568
  };
414
569
  return Destination;