@usesequential/browser 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1950 @@
1
+ /* @usesequential/browser 1.0.1: the Sequential browser SDK. MIT. https://www.usesequential.com/docs/browser-npm
2
+ * `boot` below is sequential.js, the file the script tag loads, unchanged. */
3
+ 'use strict';
4
+ var boot = (function (injectedTag) {
5
+ 'use strict';
6
+
7
+ function noop() {}
8
+
9
+ function logError(message) {
10
+ try {
11
+ if (window.console && window.console.error) window.console.error('[sequential] ' + message);
12
+ } catch (e) {}
13
+ }
14
+
15
+ function logWarn(message) {
16
+ try {
17
+ if (window.console && window.console.warn) window.console.warn('[sequential] ' + message);
18
+ } catch (e) {}
19
+ }
20
+
21
+ // sequential.core.ts ORIGIN_REFUSED_WARNING, word for word.
22
+ var ORIGIN_REFUSED_WARNING =
23
+ "Events refused: this website is not on the project's allowed websites (origin_not_allowed). This page sends no more events.";
24
+
25
+ // ─── the script tag (§5.6.2) ──────────────────────────────────────────────
26
+
27
+ // window.sequentialConfig (see the header) is page data, and the recorder loads from its api host. So it is used
28
+ // only when it is an OWN property of window (a polluted Object.prototype or an element named sequentialConfig is
29
+ // not) holding a plain object, and only when its key is valid; otherwise ownTag() goes on to the page's tags. It is
30
+ // returned as a tag-shaped object, so attr()/hasAttr() and every check below them stay the same for both paths.
31
+ var CONFIG_KEY_PATTERN = /^sq_sequential_[A-Za-z0-9]{1,64}$/;
32
+ var CONFIG_API_PATTERN = /^https:\/\/[A-Za-z0-9.-]+(:[0-9]{1,5})?\/*$/;
33
+ var CONFIG_NAMES = ['key', 'api', 'release'];
34
+
35
+ function ownValue(object, name) {
36
+ return Object.prototype.hasOwnProperty.call(object, name) ? object[name] : undefined;
37
+ }
38
+
39
+ // Its prototype is null or an Object.prototype (of any realm: one whose own prototype is null).
40
+ function isPlainObject(value) {
41
+ if (!value || typeof value !== 'object') return false;
42
+ var proto = Object.getPrototypeOf(value);
43
+ return proto === null || Object.getPrototypeOf(proto) === null;
44
+ }
45
+
46
+ function configString(config, name) {
47
+ var value = ownValue(config, name);
48
+ return typeof value === 'string' ? value.trim() : null;
49
+ }
50
+
51
+ function configTag() {
52
+ try {
53
+ var config = ownValue(window, 'sequentialConfig');
54
+ if (!isPlainObject(config)) return null;
55
+
56
+ var key = configString(config, 'key');
57
+ if (key === null || !CONFIG_KEY_PATTERN.test(key)) {
58
+ logError(
59
+ key === null
60
+ ? 'window.sequentialConfig has no key; it is not used.'
61
+ : 'window.sequentialConfig.key is not a Sequential ingest key (sq_sequential_…); it is not used.'
62
+ );
63
+ return null;
64
+ }
65
+ var values = { 'data-key': key };
66
+ var api = configString(config, 'api');
67
+ if (api !== null) {
68
+ if (CONFIG_API_PATTERN.test(api)) values['data-api'] = api;
69
+ else
70
+ logError(
71
+ 'window.sequentialConfig.api must be an https:// origin, such as https://api.usesequential.com.'
72
+ );
73
+ }
74
+ var release = configString(config, 'release');
75
+ if (release !== null && release !== '') values['data-release'] = release;
76
+
77
+ var unread = [];
78
+ var names = Object.keys(config);
79
+ for (var i = 0; i < names.length; i++) {
80
+ if (!inList(CONFIG_NAMES, names[i])) unread.push(names[i]);
81
+ }
82
+ if (unread.length) {
83
+ logWarn(
84
+ ('window.sequentialConfig.' + unread.sort().join(', ')).slice(0, 120) +
85
+ ': not read (only key, api and release are). To hold events until consent, fire the tag after consent' +
86
+ ' or call sequential.optOut().'
87
+ );
88
+ }
89
+
90
+ return {
91
+ getAttribute: function (name) {
92
+ return Object.prototype.hasOwnProperty.call(values, name) ? values[name] : null;
93
+ },
94
+ hasAttribute: function (name) {
95
+ return Object.prototype.hasOwnProperty.call(values, name);
96
+ }
97
+ };
98
+ } catch (e) {
99
+ return null;
100
+ }
101
+ }
102
+
103
+ function ownTag() {
104
+ try {
105
+ var current = document.currentScript;
106
+ if (current && current.getAttribute && current.getAttribute('data-key')) return current;
107
+
108
+ // Before the page-wide search, which takes ANY script[data-key], another vendor's too.
109
+ var fromConfig = configTag();
110
+ if (fromConfig) return fromConfig;
111
+
112
+ var tags = document.querySelectorAll('script[data-key]');
113
+ return tags.length ? tags[tags.length - 1] : null;
114
+ } catch (e) {
115
+ return null;
116
+ }
117
+ }
118
+
119
+ function attr(tag, name) {
120
+ try {
121
+ var value = tag && tag.getAttribute ? tag.getAttribute(name) : null;
122
+ return value == null ? null : String(value);
123
+ } catch (e) {
124
+ return null;
125
+ }
126
+ }
127
+
128
+ function hasAttr(tag, name) {
129
+ try {
130
+ return !!(tag && tag.hasAttribute && tag.hasAttribute(name));
131
+ } catch (e) {
132
+ return false;
133
+ }
134
+ }
135
+
136
+ // The backend's build-identity rule (BE src/adapters/release.ts), as in sequential.core.ts.
137
+ var RELEASE_PATTERN = /^[\x20-\x7E]{1,64}$/;
138
+ var RELEASE_PLACEHOLDERS = ['undefined', 'null', 'none', '(null)'];
139
+
140
+ function normalizeRelease(value) {
141
+ if (typeof value !== 'string') return undefined;
142
+ var s = value.trim();
143
+ if (!RELEASE_PATTERN.test(s) || inList(RELEASE_PLACEHOLDERS, s.toLowerCase())) return undefined;
144
+ return s;
145
+ }
146
+
147
+ var TAG = injectedTag || ownTag(); // injectedTag: from init() of @usesequential/browser; the script tag passes none.
148
+ var KEY = attr(TAG, 'data-key');
149
+ var API_HOST = attr(TAG, 'data-api');
150
+ var AUTOCAPTURE_ENABLED = attr(TAG, 'data-autocapture') !== 'false';
151
+ var DETECT_IDENTITY = attr(TAG, 'data-identity-text') !== 'off';
152
+ var OPT_OUT_ATTRIBUTE = hasAttr(TAG, 'data-opt-out');
153
+ var RELEASE_ATTRIBUTE = attr(TAG, 'data-release');
154
+ var RELEASE = normalizeRelease(RELEASE_ATTRIBUTE);
155
+ var COOKIE_DOMAIN = attr(TAG, 'data-context-cookie-domain');
156
+ // No `;` or space, so the value cannot add a cookie attribute.
157
+ if (COOKIE_DOMAIN !== null && !/^[A-Za-z0-9.-]+$/.test(COOKIE_DOMAIN)) {
158
+ logError('data-context-cookie-domain is not a domain; the context cookie is host-only.');
159
+ COOKIE_DOMAIN = null;
160
+ }
161
+ if (RELEASE_ATTRIBUTE !== null && RELEASE === undefined) {
162
+ logError('data-release is not a release (1 to 64 printable ASCII characters); events are sent without one.');
163
+ }
164
+
165
+ // No key or no API: every method stays present and inert, so a bad tag never throws.
166
+ var DISABLED = false;
167
+ if (!KEY) {
168
+ logError('the script tag has no data-key — no events will be sent.');
169
+ DISABLED = true;
170
+ } else if (!API_HOST) {
171
+ logError(
172
+ 'the script tag has no data-api — no events will be sent. The CDN origin is not the ' +
173
+ 'ingest origin, so it cannot be guessed from this script’s own src.'
174
+ );
175
+ DISABLED = true;
176
+ }
177
+
178
+ var API = API_HOST ? String(API_HOST).replace(/\/+$/, '') : '';
179
+ var INGEST_URL = API + '/i/v1/e';
180
+
181
+ // ─── storage (§5.4: best-effort, never throws) ────────────────────────────
182
+
183
+ var DISTINCT_ID_KEY = '__sq_did';
184
+ var ACCOUNT_ID_KEY = '__sq_aid';
185
+ var ACCOUNT_HASH_KEY = '__sq_ath';
186
+ var SESSION_KEY = '__sq_sid';
187
+ var OPT_OUT_KEY = '__sq_opt';
188
+ var CONTEXT_COOKIE = '__sq_ctx';
189
+ var CONTEXT_COOKIE_MAX = 600;
190
+ // A live session rewrites the cookie when the last write is this old: half its Max-Age (ruling R6).
191
+ var CONTEXT_COOKIE_REFRESH_MS = 15 * 60 * 1000;
192
+
193
+ var REPLAY_SID_KEY = '__lx_replay_sid';
194
+
195
+ var IDLE_LIMIT_MS = 30 * 60 * 1000;
196
+ var ABSOLUTE_LIMIT_MS = 24 * 60 * 60 * 1000;
197
+
198
+ var MAX_BATCH_EVENTS = 25;
199
+ var MAX_BATCH_BYTES = 32 * 1024;
200
+ var FLUSH_INTERVAL_MS = 5000;
201
+ var REQUEST_TIMEOUT_MS = 10000;
202
+ var MAX_SEND_ATTEMPTS = 3;
203
+ var RETRY_BASE_MS = 500;
204
+ // A 429 (the backend's per-project event rate limit): pause for the server's retry time, clamped; hold the refused
205
+ // batch and what is captured meanwhile, capped, the oldest dropped first (sequential.core.ts holdRateLimited).
206
+ var RATE_LIMIT_DEFAULT_SEC = 60;
207
+ var RATE_LIMIT_MIN_SEC = 1;
208
+ var RATE_LIMIT_MAX_SEC = 300;
209
+ var MAX_HELD_EVENTS = 100;
210
+ var MAX_HELD_BYTES = 128 * 1024;
211
+
212
+ var redactor = null;
213
+
214
+ var EXCEPTION_MESSAGE_MAX = 256;
215
+ var EXCEPTION_STACK_MAX = 2048;
216
+
217
+ var REDACTED_FALLBACK = '[redacted]';
218
+
219
+ var ephemeral = false;
220
+
221
+ // G-12 (sequential.core.ts storeItem): storage stays off until the stub queue has run and the visitor is not opted
222
+ // out, so a queued optOut() also writes nothing. Meanwhile each write waits in `held` (null removes).
223
+ var storageOn = false;
224
+ var held = {};
225
+ // What optOut() deletes: every key the SDK writes, except the __sq_opt mark it then sets.
226
+ var STORED_KEYS = [
227
+ ['localStorage', '__sq_did'],
228
+ ['localStorage', '__sq_aid'],
229
+ ['localStorage', '__sq_ath'],
230
+ ['localStorage', '__sq_ith'],
231
+ ['sessionStorage', '__sq_sid'],
232
+ ['sessionStorage', '__lx_replay_sid']
233
+ ];
234
+
235
+ // False only when the browser refused the write.
236
+ function storeItem(area, key, value) {
237
+ if (!storageOn) {
238
+ held[area + ':' + key] = [area, key, value];
239
+ return true;
240
+ }
241
+ try {
242
+ if (value === null) window[area].removeItem(key);
243
+ else window[area].setItem(key, value);
244
+ return true;
245
+ } catch (e) {
246
+ return false;
247
+ }
248
+ }
249
+
250
+ function startStorage() {
251
+ storageOn = true;
252
+ var writes = held;
253
+ held = {};
254
+ for (var name in writes) {
255
+ if (!Object.prototype.hasOwnProperty.call(writes, name)) continue;
256
+ var w = writes[name];
257
+ if (!storeItem(w[0], w[1], w[2]) && (w[1] === '__sq_did' || w[1] === '__sq_sid')) ephemeral = true;
258
+ }
259
+ }
260
+
261
+ // ─── ids ──────────────────────────────────────────────────────────────────
262
+
263
+ function fillRandom(bytes) {
264
+ for (var i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
265
+ }
266
+
267
+ function uuidv7(timestampMs) {
268
+ var bytes = new Uint8Array(16);
269
+ try {
270
+ if (window.crypto && window.crypto.getRandomValues) window.crypto.getRandomValues(bytes);
271
+ else fillRandom(bytes);
272
+ } catch (e) {
273
+ fillRandom(bytes);
274
+ }
275
+ var ts = Math.max(0, Math.floor(timestampMs) || 0);
276
+ bytes[0] = Math.floor(ts / 1099511627776) & 255;
277
+ bytes[1] = Math.floor(ts / 4294967296) & 255;
278
+ bytes[2] = Math.floor(ts / 16777216) & 255;
279
+ bytes[3] = Math.floor(ts / 65536) & 255;
280
+ bytes[4] = Math.floor(ts / 256) & 255;
281
+ bytes[5] = ts & 255;
282
+ bytes[6] = (bytes[6] & 15) | 112;
283
+ bytes[8] = (bytes[8] & 63) | 128;
284
+ var hex = '';
285
+ for (var i = 0; i < 16; i++) {
286
+ var part = bytes[i].toString(16);
287
+ hex += part.length === 1 ? '0' + part : part;
288
+ }
289
+ return (
290
+ hex.slice(0, 8) +
291
+ '-' +
292
+ hex.slice(8, 12) +
293
+ '-' +
294
+ hex.slice(12, 16) +
295
+ '-' +
296
+ hex.slice(16, 20) +
297
+ '-' +
298
+ hex.slice(20)
299
+ );
300
+ }
301
+
302
+ // ─── identity (§5.4) ──────────────────────────────────────────────────────
303
+
304
+ var memoryDistinctId = null;
305
+
306
+ function readDistinctId() {
307
+ try {
308
+ return window.localStorage.getItem(DISTINCT_ID_KEY);
309
+ } catch (e) {
310
+ ephemeral = true;
311
+ return memoryDistinctId;
312
+ }
313
+ }
314
+
315
+ function writeDistinctId(id) {
316
+ memoryDistinctId = id;
317
+ if (!storeItem('localStorage', DISTINCT_ID_KEY, id)) ephemeral = true;
318
+ }
319
+
320
+ // A held write first: before the stub queue has run, a repeat identify() or account() must see the first one's hash.
321
+ function readLocal(key, fallback) {
322
+ var waiting = held['localStorage:' + key];
323
+ if (waiting) return waiting[2];
324
+ try {
325
+ return window.localStorage.getItem(key);
326
+ } catch (e) {
327
+ return fallback;
328
+ }
329
+ }
330
+
331
+ function writeLocal(key, value) {
332
+ storeItem('localStorage', key, value);
333
+ }
334
+
335
+ // ─── account (sequential.core.ts accountIdOf / accountTraitsOf / accountHash; BE #429 is the contract) ───
336
+
337
+ var ACCOUNT_ID_MAX = 200;
338
+ var ACCOUNT_TRAITS_MAX_KEYS = 50;
339
+ var ACCOUNT_TRAIT_KEY_MAX = 100;
340
+ var ACCOUNT_TRAIT_VALUE_MAX = 1000;
341
+
342
+ function accountIdOf(value) {
343
+ var s;
344
+ if (typeof value === 'string') s = value;
345
+ else if (typeof value === 'number' && isFinite(value)) s = String(value);
346
+ else return null;
347
+ s = s.replace(/^\s+|\s+$/g, '');
348
+ return s.length > 0 && s.length <= ACCOUNT_ID_MAX ? s : null;
349
+ }
350
+
351
+ function accountTraitsOf(value) {
352
+ var out = [];
353
+ if (!value || typeof value !== 'object' || Object.prototype.toString.call(value) === '[object Array]') return out;
354
+ var keys = Object.keys(value);
355
+ for (var i = 0; i < keys.length && out.length < ACCOUNT_TRAITS_MAX_KEYS; i++) {
356
+ var name = keys[i];
357
+ var raw = value[name];
358
+ if (name.length === 0 || name.length > ACCOUNT_TRAIT_KEY_MAX) continue;
359
+ var v;
360
+ if (typeof raw === 'string') v = raw;
361
+ else if ((typeof raw === 'number' && isFinite(raw)) || typeof raw === 'boolean') v = String(raw);
362
+ else continue;
363
+ if (v.length > ACCOUNT_TRAIT_VALUE_MAX) continue;
364
+ out.push({ name: name, value: v });
365
+ }
366
+ return out;
367
+ }
368
+
369
+ function accountHash(id, traits) {
370
+ var pairs = [];
371
+ for (var i = 0; i < traits.length; i++) pairs.push([traits[i].name, traits[i].value]);
372
+ var text = JSON.stringify([id, pairs]);
373
+ var h = 0x811c9dc5;
374
+ for (var j = 0; j < text.length; j++) {
375
+ h ^= text.charCodeAt(j);
376
+ h = (h + (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24)) >>> 0;
377
+ }
378
+ return h.toString(16);
379
+ }
380
+
381
+ // __sq_ith: a hash of the last identify id + traits sent (keys sorted, values as JSON), never the traits themselves.
382
+ function identifyHash(id, props) {
383
+ var keys = Object.keys(props).sort();
384
+ var pairs = [];
385
+ for (var i = 0; i < keys.length; i++) {
386
+ var v = JSON.stringify(props[keys[i]]);
387
+ pairs.push([keys[i], v === undefined ? '' : v]);
388
+ }
389
+ var text = JSON.stringify([id, pairs]);
390
+ var h = 0x811c9dc5;
391
+ for (var j = 0; j < text.length; j++) {
392
+ h ^= text.charCodeAt(j);
393
+ h = (h + (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24)) >>> 0;
394
+ }
395
+ return h.toString(16);
396
+ }
397
+
398
+ var IDENTIFY_HASH_KEY = '__sq_ith';
399
+ var memoryIdentifyHash = null;
400
+ var accountId = null;
401
+ var memoryAccountHash = null;
402
+ try {
403
+ accountId = accountIdOf(readLocal(ACCOUNT_ID_KEY, null));
404
+ } catch (e) {
405
+ accountId = null;
406
+ }
407
+
408
+ function readOptOut() {
409
+ try {
410
+ return window.localStorage.getItem(OPT_OUT_KEY) === '1';
411
+ } catch (e) {
412
+ return false;
413
+ }
414
+ }
415
+
416
+ // ─── session (§5.4: 30 min idle OR 24 h absolute, whichever comes first) ───
417
+
418
+ var memorySession = null;
419
+
420
+ function readSession() {
421
+ var raw;
422
+ try {
423
+ raw = window.sessionStorage.getItem(SESSION_KEY);
424
+ } catch (e) {
425
+ ephemeral = true;
426
+ return memorySession;
427
+ }
428
+ if (!raw) return null;
429
+ try {
430
+ var parsed = JSON.parse(raw);
431
+ if (
432
+ parsed &&
433
+ typeof parsed.id === 'string' &&
434
+ typeof parsed.startedAt === 'number' &&
435
+ typeof parsed.lastActivity === 'number'
436
+ ) {
437
+ return { id: parsed.id, startedAt: parsed.startedAt, lastActivity: parsed.lastActivity };
438
+ }
439
+ } catch (e) {}
440
+ return null;
441
+ }
442
+
443
+ function writeSession(record) {
444
+ memorySession = record;
445
+ if (!storeItem('sessionStorage', SESSION_KEY, JSON.stringify(record))) ephemeral = true;
446
+ publishReplaySessionId(record.id);
447
+ }
448
+
449
+ var publishedSessionId = null;
450
+
451
+ // The recorder reads __lx_replay_sid as a PLAIN id once at boot, so publish on every rotation:
452
+ // the next page load then pins the id analytics uses (orig. comment at cac6164).
453
+ function publishReplaySessionId(id) {
454
+ if (!id || id === publishedSessionId) return;
455
+ publishedSessionId = id;
456
+ storeItem('sessionStorage', REPLAY_SID_KEY, id);
457
+ }
458
+
459
+ function startNewSession(t) {
460
+ var fresh = { id: uuidv7(t), startedAt: t, lastActivity: t };
461
+ writeSession(fresh);
462
+ return fresh;
463
+ }
464
+
465
+ var optedOut = readOptOut() || OPT_OUT_ATTRIBUTE;
466
+
467
+ var stopped = false;
468
+ var distinctId;
469
+ var session;
470
+
471
+ try {
472
+ distinctId = readDistinctId();
473
+ if (!distinctId) {
474
+ distinctId = uuidv7(Date.now());
475
+ writeDistinctId(distinctId);
476
+ }
477
+ session = readSession();
478
+ if (!session) session = startNewSession(Date.now());
479
+ else publishReplaySessionId(session.id);
480
+ } catch (e) {
481
+ ephemeral = true;
482
+ var bootTime = Date.now();
483
+ distinctId = uuidv7(bootTime);
484
+ memoryDistinctId = distinctId;
485
+ session = { id: uuidv7(bootTime), startedAt: bootTime, lastActivity: bootTime };
486
+ memorySession = session;
487
+ }
488
+
489
+ // ─── the context cookie __sq_ctx (sequential.core.ts syncContextCookie) ───
490
+ // It keeps the anonymous id identify() sent as $anon_distinct_id; after a reload it carries the stored id (core.ts).
491
+
492
+ var contextDistinctId = distinctId;
493
+ var contextOn = false;
494
+ var contextWritten = null;
495
+ var contextWrittenAt = 0;
496
+
497
+ function writeContextCookie(value) {
498
+ contextWritten = value;
499
+ contextWrittenAt = Date.now();
500
+ try {
501
+ var secure = window.location.protocol === 'https:';
502
+ document.cookie =
503
+ CONTEXT_COOKIE +
504
+ '=' +
505
+ value +
506
+ '; Path=/; Max-Age=' +
507
+ (value ? IDLE_LIMIT_MS / 1000 : 0) +
508
+ '; SameSite=Lax' +
509
+ (COOKIE_DOMAIN ? '; Domain=' + COOKIE_DOMAIN : '') +
510
+ (secure ? '; Secure' : '');
511
+ } catch (e) {}
512
+ }
513
+
514
+ // Before this page wrote one, a clear is for a cookie an earlier page left: only when it is there.
515
+ function clearContextCookie() {
516
+ if (contextWritten === '' || DISABLED) return;
517
+ if (contextWritten === null && !hasContextCookie()) return;
518
+ writeContextCookie('');
519
+ }
520
+
521
+ function hasContextCookie() {
522
+ try {
523
+ return (';' + document.cookie).replace(/\s/g, '').indexOf(';' + CONTEXT_COOKIE + '=') !== -1;
524
+ } catch (e) {
525
+ return true;
526
+ }
527
+ }
528
+
529
+ function syncContextCookie() {
530
+ if (!contextOn || optedOut || stopped) return;
531
+ // A stored session that has ended is not current: the next event starts a new one and writes that.
532
+ var t = Date.now();
533
+ if (t - session.lastActivity >= IDLE_LIMIT_MS || t - session.startedAt >= ABSOLUTE_LIMIT_MS) return;
534
+ var value = encodeURIComponent(
535
+ 'v1;d=' + encodeURIComponent(contextDistinctId) + ';s=' + encodeURIComponent(session.id)
536
+ );
537
+ if (value.length > CONTEXT_COOKIE_MAX) value = '';
538
+ // The same value again gives the cookie a fresh Max-Age. A clear ('') is never repeated.
539
+ var refresh = value !== '' && t - contextWrittenAt >= CONTEXT_COOKIE_REFRESH_MS;
540
+ if (value !== contextWritten || refresh) writeContextCookie(value);
541
+ }
542
+
543
+ function touchSession() {
544
+ var t = Date.now();
545
+ var idleExpired = t - session.lastActivity >= IDLE_LIMIT_MS;
546
+ var absoluteExpired = t - session.startedAt >= ABSOLUTE_LIMIT_MS;
547
+ if (idleExpired || absoluteExpired) {
548
+ session = startNewSession(t);
549
+ } else {
550
+ session = { id: session.id, startedAt: session.startedAt, lastActivity: t };
551
+ writeSession(session);
552
+ }
553
+ syncContextCookie();
554
+ return session.id;
555
+ }
556
+
557
+ // ─── transport (§5.5) ─────────────────────────────────────────────────────
558
+
559
+ var superProps = {};
560
+ var queue = [];
561
+ var queueBytes = 0;
562
+ var flushTimer = null;
563
+ var pauseTimer = null;
564
+ // Events already put back once after a 429 (a batch is resent once). An array, not a WeakSet: this file is ES5.
565
+ var resentOnce = [];
566
+
567
+ function assign(target, source) {
568
+ if (!source) return target;
569
+ for (var key in source) {
570
+ if (Object.prototype.hasOwnProperty.call(source, key)) target[key] = source[key];
571
+ }
572
+ return target;
573
+ }
574
+
575
+ function byteLength(value) {
576
+ try {
577
+ if (window.TextEncoder) return new window.TextEncoder().encode(value).length;
578
+ } catch (e) {}
579
+
580
+ return value.length;
581
+ }
582
+
583
+ function timeoutSignal() {
584
+ try {
585
+ if (window.AbortSignal && window.AbortSignal.timeout) {
586
+ return window.AbortSignal.timeout(REQUEST_TIMEOUT_MS);
587
+ }
588
+ } catch (e) {}
589
+ return undefined;
590
+ }
591
+
592
+ function scheduleFlushTimer() {
593
+ if (flushTimer !== null) return;
594
+ flushTimer = setTimeout(function () {
595
+ flushTimer = null;
596
+ flush();
597
+ }, FLUSH_INTERVAL_MS);
598
+ }
599
+
600
+ function clearFlushTimer() {
601
+ if (flushTimer !== null) {
602
+ clearTimeout(flushTimer);
603
+ flushTimer = null;
604
+ }
605
+ }
606
+
607
+ function buildEnvelope(events) {
608
+ try {
609
+ return JSON.stringify({ key: KEY, sent_at: new Date(Date.now()).toISOString(), events: events });
610
+ } catch (e) {
611
+ return null;
612
+ }
613
+ }
614
+
615
+ function sleep(ms) {
616
+ return new Promise(function (resolve) {
617
+ setTimeout(resolve, ms);
618
+ });
619
+ }
620
+
621
+ function canSend() {
622
+ try {
623
+ return typeof window.fetch === 'function';
624
+ } catch (e) {
625
+ return false;
626
+ }
627
+ }
628
+
629
+ function postOnce(body) {
630
+ try {
631
+ return window
632
+ .fetch(INGEST_URL, {
633
+ method: 'POST',
634
+ headers: { 'Content-Type': 'application/json' },
635
+ body: body,
636
+ signal: timeoutSignal()
637
+ })
638
+ .then(
639
+ function (res) {
640
+ return res;
641
+ },
642
+ function () {
643
+ return null;
644
+ }
645
+ );
646
+ } catch (e) {
647
+ return Promise.resolve(null);
648
+ }
649
+ }
650
+
651
+ function refusalCode(res) {
652
+ return Promise.resolve()
653
+ .then(function () {
654
+ return res.json();
655
+ })
656
+ .then(
657
+ function (b) {
658
+ return !!b && typeof b.error === 'string' ? b.error : null;
659
+ },
660
+ function () {
661
+ return null;
662
+ }
663
+ );
664
+ }
665
+
666
+ function stopSending() {
667
+ stopped = true;
668
+ clearContextCookie();
669
+ queue = [];
670
+ queueBytes = 0;
671
+ clearFlushTimer();
672
+ if (pauseTimer !== null) {
673
+ clearTimeout(pauseTimer);
674
+ pauseTimer = null;
675
+ }
676
+ }
677
+
678
+ // A refusal's JSON body, read ONCE (a fetch Response body can be read only once), or null (sequential.core.ts bodyOf).
679
+ function bodyOf(res) {
680
+ return Promise.resolve()
681
+ .then(function () {
682
+ return res.json();
683
+ })
684
+ .then(
685
+ function (b) {
686
+ return b && typeof b === 'object' ? b : null;
687
+ },
688
+ function () {
689
+ return null;
690
+ }
691
+ );
692
+ }
693
+
694
+ function retryAfterSecOf(res, b) {
695
+ var sec = b && typeof b.retry_after_sec === 'number' ? b.retry_after_sec : NaN;
696
+ if (!isFinite(sec)) {
697
+ try {
698
+ var h = res.headers && res.headers.get ? res.headers.get('retry-after') : null;
699
+ if (h != null && /^\s*\d+\s*$/.test(h)) sec = Number(h);
700
+ } catch (e) {}
701
+ }
702
+ if (!isFinite(sec)) sec = RATE_LIMIT_DEFAULT_SEC;
703
+ return Math.min(RATE_LIMIT_MAX_SEC, Math.max(RATE_LIMIT_MIN_SEC, Math.ceil(sec)));
704
+ }
705
+
706
+ function sizeOf(e) {
707
+ try {
708
+ return byteLength(JSON.stringify(e));
709
+ } catch (err) {
710
+ return 0;
711
+ }
712
+ }
713
+
714
+ function trimHeld() {
715
+ while (queue.length > MAX_HELD_EVENTS || (queue.length > 1 && queueBytes > MAX_HELD_BYTES)) {
716
+ queueBytes -= sizeOf(queue.shift());
717
+ }
718
+ }
719
+
720
+ function holdRateLimited(events, sec) {
721
+ if (stopped) return;
722
+ var again = [];
723
+ for (var i = 0; i < events.length; i++) {
724
+ if (resentOnce.indexOf(events[i]) === -1) {
725
+ again.push(events[i]);
726
+ resentOnce.push(events[i]);
727
+ }
728
+ }
729
+ while (resentOnce.length > 2 * MAX_HELD_EVENTS) resentOnce.shift();
730
+ queue = again.concat(queue);
731
+ queueBytes = 0;
732
+ for (var j = 0; j < queue.length; j++) queueBytes += sizeOf(queue[j]);
733
+ clearFlushTimer();
734
+ if (pauseTimer !== null) clearTimeout(pauseTimer);
735
+ pauseTimer = setTimeout(function () {
736
+ pauseTimer = null;
737
+ flush();
738
+ }, sec * 1000);
739
+ trimHeld();
740
+ }
741
+
742
+ function attemptSend(body, attempt, events) {
743
+ function retry() {
744
+ if (attempt >= MAX_SEND_ATTEMPTS) return;
745
+ return sleep(RETRY_BASE_MS * Math.pow(2, attempt - 1)).then(function () {
746
+ if (!stopped) return attemptSend(body, attempt + 1, events);
747
+ });
748
+ }
749
+ return postOnce(body).then(function (res) {
750
+ if (res) {
751
+ if (res.ok) return;
752
+
753
+ if (res.status === 429) {
754
+ return bodyOf(res).then(function (b) {
755
+ holdRateLimited(events, retryAfterSecOf(res, b));
756
+ });
757
+ }
758
+ // The backend is shedding load: hold and wait like a 429. Any other 503 keeps the quick retry.
759
+ if (res.status === 503) {
760
+ return bodyOf(res).then(function (b) {
761
+ if (b && b.error === 'overloaded') {
762
+ holdRateLimited(events, retryAfterSecOf(res, b));
763
+ return;
764
+ }
765
+ return retry();
766
+ });
767
+ }
768
+ if (res.status === 401) return;
769
+ if (res.status === 402) {
770
+ return refusalCode(res).then(function (code) {
771
+ if (code && code.indexOf('billing_') === 0) stopSending();
772
+ });
773
+ }
774
+ if (res.status === 403) {
775
+ return refusalCode(res).then(function (code) {
776
+ if (code !== 'origin_not_allowed' || stopped) return;
777
+ stopSending();
778
+ logWarn(ORIGIN_REFUSED_WARNING);
779
+ });
780
+ }
781
+
782
+ if (res.status < 500) return;
783
+ }
784
+ return retry();
785
+ });
786
+ }
787
+
788
+ function flush() {
789
+ try {
790
+ if (queue.length === 0) return Promise.resolve();
791
+ clearFlushTimer();
792
+ // Paused by a 429: the pause's own timer flushes what is held when it ends.
793
+ if (pauseTimer !== null) return Promise.resolve();
794
+ var events = queue;
795
+ queue = [];
796
+ queueBytes = 0;
797
+ if (!canSend()) return Promise.resolve();
798
+ var body = buildEnvelope(events);
799
+ if (body === null) return Promise.resolve();
800
+ return attemptSend(body, 1, events)['catch'](noop);
801
+ } catch (e) {
802
+ return Promise.resolve();
803
+ }
804
+ }
805
+
806
+ function drain() {
807
+ try {
808
+ if (optedOut || DISABLED || stopped) return null;
809
+ if (queue.length === 0) return null;
810
+ clearFlushTimer();
811
+ var events = queue;
812
+ queue = [];
813
+ queueBytes = 0;
814
+ var body = buildEnvelope(events);
815
+ if (body === null) return null;
816
+ return { url: INGEST_URL, body: body };
817
+ } catch (e) {
818
+ return null;
819
+ }
820
+ }
821
+
822
+ function captureInternal(name, props, at) {
823
+ try {
824
+ if (optedOut || DISABLED || stopped) return;
825
+ var sessionId = touchSession();
826
+
827
+ var eventProps = {};
828
+ var url = currentUrl();
829
+ if (url !== undefined) eventProps.$current_url = url;
830
+ // Before super properties and the call's props, so register({ $release }) still wins.
831
+ if (RELEASE !== undefined) eventProps.$release = RELEASE;
832
+ eventProps = assign(assign(eventProps, superProps), props);
833
+
834
+ if (ephemeral) eventProps.$ephemeral_id = true;
835
+
836
+ // `at`: a dead click is known 2.5 s after it happened, and is dated at the click.
837
+ var now = typeof at === 'number' ? at : Date.now();
838
+ var outgoing = {
839
+ event: name,
840
+ uuid: uuidv7(now),
841
+ ts: new Date(now).toISOString(),
842
+ distinct_id: distinctId,
843
+ session_id: sessionId,
844
+ props: eventProps
845
+ };
846
+ if (accountId !== null) outgoing.account_id = accountId;
847
+
848
+ var size;
849
+ try {
850
+ size = byteLength(JSON.stringify(outgoing));
851
+ } catch (e) {
852
+ return;
853
+ }
854
+
855
+ queue.push(outgoing);
856
+ queueBytes += size;
857
+ if (pauseTimer !== null) trimHeld();
858
+
859
+ if (queue.length >= MAX_BATCH_EVENTS || queueBytes >= MAX_BATCH_BYTES) {
860
+ clearFlushTimer();
861
+ flush();
862
+ } else {
863
+ scheduleFlushTimer();
864
+ }
865
+ } catch (e) {}
866
+ }
867
+
868
+ // ─── the public surface (§5.1, §5.2) ──────────────────────────────────────
869
+
870
+ function capture(event, props) {
871
+ if (typeof event === 'string' && event.charAt(0) === '$') {
872
+ throw new Error(
873
+ 'Sequential: "' +
874
+ event +
875
+ '" is a reserved event name — event names starting with "$" are reserved for ' +
876
+ "Sequential's own events. Choose a different name for your own event."
877
+ );
878
+ }
879
+ captureInternal(event, props);
880
+ }
881
+
882
+ // ─── identity text (spec #475 §6, as sequential.core.ts) ───
883
+ var idWords = [];
884
+ var idEmails = [];
885
+
886
+ function idTokens(text) {
887
+ var s = String(text);
888
+ return (s.normalize ? s.normalize('NFKC') : s).toLowerCase().split(/[\s!-\/:-@[-`{-~]+/);
889
+ }
890
+
891
+ function learnIdentity(id, props) {
892
+ if (id !== distinctId) idWords = idEmails = [];
893
+ if (id.indexOf('@') > 0) idEmails.push(id.toLowerCase());
894
+ for (var k in props) {
895
+ var v = props[k];
896
+ if (typeof v == 'string') {
897
+ if (/e-?mail/i.test(k)) idEmails.push(v.toLowerCase());
898
+ else if (/^\$?name$|(first|last|full|display|nick|given|family)[_-]?name$|surname$/i.test(k)) idWords = idWords.concat(idTokens(v));
899
+ }
900
+ }
901
+ }
902
+
903
+ function namesPerson(text) {
904
+ var w = idTokens(text);
905
+ for (var i = 0; i < idEmails.length; i++) if (String(text).toLowerCase().indexOf(idEmails[i]) >= 0) return true;
906
+ for (i = 0; i < w.length; i++) if (w[i].length > 2 && inList(idWords, w[i])) return true;
907
+ }
908
+
909
+ function inAccountUi(node) {
910
+ for (var i = 0; node && node.getAttribute && i++ < 4; node = node.parentNode) {
911
+ if (/(\b|_)(avatar|account|profile|user[-_]?menu)(\b|_)/.test((node.getAttribute('class') + ' ' + node.id + ' ' + node.getAttribute('data-testid')).toLowerCase()) || /account|profile|user/i.test(node.getAttribute('aria-label'))) return true;
912
+ }
913
+ }
914
+
915
+ learnIdentity(String(distinctId));
916
+
917
+ function identify(newDistinctId, props) {
918
+ try {
919
+ if (optedOut || DISABLED) return;
920
+ if (typeof newDistinctId !== 'string' || newDistinctId.length === 0) return;
921
+ learnIdentity(newDistinctId, props);
922
+ var previous = distinctId;
923
+ var hasTraits = props !== undefined && props !== null && typeof props === 'object' && Object.keys(props).length > 0;
924
+ var hash = hasTraits ? identifyHash(newDistinctId, props) : null;
925
+ if (previous === newDistinctId) {
926
+ // Same person again (a reload): changed traits still go out; the same traits, or none, send nothing.
927
+ if (hash === null || hash === readLocal(IDENTIFY_HASH_KEY, memoryIdentifyHash)) return;
928
+ memoryIdentifyHash = hash;
929
+ writeLocal(IDENTIFY_HASH_KEY, hash);
930
+ captureInternal('$identify', assign({}, props));
931
+ return;
932
+ }
933
+ memoryIdentifyHash = hash;
934
+ writeLocal(IDENTIFY_HASH_KEY, hash);
935
+ distinctId = newDistinctId;
936
+ writeDistinctId(newDistinctId);
937
+ contextDistinctId = previous;
938
+
939
+ var merged = assign({}, props);
940
+ merged.$anon_distinct_id = previous;
941
+ captureInternal('$identify', merged);
942
+ } catch (e) {}
943
+ }
944
+
945
+ // $account on an id change (empty traits too) or on traits that differ from the last sent (__sq_ath).
946
+ function account(rawId, rawTraits) {
947
+ try {
948
+ if (optedOut || DISABLED) return;
949
+ var id = accountIdOf(rawId);
950
+ if (id === null) {
951
+ logError('account() needs an id of 1 to ' + ACCOUNT_ID_MAX + ' characters (a string or a number); the call was ignored.');
952
+ return;
953
+ }
954
+ var traits = rawTraits === undefined ? [] : accountTraitsOf(rawTraits);
955
+ var hash = accountHash(id, traits);
956
+ var changed = id !== accountId;
957
+ var lastHash = readLocal(ACCOUNT_HASH_KEY, memoryAccountHash);
958
+ accountId = id;
959
+ writeLocal(ACCOUNT_ID_KEY, id);
960
+ if (!changed && (rawTraits === undefined || hash === lastHash)) return;
961
+ memoryAccountHash = hash;
962
+ writeLocal(ACCOUNT_HASH_KEY, hash);
963
+ var props = {};
964
+ for (var i = 0; i < traits.length; i++) props[traits[i].name] = traits[i].value;
965
+ captureInternal('$account', { account_props: props });
966
+ } catch (e) {}
967
+ }
968
+
969
+ function register(props) {
970
+ try {
971
+ superProps = assign(assign({}, superProps), props);
972
+ } catch (e) {}
973
+ }
974
+
975
+ function unregister(propKey) {
976
+ try {
977
+ var next = assign({}, superProps);
978
+ delete next[propKey];
979
+ superProps = next;
980
+ } catch (e) {}
981
+ }
982
+
983
+ function reset() {
984
+ try {
985
+ superProps = {};
986
+ memoryDistinctId = null;
987
+ idWords = idEmails = [];
988
+ accountId = null;
989
+ memoryAccountHash = null;
990
+ memoryIdentifyHash = null;
991
+ writeLocal(ACCOUNT_ID_KEY, null);
992
+ writeLocal(ACCOUNT_HASH_KEY, null);
993
+ writeLocal(IDENTIFY_HASH_KEY, null);
994
+ distinctId = uuidv7(Date.now());
995
+ writeDistinctId(distinctId);
996
+ session = startNewSession(Date.now());
997
+ clearContextCookie();
998
+ contextDistinctId = distinctId;
999
+ syncContextCookie();
1000
+ } catch (e) {}
1001
+ }
1002
+
1003
+ function optOut() {
1004
+ try {
1005
+ optedOut = true;
1006
+
1007
+ queue = [];
1008
+ queueBytes = 0;
1009
+ clearFlushTimer();
1010
+ clearContextCookie();
1011
+ forgetStorage();
1012
+ // The one key an opted-out visitor keeps: the choice, with no id (G-12).
1013
+ try {
1014
+ window.localStorage.setItem(OPT_OUT_KEY, '1');
1015
+ } catch (e) {}
1016
+ // C1: the recorder stops too (BE recorder-boot.js). The page flag reaches one still loading, and stands in for a
1017
+ // storage write that failed; the hook stops one that is running and drops what it holds.
1018
+ window.__lxReplayOptedOut = true;
1019
+ if (typeof window.__lxReplayOptOut === 'function') window.__lxReplayOptOut();
1020
+ } catch (e) {}
1021
+ }
1022
+
1023
+ // G-12: delete the ids the SDK stored and write none while opted out. They wait for optIn(), so they hold for this page.
1024
+ function forgetStorage() {
1025
+ storageOn = false;
1026
+ held = {};
1027
+ for (var i = 0; i < STORED_KEYS.length; i++) {
1028
+ try {
1029
+ window[STORED_KEYS[i][0]].removeItem(STORED_KEYS[i][1]);
1030
+ } catch (e) {}
1031
+ }
1032
+ writeDistinctId(distinctId);
1033
+ writeSession(session);
1034
+ if (publishedSessionId) storeItem('sessionStorage', REPLAY_SID_KEY, publishedSessionId);
1035
+ if (accountId !== null) writeLocal(ACCOUNT_ID_KEY, accountId);
1036
+ }
1037
+
1038
+ function optIn() {
1039
+ try {
1040
+ optedOut = false;
1041
+ try {
1042
+ window.localStorage.removeItem(OPT_OUT_KEY);
1043
+ } catch (e) {}
1044
+ if (!DISABLED) startStorage();
1045
+ // A recorder that boots from here records; one this page load already stopped stays stopped (fail closed).
1046
+ window.__lxReplayOptedOut = false;
1047
+
1048
+ bootSequence();
1049
+ syncContextCookie();
1050
+ } catch (e) {}
1051
+ }
1052
+
1053
+ function captureException(error, props) {
1054
+ try {
1055
+ if (optedOut || DISABLED) return;
1056
+ var isErrorLike = !!error && typeof error === 'object' && typeof error.message === 'string';
1057
+ var message = isErrorLike ? error.message : String(error);
1058
+ var stack = isErrorLike && typeof error.stack === 'string' ? error.stack : undefined;
1059
+ var merged = assign({}, props);
1060
+ merged.$exception_message = redactor
1061
+ ? redactor.boundedRedact(message, EXCEPTION_MESSAGE_MAX)
1062
+ : REDACTED_FALLBACK;
1063
+ merged.$exception_stack =
1064
+ redactor && stack !== undefined ? redactor.boundedRedact(stack, EXCEPTION_STACK_MAX) : undefined;
1065
+ captureInternal('$exception', merged);
1066
+ } catch (e) {}
1067
+ }
1068
+
1069
+ // ─── redaction (restated from sequential.autocapture.ts) ──────────────────
1070
+
1071
+ function cap(s, max) {
1072
+ return s.length > max ? s.slice(0, max) + '…' : s;
1073
+ }
1074
+
1075
+ function luhn(digits) {
1076
+ if (!/^[0-9]+$/.test(digits)) return false;
1077
+ var sum = 0;
1078
+ var alt = false;
1079
+ for (var i = digits.length - 1; i >= 0; i--) {
1080
+ var n = digits.charCodeAt(i) - 48;
1081
+ if (alt) {
1082
+ n *= 2;
1083
+ if (n > 9) n -= 9;
1084
+ }
1085
+ sum += n;
1086
+ alt = !alt;
1087
+ }
1088
+ return sum % 10 === 0;
1089
+ }
1090
+
1091
+ var TOKEN_CHAR = /[A-Za-z0-9._%+~/=@-]/;
1092
+ var CARD_RUN_CHAR = /[0-9 -]/;
1093
+ var DIGIT_CHAR = /[0-9]/;
1094
+
1095
+ var CARD_SCAN_MAX = 25;
1096
+
1097
+ function createRedactor(rules) {
1098
+ var REDACTED = (rules && rules.redacted) || '[redacted]';
1099
+ var list = (rules && rules.value_patterns) || [];
1100
+ var patterns = [];
1101
+ for (var i = 0; i < list.length; i++) {
1102
+ var p = list[i];
1103
+
1104
+ if (p.luhn_group && !p.luhn_strip) {
1105
+ throw new Error('sequential: rule "' + p.source + '" has luhn_group without luhn_strip');
1106
+ }
1107
+ patterns.push({
1108
+ re: new RegExp(p.source, p.flags),
1109
+ keepGroup: p.keep_group,
1110
+ prefixGroup: p.prefix_group,
1111
+ luhnGroup: p.luhn_group,
1112
+ luhnStrip: p.luhn_strip ? new RegExp(p.luhn_strip, 'g') : null
1113
+ });
1114
+ }
1115
+
1116
+ function replaceWith(p) {
1117
+ return function (match) {
1118
+ var rest = Array.prototype.slice.call(arguments, 1);
1119
+ function group(n) {
1120
+ return n ? String(rest[n - 1] == null ? '' : rest[n - 1]) : '';
1121
+ }
1122
+ if (p.luhnGroup) {
1123
+ return luhn(group(p.luhnGroup).replace(p.luhnStrip, ''))
1124
+ ? group(p.prefixGroup) + REDACTED
1125
+ : match;
1126
+ }
1127
+
1128
+ if (p.prefixGroup) return group(p.prefixGroup) + REDACTED;
1129
+ if (p.keepGroup) return group(p.keepGroup) + ' ' + REDACTED;
1130
+ return REDACTED;
1131
+ };
1132
+ }
1133
+
1134
+ function redactText(input) {
1135
+ var s = String(input);
1136
+ for (var i = 0; i < patterns.length; i++) {
1137
+ patterns[i].re.lastIndex = 0;
1138
+ s = s.replace(patterns[i].re, replaceWith(patterns[i]));
1139
+ }
1140
+ return s;
1141
+ }
1142
+
1143
+ function boundedRedact(input, max) {
1144
+ var s = String(input);
1145
+ var stripped = false;
1146
+ if (s.length > max * 2) {
1147
+ var sliced = s.slice(0, max * 2);
1148
+ var j = sliced.length;
1149
+ var tailIsCardRun = true;
1150
+ while (j > 0 && TOKEN_CHAR.test(sliced.charAt(j - 1))) {
1151
+ if (!CARD_RUN_CHAR.test(sliced.charAt(j - 1))) tailIsCardRun = false;
1152
+ j--;
1153
+ }
1154
+ var runEnd = tailIsCardRun ? sliced.length : j;
1155
+ var k = j;
1156
+ var sawDigit = false;
1157
+ while (k > 0 && k > runEnd - CARD_SCAN_MAX && CARD_RUN_CHAR.test(sliced.charAt(k - 1))) {
1158
+ if (DIGIT_CHAR.test(sliced.charAt(k - 1))) sawDigit = true;
1159
+ k--;
1160
+ }
1161
+ if (sawDigit) j = k;
1162
+ s = sliced.slice(0, j);
1163
+ stripped = j < sliced.length;
1164
+ }
1165
+ var out = redactText(s);
1166
+ if (stripped) out = out ? out + ' ' + REDACTED : REDACTED;
1167
+ return cap(out, max);
1168
+ }
1169
+
1170
+ return { redactText: redactText, boundedRedact: boundedRedact };
1171
+ }
1172
+
1173
+ // ─── autocapture (§5.3) ───────────────────────────────────────────────────
1174
+
1175
+ var INTERACTIVE_SELECTOR = 'a, button, input[type="submit"], [role="button"], [data-sq]';
1176
+ var CLICK_TEXT_MAX = 128;
1177
+
1178
+ var EL_DATA_MAX_ATTRS = 12;
1179
+ var EL_DATA_VALUE_MAX = 128;
1180
+
1181
+ var EL_ID_MAX = 128;
1182
+ var EL_SELECTOR_MAX = 256;
1183
+
1184
+ var URL_MAX = 512;
1185
+
1186
+ var TEXT_OPAQUE_TAGS = ['textarea', 'select'];
1187
+
1188
+ function isEditable(el) {
1189
+ try {
1190
+ if (!el || !el.getAttribute) return false;
1191
+ var value = el.getAttribute('contenteditable');
1192
+ return value !== null && String(value).toLowerCase() !== 'false';
1193
+ } catch (e) {
1194
+ return false;
1195
+ }
1196
+ }
1197
+
1198
+ var TEXT_SCAN_MAX = CLICK_TEXT_MAX * 4;
1199
+
1200
+ function inList(list, value) {
1201
+ for (var i = 0; i < list.length; i++) if (list[i] === value) return true;
1202
+ return false;
1203
+ }
1204
+
1205
+ var NEVER_READ_INPUT_TYPES = ['password', 'email', 'tel'];
1206
+
1207
+ var LABEL_INPUT_TYPES = ['submit', 'button', 'reset'];
1208
+
1209
+ function tagNameOf(el) {
1210
+ return el && el.tagName ? String(el.tagName).toLowerCase() : '';
1211
+ }
1212
+
1213
+ function matchesSelector(el, selector) {
1214
+ try {
1215
+ var fn = el.matches || el.msMatchesSelector || el.webkitMatchesSelector;
1216
+ return fn ? fn.call(el, selector) : false;
1217
+ } catch (e) {
1218
+ return false;
1219
+ }
1220
+ }
1221
+
1222
+ function closestMatching(el, selector) {
1223
+ try {
1224
+ if (el.closest) return el.closest(selector);
1225
+ } catch (e) {}
1226
+ var node = el;
1227
+ while (node && node.nodeType === 1) {
1228
+ if (matchesSelector(node, selector)) return node;
1229
+ node = node.parentNode;
1230
+ }
1231
+ return null;
1232
+ }
1233
+
1234
+ function isMasked(el) {
1235
+ return !!closestMatching(el, '[data-sq-mask], [data-sq-private]');
1236
+ }
1237
+
1238
+ function subtreeText(el) {
1239
+ var out = '';
1240
+ function visit(node) {
1241
+ for (var child = node.firstChild; child !== null; child = child.nextSibling) {
1242
+ if (out.length >= TEXT_SCAN_MAX) return;
1243
+ if (child.nodeType === 3) {
1244
+ out += child.nodeValue == null ? '' : child.nodeValue;
1245
+ continue;
1246
+ }
1247
+ if (child.nodeType !== 1) continue;
1248
+ if (inList(TEXT_OPAQUE_TAGS, tagNameOf(child))) continue;
1249
+ if (isEditable(child)) continue;
1250
+ if (child.hasAttribute && (child.hasAttribute('data-sq-mask') || child.hasAttribute('data-sq-private'))) continue;
1251
+ visit(child);
1252
+ }
1253
+ }
1254
+ visit(el);
1255
+ return out;
1256
+ }
1257
+
1258
+ function rawClickText(el) {
1259
+ if (isEditable(el)) return undefined;
1260
+ var tag = tagNameOf(el);
1261
+ if (tag === 'input') {
1262
+ var type = String(el.type || '').toLowerCase();
1263
+ if (inList(NEVER_READ_INPUT_TYPES, type)) return undefined;
1264
+ if (inList(LABEL_INPUT_TYPES, type)) return String(el.value || '').trim() || undefined;
1265
+ return undefined;
1266
+ }
1267
+ if (inList(TEXT_OPAQUE_TAGS, tag)) return undefined;
1268
+ var text = subtreeText(el).trim();
1269
+ return text || undefined;
1270
+ }
1271
+
1272
+ // sequential.autocapture.ts hashRouteOf: only a #/ or #!/ route is kept, cut before ? & #; too long → dropped.
1273
+ function hashRouteOf(fragment) {
1274
+ if (!/^#!?\//.test(fragment)) return '';
1275
+ var end = fragment.slice(1).search(/[?&#]/);
1276
+ var route = end >= 0 ? fragment.slice(0, end + 1) : fragment;
1277
+ return route.length > URL_MAX ? '' : route;
1278
+ }
1279
+
1280
+ function safeUrl(raw, rdct) {
1281
+ var s = String(raw);
1282
+ var hash = s.indexOf('#');
1283
+ var route = '';
1284
+ if (hash >= 0) {
1285
+ route = hashRouteOf(s.slice(hash));
1286
+ s = s.slice(0, hash);
1287
+ }
1288
+ s = s.replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/?#@]*@/, '$1');
1289
+ return rdct.boundedRedact(s + route, URL_MAX);
1290
+ }
1291
+
1292
+ function currentUrl() {
1293
+ if (!redactor) return undefined;
1294
+ try {
1295
+ return safeUrl(String(window.location.href), redactor);
1296
+ } catch (e) {
1297
+ return undefined;
1298
+ }
1299
+ }
1300
+
1301
+ function stableSelector(el, noIds) {
1302
+ var parts = [];
1303
+ var node = el;
1304
+ var root = document.documentElement;
1305
+ while (node && node !== root && node.nodeType === 1) {
1306
+ if (node.id && !noIds) {
1307
+ parts.unshift('#' + node.id);
1308
+ break;
1309
+ }
1310
+ var parent = node.parentNode;
1311
+ if (!parent || parent.nodeType !== 1) {
1312
+ parts.unshift(tagNameOf(node));
1313
+ break;
1314
+ }
1315
+ var children = parent.children || [];
1316
+ var sameTag = 0;
1317
+ var index = 0;
1318
+ for (var i = 0; i < children.length; i++) {
1319
+ if (children[i].tagName === node.tagName) {
1320
+ sameTag++;
1321
+ if (children[i] === node) index = sameTag;
1322
+ }
1323
+ }
1324
+ parts.unshift(sameTag > 1 ? tagNameOf(node) + ':nth-of-type(' + index + ')' : tagNameOf(node));
1325
+ node = parent;
1326
+ }
1327
+ return parts.join(' > ') || tagNameOf(el);
1328
+ }
1329
+
1330
+ function dataAttrs(el, rdct) {
1331
+ var out;
1332
+ var count = 0;
1333
+ try {
1334
+ var attrs = el.attributes;
1335
+ if (!attrs) return undefined;
1336
+ for (var i = 0; i < attrs.length; i++) {
1337
+ var name = attrs[i].name;
1338
+ if (name.indexOf('data-') !== 0) continue;
1339
+ var key = name.slice(5).replace(/-([a-z0-9])/g, function (_m, c) {
1340
+ return c.toUpperCase();
1341
+ });
1342
+ if (key === 'sqMask') continue;
1343
+ if (count >= EL_DATA_MAX_ATTRS) break;
1344
+ if (!out) out = {};
1345
+
1346
+ out[key] = rdct.boundedRedact(String(attrs[i].value), EL_DATA_VALUE_MAX);
1347
+ count++;
1348
+ }
1349
+ } catch (e) {
1350
+ return out;
1351
+ }
1352
+ return out;
1353
+ }
1354
+
1355
+ var autocaptureStarted = false;
1356
+ // Set by startAutocapture: sends an open rage burst before the unload path drains the queue.
1357
+ var flushOpenSignals = noop;
1358
+
1359
+ function installRedactor(rules) {
1360
+ try {
1361
+ redactor = createRedactor(rules);
1362
+ return true;
1363
+ } catch (e) {
1364
+ logError('the redaction rules could not be compiled — autocapture stays off.');
1365
+ redactor = null;
1366
+ return false;
1367
+ }
1368
+ }
1369
+
1370
+ function pageKey(href) {
1371
+ try {
1372
+ var u = new URL(href);
1373
+ return u.pathname + u.search + (/^#!?\//.test(u.hash) ? u.hash : '');
1374
+ } catch (e) {
1375
+ return String(href);
1376
+ }
1377
+ }
1378
+
1379
+ // $nav (sequential.autocapture.ts PageviewNav): popstate is also a forward fragment navigation, so
1380
+ // only the Navigation API's navigationType names it; without it, 'unknown'.
1381
+ function navFromNavigationType(type) {
1382
+ if (type === 'traverse') return 'pop';
1383
+ if (type === 'push' || type === 'replace') return type;
1384
+ return 'unknown';
1385
+ }
1386
+
1387
+ function loadTypeOf() {
1388
+ try {
1389
+ var type = window.performance.getEntriesByType('navigation')[0].type;
1390
+ return inList(['navigate', 'reload', 'back_forward', 'prerender'], type) ? type : 'unknown';
1391
+ } catch (e) {
1392
+ return 'unknown';
1393
+ }
1394
+ }
1395
+
1396
+ var RAGE_MS = 1000;
1397
+ var RAGE_RADIUS_PX = 30;
1398
+ var RAGE_MIN_CLICKS = 3;
1399
+ var DEAD_WAIT_MS = 2500;
1400
+ var BUTTON_INPUT_TYPES = ['submit', 'button', 'image', 'reset'];
1401
+
1402
+ function isButtonLikeInput(el) {
1403
+ return tagNameOf(el) === 'input' && inList(BUTTON_INPUT_TYPES, String(el.getAttribute('type') || 'text').toLowerCase());
1404
+ }
1405
+
1406
+ // Fast clicks are normal here (a caret, a stepper, a toggle), or the page opted out.
1407
+ function rageExcluded(el) {
1408
+ if (closestMatching(el, 'textarea, select, [data-sq-no-rage]')) return true;
1409
+ var editable = closestMatching(el, '[contenteditable]');
1410
+ if (editable && editable.getAttribute('contenteditable') !== 'false') return true;
1411
+ var input = closestMatching(el, 'input');
1412
+ return !!input && !isButtonLikeInput(input);
1413
+ }
1414
+
1415
+ // The effect happens outside the page, or the control changes state with no DOM mutation.
1416
+ function deadExcluded(matched, target) {
1417
+ if (closestMatching(target, 'label')) return true;
1418
+ if (tagNameOf(matched) === 'input' && !isButtonLikeInput(matched)) return true;
1419
+ if (tagNameOf(matched) !== 'a') return false;
1420
+ if (matched.hasAttribute('download')) return true;
1421
+ if (String(matched.getAttribute('target') || '').toLowerCase() === '_blank') return true;
1422
+ return /^(mailto|tel|sms):/i.test(String(matched.getAttribute('href') || '').replace(/^\s+/, ''));
1423
+ }
1424
+
1425
+ // sequential.autocapture.ts STATE_ATTRIBUTES: a changed state attribute on the clicked element is a response.
1426
+ var STATE_ATTRIBUTES = ['aria-checked', 'aria-pressed', 'aria-expanded', 'aria-selected', 'open', 'checked', 'value'];
1427
+
1428
+ function stateChanged(r) {
1429
+ if (r.type !== 'attributes' || !r.attributeName || !inList(STATE_ATTRIBUTES, r.attributeName)) return false;
1430
+ return r.target.getAttribute(r.attributeName) !== r.oldValue;
1431
+ }
1432
+
1433
+ // The main button and no modifier key: anything else opens a menu, a tab or a selection. Not
1434
+ // isPrimary: Chromium sends `click` as a PointerEvent with isPrimary=false; only pointer events
1435
+ // check it (isPlainPointer).
1436
+ function isPlainClick(ev) {
1437
+ return ev.button === 0 && !ev.ctrlKey && !ev.metaKey && !ev.shiftKey && !ev.altKey;
1438
+ }
1439
+
1440
+ function isPlainPointer(ev) {
1441
+ return isPlainClick(ev) && ev.isPrimary !== false;
1442
+ }
1443
+
1444
+ function startAutocapture(attachUrl) {
1445
+ if (autocaptureStarted || !redactor) return;
1446
+ autocaptureStarted = true;
1447
+
1448
+ function capturePageview(url, nav) {
1449
+ var href = url || String(window.location.href);
1450
+ var pathname;
1451
+ try {
1452
+ pathname = url ? new URL(url, href).pathname : String(window.location.pathname);
1453
+ } catch (e) {
1454
+ pathname = String(window.location.pathname);
1455
+ }
1456
+ var referrer = document.referrer || undefined;
1457
+ captureInternal('$pageview', {
1458
+ $current_url: safeUrl(href, redactor),
1459
+ $pathname: safeUrl(pathname, redactor),
1460
+ $referrer: referrer !== undefined ? safeUrl(referrer, redactor) : undefined,
1461
+ $nav: nav,
1462
+ $load_type: nav === 'load' ? loadTypeOf() : undefined
1463
+ });
1464
+ }
1465
+
1466
+ // One page key (pathname + search of the RAW URL, + the fragment only for a #/ or #!/ hash
1467
+ // route) for every trigger, as in
1468
+ // sequential.autocapture.ts pageKey: a router's same-URL replaceState is not a pageview.
1469
+ var lastPageKey = null;
1470
+ var lastNavigationType;
1471
+ var navigationApi = false;
1472
+
1473
+ function checkPage(nav) {
1474
+ try {
1475
+ lastNavigationType = undefined;
1476
+ var key = pageKey(String(window.location.href));
1477
+ if (key === lastPageKey) return;
1478
+ lastPageKey = key;
1479
+ capturePageview(undefined, nav);
1480
+ } catch (e) {}
1481
+ }
1482
+
1483
+ function onPopState() {
1484
+ checkPage(navigationApi ? navFromNavigationType(lastNavigationType) : 'unknown');
1485
+ }
1486
+
1487
+ // $click's props; $rageclick and $deadclick send the same, so the detector groups all three.
1488
+ function elementProps(matched) {
1489
+ var masked = isMasked(matched);
1490
+ var raw = masked ? undefined : rawClickText(matched);
1491
+ var identity = DETECT_IDENTITY && raw !== undefined && (inAccountUi(matched) || namesPerson(raw));
1492
+ var noIds = closestMatching(matched, '[data-sq-private]') || (DETECT_IDENTITY && namesPerson(stableSelector(matched)));
1493
+ var selector = stableSelector(matched, noIds);
1494
+ return {
1495
+ $el_tag_name: tagNameOf(matched),
1496
+ $el_selector: cap(selector, EL_SELECTOR_MAX),
1497
+ $el_id: matched.id && !noIds ? cap(String(matched.id), EL_ID_MAX) : undefined,
1498
+ $el_data: masked || identity ? undefined : dataAttrs(matched, redactor),
1499
+ $el_text: raw !== undefined && !identity ? redactor.boundedRedact(raw, CLICK_TEXT_MAX) : undefined
1500
+ };
1501
+ }
1502
+
1503
+ function onClick(ev) {
1504
+ try {
1505
+ var target = ev && ev.target;
1506
+ if (!target || target.nodeType !== 1) return;
1507
+ var matched = closestMatching(target, INTERACTIVE_SELECTOR);
1508
+ if (!matched) return;
1509
+ captureInternal('$click', elementProps(matched));
1510
+ if (isPlainClick(ev) && !deadExcluded(matched, target)) openDead(matched);
1511
+ } catch (e) {}
1512
+ }
1513
+
1514
+ // ── rage and dead clicks: as in sequential.autocapture.ts (BE spec 2026-10-08, BE #432) ──
1515
+ // One MutationObserver, only while a burst or a dead window is open. No MutationObserver:
1516
+ // neither signal runs, because "no effect" cannot be told from "an effect we cannot see".
1517
+ var Observer = window.MutationObserver;
1518
+ var rage = null;
1519
+ var dead = null;
1520
+ var observer = null;
1521
+
1522
+ function syncObserver() {
1523
+ try {
1524
+ if ((rage || dead) && !observer && Observer) {
1525
+ observer = new Observer(onMutations);
1526
+ observer.observe(document, { subtree: true, childList: true, attributes: true, attributeOldValue: true, characterData: true });
1527
+ } else if (!rage && !dead && observer) {
1528
+ observer.disconnect();
1529
+ observer = null;
1530
+ }
1531
+ } catch (e) {}
1532
+ }
1533
+
1534
+ function hasSelection() {
1535
+ try {
1536
+ var sel = window.getSelection ? window.getSelection() : null;
1537
+ return !!sel && String(sel) !== '';
1538
+ } catch (e) {
1539
+ return false;
1540
+ }
1541
+ }
1542
+
1543
+ // For rage, the clicked element's own attributes and a focus on it are not a response (own).
1544
+ function effect(own) {
1545
+ if (dead) {
1546
+ clearTimeout(dead.timer);
1547
+ dead = null;
1548
+ }
1549
+ if (rage && !own) rage.responded = true;
1550
+ syncObserver();
1551
+ }
1552
+
1553
+ function onMutations(records) {
1554
+ var own = true;
1555
+ for (var i = 0; i < records.length; i++) {
1556
+ if (records[i].type !== 'attributes' || !rage || records[i].target !== rage.el || stateChanged(records[i])) own = false;
1557
+ }
1558
+ effect(own);
1559
+ }
1560
+
1561
+ function onPointerDown(ev) {
1562
+ try {
1563
+ var target = ev && ev.target;
1564
+ if (!Observer || !target || target.nodeType !== 1 || !isPlainPointer(ev) || rageExcluded(target)) return;
1565
+ var t = Date.now();
1566
+ var dx = rage ? ev.clientX - rage.x : 0;
1567
+ var dy = rage ? ev.clientY - rage.y : 0;
1568
+ if (rage && t - rage.last <= RAGE_MS && Math.sqrt(dx * dx + dy * dy) <= RAGE_RADIUS_PX) {
1569
+ clearTimeout(rage.timer);
1570
+ rage.times.push(t);
1571
+ rage.last = t;
1572
+ rage.timer = setTimeout(endRage, RAGE_MS);
1573
+ } else {
1574
+ if (rage) endRage();
1575
+ rage = {
1576
+ first: t,
1577
+ last: t,
1578
+ x: ev.clientX,
1579
+ y: ev.clientY,
1580
+ times: [t],
1581
+ el: closestMatching(target, INTERACTIVE_SELECTOR) || target,
1582
+ href: String(window.location.href),
1583
+ responded: false,
1584
+ timer: setTimeout(endRage, RAGE_MS)
1585
+ };
1586
+ }
1587
+ syncObserver();
1588
+ } catch (e) {}
1589
+ }
1590
+
1591
+ // The burst ended (1 s with no click near it): one $rageclick, dated at its first click.
1592
+ function endRage() {
1593
+ try {
1594
+ var r = rage;
1595
+ if (!r) return;
1596
+ clearTimeout(r.timer);
1597
+ rage = null;
1598
+ syncObserver();
1599
+ // Rage: RAGE_MIN_CLICKS of the burst's clicks fall within one RAGE_MS span.
1600
+ var fast = false;
1601
+ for (var i = RAGE_MIN_CLICKS - 1; i < r.times.length; i++) {
1602
+ if (r.times[i] - r.times[i - RAGE_MIN_CLICKS + 1] <= RAGE_MS) fast = true;
1603
+ }
1604
+ if (!fast || r.responded || String(window.location.href) !== r.href || hasSelection()) return;
1605
+ var props = elementProps(r.el);
1606
+ props.$click_count = r.times.length;
1607
+ captureInternal('$rageclick', props, r.first);
1608
+ } catch (e) {}
1609
+ }
1610
+
1611
+ // A disabled control sends no click, only pointer events: its dead window opens here.
1612
+ function onPointerUp(ev) {
1613
+ try {
1614
+ var target = ev && ev.target;
1615
+ if (!target || target.nodeType !== 1 || !isPlainPointer(ev)) return;
1616
+ var disabled = closestMatching(target, ':disabled');
1617
+ if (disabled) openDead(closestMatching(target, INTERACTIVE_SELECTOR) || disabled);
1618
+ } catch (e) {}
1619
+ }
1620
+
1621
+ function openDead(el) {
1622
+ if (!Observer || document.visibilityState === 'hidden') return;
1623
+ // A new click means the person did something: the old window ends with no event.
1624
+ if (dead) clearTimeout(dead.timer);
1625
+ dead = { at: Date.now(), el: el, href: String(window.location.href), timer: setTimeout(endDead, DEAD_WAIT_MS) };
1626
+ syncObserver();
1627
+ }
1628
+
1629
+ function endDead() {
1630
+ try {
1631
+ var d = dead;
1632
+ dead = null;
1633
+ syncObserver();
1634
+ if (!d || String(window.location.href) !== d.href) return;
1635
+ var props = elementProps(d.el);
1636
+ props.$wait_ms = DEAD_WAIT_MS;
1637
+ captureInternal('$deadclick', props, d.at);
1638
+ } catch (e) {}
1639
+ }
1640
+
1641
+ function onFocusIn(ev) {
1642
+ try {
1643
+ var el = dead ? dead.el : rage ? rage.el : null;
1644
+ var node = ev && ev.target;
1645
+ if (!el || !node) return;
1646
+ // Chromium focuses the button or link it clicks: only focus moving AWAY is an effect.
1647
+ if (!(el === node || el.contains(node) || (node.contains && node.contains(el)))) effect(false);
1648
+ } catch (e) {}
1649
+ }
1650
+
1651
+ function onSelectionChange() {
1652
+ // A click on text fires selectionchange with an EMPTY selection: that is not an effect.
1653
+ if ((dead || rage) && hasSelection()) effect(false);
1654
+ }
1655
+
1656
+ function onScroll() {
1657
+ if (dead || rage) effect(false);
1658
+ }
1659
+
1660
+ // The page goes away: an open dead window ends with no event (leaving IS an effect), but an
1661
+ // open rage burst is sent now (its 1 s timer would never fire). sendOnUnload calls this
1662
+ // BEFORE it drains the queue, so the burst rides in the same beacon, whatever the order of
1663
+ // the listeners.
1664
+ function onLeave() {
1665
+ try {
1666
+ if (dead) clearTimeout(dead.timer);
1667
+ dead = null;
1668
+ endRage();
1669
+ } catch (e) {}
1670
+ }
1671
+ flushOpenSignals = onLeave;
1672
+
1673
+ function onSubmit(ev) {
1674
+ try {
1675
+ var target = ev && ev.target;
1676
+ if (!target || tagNameOf(target) !== 'form') return;
1677
+
1678
+ captureInternal('$form_submit', {
1679
+ $form_selector: cap(stableSelector(target), EL_SELECTOR_MAX),
1680
+ form: target.id ? cap(String(target.id), EL_ID_MAX) : undefined
1681
+ });
1682
+ } catch (e) {}
1683
+ }
1684
+
1685
+ document.addEventListener('click', onClick, true);
1686
+ document.addEventListener('submit', onSubmit, true);
1687
+ document.addEventListener('pointerdown', onPointerDown, true);
1688
+ document.addEventListener('pointerup', onPointerUp, true);
1689
+ document.addEventListener('focusin', onFocusIn, true);
1690
+ document.addEventListener('selectionchange', onSelectionChange, true);
1691
+ document.addEventListener('scroll', onScroll, true);
1692
+ window.addEventListener('popstate', onPopState);
1693
+ try {
1694
+ var navigation = window.navigation;
1695
+ if (navigation && typeof navigation.addEventListener === 'function') {
1696
+ navigation.addEventListener('navigate', function (ev) {
1697
+ lastNavigationType = ev.navigationType;
1698
+ });
1699
+ navigationApi = true;
1700
+ }
1701
+ } catch (e) {}
1702
+
1703
+ try {
1704
+ var history = window.history;
1705
+ var originalPush = history.pushState;
1706
+ var originalReplace = history.replaceState;
1707
+ if (typeof originalPush === 'function') {
1708
+ history.pushState = function () {
1709
+ var result = originalPush.apply(history, arguments);
1710
+ checkPage('push');
1711
+ return result;
1712
+ };
1713
+ }
1714
+ if (typeof originalReplace === 'function') {
1715
+ history.replaceState = function () {
1716
+ var result = originalReplace.apply(history, arguments);
1717
+ checkPage('replace');
1718
+ return result;
1719
+ };
1720
+ }
1721
+ } catch (e) {}
1722
+
1723
+ lastPageKey = pageKey(attachUrl || String(window.location.href));
1724
+ capturePageview(attachUrl, 'load');
1725
+ }
1726
+
1727
+ // ─── the recorder (§5.6, S6) ──────────────────────────────────────────────
1728
+
1729
+ function bootRecorder(config) {
1730
+ try {
1731
+ // C1: an opted-out visitor is never recorded. recorder-boot.js reads __sq_opt as well; this skips loading it.
1732
+ if (optedOut || DISABLED) return;
1733
+ var replay = config && config.replay;
1734
+ // S6: no replay block, not enabled, or no key: load nothing.
1735
+ if (!replay || !replay.enabled || !replay.key) return;
1736
+ // The recorder tag is on the page as well: do not load it twice.
1737
+ if (window.__lxReplayStarted) return;
1738
+ // Publish before the tag goes in: the recorder reads the id once, as it boots.
1739
+ publishReplaySessionId(session.id);
1740
+ var script = document.createElement('script');
1741
+ script.src = API + '/rec/recorder.js/' + encodeURIComponent(replay.key);
1742
+ script.async = true;
1743
+ var mount = document.head || document.documentElement;
1744
+ if (mount) mount.appendChild(script);
1745
+ } catch (e) {}
1746
+ }
1747
+
1748
+ // ─── the unload path (§5.5) ───────────────────────────────────────────────
1749
+
1750
+ function sendOnUnload() {
1751
+ try {
1752
+ flushOpenSignals();
1753
+ var envelope = drain();
1754
+ if (!envelope) return;
1755
+ var nav = window.navigator;
1756
+ if (nav && nav.sendBeacon) {
1757
+ var accepted = false;
1758
+ try {
1759
+ accepted = nav.sendBeacon(envelope.url, envelope.body);
1760
+ } catch (e) {
1761
+ accepted = false;
1762
+ }
1763
+
1764
+ // A refused beacon falls back to fetch keepalive; it is never dropped.
1765
+ if (accepted) return;
1766
+ }
1767
+ try {
1768
+ window.fetch(envelope.url, {
1769
+ method: 'POST',
1770
+ headers: { 'Content-Type': 'application/json' },
1771
+ body: envelope.body,
1772
+ keepalive: true
1773
+ })['catch'](noop);
1774
+ } catch (e) {}
1775
+ } catch (e) {}
1776
+ }
1777
+
1778
+ // ─── boot ─────────────────────────────────────────────────────────────────
1779
+
1780
+ function loadConfig() {
1781
+ try {
1782
+ if (!canSend()) return Promise.reject(new Error('fetch unavailable'));
1783
+ return window
1784
+ .fetch(API + '/i/v1/config/' + encodeURIComponent(KEY), { method: 'GET' })
1785
+ .then(function (res) {
1786
+ if (!res || !res.ok) throw new Error('config ' + (res ? res.status : 'unavailable'));
1787
+ return res.json();
1788
+ });
1789
+ } catch (e) {
1790
+ return Promise.reject(e);
1791
+ }
1792
+ }
1793
+
1794
+ var api = {
1795
+ capture: capture,
1796
+ identify: identify,
1797
+ account: account,
1798
+ register: register,
1799
+ unregister: unregister,
1800
+ reset: reset,
1801
+ optOut: optOut,
1802
+ optIn: optIn,
1803
+ captureException: captureException,
1804
+ flush: flush
1805
+ };
1806
+
1807
+ // Replay the stub queue in order; an unknown method or a throwing call is skipped.
1808
+ var pending = null;
1809
+ try {
1810
+ var stub = window.sequential;
1811
+ if (stub) {
1812
+ if (stub._q && stub._q.length) pending = stub._q;
1813
+ else if (Object.prototype.toString.call(stub) === '[object Array]' && stub.length) {
1814
+ pending = stub;
1815
+ }
1816
+ }
1817
+ } catch (e) {}
1818
+
1819
+ window.sequential = api;
1820
+
1821
+ if (pending) {
1822
+ for (var q = 0; q < pending.length; q++) {
1823
+ try {
1824
+ var call = pending[q];
1825
+ var method = call && call[0];
1826
+ var fn = method && Object.prototype.hasOwnProperty.call(api, method) ? api[method] : null;
1827
+ if (typeof fn === 'function') fn.apply(api, call[1] || []);
1828
+ } catch (e) {}
1829
+ }
1830
+ }
1831
+
1832
+ // The queue has run: a visitor who is not opted out gets the ids stored.
1833
+ if (!optedOut && !DISABLED) startStorage();
1834
+
1835
+ // Runs once, and again from optIn(). An opted-out visitor sends NO config request (C1).
1836
+ // S17: autocapture waits for the config, because the redaction rules ride on it.
1837
+ var bootStarted = false;
1838
+
1839
+ function bootSequence() {
1840
+ if (bootStarted || DISABLED || optedOut) return;
1841
+ bootStarted = true;
1842
+
1843
+ var attachUrl = null;
1844
+ try {
1845
+ attachUrl = String(window.location.href);
1846
+ } catch (e) {}
1847
+
1848
+ try {
1849
+ loadConfig().then(
1850
+ function (config) {
1851
+ try {
1852
+ // Opted out while the request was in flight.
1853
+ if (optedOut) return;
1854
+ contextOn = true;
1855
+ syncContextCookie();
1856
+ if (config && config.redaction) installRedactor(config.redaction);
1857
+
1858
+ if (AUTOCAPTURE_ENABLED) startAutocapture(attachUrl);
1859
+ bootRecorder(config);
1860
+ } catch (e) {}
1861
+ },
1862
+ function () {
1863
+ // Config failed: autocapture and replay stay off for this page (fail closed).
1864
+ }
1865
+ );
1866
+ } catch (e) {}
1867
+ }
1868
+
1869
+ if (!DISABLED) {
1870
+ try {
1871
+ document.addEventListener('visibilitychange', function () {
1872
+ if (document.visibilityState === 'hidden') sendOnUnload();
1873
+ });
1874
+ window.addEventListener('pagehide', sendOnUnload);
1875
+ } catch (e) {}
1876
+
1877
+ bootSequence();
1878
+ }
1879
+ });
1880
+
1881
+ var VERSION = '1.0.1';
1882
+ var running = null;
1883
+
1884
+ function logLine(level, message) {
1885
+ try {
1886
+ if (window.console && window.console[level]) window.console[level]('[sequential] ' + message);
1887
+ } catch (e) {}
1888
+ }
1889
+
1890
+ // Server rendering (no window), or init() without its key and api: every method is present and does nothing.
1891
+ function inert() {
1892
+ function none() {}
1893
+ return {
1894
+ capture: none,
1895
+ identify: none,
1896
+ account: none,
1897
+ register: none,
1898
+ unregister: none,
1899
+ reset: none,
1900
+ optOut: none,
1901
+ optIn: none,
1902
+ captureException: none,
1903
+ flush: function () {
1904
+ return Promise.resolve();
1905
+ }
1906
+ };
1907
+ }
1908
+
1909
+ function init(options) {
1910
+ if (typeof window === 'undefined' || typeof document === 'undefined') return inert();
1911
+ if (running) {
1912
+ logLine('warn', 'init() ran before on this page; the first instance is used and these options are not read.');
1913
+ return running;
1914
+ }
1915
+ var current = window.sequential;
1916
+ if (current && typeof current.flush === 'function' && !current._q) {
1917
+ logLine('warn', 'the script tag already loaded the SDK on this page; init() uses it and does not read its options.');
1918
+ running = current;
1919
+ return running;
1920
+ }
1921
+ var o = options && typeof options === 'object' ? options : {};
1922
+ var own = function (name) {
1923
+ return Object.prototype.hasOwnProperty.call(o, name) ? o[name] : undefined;
1924
+ };
1925
+ var key = own('key');
1926
+ var api = own('api');
1927
+ if (typeof key !== 'string' || !key || typeof api !== 'string' || !api) {
1928
+ logLine('error', 'init() needs key (the sq_sequential_ key from Setup) and api (the ingest host); no events will be sent.');
1929
+ return inert();
1930
+ }
1931
+ var values = { 'data-key': key, 'data-api': api };
1932
+ if (typeof own('release') === 'string') values['data-release'] = own('release');
1933
+ if (typeof own('contextCookieDomain') === 'string') values['data-context-cookie-domain'] = own('contextCookieDomain');
1934
+ if (own('optOut') === true) values['data-opt-out'] = '';
1935
+ if (own('autocapture') === false) values['data-autocapture'] = 'false';
1936
+ if (own('identityText') === false) values['data-identity-text'] = 'off';
1937
+ boot({
1938
+ getAttribute: function (name) {
1939
+ return Object.prototype.hasOwnProperty.call(values, name) ? values[name] : null;
1940
+ },
1941
+ hasAttribute: function (name) {
1942
+ return Object.prototype.hasOwnProperty.call(values, name);
1943
+ }
1944
+ });
1945
+ running = window.sequential;
1946
+ return running;
1947
+ }
1948
+
1949
+ exports.init = init;
1950
+ exports.VERSION = VERSION;