@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joryio/web-sdk",
3
- "version": "1.4.0-beta.8",
3
+ "version": "1.4.0-beta.9",
4
4
  "description": "Joryio Web Tracking SDK - Lightweight analytics and event tracking",
5
5
  "main": "dist/joryio.cjs.js",
6
6
  "module": "dist/joryio.mjs",
@@ -2,7 +2,7 @@
2
2
  * SDK Configuration Types and Defaults
3
3
  */
4
4
 
5
- export const SDK_VERSION = '1.4.0-beta.8'; // keep in sync with package.json (sdk-version-parity.spec.ts pins it)
5
+ export const SDK_VERSION = '1.4.0-beta.9'; // keep in sync with package.json (sdk-version-parity.spec.ts pins it)
6
6
 
7
7
  /**
8
8
  * Sent on EVERY request to the API, so the dashboard can show which SDK
@@ -212,6 +212,39 @@ export interface PageContextOptions {
212
212
  dataLayerName?: string;
213
213
  }
214
214
 
215
+ /**
216
+ * Exit intent on a touch device. There is no pointer to leave through the top
217
+ * of the window, so the signal is a fast scroll UP after reading down the page:
218
+ * the visitor heading back for the address bar or the tab switcher (mobile
219
+ * browsers reveal their toolbar on exactly that gesture).
220
+ *
221
+ * - a touch device: the PRIMARY input has no hover and is coarse,
222
+ * `(hover: none) and (pointer: coarse)`. A laptop with a touch screen, or a
223
+ * tablet with a mouse or trackpad attached, reports its primary input as fine
224
+ * with hover and keeps the desktop rule - a scroll wheel moving up fast there
225
+ * is reading, not leaving. Read live (a MediaQueryList), never cached.
226
+ * - armed only once the visitor has scrolled down at least `armPercent` of the
227
+ * page or `armPx` CSS pixels (whichever comes first) in this page view;
228
+ * - fires on a scroll up of at least `upPx` within `windowMs`;
229
+ * - never in the first `minMs` after the page view started (load or route
230
+ * change), so a page restoring its scroll position or a jump to an anchor
231
+ * is not an exit;
232
+ * - scroll positions are sampled at most every `sampleMs` (passive listener).
233
+ *
234
+ * Once per page view, like the desktop rule: the same `exitFired` flag, reset
235
+ * by a route change.
236
+ */
237
+ export const TOUCH_EXIT_INTENT = {
238
+ armPercent: 25,
239
+ armPx: 400,
240
+ upPx: 120,
241
+ windowMs: 300,
242
+ minMs: 3000,
243
+ sampleMs: 50,
244
+ } as const;
245
+
246
+ const TOUCH_PRIMARY_QUERY = '(hover: none) and (pointer: coarse)';
247
+
215
248
  export type PageSignal = { type: 'page_change'; url: string | null } | { type: 'exit_intent' } | { type: 'scroll_depth'; percent: number } | { type: 'time_on_page'; seconds: number };
216
249
 
217
250
  /**
@@ -228,6 +261,11 @@ export class PageContextTracker {
228
261
  private visibleMs = 0;
229
262
  private visibleSince: number | null = null;
230
263
  private exitFired = false;
264
+ /** Touch exit intent: when this page view started, the deepest scrollY, and the recent samples. */
265
+ private pageStartedAt = Date.now();
266
+ private maxScrollY = 0;
267
+ private scrollSamples: Array<{ y: number; t: number }> = [];
268
+ private touchQuery: MediaQueryList | null = null;
231
269
  private timer: ReturnType<typeof setInterval> | null = null;
232
270
  private undo: Array<() => void> = [];
233
271
  private started = false;
@@ -341,7 +379,21 @@ export class PageContextTracker {
341
379
  this.undo.push(() => target.removeEventListener(ev, fn, opts));
342
380
  };
343
381
  on(window, 'popstate', () => this.checkRoute());
