@usermaven/sdk-js 1.0.0

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/README.md ADDED
@@ -0,0 +1,26 @@
1
+ # Usermaven JavaScript SDK (usermaven.js)
2
+
3
+ Usermaven.js is a JavaScript SDK for [Usermaven](https://usermaven.com).
4
+
5
+ ## Maintainers Guide
6
+
7
+ This section is indented only for package maintainers.
8
+
9
+ ### Building and local debug
10
+
11
+ * _**ATTENTION**_: Use `yarn` for everything except publishing
12
+ * To spin off a local development server run `yarn devserver`, then open [http://localhost:8081](http://localhost:8081)
13
+ * The server listens to all changes to src and rebuilds npm and `lib.js` automatically. Open test cases HTML files to see
14
+ jitsu in action
15
+ * http://localhost:8081/test-case/embed.html - embedded Usermaven
16
+ * http://localhost:8081/test-case/embed-no-init.html - Usermaven without automatic initialization
17
+ * http://localhost:8081/test-case/segment-intercept.html - test segment interception
18
+ * `yarn test` runs [Playwright](https://playwright.dev/) test
19
+ * `yarn build` builds both npm package and `lib.js` browser bundle
20
+ * `npm publish --public` to publish the package (change version in `package.json` manually). You need to run `npm login` with your personal
21
+ npmjs account beforehand (make sure you have access to Usermaven team)
22
+
23
+ ### Publishing new version
24
+
25
+ * Login with your *personal* credentials with `npm login`
26
+ * Run `yarn install && yarn build && yarn test && npm publish --access public`
@@ -0,0 +1,588 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ /*! *****************************************************************************
6
+ Copyright (c) Microsoft Corporation.
7
+
8
+ Permission to use, copy, modify, and/or distribute this software for any
9
+ purpose with or without fee is hereby granted.
10
+
11
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
12
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
14
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
16
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17
+ PERFORMANCE OF THIS SOFTWARE.
18
+ ***************************************************************************** */
19
+
20
+ var __assign = function() {
21
+ __assign = Object.assign || function __assign(t) {
22
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
23
+ s = arguments[i];
24
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
25
+ }
26
+ return t;
27
+ };
28
+ return __assign.apply(this, arguments);
29
+ };
30
+
31
+ function __spreadArray(to, from, pack) {
32
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
33
+ if (ar || !(i in from)) {
34
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
35
+ ar[i] = from[i];
36
+ }
37
+ }
38
+ return to.concat(ar || Array.prototype.slice.call(from));
39
+ }
40
+
41
+ var getCookieDomain = function () {
42
+ return location.hostname.replace('www.', '');
43
+ };
44
+ var cookieParsingCache;
45
+ var getCookies = function (useCache) {
46
+ if (useCache === void 0) { useCache = false; }
47
+ if (useCache && cookieParsingCache) {
48
+ return cookieParsingCache;
49
+ }
50
+ var res = {};
51
+ var cookies = document.cookie.split(';');
52
+ for (var i = 0; i < cookies.length; i++) {
53
+ var cookie = cookies[i];
54
+ var idx = cookie.indexOf('=');
55
+ if (idx > 0) {
56
+ res[cookie.substr(i > 0 ? 1 : 0, i > 0 ? idx - 1 : idx)] = cookie.substr(idx + 1);
57
+ }
58
+ }
59
+ cookieParsingCache = res;
60
+ return res;
61
+ };
62
+ var getCookie = function (name) {
63
+ if (!name) {
64
+ return null;
65
+ }
66
+ return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(name).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
67
+ };
68
+ var setCookie = function (name, value, expire, domain, secure) {
69
+ var expireString = expire === Infinity ? " expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + expire;
70
+ document.cookie = encodeURIComponent(name) + "=" + value + "; path=/;" + expireString + (domain ? "; domain=" + domain : "") + (secure ? "; secure" : "");
71
+ };
72
+ var deleteCookie = function (name) {
73
+ document.cookie = name + '= ; expires = Thu, 01 Jan 1970 00:00:00 GMT';
74
+ };
75
+ var generateId = function () { return Math.random().toString(36).substring(2, 12); };
76
+ var generateRandom = function () { return Math.random().toString(36).substring(2, 7); };
77
+ var parseQuery = function (qs) {
78
+ var queryString = qs || window.location.search.substring(1);
79
+ var query = {};
80
+ var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
81
+ for (var i = 0; i < pairs.length; i++) {
82
+ var pair = pairs[i].split('=');
83
+ query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
84
+ }
85
+ return query;
86
+ };
87
+ var UTM_TYPES = {
88
+ utm_source: "source",
89
+ utm_medium: "medium",
90
+ utm_campaign: "campaign",
91
+ utm_term: "term",
92
+ utm_content: "content"
93
+ };
94
+ var CLICK_IDS = {
95
+ gclid: true,
96
+ fbclid: true,
97
+ dclid: true
98
+ };
99
+ var getDataFromParams = function (params) {
100
+ var result = {
101
+ utm: {},
102
+ click_id: {}
103
+ };
104
+ for (var name in params) {
105
+ if (!params.hasOwnProperty(name)) {
106
+ continue;
107
+ }
108
+ var val = params[name];
109
+ var utm = UTM_TYPES[name];
110
+ if (utm) {
111
+ result.utm[utm] = val;
112
+ }
113
+ else if (CLICK_IDS[name]) {
114
+ result.click_id[name] = val;
115
+ }
116
+ }
117
+ return result;
118
+ };
119
+ //2020-08-24T13:42:16.439Z -> 2020-08-24T13:42:16.439123Z
120
+ var reformatDate = function (strDate) {
121
+ var end = strDate.split('.')[1];
122
+ if (!end) {
123
+ return strDate;
124
+ }
125
+ if (end.length >= 7) {
126
+ return strDate;
127
+ }
128
+ return strDate.slice(0, -1) + '0'.repeat(7 - end.length) + 'Z';
129
+ };
130
+ function endsWith(str, suffix) {
131
+ return str.indexOf(suffix, str.length - suffix.length) !== -1;
132
+ }
133
+ var getHostWithProtocol = function (host) {
134
+ while (endsWith(host, "/")) {
135
+ host = host.substr(0, host.length - 1);
136
+ }
137
+ if (host.indexOf("https://") === 0 || host.indexOf("http://") === 0) {
138
+ return host;
139
+ }
140
+ else {
141
+ return "//" + host;
142
+ }
143
+ };
144
+
145
+ var LogLevels = {
146
+ DEBUG: { name: "DEBUG", severity: 10 },
147
+ INFO: { name: "INFO", severity: 100 },
148
+ WARN: { name: "WARN", severity: 1000 },
149
+ ERROR: { name: "ERROR", severity: 10000 },
150
+ NONE: { name: "NONE", severity: 10000 }
151
+ };
152
+ var rootLogger = null;
153
+ /**
154
+ * Create logger or return cached instance
155
+ */
156
+ function getLogger() {
157
+ if (rootLogger) {
158
+ return rootLogger;
159
+ }
160
+ else {
161
+ return rootLogger = createLogger();
162
+ }
163
+ }
164
+ function setRootLogLevel(logLevelName) {
165
+ var logLevel = LogLevels[logLevelName.toLocaleUpperCase()];
166
+ if (!logLevel) {
167
+ console.warn("Can't find log level with name ".concat(logLevelName.toLocaleUpperCase(), ", defaulting to INFO"));
168
+ logLevel = LogLevels.INFO;
169
+ }
170
+ rootLogger = createLogger(logLevel);
171
+ return rootLogger;
172
+ }
173
+ function setDebugVar(name, val) {
174
+ var win = window;
175
+ if (!win.__usermavenDebug) {
176
+ win.__usermavenDebug = {};
177
+ }
178
+ win.__usermavenDebug[name] = val;
179
+ }
180
+ /**
181
+ * Creates a loggger with given log-level
182
+ * @param logLevel
183
+ */
184
+ function createLogger(logLevel) {
185
+ var globalLogLevel = window['__eventNLogLevel'];
186
+ var minLogLevel = LogLevels.WARN;
187
+ if (globalLogLevel) {
188
+ var level = LogLevels[globalLogLevel.toUpperCase()];
189
+ if (level && level > 0) {
190
+ minLogLevel = level;
191
+ }
192
+ }
193
+ else if (logLevel) {
194
+ minLogLevel = logLevel;
195
+ }
196
+ var logger = { minLogLevel: minLogLevel };
197
+ Object.values(LogLevels).forEach(function (_a) {
198
+ var name = _a.name, severity = _a.severity;
199
+ logger[name.toLowerCase()] = function () {
200
+ var args = [];
201
+ for (var _i = 0; _i < arguments.length; _i++) {
202
+ args[_i] = arguments[_i];
203
+ }
204
+ if (severity >= minLogLevel.severity && args.length > 0) {
205
+ var message = args[0];
206
+ var msgArgs = args.splice(1);
207
+ var msgFormatted = "[J-".concat(name, "] ").concat(message);
208
+ if (name === 'DEBUG' || name === 'INFO') {
209
+ console.log.apply(console, __spreadArray([msgFormatted], msgArgs, false));
210
+ }
211
+ else if (name === 'WARN') {
212
+ console.warn.apply(console, __spreadArray([msgFormatted], msgArgs, false));
213
+ }
214
+ else {
215
+ console.error.apply(console, __spreadArray([msgFormatted], msgArgs, false));
216
+ }
217
+ }
218
+ };
219
+ });
220
+ setDebugVar("logger", logger);
221
+ return logger;
222
+ }
223
+
224
+ var VERSION_INFO = {
225
+ env: 'production',
226
+ date: '2022-01-09T16:15:00.168Z',
227
+ version: '1.0.0'
228
+ };
229
+ var USERMAVEN_VERSION = "".concat(VERSION_INFO.version, "/").concat(VERSION_INFO.env, "@").concat(VERSION_INFO.date);
230
+ var beaconTransport = function (url, json) {
231
+ getLogger().debug('Sending beacon', json);
232
+ var blob = new Blob([json], { type: 'text/plain' });
233
+ navigator.sendBeacon(url, blob);
234
+ return Promise.resolve();
235
+ };
236
+ var CookiePersistence = /** @class */ (function () {
237
+ function CookiePersistence(cookieDomain, cookieName) {
238
+ this.cookieDomain = cookieDomain;
239
+ this.cookieName = cookieName;
240
+ }
241
+ CookiePersistence.prototype.save = function (props) {
242
+ setCookie(this.cookieName, encodeURIComponent(JSON.stringify(props)), Infinity, this.cookieDomain, document.location.protocol !== 'http:');
243
+ };
244
+ CookiePersistence.prototype.restore = function () {
245
+ var str = getCookie(this.cookieName);
246
+ if (str) {
247
+ try {
248
+ var parsed = JSON.parse(decodeURIComponent(str));
249
+ if (typeof parsed !== 'object') {
250
+ getLogger().warn("Can't restore value of ".concat(this.cookieName, "@").concat(this.cookieDomain, ", expected to be object, but found ").concat(typeof parsed !== 'object', ": ").concat(parsed, ". Ignoring"));
251
+ return undefined;
252
+ }
253
+ return parsed;
254
+ }
255
+ catch (e) {
256
+ getLogger().error('Failed to decode JSON from ' + str, e);
257
+ return undefined;
258
+ }
259
+ }
260
+ return undefined;
261
+ };
262
+ CookiePersistence.prototype.delete = function () {
263
+ deleteCookie(this.cookieName);
264
+ };
265
+ return CookiePersistence;
266
+ }());
267
+ var NoPersistence = /** @class */ (function () {
268
+ function NoPersistence() {
269
+ }
270
+ NoPersistence.prototype.save = function (props) {
271
+ };
272
+ NoPersistence.prototype.restore = function () {
273
+ return undefined;
274
+ };
275
+ NoPersistence.prototype.delete = function () { };
276
+ return NoPersistence;
277
+ }());
278
+ var defaultCompatMode = false;
279
+ function usermavenClient(opts) {
280
+ var client = new UsermavenClientImpl();
281
+ client.init(opts);
282
+ return client;
283
+ }
284
+ var UsermavenClientImpl = /** @class */ (function () {
285
+ function UsermavenClientImpl() {
286
+ this.anonymousId = '';
287
+ this.userProperties = {};
288
+ this.permanentProperties = { globalProps: {}, propsPerEvent: {} };
289
+ this.cookieDomain = '';
290
+ this.trackingHost = '';
291
+ this.idCookieName = '';
292
+ this.randomizeUrl = false;
293
+ this.apiKey = '';
294
+ this.initialized = false;
295
+ this._3pCookies = {};
296
+ this.cookiePolicy = 'keep';
297
+ this.ipPolicy = 'keep';
298
+ this.beaconApi = false;
299
+ }
300
+ UsermavenClientImpl.prototype.id = function (props, doNotSendEvent) {
301
+ this.userProperties = __assign(__assign({}, this.userProperties), props);
302
+ getLogger().debug('Usermaven user identified', props);
303
+ if (this.userIdPersistence) {
304
+ this.userIdPersistence.save(props);
305
+ }
306
+ else {
307
+ getLogger().warn('Id() is called before initialization');
308
+ }
309
+ if (!doNotSendEvent) {
310
+ return this.track('user_identify', {});
311
+ }
312
+ else {
313
+ return Promise.resolve();
314
+ }
315
+ };
316
+ UsermavenClientImpl.prototype.rawTrack = function (payload) {
317
+ this.sendJson(payload);
318
+ };
319
+ UsermavenClientImpl.prototype.getAnonymousId = function () {
320
+ var idCookie = getCookie(this.idCookieName);
321
+ if (idCookie) {
322
+ getLogger().debug('Existing user id', idCookie);
323
+ return idCookie;
324
+ }
325
+ var newId = generateId();
326
+ getLogger().debug('New user id', newId);
327
+ setCookie(this.idCookieName, newId, Infinity, this.cookieDomain, document.location.protocol !== 'http:');
328
+ return newId;
329
+ };
330
+ UsermavenClientImpl.prototype.makeEvent = function (event_type, src, payload) {
331
+ var _a;
332
+ this.restoreId();
333
+ var context = this.getCtx();
334
+ var persistentProps = __assign(__assign({}, this.permanentProperties.globalProps), ((_a = this.permanentProperties.propsPerEvent[event_type]) !== null && _a !== void 0 ? _a : {}));
335
+ var base = __assign({ api_key: this.apiKey, src: src, event_type: event_type }, payload);
336
+ return this.compatMode ? __assign(__assign(__assign({}, persistentProps), { eventn_ctx: context }), base) : __assign(__assign(__assign({}, persistentProps), context), base);
337
+ };
338
+ UsermavenClientImpl.prototype._send3p = function (sourceType, object, type) {
339
+ var eventType = '3rdparty';
340
+ if (type && type !== '') {
341
+ eventType = type;
342
+ }
343
+ var e = this.makeEvent(eventType, sourceType, {
344
+ src_payload: object
345
+ });
346
+ return this.sendJson(e);
347
+ };
348
+ UsermavenClientImpl.prototype.sendJson = function (json) {
349
+ var cookiePolicy = this.cookiePolicy !== 'keep' ? "&cookie_policy=".concat(this.cookiePolicy) : '';
350
+ var ipPolicy = this.ipPolicy !== 'keep' ? "&ip_policy=".concat(this.ipPolicy) : '';
351
+ var url = "".concat(this.trackingHost, "/api/v1/event?token=").concat(this.apiKey).concat(cookiePolicy).concat(ipPolicy);
352
+ if (this.randomizeUrl) {
353
+ url = "".concat(this.trackingHost, "/api.").concat(generateRandom(), "?p_").concat(generateRandom(), "=").concat(this.apiKey).concat(cookiePolicy).concat(ipPolicy);
354
+ }
355
+ var jsonString = JSON.stringify(json);
356
+ if (this.beaconApi) {
357
+ return beaconTransport(url, jsonString);
358
+ }
359
+ else {
360
+ return this.xmlHttpReqTransport(url, jsonString);
361
+ }
362
+ };
363
+ UsermavenClientImpl.prototype.xmlHttpReqTransport = function (url, json) {
364
+ var _this = this;
365
+ var req = new XMLHttpRequest();
366
+ return new Promise(function (resolve, reject) {
367
+ req.onerror = function (e) {
368
+ getLogger().error('Failed to send', json, e);
369
+ _this.postHandle(-1, {});
370
+ reject(new Error("Failed to send JSON. See console logs"));
371
+ };
372
+ req.onload = function () {
373
+ _this.postHandle(req.status, req.response);
374
+ if (req.status !== 200) {
375
+ getLogger().warn("Failed to send data to ".concat(url, " (#").concat(req.status, " - ").concat(req.statusText, ")"), json);
376
+ reject(new Error("Failed to send JSON. Error code: ".concat(req.status, ". See logs for details")));
377
+ }
378
+ resolve();
379
+ };
380
+ req.open('POST', url);
381
+ req.setRequestHeader('Content-Type', 'application/json');
382
+ req.send(json);
383
+ getLogger().debug('sending json', json);
384
+ });
385
+ };
386
+ UsermavenClientImpl.prototype.postHandle = function (status, response) {
387
+ if (this.cookiePolicy === 'strict' || this.cookiePolicy === 'comply') {
388
+ if (status === 200) {
389
+ var data = response;
390
+ if (typeof response === 'string') {
391
+ data = JSON.parse(response);
392
+ }
393
+ if (!data['delete_cookie']) {
394
+ return;
395
+ }
396
+ }
397
+ this.userIdPersistence.delete();
398
+ this.propsPersistance.delete();
399
+ deleteCookie(this.idCookieName);
400
+ }
401
+ };
402
+ UsermavenClientImpl.prototype.getCtx = function () {
403
+ var now = new Date();
404
+ return __assign({ event_id: '', user: __assign({ anonymous_id: this.anonymousId }, this.userProperties), ids: this._getIds(), user_agent: navigator.userAgent, utc_time: reformatDate(now.toISOString()), local_tz_offset: now.getTimezoneOffset(), referer: document.referrer, url: window.location.href, page_title: document.title, doc_path: document.location.pathname, doc_host: document.location.hostname, doc_search: window.location.search, screen_resolution: screen.width + 'x' + screen.height, vp_size: Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0) + 'x' + Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0), user_language: navigator.language, doc_encoding: document.characterSet }, getDataFromParams(parseQuery()));
405
+ };
406
+ UsermavenClientImpl.prototype._getIds = function () {
407
+ var cookies = getCookies(false);
408
+ var res = {};
409
+ for (var _i = 0, _a = Object.entries(cookies); _i < _a.length; _i++) {
410
+ var _b = _a[_i], key = _b[0], value = _b[1];
411
+ if (this._3pCookies[key]) {
412
+ res[key.charAt(0) == '_' ?
413
+ key.substr(1) :
414
+ key] = value;
415
+ }
416
+ }
417
+ return res;
418
+ };
419
+ UsermavenClientImpl.prototype.track = function (type, payload) {
420
+ var data = payload || {};
421
+ getLogger().debug('track event of type', type, data);
422
+ var e = this.makeEvent(type, this.compatMode ?
423
+ 'eventn' :
424
+ 'jitsu', payload || {});
425
+ return this.sendJson(e);
426
+ };
427
+ UsermavenClientImpl.prototype.init = function (options) {
428
+ var _this = this;
429
+ var _a, _b;
430
+ if (options.ip_policy) {
431
+ this.ipPolicy = options.ip_policy;
432
+ }
433
+ if (options.cookie_policy) {
434
+ this.cookiePolicy = options.cookie_policy;
435
+ }
436
+ if (options.privacy_policy === 'strict') {
437
+ this.ipPolicy = 'strict';
438
+ this.cookiePolicy = 'strict';
439
+ }
440
+ if (options.use_beacon_api && navigator.sendBeacon) {
441
+ this.beaconApi = true;
442
+ }
443
+ //can't handle delete cookie response when beacon api
444
+ if (this.cookiePolicy === 'comply' && this.beaconApi) {
445
+ this.cookiePolicy = 'strict';
446
+ }
447
+ if (options.log_level) {
448
+ setRootLogLevel(options.log_level);
449
+ }
450
+ this.initialOptions = options;
451
+ getLogger().debug('Initializing Usermaven Tracker tracker', options, USERMAVEN_VERSION);
452
+ if (!options.key) {
453
+ getLogger().error('Can\'t initialize Usermaven, key property is not set');
454
+ return;
455
+ }
456
+ this.compatMode = options.compat_mode === undefined ?
457
+ defaultCompatMode :
458
+ !!options.compat_mode;
459
+ this.cookieDomain = options.cookie_domain || getCookieDomain();
460
+ this.trackingHost = getHostWithProtocol(options['tracking_host'] || 't.usermaven.com');
461
+ this.randomizeUrl = options.randomize_url || false;
462
+ this.idCookieName = options.cookie_name || '__eventn_id';
463
+ this.apiKey = options.key;
464
+ if (this.cookiePolicy === 'strict') {
465
+ this.propsPersistance = new NoPersistence();
466
+ }
467
+ else {
468
+ this.propsPersistance = new CookiePersistence(this.cookieDomain, this.idCookieName + '_props');
469
+ }
470
+ if (this.cookiePolicy === 'strict') {
471
+ this.userIdPersistence = new NoPersistence();
472
+ }
473
+ else {
474
+ this.userIdPersistence = new CookiePersistence(this.cookieDomain, this.idCookieName + '_usr');
475
+ }
476
+ if (this.propsPersistance) {
477
+ var restored = this.propsPersistance.restore();
478
+ if (restored) {
479
+ this.permanentProperties = restored;
480
+ this.permanentProperties.globalProps = (_a = restored.globalProps) !== null && _a !== void 0 ? _a : {};
481
+ this.permanentProperties.propsPerEvent = (_b = restored.propsPerEvent) !== null && _b !== void 0 ? _b : {};
482
+ }
483
+ getLogger().debug('Restored persistent properties', this.permanentProperties);
484
+ }
485
+ if (options.capture_3rd_party_cookies === false) {
486
+ this._3pCookies = {};
487
+ }
488
+ else {
489
+ (options.capture_3rd_party_cookies || ['_ga', '_fbp', '_ym_uid', 'ajs_user_id', 'ajs_anonymous_id'])
490
+ .forEach(function (name) { return _this._3pCookies[name] = true; });
491
+ }
492
+ if (options.ga_hook) {
493
+ getLogger().warn('GA event interceptor isn\'t supported anymore');
494
+ }
495
+ if (options.segment_hook) {
496
+ interceptSegmentCalls(this);
497
+ }
498
+ if (this.cookiePolicy !== 'strict') {
499
+ this.anonymousId = this.getAnonymousId();
500
+ }
501
+ this.initialized = true;
502
+ };
503
+ UsermavenClientImpl.prototype.interceptAnalytics = function (analytics) {
504
+ var _this = this;
505
+ var interceptor = function (chain) {
506
+ var _a;
507
+ try {
508
+ var payload = __assign({}, chain.payload);
509
+ getLogger().debug('Intercepted segment payload', payload.obj);
510
+ var integration = chain.integrations['Segment.io'];
511
+ if (integration && integration.analytics) {
512
+ var analyticsOriginal = integration.analytics;
513
+ if (typeof analyticsOriginal.user === 'function' && analyticsOriginal.user() && typeof analyticsOriginal.user().id === 'function') {
514
+ payload.obj.userId = analyticsOriginal.user().id();
515
+ }
516
+ }
517
+ if ((_a = payload === null || payload === void 0 ? void 0 : payload.obj) === null || _a === void 0 ? void 0 : _a.timestamp) {
518
+ payload.obj.sentAt = payload.obj.timestamp;
519
+ }
520
+ var type = chain.payload.type();
521
+ if (type === 'track') {
522
+ type = chain.payload.event();
523
+ }
524
+ _this._send3p('ajs', payload, type);
525
+ }
526
+ catch (e) {
527
+ getLogger().warn('Failed to send an event', e);
528
+ }
529
+ chain.next(chain.payload);
530
+ };
531
+ if (typeof analytics.addSourceMiddleware === 'function') {
532
+ //analytics is fully initialized
533
+ getLogger().debug('Analytics.js is initialized, calling addSourceMiddleware');
534
+ analytics.addSourceMiddleware(interceptor);
535
+ }
536
+ else {
537
+ getLogger().debug('Analytics.js is not initialized, pushing addSourceMiddleware to callstack');
538
+ analytics.push(['addSourceMiddleware', interceptor]);
539
+ }
540
+ analytics['__en_intercepted'] = true;
541
+ };
542
+ UsermavenClientImpl.prototype.restoreId = function () {
543
+ if (this.userIdPersistence) {
544
+ var props = this.userIdPersistence.restore();
545
+ if (props) {
546
+ this.userProperties = __assign(__assign({}, props), this.userProperties);
547
+ }
548
+ }
549
+ };
550
+ UsermavenClientImpl.prototype.set = function (properties, opts) {
551
+ var _a;
552
+ var eventType = opts === null || opts === void 0 ? void 0 : opts.eventType;
553
+ var persist = (opts === null || opts === void 0 ? void 0 : opts.persist) === undefined || (opts === null || opts === void 0 ? void 0 : opts.persist);
554
+ if (eventType !== undefined) {
555
+ var current = (_a = this.permanentProperties.propsPerEvent[eventType]) !== null && _a !== void 0 ? _a : {};
556
+ this.permanentProperties.propsPerEvent[eventType] = __assign(__assign({}, current), properties);
557
+ }
558
+ else {
559
+ this.permanentProperties.globalProps = __assign(__assign({}, this.permanentProperties.globalProps), properties);
560
+ }
561
+ if (this.propsPersistance && persist) {
562
+ this.propsPersistance.save(this.permanentProperties);
563
+ }
564
+ };
565
+ UsermavenClientImpl.prototype.unset = function (propertyName, opts) {
566
+ var eventType = opts === null || opts === void 0 ? void 0 : opts.eventType;
567
+ var persist = (opts === null || opts === void 0 ? void 0 : opts.persist) === undefined || (opts === null || opts === void 0 ? void 0 : opts.persist);
568
+ if (!eventType) {
569
+ delete this.permanentProperties.globalProps[propertyName];
570
+ }
571
+ else if (this.permanentProperties.propsPerEvent[eventType]) {
572
+ delete this.permanentProperties.propsPerEvent[eventType][propertyName];
573
+ }
574
+ if (this.propsPersistance && persist) {
575
+ this.propsPersistance.save(this.permanentProperties);
576
+ }
577
+ };
578
+ return UsermavenClientImpl;
579
+ }());
580
+ function interceptSegmentCalls(t) {
581
+ var win = window;
582
+ if (!win.analytics) {
583
+ win.analytics = [];
584
+ }
585
+ t.interceptAnalytics(win.analytics);
586
+ }
587
+
588
+ exports.usermavenClient = usermavenClient;