@cross-deck/web 1.4.2 → 1.5.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.
- package/CHANGELOG.md +74 -0
- package/README.md +94 -0
- package/dist/contracts 2.json +378 -0
- package/dist/contracts.json +378 -0
- package/dist/crossdeck.umd.min 2.js +3 -0
- package/dist/crossdeck.umd.min.js +2 -2
- package/dist/crossdeck.umd.min.js 2.map +1 -0
- package/dist/crossdeck.umd.min.js.map +1 -1
- package/dist/error-codes 2.json +196 -0
- package/dist/error-codes.json +1 -1
- package/dist/index 2.cjs +4778 -0
- package/dist/index 2.mjs +4742 -0
- package/dist/index.cjs +457 -0
- package/dist/index.cjs 2.map +1 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d 2.mts +938 -0
- package/dist/index.d 2.ts +938 -0
- package/dist/index.d.mts +174 -1
- package/dist/index.d.ts +174 -1
- package/dist/index.mjs +456 -0
- package/dist/index.mjs 2.map +1 -0
- package/dist/index.mjs.map +1 -1
- package/dist/react 2.cjs +4220 -0
- package/dist/react 2.mjs +4193 -0
- package/dist/react.cjs +31 -0
- package/dist/react.cjs 2.map +1 -0
- package/dist/react.cjs.map +1 -1
- package/dist/react.d 2.mts +91 -0
- package/dist/react.d 2.ts +91 -0
- package/dist/react.mjs +31 -0
- package/dist/react.mjs 2.map +1 -0
- package/dist/react.mjs.map +1 -1
- package/dist/types-Bu3jbmdq.d 2.mts +314 -0
- package/dist/types-Bu3jbmdq.d 2.ts +314 -0
- package/dist/vue 2.cjs +4185 -0
- package/dist/vue 2.mjs +4159 -0
- package/dist/vue.cjs +31 -0
- package/dist/vue.cjs 2.map +1 -0
- package/dist/vue.cjs.map +1 -1
- package/dist/vue.d 2.mts +37 -0
- package/dist/vue.d 2.ts +37 -0
- package/dist/vue.mjs +31 -0
- package/dist/vue.mjs 2.map +1 -0
- package/dist/vue.mjs.map +1 -1
- package/package.json +3 -2
package/dist/react 2.mjs
ADDED
|
@@ -0,0 +1,4193 @@
|
|
|
1
|
+
// src/react.ts
|
|
2
|
+
import { useEffect, useRef, useState } from "react";
|
|
3
|
+
|
|
4
|
+
// src/errors.ts
|
|
5
|
+
var CrossdeckError = class _CrossdeckError extends Error {
|
|
6
|
+
constructor(payload) {
|
|
7
|
+
super(payload.message);
|
|
8
|
+
this.name = "CrossdeckError";
|
|
9
|
+
this.type = payload.type;
|
|
10
|
+
this.code = payload.code;
|
|
11
|
+
this.requestId = payload.requestId;
|
|
12
|
+
this.status = payload.status;
|
|
13
|
+
this.retryAfterMs = payload.retryAfterMs;
|
|
14
|
+
Object.setPrototypeOf(this, _CrossdeckError.prototype);
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
async function crossdeckErrorFromResponse(res) {
|
|
18
|
+
const requestId = res.headers.get("x-request-id") ?? void 0;
|
|
19
|
+
const retryAfterMs = parseRetryAfterHeader(res.headers.get("retry-after"));
|
|
20
|
+
let body;
|
|
21
|
+
try {
|
|
22
|
+
body = await res.json();
|
|
23
|
+
} catch {
|
|
24
|
+
body = null;
|
|
25
|
+
}
|
|
26
|
+
const envelope = body?.error;
|
|
27
|
+
if (envelope && typeof envelope.type === "string" && typeof envelope.code === "string") {
|
|
28
|
+
return new CrossdeckError({
|
|
29
|
+
type: envelope.type,
|
|
30
|
+
code: envelope.code,
|
|
31
|
+
message: envelope.message ?? `HTTP ${res.status}`,
|
|
32
|
+
requestId: envelope.request_id ?? requestId,
|
|
33
|
+
status: res.status,
|
|
34
|
+
retryAfterMs
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
return new CrossdeckError({
|
|
38
|
+
type: typeMapForStatus(res.status),
|
|
39
|
+
code: `http_${res.status}`,
|
|
40
|
+
message: `HTTP ${res.status} ${res.statusText || ""}`.trim(),
|
|
41
|
+
requestId,
|
|
42
|
+
status: res.status,
|
|
43
|
+
retryAfterMs
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
function parseRetryAfterHeader(value) {
|
|
47
|
+
if (!value) return void 0;
|
|
48
|
+
const trimmed = value.trim();
|
|
49
|
+
if (!trimmed) return void 0;
|
|
50
|
+
if (/^\d+(\.\d+)?$/.test(trimmed)) {
|
|
51
|
+
const secs = Number(trimmed);
|
|
52
|
+
if (!Number.isFinite(secs) || secs < 0) return void 0;
|
|
53
|
+
return Math.round(secs * 1e3);
|
|
54
|
+
}
|
|
55
|
+
if (!/[a-zA-Z,/:]/.test(trimmed)) return void 0;
|
|
56
|
+
const target = Date.parse(trimmed);
|
|
57
|
+
if (!Number.isFinite(target)) return void 0;
|
|
58
|
+
const delta = target - Date.now();
|
|
59
|
+
return delta > 0 ? delta : 0;
|
|
60
|
+
}
|
|
61
|
+
function typeMapForStatus(status) {
|
|
62
|
+
if (status === 401) return "authentication_error";
|
|
63
|
+
if (status === 403) return "permission_error";
|
|
64
|
+
if (status === 429) return "rate_limit_error";
|
|
65
|
+
if (status >= 400 && status < 500) return "invalid_request_error";
|
|
66
|
+
return "internal_error";
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// src/_version.ts
|
|
70
|
+
var SDK_VERSION = "1.4.2";
|
|
71
|
+
var SDK_NAME = "@cross-deck/web";
|
|
72
|
+
|
|
73
|
+
// src/http.ts
|
|
74
|
+
var DEFAULT_BASE_URL = "https://api.cross-deck.com/v1";
|
|
75
|
+
var DEFAULT_TIMEOUT_MS = 15e3;
|
|
76
|
+
var HttpClient = class {
|
|
77
|
+
constructor(config) {
|
|
78
|
+
this.config = config;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Issue a request. `path` is relative to the configured baseUrl
|
|
82
|
+
* ("/entitlements", "/identity/alias", etc.).
|
|
83
|
+
*
|
|
84
|
+
* Throws CrossdeckError on:
|
|
85
|
+
* - Network failure (`type: "network_error"`)
|
|
86
|
+
* - Non-2xx response (typed from the body envelope)
|
|
87
|
+
* - JSON parse failure on a 2xx (treated as `internal_error`)
|
|
88
|
+
*/
|
|
89
|
+
async request(method, path, options = {}) {
|
|
90
|
+
if (this.config.localDevMode) {
|
|
91
|
+
return synthesizeLocalDevResponse(path);
|
|
92
|
+
}
|
|
93
|
+
const url = this.buildUrl(path, options.query);
|
|
94
|
+
const headers = {
|
|
95
|
+
Authorization: `Bearer ${this.config.publicKey}`,
|
|
96
|
+
"Crossdeck-Sdk-Version": `${SDK_NAME}@${this.config.sdkVersion}`,
|
|
97
|
+
Accept: "application/json"
|
|
98
|
+
};
|
|
99
|
+
if (options.idempotencyKey) {
|
|
100
|
+
headers["Idempotency-Key"] = options.idempotencyKey;
|
|
101
|
+
}
|
|
102
|
+
let bodyInit;
|
|
103
|
+
if (options.body !== void 0) {
|
|
104
|
+
headers["Content-Type"] = "application/json";
|
|
105
|
+
bodyInit = JSON.stringify(options.body);
|
|
106
|
+
}
|
|
107
|
+
const effectiveTimeout = options.timeoutMs ?? this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
108
|
+
const controller = typeof AbortController !== "undefined" && effectiveTimeout > 0 ? new AbortController() : null;
|
|
109
|
+
let timeoutHandle = null;
|
|
110
|
+
if (controller && effectiveTimeout > 0) {
|
|
111
|
+
timeoutHandle = setTimeout(() => controller.abort(), effectiveTimeout);
|
|
112
|
+
}
|
|
113
|
+
let response;
|
|
114
|
+
try {
|
|
115
|
+
response = await fetch(url, {
|
|
116
|
+
method,
|
|
117
|
+
headers,
|
|
118
|
+
body: bodyInit,
|
|
119
|
+
keepalive: options.keepalive === true,
|
|
120
|
+
signal: controller?.signal
|
|
121
|
+
});
|
|
122
|
+
} catch (err) {
|
|
123
|
+
const aborted = controller?.signal?.aborted === true;
|
|
124
|
+
throw new CrossdeckError({
|
|
125
|
+
type: "network_error",
|
|
126
|
+
code: aborted ? "request_timeout" : "fetch_failed",
|
|
127
|
+
message: aborted ? `Request to ${path} aborted after ${effectiveTimeout}ms` : err instanceof Error ? err.message : "fetch failed"
|
|
128
|
+
});
|
|
129
|
+
} finally {
|
|
130
|
+
if (timeoutHandle !== null) clearTimeout(timeoutHandle);
|
|
131
|
+
}
|
|
132
|
+
if (!response.ok) {
|
|
133
|
+
throw await crossdeckErrorFromResponse(response);
|
|
134
|
+
}
|
|
135
|
+
if (response.status === 204) return void 0;
|
|
136
|
+
try {
|
|
137
|
+
return await response.json();
|
|
138
|
+
} catch (err) {
|
|
139
|
+
throw new CrossdeckError({
|
|
140
|
+
type: "internal_error",
|
|
141
|
+
code: "invalid_json_response",
|
|
142
|
+
message: "Server returned a 2xx with an unparseable body.",
|
|
143
|
+
requestId: response.headers.get("x-request-id") ?? void 0,
|
|
144
|
+
status: response.status
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Whether this client is in localhost dev-mode short-circuit. Used
|
|
150
|
+
* by other SDK pieces (event-queue) to skip network-bound work
|
|
151
|
+
* entirely rather than going through synthesizeLocalDevResponse.
|
|
152
|
+
*/
|
|
153
|
+
get isLocalDevMode() {
|
|
154
|
+
return this.config.localDevMode === true;
|
|
155
|
+
}
|
|
156
|
+
buildUrl(path, query) {
|
|
157
|
+
const base = this.config.baseUrl.replace(/\/+$/, "");
|
|
158
|
+
const cleanPath = path.startsWith("/") ? path : `/${path}`;
|
|
159
|
+
let url = base + cleanPath;
|
|
160
|
+
if (query) {
|
|
161
|
+
const params = new URLSearchParams();
|
|
162
|
+
for (const [k, v] of Object.entries(query)) {
|
|
163
|
+
if (typeof v === "string" && v.length > 0) params.append(k, v);
|
|
164
|
+
}
|
|
165
|
+
const qs = params.toString();
|
|
166
|
+
if (qs) url += (url.includes("?") ? "&" : "?") + qs;
|
|
167
|
+
}
|
|
168
|
+
return url;
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
var cachedLocalCdcust = null;
|
|
172
|
+
function synthesizeLocalDevResponse(path) {
|
|
173
|
+
if (path.startsWith("/sdk/heartbeat")) {
|
|
174
|
+
return {
|
|
175
|
+
object: "heartbeat",
|
|
176
|
+
ok: true,
|
|
177
|
+
projectId: "proj_local_dev",
|
|
178
|
+
appId: "app_local_dev",
|
|
179
|
+
platform: "web",
|
|
180
|
+
env: "sandbox",
|
|
181
|
+
serverTime: Date.now()
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
if (path.startsWith("/identity/alias")) {
|
|
185
|
+
if (!cachedLocalCdcust) {
|
|
186
|
+
const tail = typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID().replace(/-/g, "").slice(0, 16) : Math.random().toString(36).slice(2, 18);
|
|
187
|
+
cachedLocalCdcust = `cdcust_local_${tail}`;
|
|
188
|
+
}
|
|
189
|
+
return {
|
|
190
|
+
object: "alias_result",
|
|
191
|
+
crossdeckCustomerId: cachedLocalCdcust,
|
|
192
|
+
linked: [],
|
|
193
|
+
mergePending: false,
|
|
194
|
+
env: "sandbox"
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
if (path.startsWith("/entitlements")) {
|
|
198
|
+
return {
|
|
199
|
+
object: "list",
|
|
200
|
+
data: [],
|
|
201
|
+
crossdeckCustomerId: cachedLocalCdcust ?? "",
|
|
202
|
+
env: "sandbox"
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
if (path.startsWith("/events")) {
|
|
206
|
+
return {
|
|
207
|
+
object: "list",
|
|
208
|
+
received: 0,
|
|
209
|
+
env: "sandbox"
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
return {};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// src/identity.ts
|
|
216
|
+
var KEY_ANON = "anon_id";
|
|
217
|
+
var KEY_CDCUST = "cdcust_id";
|
|
218
|
+
var IdentityStore = class {
|
|
219
|
+
constructor(primary, prefix, secondary) {
|
|
220
|
+
this.primary = primary;
|
|
221
|
+
this.prefix = prefix;
|
|
222
|
+
this.secondary = secondary ?? null;
|
|
223
|
+
const anonFromPrimary = primary.getItem(prefix + KEY_ANON);
|
|
224
|
+
const cdcustFromPrimary = primary.getItem(prefix + KEY_CDCUST);
|
|
225
|
+
const anonFromSecondary = this.secondary?.getItem(prefix + KEY_ANON) ?? null;
|
|
226
|
+
const cdcustFromSecondary = this.secondary?.getItem(prefix + KEY_CDCUST) ?? null;
|
|
227
|
+
const anon = anonFromPrimary ?? anonFromSecondary;
|
|
228
|
+
const cdcust = cdcustFromPrimary ?? cdcustFromSecondary;
|
|
229
|
+
this.state = {
|
|
230
|
+
anonymousId: anon ?? this.mintAnonymousId(),
|
|
231
|
+
crossdeckCustomerId: cdcust
|
|
232
|
+
};
|
|
233
|
+
if (!anonFromPrimary || !anonFromSecondary) {
|
|
234
|
+
this.writeBoth(prefix + KEY_ANON, this.state.anonymousId);
|
|
235
|
+
}
|
|
236
|
+
if (cdcust && (!cdcustFromPrimary || !cdcustFromSecondary)) {
|
|
237
|
+
this.writeBoth(prefix + KEY_CDCUST, cdcust);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
/** Return the persisted anonymous device ID (always set). */
|
|
241
|
+
get anonymousId() {
|
|
242
|
+
return this.state.anonymousId;
|
|
243
|
+
}
|
|
244
|
+
/** Return the resolved crossdeckCustomerId once we have one, else null. */
|
|
245
|
+
get crossdeckCustomerId() {
|
|
246
|
+
return this.state.crossdeckCustomerId;
|
|
247
|
+
}
|
|
248
|
+
/** Persist a newly-resolved Crossdeck customer ID. */
|
|
249
|
+
setCrossdeckCustomerId(value) {
|
|
250
|
+
this.state.crossdeckCustomerId = value;
|
|
251
|
+
this.writeBoth(this.prefix + KEY_CDCUST, value);
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Wipe persisted identity. Called by reset() — used when an end-user
|
|
255
|
+
* logs out. After reset the SDK mints a new anonymousId so the next
|
|
256
|
+
* pre-login session is a fresh customer in the identity graph.
|
|
257
|
+
*/
|
|
258
|
+
reset() {
|
|
259
|
+
this.deleteBoth(this.prefix + KEY_ANON);
|
|
260
|
+
this.deleteBoth(this.prefix + KEY_CDCUST);
|
|
261
|
+
this.state = {
|
|
262
|
+
anonymousId: this.mintAnonymousId(),
|
|
263
|
+
crossdeckCustomerId: null
|
|
264
|
+
};
|
|
265
|
+
this.writeBoth(this.prefix + KEY_ANON, this.state.anonymousId);
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Generate an anonymousId. Crockford-ish base32 timestamp + random
|
|
269
|
+
* suffix. Same shape Stripe / Segment / others use — sortable, log-
|
|
270
|
+
* friendly, no PII.
|
|
271
|
+
*/
|
|
272
|
+
mintAnonymousId() {
|
|
273
|
+
const ts = Date.now().toString(36);
|
|
274
|
+
const rand = randomChars(10);
|
|
275
|
+
return `anon_${ts}${rand}`;
|
|
276
|
+
}
|
|
277
|
+
writeBoth(key, value) {
|
|
278
|
+
try {
|
|
279
|
+
this.primary.setItem(key, value);
|
|
280
|
+
} catch {
|
|
281
|
+
}
|
|
282
|
+
if (this.secondary) {
|
|
283
|
+
try {
|
|
284
|
+
this.secondary.setItem(key, value);
|
|
285
|
+
} catch {
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
deleteBoth(key) {
|
|
290
|
+
try {
|
|
291
|
+
this.primary.removeItem(key);
|
|
292
|
+
} catch {
|
|
293
|
+
}
|
|
294
|
+
if (this.secondary) {
|
|
295
|
+
try {
|
|
296
|
+
this.secondary.removeItem(key);
|
|
297
|
+
} catch {
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
function randomChars(count) {
|
|
303
|
+
const alphabet = "0123456789abcdefghijklmnopqrstuvwxyz";
|
|
304
|
+
const out = [];
|
|
305
|
+
const cryptoApi = globalThis.crypto;
|
|
306
|
+
if (cryptoApi?.getRandomValues) {
|
|
307
|
+
const buf = new Uint8Array(count);
|
|
308
|
+
cryptoApi.getRandomValues(buf);
|
|
309
|
+
for (let i = 0; i < count; i++) {
|
|
310
|
+
out.push(alphabet[buf[i] % alphabet.length] ?? "0");
|
|
311
|
+
}
|
|
312
|
+
} else {
|
|
313
|
+
for (let i = 0; i < count; i++) {
|
|
314
|
+
out.push(alphabet[Math.floor(Math.random() * alphabet.length)] ?? "0");
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
return out.join("");
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// src/hash.ts
|
|
321
|
+
var K = new Uint32Array([
|
|
322
|
+
1116352408,
|
|
323
|
+
1899447441,
|
|
324
|
+
3049323471,
|
|
325
|
+
3921009573,
|
|
326
|
+
961987163,
|
|
327
|
+
1508970993,
|
|
328
|
+
2453635748,
|
|
329
|
+
2870763221,
|
|
330
|
+
3624381080,
|
|
331
|
+
310598401,
|
|
332
|
+
607225278,
|
|
333
|
+
1426881987,
|
|
334
|
+
1925078388,
|
|
335
|
+
2162078206,
|
|
336
|
+
2614888103,
|
|
337
|
+
3248222580,
|
|
338
|
+
3835390401,
|
|
339
|
+
4022224774,
|
|
340
|
+
264347078,
|
|
341
|
+
604807628,
|
|
342
|
+
770255983,
|
|
343
|
+
1249150122,
|
|
344
|
+
1555081692,
|
|
345
|
+
1996064986,
|
|
346
|
+
2554220882,
|
|
347
|
+
2821834349,
|
|
348
|
+
2952996808,
|
|
349
|
+
3210313671,
|
|
350
|
+
3336571891,
|
|
351
|
+
3584528711,
|
|
352
|
+
113926993,
|
|
353
|
+
338241895,
|
|
354
|
+
666307205,
|
|
355
|
+
773529912,
|
|
356
|
+
1294757372,
|
|
357
|
+
1396182291,
|
|
358
|
+
1695183700,
|
|
359
|
+
1986661051,
|
|
360
|
+
2177026350,
|
|
361
|
+
2456956037,
|
|
362
|
+
2730485921,
|
|
363
|
+
2820302411,
|
|
364
|
+
3259730800,
|
|
365
|
+
3345764771,
|
|
366
|
+
3516065817,
|
|
367
|
+
3600352804,
|
|
368
|
+
4094571909,
|
|
369
|
+
275423344,
|
|
370
|
+
430227734,
|
|
371
|
+
506948616,
|
|
372
|
+
659060556,
|
|
373
|
+
883997877,
|
|
374
|
+
958139571,
|
|
375
|
+
1322822218,
|
|
376
|
+
1537002063,
|
|
377
|
+
1747873779,
|
|
378
|
+
1955562222,
|
|
379
|
+
2024104815,
|
|
380
|
+
2227730452,
|
|
381
|
+
2361852424,
|
|
382
|
+
2428436474,
|
|
383
|
+
2756734187,
|
|
384
|
+
3204031479,
|
|
385
|
+
3329325298
|
|
386
|
+
]);
|
|
387
|
+
function utf8Bytes(input) {
|
|
388
|
+
if (typeof TextEncoder !== "undefined") {
|
|
389
|
+
return new TextEncoder().encode(input);
|
|
390
|
+
}
|
|
391
|
+
const out = [];
|
|
392
|
+
for (let i = 0; i < input.length; i++) {
|
|
393
|
+
let codePoint = input.charCodeAt(i);
|
|
394
|
+
if (codePoint >= 55296 && codePoint <= 56319 && i + 1 < input.length) {
|
|
395
|
+
const next = input.charCodeAt(i + 1);
|
|
396
|
+
if (next >= 56320 && next <= 57343) {
|
|
397
|
+
codePoint = 65536 + (codePoint - 55296 << 10) + (next - 56320);
|
|
398
|
+
i++;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
if (codePoint < 128) {
|
|
402
|
+
out.push(codePoint);
|
|
403
|
+
} else if (codePoint < 2048) {
|
|
404
|
+
out.push(192 | codePoint >> 6);
|
|
405
|
+
out.push(128 | codePoint & 63);
|
|
406
|
+
} else if (codePoint < 65536) {
|
|
407
|
+
out.push(224 | codePoint >> 12);
|
|
408
|
+
out.push(128 | codePoint >> 6 & 63);
|
|
409
|
+
out.push(128 | codePoint & 63);
|
|
410
|
+
} else {
|
|
411
|
+
out.push(240 | codePoint >> 18);
|
|
412
|
+
out.push(128 | codePoint >> 12 & 63);
|
|
413
|
+
out.push(128 | codePoint >> 6 & 63);
|
|
414
|
+
out.push(128 | codePoint & 63);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
return new Uint8Array(out);
|
|
418
|
+
}
|
|
419
|
+
function sha256Hex(input) {
|
|
420
|
+
const bytes = utf8Bytes(input);
|
|
421
|
+
const bitLength = bytes.length * 8;
|
|
422
|
+
const blockCount = Math.floor((bytes.length + 9 + 63) / 64);
|
|
423
|
+
const padded = new Uint8Array(blockCount * 64);
|
|
424
|
+
padded.set(bytes);
|
|
425
|
+
padded[bytes.length] = 128;
|
|
426
|
+
const high = Math.floor(bitLength / 4294967296);
|
|
427
|
+
const low = bitLength >>> 0;
|
|
428
|
+
const lenOffset = padded.length - 8;
|
|
429
|
+
padded[lenOffset + 0] = high >>> 24 & 255;
|
|
430
|
+
padded[lenOffset + 1] = high >>> 16 & 255;
|
|
431
|
+
padded[lenOffset + 2] = high >>> 8 & 255;
|
|
432
|
+
padded[lenOffset + 3] = high & 255;
|
|
433
|
+
padded[lenOffset + 4] = low >>> 24 & 255;
|
|
434
|
+
padded[lenOffset + 5] = low >>> 16 & 255;
|
|
435
|
+
padded[lenOffset + 6] = low >>> 8 & 255;
|
|
436
|
+
padded[lenOffset + 7] = low & 255;
|
|
437
|
+
const H = new Uint32Array([
|
|
438
|
+
1779033703,
|
|
439
|
+
3144134277,
|
|
440
|
+
1013904242,
|
|
441
|
+
2773480762,
|
|
442
|
+
1359893119,
|
|
443
|
+
2600822924,
|
|
444
|
+
528734635,
|
|
445
|
+
1541459225
|
|
446
|
+
]);
|
|
447
|
+
const W = new Uint32Array(64);
|
|
448
|
+
for (let block = 0; block < blockCount; block++) {
|
|
449
|
+
const offset = block * 64;
|
|
450
|
+
for (let t = 0; t < 16; t++) {
|
|
451
|
+
W[t] = (padded[offset + t * 4] << 24 | padded[offset + t * 4 + 1] << 16 | padded[offset + t * 4 + 2] << 8 | padded[offset + t * 4 + 3]) >>> 0;
|
|
452
|
+
}
|
|
453
|
+
for (let t = 16; t < 64; t++) {
|
|
454
|
+
const w15 = W[t - 15];
|
|
455
|
+
const w2 = W[t - 2];
|
|
456
|
+
const s0 = (w15 >>> 7 | w15 << 25) ^ (w15 >>> 18 | w15 << 14) ^ w15 >>> 3;
|
|
457
|
+
const s1 = (w2 >>> 17 | w2 << 15) ^ (w2 >>> 19 | w2 << 13) ^ w2 >>> 10;
|
|
458
|
+
W[t] = W[t - 16] + s0 + W[t - 7] + s1 >>> 0;
|
|
459
|
+
}
|
|
460
|
+
let a = H[0], b = H[1], c = H[2], d = H[3];
|
|
461
|
+
let e = H[4], f = H[5], g = H[6], h = H[7];
|
|
462
|
+
for (let t = 0; t < 64; t++) {
|
|
463
|
+
const S1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7);
|
|
464
|
+
const ch = e & f ^ ~e & g;
|
|
465
|
+
const temp1 = h + S1 + ch + K[t] + W[t] >>> 0;
|
|
466
|
+
const S0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10);
|
|
467
|
+
const maj = a & b ^ a & c ^ b & c;
|
|
468
|
+
const temp2 = S0 + maj >>> 0;
|
|
469
|
+
h = g;
|
|
470
|
+
g = f;
|
|
471
|
+
f = e;
|
|
472
|
+
e = d + temp1 >>> 0;
|
|
473
|
+
d = c;
|
|
474
|
+
c = b;
|
|
475
|
+
b = a;
|
|
476
|
+
a = temp1 + temp2 >>> 0;
|
|
477
|
+
}
|
|
478
|
+
H[0] = H[0] + a >>> 0;
|
|
479
|
+
H[1] = H[1] + b >>> 0;
|
|
480
|
+
H[2] = H[2] + c >>> 0;
|
|
481
|
+
H[3] = H[3] + d >>> 0;
|
|
482
|
+
H[4] = H[4] + e >>> 0;
|
|
483
|
+
H[5] = H[5] + f >>> 0;
|
|
484
|
+
H[6] = H[6] + g >>> 0;
|
|
485
|
+
H[7] = H[7] + h >>> 0;
|
|
486
|
+
}
|
|
487
|
+
let hex = "";
|
|
488
|
+
for (let i = 0; i < 8; i++) {
|
|
489
|
+
hex += H[i].toString(16).padStart(8, "0");
|
|
490
|
+
}
|
|
491
|
+
return hex;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
// src/entitlement-cache.ts
|
|
495
|
+
var DEFAULT_STALE_AFTER_MS = 24 * 60 * 60 * 1e3;
|
|
496
|
+
var ANON_SUFFIX = "_anon";
|
|
497
|
+
var INDEX_SUFFIX = "_index";
|
|
498
|
+
var EntitlementCache = class _EntitlementCache {
|
|
499
|
+
/**
|
|
500
|
+
* @param storage Device storage adapter. When omitted (tests) or
|
|
501
|
+
* a MemoryStorage (strict-consent / no-persistence
|
|
502
|
+
* mode) the cache is session-only — durability is
|
|
503
|
+
* simply absent, never wrong.
|
|
504
|
+
* @param storageKeyPrefix Prefix used to derive per-user storage keys
|
|
505
|
+
* (`<prefix>:<sha256(userId)>`). Default
|
|
506
|
+
* `crossdeck:entitlements`. The trailing user
|
|
507
|
+
* suffix is filled at identify() / reset()
|
|
508
|
+
* time — see [[setUserKey]].
|
|
509
|
+
* @param staleAfterMs Age past which last-known-good is flagged stale
|
|
510
|
+
* even without a failed refresh. Default 24h.
|
|
511
|
+
*/
|
|
512
|
+
constructor(storage, storageKeyPrefix = "crossdeck:entitlements", staleAfterMs = DEFAULT_STALE_AFTER_MS) {
|
|
513
|
+
this.all = [];
|
|
514
|
+
this.lastUpdated = 0;
|
|
515
|
+
this.lastRefreshFailedAt = 0;
|
|
516
|
+
this.listeners = /* @__PURE__ */ new Set();
|
|
517
|
+
this.listenerErrorCount = 0;
|
|
518
|
+
this.currentSuffix = ANON_SUFFIX;
|
|
519
|
+
this.storage = storage;
|
|
520
|
+
this.storageKeyPrefix = storageKeyPrefix;
|
|
521
|
+
this.staleAfterMs = staleAfterMs;
|
|
522
|
+
this.hydrate();
|
|
523
|
+
}
|
|
524
|
+
/** The full storage key the current-user blob is persisted under. */
|
|
525
|
+
get storageKey() {
|
|
526
|
+
return `${this.storageKeyPrefix}:${this.currentSuffix}`;
|
|
527
|
+
}
|
|
528
|
+
/** Key of the index blob — a JSON array of every suffix we've
|
|
529
|
+
* written. Used by clearAll() to scope a logout-wipe. */
|
|
530
|
+
get indexKey() {
|
|
531
|
+
return `${this.storageKeyPrefix}:${INDEX_SUFFIX}`;
|
|
532
|
+
}
|
|
533
|
+
/** Derive a stable suffix for a developerUserId via SHA-256. The
|
|
534
|
+
* raw userId never lands in the storage key — protects against
|
|
535
|
+
* accidentally leaking email-style identifiers through DevTools
|
|
536
|
+
* inspection. Pass `null` to switch back to the anonymous slot. */
|
|
537
|
+
static suffixForUserId(userId) {
|
|
538
|
+
if (userId == null || userId === "") return ANON_SUFFIX;
|
|
539
|
+
return sha256Hex(userId);
|
|
540
|
+
}
|
|
541
|
+
/**
|
|
542
|
+
* Switch the cache to a different user's storage slot. Bank-grade
|
|
543
|
+
* three-layer isolation:
|
|
544
|
+
* (a) Physical key separation — `<prefix>:<sha256(userId)>` so
|
|
545
|
+
* a user-switch can't physically read prior user's data
|
|
546
|
+
* even if the in-memory clear was skipped.
|
|
547
|
+
* (b) Unconditional in-memory clear — invoked whenever the
|
|
548
|
+
* active suffix changes, even on same-id re-identify.
|
|
549
|
+
* (c) Re-hydrate from the new slot — a returning user observes
|
|
550
|
+
* their last-known-good cache from storage immediately.
|
|
551
|
+
*
|
|
552
|
+
* Caller (identify() / reset()) MUST invoke this BEFORE the next
|
|
553
|
+
* setFromList() so the write lands under the right key.
|
|
554
|
+
*/
|
|
555
|
+
setUserKey(userId) {
|
|
556
|
+
const nextSuffix = _EntitlementCache.suffixForUserId(userId);
|
|
557
|
+
if (nextSuffix === this.currentSuffix) {
|
|
558
|
+
this.all = [];
|
|
559
|
+
this.lastUpdated = 0;
|
|
560
|
+
this.lastRefreshFailedAt = 0;
|
|
561
|
+
this.notify();
|
|
562
|
+
this.hydrate();
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
this.currentSuffix = nextSuffix;
|
|
566
|
+
this.all = [];
|
|
567
|
+
this.lastUpdated = 0;
|
|
568
|
+
this.lastRefreshFailedAt = 0;
|
|
569
|
+
this.hydrate();
|
|
570
|
+
this.notify();
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* Sync read — true iff the entitlement is currently granting access.
|
|
574
|
+
*
|
|
575
|
+
* Served from last-known-good: a stale cache (server unreachable since
|
|
576
|
+
* the last successful fetch) still answers true for a still-valid
|
|
577
|
+
* entitlement. The ONLY thing that turns it false is the entitlement's
|
|
578
|
+
* own expiry (validUntil) — never overall cache staleness.
|
|
579
|
+
*/
|
|
580
|
+
isEntitled(key) {
|
|
581
|
+
const nowSec = Date.now() / 1e3;
|
|
582
|
+
return this.all.some(
|
|
583
|
+
(e) => e.key === key && e.isActive && (e.validUntil == null || e.validUntil > nowSec)
|
|
584
|
+
);
|
|
585
|
+
}
|
|
586
|
+
/** Full snapshot for callers that need source / validUntil details. */
|
|
587
|
+
list() {
|
|
588
|
+
return this.all.slice();
|
|
589
|
+
}
|
|
590
|
+
/** When the cache was last refreshed from the server. 0 means "never". */
|
|
591
|
+
get freshness() {
|
|
592
|
+
return this.lastUpdated;
|
|
593
|
+
}
|
|
594
|
+
/**
|
|
595
|
+
* Whether the cache is knowingly serving older-than-trustworthy data.
|
|
596
|
+
*
|
|
597
|
+
* True when the most recent refresh ATTEMPT failed (Crossdeck
|
|
598
|
+
* unreachable since the last success — the outage case, distinct from
|
|
599
|
+
* a benign idle tab that simply hasn't re-fetched), OR when
|
|
600
|
+
* last-known-good has aged past staleAfterMs.
|
|
601
|
+
*
|
|
602
|
+
* isStale never changes what isEntitled() returns — the cache still
|
|
603
|
+
* serves last-known-good. It exists so the staleness is observable
|
|
604
|
+
* (diagnostics()) instead of an unbounded silent window where a
|
|
605
|
+
* revoked customer holds access with nobody able to see it.
|
|
606
|
+
*/
|
|
607
|
+
get isStale() {
|
|
608
|
+
if (this.lastRefreshFailedAt > this.lastUpdated) return true;
|
|
609
|
+
return this.lastUpdated > 0 && Date.now() - this.lastUpdated > this.staleAfterMs;
|
|
610
|
+
}
|
|
611
|
+
/** Epoch ms of the last failed refresh attempt. 0 if none since the last success. */
|
|
612
|
+
get refreshFailedAt() {
|
|
613
|
+
return this.lastRefreshFailedAt;
|
|
614
|
+
}
|
|
615
|
+
get listenerErrors() {
|
|
616
|
+
return this.listenerErrorCount;
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* Record that a refresh attempt failed (Crossdeck unreachable / a
|
|
620
|
+
* transient error). The SDK's getEntitlements() calls this in its
|
|
621
|
+
* catch path. It does NOT touch the cached entitlements — last-known-
|
|
622
|
+
* good keeps serving — it only flips isStale so the staleness shows
|
|
623
|
+
* up in diagnostics() rather than being silent.
|
|
624
|
+
*/
|
|
625
|
+
markRefreshFailed() {
|
|
626
|
+
this.lastRefreshFailedAt = Date.now();
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* Replace the cache with a fresh server response and persist it to
|
|
630
|
+
* device storage so it survives a reload / app restart.
|
|
631
|
+
*
|
|
632
|
+
* Called ONLY after a successful server read — a failed fetch throws
|
|
633
|
+
* before it reaches here, so last-known-good is preserved through an
|
|
634
|
+
* outage. A success also clears the stale flag.
|
|
635
|
+
*/
|
|
636
|
+
setFromList(entitlements) {
|
|
637
|
+
this.all = entitlements.slice();
|
|
638
|
+
this.lastUpdated = Date.now();
|
|
639
|
+
this.lastRefreshFailedAt = 0;
|
|
640
|
+
this.persist();
|
|
641
|
+
this.recordSuffixInIndex(this.currentSuffix);
|
|
642
|
+
this.notify();
|
|
643
|
+
}
|
|
644
|
+
/**
|
|
645
|
+
* Wipe the CURRENT user's slot. Used internally when a single
|
|
646
|
+
* user's cache needs to be invalidated without affecting other
|
|
647
|
+
* persisted slots. The full-logout path is [[clearAll]].
|
|
648
|
+
*/
|
|
649
|
+
clear() {
|
|
650
|
+
this.all = [];
|
|
651
|
+
this.lastUpdated = 0;
|
|
652
|
+
this.lastRefreshFailedAt = 0;
|
|
653
|
+
if (this.storage) {
|
|
654
|
+
try {
|
|
655
|
+
this.storage.removeItem(this.storageKey);
|
|
656
|
+
} catch {
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
this.removeSuffixFromIndex(this.currentSuffix);
|
|
660
|
+
this.notify();
|
|
661
|
+
}
|
|
662
|
+
/**
|
|
663
|
+
* Logout-grade wipe — bank-grade contract: removes EVERY per-user
|
|
664
|
+
* entitlement slot the SDK has ever written on this device, then
|
|
665
|
+
* clears the index. Used by `Crossdeck.reset()` so a logout on a
|
|
666
|
+
* shared device can never leave another user's entitlements
|
|
667
|
+
* readable (layer (c) of the v1.4.0 isolation fix).
|
|
668
|
+
*
|
|
669
|
+
* After clearAll(), the cache is back to anonymous + empty.
|
|
670
|
+
*/
|
|
671
|
+
clearAll() {
|
|
672
|
+
this.all = [];
|
|
673
|
+
this.lastUpdated = 0;
|
|
674
|
+
this.lastRefreshFailedAt = 0;
|
|
675
|
+
this.currentSuffix = ANON_SUFFIX;
|
|
676
|
+
if (this.storage) {
|
|
677
|
+
const suffixes = this.readIndex();
|
|
678
|
+
for (const suffix of suffixes) {
|
|
679
|
+
try {
|
|
680
|
+
this.storage.removeItem(`${this.storageKeyPrefix}:${suffix}`);
|
|
681
|
+
} catch {
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
try {
|
|
685
|
+
this.storage.removeItem(`${this.storageKeyPrefix}:${ANON_SUFFIX}`);
|
|
686
|
+
} catch {
|
|
687
|
+
}
|
|
688
|
+
try {
|
|
689
|
+
this.storage.removeItem(this.indexKey);
|
|
690
|
+
} catch {
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
this.notify();
|
|
694
|
+
}
|
|
695
|
+
/**
|
|
696
|
+
* Subscribe to cache mutations. Returns an idempotent unsubscribe fn.
|
|
697
|
+
* The listener fires AFTER setFromList() or clear() with the current
|
|
698
|
+
* snapshot. Used by `@cross-deck/web/react`'s `useEntitlement` hook.
|
|
699
|
+
*/
|
|
700
|
+
subscribe(listener) {
|
|
701
|
+
this.listeners.add(listener);
|
|
702
|
+
let unsubscribed = false;
|
|
703
|
+
return () => {
|
|
704
|
+
if (unsubscribed) return;
|
|
705
|
+
unsubscribed = true;
|
|
706
|
+
this.listeners.delete(listener);
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
// ----- Durable persistence -----
|
|
710
|
+
/**
|
|
711
|
+
* Load last-known-good from device storage. Runs once in the
|
|
712
|
+
* constructor, synchronously, so isEntitled() is correct from boot.
|
|
713
|
+
* Any corrupt / unparseable blob degrades silently to an empty cache —
|
|
714
|
+
* boot must never throw.
|
|
715
|
+
*/
|
|
716
|
+
hydrate() {
|
|
717
|
+
if (!this.storage) return;
|
|
718
|
+
try {
|
|
719
|
+
const raw = this.storage.getItem(this.storageKey);
|
|
720
|
+
if (!raw) return;
|
|
721
|
+
const parsed = JSON.parse(raw);
|
|
722
|
+
if (parsed && parsed.v === 1 && Array.isArray(parsed.entitlements)) {
|
|
723
|
+
this.all = parsed.entitlements;
|
|
724
|
+
this.lastUpdated = typeof parsed.lastUpdated === "number" ? parsed.lastUpdated : 0;
|
|
725
|
+
}
|
|
726
|
+
} catch {
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
/** Write last-known-good to device storage. Best-effort. */
|
|
730
|
+
persist() {
|
|
731
|
+
if (!this.storage) return;
|
|
732
|
+
try {
|
|
733
|
+
const blob = {
|
|
734
|
+
v: 1,
|
|
735
|
+
entitlements: this.all,
|
|
736
|
+
lastUpdated: this.lastUpdated
|
|
737
|
+
};
|
|
738
|
+
this.storage.setItem(this.storageKey, JSON.stringify(blob));
|
|
739
|
+
} catch {
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
/** Read the index of all per-user suffixes the SDK has written. */
|
|
743
|
+
readIndex() {
|
|
744
|
+
if (!this.storage) return [];
|
|
745
|
+
try {
|
|
746
|
+
const raw = this.storage.getItem(this.indexKey);
|
|
747
|
+
if (!raw) return [];
|
|
748
|
+
const parsed = JSON.parse(raw);
|
|
749
|
+
if (Array.isArray(parsed)) {
|
|
750
|
+
return parsed.filter((x) => typeof x === "string");
|
|
751
|
+
}
|
|
752
|
+
return [];
|
|
753
|
+
} catch {
|
|
754
|
+
return [];
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
/** Add a suffix to the persisted index. Idempotent. */
|
|
758
|
+
recordSuffixInIndex(suffix) {
|
|
759
|
+
if (!this.storage) return;
|
|
760
|
+
const existing = this.readIndex();
|
|
761
|
+
if (existing.includes(suffix)) return;
|
|
762
|
+
existing.push(suffix);
|
|
763
|
+
try {
|
|
764
|
+
this.storage.setItem(this.indexKey, JSON.stringify(existing));
|
|
765
|
+
} catch {
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
/** Remove a suffix from the persisted index. No-op if absent. */
|
|
769
|
+
removeSuffixFromIndex(suffix) {
|
|
770
|
+
if (!this.storage) return;
|
|
771
|
+
const existing = this.readIndex();
|
|
772
|
+
const next = existing.filter((s) => s !== suffix);
|
|
773
|
+
if (next.length === existing.length) return;
|
|
774
|
+
try {
|
|
775
|
+
if (next.length === 0) {
|
|
776
|
+
this.storage.removeItem(this.indexKey);
|
|
777
|
+
} else {
|
|
778
|
+
this.storage.setItem(this.indexKey, JSON.stringify(next));
|
|
779
|
+
}
|
|
780
|
+
} catch {
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
notify() {
|
|
784
|
+
if (this.listeners.size === 0) return;
|
|
785
|
+
const snapshot = this.all.slice();
|
|
786
|
+
const listenersSnapshot = [...this.listeners];
|
|
787
|
+
for (const listener of listenersSnapshot) {
|
|
788
|
+
try {
|
|
789
|
+
listener(snapshot);
|
|
790
|
+
} catch {
|
|
791
|
+
this.listenerErrorCount += 1;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
};
|
|
796
|
+
|
|
797
|
+
// src/idempotency-key.ts
|
|
798
|
+
function formatAsUuid(hex) {
|
|
799
|
+
return [
|
|
800
|
+
hex.slice(0, 8),
|
|
801
|
+
hex.slice(8, 12),
|
|
802
|
+
hex.slice(12, 16),
|
|
803
|
+
hex.slice(16, 20),
|
|
804
|
+
hex.slice(20, 32)
|
|
805
|
+
].join("-");
|
|
806
|
+
}
|
|
807
|
+
function deriveIdempotencyKeyForPurchase(body) {
|
|
808
|
+
let identifier;
|
|
809
|
+
if (body.rail === "apple") {
|
|
810
|
+
identifier = body.signedTransactionInfo ?? "";
|
|
811
|
+
} else if (body.rail === "google") {
|
|
812
|
+
identifier = body.purchaseToken ?? "";
|
|
813
|
+
} else {
|
|
814
|
+
identifier = "";
|
|
815
|
+
}
|
|
816
|
+
if (!identifier) {
|
|
817
|
+
throw new Error(
|
|
818
|
+
`deriveIdempotencyKeyForPurchase: no stable identifier in body (rail=${body.rail}). Apple needs signedTransactionInfo; Google needs purchaseToken.`
|
|
819
|
+
);
|
|
820
|
+
}
|
|
821
|
+
const namespaced = `crossdeck:purchases/sync:${body.rail}:${identifier}`;
|
|
822
|
+
return formatAsUuid(sha256Hex(namespaced));
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
// src/retry-policy.ts
|
|
826
|
+
var DEFAULT_BASE = 1e3;
|
|
827
|
+
var DEFAULT_MAX = 6e4;
|
|
828
|
+
var DEFAULT_FACTOR = 2;
|
|
829
|
+
var DEFAULT_WARN = 8;
|
|
830
|
+
function computeNextDelay(attempts, retryAfterMs, options = {}, random = Math.random) {
|
|
831
|
+
const base = options.baseMs ?? DEFAULT_BASE;
|
|
832
|
+
const max = options.maxMs ?? DEFAULT_MAX;
|
|
833
|
+
const factor = options.factor ?? DEFAULT_FACTOR;
|
|
834
|
+
const safeAttempts = Math.min(attempts, 30);
|
|
835
|
+
const ceiling = Math.min(max, base * Math.pow(factor, safeAttempts));
|
|
836
|
+
const jittered = ceiling * random();
|
|
837
|
+
if (retryAfterMs !== void 0) {
|
|
838
|
+
const ABSOLUTE_MAX_MS = 24 * 60 * 60 * 1e3;
|
|
839
|
+
const honoured = Math.min(ABSOLUTE_MAX_MS, retryAfterMs);
|
|
840
|
+
if (honoured > jittered) return honoured;
|
|
841
|
+
}
|
|
842
|
+
return Math.max(0, Math.round(jittered));
|
|
843
|
+
}
|
|
844
|
+
var RetryPolicy = class {
|
|
845
|
+
constructor(options = {}) {
|
|
846
|
+
this.options = options;
|
|
847
|
+
this.attempts = 0;
|
|
848
|
+
}
|
|
849
|
+
/** How many consecutive failures since the last success. */
|
|
850
|
+
get consecutiveFailures() {
|
|
851
|
+
return this.attempts;
|
|
852
|
+
}
|
|
853
|
+
/** Whether we've crossed the failuresBeforeWarn threshold. */
|
|
854
|
+
get isWarning() {
|
|
855
|
+
return this.attempts >= (this.options.failuresBeforeWarn ?? DEFAULT_WARN);
|
|
856
|
+
}
|
|
857
|
+
/** Schedule-time delay for the NEXT retry. Increments the counter. */
|
|
858
|
+
nextDelay(retryAfterMs, random = Math.random) {
|
|
859
|
+
const delay = computeNextDelay(this.attempts, retryAfterMs, this.options, random);
|
|
860
|
+
this.attempts += 1;
|
|
861
|
+
return delay;
|
|
862
|
+
}
|
|
863
|
+
/** Mark a successful flush — reset the counter. */
|
|
864
|
+
recordSuccess() {
|
|
865
|
+
this.attempts = 0;
|
|
866
|
+
}
|
|
867
|
+
};
|
|
868
|
+
|
|
869
|
+
// src/event-queue.ts
|
|
870
|
+
var HARD_BUFFER_CAP = 1e3;
|
|
871
|
+
var EventQueue = class {
|
|
872
|
+
constructor(cfg) {
|
|
873
|
+
this.cfg = cfg;
|
|
874
|
+
this.buffer = [];
|
|
875
|
+
/**
|
|
876
|
+
* In-flight events that have been spliced from `buffer` for the
|
|
877
|
+
* current batch but haven't yet been confirmed (success or permanent
|
|
878
|
+
* failure). On a retry-driven re-flush we re-use this slot alongside
|
|
879
|
+
* `pendingBatchId` so the Stripe-style Idempotency-Key is preserved
|
|
880
|
+
* across retries of the SAME logical batch.
|
|
881
|
+
*
|
|
882
|
+
* Pre-fix the splice cleared the buffer AND we immediately
|
|
883
|
+
* `persistent.save(empty)` BEFORE awaiting the network call — a
|
|
884
|
+
* crash mid-flight wiped the persisted blob and the batch was lost
|
|
885
|
+
* with no replay on next boot. Now the persisted blob always carries
|
|
886
|
+
* `[...pendingBatch, ...buffer]` so the in-flight events survive
|
|
887
|
+
* until the server confirms them.
|
|
888
|
+
*
|
|
889
|
+
* Pre-fix every retry attempt also minted a NEW batchId via
|
|
890
|
+
* `splice + mintBatchId`, defeating the backend's
|
|
891
|
+
* `Idempotency-Key` dedup. Reuse via this slot brings web in
|
|
892
|
+
* lockstep with node (which already had the field).
|
|
893
|
+
*/
|
|
894
|
+
this.pendingBatch = null;
|
|
895
|
+
this.pendingBatchId = null;
|
|
896
|
+
this.dropped = 0;
|
|
897
|
+
this.inFlight = 0;
|
|
898
|
+
this.lastFlushAt = 0;
|
|
899
|
+
this.lastError = null;
|
|
900
|
+
this.cancelTimer = null;
|
|
901
|
+
this.firstFlushFired = false;
|
|
902
|
+
this.nextRetryAt = null;
|
|
903
|
+
this.retry = new RetryPolicy(cfg.retry ?? {});
|
|
904
|
+
this.persistent = cfg.persistentStore ?? null;
|
|
905
|
+
if (this.persistent) {
|
|
906
|
+
const restored = this.persistent.load();
|
|
907
|
+
if (restored.length > 0) {
|
|
908
|
+
if (restored.length > HARD_BUFFER_CAP) {
|
|
909
|
+
this.dropped += restored.length - HARD_BUFFER_CAP;
|
|
910
|
+
this.buffer = restored.slice(restored.length - HARD_BUFFER_CAP);
|
|
911
|
+
} else {
|
|
912
|
+
this.buffer = restored;
|
|
913
|
+
}
|
|
914
|
+
this.cfg.onBufferChange?.(this.buffer.length);
|
|
915
|
+
this.scheduleIdleFlush();
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
enqueue(event) {
|
|
920
|
+
this.buffer.push(event);
|
|
921
|
+
if (this.buffer.length > HARD_BUFFER_CAP) {
|
|
922
|
+
const overflow = this.buffer.length - HARD_BUFFER_CAP;
|
|
923
|
+
this.buffer.splice(0, overflow);
|
|
924
|
+
this.dropped += overflow;
|
|
925
|
+
this.cfg.onDrop?.(overflow);
|
|
926
|
+
}
|
|
927
|
+
this.cfg.onBufferChange?.(this.buffer.length);
|
|
928
|
+
this.persistAll();
|
|
929
|
+
if (this.buffer.length >= this.cfg.batchSize) {
|
|
930
|
+
void this.flush();
|
|
931
|
+
} else {
|
|
932
|
+
this.scheduleIdleFlush();
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
/**
|
|
936
|
+
* Flush the buffer to /v1/events. Resolves when the network call
|
|
937
|
+
* completes (success or failure). On a retryable failure the batch
|
|
938
|
+
* stays in `pendingBatch` for the next scheduled retry — the SAME
|
|
939
|
+
* batch with the SAME `Idempotency-Key` is re-sent (Stripe pattern).
|
|
940
|
+
*
|
|
941
|
+
* Three terminal states from one call:
|
|
942
|
+
* - 2xx success: pendingBatch cleared, persisted state collapses to
|
|
943
|
+
* just `buffer` (any new events that arrived during in-flight).
|
|
944
|
+
* - 4xx permanent (except 408/429): pendingBatch DROPPED, `dropped`
|
|
945
|
+
* counter increments, a `permanent_failure` signal fires. The
|
|
946
|
+
* server is telling us our request is malformed / our key is
|
|
947
|
+
* revoked / we lack permission — retrying with the same key
|
|
948
|
+
* forever just grows the queue while the customer thinks events
|
|
949
|
+
* are landing.
|
|
950
|
+
* - 5xx / network / 408 / 429: pendingBatch + batchId stay; backoff
|
|
951
|
+
* schedules a retry; the next `flush()` re-uses both.
|
|
952
|
+
*
|
|
953
|
+
* `options.keepalive` marks the underlying fetch as keepalive so the
|
|
954
|
+
* browser keeps the request alive past page unload. Use for terminal
|
|
955
|
+
* flushes (pagehide / visibilitychange→hidden / beforeunload).
|
|
956
|
+
*/
|
|
957
|
+
async flush(options = {}) {
|
|
958
|
+
let batch;
|
|
959
|
+
let batchId;
|
|
960
|
+
if (this.pendingBatch !== null && this.pendingBatchId !== null) {
|
|
961
|
+
batch = this.pendingBatch;
|
|
962
|
+
batchId = this.pendingBatchId;
|
|
963
|
+
} else {
|
|
964
|
+
if (this.buffer.length === 0) return null;
|
|
965
|
+
batch = this.buffer.splice(0);
|
|
966
|
+
batchId = this.mintBatchId();
|
|
967
|
+
this.pendingBatch = batch;
|
|
968
|
+
this.pendingBatchId = batchId;
|
|
969
|
+
this.inFlight += batch.length;
|
|
970
|
+
this.cfg.onBufferChange?.(this.buffer.length);
|
|
971
|
+
this.persistAll();
|
|
972
|
+
}
|
|
973
|
+
this.cancelTimerIfSet();
|
|
974
|
+
this.nextRetryAt = null;
|
|
975
|
+
try {
|
|
976
|
+
const env = this.cfg.envelope();
|
|
977
|
+
const result = await this.cfg.http.request("POST", "/events", {
|
|
978
|
+
body: {
|
|
979
|
+
// NorthStar §13.1 batch envelope. The backend validates these
|
|
980
|
+
// against the API-key-resolved app and rejects mismatches
|
|
981
|
+
// loudly (env_mismatch).
|
|
982
|
+
appId: env.appId,
|
|
983
|
+
environment: env.environment,
|
|
984
|
+
sdk: env.sdk,
|
|
985
|
+
events: batch
|
|
986
|
+
},
|
|
987
|
+
keepalive: options.keepalive === true,
|
|
988
|
+
idempotencyKey: batchId
|
|
989
|
+
});
|
|
990
|
+
this.lastFlushAt = Date.now();
|
|
991
|
+
this.lastError = null;
|
|
992
|
+
this.inFlight -= batch.length;
|
|
993
|
+
this.pendingBatch = null;
|
|
994
|
+
this.pendingBatchId = null;
|
|
995
|
+
this.retry.recordSuccess();
|
|
996
|
+
this.persistAll();
|
|
997
|
+
if (!this.firstFlushFired) {
|
|
998
|
+
this.firstFlushFired = true;
|
|
999
|
+
this.cfg.onFirstFlushSuccess?.();
|
|
1000
|
+
}
|
|
1001
|
+
return result;
|
|
1002
|
+
} catch (err) {
|
|
1003
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1004
|
+
this.lastError = message;
|
|
1005
|
+
if (isPermanent4xx(err)) {
|
|
1006
|
+
const droppedCount = batch.length;
|
|
1007
|
+
this.pendingBatch = null;
|
|
1008
|
+
this.pendingBatchId = null;
|
|
1009
|
+
this.inFlight -= droppedCount;
|
|
1010
|
+
this.dropped += droppedCount;
|
|
1011
|
+
this.persistAll();
|
|
1012
|
+
this.cfg.onDrop?.(droppedCount);
|
|
1013
|
+
this.cfg.onPermanentFailure?.({
|
|
1014
|
+
status: err.status ?? 0,
|
|
1015
|
+
droppedCount,
|
|
1016
|
+
lastError: message
|
|
1017
|
+
});
|
|
1018
|
+
return null;
|
|
1019
|
+
}
|
|
1020
|
+
const retryAfterMs = extractRetryAfterMs(err);
|
|
1021
|
+
const delay = this.retry.nextDelay(retryAfterMs);
|
|
1022
|
+
this.scheduleRetry(delay);
|
|
1023
|
+
this.cfg.onRetryScheduled?.({
|
|
1024
|
+
delayMs: delay,
|
|
1025
|
+
consecutiveFailures: this.retry.consecutiveFailures,
|
|
1026
|
+
retryAfterMs,
|
|
1027
|
+
lastError: message
|
|
1028
|
+
});
|
|
1029
|
+
return null;
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
/** Cancel any pending timer and clear in-memory state. Wipes durable store too. */
|
|
1033
|
+
reset() {
|
|
1034
|
+
this.cancelTimerIfSet();
|
|
1035
|
+
this.nextRetryAt = null;
|
|
1036
|
+
this.buffer = [];
|
|
1037
|
+
this.pendingBatch = null;
|
|
1038
|
+
this.pendingBatchId = null;
|
|
1039
|
+
this.dropped = 0;
|
|
1040
|
+
this.inFlight = 0;
|
|
1041
|
+
this.lastError = null;
|
|
1042
|
+
this.retry.recordSuccess();
|
|
1043
|
+
this.persistent?.clear();
|
|
1044
|
+
this.cfg.onBufferChange?.(0);
|
|
1045
|
+
}
|
|
1046
|
+
getStats() {
|
|
1047
|
+
return {
|
|
1048
|
+
// `buffered` counts events waiting for their FIRST flush. The
|
|
1049
|
+
// in-flight pendingBatch (retrying) is tracked separately via
|
|
1050
|
+
// `inFlight` — surfacing both lets diagnostics show "we have
|
|
1051
|
+
// events stuck retrying" distinct from "new events arriving".
|
|
1052
|
+
buffered: this.buffer.length,
|
|
1053
|
+
dropped: this.dropped,
|
|
1054
|
+
inFlight: this.inFlight,
|
|
1055
|
+
lastFlushAt: this.lastFlushAt,
|
|
1056
|
+
lastError: this.lastError,
|
|
1057
|
+
consecutiveFailures: this.retry.consecutiveFailures,
|
|
1058
|
+
nextRetryAt: this.nextRetryAt
|
|
1059
|
+
};
|
|
1060
|
+
}
|
|
1061
|
+
/**
|
|
1062
|
+
* The Idempotency-Key of the in-flight pending batch (if any).
|
|
1063
|
+
* Exposed for testing the Stripe-style retry-reuse contract.
|
|
1064
|
+
* Production callers don't need this.
|
|
1065
|
+
*/
|
|
1066
|
+
get pendingIdempotencyKey() {
|
|
1067
|
+
return this.pendingBatchId;
|
|
1068
|
+
}
|
|
1069
|
+
/**
|
|
1070
|
+
* Persist `[...pendingBatch, ...buffer]` — the full set of
|
|
1071
|
+
* not-yet-confirmed events. The next boot rehydrates this exact set
|
|
1072
|
+
* into `buffer` and replays. The server dedups via eventId
|
|
1073
|
+
* (ReplacingMergeTree on the warehouse side), so re-sending an event
|
|
1074
|
+
* that may have already landed is safe.
|
|
1075
|
+
*/
|
|
1076
|
+
persistAll() {
|
|
1077
|
+
if (!this.persistent) return;
|
|
1078
|
+
if (this.pendingBatch === null) {
|
|
1079
|
+
this.persistent.save(this.buffer);
|
|
1080
|
+
return;
|
|
1081
|
+
}
|
|
1082
|
+
this.persistent.save([...this.pendingBatch, ...this.buffer]);
|
|
1083
|
+
}
|
|
1084
|
+
// ---------- internal scheduling ----------
|
|
1085
|
+
scheduleIdleFlush() {
|
|
1086
|
+
this.cancelTimerIfSet();
|
|
1087
|
+
const sched = this.cfg.scheduler ?? defaultScheduler;
|
|
1088
|
+
this.cancelTimer = sched(() => {
|
|
1089
|
+
void this.flush();
|
|
1090
|
+
}, this.cfg.intervalMs);
|
|
1091
|
+
}
|
|
1092
|
+
scheduleRetry(delayMs) {
|
|
1093
|
+
this.cancelTimerIfSet();
|
|
1094
|
+
this.nextRetryAt = Date.now() + delayMs;
|
|
1095
|
+
const sched = this.cfg.scheduler ?? defaultScheduler;
|
|
1096
|
+
this.cancelTimer = sched(() => {
|
|
1097
|
+
void this.flush();
|
|
1098
|
+
}, delayMs);
|
|
1099
|
+
}
|
|
1100
|
+
cancelTimerIfSet() {
|
|
1101
|
+
if (this.cancelTimer) {
|
|
1102
|
+
this.cancelTimer();
|
|
1103
|
+
this.cancelTimer = null;
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
mintBatchId() {
|
|
1107
|
+
return `batch_${Date.now().toString(36)}${randomChars(10)}`;
|
|
1108
|
+
}
|
|
1109
|
+
};
|
|
1110
|
+
function extractRetryAfterMs(err) {
|
|
1111
|
+
if (err && typeof err === "object" && "retryAfterMs" in err) {
|
|
1112
|
+
const v = err.retryAfterMs;
|
|
1113
|
+
return typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : void 0;
|
|
1114
|
+
}
|
|
1115
|
+
return void 0;
|
|
1116
|
+
}
|
|
1117
|
+
function isPermanent4xx(err) {
|
|
1118
|
+
if (!err || typeof err !== "object") return false;
|
|
1119
|
+
const status = err.status;
|
|
1120
|
+
if (typeof status !== "number" || !Number.isFinite(status)) return false;
|
|
1121
|
+
if (status < 400 || status >= 500) return false;
|
|
1122
|
+
if (status === 408 || status === 429) return false;
|
|
1123
|
+
return true;
|
|
1124
|
+
}
|
|
1125
|
+
function defaultScheduler(fn, ms) {
|
|
1126
|
+
const id = setTimeout(fn, ms);
|
|
1127
|
+
if (typeof id.unref === "function") {
|
|
1128
|
+
try {
|
|
1129
|
+
id.unref();
|
|
1130
|
+
} catch {
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
return () => clearTimeout(id);
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
// src/event-storage.ts
|
|
1137
|
+
var PersistentEventStore = class {
|
|
1138
|
+
constructor(options) {
|
|
1139
|
+
this.options = options;
|
|
1140
|
+
this.writeScheduled = false;
|
|
1141
|
+
// Pending events captured on the most recent write request. We keep
|
|
1142
|
+
// the latest snapshot ref so a debounced write always picks up the
|
|
1143
|
+
// freshest buffer state.
|
|
1144
|
+
this.pendingSnapshot = null;
|
|
1145
|
+
this.key = `${options.prefix}queue.v1`;
|
|
1146
|
+
}
|
|
1147
|
+
/**
|
|
1148
|
+
* Read the persisted queue on boot. Returns an empty array (with no
|
|
1149
|
+
* warning) when nothing is stored, the blob is malformed, or storage
|
|
1150
|
+
* is unavailable. Caller is responsible for treating duplicates from
|
|
1151
|
+
* the persisted queue as the SAME events (eventId-based dedup).
|
|
1152
|
+
*/
|
|
1153
|
+
load() {
|
|
1154
|
+
let raw;
|
|
1155
|
+
try {
|
|
1156
|
+
raw = this.options.storage.getItem(this.key);
|
|
1157
|
+
} catch {
|
|
1158
|
+
return [];
|
|
1159
|
+
}
|
|
1160
|
+
if (!raw) return [];
|
|
1161
|
+
try {
|
|
1162
|
+
const parsed = JSON.parse(raw);
|
|
1163
|
+
if (!parsed || parsed.version !== 1 || !Array.isArray(parsed.events)) {
|
|
1164
|
+
return [];
|
|
1165
|
+
}
|
|
1166
|
+
return parsed.events;
|
|
1167
|
+
} catch {
|
|
1168
|
+
return [];
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
/**
|
|
1172
|
+
* Schedule a write of the current buffer. Debounced via microtask so
|
|
1173
|
+
* a burst of enqueue() calls coalesces into one persistence write.
|
|
1174
|
+
* Writes are best-effort: if storage throws (quota, private mode),
|
|
1175
|
+
* we swallow and rely on the in-memory buffer.
|
|
1176
|
+
*/
|
|
1177
|
+
save(snapshot) {
|
|
1178
|
+
this.pendingSnapshot = snapshot.slice();
|
|
1179
|
+
if (this.writeScheduled) return;
|
|
1180
|
+
this.writeScheduled = true;
|
|
1181
|
+
queueMicrotask(() => this.flushWrite());
|
|
1182
|
+
}
|
|
1183
|
+
/** Synchronous variant for terminal flushes (pagehide / beforeunload). */
|
|
1184
|
+
saveSync(snapshot) {
|
|
1185
|
+
this.pendingSnapshot = snapshot.slice();
|
|
1186
|
+
this.flushWrite();
|
|
1187
|
+
}
|
|
1188
|
+
/** Wipe the persisted blob. Used by reset() (logout). */
|
|
1189
|
+
clear() {
|
|
1190
|
+
this.pendingSnapshot = null;
|
|
1191
|
+
this.writeScheduled = false;
|
|
1192
|
+
try {
|
|
1193
|
+
this.options.storage.removeItem(this.key);
|
|
1194
|
+
} catch {
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
flushWrite() {
|
|
1198
|
+
this.writeScheduled = false;
|
|
1199
|
+
const snapshot = this.pendingSnapshot;
|
|
1200
|
+
this.pendingSnapshot = null;
|
|
1201
|
+
if (snapshot === null) return;
|
|
1202
|
+
if (snapshot.length === 0) {
|
|
1203
|
+
try {
|
|
1204
|
+
this.options.storage.removeItem(this.key);
|
|
1205
|
+
} catch {
|
|
1206
|
+
}
|
|
1207
|
+
return;
|
|
1208
|
+
}
|
|
1209
|
+
const blob = { version: 1, events: snapshot };
|
|
1210
|
+
try {
|
|
1211
|
+
this.options.storage.setItem(this.key, JSON.stringify(blob));
|
|
1212
|
+
} catch {
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
};
|
|
1216
|
+
|
|
1217
|
+
// src/storage.ts
|
|
1218
|
+
var MemoryStorage = class {
|
|
1219
|
+
constructor() {
|
|
1220
|
+
this.store = /* @__PURE__ */ new Map();
|
|
1221
|
+
}
|
|
1222
|
+
getItem(key) {
|
|
1223
|
+
return this.store.get(key) ?? null;
|
|
1224
|
+
}
|
|
1225
|
+
setItem(key, value) {
|
|
1226
|
+
this.store.set(key, value);
|
|
1227
|
+
}
|
|
1228
|
+
removeItem(key) {
|
|
1229
|
+
this.store.delete(key);
|
|
1230
|
+
}
|
|
1231
|
+
};
|
|
1232
|
+
var CookieStorage = class {
|
|
1233
|
+
constructor(options) {
|
|
1234
|
+
this.maxAgeSec = options?.maxAgeSec ?? 63072e3;
|
|
1235
|
+
this.secure = options?.secure ?? defaultSecure();
|
|
1236
|
+
this.sameSite = options?.sameSite ?? "Lax";
|
|
1237
|
+
}
|
|
1238
|
+
getItem(key) {
|
|
1239
|
+
if (!hasDocument()) return null;
|
|
1240
|
+
const doc = globalThis.document;
|
|
1241
|
+
const cookies = doc.cookie ? doc.cookie.split(/;\s*/) : [];
|
|
1242
|
+
const prefix = encodeURIComponent(key) + "=";
|
|
1243
|
+
for (const c of cookies) {
|
|
1244
|
+
if (c.startsWith(prefix)) {
|
|
1245
|
+
try {
|
|
1246
|
+
return decodeURIComponent(c.slice(prefix.length));
|
|
1247
|
+
} catch {
|
|
1248
|
+
return null;
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
return null;
|
|
1253
|
+
}
|
|
1254
|
+
setItem(key, value) {
|
|
1255
|
+
if (!hasDocument()) return;
|
|
1256
|
+
const doc = globalThis.document;
|
|
1257
|
+
const parts = [
|
|
1258
|
+
`${encodeURIComponent(key)}=${encodeURIComponent(value)}`,
|
|
1259
|
+
"Path=/",
|
|
1260
|
+
`Max-Age=${this.maxAgeSec}`,
|
|
1261
|
+
`SameSite=${this.sameSite}`
|
|
1262
|
+
];
|
|
1263
|
+
if (this.secure) parts.push("Secure");
|
|
1264
|
+
try {
|
|
1265
|
+
doc.cookie = parts.join("; ");
|
|
1266
|
+
} catch {
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
removeItem(key) {
|
|
1270
|
+
if (!hasDocument()) return;
|
|
1271
|
+
const doc = globalThis.document;
|
|
1272
|
+
const parts = [
|
|
1273
|
+
`${encodeURIComponent(key)}=`,
|
|
1274
|
+
"Path=/",
|
|
1275
|
+
"Max-Age=0",
|
|
1276
|
+
`SameSite=${this.sameSite}`
|
|
1277
|
+
];
|
|
1278
|
+
if (this.secure) parts.push("Secure");
|
|
1279
|
+
try {
|
|
1280
|
+
doc.cookie = parts.join("; ");
|
|
1281
|
+
} catch {
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
};
|
|
1285
|
+
function detectDefaultStorage() {
|
|
1286
|
+
try {
|
|
1287
|
+
const ls = globalThis.localStorage;
|
|
1288
|
+
if (ls) {
|
|
1289
|
+
const probe = "__crossdeck_probe__";
|
|
1290
|
+
ls.setItem(probe, "1");
|
|
1291
|
+
ls.removeItem(probe);
|
|
1292
|
+
return ls;
|
|
1293
|
+
}
|
|
1294
|
+
} catch {
|
|
1295
|
+
}
|
|
1296
|
+
return new MemoryStorage();
|
|
1297
|
+
}
|
|
1298
|
+
function defaultSecure() {
|
|
1299
|
+
try {
|
|
1300
|
+
const loc = globalThis.location;
|
|
1301
|
+
return loc?.protocol === "https:";
|
|
1302
|
+
} catch {
|
|
1303
|
+
return false;
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
function hasDocument() {
|
|
1307
|
+
return typeof globalThis.document !== "undefined";
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
// src/device-info.ts
|
|
1311
|
+
function isBrowser() {
|
|
1312
|
+
return typeof globalThis.window !== "undefined" && typeof globalThis.document !== "undefined" && typeof globalThis.navigator !== "undefined";
|
|
1313
|
+
}
|
|
1314
|
+
function collectDeviceInfo(extra) {
|
|
1315
|
+
const info = {};
|
|
1316
|
+
if (extra?.appVersion) info.appVersion = extra.appVersion;
|
|
1317
|
+
if (!isBrowser()) return info;
|
|
1318
|
+
const w = globalThis.window;
|
|
1319
|
+
const nav = globalThis.navigator;
|
|
1320
|
+
const doc = globalThis.document;
|
|
1321
|
+
try {
|
|
1322
|
+
if (typeof nav.language === "string") info.locale = nav.language;
|
|
1323
|
+
} catch {
|
|
1324
|
+
}
|
|
1325
|
+
try {
|
|
1326
|
+
info.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
1327
|
+
} catch {
|
|
1328
|
+
}
|
|
1329
|
+
try {
|
|
1330
|
+
if (w.screen) {
|
|
1331
|
+
info.screenWidth = w.screen.width;
|
|
1332
|
+
info.screenHeight = w.screen.height;
|
|
1333
|
+
}
|
|
1334
|
+
info.viewportWidth = w.innerWidth;
|
|
1335
|
+
info.viewportHeight = w.innerHeight;
|
|
1336
|
+
info.devicePixelRatio = w.devicePixelRatio;
|
|
1337
|
+
} catch {
|
|
1338
|
+
}
|
|
1339
|
+
try {
|
|
1340
|
+
const ua = nav.userAgent ?? "";
|
|
1341
|
+
const parsed = parseUserAgent(ua);
|
|
1342
|
+
Object.assign(info, parsed);
|
|
1343
|
+
} catch {
|
|
1344
|
+
}
|
|
1345
|
+
try {
|
|
1346
|
+
const uaData = nav.userAgentData;
|
|
1347
|
+
if (uaData?.platform && !info.os) info.os = uaData.platform;
|
|
1348
|
+
if (uaData?.brands && !info.browser) {
|
|
1349
|
+
const real = uaData.brands.find(
|
|
1350
|
+
(b) => !/Not[ .;A]*Brand/i.test(b.brand) && !/Chromium/i.test(b.brand)
|
|
1351
|
+
);
|
|
1352
|
+
if (real) {
|
|
1353
|
+
info.browser = real.brand;
|
|
1354
|
+
info.browserVersion = real.version;
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
} catch {
|
|
1358
|
+
}
|
|
1359
|
+
void doc;
|
|
1360
|
+
return info;
|
|
1361
|
+
}
|
|
1362
|
+
function parseUserAgent(ua) {
|
|
1363
|
+
const out = {};
|
|
1364
|
+
if (/iPad|iPhone|iPod/.test(ua)) {
|
|
1365
|
+
out.os = "iOS";
|
|
1366
|
+
const m = ua.match(/OS (\d+[._]\d+(?:[._]\d+)?)/);
|
|
1367
|
+
if (m?.[1]) out.osVersion = m[1].replace(/_/g, ".");
|
|
1368
|
+
} else if (/Android/.test(ua)) {
|
|
1369
|
+
out.os = "Android";
|
|
1370
|
+
const m = ua.match(/Android (\d+(?:\.\d+)*)/);
|
|
1371
|
+
if (m?.[1]) out.osVersion = m[1];
|
|
1372
|
+
} else if (/Windows/.test(ua)) {
|
|
1373
|
+
out.os = "Windows";
|
|
1374
|
+
const m = ua.match(/Windows NT (\d+\.\d+)/);
|
|
1375
|
+
if (m?.[1]) out.osVersion = m[1];
|
|
1376
|
+
} else if (/Mac OS X|Macintosh/.test(ua)) {
|
|
1377
|
+
out.os = "macOS";
|
|
1378
|
+
const m = ua.match(/Mac OS X (\d+[._]\d+(?:[._]\d+)?)/);
|
|
1379
|
+
if (m?.[1]) out.osVersion = m[1].replace(/_/g, ".");
|
|
1380
|
+
} else if (/Linux/.test(ua)) {
|
|
1381
|
+
out.os = "Linux";
|
|
1382
|
+
}
|
|
1383
|
+
if (/Edg\/(\d+(?:\.\d+)*)/.test(ua)) {
|
|
1384
|
+
out.browser = "Edge";
|
|
1385
|
+
out.browserVersion = ua.match(/Edg\/(\d+(?:\.\d+)*)/)?.[1];
|
|
1386
|
+
} else if (/Firefox\/(\d+(?:\.\d+)*)/.test(ua)) {
|
|
1387
|
+
out.browser = "Firefox";
|
|
1388
|
+
out.browserVersion = ua.match(/Firefox\/(\d+(?:\.\d+)*)/)?.[1];
|
|
1389
|
+
} else if (/OPR\/(\d+(?:\.\d+)*)/.test(ua)) {
|
|
1390
|
+
out.browser = "Opera";
|
|
1391
|
+
out.browserVersion = ua.match(/OPR\/(\d+(?:\.\d+)*)/)?.[1];
|
|
1392
|
+
} else if (/Chrome\/(\d+(?:\.\d+)*)/.test(ua)) {
|
|
1393
|
+
out.browser = "Chrome";
|
|
1394
|
+
out.browserVersion = ua.match(/Chrome\/(\d+(?:\.\d+)*)/)?.[1];
|
|
1395
|
+
} else if (/Version\/(\d+(?:\.\d+)*).*Safari/.test(ua)) {
|
|
1396
|
+
out.browser = "Safari";
|
|
1397
|
+
out.browserVersion = ua.match(/Version\/(\d+(?:\.\d+)*)/)?.[1];
|
|
1398
|
+
}
|
|
1399
|
+
return out;
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
// src/auto-track.ts
|
|
1403
|
+
var DEFAULT_AUTO_TRACK = {
|
|
1404
|
+
sessions: true,
|
|
1405
|
+
pageViews: true,
|
|
1406
|
+
deviceInfo: true,
|
|
1407
|
+
clicks: true,
|
|
1408
|
+
webVitals: true,
|
|
1409
|
+
errors: true
|
|
1410
|
+
};
|
|
1411
|
+
var SESSION_RESUME_THRESHOLD_MS = 30 * 60 * 1e3;
|
|
1412
|
+
var EMPTY_ACQUISITION = {
|
|
1413
|
+
utm_source: "",
|
|
1414
|
+
utm_medium: "",
|
|
1415
|
+
utm_campaign: "",
|
|
1416
|
+
utm_content: "",
|
|
1417
|
+
utm_term: "",
|
|
1418
|
+
referrer: "",
|
|
1419
|
+
gclid: "",
|
|
1420
|
+
fbclid: "",
|
|
1421
|
+
msclkid: "",
|
|
1422
|
+
ttclid: "",
|
|
1423
|
+
li_fat_id: "",
|
|
1424
|
+
twclid: ""
|
|
1425
|
+
};
|
|
1426
|
+
var AutoTracker = class {
|
|
1427
|
+
constructor(cfg, track) {
|
|
1428
|
+
this.cfg = cfg;
|
|
1429
|
+
this.track = track;
|
|
1430
|
+
this.session = null;
|
|
1431
|
+
this.cleanups = [];
|
|
1432
|
+
/**
|
|
1433
|
+
* Stable per-page-view identifier. Minted at every `page.viewed`
|
|
1434
|
+
* emission and attached to every subsequent event until the next
|
|
1435
|
+
* `page.viewed`. Lets dashboards correlate "user clicked X" to
|
|
1436
|
+
* "user viewed page Y" without timestamp arithmetic — the canonical
|
|
1437
|
+
* Mixpanel `$current_url` / Segment `pageId` pattern.
|
|
1438
|
+
*
|
|
1439
|
+
* Null until the first `page.viewed` fires (which happens at SDK
|
|
1440
|
+
* install if `autoTrack.pageViews !== false`).
|
|
1441
|
+
*/
|
|
1442
|
+
this.pageviewId = null;
|
|
1443
|
+
}
|
|
1444
|
+
install() {
|
|
1445
|
+
if (!isBrowserSafe()) return;
|
|
1446
|
+
if (this.cfg.sessions) this.installSessionTracking();
|
|
1447
|
+
if (this.cfg.pageViews) this.installPageViewTracking();
|
|
1448
|
+
if (this.cfg.clicks) this.installClickTracking();
|
|
1449
|
+
}
|
|
1450
|
+
uninstall() {
|
|
1451
|
+
while (this.cleanups.length) {
|
|
1452
|
+
const fn = this.cleanups.pop();
|
|
1453
|
+
try {
|
|
1454
|
+
fn?.();
|
|
1455
|
+
} catch {
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
if (this.session && !this.session.endedSent) {
|
|
1459
|
+
this.emitSessionEnd();
|
|
1460
|
+
}
|
|
1461
|
+
this.session = null;
|
|
1462
|
+
}
|
|
1463
|
+
/** Exposed for tests + consumers that want to reset the session manually. */
|
|
1464
|
+
resetSession() {
|
|
1465
|
+
if (this.session && !this.session.endedSent) this.emitSessionEnd();
|
|
1466
|
+
this.pageviewId = null;
|
|
1467
|
+
this.session = this.startNewSession();
|
|
1468
|
+
this.emitSessionStart();
|
|
1469
|
+
}
|
|
1470
|
+
/** Exposed for inspection/tests — returns the current sessionId (or null if not in a session). */
|
|
1471
|
+
get currentSessionId() {
|
|
1472
|
+
return this.session?.sessionId ?? null;
|
|
1473
|
+
}
|
|
1474
|
+
/** Stable per-page-view ID. Null before the first page.viewed has fired. */
|
|
1475
|
+
get currentPageviewId() {
|
|
1476
|
+
return this.pageviewId;
|
|
1477
|
+
}
|
|
1478
|
+
/**
|
|
1479
|
+
* Per-session acquisition context — utm_* + referrer, captured once
|
|
1480
|
+
* at session start. Returns empty strings when there's no session
|
|
1481
|
+
* (Node, before init, after uninstall) so callers can spread without
|
|
1482
|
+
* conditional logic. Bank-grade rule: capture once, attach to every
|
|
1483
|
+
* event of the session, don't re-read on every track() (the URL
|
|
1484
|
+
* changes via SPA pushState; the source-of-record is the URL we
|
|
1485
|
+
* landed on).
|
|
1486
|
+
*/
|
|
1487
|
+
get currentAcquisition() {
|
|
1488
|
+
return this.session?.acquisition ?? EMPTY_ACQUISITION;
|
|
1489
|
+
}
|
|
1490
|
+
// ---------- sessions ----------
|
|
1491
|
+
installSessionTracking() {
|
|
1492
|
+
this.session = this.startNewSession();
|
|
1493
|
+
this.emitSessionStart();
|
|
1494
|
+
const onVisChange = () => {
|
|
1495
|
+
if (!this.session) return;
|
|
1496
|
+
const doc2 = globalThis.document;
|
|
1497
|
+
if (doc2.visibilityState === "hidden") {
|
|
1498
|
+
this.session.hiddenAt = Date.now();
|
|
1499
|
+
} else if (doc2.visibilityState === "visible") {
|
|
1500
|
+
const hiddenFor = this.session.hiddenAt ? Date.now() - this.session.hiddenAt : 0;
|
|
1501
|
+
if (hiddenFor >= SESSION_RESUME_THRESHOLD_MS) {
|
|
1502
|
+
this.emitSessionEnd();
|
|
1503
|
+
this.pageviewId = null;
|
|
1504
|
+
this.session = this.startNewSession();
|
|
1505
|
+
this.emitSessionStart();
|
|
1506
|
+
} else {
|
|
1507
|
+
this.session.hiddenAt = null;
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
};
|
|
1511
|
+
const onPageHide = () => this.emitSessionEnd();
|
|
1512
|
+
const w = globalThis.window;
|
|
1513
|
+
const doc = globalThis.document;
|
|
1514
|
+
doc.addEventListener("visibilitychange", onVisChange);
|
|
1515
|
+
w.addEventListener("pagehide", onPageHide);
|
|
1516
|
+
w.addEventListener("beforeunload", onPageHide);
|
|
1517
|
+
this.cleanups.push(() => {
|
|
1518
|
+
doc.removeEventListener("visibilitychange", onVisChange);
|
|
1519
|
+
w.removeEventListener("pagehide", onPageHide);
|
|
1520
|
+
w.removeEventListener("beforeunload", onPageHide);
|
|
1521
|
+
});
|
|
1522
|
+
}
|
|
1523
|
+
startNewSession() {
|
|
1524
|
+
return {
|
|
1525
|
+
sessionId: mintSessionId(),
|
|
1526
|
+
startedAt: Date.now(),
|
|
1527
|
+
hiddenAt: null,
|
|
1528
|
+
endedSent: false,
|
|
1529
|
+
acquisition: captureAcquisition()
|
|
1530
|
+
};
|
|
1531
|
+
}
|
|
1532
|
+
emitSessionStart() {
|
|
1533
|
+
if (!this.session) return;
|
|
1534
|
+
this.track("session.started", { sessionId: this.session.sessionId });
|
|
1535
|
+
}
|
|
1536
|
+
emitSessionEnd() {
|
|
1537
|
+
if (!this.session || this.session.endedSent) return;
|
|
1538
|
+
const duration = Date.now() - this.session.startedAt;
|
|
1539
|
+
this.track("session.ended", {
|
|
1540
|
+
sessionId: this.session.sessionId,
|
|
1541
|
+
durationMs: duration
|
|
1542
|
+
});
|
|
1543
|
+
this.session.endedSent = true;
|
|
1544
|
+
}
|
|
1545
|
+
// ---------- page views ----------
|
|
1546
|
+
installPageViewTracking() {
|
|
1547
|
+
const w = globalThis.window;
|
|
1548
|
+
const doc = globalThis.document;
|
|
1549
|
+
let lastFiredAt = 0;
|
|
1550
|
+
let lastFiredUrl = "";
|
|
1551
|
+
const DEDUP_WINDOW_MS = 250;
|
|
1552
|
+
const fire = (force = false) => {
|
|
1553
|
+
const loc = w.location;
|
|
1554
|
+
const url = loc.href;
|
|
1555
|
+
const now = Date.now();
|
|
1556
|
+
if (!force && url === lastFiredUrl && now - lastFiredAt < DEDUP_WINDOW_MS) return;
|
|
1557
|
+
lastFiredAt = now;
|
|
1558
|
+
lastFiredUrl = url;
|
|
1559
|
+
this.pageviewId = `pv_${Date.now().toString(36)}${randomChars(10)}`;
|
|
1560
|
+
this.track("page.viewed", {
|
|
1561
|
+
pageviewId: this.pageviewId,
|
|
1562
|
+
path: loc.pathname,
|
|
1563
|
+
url,
|
|
1564
|
+
search: loc.search || void 0,
|
|
1565
|
+
hash: loc.hash || void 0,
|
|
1566
|
+
title: doc.title,
|
|
1567
|
+
// referrer only on the first hit of the session — afterward it's
|
|
1568
|
+
// always our previous URL, which isn't useful.
|
|
1569
|
+
referrer: doc.referrer || void 0
|
|
1570
|
+
});
|
|
1571
|
+
};
|
|
1572
|
+
fire();
|
|
1573
|
+
const origPush = w.history.pushState;
|
|
1574
|
+
const origReplace = w.history.replaceState;
|
|
1575
|
+
function patchedPush(data, unused, url) {
|
|
1576
|
+
origPush.apply(this, [data, unused, url]);
|
|
1577
|
+
queueMicrotask(fire);
|
|
1578
|
+
}
|
|
1579
|
+
function patchedReplace(data, unused, url) {
|
|
1580
|
+
origReplace.apply(this, [data, unused, url]);
|
|
1581
|
+
queueMicrotask(fire);
|
|
1582
|
+
}
|
|
1583
|
+
w.history.pushState = patchedPush;
|
|
1584
|
+
w.history.replaceState = patchedReplace;
|
|
1585
|
+
const onPopState = () => fire(true);
|
|
1586
|
+
w.addEventListener("popstate", onPopState);
|
|
1587
|
+
this.cleanups.push(() => {
|
|
1588
|
+
if (w.history.pushState === patchedPush) {
|
|
1589
|
+
w.history.pushState = origPush;
|
|
1590
|
+
}
|
|
1591
|
+
if (w.history.replaceState === patchedReplace) {
|
|
1592
|
+
w.history.replaceState = origReplace;
|
|
1593
|
+
}
|
|
1594
|
+
w.removeEventListener("popstate", onPopState);
|
|
1595
|
+
});
|
|
1596
|
+
}
|
|
1597
|
+
// ---------- click autocapture ----------
|
|
1598
|
+
/**
|
|
1599
|
+
* Global click tracking — Mixpanel / Amplitude style autocapture.
|
|
1600
|
+
* Fires `element.clicked` for every interactive click with the
|
|
1601
|
+
* target element's selector path, text content, tag, href, data-*
|
|
1602
|
+
* attributes, and viewport coordinates. Powers the funnel /
|
|
1603
|
+
* attribution USP: "users who clicked X then converted within
|
|
1604
|
+
* 7 days." Default ON because behavioural attribution is the
|
|
1605
|
+
* core product promise.
|
|
1606
|
+
*
|
|
1607
|
+
* Privacy guardrails:
|
|
1608
|
+
* - Skip clicks ON inputs / textareas / selects (form interaction
|
|
1609
|
+
* isn't button telemetry; the dev should track form submits
|
|
1610
|
+
* deliberately via track('form_submitted'))
|
|
1611
|
+
* - Skip clicks INSIDE [type="password"] and password-class
|
|
1612
|
+
* elements
|
|
1613
|
+
* - Skip clicks inside elements opted out via class="cd-noTrack"
|
|
1614
|
+
* or data-cd-noTrack attribute (Mixpanel's exact opt-out
|
|
1615
|
+
* idiom — most devs already know it)
|
|
1616
|
+
* - Capture text content but cap at 64 chars and trim — never
|
|
1617
|
+
* more than what you'd see on a button label
|
|
1618
|
+
*
|
|
1619
|
+
* Volume guardrails:
|
|
1620
|
+
* - Coalesce double-clicks within 100ms (React's synthetic click
|
|
1621
|
+
* pattern + browser's native dblclick can fire twice)
|
|
1622
|
+
* - Listen on document at capture phase so we see the click
|
|
1623
|
+
* before any framework's own handlers stop propagation
|
|
1624
|
+
*/
|
|
1625
|
+
installClickTracking() {
|
|
1626
|
+
const w = globalThis.window;
|
|
1627
|
+
const doc = globalThis.document;
|
|
1628
|
+
let lastFiredAt = 0;
|
|
1629
|
+
let lastFiredTarget = null;
|
|
1630
|
+
const COALESCE_MS = 100;
|
|
1631
|
+
const TEXT_CAP = 64;
|
|
1632
|
+
const onClick = (ev) => {
|
|
1633
|
+
const target = ev.target;
|
|
1634
|
+
if (!target || !(target instanceof Element)) return;
|
|
1635
|
+
const now = Date.now();
|
|
1636
|
+
if (target === lastFiredTarget && now - lastFiredAt < COALESCE_MS) return;
|
|
1637
|
+
lastFiredAt = now;
|
|
1638
|
+
lastFiredTarget = target;
|
|
1639
|
+
const actionable = closestActionable(target);
|
|
1640
|
+
const clicked = actionable || target;
|
|
1641
|
+
if (isFormInput(clicked)) return;
|
|
1642
|
+
if (isInOptedOut(clicked)) return;
|
|
1643
|
+
if (isInsidePasswordField(clicked)) return;
|
|
1644
|
+
const tag = clicked.tagName.toLowerCase();
|
|
1645
|
+
const text = trimText(extractText(clicked), TEXT_CAP);
|
|
1646
|
+
const href = clicked.href || void 0;
|
|
1647
|
+
const linkTarget = clicked.target || void 0;
|
|
1648
|
+
const elementId = clicked.id || void 0;
|
|
1649
|
+
const role = clicked.getAttribute("role") || void 0;
|
|
1650
|
+
const ariaLabel = clicked.getAttribute("aria-label") || void 0;
|
|
1651
|
+
const selector = buildSelector(clicked);
|
|
1652
|
+
const dataAttrs = collectDataAttrs(clicked);
|
|
1653
|
+
const isLink = tag === "a" && !!href;
|
|
1654
|
+
const explicitName = clicked.getAttribute("data-cd-event");
|
|
1655
|
+
const props = {
|
|
1656
|
+
selector,
|
|
1657
|
+
tag,
|
|
1658
|
+
text,
|
|
1659
|
+
elementId,
|
|
1660
|
+
role,
|
|
1661
|
+
ariaLabel,
|
|
1662
|
+
href,
|
|
1663
|
+
isLink,
|
|
1664
|
+
linkTarget,
|
|
1665
|
+
viewportX: ev.clientX,
|
|
1666
|
+
viewportY: ev.clientY,
|
|
1667
|
+
pageX: ev.pageX,
|
|
1668
|
+
pageY: ev.pageY,
|
|
1669
|
+
...dataAttrs
|
|
1670
|
+
};
|
|
1671
|
+
for (const k of Object.keys(props)) {
|
|
1672
|
+
if (props[k] === void 0 || props[k] === null || props[k] === "") delete props[k];
|
|
1673
|
+
}
|
|
1674
|
+
this.track(explicitName || "element.clicked", props);
|
|
1675
|
+
};
|
|
1676
|
+
doc.addEventListener("click", onClick, { capture: true, passive: true });
|
|
1677
|
+
this.cleanups.push(() => {
|
|
1678
|
+
doc.removeEventListener("click", onClick, { capture: true });
|
|
1679
|
+
});
|
|
1680
|
+
}
|
|
1681
|
+
};
|
|
1682
|
+
function closestActionable(el) {
|
|
1683
|
+
return el.closest("[data-cd-event]") || el.closest("[data-cd-noTrack]") || el.closest("button, a, [role='button'], [role='link'], input[type='button'], input[type='submit']") || null;
|
|
1684
|
+
}
|
|
1685
|
+
function isFormInput(el) {
|
|
1686
|
+
if (!(el instanceof HTMLElement)) return false;
|
|
1687
|
+
const tag = el.tagName.toLowerCase();
|
|
1688
|
+
if (tag === "textarea" || tag === "select") return true;
|
|
1689
|
+
if (tag === "input") {
|
|
1690
|
+
const type = (el.type || "").toLowerCase();
|
|
1691
|
+
return type !== "button" && type !== "submit" && type !== "image" && type !== "reset";
|
|
1692
|
+
}
|
|
1693
|
+
return false;
|
|
1694
|
+
}
|
|
1695
|
+
function isInOptedOut(el) {
|
|
1696
|
+
if (el.closest("[data-cd-noTrack], [data-cd-no-track], .cd-noTrack, .cd-no-track")) return true;
|
|
1697
|
+
return false;
|
|
1698
|
+
}
|
|
1699
|
+
function isInsidePasswordField(el) {
|
|
1700
|
+
if (el.closest('input[type="password"]')) return true;
|
|
1701
|
+
return false;
|
|
1702
|
+
}
|
|
1703
|
+
function extractText(el) {
|
|
1704
|
+
const clean = (s) => s.replace(/\s+/g, " ").trim();
|
|
1705
|
+
const explicit = el.getAttribute("data-cd-track") || el.getAttribute("data-track") || el.getAttribute("data-testid");
|
|
1706
|
+
if (explicit) {
|
|
1707
|
+
const t = clean(explicit);
|
|
1708
|
+
if (t) return t;
|
|
1709
|
+
}
|
|
1710
|
+
const aria = el.getAttribute("aria-label");
|
|
1711
|
+
if (aria) {
|
|
1712
|
+
const t = clean(aria);
|
|
1713
|
+
if (t) return t;
|
|
1714
|
+
}
|
|
1715
|
+
const labelledBy = el.getAttribute("aria-labelledby");
|
|
1716
|
+
if (labelledBy && typeof el.ownerDocument?.getElementById === "function") {
|
|
1717
|
+
const parts = [];
|
|
1718
|
+
for (const id of labelledBy.split(/\s+/)) {
|
|
1719
|
+
const ref = el.ownerDocument.getElementById(id);
|
|
1720
|
+
const t = ref?.textContent ? clean(ref.textContent) : "";
|
|
1721
|
+
if (t) parts.push(t);
|
|
1722
|
+
}
|
|
1723
|
+
if (parts.length > 0) return parts.join(" ");
|
|
1724
|
+
}
|
|
1725
|
+
if (el instanceof HTMLInputElement && el.value) {
|
|
1726
|
+
const t = clean(el.value);
|
|
1727
|
+
if (t) return t;
|
|
1728
|
+
}
|
|
1729
|
+
const text = clean(el.textContent || "");
|
|
1730
|
+
if (text) return text;
|
|
1731
|
+
const title = el.getAttribute("title");
|
|
1732
|
+
if (title) {
|
|
1733
|
+
const t = clean(title);
|
|
1734
|
+
if (t) return t;
|
|
1735
|
+
}
|
|
1736
|
+
const img = el.querySelector("img[alt]");
|
|
1737
|
+
if (img) {
|
|
1738
|
+
const alt = img.getAttribute("alt") ?? "";
|
|
1739
|
+
const t = clean(alt);
|
|
1740
|
+
if (t) return t;
|
|
1741
|
+
}
|
|
1742
|
+
const svgTitle = el.querySelector("svg title");
|
|
1743
|
+
if (svgTitle?.textContent) {
|
|
1744
|
+
const t = clean(svgTitle.textContent);
|
|
1745
|
+
if (t) return t;
|
|
1746
|
+
}
|
|
1747
|
+
return "";
|
|
1748
|
+
}
|
|
1749
|
+
function trimText(s, cap) {
|
|
1750
|
+
if (s.length <= cap) return s;
|
|
1751
|
+
return s.slice(0, cap - 1) + "\u2026";
|
|
1752
|
+
}
|
|
1753
|
+
function buildSelector(el) {
|
|
1754
|
+
const parts = [];
|
|
1755
|
+
let cur = el;
|
|
1756
|
+
let depth = 0;
|
|
1757
|
+
while (cur && cur.nodeName.toLowerCase() !== "body" && depth < 5) {
|
|
1758
|
+
let part = cur.nodeName.toLowerCase();
|
|
1759
|
+
if (cur.id) {
|
|
1760
|
+
parts.unshift(`${part}#${cur.id}`);
|
|
1761
|
+
break;
|
|
1762
|
+
}
|
|
1763
|
+
if (cur.classList.length > 0) {
|
|
1764
|
+
const cls = Array.from(cur.classList).filter((c) => !c.startsWith("cd-")).slice(0, 2).join(".");
|
|
1765
|
+
if (cls) part += `.${cls}`;
|
|
1766
|
+
}
|
|
1767
|
+
parts.unshift(part);
|
|
1768
|
+
cur = cur.parentElement;
|
|
1769
|
+
depth++;
|
|
1770
|
+
}
|
|
1771
|
+
return parts.join(" > ");
|
|
1772
|
+
}
|
|
1773
|
+
function collectDataAttrs(el) {
|
|
1774
|
+
const out = {};
|
|
1775
|
+
if (!(el instanceof HTMLElement)) return out;
|
|
1776
|
+
for (const name of el.getAttributeNames()) {
|
|
1777
|
+
if (!name.startsWith("data-")) continue;
|
|
1778
|
+
if (name === "data-cd-noTrack" || name === "data-cd-no-track") continue;
|
|
1779
|
+
if (name === "data-cd-event") continue;
|
|
1780
|
+
const value = el.getAttribute(name) || "";
|
|
1781
|
+
const key = name.replace(/^data-cd-prop-/, "").replace(/^data-/, "");
|
|
1782
|
+
out[key] = value;
|
|
1783
|
+
}
|
|
1784
|
+
return out;
|
|
1785
|
+
}
|
|
1786
|
+
function isBrowserSafe() {
|
|
1787
|
+
return typeof globalThis.window !== "undefined" && typeof globalThis.document !== "undefined";
|
|
1788
|
+
}
|
|
1789
|
+
function mintSessionId() {
|
|
1790
|
+
const ts = Date.now().toString(36);
|
|
1791
|
+
return `sess_${ts}${randomChars(10)}`;
|
|
1792
|
+
}
|
|
1793
|
+
function captureAcquisition() {
|
|
1794
|
+
if (!isBrowserSafe()) return { ...EMPTY_ACQUISITION };
|
|
1795
|
+
const result = { ...EMPTY_ACQUISITION };
|
|
1796
|
+
try {
|
|
1797
|
+
const w = globalThis.window;
|
|
1798
|
+
const params = new URLSearchParams(w.location.search ?? "");
|
|
1799
|
+
result.utm_source = params.get("utm_source") ?? "";
|
|
1800
|
+
result.utm_medium = params.get("utm_medium") ?? "";
|
|
1801
|
+
result.utm_campaign = params.get("utm_campaign") ?? "";
|
|
1802
|
+
result.utm_content = params.get("utm_content") ?? "";
|
|
1803
|
+
result.utm_term = params.get("utm_term") ?? "";
|
|
1804
|
+
result.gclid = params.get("gclid") ?? "";
|
|
1805
|
+
result.fbclid = params.get("fbclid") ?? "";
|
|
1806
|
+
result.msclkid = params.get("msclkid") ?? "";
|
|
1807
|
+
result.ttclid = params.get("ttclid") ?? "";
|
|
1808
|
+
result.li_fat_id = params.get("li_fat_id") ?? "";
|
|
1809
|
+
result.twclid = params.get("twclid") ?? "";
|
|
1810
|
+
} catch {
|
|
1811
|
+
}
|
|
1812
|
+
try {
|
|
1813
|
+
const doc = globalThis.document;
|
|
1814
|
+
if (typeof doc.referrer === "string") result.referrer = doc.referrer;
|
|
1815
|
+
} catch {
|
|
1816
|
+
}
|
|
1817
|
+
return result;
|
|
1818
|
+
}
|
|
1819
|
+
|
|
1820
|
+
// src/debug.ts
|
|
1821
|
+
var SENSITIVE_KEY_PATTERNS = [
|
|
1822
|
+
/^email$/i,
|
|
1823
|
+
/^password$/i,
|
|
1824
|
+
/^token$/i,
|
|
1825
|
+
/^secret$/i,
|
|
1826
|
+
/^card$/i,
|
|
1827
|
+
/^phone$/i,
|
|
1828
|
+
/password/i,
|
|
1829
|
+
/credit_?card/i
|
|
1830
|
+
];
|
|
1831
|
+
function findSensitivePropertyKeys(properties) {
|
|
1832
|
+
if (!properties) return [];
|
|
1833
|
+
const hits = [];
|
|
1834
|
+
for (const k of Object.keys(properties)) {
|
|
1835
|
+
if (SENSITIVE_KEY_PATTERNS.some((re) => re.test(k))) hits.push(k);
|
|
1836
|
+
}
|
|
1837
|
+
return hits;
|
|
1838
|
+
}
|
|
1839
|
+
var ConsoleDebugLogger = class {
|
|
1840
|
+
constructor() {
|
|
1841
|
+
this.enabled = false;
|
|
1842
|
+
this.seen = /* @__PURE__ */ new Set();
|
|
1843
|
+
}
|
|
1844
|
+
emit(signal, message, context) {
|
|
1845
|
+
if (!this.enabled) return;
|
|
1846
|
+
if (ONCE_SIGNALS.has(signal)) {
|
|
1847
|
+
if (this.seen.has(signal)) return;
|
|
1848
|
+
this.seen.add(signal);
|
|
1849
|
+
}
|
|
1850
|
+
const ctx = context ? ` ${safeJson(context)}` : "";
|
|
1851
|
+
console.info(`[crossdeck:${signal}] ${message}${ctx}`);
|
|
1852
|
+
}
|
|
1853
|
+
};
|
|
1854
|
+
var ONCE_SIGNALS = /* @__PURE__ */ new Set([
|
|
1855
|
+
"sdk.configured",
|
|
1856
|
+
"sdk.first_event_sent",
|
|
1857
|
+
"sdk.environment_mismatch"
|
|
1858
|
+
]);
|
|
1859
|
+
function safeJson(obj) {
|
|
1860
|
+
try {
|
|
1861
|
+
return JSON.stringify(obj);
|
|
1862
|
+
} catch {
|
|
1863
|
+
return "[unserialisable context]";
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
// src/event-validation.ts
|
|
1868
|
+
var DEFAULT_MAX_STRING = 1024;
|
|
1869
|
+
var DEFAULT_MAX_BYTES = 8 * 1024;
|
|
1870
|
+
var DEFAULT_MAX_DEPTH = 5;
|
|
1871
|
+
function validateEventProperties(input, options = {}) {
|
|
1872
|
+
const warnings = [];
|
|
1873
|
+
if (!input) return { properties: {}, warnings };
|
|
1874
|
+
const maxStringLength = options.maxStringLength ?? DEFAULT_MAX_STRING;
|
|
1875
|
+
const maxBatchPropertyBytes = options.maxBatchPropertyBytes ?? DEFAULT_MAX_BYTES;
|
|
1876
|
+
const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
|
|
1877
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1878
|
+
const visit = (value, key, depth) => {
|
|
1879
|
+
if (depth > maxDepth) {
|
|
1880
|
+
warnings.push({ kind: "depth_exceeded", key });
|
|
1881
|
+
return { keep: true, value: "[depth-exceeded]" };
|
|
1882
|
+
}
|
|
1883
|
+
if (value === null) return { keep: true, value: null };
|
|
1884
|
+
const t = typeof value;
|
|
1885
|
+
if (t === "string") {
|
|
1886
|
+
const s = value;
|
|
1887
|
+
if (s.length > maxStringLength) {
|
|
1888
|
+
warnings.push({ kind: "truncated_string", key });
|
|
1889
|
+
return { keep: true, value: s.slice(0, maxStringLength - 1) + "\u2026" };
|
|
1890
|
+
}
|
|
1891
|
+
return { keep: true, value: s };
|
|
1892
|
+
}
|
|
1893
|
+
if (t === "number") {
|
|
1894
|
+
if (!Number.isFinite(value)) {
|
|
1895
|
+
warnings.push({ kind: "non_serialisable", key });
|
|
1896
|
+
return { keep: true, value: null };
|
|
1897
|
+
}
|
|
1898
|
+
return { keep: true, value };
|
|
1899
|
+
}
|
|
1900
|
+
if (t === "boolean") return { keep: true, value };
|
|
1901
|
+
if (t === "bigint") {
|
|
1902
|
+
warnings.push({ kind: "coerced_bigint", key });
|
|
1903
|
+
return { keep: true, value: value.toString() };
|
|
1904
|
+
}
|
|
1905
|
+
if (t === "function") {
|
|
1906
|
+
warnings.push({ kind: "dropped_function", key });
|
|
1907
|
+
return { keep: false, value: void 0 };
|
|
1908
|
+
}
|
|
1909
|
+
if (t === "symbol") {
|
|
1910
|
+
warnings.push({ kind: "dropped_symbol", key });
|
|
1911
|
+
return { keep: false, value: void 0 };
|
|
1912
|
+
}
|
|
1913
|
+
if (t === "undefined") {
|
|
1914
|
+
warnings.push({ kind: "dropped_undefined", key });
|
|
1915
|
+
return { keep: false, value: void 0 };
|
|
1916
|
+
}
|
|
1917
|
+
if (value instanceof Date) {
|
|
1918
|
+
warnings.push({ kind: "coerced_date", key });
|
|
1919
|
+
const iso = Number.isFinite(value.getTime()) ? value.toISOString() : null;
|
|
1920
|
+
return { keep: true, value: iso };
|
|
1921
|
+
}
|
|
1922
|
+
if (value instanceof Error) {
|
|
1923
|
+
warnings.push({ kind: "coerced_error", key });
|
|
1924
|
+
return {
|
|
1925
|
+
keep: true,
|
|
1926
|
+
value: {
|
|
1927
|
+
name: value.name,
|
|
1928
|
+
message: value.message,
|
|
1929
|
+
stack: typeof value.stack === "string" ? value.stack.slice(0, maxStringLength) : void 0
|
|
1930
|
+
}
|
|
1931
|
+
};
|
|
1932
|
+
}
|
|
1933
|
+
if (value instanceof Map) {
|
|
1934
|
+
warnings.push({ kind: "coerced_map", key });
|
|
1935
|
+
const obj = {};
|
|
1936
|
+
for (const [k, v] of value.entries()) {
|
|
1937
|
+
const subKey = typeof k === "string" ? k : String(k);
|
|
1938
|
+
const result = visit(v, `${key}.${subKey}`, depth + 1);
|
|
1939
|
+
if (result.keep) obj[subKey] = result.value;
|
|
1940
|
+
}
|
|
1941
|
+
return { keep: true, value: obj };
|
|
1942
|
+
}
|
|
1943
|
+
if (value instanceof Set) {
|
|
1944
|
+
warnings.push({ kind: "coerced_set", key });
|
|
1945
|
+
const arr = [];
|
|
1946
|
+
let i = 0;
|
|
1947
|
+
for (const v of value.values()) {
|
|
1948
|
+
const result = visit(v, `${key}[${i}]`, depth + 1);
|
|
1949
|
+
if (result.keep) arr.push(result.value);
|
|
1950
|
+
i++;
|
|
1951
|
+
}
|
|
1952
|
+
return { keep: true, value: arr };
|
|
1953
|
+
}
|
|
1954
|
+
if (Array.isArray(value)) {
|
|
1955
|
+
if (seen.has(value)) {
|
|
1956
|
+
warnings.push({ kind: "circular_reference", key });
|
|
1957
|
+
return { keep: true, value: "[circular]" };
|
|
1958
|
+
}
|
|
1959
|
+
seen.add(value);
|
|
1960
|
+
const out = [];
|
|
1961
|
+
for (let i = 0; i < value.length; i++) {
|
|
1962
|
+
const result = visit(value[i], `${key}[${i}]`, depth + 1);
|
|
1963
|
+
if (result.keep) out.push(result.value);
|
|
1964
|
+
}
|
|
1965
|
+
seen.delete(value);
|
|
1966
|
+
return { keep: true, value: out };
|
|
1967
|
+
}
|
|
1968
|
+
if (t === "object") {
|
|
1969
|
+
const obj = value;
|
|
1970
|
+
if (seen.has(obj)) {
|
|
1971
|
+
warnings.push({ kind: "circular_reference", key });
|
|
1972
|
+
return { keep: true, value: "[circular]" };
|
|
1973
|
+
}
|
|
1974
|
+
seen.add(obj);
|
|
1975
|
+
const out = {};
|
|
1976
|
+
for (const k of Object.keys(obj)) {
|
|
1977
|
+
const result = visit(obj[k], `${key}.${k}`, depth + 1);
|
|
1978
|
+
if (result.keep) out[k] = result.value;
|
|
1979
|
+
}
|
|
1980
|
+
seen.delete(obj);
|
|
1981
|
+
return { keep: true, value: out };
|
|
1982
|
+
}
|
|
1983
|
+
warnings.push({ kind: "non_serialisable", key });
|
|
1984
|
+
try {
|
|
1985
|
+
return { keep: true, value: String(value) };
|
|
1986
|
+
} catch {
|
|
1987
|
+
return { keep: false, value: void 0 };
|
|
1988
|
+
}
|
|
1989
|
+
};
|
|
1990
|
+
const cleaned = {};
|
|
1991
|
+
for (const k of Object.keys(input)) {
|
|
1992
|
+
const result = visit(input[k], k, 0);
|
|
1993
|
+
if (result.keep) cleaned[k] = result.value;
|
|
1994
|
+
}
|
|
1995
|
+
const serialised = safeStringify(cleaned);
|
|
1996
|
+
if (serialised && byteLength(serialised) > maxBatchPropertyBytes) {
|
|
1997
|
+
warnings.push({ kind: "size_cap_exceeded", key: "*" });
|
|
1998
|
+
const sizes = Object.keys(cleaned).map((k) => ({ k, size: byteLength(safeStringify(cleaned[k]) ?? "") })).sort((a, b) => b.size - a.size);
|
|
1999
|
+
let currentSize = byteLength(serialised);
|
|
2000
|
+
for (const { k } of sizes) {
|
|
2001
|
+
if (currentSize <= maxBatchPropertyBytes) break;
|
|
2002
|
+
currentSize -= sizes.find((s) => s.k === k).size;
|
|
2003
|
+
delete cleaned[k];
|
|
2004
|
+
}
|
|
2005
|
+
cleaned.__truncated = true;
|
|
2006
|
+
}
|
|
2007
|
+
return { properties: cleaned, warnings };
|
|
2008
|
+
}
|
|
2009
|
+
function safeStringify(v) {
|
|
2010
|
+
try {
|
|
2011
|
+
return JSON.stringify(v) ?? null;
|
|
2012
|
+
} catch {
|
|
2013
|
+
return null;
|
|
2014
|
+
}
|
|
2015
|
+
}
|
|
2016
|
+
function byteLength(s) {
|
|
2017
|
+
if (typeof TextEncoder !== "undefined") {
|
|
2018
|
+
return new TextEncoder().encode(s).length;
|
|
2019
|
+
}
|
|
2020
|
+
return s.length * 4;
|
|
2021
|
+
}
|
|
2022
|
+
|
|
2023
|
+
// src/super-properties.ts
|
|
2024
|
+
var KEY_SUPER = "super_props";
|
|
2025
|
+
var KEY_GROUPS = "groups";
|
|
2026
|
+
var SuperPropertyStore = class {
|
|
2027
|
+
constructor(storage, prefix) {
|
|
2028
|
+
this.storage = storage;
|
|
2029
|
+
this.prefix = prefix;
|
|
2030
|
+
this.superProps = {};
|
|
2031
|
+
this.groups = {};
|
|
2032
|
+
this.superProps = readJson(storage, prefix + KEY_SUPER) ?? {};
|
|
2033
|
+
this.groups = readJson(storage, prefix + KEY_GROUPS) ?? {};
|
|
2034
|
+
}
|
|
2035
|
+
// ---------- super properties ----------
|
|
2036
|
+
/**
|
|
2037
|
+
* Merge new keys into the super-property bag. Returns a snapshot of
|
|
2038
|
+
* the resulting bag. Values that are `null` are deleted (Mixpanel
|
|
2039
|
+
* semantics — explicit null = "stop tracking this key").
|
|
2040
|
+
*/
|
|
2041
|
+
register(props) {
|
|
2042
|
+
for (const [k, v] of Object.entries(props)) {
|
|
2043
|
+
if (v === null) {
|
|
2044
|
+
delete this.superProps[k];
|
|
2045
|
+
} else if (v !== void 0) {
|
|
2046
|
+
this.superProps[k] = v;
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
writeJson(this.storage, this.prefix + KEY_SUPER, this.superProps);
|
|
2050
|
+
return { ...this.superProps };
|
|
2051
|
+
}
|
|
2052
|
+
/** Remove a single super-property key. Idempotent. */
|
|
2053
|
+
unregister(key) {
|
|
2054
|
+
if (key in this.superProps) {
|
|
2055
|
+
delete this.superProps[key];
|
|
2056
|
+
writeJson(this.storage, this.prefix + KEY_SUPER, this.superProps);
|
|
2057
|
+
}
|
|
2058
|
+
}
|
|
2059
|
+
/** Snapshot of the current super-property bag. */
|
|
2060
|
+
getSuperProperties() {
|
|
2061
|
+
return { ...this.superProps };
|
|
2062
|
+
}
|
|
2063
|
+
// ---------- groups ----------
|
|
2064
|
+
/**
|
|
2065
|
+
* Set a group membership. Passing `id: null` clears the membership
|
|
2066
|
+
* for that group type — the SDK stops attaching it to events.
|
|
2067
|
+
*/
|
|
2068
|
+
setGroup(type, id, traits) {
|
|
2069
|
+
if (id === null) {
|
|
2070
|
+
delete this.groups[type];
|
|
2071
|
+
} else {
|
|
2072
|
+
this.groups[type] = traits !== void 0 ? { id, traits } : { id };
|
|
2073
|
+
}
|
|
2074
|
+
writeJson(this.storage, this.prefix + KEY_GROUPS, this.groups);
|
|
2075
|
+
}
|
|
2076
|
+
/**
|
|
2077
|
+
* Snapshot of the current groups map, keyed by group type. Returned
|
|
2078
|
+
* shape mirrors what the SDK attaches to every event as
|
|
2079
|
+
* `$groups.{type}`. The `traits` sub-object is the most-recent
|
|
2080
|
+
* traits payload passed to `setGroup` for that type; null when none.
|
|
2081
|
+
*/
|
|
2082
|
+
getGroups() {
|
|
2083
|
+
return JSON.parse(JSON.stringify(this.groups));
|
|
2084
|
+
}
|
|
2085
|
+
/**
|
|
2086
|
+
* The flat `{ type: id }` projection used for event-attachment. Stable
|
|
2087
|
+
* for fast every-event merge — we don't want to JSON-clone on each
|
|
2088
|
+
* track() call.
|
|
2089
|
+
*/
|
|
2090
|
+
getGroupIds() {
|
|
2091
|
+
const out = {};
|
|
2092
|
+
for (const [type, info] of Object.entries(this.groups)) {
|
|
2093
|
+
out[type] = info.id;
|
|
2094
|
+
}
|
|
2095
|
+
return out;
|
|
2096
|
+
}
|
|
2097
|
+
/** Wipe both bags. Called by Crossdeck.reset() (logout). */
|
|
2098
|
+
clear() {
|
|
2099
|
+
this.superProps = {};
|
|
2100
|
+
this.groups = {};
|
|
2101
|
+
try {
|
|
2102
|
+
this.storage.removeItem(this.prefix + KEY_SUPER);
|
|
2103
|
+
} catch {
|
|
2104
|
+
}
|
|
2105
|
+
try {
|
|
2106
|
+
this.storage.removeItem(this.prefix + KEY_GROUPS);
|
|
2107
|
+
} catch {
|
|
2108
|
+
}
|
|
2109
|
+
}
|
|
2110
|
+
};
|
|
2111
|
+
function readJson(storage, key) {
|
|
2112
|
+
let raw;
|
|
2113
|
+
try {
|
|
2114
|
+
raw = storage.getItem(key);
|
|
2115
|
+
} catch {
|
|
2116
|
+
return null;
|
|
2117
|
+
}
|
|
2118
|
+
if (!raw) return null;
|
|
2119
|
+
try {
|
|
2120
|
+
return JSON.parse(raw);
|
|
2121
|
+
} catch {
|
|
2122
|
+
return null;
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
function writeJson(storage, key, value) {
|
|
2126
|
+
try {
|
|
2127
|
+
storage.setItem(key, JSON.stringify(value));
|
|
2128
|
+
} catch {
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
|
|
2132
|
+
// src/web-vitals.ts
|
|
2133
|
+
var WebVitalsTracker = class {
|
|
2134
|
+
constructor(cfg, report) {
|
|
2135
|
+
this.cfg = cfg;
|
|
2136
|
+
this.report = report;
|
|
2137
|
+
this.observers = [];
|
|
2138
|
+
this.flushed = /* @__PURE__ */ new Set();
|
|
2139
|
+
this.cls = 0;
|
|
2140
|
+
this.clsEntries = [];
|
|
2141
|
+
this.inp = 0;
|
|
2142
|
+
this.cleanups = [];
|
|
2143
|
+
}
|
|
2144
|
+
install() {
|
|
2145
|
+
if (!this.cfg.enabled) return;
|
|
2146
|
+
if (typeof PerformanceObserver === "undefined") return;
|
|
2147
|
+
if (typeof globalThis === "undefined" || !("document" in globalThis)) return;
|
|
2148
|
+
const doc = globalThis.document;
|
|
2149
|
+
try {
|
|
2150
|
+
const navObserver = new PerformanceObserver((list) => {
|
|
2151
|
+
for (const entry of list.getEntries()) {
|
|
2152
|
+
const e = entry;
|
|
2153
|
+
if (e.responseStart > 0 && !this.flushed.has("ttfb")) {
|
|
2154
|
+
this.flushed.add("ttfb");
|
|
2155
|
+
this.report("webvitals.ttfb", { valueMs: Math.round(e.responseStart - e.startTime) });
|
|
2156
|
+
}
|
|
2157
|
+
}
|
|
2158
|
+
});
|
|
2159
|
+
navObserver.observe({ type: "navigation", buffered: true });
|
|
2160
|
+
this.observers.push(navObserver);
|
|
2161
|
+
} catch {
|
|
2162
|
+
}
|
|
2163
|
+
try {
|
|
2164
|
+
const paintObserver = new PerformanceObserver((list) => {
|
|
2165
|
+
for (const entry of list.getEntries()) {
|
|
2166
|
+
if (entry.name === "first-contentful-paint" && !this.flushed.has("fcp")) {
|
|
2167
|
+
this.flushed.add("fcp");
|
|
2168
|
+
this.report("webvitals.fcp", { valueMs: Math.round(entry.startTime) });
|
|
2169
|
+
}
|
|
2170
|
+
}
|
|
2171
|
+
});
|
|
2172
|
+
paintObserver.observe({ type: "paint", buffered: true });
|
|
2173
|
+
this.observers.push(paintObserver);
|
|
2174
|
+
} catch {
|
|
2175
|
+
}
|
|
2176
|
+
let lcpValue = 0;
|
|
2177
|
+
try {
|
|
2178
|
+
const lcpObserver = new PerformanceObserver((list) => {
|
|
2179
|
+
const entries = list.getEntries();
|
|
2180
|
+
const last = entries[entries.length - 1];
|
|
2181
|
+
if (last) lcpValue = last.startTime;
|
|
2182
|
+
});
|
|
2183
|
+
lcpObserver.observe({ type: "largest-contentful-paint", buffered: true });
|
|
2184
|
+
this.observers.push(lcpObserver);
|
|
2185
|
+
} catch {
|
|
2186
|
+
}
|
|
2187
|
+
try {
|
|
2188
|
+
const clsObserver = new PerformanceObserver((list) => {
|
|
2189
|
+
for (const entry of list.getEntries()) {
|
|
2190
|
+
const e = entry;
|
|
2191
|
+
if (typeof e.value === "number" && !e.hadRecentInput) {
|
|
2192
|
+
this.cls += e.value;
|
|
2193
|
+
this.clsEntries.push(entry);
|
|
2194
|
+
}
|
|
2195
|
+
}
|
|
2196
|
+
});
|
|
2197
|
+
clsObserver.observe({ type: "layout-shift", buffered: true });
|
|
2198
|
+
this.observers.push(clsObserver);
|
|
2199
|
+
} catch {
|
|
2200
|
+
}
|
|
2201
|
+
try {
|
|
2202
|
+
const eventObserver = new PerformanceObserver((list) => {
|
|
2203
|
+
for (const entry of list.getEntries()) {
|
|
2204
|
+
const e = entry;
|
|
2205
|
+
if (e.interactionId && e.duration > this.inp) {
|
|
2206
|
+
this.inp = e.duration;
|
|
2207
|
+
}
|
|
2208
|
+
}
|
|
2209
|
+
});
|
|
2210
|
+
try {
|
|
2211
|
+
eventObserver.observe({ type: "event", buffered: true, durationThreshold: 16 });
|
|
2212
|
+
} catch {
|
|
2213
|
+
eventObserver.observe({ type: "first-input", buffered: true });
|
|
2214
|
+
}
|
|
2215
|
+
this.observers.push(eventObserver);
|
|
2216
|
+
} catch {
|
|
2217
|
+
}
|
|
2218
|
+
const flush = () => {
|
|
2219
|
+
if (lcpValue > 0 && !this.flushed.has("lcp")) {
|
|
2220
|
+
this.flushed.add("lcp");
|
|
2221
|
+
this.report("webvitals.lcp", { valueMs: Math.round(lcpValue) });
|
|
2222
|
+
}
|
|
2223
|
+
if (this.cls > 0 && !this.flushed.has("cls")) {
|
|
2224
|
+
this.flushed.add("cls");
|
|
2225
|
+
this.report("webvitals.cls", { value: Math.round(this.cls * 1e3) / 1e3 });
|
|
2226
|
+
}
|
|
2227
|
+
if (this.inp > 0 && !this.flushed.has("inp")) {
|
|
2228
|
+
this.flushed.add("inp");
|
|
2229
|
+
this.report("webvitals.inp", { valueMs: Math.round(this.inp) });
|
|
2230
|
+
}
|
|
2231
|
+
};
|
|
2232
|
+
const onHidden = () => {
|
|
2233
|
+
if (doc.visibilityState === "hidden") flush();
|
|
2234
|
+
};
|
|
2235
|
+
doc.addEventListener("visibilitychange", onHidden);
|
|
2236
|
+
globalThis.window.addEventListener("pagehide", flush);
|
|
2237
|
+
this.cleanups.push(() => {
|
|
2238
|
+
doc.removeEventListener("visibilitychange", onHidden);
|
|
2239
|
+
globalThis.window.removeEventListener("pagehide", flush);
|
|
2240
|
+
});
|
|
2241
|
+
}
|
|
2242
|
+
uninstall() {
|
|
2243
|
+
for (const o of this.observers) {
|
|
2244
|
+
try {
|
|
2245
|
+
o.disconnect();
|
|
2246
|
+
} catch {
|
|
2247
|
+
}
|
|
2248
|
+
}
|
|
2249
|
+
this.observers = [];
|
|
2250
|
+
for (const fn of this.cleanups.splice(0)) {
|
|
2251
|
+
try {
|
|
2252
|
+
fn();
|
|
2253
|
+
} catch {
|
|
2254
|
+
}
|
|
2255
|
+
}
|
|
2256
|
+
}
|
|
2257
|
+
};
|
|
2258
|
+
|
|
2259
|
+
// src/consent.ts
|
|
2260
|
+
var ALL_GRANTED = {
|
|
2261
|
+
analytics: true,
|
|
2262
|
+
marketing: true,
|
|
2263
|
+
errors: true
|
|
2264
|
+
};
|
|
2265
|
+
var ConsentManager = class {
|
|
2266
|
+
constructor(options) {
|
|
2267
|
+
this.state = { ...ALL_GRANTED };
|
|
2268
|
+
this.dntDenied = false;
|
|
2269
|
+
if (options?.respectDnt && this.detectDnt()) {
|
|
2270
|
+
this.dntDenied = true;
|
|
2271
|
+
this.state = { analytics: false, marketing: false, errors: false };
|
|
2272
|
+
}
|
|
2273
|
+
}
|
|
2274
|
+
/**
|
|
2275
|
+
* Merge new dimensions onto the current state. Returns the resulting
|
|
2276
|
+
* snapshot. DNT-derived denies cannot be flipped back on by a `set`
|
|
2277
|
+
* call — once the browser says "don't track", we don't track even if
|
|
2278
|
+
* the developer code disagrees. That's the contract.
|
|
2279
|
+
*/
|
|
2280
|
+
set(partial) {
|
|
2281
|
+
if (this.dntDenied) return { ...this.state };
|
|
2282
|
+
for (const k of Object.keys(partial)) {
|
|
2283
|
+
const v = partial[k];
|
|
2284
|
+
if (typeof v === "boolean") this.state[k] = v;
|
|
2285
|
+
}
|
|
2286
|
+
return { ...this.state };
|
|
2287
|
+
}
|
|
2288
|
+
/** Snapshot of the current state. */
|
|
2289
|
+
get() {
|
|
2290
|
+
return { ...this.state };
|
|
2291
|
+
}
|
|
2292
|
+
/** Convenience getters for hot paths. */
|
|
2293
|
+
get analytics() {
|
|
2294
|
+
return this.state.analytics;
|
|
2295
|
+
}
|
|
2296
|
+
get marketing() {
|
|
2297
|
+
return this.state.marketing;
|
|
2298
|
+
}
|
|
2299
|
+
get errors() {
|
|
2300
|
+
return this.state.errors;
|
|
2301
|
+
}
|
|
2302
|
+
/** True iff the constructor detected and applied DNT. */
|
|
2303
|
+
get isDntDenied() {
|
|
2304
|
+
return this.dntDenied;
|
|
2305
|
+
}
|
|
2306
|
+
detectDnt() {
|
|
2307
|
+
try {
|
|
2308
|
+
const nav = globalThis.navigator;
|
|
2309
|
+
if (!nav) return false;
|
|
2310
|
+
const sources = [
|
|
2311
|
+
nav.doNotTrack,
|
|
2312
|
+
nav.msDoNotTrack,
|
|
2313
|
+
globalThis.doNotTrack
|
|
2314
|
+
];
|
|
2315
|
+
return sources.some((v) => v === "1" || v === "yes");
|
|
2316
|
+
} catch {
|
|
2317
|
+
return false;
|
|
2318
|
+
}
|
|
2319
|
+
}
|
|
2320
|
+
};
|
|
2321
|
+
var EMAIL_PATTERN = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
|
|
2322
|
+
var CARD_PATTERN = /\b\d(?:[ -]?\d){12,18}\b/g;
|
|
2323
|
+
var REPLACEMENT_EMAIL = "<email>";
|
|
2324
|
+
var REPLACEMENT_CARD = "<card>";
|
|
2325
|
+
function scrubPii(value) {
|
|
2326
|
+
if (!value) return value;
|
|
2327
|
+
return value.replace(EMAIL_PATTERN, REPLACEMENT_EMAIL).replace(CARD_PATTERN, REPLACEMENT_CARD);
|
|
2328
|
+
}
|
|
2329
|
+
function scrubPiiFromProperties(properties) {
|
|
2330
|
+
const out = {};
|
|
2331
|
+
for (const k of Object.keys(properties)) {
|
|
2332
|
+
out[k] = scrubValue(properties[k]);
|
|
2333
|
+
}
|
|
2334
|
+
return out;
|
|
2335
|
+
}
|
|
2336
|
+
function scrubValue(v) {
|
|
2337
|
+
if (typeof v === "string") return scrubPii(v);
|
|
2338
|
+
if (Array.isArray(v)) return v.map(scrubValue);
|
|
2339
|
+
if (v && typeof v === "object" && v.constructor === Object) {
|
|
2340
|
+
return scrubPiiFromProperties(v);
|
|
2341
|
+
}
|
|
2342
|
+
return v;
|
|
2343
|
+
}
|
|
2344
|
+
|
|
2345
|
+
// src/breadcrumbs.ts
|
|
2346
|
+
var BreadcrumbBuffer = class {
|
|
2347
|
+
constructor(maxSize = 50) {
|
|
2348
|
+
this.maxSize = maxSize;
|
|
2349
|
+
this.items = [];
|
|
2350
|
+
}
|
|
2351
|
+
add(crumb) {
|
|
2352
|
+
this.items.push(crumb);
|
|
2353
|
+
if (this.items.length > this.maxSize) {
|
|
2354
|
+
this.items.shift();
|
|
2355
|
+
}
|
|
2356
|
+
}
|
|
2357
|
+
/** Defensive copy — caller can read freely without mutating buffer state. */
|
|
2358
|
+
snapshot() {
|
|
2359
|
+
return this.items.slice();
|
|
2360
|
+
}
|
|
2361
|
+
clear() {
|
|
2362
|
+
this.items = [];
|
|
2363
|
+
}
|
|
2364
|
+
get size() {
|
|
2365
|
+
return this.items.length;
|
|
2366
|
+
}
|
|
2367
|
+
};
|
|
2368
|
+
|
|
2369
|
+
// src/stack-parser.ts
|
|
2370
|
+
function parseStack(stack) {
|
|
2371
|
+
if (!stack || typeof stack !== "string") return [];
|
|
2372
|
+
const lines = stack.split("\n");
|
|
2373
|
+
const frames = [];
|
|
2374
|
+
for (const line of lines) {
|
|
2375
|
+
const trimmed = line.trim();
|
|
2376
|
+
if (!trimmed) continue;
|
|
2377
|
+
const frame = parseLine(trimmed);
|
|
2378
|
+
if (frame) frames.push(frame);
|
|
2379
|
+
}
|
|
2380
|
+
return frames;
|
|
2381
|
+
}
|
|
2382
|
+
function parseLine(line) {
|
|
2383
|
+
let m = /^at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)$/.exec(line);
|
|
2384
|
+
if (m) {
|
|
2385
|
+
return buildFrame({
|
|
2386
|
+
function: m[1],
|
|
2387
|
+
filename: m[2],
|
|
2388
|
+
lineno: parseInt(m[3], 10),
|
|
2389
|
+
colno: parseInt(m[4], 10),
|
|
2390
|
+
raw: line
|
|
2391
|
+
});
|
|
2392
|
+
}
|
|
2393
|
+
m = /^at\s+(.+?):(\d+):(\d+)$/.exec(line);
|
|
2394
|
+
if (m) {
|
|
2395
|
+
return buildFrame({
|
|
2396
|
+
function: "?",
|
|
2397
|
+
filename: m[1],
|
|
2398
|
+
lineno: parseInt(m[2], 10),
|
|
2399
|
+
colno: parseInt(m[3], 10),
|
|
2400
|
+
raw: line
|
|
2401
|
+
});
|
|
2402
|
+
}
|
|
2403
|
+
m = /^(.*?)@(.+?):(\d+):(\d+)$/.exec(line);
|
|
2404
|
+
if (m) {
|
|
2405
|
+
return buildFrame({
|
|
2406
|
+
function: m[1] || "?",
|
|
2407
|
+
filename: m[2],
|
|
2408
|
+
lineno: parseInt(m[3], 10),
|
|
2409
|
+
colno: parseInt(m[4], 10),
|
|
2410
|
+
raw: line
|
|
2411
|
+
});
|
|
2412
|
+
}
|
|
2413
|
+
if (/^\w*Error/.test(line) || !line.includes(":")) {
|
|
2414
|
+
return null;
|
|
2415
|
+
}
|
|
2416
|
+
return {
|
|
2417
|
+
function: "?",
|
|
2418
|
+
filename: "",
|
|
2419
|
+
lineno: 0,
|
|
2420
|
+
colno: 0,
|
|
2421
|
+
in_app: true,
|
|
2422
|
+
raw: line
|
|
2423
|
+
};
|
|
2424
|
+
}
|
|
2425
|
+
function buildFrame(input) {
|
|
2426
|
+
return {
|
|
2427
|
+
function: input.function || "?",
|
|
2428
|
+
filename: input.filename,
|
|
2429
|
+
lineno: Number.isFinite(input.lineno) ? input.lineno : 0,
|
|
2430
|
+
colno: Number.isFinite(input.colno) ? input.colno : 0,
|
|
2431
|
+
in_app: isInAppFrame(input.filename),
|
|
2432
|
+
raw: input.raw
|
|
2433
|
+
};
|
|
2434
|
+
}
|
|
2435
|
+
function isInAppFrame(filename) {
|
|
2436
|
+
if (!filename) return true;
|
|
2437
|
+
if (/^(?:chrome|moz|safari|webkit)-extension:\/\//.test(filename)) return false;
|
|
2438
|
+
if (/\bcdn\.jsdelivr\.net\b/.test(filename)) return false;
|
|
2439
|
+
if (/\bunpkg\.com\b/.test(filename)) return false;
|
|
2440
|
+
if (/\bgoogletagmanager\.com\b/.test(filename)) return false;
|
|
2441
|
+
if (/\bgoogle-analytics\.com\b/.test(filename)) return false;
|
|
2442
|
+
if (/\b@cross-deck\/web\b/.test(filename)) return false;
|
|
2443
|
+
if (/\/crossdeck\.umd\.min\.js$/.test(filename)) return false;
|
|
2444
|
+
return true;
|
|
2445
|
+
}
|
|
2446
|
+
function fingerprintError(message, frames, location) {
|
|
2447
|
+
const inAppFrames = frames.filter((f) => f.in_app).slice(0, 3);
|
|
2448
|
+
const parts = [
|
|
2449
|
+
(message || "").slice(0, 200),
|
|
2450
|
+
...inAppFrames.map((f) => `${f.function}@${f.filename}:${f.lineno}`)
|
|
2451
|
+
];
|
|
2452
|
+
if (inAppFrames.length === 0 && location) {
|
|
2453
|
+
const loc = [
|
|
2454
|
+
location.errorType ?? "",
|
|
2455
|
+
location.filename ?? "",
|
|
2456
|
+
location.lineno ?? "",
|
|
2457
|
+
location.colno ?? ""
|
|
2458
|
+
].join(":");
|
|
2459
|
+
if (loc !== ":::") parts.push(loc);
|
|
2460
|
+
}
|
|
2461
|
+
return djb2Hex(parts.join("|"));
|
|
2462
|
+
}
|
|
2463
|
+
function djb2Hex(input) {
|
|
2464
|
+
let h = 5381;
|
|
2465
|
+
for (let i = 0; i < input.length; i++) {
|
|
2466
|
+
h = (h << 5) + h + input.charCodeAt(i) | 0;
|
|
2467
|
+
}
|
|
2468
|
+
return (h >>> 0).toString(16).padStart(8, "0");
|
|
2469
|
+
}
|
|
2470
|
+
|
|
2471
|
+
// src/error-capture.ts
|
|
2472
|
+
var DEFAULT_ERROR_CAPTURE = {
|
|
2473
|
+
enabled: true,
|
|
2474
|
+
onError: true,
|
|
2475
|
+
onUnhandledRejection: true,
|
|
2476
|
+
wrapFetch: true,
|
|
2477
|
+
wrapXhr: true,
|
|
2478
|
+
captureConsole: false,
|
|
2479
|
+
ignoreErrors: [
|
|
2480
|
+
// Classic browser noise. These aren't application bugs.
|
|
2481
|
+
"ResizeObserver loop limit exceeded",
|
|
2482
|
+
"ResizeObserver loop completed with undelivered notifications",
|
|
2483
|
+
"Non-Error promise rejection captured"
|
|
2484
|
+
// NOTE: We deliberately do NOT drop cross-origin "Script error."
|
|
2485
|
+
// events here. They used to be silently filtered as noise, but
|
|
2486
|
+
// silent drops are the opposite of "developer sleeps well at
|
|
2487
|
+
// night". We now capture them with a clear label and the
|
|
2488
|
+
// `cross_origin` tag so the dashboard surfaces them as a
|
|
2489
|
+
// distinct, actionable category (the fix is always the same —
|
|
2490
|
+
// add `crossorigin="anonymous"` to the script tag + CORS
|
|
2491
|
+
// headers on the script's origin). Apps that genuinely want
|
|
2492
|
+
// them muted can re-add "Script error" to ignoreErrors via
|
|
2493
|
+
// init config.
|
|
2494
|
+
],
|
|
2495
|
+
allowUrls: [],
|
|
2496
|
+
denyUrls: [
|
|
2497
|
+
// Common third-party extensions that pollute error streams.
|
|
2498
|
+
/^chrome-extension:\/\//,
|
|
2499
|
+
/^moz-extension:\/\//,
|
|
2500
|
+
/^safari-extension:\/\//,
|
|
2501
|
+
/^webkit-extension:\/\//,
|
|
2502
|
+
/^safari-web-extension:\/\//
|
|
2503
|
+
],
|
|
2504
|
+
sampleRate: 1,
|
|
2505
|
+
maxPerFingerprintPerMinute: 5,
|
|
2506
|
+
maxPerSession: 100
|
|
2507
|
+
};
|
|
2508
|
+
var ErrorTracker = class {
|
|
2509
|
+
constructor(opts) {
|
|
2510
|
+
this.opts = opts;
|
|
2511
|
+
this.installed = false;
|
|
2512
|
+
this.cleanups = [];
|
|
2513
|
+
this._reporting = false;
|
|
2514
|
+
this.sessionCount = 0;
|
|
2515
|
+
this.fingerprintWindow = /* @__PURE__ */ new Map();
|
|
2516
|
+
}
|
|
2517
|
+
install() {
|
|
2518
|
+
if (this.installed) return;
|
|
2519
|
+
if (!this.opts.config.enabled) return;
|
|
2520
|
+
if (typeof globalThis === "undefined" || !("window" in globalThis)) return;
|
|
2521
|
+
const w = globalThis.window;
|
|
2522
|
+
if (this.opts.config.onError) this.installOnErrorListener(w);
|
|
2523
|
+
if (this.opts.config.onUnhandledRejection) this.installRejectionListener(w);
|
|
2524
|
+
if (this.opts.config.wrapFetch) this.installFetchWrap(w);
|
|
2525
|
+
if (this.opts.config.wrapXhr) this.installXhrWrap(w);
|
|
2526
|
+
if (this.opts.config.captureConsole) this.installConsoleWrap();
|
|
2527
|
+
this.installed = true;
|
|
2528
|
+
}
|
|
2529
|
+
uninstall() {
|
|
2530
|
+
for (const fn of this.cleanups.splice(0)) {
|
|
2531
|
+
try {
|
|
2532
|
+
fn();
|
|
2533
|
+
} catch {
|
|
2534
|
+
}
|
|
2535
|
+
}
|
|
2536
|
+
this.installed = false;
|
|
2537
|
+
}
|
|
2538
|
+
/**
|
|
2539
|
+
* Manual API. Either an Error instance or any unknown value (we
|
|
2540
|
+
* coerce). Returns silently — never throws.
|
|
2541
|
+
*/
|
|
2542
|
+
captureError(error, options) {
|
|
2543
|
+
if (!this.opts.isConsented()) return;
|
|
2544
|
+
try {
|
|
2545
|
+
const captured = this.buildFromUnknown(error, "error.handled", options?.level ?? "error");
|
|
2546
|
+
if (options?.context) captured.context = { ...captured.context, ...options.context };
|
|
2547
|
+
if (options?.tags) captured.tags = { ...captured.tags, ...options.tags };
|
|
2548
|
+
this.maybeReport(captured);
|
|
2549
|
+
} catch {
|
|
2550
|
+
}
|
|
2551
|
+
}
|
|
2552
|
+
/**
|
|
2553
|
+
* Capture a non-error event as an issue. For "we hit a soft-warning
|
|
2554
|
+
* code path" / "deprecated API used" kinds of signals. Pairs with
|
|
2555
|
+
* Sentry's captureMessage().
|
|
2556
|
+
*/
|
|
2557
|
+
captureMessage(message, level = "info") {
|
|
2558
|
+
if (!this.opts.isConsented()) return;
|
|
2559
|
+
try {
|
|
2560
|
+
const captured = {
|
|
2561
|
+
timestamp: Date.now(),
|
|
2562
|
+
kind: "error.message",
|
|
2563
|
+
level,
|
|
2564
|
+
message,
|
|
2565
|
+
errorType: null,
|
|
2566
|
+
frames: [],
|
|
2567
|
+
rawStack: null,
|
|
2568
|
+
filename: null,
|
|
2569
|
+
lineno: null,
|
|
2570
|
+
colno: null,
|
|
2571
|
+
fingerprint: fingerprintError(message, []),
|
|
2572
|
+
breadcrumbs: this.opts.breadcrumbs.snapshot(),
|
|
2573
|
+
context: this.opts.getContext(),
|
|
2574
|
+
tags: this.opts.getTags()
|
|
2575
|
+
};
|
|
2576
|
+
this.maybeReport(captured);
|
|
2577
|
+
} catch {
|
|
2578
|
+
}
|
|
2579
|
+
}
|
|
2580
|
+
// ============================================================
|
|
2581
|
+
// Listener installation
|
|
2582
|
+
// ============================================================
|
|
2583
|
+
installOnErrorListener(w) {
|
|
2584
|
+
const handler = (event) => {
|
|
2585
|
+
if (this._reporting) return;
|
|
2586
|
+
if (!this.opts.isConsented()) return;
|
|
2587
|
+
try {
|
|
2588
|
+
this._reporting = true;
|
|
2589
|
+
const captured = this.buildFromErrorEvent(event);
|
|
2590
|
+
this.maybeReport(captured);
|
|
2591
|
+
} catch {
|
|
2592
|
+
} finally {
|
|
2593
|
+
this._reporting = false;
|
|
2594
|
+
}
|
|
2595
|
+
};
|
|
2596
|
+
w.addEventListener("error", handler, true);
|
|
2597
|
+
this.cleanups.push(() => w.removeEventListener("error", handler, true));
|
|
2598
|
+
}
|
|
2599
|
+
installRejectionListener(w) {
|
|
2600
|
+
const handler = (event) => {
|
|
2601
|
+
if (this._reporting) return;
|
|
2602
|
+
if (!this.opts.isConsented()) return;
|
|
2603
|
+
try {
|
|
2604
|
+
this._reporting = true;
|
|
2605
|
+
const captured = this.buildFromUnknown(
|
|
2606
|
+
event.reason,
|
|
2607
|
+
"error.unhandledrejection",
|
|
2608
|
+
"error"
|
|
2609
|
+
);
|
|
2610
|
+
this.maybeReport(captured);
|
|
2611
|
+
} catch {
|
|
2612
|
+
} finally {
|
|
2613
|
+
this._reporting = false;
|
|
2614
|
+
}
|
|
2615
|
+
};
|
|
2616
|
+
w.addEventListener("unhandledrejection", handler);
|
|
2617
|
+
this.cleanups.push(() => w.removeEventListener("unhandledrejection", handler));
|
|
2618
|
+
}
|
|
2619
|
+
/**
|
|
2620
|
+
* Wrap fetch() so failed HTTP requests get auto-captured. We do NOT
|
|
2621
|
+
* call this an "error" for 4xx (those are often expected — auth
|
|
2622
|
+
* required, validation failed). Only 5xx + network failures fire.
|
|
2623
|
+
*/
|
|
2624
|
+
installFetchWrap(w) {
|
|
2625
|
+
const origFetch = w.fetch?.bind(w);
|
|
2626
|
+
if (!origFetch) return;
|
|
2627
|
+
const wrapped = async (...args) => {
|
|
2628
|
+
const input = args[0];
|
|
2629
|
+
const init = args[1] ?? {};
|
|
2630
|
+
const url = typeof input === "string" ? input : input?.url ?? "";
|
|
2631
|
+
const method = (init.method || "GET").toUpperCase();
|
|
2632
|
+
const start = Date.now();
|
|
2633
|
+
if (!isSelfRequest(url, this.opts.selfHostname)) {
|
|
2634
|
+
this.opts.breadcrumbs.add({
|
|
2635
|
+
timestamp: start,
|
|
2636
|
+
category: "http",
|
|
2637
|
+
message: `${method} ${url}`,
|
|
2638
|
+
data: { url, method }
|
|
2639
|
+
});
|
|
2640
|
+
}
|
|
2641
|
+
try {
|
|
2642
|
+
const response = await origFetch(...args);
|
|
2643
|
+
if (response.status >= 500 && this.opts.isConsented()) {
|
|
2644
|
+
if (!isSelfRequest(url, this.opts.selfHostname)) {
|
|
2645
|
+
this.captureHttp({
|
|
2646
|
+
url,
|
|
2647
|
+
method,
|
|
2648
|
+
status: response.status,
|
|
2649
|
+
statusText: response.statusText
|
|
2650
|
+
});
|
|
2651
|
+
}
|
|
2652
|
+
}
|
|
2653
|
+
return response;
|
|
2654
|
+
} catch (err) {
|
|
2655
|
+
if (this.opts.isConsented() && !url.includes("api.cross-deck.com")) {
|
|
2656
|
+
this.captureHttp({
|
|
2657
|
+
url,
|
|
2658
|
+
method,
|
|
2659
|
+
status: 0,
|
|
2660
|
+
statusText: err instanceof Error ? err.message : "network error"
|
|
2661
|
+
});
|
|
2662
|
+
}
|
|
2663
|
+
throw err;
|
|
2664
|
+
}
|
|
2665
|
+
};
|
|
2666
|
+
w.fetch = wrapped;
|
|
2667
|
+
this.cleanups.push(() => {
|
|
2668
|
+
if (w.fetch === wrapped) w.fetch = origFetch;
|
|
2669
|
+
});
|
|
2670
|
+
}
|
|
2671
|
+
/**
|
|
2672
|
+
* Wrap XMLHttpRequest for legacy consumers (jQuery $.ajax under the
|
|
2673
|
+
* hood, older bundlers). Same capture semantics as fetch.
|
|
2674
|
+
*/
|
|
2675
|
+
installXhrWrap(w) {
|
|
2676
|
+
const xhrCtor = w.XMLHttpRequest;
|
|
2677
|
+
const proto = xhrCtor?.prototype;
|
|
2678
|
+
if (!proto) return;
|
|
2679
|
+
const origOpen = proto.open;
|
|
2680
|
+
const origSend = proto.send;
|
|
2681
|
+
const tracker = this;
|
|
2682
|
+
proto.open = function(method, url, ...rest) {
|
|
2683
|
+
this._cdMethod = method;
|
|
2684
|
+
this._cdUrl = url;
|
|
2685
|
+
return origOpen.apply(this, [method, url, ...rest]);
|
|
2686
|
+
};
|
|
2687
|
+
proto.send = function(body) {
|
|
2688
|
+
const xhr = this;
|
|
2689
|
+
const onLoad = () => {
|
|
2690
|
+
try {
|
|
2691
|
+
if (xhr.status >= 500 && tracker.opts.isConsented()) {
|
|
2692
|
+
const url = xhr._cdUrl ?? "";
|
|
2693
|
+
if (!isSelfRequest(url, tracker.opts.selfHostname)) {
|
|
2694
|
+
tracker.captureHttp({
|
|
2695
|
+
url,
|
|
2696
|
+
method: (xhr._cdMethod ?? "GET").toUpperCase(),
|
|
2697
|
+
status: xhr.status,
|
|
2698
|
+
statusText: xhr.statusText
|
|
2699
|
+
});
|
|
2700
|
+
}
|
|
2701
|
+
}
|
|
2702
|
+
} catch {
|
|
2703
|
+
}
|
|
2704
|
+
};
|
|
2705
|
+
xhr.addEventListener("loadend", onLoad);
|
|
2706
|
+
return origSend.apply(this, [body ?? null]);
|
|
2707
|
+
};
|
|
2708
|
+
this.cleanups.push(() => {
|
|
2709
|
+
proto.open = origOpen;
|
|
2710
|
+
proto.send = origSend;
|
|
2711
|
+
});
|
|
2712
|
+
}
|
|
2713
|
+
installConsoleWrap() {
|
|
2714
|
+
const console2 = globalThis.console;
|
|
2715
|
+
if (!console2) return;
|
|
2716
|
+
const orig = console2.error.bind(console2);
|
|
2717
|
+
console2.error = (...args) => {
|
|
2718
|
+
try {
|
|
2719
|
+
if (this.opts.isConsented()) {
|
|
2720
|
+
this.captureMessage(args.map((a) => safeStringify2(a)).join(" "), "error");
|
|
2721
|
+
}
|
|
2722
|
+
} catch {
|
|
2723
|
+
}
|
|
2724
|
+
return orig(...args);
|
|
2725
|
+
};
|
|
2726
|
+
this.cleanups.push(() => {
|
|
2727
|
+
console2.error = orig;
|
|
2728
|
+
});
|
|
2729
|
+
}
|
|
2730
|
+
// ============================================================
|
|
2731
|
+
// Builders
|
|
2732
|
+
// ============================================================
|
|
2733
|
+
buildFromErrorEvent(event) {
|
|
2734
|
+
const err = event.error;
|
|
2735
|
+
const filename = event.filename || null;
|
|
2736
|
+
const lineno = typeof event.lineno === "number" && event.lineno > 0 ? event.lineno : null;
|
|
2737
|
+
const colno = typeof event.colno === "number" && event.colno > 0 ? event.colno : null;
|
|
2738
|
+
const isCrossOriginStripped = err == null && !filename && lineno == null && (event.message === "Script error." || event.message === "Script error" || !event.message);
|
|
2739
|
+
if (isCrossOriginStripped) {
|
|
2740
|
+
const message2 = "Cross-origin script error (browser hid details \u2014 script needs crossorigin attribute + CORS headers)";
|
|
2741
|
+
return {
|
|
2742
|
+
timestamp: Date.now(),
|
|
2743
|
+
kind: "error.unhandled",
|
|
2744
|
+
level: "error",
|
|
2745
|
+
message: message2,
|
|
2746
|
+
errorType: "ScriptError",
|
|
2747
|
+
frames: [],
|
|
2748
|
+
rawStack: null,
|
|
2749
|
+
filename: null,
|
|
2750
|
+
lineno: null,
|
|
2751
|
+
colno: null,
|
|
2752
|
+
// No location to fingerprint by — all of these will share one
|
|
2753
|
+
// group, which is correct: developer fixes them all with the
|
|
2754
|
+
// same CORS change.
|
|
2755
|
+
fingerprint: fingerprintError(message2, []),
|
|
2756
|
+
breadcrumbs: this.opts.breadcrumbs.snapshot(),
|
|
2757
|
+
context: this.opts.getContext(),
|
|
2758
|
+
tags: { ...this.opts.getTags(), cross_origin: "true" }
|
|
2759
|
+
};
|
|
2760
|
+
}
|
|
2761
|
+
const payload = coerceErrorPayload(err);
|
|
2762
|
+
const message = (payload.message || event.message || "Unknown error").slice(0, 1024);
|
|
2763
|
+
const stack = err instanceof Error ? err.stack ?? null : null;
|
|
2764
|
+
const frames = parseStack(stack);
|
|
2765
|
+
const errorType = payload.errorType ?? null;
|
|
2766
|
+
const context = payload.extras ? { ...this.opts.getContext(), __error_extras: payload.extras } : this.opts.getContext();
|
|
2767
|
+
return {
|
|
2768
|
+
timestamp: Date.now(),
|
|
2769
|
+
kind: "error.unhandled",
|
|
2770
|
+
level: "error",
|
|
2771
|
+
message,
|
|
2772
|
+
errorType,
|
|
2773
|
+
frames,
|
|
2774
|
+
rawStack: stack,
|
|
2775
|
+
filename,
|
|
2776
|
+
lineno,
|
|
2777
|
+
colno,
|
|
2778
|
+
// Location fallback ensures distinct call sites stay separate
|
|
2779
|
+
// even when the message is generic ("Unknown error",
|
|
2780
|
+
// "[object Object]") and there are no parseable frames.
|
|
2781
|
+
fingerprint: fingerprintError(message, frames, {
|
|
2782
|
+
filename,
|
|
2783
|
+
lineno,
|
|
2784
|
+
colno,
|
|
2785
|
+
errorType
|
|
2786
|
+
}),
|
|
2787
|
+
breadcrumbs: this.opts.breadcrumbs.snapshot(),
|
|
2788
|
+
context,
|
|
2789
|
+
tags: this.opts.getTags()
|
|
2790
|
+
};
|
|
2791
|
+
}
|
|
2792
|
+
buildFromUnknown(err, kind, level) {
|
|
2793
|
+
const payload = coerceErrorPayload(err);
|
|
2794
|
+
const message = (payload.message || "Unknown error").slice(0, 1024);
|
|
2795
|
+
const stack = err instanceof Error ? err.stack ?? null : null;
|
|
2796
|
+
const frames = parseStack(stack);
|
|
2797
|
+
const errorType = payload.errorType ?? null;
|
|
2798
|
+
const context = payload.extras ? { ...this.opts.getContext(), __error_extras: payload.extras } : this.opts.getContext();
|
|
2799
|
+
return {
|
|
2800
|
+
timestamp: Date.now(),
|
|
2801
|
+
kind,
|
|
2802
|
+
level,
|
|
2803
|
+
message,
|
|
2804
|
+
errorType,
|
|
2805
|
+
frames,
|
|
2806
|
+
rawStack: stack,
|
|
2807
|
+
filename: null,
|
|
2808
|
+
lineno: null,
|
|
2809
|
+
colno: null,
|
|
2810
|
+
fingerprint: fingerprintError(message, frames, { errorType }),
|
|
2811
|
+
breadcrumbs: this.opts.breadcrumbs.snapshot(),
|
|
2812
|
+
context,
|
|
2813
|
+
tags: this.opts.getTags()
|
|
2814
|
+
};
|
|
2815
|
+
}
|
|
2816
|
+
captureHttp(info) {
|
|
2817
|
+
try {
|
|
2818
|
+
const message = `HTTP ${info.status} ${info.method} ${info.url}`;
|
|
2819
|
+
const captured = {
|
|
2820
|
+
timestamp: Date.now(),
|
|
2821
|
+
kind: "error.http",
|
|
2822
|
+
level: "error",
|
|
2823
|
+
message,
|
|
2824
|
+
errorType: `HTTPError`,
|
|
2825
|
+
frames: [],
|
|
2826
|
+
rawStack: null,
|
|
2827
|
+
filename: info.url,
|
|
2828
|
+
lineno: null,
|
|
2829
|
+
colno: null,
|
|
2830
|
+
fingerprint: fingerprintError(`HTTP ${info.status} ${info.method}`, [], {
|
|
2831
|
+
filename: info.url,
|
|
2832
|
+
errorType: "HTTPError"
|
|
2833
|
+
}),
|
|
2834
|
+
breadcrumbs: this.opts.breadcrumbs.snapshot(),
|
|
2835
|
+
context: this.opts.getContext(),
|
|
2836
|
+
tags: this.opts.getTags(),
|
|
2837
|
+
http: info
|
|
2838
|
+
};
|
|
2839
|
+
this.maybeReport(captured);
|
|
2840
|
+
} catch {
|
|
2841
|
+
}
|
|
2842
|
+
}
|
|
2843
|
+
// ============================================================
|
|
2844
|
+
// Reporting pipeline — filter / sample / rate-limit / send
|
|
2845
|
+
// ============================================================
|
|
2846
|
+
maybeReport(err) {
|
|
2847
|
+
if (this.sessionCount >= this.opts.config.maxPerSession) return;
|
|
2848
|
+
if (this.shouldIgnore(err)) return;
|
|
2849
|
+
if (!this.passesUrlGate(err)) return;
|
|
2850
|
+
if (!this.passesSample(err)) return;
|
|
2851
|
+
if (!this.passesRateLimit(err)) return;
|
|
2852
|
+
let finalErr = err;
|
|
2853
|
+
const hook = this.opts.beforeSend?.();
|
|
2854
|
+
if (hook) {
|
|
2855
|
+
try {
|
|
2856
|
+
finalErr = hook(err);
|
|
2857
|
+
} catch {
|
|
2858
|
+
finalErr = err;
|
|
2859
|
+
}
|
|
2860
|
+
if (!finalErr) return;
|
|
2861
|
+
}
|
|
2862
|
+
this.sessionCount += 1;
|
|
2863
|
+
try {
|
|
2864
|
+
this.opts.report(finalErr);
|
|
2865
|
+
} catch {
|
|
2866
|
+
}
|
|
2867
|
+
}
|
|
2868
|
+
shouldIgnore(err) {
|
|
2869
|
+
for (const pat of this.opts.config.ignoreErrors) {
|
|
2870
|
+
if (typeof pat === "string" && err.message.includes(pat)) return true;
|
|
2871
|
+
if (pat instanceof RegExp && pat.test(err.message)) return true;
|
|
2872
|
+
}
|
|
2873
|
+
return false;
|
|
2874
|
+
}
|
|
2875
|
+
passesUrlGate(err) {
|
|
2876
|
+
const topFrame = err.frames.find((f) => f.filename) ?? null;
|
|
2877
|
+
const url = topFrame?.filename ?? err.filename ?? "";
|
|
2878
|
+
if (!url) return true;
|
|
2879
|
+
for (const pat of this.opts.config.denyUrls) {
|
|
2880
|
+
if (typeof pat === "string" && url.includes(pat)) return false;
|
|
2881
|
+
if (pat instanceof RegExp && pat.test(url)) return false;
|
|
2882
|
+
}
|
|
2883
|
+
if (this.opts.config.allowUrls.length > 0) {
|
|
2884
|
+
for (const pat of this.opts.config.allowUrls) {
|
|
2885
|
+
if (typeof pat === "string" && url.includes(pat)) return true;
|
|
2886
|
+
if (pat instanceof RegExp && pat.test(url)) return true;
|
|
2887
|
+
}
|
|
2888
|
+
return false;
|
|
2889
|
+
}
|
|
2890
|
+
return true;
|
|
2891
|
+
}
|
|
2892
|
+
passesSample(err) {
|
|
2893
|
+
if (this.opts.config.sampleRate >= 1) return true;
|
|
2894
|
+
if (this.opts.config.sampleRate <= 0) return false;
|
|
2895
|
+
const hashByte = parseInt(err.fingerprint.slice(0, 2), 16);
|
|
2896
|
+
return hashByte / 255 < this.opts.config.sampleRate;
|
|
2897
|
+
}
|
|
2898
|
+
passesRateLimit(err) {
|
|
2899
|
+
const windowMs = 6e4;
|
|
2900
|
+
const now = Date.now();
|
|
2901
|
+
const max = this.opts.config.maxPerFingerprintPerMinute;
|
|
2902
|
+
const arr = this.fingerprintWindow.get(err.fingerprint) ?? [];
|
|
2903
|
+
const fresh = arr.filter((t) => now - t < windowMs);
|
|
2904
|
+
if (fresh.length >= max) {
|
|
2905
|
+
this.fingerprintWindow.set(err.fingerprint, fresh);
|
|
2906
|
+
return false;
|
|
2907
|
+
}
|
|
2908
|
+
fresh.push(now);
|
|
2909
|
+
this.fingerprintWindow.set(err.fingerprint, fresh);
|
|
2910
|
+
return true;
|
|
2911
|
+
}
|
|
2912
|
+
};
|
|
2913
|
+
function coerceErrorPayload(v) {
|
|
2914
|
+
if (v === null) return { message: "(thrown: null)", errorType: null, extras: null };
|
|
2915
|
+
if (v === void 0) return { message: "(thrown: undefined)", errorType: null, extras: null };
|
|
2916
|
+
if (typeof v === "string") {
|
|
2917
|
+
return { message: v, errorType: null, extras: null };
|
|
2918
|
+
}
|
|
2919
|
+
if (typeof v === "number" || typeof v === "boolean" || typeof v === "bigint") {
|
|
2920
|
+
return { message: String(v), errorType: typeof v, extras: null };
|
|
2921
|
+
}
|
|
2922
|
+
if (typeof v === "symbol") {
|
|
2923
|
+
return { message: v.toString(), errorType: "symbol", extras: null };
|
|
2924
|
+
}
|
|
2925
|
+
if (typeof v === "function") {
|
|
2926
|
+
return { message: `(thrown function: ${v.name || "anonymous"})`, errorType: "function", extras: null };
|
|
2927
|
+
}
|
|
2928
|
+
if (v instanceof Error) {
|
|
2929
|
+
const errorType = v.name || v.constructor?.name || "Error";
|
|
2930
|
+
const message = typeof v.message === "string" && v.message.length > 0 ? v.message : safeToString(v) || errorType;
|
|
2931
|
+
const extras = {};
|
|
2932
|
+
const causeChain = collectCauseChain(v);
|
|
2933
|
+
if (causeChain.length > 0) extras.cause = causeChain;
|
|
2934
|
+
for (const key of ["code", "status", "statusCode", "errno", "response", "data", "detail", "details"]) {
|
|
2935
|
+
const val = v[key];
|
|
2936
|
+
if (val !== void 0 && typeof val !== "function") {
|
|
2937
|
+
extras[key] = safeClone(val);
|
|
2938
|
+
}
|
|
2939
|
+
}
|
|
2940
|
+
for (const key of Object.keys(v)) {
|
|
2941
|
+
if (key === "message" || key === "stack" || key === "name" || key === "cause") continue;
|
|
2942
|
+
if (key in extras) continue;
|
|
2943
|
+
const val = v[key];
|
|
2944
|
+
if (typeof val === "function") continue;
|
|
2945
|
+
extras[key] = safeClone(val);
|
|
2946
|
+
}
|
|
2947
|
+
return {
|
|
2948
|
+
message,
|
|
2949
|
+
errorType,
|
|
2950
|
+
extras: Object.keys(extras).length > 0 ? extras : null
|
|
2951
|
+
};
|
|
2952
|
+
}
|
|
2953
|
+
if (typeof Response !== "undefined" && v instanceof Response) {
|
|
2954
|
+
return {
|
|
2955
|
+
message: `HTTP ${v.status} ${v.statusText || ""}${v.url ? ` ${v.url}` : ""}`.trim(),
|
|
2956
|
+
errorType: "Response",
|
|
2957
|
+
extras: { status: v.status, statusText: v.statusText, url: v.url, type: v.type }
|
|
2958
|
+
};
|
|
2959
|
+
}
|
|
2960
|
+
if (typeof v === "object") {
|
|
2961
|
+
const obj = v;
|
|
2962
|
+
const ctorName = obj.constructor && typeof obj.constructor === "function" && obj.constructor.name || null;
|
|
2963
|
+
const ownMessage = typeof obj.message === "string" && obj.message ? obj.message : null;
|
|
2964
|
+
const ownName = typeof obj.name === "string" && obj.name ? obj.name : null;
|
|
2965
|
+
let jsonForm = null;
|
|
2966
|
+
try {
|
|
2967
|
+
const serialised = JSON.stringify(obj);
|
|
2968
|
+
jsonForm = serialised === "{}" ? null : serialised;
|
|
2969
|
+
} catch {
|
|
2970
|
+
jsonForm = null;
|
|
2971
|
+
}
|
|
2972
|
+
const fallbackString = safeToString(obj);
|
|
2973
|
+
const message = ownMessage ?? jsonForm ?? (fallbackString && fallbackString !== "[object Object]" ? fallbackString : null) ?? (ctorName ? `(thrown ${ctorName} with no message)` : "(thrown object with no message)");
|
|
2974
|
+
const errorType = ownName ?? ctorName ?? null;
|
|
2975
|
+
const extras = {};
|
|
2976
|
+
let count = 0;
|
|
2977
|
+
for (const key of Object.keys(obj)) {
|
|
2978
|
+
if (count >= 20) break;
|
|
2979
|
+
if (key === "message" || key === "name") continue;
|
|
2980
|
+
const val = obj[key];
|
|
2981
|
+
if (typeof val === "function") continue;
|
|
2982
|
+
extras[key] = safeClone(val);
|
|
2983
|
+
count++;
|
|
2984
|
+
}
|
|
2985
|
+
return {
|
|
2986
|
+
message,
|
|
2987
|
+
errorType,
|
|
2988
|
+
extras: Object.keys(extras).length > 0 ? extras : null
|
|
2989
|
+
};
|
|
2990
|
+
}
|
|
2991
|
+
return { message: safeToString(v) || "(unstringifiable thrown value)", errorType: null, extras: null };
|
|
2992
|
+
}
|
|
2993
|
+
function collectCauseChain(err) {
|
|
2994
|
+
const out = [];
|
|
2995
|
+
let cur = err.cause;
|
|
2996
|
+
let depth = 0;
|
|
2997
|
+
while (cur != null && depth < 5) {
|
|
2998
|
+
if (cur instanceof Error) {
|
|
2999
|
+
out.push({ name: cur.name || "Error", message: cur.message || "" });
|
|
3000
|
+
cur = cur.cause;
|
|
3001
|
+
} else {
|
|
3002
|
+
out.push({ name: "non-Error", message: safeToString(cur) });
|
|
3003
|
+
cur = null;
|
|
3004
|
+
}
|
|
3005
|
+
depth++;
|
|
3006
|
+
}
|
|
3007
|
+
return out;
|
|
3008
|
+
}
|
|
3009
|
+
function safeToString(v) {
|
|
3010
|
+
try {
|
|
3011
|
+
const s = Object.prototype.toString.call(v);
|
|
3012
|
+
if (s !== "[object Object]") return s;
|
|
3013
|
+
const own = v?.toString;
|
|
3014
|
+
if (typeof own === "function" && own !== Object.prototype.toString) {
|
|
3015
|
+
const r = own.call(v);
|
|
3016
|
+
if (typeof r === "string") return r;
|
|
3017
|
+
}
|
|
3018
|
+
return s;
|
|
3019
|
+
} catch {
|
|
3020
|
+
return "(throwing toString)";
|
|
3021
|
+
}
|
|
3022
|
+
}
|
|
3023
|
+
function safeClone(v) {
|
|
3024
|
+
if (v == null) return v;
|
|
3025
|
+
const t = typeof v;
|
|
3026
|
+
if (t === "string" || t === "number" || t === "boolean") return v;
|
|
3027
|
+
if (t === "bigint") return String(v);
|
|
3028
|
+
try {
|
|
3029
|
+
const s = JSON.stringify(v);
|
|
3030
|
+
return s === void 0 ? safeToString(v) : JSON.parse(s);
|
|
3031
|
+
} catch {
|
|
3032
|
+
return safeToString(v);
|
|
3033
|
+
}
|
|
3034
|
+
}
|
|
3035
|
+
function safeStringify2(v) {
|
|
3036
|
+
return coerceErrorPayload(v).message;
|
|
3037
|
+
}
|
|
3038
|
+
function extractSelfHostname(baseUrl) {
|
|
3039
|
+
if (!baseUrl || typeof baseUrl !== "string") return null;
|
|
3040
|
+
try {
|
|
3041
|
+
return new URL(baseUrl).hostname.toLowerCase();
|
|
3042
|
+
} catch {
|
|
3043
|
+
return null;
|
|
3044
|
+
}
|
|
3045
|
+
}
|
|
3046
|
+
function isSelfRequest(requestUrl, selfHostname) {
|
|
3047
|
+
if (!selfHostname || !requestUrl) return false;
|
|
3048
|
+
try {
|
|
3049
|
+
return new URL(requestUrl).hostname.toLowerCase() === selfHostname;
|
|
3050
|
+
} catch {
|
|
3051
|
+
return false;
|
|
3052
|
+
}
|
|
3053
|
+
}
|
|
3054
|
+
|
|
3055
|
+
// src/crossdeck.ts
|
|
3056
|
+
var CrossdeckClient = class {
|
|
3057
|
+
constructor() {
|
|
3058
|
+
this.state = null;
|
|
3059
|
+
}
|
|
3060
|
+
/**
|
|
3061
|
+
* Boot the SDK. Idempotent — calling init twice with the same options
|
|
3062
|
+
* is a no-op; calling with different options replaces the previous
|
|
3063
|
+
* configuration.
|
|
3064
|
+
*
|
|
3065
|
+
* NorthStar §11.1: signature is `Crossdeck.init({ appId, publicKey,
|
|
3066
|
+
* environment })`. The trio is validated up-front so a typo'd key or a
|
|
3067
|
+
* mismatched env fails fast at boot rather than at first event-flush.
|
|
3068
|
+
*/
|
|
3069
|
+
init(options) {
|
|
3070
|
+
if (this.state) {
|
|
3071
|
+
try {
|
|
3072
|
+
this.state.uninstallUnloadFlush?.();
|
|
3073
|
+
} catch {
|
|
3074
|
+
}
|
|
3075
|
+
try {
|
|
3076
|
+
this.state.autoTracker?.uninstall();
|
|
3077
|
+
} catch {
|
|
3078
|
+
}
|
|
3079
|
+
try {
|
|
3080
|
+
this.state.webVitals?.uninstall();
|
|
3081
|
+
} catch {
|
|
3082
|
+
}
|
|
3083
|
+
try {
|
|
3084
|
+
this.state.errors?.uninstall();
|
|
3085
|
+
} catch {
|
|
3086
|
+
}
|
|
3087
|
+
try {
|
|
3088
|
+
void this.state.events.flush({ keepalive: true });
|
|
3089
|
+
} catch {
|
|
3090
|
+
}
|
|
3091
|
+
}
|
|
3092
|
+
if (!options.publicKey || !options.publicKey.startsWith("cd_pub_")) {
|
|
3093
|
+
throw new CrossdeckError({
|
|
3094
|
+
type: "configuration_error",
|
|
3095
|
+
code: "invalid_public_key",
|
|
3096
|
+
message: "Crossdeck.init requires a publishable key starting with cd_pub_."
|
|
3097
|
+
});
|
|
3098
|
+
}
|
|
3099
|
+
if (!options.appId) {
|
|
3100
|
+
throw new CrossdeckError({
|
|
3101
|
+
type: "configuration_error",
|
|
3102
|
+
code: "missing_app_id",
|
|
3103
|
+
message: "Crossdeck.init requires an appId. Find yours in the Crossdeck dashboard."
|
|
3104
|
+
});
|
|
3105
|
+
}
|
|
3106
|
+
if (options.environment !== "production" && options.environment !== "sandbox") {
|
|
3107
|
+
throw new CrossdeckError({
|
|
3108
|
+
type: "configuration_error",
|
|
3109
|
+
code: "invalid_environment",
|
|
3110
|
+
message: 'Crossdeck.init requires environment: "production" | "sandbox".'
|
|
3111
|
+
});
|
|
3112
|
+
}
|
|
3113
|
+
const keyEnv = inferEnvFromKey(options.publicKey);
|
|
3114
|
+
if (keyEnv && keyEnv !== options.environment) {
|
|
3115
|
+
throw new CrossdeckError({
|
|
3116
|
+
type: "configuration_error",
|
|
3117
|
+
code: "environment_mismatch",
|
|
3118
|
+
message: `Crossdeck.init: environment "${options.environment}" disagrees with key prefix (${keyEnv}). Reconcile the publishable key with the environment declaration.`
|
|
3119
|
+
});
|
|
3120
|
+
}
|
|
3121
|
+
const localDevMode = isLocalHostname();
|
|
3122
|
+
const storage = options.storage ?? detectDefaultStorage();
|
|
3123
|
+
const persistIdentity = options.persistIdentity ?? true;
|
|
3124
|
+
const autoTrack = resolveAutoTrack(options.autoTrack);
|
|
3125
|
+
const opts = {
|
|
3126
|
+
appId: options.appId,
|
|
3127
|
+
publicKey: options.publicKey,
|
|
3128
|
+
environment: options.environment,
|
|
3129
|
+
baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,
|
|
3130
|
+
persistIdentity,
|
|
3131
|
+
storagePrefix: options.storagePrefix ?? "crossdeck:",
|
|
3132
|
+
autoHeartbeat: options.autoHeartbeat ?? true,
|
|
3133
|
+
eventFlushBatchSize: options.eventFlushBatchSize ?? 20,
|
|
3134
|
+
// 1500ms idle window. Short enough that an event queued on page
|
|
3135
|
+
// load still flushes if the user leaves quickly (the keepalive
|
|
3136
|
+
// pagehide handler picks up anything that doesn't); long enough
|
|
3137
|
+
// that bursts of clicks coalesce into one network round-trip.
|
|
3138
|
+
// v1.4.0 Phase 3.3 — flush interval default parity. Pre-
|
|
3139
|
+
// v1.4.0: Web/Node 1500ms, RN/Swift/Android 5000ms. All
|
|
3140
|
+
// converged on 2000ms (the Stripe-adjacent industry norm)
|
|
3141
|
+
// so cross-platform funnels show events landing at the
|
|
3142
|
+
// same cadence on every SDK. Per-instance override stays.
|
|
3143
|
+
eventFlushIntervalMs: options.eventFlushIntervalMs ?? 2e3,
|
|
3144
|
+
sdkVersion: options.sdkVersion ?? SDK_VERSION,
|
|
3145
|
+
autoTrack,
|
|
3146
|
+
appVersion: options.appVersion ?? null
|
|
3147
|
+
};
|
|
3148
|
+
const debug = new ConsoleDebugLogger();
|
|
3149
|
+
debug.enabled = options.debug === true;
|
|
3150
|
+
const http = new HttpClient({
|
|
3151
|
+
publicKey: opts.publicKey,
|
|
3152
|
+
baseUrl: opts.baseUrl,
|
|
3153
|
+
sdkVersion: opts.sdkVersion,
|
|
3154
|
+
// Localhost auto-route: HttpClient short-circuits every request
|
|
3155
|
+
// to a successful no-op response when localDevMode is set.
|
|
3156
|
+
// SDK methods continue to work locally; nothing reaches the
|
|
3157
|
+
// server.
|
|
3158
|
+
localDevMode
|
|
3159
|
+
});
|
|
3160
|
+
if (localDevMode) {
|
|
3161
|
+
console.log(
|
|
3162
|
+
"[crossdeck] Localhost detected \u2014 running in dev mode (no network calls). Set publicKey: 'cd_pub_test_\u2026' and deploy to a real domain to test against the Crossdeck Sandbox."
|
|
3163
|
+
);
|
|
3164
|
+
}
|
|
3165
|
+
const effectiveStorage = persistIdentity ? storage : new MemoryStorage();
|
|
3166
|
+
const useCookieRedundancy = persistIdentity && !options.storage && // honour caller's adapter choice
|
|
3167
|
+
typeof globalThis.document !== "undefined";
|
|
3168
|
+
const cookieStore = useCookieRedundancy ? new CookieStorage() : void 0;
|
|
3169
|
+
const identity = new IdentityStore(effectiveStorage, opts.storagePrefix, cookieStore);
|
|
3170
|
+
const entitlements = new EntitlementCache(
|
|
3171
|
+
effectiveStorage,
|
|
3172
|
+
opts.storagePrefix + "entitlements"
|
|
3173
|
+
);
|
|
3174
|
+
const persistentEvents = persistIdentity ? new PersistentEventStore({ storage: effectiveStorage, prefix: opts.storagePrefix }) : null;
|
|
3175
|
+
if (persistentEvents) {
|
|
3176
|
+
debug.emit(
|
|
3177
|
+
"sdk.queue_restored",
|
|
3178
|
+
"Restored persisted event queue from a prior session."
|
|
3179
|
+
);
|
|
3180
|
+
}
|
|
3181
|
+
const events = new EventQueue({
|
|
3182
|
+
http,
|
|
3183
|
+
batchSize: opts.eventFlushBatchSize,
|
|
3184
|
+
intervalMs: opts.eventFlushIntervalMs,
|
|
3185
|
+
envelope: () => ({
|
|
3186
|
+
appId: opts.appId,
|
|
3187
|
+
environment: opts.environment,
|
|
3188
|
+
sdk: { name: SDK_NAME, version: opts.sdkVersion }
|
|
3189
|
+
}),
|
|
3190
|
+
persistentStore: persistentEvents ?? void 0,
|
|
3191
|
+
onFirstFlushSuccess: () => {
|
|
3192
|
+
debug.emit(
|
|
3193
|
+
"sdk.first_event_sent",
|
|
3194
|
+
"First telemetry event received. View it in Live Events.",
|
|
3195
|
+
{ appId: opts.appId, environment: opts.environment }
|
|
3196
|
+
);
|
|
3197
|
+
},
|
|
3198
|
+
onRetryScheduled: (info) => {
|
|
3199
|
+
debug.emit(
|
|
3200
|
+
"sdk.flush_retry_scheduled",
|
|
3201
|
+
`Event flush failed (${info.lastError}). Retrying in ${info.delayMs}ms (attempt ${info.consecutiveFailures}).`,
|
|
3202
|
+
{ ...info }
|
|
3203
|
+
);
|
|
3204
|
+
},
|
|
3205
|
+
onPermanentFailure: (info) => {
|
|
3206
|
+
const headline = `[crossdeck] Event batch DROPPED (status ${info.status}): ${info.lastError}. ${info.droppedCount} event(s) lost \u2014 check your publishable key + app config.`;
|
|
3207
|
+
console.error(headline);
|
|
3208
|
+
debug.emit(
|
|
3209
|
+
"sdk.flush_permanent_failure",
|
|
3210
|
+
headline,
|
|
3211
|
+
{ ...info }
|
|
3212
|
+
);
|
|
3213
|
+
}
|
|
3214
|
+
});
|
|
3215
|
+
const deviceInfo = autoTrack.deviceInfo ? collectDeviceInfo({ appVersion: opts.appVersion ?? void 0 }) : opts.appVersion ? { appVersion: opts.appVersion } : {};
|
|
3216
|
+
const superProps = new SuperPropertyStore(
|
|
3217
|
+
persistIdentity ? effectiveStorage : new MemoryStorage(),
|
|
3218
|
+
opts.storagePrefix
|
|
3219
|
+
);
|
|
3220
|
+
const consent = new ConsentManager({ respectDnt: options.respectDnt === true });
|
|
3221
|
+
if (consent.isDntDenied) {
|
|
3222
|
+
debug.emit(
|
|
3223
|
+
"sdk.consent_dnt_applied",
|
|
3224
|
+
"Do Not Track detected \u2014 all tracking dimensions denied at init."
|
|
3225
|
+
);
|
|
3226
|
+
}
|
|
3227
|
+
const breadcrumbs = new BreadcrumbBuffer(50);
|
|
3228
|
+
this.state = {
|
|
3229
|
+
http,
|
|
3230
|
+
identity,
|
|
3231
|
+
entitlements,
|
|
3232
|
+
events,
|
|
3233
|
+
autoTracker: null,
|
|
3234
|
+
webVitals: null,
|
|
3235
|
+
errors: null,
|
|
3236
|
+
breadcrumbs,
|
|
3237
|
+
errorContext: {},
|
|
3238
|
+
errorTags: {},
|
|
3239
|
+
errorBeforeSend: null,
|
|
3240
|
+
superProps,
|
|
3241
|
+
consent,
|
|
3242
|
+
scrubPii: options.scrubPii !== false,
|
|
3243
|
+
deviceInfo,
|
|
3244
|
+
options: opts,
|
|
3245
|
+
debug,
|
|
3246
|
+
developerUserId: null,
|
|
3247
|
+
uninstallUnloadFlush: null,
|
|
3248
|
+
lastServerTime: null,
|
|
3249
|
+
lastClientTime: null
|
|
3250
|
+
};
|
|
3251
|
+
debug.emit("sdk.configured", `Crossdeck connected to ${opts.appId} in ${opts.environment} mode.`, {
|
|
3252
|
+
appId: opts.appId,
|
|
3253
|
+
environment: opts.environment,
|
|
3254
|
+
sdkVersion: opts.sdkVersion
|
|
3255
|
+
});
|
|
3256
|
+
if (autoTrack.sessions || autoTrack.pageViews) {
|
|
3257
|
+
const tracker = new AutoTracker(
|
|
3258
|
+
autoTrack,
|
|
3259
|
+
(name, properties) => this.track(name, properties)
|
|
3260
|
+
);
|
|
3261
|
+
this.state.autoTracker = tracker;
|
|
3262
|
+
tracker.install();
|
|
3263
|
+
}
|
|
3264
|
+
if (autoTrack.webVitals) {
|
|
3265
|
+
const vitals = new WebVitalsTracker(
|
|
3266
|
+
{ enabled: true },
|
|
3267
|
+
(name, properties) => this.track(name, properties)
|
|
3268
|
+
);
|
|
3269
|
+
this.state.webVitals = vitals;
|
|
3270
|
+
vitals.install();
|
|
3271
|
+
}
|
|
3272
|
+
if (autoTrack.errors) {
|
|
3273
|
+
const tracker = new ErrorTracker({
|
|
3274
|
+
config: { ...DEFAULT_ERROR_CAPTURE, enabled: true },
|
|
3275
|
+
breadcrumbs,
|
|
3276
|
+
report: (err) => this.reportError(err),
|
|
3277
|
+
getContext: () => ({ ...this.state.errorContext }),
|
|
3278
|
+
getTags: () => ({ ...this.state.errorTags }),
|
|
3279
|
+
// GETTER, not a captured value — `setErrorBeforeSend()` mutates
|
|
3280
|
+
// `state.errorBeforeSend` after init() and the tracker MUST
|
|
3281
|
+
// pick up the new hook on the next error. The pre-fix shape
|
|
3282
|
+
// (`beforeSend: this.state!.errorBeforeSend`) snapshotted
|
|
3283
|
+
// `null` at construction and made the customer's PII scrubber
|
|
3284
|
+
// silently inert. See error-capture.ts:ErrorTrackerOptions.beforeSend.
|
|
3285
|
+
beforeSend: () => this.state.errorBeforeSend,
|
|
3286
|
+
isConsented: () => this.state.consent.errors,
|
|
3287
|
+
// Derived from the configured baseUrl at init() time. Used by
|
|
3288
|
+
// the fetch / XHR wrappers to skip captureHttp on Crossdeck's
|
|
3289
|
+
// own requests — pre-fix the skip was hardcoded to
|
|
3290
|
+
// `api.cross-deck.com` and broke for customers on staging /
|
|
3291
|
+
// regional / self-hosted base URLs (recursive capture loop).
|
|
3292
|
+
selfHostname: extractSelfHostname(opts.baseUrl)
|
|
3293
|
+
});
|
|
3294
|
+
this.state.errors = tracker;
|
|
3295
|
+
tracker.install();
|
|
3296
|
+
}
|
|
3297
|
+
this.state.uninstallUnloadFlush = installUnloadFlush(() => {
|
|
3298
|
+
void this.flush({ keepalive: true }).catch(() => void 0);
|
|
3299
|
+
});
|
|
3300
|
+
if (opts.autoHeartbeat && !localDevMode) {
|
|
3301
|
+
void this.heartbeat().catch(() => void 0);
|
|
3302
|
+
}
|
|
3303
|
+
}
|
|
3304
|
+
/**
|
|
3305
|
+
* @deprecated Use `init()` instead. NorthStar §4 standardised the
|
|
3306
|
+
* lifecycle method name across SDKs as `init` (formerly `start` /
|
|
3307
|
+
* `configure`). `start` will be removed in a future major version.
|
|
3308
|
+
*/
|
|
3309
|
+
start(options) {
|
|
3310
|
+
if (typeof console !== "undefined") {
|
|
3311
|
+
console.warn(
|
|
3312
|
+
"[crossdeck] Crossdeck.start() is deprecated \u2014 use Crossdeck.init() instead. The signature is the same."
|
|
3313
|
+
);
|
|
3314
|
+
}
|
|
3315
|
+
this.init(options);
|
|
3316
|
+
}
|
|
3317
|
+
/**
|
|
3318
|
+
* Link the anonymous device to a developer-supplied user ID. Cache
|
|
3319
|
+
* the resolved Crossdeck customer for follow-up calls.
|
|
3320
|
+
*
|
|
3321
|
+
* v0.9.0+ accepts an optional `traits` bag — profile data (name,
|
|
3322
|
+
* plan, signupDate, role) persisted on the Crossdeck customer record
|
|
3323
|
+
* and queryable from dashboards. Traits are sanitised through the
|
|
3324
|
+
* same validator that gates `track()` properties, so a `{ avatar:
|
|
3325
|
+
* <File>, onSave: () => {} }` payload can't corrupt the alias call.
|
|
3326
|
+
*
|
|
3327
|
+
* Crossdeck.identify("user_847", {
|
|
3328
|
+
* email: "wes@pinet.co.za",
|
|
3329
|
+
* traits: { name: "Wes", plan: "pro", signedUpAt: "2026-05-11" },
|
|
3330
|
+
* });
|
|
3331
|
+
*/
|
|
3332
|
+
async identify(userId, options) {
|
|
3333
|
+
const s = this.requireStarted();
|
|
3334
|
+
if (!userId) {
|
|
3335
|
+
throw new CrossdeckError({
|
|
3336
|
+
type: "invalid_request_error",
|
|
3337
|
+
code: "missing_user_id",
|
|
3338
|
+
message: "identify(userId) requires a non-empty userId."
|
|
3339
|
+
});
|
|
3340
|
+
}
|
|
3341
|
+
if (!s.consent.analytics) {
|
|
3342
|
+
s.debug.emit(
|
|
3343
|
+
"sdk.consent_denied",
|
|
3344
|
+
`identify() skipped \u2014 consent denied for analytics.`
|
|
3345
|
+
);
|
|
3346
|
+
return {
|
|
3347
|
+
object: "alias_result",
|
|
3348
|
+
crossdeckCustomerId: s.identity.crossdeckCustomerId ?? "",
|
|
3349
|
+
linked: [],
|
|
3350
|
+
mergePending: false,
|
|
3351
|
+
env: s.options.environment
|
|
3352
|
+
};
|
|
3353
|
+
}
|
|
3354
|
+
const traitsValidation = options?.traits !== void 0 ? validateEventProperties(options.traits) : null;
|
|
3355
|
+
const traits = traitsValidation && Object.keys(traitsValidation.properties).length > 0 ? traitsValidation.properties : void 0;
|
|
3356
|
+
if (s.debug.enabled && traitsValidation && traitsValidation.warnings.length > 0) {
|
|
3357
|
+
for (const w of traitsValidation.warnings) {
|
|
3358
|
+
s.debug.emit(
|
|
3359
|
+
"sdk.property_coerced",
|
|
3360
|
+
`identify() traits key ${JSON.stringify(w.key)} was ${w.kind.replace(/_/g, " ")} during validation.`,
|
|
3361
|
+
{ key: w.key, kind: w.kind }
|
|
3362
|
+
);
|
|
3363
|
+
}
|
|
3364
|
+
}
|
|
3365
|
+
const body = {
|
|
3366
|
+
userId,
|
|
3367
|
+
anonymousId: s.identity.anonymousId
|
|
3368
|
+
};
|
|
3369
|
+
if (options?.email) body.email = options.email;
|
|
3370
|
+
if (traits) body.traits = traits;
|
|
3371
|
+
s.entitlements.setUserKey(userId);
|
|
3372
|
+
const result = await s.http.request("POST", "/identity/alias", {
|
|
3373
|
+
body
|
|
3374
|
+
});
|
|
3375
|
+
s.identity.setCrossdeckCustomerId(result.crossdeckCustomerId);
|
|
3376
|
+
s.developerUserId = userId;
|
|
3377
|
+
return result;
|
|
3378
|
+
}
|
|
3379
|
+
/**
|
|
3380
|
+
* Register super-properties — Mixpanel pattern. Once set, every
|
|
3381
|
+
* subsequent event of THIS SDK instance carries these keys on its
|
|
3382
|
+
* properties bag automatically.
|
|
3383
|
+
*
|
|
3384
|
+
* Crossdeck.register({ plan: "pro", releaseChannel: "beta" });
|
|
3385
|
+
* Crossdeck.track("paywall_shown"); // includes plan + releaseChannel
|
|
3386
|
+
*
|
|
3387
|
+
* Values that are `null` are deleted (the explicit "stop tracking
|
|
3388
|
+
* this key" idiom). Returns the resulting bag.
|
|
3389
|
+
*
|
|
3390
|
+
* Sanitised through `validateEventProperties` so a `{ avatar: File }`
|
|
3391
|
+
* payload can't poison the queue at flush time.
|
|
3392
|
+
*/
|
|
3393
|
+
register(properties) {
|
|
3394
|
+
const s = this.requireStarted();
|
|
3395
|
+
const validation = validateEventProperties(properties);
|
|
3396
|
+
return s.superProps.register(validation.properties);
|
|
3397
|
+
}
|
|
3398
|
+
/** Remove a single super-property key. Idempotent. */
|
|
3399
|
+
unregister(key) {
|
|
3400
|
+
const s = this.requireStarted();
|
|
3401
|
+
s.superProps.unregister(key);
|
|
3402
|
+
}
|
|
3403
|
+
/** Snapshot of the current super-property bag. */
|
|
3404
|
+
getSuperProperties() {
|
|
3405
|
+
if (!this.state) return {};
|
|
3406
|
+
return this.state.superProps.getSuperProperties();
|
|
3407
|
+
}
|
|
3408
|
+
/**
|
|
3409
|
+
* Associate the current user with a group (org, team, account, etc.).
|
|
3410
|
+
* Mixpanel / Segment "Group Analytics" pattern.
|
|
3411
|
+
*
|
|
3412
|
+
* Crossdeck.group("org", "acme_inc");
|
|
3413
|
+
* Crossdeck.group("team", "design", { headcount: 12 });
|
|
3414
|
+
*
|
|
3415
|
+
* Once set, every subsequent event carries `$groups.<type>: id` on
|
|
3416
|
+
* its properties bag, enabling B2B dashboards ("how is Acme using
|
|
3417
|
+
* the product"). Pass `id: null` to clear a group membership.
|
|
3418
|
+
*/
|
|
3419
|
+
group(type, id, traits) {
|
|
3420
|
+
const s = this.requireStarted();
|
|
3421
|
+
if (!type) {
|
|
3422
|
+
throw new CrossdeckError({
|
|
3423
|
+
type: "invalid_request_error",
|
|
3424
|
+
code: "missing_group_type",
|
|
3425
|
+
message: "group(type, id) requires a non-empty type."
|
|
3426
|
+
});
|
|
3427
|
+
}
|
|
3428
|
+
const sanitisedTraits = traits ? validateEventProperties(traits).properties : void 0;
|
|
3429
|
+
s.superProps.setGroup(type, id, sanitisedTraits);
|
|
3430
|
+
}
|
|
3431
|
+
/** Snapshot of the current groups map keyed by type. */
|
|
3432
|
+
getGroups() {
|
|
3433
|
+
if (!this.state) return {};
|
|
3434
|
+
return this.state.superProps.getGroups();
|
|
3435
|
+
}
|
|
3436
|
+
/**
|
|
3437
|
+
* Update consent state. Three independent dimensions:
|
|
3438
|
+
*
|
|
3439
|
+
* analytics — track() + identify() + auto-emissions
|
|
3440
|
+
* marketing — paid-traffic click IDs + referrer URL on events
|
|
3441
|
+
* errors — Web Vitals + (future) error reporting
|
|
3442
|
+
*
|
|
3443
|
+
* Each defaults to `true` (granted). Pass partial state — only the
|
|
3444
|
+
* keys you provide are changed.
|
|
3445
|
+
*
|
|
3446
|
+
* Crossdeck.consent({ analytics: false });
|
|
3447
|
+
* Crossdeck.consent({ marketing: true, errors: true });
|
|
3448
|
+
*
|
|
3449
|
+
* DNT-derived denies cannot be flipped back on; if the browser said
|
|
3450
|
+
* "don't track" we don't track even if the developer code disagrees.
|
|
3451
|
+
*/
|
|
3452
|
+
consent(state) {
|
|
3453
|
+
const s = this.requireStarted();
|
|
3454
|
+
const next = s.consent.set(state);
|
|
3455
|
+
s.debug.emit("sdk.consent_changed", "Consent state updated.", { ...next });
|
|
3456
|
+
return next;
|
|
3457
|
+
}
|
|
3458
|
+
/** Snapshot of the current consent state. */
|
|
3459
|
+
consentStatus() {
|
|
3460
|
+
if (!this.state) {
|
|
3461
|
+
return { analytics: true, marketing: true, errors: true };
|
|
3462
|
+
}
|
|
3463
|
+
return this.state.consent.get();
|
|
3464
|
+
}
|
|
3465
|
+
// ============================================================
|
|
3466
|
+
// Error capture surface (v1.0.0+)
|
|
3467
|
+
// ============================================================
|
|
3468
|
+
/**
|
|
3469
|
+
* Manually capture an error from a try/catch block.
|
|
3470
|
+
*
|
|
3471
|
+
* try { …risky… } catch (err) {
|
|
3472
|
+
* Crossdeck.captureError(err, { context: { plan: "pro" } });
|
|
3473
|
+
* }
|
|
3474
|
+
*
|
|
3475
|
+
* The error is shipped through the same event queue as analytics
|
|
3476
|
+
* (durable, retried, rate-limited per fingerprint). Sends are gated
|
|
3477
|
+
* by `consent.errors`. Returns silently — never throws, even if the
|
|
3478
|
+
* SDK isn't initialised yet.
|
|
3479
|
+
*/
|
|
3480
|
+
captureError(error, options) {
|
|
3481
|
+
if (!this.state?.errors) return;
|
|
3482
|
+
this.state.errors.captureError(error, options);
|
|
3483
|
+
}
|
|
3484
|
+
/**
|
|
3485
|
+
* Capture a non-error event you want to surface as an issue
|
|
3486
|
+
* ("deprecated path hit", "we entered the slow code path"). Sentry
|
|
3487
|
+
* captureMessage pattern. Returns silently if not initialised.
|
|
3488
|
+
*/
|
|
3489
|
+
captureMessage(message, level = "info") {
|
|
3490
|
+
if (!this.state?.errors) return;
|
|
3491
|
+
this.state.errors.captureMessage(message, level);
|
|
3492
|
+
}
|
|
3493
|
+
/**
|
|
3494
|
+
* Attach a tag to every subsequent error report. Tags are key/value
|
|
3495
|
+
* strings (Sentry pattern): `setTag("flow", "checkout")` → every
|
|
3496
|
+
* error from this point on carries `tags.flow === "checkout"`.
|
|
3497
|
+
*/
|
|
3498
|
+
setTag(key, value) {
|
|
3499
|
+
if (!this.state) return;
|
|
3500
|
+
this.state.errorTags[key] = value;
|
|
3501
|
+
}
|
|
3502
|
+
/** Bulk-set tags. Merges with existing tags. */
|
|
3503
|
+
setTags(tags) {
|
|
3504
|
+
if (!this.state) return;
|
|
3505
|
+
Object.assign(this.state.errorTags, tags);
|
|
3506
|
+
}
|
|
3507
|
+
/**
|
|
3508
|
+
* Attach a structured context blob to every subsequent error report.
|
|
3509
|
+
* Unlike tags (flat key/value), context is a named bag of arbitrary
|
|
3510
|
+
* data: `setContext("cart", { items: 3, total: 42.99 })`.
|
|
3511
|
+
*/
|
|
3512
|
+
setContext(name, data) {
|
|
3513
|
+
if (!this.state) return;
|
|
3514
|
+
this.state.errorContext[name] = data;
|
|
3515
|
+
}
|
|
3516
|
+
/**
|
|
3517
|
+
* Add a custom breadcrumb to the rolling buffer. Useful for marking
|
|
3518
|
+
* domain-meaningful moments ("user opened paywall") that aren't
|
|
3519
|
+
* already auto-captured. The buffer caps at 50 entries; old ones
|
|
3520
|
+
* evict.
|
|
3521
|
+
*/
|
|
3522
|
+
addBreadcrumb(crumb) {
|
|
3523
|
+
if (!this.state) return;
|
|
3524
|
+
this.state.breadcrumbs.add(crumb);
|
|
3525
|
+
}
|
|
3526
|
+
/**
|
|
3527
|
+
* Install a pre-send hook for errors. Return null to drop, or a
|
|
3528
|
+
* modified CapturedError to scrub / rewrite. Sentry's beforeSend
|
|
3529
|
+
* pattern — the only way to redact app-specific PII (auth tokens
|
|
3530
|
+
* in URLs, etc.) before the report leaves the browser.
|
|
3531
|
+
*/
|
|
3532
|
+
setErrorBeforeSend(hook) {
|
|
3533
|
+
if (!this.state) return;
|
|
3534
|
+
this.state.errorBeforeSend = hook;
|
|
3535
|
+
}
|
|
3536
|
+
/**
|
|
3537
|
+
* Internal: turn a CapturedError into a Crossdeck event and enqueue
|
|
3538
|
+
* it. Goes through the same queue / persistence / consent / scrub
|
|
3539
|
+
* pipeline as analytics events.
|
|
3540
|
+
*/
|
|
3541
|
+
reportError(err) {
|
|
3542
|
+
const properties = {
|
|
3543
|
+
// Identifiers
|
|
3544
|
+
fingerprint: err.fingerprint,
|
|
3545
|
+
level: err.level,
|
|
3546
|
+
// Error shape
|
|
3547
|
+
errorType: err.errorType,
|
|
3548
|
+
message: err.message,
|
|
3549
|
+
// Stack
|
|
3550
|
+
stack: err.rawStack ?? void 0,
|
|
3551
|
+
frames: err.frames,
|
|
3552
|
+
filename: err.filename ?? void 0,
|
|
3553
|
+
lineno: err.lineno ?? void 0,
|
|
3554
|
+
colno: err.colno ?? void 0,
|
|
3555
|
+
// Context
|
|
3556
|
+
tags: err.tags,
|
|
3557
|
+
context: err.context,
|
|
3558
|
+
breadcrumbs: err.breadcrumbs,
|
|
3559
|
+
// HTTP (only when applicable)
|
|
3560
|
+
http: err.http
|
|
3561
|
+
};
|
|
3562
|
+
for (const k of Object.keys(properties)) {
|
|
3563
|
+
if (properties[k] === void 0) delete properties[k];
|
|
3564
|
+
}
|
|
3565
|
+
this.track(err.kind, properties);
|
|
3566
|
+
}
|
|
3567
|
+
/**
|
|
3568
|
+
* GDPR/CCPA "right to be forgotten" — calls the backend's
|
|
3569
|
+
* /v1/identity/forget endpoint to schedule a server-side deletion of
|
|
3570
|
+
* the customer's events and profile, then wipes all local state
|
|
3571
|
+
* (identity, entitlements, queue, super-props, persistent stores).
|
|
3572
|
+
*
|
|
3573
|
+
* Idempotent. Safe to call when no identity has been established
|
|
3574
|
+
* (it just wipes the empty local state).
|
|
3575
|
+
*
|
|
3576
|
+
* After forget() resolves, the SDK is in the same shape as if the
|
|
3577
|
+
* developer had called `Crossdeck.reset()` — a fresh anonymousId is
|
|
3578
|
+
* minted and the next session is a brand new identity-graph entry.
|
|
3579
|
+
*/
|
|
3580
|
+
async forget() {
|
|
3581
|
+
const s = this.requireStarted();
|
|
3582
|
+
const identityQuery = this.identityQueryParams();
|
|
3583
|
+
try {
|
|
3584
|
+
await s.http.request("POST", "/identity/forget", {
|
|
3585
|
+
body: {
|
|
3586
|
+
// Send every identity hint we hold; the server resolves the
|
|
3587
|
+
// canonical customer record and queues deletion. Missing
|
|
3588
|
+
// endpoint (older backend) gracefully degrades — local state
|
|
3589
|
+
// still wipes via the reset() call below.
|
|
3590
|
+
...identityQuery
|
|
3591
|
+
}
|
|
3592
|
+
});
|
|
3593
|
+
} catch (err) {
|
|
3594
|
+
s.debug.emit(
|
|
3595
|
+
"sdk.consent_denied",
|
|
3596
|
+
`forget() server call failed (${err instanceof Error ? err.message : String(err)}). Local state wiped anyway.`
|
|
3597
|
+
);
|
|
3598
|
+
}
|
|
3599
|
+
this.reset();
|
|
3600
|
+
}
|
|
3601
|
+
/**
|
|
3602
|
+
* Read the current customer's active entitlements from the server.
|
|
3603
|
+
* Updates the local cache so subsequent isEntitled() calls answer
|
|
3604
|
+
* synchronously.
|
|
3605
|
+
*/
|
|
3606
|
+
async getEntitlements() {
|
|
3607
|
+
const s = this.requireStarted();
|
|
3608
|
+
const query = this.identityQueryParams();
|
|
3609
|
+
let result;
|
|
3610
|
+
try {
|
|
3611
|
+
result = await s.http.request(
|
|
3612
|
+
"GET",
|
|
3613
|
+
"/entitlements",
|
|
3614
|
+
{ query }
|
|
3615
|
+
);
|
|
3616
|
+
} catch (err) {
|
|
3617
|
+
s.entitlements.markRefreshFailed();
|
|
3618
|
+
throw err;
|
|
3619
|
+
}
|
|
3620
|
+
if (result.crossdeckCustomerId) {
|
|
3621
|
+
s.identity.setCrossdeckCustomerId(result.crossdeckCustomerId);
|
|
3622
|
+
}
|
|
3623
|
+
s.entitlements.setFromList(result.data);
|
|
3624
|
+
return result.data;
|
|
3625
|
+
}
|
|
3626
|
+
/**
|
|
3627
|
+
* Synchronous read from the durable local cache — answers from
|
|
3628
|
+
* last-known-good. The cache hydrates from device storage on boot and
|
|
3629
|
+
* survives a Crossdeck outage, so a returning paying customer reads
|
|
3630
|
+
* true even before the session's first network round-trip. Returns
|
|
3631
|
+
* false only for a genuinely new install that has never completed a
|
|
3632
|
+
* getEntitlements(), or for an entitlement past its own validUntil.
|
|
3633
|
+
*/
|
|
3634
|
+
isEntitled(key) {
|
|
3635
|
+
const s = this.requireStarted();
|
|
3636
|
+
return s.entitlements.isEntitled(key);
|
|
3637
|
+
}
|
|
3638
|
+
/** Snapshot of the local entitlement cache. */
|
|
3639
|
+
listEntitlements() {
|
|
3640
|
+
const s = this.requireStarted();
|
|
3641
|
+
return s.entitlements.list();
|
|
3642
|
+
}
|
|
3643
|
+
/**
|
|
3644
|
+
* Subscribe to entitlement-cache changes. Returns an unsubscribe fn.
|
|
3645
|
+
*
|
|
3646
|
+
* The listener is invoked AFTER the cache mutates — once after a
|
|
3647
|
+
* successful `getEntitlements()` warms it, again after `syncPurchases()`
|
|
3648
|
+
* delivers fresh entitlements, and once on `reset()` to fire the
|
|
3649
|
+
* empty-cache state for logout flows.
|
|
3650
|
+
*
|
|
3651
|
+
* It is NOT invoked synchronously on subscribe. Callers that need
|
|
3652
|
+
* the current state should read it via `isEntitled()` / `listEntitlements()`
|
|
3653
|
+
* inline; the listener fires only on FUTURE changes.
|
|
3654
|
+
*
|
|
3655
|
+
* This is the foundation of the `useEntitlement` React hook in
|
|
3656
|
+
* `@cross-deck/web/react` — without it, React (or SwiftUI / Compose
|
|
3657
|
+
* / Vue) would have no way to re-render when entitlements arrive
|
|
3658
|
+
* asynchronously after init. The naive pattern of calling
|
|
3659
|
+
* `Crossdeck.isEntitled("pro")` directly inside a render path
|
|
3660
|
+
* shows the empty-cache result forever; binding the result to
|
|
3661
|
+
* component state via `onEntitlementsChange` is the correct
|
|
3662
|
+
* pattern.
|
|
3663
|
+
*
|
|
3664
|
+
* Idempotent unsubscribe — calling the returned function multiple
|
|
3665
|
+
* times is safe.
|
|
3666
|
+
*
|
|
3667
|
+
* Listener errors are swallowed (a buggy listener can't crash the
|
|
3668
|
+
* SDK or other listeners).
|
|
3669
|
+
*/
|
|
3670
|
+
onEntitlementsChange(listener) {
|
|
3671
|
+
const s = this.requireStarted();
|
|
3672
|
+
return s.entitlements.subscribe(listener);
|
|
3673
|
+
}
|
|
3674
|
+
/**
|
|
3675
|
+
* Queue a telemetry event. Returns immediately — the network round-
|
|
3676
|
+
* trip happens in the background. To flush before the page unloads,
|
|
3677
|
+
* call flush().
|
|
3678
|
+
*/
|
|
3679
|
+
/**
|
|
3680
|
+
* Emit `crossdeck.contract_failed` with the canonical property
|
|
3681
|
+
* shape (`contract_id`, `sdk_version`, `sdk_platform`,
|
|
3682
|
+
* `failure_reason`, `run_context`, `run_id`). Goes through the
|
|
3683
|
+
* standard track() pipeline — same consent gate, same queue,
|
|
3684
|
+
* same ingest, no new endpoint.
|
|
3685
|
+
*
|
|
3686
|
+
* Wire the call from a test hook, dogfood failure path, or
|
|
3687
|
+
* customer contract-verification harness; see
|
|
3688
|
+
* `contracts/README.md` for the per-test-framework hook recipes.
|
|
3689
|
+
*/
|
|
3690
|
+
reportContractFailure(input) {
|
|
3691
|
+
const props = {
|
|
3692
|
+
contract_id: input.contractId,
|
|
3693
|
+
sdk_version: SDK_VERSION,
|
|
3694
|
+
sdk_platform: "web",
|
|
3695
|
+
failure_reason: input.failureReason,
|
|
3696
|
+
run_context: input.runContext,
|
|
3697
|
+
run_id: input.runId
|
|
3698
|
+
};
|
|
3699
|
+
if (input.testRef) {
|
|
3700
|
+
props.test_file = input.testRef.file;
|
|
3701
|
+
props.test_name = input.testRef.name;
|
|
3702
|
+
}
|
|
3703
|
+
if (input.extra) {
|
|
3704
|
+
for (const [k, v] of Object.entries(input.extra)) {
|
|
3705
|
+
if (props[k] === void 0) props[k] = v;
|
|
3706
|
+
}
|
|
3707
|
+
}
|
|
3708
|
+
this.track("crossdeck.contract_failed", props);
|
|
3709
|
+
}
|
|
3710
|
+
track(name, properties) {
|
|
3711
|
+
const s = this.requireStarted();
|
|
3712
|
+
if (!name) {
|
|
3713
|
+
throw new CrossdeckError({
|
|
3714
|
+
type: "invalid_request_error",
|
|
3715
|
+
code: "missing_event_name",
|
|
3716
|
+
message: "track(name) requires a non-empty name."
|
|
3717
|
+
});
|
|
3718
|
+
}
|
|
3719
|
+
const isError = name.startsWith("error.");
|
|
3720
|
+
const isWebVital = name.startsWith("webvitals.");
|
|
3721
|
+
const consentGateOk = isError || isWebVital ? s.consent.errors : s.consent.analytics;
|
|
3722
|
+
if (!consentGateOk) {
|
|
3723
|
+
if (s.debug.enabled) {
|
|
3724
|
+
s.debug.emit(
|
|
3725
|
+
"sdk.consent_denied",
|
|
3726
|
+
`Dropped event "${name}" \u2014 consent denied for ${isWebVital ? "errors" : "analytics"}.`
|
|
3727
|
+
);
|
|
3728
|
+
}
|
|
3729
|
+
return;
|
|
3730
|
+
}
|
|
3731
|
+
if (s.debug.enabled && properties) {
|
|
3732
|
+
const flagged = findSensitivePropertyKeys(properties);
|
|
3733
|
+
if (flagged.length > 0) {
|
|
3734
|
+
s.debug.emit(
|
|
3735
|
+
"sdk.sensitive_property_warning",
|
|
3736
|
+
`Event "${name}" has potentially sensitive property names: ${flagged.join(", ")}. Crossdeck is privacy-first \u2014 avoid sending PII unless intentional.`,
|
|
3737
|
+
{ eventName: name, flagged }
|
|
3738
|
+
);
|
|
3739
|
+
}
|
|
3740
|
+
}
|
|
3741
|
+
if (s.debug.enabled && !s.developerUserId && !s.identity.crossdeckCustomerId) {
|
|
3742
|
+
s.debug.emit(
|
|
3743
|
+
"sdk.no_identity",
|
|
3744
|
+
"Using anonymous user until identify(userId) is called."
|
|
3745
|
+
);
|
|
3746
|
+
}
|
|
3747
|
+
const validation = validateEventProperties(properties);
|
|
3748
|
+
if (s.debug.enabled && validation.warnings.length > 0) {
|
|
3749
|
+
for (const w of validation.warnings) {
|
|
3750
|
+
s.debug.emit(
|
|
3751
|
+
"sdk.property_coerced",
|
|
3752
|
+
`Event "${name}" property ${JSON.stringify(w.key)} was ${w.kind.replace(/_/g, " ")} during validation.`,
|
|
3753
|
+
{ eventName: name, key: w.key, kind: w.kind }
|
|
3754
|
+
);
|
|
3755
|
+
}
|
|
3756
|
+
}
|
|
3757
|
+
const enriched = { ...s.deviceInfo };
|
|
3758
|
+
const sessionId = s.autoTracker?.currentSessionId;
|
|
3759
|
+
if (sessionId) enriched.sessionId = sessionId;
|
|
3760
|
+
const pageviewId = s.autoTracker?.currentPageviewId;
|
|
3761
|
+
if (pageviewId) enriched.pageviewId = pageviewId;
|
|
3762
|
+
const acquisition = s.autoTracker?.currentAcquisition;
|
|
3763
|
+
if (acquisition) {
|
|
3764
|
+
if (acquisition.utm_source) enriched.utm_source = acquisition.utm_source;
|
|
3765
|
+
if (acquisition.utm_medium) enriched.utm_medium = acquisition.utm_medium;
|
|
3766
|
+
if (acquisition.utm_campaign) enriched.utm_campaign = acquisition.utm_campaign;
|
|
3767
|
+
if (acquisition.utm_content) enriched.utm_content = acquisition.utm_content;
|
|
3768
|
+
if (acquisition.utm_term) enriched.utm_term = acquisition.utm_term;
|
|
3769
|
+
if (acquisition.referrer && s.consent.marketing) enriched.referrer = acquisition.referrer;
|
|
3770
|
+
if (s.consent.marketing) {
|
|
3771
|
+
if (acquisition.gclid) enriched.gclid = acquisition.gclid;
|
|
3772
|
+
if (acquisition.fbclid) enriched.fbclid = acquisition.fbclid;
|
|
3773
|
+
if (acquisition.msclkid) enriched.msclkid = acquisition.msclkid;
|
|
3774
|
+
if (acquisition.ttclid) enriched.ttclid = acquisition.ttclid;
|
|
3775
|
+
if (acquisition.li_fat_id) enriched.li_fat_id = acquisition.li_fat_id;
|
|
3776
|
+
if (acquisition.twclid) enriched.twclid = acquisition.twclid;
|
|
3777
|
+
}
|
|
3778
|
+
}
|
|
3779
|
+
const supers = s.superProps.getSuperProperties();
|
|
3780
|
+
for (const k of Object.keys(supers)) {
|
|
3781
|
+
if (!(k in enriched)) enriched[k] = supers[k];
|
|
3782
|
+
}
|
|
3783
|
+
const groupIds = s.superProps.getGroupIds();
|
|
3784
|
+
if (Object.keys(groupIds).length > 0) {
|
|
3785
|
+
enriched.$groups = groupIds;
|
|
3786
|
+
}
|
|
3787
|
+
Object.assign(enriched, validation.properties);
|
|
3788
|
+
const finalProperties = s.scrubPii ? scrubPiiFromProperties(enriched) : enriched;
|
|
3789
|
+
const event = {
|
|
3790
|
+
eventId: this.mintEventId(),
|
|
3791
|
+
name,
|
|
3792
|
+
timestamp: Date.now(),
|
|
3793
|
+
properties: finalProperties
|
|
3794
|
+
};
|
|
3795
|
+
Object.assign(event, this.identityHintForEvent());
|
|
3796
|
+
s.events.enqueue(event);
|
|
3797
|
+
if (!isError && !isWebVital) {
|
|
3798
|
+
const category = name.startsWith("page.") ? "navigation" : name.startsWith("element.") || name === "session.started" ? "ui.click" : "custom";
|
|
3799
|
+
s.breadcrumbs.add({
|
|
3800
|
+
timestamp: event.timestamp,
|
|
3801
|
+
category,
|
|
3802
|
+
message: name,
|
|
3803
|
+
// Strip the device-info / session bloat from the breadcrumb
|
|
3804
|
+
// payload — only the caller-supplied properties belong in
|
|
3805
|
+
// the user-readable trail.
|
|
3806
|
+
data: properties ? { ...properties } : void 0
|
|
3807
|
+
});
|
|
3808
|
+
}
|
|
3809
|
+
}
|
|
3810
|
+
/**
|
|
3811
|
+
* Force-flush queued events. Useful to call from page-unload handlers.
|
|
3812
|
+
*
|
|
3813
|
+
* Pass `{ keepalive: true }` from terminal handlers (pagehide /
|
|
3814
|
+
* visibilitychange→hidden / beforeunload). The browser keeps the
|
|
3815
|
+
* request alive after the page tears down, so the final batch
|
|
3816
|
+
* actually lands instead of being cancelled with the unload.
|
|
3817
|
+
*
|
|
3818
|
+
* NorthStar §4: standard method name across all Crossdeck SDKs.
|
|
3819
|
+
*/
|
|
3820
|
+
async flush(options = {}) {
|
|
3821
|
+
const s = this.requireStarted();
|
|
3822
|
+
await s.events.flush(options);
|
|
3823
|
+
}
|
|
3824
|
+
/** @deprecated Use `flush()` instead. NorthStar §4 standardised the name. */
|
|
3825
|
+
async flushEvents() {
|
|
3826
|
+
return this.flush();
|
|
3827
|
+
}
|
|
3828
|
+
/**
|
|
3829
|
+
* Forward purchase evidence to the backend for verification + entitlement
|
|
3830
|
+
* projection. NorthStar §4 + §13 canonical name.
|
|
3831
|
+
*
|
|
3832
|
+
* Today the web SDK only supports Apple StoreKit 2 forwarding (web apps
|
|
3833
|
+
* that sit alongside an iOS app). Stripe doesn't need this method —
|
|
3834
|
+
* Stripe webhooks deliver evidence server-side without a client round-trip.
|
|
3835
|
+
*/
|
|
3836
|
+
async syncPurchases(input) {
|
|
3837
|
+
const s = this.requireStarted();
|
|
3838
|
+
if (!input.signedTransactionInfo) {
|
|
3839
|
+
throw new CrossdeckError({
|
|
3840
|
+
type: "invalid_request_error",
|
|
3841
|
+
code: "missing_signed_transaction_info",
|
|
3842
|
+
message: "syncPurchases requires a signedTransactionInfo string from StoreKit 2."
|
|
3843
|
+
});
|
|
3844
|
+
}
|
|
3845
|
+
const rail = input.rail ?? "apple";
|
|
3846
|
+
const body = { ...input, rail };
|
|
3847
|
+
const idempotencyKey = deriveIdempotencyKeyForPurchase(body);
|
|
3848
|
+
const result = await s.http.request("POST", "/purchases/sync", {
|
|
3849
|
+
body,
|
|
3850
|
+
idempotencyKey
|
|
3851
|
+
});
|
|
3852
|
+
s.identity.setCrossdeckCustomerId(result.crossdeckCustomerId);
|
|
3853
|
+
s.entitlements.setFromList(result.entitlements);
|
|
3854
|
+
try {
|
|
3855
|
+
const sourceProductId = result.entitlements[0]?.source.productId;
|
|
3856
|
+
const sourceSubscriptionId = result.entitlements[0]?.source.subscriptionId;
|
|
3857
|
+
const props = { rail };
|
|
3858
|
+
if (sourceProductId) props.productId = sourceProductId;
|
|
3859
|
+
if (sourceSubscriptionId) props.subscriptionId = sourceSubscriptionId;
|
|
3860
|
+
if (result.idempotent_replay) props.idempotent_replay = true;
|
|
3861
|
+
this.track("purchase.completed", props);
|
|
3862
|
+
} catch {
|
|
3863
|
+
}
|
|
3864
|
+
s.debug.emit(
|
|
3865
|
+
"sdk.purchase_evidence_sent",
|
|
3866
|
+
"StoreKit transaction forwarded. Waiting for backend verification.",
|
|
3867
|
+
{ rail: input.rail ?? "apple" }
|
|
3868
|
+
);
|
|
3869
|
+
return result;
|
|
3870
|
+
}
|
|
3871
|
+
/** @deprecated Use `syncPurchases()` instead. NorthStar §4 standardised the name. */
|
|
3872
|
+
async purchaseApple(input) {
|
|
3873
|
+
return this.syncPurchases({ rail: "apple", ...input });
|
|
3874
|
+
}
|
|
3875
|
+
/**
|
|
3876
|
+
* Toggle verbose diagnostic logging — NorthStar §16. When enabled, the
|
|
3877
|
+
* SDK emits a fixed vocabulary of debug signals to console.info that the
|
|
3878
|
+
* dashboard's onboarding checklist can also surface as live events.
|
|
3879
|
+
*/
|
|
3880
|
+
setDebugMode(enabled) {
|
|
3881
|
+
const s = this.requireStarted();
|
|
3882
|
+
s.debug.enabled = enabled;
|
|
3883
|
+
if (enabled) {
|
|
3884
|
+
s.debug.emit(
|
|
3885
|
+
"sdk.configured",
|
|
3886
|
+
`Debug mode enabled for ${s.options.appId} in ${s.options.environment} mode.`,
|
|
3887
|
+
{ appId: s.options.appId, environment: s.options.environment }
|
|
3888
|
+
);
|
|
3889
|
+
}
|
|
3890
|
+
}
|
|
3891
|
+
/**
|
|
3892
|
+
* Send the boot heartbeat. Called automatically by start() unless
|
|
3893
|
+
* autoHeartbeat:false. Safe to call manually as a "we're still here" ping.
|
|
3894
|
+
*/
|
|
3895
|
+
async heartbeat() {
|
|
3896
|
+
const s = this.requireStarted();
|
|
3897
|
+
const result = await s.http.request("GET", "/sdk/heartbeat");
|
|
3898
|
+
if (typeof result?.serverTime === "number" && Number.isFinite(result.serverTime)) {
|
|
3899
|
+
s.lastServerTime = result.serverTime;
|
|
3900
|
+
s.lastClientTime = Date.now();
|
|
3901
|
+
}
|
|
3902
|
+
return result;
|
|
3903
|
+
}
|
|
3904
|
+
/**
|
|
3905
|
+
* Wipe persisted identity + entitlement cache. Use on logout. The
|
|
3906
|
+
* next pre-login session generates a fresh anonymousId and starts a
|
|
3907
|
+
* new identity-graph entry.
|
|
3908
|
+
*/
|
|
3909
|
+
reset() {
|
|
3910
|
+
if (!this.state) return;
|
|
3911
|
+
if (this.state.developerUserId) {
|
|
3912
|
+
try {
|
|
3913
|
+
this.track("user.signed_out", { auto: true });
|
|
3914
|
+
} catch {
|
|
3915
|
+
}
|
|
3916
|
+
}
|
|
3917
|
+
this.state.autoTracker?.uninstall();
|
|
3918
|
+
this.state.identity.reset();
|
|
3919
|
+
this.state.entitlements.clearAll();
|
|
3920
|
+
this.state.events.reset();
|
|
3921
|
+
this.state.superProps.clear();
|
|
3922
|
+
this.state.breadcrumbs.clear();
|
|
3923
|
+
this.state.errorContext = {};
|
|
3924
|
+
this.state.errorTags = {};
|
|
3925
|
+
this.state.developerUserId = null;
|
|
3926
|
+
this.state.lastServerTime = null;
|
|
3927
|
+
this.state.lastClientTime = null;
|
|
3928
|
+
if (this.state.autoTracker) {
|
|
3929
|
+
const tracker = new AutoTracker(
|
|
3930
|
+
this.state.options.autoTrack,
|
|
3931
|
+
(name, props) => this.track(name, props)
|
|
3932
|
+
);
|
|
3933
|
+
this.state.autoTracker = tracker;
|
|
3934
|
+
tracker.install();
|
|
3935
|
+
}
|
|
3936
|
+
}
|
|
3937
|
+
/**
|
|
3938
|
+
* Diagnostic: current state + queue stats. Useful for the dashboard's
|
|
3939
|
+
* heartbeat row and debugging in dev.
|
|
3940
|
+
*
|
|
3941
|
+
* Returns a stable shape regardless of whether start() has been called —
|
|
3942
|
+
* callers don't need to narrow on `started` to access `events` or
|
|
3943
|
+
* `entitlements`. Pre-start values are sensible empties.
|
|
3944
|
+
*/
|
|
3945
|
+
diagnostics() {
|
|
3946
|
+
if (!this.state) {
|
|
3947
|
+
return {
|
|
3948
|
+
started: false,
|
|
3949
|
+
anonymousId: null,
|
|
3950
|
+
crossdeckCustomerId: null,
|
|
3951
|
+
developerUserId: null,
|
|
3952
|
+
sdkVersion: null,
|
|
3953
|
+
baseUrl: null,
|
|
3954
|
+
clock: { lastServerTime: null, lastClientTime: null, skewMs: null },
|
|
3955
|
+
entitlements: { count: 0, lastUpdated: 0, stale: false, listenerErrors: 0 },
|
|
3956
|
+
events: {
|
|
3957
|
+
buffered: 0,
|
|
3958
|
+
dropped: 0,
|
|
3959
|
+
inFlight: 0,
|
|
3960
|
+
lastFlushAt: 0,
|
|
3961
|
+
lastError: null,
|
|
3962
|
+
consecutiveFailures: 0,
|
|
3963
|
+
nextRetryAt: null
|
|
3964
|
+
}
|
|
3965
|
+
};
|
|
3966
|
+
}
|
|
3967
|
+
const s = this.state;
|
|
3968
|
+
const skewMs = s.lastServerTime !== null && s.lastClientTime !== null ? s.lastClientTime - s.lastServerTime : null;
|
|
3969
|
+
return {
|
|
3970
|
+
started: true,
|
|
3971
|
+
anonymousId: s.identity.anonymousId,
|
|
3972
|
+
crossdeckCustomerId: s.identity.crossdeckCustomerId,
|
|
3973
|
+
developerUserId: s.developerUserId,
|
|
3974
|
+
sdkVersion: s.options.sdkVersion,
|
|
3975
|
+
baseUrl: s.options.baseUrl,
|
|
3976
|
+
clock: {
|
|
3977
|
+
lastServerTime: s.lastServerTime,
|
|
3978
|
+
lastClientTime: s.lastClientTime,
|
|
3979
|
+
skewMs
|
|
3980
|
+
},
|
|
3981
|
+
entitlements: {
|
|
3982
|
+
count: s.entitlements.list().length,
|
|
3983
|
+
lastUpdated: s.entitlements.freshness,
|
|
3984
|
+
stale: s.entitlements.isStale,
|
|
3985
|
+
listenerErrors: s.entitlements.listenerErrors
|
|
3986
|
+
},
|
|
3987
|
+
events: s.events.getStats()
|
|
3988
|
+
};
|
|
3989
|
+
}
|
|
3990
|
+
// ---------- private helpers ----------
|
|
3991
|
+
requireStarted() {
|
|
3992
|
+
if (!this.state) {
|
|
3993
|
+
throw new CrossdeckError({
|
|
3994
|
+
type: "configuration_error",
|
|
3995
|
+
code: "not_initialized",
|
|
3996
|
+
message: "Call Crossdeck.init({ appId, publicKey, environment }) before any other method."
|
|
3997
|
+
});
|
|
3998
|
+
}
|
|
3999
|
+
return this.state;
|
|
4000
|
+
}
|
|
4001
|
+
/**
|
|
4002
|
+
* Build the identity query for /v1/entitlements. Priority:
|
|
4003
|
+
* crossdeckCustomerId > developerUserId > anonymousId
|
|
4004
|
+
* — matches the resolveCrossdeckCustomerId precedence on the server.
|
|
4005
|
+
*/
|
|
4006
|
+
identityQueryParams() {
|
|
4007
|
+
const s = this.requireStarted();
|
|
4008
|
+
if (s.identity.crossdeckCustomerId) {
|
|
4009
|
+
return { customerId: s.identity.crossdeckCustomerId };
|
|
4010
|
+
}
|
|
4011
|
+
if (s.developerUserId) return { userId: s.developerUserId };
|
|
4012
|
+
return { anonymousId: s.identity.anonymousId };
|
|
4013
|
+
}
|
|
4014
|
+
/**
|
|
4015
|
+
* Embed every known identity axis on the event. Earlier this returned
|
|
4016
|
+
* just the highest-priority hint (cdcust → developerUserId → anonymousId)
|
|
4017
|
+
* to keep payloads small, but that leaked into analytics: once a user
|
|
4018
|
+
* was logged in, every subsequent page.viewed shipped without
|
|
4019
|
+
* anonymousId, and `uniqExact(anonymous_id)` on the warehouse side
|
|
4020
|
+
* counted 0 visitors for the entire authenticated app.
|
|
4021
|
+
*
|
|
4022
|
+
* Bank-grade rule: the server is the single source of truth on
|
|
4023
|
+
* dedup. Send everything we know; let CH count by whichever axis
|
|
4024
|
+
* matches the question. Each field is at most 32 bytes — sending
|
|
4025
|
+
* three on every event costs ~80 bytes per request, which is
|
|
4026
|
+
* trivial compared to the analytics correctness it buys.
|
|
4027
|
+
*/
|
|
4028
|
+
identityHintForEvent() {
|
|
4029
|
+
const s = this.requireStarted();
|
|
4030
|
+
const hint = {
|
|
4031
|
+
anonymousId: s.identity.anonymousId
|
|
4032
|
+
};
|
|
4033
|
+
if (s.developerUserId) hint.developerUserId = s.developerUserId;
|
|
4034
|
+
if (s.identity.crossdeckCustomerId) {
|
|
4035
|
+
hint.crossdeckCustomerId = s.identity.crossdeckCustomerId;
|
|
4036
|
+
}
|
|
4037
|
+
return hint;
|
|
4038
|
+
}
|
|
4039
|
+
mintEventId() {
|
|
4040
|
+
const ts = Date.now().toString(36);
|
|
4041
|
+
return `evt_${ts}${randomChars(8)}`;
|
|
4042
|
+
}
|
|
4043
|
+
};
|
|
4044
|
+
var Crossdeck = new CrossdeckClient();
|
|
4045
|
+
function inferEnvFromKey(publicKey) {
|
|
4046
|
+
if (publicKey.startsWith("cd_pub_test_")) return "sandbox";
|
|
4047
|
+
if (publicKey.startsWith("cd_pub_live_")) return "production";
|
|
4048
|
+
return null;
|
|
4049
|
+
}
|
|
4050
|
+
function isLocalHostname() {
|
|
4051
|
+
const w = globalThis.window;
|
|
4052
|
+
if (w?.__CROSSDECK_FORCE_LIVE__ === true) return false;
|
|
4053
|
+
const hostname = w?.location?.hostname;
|
|
4054
|
+
if (!hostname) return false;
|
|
4055
|
+
if (hostname === "localhost" || hostname === "127.0.0.1") return true;
|
|
4056
|
+
if (hostname === "0.0.0.0") return true;
|
|
4057
|
+
if (hostname === "::1" || hostname === "[::1]") return true;
|
|
4058
|
+
if (/^\[?fe80::/i.test(hostname)) return true;
|
|
4059
|
+
if (hostname.endsWith(".local")) return true;
|
|
4060
|
+
if (/^10\./.test(hostname)) return true;
|
|
4061
|
+
if (/^192\.168\./.test(hostname)) return true;
|
|
4062
|
+
if (/^172\.(1[6-9]|2\d|3[0-1])\./.test(hostname)) return true;
|
|
4063
|
+
return false;
|
|
4064
|
+
}
|
|
4065
|
+
function resolveAutoTrack(input) {
|
|
4066
|
+
if (input === false) {
|
|
4067
|
+
return {
|
|
4068
|
+
sessions: false,
|
|
4069
|
+
pageViews: false,
|
|
4070
|
+
deviceInfo: false,
|
|
4071
|
+
clicks: false,
|
|
4072
|
+
webVitals: false,
|
|
4073
|
+
errors: false
|
|
4074
|
+
};
|
|
4075
|
+
}
|
|
4076
|
+
if (input === void 0 || input === true) {
|
|
4077
|
+
return { ...DEFAULT_AUTO_TRACK };
|
|
4078
|
+
}
|
|
4079
|
+
return {
|
|
4080
|
+
sessions: input.sessions ?? DEFAULT_AUTO_TRACK.sessions,
|
|
4081
|
+
pageViews: input.pageViews ?? DEFAULT_AUTO_TRACK.pageViews,
|
|
4082
|
+
deviceInfo: input.deviceInfo ?? DEFAULT_AUTO_TRACK.deviceInfo,
|
|
4083
|
+
clicks: input.clicks ?? DEFAULT_AUTO_TRACK.clicks,
|
|
4084
|
+
webVitals: input.webVitals ?? DEFAULT_AUTO_TRACK.webVitals,
|
|
4085
|
+
errors: input.errors ?? DEFAULT_AUTO_TRACK.errors
|
|
4086
|
+
};
|
|
4087
|
+
}
|
|
4088
|
+
function installUnloadFlush(onUnload) {
|
|
4089
|
+
const w = globalThis.window;
|
|
4090
|
+
const doc = globalThis.document;
|
|
4091
|
+
if (!w || !doc) return () => void 0;
|
|
4092
|
+
const onVisChange = () => {
|
|
4093
|
+
if (doc.visibilityState === "hidden") onUnload();
|
|
4094
|
+
};
|
|
4095
|
+
const onTerminal = () => onUnload();
|
|
4096
|
+
doc.addEventListener("visibilitychange", onVisChange);
|
|
4097
|
+
w.addEventListener("pagehide", onTerminal);
|
|
4098
|
+
w.addEventListener("beforeunload", onTerminal);
|
|
4099
|
+
return () => {
|
|
4100
|
+
doc.removeEventListener("visibilitychange", onVisChange);
|
|
4101
|
+
w.removeEventListener("pagehide", onTerminal);
|
|
4102
|
+
w.removeEventListener("beforeunload", onTerminal);
|
|
4103
|
+
};
|
|
4104
|
+
}
|
|
4105
|
+
|
|
4106
|
+
// src/react.ts
|
|
4107
|
+
var _moduleInitDone = false;
|
|
4108
|
+
function CrossdeckProvider(props) {
|
|
4109
|
+
const { userId, children, ...initOptions } = props;
|
|
4110
|
+
const lastUserIdRef = useRef(void 0);
|
|
4111
|
+
useEffect(() => {
|
|
4112
|
+
if (_moduleInitDone) return;
|
|
4113
|
+
try {
|
|
4114
|
+
Crossdeck.init(initOptions);
|
|
4115
|
+
_moduleInitDone = true;
|
|
4116
|
+
} catch (err) {
|
|
4117
|
+
if (typeof console !== "undefined") {
|
|
4118
|
+
console.error("[CrossdeckProvider] init failed:", err);
|
|
4119
|
+
}
|
|
4120
|
+
}
|
|
4121
|
+
}, []);
|
|
4122
|
+
useEffect(() => {
|
|
4123
|
+
if (!_moduleInitDone) return;
|
|
4124
|
+
if (lastUserIdRef.current === userId) return;
|
|
4125
|
+
lastUserIdRef.current = userId;
|
|
4126
|
+
try {
|
|
4127
|
+
if (userId) {
|
|
4128
|
+
void Crossdeck.identify(userId);
|
|
4129
|
+
} else {
|
|
4130
|
+
Crossdeck.reset();
|
|
4131
|
+
}
|
|
4132
|
+
} catch (err) {
|
|
4133
|
+
if (typeof console !== "undefined") {
|
|
4134
|
+
console.error("[CrossdeckProvider] identity sync failed:", err);
|
|
4135
|
+
}
|
|
4136
|
+
}
|
|
4137
|
+
}, [userId]);
|
|
4138
|
+
return children;
|
|
4139
|
+
}
|
|
4140
|
+
function useEntitlement(key) {
|
|
4141
|
+
const [isEntitled, setIsEntitled] = useState(() => safeIsEntitled(key));
|
|
4142
|
+
useEffect(() => {
|
|
4143
|
+
setIsEntitled(safeIsEntitled(key));
|
|
4144
|
+
let unsubscribe = null;
|
|
4145
|
+
try {
|
|
4146
|
+
unsubscribe = Crossdeck.onEntitlementsChange(() => {
|
|
4147
|
+
setIsEntitled(safeIsEntitled(key));
|
|
4148
|
+
});
|
|
4149
|
+
} catch {
|
|
4150
|
+
}
|
|
4151
|
+
return () => {
|
|
4152
|
+
if (unsubscribe) unsubscribe();
|
|
4153
|
+
};
|
|
4154
|
+
}, [key]);
|
|
4155
|
+
return isEntitled;
|
|
4156
|
+
}
|
|
4157
|
+
function useEntitlements() {
|
|
4158
|
+
const [keys, setKeys] = useState(() => safeListKeys());
|
|
4159
|
+
useEffect(() => {
|
|
4160
|
+
setKeys(safeListKeys());
|
|
4161
|
+
let unsubscribe = null;
|
|
4162
|
+
try {
|
|
4163
|
+
unsubscribe = Crossdeck.onEntitlementsChange((entitlements) => {
|
|
4164
|
+
setKeys(entitlements.filter((e) => e.isActive).map((e) => e.key));
|
|
4165
|
+
});
|
|
4166
|
+
} catch {
|
|
4167
|
+
}
|
|
4168
|
+
return () => {
|
|
4169
|
+
if (unsubscribe) unsubscribe();
|
|
4170
|
+
};
|
|
4171
|
+
}, []);
|
|
4172
|
+
return keys;
|
|
4173
|
+
}
|
|
4174
|
+
function safeIsEntitled(key) {
|
|
4175
|
+
try {
|
|
4176
|
+
return Crossdeck.isEntitled(key);
|
|
4177
|
+
} catch {
|
|
4178
|
+
return false;
|
|
4179
|
+
}
|
|
4180
|
+
}
|
|
4181
|
+
function safeListKeys() {
|
|
4182
|
+
try {
|
|
4183
|
+
return Crossdeck.listEntitlements().filter((e) => e.isActive).map((e) => e.key);
|
|
4184
|
+
} catch {
|
|
4185
|
+
return [];
|
|
4186
|
+
}
|
|
4187
|
+
}
|
|
4188
|
+
export {
|
|
4189
|
+
CrossdeckProvider,
|
|
4190
|
+
useEntitlement,
|
|
4191
|
+
useEntitlements
|
|
4192
|
+
};
|
|
4193
|
+
//# sourceMappingURL=react.mjs.map
|