@haakco/custd-sdk 0.0.0-stage → 3.71.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.
Files changed (196) hide show
  1. package/README.md +958 -2
  2. package/dist/admin-accounting-evidence.d.ts +48 -0
  3. package/dist/admin-accounting-evidence.js +24 -0
  4. package/dist/admin-app-releases.d.ts +116 -0
  5. package/dist/admin-app-releases.js +8 -0
  6. package/dist/admin-apps.d.ts +120 -0
  7. package/dist/admin-apps.js +47 -0
  8. package/dist/admin-auth-project-domain.d.ts +125 -0
  9. package/dist/admin-auth-project-domain.js +37 -0
  10. package/dist/admin-auth-projects.d.ts +989 -0
  11. package/dist/admin-auth-projects.js +527 -0
  12. package/dist/admin-campaign-email.d.ts +120 -0
  13. package/dist/admin-campaign-email.js +64 -0
  14. package/dist/admin-client-setup.d.ts +122 -0
  15. package/dist/admin-client-setup.js +408 -0
  16. package/dist/admin-data-labels.d.ts +124 -0
  17. package/dist/admin-data-labels.js +51 -0
  18. package/dist/admin-data-scopes.d.ts +93 -0
  19. package/dist/admin-data-scopes.js +154 -0
  20. package/dist/admin-email-relay.d.ts +66 -0
  21. package/dist/admin-email-relay.js +25 -0
  22. package/dist/admin-environment-policy.d.ts +32 -0
  23. package/dist/admin-environment-policy.js +26 -0
  24. package/dist/admin-error-issues.d.ts +91 -0
  25. package/dist/admin-error-issues.js +52 -0
  26. package/dist/admin-event-types.d.ts +57 -0
  27. package/dist/admin-event-types.js +28 -0
  28. package/dist/admin-impersonation.d.ts +48 -0
  29. package/dist/admin-impersonation.js +27 -0
  30. package/dist/admin-ingest-claims.d.ts +35 -0
  31. package/dist/admin-ingest-claims.js +26 -0
  32. package/dist/admin-managed-audit.d.ts +13 -0
  33. package/dist/admin-managed-audit.js +13 -0
  34. package/dist/admin-measurement-projects.d.ts +166 -0
  35. package/dist/admin-measurement-projects.js +120 -0
  36. package/dist/admin-notification-destinations.d.ts +31 -0
  37. package/dist/admin-notification-destinations.js +19 -0
  38. package/dist/admin-notification-webhooks.d.ts +64 -0
  39. package/dist/admin-notification-webhooks.js +42 -0
  40. package/dist/admin-oauth-client-admissions.d.ts +65 -0
  41. package/dist/admin-oauth-client-admissions.js +46 -0
  42. package/dist/admin-offboarding.d.ts +123 -0
  43. package/dist/admin-offboarding.js +129 -0
  44. package/dist/admin-predictions.d.ts +266 -0
  45. package/dist/admin-predictions.js +93 -0
  46. package/dist/admin-privacy-erasures.d.ts +74 -0
  47. package/dist/admin-privacy-erasures.js +73 -0
  48. package/dist/admin-retention.d.ts +99 -0
  49. package/dist/admin-retention.js +60 -0
  50. package/dist/admin-rls.d.ts +94 -0
  51. package/dist/admin-rls.js +33 -0
  52. package/dist/admin-sdk-usage.d.ts +41 -0
  53. package/dist/admin-sdk-usage.js +23 -0
  54. package/dist/admin-site-ai.d.ts +72 -0
  55. package/dist/admin-site-ai.js +1 -0
  56. package/dist/admin-site-analytics.d.ts +52 -0
  57. package/dist/admin-site-analytics.js +14 -0
  58. package/dist/admin-site-audit-pages.d.ts +76 -0
  59. package/dist/admin-site-audit-pages.js +27 -0
  60. package/dist/admin-site-campaign-links.d.ts +40 -0
  61. package/dist/admin-site-campaign-links.js +9 -0
  62. package/dist/admin-site-domains.d.ts +733 -0
  63. package/dist/admin-site-domains.js +768 -0
  64. package/dist/admin-site-export.d.ts +76 -0
  65. package/dist/admin-site-export.js +15 -0
  66. package/dist/admin-site-insights-tasks.d.ts +44 -0
  67. package/dist/admin-site-insights-tasks.js +28 -0
  68. package/dist/admin-site-insights.d.ts +527 -0
  69. package/dist/admin-site-insights.js +61 -0
  70. package/dist/admin-site-links.d.ts +87 -0
  71. package/dist/admin-site-links.js +16 -0
  72. package/dist/admin-site-monitors.d.ts +110 -0
  73. package/dist/admin-site-monitors.js +25 -0
  74. package/dist/admin-site-next-actions.d.ts +93 -0
  75. package/dist/admin-site-next-actions.js +36 -0
  76. package/dist/admin-site-page-queries.d.ts +63 -0
  77. package/dist/admin-site-page-queries.js +20 -0
  78. package/dist/admin-site-rankings.d.ts +98 -0
  79. package/dist/admin-site-rankings.js +46 -0
  80. package/dist/admin-site-regional-trends.d.ts +30 -0
  81. package/dist/admin-site-regional-trends.js +1 -0
  82. package/dist/admin-site-saved-reports.d.ts +45 -0
  83. package/dist/admin-site-saved-reports.js +13 -0
  84. package/dist/admin-site-search-pool.d.ts +77 -0
  85. package/dist/admin-site-search-pool.js +41 -0
  86. package/dist/admin-site-search-value.d.ts +97 -0
  87. package/dist/admin-site-search-value.js +29 -0
  88. package/dist/admin-site-status-page.d.ts +57 -0
  89. package/dist/admin-site-status-page.js +10 -0
  90. package/dist/admin-site-traffic.d.ts +145 -0
  91. package/dist/admin-site-traffic.js +32 -0
  92. package/dist/admin-site-web-data.d.ts +258 -0
  93. package/dist/admin-site-web-data.js +60 -0
  94. package/dist/admin-subject-exports.d.ts +79 -0
  95. package/dist/admin-subject-exports.js +44 -0
  96. package/dist/admin-support-access.d.ts +32 -0
  97. package/dist/admin-support-access.js +21 -0
  98. package/dist/admin-system.d.ts +283 -0
  99. package/dist/admin-system.js +65 -0
  100. package/dist/admin-tenant-storage.d.ts +35 -0
  101. package/dist/admin-tenant-storage.js +24 -0
  102. package/dist/admin-timeplans.d.ts +512 -0
  103. package/dist/admin-timeplans.js +200 -0
  104. package/dist/admin-uncertainty-models.d.ts +42 -0
  105. package/dist/admin-uncertainty-models.js +53 -0
  106. package/dist/admin-usage.d.ts +124 -0
  107. package/dist/admin-usage.js +169 -0
  108. package/dist/admin-users.d.ts +124 -0
  109. package/dist/admin-users.js +82 -0
  110. package/dist/admin-workflow-timings.d.ts +367 -0
  111. package/dist/admin-workflow-timings.js +117 -0
  112. package/dist/analytics-events.d.ts +167 -0
  113. package/dist/analytics-events.js +197 -0
  114. package/dist/analytics-reads.d.ts +81 -0
  115. package/dist/analytics-reads.js +5 -0
  116. package/dist/app-account.d.ts +84 -0
  117. package/dist/app-account.js +177 -0
  118. package/dist/app-alerts.d.ts +120 -0
  119. package/dist/app-alerts.js +44 -0
  120. package/dist/app-items.d.ts +786 -0
  121. package/dist/app-items.js +524 -0
  122. package/dist/app-live.d.ts +84 -0
  123. package/dist/app-live.js +228 -0
  124. package/dist/app-meetings.d.ts +95 -0
  125. package/dist/app-meetings.js +26 -0
  126. package/dist/app-models.d.ts +271 -0
  127. package/dist/app-models.js +83 -0
  128. package/dist/app-push.d.ts +64 -0
  129. package/dist/app-push.js +178 -0
  130. package/dist/backend-lifecycle.d.ts +85 -0
  131. package/dist/backend-lifecycle.js +212 -0
  132. package/dist/browser-manifest.json +7 -0
  133. package/dist/browser-script-BWnwDjAC.js +711 -0
  134. package/dist/browser-script.d.ts +1 -0
  135. package/dist/browser-script.js +5 -0
  136. package/dist/browser-sign-in.d.ts +153 -0
  137. package/dist/browser-sign-in.js +410 -0
  138. package/dist/browser-tracker.d.ts +142 -0
  139. package/dist/browser-tracker.js +775 -0
  140. package/dist/browser-web-vitals.d.ts +22 -0
  141. package/dist/browser-web-vitals.js +116 -0
  142. package/dist/browser.d.ts +10 -0
  143. package/dist/browser.js +10 -0
  144. package/dist/download-stream.d.ts +16 -0
  145. package/dist/download-stream.js +55 -0
  146. package/dist/error-capture.d.ts +62 -0
  147. package/dist/error-capture.js +168 -0
  148. package/dist/hosted-app.d.ts +115 -0
  149. package/dist/hosted-app.js +275 -0
  150. package/dist/index.d.ts +2324 -0
  151. package/dist/index.js +2226 -0
  152. package/dist/ingest-operations.d.ts +483 -0
  153. package/dist/ingest-operations.js +154 -0
  154. package/dist/measurement.d.ts +164 -0
  155. package/dist/measurement.js +104 -0
  156. package/dist/mobile-adapter.d.ts +25 -0
  157. package/dist/mobile-adapter.js +57 -0
  158. package/dist/mobile-context.d.ts +32 -0
  159. package/dist/mobile-context.js +156 -0
  160. package/dist/mobile-queue.d.ts +22 -0
  161. package/dist/mobile-queue.js +73 -0
  162. package/dist/oauth.d.ts +1 -0
  163. package/dist/oauth.js +8 -0
  164. package/dist/parsers.d.ts +149 -0
  165. package/dist/parsers.js +115 -0
  166. package/dist/public-reads.d.ts +79 -0
  167. package/dist/public-reads.js +57 -0
  168. package/dist/reporting-catalogue.d.ts +264 -0
  169. package/dist/reporting-catalogue.js +5 -0
  170. package/dist/reporting-state.d.ts +46 -0
  171. package/dist/reporting-state.js +76 -0
  172. package/dist/response-lists.d.ts +16 -0
  173. package/dist/response-lists.generated.d.ts +7 -0
  174. package/dist/response-lists.generated.js +1927 -0
  175. package/dist/response-lists.js +70 -0
  176. package/dist/response-validation.d.ts +30 -0
  177. package/dist/response-validation.js +94 -0
  178. package/dist/runtime-readiness.d.ts +30 -0
  179. package/dist/runtime-readiness.js +150 -0
  180. package/dist/schema-registry.d.ts +45 -0
  181. package/dist/schema-registry.js +9 -0
  182. package/dist/secure-url.d.ts +4 -0
  183. package/dist/secure-url.js +23 -0
  184. package/dist/site-ai-owner.d.ts +34 -0
  185. package/dist/site-ai-owner.js +99 -0
  186. package/dist/site-monitor-reports.d.ts +15 -0
  187. package/dist/site-monitor-reports.js +87 -0
  188. package/dist/testing/fake-custd.d.ts +150 -0
  189. package/dist/testing/fake-custd.js +842 -0
  190. package/dist/testing/fake-results.d.ts +30 -0
  191. package/dist/testing/fake-results.js +293 -0
  192. package/dist/testing.d.ts +2 -0
  193. package/dist/testing.js +3 -0
  194. package/dist/version.d.ts +10 -0
  195. package/dist/version.js +10 -0
  196. package/package.json +57 -4
