@usesophi/sophi-web-object 1.3.1 → 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 CHANGED
@@ -1,7 +1,41 @@
1
1
  /*!
2
- * sophi-web-object v1.3.1
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 = {
@@ -299,6 +333,26 @@ function enqueue(envelope) {
299
333
  log(`Queued event: ${envelope.event_type} (queue size: ${queue.length})`);
300
334
  scheduleFlush();
301
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
+ }
302
356
  function scheduleFlush() {
303
357
  if (debounceTimer !== null)
304
358
  return;
@@ -352,6 +406,213 @@ function flushOnUnload() {
352
406
  queue.length = 0;
353
407
  }
354
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
+
355
616
  function mapPageEvent(page, sdkVersion, context) {
356
617
  if (!page.type) {
357
618
  warn('page.type is required — skipping page_view event');
@@ -364,6 +625,90 @@ function mapPageEvent(page, sdkVersion, context) {
364
625
  return Object.assign({ event_type: 'page_view', client_timestamp: Math.floor(Date.now() / 1000), sdk_version: sdkVersion, page }, context);
365
626
  }
366
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
+
367
712
  function mapUserEvent(user, page, sdkVersion, context) {
368
713
  if (!user.consent) {
369
714
  warn('user.consent is required — skipping identify event');
@@ -499,7 +844,7 @@ function mapTransactionEvent(transaction, page, sdkVersion, context) {
499
844
  }
500
845
 
501
846
  // Injected at build time via rollup-plugin-replace; falls back to package version.
502
- const SDK_VERSION = '"1.3.1"';
847
+ const SDK_VERSION = '"1.3.2"';
503
848
  // ─── Default event types per object key ──────────────────────────────────────
504
849
  const DEFAULT_EVENT_TYPE = {
505
850
  page: 'page_view',
@@ -595,7 +940,36 @@ function collectInternal(triggeredBy, obj, shouldLogCollection) {
595
940
  if (shouldLogCollection) {
596
941
  log(`Collected: ${envelope.event_type} (triggered by: ${triggeredBy})`);
597
942
  }
598
- 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));
599
973
  }
600
974
  }
601
975
  /**
@@ -703,6 +1077,7 @@ function resetTrackerState() {
703
1077
  */
704
1078
  let bootstrapGuard = false;
705
1079
  let unloadFlushRegistered = false;
1080
+ let entryClickListenerRegistered = false;
706
1081
  // ─── Private push implementation ──────────────────────────────────────────────
707
1082
  /**
708
1083
  * Execute a push() call immediately against the current sophi_object state.
@@ -728,9 +1103,10 @@ function processPush(partial) {
728
1103
  finally {
729
1104
  endInternalPushSuppression();
730
1105
  }
731
- const explicitTrigger = resolveExplicitTriggeredKey(partial);
1106
+ const eventPartial = omitEmptyBasketOnRemove(partial);
1107
+ const explicitTrigger = resolveExplicitTriggeredKey(eventPartial);
732
1108
  if (explicitTrigger) {
733
- const scopedObj = buildExplicitScopedObject(partial, window.sophi_object);
1109
+ const scopedObj = buildExplicitScopedObject(eventPartial, window.sophi_object);
734
1110
  collectExplicit(explicitTrigger, scopedObj);
735
1111
  }
736
1112
  log(`Explicit push ${String((_a = partial.event_type) !== null && _a !== void 0 ? _a : 'custom')} queued once`);
@@ -818,6 +1194,13 @@ const SophiTracker = {
818
1194
  initConfig(Object.assign(Object.assign({}, getConfig()), { userId }));
819
1195
  resetSession();
820
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
+ }
821
1204
  void getSession();
822
1205
  },
823
1206
  /**
@@ -849,6 +1232,7 @@ const SophiTracker = {
849
1232
  void (async () => {
850
1233
  try {
851
1234
  await getSession();
1235
+ persistAttribution();
852
1236
  if (window.sophi_object) {
853
1237
  collectAll(window.sophi_object);
854
1238
  }
@@ -867,13 +1251,62 @@ const SophiTracker = {
867
1251
  return;
868
1252
  setStorageConsentState(false);
869
1253
  clearSession();
1254
+ clearAttribution();
870
1255
  log('Storage consent withdrawn — Web Object is now passive.');
871
1256
  }
872
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
+ },
873
1287
  /** Expose session info for debugging */
874
1288
  getSession,
875
1289
  };
876
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
+ }
877
1310
  function resolveExplicitTriggeredKey(partial) {
878
1311
  var _a;
879
1312
  // Prefer specific commerce objects over page when multiple keys are present.
@@ -922,6 +1355,12 @@ async function bootstrap() {
922
1355
  // no session, no cookies, no events — until SophiTracker.setConsent(true).
923
1356
  const consentGranted = getConfig().storageConsent !== false;
924
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();
925
1364
  if (!consentGranted) {
926
1365
  log('Initialised in anonymous mode — no session, cookies, or events until consent is granted.');
927
1366
  // Keep the object reactive so its state is current when consent arrives.
@@ -968,6 +1407,64 @@ function registerUnloadFlush() {
968
1407
  }
969
1408
  });
970
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
+ }
971
1468
  // ─── Stub adoption ────────────────────────────────────────────────────────────
972
1469
  /**
973
1470
  * Inspect the existing window.SophiTracker value before replacing it.
@@ -1021,6 +1518,10 @@ else {
1021
1518
  function _resetBootstrapGuard() {
1022
1519
  bootstrapGuard = false;
1023
1520
  unloadFlushRegistered = false;
1521
+ if (entryClickListenerRegistered) {
1522
+ window.removeEventListener('click', handleEntryClick, true);
1523
+ entryClickListenerRegistered = false;
1524
+ }
1024
1525
  }
1025
1526
 
1026
1527
  export { bootstrap as _bootstrap, _resetBootstrapGuard, SophiTracker as default, resetTrackerState };