@amplitude/analytics-core 2.56.0 → 2.57.0-video-analytics-4.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 (57) 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/observers/video.d.ts +4 -2
  6. package/lib/cjs/observers/video.d.ts.map +1 -1
  7. package/lib/cjs/observers/video.js +31 -3
  8. package/lib/cjs/observers/video.js.map +1 -1
  9. package/lib/cjs/plugins/destination.d.ts +21 -1
  10. package/lib/cjs/plugins/destination.d.ts.map +1 -1
  11. package/lib/cjs/plugins/destination.js +178 -25
  12. package/lib/cjs/plugins/destination.js.map +1 -1
  13. package/lib/cjs/types/config/core-config.d.ts +5 -0
  14. package/lib/cjs/types/config/core-config.d.ts.map +1 -1
  15. package/lib/cjs/types/config/core-config.js.map +1 -1
  16. package/lib/cjs/types/event/base-event.d.ts +1 -0
  17. package/lib/cjs/types/event/base-event.d.ts.map +1 -1
  18. package/lib/cjs/types/event/base-event.js.map +1 -1
  19. package/lib/cjs/types/event/event.d.ts +4 -1
  20. package/lib/cjs/types/event/event.d.ts.map +1 -1
  21. package/lib/cjs/types/event/event.js.map +1 -1
  22. package/lib/cjs/types/payload.d.ts +5 -0
  23. package/lib/cjs/types/payload.d.ts.map +1 -1
  24. package/lib/cjs/types/payload.js.map +1 -1
  25. package/lib/cjs/video-analytics/track-video.d.ts +1 -1
  26. package/lib/cjs/video-analytics/track-video.d.ts.map +1 -1
  27. package/lib/cjs/video-analytics/track-video.js +40 -17
  28. package/lib/cjs/video-analytics/track-video.js.map +1 -1
  29. package/lib/esm/config.d.ts +1 -0
  30. package/lib/esm/config.d.ts.map +1 -1
  31. package/lib/esm/config.js +1 -0
  32. package/lib/esm/config.js.map +1 -1
  33. package/lib/esm/observers/video.d.ts +4 -2
  34. package/lib/esm/observers/video.d.ts.map +1 -1
  35. package/lib/esm/observers/video.js +31 -3
  36. package/lib/esm/observers/video.js.map +1 -1
  37. package/lib/esm/plugins/destination.d.ts +21 -1
  38. package/lib/esm/plugins/destination.d.ts.map +1 -1
  39. package/lib/esm/plugins/destination.js +179 -26
  40. package/lib/esm/plugins/destination.js.map +1 -1
  41. package/lib/esm/types/config/core-config.d.ts +5 -0
  42. package/lib/esm/types/config/core-config.d.ts.map +1 -1
  43. package/lib/esm/types/config/core-config.js.map +1 -1
  44. package/lib/esm/types/event/base-event.d.ts +1 -0
  45. package/lib/esm/types/event/base-event.d.ts.map +1 -1
  46. package/lib/esm/types/event/base-event.js.map +1 -1
  47. package/lib/esm/types/event/event.d.ts +4 -1
  48. package/lib/esm/types/event/event.d.ts.map +1 -1
  49. package/lib/esm/types/event/event.js.map +1 -1
  50. package/lib/esm/types/payload.d.ts +5 -0
  51. package/lib/esm/types/payload.d.ts.map +1 -1
  52. package/lib/esm/types/payload.js.map +1 -1
  53. package/lib/esm/video-analytics/track-video.d.ts +1 -1
  54. package/lib/esm/video-analytics/track-video.d.ts.map +1 -1
  55. package/lib/esm/video-analytics/track-video.js +40 -17
  56. package/lib/esm/video-analytics/track-video.js.map +1 -1
  57. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  import type { VideoEvent, EmbeddedVideoPlayer, MuxElement, Vendor } from '../video-analytics/types';
2
2
  export type { Vendor };