@@ -0,0 +1,775 @@
1
+ import { startWebVitals } from "./browser-web-vitals.js";
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";
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;
30
+ const maxQueuedGlobalCalls = 1000;
31
+ const redactedPathSegment = "[redacted]";
32
+ const safePathSegment = /^[A-Za-z][A-Za-z0-9._~-]{0,63}$/u;
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;
34
+ const opaquePathSegment = /^[A-Za-z0-9_-]{24,}$/u;
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]);
48
+ export function createBrowserTracker(config) {
49
+ return new DefaultBrowserTracker(config);
50
+ }
51
+ class DefaultBrowserTracker {
52
+ constructor(config) {
53
+ this.queue = [];
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;
59
+ this.originalPushState = null;
60
+ this.originalReplaceState = null;
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());
72
+ this.config = config;
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 ?? {}) };
80
+ this.queueStorage = config.queueStorage ?? browserQueueStorage(config.siteUuid, config.persistentQueue === true);
81
+ this.retry = normalizeRetryOptions(config.retry);
82
+ this.maxQueueSize = config.maxQueueSize ?? 1000;
83
+ this.queue = this.queueStorage.load();
84
+ this.trimQueue();
85
+ this.consent = config.consent === "required" ? "denied" : "granted";
86
+ if (this.trackingDisabled()) {
87
+ this.clearStoredState();
88
+ }
89
+ assertSecureOrLocalHTTP(this.baseUrl, "baseUrl");
90
+ assertAllowedOrigin(config);
91
+ window.addEventListener("online", this.onlineHandler);
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
+ }
98
+ }
99
+ async track(eventTypeSlug, payload = {}) {
100
+ if (this.trackingDisabled()) {
101
+ return;
102
+ }
103
+ const event = this.buildEvent(eventTypeSlug, payload);
104
+ if ((this.config.batchSize ?? 0) > 1) {
105
+ this.enqueue(event);
106
+ if (this.queue.length >= (this.config.batchSize ?? 0)) {
107
+ await this.flush();
108
+ }
109
+ return;
110
+ }
111
+ await this.sendEvent(event);
112
+ }
113
+ trackPageView() {
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
+ });
120
+ }
121
+ installSpaTracking() {
122
+ if (this.installedSpaTracking) {
123
+ return;
124
+ }
125
+ this.installedSpaTracking = true;
126
+ this.originalPushState = window.history.pushState;
127
+ this.originalReplaceState = window.history.replaceState;
128
+ window.history.pushState = this.wrapHistoryMethod(this.originalPushState);
129
+ window.history.replaceState = this.wrapHistoryMethod(this.originalReplaceState);
130
+ window.addEventListener("popstate", this.popstateHandler);
131
+ if (this.config.trackInitialPageView !== false) {
132
+ this.detach("page-view", () => this.trackPageView());
133
+ }
134
+ }
135
+ setConsent(state) {
136
+ this.consent = state;
137
+ if (state === "denied") {
138
+ this.clearStoredState();
139
+ }
140
+ }
141
+ async flush() {
142
+ if (this.trackingDisabled()) {
143
+ this.clearStoredState();
144
+ return;
145
+ }
146
+ if (this.queue.length === 0 || !isOnline()) {
147
+ return;
148
+ }
149
+ const events = this.queue.splice(0, this.queue.length);
150
+ let outcome;
151
+ try {
152
+ outcome = await this.sendBatch(events);
153
+ }
154
+ catch (error) {
155
+ this.queue.unshift(...events);
156
+ this.trimQueue();
157
+ this.queueStorage.save(this.queue);
158
+ throw error;
159
+ }
160
+ this.applyBatchOutcome("flush", outcome);
161
+ if (outcome.retryable.length > 0) {
162
+ throw new RetryableCollectorStatusError(outcome.retryableStatus ?? 503);
163
+ }
164
+ }
165
+ close() {
166
+ window.removeEventListener("online", this.onlineHandler);
167
+ window.removeEventListener("pagehide", this.pagehideHandler);
168
+ window.removeEventListener("popstate", this.popstateHandler);
169
+ window.removeEventListener("visibilitychange", this.visibilityHandler);
170
+ this.webVitals?.stop();
171
+ this.webVitals = null;
172
+ if (this.originalPushState) {
173
+ window.history.pushState = this.originalPushState;
174
+ }
175
+ if (this.originalReplaceState) {
176
+ window.history.replaceState = this.originalReplaceState;
177
+ }
178
+ this.installedSpaTracking = false;
179
+ this.originalPushState = null;
180
+ this.originalReplaceState = null;
181
+ }
182
+ wrapHistoryMethod(original) {
183
+ return ((...args) => {
184
+ const previousPath = window.location.pathname;
185
+ const result = original.apply(window.history, args);
186
+ if (window.location.pathname !== previousPath) {
187
+ this.detach("page-view", () => this.trackPageView());
188
+ }
189
+ return result;
190
+ });
191
+ }
192
+ trackingDisabled() {
193
+ if (this.consent !== "granted") {
194
+ return true;
195
+ }
196
+ if (doNotTrackEnabled()) {
197
+ return true;
198
+ }
199
+ return false;
200
+ }
201
+ enqueue(event) {
202
+ this.queue.push(event);
203
+ this.trimQueue();
204
+ this.queueStorage.save(this.queue);
205
+ }
206
+ trimQueue() {
207
+ if (this.queue.length > this.maxQueueSize) {
208
+ this.queue = this.queue.slice(this.queue.length - this.maxQueueSize);
209
+ }
210
+ }
211
+ clearStoredState() {
212
+ this.queue = [];
213
+ this.queueStorage.clear();
214
+ if (typeof localStorage !== "undefined") {
215
+ localStorage.removeItem(anonymousIDStorageKey(this.config.siteUuid));
216
+ localStorage.removeItem(queueStorageKey(this.config.siteUuid));
217
+ }
218
+ if (typeof sessionStorage !== "undefined") {
219
+ sessionStorage.removeItem(sessionIDStorageKey(this.config.siteUuid));
220
+ }
221
+ }
222
+ buildEvent(eventTypeSlug, payload) {
223
+ const identity = this.identityFields();
224
+ const page = this.pageContext();
225
+ const event = {
226
+ eventTypeSlug,
227
+ schemaVersion: eventTypeSlug === pageViewEventType ? this.pageViewSchemaVersion : this.schemaVersion,
228
+ timestamp: new Date().toISOString(),
229
+ ...identity,
230
+ context: browserContext(page),
231
+ payload: {
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 } : {}),
235
+ ...payload,
236
+ },
237
+ };
238
+ if (Object.keys(this.labels).length > 0) {
239
+ event.labels = { ...this.labels };
240
+ }
241
+ const mode = this.config.identityMode === "extended" ? "producer" : "browser-cookieless";
242
+ const prepared = prepareEvent(event, { mode });
243
+ validateBrowserEvent(prepared);
244
+ applyEnvironmentLabel(prepared, this.config.environment);
245
+ return prepared;
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
+ }
278
+ identityFields() {
279
+ if (this.config.identityMode !== "extended") {
280
+ return { anonymousId: "", sessionId: "" };
281
+ }
282
+ return {
283
+ anonymousId: storedUUID(anonymousIDStorageKey(this.config.siteUuid), localStorage),
284
+ sessionId: storedUUID(sessionIDStorageKey(this.config.siteUuid), sessionStorage),
285
+ };
286
+ }
287
+ async sendEvent(event) {
288
+ await withRetry(this.retry, async () => {
289
+ const response = await fetch(`${this.baseUrl}/api/v1/collect/events`, {
290
+ method: "POST",
291
+ headers: collectorHeaders(this.config.writeKey),
292
+ body: JSON.stringify(event),
293
+ credentials: "omit",
294
+ });
295
+ assertAccepted(response);
296
+ });
297
+ }
298
+ async sendBatch(events, keepalive = false) {
299
+ const results = await withRetry(this.retry, async () => {
300
+ const response = await fetch(`${this.baseUrl}/api/v1/collect/events/batch`, {
301
+ method: "POST",
302
+ headers: collectorHeaders(this.config.writeKey),
303
+ body: JSON.stringify({ events }),
304
+ credentials: "omit",
305
+ keepalive,
306
+ });
307
+ assertAccepted(response);
308
+ return readCollectorBatchResults(response, events.length);
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
+ }
372
+ }
373
+ flushWithKeepalive() {
374
+ if (this.trackingDisabled()) {
375
+ this.clearStoredState();
376
+ return;
377
+ }
378
+ if (this.queue.length === 0) {
379
+ return;
380
+ }
381
+ const events = this.queue.splice(0, this.queue.length);
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) => {
388
+ this.queue.unshift(...events);
389
+ this.trimQueue();
390
+ this.queueStorage.save(this.queue);
391
+ this.notifyFailure({ source: "flush", status: collectorStatus(error) });
392
+ });
393
+ }
394
+ }
395
+ function anonymousIDStorageKey(siteUuid) {
396
+ return `custd:${siteUuid}:anonymous_id`;
397
+ }
398
+ function sessionIDStorageKey(siteUuid) {
399
+ return `custd:${siteUuid}:session_id`;
400
+ }
401
+ function queueStorageKey(siteUuid) {
402
+ return `custd:${siteUuid}:event_queue`;
403
+ }
404
+ export async function installBrowserTrackerFromScript(scriptElement) {
405
+ const script = scriptElement ?? currentScript();
406
+ const queuedGlobal = installQueuedGlobal();
407
+ try {
408
+ const siteUuid = script.dataset.siteUuid;
409
+ const writeKey = script.dataset.writeKey;
410
+ if (!siteUuid || !writeKey) {
411
+ throw new Error("custd: browser script requires data-site-uuid and data-write-key");
412
+ }
413
+ const baseUrl = script.dataset.baseUrl ?? new URL(script.src).origin;
414
+ assertSecureOrLocalHTTP(baseUrl, "baseUrl");
415
+ const siteConfig = await fetchBrowserSiteConfig(baseUrl, siteUuid);
416
+ const tracker = createBrowserTracker({
417
+ baseUrl,
418
+ siteUuid,
419
+ writeKey,
420
+ identityMode: siteConfig.identityMode,
421
+ allowedOrigins: siteConfig.allowedOrigins,
422
+ pageViewSchemaVersion: siteConfigSchemaVersion(siteConfig.pageViewSchemaVersion),
423
+ batchSize: Number(script.dataset.batchSize || defaultSiteBatchSize(siteConfig)),
424
+ consent: scriptConsent(script, siteConfig),
425
+ persistentQueue: script.dataset.persistentQueue === "true",
426
+ webVitals: script.dataset.webVitals === "true",
427
+ });
428
+ window.custd = {
429
+ track: (eventTypeSlug, payload) => tracker.track(eventTypeSlug, payload),
430
+ trackPageView: () => tracker.trackPageView(),
431
+ setConsent: (state) => tracker.setConsent(state),
432
+ };
433
+ await drainQueuedGlobal(tracker, queuedGlobal);
434
+ return tracker;
435
+ }
436
+ catch (error) {
437
+ rejectQueuedGlobal(queuedGlobal, error);
438
+ installRejectingGlobal(error);
439
+ throw error;
440
+ }
441
+ }
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" });
446
+ if (!response.ok) {
447
+ throw new Error(`custd: site config request failed with status ${response.status}`);
448
+ }
449
+ return emptySiteConfigNullLists("GET", path, (await response.json()));
450
+ }
451
+ function browserContext(page) {
452
+ const context = {
453
+ device: { type: deviceType() },
454
+ locale: navigator.language,
455
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
456
+ };
457
+ if (page.path !== undefined || page.title !== undefined) {
458
+ context.page = page;
459
+ }
460
+ return context;
461
+ }
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) {
507
+ const project = query.get("ref") ?? "";
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
+ }
523
+ }
524
+ return attribution;
525
+ }
526
+ function sanitizeBrowserPath(pathname) {
527
+ const path = pathname.startsWith("/") ? pathname : `/${pathname}`;
528
+ const segments = path.split("/").map(sanitizePathSegment);
529
+ return segments.join("/") || "/";
530
+ }
531
+ function sanitizePathSegment(segment) {
532
+ if (segment === "") {
533
+ return "";
534
+ }
535
+ let decoded;
536
+ try {
537
+ decoded = decodeURIComponent(segment);
538
+ }
539
+ catch {
540
+ return redactedPathSegment;
541
+ }
542
+ if (!safePathSegment.test(decoded) ||
543
+ uuidPathSegment.test(decoded) ||
544
+ /^\d+$/u.test(decoded) ||
545
+ opaquePathSegment.test(decoded)) {
546
+ return redactedPathSegment;
547
+ }
548
+ return decoded;
549
+ }
550
+ function collectorHeaders(writeKey) {
551
+ return {
552
+ "Content-Type": "application/json",
553
+ Authorization: `Bearer ${writeKey}`,
554
+ };
555
+ }
556
+ function assertAccepted(response) {
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();
605
+ }
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;
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;
636
+ }
637
+ function assertAllowedOrigin(config) {
638
+ const allowedOrigins = config.allowedOrigins ?? [];
639
+ if (allowedOrigins.length === 0) {
640
+ throw new Error("custd: site config must include allowed origins for this site");
641
+ }
642
+ if (!allowedOrigins.includes(window.location.origin)) {
643
+ throw new Error("custd: origin is not allowed for this site");
644
+ }
645
+ }
646
+ function installQueuedGlobal() {
647
+ const queued = { calls: [], promises: [] };
648
+ window.custd = {
649
+ track: (eventTypeSlug, payload) => enqueueGlobalCall(queued, { type: "track", eventTypeSlug, payload }),
650
+ trackPageView: () => enqueueGlobalCall(queued, { type: "trackPageView" }),
651
+ setConsent: (state) => {
652
+ enqueueGlobalStateCall(queued, { type: "setConsent", state });
653
+ },
654
+ };
655
+ return queued;
656
+ }
657
+ function enqueueGlobalCall(queued, call) {
658
+ if (queued.calls.length >= maxQueuedGlobalCalls) {
659
+ return Promise.reject(new Error("custd: queued global call limit exceeded"));
660
+ }
661
+ return new Promise((resolve, reject) => {
662
+ queued.calls.push(call);
663
+ queued.promises.push({ resolve, reject });
664
+ });
665
+ }
666
+ function enqueueGlobalStateCall(queued, call) {
667
+ if (queued.calls.length >= maxQueuedGlobalCalls) {
668
+ return;
669
+ }
670
+ queued.calls.push(call);
671
+ }
672
+ async function drainQueuedGlobal(tracker, queued) {
673
+ for (const call of queued.calls) {
674
+ const deferred = call.type === "setConsent" ? undefined : queued.promises.shift();
675
+ try {
676
+ if (call.type === "track") {
677
+ await tracker.track(call.eventTypeSlug, call.payload);
678
+ }
679
+ else if (call.type === "trackPageView") {
680
+ await tracker.trackPageView();
681
+ }
682
+ else {
683
+ tracker.setConsent(call.state);
684
+ }
685
+ deferred?.resolve();
686
+ }
687
+ catch (error) {
688
+ deferred?.reject(error);
689
+ }
690
+ }
691
+ }
692
+ function rejectQueuedGlobal(queued, error) {
693
+ for (const deferred of queued.promises.splice(0, queued.promises.length)) {
694
+ deferred.reject(error);
695
+ }
696
+ }
697
+ function installRejectingGlobal(error) {
698
+ window.custd = {
699
+ track: () => Promise.reject(error),
700
+ trackPageView: () => Promise.reject(error),
701
+ setConsent: () => {
702
+ throw error;
703
+ },
704
+ };
705
+ }
706
+ function storedUUID(key, storage) {
707
+ const existing = storage.getItem(key);
708
+ if (existing) {
709
+ return existing;
710
+ }
711
+ const value = randomUUID();
712
+ storage.setItem(key, value);
713
+ return value;
714
+ }
715
+ function browserQueueStorage(siteUuid, persistent) {
716
+ if (!persistent || typeof localStorage === "undefined") {
717
+ return new MemoryQueueStorage();
718
+ }
719
+ return new LocalStorageQueueStorage(`custd:${siteUuid}:event_queue`);
720
+ }
721
+ function currentScript() {
722
+ const script = document.currentScript;
723
+ if (!script) {
724
+ throw new Error("custd: browser script could not find document.currentScript");
725
+ }
726
+ return script;
727
+ }
728
+ function scriptConsent(script, siteConfig) {
729
+ if (script.dataset.consent === "granted") {
730
+ return "granted";
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) {
736
+ return siteConfig.identityMode === "extended" ? "required" : undefined;
737
+ }
738
+ /** Extended-identity Sites batch; cookieless Sites send each event as it happens. */
739
+ export function defaultSiteBatchSize(siteConfig) {
740
+ return siteConfig.identityMode === "extended" ? 25 : 1;
741
+ }
742
+ function doNotTrackEnabled() {
743
+ const value = navigator.doNotTrack;
744
+ return value === "1" || value === "yes";
745
+ }
746
+ function isOnline() {
747
+ return typeof navigator.onLine !== "boolean" || navigator.onLine;
748
+ }
749
+ function deviceType() {
750
+ return /Mobi|Android/i.test(navigator.userAgent) ? "mobile" : "desktop";
751
+ }
752
+ function assertSecureOrLocalHTTP(rawUrl, field) {
753
+ const parsed = new URL(rawUrl);
754
+ if (parsed.protocol === "https:") {
755
+ return;
756
+ }
757
+ if (parsed.protocol === "http:" && isLocalHostname(parsed.hostname)) {
758
+ return;
759
+ }
760
+ throw new Error(`custd: ${field} must use https unless it targets localhost`);
761
+ }
762
+ function randomUUID() {
763
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
764
+ return crypto.randomUUID();
765
+ }
766
+ return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (Number(c) ^ ((Math.random() * 16) >> (Number(c) / 4))).toString(16));
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
+ }