@haakco/custd-sdk 0.0.0-stage → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +412 -2
  2. package/dist/admin-client-setup.d.ts +100 -0
  3. package/dist/admin-client-setup.js +398 -0
  4. package/dist/admin-data-labels.d.ts +124 -0
  5. package/dist/admin-data-labels.js +51 -0
  6. package/dist/admin-offboarding.d.ts +109 -0
  7. package/dist/admin-offboarding.js +108 -0
  8. package/dist/admin-predictions.d.ts +147 -0
  9. package/dist/admin-predictions.js +83 -0
  10. package/dist/admin-privacy-erasures.d.ts +62 -0
  11. package/dist/admin-privacy-erasures.js +72 -0
  12. package/dist/admin-retention.d.ts +51 -0
  13. package/dist/admin-retention.js +35 -0
  14. package/dist/admin-subject-exports.d.ts +48 -0
  15. package/dist/admin-subject-exports.js +28 -0
  16. package/dist/admin-tenant-storage.d.ts +27 -0
  17. package/dist/admin-tenant-storage.js +25 -0
  18. package/dist/admin-timeplans.d.ts +238 -0
  19. package/dist/admin-timeplans.js +146 -0
  20. package/dist/analytics-events.d.ts +85 -0
  21. package/dist/analytics-events.js +40 -0
  22. package/dist/backend-lifecycle.d.ts +85 -0
  23. package/dist/backend-lifecycle.js +212 -0
  24. package/dist/browser-manifest.json +7 -0
  25. package/dist/browser-script-BvgjdZSO.js +429 -0
  26. package/dist/browser-script.d.ts +1 -0
  27. package/dist/browser-script.js +5 -0
  28. package/dist/browser-tracker.d.ts +47 -0
  29. package/dist/browser-tracker.js +453 -0
  30. package/dist/browser.d.ts +1 -0
  31. package/dist/browser.js +1 -0
  32. package/dist/fixtures.d.ts +10 -0
  33. package/dist/fixtures.js +57 -0
  34. package/dist/index.d.ts +1310 -0
  35. package/dist/index.js +1706 -0
  36. package/dist/mobile-adapter.d.ts +25 -0
  37. package/dist/mobile-adapter.js +57 -0
  38. package/dist/mobile-context.d.ts +32 -0
  39. package/dist/mobile-context.js +156 -0
  40. package/dist/mobile-queue.d.ts +22 -0
  41. package/dist/mobile-queue.js +73 -0
  42. package/dist/oauth.d.ts +1 -0
  43. package/dist/oauth.js +8 -0
  44. package/dist/reporting-state.d.ts +46 -0
  45. package/dist/reporting-state.js +76 -0
  46. package/dist/runtime-readiness.d.ts +30 -0
  47. package/dist/runtime-readiness.js +150 -0
  48. package/dist/version.d.ts +10 -0
  49. package/dist/version.js +10 -0
  50. package/package.json +46 -4
