@joryio/web-sdk 1.3.2 → 1.3.3-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/core/inapp.ts CHANGED
@@ -258,6 +258,32 @@ const MAX_DISPLAYED_MESSAGES = 500;
258
258
  const MAX_IMPRESSION_TIMESTAMPS = 500;
259
259
  const MAX_WATCHED_ATTRIBUTES = 200;
260
260
 
261
+ /**
262
+ * How long (ms) a message must have been on screen - page visible, message
263
+ * mounted, page not unloading - before it counts as displayed: only then is
264
+ * `in_app.displayed` reported and the local frequency cap consumed. Same name
265
+ * and value in every SDK (backend sdk-inapp-display-dwell-parity.spec.ts).
266
+ *
267
+ * Why: a message mounted during a sign-in redirect or a logout - served and
268
+ * "displayed" in the same second, seen at most as a flash - used to be counted,
269
+ * which spent the campaign's frequency cap on a message nobody could read
270
+ * (prod 2026-11-02/03, BACKLOG D320). A click or a dismiss before the dwell
271
+ * means the person saw it: it counts as displayed, then clicked/dismissed.
272
+ */
273
+ export const IN_APP_DISPLAY_DWELL_MS = 1000;
274
+ /** No requestIdleCallback (Safari): wait this long after `load` instead. */
275
+ const PAGE_SETTLE_FALLBACK_MS = 50;
276
+ /** requestIdleCallback's timeout: a page that is never idle still shows the message. */
277
+ const PAGE_SETTLE_IDLE_TIMEOUT_MS = 500;
278
+ /** `load` never fired (a hung resource): stop waiting for it after this. */
279
+ const PAGE_LOAD_MAX_WAIT_MS = 10_000;
280
+ /**
281
+ * Dismiss actions a PERSON takes on the message. Any other dismiss (reset,
282
+ * destroy, the host's dismissInAppMessage, a blocked frame navigation) before
283
+ * the dwell reports nothing: there is no evidence anyone saw the message.
284
+ */
285
+ const USER_DISMISS_ACTIONS = new Set(['close_button', 'backdrop', 'button', 'bridge_close']);
286
+
261
287
  /** The shape of a parsed CSS rule this module cares about - a structural
262
288
  * subset of CSSOM, so the rewriting below is testable without a browser. */
