@amplitude/plugin-engaged-time-tracking-browser 0.0.0-stage → 1.1.0-video-analytics-plus-page-x-y.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 (35) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +74 -2
  3. package/lib/cjs/engaged-time-tracking.d.ts +4 -0
  4. package/lib/cjs/engaged-time-tracking.d.ts.map +1 -0
  5. package/lib/cjs/engaged-time-tracking.js +162 -0
  6. package/lib/cjs/engaged-time-tracking.js.map +1 -0
  7. package/lib/cjs/index.d.ts +2 -0
  8. package/lib/cjs/index.d.ts.map +1 -0
  9. package/lib/cjs/index.js +7 -0
  10. package/lib/cjs/index.js.map +1 -0
  11. package/lib/cjs/page-engagement.d.ts +15 -0
  12. package/lib/cjs/page-engagement.d.ts.map +1 -0
  13. package/lib/cjs/page-engagement.js +238 -0
  14. package/lib/cjs/page-engagement.js.map +1 -0
  15. package/lib/esm/engaged-time-tracking.d.ts +4 -0
  16. package/lib/esm/engaged-time-tracking.d.ts.map +1 -0
  17. package/lib/esm/engaged-time-tracking.js +158 -0
  18. package/lib/esm/engaged-time-tracking.js.map +1 -0
  19. package/lib/esm/index.d.ts +2 -0
  20. package/lib/esm/index.d.ts.map +1 -0
  21. package/lib/esm/index.js +2 -0
  22. package/lib/esm/index.js.map +1 -0
  23. package/lib/esm/page-engagement.d.ts +15 -0
  24. package/lib/esm/page-engagement.d.ts.map +1 -0
  25. package/lib/esm/page-engagement.js +234 -0
  26. package/lib/esm/page-engagement.js.map +1 -0
  27. package/lib/scripts/amplitude-min.umd.js +1 -0
  28. package/lib/scripts/amplitude-min.umd.js.gz +0 -0
  29. package/lib/scripts/engaged-time-tracking.d.ts +4 -0
  30. package/lib/scripts/engaged-time-tracking.d.ts.map +1 -0
  31. package/lib/scripts/index.d.ts +2 -0
  32. package/lib/scripts/index.d.ts.map +1 -0
  33. package/lib/scripts/page-engagement.d.ts +15 -0
  34. package/lib/scripts/page-engagement.d.ts.map +1 -0
  35. package/package.json +52 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Amplitude Analytics
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,75 @@
1
- # Temporary Holding Version
1
+ # Engaged-time tracking
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Experimental browser enrichment plugin for cumulative engaged time on default or custom page-view events. It uses the existing heartbeat and delayed-ingestion service. Each logical page view retains its event name, original timestamp, insert ID, identity, and business properties across snapshots.
4
+
5
+ ## Browser SDK configuration
6
+
7
+ `engagedTimeTracking` is an opt-in sibling of `pageViews` under `autocapture`. Its type is `boolean | EngagedTimeOptions`:
8
+
9
+ ```ts
10
+ amplitude.init(API_KEY, {
11
+ autocapture: {
12
+ pageViews: false,
13
+ engagedTimeTracking: {
14
+ pageViewEventType: 'page_view',
15
+ secondaryPageViewEventType: 'Engagement Resumed',
16
+ activityWindowMillis: 5_000,
17
+ heartbeatIntervalMillis: 15_000,
18
+ inactivityTimeoutMillis: 180_000,
19
+ },
20
+ },
21
+ });
22
+
23
+ // The application supplies the initial view and subsequent navigation views.
24
+ amplitude.track('page_view', { article_id: '123' });
25
+ ```
26
+
27
+ - `false` or omitted: disabled. `autocapture: true` does not enable this experimental feature.
28
+ - `true` or `{}`: use `[Amplitude] Page Viewed` and the default timings above.
29
+ - An options object: optionally override `pageViewEventType`, `secondaryPageViewEventType`, and any of the three durations.
30
+
31
+ `true` uses `[Amplitude] Page Viewed`, even if `pageViews.eventType` renames automatic events. Set `pageViewEventType` explicitly to track a renamed or custom event. Matching is exact and case-sensitive; other event types are delivered normally. Installation depends only on `autocapture.engagedTimeTracking`; `pageViews` is not changed or inspected. The plugin waits for a matching event. With `pageViews: false` and no matching event, engagement never starts—even after focus, activity, or navigation.
32
+
33
+ ## Lifecycle and delivery
34
+
35
+ **Behavior to highlight: inactivity renewal creates another PageView, including for custom event names.** The expired view is finalized. Once the user becomes active again on the same page (or returns to a visible page via focus), a new event is generated with `secondaryPageViewEventType` (falling back to `pageViewEventType` when omitted), fresh timestamp, insert ID, and delay group. The renewal supplies only the event name and internal lifecycle context. It does not copy article, campaign, URL, title, scroll, viewport, or other properties from the previous view, and this plugin does not generate Page View ID or Page Counter properties. Normal SDK enrichment may add its own fields; the engagement engine adds its existing timing and snapshot diagnostics. Original application events retain their supplied properties throughout their own snapshots.
36
+
37
+ Set `secondaryPageViewEventType` to distinguish resumed engagement from primary PageViews in analytics. Omitting it preserves the primary event name, including the default `[Amplitude] Page Viewed`. Every SDK-generated lifecycle renewal uses this secondary name, including repeated idle cycles and recovery after BFCache or identity/session/reset boundaries. Application-supplied navigation events still use `pageViewEventType`; the plugin does not start timing arbitrary application events with the secondary name. Snapshots retain the name of their own logical view. The old view finalizes at the existing inactivity deadline; configuring a secondary name does not extend it. Aggregate both names when reporting total engagement across these periods.
38
+
39
+ Initialization and navigation do not create events in this plugin. The existing PageView plugin supplies default events according to its own configuration; applications supply custom events with `track(pageViewEventType, properties)`. Each matching event finalizes the preceding logical view and starts the next delay group. URL/history changes alone do not define a new custom logical view or end the current one. After a URL change, renewal also waits for a matching PageView for that URL.
40
+
41
+ Switching tabs pauses engagement. Returning before expiry resumes the same view without generating another. Returning after expiry, renewed activity after identity/session/reset boundaries, and BFCache restoration can generate a new view. Before the first accepted matching event, activation, focus, activity, identity changes, and BFCache restoration cannot generate a view. Teardown and opt-out stop generation; opt-in re-enables activity-based renewal. The next explicitly tracked matching event always starts a fresh view, even at the same URL. Applications that also manually emit page views for an automatic lifecycle transition must account for the additional view; this API does not silently deduplicate business events.
42
+
43
+ `pageViews.trackOn` controls the default page-view source, not event-name matching or engagement enablement. Its default emits at initialization/navigation; a callback gates those automatic events; `'attribution'` converts a campaign identify into a page view. The independent option remains opt-in and matches the final event name regardless of the source. The engagement plugin always waits for its first matching event and never bypasses a source's `trackOn` decision. After accepting a view, it owns lifecycle renewal.
44
+
45
+ During normal initialization, the Browser SDK installs engagement after PageView tracking and Page URL enrichment. Page Counter is part of PageView tracking: it increments once for each event matching that source's configured name. The first event continues through the original pipeline once. Heartbeat/final snapshots use the real client and carry the internal `extra.engagedTimeReplay` marker: PageView tracking preserves their counter without incrementing SDK state, and URL enrichment preserves every captured page field, including Previous Page. Other delayed events, including Video Analytics, are enriched normally. A genuine renewed PageView passes through normal enrichment once and can increment the counter. Custom events do not acquire a counter when the PageView source is disabled or matches another name.
46
+
47
+ For example, with `pageViews: { trackOn: 'attribution' }`, `engagedTimeTracking: true`, and user-property attribution enabled, visiting `?utm_source=newsletter&utm_medium=email&utm_campaign=launch` causes attribution to emit a campaign `$identify`. PageView tracking converts that campaign event to `[Amplitude] Page Viewed` and assigns counter 1; URL enrichment adds page/referrer context; engagement then starts timing. Repeated heartbeats retain counter 1. An ordinary `$identify` such as a plan update is not converted. `trackOn: 'attribution'` does not itself emit page views at initialization or on every navigation; it requires a qualifying campaign event.
48
+
49
+ The new plugin calls `pageEngagement.start(event)` during enrichment, after the event reaches its `execute()` method, as did the earlier implementation before extraction. Neither begins counting synchronously inside `track()`. Queueing, event-loop scheduling, and upstream async enrichment can delay that call; it has no fixed upper bound. Original `event.time` is preserved, but engagement/total-time accumulation begins at the actual `start()` call and is not backdated. Heartbeat cadence, batch flush interval, and backend finalization are separate delivery timings, not a fixed delay before counting starts.
50
+
51
+ Snapshots add `[Amplitude] Engaged Time` and `[Amplitude] Total Time` in milliseconds. They also include snapshot version/reason diagnostics. Ingestion is delayed until finalization or the service fallback timeout. Snapshots retain the original enriched page context. Delayed events omit `user_properties`; send user-property updates using a separate `identify()` call. If source data cannot be serialized or a snapshot is too large for the heartbeat queue, the original event is sent normally without engagement tracking.
52
+
53
+ Opt-out discards active state. Opt-in permits the next matching event, or qualifying activity after a previously accepted view, to create a view. A view held in asynchronous enrichment across an identity, session, consent, or page-exit boundary is canceled; an application view held across navigation is sent normally without starting engagement for a later page. A generated renewal queued across navigation is canceled before page enrichment when detected in the before phase; if navigation occurs during upstream asynchronous enrichment, it is canceled at engagement instead.
54
+
55
+ ## Enrichment order and replay
56
+
57
+ The Browser SDK adds engagement at the end of normal built-in plugin installation, after PageView/counter and URL enrichment. Engagement copies the event at that point, adds its delay group and initial timing properties, and returns the first event to the existing pipeline. It does not enqueue another immediate send. Enrichment plugins registered afterward, including Session Replay in Unified, continue processing that first event and every replay.
58
+
59
+ Heartbeat and final snapshots call the real `client.track()`. Only these replays carry `extra.engagedTimeReplay: true`; the engagement plugin passes them through without starting another view. PageView and URL plugins skip their page mutation for this specific marker. Renewed views are new, unmarked source events and receive normal counting and page enrichment. The internal marker is not a public configuration option or a new plugin interface.
60
+
61
+ The saved data includes the source timestamp, insert ID, identity/session, business properties and page fields already added by preceding plugins. The event and its top-level event properties are shallow-copied; nested business objects remain shared references, consistent with ordinary SDK event handling. Applications and custom plugins must not mutate those nested objects after tracking. Later plugins may return new objects; their results do not automatically update the saved source. They execute afresh on every snapshot, so their own properties (including SR ID) may change or be removed according to their current logic. Arbitrary custom enrichment can still overwrite fields. Manually installing a page-context plugin after engagement does not retroactively add its context to the saved view.
62
+
63
+ Initial opt-out can defer another plugin's registration until opt-in, placing that plugin after engagement. This PR does not add special installation ordering for that general SDK case. The first event still continues through later plugins, but their returned fields are not automatically captured for replays; a deferred PageView counter or URL plugin may therefore add fields to the initial event that are absent from the saved snapshots.
64
+
65
+ ## Processing and lifecycle
66
+
67
+ Replays run `process()` and the complete before/enrichment/destination pipeline. With an original nonzero `time`, Browser Context does not advance `lastEventTime`; the saved event/session IDs are supplied again. Browser still evaluates session expiration and campaign changes. A replay in the current session can therefore start a new SDK session and finalize the old logical view. A replay explicitly belonging to an older session does not start another session. Session start/end tracking and other plugins retain their ordinary SDK side effects. Context also assigns the supplied event ID back to `lastEventId`; this is normal replay processing, not a side-effect-free delivery path.
68
+
69
+ Identity/session/reset boundaries keep the old view's identity on its final snapshot. Final delivery is deferred to a microtask so synchronous Browser identity/session updates complete before reentering `track()`. `flush()` drains pending timeline events before flushing destinations; asynchronous plugins and browser page-exit constraints can still delay or prevent delivery. Separate logical views can be delivered in a different order after enrichment, but each keeps its original time and delay group.
70
+
71
+ ## Ownership boundary
72
+
73
+ `autocapture.engagedTimeTracking` is the only engagement entry point. The superseded nested page-view option is removed. PageView has no timer, heartbeat, or lifecycle-renewal ownership; PageView and URL enrichment only recognize marked replays to avoid repeating their page mutations.
74
+
75
+ The original event supplies the first delayed snapshot. The engagement engine then updates a private Heartbeat queue at the configured cadence and sends subsequent/final snapshots through the real client. The snapshot-client destination adapter has been removed. Existing destination queues, storage, batching, retry, coalescing and delayed-service routing remain in use. Finalization retains the original insert ID, timestamp and delay ID, and removes `delay.timeout` for the service's `instant_events` path. Delayed events continue to omit `user_properties`.
@@ -0,0 +1,4 @@
1
+ import { EngagedTimeOptions, EnrichmentPlugin } from '@amplitude/analytics-core';
2
+ /** Observe configured page views; only idle/lifecycle recovery creates replacement views. */
3
+ export declare const engagedTimeTrackingPlugin: (options?: EngagedTimeOptions) => EnrichmentPlugin;
4
+ //# sourceMappingURL=engaged-time-tracking.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engaged-time-tracking.d.ts","sourceRoot":"","sources":["../../src/engaged-time-tracking.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,kBAAkB,EAClB,gBAAgB,EAGjB,MAAM,2BAA2B,CAAC;AAGnC,6FAA6F;AAC7F,eAAO,MAAM,yBAAyB,aAAa,kBAAkB,KAAQ,gBAuJ5E,CAAC"}
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.engagedTimeTrackingPlugin = void 0;
4
+ var tslib_1 = require("tslib");
5
+ var analytics_core_1 = require("@amplitude/analytics-core");
6
+ var page_engagement_1 = require("./page-engagement");
7
+ /** Observe configured page views; only idle/lifecycle recovery creates replacement views. */
8
+ var engagedTimeTrackingPlugin = function (options) {
9
+ var _a, _b;
10
+ if (options === void 0) { options = {}; }
11
+ // Exact application PageView event name to observe.
12
+ var eventType = (_a = options.pageViewEventType) !== null && _a !== void 0 ? _a : analytics_core_1.DEFAULT_PAGE_VIEW_EVENT;
13
+ // Generated lifecycle renewals can use a separate analytics event name.
14
+ var secondaryEventType = (_b = options.secondaryPageViewEventType) !== null && _b !== void 0 ? _b : eventType;
15
+ // Tracks the current view's elapsed time, activity, and heartbeat.
16
+ var pageEngagement;
17
+ // Shared SDK settings, including the current opt-out value.
18
+ var browserConfig;
19
+ // Blocks renewal after pagehide until pageshow, including BFCache.
20
+ var exited = false;
21
+ // Prevents this plugin from generating events after teardown.
22
+ var installed = false;
23
+ // URL of the last accepted view; renewal waits on this same URL.
24
+ var pageHref;
25
+ // Invalidates queued events across identity, session, consent, or exit boundaries.
26
+ var cancellation = 0;
27
+ // Advances for each accepted view so an older renewal cannot replace it.
28
+ var revision = 0;
29
+ // Identifies an in-flight renewal to suppress repeated activity/focus requests.
30
+ var pendingContext;
31
+ // Removes the before-plugin that stamps each event's lifecycle context.
32
+ var removeContext;
33
+ // Unsubscribes this plugin's DOM lifecycle listeners during teardown.
34
+ var removeListeners = [];
35
+ // Reuses a completed promise for synchronous plugin hooks.
36
+ var resolved = Promise.resolve();
37
+ // Cancels stale queued events and finalizes the active view.
38
+ var finish = function (reason) {
39
+ cancellation += 1;
40
+ pageEngagement === null || pageEngagement === void 0 ? void 0 : pageEngagement.finish(reason);
41
+ };
42
+ return {
43
+ name: '@amplitude/plugin-engaged-time-tracking-browser',
44
+ type: 'enrichment',
45
+ setup: function (config, client) {
46
+ browserConfig = config;
47
+ var scope = (0, analytics_core_1.getGlobalScope)();
48
+ if (!(scope === null || scope === void 0 ? void 0 : scope.document))
49
+ return resolved;
50
+ installed = true;
51
+ var doc = scope.document;
52
+ var listen = function (target, type, listener) {
53
+ target.addEventListener(type, listener);
54
+ removeListeners.push(function () { return target.removeEventListener(type, listener); });
55
+ };
56
+ // Register before the engagement tracker so BFCache restore clears the exit guard before resume.
57
+ listen(scope, 'pagehide', function () {
58
+ exited = true;
59
+ cancellation += 1;
60
+ });
61
+ listen(scope, 'pageshow', function () {
62
+ exited = false;
63
+ });
64
+ var trackPageView = function () {
65
+ if (!installed ||
66
+ exited ||
67
+ config.optOut ||
68
+ doc.prerendering ||
69
+ scope.location.href !== pageHref ||
70
+ ((pendingContext === null || pendingContext === void 0 ? void 0 : pendingContext.revision) === revision && pendingContext.cancellation === cancellation))
71
+ return resolved;
72
+ var context = { revision: revision, cancellation: cancellation, href: scope.location.href };
73
+ pendingContext = context;
74
+ // Renew without carrying application properties from the previous view.
75
+ var event = { event_type: secondaryEventType, extra: { engagedTimeContext: context } };
76
+ return client.track(event).promise.finally(function () {
77
+ if (pendingContext === context)
78
+ pendingContext = undefined;
79
+ });
80
+ };
81
+ pageEngagement = (0, page_engagement_1.createPageEngagement)(client, scope, options, config, function () {
82
+ void trackPageView();
83
+ });
84
+ pageEngagement.setOptOut(config.optOut);
85
+ var contextName = '@amplitude/plugin-engaged-time-tracking-browser/context';
86
+ return client
87
+ .add({
88
+ name: contextName,
89
+ type: 'before',
90
+ execute: function (event) {
91
+ var _a, _b, _c, _d;
92
+ // Drop stale generated renewals before page counter/URL enrichment mutates state.
93
+ var context = (_a = event.extra) === null || _a === void 0 ? void 0 : _a.engagedTimeContext;
94
+ if (((_b = event.extra) === null || _b === void 0 ? void 0 : _b.engagedTimeReplay) !== true &&
95
+ (context === null || context === void 0 ? void 0 : context.revision) !== undefined &&
96
+ (context.revision !== revision ||
97
+ context.cancellation !== cancellation ||
98
+ context.href !== scope.location.href))
99
+ return Promise.resolve(null);
100
+ if (((_c = event.extra) === null || _c === void 0 ? void 0 : _c.engagedTimeReplay) !== true && !((_d = event.extra) === null || _d === void 0 ? void 0 : _d.engagedTimeContext)) {
101
+ event.extra = tslib_1.__assign(tslib_1.__assign({}, event.extra), { engagedTimeContext: { cancellation: cancellation, href: scope.location.href } });
102
+ }
103
+ return Promise.resolve(event);
104
+ },
105
+ })
106
+ .promise.then(function () {
107
+ removeContext = function () { return client.remove(contextName).promise; };
108
+ });
109
+ },
110
+ execute: function (event) {
111
+ var _a, _b, _c;
112
+ var context = (_a = event.extra) === null || _a === void 0 ? void 0 : _a.engagedTimeContext;
113
+ if (!pageEngagement ||
114
+ ((_b = event.extra) === null || _b === void 0 ? void 0 : _b.engagedTimeReplay) === true ||
115
+ (event.event_type !== eventType &&
116
+ !(event.event_type === secondaryEventType && (context === null || context === void 0 ? void 0 : context.revision) !== undefined)))
117
+ return Promise.resolve(event);
118
+ if (exited || browserConfig.optOut)
119
+ return Promise.resolve(null);
120
+ if (context && context.cancellation !== cancellation)
121
+ return Promise.resolve(null);
122
+ if ((context === null || context === void 0 ? void 0 : context.revision) !== undefined && context.revision !== revision)
123
+ return Promise.resolve(null);
124
+ if ((context === null || context === void 0 ? void 0 : context.href) !== undefined && context.href !== (0, analytics_core_1.getGlobalScope)().location.href)
125
+ return Promise.resolve(context.revision !== undefined ? null : event);
126
+ pageHref = (0, analytics_core_1.getGlobalScope)().location.href;
127
+ revision += 1;
128
+ return Promise.resolve((_c = pageEngagement.start(event)) !== null && _c !== void 0 ? _c : event);
129
+ },
130
+ teardown: function () {
131
+ var _a;
132
+ installed = false;
133
+ cancellation += 1;
134
+ pageEngagement === null || pageEngagement === void 0 ? void 0 : pageEngagement.teardown();
135
+ pageEngagement = undefined;
136
+ removeListeners.forEach(function (remove) { return remove(); });
137
+ return (_a = removeContext === null || removeContext === void 0 ? void 0 : removeContext()) !== null && _a !== void 0 ? _a : resolved;
138
+ },
139
+ onOptOutChanged: function (optOut) {
140
+ if (optOut) {
141
+ cancellation += 1;
142
+ }
143
+ pageEngagement === null || pageEngagement === void 0 ? void 0 : pageEngagement.setOptOut(optOut);
144
+ return resolved;
145
+ },
146
+ onReset: function () {
147
+ finish('reset');
148
+ return resolved;
149
+ },
150
+ onIdentityChanged: function (identity) {
151
+ if ('userId' in identity || 'deviceId' in identity)
152
+ finish('identity_change');
153
+ return resolved;
154
+ },
155
+ onSessionIdChanged: function () {
156
+ finish('session_change');
157
+ return resolved;
158
+ },
159
+ };
160
+ };
161
+ exports.engagedTimeTrackingPlugin = engagedTimeTrackingPlugin;
162
+ //# sourceMappingURL=engaged-time-tracking.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engaged-time-tracking.js","sourceRoot":"","sources":["../../src/engaged-time-tracking.ts"],"names":[],"mappings":";;;;AAAA,4DAQmC;AACnC,qDAAyE;AAEzE,6FAA6F;AACtF,IAAM,yBAAyB,GAAG,UAAC,OAAgC;;IAAhC,wBAAA,EAAA,YAAgC;IACxE,oDAAoD;IACpD,IAAM,SAAS,GAAG,MAAA,OAAO,CAAC,iBAAiB,mCAAI,wCAAuB,CAAC;IACvE,wEAAwE;IACxE,IAAM,kBAAkB,GAAG,MAAA,OAAO,CAAC,0BAA0B,mCAAI,SAAS,CAAC;IAC3E,mEAAmE;I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AAC,mCAAI,KAAK,CAAC,CAAC;QAC/D,CAAC;QACD,QAAQ,EAAE;;YACR,SAAS,GAAG,KAAK,CAAC;YAClB,YAAY,IAAI,CAAC,CAAC;YAClB,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,QAAQ,EAAE,CAAC;YAC3B,cAAc,GAAG,SAAS,CAAC;YAC3B,eAAe,CAAC,OAAO,CAAC,UAAC,MAAM,IAAK,OAAA,MAAM,EAAE,EAAR,CAAQ,CAAC,CAAC;YAC9C,OAAO,MAAA,aAAa,aAAb,aAAa,uBAAb,aAAa,EAAI,mCAAI,QAAQ,CAAC;QACvC,CAAC;QACD,eAAe,EAAE,UAAC,MAAM;YACtB,IAAI,MAAM,EAAE;gBACV,YAAY,IAAI,CAAC,CAAC;aACnB;YACD,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,SAAS,CAAC,MAAM,CAAC,CAAC;YAClC,OAAO,QAAQ,CAAC;QAClB,CAAC;QACD,OAAO,EAAE;YACP,MAAM,CAAC,OAAO,CAAC,CAAC;YAChB,OAAO,QAAQ,CAAC;QAClB,CAAC;QACD,iBAAiB,EAAE,UAAC,QAAQ;YAC1B,IAAI,QAAQ,IAAI,QAAQ,IAAI,UAAU,IAAI,QAAQ;gBAAE,MAAM,CAAC,iBAAiB,CAAC,CAAC;YAC9E,OAAO,QAAQ,CAAC;QAClB,CAAC;QACD,kBAAkB,EAAE;YAClB,MAAM,CAAC,gBAAgB,CAAC,CAAC;YACzB,OAAO,QAAQ,CAAC;QAClB,CAAC;KACF,CAAC;AACJ,CAAC,CAAC;AAvJW,QAAA,yBAAyB,6BAuJpC","sourcesContent":["import {\n BrowserClient,\n BrowserConfig,\n DEFAULT_PAGE_VIEW_EVENT,\n EngagedTimeOptions,\n EnrichmentPlugin,\n Event,\n getGlobalScope,\n} from '@amplitude/analytics-core';\nimport { createPageEngagement, PageEngagement } from './page-engagement';\n\n/** Observe configured page views; only idle/lifecycle recovery creates replacement views. */\nexport const engagedTimeTrackingPlugin = (options: EngagedTimeOptions = {}): EnrichmentPlugin => {\n // Exact application PageView event name to observe.\n const eventType = options.pageViewEventType ?? DEFAULT_PAGE_VIEW_EVENT;\n // Generated lifecycle renewals can use a separate analytics event name.\n const secondaryEventType = options.secondaryPageViewEventType ?? eventType;\n // Tracks the current view's elapsed time, activity, and heartbeat.\n let pageEngagement: PageEngagement | undefined;\n // Shared SDK settings, including the current opt-out value.\n let browserConfig: BrowserConfig;\n // Blocks renewal after pagehide until pageshow, including BFCache.\n let exited = false;\n // Prevents this plugin from generating events after teardown.\n let installed = false;\n // URL of the last accepted view; renewal waits on this same URL.\n let pageHref: string | undefined;\n // Invalidates queued events across identity, session, consent, or exit boundaries.\n let cancellation = 0;\n // Advances for each accepted view so an older renewal cannot replace it.\n let revision = 0;\n // Identifies an in-flight renewal to suppress repeated activity/focus requests.\n let pendingContext: { revision: number; cancellation: number } | undefined;\n // Removes the before-plugin that stamps each event's lifecycle context.\n let removeContext: (() => Promise<void>) | undefined;\n // Unsubscribes this plugin's DOM lifecycle listeners during teardown.\n const removeListeners: (() => void)[] = [];\n // Reuses a completed promise for synchronous plugin hooks.\n const resolved = Promise.resolve();\n // Cancels stale queued events and finalizes the active view.\n const finish = (reason: string) => {\n cancellation += 1;\n pageEngagement?.finish(reason);\n };\n\n return {\n name: '@amplitude/plugin-engaged-time-tracking-browser',\n type: 'enrichment',\n setup: (config: BrowserConfig, client: BrowserClient) => {\n browserConfig = config;\n const scope = getGlobalScope();\n if (!scope?.document) return resolved;\n installed = true;\n const doc = scope.document as Document & { prerendering?: boolean };\n const listen = (target: EventTarget, type: string, listener: EventListener) => {\n target.addEventListener(type, listener);\n removeListeners.push(() => target.removeEventListener(type, listener));\n };\n // Register before the engagement tracker so BFCache restore clears the exit guard before resume.\n listen(scope, 'pagehide', () => {\n exited = true;\n cancellation += 1;\n });\n listen(scope, 'pageshow', () => {\n exited = false;\n });\n\n const trackPageView = () => {\n if (\n !installed ||\n exited ||\n config.optOut ||\n doc.prerendering ||\n scope.location.href !== pageHref ||\n (pendingContext?.revision === revision && pendingContext.cancellation === cancellation)\n )\n return resolved;\n const context = { revision, cancellation, href: scope.location.href };\n pendingContext = context;\n // Renew without carrying application properties from the previous view.\n const event: Event = { event_type: secondaryEventType, extra: { engagedTimeContext: context } };\n return client.track(event).promise.finally(() => {\n if (pendingContext === context) pendingContext = undefined;\n });\n };\n pageEngagement = createPageEngagement(client, scope, options, config, () => {\n void trackPageView();\n });\n pageEngagement.setOptOut(config.optOut);\n const contextName = '@amplitude/plugin-engaged-time-tracking-browser/context';\n return client\n .add({\n name: contextName,\n type: 'before',\n execute: (event) => {\n // Drop stale generated renewals before page counter/URL enrichment mutates state.\n const context = event.extra?.engagedTimeContext as typeof pendingContext & { href?: string };\n if (\n event.extra?.engagedTimeReplay !== true &&\n context?.revision !== undefined &&\n (context.revision !== revision ||\n context.cancellation !== cancellation ||\n context.href !== scope.location.href)\n )\n return Promise.resolve(null);\n if (event.extra?.engagedTimeReplay !== true && !event.extra?.engagedTimeContext) {\n event.extra = { ...event.extra, engagedTimeContext: { cancellation, href: scope.location.href } };\n }\n return Promise.resolve(event);\n },\n })\n .promise.then(() => {\n removeContext = () => client.remove(contextName).promise;\n });\n },\n execute: (event) => {\n const context = event.extra?.engagedTimeContext as\n | { cancellation: number; revision?: number; href?: string }\n | undefined;\n if (\n !pageEngagement ||\n event.extra?.engagedTimeReplay === true ||\n (event.event_type !== eventType &&\n !(event.event_type === secondaryEventType && context?.revision !== undefined))\n )\n return Promise.resolve(event);\n if (exited || browserConfig.optOut) return Promise.resolve(null);\n if (context && context.cancellation !== cancellation) return Promise.resolve(null);\n if (context?.revision !== undefined && context.revision !== revision) return Promise.resolve(null);\n if (context?.href !== undefined && context.href !== getGlobalScope()!.location.href)\n return Promise.resolve(context.revision !== undefined ? null : event);\n pageHref = getGlobalScope()!.location.href;\n revision += 1;\n return Promise.resolve(pageEngagement.start(event) ?? event);\n },\n teardown: () => {\n installed = false;\n cancellation += 1;\n pageEngagement?.teardown();\n pageEngagement = undefined;\n removeListeners.forEach((remove) => remove());\n return removeContext?.() ?? resolved;\n },\n onOptOutChanged: (optOut) => {\n if (optOut) {\n cancellation += 1;\n }\n pageEngagement?.setOptOut(optOut);\n return resolved;\n },\n onReset: () => {\n finish('reset');\n return resolved;\n },\n onIdentityChanged: (identity) => {\n if ('userId' in identity || 'deviceId' in identity) finish('identity_change');\n return resolved;\n },\n onSessionIdChanged: () => {\n finish('session_change');\n return resolved;\n },\n };\n};\n"]}
@@ -0,0 +1,2 @@
1
+ export { engagedTimeTrackingPlugin, engagedTimeTrackingPlugin as plugin } from './engaged-time-tracking';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,yBAAyB,IAAI,MAAM,EAAE,MAAM,yBAAyB,CAAC"}
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.plugin = exports.engagedTimeTrackingPlugin = void 0;
4
+ var engaged_time_tracking_1 = require("./engaged-time-tracking");
5
+ Object.defineProperty(exports, "engagedTimeTrackingPlugin", { enumerable: true, get: function () { return engaged_time_tracking_1.engagedTimeTrackingPlugin; } });
6
+ Object.defineProperty(exports, "plugin", { enumerable: true, get: function () { return engaged_time_tracking_1.engagedTimeTrackingPlugin; } });
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,iEAAyG;AAAhG,kIAAA,yBAAyB,OAAA;AAAE,+GAAA,yBAAyB,OAAU","sourcesContent":["export { engagedTimeTrackingPlugin, engagedTimeTrackingPlugin as plugin } from './engaged-time-tracking';\n"]}
@@ -0,0 +1,15 @@
1
+ import { getGlobalScope, BrowserClient, Event, BrowserConfig, EngagedTimeOptions } from '@amplitude/analytics-core';
2
+ export declare const DEFAULT_ACTIVITY_WINDOW = 5000;
3
+ export declare const DEFAULT_ENGAGEMENT_HEARTBEAT = 15000;
4
+ export declare const DEFAULT_INACTIVITY_TIMEOUT = 180000;
5
+ /** Owns one page-view delay group at a time, independently of the video heartbeat.
6
+ * Keep per-owner state in a closure so ES5 bundles can minify internal names.
7
+ */
8
+ export declare const createPageEngagement: (client: BrowserClient, scope: NonNullable<ReturnType<typeof getGlobalScope>>, options: EngagedTimeOptions, config: BrowserConfig, newPageView: () => void) => {
9
+ start: (event: Event) => Event | undefined;
10
+ finish: (reason: string) => void;
11
+ setOptOut: (optOut: boolean) => void;
12
+ teardown: () => void;
13
+ };
14
+ export type PageEngagement = ReturnType<typeof createPageEngagement>;
15
+ //# sourceMappingURL=page-engagement.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"page-engagement.d.ts","sourceRoot":"","sources":["../../src/page-engagement.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,aAAa,EACb,KAAK,EAEL,aAAa,EAEb,kBAAkB,EAEnB,MAAM,2BAA2B,CAAC;AAEnC,eAAO,MAAM,uBAAuB,OAAQ,CAAC;AAC7C,eAAO,MAAM,4BAA4B,QAAS,CAAC;AACnD,eAAO,MAAM,0BAA0B,SAAU,CAAC;AAsClD;;GAEG;AACH,eAAO,MAAM,oBAAoB,WACvB,aAAa,SACd,YAAY,WAAW,qBAAqB,CAAC,CAAC,WAC5C,kBAAkB,UACnB,aAAa,eACR,MAAM,IAAI;mBA4BD,KAAK,KAAG,KAAK,GAAG,SAAS;qBAoKvB,MAAM;wBAiBH,OAAO;;CAoCnC,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,UAAU,CAAC,OAAO,oBAAoB,CAAC,CAAC"}
@@ -0,0 +1,238 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createPageEngagement = exports.DEFAULT_INACTIVITY_TIMEOUT = exports.DEFAULT_ENGAGEMENT_HEARTBEAT = exports.DEFAULT_ACTIVITY_WINDOW = void 0;
4
+ var tslib_1 = require("tslib");
5
+ var analytics_core_1 = require("@amplitude/analytics-core");
6
+ exports.DEFAULT_ACTIVITY_WINDOW = 5000;
7
+ exports.DEFAULT_ENGAGEMENT_HEARTBEAT = 15000;
8
+ exports.DEFAULT_INACTIVITY_TIMEOUT = 180000;
9
+ var BACKGROUND_SEND_INTERVAL = 1000;
10
+ // Browser timers use a signed 32-bit millisecond delay. Larger values can overflow.
11
+ var MAX_TIMER_DELAY_MILLIS = 2147483647;
12
+ // The delayed-event service rejects request timeouts greater than 24 hours.
13
+ var MAX_INACTIVITY_TIMEOUT_MILLIS = 86400000;
14
+ function resolveDurationMillis(value, defaultValue, logger, maximum) {
15
+ if (maximum === void 0) { maximum = MAX_TIMER_DELAY_MILLIS; }
16
+ if (value === undefined)
17
+ return defaultValue;
18
+ if (!Number.isFinite(value) || value <= 0 || value > maximum) {
19
+ logger.warn("Page engagement: invalid duration ".concat(value, " ms; using default ").concat(defaultValue, " ms. Expected 0 < finite duration <= ").concat(maximum, " ms."));
20
+ return defaultValue;
21
+ }
22
+ return value;
23
+ }
24
+ /** Owns one page-view delay group at a time, independently of the video heartbeat.
25
+ * Keep per-owner state in a closure so ES5 bundles can minify internal names.
26
+ */
27
+ var createPageEngagement = function (client, scope, options, config, newPageView) {
28
+ var currentPage;
29
+ var inactivityTimer;
30
+ var foreground = isForeground();
31
+ var enabled = true;
32
+ var skippedPage = false;
33
+ var removeListeners = [];
34
+ var timeout = resolveDurationMillis(options.inactivityTimeoutMillis, exports.DEFAULT_INACTIVITY_TIMEOUT, config.loggerProvider, MAX_INACTIVITY_TIMEOUT_MILLIS);
35
+ var activityWindow = resolveDurationMillis(options.activityWindowMillis, exports.DEFAULT_ACTIVITY_WINDOW, config.loggerProvider);
36
+ var pulse = Math.min(resolveDurationMillis(options.heartbeatIntervalMillis, exports.DEFAULT_ENGAGEMENT_HEARTBEAT, config.loggerProvider), timeout / 2);
37
+ function isForeground() {
38
+ return scope.document.visibilityState === 'visible' && scope.document.hasFocus();
39
+ }
40
+ function start(event) {
41
+ var _a;
42
+ finish('navigation');
43
+ if (!enabled)
44
+ return undefined;
45
+ var now = Date.now();
46
+ foreground = isForeground();
47
+ var pageState = {
48
+ event: tslib_1.__assign(tslib_1.__assign({}, event), {
49
+ // Capture top-level properties; snapshots add timing without mutating this object.
50
+ event_properties: tslib_1.__assign({}, event.event_properties), insert_id: event.insert_id || (0, analytics_core_1.UUID)(), time: (_a = event.time) !== null && _a !== void 0 ? _a : now,
51
+ // Share the SDK inactivity duration with the service fallback. The SDK counts
52
+ // from last activity; the service counts from the last accepted heartbeat.
53
+ delay: { id: (0, analytics_core_1.UUID)(), timeout: timeout } }),
54
+ heartbeat: new analytics_core_1.Heartbeat(client, pulse, timeout, config.loggerProvider, {
55
+ // This owner settles elapsed time and finalizes before sending.
56
+ // Avoid a second set of lifecycle sends.
57
+ sendOnPageLifecycle: false,
58
+ beforeHeartbeat: function () {
59
+ // A heartbeat scheduled by the previous page must not update the new page state.
60
+ if (currentPage === pageState) {
61
+ if (Date.now() >= pageState.lastActivity + timeout) {
62
+ retire(pageState, 'inactivity');
63
+ }
64
+ else {
65
+ void pageState.heartbeat.update(snapshot(pageState, pageState.nextSnapshotReason));
66
+ pageState.nextSnapshotReason = 'heartbeat';
67
+ }
68
+ }
69
+ },
70
+ }),
71
+ started: now,
72
+ updated: now,
73
+ lastActivity: now,
74
+ engaged: 0,
75
+ version: 0,
76
+ nextSnapshotReason: 'heartbeat',
77
+ };
78
+ // Arrival after server expiry must not overwrite more recent identify updates.
79
+ delete pageState.event.user_properties;
80
+ var initial = snapshot(pageState, 'initial');
81
+ var isEnqueued = false;
82
+ try {
83
+ isEnqueued = pageState.heartbeat.enqueue(initial);
84
+ }
85
+ catch (_b) {
86
+ // Heartbeat's size check serializes the event and can reject invalid source data.
87
+ pageState.heartbeat.stop();
88
+ }
89
+ if (!isEnqueued) {
90
+ // Do not turn subsequent activity on this page into repeated fallback views.
91
+ skippedPage = true;
92
+ config.loggerProvider.warn('Page engagement: snapshot cannot be queued (invalid data or size limit); sending without engaged-time tracking.');
93
+ return undefined;
94
+ }
95
+ currentPage = pageState;
96
+ scheduleInactivity();
97
+ // The original pipeline sends initial. Start only the periodic pulse here;
98
+ // Heartbeat.resetHeartbeat() would send a duplicate initial copy.
99
+ pageState.pulseTimer = setInterval(function () { return void pageState.heartbeat.heartbeat(); }, pulse);
100
+ return initial;
101
+ }
102
+ function settle(pageState) {
103
+ // Cap a late callback at the inactivity deadline; heartbeats never extend it.
104
+ var now = Math.max(pageState.updated, Math.min(Date.now(), pageState.lastActivity + timeout));
105
+ if (foreground) {
106
+ pageState.engaged += Math.max(0, Math.min(now, pageState.lastActivity + activityWindow) - pageState.updated);
107
+ }
108
+ pageState.updated = now;
109
+ }
110
+ function snapshot(pageState, reason) {
111
+ settle(pageState);
112
+ var version = ++pageState.version;
113
+ return tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, pageState.event), (reason === 'initial' ? {} : { extra: tslib_1.__assign(tslib_1.__assign({}, pageState.event.extra), { engagedTimeReplay: true }) })), { event_properties: tslib_1.__assign(tslib_1.__assign({}, pageState.event.event_properties), { '[Amplitude] Engaged Time': pageState.engaged, '[Amplitude] Total Time': pageState.updated - pageState.started,
114
+ // Internal diagnostics; version counts constructed snapshots, not requests.
115
+ '[Amplitude] Snapshot Version': version, '[Amplitude] Engagement Snapshot Reason': reason }) });
116
+ }
117
+ function scheduleInactivity() {
118
+ clearTimeout(inactivityTimer);
119
+ inactivityTimer = setTimeout(function () { return finish('inactivity'); }, timeout);
120
+ }
121
+ var activity = function () {
122
+ if (!enabled ||
123
+ skippedPage ||
124
+ !foreground ||
125
+ scope.document.prerendering)
126
+ return;
127
+ if (currentPage && Date.now() >= currentPage.lastActivity + timeout)
128
+ finish('inactivity');
129
+ if (!currentPage) {
130
+ newPageView();
131
+ return;
132
+ }
133
+ settle(currentPage);
134
+ currentPage.lastActivity = Date.now();
135
+ scheduleInactivity();
136
+ };
137
+ var resume = function () {
138
+ if (scope.document.visibilityState !== 'visible')
139
+ return;
140
+ if (currentPage)
141
+ settle(currentPage);
142
+ foreground = true;
143
+ activity();
144
+ };
145
+ var pause = function () {
146
+ if (currentPage)
147
+ settle(currentPage);
148
+ foreground = false;
149
+ if (currentPage) {
150
+ sendBackground(currentPage);
151
+ }
152
+ };
153
+ function sendBackground(pageState) {
154
+ var remaining = pageState.lastBackgroundSent === undefined
155
+ ? 0
156
+ : pageState.lastBackgroundSent + BACKGROUND_SEND_INTERVAL - Date.now();
157
+ if (remaining > 0) {
158
+ // blur and hidden can describe the same transition. Keep a single trailing
159
+ // send at the original deadline, using the latest state when it fires.
160
+ if (pageState.backgroundTimer === undefined) {
161
+ pageState.backgroundTimer = setTimeout(function () {
162
+ pageState.backgroundTimer = undefined;
163
+ sendBackground(pageState);
164
+ }, remaining);
165
+ }
166
+ return;
167
+ }
168
+ clearTimeout(pageState.backgroundTimer);
169
+ pageState.backgroundTimer = undefined;
170
+ pageState.lastBackgroundSent = Date.now();
171
+ pageState.nextSnapshotReason = 'background';
172
+ void pageState.heartbeat.heartbeat();
173
+ client.flush();
174
+ }
175
+ function retire(pageState, reason) {
176
+ clearInterval(pageState.pulseTimer);
177
+ clearTimeout(pageState.backgroundTimer);
178
+ clearTimeout(inactivityTimer);
179
+ var event = snapshot(pageState, reason);
180
+ event.delay = tslib_1.__assign(tslib_1.__assign({}, event.delay), { timeout: undefined });
181
+ void pageState.heartbeat.update(event);
182
+ pageState.heartbeat.pause();
183
+ currentPage = undefined;
184
+ }
185
+ function finish(reason) {
186
+ skippedPage = false;
187
+ var pageState = currentPage;
188
+ if (!pageState)
189
+ return;
190
+ retire(pageState, reason);
191
+ // Enqueue the final copy before clearing this page's heartbeat. Destination
192
+ // coalesces pending snapshots and preserves in-flight ordering by delay ID.
193
+ // Session/identity hooks run before Browser config updates. Defer delivery
194
+ // until that update completes to avoid reentering session creation from track().
195
+ void Promise.resolve().then(function () {
196
+ void pageState.heartbeat.heartbeat();
197
+ // flush() drains the timeline before flushing destination queues.
198
+ client.flush();
199
+ pageState.heartbeat.stop();
200
+ });
201
+ }
202
+ function setOptOut(optOut) {
203
+ enabled = !optOut;
204
+ if (optOut) {
205
+ skippedPage = false;
206
+ clearTimeout(inactivityTimer);
207
+ clearTimeout(currentPage === null || currentPage === void 0 ? void 0 : currentPage.backgroundTimer);
208
+ clearInterval(currentPage === null || currentPage === void 0 ? void 0 : currentPage.pulseTimer);
209
+ currentPage === null || currentPage === void 0 ? void 0 : currentPage.heartbeat.stop();
210
+ currentPage = undefined;
211
+ }
212
+ }
213
+ function teardown() {
214
+ finish('teardown');
215
+ enabled = false;
216
+ removeListeners.forEach(function (remove) { return remove(); });
217
+ }
218
+ var listen = function (target, type, listener) {
219
+ target.addEventListener(type, listener, { passive: true });
220
+ removeListeners.push(function () { return target.removeEventListener(type, listener); });
221
+ };
222
+ ['pointerdown', 'pointermove', 'keydown', 'scroll', 'touchstart', 'wheel'].forEach(function (type) {
223
+ listen(scope.document, type, activity);
224
+ });
225
+ listen(scope, 'focus', resume);
226
+ listen(scope, 'blur', pause);
227
+ listen(scope.document, 'visibilitychange', function () { return (isForeground() ? resume() : pause()); });
228
+ // Leaving the document always ends this view, including entry into BFCache.
229
+ listen(scope, 'pagehide', function () { return finish('pagehide'); });
230
+ listen(scope, 'pageshow', function () {
231
+ // A restored page starts a fresh view through the existing activity path.
232
+ if (isForeground())
233
+ resume();
234
+ });
235
+ return { start: start, finish: finish, setOptOut: setOptOut, teardown: teardown };
236
+ };
237
+ exports.createPageEngagement = createPageEngagement;
238
+ //# sourceMappingURL=page-engagement.js.map