344
- on(window, 'scroll', () => this.measureScroll(), { passive: true });
382
+ this.pageStartedAt = Date.now();
383
+ try {
384
+ this.touchQuery = typeof window.matchMedia === 'function' ? window.matchMedia(TOUCH_PRIMARY_QUERY) : null;
385
+ } catch {
386
+ this.touchQuery = null;
387
+ }
388
+ on(
389
+ window,
390
+ 'scroll',
391
+ () => {
392
+ this.measureScroll();
393
+ this.touchExitIntent();
394
+ },
395
+ { passive: true },
396
+ );
345
397
  on(document, 'mouseout', (e: MouseEvent) => {
346
398
  // Leaving through the top of the window, toward the tabs and the address bar.
347
399
  if (this.exitFired || e.relatedTarget || (e as any).toElement) return;
@@ -370,6 +422,8 @@ export class PageContextTracker {
370
422
  }
371
423
  }
372
424
  this.listeners.clear();
425
+ this.scrollSamples = [];
426
+ this.touchQuery = null;
373
427
  this.started = false;
374
428
  }
375
429
 
@@ -382,6 +436,9 @@ export class PageContextTracker {
382
436
  this.visibleMs = 0;
383
437
  this.visibleSince = typeof document !== 'undefined' && document.visibilityState === 'hidden' ? null : Date.now();
384
438
  this.exitFired = false;
439
+ this.pageStartedAt = Date.now();
440
+ this.maxScrollY = 0;
441
+ this.scrollSamples = [];
385
442
  this.emit({ type: 'page_change', url });
386
443
  }
387
444
 
@@ -422,6 +479,32 @@ export class PageContextTracker {
422
479
  }
423
480
  }
424
481
 