263
289
  interface ScopableRule {
@@ -420,6 +446,17 @@ export class InAppMessagingManager {
420
446
  * burst cannot both pass the "already shown?" check (contract item 27).
421
447
  */
422
448
  private claimed = new Set<string>();
449
+ /**
450
+ * Messages on screen that have not yet counted as displayed, with their
451
+ * dwell timer (null while paused: page hidden or unloading) and the
452
+ * generation they were shown under. See IN_APP_DISPLAY_DWELL_MS.
453
+ */
454
+ private awaitingDwell = new Map<string, { timer: ReturnType<typeof setTimeout> | null; generation: number }>();
455
+ /** beforeunload/pagehide seen and not yet undone (pageshow, visible again, or interaction). */
456
+ private pageLeaving = false;
457
+ /** Pending "wait for the page to settle" promises, resolved false when the page starts leaving. */
458
+ private settleWaiters = new Set<() => void>();
459
+ private pageListeners: Array<[any, string, () => void]> = [];
423
460
  // Per-campaign content iframe (so we can auto-size + clean it up).
424
461
  private iframes: Map<string, HTMLIFrameElement> = new Map();
425
462
  /**
@@ -521,6 +558,186 @@ export class InAppMessagingManager {
521
558
  this.auth = auth || null;
522
559
  this.loadImpressionTimestamps();
523
560
  this.installHostBridge();
561
+ this.installPageLifecycle();
562
+ }
563
+
564
+ // ---------------------------------------------------------------------------
565
+ // When a message may appear, and when it counts as displayed
566
+ // (IN_APP_DISPLAY_DWELL_MS).
567
+ // ---------------------------------------------------------------------------
568
+
569
+ private pageHidden(): boolean {
570
+ if (typeof document === 'undefined') return false;
571
+ return (document as any).visibilityState === 'hidden' || (document as any).hidden === true;
572
+ }
573
+
574
+ /**
575
+ * Watch the page leaving and coming back. `beforeunload` is the one that
576
+ * matters for a sign-in redirect or a logout link: it fires when navigation
577
+ * STARTS, while `pagehide` waits for the next page to be ready.
578
+ */
579
+ private installPageLifecycle(): void {
580
+ if (typeof window === 'undefined' || typeof (window as any).addEventListener !== 'function') return;
581
+ const on = (target: any, type: string, fn: () => void) => {
582
+ if (!target || typeof target.addEventListener !== 'function') return;
583
+ target.addEventListener(type, fn);
584
+ this.pageListeners.push([target, type, fn]);
585
+ };
586
+ const leaving = () => {
587
+ this.pageLeaving = true;
588
+ this.pauseDwells();
589
+ this.settleWaiters.forEach((cancel) => cancel());
590
+ };
591
+ // The page is still here after all: bfcache restore, a cancelled
592
+ // "leave site?" prompt or a download link (the person then interacts).
593
+ const stayed = () => {
594
+ if (!this.pageLeaving) return;
595
+ this.pageLeaving = false;
596
+ this.resumeDwells();
597
+ };
598
+ on(window, 'beforeunload', leaving);
599
+ on(window, 'pagehide', leaving);
600
+ on(window, 'pageshow', () => {
601
+ this.pageLeaving = false;
602
+ this.resumeDwells();
603
+ });
604
+ on(window, 'pointerdown', stayed);
605
+ on(window, 'keydown', stayed);
606
+ if (typeof document !== 'undefined') {
607
+ on(document, 'visibilitychange', () => {
608
+ if (this.pageHidden()) {
609
+ this.pauseDwells();
610
+ } else {
611
+ this.pageLeaving = false;
612
+ this.resumeDwells();
613
+ }
614
+ });
615
+ }
616
+ }
617
+
618
+ private removePageLifecycle(): void {
619
+ for (const [target, type, fn] of this.pageListeners) {
620
+ try {
621
+ target.removeEventListener?.(type, fn);
622
+ } catch {
623
+ // best-effort
624
+ }
625
+ }
626
+ this.pageListeners = [];
627
+ }
628
+
629
+ /**
630
+ * Resolves true once the page has finished loading and gone idle - the
631
+ * point at which a message can be read - or false if the page starts to
632
+ * unload first (or the manager is stopped). A message is never mounted into
633
+ * a page that is on its way out.
634
+ */
635
+ private whenPageSettled(): Promise<boolean> {
636
+ if (typeof window === 'undefined' || typeof document === 'undefined') return Promise.resolve(true);
637
+ if (this.pageLeaving) return Promise.resolve(false);
638
+ return new Promise<boolean>((resolve) => {
639
+ let done = false;
640
+ let loadTimer: ReturnType<typeof setTimeout> | undefined;
641
+ let idleTimer: ReturnType<typeof setTimeout> | undefined;
642
+ const w = window as any;
643
+ const finish = (ok: boolean) => {
644
+ if (done) return;
645
+ done = true;
646
+ this.settleWaiters.delete(cancel);
647
+ if (loadTimer) clearTimeout(loadTimer);
648
+ if (idleTimer) clearTimeout(idleTimer);
649
+ if (typeof w.removeEventListener === 'function') w.removeEventListener('load', onLoad);
650
+ resolve(ok && !this.pageLeaving);
651
+ };
652
+ const cancel = () => finish(false);
653
+ const idle = () => {
654
+ if (done) return;
655
+ if (typeof w.requestIdleCallback === 'function') {
656
+ w.requestIdleCallback(() => finish(true), { timeout: PAGE_SETTLE_IDLE_TIMEOUT_MS });
657
+ } else {
658
+ idleTimer = setTimeout(() => finish(true), PAGE_SETTLE_FALLBACK_MS);
659
+ }
660
+ };
661
+ const onLoad = () => {
662
+ if (loadTimer) clearTimeout(loadTimer);
663
+ loadTimer = undefined;
664
+ idle();
665
+ };
666
+ this.settleWaiters.add(cancel);
667
+ const state = (document as any).readyState;
668
+ if (!state || state === 'complete' || typeof w.addEventListener !== 'function') {
669
+ idle();
670
+ } else {
671
+ w.addEventListener('load', onLoad, { once: true });
672
+ loadTimer = setTimeout(onLoad, PAGE_LOAD_MAX_WAIT_MS);
673
+ }
674
+ });
675
+ }
676
+
677
+ private isMounted(campaignId: string): boolean {
678
+ if (!this.displayedMessages.has(campaignId) || typeof document === 'undefined') return false;
679
+ const el: any = document.getElementById(`joryio-inapp-${campaignId}`);
680
+ return !!el && el.isConnected !== false;
681
+ }
682
+
683
+ /** Start (or restart) the dwell for a message now on screen. */
684
+ private scheduleDwell(campaignId: string, generation: number): void {
685
+ const existing = this.awaitingDwell.get(campaignId);
686
+ if (existing?.timer) clearTimeout(existing.timer);
687
+ if (this.pageLeaving || this.pageHidden()) {
688
+ this.awaitingDwell.set(campaignId, { timer: null, generation });
689
+ return;
690
+ }
691
+ const timer = setTimeout(() => {
692
+ const entry = this.awaitingDwell.get(campaignId);
693
+ if (!entry || entry.timer !== timer) return;
694
+ entry.timer = null;
695
+ // Still on screen, page still visible and staying, still the same person.
696
+ if (this.pageLeaving || this.pageHidden() || !this.isMounted(campaignId)) return;
697
+ if (entry.generation !== this.generation) return;
698
+ this.confirmDisplay(campaignId).catch(() => undefined);
699
+ }, IN_APP_DISPLAY_DWELL_MS);
700
+ this.awaitingDwell.set(campaignId, { timer, generation });
701
+ }
702
+
703
+ /** Page hidden or leaving: the dwell starts again from zero when it is back. */
704
+ private pauseDwells(): void {
705
+ this.awaitingDwell.forEach((entry) => {
706
+ if (entry.timer) clearTimeout(entry.timer);
707
+ entry.timer = null;
708
+ });
709
+ }
710
+
711
+ private resumeDwells(): void {
712
+ if (this.pageLeaving || this.pageHidden()) return;
713
+ this.awaitingDwell.forEach((entry, campaignId) => {
714
+ if (!entry.timer && this.isMounted(campaignId)) this.scheduleDwell(campaignId, entry.generation);
715
+ });
716
+ }
717
+
718
+ /** Forget a message's dwell without counting it. */
719
+ private dropDwell(campaignId: string): void {
720
+ const entry = this.awaitingDwell.get(campaignId);
721
+ if (entry?.timer) clearTimeout(entry.timer);
722
+ this.awaitingDwell.delete(campaignId);
723
+ }
724
+
725
+ /**
726
+ * The message counts as displayed: consume the frequency cap (persisted, so
727
+ * 'once'/'session' caps survive reloads) and report `in_app.displayed`.
728
+ * Once per mount - a no-op for a message already confirmed.
729
+ */
730
+ private confirmDisplay(campaignId: string): Promise<void> {
731
+ if (!this.awaitingDwell.has(campaignId)) return Promise.resolve();
732
+ this.dropDwell(campaignId);
733
+ const timestamps = this.impressionTimestamps.get(campaignId) || [];
734
+ timestamps.push(Date.now());
735
+ this.boundedMapSet(this.impressionTimestamps, campaignId, timestamps, MAX_IMPRESSION_TIMESTAMPS);
736
+ this.persistImpressionTimestamps();
737
+ const reported = this.trackImpression(campaignId, 'displayed');
738
+ const message = this.displayedMessages.get(campaignId);
739
+ if (message) this.callHost('onMessageDisplay', () => this.displayOptions.onDisplay?.(message));
740
+ return reported;
524
741
  }
525
742
 
526
743
  /**
@@ -699,6 +916,8 @@ export class InAppMessagingManager {
699
916
  this.syncRetried = false;
700
917
  this.pendingDelays.forEach((timer) => clearTimeout(timer));
701
918
  this.pendingDelays.clear();
919
+ // Messages waiting for the page to settle are not shown after a stop.
920
+ this.settleWaiters.forEach((cancel) => cancel());
702
921
  }
703
922
 
704
923
  /**
@@ -1147,35 +1366,50 @@ export class InAppMessagingManager {
1147
1366
  return;
1148
1367
  }
1149
1368
 
1150
- const message: InAppMessage = {
1151
- campaign,
1152
- renderedHtml,
1153
- displayedAt: new Date(),
1154
- };
1155
-
1156
1369
  /**
1157
- * Everything that means "this was shown", in one place.
1370
+ * Putting the message on screen. NOT yet "displayed": registering it
1371
+ * (displayedMessages, so the content frame's bridge calls are accepted),
1372
+ * mounting it, and starting its dwell. Only once it has been visible for
1373
+ * IN_APP_DISPLAY_DWELL_MS - or the person clicked or dismissed it - does
1374
+ * confirmDisplay() consume the frequency cap and report `in_app.displayed`.
1158
1375
  *
1159
- * Registering the message BEFORE the async impression-track is deliberate:
1160
- * the content iframe's bootstrap calls back (setSize/logClick/...) on load,
1161
- * which fires before a network trackImpression resolves, and the
1162
- * host-bridge guards key off displayedMessages - so registering after would
1163
- * leave the iframe rejected and stuck at height:0.
1376
+ * Registering BEFORE any impression is deliberate: the content iframe's
1377
+ * bootstrap calls back (setSize/logClick/...) on load, and the host-bridge
1378
+ * guards key off displayedMessages.
1164
1379
  *
1165
- * All of it happens at DISPLAY time, including the frequency-cap
1166
- * timestamp. Recording the cap when the message was merely SCHEDULED burns
1167
- * an impression on a message the user never saw - which is precisely the
1168
- * bug fixed on iOS earlier (an impression tracked before a render that then
1169
- * failed), and my delay had just reintroduced it here.
1380
+ * Recording the cap at mount time (as this used to) counted a message
1381
+ * mounted during a sign-in redirect or a logout - a flash nobody could
1382
+ * read - and spent the campaign's cap on it (prod 2026-11-02/03).
1170
1383
  */
1171
1384
  const commitDisplay = () => {
1385
+ const message: InAppMessage = {
1386
+ campaign,
1387
+ renderedHtml,
1388
+ displayedAt: new Date(),
1389
+ };
1172
1390
  this.boundedMapSet(this.displayedMessages, campaign.id, message, MAX_DISPLAYED_MESSAGES);
1173
- const timestamps = this.impressionTimestamps.get(campaign.id) || [];
1174
- timestamps.push(Date.now());
1175
- this.boundedMapSet(this.impressionTimestamps, campaign.id, timestamps, MAX_IMPRESSION_TIMESTAMPS);
1176
- // Persist so 'once'/'lifetime'/'session' caps survive reloads and sessions.
1177
- this.persistImpressionTimestamps();
1178
1391
  this.display(message);
1392
+ this.scheduleDwell(campaign.id, generation);
1393
+ };
1394
+
1395
+ /**
1396
+ * Wait for the page to settle (loaded and idle) and never show into a
1397
+ * page that is unloading; then re-check everything that may have
1398
+ * changed during the wait.
1399
+ */
1400
+ const show = async (): Promise<void> => {
1401
+ if (!(await this.whenPageSettled())) {
1402
+ this.logger.debug(`Campaign ${campaign.id} not displayed: the page is unloading. It stays eligible.`);
1403
+ return;
1404
+ }
1405
+ if (generation !== this.generation || !this.runtime.canSend()) {
1406
+ this.logger.debug(`Campaign ${campaign.id} not displayed: the visitor or consent changed`);
1407
+ return;
1408
+ }
1409
+ // The cap may have been spent meanwhile (manual displayInAppCampaign,
1410
+ // another tab's impression after a reload).
1411
+ if (this.displayedMessages.has(campaign.id) || !this.checkFrequencyCap(campaign)) return;
1412
+ commitDisplay();
1179
1413
  };
1180
1414
 
1181
1415
  // Display delay: the campaign's `delay` is SECONDS to wait after the
@@ -1188,17 +1422,14 @@ export class InAppMessagingManager {
1188
1422
  this.pendingDelays.delete(campaign.id);
1189
1423
  // Tied to WHO and WHETHER (contract item 43): an identify of another
1190
1424
  // user (even without reset()), an opt-out or a consent change while
1191
- // the delay ran bumps the generation, and the message was the
1192
- // previous audience's - or may no longer be shown at all.
1193
- if (generation !== this.generation || !this.runtime.canSend()) {
1194
- this.logger.debug(`Campaign ${campaign.id} not displayed after its delay: the visitor or consent changed`);
1195
- return;
1196
- }
1197
- // Re-checked at display time: the cap may have been spent meanwhile
1198
- // (manual displayInAppCampaign, another tab's impression after a reload).
1199
- if (this.displayedMessages.has(campaign.id) || !this.checkFrequencyCap(campaign)) return;
1200
- commitDisplay();
1201
- this.trackImpression(campaign.id, 'displayed').catch(() => undefined);
1425
+ // the delay ran bumps the generation - show() re-checks it.
1426
+ if (this.claimed.has(id) || this.displayedMessages.has(id)) return;
1427
+ // Claimed again for the settle wait, so a trigger meanwhile cannot
1428
+ // schedule a second copy (contract item 27).
1429
+ this.claimed.add(id);
1430
+ show()
1431
+ .catch((error) => this.logger.error('In-app display failed:', error))
1432
+ .finally(() => this.claimed.delete(id));
1202
1433
  }, delayMs);
1203
1434
  // Tracked so dismiss()/clear() can cancel a message that has not appeared
1204
1435
  // yet, instead of it popping up after the user navigated away.
@@ -1206,10 +1437,7 @@ export class InAppMessagingManager {
1206
1437
  return;
1207
1438
  }
1208
1439
 
1209
- commitDisplay();
1210
-
1211
- // Track impression (fire-and-forget analytics; the message is already shown)
1212
- await this.trackImpression(campaign.id, 'displayed');
1440
+ await show();
1213
1441
  } finally {
1214
1442
  this.claimed.delete(id);
1215
1443
  }
