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

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.
@@ -0,0 +1,376 @@
1
+ import { TRACKER_SOURCE } from '../src/analytics/tracker-source'
2
+
3
+ /**
4
+ * The funnel steps a page declares with `data-tq-commerce-view`, run through
5
+ * the emitted tracker against a stubbed browser whose page changes the way a
6
+ * published store's does.
7
+ *
8
+ * The order page is the case this exists for. The editor builds it with its
9
+ * "loaded" section (which carries the purchase marker) showing by default, so
10
+ * the designer can preview it; on the live site the page therefore paints that
11
+ * section with an EMPTY order, then hides it while the order loads, then shows
12
+ * it again with the real order number. The tracker used to look once, when the
13
+ * page had painted: it either caught the empty section and sent the store's
14
+ * Google tags a purchase with no order number, or caught the loading state and
15
+ * sent nothing.
16
+ */
17
+
18
+ type Attributes = Record<string, string>
19
+ type Sent = Record<string, unknown>
20
+
21
+ interface Mutation {
22
+ type: 'childList' | 'attributes'
23
+ addedNodes: FakeElement[]
24
+ attributeName?: string
25
+ }
26
+
27
+ const MARKER = 'data-tq-commerce-view'
28
+
29
+ class FakeElement {
30
+ readonly nodeType = 1
31
+
32
+ constructor(public attributes: Attributes, public children: FakeElement[] = []) {}
33
+
34
+ getAttribute(name: string): string | null {
35
+ return Object.prototype.hasOwnProperty.call(this.attributes, name)
36
+ ? this.attributes[name]
37
+ : null
38
+ }
39
+
40
+ matches(selector: string): boolean {
41
+ const attribute = /^\[([\w-]+)\]$/.exec(selector)
42
+ return attribute !== null && this.getAttribute(attribute[1]) !== null
43
+ }
44
+
45
+ querySelector(selector: string): FakeElement | null {
46
+ for (const child of this.children) {
47
+ if (child.matches(selector)) {
48
+ return child
49
+ }
50
+ const inside = child.querySelector(selector)
51
+ if (inside) {
52
+ return inside
53
+ }
54
+ }
55
+ return null
56
+ }
57
+ }
58
+
59
+ function memoryStorage() {
60
+ const values = new Map<string, string>()
61
+ return {
62
+ getItem: (key: string) => (values.has(key) ? values.get(key) : null),
63
+ setItem: (key: string, value: string) => values.set(key, String(value)),
64
+ removeItem: (key: string) => values.delete(key),
65
+ }
66
+ }
67
+
68
+ function bootTracker(
69
+ options: {
70
+ path?: string
71
+ localStorage?: ReturnType<typeof memoryStorage>
72
+ /** No analytics key: our tracker is off, the merchant's Google tags are not. */
73
+ analyticsOff?: boolean
74
+ } = {}
75
+ ) {
76
+ const localStorage = options.localStorage || memoryStorage()
77
+ const batches: Sent[][] = []
78
+ const documentListeners: Record<string, () => void> = {}
79
+ const body = new FakeElement({})
80
+
81
+ const observers = new Set<FakeMutationObserver>()
82
+ class FakeMutationObserver {
83
+ private attributeFilter: string[] | null = null
84
+
85
+ constructor(private readonly callback: (records: Mutation[]) => void) {}
86
+
87
+ observe(_root: unknown, init: { attributeFilter?: string[] }) {
88
+ this.attributeFilter = init.attributeFilter || null
89
+ observers.add(this)
90
+ }
91
+
92
+ disconnect() {
93
+ observers.delete(this)
94
+ }
95
+
96
+ deliver(records: Mutation[]) {
97
+ const seen = records.filter(
98
+ (record) =>
99
+ record.type !== 'attributes' ||
100
+ !this.attributeFilter ||
101
+ this.attributeFilter.includes(record.attributeName as string)
102
+ )
103
+ if (seen.length > 0) {
104
+ this.callback(seen)
105
+ }
106
+ }
107
+ }
108
+ const mutate = (records: Mutation[]) => Array.from(observers).forEach((o) => o.deliver(records))
109
+
110
+ const fakeDocument = {
111
+ visibilityState: 'visible',
112
+ referrer: '',
113
+ body,
114
+ documentElement: { scrollHeight: 0 },
115
+ addEventListener: (type: string, listener: () => void) => {
116
+ documentListeners[type] = listener
117
+ },
118
+ querySelector: (selector: string) => body.querySelector(selector),
119
+ querySelectorAll: (): FakeElement[] => [],
120
+ }
121
+ const fakeWindow = {
122
+ location: { hostname: 'shop.example.com', pathname: options.path || '/', search: '' },
123
+ localStorage,
124
+ sessionStorage: memoryStorage(),
125
+ screen: { width: 1440 },
126
+ innerHeight: 900,
127
+ scrollY: 0,
128
+ addEventListener: (): void => undefined,
129
+ // The merchant's Google tag, as a fresh page load starts it.
130
+ dataLayer: [] as Array<Record<string, unknown>>,
131
+ }
132
+ const fakeFetch = (url: string, init: { body: string }) => {
133
+ if (!url.endsWith('/heartbeat')) {
134
+ batches.push(JSON.parse(init.body).events)
135
+ }
136
+ return Promise.resolve({ status: 202 })
137
+ }
138
+
139
+ const source = TRACKER_SOURCE.replace(/^export\s+/gm, '')
140
+ const tracker = new Function(
141
+ 'process',
142
+ 'window',
143
+ 'document',
144
+ 'navigator',
145
+ 'fetch',
146
+ 'setInterval',
147
+ 'setTimeout',
148
+ 'MutationObserver',
149
+ `${source}\nreturn { initTeleportAnalytics, trackRouteChange, trackCommerceView, resetCommerceView }`
150
+ )(
151
+ {
152
+ env: {
153
+ NEXT_PUBLIC_TELEPORT_ANALYTICS_URL: 'https://analytics.example.com',
154
+ NEXT_PUBLIC_TELEPORT_ANALYTICS_KEY: options.analyticsOff ? '' : 'public-key',
155
+ },
156
+ },
157
+ fakeWindow,
158
+ fakeDocument,
159
+ { webdriver: false },
160
+ fakeFetch,
161
+ () => 0,
162
+ () => 0,
163
+ FakeMutationObserver
164
+ )
165
+
166
+ const page = {
167
+ tracker,
168
+ localStorage,
169
+ show(node: FakeElement) {
170
+ body.children.push(node)
171
+ mutate([{ type: 'childList', addedNodes: [node] }])
172
+ },
173
+ hide(node: FakeElement) {
174
+ body.children = body.children.filter((child) => child !== node)
175
+ mutate([{ type: 'childList', addedNodes: [] }])
176
+ },
177
+ setAttribute(node: FakeElement, name: string, value: string) {
178
+ node.attributes[name] = value
179
+ mutate([{ type: 'attributes', addedNodes: [], attributeName: name }])
180
+ },
181
+ /** What the tracker component does once the page it mounted on has painted. */
182
+ painted() {
183
+ tracker.initTeleportAnalytics({})
184
+ tracker.trackCommerceView()
185
+ },
186
+ /**
187
+ * A client-side navigation, in the router's order: the address changes and
188
+ * the next page paints BEFORE the navigation is announced to the component.
189
+ */
190
+ navigate(path: string, ...nextPage: FakeElement[]) {
191
+ fakeWindow.location.pathname = path
192
+ body.children = nextPage
193
+ mutate([{ type: 'childList', addedNodes: nextPage }])
194
+ tracker.trackRouteChange(path)
195
+ tracker.resetCommerceView()
196
+ tracker.trackCommerceView()
197
+ },
198
+ /** The commerce steps sent to our analytics, as "step@page[:record]". */
199
+ commerceSent(): string[] {
200
+ if (documentListeners.visibilitychange) {
201
+ fakeDocument.visibilityState = 'hidden'
202
+ documentListeners.visibilitychange()
203
+ fakeDocument.visibilityState = 'visible'
204
+ }
205
+ return batches
206
+ .splice(0)
207
+ .flat()
208
+ .filter((event) => event.type === 'commerce')
209
+ .map((event) => `${event.name}@${event.path}${event.rid ? `:${event.rid}` : ''}`)
210
+ },
211
+ /** What reached the store's Google tags, as "event[:transaction_id]". */
212
+ sentToGoogle(): string[] {
213
+ return fakeWindow.dataLayer
214
+ .filter((entry) => entry.event)
215
+ .map((entry) => `${entry.event}${entry.transaction_id ? `:${entry.transaction_id}` : ''}`)
216
+ },
217
+ }
218
+ return page
219
+ }
220
+
221
+ // The order page's loaded section as the editor builds it: the marker's
222
+ // attributes are bound to the order's page state, empty until the order loads.
223
+ const orderSection = (orderId = '') =>
224
+ new FakeElement({
225
+ [MARKER]: 'purchase',
226
+ 'data-tq-commerce-id': orderId,
227
+ 'data-tq-commerce-value': orderId ? '42.5' : '',
228
+ 'data-tq-commerce-currency': orderId ? 'EUR' : '',
229
+ })
230
+
231
+ const ledger = (page: { localStorage: ReturnType<typeof memoryStorage> }) =>
232
+ JSON.parse(page.localStorage.getItem('tp_purchases') || 'null')
233
+
234
+ describe('tracker — an order page reports its purchase once the order has loaded', () => {
235
+ it('when the tracker first looks at the empty order the page paints before loading', () => {
236
+ const page = bootTracker({ path: '/orders/ORD-1' })
237
+ const emptyOrder = orderSection()
238
+ page.show(emptyOrder)
239
+ page.painted()
240
+
241
+ page.hide(emptyOrder)
242
+ page.show(orderSection('ORD-1'))
243
+
244
+ expect(page.sentToGoogle()).toEqual(['purchase:ORD-1'])
245
+ // The sale itself is reported by the site's server, never by the browser.
246
+ expect(page.commerceSent()).toEqual([])
247
+ })
248
+
249
+ it('when the tracker first looks while the order is still loading', () => {
250
+ const page = bootTracker({ path: '/orders/ORD-1' })
251
+ const emptyOrder = orderSection()
252
+ page.show(emptyOrder)
253
+ page.hide(emptyOrder)
254
+ page.painted()
255
+
256
+ page.show(orderSection('ORD-1'))
257
+
258
+ expect(page.sentToGoogle()).toEqual(['purchase:ORD-1'])
259
+ })
260
+
261
+ it('records the order in the ledger when the visitor has accepted cookies', () => {
262
+ const localStorage = memoryStorage()
263
+ localStorage.setItem('cookieConsent', 'accepted')
264
+ const page = bootTracker({ path: '/orders/ORD-1', localStorage })
265
+ page.painted()
266
+ page.show(orderSection('ORD-1'))
267
+
268
+ expect(ledger(page)).toEqual(['ORD-1'])
269
+ })
270
+
271
+ it('keeps it in memory, not on the device, until cookies are accepted', () => {
272
+ const page = bootTracker({ path: '/orders/ORD-1' })
273
+ page.painted()
274
+ page.show(orderSection('ORD-1'))
275
+
276
+ expect(page.sentToGoogle()).toEqual(['purchase:ORD-1'])
277
+ expect(ledger(page)).toBeNull()
278
+ })
279
+
280
+ it('reaches the Google tags even when our own analytics is off', () => {
281
+ const page = bootTracker({ path: '/orders/ORD-1', analyticsOff: true })
282
+ page.painted()
283
+ page.show(orderSection('ORD-1'))
284
+
285
+ expect(page.sentToGoogle()).toEqual(['purchase:ORD-1'])
286
+ })
287
+
288
+ it('is not sent again when the loaded order re-renders', () => {
289
+ const page = bootTracker({ path: '/orders/ORD-1' })
290
+ page.painted()
291
+ const loaded = orderSection('ORD-1')
292
+ page.show(loaded)
293
+ page.hide(loaded)
294
+ page.show(orderSection('ORD-1'))
295
+ page.setAttribute(loaded, 'data-tq-commerce-id', 'ORD-1')
296
+
297
+ expect(page.sentToGoogle()).toEqual(['purchase:ORD-1'])
298
+ })
299
+
300
+ it('is not sent again when the shopper comes back to it in the same visit', () => {
301
+ const page = bootTracker({ path: '/orders/ORD-1' })
302
+ page.painted()
303
+ page.show(orderSection('ORD-1'))
304
+ page.navigate('/orders')
305
+ page.navigate('/orders/ORD-1', orderSection('ORD-1'))
306
+
307
+ expect(page.sentToGoogle()).toEqual(['purchase:ORD-1'])
308
+ })
309
+
310
+ it('with consent, is not sent again when the order page is reloaded', () => {
311
+ const localStorage = memoryStorage()
312
+ localStorage.setItem('cookieConsent', 'accepted')
313
+ const confirmation = bootTracker({ path: '/orders/ORD-1', localStorage })
314
+ const emptyOrder = orderSection()
315
+ confirmation.show(emptyOrder)
316
+ confirmation.painted()
317
+ confirmation.hide(emptyOrder)
318
+ confirmation.show(orderSection('ORD-1'))
319
+ expect(confirmation.sentToGoogle()).toEqual(['purchase:ORD-1'])
320
+
321
+ const reloaded = bootTracker({ path: '/orders/ORD-1', localStorage })
322
+ const reloadedEmptyOrder = orderSection()
323
+ reloaded.show(reloadedEmptyOrder)
324
+ reloaded.painted()
325
+ reloaded.hide(reloadedEmptyOrder)
326
+ reloaded.show(orderSection('ORD-1'))
327
+
328
+ expect(reloaded.sentToGoogle()).toEqual([])
329
+ expect(ledger(reloaded)).toEqual(['ORD-1'])
330
+ })
331
+ })
332
+
333
+ describe('tracker — a funnel step whose marker appears after the page has painted', () => {
334
+ it('is reported once when the marker is inserted later', () => {
335
+ const page = bootTracker({ path: '/items/rose' })
336
+ page.painted()
337
+
338
+ const item = new FakeElement({ [MARKER]: 'view_item', 'data-tq-commerce-id': 'item-7' })
339
+ page.show(new FakeElement({}, [item]))
340
+ page.setAttribute(item, 'data-tq-commerce-id', 'item-7')
341
+ page.show(new FakeElement({}, [new FakeElement({ [MARKER]: 'view_item' })]))
342
+
343
+ expect(page.commerceSent()).toEqual(['view_item@/items/rose:item-7'])
344
+ expect(page.sentToGoogle()).toEqual(['view_item'])
345
+ })
346
+
347
+ it('waits for an id that is bound but not filled in yet', () => {
348
+ const page = bootTracker({ path: '/items/rose' })
349
+ const item = new FakeElement({ [MARKER]: 'view_item', 'data-tq-commerce-id': '' })
350
+ page.show(item)
351
+ page.painted()
352
+
353
+ page.setAttribute(item, 'data-tq-commerce-id', 'item-7')
354
+
355
+ expect(page.commerceSent()).toEqual(['view_item@/items/rose:item-7'])
356
+ })
357
+
358
+ it('still reports a marker that names no id the moment the page paints', () => {
359
+ const page = bootTracker({ path: '/checkout' })
360
+ page.show(new FakeElement({ [MARKER]: 'begin_checkout' }))
361
+ page.painted()
362
+
363
+ expect(page.commerceSent()).toEqual(['begin_checkout@/checkout'])
364
+ expect(page.sentToGoogle()).toEqual(['begin_checkout'])
365
+ })
366
+
367
+ it("counts the next page's step once, for that page, when the router paints it before announcing the navigation", () => {
368
+ const page = bootTracker({ path: '/cart' })
369
+ page.painted()
370
+
371
+ page.navigate('/checkout', new FakeElement({ [MARKER]: 'begin_checkout' }))
372
+
373
+ expect(page.commerceSent()).toEqual(['begin_checkout@/checkout'])
374
+ expect(page.sentToGoogle()).toEqual(['begin_checkout'])
375
+ })
376
+ })
@@ -0,0 +1,48 @@
1
+ import { GeneratedFolder, ProjectUIDL } from '@teleporthq/teleport-types'
2
+ import uidlSample from '../../../examples/test-samples/project-sample.json'
3
+ import { createNextProjectGenerator } from '../src'
4
+ import NextTemplate from '../src/project-template'
5
+
6
+ const template = JSON.parse(JSON.stringify(NextTemplate)) as GeneratedFolder
7
+
8
+ const allFiles = (folder: GeneratedFolder): Array<{ path: string; content: string }> => [
9
+ ...folder.files.map((file) => ({ path: `${file.name}.${file.fileType}`, content: file.content })),
10
+ ...folder.subFolders.flatMap((sub) =>
11
+ allFiles(sub).map((file) => ({ ...file, path: `${sub.name}/${file.path}` }))
12
+ ),
13
+ ]
14
+
15
+ const sampleWithHeadingClass = (): ProjectUIDL => {
16
+ const uidl = JSON.parse(JSON.stringify(uidlSample)) as ProjectUIDL
17
+ uidl.root.styleSetDefinitions = {
18
+ ...(uidl.root.styleSetDefinitions || {}),
19
+ 'brand-heading': {
20
+ type: 'reusable-project-style-map',
21
+ content: { fontFamily: 'Roboto' },
22
+ } as never,
23
+ }
24
+ return uidl
25
+ }
26
+
27
+ describe('Google fonts get a size-matched stand-in in the generated Next project', () => {
28
+ it('declares the stand-in once in the head and names it after the font everywhere', async () => {
29
+ const output = await createNextProjectGenerator().generateProject(
30
+ sampleWithHeadingClass(),
31
+ template
32
+ )
33
+ const files = allFiles(output)
34
+ const document = files.find((file) => file.path === 'pages/_document.js')
35
+
36
+ expect(document?.content).toContain('font-family: Roboto Fallback;')
37
+ expect(document?.content).toContain('size-adjust:')
38
+ expect(document?.content).toContain("font-family: 'Roboto', Roboto Fallback, sans-serif;")
39
+ expect(document?.content.match(/font-family: Roboto Fallback;/g)).toHaveLength(1)
40
+
41
+ const brandHeading = files.find((file) =>
42
+ /brand-heading\s*\{[^}]*font-family/.test(file.content)
43
+ )
44
+ expect(brandHeading?.content).toMatch(
45
+ /brand-heading\s*\{[^}]*font-family: Roboto, Roboto Fallback;/
46
+ )
47
+ })
48
+ })