482
+ /** Exit intent on a touch device: a fast scroll up once the page was read down (TOUCH_EXIT_INTENT). */
483
+ private touchExitIntent(): void {
484
+ if (this.exitFired || !this.touchQuery?.matches) return;
485
+ try {
486
+ const c = TOUCH_EXIT_INTENT;
487
+ const now = Date.now();
488
+ const last = this.scrollSamples[this.scrollSamples.length - 1];
489
+ if (last && now - last.t < c.sampleMs) return;
490
+ const y = Math.max(0, window.scrollY || document.documentElement.scrollTop || 0);
491
+ if (y > this.maxScrollY) this.maxScrollY = y;
492
+ this.scrollSamples = this.scrollSamples.filter((s) => now - s.t <= c.windowMs);
493
+ this.scrollSamples.push({ y, t: now });
494
+ if (now - this.pageStartedAt < c.minMs) return;
495
+ if (this.maxScrollY < c.armPx && this.maxScrollPercent < c.armPercent) return;
496
+ let peak = y;
497
+ for (const s of this.scrollSamples) if (s.y > peak) peak = s.y;
498
+ if (peak - y >= c.upPx) {
499
+ this.exitFired = true;
500
+ this.scrollSamples = [];
501
+ this.emit({ type: 'exit_intent' });
502
+ }
503
+ } catch {
504
+ /* ignore */
505
+ }
506
+ }
507
+
425
508
  private visibilityChanged(): void {
426
509
  if (document.visibilityState === 'hidden') {
427
510
  if (this.visibleSince !== null) this.visibleMs += Date.now() - this.visibleSince;
@@ -31,9 +31,9 @@
31
31
  * device is not applied; when the viewport crosses the breakpoint (a
32
32
  * resize, a turned phone) every edit is undone and the ones for the new
33
33
  * width applied again, so a desktop and a mobile edit of one element never
34
- * fight. The SDK says it understands this with the capability
35
- * `page_edit_device`; the server sends an SDK without it no per-device
36
- * edit at all (an older build would apply both versions everywhere).
34
+ * fight. The server sends per-device edits to every build (1.4.0-beta.9
35
+ * dropped the `page_edit_device` capability); a build before beta.8
36
+ * applies them on every device.
37
37
  * - Exposure: `in_app.displayed` once an edit of the experience landed on an
38
38
  * element; a control visitor reports `in_app.control_viewed` once one of
39
39
  * the control's selectors is on the page.
@@ -48,6 +48,15 @@
48
48
  * when the definitive answer for this visitor no longer carries it -
49
49
  * paused, edited, the visitor suppressed or in a control, page edits
50
50
  * switched off - or on a route change to another page.
51
+ * - Show when (D465, show-when.ts): an experience with a `showWhen` other
52
+ * than load is held - not applied, kept out of the anti-flicker rule and
53
+ * out of the selectors remembered for it - and applied at its moment in
54
+ * this page view; `in_app.displayed` once an edit lands after it. A
55
+ * control's `control_viewed` waits for its moment too. A route change asks
56
+ * for the new page and the moments start again. An event in the answer's
57
+ * `recheckOn` (or one an experience waits on) asks again for this page at
58
+ * once, once per page view. A server-applied edit of an experience that
59
+ * now waits for a moment is undone and re-applied by the SDK at the moment.
51
60
  */
52
61
  import { bucketHash } from '../utils/bucket-hash';
53
62
  import type { IdentityManager } from './identity';
@@ -57,6 +66,7 @@ import type { InAppAuthProvider } from './inapp';
57
66
  import type { PlacementConsent } from './placements';
58
67
  import { sdkIdentityHeaders } from './config';
59
68
  import { currentPageUrl, PAGE_CONTEXT_CAPABILITY, type PageContextTracker } from './page-context';
69
+ import { eventNames, isDeferred, parseShowWhen, type RecheckEvent, type ShowWhenMoments } from './show-when';
60
70
 
61
71
  export const PAGE_EDIT_OPERATIONS = ['replace_text', 'replace_image', 'replace_link', 'hide', 'insert_placement'] as const;
62
72
  /** `replace` ("Instead of it"): the element is hidden and the spot takes its place, right after it. */
@@ -64,8 +74,6 @@ export const PAGE_EDIT_POSITIONS = ['before', 'after', 'prepend', 'append', 'rep
64
74
  export const PAGE_EDITS_CAPABILITY = 'page_edits';
65
75
  /** Which viewport an edit is for; absent = `all`. */
66
76
  export const PAGE_EDIT_DEVICES = ['all', 'mobile', 'desktop'] as const;
67
- /** Sent with `page_edits` by a build that applies an edit only on its device. */
68
- export const PAGE_EDIT_DEVICE_CAPABILITY = 'page_edit_device';
69
77
  /** Mobile = viewport width below this many CSS pixels (backend PAGE_EDIT_MOBILE_BREAKPOINT, the dashboard, the editor). */
70
78
  export const PAGE_EDIT_MOBILE_BREAKPOINT = 768;
71
79
  export const PAGE_EDIT_MOBILE_QUERY = '(max-width: 767.98px)';
@@ -147,7 +155,8 @@ const sameEdit = (a: PageEditWire, b: PageEditWire): boolean =>
147
155
  (a.device ?? null) === (b.device ?? null) &&
148
156
  !b.personalized;
149
157
 
150
- function serverMarkerElement(): HTMLScriptElement | null {
158
+ /** The plugin's marker block: a JSON `<script>` that is a direct child of `<head>`, or null (also read by placements.ts). */
159
+ export function serverMarkerElement(): HTMLScriptElement | null {
151
160
  const head = document.head;
152
161
  if (!head) return null;
153
162
  for (const c of Array.from(head.children)) {
@@ -286,12 +295,16 @@ export interface PageEditExperienceWire {
286
295
  controlToken: string | null;
287
296
  selectors: string[];
288
297
  edits: PageEditWire[];
298
+ /** Show when (D465): the moment its edits are applied (control: the moment it counts as viewed); absent = on load. */
299
+ showWhen?: unknown;
289
300
  }
290
301
 
291
302
  export interface PageEditsResponse {
292
303
  success?: boolean;
293
304
  ttlSeconds?: number;
294
305
  experiences?: PageEditExperienceWire[];
306
+ /** Show when: event names that make the SDK ask again for this page at once. */
307
+ recheckOn?: string[];
295
308
  }
296
309
 
297
310
  export interface PageEditRuntime {
@@ -398,6 +411,14 @@ export class PageEditManager {
398
411
  private offMedia: (() => void) | null = null;
399
412
  private started = false;
400
413
  private destroyed = false;
414
+ /** Show when (D465): the moments; null = every non-load experience stays held. */
415
+ private moments: ShowWhenMoments | null = null;
416
+ private momentsUnsubscribe: (() => void) | null = null;
417
+ /** Experiences revealed in this page view. */
418
+ private revealed = new Set<string>();
419
+ /** The answer's `recheckOn`, and the events already re-checked in this page view. */
420
+ private recheckOn: string[] = [];
421
+ private rechecked = new Set<string>();
401
422
 
402
423
  constructor(
403
424
  private apiEndpoint: string,
@@ -429,6 +450,51 @@ export class PageEditManager {
429
450
  }
430
451
  }
431
452
 
453
+ /** Show when (D465): the SDK's moments. A held experience is applied as its moment comes. */
454
+ setShowWhen(moments: ShowWhenMoments | null): void {
455
+ this.momentsUnsubscribe?.();
456
+ this.moments = moments;
457
+ this.momentsUnsubscribe = moments ? moments.onChange(() => this.sweep()) : null;
458
+ }
459
+
460
+ /** Has this experience's moment come in this page view (it stays come)? An invalid one never. */
461
+ private due(x: PageEditExperienceWire): boolean {
462
+ const sw = parseShowWhen(x.showWhen);
463
+ return !!sw && (sw.kind === 'load' || this.revealed.has(x.id) || (!!this.moments && this.moments.met(sw)));
464
+ }
465
+
466
+ /** A moment may have come: apply the experiences now due. */
467
+ private sweep(): void {
468
+ if (!this.started || this.destroyed) return;
469
+ let any = false;
470
+ for (const x of this.experiences) {
471
+ if (this.revealed.has(x.wire.id) || !isDeferred(x.wire.showWhen) || !this.due(x.wire)) continue;
472
+ this.revealed.add(x.wire.id);
473
+ any = true;
474
+ }
475
+ if (any) this.applyAll();
476
+ }
477
+
478
+ /**
479
+ * Show when: should `eventName` ask again for this page now? Yes when the
480
+ * answer lists it in `recheckOn` or an experience waits on it, once per page
481
+ * view. Marks it as asked.
482
+ */
483
+ claimRecheck(eventName: string): boolean {
484
+ if (!this.moments || !this.started || this.destroyed || this.rechecked.has(eventName)) return false;
485
+ const waits =
486
+ this.recheckOn.includes(eventName) ||
487
+ this.experiences.some((x) => (parseShowWhen(x.wire.showWhen) as { event?: string } | null)?.event === eventName);
488
+ if (waits) this.rechecked.add(eventName);
489
+ return waits;
490
+ }
491
+
492
+ /** Ask again for the current page now (the show-when re-check), carrying the event that caused it. */
493
+ recheck(event?: RecheckEvent): void {
494
+ const url = this.url();
495
+ if (url && this.started && !this.destroyed) void this.fetch(url, this.generation, event);
496
+ }
497
+
432
498
  /** Hide what was edited here last time, apply what is known, observe the DOM, ask the server. */
433
499
  start(): void {
434
500
  if (this.started || this.destroyed || typeof document === 'undefined') return;
@@ -479,6 +545,7 @@ export class PageEditManager {
479
545
  destroy(): void {
480
546
  this.destroyed = true;
481
547
  this.pageUnsubscribe?.();
548
+ this.momentsUnsubscribe?.();
482
549
  this.offMedia?.();
483
550
  this.offMedia = null;
484
551
  this.observer?.disconnect();
@@ -506,6 +573,10 @@ export class PageEditManager {
506
573
  private loadPage(): void {
507
574
  const generation = ++this.generation;
508
575
  this.revertAll();
576
+ // A new page view: held experiences wait for this page's moment, events may re-check again.
577
+ this.revealed.clear();
578
+ this.rechecked.clear();
579
+ this.recheckOn = [];
509
580
  const url = this.url();
510
581
  if (!url) {
511
582
  this.experiences = [];
@@ -658,7 +729,7 @@ export class PageEditManager {
658
729
  return request;
659
730
  }
660
731
 
661
- private async fetch(url: string, generation: number): Promise<void> {
732
+ private async fetch(url: string, generation: number, recheckEvent?: RecheckEvent): Promise<void> {
662
733
  const consent = this.runtime.consent();
663
734
  if (consent === null || this.destroyed) {
664
735
  this.showAll();
@@ -673,9 +744,10 @@ export class PageEditManager {
673
744
  ...(personal ? { sessionId: this.session.getSessionId() } : {}),
674
745
  deviceType: 'web',
675
746
  locale: typeof navigator !== 'undefined' ? navigator.language : undefined,
676
- capabilities: [PAGE_CONTEXT_CAPABILITY, PAGE_EDITS_CAPABILITY, PAGE_EDIT_DEVICE_CAPABILITY],
747
+ capabilities: [PAGE_CONTEXT_CAPABILITY, PAGE_EDITS_CAPABILITY],
677
748
  trackingConsent: consent,
678
749
  context: this.page ? this.page.current() : { url, pageVariables: {}, dataLayer: {} },
750
+ ...(recheckEvent ? { recheckEvent } : {}),
679
751
  };
680
752
  const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
681
753
  const timeout = setTimeout(() => controller?.abort(), this.runtime.requestTimeoutMs ?? 10000);
@@ -704,6 +776,7 @@ export class PageEditManager {
704
776
  .map((wire) => ({ wire, edits: (Array.isArray(wire.edits) ? wire.edits : []).map(trustedEdit).filter((e): e is PageEditWire => !!e) }));
705
777
  this.revertAll();
706
778
  this.experiences = experiences;
779
+ this.recheckOn = eventNames(data.recheckOn);
707
780
  // The definitive answer: a server-applied edit it no longer carries is undone first.
708
781
  this.reconcileServer(experiences);
709
782
  this.remember(url, experiences, data.ttlSeconds);
@@ -735,6 +808,8 @@ export class PageEditManager {
735
808
  this.observer?.disconnect();
736
809
  try {
737
810
  for (const x of this.experiences) {
811
+ // Show when: held until its moment (treatment and control alike).
812
+ if (!this.due(x.wire)) continue;
738
813
  if (x.wire.isControl) {
739
814
  const seen = (x.wire.selectors || []).some((s) => isSafeSelector(s) && this.query(s).length > 0);
740
815
  if (seen) this.reportControl(x.wire);
@@ -892,7 +967,8 @@ export class PageEditManager {
892
967
 
893
968
  private remember(url: string, experiences: Experience[], ttlSeconds?: number): void {
894
969
  // Held back next time: only what this viewport shows.
895
- const selectors = [...new Set(experiences.flatMap((x) => (x.wire.isControl ? [] : x.edits.filter((e) => editShowsOn(e, this.mobile)).map((e) => e.selector))))];
970
+ // Never an experience that waits for a moment: it shows the original until then.
971
+ 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))))];
896
972
  try {
897
973
  const all = JSON.parse(localStorage.getItem(this.stores.selectors) || '{}') || {};
898
974
  delete all[url];
@@ -989,7 +1065,8 @@ export class PageEditManager {
989
1065
  if (!server.size || typeof document === 'undefined') return;
990
1066
  const keep = new Set<string>();
991
1067
  for (const x of experiences) {
992
- if (x.wire.isControl) continue;
1068
+ // A control, or an experience that now waits for a moment: its server-applied edits go (applied by the SDK at the moment).
1069
+ if (x.wire.isControl || isDeferred(x.wire.showWhen)) continue;
993
1070
  for (const e of x.edits) {
994
1071
  const token = `${x.wire.id}:${e.id}`;
995
1072
  const s = server.get(token);