@@ -1853,8 +2081,8 @@ export class InAppMessagingManager {
1853
2081
 
1854
2082
  targetContainer.appendChild(container);
1855
2083
 
1856
- // Call onDisplay callback
1857
- this.callHost('onMessageDisplay', () => this.displayOptions.onDisplay?.(message));
2084
+ // onDisplay is NOT called here: it fires when the message counts as
2085
+ // displayed (confirmDisplay), paired with the `displayed` report - as on iOS.
1858
2086
 
1859
2087
  this.logger.info(`Displayed campaign: ${campaign.name} (${campaign.id})`);
1860
2088
  }
@@ -2096,6 +2324,22 @@ export class InAppMessagingManager {
2096
2324
  this.pendingDelays.delete(campaignId);
2097
2325
  }
2098
2326
 
2327
+ // Removed before it counted as displayed (IN_APP_DISPLAY_DWELL_MS). The
2328
+ // person closing it is evidence they saw it: it counts as displayed, then
2329
+ // dismissed. Any other removal (reset, destroy, the host's
2330
+ // dismissInAppMessage) reports nothing and leaves the cap untouched.
2331
+ let report = true;
2332
+ const dwell = this.awaitingDwell.get(campaignId);
2333
+ if (dwell) {
2334
+ // Shown to the previous visitor (identify/consent changed since): not theirs to count.
2335
+ if (USER_DISMISS_ACTIONS.has(action) && dwell.generation === this.generation) {
2336
+ this.confirmDisplay(campaignId).catch(() => undefined);
2337
+ } else {
2338
+ this.dropDwell(campaignId);
2339
+ report = false;
2340
+ }
2341
+ }
2342
+
2099
2343
  const container = document.getElementById(`joryio-inapp-${campaignId}`);
