@haakco/custd-sdk 2.4.0 → 3.71.2
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.
- package/LICENSE +21 -0
- package/README.md +586 -40
- package/dist/admin-accounting-evidence.d.ts +48 -0
- package/dist/admin-accounting-evidence.js +24 -0
- package/dist/admin-app-releases.d.ts +116 -0
- package/dist/admin-app-releases.js +8 -0
- package/dist/admin-apps.d.ts +120 -0
- package/dist/admin-apps.js +47 -0
- package/dist/admin-auth-project-domain.d.ts +125 -0
- package/dist/admin-auth-project-domain.js +37 -0
- package/dist/admin-auth-projects.d.ts +989 -0
- package/dist/admin-auth-projects.js +527 -0
- package/dist/admin-campaign-email.d.ts +120 -0
- package/dist/admin-campaign-email.js +64 -0
- package/dist/admin-client-setup.d.ts +22 -0
- package/dist/admin-client-setup.js +11 -1
- package/dist/admin-data-scopes.d.ts +93 -0
- package/dist/admin-data-scopes.js +154 -0
- package/dist/admin-email-relay.d.ts +66 -0
- package/dist/admin-email-relay.js +25 -0
- package/dist/admin-environment-policy.d.ts +32 -0
- package/dist/admin-environment-policy.js +26 -0
- package/dist/admin-error-issues.d.ts +91 -0
- package/dist/admin-error-issues.js +52 -0
- package/dist/admin-event-types.d.ts +57 -0
- package/dist/admin-event-types.js +28 -0
- package/dist/admin-impersonation.d.ts +48 -0
- package/dist/admin-impersonation.js +27 -0
- package/dist/admin-ingest-claims.d.ts +35 -0
- package/dist/admin-ingest-claims.js +26 -0
- package/dist/admin-managed-audit.d.ts +13 -0
- package/dist/admin-managed-audit.js +13 -0
- package/dist/admin-measurement-projects.d.ts +166 -0
- package/dist/admin-measurement-projects.js +120 -0
- package/dist/admin-notification-destinations.d.ts +31 -0
- package/dist/admin-notification-destinations.js +19 -0
- package/dist/admin-notification-webhooks.d.ts +64 -0
- package/dist/admin-notification-webhooks.js +42 -0
- package/dist/admin-oauth-client-admissions.d.ts +65 -0
- package/dist/admin-oauth-client-admissions.js +46 -0
- package/dist/admin-offboarding.d.ts +20 -6
- package/dist/admin-offboarding.js +27 -6
- package/dist/admin-predictions.d.ts +127 -8
- package/dist/admin-predictions.js +22 -12
- package/dist/admin-privacy-erasures.d.ts +24 -12
- package/dist/admin-privacy-erasures.js +3 -2
- package/dist/admin-retention.d.ts +72 -24
- package/dist/admin-retention.js +38 -13
- package/dist/admin-rls.d.ts +94 -0
- package/dist/admin-rls.js +33 -0
- package/dist/admin-sdk-usage.d.ts +41 -0
- package/dist/admin-sdk-usage.js +23 -0
- package/dist/admin-site-ai.d.ts +72 -0
- package/dist/admin-site-ai.js +1 -0
- package/dist/admin-site-analytics.d.ts +52 -0
- package/dist/admin-site-analytics.js +14 -0
- package/dist/admin-site-audit-pages.d.ts +76 -0
- package/dist/admin-site-audit-pages.js +27 -0
- package/dist/admin-site-campaign-links.d.ts +40 -0
- package/dist/admin-site-campaign-links.js +9 -0
- package/dist/admin-site-domains.d.ts +733 -0
- package/dist/admin-site-domains.js +768 -0
- package/dist/admin-site-export.d.ts +76 -0
- package/dist/admin-site-export.js +15 -0
- package/dist/admin-site-insights-tasks.d.ts +44 -0
- package/dist/admin-site-insights-tasks.js +28 -0
- package/dist/admin-site-insights.d.ts +527 -0
- package/dist/admin-site-insights.js +61 -0
- package/dist/admin-site-links.d.ts +87 -0
- package/dist/admin-site-links.js +16 -0
- package/dist/admin-site-monitors.d.ts +110 -0
- package/dist/admin-site-monitors.js +25 -0
- package/dist/admin-site-next-actions.d.ts +93 -0
- package/dist/admin-site-next-actions.js +36 -0
- package/dist/admin-site-page-queries.d.ts +63 -0
- package/dist/admin-site-page-queries.js +20 -0
- package/dist/admin-site-rankings.d.ts +98 -0
- package/dist/admin-site-rankings.js +46 -0
- package/dist/admin-site-regional-trends.d.ts +30 -0
- package/dist/admin-site-regional-trends.js +1 -0
- package/dist/admin-site-saved-reports.d.ts +45 -0
- package/dist/admin-site-saved-reports.js +13 -0
- package/dist/admin-site-search-pool.d.ts +77 -0
- package/dist/admin-site-search-pool.js +41 -0
- package/dist/admin-site-search-value.d.ts +97 -0
- package/dist/admin-site-search-value.js +29 -0
- package/dist/admin-site-status-page.d.ts +57 -0
- package/dist/admin-site-status-page.js +10 -0
- package/dist/admin-site-traffic.d.ts +145 -0
- package/dist/admin-site-traffic.js +32 -0
- package/dist/admin-site-web-data.d.ts +258 -0
- package/dist/admin-site-web-data.js +60 -0
- package/dist/admin-subject-exports.d.ts +58 -27
- package/dist/admin-subject-exports.js +32 -16
- package/dist/admin-support-access.d.ts +32 -0
- package/dist/admin-support-access.js +21 -0
- package/dist/admin-system.d.ts +283 -0
- package/dist/admin-system.js +65 -0
- package/dist/admin-tenant-storage.d.ts +22 -14
- package/dist/admin-tenant-storage.js +13 -14
- package/dist/admin-timeplans.d.ts +276 -2
- package/dist/admin-timeplans.js +54 -0
- package/dist/admin-uncertainty-models.d.ts +42 -0
- package/dist/admin-uncertainty-models.js +53 -0
- package/dist/admin-usage.d.ts +124 -0
- package/dist/admin-usage.js +169 -0
- package/dist/admin-users.d.ts +124 -0
- package/dist/admin-users.js +82 -0
- package/dist/admin-workflow-timings.d.ts +367 -0
- package/dist/admin-workflow-timings.js +117 -0
- package/dist/analytics-events.d.ts +82 -0
- package/dist/analytics-events.js +157 -0
- package/dist/analytics-reads.d.ts +81 -0
- package/dist/analytics-reads.js +5 -0
- package/dist/app-account.d.ts +84 -0
- package/dist/app-account.js +177 -0
- package/dist/app-alerts.d.ts +120 -0
- package/dist/app-alerts.js +44 -0
- package/dist/app-items.d.ts +786 -0
- package/dist/app-items.js +524 -0
- package/dist/app-live.d.ts +84 -0
- package/dist/app-live.js +228 -0
- package/dist/app-meetings.d.ts +95 -0
- package/dist/app-meetings.js +26 -0
- package/dist/app-models.d.ts +271 -0
- package/dist/app-models.js +83 -0
- package/dist/app-push.d.ts +64 -0
- package/dist/app-push.js +178 -0
- package/dist/backend-lifecycle.d.ts +2 -2
- package/dist/browser-manifest.json +5 -5
- package/dist/browser-script-BWnwDjAC.js +711 -0
- package/dist/browser-sign-in.d.ts +153 -0
- package/dist/browser-sign-in.js +410 -0
- package/dist/browser-tracker.d.ts +95 -0
- package/dist/browser-tracker.js +362 -40
- package/dist/browser-web-vitals.d.ts +22 -0
- package/dist/browser-web-vitals.js +116 -0
- package/dist/browser.d.ts +9 -0
- package/dist/browser.js +9 -0
- package/dist/download-stream.d.ts +16 -0
- package/dist/download-stream.js +55 -0
- package/dist/error-capture.d.ts +62 -0
- package/dist/error-capture.js +168 -0
- package/dist/hosted-app.d.ts +115 -0
- package/dist/hosted-app.js +275 -0
- package/dist/index.d.ts +1168 -154
- package/dist/index.js +682 -162
- package/dist/ingest-operations.d.ts +483 -0
- package/dist/ingest-operations.js +154 -0
- package/dist/measurement.d.ts +164 -0
- package/dist/measurement.js +104 -0
- package/dist/parsers.d.ts +149 -0
- package/dist/parsers.js +115 -0
- package/dist/public-reads.d.ts +79 -0
- package/dist/public-reads.js +57 -0
- package/dist/reporting-catalogue.d.ts +264 -0
- package/dist/reporting-catalogue.js +5 -0
- package/dist/response-lists.d.ts +16 -0
- package/dist/response-lists.generated.d.ts +7 -0
- package/dist/response-lists.generated.js +1927 -0
- package/dist/response-lists.js +70 -0
- package/dist/response-validation.d.ts +30 -0
- package/dist/response-validation.js +94 -0
- package/dist/schema-registry.d.ts +45 -0
- package/dist/schema-registry.js +9 -0
- package/dist/secure-url.d.ts +4 -0
- package/dist/secure-url.js +23 -0
- package/dist/site-ai-owner.d.ts +34 -0
- package/dist/site-ai-owner.js +99 -0
- package/dist/site-monitor-reports.d.ts +15 -0
- package/dist/site-monitor-reports.js +87 -0
- package/dist/testing/fake-custd.d.ts +150 -0
- package/dist/testing/fake-custd.js +842 -0
- package/dist/testing/fake-results.d.ts +30 -0
- package/dist/testing/fake-results.js +293 -0
- package/dist/testing.d.ts +2 -0
- package/dist/testing.js +3 -0
- package/dist/version.d.ts +2 -2
- package/dist/version.js +1 -1
- package/package.json +25 -14
- package/dist/browser-script-BvgjdZSO.js +0 -429
- package/dist/fixtures.d.ts +0 -10
- package/dist/fixtures.js +0 -57
package/dist/browser-tracker.js
CHANGED
|
@@ -1,11 +1,50 @@
|
|
|
1
|
+
import { startWebVitals } from "./browser-web-vitals.js";
|
|
1
2
|
import { applyEnvironmentLabel, LocalStorageQueueStorage, MemoryQueueStorage, normalizeRetryOptions, prepareEvent, RetryableError, validateBrowserEvent, withRetry, } from "./index.js";
|
|
3
|
+
import { emptySiteConfigNullLists } from "./response-lists.js";
|
|
4
|
+
import { isLocalHostname } from "./secure-url.js";
|
|
2
5
|
const defaultSchemaVersion = "1.0.0";
|
|
6
|
+
const pageViewEventType = "page-view";
|
|
7
|
+
const webVitalsEventType = "web-vitals";
|
|
8
|
+
const aiAssistantReferrerClass = "ai-assistant";
|
|
9
|
+
/**
|
|
10
|
+
* AI assistants whose links bring visitors, by referrer hostname, mapped to the
|
|
11
|
+
* assistant name sent as `aiAssistant`. A page view only ever carries this class
|
|
12
|
+
* and name, never the referrer URL itself.
|
|
13
|
+
*/
|
|
14
|
+
export const aiAssistantReferrers = new Map([
|
|
15
|
+
["chatgpt.com", "chatgpt"],
|
|
16
|
+
["chat.openai.com", "chatgpt"],
|
|
17
|
+
["perplexity.ai", "perplexity"],
|
|
18
|
+
["claude.ai", "claude"],
|
|
19
|
+
["gemini.google.com", "gemini"],
|
|
20
|
+
["bard.google.com", "gemini"],
|
|
21
|
+
["copilot.microsoft.com", "copilot"],
|
|
22
|
+
["chat.deepseek.com", "deepseek"],
|
|
23
|
+
["chat.mistral.ai", "mistral"],
|
|
24
|
+
["grok.com", "grok"],
|
|
25
|
+
["meta.ai", "meta-ai"],
|
|
26
|
+
["you.com", "you"],
|
|
27
|
+
["phind.com", "phind"],
|
|
28
|
+
]);
|
|
29
|
+
const schemaVersionPattern = /^[0-9]+\.[0-9]+\.[0-9]+$/u;
|
|
3
30
|
const maxQueuedGlobalCalls = 1000;
|
|
4
31
|
const redactedPathSegment = "[redacted]";
|
|
5
32
|
const safePathSegment = /^[A-Za-z][A-Za-z0-9._~-]{0,63}$/u;
|
|
6
33
|
const uuidPathSegment = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
|
|
7
34
|
const opaquePathSegment = /^[A-Za-z0-9_-]{24,}$/u;
|
|
8
35
|
const poweredByProjectSlug = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;
|
|
36
|
+
const campaignQueryFields = [
|
|
37
|
+
["utm_source", "utmSource"],
|
|
38
|
+
["utm_medium", "utmMedium"],
|
|
39
|
+
["utm_campaign", "utmCampaign"],
|
|
40
|
+
["utm_term", "utmTerm"],
|
|
41
|
+
["utm_content", "utmContent"],
|
|
42
|
+
];
|
|
43
|
+
const maxCampaignValueLength = 100;
|
|
44
|
+
const safeRoutePathSegment = /^[A-Za-z0-9._~:{}*[\]-]*$/u;
|
|
45
|
+
const maxRoutePathLength = 1024;
|
|
46
|
+
const maxPageTitleLength = 200;
|
|
47
|
+
const retryableCollectorStatuses = new Set([408, 429, 500, 502, 503, 504]);
|
|
9
48
|
export function createBrowserTracker(config) {
|
|
10
49
|
return new DefaultBrowserTracker(config);
|
|
11
50
|
}
|
|
@@ -13,13 +52,31 @@ class DefaultBrowserTracker {
|
|
|
13
52
|
constructor(config) {
|
|
14
53
|
this.queue = [];
|
|
15
54
|
this.installedSpaTracking = false;
|
|
55
|
+
this.lastTrackedPath = null;
|
|
56
|
+
/** The landing page's referral class is sent once; later SPA routes keep the same document referrer. */
|
|
57
|
+
this.referrerClassified = false;
|
|
58
|
+
this.webVitals = null;
|
|
16
59
|
this.originalPushState = null;
|
|
17
60
|
this.originalReplaceState = null;
|
|
18
|
-
this.onlineHandler = () =>
|
|
19
|
-
this.pagehideHandler = () =>
|
|
20
|
-
|
|
61
|
+
this.onlineHandler = () => this.detach("flush", () => this.flush());
|
|
62
|
+
this.pagehideHandler = () => {
|
|
63
|
+
this.enqueueWebVitals();
|
|
64
|
+
this.flushWithKeepalive();
|
|
65
|
+
};
|
|
66
|
+
this.visibilityHandler = () => {
|
|
67
|
+
if (document.visibilityState === "hidden" && this.enqueueWebVitals()) {
|
|
68
|
+
this.flushWithKeepalive();
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
this.popstateHandler = () => this.detachPathChange(() => this.trackPageView());
|
|
21
72
|
this.config = config;
|
|
22
73
|
this.baseUrl = config.baseUrl.replace(/\/$/, "");
|
|
74
|
+
this.schemaVersion = resolveSchemaVersion(config.schemaVersion);
|
|
75
|
+
this.pageViewSchemaVersion =
|
|
76
|
+
config.pageViewSchemaVersion === undefined
|
|
77
|
+
? this.schemaVersion
|
|
78
|
+
: resolveSchemaVersion(config.pageViewSchemaVersion);
|
|
79
|
+
this.labels = { ...(config.labels ?? {}) };
|
|
23
80
|
this.queueStorage = config.queueStorage ?? browserQueueStorage(config.siteUuid, config.persistentQueue === true);
|
|
24
81
|
this.retry = normalizeRetryOptions(config.retry);
|
|
25
82
|
this.maxQueueSize = config.maxQueueSize ?? 1000;
|
|
@@ -33,6 +90,11 @@ class DefaultBrowserTracker {
|
|
|
33
90
|
assertAllowedOrigin(config);
|
|
34
91
|
window.addEventListener("online", this.onlineHandler);
|
|
35
92
|
window.addEventListener("pagehide", this.pagehideHandler);
|
|
93
|
+
if (config.webVitals === true) {
|
|
94
|
+
this.webVitalsPath = this.pageContext().path;
|
|
95
|
+
this.webVitals = startWebVitals();
|
|
96
|
+
window.addEventListener("visibilitychange", this.visibilityHandler);
|
|
97
|
+
}
|
|
36
98
|
}
|
|
37
99
|
async track(eventTypeSlug, payload = {}) {
|
|
38
100
|
if (this.trackingDisabled()) {
|
|
@@ -49,7 +111,12 @@ class DefaultBrowserTracker {
|
|
|
49
111
|
await this.sendEvent(event);
|
|
50
112
|
}
|
|
51
113
|
trackPageView() {
|
|
52
|
-
|
|
114
|
+
this.lastTrackedPath = window.location.pathname;
|
|
115
|
+
const referral = this.trackingDisabled() ? {} : this.landingReferral();
|
|
116
|
+
return this.track("page-view", {
|
|
117
|
+
...campaignAttribution(new URL(window.location.href).searchParams),
|
|
118
|
+
...referral,
|
|
119
|
+
});
|
|
53
120
|
}
|
|
54
121
|
installSpaTracking() {
|
|
55
122
|
if (this.installedSpaTracking) {
|
|
@@ -62,7 +129,7 @@ class DefaultBrowserTracker {
|
|
|
62
129
|
window.history.replaceState = this.wrapHistoryMethod(this.originalReplaceState);
|
|
63
130
|
window.addEventListener("popstate", this.popstateHandler);
|
|
64
131
|
if (this.config.trackInitialPageView !== false) {
|
|
65
|
-
|
|
132
|
+
this.detach("page-view", () => this.trackPageView());
|
|
66
133
|
}
|
|
67
134
|
}
|
|
68
135
|
setConsent(state) {
|
|
@@ -80,8 +147,9 @@ class DefaultBrowserTracker {
|
|
|
80
147
|
return;
|
|
81
148
|
}
|
|
82
149
|
const events = this.queue.splice(0, this.queue.length);
|
|
150
|
+
let outcome;
|
|
83
151
|
try {
|
|
84
|
-
await this.sendBatch(events);
|
|
152
|
+
outcome = await this.sendBatch(events);
|
|
85
153
|
}
|
|
86
154
|
catch (error) {
|
|
87
155
|
this.queue.unshift(...events);
|
|
@@ -89,12 +157,18 @@ class DefaultBrowserTracker {
|
|
|
89
157
|
this.queueStorage.save(this.queue);
|
|
90
158
|
throw error;
|
|
91
159
|
}
|
|
92
|
-
this.
|
|
160
|
+
this.applyBatchOutcome("flush", outcome);
|
|
161
|
+
if (outcome.retryable.length > 0) {
|
|
162
|
+
throw new RetryableCollectorStatusError(outcome.retryableStatus ?? 503);
|
|
163
|
+
}
|
|
93
164
|
}
|
|
94
165
|
close() {
|
|
95
166
|
window.removeEventListener("online", this.onlineHandler);
|
|
96
167
|
window.removeEventListener("pagehide", this.pagehideHandler);
|
|
97
168
|
window.removeEventListener("popstate", this.popstateHandler);
|
|
169
|
+
window.removeEventListener("visibilitychange", this.visibilityHandler);
|
|
170
|
+
this.webVitals?.stop();
|
|
171
|
+
this.webVitals = null;
|
|
98
172
|
if (this.originalPushState) {
|
|
99
173
|
window.history.pushState = this.originalPushState;
|
|
100
174
|
}
|
|
@@ -107,8 +181,11 @@ class DefaultBrowserTracker {
|
|
|
107
181
|
}
|
|
108
182
|
wrapHistoryMethod(original) {
|
|
109
183
|
return ((...args) => {
|
|
184
|
+
const previousPath = window.location.pathname;
|
|
110
185
|
const result = original.apply(window.history, args);
|
|
111
|
-
|
|
186
|
+
if (window.location.pathname !== previousPath) {
|
|
187
|
+
this.detach("page-view", () => this.trackPageView());
|
|
188
|
+
}
|
|
112
189
|
return result;
|
|
113
190
|
});
|
|
114
191
|
}
|
|
@@ -144,23 +221,60 @@ class DefaultBrowserTracker {
|
|
|
144
221
|
}
|
|
145
222
|
buildEvent(eventTypeSlug, payload) {
|
|
146
223
|
const identity = this.identityFields();
|
|
224
|
+
const page = this.pageContext();
|
|
147
225
|
const event = {
|
|
148
226
|
eventTypeSlug,
|
|
149
|
-
schemaVersion:
|
|
227
|
+
schemaVersion: eventTypeSlug === pageViewEventType ? this.pageViewSchemaVersion : this.schemaVersion,
|
|
150
228
|
timestamp: new Date().toISOString(),
|
|
151
229
|
...identity,
|
|
152
|
-
context: browserContext(),
|
|
230
|
+
context: browserContext(page),
|
|
153
231
|
payload: {
|
|
154
232
|
siteUuid: this.config.siteUuid,
|
|
233
|
+
// Reporting groups page views by payload path, so it mirrors the page context's path.
|
|
234
|
+
...(eventTypeSlug === pageViewEventType && page.path !== undefined ? { path: page.path } : {}),
|
|
155
235
|
...payload,
|
|
156
236
|
},
|
|
157
237
|
};
|
|
238
|
+
if (Object.keys(this.labels).length > 0) {
|
|
239
|
+
event.labels = { ...this.labels };
|
|
240
|
+
}
|
|
158
241
|
const mode = this.config.identityMode === "extended" ? "producer" : "browser-cookieless";
|
|
159
242
|
const prepared = prepareEvent(event, { mode });
|
|
160
243
|
validateBrowserEvent(prepared);
|
|
161
244
|
applyEnvironmentLabel(prepared, this.config.environment);
|
|
162
245
|
return prepared;
|
|
163
246
|
}
|
|
247
|
+
/** The first page view's AI-assistant referral, as a class and name only. */
|
|
248
|
+
landingReferral() {
|
|
249
|
+
if (this.referrerClassified) {
|
|
250
|
+
return {};
|
|
251
|
+
}
|
|
252
|
+
this.referrerClassified = true;
|
|
253
|
+
const assistant = aiAssistantReferrer(document.referrer);
|
|
254
|
+
return assistant ? { referrerClass: aiAssistantReferrerClass, aiAssistant: assistant } : {};
|
|
255
|
+
}
|
|
256
|
+
/** Queue this document's one `web-vitals` event; true when one was queued. */
|
|
257
|
+
enqueueWebVitals() {
|
|
258
|
+
const collector = this.webVitals;
|
|
259
|
+
if (!collector || this.trackingDisabled()) {
|
|
260
|
+
return false;
|
|
261
|
+
}
|
|
262
|
+
this.webVitals = null;
|
|
263
|
+
collector.stop();
|
|
264
|
+
const vitals = collector.snapshot();
|
|
265
|
+
if (Object.keys(vitals).length === 0) {
|
|
266
|
+
return false;
|
|
267
|
+
}
|
|
268
|
+
const path = this.webVitalsPath === undefined ? {} : { path: this.webVitalsPath };
|
|
269
|
+
try {
|
|
270
|
+
this.enqueue(this.buildEvent(webVitalsEventType, { ...path, ...vitals }));
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
// A page that is going away has nowhere to raise this; the page view itself is unaffected.
|
|
274
|
+
return false;
|
|
275
|
+
}
|
|
276
|
+
return true;
|
|
277
|
+
}
|
|
164
278
|
identityFields() {
|
|
165
279
|
if (this.config.identityMode !== "extended") {
|
|
166
280
|
return { anonymousId: "", sessionId: "" };
|
|
@@ -182,7 +296,7 @@ class DefaultBrowserTracker {
|
|
|
182
296
|
});
|
|
183
297
|
}
|
|
184
298
|
async sendBatch(events, keepalive = false) {
|
|
185
|
-
await withRetry(this.retry, async () => {
|
|
299
|
+
const results = await withRetry(this.retry, async () => {
|
|
186
300
|
const response = await fetch(`${this.baseUrl}/api/v1/collect/events/batch`, {
|
|
187
301
|
method: "POST",
|
|
188
302
|
headers: collectorHeaders(this.config.writeKey),
|
|
@@ -191,7 +305,70 @@ class DefaultBrowserTracker {
|
|
|
191
305
|
keepalive,
|
|
192
306
|
});
|
|
193
307
|
assertAccepted(response);
|
|
308
|
+
return readCollectorBatchResults(response, events.length);
|
|
194
309
|
});
|
|
310
|
+
return classifyBatchResults(events, results);
|
|
311
|
+
}
|
|
312
|
+
/** Settle the queue and report permanent rejections for an answered batch. */
|
|
313
|
+
applyBatchOutcome(source, outcome) {
|
|
314
|
+
if (outcome.retryable.length > 0) {
|
|
315
|
+
this.queue.unshift(...outcome.retryable);
|
|
316
|
+
this.trimQueue();
|
|
317
|
+
}
|
|
318
|
+
this.queueStorage.save(this.queue);
|
|
319
|
+
if (outcome.rejected.length > 0) {
|
|
320
|
+
this.notifyFailure({ source, rejectedEvents: outcome.rejected.length });
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
pageContext() {
|
|
324
|
+
const defaults = {
|
|
325
|
+
path: sanitizeBrowserPath(window.location.pathname),
|
|
326
|
+
title: document.title,
|
|
327
|
+
};
|
|
328
|
+
const provider = this.config.pageContext;
|
|
329
|
+
if (!provider) {
|
|
330
|
+
return defaults;
|
|
331
|
+
}
|
|
332
|
+
let provided;
|
|
333
|
+
try {
|
|
334
|
+
provided = provider(defaults);
|
|
335
|
+
}
|
|
336
|
+
catch {
|
|
337
|
+
// A provider that cannot describe the page must not fall back to page content.
|
|
338
|
+
return {};
|
|
339
|
+
}
|
|
340
|
+
return safePageContext(provided, defaults.path);
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Run a fire-and-forget tracker call whose rejection has nowhere to go.
|
|
344
|
+
*
|
|
345
|
+
* SPA and lifecycle call sites cannot return a promise to the host page, so an unhandled rejection there would
|
|
346
|
+
* surface as a page-level error in the consumer's console while the queue already retains undelivered events for
|
|
347
|
+
* the next retry. The failure is absorbed here and reported as a sanitized `onFailure` description instead.
|
|
348
|
+
*/
|
|
349
|
+
detach(source, operation) {
|
|
350
|
+
void operation().catch((error) => this.notifyFailure({ source, status: collectorStatus(error) }));
|
|
351
|
+
}
|
|
352
|
+
/** Track a popstate only when it lands on a different route path. */
|
|
353
|
+
detachPathChange(operation) {
|
|
354
|
+
if (window.location.pathname === this.lastTrackedPath) {
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
this.detach("page-view", operation);
|
|
358
|
+
}
|
|
359
|
+
notifyFailure(failure) {
|
|
360
|
+
const onFailure = this.config.onFailure;
|
|
361
|
+
if (!onFailure) {
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
try {
|
|
365
|
+
// An async callback is valid for a void signature. Absorb its rejection
|
|
366
|
+
// without awaiting, so queue settlement never depends on the observer.
|
|
367
|
+
void Promise.resolve(onFailure(failure)).catch(() => undefined);
|
|
368
|
+
}
|
|
369
|
+
catch {
|
|
370
|
+
// A consumer callback must never break tracking or mask the original failure.
|
|
371
|
+
}
|
|
195
372
|
}
|
|
196
373
|
flushWithKeepalive() {
|
|
197
374
|
if (this.trackingDisabled()) {
|
|
@@ -202,12 +379,16 @@ class DefaultBrowserTracker {
|
|
|
202
379
|
return;
|
|
203
380
|
}
|
|
204
381
|
const events = this.queue.splice(0, this.queue.length);
|
|
205
|
-
void this.sendBatch(events, true).then(() => {
|
|
206
|
-
this.
|
|
207
|
-
|
|
382
|
+
void this.sendBatch(events, true).then((outcome) => {
|
|
383
|
+
this.applyBatchOutcome("flush", outcome);
|
|
384
|
+
if (outcome.retryable.length > 0) {
|
|
385
|
+
this.notifyFailure({ source: "flush", status: outcome.retryableStatus ?? 503 });
|
|
386
|
+
}
|
|
387
|
+
}, (error) => {
|
|
208
388
|
this.queue.unshift(...events);
|
|
209
389
|
this.trimQueue();
|
|
210
390
|
this.queueStorage.save(this.queue);
|
|
391
|
+
this.notifyFailure({ source: "flush", status: collectorStatus(error) });
|
|
211
392
|
});
|
|
212
393
|
}
|
|
213
394
|
}
|
|
@@ -231,16 +412,18 @@ export async function installBrowserTrackerFromScript(scriptElement) {
|
|
|
231
412
|
}
|
|
232
413
|
const baseUrl = script.dataset.baseUrl ?? new URL(script.src).origin;
|
|
233
414
|
assertSecureOrLocalHTTP(baseUrl, "baseUrl");
|
|
234
|
-
const siteConfig = await
|
|
415
|
+
const siteConfig = await fetchBrowserSiteConfig(baseUrl, siteUuid);
|
|
235
416
|
const tracker = createBrowserTracker({
|
|
236
417
|
baseUrl,
|
|
237
418
|
siteUuid,
|
|
238
419
|
writeKey,
|
|
239
420
|
identityMode: siteConfig.identityMode,
|
|
240
421
|
allowedOrigins: siteConfig.allowedOrigins,
|
|
241
|
-
|
|
422
|
+
pageViewSchemaVersion: siteConfigSchemaVersion(siteConfig.pageViewSchemaVersion),
|
|
423
|
+
batchSize: Number(script.dataset.batchSize || defaultSiteBatchSize(siteConfig)),
|
|
242
424
|
consent: scriptConsent(script, siteConfig),
|
|
243
425
|
persistentQueue: script.dataset.persistentQueue === "true",
|
|
426
|
+
webVitals: script.dataset.webVitals === "true",
|
|
244
427
|
});
|
|
245
428
|
window.custd = {
|
|
246
429
|
track: (eventTypeSlug, payload) => tracker.track(eventTypeSlug, payload),
|
|
@@ -256,33 +439,89 @@ export async function installBrowserTrackerFromScript(scriptElement) {
|
|
|
256
439
|
throw error;
|
|
257
440
|
}
|
|
258
441
|
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
});
|
|
442
|
+
/** Reads a registered browser Site's public identity mode and allowed origins. */
|
|
443
|
+
export async function fetchBrowserSiteConfig(baseUrl, siteUuid, fetchImpl = (input, init) => globalThis.fetch(input, init)) {
|
|
444
|
+
const path = `/api/v1/sites/${encodeURIComponent(siteUuid)}/config`;
|
|
445
|
+
const response = await fetchImpl(`${baseUrl.replace(/\/$/, "")}${path}`, { credentials: "omit" });
|
|
263
446
|
if (!response.ok) {
|
|
264
447
|
throw new Error(`custd: site config request failed with status ${response.status}`);
|
|
265
448
|
}
|
|
266
|
-
return (await response.json());
|
|
449
|
+
return emptySiteConfigNullLists("GET", path, (await response.json()));
|
|
267
450
|
}
|
|
268
|
-
function browserContext() {
|
|
269
|
-
|
|
270
|
-
page: {
|
|
271
|
-
path: sanitizeBrowserPath(window.location.pathname),
|
|
272
|
-
title: document.title,
|
|
273
|
-
},
|
|
451
|
+
function browserContext(page) {
|
|
452
|
+
const context = {
|
|
274
453
|
device: { type: deviceType() },
|
|
275
454
|
locale: navigator.language,
|
|
276
455
|
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
277
456
|
};
|
|
457
|
+
if (page.path !== undefined || page.title !== undefined) {
|
|
458
|
+
context.page = page;
|
|
459
|
+
}
|
|
460
|
+
return context;
|
|
278
461
|
}
|
|
279
|
-
|
|
280
|
-
|
|
462
|
+
/** Apply a supplied page context, never forwarding a value the collector must not receive. */
|
|
463
|
+
function safePageContext(provided, fallbackPath) {
|
|
464
|
+
const page = {};
|
|
465
|
+
if (typeof provided?.path === "string") {
|
|
466
|
+
page.path = isSafeRoutePath(provided.path) ? provided.path : fallbackPath;
|
|
467
|
+
}
|
|
468
|
+
const title = sanitizePageTitle(provided?.title);
|
|
469
|
+
if (title !== undefined) {
|
|
470
|
+
page.title = title;
|
|
471
|
+
}
|
|
472
|
+
return page;
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* A route path or template: absolute, without scheme, query, fragment, or
|
|
476
|
+
* encoded bytes. Colon, brace, bracket, and star placeholders are allowed so a
|
|
477
|
+
* router can name the dynamic segment instead of sending its value.
|
|
478
|
+
*/
|
|
479
|
+
function isSafeRoutePath(path) {
|
|
480
|
+
if (path.length === 0 || path.length > maxRoutePathLength || !path.startsWith("/") || path.startsWith("//")) {
|
|
481
|
+
return false;
|
|
482
|
+
}
|
|
483
|
+
return path.split("/").every((segment) => safeRoutePathSegment.test(segment));
|
|
484
|
+
}
|
|
485
|
+
function sanitizePageTitle(title) {
|
|
486
|
+
if (typeof title !== "string") {
|
|
487
|
+
return undefined;
|
|
488
|
+
}
|
|
489
|
+
const cleaned = title.replace(/[\p{Cc}]/gu, "").trim();
|
|
490
|
+
return cleaned === "" ? undefined : cleaned.slice(0, maxPageTitleLength);
|
|
491
|
+
}
|
|
492
|
+
/** The AI assistant a referrer URL names, or undefined for any other or unreadable referrer. */
|
|
493
|
+
export function aiAssistantReferrer(referrer) {
|
|
494
|
+
if (!referrer) {
|
|
495
|
+
return undefined;
|
|
496
|
+
}
|
|
497
|
+
let hostname;
|
|
498
|
+
try {
|
|
499
|
+
hostname = new URL(referrer).hostname.toLowerCase();
|
|
500
|
+
}
|
|
501
|
+
catch {
|
|
502
|
+
return undefined;
|
|
503
|
+
}
|
|
504
|
+
return aiAssistantReferrers.get(hostname.replace(/^www\./u, ""));
|
|
505
|
+
}
|
|
506
|
+
function campaignAttribution(query) {
|
|
281
507
|
const project = query.get("ref") ?? "";
|
|
282
|
-
if (query.get("source")
|
|
283
|
-
return {};
|
|
508
|
+
if (query.get("source") === "powered-by" && poweredByProjectSlug.test(project)) {
|
|
509
|
+
return { utmSource: project, utmMedium: "powered-by" };
|
|
510
|
+
}
|
|
511
|
+
// Match the saved campaign-link values without forwarding the URL or unrelated query fields.
|
|
512
|
+
const attribution = {};
|
|
513
|
+
for (const [parameter, field] of campaignQueryFields) {
|
|
514
|
+
const value = query
|
|
515
|
+
.get(parameter)
|
|
516
|
+
?.toLowerCase()
|
|
517
|
+
.split(/\p{White_Space}+/u)
|
|
518
|
+
.filter(Boolean)
|
|
519
|
+
.join("_");
|
|
520
|
+
if (value && [...value].length <= maxCampaignValueLength && !/\p{Cc}/u.test(value)) {
|
|
521
|
+
attribution[field] = value;
|
|
522
|
+
}
|
|
284
523
|
}
|
|
285
|
-
return
|
|
524
|
+
return attribution;
|
|
286
525
|
}
|
|
287
526
|
function sanitizeBrowserPath(pathname) {
|
|
288
527
|
const path = pathname.startsWith("/") ? pathname : `/${pathname}`;
|
|
@@ -315,12 +554,85 @@ function collectorHeaders(writeKey) {
|
|
|
315
554
|
};
|
|
316
555
|
}
|
|
317
556
|
function assertAccepted(response) {
|
|
318
|
-
if (
|
|
319
|
-
|
|
320
|
-
|
|
557
|
+
if (response.ok) {
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
if (retryableCollectorStatuses.has(response.status)) {
|
|
561
|
+
throw new RetryableCollectorStatusError(response.status);
|
|
562
|
+
}
|
|
563
|
+
throw new CollectorStatusError(response.status);
|
|
564
|
+
}
|
|
565
|
+
class CollectorStatusError extends Error {
|
|
566
|
+
constructor(status) {
|
|
567
|
+
super(`custd: collector request failed with status ${status}`);
|
|
568
|
+
this.status = status;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
class RetryableCollectorStatusError extends RetryableError {
|
|
572
|
+
constructor(status) {
|
|
573
|
+
super(`custd: retryable collector status ${status}`);
|
|
574
|
+
this.status = status;
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
/** A 2xx answer whose body does not match the collector batch contract. */
|
|
578
|
+
class MalformedCollectorResponseError extends RetryableError {
|
|
579
|
+
constructor() {
|
|
580
|
+
super("custd: collector response did not match the batch contract");
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
function collectorStatus(error) {
|
|
584
|
+
if (error instanceof RetryableCollectorStatusError || error instanceof CollectorStatusError) {
|
|
585
|
+
return error.status;
|
|
586
|
+
}
|
|
587
|
+
return undefined;
|
|
588
|
+
}
|
|
589
|
+
async function readCollectorBatchResults(response, expectedCount) {
|
|
590
|
+
let body;
|
|
591
|
+
try {
|
|
592
|
+
body = await response.json();
|
|
593
|
+
}
|
|
594
|
+
catch {
|
|
595
|
+
throw new MalformedCollectorResponseError();
|
|
596
|
+
}
|
|
597
|
+
const results = typeof body === "object" && body !== null ? body.results : undefined;
|
|
598
|
+
if (!Array.isArray(results) || results.length !== expectedCount) {
|
|
599
|
+
throw new MalformedCollectorResponseError();
|
|
600
|
+
}
|
|
601
|
+
return results.map((item) => {
|
|
602
|
+
const result = typeof item === "object" && item !== null ? item : {};
|
|
603
|
+
if (typeof result.success !== "boolean" || typeof result.status !== "number") {
|
|
604
|
+
throw new MalformedCollectorResponseError();
|
|
321
605
|
}
|
|
322
|
-
|
|
606
|
+
return { success: result.success, status: result.status };
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
function classifyBatchResults(events, results) {
|
|
610
|
+
const outcome = { rejected: [], retryable: [] };
|
|
611
|
+
results.forEach((result, index) => {
|
|
612
|
+
if (result.success) {
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
if (retryableCollectorStatuses.has(result.status)) {
|
|
616
|
+
outcome.retryable.push(events[index]);
|
|
617
|
+
outcome.retryableStatus ?? (outcome.retryableStatus = result.status);
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
outcome.rejected.push(events[index]);
|
|
621
|
+
});
|
|
622
|
+
return outcome;
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* Resolve the declared schema version, refusing a malformed value at
|
|
626
|
+
* construction so it is never sent as an event the collector cannot match.
|
|
627
|
+
*/
|
|
628
|
+
function resolveSchemaVersion(value) {
|
|
629
|
+
if (value === undefined) {
|
|
630
|
+
return defaultSchemaVersion;
|
|
323
631
|
}
|
|
632
|
+
if (!schemaVersionPattern.test(value)) {
|
|
633
|
+
throw new Error(`custd: schemaVersion ${JSON.stringify(value)} must be a dotted numeric version such as "1.0.0"`);
|
|
634
|
+
}
|
|
635
|
+
return value;
|
|
324
636
|
}
|
|
325
637
|
function assertAllowedOrigin(config) {
|
|
326
638
|
const allowedOrigins = config.allowedOrigins ?? [];
|
|
@@ -417,9 +729,14 @@ function scriptConsent(script, siteConfig) {
|
|
|
417
729
|
if (script.dataset.consent === "granted") {
|
|
418
730
|
return "granted";
|
|
419
731
|
}
|
|
732
|
+
return defaultSiteConsent(siteConfig);
|
|
733
|
+
}
|
|
734
|
+
/** An extended-identity Site waits for consent; a cookieless Site tracks without it. */
|
|
735
|
+
export function defaultSiteConsent(siteConfig) {
|
|
420
736
|
return siteConfig.identityMode === "extended" ? "required" : undefined;
|
|
421
737
|
}
|
|
422
|
-
|
|
738
|
+
/** Extended-identity Sites batch; cookieless Sites send each event as it happens. */
|
|
739
|
+
export function defaultSiteBatchSize(siteConfig) {
|
|
423
740
|
return siteConfig.identityMode === "extended" ? 25 : 1;
|
|
424
741
|
}
|
|
425
742
|
function doNotTrackEnabled() {
|
|
@@ -442,12 +759,17 @@ function assertSecureOrLocalHTTP(rawUrl, field) {
|
|
|
442
759
|
}
|
|
443
760
|
throw new Error(`custd: ${field} must use https unless it targets localhost`);
|
|
444
761
|
}
|
|
445
|
-
function isLocalHostname(hostname) {
|
|
446
|
-
return (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "host.docker.internal");
|
|
447
|
-
}
|
|
448
762
|
function randomUUID() {
|
|
449
763
|
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
|
450
764
|
return crypto.randomUUID();
|
|
451
765
|
}
|
|
452
766
|
return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (Number(c) ^ ((Math.random() * 16) >> (Number(c) / 4))).toString(16));
|
|
453
767
|
}
|
|
768
|
+
/**
|
|
769
|
+
* The Site configuration's page-view version, or undefined when it is absent or
|
|
770
|
+
* malformed, so an unexpected configuration falls back to the default rather
|
|
771
|
+
* than stopping the tracker.
|
|
772
|
+
*/
|
|
773
|
+
export function siteConfigSchemaVersion(value) {
|
|
774
|
+
return typeof value === "string" && schemaVersionPattern.test(value) ? value : undefined;
|
|
775
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Real-user Core Web Vitals for one document load, read with the browser's own
|
|
3
|
+
* PerformanceObserver entries. A metric the browser cannot observe, or that the
|
|
4
|
+
* visit never produced (INP without an interaction), is absent rather than zero.
|
|
5
|
+
*/
|
|
6
|
+
export type WebVitalsSnapshot = {
|
|
7
|
+
/** Largest Contentful Paint, in milliseconds. */
|
|
8
|
+
lcp?: number;
|
|
9
|
+
/** Interaction to Next Paint, in milliseconds. */
|
|
10
|
+
inp?: number;
|
|
11
|
+
/** Cumulative Layout Shift, a unitless score. */
|
|
12
|
+
cls?: number;
|
|
13
|
+
/** First Contentful Paint, in milliseconds. */
|
|
14
|
+
fcp?: number;
|
|
15
|
+
/** Time to First Byte, in milliseconds. */
|
|
16
|
+
ttfb?: number;
|
|
17
|
+
};
|
|
18
|
+
export type WebVitalsCollector = {
|
|
19
|
+
snapshot: () => WebVitalsSnapshot;
|
|
20
|
+
stop: () => void;
|
|
21
|
+
};
|
|
22
|
+
export declare function startWebVitals(): WebVitalsCollector;
|