@joryio/web-sdk 1.4.0-beta.7 → 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.
Files changed (48) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/core/config.d.ts +1 -1
  3. package/dist/core/editor-gate.d.ts +2 -0
  4. package/dist/core/editor-gate.d.ts.map +1 -1
  5. package/dist/core/page-context.d.ts +13 -0
  6. package/dist/core/page-context.d.ts.map +1 -1
  7. package/dist/core/page-edits.d.ts +26 -0
  8. package/dist/core/page-edits.d.ts.map +1 -1
  9. package/dist/core/placements.d.ts +34 -0
  10. package/dist/core/placements.d.ts.map +1 -1
  11. package/dist/core/sdk.d.ts +5 -0
  12. package/dist/core/sdk.d.ts.map +1 -1
  13. package/dist/core/show-when.d.ts +42 -0
  14. package/dist/core/show-when.d.ts.map +1 -0
  15. package/dist/editor/editor-strings.d.ts +11 -0
  16. package/dist/editor/editor-strings.d.ts.map +1 -1
  17. package/dist/editor/editor-ui.d.ts +4 -1
  18. package/dist/editor/editor-ui.d.ts.map +1 -1
  19. package/dist/editor/liquid-field.d.ts +1 -0
  20. package/dist/editor/liquid-field.d.ts.map +1 -1
  21. package/dist/editor/visual-editor.d.ts +25 -2
  22. package/dist/editor/visual-editor.d.ts.map +1 -1
  23. package/dist/index.d.mts +25 -3
  24. package/dist/index.d.ts +2 -0
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/joryio-cards-ui.min.js +1 -1
  27. package/dist/joryio-cards-ui.min.js.map +1 -1
  28. package/dist/joryio-editor.min.js +2 -2
  29. package/dist/joryio-editor.min.js.map +1 -1
  30. package/dist/joryio-sw.js +1 -1
  31. package/dist/joryio.cjs.js +631 -26
  32. package/dist/joryio.min.js +2 -2
  33. package/dist/joryio.min.js.map +1 -1
  34. package/dist/joryio.mjs +631 -27
  35. package/dist/joryio.umd.js +631 -26
  36. package/package.json +1 -1
  37. package/src/core/config.ts +1 -1
  38. package/src/core/editor-gate.ts +21 -0
  39. package/src/core/page-context.ts +84 -1
  40. package/src/core/page-edits.ts +149 -5
  41. package/src/core/placements.ts +373 -6
  42. package/src/core/sdk.ts +79 -1
  43. package/src/core/show-when.ts +159 -0
  44. package/src/editor/editor-strings.ts +11 -0
  45. package/src/editor/editor-ui.ts +15 -1
  46. package/src/editor/liquid-field.ts +17 -2
  47. package/src/editor/visual-editor.ts +350 -75
  48. package/src/index.ts +4 -0
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Joryio Web SDK v1.4.0-beta.7
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.7';
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,8 +610,119 @@ 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';
714
+ const PAGE_EDIT_DEVICES = ['all', 'mobile', 'desktop'];
715
+ const PAGE_EDIT_MOBILE_BREAKPOINT = 768;
716
+ const PAGE_EDIT_MOBILE_QUERY = '(max-width: 767.98px)';
717
+ function isMobileViewport(win = window) {
718
+ try {
719
+ return typeof win.matchMedia === 'function' ? win.matchMedia(PAGE_EDIT_MOBILE_QUERY).matches : win.innerWidth < PAGE_EDIT_MOBILE_BREAKPOINT;
720
+ }
721
+ catch (_a) {
722
+ return false;
723
+ }
724
+ }
725
+ const editShowsOn = (e, mobile) => !e.device || e.device === 'all' || (e.device === 'mobile') === mobile;
555
726
  const PAGE_EDIT_ANTI_FLICKER_MS = 300;
556
727
  const MAX_SELECTOR_LENGTH = 500;
557
728
  const MAX_TEXT_LENGTH = 2000;
@@ -574,13 +745,14 @@ const SERVER_ORIG_ATTR = 'data-joryio-orig';
574
745
  const SERVER_SPOT_ATTR = 'data-joryio-server-spot';
575
746
  const SERVER_MARKER_VERSION = 1;
