@temps-sdk/analytics-core 0.0.6 → 0.0.7-beta.1

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.
@@ -1 +1 @@
1
- {"version":3,"file":"Analytics.d.ts","sourceRoot":"","sources":["../src/Analytics.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAa,MAAM,SAAS,CAAC;AAezE;;;GAGG;AACH,wBAAgB,eAAe,CAAC,OAAO,GAAE,gBAAqB,GAAG,YAAY,CAsJ5E"}
1
+ {"version":3,"file":"Analytics.d.ts","sourceRoot":"","sources":["../src/Analytics.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAa,MAAM,SAAS,CAAC;AAgCzE;;;GAGG;AACH,wBAAgB,eAAe,CAAC,OAAO,GAAE,gBAAqB,GAAG,YAAY,CAyT5E"}
package/dist/Analytics.js CHANGED
@@ -5,16 +5,31 @@ import { isLocalhostLike, isTestEnvironment, sendAnalytics, sendAnalyticsReliabl
5
5
  import { EngagementTracker } from "./EngagementTracker";
6
6
  import { SpeedTracker } from "./SpeedTracker";
7
7
  import { SessionRecorder } from "./SessionRecorder";
8
+ import { NOT_FOUND_EVENT, NotFoundMarkerWatcher, notFoundEventData, setupLinkTracking, } from "./AutoTracking";
9
+ import { enableCookielessIdentity, getStoredVisitorId, isCookielessIdentity, onCookielessIdentity, onIdentityReset, } from "./identity";
10
+ import { exposureEventData, FeatureFlags } from "./FeatureFlags";
11
+ import { Surveys } from "./Surveys";
12
+ import { renderSurveyWidget } from "./SurveyWidget";
13
+ import { identifyVisitor, resetVisitor } from "./Identify";
8
14
  /**
9
15
  * Framework-agnostic factory. Call once at app startup in the browser to get an
10
16
  * analytics instance. All framework adapters wrap this factory.
11
17
  */
12
18
  export function createAnalytics(options = {}) {
13
- const { basePath = DEFAULT_BASE_PATH, disabled = false, ignoreLocalhost = true, domain, ingestKey, autoTrackPageviews = true, autoTrackPageLeave = true, pageLeaveEventName = "page_leave", autoTrackSpeedAnalytics = true, autoTrackEngagement = true, heartbeatInterval = 30000, inactivityTimeout = 30000, engagementThreshold = 10000, enableSessionRecording = false, sessionRecordingConfig = {}, } = options;
19
+ const { basePath = DEFAULT_BASE_PATH, disabled = false, ignoreLocalhost = true, domain, ingestKey, autoTrackPageviews = true, autoTrackPageLeave = true, pageLeaveEventName = "page_leave", autoTrackSpeedAnalytics = true, autoTrackEngagement = true, heartbeatInterval = 30000, inactivityTimeout = 30000, engagementThreshold = 10000, enableSessionRecording = false, sessionRecordingConfig = {}, autoTrackOutboundLinks = true, autoTrackFileDownloads = true, fileDownloadExtensions, autoTrackNotFound = true, cookieless = false, flags: flagOptions = {}, surveys: surveyOptions = {}, } = options;
14
20
  const cleanups = [];
21
+ // Before anything can send an event, so the first page view already goes
22
+ // out without a stored id (ADR 109 D3).
23
+ if (cookieless)
24
+ enableCookielessIdentity();
25
+ // Session replay needs a visitor that persists across page loads, which is
26
+ // exactly what cookieless mode gives up. Cookieless is page-wide and
27
+ // one-way, so it is read when recording would start, not from this
28
+ // instance's own option: an earlier instance may have switched it on.
29
+ const recordingAllowed = () => !isCookielessIdentity();
15
30
  const enabled = computeEnabled(disabled, ignoreLocalhost);
16
31
  const resolveDomain = () => domain || (typeof window !== "undefined" ? window.location.hostname : "");
17
- const trackEvent = async (eventName, data = {}) => {
32
+ const sendEvent = async (eventName, data = {}) => {
18
33
  if (!enabled)
19
34
  return;
20
35
  await sendAnalytics("event", {
@@ -26,10 +41,26 @@ export function createAnalytics(options = {}) {
26
41
  event_data: data,
27
42
  }, "POST", basePath, ingestKey);
28
43
  };
44
+ // Checks `enabled` before reading the page, so a call while rendering on
45
+ // the server does nothing, like the other tracking methods.
46
+ const trackNotFound = async (data = {}) => {
47
+ if (!enabled)
48
+ return;
49
+ await trackEvent(NOT_FOUND_EVENT, notFoundEventData(data));
50
+ };
51
+ // Created before the first page view so that page view is checked too.
52
+ const notFoundWatcher = enabled && autoTrackNotFound
53
+ ? new NotFoundMarkerWatcher(() => void trackNotFound())
54
+ : null;
55
+ if (notFoundWatcher)
56
+ cleanups.push(() => notFoundWatcher.cancel());
57
+ // The last page view in flight: identify waits for it, because a first
58
+ // visit's visitor only exists once its first event has been recorded.
59
+ let pendingPageview = Promise.resolve();
29
60
  const trackPageview = () => {
30
61
  if (!enabled)
31
62
  return;
32
- void sendAnalytics("event", {
63
+ pendingPageview = sendAnalytics("event", {
33
64
  event_name: "page_view",
34
65
  request_query: window.location.search,
35
66
  request_path: window.location.pathname,
@@ -41,13 +72,94 @@ export function createAnalytics(options = {}) {
41
72
  timestamp: new Date().toISOString(),
42
73
  },
43
74
  }, "POST", basePath, ingestKey);
75
+ notFoundWatcher?.afterPageview();
76
+ };
77
+ // Flags work wherever the page is served by Temps, including when
78
+ // analytics is off for localhost; only `disabled` turns them off. Exposure
79
+ // events need analytics, so they are only sent when it is on.
80
+ const flags = new FeatureFlags({
81
+ ...flagOptions,
82
+ basePath,
83
+ disabled,
84
+ onExposure: (exposure) => {
85
+ if (enabled)
86
+ void sendEvent("flag_exposure", exposureEventData(exposure));
87
+ },
88
+ });
89
+ // Surveys record answers as analytics events, so they need analytics on.
90
+ const surveysEnabled = enabled && surveyOptions.enabled === true;
91
+ const autoShowSurveys = surveysEnabled && surveyOptions.autoShow !== false;
92
+ const surveys = new Surveys({
93
+ basePath,
94
+ key: surveyOptions.key,
95
+ attributes: surveyOptions.attributes,
96
+ onError: surveyOptions.onError,
97
+ disabled: !surveysEnabled,
98
+ onEvent: (name, data) => {
99
+ void sendEvent(name, data);
100
+ },
101
+ });
102
+ let openSurvey = null;
103
+ // Set by destroy(): a delivery request still in flight must not open a
104
+ // widget after cleanup has run.
105
+ let destroyed = false;
106
+ const showSurvey = async (event) => {
107
+ if (!autoShowSurveys || openSurvey || destroyed)
108
+ return;
109
+ await surveys.load();
110
+ if (openSurvey || destroyed)
111
+ return;
112
+ const next = surveys.eligible(window.location.pathname, event)[0];
113
+ if (!next)
114
+ return;
115
+ surveys.markShown(next);
116
+ // The card stays owned until it has left the page, thank-you message
117
+ // included, so a later event cannot open a second one over it and
118
+ // `destroy()` can still remove it.
119
+ let closed = false;
120
+ const close = renderSurveyWidget(next, {
121
+ onSubmit: (answers) => {
122
+ const result = surveys.submit(next, answers);
123
+ return result.ok ? null : result.errors;
124
+ },
125
+ onDismiss: () => surveys.dismiss(next),
126
+ onClosed: () => {
127
+ closed = true;
128
+ if (openSurvey === closeThis)
129
+ openSurvey = null;
130
+ },
131
+ });
132
+ const closeThis = () => close();
133
+ if (!closed)
134
+ openSurvey = closeThis;
135
+ };
136
+ cleanups.push(() => {
137
+ destroyed = true;
138
+ openSurvey?.();
139
+ });
140
+ const trackEvent = async (eventName, data = {}) => {
141
+ // A survey triggered by this event is shown without waiting for the send.
142
+ if (!eventName.startsWith("survey_"))
143
+ void showSurvey(eventName);
144
+ await sendEvent(eventName, data);
44
145
  };
45
- const identify = async () => {
46
- // Placeholder for SDK parity; implement when identity endpoint is available.
146
+ const identify = async (userId, traits) => {
147
+ if (!enabled) {
148
+ return { applied: false, outcome: "disabled", message: "Analytics is disabled on this page." };
149
+ }
150
+ return identifyVisitor({ basePath, ingestKey, userId, traits, ready: pendingPageview });
151
+ };
152
+ const reset = async () => {
153
+ if (!enabled)
154
+ return;
155
+ await resetVisitor({ basePath, ingestKey });
47
156
  };
48
157
  if (enabled) {
49
158
  if (autoTrackPageviews) {
50
- cleanups.push(setupPageviewTracking(trackPageview));
159
+ cleanups.push(setupPageviewTracking(() => {
160
+ trackPageview();
161
+ void showSurvey();
162
+ }));
51
163
  }
52
164
  if (autoTrackEngagement) {
53
165
  const tracker = new EngagementTracker({
@@ -68,8 +180,25 @@ export function createAnalytics(options = {}) {
68
180
  cleanups.push(() => speed.destroy());
69
181
  }
70
182
  cleanups.push(setupClickDelegation(trackEvent));
183
+ cleanups.push(setupLinkTracking({ autoTrackOutboundLinks, autoTrackFileDownloads, fileDownloadExtensions }, (eventName, data) => {
184
+ sendAnalyticsReliable("event", {
185
+ event_name: eventName,
186
+ request_query: window.location.search,
187
+ request_path: window.location.pathname,
188
+ domain: resolveDomain(),
189
+ language: navigator.language,
190
+ event_data: data,
191
+ }, basePath, ingestKey);
192
+ }));
193
+ // Without automatic pageviews, surveys are still offered on load.
194
+ if (!autoTrackPageviews)
195
+ void showSurvey();
196
+ }
197
+ if (!recordingAllowed() && enableSessionRecording) {
198
+ // eslint-disable-next-line no-console
199
+ console.warn("[temps] Session recording is off in cookieless mode: a replay needs a visitor id stored on the device.");
71
200
  }
72
- const recorder = enabled && enableSessionRecording
201
+ const recorder = enabled && enableSessionRecording && recordingAllowed()
73
202
  ? new SessionRecorder({
74
203
  basePath,
75
204
  ingestKey,
@@ -82,16 +211,35 @@ export function createAnalytics(options = {}) {
82
211
  cleanups.push(() => recorder.destroy());
83
212
  // Runtime-controlled recorder handle for enable/disable after init
84
213
  let runtimeRecorder = recorder;
214
+ // Another instance switching the page to cookieless ends this one's replay
215
+ // and drops what it has not uploaded yet.
216
+ cleanups.push(onCookielessIdentity(() => {
217
+ runtimeRecorder?.discard();
218
+ runtimeRecorder = null;
219
+ }));
220
+ // `reset()` (from any instance) gives the page a new visitor: the replay
221
+ // in progress ends, and a new one starts once the server confirmed it.
222
+ cleanups.push(onIdentityReset((phase) => {
223
+ if (phase === "started")
224
+ runtimeRecorder?.endForReset();
225
+ else
226
+ runtimeRecorder?.resumeAfterReset();
227
+ }));
85
228
  return {
86
229
  get enabled() {
87
230
  return enabled;
88
231
  },
89
232
  ingestKey,
233
+ flags,
234
+ surveys,
90
235
  trackEvent,
91
236
  trackPageview,
237
+ trackNotFound,
92
238
  identify,
239
+ reset,
240
+ getVisitorId: getStoredVisitorId,
93
241
  enableSessionRecording() {
94
- if (!enabled)
242
+ if (!enabled || !recordingAllowed())
95
243
  return;
96
244
  if (runtimeRecorder) {
97
245
  runtimeRecorder.start();
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Events the tracker emits without any code from the site owner beyond
3
+ * installing it (ADR 109 D1): clicks on links to other sites, clicks on file
4
+ * downloads, and pages the site marks as "not found".
5
+ *
6
+ * They are ordinary events. They show up in the event list and event detail
7
+ * pages like any `trackEvent()` call, and can be used as funnel steps and
8
+ * conversion goals with no extra work.
9
+ */
10
+ import type { JsonValue } from "./types";
11
+ /** Event emitted when a visitor clicks a link to another host. */
12
+ export declare const OUTBOUND_CLICK_EVENT = "outbound_click";
13
+ /** Event emitted when a visitor clicks a link to a downloadable file. */
14
+ export declare const FILE_DOWNLOAD_EVENT = "file_download";
15
+ /** Event emitted for a page the site reports as missing. */
16
+ export declare const NOT_FOUND_EVENT = "not_found";
17
+ /**
18
+ * Attribute that marks a rendered page as a "not found" page. Put it on any
19
+ * element of your 404 page, e.g. `<main data-temps-404>`.
20
+ */
21
+ export declare const NOT_FOUND_MARKER_ATTRIBUTE = "data-temps-404";
22
+ /**
23
+ * Extensions counted as file downloads when `fileDownloadExtensions` is not
24
+ * set: documents, spreadsheets and slides, archives, audio and video, disk
25
+ * images and installers. Spread it to extend rather than replace:
26
+ * `fileDownloadExtensions: [...DEFAULT_FILE_DOWNLOAD_EXTENSIONS, "stl"]`.
27
+ */
28
+ export declare const DEFAULT_FILE_DOWNLOAD_EXTENSIONS: readonly string[];
29
+ /**
30
+ * How long after a page view the tracker looks for the 404 marker a second
31
+ * time. Single-page apps render their "not found" view after the route change
32
+ * that produced the page view, so the first check usually runs too early.
33
+ */
34
+ export declare const NOT_FOUND_RECHECK_DELAY_MS = 1000;
35
+ export interface AutoTrackOptions {
36
+ /**
37
+ * Emit `outbound_click` when a visitor clicks a link to another host.
38
+ * Defaults to true.
39
+ */
40
+ autoTrackOutboundLinks?: boolean;
41
+ /**
42
+ * Emit `file_download` when a visitor clicks a link whose path ends in one
43
+ * of `fileDownloadExtensions`, or that carries the `download` attribute.
44
+ * Defaults to true.
45
+ */
46
+ autoTrackFileDownloads?: boolean;
47
+ /**
48
+ * File extensions (without the dot, case-insensitive) counted as downloads.
49
+ * Replaces the default list; defaults to `DEFAULT_FILE_DOWNLOAD_EXTENSIONS`.
50
+ */
51
+ fileDownloadExtensions?: readonly string[];
52
+ /**
53
+ * Emit `not_found` after a page view when the page contains an element with
54
+ * the `data-temps-404` attribute. Defaults to true; pages without the marker
55
+ * are unaffected. `trackNotFound()` works either way.
56
+ */
57
+ autoTrackNotFound?: boolean;
58
+ }
59
+ /** What a link click resolves to, or `null` when it is not tracked. */
60
+ export interface LinkClassification {
61
+ eventName: typeof OUTBOUND_CLICK_EVENT | typeof FILE_DOWNLOAD_EVENT;
62
+ data: Record<string, JsonValue>;
63
+ }
64
+ /** The parts of a link the classifier needs; an `HTMLAnchorElement` fits. */
65
+ export interface LinkLike {
66
+ href: string;
67
+ hasAttribute(name: string): boolean;
68
+ }
69
+ export interface ClassifyLinkOptions {
70
+ trackOutboundLinks: boolean;
71
+ trackFileDownloads: boolean;
72
+ fileDownloadExtensions: readonly string[];
73
+ }
74
+ /** Lower-cased extension of the last path segment, or `null` when it has none. */
75
+ export declare function pathExtension(pathname: string): string | null;
76
+ /**
77
+ * Decide whether a click on `link` is a file download, an outbound click, or
78
+ * neither. A download takes precedence: a PDF on a CDN is reported once, as a
79
+ * download, rather than twice. Only `http:` and `https:` links are tracked;
80
+ * `mailto:`, `tel:`, `javascript:` and `blob:` links are ignored.
81
+ */
82
+ export declare function classifyLink(link: LinkLike, currentHost: string, options: ClassifyLinkOptions): LinkClassification | null;
83
+ /**
84
+ * Install one delegated listener on the document for outbound links and file
85
+ * downloads. No per-link handlers: links added later are covered too. The
86
+ * same handler also receives `auxclick`, because a middle click opens the
87
+ * link in a new tab without firing `click`.
88
+ *
89
+ * `send` must survive the navigation the click starts, so callers pass a
90
+ * beacon-based sender (`sendAnalyticsReliable`).
91
+ */
92
+ export declare function setupLinkTracking(options: AutoTrackOptions, send: (eventName: string, data: Record<string, JsonValue>) => void): () => void;
93
+ /** Properties of a `not_found` event. `path` is the page the visitor asked for. */
94
+ export declare function notFoundEventData(extra?: Record<string, JsonValue>): Record<string, JsonValue>;
95
+ /** Whether the current document carries the `data-temps-404` marker. */
96
+ export declare function hasNotFoundMarker(): boolean;
97
+ /**
98
+ * Watches for the 404 marker after each page view. Call `afterPageview()`
99
+ * whenever a page view is recorded; it emits `not_found` at most once for
100
+ * that page view, checking immediately and once more after
101
+ * `NOT_FOUND_RECHECK_DELAY_MS` for apps that render the 404 view late.
102
+ *
103
+ * On an in-app navigation the page view is recorded when the URL changes,
104
+ * before the router has replaced the old view, so a marker already in the
105
+ * document at that moment belongs to the page being left and is ignored. Only
106
+ * the first page view of a document counts a marker that is already there.
107
+ */
108
+ export declare class NotFoundMarkerWatcher {
109
+ private readonly report;
110
+ private timer;
111
+ private reported;
112
+ /**
113
+ * Markers seen while the previous page view was current: a view the router
114
+ * has not torn down yet when the next page view is recorded. A marker the
115
+ * new route rendered before its page view (a manual `trackPageview()` in
116
+ * an effect) was never seen, so it still counts.
117
+ */
118
+ private previousMarkers;
119
+ private observedMarkers;
120
+ private path;
121
+ constructor(report: () => void);
122
+ afterPageview(): void;
123
+ /** Stop any pending re-check. */
124
+ cancel(): void;
125
+ private check;
126
+ }
127
+ //# sourceMappingURL=AutoTracking.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AutoTracking.d.ts","sourceRoot":"","sources":["../src/AutoTracking.ts"],"names":[],"mappings":"AAGA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAEzC,kEAAkE;AAClE,eAAO,MAAM,oBAAoB,mBAAmB,CAAC;AACrD,yEAAyE;AACzE,eAAO,MAAM,mBAAmB,kBAAkB,CAAC;AACnD,4DAA4D;AAC5D,eAAO,MAAM,eAAe,cAAc,CAAC;AAC3C;;;GAGG;AACH,eAAO,MAAM,0BAA0B,mBAAmB,CAAC;AAE3D;;;;;GAKG;AACH,eAAO,MAAM,gCAAgC,EAAE,SAAS,MAAM,EAW7D,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,0BAA0B,OAAO,CAAC;AAE/C,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,sBAAsB,CAAC,EAAE,OAAO,CAAC;IACjC;;;;OAIG;IACH,sBAAsB,CAAC,EAAE,OAAO,CAAC;IACjC;;;OAGG;IACH,sBAAsB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3C;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED,uEAAuE;AACvE,MAAM,WAAW,kBAAkB;IACjC,SAAS,EAAE,OAAO,oBAAoB,GAAG,OAAO,mBAAmB,CAAC;IACpE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;CACjC;AAED,6EAA6E;AAC7E,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;CACrC;AAED,MAAM,WAAW,mBAAmB;IAClC,kBAAkB,EAAE,OAAO,CAAC;IAC5B,kBAAkB,EAAE,OAAO,CAAC;IAC5B,sBAAsB,EAAE,SAAS,MAAM,EAAE,CAAC;CAC3C;AAYD,kFAAkF;AAClF,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAK7D;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAC1B,IAAI,EAAE,QAAQ,EACd,WAAW,EAAE,MAAM,EACnB,OAAO,EAAE,mBAAmB,GAC3B,kBAAkB,GAAG,IAAI,CA8B3B;AAED;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,gBAAgB,EACzB,IAAI,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,KAAK,IAAI,GACjE,MAAM,IAAI,CA0BZ;AAED,mFAAmF;AACnF,wBAAgB,iBAAiB,CAAC,KAAK,GAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAM,GAAG,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAQlG;AAED,wEAAwE;AACxE,wBAAgB,iBAAiB,IAAI,OAAO,CAE3C;AAED;;;;;;;;;;GAUG;AACH,qBAAa,qBAAqB;IAapB,OAAO,CAAC,QAAQ,CAAC,MAAM;IAZnC,OAAO,CAAC,KAAK,CAA8C;IAC3D,OAAO,CAAC,QAAQ,CAAS;IACzB;;;;;OAKG;IACH,OAAO,CAAC,eAAe,CAA2B;IAClD,OAAO,CAAC,eAAe,CAA2B;IAClD,OAAO,CAAC,IAAI,CAAM;gBAEW,MAAM,EAAE,MAAM,IAAI;IAE/C,aAAa,IAAI,IAAI;IAarB,iCAAiC;IACjC,MAAM,IAAI,IAAI;IAOd,OAAO,CAAC,KAAK;CAYd"}
@@ -0,0 +1,207 @@
1
+ // SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ // SPDX-License-Identifier: MIT OR Apache-2.0
3
+ /** Event emitted when a visitor clicks a link to another host. */
4
+ export const OUTBOUND_CLICK_EVENT = "outbound_click";
5
+ /** Event emitted when a visitor clicks a link to a downloadable file. */
6
+ export const FILE_DOWNLOAD_EVENT = "file_download";
7
+ /** Event emitted for a page the site reports as missing. */
8
+ export const NOT_FOUND_EVENT = "not_found";
9
+ /**
10
+ * Attribute that marks a rendered page as a "not found" page. Put it on any
11
+ * element of your 404 page, e.g. `<main data-temps-404>`.
12
+ */
13
+ export const NOT_FOUND_MARKER_ATTRIBUTE = "data-temps-404";
14
+ /**
15
+ * Extensions counted as file downloads when `fileDownloadExtensions` is not
16
+ * set: documents, spreadsheets and slides, archives, audio and video, disk
17
+ * images and installers. Spread it to extend rather than replace:
18
+ * `fileDownloadExtensions: [...DEFAULT_FILE_DOWNLOAD_EXTENSIONS, "stl"]`.
19
+ */
20
+ export const DEFAULT_FILE_DOWNLOAD_EXTENSIONS = [
21
+ // Documents
22
+ "pdf", "doc", "docx", "odt", "rtf", "txt", "md", "epub",
23
+ // Spreadsheets and slides
24
+ "xls", "xlsx", "ods", "csv", "ppt", "pptx", "pps", "odp", "key",
25
+ // Archives
26
+ "zip", "7z", "rar", "tar", "gz", "tgz", "bz2", "xz",
27
+ // Audio and video
28
+ "mp3", "wav", "wma", "flac", "midi", "mp4", "mov", "avi", "wmv", "mpeg", "webm", "mkv",
29
+ // Disk images and installers
30
+ "dmg", "iso", "exe", "msi", "pkg", "deb", "rpm", "apk", "appimage",
31
+ ];
32
+ /**
33
+ * How long after a page view the tracker looks for the 404 marker a second
34
+ * time. Single-page apps render their "not found" view after the route change
35
+ * that produced the page view, so the first check usually runs too early.
36
+ */
37
+ export const NOT_FOUND_RECHECK_DELAY_MS = 1000;
38
+ /**
39
+ * The recorded URL: origin and path only. Query strings and fragments are
40
+ * dropped on purpose. Download links are often pre-signed object-store URLs
41
+ * whose query string is a credential, and outbound query strings mostly carry
42
+ * tracking parameters that would split one destination into thousands of rows.
43
+ */
44
+ function recordedUrl(url) {
45
+ return `${url.origin}${url.pathname}`;
46
+ }
47
+ /** Lower-cased extension of the last path segment, or `null` when it has none. */
48
+ export function pathExtension(pathname) {
49
+ const segment = pathname.slice(pathname.lastIndexOf("/") + 1);
50
+ const dot = segment.lastIndexOf(".");
51
+ if (dot <= 0 || dot === segment.length - 1)
52
+ return null;
53
+ return segment.slice(dot + 1).toLowerCase();
54
+ }
55
+ /**
56
+ * Decide whether a click on `link` is a file download, an outbound click, or
57
+ * neither. A download takes precedence: a PDF on a CDN is reported once, as a
58
+ * download, rather than twice. Only `http:` and `https:` links are tracked;
59
+ * `mailto:`, `tel:`, `javascript:` and `blob:` links are ignored.
60
+ */
61
+ export function classifyLink(link, currentHost, options) {
62
+ let url;
63
+ try {
64
+ url = new URL(link.href);
65
+ }
66
+ catch {
67
+ return null;
68
+ }
69
+ if (url.protocol !== "http:" && url.protocol !== "https:")
70
+ return null;
71
+ if (options.trackFileDownloads) {
72
+ const extension = pathExtension(url.pathname);
73
+ const listed = extension !== null &&
74
+ options.fileDownloadExtensions.some((candidate) => candidate.toLowerCase() === extension);
75
+ if (listed || link.hasAttribute("download")) {
76
+ return {
77
+ eventName: FILE_DOWNLOAD_EVENT,
78
+ data: { url: recordedUrl(url), extension: extension ?? "", host: url.host },
79
+ };
80
+ }
81
+ }
82
+ if (options.trackOutboundLinks && url.host !== currentHost) {
83
+ return {
84
+ eventName: OUTBOUND_CLICK_EVENT,
85
+ data: { url: recordedUrl(url), host: url.host },
86
+ };
87
+ }
88
+ return null;
89
+ }
90
+ /**
91
+ * Install one delegated listener on the document for outbound links and file
92
+ * downloads. No per-link handlers: links added later are covered too. The
93
+ * same handler also receives `auxclick`, because a middle click opens the
94
+ * link in a new tab without firing `click`.
95
+ *
96
+ * `send` must survive the navigation the click starts, so callers pass a
97
+ * beacon-based sender (`sendAnalyticsReliable`).
98
+ */
99
+ export function setupLinkTracking(options, send) {
100
+ const classify = {
101
+ trackOutboundLinks: options.autoTrackOutboundLinks ?? true,
102
+ trackFileDownloads: options.autoTrackFileDownloads ?? true,
103
+ fileDownloadExtensions: options.fileDownloadExtensions ?? DEFAULT_FILE_DOWNLOAD_EXTENSIONS,
104
+ };
105
+ if (!classify.trackOutboundLinks && !classify.trackFileDownloads) {
106
+ return () => { };
107
+ }
108
+ const onClick = (event) => {
109
+ // Primary click, or a middle click (auxclick). Right clicks open a menu.
110
+ if (event.type === "auxclick" ? event.button !== 1 : event.button !== 0)
111
+ return;
112
+ const target = event.target;
113
+ const link = target?.closest?.("a[href]");
114
+ if (!link || !("href" in link))
115
+ return;
116
+ const result = classifyLink(link, window.location.host, classify);
117
+ if (result)
118
+ send(result.eventName, result.data);
119
+ };
120
+ document.addEventListener("click", onClick);
121
+ document.addEventListener("auxclick", onClick);
122
+ return () => {
123
+ document.removeEventListener("click", onClick);
124
+ document.removeEventListener("auxclick", onClick);
125
+ };
126
+ }
127
+ /** Properties of a `not_found` event. `path` is the page the visitor asked for. */
128
+ export function notFoundEventData(extra = {}) {
129
+ // Outside a browser there is no page to describe.
130
+ if (typeof window === "undefined" || typeof document === "undefined")
131
+ return { ...extra };
132
+ return {
133
+ path: window.location.pathname,
134
+ referrer: document.referrer,
135
+ ...extra,
136
+ };
137
+ }
138
+ /** Whether the current document carries the `data-temps-404` marker. */
139
+ export function hasNotFoundMarker() {
140
+ return document.querySelector(`[${NOT_FOUND_MARKER_ATTRIBUTE}]`) !== null;
141
+ }
142
+ /**
143
+ * Watches for the 404 marker after each page view. Call `afterPageview()`
144
+ * whenever a page view is recorded; it emits `not_found` at most once for
145
+ * that page view, checking immediately and once more after
146
+ * `NOT_FOUND_RECHECK_DELAY_MS` for apps that render the 404 view late.
147
+ *
148
+ * On an in-app navigation the page view is recorded when the URL changes,
149
+ * before the router has replaced the old view, so a marker already in the
150
+ * document at that moment belongs to the page being left and is ignored. Only
151
+ * the first page view of a document counts a marker that is already there.
152
+ */
153
+ export class NotFoundMarkerWatcher {
154
+ constructor(report) {
155
+ this.report = report;
156
+ this.timer = null;
157
+ this.reported = false;
158
+ /**
159
+ * Markers seen while the previous page view was current: a view the router
160
+ * has not torn down yet when the next page view is recorded. A marker the
161
+ * new route rendered before its page view (a manual `trackPageview()` in
162
+ * an effect) was never seen, so it still counts.
163
+ */
164
+ this.previousMarkers = new Set();
165
+ this.observedMarkers = new Set();
166
+ this.path = "";
167
+ }
168
+ afterPageview() {
169
+ this.cancel();
170
+ this.reported = false;
171
+ this.path = window.location.pathname;
172
+ this.previousMarkers = this.observedMarkers;
173
+ this.observedMarkers = new Set();
174
+ if (this.check())
175
+ return;
176
+ this.timer = setTimeout(() => {
177
+ this.timer = null;
178
+ this.check();
179
+ }, NOT_FOUND_RECHECK_DELAY_MS);
180
+ }
181
+ /** Stop any pending re-check. */
182
+ cancel() {
183
+ if (this.timer !== null) {
184
+ clearTimeout(this.timer);
185
+ this.timer = null;
186
+ }
187
+ }
188
+ check() {
189
+ if (this.reported)
190
+ return false;
191
+ // The visitor moved on; that navigation records its own page view.
192
+ if (window.location.pathname !== this.path)
193
+ return false;
194
+ const markers = markerElements();
195
+ for (const element of markers)
196
+ this.observedMarkers.add(element);
197
+ const fresh = markers.some((element) => !this.previousMarkers.has(element));
198
+ if (!fresh)
199
+ return false;
200
+ this.reported = true;
201
+ this.report();
202
+ return true;
203
+ }
204
+ }
205
+ function markerElements() {
206
+ return Array.from(document.querySelectorAll(`[${NOT_FOUND_MARKER_ATTRIBUTE}]`));
207
+ }