@usesophi/sophi-web-object 1.3.0 → 1.3.2
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/sophi.esm.js +574 -20
- package/dist/sophi.esm.js.map +1 -1
- package/dist/sophi.js +572 -44
- package/dist/sophi.js.map +1 -1
- package/dist/sophi.min.js +2 -2
- package/dist/types/attribution.d.ts +19 -0
- package/dist/types/auth.d.ts +7 -0
- package/dist/types/collector.d.ts +13 -1
- package/dist/types/iife.d.ts +13 -0
- package/dist/types/index.d.ts +14 -2
- package/dist/types/objects/entry.d.ts +16 -0
- package/dist/types/queue.d.ts +11 -2
- package/dist/types/sender.d.ts +2 -2
- package/dist/types/types.d.ts +40 -0
- package/package.json +2 -1
package/dist/sophi.esm.js
CHANGED
|
@@ -1,7 +1,41 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* sophi-web-object v1.3.
|
|
2
|
+
* sophi-web-object v1.3.2
|
|
3
3
|
* Framework-agnostic e-commerce tracking script
|
|
4
4
|
*/
|
|
5
|
+
/******************************************************************************
|
|
6
|
+
Copyright (c) Microsoft Corporation.
|
|
7
|
+
|
|
8
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
9
|
+
purpose with or without fee is hereby granted.
|
|
10
|
+
|
|
11
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
12
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
13
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
14
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
15
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
16
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
17
|
+
PERFORMANCE OF THIS SOFTWARE.
|
|
18
|
+
***************************************************************************** */
|
|
19
|
+
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
function __rest(s, e) {
|
|
23
|
+
var t = {};
|
|
24
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
|
25
|
+
t[p] = s[p];
|
|
26
|
+
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
|
27
|
+
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
|
28
|
+
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
|
29
|
+
t[p[i]] = s[p[i]];
|
|
30
|
+
}
|
|
31
|
+
return t;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
|
|
35
|
+
var e = new Error(message);
|
|
36
|
+
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
37
|
+
};
|
|
38
|
+
|
|
5
39
|
/** Sophi API origin — set via SOPHI_API_URL in .env at build time. */
|
|
6
40
|
const SOPHI_API_ORIGIN = "https://api.usesophi.com";
|
|
7
41
|
const DEFAULTS = {
|
|
@@ -109,6 +143,16 @@ async function callMergeUser(clientId, userId) {
|
|
|
109
143
|
}
|
|
110
144
|
// ─── Public API ───────────────────────────────────────────────────────────────
|
|
111
145
|
let sessionPromise = null;
|
|
146
|
+
let resolvedSession = null;
|
|
147
|
+
/**
|
|
148
|
+
* Synchronous view of the established session, or null if none has resolved
|
|
149
|
+
* yet. The unload flush runs inside a visibilitychange(hidden) handler where
|
|
150
|
+
* awaiting a promise is unreliable — the page can be torn down before the
|
|
151
|
+
* microtask runs — so it must read the session without going async.
|
|
152
|
+
*/
|
|
153
|
+
function getResolvedSession() {
|
|
154
|
+
return resolvedSession;
|
|
155
|
+
}
|
|
112
156
|
function getSession() {
|
|
113
157
|
if (sessionPromise)
|
|
114
158
|
return sessionPromise;
|
|
@@ -152,7 +196,8 @@ function getSession() {
|
|
|
152
196
|
writeCookie(ns("client-id"), clientId);
|
|
153
197
|
writeCookie(ns("external-user-id"), userId !== null && userId !== void 0 ? userId : "");
|
|
154
198
|
log("Session created and stored in cookies");
|
|
155
|
-
|
|
199
|
+
resolvedSession = { accessToken, clientId };
|
|
200
|
+
return resolvedSession;
|
|
156
201
|
})();
|
|
157
202
|
return sessionPromise;
|
|
158
203
|
}
|
|
@@ -164,10 +209,12 @@ function getSession() {
|
|
|
164
209
|
*/
|
|
165
210
|
function resetSession() {
|
|
166
211
|
sessionPromise = null;
|
|
212
|
+
resolvedSession = null;
|
|
167
213
|
log("Session promise reset (cookies preserved)");
|
|
168
214
|
}
|
|
169
215
|
function clearSession() {
|
|
170
216
|
sessionPromise = null;
|
|
217
|
+
resolvedSession = null;
|
|
171
218
|
clearCookie(ns("access-token"));
|
|
172
219
|
clearCookie(ns("client-id"));
|
|
173
220
|
clearCookie(ns("external-user-id"));
|
|
@@ -218,14 +265,41 @@ function xhrSend(url, body, headers) {
|
|
|
218
265
|
xhr.send(body);
|
|
219
266
|
});
|
|
220
267
|
}
|
|
221
|
-
function
|
|
268
|
+
function sendOnUnload(envelope, session) {
|
|
222
269
|
const { endpoint } = getConfig();
|
|
223
270
|
const url = `${endpoint}/event/v1/external-events`;
|
|
271
|
+
const body = JSON.stringify(envelope);
|
|
272
|
+
// navigator.sendBeacon cannot carry headers, and the external-events route
|
|
273
|
+
// sits behind an authorizer — an unauthenticated beacon is always rejected
|
|
274
|
+
// server-side. fetch keepalive survives page teardown like a beacon while
|
|
275
|
+
// keeping the auth headers, so it is the primary path; the beacon is only a
|
|
276
|
+
// last-resort fallback for browsers without fetch.
|
|
277
|
+
if (typeof fetch !== "undefined") {
|
|
278
|
+
try {
|
|
279
|
+
fetch(url, {
|
|
280
|
+
method: "POST",
|
|
281
|
+
keepalive: true,
|
|
282
|
+
headers: {
|
|
283
|
+
"Content-Type": "application/json",
|
|
284
|
+
Authorization: `Bearer ${session.accessToken}`,
|
|
285
|
+
"x-sophi-client-id": session.clientId,
|
|
286
|
+
},
|
|
287
|
+
body,
|
|
288
|
+
}).catch(() => {
|
|
289
|
+
// Page is going away — nothing left to retry against.
|
|
290
|
+
});
|
|
291
|
+
return true;
|
|
292
|
+
}
|
|
293
|
+
catch (_a) {
|
|
294
|
+
// keepalive rejected synchronously (e.g. body over the in-flight quota) —
|
|
295
|
+
// fall through to the beacon attempt below.
|
|
296
|
+
}
|
|
297
|
+
}
|
|
224
298
|
if (typeof navigator === "undefined" || !navigator.sendBeacon) {
|
|
225
299
|
warn("sendBeacon not available — event may be lost on page unload");
|
|
226
300
|
return false;
|
|
227
301
|
}
|
|
228
|
-
const blob = new Blob([
|
|
302
|
+
const blob = new Blob([body], { type: "application/json" });
|
|
229
303
|
return navigator.sendBeacon(url, blob);
|
|
230
304
|
}
|
|
231
305
|
|
|
@@ -259,6 +333,26 @@ function enqueue(envelope) {
|
|
|
259
333
|
log(`Queued event: ${envelope.event_type} (queue size: ${queue.length})`);
|
|
260
334
|
scheduleFlush();
|
|
261
335
|
}
|
|
336
|
+
/**
|
|
337
|
+
* Send one event right away, bypassing the debounce window. Used for Sophi
|
|
338
|
+
* button clicks, which are usually followed by a same-tab navigation.
|
|
339
|
+
*
|
|
340
|
+
* With an established session the event goes out through fetch keepalive
|
|
341
|
+
* (with auth headers), which survives the page being torn down. Without a
|
|
342
|
+
* session yet it falls back to the normal queue.
|
|
343
|
+
*/
|
|
344
|
+
function sendImmediate(envelope) {
|
|
345
|
+
if (!hasStorageConsent()) {
|
|
346
|
+
log(`Dropped event (no storage consent): ${envelope.event_type}`);
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
const session = getResolvedSession();
|
|
350
|
+
if (session && sendOnUnload(envelope, session)) {
|
|
351
|
+
log(`Sent event immediately: ${envelope.event_type}`);
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
enqueue(envelope);
|
|
355
|
+
}
|
|
262
356
|
function scheduleFlush() {
|
|
263
357
|
if (debounceTimer !== null)
|
|
264
358
|
return;
|
|
@@ -296,19 +390,229 @@ async function flush() {
|
|
|
296
390
|
}
|
|
297
391
|
flushing = false;
|
|
298
392
|
}
|
|
299
|
-
/** Flush remaining events
|
|
300
|
-
|
|
393
|
+
/** Flush remaining events before page teardown. */
|
|
394
|
+
function flushOnUnload() {
|
|
301
395
|
if (queue.length === 0)
|
|
302
396
|
return;
|
|
303
|
-
|
|
397
|
+
// Runs inside visibilitychange(hidden) — the page may be torn down before a
|
|
398
|
+
// microtask resolves, so only an already-established session is usable here.
|
|
399
|
+
// No session yet means no event ever left this page anyway.
|
|
400
|
+
const session = getResolvedSession();
|
|
304
401
|
if (!session)
|
|
305
402
|
return;
|
|
306
403
|
for (const item of queue) {
|
|
307
|
-
|
|
404
|
+
sendOnUnload(item.envelope, session);
|
|
308
405
|
}
|
|
309
406
|
queue.length = 0;
|
|
310
407
|
}
|
|
311
408
|
|
|
409
|
+
/**
|
|
410
|
+
* Campaign attribution (opt-in via `config.attribution: true`).
|
|
411
|
+
*
|
|
412
|
+
* On boot the SDK reads UTM parameters, ad click IDs and the external referrer
|
|
413
|
+
* hostname of the current page view. A page view that has any of them is a
|
|
414
|
+
* "touch". The first touch is kept for 30 days; the last touch is replaced by
|
|
415
|
+
* every new touch; direct visits and internal navigation change nothing.
|
|
416
|
+
*
|
|
417
|
+
* The value is held in memory and written to localStorage only while storage
|
|
418
|
+
* consent is granted. It is attached to every event under
|
|
419
|
+
* `page.custom._sophi.attribution` by the collector.
|
|
420
|
+
*/
|
|
421
|
+
const UTM_FIELDS = {
|
|
422
|
+
utm_source: 'source',
|
|
423
|
+
utm_medium: 'medium',
|
|
424
|
+
utm_campaign: 'campaign',
|
|
425
|
+
utm_term: 'term',
|
|
426
|
+
utm_content: 'content',
|
|
427
|
+
};
|
|
428
|
+
const CLICK_ID_SOURCES = {
|
|
429
|
+
gclid: 'google',
|
|
430
|
+
gbraid: 'google',
|
|
431
|
+
wbraid: 'google',
|
|
432
|
+
fbclid: 'facebook',
|
|
433
|
+
msclkid: 'bing',
|
|
434
|
+
ttclid: 'tiktok',
|
|
435
|
+
li_fat_id: 'linkedin',
|
|
436
|
+
};
|
|
437
|
+
const TOUCH_TTL_SECONDS = 30 * 86400;
|
|
438
|
+
const MAX_VALUE_LENGTH = 256;
|
|
439
|
+
/** Touch detected on this page view (null = direct / internal). */
|
|
440
|
+
let pageTouch = null;
|
|
441
|
+
/** Resolved attribution for this page view, attached to events. */
|
|
442
|
+
let current = null;
|
|
443
|
+
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
|
444
|
+
function isEnabled() {
|
|
445
|
+
return getConfig().attribution === true;
|
|
446
|
+
}
|
|
447
|
+
function storageKey() {
|
|
448
|
+
return `sophi-${hashKey(getConfig().apiKey)}-attribution`;
|
|
449
|
+
}
|
|
450
|
+
function clip(value) {
|
|
451
|
+
const trimmed = value === null || value === void 0 ? void 0 : value.trim();
|
|
452
|
+
return trimmed ? trimmed.slice(0, MAX_VALUE_LENGTH) : undefined;
|
|
453
|
+
}
|
|
454
|
+
function bareHost(host) {
|
|
455
|
+
return host.toLowerCase().replace(/^www\./, '');
|
|
456
|
+
}
|
|
457
|
+
function isTouch(value) {
|
|
458
|
+
return (typeof value === 'object' &&
|
|
459
|
+
value !== null &&
|
|
460
|
+
typeof value.timestamp === 'number');
|
|
461
|
+
}
|
|
462
|
+
function readStored() {
|
|
463
|
+
try {
|
|
464
|
+
const raw = localStorage.getItem(storageKey());
|
|
465
|
+
if (!raw)
|
|
466
|
+
return null;
|
|
467
|
+
const parsed = JSON.parse(raw);
|
|
468
|
+
return {
|
|
469
|
+
first: isTouch(parsed === null || parsed === void 0 ? void 0 : parsed.first) ? parsed.first : undefined,
|
|
470
|
+
last: isTouch(parsed === null || parsed === void 0 ? void 0 : parsed.last) ? parsed.last : undefined,
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
catch (_a) {
|
|
474
|
+
return null;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
function writeStored(value) {
|
|
478
|
+
try {
|
|
479
|
+
if (value) {
|
|
480
|
+
localStorage.setItem(storageKey(), JSON.stringify(value));
|
|
481
|
+
}
|
|
482
|
+
else {
|
|
483
|
+
localStorage.removeItem(storageKey());
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
catch (_a) {
|
|
487
|
+
// Storage unavailable (private mode, blocked) — keep the in-memory value.
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
function fresh(touch, now) {
|
|
491
|
+
return touch && now - touch.timestamp < TOUCH_TTL_SECONDS ? touch : undefined;
|
|
492
|
+
}
|
|
493
|
+
/** Combines stored state with this page view's touch. */
|
|
494
|
+
function mergeAttribution(stored, touch, now) {
|
|
495
|
+
let first = fresh(stored === null || stored === void 0 ? void 0 : stored.first, now);
|
|
496
|
+
let last = fresh(stored === null || stored === void 0 ? void 0 : stored.last, now);
|
|
497
|
+
if (touch) {
|
|
498
|
+
last = touch;
|
|
499
|
+
first = first !== null && first !== void 0 ? first : touch;
|
|
500
|
+
}
|
|
501
|
+
if (!first && !last)
|
|
502
|
+
return null;
|
|
503
|
+
const result = {};
|
|
504
|
+
if (first)
|
|
505
|
+
result.first = first;
|
|
506
|
+
if (last)
|
|
507
|
+
result.last = last;
|
|
508
|
+
return result;
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* Reads the touch from a page URL and referrer. Returns null for a direct
|
|
512
|
+
* visit or internal navigation. Only the referrer hostname is kept, and the
|
|
513
|
+
* landing URL keeps only its origin, path, UTM and click-ID parameters.
|
|
514
|
+
*/
|
|
515
|
+
function detectTouch(href, referrer, now) {
|
|
516
|
+
var _a, _b;
|
|
517
|
+
let url;
|
|
518
|
+
try {
|
|
519
|
+
url = new URL(href);
|
|
520
|
+
}
|
|
521
|
+
catch (_c) {
|
|
522
|
+
return null;
|
|
523
|
+
}
|
|
524
|
+
const params = url.searchParams;
|
|
525
|
+
const touch = { timestamp: now };
|
|
526
|
+
const kept = new URLSearchParams();
|
|
527
|
+
for (const [param, field] of Object.entries(UTM_FIELDS)) {
|
|
528
|
+
const value = clip(params.get(param));
|
|
529
|
+
if (value) {
|
|
530
|
+
touch[field] = value;
|
|
531
|
+
kept.set(param, value);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
for (const param of Object.keys(CLICK_ID_SOURCES)) {
|
|
535
|
+
const value = clip(params.get(param));
|
|
536
|
+
if (value) {
|
|
537
|
+
kept.set(param, value);
|
|
538
|
+
if (!touch.click_id) {
|
|
539
|
+
touch.click_id = value;
|
|
540
|
+
touch.click_id_type = param;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
let referrerHost;
|
|
545
|
+
if (referrer) {
|
|
546
|
+
try {
|
|
547
|
+
const host = new URL(referrer).hostname;
|
|
548
|
+
if (host && bareHost(host) !== bareHost(url.hostname)) {
|
|
549
|
+
referrerHost = host.toLowerCase();
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
catch (_d) {
|
|
553
|
+
// Malformed referrer — ignore.
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
const hasCampaign = kept.toString() !== '';
|
|
557
|
+
if (!hasCampaign && !referrerHost)
|
|
558
|
+
return null;
|
|
559
|
+
if (referrerHost)
|
|
560
|
+
touch.referrer = referrerHost;
|
|
561
|
+
if (!touch.source) {
|
|
562
|
+
if (touch.click_id_type) {
|
|
563
|
+
touch.source = CLICK_ID_SOURCES[touch.click_id_type];
|
|
564
|
+
}
|
|
565
|
+
else if (referrerHost) {
|
|
566
|
+
touch.source = referrerHost;
|
|
567
|
+
touch.medium = (_a = touch.medium) !== null && _a !== void 0 ? _a : 'referral';
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
const query = kept.toString();
|
|
571
|
+
touch.landing_url = (_b = clip(`${url.origin}${url.pathname}${query ? `?${query}` : ''}`)) !== null && _b !== void 0 ? _b : url.origin;
|
|
572
|
+
return touch;
|
|
573
|
+
}
|
|
574
|
+
// ─── Public API ───────────────────────────────────────────────────────────────
|
|
575
|
+
/** Called once at bootstrap. Does nothing unless `config.attribution` is true. */
|
|
576
|
+
function captureAttribution() {
|
|
577
|
+
pageTouch = null;
|
|
578
|
+
current = null;
|
|
579
|
+
if (!isEnabled())
|
|
580
|
+
return;
|
|
581
|
+
const now = Math.floor(Date.now() / 1000);
|
|
582
|
+
pageTouch = detectTouch(window.location.href, document.referrer, now);
|
|
583
|
+
if (hasStorageConsent()) {
|
|
584
|
+
current = mergeAttribution(readStored(), pageTouch, now);
|
|
585
|
+
writeStored(current);
|
|
586
|
+
}
|
|
587
|
+
else {
|
|
588
|
+
// No consent: keep this page view's touch in memory only.
|
|
589
|
+
current = mergeAttribution(null, pageTouch, now);
|
|
590
|
+
}
|
|
591
|
+
if (current)
|
|
592
|
+
log('Attribution captured', current);
|
|
593
|
+
}
|
|
594
|
+
/** Called once storage consent is granted: merges with stored state and persists. */
|
|
595
|
+
function persistAttribution() {
|
|
596
|
+
if (!isEnabled() || !hasStorageConsent())
|
|
597
|
+
return;
|
|
598
|
+
const now = Math.floor(Date.now() / 1000);
|
|
599
|
+
current = mergeAttribution(readStored(), pageTouch, now);
|
|
600
|
+
writeStored(current);
|
|
601
|
+
}
|
|
602
|
+
/** Called when storage consent is withdrawn: removes the stored value. */
|
|
603
|
+
function clearAttribution() {
|
|
604
|
+
if (!isEnabled())
|
|
605
|
+
return;
|
|
606
|
+
writeStored(null);
|
|
607
|
+
current = mergeAttribution(null, pageTouch, Math.floor(Date.now() / 1000));
|
|
608
|
+
}
|
|
609
|
+
/** Attribution to attach to events, or undefined when there is none. */
|
|
610
|
+
function getAttribution() {
|
|
611
|
+
if (!current || !isEnabled())
|
|
612
|
+
return undefined;
|
|
613
|
+
return Object.assign({}, current);
|
|
614
|
+
}
|
|
615
|
+
|
|
312
616
|
function mapPageEvent(page, sdkVersion, context) {
|
|
313
617
|
if (!page.type) {
|
|
314
618
|
warn('page.type is required — skipping page_view event');
|
|
@@ -321,6 +625,90 @@ function mapPageEvent(page, sdkVersion, context) {
|
|
|
321
625
|
return Object.assign({ event_type: 'page_view', client_timestamp: Math.floor(Date.now() / 1000), sdk_version: sdkVersion, page }, context);
|
|
322
626
|
}
|
|
323
627
|
|
|
628
|
+
const MAX_LENGTH = 64;
|
|
629
|
+
const ENTRY_TYPES = [
|
|
630
|
+
'search_bar',
|
|
631
|
+
'post_search',
|
|
632
|
+
'floating_trigger',
|
|
633
|
+
'homepage_widget',
|
|
634
|
+
'pdp',
|
|
635
|
+
'product_grid',
|
|
636
|
+
'menu',
|
|
637
|
+
'checkout',
|
|
638
|
+
];
|
|
639
|
+
/**
|
|
640
|
+
* Returns a copy of `page` with `patch` merged into `page.custom._sophi`.
|
|
641
|
+
* The integrator's own `page.custom` keys are kept, and the original object
|
|
642
|
+
* is never mutated (writing back into sophi_object.page would make the Proxy
|
|
643
|
+
* emit an extra page_view).
|
|
644
|
+
*/
|
|
645
|
+
function withSophi(page, patch) {
|
|
646
|
+
var _a;
|
|
647
|
+
const custom = (_a = page.custom) !== null && _a !== void 0 ? _a : {};
|
|
648
|
+
const existing = custom._sophi;
|
|
649
|
+
const previous = typeof existing === 'object' && existing !== null && !Array.isArray(existing)
|
|
650
|
+
? existing
|
|
651
|
+
: {};
|
|
652
|
+
return Object.assign(Object.assign({}, page), { custom: Object.assign(Object.assign({}, custom), { _sophi: Object.assign(Object.assign({}, previous), patch) }) });
|
|
653
|
+
}
|
|
654
|
+
/** Validates and normalises an entry. Returns null (after a warning) when invalid. */
|
|
655
|
+
function normalizeEntry(input) {
|
|
656
|
+
const placement = typeof (input === null || input === void 0 ? void 0 : input.placement) === 'string' ? input.placement.trim() : '';
|
|
657
|
+
if (!placement) {
|
|
658
|
+
warn('entry.placement is required — skipping entry event');
|
|
659
|
+
return null;
|
|
660
|
+
}
|
|
661
|
+
if (placement.length > MAX_LENGTH) {
|
|
662
|
+
warn(`entry.placement must be at most ${MAX_LENGTH} characters — skipping entry event`);
|
|
663
|
+
return null;
|
|
664
|
+
}
|
|
665
|
+
const entry = { placement };
|
|
666
|
+
if ((input === null || input === void 0 ? void 0 : input.group) !== undefined) {
|
|
667
|
+
const group = typeof input.group === 'string' ? input.group.trim() : '';
|
|
668
|
+
if (!group) {
|
|
669
|
+
warn('entry.group must be a non-empty string — sending without group');
|
|
670
|
+
}
|
|
671
|
+
else if (group.length > MAX_LENGTH) {
|
|
672
|
+
warn(`entry.group must be at most ${MAX_LENGTH} characters — sending without group`);
|
|
673
|
+
}
|
|
674
|
+
else {
|
|
675
|
+
entry.group = group;
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
if ((input === null || input === void 0 ? void 0 : input.type) !== undefined) {
|
|
679
|
+
if (ENTRY_TYPES.includes(input.type)) {
|
|
680
|
+
entry.type = input.type;
|
|
681
|
+
}
|
|
682
|
+
else {
|
|
683
|
+
warn(`entry.type "${String(input.type)}" is not a standard type — sending without type`);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
return entry;
|
|
687
|
+
}
|
|
688
|
+
/**
|
|
689
|
+
* Maps a Sophi button click to a `custom` event. The entry travels under
|
|
690
|
+
* `page.custom._sophi.entry`, so no change to the ingest contract is needed.
|
|
691
|
+
*/
|
|
692
|
+
function mapEntryEvent(input, page, sdkVersion) {
|
|
693
|
+
if (!page.type) {
|
|
694
|
+
warn('page.type is required — skipping entry event');
|
|
695
|
+
return null;
|
|
696
|
+
}
|
|
697
|
+
if (!page.url) {
|
|
698
|
+
warn('page.url is required — skipping entry event');
|
|
699
|
+
return null;
|
|
700
|
+
}
|
|
701
|
+
const entry = normalizeEntry(input);
|
|
702
|
+
if (!entry)
|
|
703
|
+
return null;
|
|
704
|
+
return {
|
|
705
|
+
event_type: 'custom',
|
|
706
|
+
client_timestamp: Math.floor(Date.now() / 1000),
|
|
707
|
+
sdk_version: sdkVersion,
|
|
708
|
+
page: withSophi(page, { entry }),
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
|
|
324
712
|
function mapUserEvent(user, page, sdkVersion, context) {
|
|
325
713
|
if (!user.consent) {
|
|
326
714
|
warn('user.consent is required — skipping identify event');
|
|
@@ -456,7 +844,7 @@ function mapTransactionEvent(transaction, page, sdkVersion, context) {
|
|
|
456
844
|
}
|
|
457
845
|
|
|
458
846
|
// Injected at build time via rollup-plugin-replace; falls back to package version.
|
|
459
|
-
const SDK_VERSION = '"1.3.
|
|
847
|
+
const SDK_VERSION = '"1.3.2"';
|
|
460
848
|
// ─── Default event types per object key ──────────────────────────────────────
|
|
461
849
|
const DEFAULT_EVENT_TYPE = {
|
|
462
850
|
page: 'page_view',
|
|
@@ -552,16 +940,53 @@ function collectInternal(triggeredBy, obj, shouldLogCollection) {
|
|
|
552
940
|
if (shouldLogCollection) {
|
|
553
941
|
log(`Collected: ${envelope.event_type} (triggered by: ${triggeredBy})`);
|
|
554
942
|
}
|
|
555
|
-
enqueue(envelope);
|
|
943
|
+
enqueue(withAttribution(envelope));
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
/**
|
|
947
|
+
* Attach campaign attribution under `page.custom._sophi.attribution` when it
|
|
948
|
+
* is enabled and known. Returns the envelope unchanged otherwise, so events
|
|
949
|
+
* stay byte-identical for integrations that have not opted in.
|
|
950
|
+
*/
|
|
951
|
+
function withAttribution(envelope) {
|
|
952
|
+
const attribution = getAttribution();
|
|
953
|
+
if (!attribution)
|
|
954
|
+
return envelope;
|
|
955
|
+
return Object.assign(Object.assign({}, envelope), { page: withSophi(envelope.page, { attribution }) });
|
|
956
|
+
}
|
|
957
|
+
/**
|
|
958
|
+
* Collect a Sophi button click (`SophiTracker.trackEntry` or a tagged element)
|
|
959
|
+
* and send it immediately. The click usually triggers a same-tab navigation,
|
|
960
|
+
* so it bypasses the debounced queue when a session is available.
|
|
961
|
+
*/
|
|
962
|
+
function collectEntry(entry, obj) {
|
|
963
|
+
var _a;
|
|
964
|
+
const page = obj === null || obj === void 0 ? void 0 : obj.page;
|
|
965
|
+
if (!page) {
|
|
966
|
+
warn(`sophi_object.page is required to send any event — skipping`);
|
|
967
|
+
return;
|
|
968
|
+
}
|
|
969
|
+
const envelope = mapEntryEvent(entry, page, SDK_VERSION);
|
|
970
|
+
if (envelope) {
|
|
971
|
+
log(`Collected: custom (entry: ${((_a = envelope.page.custom) === null || _a === void 0 ? void 0 : _a._sophi).entry.placement})`);
|
|
972
|
+
sendImmediate(withAttribution(envelope));
|
|
556
973
|
}
|
|
557
974
|
}
|
|
975
|
+
/**
|
|
976
|
+
* When `transaction` is among the keys to collect, omit `page`.
|
|
977
|
+
* `page` remains on the object as envelope context for purchase; it must not
|
|
978
|
+
* also emit a sibling `page_view`.
|
|
979
|
+
*/
|
|
980
|
+
function omitPageWhenTransactionPresent(keys) {
|
|
981
|
+
if (!keys.includes('transaction'))
|
|
982
|
+
return keys;
|
|
983
|
+
return keys.filter((k) => k !== 'page');
|
|
984
|
+
}
|
|
558
985
|
/** Collect all present sub-objects from the full sophi_object snapshot at load time. */
|
|
559
986
|
function collectAll(obj) {
|
|
560
|
-
const
|
|
561
|
-
for (const key of
|
|
562
|
-
|
|
563
|
-
collect(key, obj);
|
|
564
|
-
}
|
|
987
|
+
const present = ['page', 'user', 'product', 'basket', 'listing', 'transaction'].filter((key) => obj[key] !== undefined);
|
|
988
|
+
for (const key of omitPageWhenTransactionPresent(present)) {
|
|
989
|
+
collect(key, obj);
|
|
565
990
|
}
|
|
566
991
|
}
|
|
567
992
|
|
|
@@ -652,6 +1077,7 @@ function resetTrackerState() {
|
|
|
652
1077
|
*/
|
|
653
1078
|
let bootstrapGuard = false;
|
|
654
1079
|
let unloadFlushRegistered = false;
|
|
1080
|
+
let entryClickListenerRegistered = false;
|
|
655
1081
|
// ─── Private push implementation ──────────────────────────────────────────────
|
|
656
1082
|
/**
|
|
657
1083
|
* Execute a push() call immediately against the current sophi_object state.
|
|
@@ -677,9 +1103,10 @@ function processPush(partial) {
|
|
|
677
1103
|
finally {
|
|
678
1104
|
endInternalPushSuppression();
|
|
679
1105
|
}
|
|
680
|
-
const
|
|
1106
|
+
const eventPartial = omitEmptyBasketOnRemove(partial);
|
|
1107
|
+
const explicitTrigger = resolveExplicitTriggeredKey(eventPartial);
|
|
681
1108
|
if (explicitTrigger) {
|
|
682
|
-
const scopedObj = buildExplicitScopedObject(
|
|
1109
|
+
const scopedObj = buildExplicitScopedObject(eventPartial, window.sophi_object);
|
|
683
1110
|
collectExplicit(explicitTrigger, scopedObj);
|
|
684
1111
|
}
|
|
685
1112
|
log(`Explicit push ${String((_a = partial.event_type) !== null && _a !== void 0 ? _a : 'custom')} queued once`);
|
|
@@ -696,7 +1123,9 @@ function processPush(partial) {
|
|
|
696
1123
|
finally {
|
|
697
1124
|
endInternalPushSuppression();
|
|
698
1125
|
}
|
|
699
|
-
|
|
1126
|
+
// When transaction is present, skip collecting `page` so confirmation
|
|
1127
|
+
// pushes emit one purchase (page is envelope context, not page_view).
|
|
1128
|
+
const triggeredKeys = omitPageWhenTransactionPresent(watchedKeys.filter((k) => k in partial));
|
|
700
1129
|
for (const key of triggeredKeys) {
|
|
701
1130
|
collect(key, window.sophi_object);
|
|
702
1131
|
}
|
|
@@ -765,6 +1194,13 @@ const SophiTracker = {
|
|
|
765
1194
|
initConfig(Object.assign(Object.assign({}, getConfig()), { userId }));
|
|
766
1195
|
resetSession();
|
|
767
1196
|
window.sophi_object.config.userId = userId !== null && userId !== void 0 ? userId : '';
|
|
1197
|
+
// Without storage consent the SDK stays passive: no session request and no
|
|
1198
|
+
// cookies. The new userId is kept in config, so setConsent(true) creates
|
|
1199
|
+
// the session for this user (and merges a guest session if one exists).
|
|
1200
|
+
if (!hasStorageConsent()) {
|
|
1201
|
+
log('updateUser: no storage consent — session will be created when consent is granted.');
|
|
1202
|
+
return;
|
|
1203
|
+
}
|
|
768
1204
|
void getSession();
|
|
769
1205
|
},
|
|
770
1206
|
/**
|
|
@@ -796,6 +1232,7 @@ const SophiTracker = {
|
|
|
796
1232
|
void (async () => {
|
|
797
1233
|
try {
|
|
798
1234
|
await getSession();
|
|
1235
|
+
persistAttribution();
|
|
799
1236
|
if (window.sophi_object) {
|
|
800
1237
|
collectAll(window.sophi_object);
|
|
801
1238
|
}
|
|
@@ -814,13 +1251,62 @@ const SophiTracker = {
|
|
|
814
1251
|
return;
|
|
815
1252
|
setStorageConsentState(false);
|
|
816
1253
|
clearSession();
|
|
1254
|
+
clearAttribution();
|
|
817
1255
|
log('Storage consent withdrawn — Web Object is now passive.');
|
|
818
1256
|
}
|
|
819
1257
|
},
|
|
1258
|
+
/**
|
|
1259
|
+
* Record a click on a Sophi entry point (a button or link that opens Sophi).
|
|
1260
|
+
* Sent as a `custom` event with the entry under `page.custom._sophi.entry`.
|
|
1261
|
+
*
|
|
1262
|
+
* Use this for flows where no element tagged with `data-sophi-placement` is
|
|
1263
|
+
* clicked (e.g. a search submitted with Enter). Do not combine it with the
|
|
1264
|
+
* data attributes on the same button, or the click is counted twice.
|
|
1265
|
+
*
|
|
1266
|
+
* @example
|
|
1267
|
+
* SophiTracker.trackEntry({ placement: 'header_search', group: 'search', type: 'search_bar' })
|
|
1268
|
+
*/
|
|
1269
|
+
trackEntry(entry) {
|
|
1270
|
+
if (getState() === TrackerState.FAILED) {
|
|
1271
|
+
warn('SophiTracker.trackEntry() called after bootstrap failure — ignoring.');
|
|
1272
|
+
return;
|
|
1273
|
+
}
|
|
1274
|
+
try {
|
|
1275
|
+
getConfig();
|
|
1276
|
+
}
|
|
1277
|
+
catch (_a) {
|
|
1278
|
+
warn('SophiTracker.trackEntry() called before initialisation — ignoring.');
|
|
1279
|
+
return;
|
|
1280
|
+
}
|
|
1281
|
+
if (!hasStorageConsent()) {
|
|
1282
|
+
log('trackEntry ignored — no storage consent.');
|
|
1283
|
+
return;
|
|
1284
|
+
}
|
|
1285
|
+
collectEntry(entry, window.sophi_object);
|
|
1286
|
+
},
|
|
820
1287
|
/** Expose session info for debugging */
|
|
821
1288
|
getSession,
|
|
822
1289
|
};
|
|
823
1290
|
// ─── Private helpers ──────────────────────────────────────────────────────────
|
|
1291
|
+
/**
|
|
1292
|
+
* Removing the last item leaves an empty basket. The external-events contract
|
|
1293
|
+
* rejects an empty `basket.line_items` and represents an empty basket by
|
|
1294
|
+
* omitting `basket`, so `remove_from_cart` is sent by its product without the
|
|
1295
|
+
* basket. Applies only to `remove_from_cart` with a product: anywhere else an
|
|
1296
|
+
* empty basket is an integration error and still skips with a warning.
|
|
1297
|
+
* Only the event changes — `sophi_object` keeps what the integrator pushed.
|
|
1298
|
+
*/
|
|
1299
|
+
function omitEmptyBasketOnRemove(partial) {
|
|
1300
|
+
var _a;
|
|
1301
|
+
if (partial.event_type !== 'remove_from_cart' || !partial.product)
|
|
1302
|
+
return partial;
|
|
1303
|
+
const lineItems = (_a = partial.basket) === null || _a === void 0 ? void 0 : _a.line_items;
|
|
1304
|
+
if (!Array.isArray(lineItems) || lineItems.length > 0)
|
|
1305
|
+
return partial;
|
|
1306
|
+
log('remove_from_cart: basket is empty — sending the event without basket.');
|
|
1307
|
+
const { basket: _emptyBasket } = partial, rest = __rest(partial, ["basket"]);
|
|
1308
|
+
return rest;
|
|
1309
|
+
}
|
|
824
1310
|
function resolveExplicitTriggeredKey(partial) {
|
|
825
1311
|
var _a;
|
|
826
1312
|
// Prefer specific commerce objects over page when multiple keys are present.
|
|
@@ -869,6 +1355,12 @@ async function bootstrap() {
|
|
|
869
1355
|
// no session, no cookies, no events — until SophiTracker.setConsent(true).
|
|
870
1356
|
const consentGranted = getConfig().storageConsent !== false;
|
|
871
1357
|
setStorageConsentState(consentGranted);
|
|
1358
|
+
// Opt-in campaign attribution (no-op unless config.attribution is true).
|
|
1359
|
+
// Held in memory without consent; persisted only with consent.
|
|
1360
|
+
captureAttribution();
|
|
1361
|
+
// Sophi button clicks on elements tagged with data-sophi-placement. Installed
|
|
1362
|
+
// in passive mode too; trackEntry() ignores clicks until consent is granted.
|
|
1363
|
+
registerEntryClickListener();
|
|
872
1364
|
if (!consentGranted) {
|
|
873
1365
|
log('Initialised in anonymous mode — no session, cookies, or events until consent is granted.');
|
|
874
1366
|
// Keep the object reactive so its state is current when consent arrives.
|
|
@@ -901,7 +1393,7 @@ async function bootstrap() {
|
|
|
901
1393
|
// Drain pre-load and bootstrap-time push() calls in FIFO order.
|
|
902
1394
|
// collectAll events are already enqueued before any push() drain entries.
|
|
903
1395
|
drainPendingQueue();
|
|
904
|
-
// Flush remaining events on page unload (
|
|
1396
|
+
// Flush remaining events on page unload (keepalive fetch with auth headers).
|
|
905
1397
|
registerUnloadFlush();
|
|
906
1398
|
log('Ready');
|
|
907
1399
|
}
|
|
@@ -911,10 +1403,68 @@ function registerUnloadFlush() {
|
|
|
911
1403
|
unloadFlushRegistered = true;
|
|
912
1404
|
window.addEventListener('visibilitychange', () => {
|
|
913
1405
|
if (document.visibilityState === 'hidden') {
|
|
914
|
-
|
|
1406
|
+
flushOnUnload();
|
|
915
1407
|
}
|
|
916
1408
|
});
|
|
917
1409
|
}
|
|
1410
|
+
/**
|
|
1411
|
+
* One capture-phase click listener on window. Capture runs before the page's
|
|
1412
|
+
* own handlers, so a `stopPropagation()` in an integrator's onclick cannot
|
|
1413
|
+
* hide the click. The innermost tagged element wins, so a chip nested inside a
|
|
1414
|
+
* tagged banner is counted once, as the chip. Never stops or cancels the click.
|
|
1415
|
+
*/
|
|
1416
|
+
function registerEntryClickListener() {
|
|
1417
|
+
if (entryClickListenerRegistered)
|
|
1418
|
+
return;
|
|
1419
|
+
entryClickListenerRegistered = true;
|
|
1420
|
+
window.addEventListener('click', handleEntryClick, true);
|
|
1421
|
+
}
|
|
1422
|
+
function handleEntryClick(event) {
|
|
1423
|
+
try {
|
|
1424
|
+
const entry = readEntryFromEvent(event);
|
|
1425
|
+
if (entry)
|
|
1426
|
+
SophiTracker.trackEntry(entry);
|
|
1427
|
+
}
|
|
1428
|
+
catch (err) {
|
|
1429
|
+
warn('Entry click tracking failed', err);
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
/**
|
|
1433
|
+
* Finds the innermost element with `data-sophi-placement` on the event path
|
|
1434
|
+
* (composedPath also crosses open shadow roots) and reads `data-sophi-group`
|
|
1435
|
+
* and `data-sophi-type` from it or its nearest ancestor on the path.
|
|
1436
|
+
*/
|
|
1437
|
+
function readEntryFromEvent(event) {
|
|
1438
|
+
var _a;
|
|
1439
|
+
const path = [];
|
|
1440
|
+
if (typeof event.composedPath === 'function') {
|
|
1441
|
+
for (const node of event.composedPath()) {
|
|
1442
|
+
if (node instanceof Element)
|
|
1443
|
+
path.push(node);
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
else {
|
|
1447
|
+
let node = event.target instanceof Element ? event.target : null;
|
|
1448
|
+
while (node) {
|
|
1449
|
+
path.push(node);
|
|
1450
|
+
node = node.parentElement;
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
const index = path.findIndex((el) => el.hasAttribute('data-sophi-placement'));
|
|
1454
|
+
if (index === -1)
|
|
1455
|
+
return null;
|
|
1456
|
+
const inherited = (name) => { var _a, _b; return (_b = (_a = path.slice(index).find((el) => el.hasAttribute(name))) === null || _a === void 0 ? void 0 : _a.getAttribute(name)) !== null && _b !== void 0 ? _b : undefined; };
|
|
1457
|
+
const entry = {
|
|
1458
|
+
placement: (_a = path[index].getAttribute('data-sophi-placement')) !== null && _a !== void 0 ? _a : '',
|
|
1459
|
+
};
|
|
1460
|
+
const group = inherited('data-sophi-group');
|
|
1461
|
+
const type = inherited('data-sophi-type');
|
|
1462
|
+
if (group !== undefined)
|
|
1463
|
+
entry.group = group;
|
|
1464
|
+
if (type !== undefined)
|
|
1465
|
+
entry.type = type;
|
|
1466
|
+
return entry;
|
|
1467
|
+
}
|
|
918
1468
|
// ─── Stub adoption ────────────────────────────────────────────────────────────
|
|
919
1469
|
/**
|
|
920
1470
|
* Inspect the existing window.SophiTracker value before replacing it.
|
|
@@ -968,6 +1518,10 @@ else {
|
|
|
968
1518
|
function _resetBootstrapGuard() {
|
|
969
1519
|
bootstrapGuard = false;
|
|
970
1520
|
unloadFlushRegistered = false;
|
|
1521
|
+
if (entryClickListenerRegistered) {
|
|
1522
|
+
window.removeEventListener('click', handleEntryClick, true);
|
|
1523
|
+
entryClickListenerRegistered = false;
|
|
1524
|
+
}
|
|
971
1525
|
}
|
|
972
1526
|
|
|
973
1527
|
export { bootstrap as _bootstrap, _resetBootstrapGuard, SophiTracker as default, resetTrackerState };
|