-
Notifications
You must be signed in to change notification settings - Fork 223
/
Copy pathcore.ts
1380 lines (1257 loc) · 41.9 KB
/
core.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2022 Snowplow Analytics Ltd, 2010 Anthon Pang
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import { v4 as uuid } from 'uuid';
import { payloadBuilder, PayloadBuilder, Payload, isJson, payloadJsonProcessor } from './payload';
import {
globalContexts,
ConditionalContextProvider,
ContextPrimitive,
GlobalContexts,
PluginContexts,
pluginContexts,
} from './contexts';
import { CorePlugin } from './plugins';
import { LOG } from './logger';
/**
* export interface for any Self-Describing JSON such as context or Self Describing events
* @typeParam T - The type of the data object within a SelfDescribingJson
*/
export type SelfDescribingJson<T extends Record<keyof T, unknown> = Record<string, unknown>> = {
/**
* The schema string
* @example 'iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0'
*/
schema: string;
/**
* The data object which should conform to the supplied schema
*/
data: T;
};
/**
* export interface for any Self-Describing JSON which has the data attribute as an array
* @typeParam T - The type of the data object within the SelfDescribingJson data array
*/
export type SelfDescribingJsonArray<T extends Record<keyof T, unknown> = Record<string, unknown>> = {
/**
* The schema string
* @example 'iglu:com.snowplowanalytics.snowplow/contexts/jsonschema/1-0-1'
*/
schema: string;
/**
* The data array which should conform to the supplied schema
*/
data: Array<T>;
};
/**
* Algebraic datatype representing possible timestamp type choice
*/
export type Timestamp = TrueTimestamp | DeviceTimestamp | number;
/**
* A representation of a True Timestamp (ttm)
*/
export interface TrueTimestamp {
readonly type: 'ttm';
readonly value: number;
}
/**
* A representation of a Device Timestamp (dtm)
*/
export interface DeviceTimestamp {
readonly type: 'dtm';
readonly value: number;
}
/**
* Pair of timestamp type ready to be included to payload
*/
type TimestampPayload = TrueTimestamp | DeviceTimestamp;
/**
* Transform optional/old-behavior number timestamp into`Timestamp` ADT
*
* @param timestamp - optional number or timestamp object
* @returns correct timestamp object
*/
function getTimestamp(timestamp?: Timestamp | null): TimestampPayload {
if (timestamp == null) {
return { type: 'dtm', value: new Date().getTime() };
} else if (typeof timestamp === 'number') {
return { type: 'dtm', value: timestamp };
} else if (timestamp.type === 'ttm') {
// We can return timestamp here, but this is safer fallback
return { type: 'ttm', value: timestamp.value };
} else {
return { type: 'dtm', value: timestamp.value || new Date().getTime() };
}
}
/** Additional data points to set when tracking an event */
export interface CommonEventProperties {
/** Add context to an event by setting an Array of Self Describing JSON */
context?: Array<SelfDescribingJson> | null;
/** Set the true timestamp or overwrite the device sent timestamp on an event */
timestamp?: Timestamp | null;
}
/**
* export interface containing all Core functions
*/
export interface TrackerCore {
/**
* Call with a payload from a buildX function
* Adds context and payloadPairs name-value pairs to the payload
* Applies the callback to the built payload
*
* @param pb - Payload
* @param context - Custom contexts relating to the event
* @param timestamp - Timestamp of the event
* @returns Payload after the callback is applied
*/
track: (
/** A PayloadBuilder created by one of the `buildX` functions */
pb: PayloadBuilder,
/** The additional contextual information related to the event */
context?: Array<SelfDescribingJson> | null,
/** Timestamp override */
timestamp?: Timestamp | null
) => Payload;
/**
* Set a persistent key-value pair to be added to every payload
*
* @param key - Field name
* @param value - Field value
*/
addPayloadPair: (key: string, value: string | number) => void;
/**
* Get current base64 encoding state
*/
getBase64Encoding(): boolean;
/**
* Turn base 64 encoding on or off
*
* @param encode - Whether to encode payload
*/
setBase64Encoding(encode: boolean): void;
/**
* Merges a dictionary into payloadPairs
*
* @param dict - Adds a new payload dictionary to the existing one
*/
addPayloadDict(dict: Payload): void;
/**
* Replace payloadPairs with a new dictionary
*
* @param dict - Resets all current payload pairs with a new dictionary of pairs
*/
resetPayloadPairs(dict: Payload): void;
/**
* Set the tracker version
*
* @param version - The version of the current tracker
*/
setTrackerVersion(version: string): void;
/**
* Set the tracker namespace
*
* @param name - The trackers namespace
*/
setTrackerNamespace(name: string): void;
/**
* Set the application ID
*
* @param appId - An application ID which identifies the current application
*/
setAppId(appId: string): void;
/**
* Set the platform
*
* @param value - A valid Snowplow platform value
*/
setPlatform(value: string): void;
/**
* Set the user ID
*
* @param userId - The custom user id
*/
setUserId(userId: string): void;
/**
* Set the screen resolution
*
* @param width - screen resolution width
* @param height - screen resolution height
*/
setScreenResolution(width: string, height: string): void;
/**
* Set the viewport dimensions
*
* @param width - viewport width
* @param height - viewport height
*/
setViewport(width: string, height: string): void;
/**
* Set the color depth
*
* @param depth - A color depth value as string
*/
setColorDepth(depth: string): void;
/**
* Set the timezone
*
* @param timezone - A timezone string
*/
setTimezone(timezone: string): void;
/**
* Set the language
*
* @param lang - A language string e.g. 'en-UK'
*/
setLang(lang: string): void;
/**
* Set the IP address
*
* @param ip - An IP Address string
*/
setIpAddress(ip: string): void;
/**
* Set the Useragent
*
* @param useragent - A useragent string
*/
setUseragent(useragent: string): void;
/**
* Adds contexts globally, contexts added here will be attached to all applicable events
* @param contexts - An array containing either contexts or a conditional contexts
*/
addGlobalContexts(contexts: Array<ConditionalContextProvider | ContextPrimitive>): void;
/**
* Removes all global contexts
*/
clearGlobalContexts(): void;
/**
* Removes previously added global context, performs a deep comparison of the contexts or conditional contexts
* @param contexts - An array containing either contexts or a conditional contexts
*/
removeGlobalContexts(contexts: Array<ConditionalContextProvider | ContextPrimitive>): void;
/**
* Add a plugin into the plugin collection after Core has already been initialised
* @param configuration - The plugin to add
*/
addPlugin(configuration: CorePluginConfiguration): void;
}
/**
* The configuration object for the tracker core library
*/
export interface CoreConfiguration {
/* Should payloads be base64 encoded when built */
base64?: boolean;
/* A list of all the plugins to include at load */
corePlugins?: Array<CorePlugin>;
/* The callback which will fire each time `track()` is called */
callback?: (PayloadData: PayloadBuilder) => void;
}
/**
* The configuration of the plugin to add
*/
export interface CorePluginConfiguration {
/* The plugin to add */
plugin: CorePlugin;
}
/**
* Create a tracker core object
*
* @param base64 - Whether to base 64 encode contexts and self describing event JSONs
* @param corePlugins - The core plugins to be processed with each event
* @param callback - Function applied to every payload dictionary object
* @returns Tracker core
*/
export function trackerCore(configuration: CoreConfiguration = {}): TrackerCore {
function newCore(base64: boolean, corePlugins: Array<CorePlugin>, callback?: (PayloadData: PayloadBuilder) => void) {
const pluginContextsHelper: PluginContexts = pluginContexts(corePlugins),
globalContextsHelper: GlobalContexts = globalContexts();
let encodeBase64 = base64,
payloadPairs: Payload = {}; // Dictionary of key-value pairs which get added to every payload, e.g. tracker version
/**
* Wraps an array of custom contexts in a self-describing JSON
*
* @param contexts - Array of custom context self-describing JSONs
* @returns Outer JSON
*/
function completeContexts(
contexts?: Array<SelfDescribingJson>
): SelfDescribingJsonArray<SelfDescribingJson> | undefined {
if (contexts && contexts.length) {
return {
schema: 'iglu:com.snowplowanalytics.snowplow/contexts/jsonschema/1-0-0',
data: contexts,
};
}
return undefined;
}
/**
* Adds all global contexts to a contexts array
*
* @param pb - PayloadData
* @param contexts - Custom contexts relating to the event
*/
function attachGlobalContexts(
pb: PayloadBuilder,
contexts?: Array<SelfDescribingJson> | null
): Array<SelfDescribingJson> {
const applicableContexts: Array<SelfDescribingJson> = globalContextsHelper.getApplicableContexts(pb);
const returnedContexts: Array<SelfDescribingJson> = [];
if (contexts && contexts.length) {
returnedContexts.push(...contexts);
}
if (applicableContexts && applicableContexts.length) {
returnedContexts.push(...applicableContexts);
}
return returnedContexts;
}
/**
* Gets called by every trackXXX method
* Adds context and payloadPairs name-value pairs to the payload
* Applies the callback to the built payload
*
* @param pb - Payload
* @param context - Custom contexts relating to the event
* @param timestamp - Timestamp of the event
* @returns Payload after the callback is applied
*/
function track(
pb: PayloadBuilder,
context?: Array<SelfDescribingJson> | null,
timestamp?: Timestamp | null
): Payload {
pb.withJsonProcessor(payloadJsonProcessor(encodeBase64));
pb.add('eid', uuid());
pb.addDict(payloadPairs);
const tstamp = getTimestamp(timestamp);
pb.add(tstamp.type, tstamp.value.toString());
const allContexts = attachGlobalContexts(pb, pluginContextsHelper.addPluginContexts(context));
const wrappedContexts = completeContexts(allContexts);
if (wrappedContexts !== undefined) {
pb.addJson('cx', 'co', wrappedContexts);
}
corePlugins.forEach((plugin) => {
try {
if (plugin.beforeTrack) {
plugin.beforeTrack(pb);
}
} catch (ex) {
LOG.error('Plugin beforeTrack', ex);
}
});
if (typeof callback === 'function') {
callback(pb);
}
const finalPayload = pb.build();
corePlugins.forEach((plugin) => {
try {
if (plugin.afterTrack) {
plugin.afterTrack(finalPayload);
}
} catch (ex) {
LOG.error('Plugin afterTrack', ex);
}
});
return finalPayload;
}
/**
* Set a persistent key-value pair to be added to every payload
*
* @param key - Field name
* @param value - Field value
*/
function addPayloadPair(key: string, value: string | number): void {
payloadPairs[key] = value;
}
const core = {
track,
addPayloadPair,
getBase64Encoding() {
return encodeBase64;
},
setBase64Encoding(encode: boolean) {
encodeBase64 = encode;
},
addPayloadDict(dict: Payload) {
for (const key in dict) {
if (Object.prototype.hasOwnProperty.call(dict, key)) {
payloadPairs[key] = dict[key];
}
}
},
resetPayloadPairs(dict: Payload) {
payloadPairs = isJson(dict) ? dict : {};
},
setTrackerVersion(version: string) {
addPayloadPair('tv', version);
},
setTrackerNamespace(name: string) {
addPayloadPair('tna', name);
},
setAppId(appId: string) {
addPayloadPair('aid', appId);
},
setPlatform(value: string) {
addPayloadPair('p', value);
},
setUserId(userId: string) {
addPayloadPair('uid', userId);
},
setScreenResolution(width: string, height: string) {
addPayloadPair('res', width + 'x' + height);
},
setViewport(width: string, height: string) {
addPayloadPair('vp', width + 'x' + height);
},
setColorDepth(depth: string) {
addPayloadPair('cd', depth);
},
setTimezone(timezone: string) {
addPayloadPair('tz', timezone);
},
setLang(lang: string) {
addPayloadPair('lang', lang);
},
setIpAddress(ip: string) {
addPayloadPair('ip', ip);
},
setUseragent(useragent: string) {
addPayloadPair('ua', useragent);
},
addGlobalContexts(contexts: Array<ConditionalContextProvider | ContextPrimitive>) {
globalContextsHelper.addGlobalContexts(contexts);
},
clearGlobalContexts(): void {
globalContextsHelper.clearGlobalContexts();
},
removeGlobalContexts(contexts: Array<ConditionalContextProvider | ContextPrimitive>) {
globalContextsHelper.removeGlobalContexts(contexts);
},
};
return core;
}
const { base64, corePlugins, callback } = configuration,
plugins = corePlugins ?? [],
partialCore = newCore(base64 ?? true, plugins, callback),
core = {
...partialCore,
addPlugin: (configuration: CorePluginConfiguration) => {
const { plugin } = configuration;
plugins.push(plugin);
plugin.logger?.(LOG);
plugin.activateCorePlugin?.(core);
},
};
plugins?.forEach((plugin) => {
plugin.logger?.(LOG);
plugin.activateCorePlugin?.(core);
});
return core;
}
/**
* A Self Describing Event
* A custom event type, allowing for an event to be tracked using your own custom schema
* and a data object which conforms to the supplied schema
*/
export interface SelfDescribingEvent {
/** The Self Describing JSON which describes the event */
event: SelfDescribingJson;
}
/**
* Build a self-describing event
* A custom event type, allowing for an event to be tracked using your own custom schema
* and a data object which conforms to the supplied schema
*
* @param event - Contains the properties and schema location for the event
* @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track}
*/
export function buildSelfDescribingEvent(event: SelfDescribingEvent): PayloadBuilder {
const {
event: { schema, data },
} = event,
pb = payloadBuilder();
const ueJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/unstruct_event/jsonschema/1-0-0',
data: { schema, data },
};
pb.add('e', 'ue');
pb.addJson('ue_px', 'ue_pr', ueJson);
return pb;
}
/**
* A Page View Event
* Represents a Page View, which is typically fired as soon as possible when a web page
* is loaded within the users browser. Often also fired on "virtual page views" within
* Single Page Applications (SPA).
*/
export interface PageViewEvent {
/** The current URL visible in the users browser */
pageUrl?: string | null;
/** The current page title in the users browser */
pageTitle?: string | null;
/** The URL of the referring page */
referrer?: string | null;
}
/**
* Build a Page View Event
* Represents a Page View, which is typically fired as soon as possible when a web page
* is loaded within the users browser. Often also fired on "virtual page views" within
* Single Page Applications (SPA).
*
* @param event - Contains the properties for the Page View event
* @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track}
*/
export function buildPageView(event: PageViewEvent): PayloadBuilder {
const { pageUrl, pageTitle, referrer } = event,
pb = payloadBuilder();
pb.add('e', 'pv'); // 'pv' for Page View
pb.add('url', pageUrl);
pb.add('page', pageTitle);
pb.add('refr', referrer);
return pb;
}
/**
* A Page Ping Event
* Fires when activity tracking is enabled in the browser.
* Tracks same information as the last tracked Page View and includes scroll
* information from the current page view
*/
export interface PagePingEvent extends PageViewEvent {
/** The minimum X scroll position for the current page view */
minXOffset?: number;
/** The maximum X scroll position for the current page view */
maxXOffset?: number;
/** The minimum Y scroll position for the current page view */
minYOffset?: number;
/** The maximum Y scroll position for the current page view */
maxYOffset?: number;
}
/**
* Build a Page Ping Event
* Fires when activity tracking is enabled in the browser.
* Tracks same information as the last tracked Page View and includes scroll
* information from the current page view
*
* @param event - Contains the properties for the Page Ping event
* @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track}
*/
export function buildPagePing(event: PagePingEvent): PayloadBuilder {
const { pageUrl, pageTitle, referrer, minXOffset, maxXOffset, minYOffset, maxYOffset } = event,
pb = payloadBuilder();
pb.add('e', 'pp'); // 'pp' for Page Ping
pb.add('url', pageUrl);
pb.add('page', pageTitle);
pb.add('refr', referrer);
if (minXOffset && !isNaN(Number(minXOffset))) pb.add('pp_mix', minXOffset.toString());
if (maxXOffset && !isNaN(Number(maxXOffset))) pb.add('pp_max', maxXOffset.toString());
if (minYOffset && !isNaN(Number(minYOffset))) pb.add('pp_miy', minYOffset.toString());
if (maxYOffset && !isNaN(Number(maxYOffset))) pb.add('pp_may', maxYOffset.toString());
return pb;
}
/**
* A Structured Event
* A classic style of event tracking, allows for easier movement between analytics
* systems. A loosely typed event, creating a Self Describing event is preferred, but
* useful for interoperability.
*/
export interface StructuredEvent {
category: string;
action: string;
label?: string;
property?: string;
value?: number;
}
/**
* Build a Structured Event
* A classic style of event tracking, allows for easier movement between analytics
* systems. A loosely typed event, creating a Self Describing event is preferred, but
* useful for interoperability.
*
* @param event - Contains the properties for the Structured event
* @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track}
*/
export function buildStructEvent(event: StructuredEvent): PayloadBuilder {
const { category, action, label, property, value } = event,
pb = payloadBuilder();
pb.add('e', 'se'); // 'se' for Structured Event
pb.add('se_ca', category);
pb.add('se_ac', action);
pb.add('se_la', label);
pb.add('se_pr', property);
pb.add('se_va', value == null ? undefined : value.toString());
return pb;
}
/**
* An Ecommerce Transaction Event
* Allows for tracking common ecommerce events, this event is usually used when
* a customer completes a transaction.
*/
export interface EcommerceTransactionEvent {
/** An identifier for the order */
orderId: string;
/** The total value of the order */
total: number;
/** Transaction affiliation (e.g. store where sale took place) */
affiliation?: string;
/** The amount of tax on the transaction */
tax?: number;
/** The amount of shipping costs for this transaction */
shipping?: number;
/** Delivery address, city */
city?: string;
/** Delivery address, state */
state?: string;
/** Delivery address, country */
country?: string;
/** Currency of the transaction */
currency?: string;
}
/**
* Build an Ecommerce Transaction Event
* Allows for tracking common ecommerce events, this event is usually used when
* a consumer completes a transaction.
*
* @param event - Contains the properties for the Ecommerce Transactoion event
* @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track}
*/
export function buildEcommerceTransaction(event: EcommerceTransactionEvent): PayloadBuilder {
const { orderId, total, affiliation, tax, shipping, city, state, country, currency } = event,
pb = payloadBuilder();
pb.add('e', 'tr'); // 'tr' for Transaction
pb.add('tr_id', orderId);
pb.add('tr_af', affiliation);
pb.add('tr_tt', total);
pb.add('tr_tx', tax);
pb.add('tr_sh', shipping);
pb.add('tr_ci', city);
pb.add('tr_st', state);
pb.add('tr_co', country);
pb.add('tr_cu', currency);
return pb;
}
/**
* An Ecommerce Transaction Item
* Related to the {@link EcommerceTransactionEvent}
* Each Ecommerce Transaction may contain one or more EcommerceTransactionItem events
*/
export interface EcommerceTransactionItemEvent {
/** An identifier for the order */
orderId: string;
/** A Product Stock Keeping Unit (SKU) */
sku: string;
/** The price of the product */
price: number;
/** The name of the product */
name?: string;
/** The category the product belongs to */
category?: string;
/** The quanity of this product within the transaction */
quantity?: number;
/** The currency of the product for the transaction */
currency?: string;
}
/**
* Build an Ecommerce Transaction Item Event
* Related to the {@link buildEcommerceTransaction}
* Each Ecommerce Transaction may contain one or more EcommerceTransactionItem events
*
* @param event - Contains the properties for the Ecommerce Transaction Item event
* @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track}
*/
export function buildEcommerceTransactionItem(event: EcommerceTransactionItemEvent): PayloadBuilder {
const { orderId, sku, price, name, category, quantity, currency } = event,
pb = payloadBuilder();
pb.add('e', 'ti'); // 'tr' for Transaction Item
pb.add('ti_id', orderId);
pb.add('ti_sk', sku);
pb.add('ti_nm', name);
pb.add('ti_ca', category);
pb.add('ti_pr', price);
pb.add('ti_qu', quantity);
pb.add('ti_cu', currency);
return pb;
}
/**
* A Screen View Event
* Similar to a Page View but less focused on typical web properties
* Often used for mobile applications as the user is presented with
* new views as they performance navigation events
*/
export interface ScreenViewEvent {
/** The name of the screen */
name?: string;
/** The identifier of the screen */
id?: string;
}
/**
* Build a Scren View Event
* Similar to a Page View but less focused on typical web properties
* Often used for mobile applications as the user is presented with
* new views as they performance navigation events
*
* @param event - Contains the properties for the Screen View event. One or more properties must be included.
* @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track}
*/
export function buildScreenView(event: ScreenViewEvent): PayloadBuilder {
const { name, id } = event;
return buildSelfDescribingEvent({
event: {
schema: 'iglu:com.snowplowanalytics.snowplow/screen_view/jsonschema/1-0-0',
data: removeEmptyProperties({ name, id }),
},
});
}
/**
* A Link Click Event
* Used when a user clicks on a link on a webpage, typically an anchor tag <a>
*/
export interface LinkClickEvent {
/** The target URL of the link */
targetUrl: string;
/** The ID of the element clicked if present */
elementId?: string;
/** An array of class names from the element clicked */
elementClasses?: Array<string>;
/** The target value of the element if present */
elementTarget?: string;
/** The content of the element if present and enabled */
elementContent?: string;
}
/**
* Build a Link Click Event
* Used when a user clicks on a link on a webpage, typically an anchor tag <a>
*
* @param event - Contains the properties for the Link Click event
* @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track}
*/
export function buildLinkClick(event: LinkClickEvent): PayloadBuilder {
const { targetUrl, elementId, elementClasses, elementTarget, elementContent } = event;
const eventJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/link_click/jsonschema/1-0-1',
data: removeEmptyProperties({ targetUrl, elementId, elementClasses, elementTarget, elementContent }),
};
return buildSelfDescribingEvent({ event: eventJson });
}
/**
* An Ad Impression Event
* Used to track an advertisement impression
*
* @remarks
* If you provide the cost field, you must also provide one of 'cpa', 'cpc', and 'cpm' for the costModel field.
*/
export interface AdImpressionEvent {
/** Identifier for the particular impression instance */
impressionId?: string;
/** The cost model for the campaign */
costModel?: 'cpa' | 'cpc' | 'cpm';
/** Advertisement cost */
cost?: number;
/** The destination URL of the advertisement */
targetUrl?: string;
/** Identifier for the ad banner being displayed */
bannerId?: string;
/** Identifier for the zone where the ad banner is located */
zoneId?: string;
/** Identifier for the advertiser which the campaign belongs to */
advertiserId?: string;
/** Identifier for the advertiser which the campaign belongs to */
campaignId?: string;
}
/**
* Build a Ad Impression Event
* Used to track an advertisement impression
*
* @remarks
* If you provide the cost field, you must also provide one of 'cpa', 'cpc', and 'cpm' for the costModel field.
*
* @param event - Contains the properties for the Ad Impression event
* @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track}
*/
export function buildAdImpression(event: AdImpressionEvent): PayloadBuilder {
const { impressionId, costModel, cost, targetUrl, bannerId, zoneId, advertiserId, campaignId } = event;
const eventJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/ad_impression/jsonschema/1-0-0',
data: removeEmptyProperties({
impressionId,
costModel,
cost,
targetUrl,
bannerId,
zoneId,
advertiserId,
campaignId,
}),
};
return buildSelfDescribingEvent({ event: eventJson });
}
/**
* An Ad Click Event
* Used to track an advertisement click
*
* @remarks
* If you provide the cost field, you must also provide one of 'cpa', 'cpc', and 'cpm' for the costModel field.
*/
export interface AdClickEvent {
/** The destination URL of the advertisement */
targetUrl: string;
/** Identifier for the particular click instance */
clickId?: string;
/** The cost model for the campaign */
costModel?: 'cpa' | 'cpc' | 'cpm';
/** Advertisement cost */
cost?: number;
/** Identifier for the ad banner being displayed */
bannerId?: string;
/** Identifier for the zone where the ad banner is located */
zoneId?: string;
/** Identifier for the particular impression instance */
impressionId?: string;
/** Identifier for the advertiser which the campaign belongs to */
advertiserId?: string;
/** Identifier for the advertiser which the campaign belongs to */
campaignId?: string;
}
/**
* Build a Ad Click Event
* Used to track an advertisement click
*
* @remarks
* If you provide the cost field, you must also provide one of 'cpa', 'cpc', and 'cpm' for the costModel field.
*
* @param event - Contains the properties for the Ad Click event
* @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track}
*/
export function buildAdClick(event: AdClickEvent): PayloadBuilder {
const { targetUrl, clickId, costModel, cost, bannerId, zoneId, impressionId, advertiserId, campaignId } = event;
const eventJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/ad_click/jsonschema/1-0-0',
data: removeEmptyProperties({
targetUrl,
clickId,
costModel,
cost,
bannerId,
zoneId,
impressionId,
advertiserId,
campaignId,
}),
};
return buildSelfDescribingEvent({ event: eventJson });
}
/**
* An Ad Conversion Event
* Used to track an advertisement click
*
* @remarks
* If you provide the cost field, you must also provide one of 'cpa', 'cpc', and 'cpm' for the costModel field.
*/
export interface AdConversionEvent {
/** Identifier for the particular conversion instance */
conversionId?: string;
/** The cost model for the campaign */
costModel?: 'cpa' | 'cpc' | 'cpm';
/** Advertisement cost */
cost?: number;
/** Conversion category */
category?: string;
/** The type of user interaction e.g. 'purchase' */
action?: string;
/** Describes the object of the conversion */
property?: string;
/** How much the conversion is initially worth */
initialValue?: number;
/** Identifier for the advertiser which the campaign belongs to */
advertiserId?: string;
/** Identifier for the advertiser which the campaign belongs to */
campaignId?: string;
}
/**
* Build a Ad Conversion Event
* Used to track an advertisement click
*
* @remarks
* If you provide the cost field, you must also provide one of 'cpa', 'cpc', and 'cpm' for the costModel field.