3
- type PlaybackState = 'playing' | 'paused' | 'ended' | 'error' | 'seeking';
3
+ type PlaybackState = 'playing' | 'paused' | 'ended' | 'error' | 'seeking' | 'waiting';
4
4
  export type State = {
5
5
  playbackState: PlaybackState;
6
6
  errorMessage?: string;
@@ -10,13 +10,14 @@ export type State = {
10
10
  isSeeking?: boolean;
11
11
  };
12
12
  export type VideoObserverParams = {
13
- videoEl: HTMLVideoElement | EmbeddedVideoPlayer | MuxElement;
13
+ videoEl: HTMLMediaElement | EmbeddedVideoPlayer | MuxElement;
14
14
  onStateChange: (previousState: State, nextState: State) => void;
15
15
  vendor?: Vendor;
16
16
  isEmbedded?: boolean;
17
17
  };
18
18
  export declare class VideoObserver {
19
19
  private state;
20
+ private waitingInterval;
20
21
  private untrack;
21
22
  private onStateChange;
22
23
  private handler;
@@ -24,6 +25,7 @@ export declare class VideoObserver {
24
25
  private stateChangeHandler;
25
26
  private updateStateWithError;
26
27
  private updatePlaybackState;
28
+ private clearWaitingInterval;
27
29
  private updateTime;
28
30
  private updateState;
29
31
  destroy(): void;
@@ -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;IACnB,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB,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,OAAO,CAAa;IAC5B,OAAO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AAO,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;IAW5B,OAAO,CAAC,mBAAmB;IA4B3B,OAAO,CAAC,oBAAoB;IAO5B,OAAO,CAAC,UAAU;IA2BlB,OAAO,CAAC,WAAW;IAMnB,OAAO;CAIR"}
@@ -7,6 +7,7 @@ var VideoObserver = /** @class */ (function () {
7
7
  this.state = {
8
8
  playbackState: 'paused',
9
9
  };
10
+ this.waitingInterval = null;
10
11
  this.handler = {
11
12
  onPlay: function (evt) {
12
13
  _this.updatePlaybackState('playing', evt);
@@ -49,18 +50,44 @@ var VideoObserver = /** @class */ (function () {
49
50
  }
50
51
  };
51
52
  VideoObserver.prototype.updateStateWithError = function (error) {
53
+ this.clearWaitingInterval();
52
54
  var previousState = this.state;
53
55
  var nextState = __assign(__assign({}, previousState), { playbackState: 'error', errorMessage: error });
54
56
  this.updateState(nextState);
55
57
  };
56
58
  VideoObserver.prototype.updatePlaybackState = function (playbackState, event) {
57
- var nextState = __assign(__assign({}, this.state), { playbackState: playbackState, lastEvent: event, position: event.last_position });
59
+ var _this = this;
60
+ var nextState = __assign(__assign({}, this.state), { playbackState: playbackState, errorMessage: undefined, lastEvent: event, position: event.last_position });
58
61
  this.updateState(nextState);
62
+ this.clearWaitingInterval();
63
+ if (playbackState !== 'playing') {
64
+ return;
65
+ }
66
+ // if it's in a playing state, but the playhead is not moving,
67
+ // then transition playback from 'playing' to 'waiting'
68
+ // (the "waiting" listener isn't reliable, so this is a fallback)
69
+ var prevPosition = this.state.position;
70
+ this.waitingInterval = setInterval(function () {
71
+ var position = _this.state.position;
72
+ if (_this.state.playbackState === 'playing' && typeof prevPosition === 'number' && prevPosition === position) {
73
+ // no new player event backs this transition, so carry the current position and metadata over
74
+ _this.updateState(__assign(__assign({}, _this.state), { playbackState: 'waiting' }));
75
+ }
76
+ prevPosition = position;
77
+ }, 1000);
78
+ };
79
+ VideoObserver.prototype.clearWaitingInterval = function () {
80
+ if (this.waitingInterval) {
81
+ clearInterval(this.waitingInterval);
82
+ this.waitingInterval = null;
83
+ }
59
84
  };
60
85
  VideoObserver.prototype.updateTime = function (event) {
61
86
  var _a, _b;
62
87
  var lastVideoEvent = this.state.lastEvent;
63
- if (!lastVideoEvent || this.state.playbackState !== 'playing') {
88
+ var isWaiting = this.state.playbackState === 'waiting';
89
+ var isPlaying = this.state.playbackState === 'playing';
90
+ if (!lastVideoEvent || (!isPlaying && !isWaiting)) {
64
91
  return;
65
92
  }
66
93
  var isSeeking = event.isSeeking || this.state.isSeeking;
@@ -71,7 +98,7 @@ var VideoObserver = /** @class */ (function () {
71
98
  return;
72
99
  }
73
100
  var timeDelta = nextPosition - lastPosition;
74
- var nextState = __assign(__assign({}, this.state), { position: nextPosition, watchTime: ((_b = this.state.watchTime) !== null && _b !== void 0 ? _b : 0) + timeDelta });
101
+ var nextState = __assign(__assign({}, this.state), { playbackState: 'playing', position: nextPosition, watchTime: ((_b = this.state.watchTime) !== null && _b !== void 0 ? _b : 0) + timeDelta });
75
102
  this.updateState(nextState);
76
103
  };
77
104
  VideoObserver.prototype.updateState = function (nextState) {
@@ -80,6 +107,7 @@ var VideoObserver = /** @class */ (function () {
80
107
  this.stateChangeHandler(previousState, nextState);
81
108
  };
82
109
  VideoObserver.prototype.destroy = function () {
110
+ this.clearWaitingInterval();
83
111
  this.untrack();
84
112
  };
85
113
  return VideoObserver;
@@ -1 +1 @@
1
- {"version":3,"file":"video.js","sourceRoot":"","sources":["../../../src/observers/video.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AA8BpF;IAwCE,uBAAY,EAAmE;YAAjE,OAAO,aAAA,EAAE,aAAa,mBAAA,EAAE,MAAM,YAAA,EAAE,UAA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;QACD,IAAM,SAAS,GAAG,YAAY,GAAG,YAAY,CAAC;QAC9C,IAAM,SAAS,yBACV,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","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,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AA8BpF;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;gBACvB,KAAI,CAAC,mBAAmB,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;YACzC,CAAC;YACD,SAAS,EAAE;gBACT,IAAM,SAAS,yBACV,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,yBACV,KAAI,CAAC,KAAK,KACb,SAAS,EAAE,KAAK,EAChB,QAAQ,EAAE,KAAK,CAAC,aAAa,GAC9B,CAAC;gBACF,KAAI,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC;YAC9B,CAAC;YACD,OAAO,EAAE,UAAC,YAAoB;gBAC5B,KAAI,CAAC,oBAAoB,CAAC,YAAY,CAAC,CAAC;YAC1C,CAAC;YACD,YAAY,EAAE,U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I,CAAC,KAAK,yBACL,IAAI,CAAC,KAAK,KACb,QAAQ,EAAE,YAAY,GACvB,CAAC;YACF,OAAO;SACR;QACD,IAAM,SAAS,GAAG,YAAY,GAAG,YAAY,CAAC;QAC9C,IAAM,SAAS,yBACV,IAAI,CAAC,KAAK,KACb,aAAa,EAAE,SAAS,EACxB,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,oBAAoB,EAAE,CAAC;QAC5B,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;IACH,oBAAC;AAAD,CAAC,AA7ID,IA6IC","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' | '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};\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) => {\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 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 };\n this.updateState(nextState);\n }\n\n private updatePlaybackState(playbackState: PlaybackState, event: VideoEvent) {\n const nextState: State = {\n ...this.state,\n playbackState,\n errorMessage: undefined,\n lastEvent: event,\n position: event.last_position,\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"]}
@@ -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.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"tslib";
2
2
  import { Status } from '../types/status';
3
3
  import { INVALID_API_KEY, MAX_RETRIES_EXCEEDED_MESSAGE, MISSING_API_KEY_MESSAGE, SUCCESS_MESSAGE, UNEXPECTED_ERROR_MESSAGE, } from '../types/messages';
4
4
  import { AMPLITUDE_BATCH_SERVER_URL, AMPLITUDE_SERVER_URL, EU_AMPLITUDE_BATCH_SERVER_URL, EU_AMPLITUDE_SERVER_URL, STORAGE_PREFIX, } from '../types/constants';
@@ -26,6 +26,9 @@ function getErrorMessage(error) {
26
26
  return error.message;
27
27
  return String(error);
28
28
  }
29
+ function isDelayedEvent(event) {
30
+ return event.delay !== undefined && event.delay !== null;
31
+ }
29
32
  export function getResponseBodyString(res) {
30
33
  var responseBodyString = '';
31
34
  try {
@@ -56,6 +59,7 @@ var Destination = /** @class */ (function () {
56
59
  // When flush resolves, set `flushId` to null
57
60
  this.flushId = null;
58
61
  this.queue = [];
62
+ this.inFlightDelayedEvents = {};
59
63
  this.diagnosticsClient = context === null || context === void 0 ? void 0 : context.diagnosticsClient;
60
64
  }
61
65
  Destination.prototype.setup = function (config) {
@@ -92,11 +96,63 @@ var Destination = /** @class */ (function () {
92
96
  callback: function (result) { return resolve(result); },
93
97
  timeout: 0,
94
98
  };
99
+ if (isDelayedEvent(event)) {
100
+ _this.removeStaleDelayedEvents(event);
101
+ }
95
102
  _this.queue.push(context);
96
103
  _this.schedule(_this.config.flushIntervalMillis);
97
104
  _this.saveEvents();
98
105
  });
99
106
  };
107
+ /**
108
+ * If a stale delayed event is sitting in the queue, and it is not in flight,
109
+ * remove it and resolve as "stale" with status code 0.
110
+ *
111
+ * If a matching delayed event is already in flight, clone `delay` onto the
112
+ * incoming event and set skipRemoval so the in-flight send does not drop the
113
+ * replacement. Earlier replacements waiting on the same send are discarded
114
+ * as stale so only the latest copy remains.
115
+ * @param incomingEvent { Event } the new event to check old events against
116
+ * @returns void
117
+ */
118
+ Destination.prototype.removeStaleDelayedEvents = function (incomingEvent) {
119
+ var _this = this;
120
+ try {
121
+ /* istanbul ignore next */
122
+ this.queue = this.queue.filter(function (context) {
123
+ var _a;
124
+ var targetEvent = context.event;
125
+ if (!isDelayedEvent(targetEvent)) {
126
+ return true;
127
+ }
128
+ // target event matches the incoming event if it has the same insert_id and delay id
129
+ // as the incoming event (the incoming event takes precedence)
130
+ var isMatchingEvent = targetEvent.delay.id === incomingEvent.delay.id && targetEvent.insert_id === incomingEvent.insert_id;
131
+ // do not filter out non matching events
132
+ if (!isMatchingEvent) {
133
+ return true;
134
+ }
135
+ // are there delayed events for this delay id currently in flight?
136
+ var areDelayedEventsInFlight = _this.inFlightDelayedEvents[incomingEvent.delay.id];
137
+ // if they are, then protect the target event from being removed from the queue
138
+ // after the in-flight send completes by setting skipRemoval on the incoming event
139
+ if (areDelayedEventsInFlight) {
140
+ incomingEvent.delay = __assign(__assign({}, incomingEvent.delay), { skipRemoval: true });
141
+ }
142
+ // if events are not in flight, or if the target event is marked to skipRemoval,
143
+ // then the incoming event supersedes the target event, and target event should be dropped
144
+ if (!areDelayedEventsInFlight || ((_a = targetEvent.delay) === null || _a === void 0 ? void 0 : _a.skipRemoval)) {
145
+ context.callback(buildResult(targetEvent, 0, 'Stale event overwritten'));
146
+ return false;
147
+ }
148
+ return true;
149
+ });
150
+ /* istanbul ignore next */
151
+ }
152
+ catch (e) {
153
+ // swallow error
154
+ }
155
+ };
100
156
  Destination.prototype.removeEventsExceedFlushMaxRetries = function (list) {
101
157
  var _this = this;
102
158
  return list.filter(function (context) {
@@ -147,7 +203,7 @@ var Destination = /** @class */ (function () {
147
203
  Destination.prototype.flush = function (useRetry) {
148
204
  if (useRetry === void 0) { useRetry = false; }
149
205
  return __awaiter(this, void 0, void 0, function () {
150
- var list, later, batches;
206
+ var list, delayed, later, batches, regularEventBatch, eventPromises;
151
207
  var _this = this;
152
208
  return __generator(this, function (_a) {
153
209
  switch (_a.label) {
@@ -166,25 +222,40 @@ var Destination = /** @class */ (function () {
166
222
  this.flushId = this.scheduleId;
167
223
  this.resetSchedule();
168
224
  list = [];
225
+ delayed = {};
169
226
  later = [];
170
- this.queue.forEach(function (context) { return (context.timeout === 0 ? list.push(context) : later.push(context)); });
227
+ this.queue.forEach(function (context) {
228
+ var _a;
229
+ if (context.timeout !== 0) {
230
+ later.push(context);
231
+ }
232
+ else if ((_a = context.event.delay) === null || _a === void 0 ? void 0 : _a.id) {
233
+ var delay = context.event.delay;
234
+ delayed[delay.id] = delayed[delay.id] || [];
235
+ delayed[delay.id].push(context);
236
+ }
237
+ else {
238
+ list.push(context);
239
+ }
240
+ });
171
241
  batches = chunk(list, this.config.flushQueueSize);
172
- // Promise.all() doesn't guarantee resolve order.
173
- // Sequentially resolve to make sure backend receives events in order
174
- return [4 /*yield*/, batches.reduce(function (promise, batch) { return __awaiter(_this, void 0, void 0, function () {
175
- return __generator(this, function (_a) {
176
- switch (_a.label) {
177
- case 0: return [4 /*yield*/, promise];
178
- case 1:
179
- _a.sent();
180
- return [4 /*yield*/, this.send(batch, useRetry)];
181
- case 2: return [2 /*return*/, _a.sent()];
182
- }
183
- });
184
- }); }, Promise.resolve())];
242
+ regularEventBatch = batches.reduce(function (promise, batch) { return __awaiter(_this, void 0, void 0, function () {
243
+ return __generator(this, function (_a) {
244
+ switch (_a.label) {
245
+ case 0: return [4 /*yield*/, promise];
246
+ case 1:
247
+ _a.sent();
248
+ return [4 /*yield*/, this.send(batch, useRetry)];
249
+ case 2: return [2 /*return*/, _a.sent()];
250
+ }
251
+ });
252
+ }); }, Promise.resolve());
253
+ eventPromises = [regularEventBatch];
254
+ if (Object.keys(delayed).length > 0) {
255
+ eventPromises.push(this.sendDelayedEvents(delayed, useRetry));
256
+ }
257
+ return [4 /*yield*/, Promise.all(eventPromises)];
185
258
  case 1:
186
- // Promise.all() doesn't guarantee resolve order.
187
- // Sequentially resolve to make sure backend receives events in order
188
259
  _a.sent();
189
260
  // Mark current flush is done
190
261
  this.flushId = null;
@@ -194,11 +265,77 @@ var Destination = /** @class */ (function () {
194
265
  });
195
266
  });
196
267
  };
197
- Destination.prototype.send = function (list, useRetry) {
268
+ Destination.prototype.sendDelayedEvents = function (delayed, useRetry) {
269
+ var e_1, _a;
270
+ var _this = this;
271
+ var eventPromises = [];
272
+ try {
273
+ var _loop_1 = function (delayId, contexts) {
274
+ this_1.inFlightDelayedEvents[delayId] = true;
275
+ var delayedEventsSend = this_1.send(contexts, useRetry, true);
276
+ eventPromises.push(delayedEventsSend);
277
+ delayedEventsSend.finally(function () {
278
+ delete _this.inFlightDelayedEvents[delayId];
279
+ });
280
+ };
281
+ var this_1 = this;
282
+ try {
283
+ for (var _b = __values(Object.entries(delayed)), _c = _b.next(); !_c.done; _c = _b.next()) {
284
+ var _d = __read(_c.value, 2), delayId = _d[0], contexts = _d[1];
285
+ _loop_1(delayId, contexts);
286
+ }
287
+ }
288
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
289
+ finally {
290
+ try {
291
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
292
+ }
293
+ finally { if (e_1) throw e_1.error; }
294
+ }
295
+ }
296
+ catch (e) {
297
+ // swallow error
298
+ }
299
+ return eventPromises.reduce(function (promise, batch) { return __awaiter(_this, void 0, void 0, function () {
300
+ return __generator(this, function (_a) {
301
+ switch (_a.label) {
302
+ case 0: return [4 /*yield*/, promise];
303
+ case 1:
304
+ _a.sent();
305
+ return [4 /*yield*/, batch];
306
+ case 2: return [2 /*return*/, _a.sent()];
307
+ }
308
+ });
309
+ }); }, Promise.resolve());
310
+ };
311
+ Destination.prototype.translatePayloadToDelayedPayload = function (payload, list) {
312
+ var _a, _b;
313
+ var delayedEvents = [];
314
+ var instantEvents = [];
315
+ var delayedContexts = [];
316
+ var instantContexts = [];
317
+ list.forEach(function (context, index) {
318
+ if (context.event.delay.timeout) {
319
+ delayedEvents.push(payload.events[index]);
320
+ delayedContexts.push(context);
321
+ }
322
+ else {
323
+ instantEvents.push(payload.events[index]);
324
+ instantContexts.push(context);
325
+ }
326
+ });
327
+ list.splice.apply(list, __spreadArray(__spreadArray([0, list.length], __read(delayedContexts), false), __read(instantContexts), false));
328
+ /* istanbul ignore next */
329
+ payload.timeout = (_b = (_a = delayedContexts[0]) === null || _a === void 0 ? void 0 : _a.event.delay.timeout) !== null && _b !== void 0 ? _b : 0;
330
+ payload.id = list[0].event.delay.id;
331
+ payload.events = delayedEvents;
332
+ payload.instant_events = instantEvents;
333
+ };
334
+ Destination.prototype.send = function (list, useRetry, delay) {
198
335
  var _a;
199
336
  if (useRetry === void 0) { useRetry = true; }
200
337
  return __awaiter(this, void 0, void 0, function () {
201
- var payload, serverUrl, shouldCompressUploadBody, res, e_1, errorMessage;
338
+ var payload, serverUrl, shouldCompressUploadBody, res, e_2, errorMessage;
202
339
  return __generator(this, function (_b) {
203
340
  switch (_b.label) {
204
341
  case 0:
@@ -209,21 +346,28 @@ var Destination = /** @class */ (function () {
209
346
  api_key: this.config.apiKey,
210
347
  events: list.map(function (context) {
211
348
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
212
- var _a = context.event, extra = _a.extra, eventWithoutExtra = __rest(_a, ["extra"]);
349
+ var _a = context.event, extra = _a.extra, delay = _a.delay, eventWithoutExtra = __rest(_a, ["extra", "delay"]);
213
350
  return eventWithoutExtra;
214
351
  }),
215
352
  options: {
216
353
  min_id_length: this.config.minIdLength,
217
354
  },
218
355
  client_upload_time: new Date().toISOString(),
219
- request_metadata: this.config.requestMetadata,
356
+ request_metadata: delay ? undefined : this.config.requestMetadata,
220
357
  };
221
- this.config.requestMetadata = new RequestMetadata();
358
+ if (!delay) {
359
+ this.config.requestMetadata = new RequestMetadata();
360
+ }
222
361
  _b.label = 1;
223
362
  case 1:
224
363
  _b.trys.push([1, 3, , 4]);
225
364
  serverUrl = createServerConfig(this.config.serverUrl, this.config.serverZone, this.config.useBatch).serverUrl;
226
365
  shouldCompressUploadBody = shouldCompressUploadBodyForRequest(serverUrl, this.config.enableRequestBodyCompression);
366
+ if (delay) {
367
+ serverUrl = this.config.delayedEventsServerUrl || "".concat(serverUrl, "/delayed");
368
+ this.translatePayloadToDelayedPayload(payload, list);
369
+ shouldCompressUploadBody = false; // delayed events doesn't support compression
370
+ }
227
371
  return [4 /*yield*/, this.config.transportProvider.send(serverUrl, payload, shouldCompressUploadBody)];
228
372
  case 2:
229
373
  res = _b.sent();
@@ -243,8 +387,8 @@ var Destination = /** @class */ (function () {
243
387
  this.handleResponse(res, list);
244
388
  return [3 /*break*/, 4];
245
389
  case 3:
246
- e_1 = _b.sent();
247
- errorMessage = getErrorMessage(e_1);
390
+ e_2 = _b.sent();
391
+ errorMessage = getErrorMessage(e_2);
248
392
  this.config.loggerProvider.error(errorMessage);
249
393
  (_a = this.diagnosticsClient) === null || _a === void 0 ? void 0 : _a.recordEvent('analytics.events.unsuccessful.from.catch.error', {
250
394
  events: list.map(function (context) { return context.event.event_type; }),
@@ -402,7 +546,16 @@ var Destination = /** @class */ (function () {
402
546
  * This is called on response comes back for a request
403
547
  */
404
548
  Destination.prototype.removeEvents = function (eventsToRemove) {
405
- this.queue = this.queue.filter(function (queuedContext) { return !eventsToRemove.some(function (context) { return context.event.insert_id === queuedContext.event.insert_id; }); });
549
+ var insertIdsBeingRemoved = new Set(eventsToRemove.map(function (context) { return context.event.insert_id; }));
550
+ this.queue = this.queue.filter(function (queuedContext) {
551
+ return !eventsToRemove.some(function (context) { var _a; return context.event.insert_id === queuedContext.event.insert_id && !((_a = queuedContext.event.delay) === null || _a === void 0 ? void 0 : _a.skipRemoval); });
552
+ });
553
+ this.queue.forEach(function (context) {
554
+ var _a;
555
+ if (((_a = context.event.delay) === null || _a === void 0 ? void 0 : _a.skipRemoval) && insertIdsBeingRemoved.has(context.event.insert_id)) {
556
+ delete context.event.delay.skipRemoval;
557
+ }
558
+ });
406
559
  this.saveEvents();
407
560
  };
408
561
  return Destination;