-
Notifications
You must be signed in to change notification settings - Fork 144
/
Copy pathindex.js
346 lines (293 loc) · 7.59 KB
/
index.js
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
'use strict';
/**
* Module dependencies.
*/
var each = require('component-each');
var integration = require('@segment/analytics.js-integration');
var is = require('is');
var push = require('global-queue')('_kmq');
var extend = require('@ndhoule/extend');
var del = require('obj-case').del;
/**
* Expose `KISSmetrics` integration.
*/
var KISSmetrics = (module.exports = integration('KISSmetrics')
.global('KM')
.global('_kmil')
.global('_kmq')
.option('apiKey', '')
.option('prefixProperties', true)
.option('trackCategorizedPages', true)
.option('trackNamedPages', true)
.tag(
'library',
'<script src="//scripts.kissmetrics.io/{{ apiKey }}.2.js">'
));
/**
* Check if browser is mobile, for kissmetrics.
*
*/
exports.isMobile =
navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/BlackBerry/i) ||
navigator.userAgent.match(/IEMobile/i) ||
navigator.userAgent.match(/Opera Mini/i) ||
navigator.userAgent.match(/iPad/i) ||
navigator.userAgent.match(/iPhone|iPod/i);
/**
* Initialize.
*
* http://support.kissmetrics.io/apis/javascript
*/
KISSmetrics.prototype.initialize = function() {
window._kmq = window._kmq || [];
if (exports.isMobile) push('set', { 'Mobile Session': 'Yes' });
this.load('library', this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
KISSmetrics.prototype.loaded = function() {
return is.object(window.KM);
};
/**
* Page.
*
* @param {Page} page
*/
KISSmetrics.prototype.page = function(page) {
if (!window.KM_SKIP_PAGE_VIEW) {
push('record', 'Page View', {
'Viewed URL': page.url(),
Referrer: page.referrer() || 'Direct'
});
}
this.trackPage(page);
};
/**
* Track page.
*
* @param {Page} page
*/
KISSmetrics.prototype.trackPage = function(page) {
var category = page.category();
var name = page.fullName();
var opts = this.options;
var e;
// categorized pages
if (opts.trackCategorizedPages && category) {
e = page.category();
}
// named pages
if (opts.trackNamedPages && name) {
e = page.name();
}
if (!e) {
return;
}
var event = 'Viewed ' + e + ' Page';
var properties = prefix('Page', page.properties());
push('record', event, properties);
};
/**
* Identify.
*
* @param {Identify} identify
*/
KISSmetrics.prototype.identify = function(identify) {
var traits = clean(identify.traits());
var id = identify.userId();
if (id) push('identify', id);
if (traits) push('set', traits);
};
/**
* Track.
*
* @param {Track} track
*/
KISSmetrics.prototype.track = function(track) {
var mapping = { revenue: 'Billing Amount' };
var event = track.event();
var properties = clean(track.properties(mapping));
var revenue = track.revenue();
if (revenue) {
// legacy: client side integration used to only send 'Billing Amount', but
// our server side sent both 'revenue' and 'Billing Amount'. From the docs,
// http://support.kissmetrics.io/tools/revenue-report.html, ther is no
// reason to send it as 'Billing Amount', but we don't want to break reports
// so we send it as 'revenue' and 'Billing Amount' for consistency across
// platforms.
properties.revenue = revenue;
}
if (this.options.prefixProperties) properties = prefix(event, properties);
push('record', event, properties);
};
/**
* Alias.
*
* @param {Alias} to
*/
KISSmetrics.prototype.alias = function(alias) {
push('alias', alias.to(), alias.from());
};
/**
* Group.
*
* @param {Group} to
*/
KISSmetrics.prototype.group = function(group) {
push('set', prefix('Group', group.traits()));
};
/**
* Completed order.
*
* @param {Track} track
* @api private
*/
KISSmetrics.prototype.completedOrder = function(track) {
var opts = this.options;
var event = track.event();
var products = track.products();
var timestamp = toUnixTimestamp(track.timestamp() || new Date());
var properties = track.properties();
// since we send product data separately and KM doesn't serialize it anyway (shows up as '[object Object]')
// we're going to delete the property
del(properties, 'products');
if (opts.prefixProperties) properties = prefix(event, properties);
// transaction
push('record', event, properties);
// items
window._kmq.push(function() {
each(products, function(product, i) {
var item = product;
if (opts) item = prefix(event, item);
item._t = timestamp + i;
item._d = 1;
window.KM.set(item);
});
});
};
/**
* Prefix properties with the event name.
*
* @param {String} event
* @param {Object} properties
* @return {Object} prefixed
* @api private
*/
function prefix(event, properties) {
var prefixed = {};
each(properties, function(key, val) {
if (key === 'Billing Amount') {
prefixed[key] = val;
} else if (key === 'revenue') {
prefixed[event + ' - ' + key] = val;
prefixed['Billing Amount'] = val;
} else {
prefixed[event + ' - ' + key] = val;
}
});
return prefixed;
}
function toUnixTimestamp(date) {
var d = new Date(date);
return Math.floor(d.getTime() / 1000);
}
/**
* Clean all nested objects and arrays.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function clean(obj) {
var ret = {};
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
var value = obj[k];
if (value === null || typeof value === 'undefined') continue;
// convert date to unix
if (is.date(value)) {
ret[k] = toUnixTimestamp(value);
continue;
}
// leave boolean as is
if (is.bool(value)) {
ret[k] = value;
continue;
}
// leave numbers as is
if (is.number(value)) {
ret[k] = value;
continue;
}
// convert non objects to strings
if (value.toString() !== '[object Object]') {
ret[k] = value.toString();
continue;
}
// json
// must flatten including the name of the original trait/property
var nestedObj = {};
nestedObj[k] = value;
var flattenedObj = flatten(nestedObj, { safe: true });
// stringify arrays inside nested object to be consistent with top level behavior of arrays
for (var key in flattenedObj) {
if (is.array(flattenedObj[key])) {
flattenedObj[key] = flattenedObj[key].toString();
}
}
ret = extend(ret, flattenedObj);
delete ret[k];
}
}
return ret;
}
/**
* Flatten nested objects
* taken from https://www.npmjs.com/package/flat
* @param {Object} obj
* @return {Object} obj
* @api public
*/
function flatten(target, options) {
var opts = options || {};
var delimiter = opts.delimiter || '.';
var maxDepth = opts.maxDepth;
var currentDepth = 1;
var output = {};
// for (var key in p) {
// if (p.hasOwnProperty(key)) {
// alert(key + " -> " + p[key]);
// }
// }
function step(object, prev) {
for (var key in object) {
if (object.hasOwnProperty(key)) {
var value = object[key];
var isarray = opts.safe && is.array(value);
var type = Object.prototype.toString.call(value);
var isobject = type === '[object Object]' || type === '[object Array]';
var arr = [];
var newKey = prev ? prev + delimiter + key : key;
if (!opts.maxDepth) {
maxDepth = currentDepth + 1;
}
for (var keys in value) {
if (value.hasOwnProperty(keys)) {
arr.push(keys);
}
}
if (!isarray && isobject && arr.length && currentDepth < maxDepth) {
++currentDepth;
return step(value, newKey);
}
output[newKey] = value;
}
}
}
step(target);
return output;
}