@@ -0,0 +1,212 @@
1
+ import { OffboardingClient, } from "./admin-offboarding.js";
2
+ import { checkRuntimeReadiness } from "./runtime-readiness.js";
3
+ function hex(bytes) {
4
+ return Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("");
5
+ }
6
+ export function createVerifiedOffboardingExportReceiver(options) {
7
+ if (typeof options.persist !== "function") {
8
+ throw new Error("Custd lifecycle requires an export persistence callback");
9
+ }
10
+ return async ({ tenantSlug, requestUuid, download, export: exported }) => {
11
+ if (download.bytes.byteLength !== download.byteSize || (exported && download.byteSize !== exported.byteSize)) {
12
+ throw new Error("Custd lifecycle export byte size did not match server metadata");
13
+ }
14
+ const digest = hex(new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", Uint8Array.from(download.bytes).buffer)));
15
+ if (digest !== download.checksumSha256 || (exported && digest !== exported.checksumSha256)) {
16
+ throw new Error("Custd lifecycle export checksum verification failed");
17
+ }
18
+ const evidence = await options.persist({
19
+ tenantSlug,
20
+ requestUuid,
21
+ bytes: download.bytes,
22
+ checksumSha256: digest,
23
+ });
24
+ return { verified: true, ...(evidence ? { evidence } : {}) };
25
+ };
26
+ }
27
+ const purposeProfiles = [
28
+ "ingest",
29
+ "schema",
30
+ "reporting",
31
+ "lifecycle",
32
+ "broker",
33
+ ];
34
+ function nonEmpty(value) {
35
+ return typeof value === "string" && value.trim() !== "";
36
+ }
37
+ function requireText(name, value) {
38
+ if (!nonEmpty(value))
39
+ throw new Error(`Custd lifecycle requires ${name}`);
40
+ }
41
+ function requirePurpose(value) {
42
+ if (!purposeProfiles.includes(value)) {
43
+ throw new Error(`Custd lifecycle does not support credential purpose "${String(value)}"`);
44
+ }
45
+ }
46
+ function requireRequestUuid(value, expected, step) {
47
+ if (!value || typeof value !== "object" || value.requestUuid !== expected) {
48
+ throw new Error(`Custd lifecycle ${step} returned a different offboarding request`);
49
+ }
50
+ }
51
+ function requireReceipt(receipt) {
52
+ if (receipt.finalState !== "complete") {
53
+ throw new Error(`Custd lifecycle receipt is not complete (state ${receipt.finalState || "unknown"})`);
54
+ }
55
+ }
56
+ function requireNonNegativeInteger(name, value) {
57
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
58
+ throw new Error(`Custd lifecycle requires valid ${name}`);
59
+ }
60
+ }
61
+ function requireMatchingExportMetadata(exported, download) {
62
+ const matches = [exported.checksumSha256 === download.checksumSha256, exported.byteSize === download.byteSize].every(Boolean);
63
+ if (!matches) {
64
+ throw new Error("Custd lifecycle export metadata did not match the download");
65
+ }
66
+ }
67
+ function requireDownload(download) {
68
+ if (!(download.bytes instanceof Uint8Array)) {
69
+ throw new Error("Custd lifecycle requires offboarding download bytes");
70
+ }
71
+ requireText("offboarding download checksum", download.checksumSha256);
72
+ requireNonNegativeInteger("offboarding download byte size", download.byteSize);
73
+ if (download.bytes.byteLength !== download.byteSize) {
74
+ throw new Error("Custd lifecycle offboarding download byte size did not match its body");
75
+ }
76
+ }
77
+ function validateRotation(options) {
78
+ requireText("tenant slug", options.tenantSlug);
79
+ requireText("client ID", options.clientId);
80
+ requirePurpose(options.purposeProfile);
81
+ if (typeof options.persistSecret !== "function") {
82
+ throw new Error("Custd lifecycle requires a one-time secret persistence callback");
83
+ }
84
+ }
85
+ function validateOffboarding(options) {
86
+ requireText("tenant slug", options.tenantSlug);
87
+ requireText("offboarding request UUID", options.requestUuid);
88
+ if (typeof options.receiveAndVerifyExport !== "function") {
89
+ throw new Error("Custd lifecycle requires an export download, persistence, and verification callback");
90
+ }
91
+ if (typeof options.verifyZeroState !== "function") {
92
+ throw new Error("Custd lifecycle requires a zero-state reconciliation callback");
93
+ }
94
+ }
95
+ export class BackendLifecycleClient {
96
+ constructor(request, offboardingDownload) {
97
+ this.request = request;
98
+ this.offboarding = new OffboardingClient(request, offboardingDownload);
99
+ }
100
+ async rotateCredential(options) {
101
+ validateRotation(options);
102
+ const existing = await this.request("GET", `/oauth-clients/${encodeURIComponent(options.clientId)}`, undefined, options);
103
+ if (existing.clientId !== options.clientId || existing.companySlug !== options.tenantSlug) {
104
+ throw new Error("Custd lifecycle credential does not belong to the requested tenant");
105
+ }
106
+ const rotated = await this.request("POST", `/oauth-clients/${encodeURIComponent(options.clientId)}/rotate-secret`, undefined, options);
107
+ requireText("rotated client secret", rotated?.clientSecret);
108
+ try {
109
+ await options.persistSecret({
110
+ tenantSlug: options.tenantSlug,
111
+ clientId: options.clientId,
112
+ purposeProfile: options.purposeProfile,
113
+ clientSecret: rotated.clientSecret,
114
+ });
115
+ }
116
+ catch {
117
+ throw new Error("Custd lifecycle credential rotation completed but secret persistence failed; reconcile before retrying");
118
+ }
119
+ return {
120
+ tenantSlug: options.tenantSlug,
121
+ clientId: options.clientId,
122
+ purposeProfile: options.purposeProfile,
123
+ secretPersisted: true,
124
+ };
125
+ }
126
+ verifyReadiness(options) {
127
+ return checkRuntimeReadiness(options);
128
+ }
129
+ async reconcileZeroState(options) {
130
+ requireText("tenant slug", options.tenantSlug);
131
+ requireText("offboarding request UUID", options.requestUuid);
132
+ if (typeof options.verifyZeroState !== "function") {
133
+ throw new Error("Custd lifecycle requires a zero-state reconciliation callback");
134
+ }
135
+ let result;
136
+ try {
137
+ result = await options.verifyZeroState({
138
+ tenantSlug: options.tenantSlug,
139
+ requestUuid: options.requestUuid,
140
+ receipt: options.receipt,
141
+ });
142
+ }
143
+ catch {
144
+ throw new Error("Custd lifecycle zero-state reconciliation failed");
145
+ }
146
+ if (result?.zero !== true) {
147
+ throw new Error("Custd lifecycle zero-state reconciliation did not confirm an empty tenant");
148
+ }
149
+ return result;
150
+ }
151
+ async completeOffboarding(options) {
152
+ validateOffboarding(options);
153
+ const current = await this.offboarding.getRequest(options.requestUuid, options);
154
+ requireRequestUuid(current, options.requestUuid, "state");
155
+ let preview;
156
+ let exported;
157
+ switch (current.state) {
158
+ case "preview":
159
+ preview = await this.offboarding.preview(options.requestUuid, options);
160
+ requireRequestUuid(preview, options.requestUuid, "preview");
161
+ if (!preview.complete || preview.partial) {
162
+ throw new Error("Custd lifecycle offboarding preview is incomplete");
163
+ }
164
+ exported = await this.offboarding.export(options.requestUuid, options);
165
+ requireRequestUuid(exported, options.requestUuid, "export");
166
+ break;
167
+ case "exported":
168
+ break;
169
+ default:
170
+ throw new Error(`Custd lifecycle cannot complete offboarding from state ${current.state || "unknown"}`);
171
+ }
172
+ const download = await this.offboarding.download(options.requestUuid, options);
173
+ requireDownload(download);
174
+ if (exported) {
175
+ requireMatchingExportMetadata(exported, download);
176
+ }
177
+ const exportDelivery = await options.receiveAndVerifyExport({
178
+ tenantSlug: options.tenantSlug,
179
+ requestUuid: options.requestUuid,
180
+ download,
181
+ ...(exported ? { export: exported } : {}),
182
+ });
183
+ if (exportDelivery?.verified !== true) {
184
+ throw new Error("Custd lifecycle export delivery was not verified");
185
+ }
186
+ const acknowledgement = await this.offboarding.acknowledge(options.requestUuid, options);
187
+ requireRequestUuid(acknowledgement, options.requestUuid, "acknowledgement");
188
+ const confirmation = await this.offboarding.confirmRequest(options.requestUuid, options);
189
+ requireRequestUuid(confirmation, options.requestUuid, "confirmation");
190
+ const execution = await this.offboarding.execute(options.requestUuid, options);
191
+ const receipt = await this.offboarding.receipt(options.requestUuid, options);
192
+ requireReceipt(receipt);
193
+ const zeroState = await this.reconcileZeroState({
194
+ tenantSlug: options.tenantSlug,
195
+ requestUuid: options.requestUuid,
196
+ receipt,
197
+ verifyZeroState: options.verifyZeroState,
198
+ });
199
+ return {
200
+ tenantSlug: options.tenantSlug,
201
+ requestUuid: options.requestUuid,
202
+ ...(preview ? { preview } : {}),
203
+ ...(exported ? { export: exported } : {}),
204
+ download,
205
+ exportDelivery,
206
+ acknowledgement,
207
+ execution,
208
+ receipt,
209
+ zeroState,
210
+ };
211
+ }
212
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "file": "browser-script-BvgjdZSO.js",
3
+ "sha256": "c41915184819681a366011fb6e34e046399aa400a08031a95c72f7e535d00f74",
4
+ "bytes": 14138,
5
+ "gzipBytes": 4538,
6
+ "sdkVersion": "2.4.0"
7
+ }
@@ -0,0 +1,429 @@
1
+ //#endregion
2
+ //#region src/index.ts
3
+ var e = class {
4
+ constructor() {
5
+ this.events = [];
6
+ }
7
+ load() {
8
+ return [...this.events];
9
+ }
10
+ save(e) {
11
+ this.events = [...e];
12
+ }
13
+ clear() {
14
+ this.events = [];
15
+ }
16
+ }, t = class {
17
+ constructor(e = "custd_event_queue") {
18
+ this.key = e;
19
+ }
20
+ load() {
21
+ if (typeof localStorage > "u") return [];
22
+ let e = localStorage.getItem(this.key);
23
+ if (!e) return [];
24
+ try {
25
+ let t = JSON.parse(e);
26
+ if (Array.isArray(t)) return t;
27
+ } catch {
28
+ return [];
29
+ }
30
+ return [];
31
+ }
32
+ save(e) {
33
+ typeof localStorage > "u" || localStorage.setItem(this.key, JSON.stringify(e));
34
+ }
35
+ clear() {
36
+ typeof localStorage > "u" || localStorage.removeItem(this.key);
37
+ }
38
+ }, n = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/, r = "custd.environment", i = /^[a-z][a-z0-9-]{0,31}$/;
39
+ function a(e) {
40
+ if (e !== "") {
41
+ if (e !== e.trim() || !i.test(e)) throw Error(`custd: environment ${JSON.stringify(e)} must be lowercase letters, digits and hyphens, at most 32 characters`);
42
+ if (e === "unclassified") throw Error("custd: environment \"unclassified\" is reserved");
43
+ }
44
+ }
45
+ function o(e, t) {
46
+ let n = e.environment || t || "";
47
+ n !== "" && (e.labels = { ...e.labels ?? {} }, e.labels["custd.environment"] === void 0 && (e.labels[r] = n));
48
+ }
49
+ function s(e) {
50
+ if ("resolvedLabels" in e || "vocabularyFingerprint" in e) throw Error("custd: server-owned label fields are not accepted");
51
+ if (e.labels === void 0) return;
52
+ if (e.labels === null || typeof e.labels != "object" || Array.isArray(e.labels)) throw Error("custd: labels must be an object of strings");
53
+ let t = Object.entries(e.labels);
54
+ if (t.length > 16) throw Error("custd: labels may contain at most 16 entries");
55
+ for (let [e, r] of t) {
56
+ if (!n.test(e) || c(e) > 64 || e.startsWith("custd.")) throw Error(`custd: labels.${e} has an invalid key`);
57
+ if (typeof r != "string" || r === "" || r !== r.trim() || c(r) > 128) throw Error(`custd: labels.${e} has an invalid value`);
58
+ }
59
+ }
60
+ function c(e) {
61
+ return new TextEncoder().encode(e).length;
62
+ }
63
+ function l(e) {
64
+ let t = [];
65
+ if (e.eventUuid || t.push("eventUuid"), e.eventTypeSlug || t.push("eventTypeSlug"), e.schemaVersion || t.push("schemaVersion"), e.timestamp || t.push("timestamp"), e.context || t.push("context"), e.payload || t.push("payload"), e.payload?.siteUuid || t.push("payload.siteUuid"), e.context?.device?.type || t.push("context.device.type"), t.length > 0) throw Error(`custd: missing required browser fields: ${t.join(", ")}`);
66
+ a(e.environment ?? ""), s(e);
67
+ }
68
+ function u(e, t = {}) {
69
+ return t.mode === "browser-cookieless" ? {
70
+ ...e,
71
+ eventUuid: e.eventUuid || g(),
72
+ sessionId: e.sessionId ?? "",
73
+ anonymousId: e.anonymousId ?? ""
74
+ } : {
75
+ ...e,
76
+ eventUuid: e.eventUuid || g(),
77
+ sessionId: e.sessionId || g(),
78
+ anonymousId: e.anonymousId || g()
79
+ };
80
+ }
81
+ var d = class extends Error {};
82
+ function f(e) {
83
+ return {
84
+ maxAttempts: e?.maxAttempts ?? 3,
85
+ baseDelayMs: e?.baseDelayMs ?? 200,
86
+ maxDelayMs: e?.maxDelayMs ?? 2e3,
87
+ jitter: e?.jitter ?? .2,
88
+ retryOnStatuses: e?.retryOnStatuses ?? [
89
+ 408,
90
+ 429,
91
+ 500,
92
+ 502,
93
+ 503,
94
+ 504
95
+ ]
96
+ };
97
+ }
98
+ async function p(e, t) {
99
+ let n = 0;
100
+ for (;;) {
101
+ n++;
102
+ try {
103
+ return await t();
104
+ } catch (t) {
105
+ if (!(t instanceof d || t instanceof TypeError) || n >= e.maxAttempts) throw t;
106
+ await h(m(e, n));
107
+ }
108
+ }
109
+ }
110
+ function m(e, t) {
111
+ let n = e.baseDelayMs * 2 ** (t - 1), r = Math.min(n, e.maxDelayMs), i = r * e.jitter * (Math.random() * 2 - 1);
112
+ return Math.max(0, r + i);
113
+ }
114
+ function h(e) {
115
+ return new Promise((t) => setTimeout(t, e));
116
+ }
117
+ function g() {
118
+ return typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (e) => (Number(e) ^ Math.random() * 16 >> Number(e) / 4).toString(16));
119
+ }
120
+ //#endregion
121
+ //#region src/browser-tracker.ts
122
+ var _ = "1.0.0", v = 1e3, y = "[redacted]", b = /^[A-Za-z][A-Za-z0-9._~-]{0,63}$/u, x = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu, S = /^[A-Za-z0-9_-]{24,}$/u, C = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;
123
+ function w(e) {
124
+ return new T(e);
125
+ }
126
+ var T = class {
127
+ constructor(e) {
128
+ this.queue = [], this.installedSpaTracking = !1, this.originalPushState = null, this.originalReplaceState = null, this.onlineHandler = () => void this.flush(), this.pagehideHandler = () => this.flushWithKeepalive(), this.popstateHandler = () => void this.trackPageView(), this.config = e, this.baseUrl = e.baseUrl.replace(/\/$/, ""), this.queueStorage = e.queueStorage ?? W(e.siteUuid, e.persistentQueue === !0), this.retry = f(e.retry), this.maxQueueSize = e.maxQueueSize ?? 1e3, this.queue = this.queueStorage.load(), this.trimQueue(), this.consent = e.consent === "required" ? "denied" : "granted", this.trackingDisabled() && this.clearStoredState(), Z(this.baseUrl, "baseUrl"), ee(e), window.addEventListener("online", this.onlineHandler), window.addEventListener("pagehide", this.pagehideHandler);
129
+ }
130
+ async track(e, t = {}) {
131
+ if (this.trackingDisabled()) return;
132
+ let n = this.buildEvent(e, t);
133
+ if ((this.config.batchSize ?? 0) > 1) {
134
+ this.enqueue(n), this.queue.length >= (this.config.batchSize ?? 0) && await this.flush();
135
+ return;
136
+ }
137
+ await this.sendEvent(n);
138
+ }
139
+ trackPageView() {
140
+ return this.track("page-view", M());
141
+ }
142
+ installSpaTracking() {
143
+ this.installedSpaTracking || (this.installedSpaTracking = !0, this.originalPushState = window.history.pushState, this.originalReplaceState = window.history.replaceState, window.history.pushState = this.wrapHistoryMethod(this.originalPushState), window.history.replaceState = this.wrapHistoryMethod(this.originalReplaceState), window.addEventListener("popstate", this.popstateHandler), this.config.trackInitialPageView !== !1 && this.trackPageView());
144
+ }
145
+ setConsent(e) {
146
+ this.consent = e, e === "denied" && this.clearStoredState();
147
+ }
148
+ async flush() {
149
+ if (this.trackingDisabled()) {
150
+ this.clearStoredState();
151
+ return;
152
+ }
153
+ if (this.queue.length === 0 || !Y()) return;
154
+ let e = this.queue.splice(0, this.queue.length);
155
+ try {
156
+ await this.sendBatch(e);
157
+ } catch (t) {
158
+ throw this.queue.unshift(...e), this.trimQueue(), this.queueStorage.save(this.queue), t;
159
+ }
160
+ this.queueStorage.save(this.queue);
161
+ }
162
+ close() {
163
+ window.removeEventListener("online", this.onlineHandler), window.removeEventListener("pagehide", this.pagehideHandler), window.removeEventListener("popstate", this.popstateHandler), this.originalPushState && (window.history.pushState = this.originalPushState), this.originalReplaceState && (window.history.replaceState = this.originalReplaceState), this.installedSpaTracking = !1, this.originalPushState = null, this.originalReplaceState = null;
164
+ }
165
+ wrapHistoryMethod(e) {
166
+ return ((...t) => {
167
+ let n = e.apply(window.history, t);
168
+ return this.trackPageView(), n;
169
+ });
170
+ }
171
+ trackingDisabled() {
172
+ return !!(this.consent !== "granted" || J());
173
+ }
174
+ enqueue(e) {
175
+ this.queue.push(e), this.trimQueue(), this.queueStorage.save(this.queue);
176
+ }
177
+ trimQueue() {
178
+ this.queue.length > this.maxQueueSize && (this.queue = this.queue.slice(this.queue.length - this.maxQueueSize));
179
+ }
180
+ clearStoredState() {
181
+ this.queue = [], this.queueStorage.clear(), typeof localStorage < "u" && (localStorage.removeItem(E(this.config.siteUuid)), localStorage.removeItem(O(this.config.siteUuid))), typeof sessionStorage < "u" && sessionStorage.removeItem(D(this.config.siteUuid));
182
+ }
183
+ buildEvent(e, t) {
184
+ let n = this.identityFields(), r = u({
185
+ eventTypeSlug: e,
186
+ schemaVersion: _,
187
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
188
+ ...n,
189
+ context: j(),
190
+ payload: {
191
+ siteUuid: this.config.siteUuid,
192
+ ...t
193
+ }
194
+ }, { mode: this.config.identityMode === "extended" ? "producer" : "browser-cookieless" });
195
+ return l(r), o(r, this.config.environment), r;
196
+ }
197
+ identityFields() {
198
+ return this.config.identityMode === "extended" ? {
199
+ anonymousId: U(E(this.config.siteUuid), localStorage),
200
+ sessionId: U(D(this.config.siteUuid), sessionStorage)
201
+ } : {
202
+ anonymousId: "",
203
+ sessionId: ""
204
+ };
205
+ }
206
+ async sendEvent(e) {
207
+ await p(this.retry, async () => {
208
+ I(await fetch(`${this.baseUrl}/api/v1/collect/events`, {
209
+ method: "POST",
210
+ headers: F(this.config.writeKey),
211
+ body: JSON.stringify(e),
212
+ credentials: "omit"
213
+ }));
214
+ });
215
+ }
216
+ async sendBatch(e, t = !1) {
217
+ await p(this.retry, async () => {
218
+ I(await fetch(`${this.baseUrl}/api/v1/collect/events/batch`, {
219
+ method: "POST",
220
+ headers: F(this.config.writeKey),
221
+ body: JSON.stringify({ events: e }),
222
+ credentials: "omit",
223
+ keepalive: t
224
+ }));
225
+ });
226
+ }
227
+ flushWithKeepalive() {
228
+ if (this.trackingDisabled()) {
229
+ this.clearStoredState();
230
+ return;
231
+ }
232
+ if (this.queue.length === 0) return;
233
+ let e = this.queue.splice(0, this.queue.length);
234
+ this.sendBatch(e, !0).then(() => {
235
+ this.queueStorage.save(this.queue);
236
+ }, () => {
237
+ this.queue.unshift(...e), this.trimQueue(), this.queueStorage.save(this.queue);
238
+ });
239
+ }
240
+ };
241
+ function E(e) {
242
+ return `custd:${e}:anonymous_id`;
243
+ }
244
+ function D(e) {
245
+ return `custd:${e}:session_id`;
246
+ }
247
+ function O(e) {
248
+ return `custd:${e}:event_queue`;
249
+ }
250
+ async function k(e) {
251
+ let t = e ?? G(), n = L();
252
+ try {
253
+ let e = t.dataset.siteUuid, r = t.dataset.writeKey;
254
+ if (!e || !r) throw Error("custd: browser script requires data-site-uuid and data-write-key");
255
+ let i = t.dataset.baseUrl ?? new URL(t.src).origin;
256
+ Z(i, "baseUrl");
257
+ let a = await A(i, e), o = w({
258
+ baseUrl: i,
259
+ siteUuid: e,
260
+ writeKey: r,
261
+ identityMode: a.identityMode,
262
+ allowedOrigins: a.allowedOrigins,
263
+ batchSize: Number(t.dataset.batchSize || q(a)),
264
+ consent: K(t, a),
265
+ persistentQueue: t.dataset.persistentQueue === "true"
266
+ });
267
+ return window.custd = {
268
+ track: (e, t) => o.track(e, t),
269
+ trackPageView: () => o.trackPageView(),
270
+ setConsent: (e) => o.setConsent(e)
271
+ }, await B(o, n), o;
272
+ } catch (e) {
273
+ throw V(n, e), H(e), e;
274
+ }
275
+ }
276
+ async function A(e, t) {
277
+ let n = await fetch(`${e.replace(/\/$/, "")}/api/v1/sites/${encodeURIComponent(t)}/config`, { credentials: "omit" });
278
+ if (!n.ok) throw Error(`custd: site config request failed with status ${n.status}`);
279
+ return await n.json();
280
+ }
281
+ function j() {
282
+ return {
283
+ page: {
284
+ path: N(window.location.pathname),
285
+ title: document.title
286
+ },
287
+ device: { type: X() },
288
+ locale: navigator.language,
289
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
290
+ };
291
+ }
292
+ function M() {
293
+ let e = new URL(window.location.href).searchParams, t = e.get("ref") ?? "";
294
+ return e.get("source") !== "powered-by" || !C.test(t) ? {} : {
295
+ utmSource: t,
296
+ utmMedium: "powered-by"
297
+ };
298
+ }
299
+ function N(e) {
300
+ return (e.startsWith("/") ? e : `/${e}`).split("/").map(P).join("/") || "/";
301
+ }
302
+ function P(e) {
303
+ if (e === "") return "";
304
+ let t;
305
+ try {
306
+ t = decodeURIComponent(e);
307
+ } catch {
308
+ return y;
309
+ }
310
+ return !b.test(t) || x.test(t) || /^\d+$/u.test(t) || S.test(t) ? y : t;
311
+ }
312
+ function F(e) {
313
+ return {
314
+ "Content-Type": "application/json",
315
+ Authorization: `Bearer ${e}`
316
+ };
317
+ }
318
+ function I(e) {
319
+ if (!e.ok) throw [
320
+ 408,
321
+ 429,
322
+ 500,
323
+ 502,
324
+ 503,
325
+ 504
326
+ ].includes(e.status) ? new d(`custd: retryable collector status ${e.status}`) : Error(`custd: collector request failed with status ${e.status}`);
327
+ }
328
+ function ee(e) {
329
+ let t = e.allowedOrigins ?? [];
330
+ if (t.length === 0) throw Error("custd: site config must include allowed origins for this site");
331
+ if (!t.includes(window.location.origin)) throw Error("custd: origin is not allowed for this site");
332
+ }
333
+ function L() {
334
+ let e = {
335
+ calls: [],
336
+ promises: []
337
+ };
338
+ return window.custd = {
339
+ track: (t, n) => R(e, {
340
+ type: "track",
341
+ eventTypeSlug: t,
342
+ payload: n
343
+ }),
344
+ trackPageView: () => R(e, { type: "trackPageView" }),
345
+ setConsent: (t) => {
346
+ z(e, {
347
+ type: "setConsent",
348
+ state: t
349
+ });
350
+ }
351
+ }, e;
352
+ }
353
+ function R(e, t) {
354
+ return e.calls.length >= v ? Promise.reject(/* @__PURE__ */ Error("custd: queued global call limit exceeded")) : new Promise((n, r) => {
355
+ e.calls.push(t), e.promises.push({
356
+ resolve: n,
357
+ reject: r
358
+ });
359
+ });
360
+ }
361
+ function z(e, t) {
362
+ e.calls.length >= v || e.calls.push(t);
363
+ }
364
+ async function B(e, t) {
365
+ for (let n of t.calls) {
366
+ let r = n.type === "setConsent" ? void 0 : t.promises.shift();
367
+ try {
368
+ n.type === "track" ? await e.track(n.eventTypeSlug, n.payload) : n.type === "trackPageView" ? await e.trackPageView() : e.setConsent(n.state), r?.resolve();
369
+ } catch (e) {
370
+ r?.reject(e);
371
+ }
372
+ }
373
+ }
374
+ function V(e, t) {
375
+ for (let n of e.promises.splice(0, e.promises.length)) n.reject(t);
376
+ }
377
+ function H(e) {
378
+ window.custd = {
379
+ track: () => Promise.reject(e),
380
+ trackPageView: () => Promise.reject(e),
381
+ setConsent: () => {
382
+ throw e;
383
+ }
384
+ };
385
+ }
386
+ function U(e, t) {
387
+ let n = t.getItem(e);
388
+ if (n) return n;
389
+ let r = $();
390
+ return t.setItem(e, r), r;
391
+ }
392
+ function W(n, r) {
393
+ return !r || typeof localStorage > "u" ? new e() : new t(`custd:${n}:event_queue`);
394
+ }
395
+ function G() {
396
+ let e = document.currentScript;
397
+ if (!e) throw Error("custd: browser script could not find document.currentScript");
398
+ return e;
399
+ }
400
+ function K(e, t) {
401
+ return e.dataset.consent === "granted" ? "granted" : t.identityMode === "extended" ? "required" : void 0;
402
+ }
403
+ function q(e) {
404
+ return e.identityMode === "extended" ? 25 : 1;
405
+ }
406
+ function J() {
407
+ let e = navigator.doNotTrack;
408
+ return e === "1" || e === "yes";
409
+ }
410
+ function Y() {
411
+ return typeof navigator.onLine != "boolean" || navigator.onLine;
412
+ }
413
+ function X() {
414
+ return /Mobi|Android/i.test(navigator.userAgent) ? "mobile" : "desktop";
415
+ }
416
+ function Z(e, t) {
417
+ let n = new URL(e);
418
+ if (n.protocol !== "https:" && !(n.protocol === "http:" && Q(n.hostname))) throw Error(`custd: ${t} must use https unless it targets localhost`);
419
+ }
420
+ function Q(e) {
421
+ return e === "localhost" || e === "127.0.0.1" || e === "::1" || e === "host.docker.internal";
422
+ }
423
+ function $() {
424
+ return typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (e) => (Number(e) ^ Math.random() * 16 >> Number(e) / 4).toString(16));
425
+ }
426
+ //#endregion
427
+ //#region src/browser-script.ts
428
+ k(Array.from(document.scripts).find((e) => e.src === import.meta.url)).then((e) => e.installSpaTracking()).catch(() => void 0);
429
+ //#endregion
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,5 @@
1
+ import { installBrowserTrackerFromScript } from "./browser-tracker.js";
2
+ const script = Array.from(document.scripts).find((candidate) => candidate.src === import.meta.url);
3
+ void installBrowserTrackerFromScript(script)
4
+ .then((tracker) => tracker.installSpaTracking())
5
+ .catch(() => undefined);