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