2100
2344
  const backdrop = document.getElementById(`joryio-backdrop-${campaignId}`);
2101
2345
  const style = document.getElementById(`joryio-style-${campaignId}`);
@@ -2125,7 +2369,7 @@ export class InAppMessagingManager {
2125
2369
  // the wire carries the vocabulary value, which trackImpression sets.
2126
2370
  // The slot is released whatever happens to the report (sending blocked,
2127
2371
  // a failed request) - contract item 43.
2128
- await this.trackImpression(campaignId, 'dismissed').catch(() => undefined);
2372
+ if (report) await this.trackImpression(campaignId, 'dismissed').catch(() => undefined);
2129
2373
 
2130
2374
  this.callHost('onMessageDismiss', () => this.displayOptions.onDismiss?.(message, action));
2131
2375
 
@@ -2192,6 +2436,15 @@ export class InAppMessagingManager {
2192
2436
  if (!campaign) return;
2193
2437
  // Opted out / consent pending / suspended: an impression is tracking too.
2194
2438
  if (!this.runtime.canSend()) return;
2439
+ // A click or conversion before the dwell ran out: the person saw it, so
2440
+ // it counts as displayed first (started, not awaited, so the reports
2441
+ // leave in the order they happened).
2442
+ const dwell = type !== 'displayed' ? this.awaitingDwell.get(campaignId) : undefined;
2443
+ if (dwell) {
2444
+ // Shown before the visitor changed (identify, consent): report nothing for it.
2445
+ if (dwell.generation !== this.generation) return;
2446
+ this.confirmDisplay(campaignId).catch(() => undefined);
2447
+ }
2195
2448
 
2196
2449
  const sessionId = this.session.getSessionId();
2197
2450
 
@@ -2464,6 +2717,8 @@ export class InAppMessagingManager {
2464
2717
  // stored caps of every other campaign were silently erased.
2465
2718
  this.campaigns.clear();
2466
2719
  this.displayedMessages.clear();
2720
+ // Dropped uncounted: the dismissals above already did, this is belt and braces.
2721
+ this.awaitingDwell.forEach((_entry, campaignId) => this.dropDwell(campaignId));
2467
2722
  this.watchedAttributes.clear();
2468
2723
  this.iframes.clear();
2469
2724
  this.frameMaxWidths.clear();
@@ -2530,6 +2785,8 @@ export class InAppMessagingManager {
2530
2785
  // Clear caches
2531
2786
  this.campaigns.clear();
2532
2787
  this.displayedMessages.clear();
2788
+ this.awaitingDwell.forEach((_entry, campaignId) => this.dropDwell(campaignId));
2789
+ this.removePageLifecycle();
2533
2790
  this.impressionTimestamps.clear();
2534
2791
  this.watchedAttributes.clear();
2535
2792
  this.iframes.clear();
package/src/index.ts CHANGED
@@ -65,6 +65,10 @@ export type {
65
65
  // Export SDK version
66
66
  export { SDK_VERSION } from './core/config';
67
67
 
68
+ // How long an in-app message must be visible before it counts as displayed
69
+ // (the same constant on every Joryio SDK).
70
+ export { IN_APP_DISPLAY_DWELL_MS } from './core/inapp';
71
+
68
72
  // Default export for convenience
69
73
  export default JoryioSDK;
70
74