@joryio/web-sdk 1.4.0-beta.8 → 1.4.0-beta.9

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.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Joryio Web SDK v1.4.0-beta.8
2
+ * Joryio Web SDK v1.4.0-beta.9
3
3
  * (c) 2026 Joryio. All rights reserved.
4
4
  * @license Commercial - see https://github.com/joryio/joryio-web-sdk/blob/main/LICENSE
5
5
  */
@@ -29,7 +29,7 @@ function bucketHash(input) {
29
29
  return fmix32(hash >>> 0);
30
30
  }
31
31
 
32
- const SDK_VERSION = '1.4.0-beta.8';
32
+ const SDK_VERSION = '1.4.0-beta.9';
33
33
  const SDK_PLATFORM_HEADER = 'X-Joryio-SDK';
34
34
  const SDK_VERSION_HEADER = 'X-Joryio-SDK-Version';
35
35
  const SDK_PLATFORM = 'web';
@@ -313,6 +313,15 @@ function readPath(root, path) {
313
313
  }
314
314
  return cur;
315
315
  }
316
+ const TOUCH_EXIT_INTENT = {
317
+ armPercent: 25,
318
+ armPx: 400,
319
+ upPx: 120,
320
+ windowMs: 300,
321
+ minMs: 3000,
322
+ sampleMs: 50,
323
+ };
324
+ const TOUCH_PRIMARY_QUERY = '(hover: none) and (pointer: coarse)';
316
325
  class PageContextTracker {
317
326
  constructor(options = {}) {
318
327
  this.options = options;
@@ -323,6 +332,10 @@ class PageContextTracker {
323
332
  this.visibleMs = 0;
324
333
  this.visibleSince = null;
325
334
  this.exitFired = false;
335
+ this.pageStartedAt = Date.now();
336
+ this.maxScrollY = 0;
337
+ this.scrollSamples = [];
338
+ this.touchQuery = null;
326
339
  this.timer = null;
327
340
  this.undo = [];
328
341
  this.started = false;
@@ -431,7 +444,17 @@ class PageContextTracker {
431
444
  this.undo.push(() => target.removeEventListener(ev, fn, opts));
432
445
  };
433
446
  on(window, 'popstate', () => this.checkRoute());
434
- on(window, 'scroll', () => this.measureScroll(), { passive: true });
447
+ this.pageStartedAt = Date.now();
448
+ try {
449
+ this.touchQuery = typeof window.matchMedia === 'function' ? window.matchMedia(TOUCH_PRIMARY_QUERY) : null;
450
+ }
451
+ catch (_a) {
452
+ this.touchQuery = null;
453
+ }
454
+ on(window, 'scroll', () => {
455
+ this.measureScroll();
456
+ this.touchExitIntent();
457
+ }, { passive: true });
435
458
  on(document, 'mouseout', (e) => {
436
459
  if (this.exitFired || e.relatedTarget || e.toElement)
437
460
  return;
@@ -462,6 +485,8 @@ class PageContextTracker {
462
485
  }
463
486
  }
464
487
  this.listeners.clear();
488
+ this.scrollSamples = [];
489
+ this.touchQuery = null;
465
490
  this.started = false;
466
491
  }
467
492
  checkRoute() {
@@ -473,6 +498,9 @@ class PageContextTracker {
473
498
  this.visibleMs = 0;
474
499
  this.visibleSince = typeof document !== 'undefined' && document.visibilityState === 'hidden' ? null : Date.now();
475
500
  this.exitFired = false;
501
+ this.pageStartedAt = Date.now();
502
+ this.maxScrollY = 0;
503
+ this.scrollSamples = [];
476
504
  this.emit({ type: 'page_change', url });
477
505
  }
478
506
  patchHistory() {
@@ -514,6 +542,38 @@ class PageContextTracker {
514
542
  catch (_b) {
515
543
  }
516
544
  }
545
+ touchExitIntent() {
546
+ var _a;
547
+ if (this.exitFired || !((_a = this.touchQuery) === null || _a === void 0 ? void 0 : _a.matches))
548
+ return;
549
+ try {
550
+ const c = TOUCH_EXIT_INTENT;
551
+ const now = Date.now();
552
+ const last = this.scrollSamples[this.scrollSamples.length - 1];
553
+ if (last && now - last.t < c.sampleMs)
554
+ return;
555
+ const y = Math.max(0, window.scrollY || document.documentElement.scrollTop || 0);
556
+ if (y > this.maxScrollY)
557
+ this.maxScrollY = y;
558
+ this.scrollSamples = this.scrollSamples.filter((s) => now - s.t <= c.windowMs);
559
+ this.scrollSamples.push({ y, t: now });
560
+ if (now - this.pageStartedAt < c.minMs)
561
+ return;
562
+ if (this.maxScrollY < c.armPx && this.maxScrollPercent < c.armPercent)
563
+ return;
564
+ let peak = y;
565
+ for (const s of this.scrollSamples)
566
+ if (s.y > peak)
567
+ peak = s.y;
568
+ if (peak - y >= c.upPx) {
569
+ this.exitFired = true;
570
+ this.scrollSamples = [];
571
+ this.emit({ type: 'exit_intent' });
572
+ }
573
+ }
574
+ catch (_b) {
575
+ }
576
+ }
517
577
  visibilityChanged() {
518
578
  if (document.visibilityState === 'hidden') {
519
579
  if (this.visibleSince !== null)
@@ -550,10 +610,108 @@ function pageTriggerMet(trigger, signal, progress) {
550
610
  }
551
611
  }
552
612
 
613
+ const SHOW_WHEN_KINDS = ['load', 'seconds', 'scroll', 'exit', 'event'];
614
+ const intIn = (v, min, max) => typeof v === 'number' && Number.isInteger(v) && v >= min && v <= max;
615
+ function parseShowWhen(raw) {
616
+ if (raw === undefined || raw === null)
617
+ return { kind: 'load' };
618
+ if (typeof raw !== 'object')
619
+ return null;
620
+ const o = raw;
621
+ switch (o.kind) {
622
+ case 'load':
623
+ case 'exit':
624
+ return { kind: o.kind };
625
+ case 'seconds':
626
+ return intIn(o.seconds, 1, 3600) ? { kind: 'seconds', seconds: o.seconds } : null;
627
+ case 'scroll':
628
+ return intIn(o.percent, 1, 100) ? { kind: 'scroll', percent: o.percent } : null;
629
+ case 'event': {
630
+ const e = typeof o.event === 'string' ? o.event.trim() : '';
631
+ return e && e.length <= 255 ? { kind: 'event', event: e } : null;
632
+ }
633
+ default:
634
+ return null;
635
+ }
636
+ }
637
+ const isDeferred = (raw) => { var _a; return ((_a = parseShowWhen(raw)) === null || _a === void 0 ? void 0 : _a.kind) !== 'load'; };
638
+ function eventNames(raw, max = 50) {
639
+ return Array.isArray(raw) ? raw.filter((e) => typeof e === 'string' && e.length > 0 && e.length <= 255).slice(0, max) : [];
640
+ }
641
+ const MAX_EVENTS = 200;
642
+ class ShowWhenMoments {
643
+ constructor(page, sessionId, sdkKey) {
644
+ this.page = page;
645
+ this.sessionId = sessionId;
646
+ this.events = new Set();
647
+ this.sid = undefined;
648
+ this.listeners = new Set();
649
+ this.store = `jry_show_when_${bucketHash(sdkKey).toString(36)}`;
650
+ this.off = page ? page.onSignal(() => this.emit()) : null;
651
+ }
652
+ met(sw) {
653
+ var _a;
654
+ if (!sw)
655
+ return false;
656
+ if (sw.kind === 'load')
657
+ return true;
658
+ if (sw.kind === 'event')
659
+ return this.visitEvents().has(sw.event);
660
+ const p = (_a = this.page) === null || _a === void 0 ? void 0 : _a.progress();
661
+ if (!p)
662
+ return false;
663
+ return sw.kind === 'seconds' ? p.seconds >= sw.seconds : sw.kind === 'scroll' ? p.scrollPercent >= sw.percent : p.exitIntent;
664
+ }
665
+ noteEvent(name) {
666
+ const events = this.visitEvents();
667
+ if (!events.has(name) && events.size < MAX_EVENTS) {
668
+ events.add(name);
669
+ try {
670
+ sessionStorage.setItem(this.store, JSON.stringify({ sid: this.sid, names: Array.from(events) }));
671
+ }
672
+ catch (_a) {
673
+ }
674
+ }
675
+ this.emit();
676
+ }
677
+ onChange(cb) {
678
+ this.listeners.add(cb);
679
+ return () => this.listeners.delete(cb);
680
+ }
681
+ destroy() {
682
+ var _a;
683
+ (_a = this.off) === null || _a === void 0 ? void 0 : _a.call(this);
684
+ this.listeners.clear();
685
+ }
686
+ visitEvents() {
687
+ const sid = this.sessionId();
688
+ if (sid !== this.sid) {
689
+ this.sid = sid;
690
+ this.events = new Set();
691
+ try {
692
+ const raw = JSON.parse(sessionStorage.getItem(this.store) || 'null');
693
+ if (raw && sid && raw.sid === sid)
694
+ this.events = new Set(eventNames(raw.names, MAX_EVENTS));
695
+ }
696
+ catch (_a) {
697
+ }
698
+ }
699
+ return this.events;
700
+ }
701
+ emit() {
702
+ for (const cb of Array.from(this.listeners)) {
703
+ try {
704
+ cb();
705
+ }
706
+ catch (_a) {
707
+ }
708
+ }
709
+ }
710
+ }
711
+
553
712
  const PAGE_EDIT_POSITIONS = ['before', 'after', 'prepend', 'append', 'replace'];
554
713
  const PAGE_EDITS_CAPABILITY = 'page_edits';
555
714
  const PAGE_EDIT_DEVICES = ['all', 'mobile', 'desktop'];
556
- const PAGE_EDIT_DEVICE_CAPABILITY = 'page_edit_device';
557
715
  const PAGE_EDIT_MOBILE_BREAKPOINT = 768;
558
716
  const PAGE_EDIT_MOBILE_QUERY = '(max-width: 767.98px)';
559
717
  function isMobileViewport(win = window) {
@@ -767,6 +925,11 @@ class PageEditManager {
767
925
  this.offMedia = null;
768
926
  this.started = false;
769
927
  this.destroyed = false;
928
+ this.moments = null;
929
+ this.momentsUnsubscribe = null;
930
+ this.revealed = new Set();
931
+ this.recheckOn = [];
932
+ this.rechecked = new Set();
770
933
  this.stores = pageEditsStorageKeys(sdkKey);
771
934
  try {
772
935
  localStorage.removeItem(LEGACY_SELECTOR_STORE);
@@ -787,6 +950,43 @@ class PageEditManager {
787
950
  });
788
951
  }
789
952
  }
953
+ setShowWhen(moments) {
954
+ var _a;
955
+ (_a = this.momentsUnsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
956
+ this.moments = moments;
957
+ this.momentsUnsubscribe = moments ? moments.onChange(() => this.sweep()) : null;
958
+ }
959
+ due(x) {
960
+ const sw = parseShowWhen(x.showWhen);
961
+ return !!sw && (sw.kind === 'load' || this.revealed.has(x.id) || (!!this.moments && this.moments.met(sw)));
962
+ }
963
+ sweep() {
964
+ if (!this.started || this.destroyed)
965
+ return;
966
+ let any = false;
967
+ for (const x of this.experiences) {
968
+ if (this.revealed.has(x.wire.id) || !isDeferred(x.wire.showWhen) || !this.due(x.wire))
969
+ continue;
970
+ this.revealed.add(x.wire.id);
971
+ any = true;
972
+ }
973
+ if (any)
974
+ this.applyAll();
975
+ }
976
+ claimRecheck(eventName) {
977
+ if (!this.moments || !this.started || this.destroyed || this.rechecked.has(eventName))
978
+ return false;
979
+ const waits = this.recheckOn.includes(eventName) ||
980
+ this.experiences.some((x) => { var _a; return ((_a = parseShowWhen(x.wire.showWhen)) === null || _a === void 0 ? void 0 : _a.event) === eventName; });
981
+ if (waits)
982
+ this.rechecked.add(eventName);
983
+ return waits;
984
+ }
985
+ recheck(event) {
986
+ const url = this.url();
987
+ if (url && this.started && !this.destroyed)
988
+ void this.fetch(url, this.generation, event);
989
+ }
790
990
  start() {
791
991
  var _a;
792
992
  if (this.started || this.destroyed || typeof document === 'undefined')
@@ -832,12 +1032,13 @@ class PageEditManager {
832
1032
  this.loadPage();
833
1033
  }
834
1034
  destroy() {
835
- var _a, _b, _c;
1035
+ var _a, _b, _c, _d;
836
1036
  this.destroyed = true;
837
1037
  (_a = this.pageUnsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
838
- (_b = this.offMedia) === null || _b === void 0 ? void 0 : _b.call(this);
1038
+ (_b = this.momentsUnsubscribe) === null || _b === void 0 ? void 0 : _b.call(this);
1039
+ (_c = this.offMedia) === null || _c === void 0 ? void 0 : _c.call(this);
839
1040
  this.offMedia = null;
840
- (_c = this.observer) === null || _c === void 0 ? void 0 : _c.disconnect();
1041
+ (_d = this.observer) === null || _d === void 0 ? void 0 : _d.disconnect();
841
1042
  this.observer = null;
842
1043
  this.revertAll();
843
1044
  this.showAll();
@@ -854,6 +1055,9 @@ class PageEditManager {
854
1055
  loadPage() {
855
1056
  const generation = ++this.generation;
856
1057
  this.revertAll();
1058
+ this.revealed.clear();
1059
+ this.rechecked.clear();
1060
+ this.recheckOn = [];
857
1061
  const url = this.url();
858
1062
  if (!url) {
859
1063
  this.experiences = [];
@@ -989,7 +1193,7 @@ class PageEditManager {
989
1193
  this.siteRequest = request;
990
1194
  return request;
991
1195
  }
992
- async fetch(url, generation) {
1196
+ async fetch(url, generation, recheckEvent) {
993
1197
  var _a, _b, _c, _d;
994
1198
  const consent = this.runtime.consent();
995
1199
  if (consent === null || this.destroyed) {
@@ -999,7 +1203,7 @@ class PageEditManager {
999
1203
  const personal = consent === 'granted';
1000
1204
  const userId = personal ? this.identity.getUserId() : null;
1001
1205
  const anonymousId = personal ? this.identity.getAnonymousId() : null;
1002
- const body = Object.assign(Object.assign(Object.assign(Object.assign({}, (userId ? { userId } : {})), (anonymousId ? { anonymousId } : {})), (personal ? { sessionId: this.session.getSessionId() } : {})), { deviceType: 'web', locale: typeof navigator !== 'undefined' ? navigator.language : undefined, capabilities: [PAGE_CONTEXT_CAPABILITY, PAGE_EDITS_CAPABILITY, PAGE_EDIT_DEVICE_CAPABILITY], trackingConsent: consent, context: this.page ? this.page.current() : { url, pageVariables: {}, dataLayer: {} } });
1206
+ const body = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (userId ? { userId } : {})), (anonymousId ? { anonymousId } : {})), (personal ? { sessionId: this.session.getSessionId() } : {})), { deviceType: 'web', locale: typeof navigator !== 'undefined' ? navigator.language : undefined, capabilities: [PAGE_CONTEXT_CAPABILITY, PAGE_EDITS_CAPABILITY], trackingConsent: consent, context: this.page ? this.page.current() : { url, pageVariables: {}, dataLayer: {} } }), (recheckEvent ? { recheckEvent } : {}));
1003
1207
  const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
1004
1208
  const timeout = setTimeout(() => controller === null || controller === void 0 ? void 0 : controller.abort(), (_a = this.runtime.requestTimeoutMs) !== null && _a !== void 0 ? _a : 10000);
1005
1209
  try {
@@ -1018,6 +1222,7 @@ class PageEditManager {
1018
1222
  .map((wire) => ({ wire, edits: (Array.isArray(wire.edits) ? wire.edits : []).map(trustedEdit).filter((e) => !!e) }));
1019
1223
  this.revertAll();
1020
1224
  this.experiences = experiences;
1225
+ this.recheckOn = eventNames(data.recheckOn);
1021
1226
  this.reconcileServer(experiences);
1022
1227
  this.remember(url, experiences, data.ttlSeconds);
1023
1228
  this.applyAll();
@@ -1051,6 +1256,8 @@ class PageEditManager {
1051
1256
  (_a = this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
1052
1257
  try {
1053
1258
  for (const x of this.experiences) {
1259
+ if (!this.due(x.wire))
1260
+ continue;
1054
1261
  if (x.wire.isControl) {
1055
1262
  const seen = (x.wire.selectors || []).some((s) => isSafeSelector(s) && this.query(s).length > 0);
1056
1263
  if (seen)
@@ -1208,7 +1415,7 @@ class PageEditManager {
1208
1415
  return `${this.identity.getUserId() || ''}|${this.identity.getAnonymousId()}`;
1209
1416
  }
1210
1417
  remember(url, experiences, ttlSeconds) {
1211
- const selectors = [...new Set(experiences.flatMap((x) => (x.wire.isControl ? [] : x.edits.filter((e) => editShowsOn(e, this.mobile)).map((e) => e.selector))))];
1418
+ const selectors = [...new Set(experiences.flatMap((x) => (x.wire.isControl || isDeferred(x.wire.showWhen) ? [] : x.edits.filter((e) => editShowsOn(e, this.mobile)).map((e) => e.selector))))];
1212
1419
  try {
1213
1420
  const all = JSON.parse(localStorage.getItem(this.stores.selectors) || '{}') || {};
1214
1421
  delete all[url];
@@ -1302,7 +1509,7 @@ class PageEditManager {
1302
1509
  return;
1303
1510
  const keep = new Set();
1304
1511
  for (const x of experiences) {
1305
- if (x.wire.isControl)
1512
+ if (x.wire.isControl || isDeferred(x.wire.showWhen))
1306
1513
  continue;
1307
1514
  for (const e of x.edits) {
1308
1515
  const token = `${x.wire.id}:${e.id}`;
@@ -5664,6 +5871,9 @@ const PLACEMENT_PRODUCT_CARD_WIDTH = 160;
5664
5871
  function placementProductElementId(productId) {
5665
5872
  return `${PLACEMENT_PRODUCT_ELEMENT_PREFIX}${productId}`.slice(0, 128);
5666
5873
  }
5874
+ const SERVER_FILLED_ATTR = 'data-joryio-server-filled';
5875
+ const SERVER_FILL_ATTR = 'data-joryio-server-fill';
5876
+ const SERVER_FILLS_MARKER_KEY = 'fills';
5667
5877
  const DEFAULT_TTL_SECONDS = 300;
5668
5878
  const LEGACY_CACHE_STORAGE_NAME = 'joryio_placements_v1';
5669
5879
  const placementsStorageKey = (sdkKey) => `joryio_placements_v1_${bucketHash(sdkKey).toString(36)}`;
@@ -5780,7 +5990,14 @@ class PlacementManager {
5780
5990
  this.destroyed = false;
5781
5991
  this.page = null;
5782
5992
  this.pageUnsubscribe = null;
5993
+ this.moments = null;
5994
+ this.momentsUnsubscribe = null;
5995
+ this.revealed = new Set();
5996
+ this.spotViewable = new Set();
5997
+ this.rechecked = new Set();
5998
+ this.recheckEvent = null;
5783
5999
  this.pageScopedKeys = new Set();
6000
+ this.markerFills = null;
5784
6001
  this.loadCache();
5785
6002
  this.installBridge();
5786
6003
  this.installPageVisibility();
@@ -5809,6 +6026,7 @@ class PlacementManager {
5809
6026
  hostObserver: null,
5810
6027
  trackers: [],
5811
6028
  frameIds: [],
6029
+ serverFill: this.serverFillOf(key, element),
5812
6030
  };
5813
6031
  this.mounts.add(mount);
5814
6032
  this.observeHost(mount);
@@ -5880,6 +6098,8 @@ class PlacementManager {
5880
6098
  this.triggeredAt.clear();
5881
6099
  this.dismissedLocally.clear();
5882
6100
  this.reported.clear();
6101
+ this.revealed.clear();
6102
+ this.spotViewable.clear();
5883
6103
  this.persistCache();
5884
6104
  const keys = this.mountedKeys();
5885
6105
  for (const mount of this.mounts)
@@ -5888,13 +6108,15 @@ class PlacementManager {
5888
6108
  this.fetchKeys(keys, true).catch(() => undefined);
5889
6109
  }
5890
6110
  destroy() {
5891
- var _a, _b, _c;
6111
+ var _a, _b, _c, _d;
5892
6112
  this.destroyed = true;
5893
6113
  (_a = this.pageUnsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
5894
6114
  this.pageUnsubscribe = null;
6115
+ (_b = this.momentsUnsubscribe) === null || _b === void 0 ? void 0 : _b.call(this);
6116
+ this.momentsUnsubscribe = null;
5895
6117
  for (const mount of Array.from(this.mounts))
5896
6118
  this.unmount(mount);
5897
- (_b = this.mutationObserver) === null || _b === void 0 ? void 0 : _b.disconnect();
6119
+ (_c = this.mutationObserver) === null || _c === void 0 ? void 0 : _c.disconnect();
5898
6120
  this.mutationObserver = null;
5899
6121
  if (this.batchTimer)
5900
6122
  clearTimeout(this.batchTimer);
@@ -5909,11 +6131,11 @@ class PlacementManager {
5909
6131
  document.removeEventListener('visibilitychange', this.pageListener);
5910
6132
  }
5911
6133
  try {
5912
- if (typeof window !== 'undefined' && ((_c = window[PLACEMENT_BRIDGE_GLOBAL]) === null || _c === void 0 ? void 0 : _c.__owner) === this) {
6134
+ if (typeof window !== 'undefined' && ((_d = window[PLACEMENT_BRIDGE_GLOBAL]) === null || _d === void 0 ? void 0 : _d.__owner) === this) {
5913
6135
  delete window[PLACEMENT_BRIDGE_GLOBAL];
5914
6136
  }
5915
6137
  }
5916
- catch (_d) {
6138
+ catch (_e) {
5917
6139
  }
5918
6140
  }
5919
6141
  cleanKeys(keys) {
@@ -5942,11 +6164,23 @@ class PlacementManager {
5942
6164
  this.pageUnsubscribe = tracker.onSignal((signal) => {
5943
6165
  if (signal.type !== 'page_change' || this.destroyed)
5944
6166
  return;
6167
+ const held = this.revealed.size ? this.keysWithMoments() : [];
6168
+ this.revealed.clear();
6169
+ this.spotViewable.clear();
6170
+ this.rechecked.clear();
5945
6171
  const stale = [];
5946
6172
  this.cache.forEach((entry, key) => {
5947
6173
  if (entry.placement.pageScoped && entry.url !== signal.url)
5948
6174
  stale.push(key);
5949
6175
  });
6176
+ const rehide = held.filter((key) => !stale.includes(key));
6177
+ if (rehide.length) {
6178
+ for (const mount of this.mounts)
6179
+ if (rehide.includes(mount.key))
6180
+ this.render(mount);
6181
+ this.notify(rehide);
6182
+ this.sweep();
6183
+ }
5950
6184
  if (!stale.length)
5951
6185
  return;
5952
6186
  stale.forEach((key) => this.cache.delete(key));
@@ -5966,6 +6200,75 @@ class PlacementManager {
5966
6200
  }
5967
6201
  });
5968
6202
  }
6203
+ setShowWhen(moments) {
6204
+ var _a;
6205
+ (_a = this.momentsUnsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
6206
+ this.moments = moments;
6207
+ this.momentsUnsubscribe = moments ? moments.onChange(() => !this.destroyed && this.sweep()) : null;
6208
+ }
6209
+ due(handle, raw) {
6210
+ const sw = parseShowWhen(raw);
6211
+ if (!sw)
6212
+ return false;
6213
+ return sw.kind === 'load' || this.revealed.has(handle) || (!!this.moments && this.moments.met(sw));
6214
+ }
6215
+ keysWithMoments() {
6216
+ const out = [];
6217
+ this.cache.forEach((entry, key) => {
6218
+ var _a;
6219
+ const p = entry.placement;
6220
+ if (p.showWhen !== undefined || ((_a = p.deferredControls) === null || _a === void 0 ? void 0 : _a.length) || (p.items || []).some((i) => i.showWhen !== undefined))
6221
+ out.push(key);
6222
+ });
6223
+ return out;
6224
+ }
6225
+ sweep() {
6226
+ const changed = [];
6227
+ this.cache.forEach((entry, key) => {
6228
+ const p = entry.placement;
6229
+ const handles = (p.items || []).filter((i) => isDeferred(i.showWhen)).map((i) => [this.handle(key, i), i.showWhen]);
6230
+ if (p.isControl && isDeferred(p.showWhen))
6231
+ handles.push([`ctl:${key}:${p.controlToken || ''}`, p.showWhen]);
6232
+ for (const [h, raw] of handles) {
6233
+ if (this.revealed.has(h) || !this.due(h, raw))
6234
+ continue;
6235
+ this.revealed.add(h);
6236
+ if (!changed.includes(key))
6237
+ changed.push(key);
6238
+ }
6239
+ this.reportDeferred(key);
6240
+ });
6241
+ if (changed.length)
6242
+ this.applyChanged(changed);
6243
+ }
6244
+ recheckKeysFor(eventName) {
6245
+ if (!this.moments || this.destroyed)
6246
+ return [];
6247
+ const out = [];
6248
+ this.cache.forEach((entry, key) => {
6249
+ const p = entry.placement;
6250
+ if (p.pageScoped && entry.url !== this.currentUrl())
6251
+ return;
6252
+ const waits = (p.recheckOn || []).includes(eventName) ||
6253
+ (p.items || []).some((i) => { var _a; return ((_a = parseShowWhen(i.showWhen)) === null || _a === void 0 ? void 0 : _a.event) === eventName; });
6254
+ const once = `${key}\u0000${eventName}`;
6255
+ if (!waits || this.rechecked.has(once))
6256
+ return;
6257
+ this.rechecked.add(once);
6258
+ out.push(key);
6259
+ });
6260
+ return out;
6261
+ }
6262
+ recheck(keys, event) {
6263
+ const go = () => {
6264
+ keys.forEach((key) => this.lastNetworkAt.delete(this.rateKey(key)));
6265
+ if (event)
6266
+ this.recheckEvent = event;
6267
+ return this.fetchKeys(keys, false);
6268
+ };
6269
+ const inflight = keys.map((key) => this.inflight.get(key)).filter(Boolean);
6270
+ return (inflight.length ? Promise.all(inflight).then(go) : go()).catch(() => undefined);
6271
+ }
5969
6272
  currentUrl() {
5970
6273
  return this.page ? this.page.current().url : currentPageUrl();
5971
6274
  }
@@ -6037,19 +6340,21 @@ class PlacementManager {
6037
6340
  this.batchKeys.clear();
6038
6341
  const waiters = this.batchWaiters;
6039
6342
  this.batchWaiters = [];
6343
+ const recheckEvent = this.recheckEvent;
6344
+ this.recheckEvent = null;
6040
6345
  const chunks = [];
6041
6346
  for (let i = 0; i < keys.length; i += PLACEMENT_MAX_KEYS_PER_REQUEST) {
6042
6347
  chunks.push(keys.slice(i, i + PLACEMENT_MAX_KEYS_PER_REQUEST));
6043
6348
  }
6044
6349
  try {
6045
- await Promise.all(chunks.map((chunk) => this.request(chunk)));
6350
+ await Promise.all(chunks.map((chunk) => this.request(chunk, recheckEvent)));
6046
6351
  }
6047
6352
  finally {
6048
6353
  keys.forEach((key) => this.inflight.delete(key));
6049
6354
  waiters.forEach((w) => w.resolve());
6050
6355
  }
6051
6356
  }
6052
- async request(keys) {
6357
+ async request(keys, recheckEvent) {
6053
6358
  var _a, _b, _c, _d;
6054
6359
  const consent = this.runtime.consent();
6055
6360
  if (consent === null || this.destroyed)
@@ -6066,7 +6371,7 @@ class PlacementManager {
6066
6371
  }
6067
6372
  const userId = personal ? this.identity.getUserId() : null;
6068
6373
  const anonymousId = personal ? this.identity.getAnonymousId() : null;
6069
- const body = Object.assign(Object.assign(Object.assign(Object.assign({}, (userId ? { userId } : {})), (anonymousId ? { anonymousId } : {})), (personal ? { sessionId: this.session.getSessionId() } : {})), { deviceType: 'web', locale: typeof navigator !== 'undefined' ? navigator.language : undefined, capabilities: this.capabilities(), trackingConsent: consent, placements: keys, shown, context: this.page ? Object.assign(Object.assign({}, this.page.current()), { screen: null }) : pageContext() });
6374
+ const body = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (userId ? { userId } : {})), (anonymousId ? { anonymousId } : {})), (personal ? { sessionId: this.session.getSessionId() } : {})), { deviceType: 'web', locale: typeof navigator !== 'undefined' ? navigator.language : undefined, capabilities: this.capabilities(), trackingConsent: consent, placements: keys, shown, context: this.page ? Object.assign(Object.assign({}, this.page.current()), { screen: null }) : pageContext() }), (recheckEvent ? { recheckEvent } : {}));
6070
6375
  const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
6071
6376
  const timeout = setTimeout(() => controller === null || controller === void 0 ? void 0 : controller.abort(), (_a = this.runtime.requestTimeoutMs) !== null && _a !== void 0 ? _a : 10000);
6072
6377
  const url = `${this.apiEndpoint}/v1/in-app/placements`;
@@ -6124,7 +6429,9 @@ class PlacementManager {
6124
6429
  }
6125
6430
  normalize(key, wire) {
6126
6431
  const items = Array.isArray(wire.items) ? wire.items.filter((i) => i && typeof i.id === 'string') : [];
6127
- return Object.assign({ placementKey: key, emptyBehavior: wire.emptyBehavior === 'keep_space' ? 'keep_space' : 'collapse', maxItems: typeof wire.maxItems === 'number' && wire.maxItems > 0 ? wire.maxItems : 1, ttlSeconds: typeof wire.ttlSeconds === 'number' && wire.ttlSeconds > 0 ? wire.ttlSeconds : DEFAULT_TTL_SECONDS, isControl: wire.isControl === true, controlToken: wire.controlToken || null, items }, (wire.pageScoped === true ? { pageScoped: true } : {}));
6432
+ return Object.assign(Object.assign(Object.assign(Object.assign({ placementKey: key, emptyBehavior: wire.emptyBehavior === 'keep_space' ? 'keep_space' : 'collapse', maxItems: typeof wire.maxItems === 'number' && wire.maxItems > 0 ? wire.maxItems : 1, ttlSeconds: typeof wire.ttlSeconds === 'number' && wire.ttlSeconds > 0 ? wire.ttlSeconds : DEFAULT_TTL_SECONDS, isControl: wire.isControl === true, controlToken: wire.controlToken || null, items }, (wire.pageScoped === true ? { pageScoped: true } : {})), (wire.isControl === true && wire.showWhen != null ? { showWhen: wire.showWhen } : {})), (Array.isArray(wire.deferredControls) && wire.deferredControls.length
6433
+ ? { deferredControls: wire.deferredControls.filter((d) => d && typeof d.controlToken === 'string' && d.controlToken) }
6434
+ : {})), (eventNames(wire.recheckOn).length ? { recheckOn: eventNames(wire.recheckOn) } : {}));
6128
6435
  }
6129
6436
  applyChanged(keys) {
6130
6437
  for (const mount of this.mounts) {
@@ -6135,6 +6442,9 @@ class PlacementManager {
6135
6442
  else
6136
6443
  this.render(mount);
6137
6444
  }
6445
+ this.notify(keys);
6446
+ }
6447
+ notify(keys) {
6138
6448
  if (!this.listeners.size)
6139
6449
  return;
6140
6450
  const update = {};
@@ -6163,6 +6473,8 @@ class PlacementManager {
6163
6473
  return false;
6164
6474
  if (this.dismissedLocally.has(this.handle(key, item)))
6165
6475
  return false;
6476
+ if (item.showWhen !== undefined && !this.due(this.handle(key, item), item.showWhen))
6477
+ return false;
6166
6478
  const eventTriggers = (item.triggers || []).filter((t) => t.type === 'event');
6167
6479
  if (eventTriggers.length) {
6168
6480
  const at = this.triggeredAt.get(this.handle(key, item));
@@ -6185,7 +6497,12 @@ class PlacementManager {
6185
6497
  emptyBehavior: wire.emptyBehavior || 'collapse',
6186
6498
  maxItems: wire.maxItems || 1,
6187
6499
  ttlSeconds: wire.ttlSeconds || DEFAULT_TTL_SECONDS,
6188
- markDisplayed: () => this.current(generation) && this.reportControl(key),
6500
+ markDisplayed: () => {
6501
+ if (!this.current(generation))
6502
+ return;
6503
+ this.reportControl(key);
6504
+ this.markSpotViewable(key);
6505
+ },
6189
6506
  };
6190
6507
  }
6191
6508
  current(generation) {
@@ -6215,6 +6532,8 @@ class PlacementManager {
6215
6532
  this.render(mount);
6216
6533
  }
6217
6534
  report(key, item, type, elementId) {
6535
+ if (type === 'displayed')
6536
+ this.markSpotViewable(key);
6218
6537
  if (this.runtime.consent() !== 'granted')
6219
6538
  return;
6220
6539
  const once = `${type}:${this.handle(key, item)}`;
@@ -6234,13 +6553,33 @@ class PlacementManager {
6234
6553
  const entry = this.cache.get(key);
6235
6554
  if (!(entry === null || entry === void 0 ? void 0 : entry.placement.isControl) || !entry.placement.controlToken)
6236
6555
  return;
6556
+ if (!this.due(`ctl:${key}:${entry.placement.controlToken}`, entry.placement.showWhen))
6557
+ return;
6558
+ this.postControl(key, entry.placement.controlToken);
6559
+ }
6560
+ markSpotViewable(key) {
6561
+ if (this.spotViewable.has(key))
6562
+ return;
6563
+ this.spotViewable.add(key);
6564
+ this.reportDeferred(key);
6565
+ }
6566
+ reportDeferred(key) {
6567
+ var _a;
6568
+ const list = (_a = this.cache.get(key)) === null || _a === void 0 ? void 0 : _a.placement.deferredControls;
6569
+ if (!(list === null || list === void 0 ? void 0 : list.length) || !this.spotViewable.has(key))
6570
+ return;
6571
+ for (const d of list)
6572
+ if (this.due(`ctl:${key}:${d.controlToken}`, d.showWhen))
6573
+ this.postControl(key, d.controlToken);
6574
+ }
6575
+ postControl(key, controlToken) {
6237
6576
  if (this.runtime.consent() !== 'granted')
6238
6577
  return;
6239
- const once = `control:${entry.placement.controlToken}`;
6578
+ const once = `control:${controlToken}`;
6240
6579
  if (this.reported.has(once))
6241
6580
  return;
6242
6581
  this.reported.add(once);
6243
- this.post('/v1/in-app/track', Object.assign(Object.assign({ action: 'control_viewed', controlToken: entry.placement.controlToken, placementKey: key }, this.subject()), { sessionId: this.session.getSessionId(), deviceType: 'web', viewedAt: new Date().toISOString() }));
6582
+ this.post('/v1/in-app/track', Object.assign(Object.assign({ action: 'control_viewed', controlToken, placementKey: key }, this.subject()), { sessionId: this.session.getSessionId(), deviceType: 'web', viewedAt: new Date().toISOString() }));
6244
6583
  }
6245
6584
  subject() {
6246
6585
  const userId = this.identity.getUserId();
@@ -6293,15 +6632,143 @@ class PlacementManager {
6293
6632
  }
6294
6633
  clearDrawn(mount) {
6295
6634
  var _a;
6635
+ if (mount.serverFill) {
6636
+ this.dropServerFill(mount.element, mount.serverFill.wrapper);
6637
+ mount.serverFill = null;
6638
+ }
6296
6639
  mount.frameIds.forEach((id) => this.frames.delete(id));
6297
6640
  mount.frameIds = [];
6298
6641
  (_a = mount.wrapper) === null || _a === void 0 ? void 0 : _a.remove();
6299
6642
  mount.wrapper = null;
6300
6643
  mount.shown = [];
6301
6644
  }
6645
+ serverFillsOfMarker() {
6646
+ if (this.markerFills)
6647
+ return this.markerFills;
6648
+ const out = new Map();
6649
+ try {
6650
+ const el = typeof document !== 'undefined' ? serverMarkerElement() : null;
6651
+ const data = el ? JSON.parse(el.textContent || 'null') : null;
6652
+ const list = data && data.v === 1 && Array.isArray(data[SERVER_FILLS_MARKER_KEY]) ? data[SERVER_FILLS_MARKER_KEY] : [];
6653
+ for (const f of list.slice(0, 20)) {
6654
+ if (!f || !validKey(f.placementKey) || typeof f.campaignId !== 'string' || !f.campaignId)
6655
+ continue;
6656
+ const products = Array.isArray(f.products) ? f.products.filter((p) => typeof p === 'string').slice(0, 24) : [];
6657
+ out.set(f.placementKey, { campaignId: f.campaignId, variantId: typeof f.variantId === 'string' ? f.variantId : '', products });
6658
+ }
6659
+ }
6660
+ catch (_a) {
6661
+ }
6662
+ this.markerFills = out;
6663
+ return out;
6664
+ }
6665
+ serverFillOf(key, element) {
6666
+ var _a;
6667
+ const token = (_a = element.getAttribute) === null || _a === void 0 ? void 0 : _a.call(element, SERVER_FILLED_ATTR);
6668
+ if (!token)
6669
+ return null;
6670
+ const wrapper = Array.from(element.children || []).find((c) => { var _a, _b; return ((_a = c.classList) === null || _a === void 0 ? void 0 : _a.contains('joryio-placement')) && ((_b = c.hasAttribute) === null || _b === void 0 ? void 0 : _b.call(c, SERVER_FILL_ATTR)); });
6671
+ const fill = this.serverFillsOfMarker().get(key);
6672
+ const ok = !!wrapper &&
6673
+ !!fill &&
6674
+ wrapper.getAttribute(SERVER_FILL_ATTR) === token &&
6675
+ token === `${key}:${fill.campaignId}:${fill.variantId}` &&
6676
+ (this.runtime.allowHtml() || !wrapper.querySelector('.joryio-placement-html'));
6677
+ if (!ok) {
6678
+ this.dropServerFill(element, wrapper !== null && wrapper !== void 0 ? wrapper : null);
6679
+ return null;
6680
+ }
6681
+ attachServerShadowRoots(wrapper);
6682
+ return Object.assign(Object.assign({}, fill), { wrapper: wrapper });
6683
+ }
6684
+ dropServerFill(element, wrapper) {
6685
+ var _a, _b;
6686
+ wrapper === null || wrapper === void 0 ? void 0 : wrapper.remove();
6687
+ (_a = element.removeAttribute) === null || _a === void 0 ? void 0 : _a.call(element, SERVER_FILLED_ATTR);
6688
+ (_b = element.removeAttribute) === null || _b === void 0 ? void 0 : _b.call(element, 'data-joryio-placement-state');
6689
+ }
6690
+ settleServerFill(mount) {
6691
+ var _a, _b;
6692
+ const sf = mount.serverFill;
6693
+ if (!sf)
6694
+ return 'dropped';
6695
+ const entry = this.cache.get(mount.key);
6696
+ if (!entry)
6697
+ return 'waiting';
6698
+ mount.serverFill = null;
6699
+ const items = this.visibleItems(mount.key);
6700
+ const item = items[0];
6701
+ const products = toProducts(item === null || item === void 0 ? void 0 : item.products).map((p) => p.id);
6702
+ const html = !!sf.wrapper.querySelector('.joryio-placement-html');
6703
+ const same = items.length === 1 &&
6704
+ entry.placement.isControl !== true &&
6705
+ item.id === sf.campaignId &&
6706
+ ((_a = item.variantId) !== null && _a !== void 0 ? _a : '') === sf.variantId &&
6707
+ products.length === sf.products.length &&
6708
+ products.every((id, i) => id === sf.products[i]) &&
6709
+ (((_b = item.content) === null || _b === void 0 ? void 0 : _b.kind) === 'html') === html &&
6710
+ (!html || this.runtime.allowHtml()) &&
6711
+ (mount.options.showProducts !== false || !products.length);
6712
+ if (!same) {
6713
+ this.dropServerFill(mount.element, sf.wrapper);
6714
+ return 'dropped';
6715
+ }
6716
+ mount.pendingUpdate = false;
6717
+ this.clearTrackers(mount);
6718
+ mount.wrapper = sf.wrapper;
6719
+ mount.shown = [item.deliveryId || item.id];
6720
+ mount.element.setAttribute('data-joryio-placement-state', 'filled');
6721
+ const node = sf.wrapper.firstElementChild || sf.wrapper;
6722
+ this.trackViewability(mount, node, () => this.report(mount.key, item, 'displayed'));
6723
+ this.bindServerFill(mount, sf.wrapper, item);
6724
+ if (mount.options.onRender) {
6725
+ try {
6726
+ mount.options.onRender(this.toPlacement(mount.key), mount.element);
6727
+ }
6728
+ catch (error) {
6729
+ this.logger.error('The insertPlacement onRender callback threw; ignored:', error);
6730
+ }
6731
+ }
6732
+ return 'kept';
6733
+ }
6734
+ bindServerFill(mount, wrapper, item) {
6735
+ wrapper.addEventListener('click', (event) => {
6736
+ var _a, _b;
6737
+ if (!this.mounts.has(mount) || mount.wrapper !== wrapper)
6738
+ return;
6739
+ const path = (typeof event.composedPath === 'function' ? event.composedPath() : [event.target]);
6740
+ for (const el of path) {
6741
+ if (!el || el === wrapper || typeof el.getAttribute !== 'function')
6742
+ break;
6743
+ const productId = el.getAttribute('data-joryio-product');
6744
+ if (productId) {
6745
+ const href = el.getAttribute('href');
6746
+ if (href)
6747
+ (_a = event.preventDefault) === null || _a === void 0 ? void 0 : _a.call(event);
6748
+ this.buttonAction(mount, item, { id: placementProductElementId(productId), action: 'deep_link', url: href || undefined });
6749
+ return;
6750
+ }
6751
+ const tag = (el.tagName || '').toUpperCase();
6752
+ if (tag === 'A' || tag === 'BUTTON') {
6753
+ const href = tag === 'A' ? el.getAttribute('href') : null;
6754
+ if (hasUserGesture())
6755
+ this.report(mount.key, item, 'clicked', el.getAttribute('data-action') || (href ? 'link_click' : 'cta_click'));
6756
+ if (href && !/^(#|mailto:|tel:|sms:)/i.test(href.trim())) {
6757
+ (_b = event.preventDefault) === null || _b === void 0 ? void 0 : _b.call(event);
6758
+ const safe = safeHttpUrl(href.trim());
6759
+ if (safe && hasUserGesture())
6760
+ this.openLink(safe, { placementKey: mount.key, itemId: item.id }, () => window.open(safe, '_blank', 'noopener'));
6761
+ }
6762
+ return;
6763
+ }
6764
+ }
6765
+ }, true);
6766
+ }
6302
6767
  render(mount) {
6303
6768
  if (!this.mounts.has(mount))
6304
6769
  return;
6770
+ if (mount.serverFill && this.settleServerFill(mount) !== 'dropped')
6771
+ return;
6305
6772
  mount.pendingUpdate = false;
6306
6773
  this.clearTrackers(mount);
6307
6774
  this.clearDrawn(mount);
@@ -6327,7 +6794,10 @@ class PlacementManager {
6327
6794
  if (!drawn.length) {
6328
6795
  wrapper.style.display = placement.emptyBehavior === 'keep_space' ? '' : 'none';
6329
6796
  if (placement.isControl && (entry === null || entry === void 0 ? void 0 : entry.placement.controlToken)) {
6330
- this.trackViewability(mount, mount.element, () => this.reportControl(mount.key));
6797
+ this.trackViewability(mount, mount.element, () => {
6798
+ this.reportControl(mount.key);
6799
+ this.markSpotViewable(mount.key);
6800
+ });
6331
6801
  }
6332
6802
  }
6333
6803
  if (mount.options.onRender) {
@@ -6669,6 +7139,22 @@ class PlacementManager {
6669
7139
  }
6670
7140
  }
6671
7141
  }
7142
+ function attachServerShadowRoots(wrapper) {
7143
+ var _a;
7144
+ for (const host of Array.from(((_a = wrapper.querySelectorAll) === null || _a === void 0 ? void 0 : _a.call(wrapper, '.joryio-placement-html')) || [])) {
7145
+ if (host.shadowRoot || typeof host.attachShadow !== 'function')
7146
+ continue;
7147
+ const tpl = Array.from(host.children).find((c) => c.tagName === 'TEMPLATE' && c.getAttribute('shadowrootmode') === 'open');
7148
+ if (!tpl)
7149
+ continue;
7150
+ try {
7151
+ host.attachShadow({ mode: 'open' }).appendChild(tpl.content);
7152
+ tpl.remove();
7153
+ }
7154
+ catch (_b) {
7155
+ }
7156
+ }
7157
+ }
6672
7158
  function toProducts(raw) {
6673
7159
  if (!Array.isArray(raw))
6674
7160
  return [];
@@ -9358,6 +9844,7 @@ class JoryioSDK {
9358
9844
  this.attributeGeneration = 0;
9359
9845
  this.attributeFailures = 0;
9360
9846
  this.links = new LinkRouter((error) => { var _a; return (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error('Your link handler threw; the link opens as without one:', error); });
9847
+ this.pendingRechecks = [];
9361
9848
  this.editor = null;
9362
9849
  this._ecommerce = null;
9363
9850
  this.isInitialized = false;
@@ -9499,6 +9986,11 @@ class JoryioSDK {
9499
9986
  this.pageContext = new PageContextTracker(this.config.pageContext);
9500
9987
  this.pageContext.setUtmSource(() => (this.config.captureUTM && this.utm ? this.utm.getUTMData() : null));
9501
9988
  this.inapp.setPageContext(this.pageContext);
9989
+ this.showWhen = new ShowWhenMoments(this.pageContext, () => this.session.getSessionId(), this.config.sdkKey);
9990
+ this.pageContext.onSignal((s) => {
9991
+ if (s.type === 'page_change')
9992
+ this.pendingRechecks = [];
9993
+ });
9502
9994
  this.placements = new PlacementManager(this.config.apiEndpoint, this.config.sdkKey, this.identity, this.session, this.logger, {
9503
9995
  consent: () => this.placementConsent(),
9504
9996
  allowHtml: () => this.config.inApp.allowHtmlJsInAppMessages,
@@ -9514,12 +10006,14 @@ class JoryioSDK {
9514
10006
  },
9515
10007
  }, this.network);
9516
10008
  this.placements.setPageContext(this.pageContext);
10009
+ this.placements.setShowWhen(this.showWhen);
9517
10010
  this.pageEdits = new PageEditManager(this.config.apiEndpoint, this.config.sdkKey, this.identity, this.session, this.logger, {
9518
10011
  consent: () => this.placementConsent(),
9519
10012
  requestTimeoutMs: this.config.requestTimeout,
9520
10013
  noteStatus: (status, data) => this.network.noteSuspended(status, data),
9521
10014
  }, this.network);
9522
10015
  this.pageEdits.setPageContext(this.pageContext);
10016
+ this.pageEdits.setShowWhen(this.showWhen);
9523
10017
  this.cards = new CardManager(this.config.apiEndpoint, this.config.sdkKey, this.identity, this.session, this.logger, {
9524
10018
  consent: () => this.placementConsent(),
9525
10019
  requestTimeoutMs: this.config.requestTimeout,
@@ -9559,6 +10053,8 @@ class JoryioSDK {
9559
10053
  return await this.flushEvents(events, identify);
9560
10054
  }
9561
10055
  finally {
10056
+ if (this.pendingRechecks.length)
10057
+ setTimeout(() => this.runRechecks(), 0);
9562
10058
  this.scheduleRetiredTokenPrune();
9563
10059
  }
9564
10060
  });
@@ -9855,6 +10351,7 @@ class JoryioSDK {
9855
10351
  this.network.switchUser(userId);
9856
10352
  this.identity.adopt(anonymousId, userId);
9857
10353
  this.placements.invalidate();
10354
+ this.pendingRechecks = [];
9858
10355
  this.cards.invalidate(true);
9859
10356
  (_b = this.pageEdits) === null || _b === void 0 ? void 0 : _b.invalidate();
9860
10357
  this.flags.onIdentityChanged();
@@ -10120,6 +10617,7 @@ class JoryioSDK {
10120
10617
  if (wasOptedOut !== this.isOptedOut || wasPending !== this.consentPending) {
10121
10618
  this.inapp.invalidate();
10122
10619
  (_a = this.placements) === null || _a === void 0 ? void 0 : _a.invalidate();
10620
+ this.pendingRechecks = [];
10123
10621
  (_b = this.cards) === null || _b === void 0 ? void 0 : _b.invalidate(false);
10124
10622
  (_c = this.pageEdits) === null || _c === void 0 ? void 0 : _c.invalidate({ siteSettings: true });
10125
10623
  (_d = this.flags) === null || _d === void 0 ? void 0 : _d.onIdentityChanged();
@@ -10323,7 +10821,7 @@ class JoryioSDK {
10323
10821
  this.track('Page Viewed', properties);
10324
10822
  }
10325
10823
  track(eventName, properties) {
10326
- var _a, _b;
10824
+ var _a, _b, _c;
10327
10825
  if (!this.isInitialized) {
10328
10826
  this.logger.error('SDK not initialized');
10329
10827
  return;
@@ -10389,6 +10887,8 @@ class JoryioSDK {
10389
10887
  try {
10390
10888
  (_a = this.inapp) === null || _a === void 0 ? void 0 : _a.onEventTracked(eventName, eventProperties);
10391
10889
  (_b = this.placements) === null || _b === void 0 ? void 0 : _b.onEventTracked(eventName, eventProperties);
10890
+ (_c = this.showWhen) === null || _c === void 0 ? void 0 : _c.noteEvent(eventName);
10891
+ this.recheckShowWhen(eventName, processedEvent);
10392
10892
  }
10393
10893
  catch (error) {
10394
10894
  this.logger.error('In-app trigger evaluation failed:', error);
@@ -10412,6 +10912,45 @@ class JoryioSDK {
10412
10912
  this.logger.error('track() failed:', error);
10413
10913
  }
10414
10914
  }
10915
+ recheckShowWhen(eventName, queued) {
10916
+ var _a, _b;
10917
+ const keys = ((_a = this.placements) === null || _a === void 0 ? void 0 : _a.recheckKeysFor(eventName)) || [];
10918
+ const edits = !!((_b = this.pageEdits) === null || _b === void 0 ? void 0 : _b.claimRecheck(eventName));
10919
+ if (!keys.length && !edits)
10920
+ return;
10921
+ const event = { name: eventName, eventId: queued.eventId, properties: Object.assign({}, (queued.properties || {})) };
10922
+ this.pendingRechecks.push({ event, keys, edits, who: this.recheckOwner(), at: Date.now() });
10923
+ if (this.pendingRechecks.length > 20)
10924
+ this.pendingRechecks.shift();
10925
+ void this.queue
10926
+ .flush(false, true)
10927
+ .catch(() => undefined)
10928
+ .then(() => this.runRechecks());
10929
+ }
10930
+ recheckOwner() {
10931
+ var _a;
10932
+ return [this.identity.getUserId() || '', this.identity.getAnonymousId(), this.placementConsent() || '', ((_a = this.pageContext) === null || _a === void 0 ? void 0 : _a.current().url) || ''].join('\u0000');
10933
+ }
10934
+ runRechecks() {
10935
+ if (!this.pendingRechecks.length || !this.isInitialized)
10936
+ return;
10937
+ const owner = this.recheckOwner();
10938
+ const now = Date.now();
10939
+ this.pendingRechecks = this.pendingRechecks.filter((r) => r.who === owner && now - r.at <= 60000);
10940
+ const waiting = new Set([...this.queue.getQueuedEvents(), ...this.queue.getInflightEvents()].map((e) => e.eventId));
10941
+ const due = this.pendingRechecks.filter((r) => !waiting.has(r.event.eventId));
10942
+ if (!due.length)
10943
+ return;
10944
+ this.pendingRechecks = this.pendingRechecks.filter((r) => waiting.has(r.event.eventId));
10945
+ if (!this.canSend())
10946
+ return;
10947
+ for (const r of due) {
10948
+ if (r.keys.length)
10949
+ void this.placements.recheck(r.keys, r.event);
10950
+ if (r.edits)
10951
+ this.pageEdits.recheck(r.event);
10952
+ }
10953
+ }
10415
10954
  identify(userId) {
10416
10955
  var _a;
10417
10956
  if (!this.isInitialized) {
@@ -10447,6 +10986,7 @@ class JoryioSDK {
10447
10986
  if (previousUserId !== userId) {
10448
10987
  this.inapp.invalidate();
10449
10988
  this.placements.invalidate();
10989
+ this.pendingRechecks = [];
10450
10990
  this.cards.invalidate(true);
10451
10991
  (_a = this.pageEdits) === null || _a === void 0 ? void 0 : _a.invalidate();
10452
10992
  this.flags.onIdentityChanged();
@@ -10783,6 +11323,7 @@ class JoryioSDK {
10783
11323
  this.flags.onIdentityChanged();
10784
11324
  this.network.setCurrentUserId(this.identity.getUserId());
10785
11325
  this.placements.invalidate();
11326
+ this.pendingRechecks = [];
10786
11327
  this.cards.invalidate(true);
10787
11328
  (_a = this.pageEdits) === null || _a === void 0 ? void 0 : _a.invalidate({ siteSettings: true });
10788
11329
  this.utm.reset();
@@ -10849,6 +11390,7 @@ class JoryioSDK {
10849
11390
  this.flags.onIdentityChanged();
10850
11391
  this.network.setCurrentUserId(null);
10851
11392
  this.placements.invalidate();
11393
+ this.pendingRechecks = [];
10852
11394
  (_a = this.cards) === null || _a === void 0 ? void 0 : _a.invalidate(true);
10853
11395
  (_b = this.pageEdits) === null || _b === void 0 ? void 0 : _b.invalidate({ siteSettings: true });
10854
11396
  this.utm.reset();
@@ -11445,7 +11987,7 @@ class JoryioSDK {
11445
11987
  return this.flags.onFlagsUpdated(callback);
11446
11988
  }
11447
11989
  async destroy() {
11448
- var _a, _b, _c;
11990
+ var _a, _b, _c, _d;
11449
11991
  if (!this.isInitialized) {
11450
11992
  return;
11451
11993
  }
@@ -11487,7 +12029,9 @@ class JoryioSDK {
11487
12029
  this.cards.destroy();
11488
12030
  (_a = this.pageEdits) === null || _a === void 0 ? void 0 : _a.destroy();
11489
12031
  (_b = this.editor) === null || _b === void 0 ? void 0 : _b.stop();
11490
- (_c = this.pageContext) === null || _c === void 0 ? void 0 : _c.destroy();
12032
+ (_c = this.showWhen) === null || _c === void 0 ? void 0 : _c.destroy();
12033
+ this.pendingRechecks = [];
12034
+ (_d = this.pageContext) === null || _d === void 0 ? void 0 : _d.destroy();
11491
12035
  this.flags.destroy();
11492
12036
  this.isInitialized = false;
11493
12037
  if (JoryioSDK.instance === this)
@@ -11687,6 +12231,7 @@ exports.PLACEMENT_PRODUCT_ELEMENT_PREFIX = PLACEMENT_PRODUCT_ELEMENT_PREFIX;
11687
12231
  exports.PLACEMENT_VIEWABLE_FRACTION = PLACEMENT_VIEWABLE_FRACTION;
11688
12232
  exports.PushManager = PushManager;
11689
12233
  exports.SDK_VERSION = SDK_VERSION;
12234
+ exports.SHOW_WHEN_KINDS = SHOW_WHEN_KINDS;
11690
12235
  exports.User = User;
11691
12236
  exports.createEcommerceTracker = createEcommerceTracker;
11692
12237
  exports.default = JoryioSDK;