@teleporthq/teleport-project-generator-next 0.45.8 → 0.45.10

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.
@@ -24,8 +24,14 @@ function memoryStorage() {
24
24
  }
25
25
  }
26
26
 
27
- function bootTracker(options: { experiments?: Record<string, string> } = {}) {
28
- const localStorage = memoryStorage()
27
+ function bootTracker(
28
+ options: {
29
+ experiments?: Record<string, string>
30
+ /** localStorage carried over from an earlier page load. */
31
+ localStorage?: ReturnType<typeof memoryStorage>
32
+ } = {}
33
+ ) {
34
+ const localStorage = options.localStorage || memoryStorage()
29
35
  const sessionStorage = memoryStorage()
30
36
  const batches: Sent[][] = []
31
37
  const heartbeats: Sent[] = []
@@ -52,6 +58,8 @@ function bootTracker(options: { experiments?: Record<string, string> } = {}) {
52
58
  scrollY: 0,
53
59
  addEventListener: () => undefined,
54
60
  __tpExp: options.experiments,
61
+ // The merchant's Google tag, as a fresh page load starts it.
62
+ dataLayer: [] as Array<Record<string, unknown>>,
55
63
  }
56
64
  const fakeFetch = (url: string, init: { body: string }) => {
57
65
  const payload = JSON.parse(init.body)
@@ -71,7 +79,7 @@ function bootTracker(options: { experiments?: Record<string, string> } = {}) {
71
79
  'navigator',
72
80
  'fetch',
73
81
  'setInterval',
74
- `${body}\nreturn { initTeleportAnalytics, trackRouteChange }`
82
+ `${body}\nreturn { initTeleportAnalytics, trackRouteChange, trackCommerceEvent }`
75
83
  )(
76
84
  {
77
85
  env: {
@@ -106,6 +114,10 @@ function bootTracker(options: { experiments?: Record<string, string> } = {}) {
106
114
  const showExperiments = (experiments: string[]) => {
107
115
  experimentsOnPage = experiments
108
116
  }
117
+ const purchasesSentToGoogle = () =>
118
+ fakeWindow.dataLayer
119
+ .filter((entry) => entry.event === 'purchase')
120
+ .map((entry) => entry.transaction_id)
109
121
 
110
122
  return {
111
123
  tracker,
@@ -116,6 +128,7 @@ function bootTracker(options: { experiments?: Record<string, string> } = {}) {
116
128
  show,
117
129
  navigate,
118
130
  showExperiments,
131
+ purchasesSentToGoogle,
119
132
  }
120
133
  }
121
134
 
@@ -232,3 +245,73 @@ describe('tracker — the A/B test versions a visitor has seen', () => {
232
245
  })
233
246
  })
234
247
  })
248
+
249
+ describe('tracker — the order numbers it has counted', () => {
250
+ const LEDGER_KEY = 'tp_purchases'
251
+ const ledger = (page: { localStorage: ReturnType<typeof memoryStorage> }) =>
252
+ JSON.parse(page.localStorage.getItem(LEDGER_KEY) || 'null')
253
+
254
+ it('keeps them in memory until the banner is accepted, then stores them', () => {
255
+ const page = bootTracker()
256
+ page.tracker.initTeleportAnalytics({})
257
+ page.tracker.trackCommerceEvent('purchase', { orderId: 'order-1' })
258
+ expect(ledger(page)).toBeNull()
259
+
260
+ page.localStorage.setItem('cookieConsent', 'accepted')
261
+ page.navigate('/account')
262
+ expect(ledger(page)).toEqual(['order-1'])
263
+ })
264
+
265
+ it('removes the ones an earlier build stored for a visitor who has not accepted', () => {
266
+ const page = bootTracker()
267
+ page.localStorage.setItem(LEDGER_KEY, JSON.stringify(['order-0']))
268
+ page.tracker.initTeleportAnalytics({})
269
+ expect(ledger(page)).toBeNull()
270
+ })
271
+
272
+ it('with consent, stores each order once, also when the confirmation page is reloaded', () => {
273
+ const localStorage = memoryStorage()
274
+ localStorage.setItem('cookieConsent', 'accepted')
275
+ const confirmation = bootTracker({ localStorage })
276
+ confirmation.tracker.initTeleportAnalytics({})
277
+ confirmation.tracker.trackCommerceEvent('purchase', { orderId: 'order-1' })
278
+ expect(ledger(confirmation)).toEqual(['order-1'])
279
+
280
+ const reloaded = bootTracker({ localStorage })
281
+ reloaded.tracker.initTeleportAnalytics({})
282
+ reloaded.tracker.trackCommerceEvent('purchase', { orderId: 'order-1' })
283
+ reloaded.tracker.trackCommerceEvent('purchase', { orderId: 'order-2' })
284
+ expect(ledger(reloaded)).toEqual(['order-1', 'order-2'])
285
+ })
286
+ })
287
+
288
+ describe("tracker — a purchase reaches the store's Google tags once", () => {
289
+ it('with consent, a reloaded confirmation page does not send it again', () => {
290
+ const localStorage = memoryStorage()
291
+ localStorage.setItem('cookieConsent', 'accepted')
292
+ const confirmation = bootTracker({ localStorage })
293
+ confirmation.tracker.initTeleportAnalytics({})
294
+ confirmation.tracker.trackCommerceEvent('purchase', { orderId: 'order-1', value: 50 })
295
+ expect(confirmation.purchasesSentToGoogle()).toEqual(['order-1'])
296
+
297
+ const reloaded = bootTracker({ localStorage })
298
+ reloaded.tracker.initTeleportAnalytics({})
299
+ reloaded.tracker.trackCommerceEvent('purchase', { orderId: 'order-1', value: 50 })
300
+ expect(reloaded.purchasesSentToGoogle()).toEqual([])
301
+ })
302
+
303
+ it('without consent, once while the visitor browses, and again after a full reload', () => {
304
+ const confirmation = bootTracker()
305
+ confirmation.tracker.initTeleportAnalytics({})
306
+ confirmation.tracker.trackCommerceEvent('purchase', { orderId: 'order-1', value: 50 })
307
+ // Back to the confirmation page by client-side navigation.
308
+ confirmation.navigate('/thank-you')
309
+ confirmation.tracker.trackCommerceEvent('purchase', { orderId: 'order-1', value: 50 })
310
+ expect(confirmation.purchasesSentToGoogle()).toEqual(['order-1'])
311
+
312
+ const reloaded = bootTracker({ localStorage: confirmation.localStorage })
313
+ reloaded.tracker.initTeleportAnalytics({})
314
+ reloaded.tracker.trackCommerceEvent('purchase', { orderId: 'order-1', value: 50 })
315
+ expect(reloaded.purchasesSentToGoogle()).toEqual(['order-1'])
316
+ })
317
+ })
@@ -68,12 +68,13 @@ describe('commerce analytics — the emitted tracker', () => {
68
68
  })
69
69
 
70
70
  it('never reports a purchase from the browser — the server does, with its key', () => {
71
- // The dataLayer mirror still runs (the merchant's GA4 is theirs), and the
72
- // ledger still claims the order so a refreshed confirmation page cannot
73
- // re-push it; only OUR beacon is withheld.
71
+ // The ledger claims the order before the dataLayer mirror (the merchant's
72
+ // GA4 is theirs), so a refreshed confirmation page cannot re-push it; only
73
+ // OUR beacon is withheld.
74
74
  expect(TRACKER_SOURCE).toMatch(
75
- /if \(name === 'purchase'\) \{[\s\S]*?claimPurchase\(detail && detail\.orderId\)\s*return\s*\}/
75
+ /if \(name === 'purchase' && !claimPurchase\(detail && detail\.orderId\)\) \{\s*return\s*\}\s*(\/\/[^\n]*\s*)*pushToDataLayer\(name, detail\)/
76
76
  )
77
+ expect(TRACKER_SOURCE).toMatch(/if \(name === 'purchase'\) \{\s*(\/\/[^\n]*\s*)*return\s*\}/)
77
78
  })
78
79
 
79
80
  it('mirrors to the GA4 dataLayer independently of our own tracker', () => {
@@ -45,6 +45,8 @@ const describeInDom = jsdom ? describe : describe.skip
45
45
 
46
46
  const DAY_MS = 24 * 60 * 60 * 1000
47
47
  const OPEN_PREFIX = 'workflow:custom:tq-popup-open-'
48
+ /** A visitor who accepted the cookie banner on an earlier visit. */
49
+ const ACCEPTED = { cookieConsent: 'accepted' }
48
50
 
49
51
  const popup = (overrides: Partial<UIDLPopup> = {}): UIDLPopup => ({
50
52
  id: 'welcome',
@@ -212,17 +214,39 @@ async function loadPage(options: LoadOptions) {
212
214
  window.eval(script)
213
215
  await parsed
214
216
 
215
- const storage = () => {
217
+ const contentsOf = (area: Storage) => {
216
218
  const values: Record<string, string> = {}
217
- for (let i = 0; i < window.localStorage.length; i++) {
218
- const key = window.localStorage.key(i)
219
- values[key] = window.localStorage.getItem(key)
219
+ for (let i = 0; i < area.length; i++) {
220
+ const key = area.key(i)
221
+ values[key] = area.getItem(key)
220
222
  }
221
223
  return values
222
224
  }
225
+ const storage = () => contentsOf(window.localStorage)
226
+ const session = () => contentsOf(window.sessionStorage)
223
227
  const card = (id: string) => document.querySelector(`[data-tq-popup-root="${id}"]`)
228
+ // What the cookie banner's button does: the workflow step writes the answer
229
+ // and announces the write in this tab.
230
+ const answer = (value: 'accepted' | 'declined') => {
231
+ window.localStorage.setItem('cookieConsent', value)
232
+ window.dispatchEvent(
233
+ new window.CustomEvent('teleport:local-storage', { detail: { key: 'cookieConsent', value } })
234
+ )
235
+ }
224
236
 
225
- return { window, document, clock, dispatched, closed, tracked, errors, storage, card }
237
+ return {
238
+ window,
239
+ document,
240
+ clock,
241
+ dispatched,
242
+ closed,
243
+ tracked,
244
+ errors,
245
+ storage,
246
+ session,
247
+ card,
248
+ answer,
249
+ }
226
250
  }
227
251
 
228
252
  describeInDom('popup runtime — the emitted head script', () => {
@@ -301,7 +325,11 @@ describeInDom('popup runtime — where a popup may open', () => {
301
325
 
302
326
  describeInDom('popup runtime — the cookie banner comes first', () => {
303
327
  const BANNER = '<div data-thq="thq-cookie-consent"><button>Accept</button></div>'
304
- const answerBanner = async (page: { document: Document }) => {
328
+ const answerBanner = async (
329
+ page: { document: Document; answer: (value: 'accepted' | 'declined') => void },
330
+ value: 'accepted' | 'declined' = 'accepted'
331
+ ) => {
332
+ page.answer(value)
305
333
  page.document.querySelector('[data-thq="thq-cookie-consent"]').remove()
306
334
  await Promise.resolve()
307
335
  await Promise.resolve()
@@ -324,6 +352,18 @@ describeInDom('popup runtime — the cookie banner comes first', () => {
324
352
  expect(page.tracked).toEqual([{ name: 'popup_shown', detail: { recordId: 'welcome' } }])
325
353
  })
326
354
 
355
+ it('opens it after a Decline too, and stores nothing on the device', async () => {
356
+ const page = await loadPage({ popups: [popup()], body: BANNER })
357
+ page.clock.advance(60000)
358
+
359
+ await answerBanner(page, 'declined')
360
+ expect(page.dispatched).toEqual(['welcome'])
361
+ expect(page.card('welcome')).not.toBeNull()
362
+ expect(page.tracked).toEqual([{ name: 'popup_shown', detail: { recordId: 'welcome' } }])
363
+ expect(page.storage()).toEqual({ cookieConsent: 'declined' })
364
+ expect(page.session()).toEqual({})
365
+ })
366
+
327
367
  it('spends no opening attempts on the wait, however long it takes', async () => {
328
368
  const page = await loadPage({
329
369
  popups: [popup({ layout: 'bottom' })],
@@ -379,9 +419,11 @@ describeInDom('popup runtime — the cookie banner comes first', () => {
379
419
  })
380
420
  })
381
421
 
422
+ // The visitors in this block accepted the cookie banner earlier, so what the
423
+ // runtime remembers is stored; see the block after it for everyone else.
382
424
  describeInDom('popup runtime — when it opens', () => {
383
425
  it('opens a delay popup after its timer, then remembers it was shown', async () => {
384
- const page = await loadPage({ popups: [popup()] })
426
+ const page = await loadPage({ popups: [popup()], storage: ACCEPTED })
385
427
  page.clock.advance(4999)
386
428
  expect(page.dispatched).toEqual([])
387
429
 
@@ -394,7 +436,7 @@ describeInDom('popup runtime — when it opens', () => {
394
436
  })
395
437
 
396
438
  it('does not open again on a load within 7 days, and does after them', async () => {
397
- const first = await loadPage({ popups: [popup()] })
439
+ const first = await loadPage({ popups: [popup()], storage: ACCEPTED })
398
440
  first.clock.advance(60000)
399
441
  expect(first.dispatched).toEqual(['welcome'])
400
442
 
@@ -404,7 +446,7 @@ describeInDom('popup runtime — when it opens', () => {
404
446
 
405
447
  const later = await loadPage({
406
448
  popups: [popup()],
407
- storage: { 'tq_popup:welcome': String(Date.now() - 8 * DAY_MS) },
449
+ storage: { ...ACCEPTED, 'tq_popup:welcome': String(Date.now() - 8 * DAY_MS) },
408
450
  })
409
451
  later.clock.advance(60000)
410
452
  expect(later.dispatched).toEqual(['welcome'])
@@ -413,12 +455,15 @@ describeInDom('popup runtime — when it opens', () => {
413
455
  it('keeps "once" forever and "session" in the session', async () => {
414
456
  const once = popup({ frequency: { kind: 'once', days: 0 } })
415
457
  const old = String(Date.now() - 365 * DAY_MS)
416
- const onceAgain = await loadPage({ popups: [once], storage: { 'tq_popup:welcome': old } })
458
+ const onceAgain = await loadPage({
459
+ popups: [once],
460
+ storage: { ...ACCEPTED, 'tq_popup:welcome': old },
461
+ })
417
462
  onceAgain.clock.advance(60000)
418
463
  expect(onceAgain.dispatched).toEqual([])
419
464
 
420
465
  const session = popup({ frequency: { kind: 'session', days: 0 } })
421
- const first = await loadPage({ popups: [session] })
466
+ const first = await loadPage({ popups: [session], storage: ACCEPTED })
422
467
  first.clock.advance(60000)
423
468
  expect(first.dispatched).toEqual(['welcome'])
424
469
  expect(first.window.sessionStorage.getItem('tq_popup:welcome')).not.toBeNull()
@@ -426,6 +471,7 @@ describeInDom('popup runtime — when it opens', () => {
426
471
 
427
472
  const sameSession = await loadPage({
428
473
  popups: [session],
474
+ storage: ACCEPTED,
429
475
  session: { 'tq_popup:welcome': first.window.sessionStorage.getItem('tq_popup:welcome') },
430
476
  })
431
477
  sameSession.clock.advance(60000)
@@ -436,7 +482,7 @@ describeInDom('popup runtime — when it opens', () => {
436
482
  const forNew = popup({ id: 'new', audience: 'new' })
437
483
  const forReturning = popup({ id: 'returning', audience: 'returning' })
438
484
 
439
- const first = await loadPage({ popups: [forNew, forReturning] })
485
+ const first = await loadPage({ popups: [forNew, forReturning], storage: ACCEPTED })
440
486
  first.clock.advance(60000)
441
487
  expect(first.dispatched).toEqual(['new'])
442
488
  expect(first.storage().tq_popup_visited).toBeTruthy()
@@ -488,6 +534,7 @@ describeInDom('popup runtime — when it opens', () => {
488
534
  popups: [
489
535
  popup({ trigger: { desktop: 'load', phone: 'load', delaySeconds: 0, scrollPercent: 0 } }),
490
536
  ],
537
+ storage: ACCEPTED,
491
538
  listenAfterMs: 1200,
492
539
  })
493
540
  page.clock.advance(100)
@@ -540,9 +587,102 @@ describeInDom('popup runtime — when it opens', () => {
540
587
  })
541
588
  })
542
589
 
590
+ describeInDom('popup runtime — nothing stored before the cookie banner is accepted', () => {
591
+ it('holds what was shown in memory while the visitor browses, and stores nothing', async () => {
592
+ const weekly = popup({ id: 'weekly' })
593
+ const perSession = popup({ id: 'per-session', frequency: { kind: 'session', days: 0 } })
594
+ const page = await loadPage({ popups: [weekly, perSession] })
595
+ page.clock.advance(60000)
596
+ expect(page.dispatched).toEqual(['per-session'])
597
+
598
+ page.window.history.pushState({}, '', '/shop')
599
+ page.clock.advance(60000)
600
+ expect(page.dispatched).toEqual(['per-session', 'weekly'])
601
+
602
+ page.window.history.pushState({}, '', '/about')
603
+ page.clock.advance(60000)
604
+ expect(page.dispatched).toEqual(['per-session', 'weekly'])
605
+ expect(page.storage()).toEqual({})
606
+ expect(page.session()).toEqual({})
607
+ })
608
+
609
+ it('treats a full page load as a new visit: a "once" popup shows again', async () => {
610
+ const once = popup({ frequency: { kind: 'once', days: 0 } })
611
+ const first = await loadPage({ popups: [once] })
612
+ first.clock.advance(60000)
613
+ expect(first.dispatched).toEqual(['welcome'])
614
+
615
+ const reloaded = await loadPage({ popups: [once], storage: first.storage() })
616
+ reloaded.clock.advance(60000)
617
+ expect(reloaded.dispatched).toEqual(['welcome'])
618
+ })
619
+
620
+ it('removes what an earlier build stored, and does not go by it', async () => {
621
+ const page = await loadPage({
622
+ popups: [popup()],
623
+ storage: {
624
+ cookieConsent: 'declined',
625
+ 'tq_popup:welcome': String(Date.now()),
626
+ 'tq_popup:retired': String(Date.now()),
627
+ tq_popup_visited: '1',
628
+ workflow_cart: '[]',
629
+ },
630
+ session: { 'tq_popup:welcome': String(Date.now()) },
631
+ })
632
+ expect(page.storage()).toEqual({ cookieConsent: 'declined', workflow_cart: '[]' })
633
+ expect(page.session()).toEqual({})
634
+
635
+ page.clock.advance(60000)
636
+ expect(page.dispatched).toEqual(['welcome'])
637
+ })
638
+
639
+ it('counts no visitor as returning without consent', async () => {
640
+ const forNew = popup({ id: 'new', audience: 'new' })
641
+ const forReturning = popup({ id: 'returning', audience: 'returning' })
642
+ const page = await loadPage({
643
+ popups: [forNew, forReturning],
644
+ storage: { tq_popup_visited: '1' },
645
+ })
646
+ page.clock.advance(60000)
647
+ expect(page.dispatched).toEqual(['new'])
648
+ })
649
+
650
+ it('stores what the visit held once the visitor accepts on the page, and goes by it after', async () => {
651
+ const page = await loadPage({ popups: [popup()] })
652
+ page.clock.advance(60000)
653
+ expect(page.dispatched).toEqual(['welcome'])
654
+ expect(page.storage()).toEqual({})
655
+
656
+ page.answer('accepted')
657
+ const stored = page.storage()
658
+ expect(stored.tq_popup_visited).toBe('1')
659
+ expect(Math.abs(Date.now() - Number(stored['tq_popup:welcome']))).toBeLessThan(5000)
660
+
661
+ const nextVisit = await loadPage({ popups: [popup()], storage: stored })
662
+ nextVisit.clock.advance(60000)
663
+ expect(nextVisit.dispatched).toEqual([])
664
+
665
+ const forReturning = popup({ id: 'returning', audience: 'returning' })
666
+ const returning = await loadPage({ popups: [forReturning], storage: stored })
667
+ returning.clock.advance(60000)
668
+ expect(returning.dispatched).toEqual(['returning'])
669
+ })
670
+
671
+ it('stores a "once per session" popup in the session when the visitor accepts', async () => {
672
+ const perSession = popup({ frequency: { kind: 'session', days: 0 } })
673
+ const page = await loadPage({ popups: [perSession] })
674
+ page.clock.advance(60000)
675
+ expect(page.session()).toEqual({})
676
+
677
+ page.answer('accepted')
678
+ expect(page.session()['tq_popup:welcome']).toBeTruthy()
679
+ expect(page.storage()['tq_popup:welcome']).toBeUndefined()
680
+ })
681
+ })
682
+
543
683
  describeInDom('popup runtime — what the visitor does with it', () => {
544
684
  it('runs without analytics on the page', async () => {
545
- const page = await loadPage({ popups: [popup()], analytics: false })
685
+ const page = await loadPage({ popups: [popup()], analytics: false, storage: ACCEPTED })
546
686
  page.clock.advance(60000)
547
687
  expect(page.dispatched).toEqual(['welcome'])
548
688
  page.card('welcome').querySelector('[data-tq-popup-convert]').click()