576
747
  const sameEdit = (a, b) => {
577
- var _a, _b, _c, _d, _e, _f;
748
+ var _a, _b, _c, _d, _e, _f, _g, _h;
578
749
  return a.id === b.id &&
579
750
  a.selector === b.selector &&
580
751
  a.operation === b.operation &&
581
752
  ((_a = a.value) !== null && _a !== void 0 ? _a : null) === ((_b = b.value) !== null && _b !== void 0 ? _b : null) &&
582
753
  ((_c = a.placementKey) !== null && _c !== void 0 ? _c : null) === ((_d = b.placementKey) !== null && _d !== void 0 ? _d : null) &&
583
754
  ((_e = a.position) !== null && _e !== void 0 ? _e : null) === ((_f = b.position) !== null && _f !== void 0 ? _f : null) &&
755
+ ((_g = a.device) !== null && _g !== void 0 ? _g : null) === ((_h = b.device) !== null && _h !== void 0 ? _h : null) &&
584
756
  !b.personalized;
585
757
  };
586
758
  function serverMarkerElement() {
@@ -707,7 +879,10 @@ function isSafeEditUrl(url) {
707
879
  function trustedEdit(e) {
708
880
  if (!e || typeof e !== 'object' || typeof e.id !== 'string' || !isSafeSelector(e.selector))
709
881
  return null;
710
- const base = Object.assign({ id: e.id, selector: e.selector.trim() }, (e.personalized === true ? { personalized: true } : {}));
882
+ const device = e.device;
883
+ if (device != null && !PAGE_EDIT_DEVICES.includes(device))
884
+ return null;
885
+ const base = Object.assign(Object.assign({ id: e.id, selector: e.selector.trim() }, (device === 'mobile' || device === 'desktop' ? { device: device } : {})), (e.personalized === true ? { personalized: true } : {}));
711
886
  switch (e.operation) {
712
887
  case 'hide':
713
888
  return Object.assign(Object.assign({}, base), { operation: 'hide' });
@@ -746,8 +921,15 @@ class PageEditManager {
746
921
  this.server = null;
747
922
  this.serverUrl = null;
748
923
  this.generation = 0;
924
+ this.mobile = false;
925
+ this.offMedia = null;
749
926
  this.started = false;
750
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();
751
933
  this.stores = pageEditsStorageKeys(sdkKey);
752
934
  try {
753
935
  localStorage.removeItem(LEGACY_SELECTOR_STORE);
@@ -768,7 +950,45 @@ class PageEditManager {
768
950
  });
769
951
  }
770
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
+ }
771
990
  start() {
991
+ var _a;
772
992
  if (this.started || this.destroyed || typeof document === 'undefined')
773
993
  return;
774
994
  this.started = true;
@@ -776,8 +996,28 @@ class PageEditManager {
776
996
  this.observer = new MutationObserver(() => this.schedule());
777
997
  this.observer.observe(document.documentElement, { childList: true, subtree: true });
778
998
  }
999
+ this.mobile = isMobileViewport();
1000
+ const mq = typeof window.matchMedia === 'function' ? window.matchMedia(PAGE_EDIT_MOBILE_QUERY) : null;
1001
+ if (mq) {
1002
+ const onChange = () => this.viewportChanged();
1003
+ if (mq.addEventListener)
1004
+ mq.addEventListener('change', onChange);
1005
+ else
1006
+ (_a = mq.addListener) === null || _a === void 0 ? void 0 : _a.call(mq, onChange);
1007
+ this.offMedia = () => { var _a; return (mq.removeEventListener ? mq.removeEventListener('change', onChange) : (_a = mq.removeListener) === null || _a === void 0 ? void 0 : _a.call(mq, onChange)); };
1008
+ }
779
1009
  this.loadPage();
780
1010
  }
1011
+ viewportChanged() {
1012
+ const mobile = isMobileViewport();
1013
+ if (this.destroyed || mobile === this.mobile)
1014
+ return;
1015
+ this.mobile = mobile;
1016
+ if (!this.experiences.some((x) => x.edits.some((e) => e.device)))
1017
+ return;
1018
+ this.revertAll();
1019
+ this.applyAll();
1020
+ }
781
1021
  invalidate(opts = {}) {
782
1022
  this.generation++;
783
1023
  this.reported.clear();
@@ -792,10 +1032,13 @@ class PageEditManager {
792
1032
  this.loadPage();
793
1033
  }
794
1034
  destroy() {
795
- var _a, _b;
1035
+ var _a, _b, _c, _d;
796
1036
  this.destroyed = true;
797
1037
  (_a = this.pageUnsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
798
- (_b = this.observer) === null || _b === void 0 ? void 0 : _b.disconnect();
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);
1040
+ this.offMedia = null;
1041
+ (_d = this.observer) === null || _d === void 0 ? void 0 : _d.disconnect();
799
1042
  this.observer = null;
800
1043
  this.revertAll();
801
1044
  this.showAll();
@@ -812,6 +1055,9 @@ class PageEditManager {
812
1055
  loadPage() {
813
1056
  const generation = ++this.generation;
814
1057
  this.revertAll();
1058
+ this.revealed.clear();
1059
+ this.rechecked.clear();
1060
+ this.recheckOn = [];
815
1061
  const url = this.url();
816
1062
  if (!url) {
817
1063
  this.experiences = [];
@@ -947,7 +1193,7 @@ class PageEditManager {
947
1193
  this.siteRequest = request;
948
1194
  return request;
949
1195
  }
950
- async fetch(url, generation) {
1196
+ async fetch(url, generation, recheckEvent) {
951
1197
  var _a, _b, _c, _d;
952
1198
  const consent = this.runtime.consent();
953
1199
  if (consent === null || this.destroyed) {
@@ -957,7 +1203,7 @@ class PageEditManager {
957
1203
  const personal = consent === 'granted';
958
1204
  const userId = personal ? this.identity.getUserId() : null;
959
1205
  const anonymousId = personal ? this.identity.getAnonymousId() : null;
960
- 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], 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 } : {}));
961
1207
  const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
962
1208
  const timeout = setTimeout(() => controller === null || controller === void 0 ? void 0 : controller.abort(), (_a = this.runtime.requestTimeoutMs) !== null && _a !== void 0 ? _a : 10000);
963
1209
  try {
@@ -976,6 +1222,7 @@ class PageEditManager {
976
1222
  .map((wire) => ({ wire, edits: (Array.isArray(wire.edits) ? wire.edits : []).map(trustedEdit).filter((e) => !!e) }));
977
1223
  this.revertAll();
978
1224
  this.experiences = experiences;
1225
+ this.recheckOn = eventNames(data.recheckOn);
979
1226
  this.reconcileServer(experiences);
980
1227
  this.remember(url, experiences, data.ttlSeconds);
981
1228
  this.applyAll();
@@ -1009,6 +1256,8 @@ class PageEditManager {
1009
1256
  (_a = this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
1010
1257
  try {
1011
1258
  for (const x of this.experiences) {
1259
+ if (!this.due(x.wire))
1260
+ continue;
1012
1261
  if (x.wire.isControl) {
1013
1262
  const seen = (x.wire.selectors || []).some((s) => isSafeSelector(s) && this.query(s).length > 0);
1014
1263
  if (seen)
@@ -1017,6 +1266,8 @@ class PageEditManager {
1017
1266
  }
1018
1267
  let landed = false;
1019
1268
  for (const edit of x.edits) {
1269
+ if (!editShowsOn(edit, this.mobile))
1270
+ continue;
1020
1271
  const token = `${x.wire.id}:${edit.id}`;
1021
1272
  const server = this.serverEdits().get(token);
1022
1273
  const byServer = !!server && server.variantId === ((_b = x.wire.variantId) !== null && _b !== void 0 ? _b : null) && sameEdit(server.edit, edit);
@@ -1164,7 +1415,7 @@ class PageEditManager {
1164
1415
  return `${this.identity.getUserId() || ''}|${this.identity.getAnonymousId()}`;
1165
1416
  }
1166
1417
  remember(url, experiences, ttlSeconds) {
1167
- const selectors = [...new Set(experiences.flatMap((x) => (x.wire.isControl ? [] : x.edits.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))))];
1168
1419
  try {
1169
1420
  const all = JSON.parse(localStorage.getItem(this.stores.selectors) || '{}') || {};
1170
1421
  delete all[url];
@@ -1258,7 +1509,7 @@ class PageEditManager {
1258
1509
  return;
1259
1510
  const keep = new Set();
1260
1511
  for (const x of experiences) {
1261
- if (x.wire.isControl)
1512
+ if (x.wire.isControl || isDeferred(x.wire.showWhen))
1262
1513
  continue;
1263
1514
  for (const e of x.edits) {
1264
1515
  const token = `${x.wire.id}:${e.id}`;
@@ -1481,6 +1732,19 @@ function editorRequested() {
1481
1732
  return false;
1482
1733
  }
1483
1734
  }
1735
+ const EDITOR_FRAME_FLAG = 'frame';
1736
+ function editorFrame() {
1737
+ try {
1738
+ if (typeof window === 'undefined' || window.parent === window)
1739
+ return false;
1740
+ if (new URLSearchParams(window.location.search).get(EDITOR_QUERY_FLAG) !== EDITOR_FRAME_FLAG)
1741
+ return false;
1742
+ return !!window.parent[EDITOR_GLOBAL];
1743
+ }
1744
+ catch (_a) {
1745
+ return false;
1746
+ }
1747
+ }
1484
1748
  function loadScript(src) {
1485
1749
  return loadSdkScript(src, 'data-joryio-editor');
1486
1750
  }
@@ -5607,6 +5871,9 @@ const PLACEMENT_PRODUCT_CARD_WIDTH = 160;
5607
5871
  function placementProductElementId(productId) {
5608
5872
  return `${PLACEMENT_PRODUCT_ELEMENT_PREFIX}${productId}`.slice(0, 128);
5609
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';
5610
5877
  const DEFAULT_TTL_SECONDS = 300;
5611
5878
  const LEGACY_CACHE_STORAGE_NAME = 'joryio_placements_v1';
5612
5879
  const placementsStorageKey = (sdkKey) => `joryio_placements_v1_${bucketHash(sdkKey).toString(36)}`;
@@ -5723,7 +5990,14 @@ class PlacementManager {
5723
5990
  this.destroyed = false;
5724
5991
  this.page = null;
5725
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;
5726
5999
  this.pageScopedKeys = new Set();
6000
+ this.markerFills = null;
5727
6001
  this.loadCache();
5728
6002
  this.installBridge();
5729
6003
  this.installPageVisibility();
@@ -5752,6 +6026,7 @@ class PlacementManager {
5752
6026
  hostObserver: null,
5753
6027
  trackers: [],
5754
6028
  frameIds: [],
6029
+ serverFill: this.serverFillOf(key, element),
5755
6030
  };
5756
6031
  this.mounts.add(mount);
5757
6032
  this.observeHost(mount);
@@ -5823,6 +6098,8 @@ class PlacementManager {
5823
6098
  this.triggeredAt.clear();
5824
6099
  this.dismissedLocally.clear();
5825
6100
  this.reported.clear();
6101
+ this.revealed.clear();
6102
+ this.spotViewable.clear();
5826
6103
  this.persistCache();
5827
6104
  const keys = this.mountedKeys();
5828
6105
  for (const mount of this.mounts)
@@ -5831,13 +6108,15 @@ class PlacementManager {
5831
6108
  this.fetchKeys(keys, true).catch(() => undefined);
5832
6109
  }
5833
6110
  destroy() {
5834
- var _a, _b, _c;
6111
+ var _a, _b, _c, _d;
5835
6112
  this.destroyed = true;
5836
6113
  (_a = this.pageUnsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
5837
6114
  this.pageUnsubscribe = null;
6115
+ (_b = this.momentsUnsubscribe) === null || _b === void 0 ? void 0 : _b.call(this);
6116
+ this.momentsUnsubscribe = null;
5838
6117
  for (const mount of Array.from(this.mounts))
5839
6118
  this.unmount(mount);
5840
- (_b = this.mutationObserver) === null || _b === void 0 ? void 0 : _b.disconnect();
6119
+ (_c = this.mutationObserver) === null || _c === void 0 ? void 0 : _c.disconnect();
5841
6120
  this.mutationObserver = null;
5842
6121
  if (this.batchTimer)
5843
6122
  clearTimeout(this.batchTimer);
@@ -5852,11 +6131,11 @@ class PlacementManager {
5852
6131
  document.removeEventListener('visibilitychange', this.pageListener);
5853
6132
  }
5854
6133
  try {
5855
- 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) {
5856
6135
  delete window[PLACEMENT_BRIDGE_GLOBAL];
5857
6136
  }
5858
6137
  }
5859
- catch (_d) {
6138
+ catch (_e) {
5860
6139
  }
5861
6140
  }
5862
6141
  cleanKeys(keys) {
@@ -5885,11 +6164,23 @@ class PlacementManager {
5885
6164
  this.pageUnsubscribe = tracker.onSignal((signal) => {
5886
6165
  if (signal.type !== 'page_change' || this.destroyed)
5887
6166
  return;
6167
+ const held = this.revealed.size ? this.keysWithMoments() : [];
6168
+ this.revealed.clear();
6169
+ this.spotViewable.clear();
6170
+ this.rechecked.clear();
5888
6171
  const stale = [];
5889
6172
  this.cache.forEach((entry, key) => {
5890
6173
  if (entry.placement.pageScoped && entry.url !== signal.url)
5891
6174
  stale.push(key);
5892
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
+ }
5893
6184
  if (!stale.length)
5894
6185
  return;
5895
6186
  stale.forEach((key) => this.cache.delete(key));
@@ -5909,6 +6200,75 @@ class PlacementManager {
5909
6200
  }
5910
6201
  });
5911
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
+ }
5912
6272
  currentUrl() {
5913
6273
  return this.page ? this.page.current().url : currentPageUrl();
5914
6274
  }
@@ -5980,19 +6340,21 @@ class PlacementManager {
5980
6340
  this.batchKeys.clear();
5981
6341
  const waiters = this.batchWaiters;
5982
6342
  this.batchWaiters = [];
6343
+ const recheckEvent = this.recheckEvent;
6344
+ this.recheckEvent = null;
5983
6345
  const chunks = [];
5984
6346
  for (let i = 0; i < keys.length; i += PLACEMENT_MAX_KEYS_PER_REQUEST) {
5985
6347
  chunks.push(keys.slice(i, i + PLACEMENT_MAX_KEYS_PER_REQUEST));
5986
6348
  }
5987
6349
  try {
5988
- await Promise.all(chunks.map((chunk) => this.request(chunk)));
6350
+ await Promise.all(chunks.map((chunk) => this.request(chunk, recheckEvent)));
5989
6351
  }
5990
6352
  finally {
5991
6353
  keys.forEach((key) => this.inflight.delete(key));
5992
6354
  waiters.forEach((w) => w.resolve());
5993
6355
  }
5994
6356
  }
5995
- async request(keys) {
6357
+ async request(keys, recheckEvent) {
5996
6358
  var _a, _b, _c, _d;
5997
6359
  const consent = this.runtime.consent();
5998
6360
  if (consent === null || this.destroyed)
@@ -6009,7 +6371,7 @@ class PlacementManager {
6009
6371
  }
6010
6372
  const userId = personal ? this.identity.getUserId() : null;
6011
6373
  const anonymousId = personal ? this.identity.getAnonymousId() : null;
6012
- 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 } : {}));
6013
6375
  const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
6014
6376
  const timeout = setTimeout(() => controller === null || controller === void 0 ? void 0 : controller.abort(), (_a = this.runtime.requestTimeoutMs) !== null && _a !== void 0 ? _a : 10000);
6015
6377
  const url = `${this.apiEndpoint}/v1/in-app/placements`;
@@ -6067,7 +6429,9 @@ class PlacementManager {
6067
6429
  }
6068
6430
  normalize(key, wire) {
6069
6431
  const items = Array.isArray(wire.items) ? wire.items.filter((i) => i && typeof i.id === 'string') : [];
6070
- 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) } : {}));
6071
6435
  }
6072
6436
  applyChanged(keys) {
6073
6437
  for (const mount of this.mounts) {
@@ -6078,6 +6442,9 @@ class PlacementManager {
6078
6442
  else
6079
6443
  this.render(mount);
6080
6444
  }
6445
+ this.notify(keys);
6446
+ }
6447
+ notify(keys) {
6081
6448
  if (!this.listeners.size)
6082
6449
  return;
6083
6450
  const update = {};
@@ -6106,6 +6473,8 @@ class PlacementManager {
6106
6473
  return false;
6107
6474
  if (this.dismissedLocally.has(this.handle(key, item)))
6108
6475
  return false;
6476
+ if (item.showWhen !== undefined && !this.due(this.handle(key, item), item.showWhen))
6477
+ return false;
6109
6478
  const eventTriggers = (item.triggers || []).filter((t) => t.type === 'event');
6110
6479
  if (eventTriggers.length) {
6111
6480
  const at = this.triggeredAt.get(this.handle(key, item));
@@ -6128,7 +6497,12 @@ class PlacementManager {
6128
6497
  emptyBehavior: wire.emptyBehavior || 'collapse',
6129
6498
  maxItems: wire.maxItems || 1,
6130
6499
  ttlSeconds: wire.ttlSeconds || DEFAULT_TTL_SECONDS,
6131
- 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
+ },
6132
6506
  };
6133
6507
  }
6134
6508
  current(generation) {
@@ -6158,6 +6532,8 @@ class PlacementManager {
6158
6532
  this.render(mount);
6159
6533
  }
6160
6534
  report(key, item, type, elementId) {
6535
+ if (type === 'displayed')
6536
+ this.markSpotViewable(key);
6161
6537
  if (this.runtime.consent() !== 'granted')
6162
6538
  return;
6163
6539
  const once = `${type}:${this.handle(key, item)}`;
@@ -6177,13 +6553,33 @@ class PlacementManager {
6177
6553
  const entry = this.cache.get(key);
6178
6554
  if (!(entry === null || entry === void 0 ? void 0 : entry.placement.isControl) || !entry.placement.controlToken)
6179
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) {
6180
6576
  if (this.runtime.consent() !== 'granted')
6181
6577
  return;
6182
- const once = `control:${entry.placement.controlToken}`;
6578
+ const once = `control:${controlToken}`;
6183
6579
  if (this.reported.has(once))
6184
6580
  return;
6185
6581
  this.reported.add(once);
6186
- 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() }));
6187
6583
  }
6188
6584
  subject() {
6189
6585
  const userId = this.identity.getUserId();
@@ -6236,15 +6632,143 @@ class PlacementManager {
6236
6632
  }
6237
6633
  clearDrawn(mount) {
6238
6634
  var _a;
6635
+ if (mount.serverFill) {
6636
+ this.dropServerFill(mount.element, mount.serverFill.wrapper);
6637
+ mount.serverFill = null;
6638
+ }
6239
6639
  mount.frameIds.forEach((id) => this.frames.delete(id));
6240
6640
  mount.frameIds = [];
6241
6641
  (_a = mount.wrapper) === null || _a === void 0 ? void 0 : _a.remove();
6242
6642
  mount.wrapper = null;
6243
6643
  mount.shown = [];
6244
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
+ }
6245
6767
  render(mount) {
6246
6768
  if (!this.mounts.has(mount))
6247
6769
  return;
6770
+ if (mount.serverFill && this.settleServerFill(mount) !== 'dropped')
6771
+ return;
6248
6772
  mount.pendingUpdate = false;
6249
6773
  this.clearTrackers(mount);
6250
6774
  this.clearDrawn(mount);
@@ -6270,7 +6794,10 @@ class PlacementManager {
6270
6794
  if (!drawn.length) {
6271
6795
  wrapper.style.display = placement.emptyBehavior === 'keep_space' ? '' : 'none';
6272
6796
  if (placement.isControl && (entry === null || entry === void 0 ? void 0 : entry.placement.controlToken)) {
6273
- 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
+ });
6274
6801
  }
6275
6802
  }
6276
6803
  if (mount.options.onRender) {
@@ -6612,6 +7139,22 @@ class PlacementManager {
6612
7139
  }
6613
7140
  }
6614
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
+ }
6615
7158
  function toProducts(raw) {
6616
7159
  if (!Array.isArray(raw))
6617
7160
  return [];
@@ -9301,6 +9844,7 @@ class JoryioSDK {
9301
9844
  this.attributeGeneration = 0;
9302
9845
  this.attributeFailures = 0;
9303
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 = [];
9304
9848
  this.editor = null;
9305
9849
  this._ecommerce = null;
9306
9850
  this.isInitialized = false;
@@ -9339,6 +9883,9 @@ class JoryioSDK {
9339
9883
  console.error(`[Joryio] SDK not started: ${keyProblem}. Calls on this instance are ignored.`);
9340
9884
  this.disabled = true;
9341
9885
  }
9886
+ else if (editorFrame()) {
9887
+ this.disabled = true;
9888
+ }
9342
9889
  this.config = resolveConfig(keyProblem
9343
9890
  ? Object.assign(Object.assign({}, (config && typeof config === 'object' ? config : {})), { sdkKey: 'jry_sdk_invalid', optOut: false }) : config);
9344
9891
  this.logger = new Logger(this.config.loggingEnabled, this.config.logLevel);
@@ -9439,6 +9986,11 @@ class JoryioSDK {
9439
9986
  this.pageContext = new PageContextTracker(this.config.pageContext);
9440
9987
  this.pageContext.setUtmSource(() => (this.config.captureUTM && this.utm ? this.utm.getUTMData() : null));
9441
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
+ });
9442
9994
  this.placements = new PlacementManager(this.config.apiEndpoint, this.config.sdkKey, this.identity, this.session, this.logger, {
9443
9995
  consent: () => this.placementConsent(),
9444
9996
  allowHtml: () => this.config.inApp.allowHtmlJsInAppMessages,
@@ -9454,12 +10006,14 @@ class JoryioSDK {
9454
10006
  },
9455
10007
  }, this.network);
9456
10008
  this.placements.setPageContext(this.pageContext);
10009
+ this.placements.setShowWhen(this.showWhen);
9457
10010
  this.pageEdits = new PageEditManager(this.config.apiEndpoint, this.config.sdkKey, this.identity, this.session, this.logger, {
9458
10011
  consent: () => this.placementConsent(),
9459
10012
  requestTimeoutMs: this.config.requestTimeout,
9460
10013
  noteStatus: (status, data) => this.network.noteSuspended(status, data),
9461
10014
  }, this.network);
9462
10015
  this.pageEdits.setPageContext(this.pageContext);
10016
+ this.pageEdits.setShowWhen(this.showWhen);
9463
10017
  this.cards = new CardManager(this.config.apiEndpoint, this.config.sdkKey, this.identity, this.session, this.logger, {
9464
10018
  consent: () => this.placementConsent(),
9465
10019
  requestTimeoutMs: this.config.requestTimeout,
@@ -9499,6 +10053,8 @@ class JoryioSDK {
9499
10053
  return await this.flushEvents(events, identify);
9500
10054
  }
9501
10055
  finally {
10056
+ if (this.pendingRechecks.length)
10057
+ setTimeout(() => this.runRechecks(), 0);
9502
10058
  this.scheduleRetiredTokenPrune();
9503
10059
  }
9504
10060
  });
@@ -9795,6 +10351,7 @@ class JoryioSDK {
9795
10351
  this.network.switchUser(userId);
9796
10352
  this.identity.adopt(anonymousId, userId);
9797
10353
  this.placements.invalidate();
10354
+ this.pendingRechecks = [];
9798
10355
  this.cards.invalidate(true);
9799
10356
  (_b = this.pageEdits) === null || _b === void 0 ? void 0 : _b.invalidate();
9800
10357
  this.flags.onIdentityChanged();
@@ -10060,6 +10617,7 @@ class JoryioSDK {
10060
10617
  if (wasOptedOut !== this.isOptedOut || wasPending !== this.consentPending) {
10061
10618
  this.inapp.invalidate();
10062
10619
  (_a = this.placements) === null || _a === void 0 ? void 0 : _a.invalidate();
10620
+ this.pendingRechecks = [];
10063
10621
  (_b = this.cards) === null || _b === void 0 ? void 0 : _b.invalidate(false);
10064
10622
  (_c = this.pageEdits) === null || _c === void 0 ? void 0 : _c.invalidate({ siteSettings: true });
10065
10623
  (_d = this.flags) === null || _d === void 0 ? void 0 : _d.onIdentityChanged();
@@ -10263,7 +10821,7 @@ class JoryioSDK {
10263
10821
  this.track('Page Viewed', properties);
10264
10822
  }
10265
10823
  track(eventName, properties) {
10266
- var _a, _b;
10824
+ var _a, _b, _c;
10267
10825
  if (!this.isInitialized) {
10268
10826
  this.logger.error('SDK not initialized');
10269
10827
  return;
@@ -10329,6 +10887,8 @@ class JoryioSDK {
10329
10887
  try {
10330
10888
  (_a = this.inapp) === null || _a === void 0 ? void 0 : _a.onEventTracked(eventName, eventProperties);
10331
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);
10332
10892
  }
10333
10893
  catch (error) {
10334
10894
  this.logger.error('In-app trigger evaluation failed:', error);
@@ -10352,6 +10912,45 @@ class JoryioSDK {
10352
10912
  this.logger.error('track() failed:', error);
10353
10913
  }
10354
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
+ }
10355
10954
  identify(userId) {
10356
10955
  var _a;
10357
10956
  if (!this.isInitialized) {
@@ -10387,6 +10986,7 @@ class JoryioSDK {
10387
10986
  if (previousUserId !== userId) {
10388
10987
  this.inapp.invalidate();
10389
10988
  this.placements.invalidate();
10989
+ this.pendingRechecks = [];
10390
10990
  this.cards.invalidate(true);
10391
10991
  (_a = this.pageEdits) === null || _a === void 0 ? void 0 : _a.invalidate();
10392
10992
  this.flags.onIdentityChanged();
@@ -10723,6 +11323,7 @@ class JoryioSDK {
10723
11323
  this.flags.onIdentityChanged();
10724
11324
  this.network.setCurrentUserId(this.identity.getUserId());
10725
11325
  this.placements.invalidate();
11326
+ this.pendingRechecks = [];
10726
11327
  this.cards.invalidate(true);
10727
11328
  (_a = this.pageEdits) === null || _a === void 0 ? void 0 : _a.invalidate({ siteSettings: true });
10728
11329
  this.utm.reset();
@@ -10789,6 +11390,7 @@ class JoryioSDK {
10789
11390
  this.flags.onIdentityChanged();
10790
11391
  this.network.setCurrentUserId(null);
10791
11392
  this.placements.invalidate();
11393
+ this.pendingRechecks = [];
10792
11394
  (_a = this.cards) === null || _a === void 0 ? void 0 : _a.invalidate(true);
10793
11395
  (_b = this.pageEdits) === null || _b === void 0 ? void 0 : _b.invalidate({ siteSettings: true });
10794
11396
  this.utm.reset();
@@ -11385,7 +11987,7 @@ class JoryioSDK {
11385
11987
  return this.flags.onFlagsUpdated(callback);
11386
11988
  }
11387
11989
  async destroy() {
11388
- var _a, _b, _c;
11990
+ var _a, _b, _c, _d;
11389
11991
  if (!this.isInitialized) {
11390
11992
  return;
11391
11993
  }
@@ -11427,7 +12029,9 @@ class JoryioSDK {
11427
12029
  this.cards.destroy();
11428
12030
  (_a = this.pageEdits) === null || _a === void 0 ? void 0 : _a.destroy();
11429
12031
  (_b = this.editor) === null || _b === void 0 ? void 0 : _b.stop();
11430
- (_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();
11431
12035
  this.flags.destroy();
11432
12036
  this.isInitialized = false;
11433
12037
  if (JoryioSDK.instance === this)
@@ -11627,6 +12231,7 @@ exports.PLACEMENT_PRODUCT_ELEMENT_PREFIX = PLACEMENT_PRODUCT_ELEMENT_PREFIX;
11627
12231
  exports.PLACEMENT_VIEWABLE_FRACTION = PLACEMENT_VIEWABLE_FRACTION;
11628
12232
  exports.PushManager = PushManager;
11629
12233
  exports.SDK_VERSION = SDK_VERSION;
12234
+ exports.SHOW_WHEN_KINDS = SHOW_WHEN_KINDS;
11630
12235
  exports.User = User;
11631
12236
  exports.createEcommerceTracker = createEcommerceTracker;
11632
12237
  exports.default = JoryioSDK;