@usesophi/sophi-web-object 1.3.1 → 1.3.3

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.3
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,220 @@ function flushOnUnload() {
352
406
  queue.length = 0;
353
407
  }
354
408
 
409
+ /**
410
+ * Campaign attribution. On by default; `config.attribution: false` turns it off
411
+ * and removes any stored value.
412
+ *
413
+ * On boot the SDK reads UTM parameters, ad click IDs and the external referrer
414
+ * hostname of the current page view. A page view that has any of them is a
415
+ * "touch". The first touch is kept for 30 days; the last touch is replaced by
416
+ * every new touch; direct visits and internal navigation change nothing.
417
+ *
418
+ * The value is held in memory and written to localStorage only while storage
419
+ * consent is granted. It is attached to every event under
420
+ * `page.custom._sophi.attribution` by the collector.
421
+ */
422
+ const UTM_FIELDS = {
423
+ utm_source: 'source',
424
+ utm_medium: 'medium',
425
+ utm_campaign: 'campaign',
426
+ utm_term: 'term',
427
+ utm_content: 'content',
428
+ };
429
+ const CLICK_ID_SOURCES = {
430
+ gclid: 'google',
431
+ gbraid: 'google',
432
+ wbraid: 'google',
433
+ fbclid: 'facebook',
434
+ msclkid: 'bing',
435
+ ttclid: 'tiktok',
436
+ li_fat_id: 'linkedin',
437
+ };
438
+ const TOUCH_TTL_SECONDS = 30 * 86400;
439
+ const MAX_VALUE_LENGTH = 256;
440
+ /** Touch detected on this page view (null = direct / internal). */
441
+ let pageTouch = null;
442
+ /** Resolved attribution for this page view, attached to events. */
443
+ let current = null;
444
+ // ─── Helpers ──────────────────────────────────────────────────────────────────
445
+ /** On unless the integrator sets `config.attribution: false` (default on since 1.3.3). */
446
+ function isEnabled() {
447
+ return getConfig().attribution !== false;
448
+ }
449
+ function storageKey() {
450
+ return `sophi-${hashKey(getConfig().apiKey)}-attribution`;
451
+ }
452
+ function clip(value) {
453
+ const trimmed = value === null || value === void 0 ? void 0 : value.trim();
454
+ return trimmed ? trimmed.slice(0, MAX_VALUE_LENGTH) : undefined;
455
+ }
456
+ function bareHost(host) {
457
+ return host.toLowerCase().replace(/^www\./, '');
458
+ }
459
+ function isTouch(value) {
460
+ return (typeof value === 'object' &&
461
+ value !== null &&
462
+ typeof value.timestamp === 'number');
463
+ }
464
+ function readStored() {
465
+ try {
466
+ const raw = localStorage.getItem(storageKey());
467
+ if (!raw)
468
+ return null;
469
+ const parsed = JSON.parse(raw);
470
+ return {
471
+ first: isTouch(parsed === null || parsed === void 0 ? void 0 : parsed.first) ? parsed.first : undefined,
472
+ last: isTouch(parsed === null || parsed === void 0 ? void 0 : parsed.last) ? parsed.last : undefined,
473
+ };
474
+ }
475
+ catch (_a) {
476
+ return null;
477
+ }
478
+ }
479
+ function writeStored(value) {
480
+ try {
481
+ if (value) {
482
+ localStorage.setItem(storageKey(), JSON.stringify(value));
483
+ }
484
+ else {
485
+ localStorage.removeItem(storageKey());
486
+ }
487
+ }
488
+ catch (_a) {
489
+ // Storage unavailable (private mode, blocked) — keep the in-memory value.
490
+ }
491
+ }
492
+ function fresh(touch, now) {
493
+ return touch && now - touch.timestamp < TOUCH_TTL_SECONDS ? touch : undefined;
494
+ }
495
+ /** Combines stored state with this page view's touch. */
496
+ function mergeAttribution(stored, touch, now) {
497
+ let first = fresh(stored === null || stored === void 0 ? void 0 : stored.first, now);
498
+ let last = fresh(stored === null || stored === void 0 ? void 0 : stored.last, now);
499
+ if (touch) {
500
+ last = touch;
501
+ first = first !== null && first !== void 0 ? first : touch;
502
+ }
503
+ if (!first && !last)
504
+ return null;
505
+ const result = {};
506
+ if (first)
507
+ result.first = first;
508
+ if (last)
509
+ result.last = last;
510
+ return result;
511
+ }
512
+ /**
513
+ * Reads the touch from a page URL and referrer. Returns null for a direct
514
+ * visit or internal navigation. Only the referrer hostname is kept, and the
515
+ * landing URL keeps only its origin, path, UTM and click-ID parameters.
516
+ */
517
+ function detectTouch(href, referrer, now) {
518
+ var _a, _b;
519
+ let url;
520
+ try {
521
+ url = new URL(href);
522
+ }
523
+ catch (_c) {
524
+ return null;
525
+ }
526
+ const params = url.searchParams;
527
+ const touch = { timestamp: now };
528
+ const kept = new URLSearchParams();
529
+ for (const [param, field] of Object.entries(UTM_FIELDS)) {
530
+ const value = clip(params.get(param));
531
+ if (value) {
532
+ touch[field] = value;
533
+ kept.set(param, value);
534
+ }
535
+ }
536
+ for (const param of Object.keys(CLICK_ID_SOURCES)) {
537
+ const value = clip(params.get(param));
538
+ if (value) {
539
+ kept.set(param, value);
540
+ if (!touch.click_id) {
541
+ touch.click_id = value;
542
+ touch.click_id_type = param;
543
+ }
544
+ }
545
+ }
546
+ let referrerHost;
547
+ if (referrer) {
548
+ try {
549
+ const host = new URL(referrer).hostname;
550
+ if (host && bareHost(host) !== bareHost(url.hostname)) {
551
+ referrerHost = host.toLowerCase();
552
+ }
553
+ }
554
+ catch (_d) {
555
+ // Malformed referrer — ignore.
556
+ }
557
+ }
558
+ const hasCampaign = kept.toString() !== '';
559
+ if (!hasCampaign && !referrerHost)
560
+ return null;
561
+ if (referrerHost)
562
+ touch.referrer = referrerHost;
563
+ if (!touch.source) {
564
+ if (touch.click_id_type) {
565
+ touch.source = CLICK_ID_SOURCES[touch.click_id_type];
566
+ }
567
+ else if (referrerHost) {
568
+ touch.source = referrerHost;
569
+ touch.medium = (_a = touch.medium) !== null && _a !== void 0 ? _a : 'referral';
570
+ }
571
+ }
572
+ const query = kept.toString();
573
+ touch.landing_url = (_b = clip(`${url.origin}${url.pathname}${query ? `?${query}` : ''}`)) !== null && _b !== void 0 ? _b : url.origin;
574
+ return touch;
575
+ }
576
+ // ─── Public API ───────────────────────────────────────────────────────────────
577
+ /**
578
+ * Called once at bootstrap. With `config.attribution: false` it captures
579
+ * nothing and removes a value stored while attribution was on.
580
+ */
581
+ function captureAttribution() {
582
+ pageTouch = null;
583
+ current = null;
584
+ if (!isEnabled()) {
585
+ writeStored(null);
586
+ return;
587
+ }
588
+ const now = Math.floor(Date.now() / 1000);
589
+ pageTouch = detectTouch(window.location.href, document.referrer, now);
590
+ if (hasStorageConsent()) {
591
+ current = mergeAttribution(readStored(), pageTouch, now);
592
+ writeStored(current);
593
+ }
594
+ else {
595
+ // No consent: keep this page view's touch in memory only.
596
+ current = mergeAttribution(null, pageTouch, now);
597
+ }
598
+ if (current)
599
+ log('Attribution captured', current);
600
+ }
601
+ /** Called once storage consent is granted: merges with stored state and persists. */
602
+ function persistAttribution() {
603
+ if (!isEnabled() || !hasStorageConsent())
604
+ return;
605
+ const now = Math.floor(Date.now() / 1000);
606
+ current = mergeAttribution(readStored(), pageTouch, now);
607
+ writeStored(current);
608
+ }
609
+ /** Called when storage consent is withdrawn: removes the stored value. */
610
+ function clearAttribution() {
611
+ writeStored(null);
612
+ if (!isEnabled())
613
+ return;
614
+ current = mergeAttribution(null, pageTouch, Math.floor(Date.now() / 1000));
615
+ }
616
+ /** Attribution to attach to events, or undefined when there is none. */
617
+ function getAttribution() {
618
+ if (!current || !isEnabled())
619
+ return undefined;
620
+ return Object.assign({}, current);
621
+ }
622
+
355
623
  function mapPageEvent(page, sdkVersion, context) {
356
624
  if (!page.type) {
357
625
  warn('page.type is required — skipping page_view event');
@@ -364,6 +632,90 @@ function mapPageEvent(page, sdkVersion, context) {
364
632
  return Object.assign({ event_type: 'page_view', client_timestamp: Math.floor(Date.now() / 1000), sdk_version: sdkVersion, page }, context);
365
633
  }
366
634
 
635
+ const MAX_LENGTH = 64;
636
+ const ENTRY_TYPES = [
637
+ 'search_bar',
638
+ 'post_search',
639
+ 'floating_trigger',
640
+ 'homepage_widget',
641
+ 'pdp',
642
+ 'product_grid',
643
+ 'menu',
644
+ 'checkout',
645
+ ];
646
+ /**
647
+ * Returns a copy of `page` with `patch` merged into `page.custom._sophi`.
648
+ * The integrator's own `page.custom` keys are kept, and the original object
649
+ * is never mutated (writing back into sophi_object.page would make the Proxy
650
+ * emit an extra page_view).
651
+ */
652
+ function withSophi(page, patch) {
653
+ var _a;
654
+ const custom = (_a = page.custom) !== null && _a !== void 0 ? _a : {};
655
+ const existing = custom._sophi;
656
+ const previous = typeof existing === 'object' && existing !== null && !Array.isArray(existing)
657
+ ? existing
658
+ : {};
659
+ return Object.assign(Object.assign({}, page), { custom: Object.assign(Object.assign({}, custom), { _sophi: Object.assign(Object.assign({}, previous), patch) }) });
660
+ }
661
+ /** Validates and normalises an entry. Returns null (after a warning) when invalid. */
662
+ function normalizeEntry(input) {
663
+ const placement = typeof (input === null || input === void 0 ? void 0 : input.placement) === 'string' ? input.placement.trim() : '';
664
+ if (!placement) {
665
+ warn('entry.placement is required — skipping entry event');
666
+ return null;
667
+ }
668
+ if (placement.length > MAX_LENGTH) {
669
+ warn(`entry.placement must be at most ${MAX_LENGTH} characters — skipping entry event`);
670
+ return null;
671
+ }
672
+ const entry = { placement };
673
+ if ((input === null || input === void 0 ? void 0 : input.group) !== undefined) {
674
+ const group = typeof input.group === 'string' ? input.group.trim() : '';
675
+ if (!group) {
676
+ warn('entry.group must be a non-empty string — sending without group');
677
+ }
678
+ else if (group.length > MAX_LENGTH) {
679
+ warn(`entry.group must be at most ${MAX_LENGTH} characters — sending without group`);
680
+ }
681
+ else {
682
+ entry.group = group;
683
+ }
684
+ }
685
+ if ((input === null || input === void 0 ? void 0 : input.type) !== undefined) {
686
+ if (ENTRY_TYPES.includes(input.type)) {
687
+ entry.type = input.type;
688
+ }
689
+ else {
690
+ warn(`entry.type "${String(input.type)}" is not a standard type — sending without type`);
691
+ }
692
+ }
693
+ return entry;
694
+ }
695
+ /**
696
+ * Maps a Sophi button click to a `custom` event. The entry travels under
697
+ * `page.custom._sophi.entry`, so no change to the ingest contract is needed.
698
+ */
699
+ function mapEntryEvent(input, page, sdkVersion) {
700
+ if (!page.type) {
701
+ warn('page.type is required — skipping entry event');
702
+ return null;
703
+ }
704
+ if (!page.url) {
705
+ warn('page.url is required — skipping entry event');
706
+ return null;
707
+ }
708
+ const entry = normalizeEntry(input);
709
+ if (!entry)
710
+ return null;
711
+ return {
712
+ event_type: 'custom',
713
+ client_timestamp: Math.floor(Date.now() / 1000),
714
+ sdk_version: sdkVersion,
715
+ page: withSophi(page, { entry }),
716
+ };
717
+ }
718
+
367
719
  function mapUserEvent(user, page, sdkVersion, context) {
368
720
  if (!user.consent) {
369
721
  warn('user.consent is required — skipping identify event');
@@ -499,7 +851,7 @@ function mapTransactionEvent(transaction, page, sdkVersion, context) {
499
851
  }
500
852
 
501
853
  // Injected at build time via rollup-plugin-replace; falls back to package version.
502
- const SDK_VERSION = '"1.3.1"';
854
+ const SDK_VERSION = '"1.3.3"';
503
855
  // ─── Default event types per object key ──────────────────────────────────────
504
856
  const DEFAULT_EVENT_TYPE = {
505
857
  page: 'page_view',
@@ -595,7 +947,36 @@ function collectInternal(triggeredBy, obj, shouldLogCollection) {
595
947
  if (shouldLogCollection) {
596
948
  log(`Collected: ${envelope.event_type} (triggered by: ${triggeredBy})`);
597
949
  }
598
- enqueue(envelope);
950
+ enqueue(withAttribution(envelope));
951
+ }
952
+ }
953
+ /**
954
+ * Attach campaign attribution under `page.custom._sophi.attribution` when it
955
+ * is enabled and known. Returns the envelope unchanged otherwise, so events
956
+ * stay byte-identical for integrations that have not opted in.
957
+ */
958
+ function withAttribution(envelope) {
959
+ const attribution = getAttribution();
960
+ if (!attribution)
961
+ return envelope;
962
+ return Object.assign(Object.assign({}, envelope), { page: withSophi(envelope.page, { attribution }) });
963
+ }
964
+ /**
965
+ * Collect a Sophi button click (`SophiTracker.trackEntry` or a tagged element)
966
+ * and send it immediately. The click usually triggers a same-tab navigation,
967
+ * so it bypasses the debounced queue when a session is available.
968
+ */
969
+ function collectEntry(entry, obj) {
970
+ var _a;
971
+ const page = obj === null || obj === void 0 ? void 0 : obj.page;
972
+ if (!page) {
973
+ warn(`sophi_object.page is required to send any event — skipping`);
974
+ return;
975
+ }
976
+ const envelope = mapEntryEvent(entry, page, SDK_VERSION);
977
+ if (envelope) {
978
+ log(`Collected: custom (entry: ${((_a = envelope.page.custom) === null || _a === void 0 ? void 0 : _a._sophi).entry.placement})`);
979
+ sendImmediate(withAttribution(envelope));
599
980
  }
600
981
  }
601
982
  /**
@@ -703,6 +1084,7 @@ function resetTrackerState() {
703
1084
  */
704
1085
  let bootstrapGuard = false;
705
1086
  let unloadFlushRegistered = false;
1087
+ let entryClickListenerRegistered = false;
706
1088
  // ─── Private push implementation ──────────────────────────────────────────────
707
1089
  /**
708
1090
  * Execute a push() call immediately against the current sophi_object state.
@@ -728,9 +1110,10 @@ function processPush(partial) {
728
1110
  finally {
729
1111
  endInternalPushSuppression();
730
1112
  }
731
- const explicitTrigger = resolveExplicitTriggeredKey(partial);
1113
+ const eventPartial = omitEmptyBasketOnRemove(partial);
1114
+ const explicitTrigger = resolveExplicitTriggeredKey(eventPartial);
732
1115
  if (explicitTrigger) {
733
- const scopedObj = buildExplicitScopedObject(partial, window.sophi_object);
1116
+ const scopedObj = buildExplicitScopedObject(eventPartial, window.sophi_object);
734
1117
  collectExplicit(explicitTrigger, scopedObj);
735
1118
  }
736
1119
  log(`Explicit push ${String((_a = partial.event_type) !== null && _a !== void 0 ? _a : 'custom')} queued once`);
@@ -818,6 +1201,13 @@ const SophiTracker = {
818
1201
  initConfig(Object.assign(Object.assign({}, getConfig()), { userId }));
819
1202
  resetSession();
820
1203
  window.sophi_object.config.userId = userId !== null && userId !== void 0 ? userId : '';
1204
+ // Without storage consent the SDK stays passive: no session request and no
1205
+ // cookies. The new userId is kept in config, so setConsent(true) creates
1206
+ // the session for this user (and merges a guest session if one exists).
1207
+ if (!hasStorageConsent()) {
1208
+ log('updateUser: no storage consent — session will be created when consent is granted.');
1209
+ return;
1210
+ }
821
1211
  void getSession();
822
1212
  },
823
1213
  /**
@@ -849,6 +1239,7 @@ const SophiTracker = {
849
1239
  void (async () => {
850
1240
  try {
851
1241
  await getSession();
1242
+ persistAttribution();
852
1243
  if (window.sophi_object) {
853
1244
  collectAll(window.sophi_object);
854
1245
  }
@@ -867,13 +1258,62 @@ const SophiTracker = {
867
1258
  return;
868
1259
  setStorageConsentState(false);
869
1260
  clearSession();
1261
+ clearAttribution();
870
1262
  log('Storage consent withdrawn — Web Object is now passive.');
871
1263
  }
872
1264
  },
1265
+ /**
1266
+ * Record a click on a Sophi entry point (a button or link that opens Sophi).
1267
+ * Sent as a `custom` event with the entry under `page.custom._sophi.entry`.
1268
+ *
1269
+ * Use this for flows where no element tagged with `data-sophi-placement` is
1270
+ * clicked (e.g. a search submitted with Enter). Do not combine it with the
1271
+ * data attributes on the same button, or the click is counted twice.
1272
+ *
1273
+ * @example
1274
+ * SophiTracker.trackEntry({ placement: 'header_search', group: 'search', type: 'search_bar' })
1275
+ */
1276
+ trackEntry(entry) {
1277
+ if (getState() === TrackerState.FAILED) {
1278
+ warn('SophiTracker.trackEntry() called after bootstrap failure — ignoring.');
1279
+ return;
1280
+ }
1281
+ try {
1282
+ getConfig();
1283
+ }
1284
+ catch (_a) {
1285
+ warn('SophiTracker.trackEntry() called before initialisation — ignoring.');
1286
+ return;
1287
+ }
1288
+ if (!hasStorageConsent()) {
1289
+ log('trackEntry ignored — no storage consent.');
1290
+ return;
1291
+ }
1292
+ collectEntry(entry, window.sophi_object);
1293
+ },
873
1294
  /** Expose session info for debugging */
874
1295
  getSession,
875
1296
  };
876
1297
  // ─── Private helpers ──────────────────────────────────────────────────────────
1298
+ /**
1299
+ * Removing the last item leaves an empty basket. The external-events contract
1300
+ * rejects an empty `basket.line_items` and represents an empty basket by
1301
+ * omitting `basket`, so `remove_from_cart` is sent by its product without the
1302
+ * basket. Applies only to `remove_from_cart` with a product: anywhere else an
1303
+ * empty basket is an integration error and still skips with a warning.
1304
+ * Only the event changes — `sophi_object` keeps what the integrator pushed.
1305
+ */
1306
+ function omitEmptyBasketOnRemove(partial) {
1307
+ var _a;
1308
+ if (partial.event_type !== 'remove_from_cart' || !partial.product)
1309
+ return partial;
1310
+ const lineItems = (_a = partial.basket) === null || _a === void 0 ? void 0 : _a.line_items;
1311
+ if (!Array.isArray(lineItems) || lineItems.length > 0)
1312
+ return partial;
1313
+ log('remove_from_cart: basket is empty — sending the event without basket.');
1314
+ const { basket: _emptyBasket } = partial, rest = __rest(partial, ["basket"]);
1315
+ return rest;
1316
+ }
877
1317
  function resolveExplicitTriggeredKey(partial) {
878
1318
  var _a;
879
1319
  // Prefer specific commerce objects over page when multiple keys are present.
@@ -922,6 +1362,12 @@ async function bootstrap() {
922
1362
  // no session, no cookies, no events — until SophiTracker.setConsent(true).
923
1363
  const consentGranted = getConfig().storageConsent !== false;
924
1364
  setStorageConsentState(consentGranted);
1365
+ // Campaign attribution: on unless config.attribution is false.
1366
+ // Held in memory without consent; persisted only with consent.
1367
+ captureAttribution();
1368
+ // Sophi button clicks on elements tagged with data-sophi-placement. Installed
1369
+ // in passive mode too; trackEntry() ignores clicks until consent is granted.
1370
+ registerEntryClickListener();
925
1371
  if (!consentGranted) {
926
1372
  log('Initialised in anonymous mode — no session, cookies, or events until consent is granted.');
927
1373
  // Keep the object reactive so its state is current when consent arrives.
@@ -968,6 +1414,64 @@ function registerUnloadFlush() {
968
1414
  }
969
1415
  });
970
1416
  }
1417
+ /**
1418
+ * One capture-phase click listener on window. Capture runs before the page's
1419
+ * own handlers, so a `stopPropagation()` in an integrator's onclick cannot
1420
+ * hide the click. The innermost tagged element wins, so a chip nested inside a
1421
+ * tagged banner is counted once, as the chip. Never stops or cancels the click.
1422
+ */
1423
+ function registerEntryClickListener() {
1424
+ if (entryClickListenerRegistered)
1425
+ return;
1426
+ entryClickListenerRegistered = true;
1427
+ window.addEventListener('click', handleEntryClick, true);
1428
+ }
1429
+ function handleEntryClick(event) {
1430
+ try {
1431
+ const entry = readEntryFromEvent(event);
1432
+ if (entry)
1433
+ SophiTracker.trackEntry(entry);
1434
+ }
1435
+ catch (err) {
1436
+ warn('Entry click tracking failed', err);
1437
+ }
1438
+ }
1439
+ /**
1440
+ * Finds the innermost element with `data-sophi-placement` on the event path
1441
+ * (composedPath also crosses open shadow roots) and reads `data-sophi-group`
1442
+ * and `data-sophi-type` from it or its nearest ancestor on the path.
1443
+ */
1444
+ function readEntryFromEvent(event) {
1445
+ var _a;
1446
+ const path = [];
1447
+ if (typeof event.composedPath === 'function') {
1448
+ for (const node of event.composedPath()) {
1449
+ if (node instanceof Element)
1450
+ path.push(node);
1451
+ }
1452
+ }
1453
+ else {
1454
+ let node = event.target instanceof Element ? event.target : null;
1455
+ while (node) {
1456
+ path.push(node);
1457
+ node = node.parentElement;
1458
+ }
1459
+ }
1460
+ const index = path.findIndex((el) => el.hasAttribute('data-sophi-placement'));
1461
+ if (index === -1)
1462
+ return null;
1463
+ 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; };
1464
+ const entry = {
1465
+ placement: (_a = path[index].getAttribute('data-sophi-placement')) !== null && _a !== void 0 ? _a : '',
1466
+ };
1467
+ const group = inherited('data-sophi-group');
1468
+ const type = inherited('data-sophi-type');
1469
+ if (group !== undefined)
1470
+ entry.group = group;
1471
+ if (type !== undefined)
1472
+ entry.type = type;
1473
+ return entry;
1474
+ }
971
1475
  // ─── Stub adoption ────────────────────────────────────────────────────────────
972
1476
  /**
973
1477
  * Inspect the existing window.SophiTracker value before replacing it.
@@ -1021,6 +1525,10 @@ else {
1021
1525
  function _resetBootstrapGuard() {
1022
1526
  bootstrapGuard = false;
1023
1527
  unloadFlushRegistered = false;
1528
+ if (entryClickListenerRegistered) {
1529
+ window.removeEventListener('click', handleEntryClick, true);
1530
+ entryClickListenerRegistered = false;
1531
+ }
1024
1532
  }
1025
1533
 
1026
1534
  export { bootstrap as _bootstrap, _resetBootstrapGuard, SophiTracker as default, resetTrackerState };