@leanbase.com/js 0.1.3 → 0.2.0-alpha.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.
Files changed (137) hide show
  1. package/LICENSE +37 -0
  2. package/dist/autocapture-utils.d.ts +17 -0
  3. package/dist/autocapture.d.ts +35 -0
  4. package/dist/config.d.ts +5 -0
  5. package/dist/constants.d.ts +54 -0
  6. package/dist/entrypoints/main.cjs.d.ts +4 -0
  7. package/dist/entrypoints/module.es.d.ts +4 -0
  8. package/dist/extensions/rageclick.d.ts +9 -0
  9. package/dist/iife.d.ts +19 -0
  10. package/dist/index.d.ts +2 -779
  11. package/dist/leanbase-logger.d.ts +6 -0
  12. package/dist/leanbase-persistence.d.ts +64 -0
  13. package/dist/leanbase.d.ts +49 -0
  14. package/dist/leanbase.iife.js +1 -4747
  15. package/dist/leanbase.iife.js.map +1 -1
  16. package/dist/main.js +2 -0
  17. package/dist/main.js.map +1 -0
  18. package/dist/module.d.ts +780 -0
  19. package/dist/module.js +2 -0
  20. package/dist/module.js.map +1 -0
  21. package/dist/page-view.d.ts +29 -0
  22. package/dist/scroll-manager.d.ts +21 -0
  23. package/dist/session-props.d.ts +32 -0
  24. package/dist/sessionid.d.ts +50 -0
  25. package/dist/storage.d.ts +24 -0
  26. package/{src/types.ts → dist/types.d.ts} +145 -235
  27. package/dist/utils/blocked-uas.d.ts +17 -0
  28. package/dist/utils/element-utils.d.ts +5 -0
  29. package/dist/utils/event-utils.d.ts +22 -0
  30. package/dist/utils/index.d.ts +44 -0
  31. package/dist/utils/request-utils.d.ts +12 -0
  32. package/dist/utils/simple-event-emitter.d.ts +6 -0
  33. package/dist/utils/user-agent-utils.d.ts +18 -0
  34. package/dist/uuidv7.d.ts +43 -0
  35. package/dist/version.d.ts +1 -0
  36. package/lib/autocapture-utils.d.ts +17 -0
  37. package/{src/autocapture-utils.ts → lib/autocapture-utils.js} +196 -280
  38. package/lib/autocapture-utils.js.map +1 -0
  39. package/lib/autocapture.d.ts +35 -0
  40. package/lib/autocapture.js +311 -0
  41. package/lib/autocapture.js.map +1 -0
  42. package/lib/config.d.ts +5 -0
  43. package/lib/config.js +7 -0
  44. package/lib/config.js.map +1 -0
  45. package/lib/constants.d.ts +54 -0
  46. package/{src/constants.ts → lib/constants.js} +50 -57
  47. package/lib/constants.js.map +1 -0
  48. package/lib/entrypoints/main.cjs.d.ts +4 -0
  49. package/lib/entrypoints/main.cjs.js +3 -0
  50. package/lib/entrypoints/main.cjs.js.map +1 -0
  51. package/lib/entrypoints/module.es.d.ts +4 -0
  52. package/lib/entrypoints/module.es.js +3 -0
  53. package/lib/entrypoints/module.es.js.map +1 -0
  54. package/lib/extensions/rageclick.d.ts +9 -0
  55. package/lib/extensions/rageclick.js +27 -0
  56. package/lib/extensions/rageclick.js.map +1 -0
  57. package/lib/iife.d.ts +19 -0
  58. package/lib/iife.js +67 -0
  59. package/lib/iife.js.map +1 -0
  60. package/{src/index.ts → lib/index.d.ts} +2 -2
  61. package/lib/index.js +2 -0
  62. package/lib/index.js.map +1 -0
  63. package/lib/leanbase-logger.d.ts +6 -0
  64. package/lib/leanbase-logger.js +25 -0
  65. package/lib/leanbase-logger.js.map +1 -0
  66. package/lib/leanbase-persistence.d.ts +64 -0
  67. package/lib/leanbase-persistence.js +287 -0
  68. package/lib/leanbase-persistence.js.map +1 -0
  69. package/lib/leanbase.d.ts +49 -0
  70. package/lib/leanbase.js +294 -0
  71. package/lib/leanbase.js.map +1 -0
  72. package/lib/page-view.d.ts +29 -0
  73. package/lib/page-view.js +81 -0
  74. package/lib/page-view.js.map +1 -0
  75. package/lib/scroll-manager.d.ts +21 -0
  76. package/lib/scroll-manager.js +79 -0
  77. package/lib/scroll-manager.js.map +1 -0
  78. package/lib/session-props.d.ts +32 -0
  79. package/lib/session-props.js +73 -0
  80. package/lib/session-props.js.map +1 -0
  81. package/lib/sessionid.d.ts +50 -0
  82. package/{src/sessionid.ts → lib/sessionid.js} +128 -204
  83. package/lib/sessionid.js.map +1 -0
  84. package/lib/storage.d.ts +24 -0
  85. package/{src/storage.ts → lib/storage.js} +182 -225
  86. package/lib/storage.js.map +1 -0
  87. package/lib/types.d.ts +544 -0
  88. package/lib/types.js +7 -0
  89. package/lib/types.js.map +1 -0
  90. package/lib/utils/blocked-uas.d.ts +17 -0
  91. package/{src/utils/blocked-uas.ts → lib/utils/blocked-uas.js} +19 -48
  92. package/lib/utils/blocked-uas.js.map +1 -0
  93. package/lib/utils/element-utils.d.ts +5 -0
  94. package/{src/utils/element-utils.ts → lib/utils/element-utils.js} +13 -17
  95. package/lib/utils/element-utils.js.map +1 -0
  96. package/lib/utils/event-utils.d.ts +22 -0
  97. package/lib/utils/event-utils.js +258 -0
  98. package/lib/utils/event-utils.js.map +1 -0
  99. package/lib/utils/index.d.ts +44 -0
  100. package/lib/utils/index.js +183 -0
  101. package/lib/utils/index.js.map +1 -0
  102. package/lib/utils/request-utils.d.ts +12 -0
  103. package/lib/utils/request-utils.js +107 -0
  104. package/lib/utils/request-utils.js.map +1 -0
  105. package/lib/utils/simple-event-emitter.d.ts +6 -0
  106. package/lib/utils/simple-event-emitter.js +24 -0
  107. package/lib/utils/simple-event-emitter.js.map +1 -0
  108. package/lib/utils/user-agent-utils.d.ts +18 -0
  109. package/lib/utils/user-agent-utils.js +369 -0
  110. package/lib/utils/user-agent-utils.js.map +1 -0
  111. package/lib/uuidv7.d.ts +43 -0
  112. package/{src/uuidv7.ts → lib/uuidv7.js} +103 -131
  113. package/lib/uuidv7.js.map +1 -0
  114. package/lib/version.d.ts +1 -0
  115. package/lib/version.js +2 -0
  116. package/lib/version.js.map +1 -0
  117. package/package.json +56 -45
  118. package/dist/index.cjs +0 -3034
  119. package/dist/index.cjs.map +0 -1
  120. package/dist/index.mjs +0 -3032
  121. package/dist/index.mjs.map +0 -1
  122. package/src/autocapture.ts +0 -415
  123. package/src/config.ts +0 -8
  124. package/src/extensions/rageclick.ts +0 -34
  125. package/src/iife.ts +0 -87
  126. package/src/leanbase-logger.ts +0 -26
  127. package/src/leanbase-persistence.ts +0 -374
  128. package/src/leanbase.ts +0 -424
  129. package/src/page-view.ts +0 -124
  130. package/src/scroll-manager.ts +0 -103
  131. package/src/session-props.ts +0 -114
  132. package/src/utils/event-utils.ts +0 -304
  133. package/src/utils/index.ts +0 -222
  134. package/src/utils/request-utils.ts +0 -128
  135. package/src/utils/simple-event-emitter.ts +0 -27
  136. package/src/utils/user-agent-utils.ts +0 -357
  137. package/src/version.ts +0 -1
package/dist/index.mjs DELETED
@@ -1,3032 +0,0 @@
1
- import { isArray, isString, isNullish, isFormData, hasOwnProperty, isNumber, isNull, PostHogPersistedProperty, isUndefined, isFunction, includes, stripLeadingDollar, isObject, isEmptyObject, isBoolean, trim, clampToRange, PostHogCore, getFetch, isEmptyString } from '@posthog/core';
2
-
3
- const breaker = {};
4
- const ArrayProto = Array.prototype;
5
- const nativeForEach = ArrayProto.forEach;
6
- const nativeIndexOf = ArrayProto.indexOf;
7
- const win = typeof window !== 'undefined' ? window : undefined;
8
- const global = typeof globalThis !== 'undefined' ? globalThis : win;
9
- const navigator$1 = global?.navigator;
10
- const document = global?.document;
11
- const location = global?.location;
12
- global?.fetch;
13
- global?.XMLHttpRequest && 'withCredentials' in new global.XMLHttpRequest() ? global.XMLHttpRequest : undefined;
14
- global?.AbortController;
15
- const userAgent = navigator$1?.userAgent;
16
- function eachArray(obj, iterator, thisArg) {
17
- if (isArray(obj)) {
18
- if (nativeForEach && obj.forEach === nativeForEach) {
19
- obj.forEach(iterator, thisArg);
20
- } else if ('length' in obj && obj.length === +obj.length) {
21
- for (let i = 0, l = obj.length; i < l; i++) {
22
- if (i in obj && iterator.call(thisArg, obj[i], i) === breaker) {
23
- return;
24
- }
25
- }
26
- }
27
- }
28
- }
29
- /**
30
- * @param {*=} obj
31
- * @param {function(...*)=} iterator
32
- * @param {Object=} thisArg
33
- */
34
- function each(obj, iterator, thisArg) {
35
- if (isNullish(obj)) {
36
- return;
37
- }
38
- if (isArray(obj)) {
39
- return eachArray(obj, iterator, thisArg);
40
- }
41
- if (isFormData(obj)) {
42
- for (const pair of obj.entries()) {
43
- if (iterator.call(thisArg, pair[1], pair[0]) === breaker) {
44
- return;
45
- }
46
- }
47
- return;
48
- }
49
- for (const key in obj) {
50
- if (hasOwnProperty.call(obj, key)) {
51
- if (iterator.call(thisArg, obj[key], key) === breaker) {
52
- return;
53
- }
54
- }
55
- }
56
- }
57
- const extend = function (obj, ...args) {
58
- eachArray(args, function (source) {
59
- for (const prop in source) {
60
- if (source[prop] !== void 0) {
61
- obj[prop] = source[prop];
62
- }
63
- }
64
- });
65
- return obj;
66
- };
67
- const extendArray = function (obj, ...args) {
68
- eachArray(args, function (source) {
69
- eachArray(source, function (item) {
70
- obj.push(item);
71
- });
72
- });
73
- return obj;
74
- };
75
- const include = function (obj, target) {
76
- let found = false;
77
- if (isNull(obj)) {
78
- return found;
79
- }
80
- if (nativeIndexOf && obj.indexOf === nativeIndexOf) {
81
- return obj.indexOf(target) != -1;
82
- }
83
- each(obj, function (value) {
84
- if (found || (found = value === target)) {
85
- return breaker;
86
- }
87
- return;
88
- });
89
- return found;
90
- };
91
- /**
92
- * Object.entries() polyfill
93
- * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
94
- */
95
- function entries(obj) {
96
- const ownProps = Object.keys(obj);
97
- let i = ownProps.length;
98
- const resArray = new Array(i); // preallocate the Array
99
- while (i--) {
100
- resArray[i] = [ownProps[i], obj[ownProps[i]]];
101
- }
102
- return resArray;
103
- }
104
- function addEventListener(element, event, callback, options) {
105
- const {
106
- capture = false,
107
- passive = true
108
- } = options ?? {};
109
- // This is the only place where we are allowed to call this function
110
- // because the whole idea is that we should be calling this instead of the built-in one
111
- // eslint-disable-next-line posthog-js/no-add-event-listener
112
- element?.addEventListener(event, callback, {
113
- capture,
114
- passive
115
- });
116
- }
117
- const stripEmptyProperties = function (p) {
118
- const ret = {};
119
- each(p, function (v, k) {
120
- if (isString(v) && v.length > 0 || isNumber(v)) {
121
- ret[k] = v;
122
- }
123
- });
124
- return ret;
125
- };
126
- const EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE = ['herokuapp.com', 'vercel.app', 'netlify.app'];
127
- function isCrossDomainCookie(documentLocation) {
128
- const hostname = documentLocation?.hostname;
129
- if (!isString(hostname)) {
130
- return false;
131
- }
132
- // split and slice isn't a great way to match arbitrary domains,
133
- // but it's good enough for ensuring we only match herokuapp.com when it is the TLD
134
- // for the hostname
135
- const lastTwoParts = hostname.split('.').slice(-2).join('.');
136
- for (const excluded of EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE) {
137
- if (lastTwoParts === excluded) {
138
- return false;
139
- }
140
- }
141
- return true;
142
- }
143
- /**
144
- * Deep copies an object.
145
- * It handles cycles by replacing all references to them with `undefined`
146
- * Also supports customizing native values
147
- *
148
- * @param value
149
- * @param customizer
150
- * @returns {{}|undefined|*}
151
- */
152
- function deepCircularCopy(value, customizer) {
153
- const COPY_IN_PROGRESS_SET = new Set();
154
- function internalDeepCircularCopy(value, key) {
155
- if (value !== Object(value)) return customizer ? customizer(value, key) : value; // primitive value
156
- if (COPY_IN_PROGRESS_SET.has(value)) return undefined;
157
- COPY_IN_PROGRESS_SET.add(value);
158
- let result;
159
- if (isArray(value)) {
160
- result = [];
161
- eachArray(value, it => {
162
- result.push(internalDeepCircularCopy(it));
163
- });
164
- } else {
165
- result = {};
166
- each(value, (val, key) => {
167
- if (!COPY_IN_PROGRESS_SET.has(val)) {
168
- result[key] = internalDeepCircularCopy(val, key);
169
- }
170
- });
171
- }
172
- return result;
173
- }
174
- return internalDeepCircularCopy(value);
175
- }
176
- function copyAndTruncateStrings(object, maxStringLength) {
177
- return deepCircularCopy(object, value => {
178
- if (isString(value) && !isNull(maxStringLength)) {
179
- return value.slice(0, maxStringLength);
180
- }
181
- return value;
182
- });
183
- }
184
-
185
- /*
186
- * Constants
187
- */
188
- /* PROPERTY KEYS */
189
- // This key is deprecated, but we want to check for it to see whether aliasing is allowed.
190
- const PEOPLE_DISTINCT_ID_KEY = '$people_distinct_id';
191
- const DISTINCT_ID = 'distinct_id';
192
- const ALIAS_ID_KEY = '__alias';
193
- const CAMPAIGN_IDS_KEY = '__cmpns';
194
- const EVENT_TIMERS_KEY = '__timers';
195
- const AUTOCAPTURE_DISABLED_SERVER_SIDE = '$autocapture_disabled_server_side';
196
- const HEATMAPS_ENABLED_SERVER_SIDE = '$heatmaps_enabled_server_side';
197
- const ERROR_TRACKING_SUPPRESSION_RULES = '$error_tracking_suppression_rules';
198
- // @deprecated can be removed along with eager loaded replay
199
- const SESSION_RECORDING_ENABLED_SERVER_SIDE = '$session_recording_enabled_server_side';
200
- const SESSION_ID = '$sesid';
201
- const SESSION_RECORDING_IS_SAMPLED = '$session_is_sampled';
202
- const ENABLED_FEATURE_FLAGS = '$enabled_feature_flags';
203
- const PERSISTENCE_EARLY_ACCESS_FEATURES = '$early_access_features';
204
- const PERSISTENCE_FEATURE_FLAG_DETAILS = '$feature_flag_details';
205
- const STORED_PERSON_PROPERTIES_KEY = '$stored_person_properties';
206
- const STORED_GROUP_PROPERTIES_KEY = '$stored_group_properties';
207
- const SURVEYS = '$surveys';
208
- const FLAG_CALL_REPORTED = '$flag_call_reported';
209
- const USER_STATE = '$user_state';
210
- const CLIENT_SESSION_PROPS = '$client_session_props';
211
- const CAPTURE_RATE_LIMIT = '$capture_rate_limit';
212
- /** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */
213
- const INITIAL_CAMPAIGN_PARAMS = '$initial_campaign_params';
214
- /** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */
215
- const INITIAL_REFERRER_INFO = '$initial_referrer_info';
216
- const INITIAL_PERSON_INFO = '$initial_person_info';
217
- const ENABLE_PERSON_PROCESSING = '$epp';
218
- const COOKIELESS_MODE_FLAG_PROPERTY = '$cookieless_mode';
219
- // These are properties that are reserved and will not be automatically included in events
220
- const PERSISTENCE_RESERVED_PROPERTIES = [PEOPLE_DISTINCT_ID_KEY, ALIAS_ID_KEY, CAMPAIGN_IDS_KEY, EVENT_TIMERS_KEY, SESSION_RECORDING_ENABLED_SERVER_SIDE, HEATMAPS_ENABLED_SERVER_SIDE, SESSION_ID, ENABLED_FEATURE_FLAGS, ERROR_TRACKING_SUPPRESSION_RULES, USER_STATE, PERSISTENCE_EARLY_ACCESS_FEATURES, PERSISTENCE_FEATURE_FLAG_DETAILS, STORED_GROUP_PROPERTIES_KEY, STORED_PERSON_PROPERTIES_KEY, SURVEYS, FLAG_CALL_REPORTED, CLIENT_SESSION_PROPS, CAPTURE_RATE_LIMIT, INITIAL_CAMPAIGN_PARAMS, INITIAL_REFERRER_INFO, ENABLE_PERSON_PROCESSING, INITIAL_PERSON_INFO,
221
- // Ignore posthog persisted properties
222
- PostHogPersistedProperty.Queue, PostHogPersistedProperty.FeatureFlagDetails, PostHogPersistedProperty.FlagsEndpointWasHit, PostHogPersistedProperty.AnonymousId, PostHogPersistedProperty.RemoteConfig, PostHogPersistedProperty.Surveys, PostHogPersistedProperty.FeatureFlags];
223
-
224
- /* eslint-disable no-console */
225
- const PREFIX = '[Leanbase]';
226
- const logger = {
227
- info: (...args) => {
228
- if (typeof console !== 'undefined') {
229
- console.log(PREFIX, ...args);
230
- }
231
- },
232
- warn: (...args) => {
233
- if (typeof console !== 'undefined') {
234
- console.warn(PREFIX, ...args);
235
- }
236
- },
237
- error: (...args) => {
238
- if (typeof console !== 'undefined') {
239
- console.error(PREFIX, ...args);
240
- }
241
- },
242
- critical: (...args) => {
243
- if (typeof console !== 'undefined') {
244
- console.error(PREFIX, 'CRITICAL:', ...args);
245
- }
246
- }
247
- };
248
-
249
- /**
250
- * uuidv7: An experimental implementation of the proposed UUID Version 7
251
- *
252
- * @license Apache-2.0
253
- * @copyright 2021-2023 LiosK
254
- * @packageDocumentation
255
- *
256
- * from https://github.com/LiosK/uuidv7/blob/e501462ea3d23241de13192ceae726956f9b3b7d/src/index.ts
257
- */
258
- // polyfill for IE11
259
- if (!Math.trunc) {
260
- Math.trunc = function (v) {
261
- return v < 0 ? Math.ceil(v) : Math.floor(v);
262
- };
263
- }
264
- // polyfill for IE11
265
- if (!Number.isInteger) {
266
- Number.isInteger = function (value) {
267
- return isNumber(value) && isFinite(value) && Math.floor(value) === value;
268
- };
269
- }
270
- const DIGITS = '0123456789abcdef';
271
- /** Represents a UUID as a 16-byte byte array. */
272
- class UUID {
273
- /** @param bytes - The 16-byte byte array representation. */
274
- constructor(bytes) {
275
- this.bytes = bytes;
276
- if (bytes.length !== 16) {
277
- throw new TypeError('not 128-bit length');
278
- }
279
- }
280
- /**
281
- * Builds a byte array from UUIDv7 field values.
282
- *
283
- * @param unixTsMs - A 48-bit `unix_ts_ms` field value.
284
- * @param randA - A 12-bit `rand_a` field value.
285
- * @param randBHi - The higher 30 bits of 62-bit `rand_b` field value.
286
- * @param randBLo - The lower 32 bits of 62-bit `rand_b` field value.
287
- */
288
- static fromFieldsV7(unixTsMs, randA, randBHi, randBLo) {
289
- if (!Number.isInteger(unixTsMs) || !Number.isInteger(randA) || !Number.isInteger(randBHi) || !Number.isInteger(randBLo) || unixTsMs < 0 || randA < 0 || randBHi < 0 || randBLo < 0 || unixTsMs > 281474976710655 || randA > 0xfff || randBHi > 1073741823 || randBLo > 4294967295) {
290
- throw new RangeError('invalid field value');
291
- }
292
- const bytes = new Uint8Array(16);
293
- bytes[0] = unixTsMs / 2 ** 40;
294
- bytes[1] = unixTsMs / 2 ** 32;
295
- bytes[2] = unixTsMs / 2 ** 24;
296
- bytes[3] = unixTsMs / 2 ** 16;
297
- bytes[4] = unixTsMs / 2 ** 8;
298
- bytes[5] = unixTsMs;
299
- bytes[6] = 0x70 | randA >>> 8;
300
- bytes[7] = randA;
301
- bytes[8] = 0x80 | randBHi >>> 24;
302
- bytes[9] = randBHi >>> 16;
303
- bytes[10] = randBHi >>> 8;
304
- bytes[11] = randBHi;
305
- bytes[12] = randBLo >>> 24;
306
- bytes[13] = randBLo >>> 16;
307
- bytes[14] = randBLo >>> 8;
308
- bytes[15] = randBLo;
309
- return new UUID(bytes);
310
- }
311
- /** @returns The 8-4-4-4-12 canonical hexadecimal string representation. */
312
- toString() {
313
- let text = '';
314
- for (let i = 0; i < this.bytes.length; i++) {
315
- text = text + DIGITS.charAt(this.bytes[i] >>> 4) + DIGITS.charAt(this.bytes[i] & 0xf);
316
- if (i === 3 || i === 5 || i === 7 || i === 9) {
317
- text += '-';
318
- }
319
- }
320
- if (text.length !== 36) {
321
- // We saw one customer whose bundling code was mangling the UUID generation
322
- // rather than accept a bad UUID, we throw an error here.
323
- throw new Error('Invalid UUIDv7 was generated');
324
- }
325
- return text;
326
- }
327
- /** Creates an object from `this`. */
328
- clone() {
329
- return new UUID(this.bytes.slice(0));
330
- }
331
- /** Returns true if `this` is equivalent to `other`. */
332
- equals(other) {
333
- return this.compareTo(other) === 0;
334
- }
335
- /**
336
- * Returns a negative integer, zero, or positive integer if `this` is less
337
- * than, equal to, or greater than `other`, respectively.
338
- */
339
- compareTo(other) {
340
- for (let i = 0; i < 16; i++) {
341
- const diff = this.bytes[i] - other.bytes[i];
342
- if (diff !== 0) {
343
- return Math.sign(diff);
344
- }
345
- }
346
- return 0;
347
- }
348
- }
349
- /** Encapsulates the monotonic counter state. */
350
- class V7Generator {
351
- constructor() {
352
- this._timestamp = 0;
353
- this._counter = 0;
354
- this._random = new DefaultRandom();
355
- }
356
- /**
357
- * Generates a new UUIDv7 object from the current timestamp, or resets the
358
- * generator upon significant timestamp rollback.
359
- *
360
- * This method returns monotonically increasing UUIDs unless the up-to-date
361
- * timestamp is significantly (by ten seconds or more) smaller than the one
362
- * embedded in the immediately preceding UUID. If such a significant clock
363
- * rollback is detected, this method resets the generator and returns a new
364
- * UUID based on the current timestamp.
365
- */
366
- generate() {
367
- const value = this.generateOrAbort();
368
- if (!isUndefined(value)) {
369
- return value;
370
- } else {
371
- // reset state and resume
372
- this._timestamp = 0;
373
- const valueAfterReset = this.generateOrAbort();
374
- if (isUndefined(valueAfterReset)) {
375
- throw new Error('Could not generate UUID after timestamp reset');
376
- }
377
- return valueAfterReset;
378
- }
379
- }
380
- /**
381
- * Generates a new UUIDv7 object from the current timestamp, or returns
382
- * `undefined` upon significant timestamp rollback.
383
- *
384
- * This method returns monotonically increasing UUIDs unless the up-to-date
385
- * timestamp is significantly (by ten seconds or more) smaller than the one
386
- * embedded in the immediately preceding UUID. If such a significant clock
387
- * rollback is detected, this method aborts and returns `undefined`.
388
- */
389
- generateOrAbort() {
390
- const MAX_COUNTER = 4398046511103;
391
- const ROLLBACK_ALLOWANCE = 10000; // 10 seconds
392
- const ts = Date.now();
393
- if (ts > this._timestamp) {
394
- this._timestamp = ts;
395
- this._resetCounter();
396
- } else if (ts + ROLLBACK_ALLOWANCE > this._timestamp) {
397
- // go on with previous timestamp if new one is not much smaller
398
- this._counter++;
399
- if (this._counter > MAX_COUNTER) {
400
- // increment timestamp at counter overflow
401
- this._timestamp++;
402
- this._resetCounter();
403
- }
404
- } else {
405
- // abort if clock went backwards to unbearable extent
406
- return undefined;
407
- }
408
- return UUID.fromFieldsV7(this._timestamp, Math.trunc(this._counter / 2 ** 30), this._counter & 2 ** 30 - 1, this._random.nextUint32());
409
- }
410
- /** Initializes the counter at a 42-bit random integer. */
411
- _resetCounter() {
412
- this._counter = this._random.nextUint32() * 0x400 + (this._random.nextUint32() & 0x3ff);
413
- }
414
- }
415
- /** Stores `crypto.getRandomValues()` available in the environment. */
416
- let getRandomValues = buffer => {
417
- // fall back on Math.random() unless the flag is set to true
418
- // TRICKY: don't use the isUndefined method here as can't pass the reference
419
- if (typeof UUIDV7_DENY_WEAK_RNG !== 'undefined' && UUIDV7_DENY_WEAK_RNG) {
420
- throw new Error('no cryptographically strong RNG available');
421
- }
422
- for (let i = 0; i < buffer.length; i++) {
423
- buffer[i] = Math.trunc(Math.random() * 65536) * 65536 + Math.trunc(Math.random() * 65536);
424
- }
425
- return buffer;
426
- };
427
- // detect Web Crypto API
428
- if (win && !isUndefined(win.crypto) && crypto.getRandomValues) {
429
- getRandomValues = buffer => crypto.getRandomValues(buffer);
430
- }
431
- /**
432
- * Wraps `crypto.getRandomValues()` and compatibles to enable buffering; this
433
- * uses a small buffer by default to avoid unbearable throughput decline in some
434
- * environments as well as the waste of time and space for unused values.
435
- */
436
- class DefaultRandom {
437
- constructor() {
438
- this._buffer = new Uint32Array(8);
439
- this._cursor = Infinity;
440
- }
441
- nextUint32() {
442
- if (this._cursor >= this._buffer.length) {
443
- getRandomValues(this._buffer);
444
- this._cursor = 0;
445
- }
446
- return this._buffer[this._cursor++];
447
- }
448
- }
449
- let defaultGenerator;
450
- /**
451
- * Generates a UUIDv7 string.
452
- *
453
- * @returns The 8-4-4-4-12 canonical hexadecimal string representation
454
- * ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").
455
- */
456
- const uuidv7 = () => uuidv7obj().toString();
457
- /** Generates a UUIDv7 object. */
458
- const uuidv7obj = () => (defaultGenerator || (defaultGenerator = new V7Generator())).generate();
459
-
460
- // we store the discovered subdomain in memory because it might be read multiple times
461
- let firstNonPublicSubDomain = '';
462
- /**
463
- * Browsers don't offer a way to check if something is a public suffix
464
- * e.g. `.com.au`, `.io`, `.org.uk`
465
- *
466
- * But they do reject cookies set on public suffixes
467
- * Setting a cookie on `.co.uk` would mean it was sent for every `.co.uk` site visited
468
- *
469
- * So, we can use this to check if a domain is a public suffix
470
- * by trying to set a cookie on a subdomain of the provided hostname
471
- * until the browser accepts it
472
- *
473
- * inspired by https://github.com/AngusFu/browser-root-domain
474
- */
475
- function seekFirstNonPublicSubDomain(hostname, cookieJar = document) {
476
- if (firstNonPublicSubDomain) {
477
- return firstNonPublicSubDomain;
478
- }
479
- if (!cookieJar) {
480
- return '';
481
- }
482
- if (['localhost', '127.0.0.1'].includes(hostname)) return '';
483
- const list = hostname.split('.');
484
- let len = Math.min(list.length, 8); // paranoia - we know this number should be small
485
- const key = 'dmn_chk_' + uuidv7();
486
- while (!firstNonPublicSubDomain && len--) {
487
- const candidate = list.slice(len).join('.');
488
- const candidateCookieValue = key + '=1;domain=.' + candidate + ';path=/';
489
- // try to set cookie, include a short expiry in seconds since we'll check immediately
490
- cookieJar.cookie = candidateCookieValue + ';max-age=3';
491
- if (cookieJar.cookie.includes(key)) {
492
- // the cookie was accepted by the browser, remove the test cookie
493
- cookieJar.cookie = candidateCookieValue + ';max-age=0';
494
- firstNonPublicSubDomain = candidate;
495
- }
496
- }
497
- return firstNonPublicSubDomain;
498
- }
499
- const DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;
500
- const originalCookieDomainFn = hostname => {
501
- const matches = hostname.match(DOMAIN_MATCH_REGEX);
502
- return matches ? matches[0] : '';
503
- };
504
- function chooseCookieDomain(hostname, cross_subdomain) {
505
- if (cross_subdomain) {
506
- // NOTE: Could we use this for cross domain tracking?
507
- let matchedSubDomain = seekFirstNonPublicSubDomain(hostname);
508
- if (!matchedSubDomain) {
509
- const originalMatch = originalCookieDomainFn(hostname);
510
- if (originalMatch !== matchedSubDomain) {
511
- logger.info('Warning: cookie subdomain discovery mismatch', originalMatch, matchedSubDomain);
512
- }
513
- matchedSubDomain = originalMatch;
514
- }
515
- return matchedSubDomain ? '; domain=.' + matchedSubDomain : '';
516
- }
517
- return '';
518
- }
519
- // Methods partially borrowed from quirksmode.org/js/cookies.html
520
- const cookieStore = {
521
- _is_supported: () => !!document,
522
- _error: function (msg) {
523
- logger.error('cookieStore error: ' + msg);
524
- },
525
- _get: function (name) {
526
- if (!document) {
527
- return;
528
- }
529
- try {
530
- const nameEQ = name + '=';
531
- const ca = document.cookie.split(';').filter(x => x.length);
532
- for (let i = 0; i < ca.length; i++) {
533
- let c = ca[i];
534
- while (c.charAt(0) == ' ') {
535
- c = c.substring(1, c.length);
536
- }
537
- if (c.indexOf(nameEQ) === 0) {
538
- return decodeURIComponent(c.substring(nameEQ.length, c.length));
539
- }
540
- }
541
- } catch {}
542
- return null;
543
- },
544
- _parse: function (name) {
545
- let cookie;
546
- try {
547
- cookie = JSON.parse(cookieStore._get(name)) || {};
548
- } catch {
549
- // noop
550
- }
551
- return cookie;
552
- },
553
- _set: function (name, value, days, cross_subdomain, is_secure) {
554
- if (!document) {
555
- return;
556
- }
557
- try {
558
- let expires = '',
559
- secure = '';
560
- const cdomain = chooseCookieDomain(document.location.hostname, cross_subdomain);
561
- if (days) {
562
- const date = new Date();
563
- date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
564
- expires = '; expires=' + date.toUTCString();
565
- }
566
- if (is_secure) {
567
- secure = '; secure';
568
- }
569
- const new_cookie_val = name + '=' + encodeURIComponent(JSON.stringify(value)) + expires + '; SameSite=Lax; path=/' + cdomain + secure;
570
- // 4096 bytes is the size at which some browsers (e.g. firefox) will not store a cookie, warn slightly before that
571
- if (new_cookie_val.length > 4096 * 0.9) {
572
- logger.warn('cookieStore warning: large cookie, len=' + new_cookie_val.length);
573
- }
574
- document.cookie = new_cookie_val;
575
- return new_cookie_val;
576
- } catch {
577
- return;
578
- }
579
- },
580
- _remove: function (name, cross_subdomain) {
581
- if (!document?.cookie) {
582
- return;
583
- }
584
- try {
585
- cookieStore._set(name, '', -1, cross_subdomain);
586
- } catch {
587
- return;
588
- }
589
- }
590
- };
591
- let _localStorage_supported = null;
592
- const localStore = {
593
- _is_supported: function () {
594
- if (!isNull(_localStorage_supported)) {
595
- return _localStorage_supported;
596
- }
597
- let supported = true;
598
- if (!isUndefined(win)) {
599
- try {
600
- const key = '__mplssupport__',
601
- val = 'xyz';
602
- localStore._set(key, val);
603
- if (localStore._get(key) !== '"xyz"') {
604
- supported = false;
605
- }
606
- localStore._remove(key);
607
- } catch {
608
- supported = false;
609
- }
610
- } else {
611
- supported = false;
612
- }
613
- if (!supported) {
614
- logger.error('localStorage unsupported; falling back to cookie store');
615
- }
616
- _localStorage_supported = supported;
617
- return supported;
618
- },
619
- _error: function (msg) {
620
- logger.error('localStorage error: ' + msg);
621
- },
622
- _get: function (name) {
623
- try {
624
- return win?.localStorage.getItem(name);
625
- } catch (err) {
626
- localStore._error(err);
627
- }
628
- return null;
629
- },
630
- _parse: function (name) {
631
- try {
632
- return JSON.parse(localStore._get(name)) || {};
633
- } catch {
634
- // noop
635
- }
636
- return null;
637
- },
638
- _set: function (name, value) {
639
- try {
640
- win?.localStorage.setItem(name, JSON.stringify(value));
641
- } catch (err) {
642
- localStore._error(err);
643
- }
644
- },
645
- _remove: function (name) {
646
- try {
647
- win?.localStorage.removeItem(name);
648
- } catch (err) {
649
- localStore._error(err);
650
- }
651
- }
652
- };
653
- // Use localstorage for most data but still use cookie for COOKIE_PERSISTED_PROPERTIES
654
- // This solves issues with cookies having too much data in them causing headers too large
655
- // Also makes sure we don't have to send a ton of data to the server
656
- const COOKIE_PERSISTED_PROPERTIES = [DISTINCT_ID, SESSION_ID, SESSION_RECORDING_IS_SAMPLED, ENABLE_PERSON_PROCESSING, INITIAL_PERSON_INFO];
657
- const localPlusCookieStore = {
658
- ...localStore,
659
- _parse: function (name) {
660
- try {
661
- let cookieProperties = {};
662
- try {
663
- // See if there's a cookie stored with data.
664
- cookieProperties = cookieStore._parse(name) || {};
665
- } catch {}
666
- const value = extend(cookieProperties, JSON.parse(localStore._get(name) || '{}'));
667
- localStore._set(name, value);
668
- return value;
669
- } catch {
670
- // noop
671
- }
672
- return null;
673
- },
674
- _set: function (name, value, days, cross_subdomain, is_secure, debug) {
675
- try {
676
- localStore._set(name, value, undefined, undefined, debug);
677
- const cookiePersistedProperties = {};
678
- COOKIE_PERSISTED_PROPERTIES.forEach(key => {
679
- if (value[key]) {
680
- cookiePersistedProperties[key] = value[key];
681
- }
682
- });
683
- if (Object.keys(cookiePersistedProperties).length) {
684
- cookieStore._set(name, cookiePersistedProperties, days, cross_subdomain, is_secure, debug);
685
- }
686
- } catch (err) {
687
- localStore._error(err);
688
- }
689
- },
690
- _remove: function (name, cross_subdomain) {
691
- try {
692
- win?.localStorage.removeItem(name);
693
- cookieStore._remove(name, cross_subdomain);
694
- } catch (err) {
695
- localStore._error(err);
696
- }
697
- }
698
- };
699
- const memoryStorage = {};
700
- // Storage that only lasts the length of the pageview if we don't want to use cookies
701
- const memoryStore = {
702
- _is_supported: function () {
703
- return true;
704
- },
705
- _error: function (msg) {
706
- logger.error('memoryStorage error: ' + msg);
707
- },
708
- _get: function (name) {
709
- return memoryStorage[name] || null;
710
- },
711
- _parse: function (name) {
712
- return memoryStorage[name] || null;
713
- },
714
- _set: function (name, value) {
715
- memoryStorage[name] = value;
716
- },
717
- _remove: function (name) {
718
- delete memoryStorage[name];
719
- }
720
- };
721
- let sessionStorageSupported = null;
722
- // Storage that only lasts the length of a tab/window. Survives page refreshes
723
- const sessionStore = {
724
- _is_supported: function () {
725
- if (!isNull(sessionStorageSupported)) {
726
- return sessionStorageSupported;
727
- }
728
- sessionStorageSupported = true;
729
- if (!isUndefined(win)) {
730
- try {
731
- const key = '__support__',
732
- val = 'xyz';
733
- sessionStore._set(key, val);
734
- if (sessionStore._get(key) !== '"xyz"') {
735
- sessionStorageSupported = false;
736
- }
737
- sessionStore._remove(key);
738
- } catch {
739
- sessionStorageSupported = false;
740
- }
741
- } else {
742
- sessionStorageSupported = false;
743
- }
744
- return sessionStorageSupported;
745
- },
746
- _error: function (msg) {
747
- logger.error('sessionStorage error: ', msg);
748
- },
749
- _get: function (name) {
750
- try {
751
- return win?.sessionStorage.getItem(name);
752
- } catch (err) {
753
- sessionStore._error(err);
754
- }
755
- return null;
756
- },
757
- _parse: function (name) {
758
- try {
759
- return JSON.parse(sessionStore._get(name)) || null;
760
- } catch {
761
- // noop
762
- }
763
- return null;
764
- },
765
- _set: function (name, value) {
766
- try {
767
- win?.sessionStorage.setItem(name, JSON.stringify(value));
768
- } catch (err) {
769
- sessionStore._error(err);
770
- }
771
- },
772
- _remove: function (name) {
773
- try {
774
- win?.sessionStorage.removeItem(name);
775
- } catch (err) {
776
- sessionStore._error(err);
777
- }
778
- }
779
- };
780
-
781
- /**
782
- * IE11 doesn't support `new URL`
783
- * so we can create an anchor element and use that to parse the URL
784
- * there's a lot of overlap between HTMLHyperlinkElementUtils and URL
785
- * meaning useful properties like `pathname` are available on both
786
- */
787
- const convertToURL = url => {
788
- const location = document?.createElement('a');
789
- if (isUndefined(location)) {
790
- return null;
791
- }
792
- location.href = url;
793
- return location;
794
- };
795
- // NOTE: Once we get rid of IE11/op_mini we can start using URLSearchParams
796
- const getQueryParam = function (url, param) {
797
- const withoutHash = url.split('#')[0] || '';
798
- // Split only on the first ? to sort problem out for those with multiple ?s
799
- // and then remove them
800
- const queryParams = withoutHash.split(/\?(.*)/)[1] || '';
801
- const cleanedQueryParams = queryParams.replace(/^\?+/g, '');
802
- const queryParts = cleanedQueryParams.split('&');
803
- let keyValuePair;
804
- for (let i = 0; i < queryParts.length; i++) {
805
- const parts = queryParts[i].split('=');
806
- if (parts[0] === param) {
807
- keyValuePair = parts;
808
- break;
809
- }
810
- }
811
- if (!isArray(keyValuePair) || keyValuePair.length < 2) {
812
- return '';
813
- } else {
814
- let result = keyValuePair[1];
815
- try {
816
- result = decodeURIComponent(result);
817
- } catch {
818
- logger.error('Skipping decoding for malformed query param: ' + result);
819
- }
820
- return result.replace(/\+/g, ' ');
821
- }
822
- };
823
- // replace any query params in the url with the provided mask value. Tries to keep the URL as instant as possible,
824
- // including preserving malformed text in most cases
825
- const maskQueryParams = function (url, maskedParams, mask) {
826
- if (!url || !maskedParams || !maskedParams.length) {
827
- return url;
828
- }
829
- const splitHash = url.split('#');
830
- const withoutHash = splitHash[0] || '';
831
- const hash = splitHash[1];
832
- const splitQuery = withoutHash.split('?');
833
- const queryString = splitQuery[1];
834
- const urlWithoutQueryAndHash = splitQuery[0];
835
- const queryParts = (queryString || '').split('&');
836
- // use an array of strings rather than an object to preserve ordering and duplicates
837
- const paramStrings = [];
838
- for (let i = 0; i < queryParts.length; i++) {
839
- const keyValuePair = queryParts[i].split('=');
840
- if (!isArray(keyValuePair)) {
841
- continue;
842
- } else if (maskedParams.includes(keyValuePair[0])) {
843
- paramStrings.push(keyValuePair[0] + '=' + mask);
844
- } else {
845
- paramStrings.push(queryParts[i]);
846
- }
847
- }
848
- let result = urlWithoutQueryAndHash;
849
- if (queryString != null) {
850
- result += '?' + paramStrings.join('&');
851
- }
852
- if (hash != null) {
853
- result += '#' + hash;
854
- }
855
- return result;
856
- };
857
-
858
- /**
859
- * this device detection code is (at time of writing) about 3% of the size of the entire library
860
- * this is mostly because the identifiers user in regexes and results can't be minified away since
861
- * they have meaning
862
- *
863
- * so, there are some pre-uglifying choices in the code to help reduce the size
864
- * e.g. many repeated strings are stored as variables and then old-fashioned concatenated together
865
- *
866
- * TL;DR here be dragons
867
- */
868
- const FACEBOOK = 'Facebook';
869
- const MOBILE = 'Mobile';
870
- const IOS = 'iOS';
871
- const ANDROID = 'Android';
872
- const TABLET = 'Tablet';
873
- const ANDROID_TABLET = ANDROID + ' ' + TABLET;
874
- const IPAD = 'iPad';
875
- const APPLE = 'Apple';
876
- const APPLE_WATCH = APPLE + ' Watch';
877
- const SAFARI = 'Safari';
878
- const BLACKBERRY = 'BlackBerry';
879
- const SAMSUNG = 'Samsung';
880
- const SAMSUNG_BROWSER = SAMSUNG + 'Browser';
881
- const SAMSUNG_INTERNET = SAMSUNG + ' Internet';
882
- const CHROME = 'Chrome';
883
- const CHROME_OS = CHROME + ' OS';
884
- const CHROME_IOS = CHROME + ' ' + IOS;
885
- const INTERNET_EXPLORER = 'Internet Explorer';
886
- const INTERNET_EXPLORER_MOBILE = INTERNET_EXPLORER + ' ' + MOBILE;
887
- const OPERA = 'Opera';
888
- const OPERA_MINI = OPERA + ' Mini';
889
- const EDGE = 'Edge';
890
- const MICROSOFT_EDGE = 'Microsoft ' + EDGE;
891
- const FIREFOX = 'Firefox';
892
- const FIREFOX_IOS = FIREFOX + ' ' + IOS;
893
- const NINTENDO = 'Nintendo';
894
- const PLAYSTATION = 'PlayStation';
895
- const XBOX = 'Xbox';
896
- const ANDROID_MOBILE = ANDROID + ' ' + MOBILE;
897
- const MOBILE_SAFARI = MOBILE + ' ' + SAFARI;
898
- const WINDOWS = 'Windows';
899
- const WINDOWS_PHONE = WINDOWS + ' Phone';
900
- const NOKIA = 'Nokia';
901
- const OUYA = 'Ouya';
902
- const GENERIC = 'Generic';
903
- const GENERIC_MOBILE = GENERIC + ' ' + MOBILE.toLowerCase();
904
- const GENERIC_TABLET = GENERIC + ' ' + TABLET.toLowerCase();
905
- const KONQUEROR = 'Konqueror';
906
- const BROWSER_VERSION_REGEX_SUFFIX = '(\\d+(\\.\\d+)?)';
907
- const DEFAULT_BROWSER_VERSION_REGEX = new RegExp('Version/' + BROWSER_VERSION_REGEX_SUFFIX);
908
- const XBOX_REGEX = new RegExp(XBOX, 'i');
909
- const PLAYSTATION_REGEX = new RegExp(PLAYSTATION + ' \\w+', 'i');
910
- const NINTENDO_REGEX = new RegExp(NINTENDO + ' \\w+', 'i');
911
- const BLACKBERRY_REGEX = new RegExp(BLACKBERRY + '|PlayBook|BB10', 'i');
912
- const windowsVersionMap = {
913
- 'NT3.51': 'NT 3.11',
914
- 'NT4.0': 'NT 4.0',
915
- '5.0': '2000',
916
- '5.1': 'XP',
917
- '5.2': 'XP',
918
- '6.0': 'Vista',
919
- '6.1': '7',
920
- '6.2': '8',
921
- '6.3': '8.1',
922
- '6.4': '10',
923
- '10.0': '10'
924
- };
925
- /**
926
- * Safari detection turns out to be complicated. For e.g. https://stackoverflow.com/a/29696509
927
- * We can be slightly loose because some options have been ruled out (e.g. firefox on iOS)
928
- * before this check is made
929
- */
930
- function isSafari(userAgent) {
931
- return includes(userAgent, SAFARI) && !includes(userAgent, CHROME) && !includes(userAgent, ANDROID);
932
- }
933
- const safariCheck = (ua, vendor) => vendor && includes(vendor, APPLE) || isSafari(ua);
934
- /**
935
- * This function detects which browser is running this script.
936
- * The order of the checks are important since many user agents
937
- * include keywords used in later checks.
938
- */
939
- const detectBrowser = function (user_agent, vendor) {
940
- vendor = vendor || ''; // vendor is undefined for at least IE9
941
- if (includes(user_agent, ' OPR/') && includes(user_agent, 'Mini')) {
942
- return OPERA_MINI;
943
- } else if (includes(user_agent, ' OPR/')) {
944
- return OPERA;
945
- } else if (BLACKBERRY_REGEX.test(user_agent)) {
946
- return BLACKBERRY;
947
- } else if (includes(user_agent, 'IE' + MOBILE) || includes(user_agent, 'WPDesktop')) {
948
- return INTERNET_EXPLORER_MOBILE;
949
- }
950
- // https://developer.samsung.com/internet/user-agent-string-format
951
- else if (includes(user_agent, SAMSUNG_BROWSER)) {
952
- return SAMSUNG_INTERNET;
953
- } else if (includes(user_agent, EDGE) || includes(user_agent, 'Edg/')) {
954
- return MICROSOFT_EDGE;
955
- } else if (includes(user_agent, 'FBIOS')) {
956
- return FACEBOOK + ' ' + MOBILE;
957
- } else if (includes(user_agent, 'UCWEB') || includes(user_agent, 'UCBrowser')) {
958
- return 'UC Browser';
959
- } else if (includes(user_agent, 'CriOS')) {
960
- return CHROME_IOS; // why not just Chrome?
961
- } else if (includes(user_agent, 'CrMo')) {
962
- return CHROME;
963
- } else if (includes(user_agent, CHROME)) {
964
- return CHROME;
965
- } else if (includes(user_agent, ANDROID) && includes(user_agent, SAFARI)) {
966
- return ANDROID_MOBILE;
967
- } else if (includes(user_agent, 'FxiOS')) {
968
- return FIREFOX_IOS;
969
- } else if (includes(user_agent.toLowerCase(), KONQUEROR.toLowerCase())) {
970
- return KONQUEROR;
971
- } else if (safariCheck(user_agent, vendor)) {
972
- return includes(user_agent, MOBILE) ? MOBILE_SAFARI : SAFARI;
973
- } else if (includes(user_agent, FIREFOX)) {
974
- return FIREFOX;
975
- } else if (includes(user_agent, 'MSIE') || includes(user_agent, 'Trident/')) {
976
- return INTERNET_EXPLORER;
977
- } else if (includes(user_agent, 'Gecko')) {
978
- return FIREFOX;
979
- }
980
- return '';
981
- };
982
- const versionRegexes = {
983
- [INTERNET_EXPLORER_MOBILE]: [new RegExp('rv:' + BROWSER_VERSION_REGEX_SUFFIX)],
984
- [MICROSOFT_EDGE]: [new RegExp(EDGE + '?\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
985
- [CHROME]: [new RegExp('(' + CHROME + '|CrMo)\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
986
- [CHROME_IOS]: [new RegExp('CriOS\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
987
- 'UC Browser': [new RegExp('(UCBrowser|UCWEB)\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
988
- [SAFARI]: [DEFAULT_BROWSER_VERSION_REGEX],
989
- [MOBILE_SAFARI]: [DEFAULT_BROWSER_VERSION_REGEX],
990
- [OPERA]: [new RegExp('(' + OPERA + '|OPR)\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
991
- [FIREFOX]: [new RegExp(FIREFOX + '\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
992
- [FIREFOX_IOS]: [new RegExp('FxiOS\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
993
- [KONQUEROR]: [new RegExp('Konqueror[:/]?' + BROWSER_VERSION_REGEX_SUFFIX, 'i')],
994
- // not every blackberry user agent has the version after the name
995
- [BLACKBERRY]: [new RegExp(BLACKBERRY + ' ' + BROWSER_VERSION_REGEX_SUFFIX), DEFAULT_BROWSER_VERSION_REGEX],
996
- [ANDROID_MOBILE]: [new RegExp('android\\s' + BROWSER_VERSION_REGEX_SUFFIX, 'i')],
997
- [SAMSUNG_INTERNET]: [new RegExp(SAMSUNG_BROWSER + '\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
998
- [INTERNET_EXPLORER]: [new RegExp('(rv:|MSIE )' + BROWSER_VERSION_REGEX_SUFFIX)],
999
- Mozilla: [new RegExp('rv:' + BROWSER_VERSION_REGEX_SUFFIX)]
1000
- };
1001
- /**
1002
- * This function detects which browser version is running this script,
1003
- * parsing major and minor version (e.g., 42.1). User agent strings from:
1004
- * http://www.useragentstring.com/pages/useragentstring.php
1005
- *
1006
- * `navigator.vendor` is passed in and used to help with detecting certain browsers
1007
- * NB `navigator.vendor` is deprecated and not present in every browser
1008
- */
1009
- const detectBrowserVersion = function (userAgent, vendor) {
1010
- const browser = detectBrowser(userAgent, vendor);
1011
- const regexes = versionRegexes[browser];
1012
- if (isUndefined(regexes)) {
1013
- return null;
1014
- }
1015
- for (let i = 0; i < regexes.length; i++) {
1016
- const regex = regexes[i];
1017
- const matches = userAgent.match(regex);
1018
- if (matches) {
1019
- return parseFloat(matches[matches.length - 2]);
1020
- }
1021
- }
1022
- return null;
1023
- };
1024
- // to avoid repeating regexes or calling them twice, we have an array of matches
1025
- // the first regex that matches uses its matcher function to return the result
1026
- const osMatchers = [[new RegExp(XBOX + '; ' + XBOX + ' (.*?)[);]', 'i'), match => {
1027
- return [XBOX, match && match[1] || ''];
1028
- }], [new RegExp(NINTENDO, 'i'), [NINTENDO, '']], [new RegExp(PLAYSTATION, 'i'), [PLAYSTATION, '']], [BLACKBERRY_REGEX, [BLACKBERRY, '']], [new RegExp(WINDOWS, 'i'), (_, user_agent) => {
1029
- if (/Phone/.test(user_agent) || /WPDesktop/.test(user_agent)) {
1030
- return [WINDOWS_PHONE, ''];
1031
- }
1032
- // not all JS versions support negative lookbehind, so we need two checks here
1033
- if (new RegExp(MOBILE).test(user_agent) && !/IEMobile\b/.test(user_agent)) {
1034
- return [WINDOWS + ' ' + MOBILE, ''];
1035
- }
1036
- const match = /Windows NT ([0-9.]+)/i.exec(user_agent);
1037
- if (match && match[1]) {
1038
- const version = match[1];
1039
- let osVersion = windowsVersionMap[version] || '';
1040
- if (/arm/i.test(user_agent)) {
1041
- osVersion = 'RT';
1042
- }
1043
- return [WINDOWS, osVersion];
1044
- }
1045
- return [WINDOWS, ''];
1046
- }], [/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/, match => {
1047
- if (match && match[3]) {
1048
- const versionParts = [match[3], match[4], match[5] || '0'];
1049
- return [IOS, versionParts.join('.')];
1050
- }
1051
- return [IOS, ''];
1052
- }], [/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i, match => {
1053
- // e.g. Watch4,3/5.3.8 (16U680)
1054
- let version = '';
1055
- if (match && match.length >= 3) {
1056
- version = isUndefined(match[2]) ? match[3] : match[2];
1057
- }
1058
- return ['watchOS', version];
1059
- }], [new RegExp('(' + ANDROID + ' (\\d+)\\.(\\d+)\\.?(\\d+)?|' + ANDROID + ')', 'i'), match => {
1060
- if (match && match[2]) {
1061
- const versionParts = [match[2], match[3], match[4] || '0'];
1062
- return [ANDROID, versionParts.join('.')];
1063
- }
1064
- return [ANDROID, ''];
1065
- }], [/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i, match => {
1066
- const result = ['Mac OS X', ''];
1067
- if (match && match[1]) {
1068
- const versionParts = [match[1], match[2], match[3] || '0'];
1069
- result[1] = versionParts.join('.');
1070
- }
1071
- return result;
1072
- }], [/Mac/i,
1073
- // mop up a few non-standard UAs that should match mac
1074
- ['Mac OS X', '']], [/CrOS/, [CHROME_OS, '']], [/Linux|debian/i, ['Linux', '']]];
1075
- const detectOS = function (user_agent) {
1076
- for (let i = 0; i < osMatchers.length; i++) {
1077
- const [rgex, resultOrFn] = osMatchers[i];
1078
- const match = rgex.exec(user_agent);
1079
- const result = match && (isFunction(resultOrFn) ? resultOrFn(match, user_agent) : resultOrFn);
1080
- if (result) {
1081
- return result;
1082
- }
1083
- }
1084
- return ['', ''];
1085
- };
1086
- const detectDevice = function (user_agent) {
1087
- if (NINTENDO_REGEX.test(user_agent)) {
1088
- return NINTENDO;
1089
- } else if (PLAYSTATION_REGEX.test(user_agent)) {
1090
- return PLAYSTATION;
1091
- } else if (XBOX_REGEX.test(user_agent)) {
1092
- return XBOX;
1093
- } else if (new RegExp(OUYA, 'i').test(user_agent)) {
1094
- return OUYA;
1095
- } else if (new RegExp('(' + WINDOWS_PHONE + '|WPDesktop)', 'i').test(user_agent)) {
1096
- return WINDOWS_PHONE;
1097
- } else if (/iPad/.test(user_agent)) {
1098
- return IPAD;
1099
- } else if (/iPod/.test(user_agent)) {
1100
- return 'iPod Touch';
1101
- } else if (/iPhone/.test(user_agent)) {
1102
- return 'iPhone';
1103
- } else if (/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(user_agent)) {
1104
- return APPLE_WATCH;
1105
- } else if (BLACKBERRY_REGEX.test(user_agent)) {
1106
- return BLACKBERRY;
1107
- } else if (/(kobo)\s(ereader|touch)/i.test(user_agent)) {
1108
- return 'Kobo';
1109
- } else if (new RegExp(NOKIA, 'i').test(user_agent)) {
1110
- return NOKIA;
1111
- } else if (
1112
- // Kindle Fire without Silk / Echo Show
1113
- /(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(user_agent) ||
1114
- // Kindle Fire HD
1115
- /(kf[a-z]+)( bui|\)).+silk\//i.test(user_agent)) {
1116
- return 'Kindle Fire';
1117
- } else if (/(Android|ZTE)/i.test(user_agent)) {
1118
- if (!new RegExp(MOBILE).test(user_agent) || /(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(user_agent)) {
1119
- if (/pixel[\daxl ]{1,6}/i.test(user_agent) && !/pixel c/i.test(user_agent) || /(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(user_agent) || /lmy47v/i.test(user_agent) && !/QTAQZ3/i.test(user_agent)) {
1120
- return ANDROID;
1121
- }
1122
- return ANDROID_TABLET;
1123
- } else {
1124
- return ANDROID;
1125
- }
1126
- } else if (new RegExp('(pda|' + MOBILE + ')', 'i').test(user_agent)) {
1127
- return GENERIC_MOBILE;
1128
- } else if (new RegExp(TABLET, 'i').test(user_agent) && !new RegExp(TABLET + ' pc', 'i').test(user_agent)) {
1129
- return GENERIC_TABLET;
1130
- } else {
1131
- return '';
1132
- }
1133
- };
1134
- const detectDeviceType = function (user_agent) {
1135
- const device = detectDevice(user_agent);
1136
- if (device === IPAD || device === ANDROID_TABLET || device === 'Kobo' || device === 'Kindle Fire' || device === GENERIC_TABLET) {
1137
- return TABLET;
1138
- } else if (device === NINTENDO || device === XBOX || device === PLAYSTATION || device === OUYA) {
1139
- return 'Console';
1140
- } else if (device === APPLE_WATCH) {
1141
- return 'Wearable';
1142
- } else if (device) {
1143
- return MOBILE;
1144
- } else {
1145
- return 'Desktop';
1146
- }
1147
- };
1148
-
1149
- var version = "0.1.3";
1150
- var packageInfo = {
1151
- version: version};
1152
-
1153
- const Config = {
1154
- LIB_VERSION: packageInfo.version
1155
- };
1156
-
1157
- const URL_REGEX_PREFIX = 'https?://(.*)';
1158
- // CAMPAIGN_PARAMS and EVENT_TO_PERSON_PROPERTIES should be kept in sync with
1159
- // https://github.com/PostHog/posthog/blob/master/plugin-server/src/utils/db/utils.ts#L60
1160
- // The list of campaign parameters that could be considered personal data under e.g. GDPR.
1161
- // These can be masked in URLs and properties before being sent to posthog.
1162
- const PERSONAL_DATA_CAMPAIGN_PARAMS = ['gclid',
1163
- // google ads
1164
- 'gclsrc',
1165
- // google ads 360
1166
- 'dclid',
1167
- // google display ads
1168
- 'gbraid',
1169
- // google ads, web to app
1170
- 'wbraid',
1171
- // google ads, app to web
1172
- 'fbclid',
1173
- // facebook
1174
- 'msclkid',
1175
- // microsoft
1176
- 'twclid',
1177
- // twitter
1178
- 'li_fat_id',
1179
- // linkedin
1180
- 'igshid',
1181
- // instagram
1182
- 'ttclid',
1183
- // tiktok
1184
- 'rdt_cid',
1185
- // reddit
1186
- 'epik',
1187
- // pinterest
1188
- 'qclid',
1189
- // quora
1190
- 'sccid',
1191
- // snapchat
1192
- 'irclid',
1193
- // impact
1194
- '_kx' // klaviyo
1195
- ];
1196
- const CAMPAIGN_PARAMS = extendArray(['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term', 'gad_source',
1197
- // google ads source
1198
- 'mc_cid' // mailchimp campaign id
1199
- ], PERSONAL_DATA_CAMPAIGN_PARAMS);
1200
- const MASKED = '<masked>';
1201
- // Campaign params that can be read from the cookie store
1202
- const COOKIE_CAMPAIGN_PARAMS = ['li_fat_id' // linkedin
1203
- ];
1204
- function getCampaignParams(customTrackedParams, maskPersonalDataProperties, customPersonalDataProperties) {
1205
- if (!document) {
1206
- return {};
1207
- }
1208
- const paramsToMask = maskPersonalDataProperties ? extendArray([], PERSONAL_DATA_CAMPAIGN_PARAMS, customPersonalDataProperties || []) : [];
1209
- // Initially get campaign params from the URL
1210
- const urlCampaignParams = _getCampaignParamsFromUrl(maskQueryParams(document.URL, paramsToMask, MASKED), customTrackedParams);
1211
- // But we can also get some of them from the cookie store
1212
- // For example: https://learn.microsoft.com/en-us/linkedin/marketing/conversions/enabling-first-party-cookies?view=li-lms-2025-05#reading-li_fat_id-from-cookies
1213
- const cookieCampaignParams = _getCampaignParamsFromCookie();
1214
- // Prefer the values found in the urlCampaignParams if possible
1215
- // `extend` will override the values if found in the second argument
1216
- return extend(cookieCampaignParams, urlCampaignParams);
1217
- }
1218
- function _getCampaignParamsFromUrl(url, customParams) {
1219
- const campaign_keywords = CAMPAIGN_PARAMS.concat(customParams || []);
1220
- const params = {};
1221
- each(campaign_keywords, function (kwkey) {
1222
- const kw = getQueryParam(url, kwkey);
1223
- params[kwkey] = kw ? kw : null;
1224
- });
1225
- return params;
1226
- }
1227
- function _getCampaignParamsFromCookie() {
1228
- const params = {};
1229
- each(COOKIE_CAMPAIGN_PARAMS, function (kwkey) {
1230
- const kw = cookieStore._get(kwkey);
1231
- params[kwkey] = kw ? kw : null;
1232
- });
1233
- return params;
1234
- }
1235
- function _getSearchEngine(referrer) {
1236
- if (!referrer) {
1237
- return null;
1238
- } else {
1239
- if (referrer.search(URL_REGEX_PREFIX + 'google.([^/?]*)') === 0) {
1240
- return 'google';
1241
- } else if (referrer.search(URL_REGEX_PREFIX + 'bing.com') === 0) {
1242
- return 'bing';
1243
- } else if (referrer.search(URL_REGEX_PREFIX + 'yahoo.com') === 0) {
1244
- return 'yahoo';
1245
- } else if (referrer.search(URL_REGEX_PREFIX + 'duckduckgo.com') === 0) {
1246
- return 'duckduckgo';
1247
- } else {
1248
- return null;
1249
- }
1250
- }
1251
- }
1252
- function _getSearchInfoFromReferrer(referrer) {
1253
- const search = _getSearchEngine(referrer);
1254
- const param = search != 'yahoo' ? 'q' : 'p';
1255
- const ret = {};
1256
- if (!isNull(search)) {
1257
- ret['$search_engine'] = search;
1258
- const keyword = document ? getQueryParam(document.referrer, param) : '';
1259
- if (keyword.length) {
1260
- ret['ph_keyword'] = keyword;
1261
- }
1262
- }
1263
- return ret;
1264
- }
1265
- function getSearchInfo() {
1266
- const referrer = document?.referrer;
1267
- if (!referrer) {
1268
- return {};
1269
- }
1270
- return _getSearchInfoFromReferrer(referrer);
1271
- }
1272
- function getBrowserLanguage() {
1273
- return navigator.language ||
1274
- // Any modern browser
1275
- navigator.userLanguage // IE11
1276
- ;
1277
- }
1278
- function getBrowserLanguagePrefix() {
1279
- const lang = getBrowserLanguage();
1280
- return typeof lang === 'string' ? lang.split('-')[0] : undefined;
1281
- }
1282
- function getReferrer() {
1283
- return document?.referrer || '$direct';
1284
- }
1285
- function getReferringDomain() {
1286
- if (!document?.referrer) {
1287
- return '$direct';
1288
- }
1289
- return convertToURL(document.referrer)?.host || '$direct';
1290
- }
1291
- function getReferrerInfo() {
1292
- return {
1293
- $referrer: getReferrer(),
1294
- $referring_domain: getReferringDomain()
1295
- };
1296
- }
1297
- function getPersonInfo(maskPersonalDataProperties, customPersonalDataProperties) {
1298
- const paramsToMask = maskPersonalDataProperties ? extendArray([], PERSONAL_DATA_CAMPAIGN_PARAMS, customPersonalDataProperties || []) : [];
1299
- const url = location?.href.substring(0, 1000);
1300
- // we're being a bit more economical with bytes here because this is stored in the cookie
1301
- return {
1302
- r: getReferrer().substring(0, 1000),
1303
- u: url ? maskQueryParams(url, paramsToMask, MASKED) : undefined
1304
- };
1305
- }
1306
- function getPersonPropsFromInfo(info) {
1307
- const {
1308
- r: referrer,
1309
- u: url
1310
- } = info;
1311
- const referring_domain = referrer == null ? undefined : referrer == '$direct' ? '$direct' : convertToURL(referrer)?.host;
1312
- const props = {
1313
- $referrer: referrer,
1314
- $referring_domain: referring_domain
1315
- };
1316
- if (url) {
1317
- props['$current_url'] = url;
1318
- const location = convertToURL(url);
1319
- props['$host'] = location?.host;
1320
- props['$pathname'] = location?.pathname;
1321
- const campaignParams = _getCampaignParamsFromUrl(url);
1322
- extend(props, campaignParams);
1323
- }
1324
- if (referrer) {
1325
- const searchInfo = _getSearchInfoFromReferrer(referrer);
1326
- extend(props, searchInfo);
1327
- }
1328
- return props;
1329
- }
1330
- function getInitialPersonPropsFromInfo(info) {
1331
- const personProps = getPersonPropsFromInfo(info);
1332
- const props = {};
1333
- each(personProps, function (val, key) {
1334
- props[`$initial_${stripLeadingDollar(key)}`] = val;
1335
- });
1336
- return props;
1337
- }
1338
- function getTimezone() {
1339
- try {
1340
- return Intl.DateTimeFormat().resolvedOptions().timeZone;
1341
- } catch {
1342
- return undefined;
1343
- }
1344
- }
1345
- function getTimezoneOffset() {
1346
- try {
1347
- return new Date().getTimezoneOffset();
1348
- } catch {
1349
- return undefined;
1350
- }
1351
- }
1352
- function getEventProperties(maskPersonalDataProperties, customPersonalDataProperties) {
1353
- if (!userAgent) {
1354
- return {};
1355
- }
1356
- const paramsToMask = maskPersonalDataProperties ? extendArray([], PERSONAL_DATA_CAMPAIGN_PARAMS, customPersonalDataProperties || []) : [];
1357
- const [os_name, os_version] = detectOS(userAgent);
1358
- return extend(stripEmptyProperties({
1359
- $os: os_name,
1360
- $os_version: os_version,
1361
- $browser: detectBrowser(userAgent, navigator.vendor),
1362
- $device: detectDevice(userAgent),
1363
- $device_type: detectDeviceType(userAgent),
1364
- $timezone: getTimezone(),
1365
- $timezone_offset: getTimezoneOffset()
1366
- }), {
1367
- $current_url: maskQueryParams(location?.href, paramsToMask, MASKED),
1368
- $host: location?.host,
1369
- $pathname: location?.pathname,
1370
- $raw_user_agent: userAgent.length > 1000 ? userAgent.substring(0, 997) + '...' : userAgent,
1371
- $browser_version: detectBrowserVersion(userAgent, navigator.vendor),
1372
- $browser_language: getBrowserLanguage(),
1373
- $browser_language_prefix: getBrowserLanguagePrefix(),
1374
- $screen_height: win?.screen.height,
1375
- $screen_width: win?.screen.width,
1376
- $viewport_height: win?.innerHeight,
1377
- $viewport_width: win?.innerWidth,
1378
- $lib: 'web',
1379
- $lib_version: Config.LIB_VERSION,
1380
- $insert_id: Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10),
1381
- $time: Date.now() / 1000 // epoch time in seconds
1382
- });
1383
- }
1384
-
1385
- /* eslint camelcase: "off" */
1386
- const CASE_INSENSITIVE_PERSISTENCE_TYPES = ['cookie', 'localstorage', 'localstorage+cookie', 'sessionstorage', 'memory'];
1387
- const parseName = config => {
1388
- let token = '';
1389
- if (config['token']) {
1390
- token = config['token'].replace(/\+/g, 'PL').replace(/\//g, 'SL').replace(/=/g, 'EQ');
1391
- }
1392
- if (config['persistence_name']) {
1393
- return config['persistence_name'];
1394
- }
1395
- return 'leanbase_' + token;
1396
- };
1397
- /**
1398
- * Leanbase Persistence Object
1399
- * @constructor
1400
- */
1401
- class LeanbasePersistence {
1402
- /**
1403
- * @param {LeanbaseConfig} config initial PostHog configuration
1404
- * @param {boolean=} isDisabled should persistence be disabled (e.g. because of consent management)
1405
- */
1406
- constructor(config, isDisabled) {
1407
- this._config = config;
1408
- this.props = {};
1409
- this._campaign_params_saved = false;
1410
- this._name = parseName(config);
1411
- this._storage = this._buildStorage(config);
1412
- this.load();
1413
- if (config.debug) {
1414
- logger.info('Persistence loaded', config['persistence'], {
1415
- ...this.props
1416
- });
1417
- }
1418
- this.update_config(config, config, isDisabled);
1419
- this.save();
1420
- }
1421
- /**
1422
- * Returns whether persistence is disabled. Only available in SDKs > 1.257.1. Do not use on extensions, otherwise
1423
- * it'll break backwards compatibility for any version before 1.257.1.
1424
- */
1425
- isDisabled() {
1426
- return !!this._disabled;
1427
- }
1428
- _buildStorage(config) {
1429
- if (CASE_INSENSITIVE_PERSISTENCE_TYPES.indexOf(config['persistence'].toLowerCase()) === -1) {
1430
- logger.info('Unknown persistence type ' + config['persistence'] + '; falling back to localStorage+cookie');
1431
- config['persistence'] = 'localStorage+cookie';
1432
- }
1433
- let store;
1434
- const storage_type = config['persistence'].toLowerCase();
1435
- if (storage_type === 'localstorage' && localStore._is_supported()) {
1436
- store = localStore;
1437
- } else if (storage_type === 'localstorage+cookie' && localPlusCookieStore._is_supported()) {
1438
- store = localPlusCookieStore;
1439
- } else if (storage_type === 'sessionstorage' && sessionStore._is_supported()) {
1440
- store = sessionStore;
1441
- } else if (storage_type === 'memory') {
1442
- store = memoryStore;
1443
- } else if (storage_type === 'cookie') {
1444
- store = cookieStore;
1445
- } else if (localPlusCookieStore._is_supported()) {
1446
- store = localPlusCookieStore;
1447
- } else {
1448
- store = cookieStore;
1449
- }
1450
- return store;
1451
- }
1452
- properties() {
1453
- const p = {};
1454
- // Filter out reserved properties
1455
- each(this.props, function (v, k) {
1456
- if (k === ENABLED_FEATURE_FLAGS && isObject(v)) {
1457
- const keys = Object.keys(v);
1458
- for (let i = 0; i < keys.length; i++) {
1459
- p[`$feature/${keys[i]}`] = v[keys[i]];
1460
- }
1461
- } else if (!include(PERSISTENCE_RESERVED_PROPERTIES, k)) {
1462
- p[k] = v;
1463
- }
1464
- });
1465
- return p;
1466
- }
1467
- load() {
1468
- if (this._disabled) {
1469
- return;
1470
- }
1471
- const entry = this._storage._parse(this._name);
1472
- if (entry) {
1473
- this.props = extend({}, entry);
1474
- }
1475
- }
1476
- /**
1477
- * NOTE: Saving frequently causes issues with Recordings and Consent Management Platform (CMP) tools which
1478
- * observe cookie changes, and modify their UI, often causing infinite loops.
1479
- * As such callers of this should ideally check that the data has changed beforehand
1480
- */
1481
- save() {
1482
- if (this._disabled) {
1483
- return;
1484
- }
1485
- this._storage._set(this._name, this.props, this._expire_days, this._cross_subdomain, this._secure, this._config.debug);
1486
- }
1487
- remove() {
1488
- this._storage._remove(this._name, false);
1489
- this._storage._remove(this._name, true);
1490
- }
1491
- clear() {
1492
- this.remove();
1493
- this.props = {};
1494
- }
1495
- /**
1496
- * @param {Object} props
1497
- * @param {*=} default_value
1498
- * @param {number=} days
1499
- */
1500
- register_once(props, default_value, days) {
1501
- if (isObject(props)) {
1502
- if (isUndefined(default_value)) {
1503
- default_value = 'None';
1504
- }
1505
- this._expire_days = isUndefined(days) ? this._default_expiry : days;
1506
- let hasChanges = false;
1507
- each(props, (val, prop) => {
1508
- if (!this.props.hasOwnProperty(prop) || this.props[prop] === default_value) {
1509
- this.props[prop] = val;
1510
- hasChanges = true;
1511
- }
1512
- });
1513
- if (hasChanges) {
1514
- this.save();
1515
- return true;
1516
- }
1517
- }
1518
- return false;
1519
- }
1520
- /**
1521
- * @param {Object} props
1522
- * @param {number=} days
1523
- */
1524
- register(props, days) {
1525
- if (isObject(props)) {
1526
- this._expire_days = isUndefined(days) ? this._default_expiry : days;
1527
- let hasChanges = false;
1528
- each(props, (val, prop) => {
1529
- if (props.hasOwnProperty(prop) && this.props[prop] !== val) {
1530
- this.props[prop] = val;
1531
- hasChanges = true;
1532
- }
1533
- });
1534
- if (hasChanges) {
1535
- this.save();
1536
- return true;
1537
- }
1538
- }
1539
- return false;
1540
- }
1541
- unregister(prop) {
1542
- if (prop in this.props) {
1543
- delete this.props[prop];
1544
- this.save();
1545
- }
1546
- }
1547
- update_campaign_params() {
1548
- if (!this._campaign_params_saved) {
1549
- const campaignParams = getCampaignParams(this._config.custom_campaign_params, this._config.mask_personal_data_properties, this._config.custom_personal_data_properties);
1550
- if (!isEmptyObject(stripEmptyProperties(campaignParams))) {
1551
- this.register(campaignParams);
1552
- }
1553
- this._campaign_params_saved = true;
1554
- }
1555
- }
1556
- update_search_keyword() {
1557
- this.register(getSearchInfo());
1558
- }
1559
- update_referrer_info() {
1560
- this.register_once(getReferrerInfo(), undefined);
1561
- }
1562
- set_initial_person_info() {
1563
- if (this.props[INITIAL_CAMPAIGN_PARAMS] || this.props[INITIAL_REFERRER_INFO]) {
1564
- return;
1565
- }
1566
- this.register_once({
1567
- [INITIAL_PERSON_INFO]: getPersonInfo(this._config.mask_personal_data_properties, this._config.custom_personal_data_properties)
1568
- }, undefined);
1569
- }
1570
- get_initial_props() {
1571
- const p = {};
1572
- each([INITIAL_REFERRER_INFO, INITIAL_CAMPAIGN_PARAMS], key => {
1573
- const initialReferrerInfo = this.props[key];
1574
- if (initialReferrerInfo) {
1575
- each(initialReferrerInfo, function (v, k) {
1576
- p['$initial_' + stripLeadingDollar(k)] = v;
1577
- });
1578
- }
1579
- });
1580
- const initialPersonInfo = this.props[INITIAL_PERSON_INFO];
1581
- if (initialPersonInfo) {
1582
- const initialPersonProps = getInitialPersonPropsFromInfo(initialPersonInfo);
1583
- extend(p, initialPersonProps);
1584
- }
1585
- return p;
1586
- }
1587
- safe_merge(props) {
1588
- each(this.props, function (val, prop) {
1589
- if (!(prop in props)) {
1590
- props[prop] = val;
1591
- }
1592
- });
1593
- return props;
1594
- }
1595
- update_config(config, oldConfig, isDisabled) {
1596
- this._default_expiry = this._expire_days = config['cookie_expiration'];
1597
- this.set_disabled(config['disable_persistence'] || !!isDisabled);
1598
- this.set_cross_subdomain(config['cross_subdomain_cookie']);
1599
- this.set_secure(config['secure_cookie']);
1600
- if (config.persistence !== oldConfig.persistence) {
1601
- const newStore = this._buildStorage(config);
1602
- const props = this.props;
1603
- this.clear();
1604
- this._storage = newStore;
1605
- this.props = props;
1606
- this.save();
1607
- }
1608
- }
1609
- set_disabled(disabled) {
1610
- this._disabled = disabled;
1611
- if (this._disabled) {
1612
- return this.remove();
1613
- }
1614
- this.save();
1615
- }
1616
- set_cross_subdomain(cross_subdomain) {
1617
- if (cross_subdomain !== this._cross_subdomain) {
1618
- this._cross_subdomain = cross_subdomain;
1619
- this.remove();
1620
- this.save();
1621
- }
1622
- }
1623
- set_secure(secure) {
1624
- if (secure !== this._secure) {
1625
- this._secure = secure;
1626
- this.remove();
1627
- this.save();
1628
- }
1629
- }
1630
- set_event_timer(event_name, timestamp) {
1631
- const timers = this.props[EVENT_TIMERS_KEY] || {};
1632
- timers[event_name] = timestamp;
1633
- this.props[EVENT_TIMERS_KEY] = timers;
1634
- this.save();
1635
- }
1636
- remove_event_timer(event_name) {
1637
- const timers = this.props[EVENT_TIMERS_KEY] || {};
1638
- const timestamp = timers[event_name];
1639
- if (!isUndefined(timestamp)) {
1640
- delete this.props[EVENT_TIMERS_KEY][event_name];
1641
- this.save();
1642
- }
1643
- return timestamp;
1644
- }
1645
- get_property(prop) {
1646
- return this.props[prop];
1647
- }
1648
- set_property(prop, to) {
1649
- this.props[prop] = to;
1650
- this.save();
1651
- }
1652
- }
1653
-
1654
- /*
1655
- * Check whether an element has nodeType Node.ELEMENT_NODE
1656
- * @param {Element} el - element to check
1657
- * @returns {boolean} whether el is of the correct nodeType
1658
- */
1659
- function isElementNode(el) {
1660
- return !!el && el.nodeType === 1; // Node.ELEMENT_NODE - use integer constant for browser portability
1661
- }
1662
- /*
1663
- * Check whether an element is of a given tag type.
1664
- * Due to potential reference discrepancies (such as the webcomponents.js polyfill),
1665
- * we want to match tagNames instead of specific references because something like
1666
- * element === document.body won't always work because element might not be a native
1667
- * element.
1668
- * @param {Element} el - element to check
1669
- * @param {string} tag - tag name (e.g., "div")
1670
- * @returns {boolean} whether el is of the given tag type
1671
- */
1672
- function isTag(el, tag) {
1673
- return !!el && !!el.tagName && el.tagName.toLowerCase() === tag.toLowerCase();
1674
- }
1675
- /*
1676
- * Check whether an element has nodeType Node.TEXT_NODE
1677
- * @param {Element} el - element to check
1678
- * @returns {boolean} whether el is of the correct nodeType
1679
- */
1680
- function isTextNode(el) {
1681
- return !!el && el.nodeType === 3; // Node.TEXT_NODE - use integer constant for browser portability
1682
- }
1683
- /*
1684
- * Check whether an element has nodeType Node.DOCUMENT_FRAGMENT_NODE
1685
- * @param {Element} el - element to check
1686
- * @returns {boolean} whether el is of the correct nodeType
1687
- */
1688
- function isDocumentFragment(el) {
1689
- return !!el && el.nodeType === 11; // Node.DOCUMENT_FRAGMENT_NODE - use integer constant for browser portability
1690
- }
1691
-
1692
- function splitClassString(s) {
1693
- return s ? trim(s).split(/\s+/) : [];
1694
- }
1695
- function checkForURLMatches(urlsList) {
1696
- const url = window?.location.href;
1697
- return !!(url && urlsList && urlsList.some(regex => url.match(regex)));
1698
- }
1699
- /*
1700
- * Get the className of an element, accounting for edge cases where element.className is an object
1701
- *
1702
- * Because this is a string it can contain unexpected characters
1703
- * So, this method safely splits the className and returns that array.
1704
- */
1705
- function getClassNames(el) {
1706
- let className = '';
1707
- switch (typeof el.className) {
1708
- case 'string':
1709
- className = el.className;
1710
- break;
1711
- // TODO: when is this ever used?
1712
- case 'object':
1713
- // handle cases where className might be SVGAnimatedString or some other type
1714
- className = (el.className && 'baseVal' in el.className ? el.className.baseVal : null) || el.getAttribute('class') || '';
1715
- break;
1716
- default:
1717
- className = '';
1718
- }
1719
- return splitClassString(className);
1720
- }
1721
- function makeSafeText(s) {
1722
- if (isNullish(s)) {
1723
- return null;
1724
- }
1725
- return trim(s)
1726
- // scrub potentially sensitive values
1727
- .split(/(\s+)/).filter(s => shouldCaptureValue(s)).join('')
1728
- // normalize whitespace
1729
- .replace(/[\r\n]/g, ' ').replace(/[ ]+/g, ' ')
1730
- // truncate
1731
- .substring(0, 255);
1732
- }
1733
- /*
1734
- * Get the direct text content of an element, protecting against sensitive data collection.
1735
- * Concats textContent of each of the element's text node children; this avoids potential
1736
- * collection of sensitive data that could happen if we used element.textContent and the
1737
- * element had sensitive child elements, since element.textContent includes child content.
1738
- * Scrubs values that look like they could be sensitive (i.e. cc or ssn number).
1739
- * @param {Element} el - element to get the text of
1740
- * @returns {string} the element's direct text content
1741
- */
1742
- function getSafeText(el) {
1743
- let elText = '';
1744
- if (shouldCaptureElement(el) && !isSensitiveElement(el) && el.childNodes && el.childNodes.length) {
1745
- each(el.childNodes, function (child) {
1746
- if (isTextNode(child) && child.textContent) {
1747
- elText += makeSafeText(child.textContent) ?? '';
1748
- }
1749
- });
1750
- }
1751
- return trim(elText);
1752
- }
1753
- function getEventTarget(e) {
1754
- // https://developer.mozilla.org/en-US/docs/Web/API/Event/target#Compatibility_notes
1755
- if (isUndefined(e.target)) {
1756
- return e.srcElement || null;
1757
- } else {
1758
- if (e.target?.shadowRoot) {
1759
- return e.composedPath()[0] || null;
1760
- }
1761
- return e.target || null;
1762
- }
1763
- }
1764
- const autocaptureCompatibleElements = ['a', 'button', 'form', 'input', 'select', 'textarea', 'label'];
1765
- /*
1766
- if there is no config, then all elements are allowed
1767
- if there is a config, and there is an allow list, then only elements in the allow list are allowed
1768
- assumes that some other code is checking this element's parents
1769
- */
1770
- function checkIfElementTreePassesElementAllowList(elements, autocaptureConfig) {
1771
- const allowlist = autocaptureConfig?.element_allowlist;
1772
- if (isUndefined(allowlist)) {
1773
- // everything is allowed, when there is no allow list
1774
- return true;
1775
- }
1776
- // check each element in the tree
1777
- // if any of the elements are in the allow list, then the tree is allowed
1778
- for (const el of elements) {
1779
- if (allowlist.some(elementType => el.tagName.toLowerCase() === elementType)) {
1780
- return true;
1781
- }
1782
- }
1783
- // otherwise there is an allow list and this element tree didn't match it
1784
- return false;
1785
- }
1786
- /*
1787
- if there is no selector list (i.e. it is undefined), then any elements matches
1788
- if there is an empty list, then no elements match
1789
- if there is a selector list, then check it against each element provided
1790
- */
1791
- function checkIfElementsMatchCSSSelector(elements, selectorList) {
1792
- if (isUndefined(selectorList)) {
1793
- // everything is allowed, when there is no selector list
1794
- return true;
1795
- }
1796
- for (const el of elements) {
1797
- if (selectorList.some(selector => el.matches(selector))) {
1798
- return true;
1799
- }
1800
- }
1801
- return false;
1802
- }
1803
- function getParentElement(curEl) {
1804
- const parentNode = curEl.parentNode;
1805
- if (!parentNode || !isElementNode(parentNode)) return false;
1806
- return parentNode;
1807
- }
1808
- // autocapture check will already filter for ph-no-capture,
1809
- // but we include it here to protect against future changes accidentally removing that check
1810
- const DEFAULT_RAGE_CLICK_IGNORE_LIST = ['.ph-no-rageclick', '.ph-no-capture'];
1811
- function shouldCaptureRageclick(el, _config) {
1812
- if (!window || cannotCheckForAutocapture(el)) {
1813
- return false;
1814
- }
1815
- let selectorIgnoreList;
1816
- if (isBoolean(_config)) {
1817
- selectorIgnoreList = _config ? DEFAULT_RAGE_CLICK_IGNORE_LIST : false;
1818
- } else {
1819
- selectorIgnoreList = _config?.css_selector_ignorelist ?? DEFAULT_RAGE_CLICK_IGNORE_LIST;
1820
- }
1821
- if (selectorIgnoreList === false) {
1822
- return false;
1823
- }
1824
- const {
1825
- targetElementList
1826
- } = getElementAndParentsForElement(el, false);
1827
- // we don't capture if we match the ignore list
1828
- return !checkIfElementsMatchCSSSelector(targetElementList, selectorIgnoreList);
1829
- }
1830
- const cannotCheckForAutocapture = el => {
1831
- return !el || isTag(el, 'html') || !isElementNode(el);
1832
- };
1833
- const getElementAndParentsForElement = (el, captureOnAnyElement) => {
1834
- if (!window || cannotCheckForAutocapture(el)) {
1835
- return {
1836
- parentIsUsefulElement: false,
1837
- targetElementList: []
1838
- };
1839
- }
1840
- let parentIsUsefulElement = false;
1841
- const targetElementList = [el];
1842
- let curEl = el;
1843
- while (curEl.parentNode && !isTag(curEl, 'body')) {
1844
- // If element is a shadow root, we skip it
1845
- if (isDocumentFragment(curEl.parentNode)) {
1846
- targetElementList.push(curEl.parentNode.host);
1847
- curEl = curEl.parentNode.host;
1848
- continue;
1849
- }
1850
- const parentNode = getParentElement(curEl);
1851
- if (!parentNode) break;
1852
- if (captureOnAnyElement || autocaptureCompatibleElements.indexOf(parentNode.tagName.toLowerCase()) > -1) {
1853
- parentIsUsefulElement = true;
1854
- } else {
1855
- const compStyles = window.getComputedStyle(parentNode);
1856
- if (compStyles && compStyles.getPropertyValue('cursor') === 'pointer') {
1857
- parentIsUsefulElement = true;
1858
- }
1859
- }
1860
- targetElementList.push(parentNode);
1861
- curEl = parentNode;
1862
- }
1863
- return {
1864
- parentIsUsefulElement,
1865
- targetElementList
1866
- };
1867
- };
1868
- /*
1869
- * Check whether a DOM event should be "captured" or if it may contain sensitive data
1870
- * using a variety of heuristics.
1871
- * @param {Element} el - element to check
1872
- * @param {Event} event - event to check
1873
- * @param {Object} autocaptureConfig - autocapture config
1874
- * @param {boolean} captureOnAnyElement - whether to capture on any element, clipboard autocapture doesn't restrict to "clickable" elements
1875
- * @param {string[]} allowedEventTypes - event types to capture, normally just 'click', but some autocapture types react to different events, some elements have fixed events (e.g., form has "submit")
1876
- * @returns {boolean} whether the event should be captured
1877
- */
1878
- function shouldCaptureDomEvent(el, event, autocaptureConfig = undefined, captureOnAnyElement, allowedEventTypes) {
1879
- if (!window || cannotCheckForAutocapture(el)) {
1880
- return false;
1881
- }
1882
- if (autocaptureConfig?.url_allowlist) {
1883
- // if the current URL is not in the allow list, don't capture
1884
- if (!checkForURLMatches(autocaptureConfig.url_allowlist)) {
1885
- return false;
1886
- }
1887
- }
1888
- if (autocaptureConfig?.url_ignorelist) {
1889
- // if the current URL is in the ignore list, don't capture
1890
- if (checkForURLMatches(autocaptureConfig.url_ignorelist)) {
1891
- return false;
1892
- }
1893
- }
1894
- if (autocaptureConfig?.dom_event_allowlist) {
1895
- const allowlist = autocaptureConfig.dom_event_allowlist;
1896
- if (allowlist && !allowlist.some(eventType => event.type === eventType)) {
1897
- return false;
1898
- }
1899
- }
1900
- const {
1901
- parentIsUsefulElement,
1902
- targetElementList
1903
- } = getElementAndParentsForElement(el, captureOnAnyElement);
1904
- if (!checkIfElementTreePassesElementAllowList(targetElementList, autocaptureConfig)) {
1905
- return false;
1906
- }
1907
- if (!checkIfElementsMatchCSSSelector(targetElementList, autocaptureConfig?.css_selector_allowlist)) {
1908
- return false;
1909
- }
1910
- const compStyles = window.getComputedStyle(el);
1911
- if (compStyles && compStyles.getPropertyValue('cursor') === 'pointer' && event.type === 'click') {
1912
- return true;
1913
- }
1914
- const tag = el.tagName.toLowerCase();
1915
- switch (tag) {
1916
- case 'html':
1917
- return false;
1918
- case 'form':
1919
- return (allowedEventTypes || ['submit']).indexOf(event.type) >= 0;
1920
- case 'input':
1921
- case 'select':
1922
- case 'textarea':
1923
- return (allowedEventTypes || ['change', 'click']).indexOf(event.type) >= 0;
1924
- default:
1925
- if (parentIsUsefulElement) return (allowedEventTypes || ['click']).indexOf(event.type) >= 0;
1926
- return (allowedEventTypes || ['click']).indexOf(event.type) >= 0 && (autocaptureCompatibleElements.indexOf(tag) > -1 || el.getAttribute('contenteditable') === 'true');
1927
- }
1928
- }
1929
- /*
1930
- * Check whether a DOM element should be "captured" or if it may contain sensitive data
1931
- * using a variety of heuristics.
1932
- * @param {Element} el - element to check
1933
- * @returns {boolean} whether the element should be captured
1934
- */
1935
- function shouldCaptureElement(el) {
1936
- for (let curEl = el; curEl.parentNode && !isTag(curEl, 'body'); curEl = curEl.parentNode) {
1937
- const classes = getClassNames(curEl);
1938
- if (includes(classes, 'ph-sensitive') || includes(classes, 'ph-no-capture')) {
1939
- return false;
1940
- }
1941
- }
1942
- if (includes(getClassNames(el), 'ph-include')) {
1943
- return true;
1944
- }
1945
- // don't include hidden or password fields
1946
- const type = el.type || '';
1947
- if (isString(type)) {
1948
- // it's possible for el.type to be a DOM element if el is a form with a child input[name="type"]
1949
- switch (type.toLowerCase()) {
1950
- case 'hidden':
1951
- return false;
1952
- case 'password':
1953
- return false;
1954
- }
1955
- }
1956
- // filter out data from fields that look like sensitive fields
1957
- const name = el.name || el.id || '';
1958
- // See https://github.com/posthog/posthog-js/issues/165
1959
- // Under specific circumstances a bug caused .replace to be called on a DOM element
1960
- // instead of a string, removing the element from the page. Ensure this issue is mitigated.
1961
- if (isString(name)) {
1962
- // it's possible for el.name or el.id to be a DOM element if el is a form with a child input[name="name"]
1963
- const sensitiveNameRegex = /^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i;
1964
- if (sensitiveNameRegex.test(name.replace(/[^a-zA-Z0-9]/g, ''))) {
1965
- return false;
1966
- }
1967
- }
1968
- return true;
1969
- }
1970
- /*
1971
- * Check whether a DOM element is 'sensitive' and we should only capture limited data
1972
- * @param {Element} el - element to check
1973
- * @returns {boolean} whether the element should be captured
1974
- */
1975
- function isSensitiveElement(el) {
1976
- // don't send data from inputs or similar elements since there will always be
1977
- // a risk of clientside javascript placing sensitive data in attributes
1978
- const allowedInputTypes = ['button', 'checkbox', 'submit', 'reset'];
1979
- if (isTag(el, 'input') && !allowedInputTypes.includes(el.type) || isTag(el, 'select') || isTag(el, 'textarea') || el.getAttribute('contenteditable') === 'true') {
1980
- return true;
1981
- }
1982
- return false;
1983
- }
1984
- // Define the core pattern for matching credit card numbers
1985
- const coreCCPattern = `(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})`;
1986
- // Create the Anchored version of the regex by adding '^' at the start and '$' at the end
1987
- const anchoredCCRegex = new RegExp(`^(?:${coreCCPattern})$`);
1988
- // The Unanchored version is essentially the core pattern, usable as is for partial matches
1989
- const unanchoredCCRegex = new RegExp(coreCCPattern);
1990
- // Define the core pattern for matching SSNs with optional dashes
1991
- const coreSSNPattern = `\\d{3}-?\\d{2}-?\\d{4}`;
1992
- // Create the Anchored version of the regex by adding '^' at the start and '$' at the end
1993
- const anchoredSSNRegex = new RegExp(`^(${coreSSNPattern})$`);
1994
- // The Unanchored version is essentially the core pattern itself, usable for partial matches
1995
- const unanchoredSSNRegex = new RegExp(`(${coreSSNPattern})`);
1996
- /*
1997
- * Check whether a string value should be "captured" or if it may contain sensitive data
1998
- * using a variety of heuristics.
1999
- * @param {string} value - string value to check
2000
- * @param {boolean} anchorRegexes - whether to anchor the regexes to the start and end of the string
2001
- * @returns {boolean} whether the element should be captured
2002
- */
2003
- function shouldCaptureValue(value, anchorRegexes = true) {
2004
- if (isNullish(value)) {
2005
- return false;
2006
- }
2007
- if (isString(value)) {
2008
- value = trim(value);
2009
- // check to see if input value looks like a credit card number
2010
- // see: https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s20.html
2011
- const ccRegex = anchorRegexes ? anchoredCCRegex : unanchoredCCRegex;
2012
- if (ccRegex.test((value || '').replace(/[- ]/g, ''))) {
2013
- return false;
2014
- }
2015
- // check to see if input value looks like a social security number
2016
- const ssnRegex = anchorRegexes ? anchoredSSNRegex : unanchoredSSNRegex;
2017
- if (ssnRegex.test(value)) {
2018
- return false;
2019
- }
2020
- }
2021
- return true;
2022
- }
2023
- /*
2024
- * Check whether an attribute name is an Angular style attr (either _ngcontent or _nghost)
2025
- * These update on each build and lead to noise in the element chain
2026
- * More details on the attributes here: https://angular.io/guide/view-encapsulation
2027
- * @param {string} attributeName - string value to check
2028
- * @returns {boolean} whether the element is an angular tag
2029
- */
2030
- function isAngularStyleAttr(attributeName) {
2031
- if (isString(attributeName)) {
2032
- return attributeName.substring(0, 10) === '_ngcontent' || attributeName.substring(0, 7) === '_nghost';
2033
- }
2034
- return false;
2035
- }
2036
- /*
2037
- * Iterate through children of a target element looking for span tags
2038
- * and return the text content of the span tags, separated by spaces,
2039
- * along with the direct text content of the target element
2040
- * @param {Element} target - element to check
2041
- * @returns {string} text content of the target element and its child span tags
2042
- */
2043
- function getDirectAndNestedSpanText(target) {
2044
- let text = getSafeText(target);
2045
- text = `${text} ${getNestedSpanText(target)}`.trim();
2046
- return shouldCaptureValue(text) ? text : '';
2047
- }
2048
- /*
2049
- * Iterate through children of a target element looking for span tags
2050
- * and return the text content of the span tags, separated by spaces
2051
- * @param {Element} target - element to check
2052
- * @returns {string} text content of span tags
2053
- */
2054
- function getNestedSpanText(target) {
2055
- let text = '';
2056
- if (target && target.childNodes && target.childNodes.length) {
2057
- each(target.childNodes, function (child) {
2058
- if (child && child.tagName?.toLowerCase() === 'span') {
2059
- try {
2060
- const spanText = getSafeText(child);
2061
- text = `${text} ${spanText}`.trim();
2062
- if (child.childNodes && child.childNodes.length) {
2063
- text = `${text} ${getNestedSpanText(child)}`.trim();
2064
- }
2065
- } catch (e) {
2066
- logger.error('[AutoCapture]', e);
2067
- }
2068
- }
2069
- });
2070
- }
2071
- return text;
2072
- }
2073
- /*
2074
- Back in the day storing events in Postgres we use Elements for autocapture events.
2075
- Now we're using elements_chain. We used to do this parsing/processing during ingestion.
2076
- This code is just copied over from ingestion, but we should optimize it
2077
- to create elements_chain string directly.
2078
- */
2079
- function getElementsChainString(elements) {
2080
- return elementsToString(extractElements(elements));
2081
- }
2082
- function escapeQuotes(input) {
2083
- return input.replace(/"|\\"/g, '\\"');
2084
- }
2085
- function elementsToString(elements) {
2086
- const ret = elements.map(element => {
2087
- let el_string = '';
2088
- if (element.tag_name) {
2089
- el_string += element.tag_name;
2090
- }
2091
- if (element.attr_class) {
2092
- element.attr_class.sort();
2093
- for (const single_class of element.attr_class) {
2094
- el_string += `.${single_class.replace(/"/g, '')}`;
2095
- }
2096
- }
2097
- const attributes = {
2098
- ...(element.text ? {
2099
- text: element.text
2100
- } : {}),
2101
- 'nth-child': element.nth_child ?? 0,
2102
- 'nth-of-type': element.nth_of_type ?? 0,
2103
- ...(element.href ? {
2104
- href: element.href
2105
- } : {}),
2106
- ...(element.attr_id ? {
2107
- attr_id: element.attr_id
2108
- } : {}),
2109
- ...element.attributes
2110
- };
2111
- const sortedAttributes = {};
2112
- entries(attributes).sort(([a], [b]) => a.localeCompare(b)).forEach(([key, value]) => sortedAttributes[escapeQuotes(key.toString())] = escapeQuotes(value.toString()));
2113
- el_string += ':';
2114
- el_string += entries(sortedAttributes).map(([key, value]) => `${key}="${value}"`).join('');
2115
- return el_string;
2116
- });
2117
- return ret.join(';');
2118
- }
2119
- function extractElements(elements) {
2120
- return elements.map(el => {
2121
- const response = {
2122
- text: el['$el_text']?.slice(0, 400),
2123
- tag_name: el['tag_name'],
2124
- href: el['attr__href']?.slice(0, 2048),
2125
- attr_class: extractAttrClass(el),
2126
- attr_id: el['attr__id'],
2127
- nth_child: el['nth_child'],
2128
- nth_of_type: el['nth_of_type'],
2129
- attributes: {}
2130
- };
2131
- entries(el).filter(([key]) => key.indexOf('attr__') === 0).forEach(([key, value]) => response.attributes[key] = value);
2132
- return response;
2133
- });
2134
- }
2135
- function extractAttrClass(el) {
2136
- const attr_class = el['attr__class'];
2137
- if (!attr_class) {
2138
- return undefined;
2139
- } else if (isArray(attr_class)) {
2140
- return attr_class;
2141
- } else {
2142
- return splitClassString(attr_class);
2143
- }
2144
- }
2145
-
2146
- // Naive rage click implementation: If mouse has not moved further than RAGE_CLICK_THRESHOLD_PX
2147
- // over RAGE_CLICK_CLICK_COUNT clicks with max RAGE_CLICK_TIMEOUT_MS between clicks, it's
2148
- // counted as a rage click
2149
- const RAGE_CLICK_THRESHOLD_PX = 30;
2150
- const RAGE_CLICK_TIMEOUT_MS = 1000;
2151
- const RAGE_CLICK_CLICK_COUNT = 3;
2152
- class RageClick {
2153
- constructor() {
2154
- this.clicks = [];
2155
- }
2156
- isRageClick(x, y, timestamp) {
2157
- const lastClick = this.clicks[this.clicks.length - 1];
2158
- if (lastClick && Math.abs(x - lastClick.x) + Math.abs(y - lastClick.y) < RAGE_CLICK_THRESHOLD_PX && timestamp - lastClick.timestamp < RAGE_CLICK_TIMEOUT_MS) {
2159
- this.clicks.push({
2160
- x,
2161
- y,
2162
- timestamp
2163
- });
2164
- if (this.clicks.length === RAGE_CLICK_CLICK_COUNT) {
2165
- return true;
2166
- }
2167
- } else {
2168
- this.clicks = [{
2169
- x,
2170
- y,
2171
- timestamp
2172
- }];
2173
- }
2174
- return false;
2175
- }
2176
- }
2177
-
2178
- const COPY_AUTOCAPTURE_EVENT = '$copy_autocapture';
2179
- var Compression;
2180
- (function (Compression) {
2181
- Compression["GZipJS"] = "gzip-js";
2182
- Compression["Base64"] = "base64";
2183
- })(Compression || (Compression = {}));
2184
-
2185
- function limitText(length, text) {
2186
- if (text.length > length) {
2187
- return text.slice(0, length) + '...';
2188
- }
2189
- return text;
2190
- }
2191
- function getAugmentPropertiesFromElement(elem) {
2192
- const shouldCaptureEl = shouldCaptureElement(elem);
2193
- if (!shouldCaptureEl) {
2194
- return {};
2195
- }
2196
- const props = {};
2197
- each(elem.attributes, function (attr) {
2198
- if (attr.name && attr.name.indexOf('data-ph-capture-attribute') === 0) {
2199
- const propertyKey = attr.name.replace('data-ph-capture-attribute-', '');
2200
- const propertyValue = attr.value;
2201
- if (propertyKey && propertyValue && shouldCaptureValue(propertyValue)) {
2202
- props[propertyKey] = propertyValue;
2203
- }
2204
- }
2205
- });
2206
- return props;
2207
- }
2208
- function previousElementSibling(el) {
2209
- if (el.previousElementSibling) {
2210
- return el.previousElementSibling;
2211
- }
2212
- let _el = el;
2213
- do {
2214
- _el = _el.previousSibling; // resolves to ChildNode->Node, which is Element's parent class
2215
- } while (_el && !isElementNode(_el));
2216
- return _el;
2217
- }
2218
- function getDefaultProperties(eventType) {
2219
- return {
2220
- $event_type: eventType,
2221
- $ce_version: 1
2222
- };
2223
- }
2224
- function getPropertiesFromElement(elem, maskAllAttributes, maskText, elementAttributeIgnorelist) {
2225
- const tag_name = elem.tagName.toLowerCase();
2226
- const props = {
2227
- tag_name: tag_name
2228
- };
2229
- if (autocaptureCompatibleElements.indexOf(tag_name) > -1 && !maskText) {
2230
- if (tag_name.toLowerCase() === 'a' || tag_name.toLowerCase() === 'button') {
2231
- props['$el_text'] = limitText(1024, getDirectAndNestedSpanText(elem));
2232
- } else {
2233
- props['$el_text'] = limitText(1024, getSafeText(elem));
2234
- }
2235
- }
2236
- const classes = getClassNames(elem);
2237
- if (classes.length > 0) props['classes'] = classes.filter(function (c) {
2238
- return c !== '';
2239
- });
2240
- // capture the deny list here because this not-a-class class makes it tricky to use this.config in the function below
2241
- each(elem.attributes, function (attr) {
2242
- // Only capture attributes we know are safe
2243
- if (isSensitiveElement(elem) && ['name', 'id', 'class', 'aria-label'].indexOf(attr.name) === -1) return;
2244
- if (elementAttributeIgnorelist?.includes(attr.name)) return;
2245
- if (!maskAllAttributes && shouldCaptureValue(attr.value) && !isAngularStyleAttr(attr.name)) {
2246
- let value = attr.value;
2247
- if (attr.name === 'class') {
2248
- // html attributes can _technically_ contain linebreaks,
2249
- // but we're very intolerant of them in the class string,
2250
- // so we strip them.
2251
- value = splitClassString(value).join(' ');
2252
- }
2253
- props['attr__' + attr.name] = limitText(1024, value);
2254
- }
2255
- });
2256
- let nthChild = 1;
2257
- let nthOfType = 1;
2258
- let currentElem = elem;
2259
- while (currentElem = previousElementSibling(currentElem)) {
2260
- // eslint-disable-line no-cond-assign
2261
- nthChild++;
2262
- if (currentElem.tagName === elem.tagName) {
2263
- nthOfType++;
2264
- }
2265
- }
2266
- props['nth_child'] = nthChild;
2267
- props['nth_of_type'] = nthOfType;
2268
- return props;
2269
- }
2270
- function autocapturePropertiesForElement(target, {
2271
- e,
2272
- maskAllElementAttributes,
2273
- maskAllText,
2274
- elementAttributeIgnoreList,
2275
- elementsChainAsString
2276
- }) {
2277
- const targetElementList = [target];
2278
- let curEl = target;
2279
- while (curEl.parentNode && !isTag(curEl, 'body')) {
2280
- if (isDocumentFragment(curEl.parentNode)) {
2281
- targetElementList.push(curEl.parentNode.host);
2282
- curEl = curEl.parentNode.host;
2283
- continue;
2284
- }
2285
- targetElementList.push(curEl.parentNode);
2286
- curEl = curEl.parentNode;
2287
- }
2288
- const elementsJson = [];
2289
- const autocaptureAugmentProperties = {};
2290
- let href = false;
2291
- let explicitNoCapture = false;
2292
- each(targetElementList, el => {
2293
- const shouldCaptureEl = shouldCaptureElement(el);
2294
- // if the element or a parent element is an anchor tag
2295
- // include the href as a property
2296
- if (el.tagName.toLowerCase() === 'a') {
2297
- href = el.getAttribute('href');
2298
- href = shouldCaptureEl && href && shouldCaptureValue(href) && href;
2299
- }
2300
- // allow users to programmatically prevent capturing of elements by adding class 'ph-no-capture'
2301
- const classes = getClassNames(el);
2302
- if (includes(classes, 'ph-no-capture')) {
2303
- explicitNoCapture = true;
2304
- }
2305
- elementsJson.push(getPropertiesFromElement(el, maskAllElementAttributes, maskAllText, elementAttributeIgnoreList));
2306
- const augmentProperties = getAugmentPropertiesFromElement(el);
2307
- extend(autocaptureAugmentProperties, augmentProperties);
2308
- });
2309
- if (explicitNoCapture) {
2310
- return {
2311
- props: {},
2312
- explicitNoCapture
2313
- };
2314
- }
2315
- if (!maskAllText) {
2316
- // if the element is a button or anchor tag get the span text from any
2317
- // children and include it as/with the text property on the parent element
2318
- if (target.tagName.toLowerCase() === 'a' || target.tagName.toLowerCase() === 'button') {
2319
- elementsJson[0]['$el_text'] = getDirectAndNestedSpanText(target);
2320
- } else {
2321
- elementsJson[0]['$el_text'] = getSafeText(target);
2322
- }
2323
- }
2324
- let externalHref;
2325
- if (href) {
2326
- elementsJson[0]['attr__href'] = href;
2327
- const hrefHost = convertToURL(href)?.host;
2328
- const locationHost = win?.location?.host;
2329
- if (hrefHost && locationHost && hrefHost !== locationHost) {
2330
- externalHref = href;
2331
- }
2332
- }
2333
- const props = extend(getDefaultProperties(e.type),
2334
- // Sending "$elements" is deprecated. Only one client on US cloud uses this.
2335
- !elementsChainAsString ? {
2336
- $elements: elementsJson
2337
- } : {},
2338
- // Always send $elements_chain, as it's needed downstream in site app filtering
2339
- {
2340
- $elements_chain: getElementsChainString(elementsJson)
2341
- }, elementsJson[0]?.['$el_text'] ? {
2342
- $el_text: elementsJson[0]?.['$el_text']
2343
- } : {}, externalHref && e.type === 'click' ? {
2344
- $external_click_url: externalHref
2345
- } : {}, autocaptureAugmentProperties);
2346
- return {
2347
- props
2348
- };
2349
- }
2350
- class Autocapture {
2351
- constructor(instance) {
2352
- this._initialized = false;
2353
- this._isDisabledServerSide = null;
2354
- this.rageclicks = new RageClick();
2355
- this._elementsChainAsString = false;
2356
- this.instance = instance;
2357
- this._elementSelectors = null;
2358
- }
2359
- get _config() {
2360
- const config = isObject(this.instance.config.autocapture) ? this.instance.config.autocapture : {};
2361
- // precompile the regex
2362
- config.url_allowlist = config.url_allowlist?.map(url => new RegExp(url));
2363
- config.url_ignorelist = config.url_ignorelist?.map(url => new RegExp(url));
2364
- return config;
2365
- }
2366
- _addDomEventHandlers() {
2367
- if (!this.isBrowserSupported()) {
2368
- logger.info('Disabling Automatic Event Collection because this browser is not supported');
2369
- return;
2370
- }
2371
- if (!win || !document) {
2372
- return;
2373
- }
2374
- const handler = e => {
2375
- e = e || win?.event;
2376
- try {
2377
- this._captureEvent(e);
2378
- } catch (error) {
2379
- logger.error('Failed to capture event', error);
2380
- }
2381
- };
2382
- addEventListener(document, 'submit', handler, {
2383
- capture: true
2384
- });
2385
- addEventListener(document, 'change', handler, {
2386
- capture: true
2387
- });
2388
- addEventListener(document, 'click', handler, {
2389
- capture: true
2390
- });
2391
- if (this._config.capture_copied_text) {
2392
- const copiedTextHandler = e => {
2393
- e = e || win?.event;
2394
- this._captureEvent(e, COPY_AUTOCAPTURE_EVENT);
2395
- };
2396
- addEventListener(document, 'copy', copiedTextHandler, {
2397
- capture: true
2398
- });
2399
- addEventListener(document, 'cut', copiedTextHandler, {
2400
- capture: true
2401
- });
2402
- }
2403
- }
2404
- startIfEnabled() {
2405
- if (this.isEnabled && !this._initialized) {
2406
- this._addDomEventHandlers();
2407
- this._initialized = true;
2408
- }
2409
- }
2410
- onRemoteConfig(response) {
2411
- if (response.elementsChainAsString) {
2412
- this._elementsChainAsString = response.elementsChainAsString;
2413
- }
2414
- if (this.instance.persistence) {
2415
- this.instance.persistence.register({
2416
- [AUTOCAPTURE_DISABLED_SERVER_SIDE]: !!response['autocapture_opt_out']
2417
- });
2418
- }
2419
- this._isDisabledServerSide = !!response['autocapture_opt_out'];
2420
- this.startIfEnabled();
2421
- }
2422
- setElementSelectors(selectors) {
2423
- this._elementSelectors = selectors;
2424
- }
2425
- getElementSelectors(element) {
2426
- const elementSelectors = [];
2427
- this._elementSelectors?.forEach(selector => {
2428
- const matchedElements = document?.querySelectorAll(selector);
2429
- matchedElements?.forEach(matchedElement => {
2430
- if (element === matchedElement) {
2431
- elementSelectors.push(selector);
2432
- }
2433
- });
2434
- });
2435
- return elementSelectors;
2436
- }
2437
- get isEnabled() {
2438
- const persistedServerDisabled = this.instance.persistence?.props[AUTOCAPTURE_DISABLED_SERVER_SIDE];
2439
- const memoryDisabled = this._isDisabledServerSide;
2440
- if (isNull(memoryDisabled) && !isBoolean(persistedServerDisabled)) {
2441
- return false;
2442
- }
2443
- const disabledServer = this._isDisabledServerSide ?? !!persistedServerDisabled;
2444
- const disabledClient = !this.instance.config.autocapture;
2445
- return !disabledClient && !disabledServer;
2446
- }
2447
- _captureEvent(e, eventName = '$autocapture') {
2448
- if (!this.isEnabled) {
2449
- return;
2450
- }
2451
- /*** Don't mess with this code without running IE8 tests on it ***/
2452
- let target = getEventTarget(e);
2453
- if (isTextNode(target)) {
2454
- // defeat Safari bug (see: http://www.quirksmode.org/js/events_properties.html)
2455
- target = target.parentNode || null;
2456
- }
2457
- if (eventName === '$autocapture' && e.type === 'click' && e instanceof MouseEvent) {
2458
- if (!!this.instance.config.rageclick && this.rageclicks?.isRageClick(e.clientX, e.clientY, new Date().getTime())) {
2459
- if (shouldCaptureRageclick(target, this.instance.config.rageclick)) {
2460
- this._captureEvent(e, '$rageclick');
2461
- }
2462
- }
2463
- }
2464
- const isCopyAutocapture = eventName === COPY_AUTOCAPTURE_EVENT;
2465
- if (target && shouldCaptureDomEvent(target, e, this._config,
2466
- // mostly this method cares about the target element, but in the case of copy events,
2467
- // we want some of the work this check does without insisting on the target element's type
2468
- isCopyAutocapture,
2469
- // we also don't want to restrict copy checks to clicks,
2470
- // so we pass that knowledge in here, rather than add the logic inside the check
2471
- isCopyAutocapture ? ['copy', 'cut'] : undefined)) {
2472
- const {
2473
- props,
2474
- explicitNoCapture
2475
- } = autocapturePropertiesForElement(target, {
2476
- e,
2477
- maskAllElementAttributes: this.instance.config.mask_all_element_attributes,
2478
- maskAllText: this.instance.config.mask_all_text,
2479
- elementAttributeIgnoreList: this._config.element_attribute_ignorelist,
2480
- elementsChainAsString: this._elementsChainAsString
2481
- });
2482
- if (explicitNoCapture) {
2483
- return false;
2484
- }
2485
- const elementSelectors = this.getElementSelectors(target);
2486
- if (elementSelectors && elementSelectors.length > 0) {
2487
- props['$element_selectors'] = elementSelectors;
2488
- }
2489
- if (eventName === COPY_AUTOCAPTURE_EVENT) {
2490
- // you can't read the data from the clipboard event,
2491
- // but you can guess that you can read it from the window's current selection
2492
- const selectedContent = makeSafeText(win?.getSelection()?.toString());
2493
- const clipType = e.type || 'clipboard';
2494
- if (!selectedContent) {
2495
- return false;
2496
- }
2497
- props['$selected_content'] = selectedContent;
2498
- props['$copy_type'] = clipType;
2499
- }
2500
- this.instance.capture(eventName, props);
2501
- return true;
2502
- }
2503
- }
2504
- isBrowserSupported() {
2505
- return isFunction(document?.querySelectorAll);
2506
- }
2507
- }
2508
-
2509
- // This keeps track of the PageView state (such as the previous PageView's path, timestamp, id, and scroll properties).
2510
- // We store the state in memory, which means that for non-SPA sites, the state will be lost on page reload. This means
2511
- // that non-SPA sites should always send a $pageleave event on any navigation, before the page unloads. For SPA sites,
2512
- // they only need to send a $pageleave event when the user navigates away from the site, as the information is not lost
2513
- // on an internal navigation, and is included as the $prev_pageview_ properties in the next $pageview event.
2514
- // Practically, this means that to find the scroll properties for a given pageview, you need to find the event where
2515
- // event name is $pageview or $pageleave and where $prev_pageview_id matches the original pageview event's id.
2516
- class PageViewManager {
2517
- constructor(instance) {
2518
- this._instance = instance;
2519
- }
2520
- doPageView(timestamp, pageViewId) {
2521
- const response = this._previousPageViewProperties(timestamp, pageViewId);
2522
- // On a pageview we reset the contexts
2523
- this._currentPageview = {
2524
- pathname: win?.location.pathname ?? '',
2525
- pageViewId,
2526
- timestamp
2527
- };
2528
- this._instance.scrollManager.resetContext();
2529
- return response;
2530
- }
2531
- doPageLeave(timestamp) {
2532
- return this._previousPageViewProperties(timestamp, this._currentPageview?.pageViewId);
2533
- }
2534
- doEvent() {
2535
- return {
2536
- $pageview_id: this._currentPageview?.pageViewId
2537
- };
2538
- }
2539
- _previousPageViewProperties(timestamp, pageviewId) {
2540
- const previousPageView = this._currentPageview;
2541
- if (!previousPageView) {
2542
- return {
2543
- $pageview_id: pageviewId
2544
- };
2545
- }
2546
- let properties = {
2547
- $pageview_id: pageviewId,
2548
- $prev_pageview_id: previousPageView.pageViewId
2549
- };
2550
- const scrollContext = this._instance.scrollManager.getContext();
2551
- if (scrollContext && !this._instance.config.disable_scroll_properties) {
2552
- let {
2553
- maxScrollHeight,
2554
- lastScrollY,
2555
- maxScrollY,
2556
- maxContentHeight,
2557
- lastContentY,
2558
- maxContentY
2559
- } = scrollContext;
2560
- if (!isUndefined(maxScrollHeight) && !isUndefined(lastScrollY) && !isUndefined(maxScrollY) && !isUndefined(maxContentHeight) && !isUndefined(lastContentY) && !isUndefined(maxContentY)) {
2561
- // Use ceil, so that e.g. scrolling 999.5px of a 1000px page is considered 100% scrolled
2562
- maxScrollHeight = Math.ceil(maxScrollHeight);
2563
- lastScrollY = Math.ceil(lastScrollY);
2564
- maxScrollY = Math.ceil(maxScrollY);
2565
- maxContentHeight = Math.ceil(maxContentHeight);
2566
- lastContentY = Math.ceil(lastContentY);
2567
- maxContentY = Math.ceil(maxContentY);
2568
- // if the maximum scroll height is near 0, then the percentage is 1
2569
- const lastScrollPercentage = maxScrollHeight <= 1 ? 1 : clampToRange(lastScrollY / maxScrollHeight, 0, 1, logger);
2570
- const maxScrollPercentage = maxScrollHeight <= 1 ? 1 : clampToRange(maxScrollY / maxScrollHeight, 0, 1, logger);
2571
- const lastContentPercentage = maxContentHeight <= 1 ? 1 : clampToRange(lastContentY / maxContentHeight, 0, 1, logger);
2572
- const maxContentPercentage = maxContentHeight <= 1 ? 1 : clampToRange(maxContentY / maxContentHeight, 0, 1, logger);
2573
- properties = extend(properties, {
2574
- $prev_pageview_last_scroll: lastScrollY,
2575
- $prev_pageview_last_scroll_percentage: lastScrollPercentage,
2576
- $prev_pageview_max_scroll: maxScrollY,
2577
- $prev_pageview_max_scroll_percentage: maxScrollPercentage,
2578
- $prev_pageview_last_content: lastContentY,
2579
- $prev_pageview_last_content_percentage: lastContentPercentage,
2580
- $prev_pageview_max_content: maxContentY,
2581
- $prev_pageview_max_content_percentage: maxContentPercentage
2582
- });
2583
- }
2584
- }
2585
- if (previousPageView.pathname) {
2586
- properties.$prev_pageview_pathname = previousPageView.pathname;
2587
- }
2588
- if (previousPageView.timestamp) {
2589
- // Use seconds, for consistency with our other duration-related properties like $duration
2590
- properties.$prev_pageview_duration = (timestamp.getTime() - previousPageView.timestamp.getTime()) / 1000;
2591
- }
2592
- return properties;
2593
- }
2594
- }
2595
-
2596
- // This class is responsible for tracking scroll events and maintaining the scroll context
2597
- class ScrollManager {
2598
- constructor(_instance) {
2599
- this._instance = _instance;
2600
- this._updateScrollData = () => {
2601
- if (!this._context) {
2602
- this._context = {};
2603
- }
2604
- const el = this.scrollElement();
2605
- const scrollY = this.scrollY();
2606
- const scrollHeight = el ? Math.max(0, el.scrollHeight - el.clientHeight) : 0;
2607
- const contentY = scrollY + (el?.clientHeight || 0);
2608
- const contentHeight = el?.scrollHeight || 0;
2609
- this._context.lastScrollY = Math.ceil(scrollY);
2610
- this._context.maxScrollY = Math.max(scrollY, this._context.maxScrollY ?? 0);
2611
- this._context.maxScrollHeight = Math.max(scrollHeight, this._context.maxScrollHeight ?? 0);
2612
- this._context.lastContentY = contentY;
2613
- this._context.maxContentY = Math.max(contentY, this._context.maxContentY ?? 0);
2614
- this._context.maxContentHeight = Math.max(contentHeight, this._context.maxContentHeight ?? 0);
2615
- };
2616
- }
2617
- getContext() {
2618
- return this._context;
2619
- }
2620
- resetContext() {
2621
- const ctx = this._context;
2622
- // update the scroll properties for the new page, but wait until the next tick
2623
- // of the event loop
2624
- setTimeout(this._updateScrollData, 0);
2625
- return ctx;
2626
- }
2627
- // `capture: true` is required to get scroll events for other scrollable elements
2628
- // on the page, not just the window
2629
- // see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#usecapture
2630
- startMeasuringScrollPosition() {
2631
- addEventListener(win, 'scroll', this._updateScrollData, {
2632
- capture: true
2633
- });
2634
- addEventListener(win, 'scrollend', this._updateScrollData, {
2635
- capture: true
2636
- });
2637
- addEventListener(win, 'resize', this._updateScrollData);
2638
- }
2639
- scrollElement() {
2640
- if (this._instance.config.scroll_root_selector) {
2641
- const selectors = isArray(this._instance.config.scroll_root_selector) ? this._instance.config.scroll_root_selector : [this._instance.config.scroll_root_selector];
2642
- for (const selector of selectors) {
2643
- const element = win?.document.querySelector(selector);
2644
- if (element) {
2645
- return element;
2646
- }
2647
- }
2648
- return undefined;
2649
- } else {
2650
- return win?.document.documentElement;
2651
- }
2652
- }
2653
- scrollY() {
2654
- if (this._instance.config.scroll_root_selector) {
2655
- const element = this.scrollElement();
2656
- return element && element.scrollTop || 0;
2657
- } else {
2658
- return win ? win.scrollY || win.pageYOffset || win.document.documentElement.scrollTop || 0 : 0;
2659
- }
2660
- }
2661
- scrollX() {
2662
- if (this._instance.config.scroll_root_selector) {
2663
- const element = this.scrollElement();
2664
- return element && element.scrollLeft || 0;
2665
- } else {
2666
- return win ? win.scrollX || win.pageXOffset || win.document.documentElement.scrollLeft || 0 : 0;
2667
- }
2668
- }
2669
- }
2670
-
2671
- const DEFAULT_BLOCKED_UA_STRS = [
2672
- // Random assortment of bots
2673
- 'amazonbot', 'amazonproductbot', 'app.hypefactors.com',
2674
- // Buck, but "buck" is too short to be safe to block (https://app.hypefactors.com/media-monitoring/about.htm)
2675
- 'applebot', 'archive.org_bot', 'awariobot', 'backlinksextendedbot', 'baiduspider', 'bingbot', 'bingpreview', 'chrome-lighthouse', 'dataforseobot', 'deepscan', 'duckduckbot', 'facebookexternal', 'facebookcatalog', 'http://yandex.com/bots', 'hubspot', 'ia_archiver', 'leikibot', 'linkedinbot', 'meta-externalagent', 'mj12bot', 'msnbot', 'nessus', 'petalbot', 'pinterest', 'prerender', 'rogerbot', 'screaming frog', 'sebot-wa', 'sitebulb', 'slackbot', 'slurp', 'trendictionbot', 'turnitin', 'twitterbot', 'vercel-screenshot', 'vercelbot', 'yahoo! slurp', 'yandexbot', 'zoombot',
2676
- // Bot-like words, maybe we should block `bot` entirely?
2677
- 'bot.htm', 'bot.php', '(bot;', 'bot/', 'crawler',
2678
- // Ahrefs: https://ahrefs.com/seo/glossary/ahrefsbot
2679
- 'ahrefsbot', 'ahrefssiteaudit',
2680
- // Semrush bots: https://www.semrush.com/bot/
2681
- 'semrushbot', 'siteauditbot', 'splitsignalbot',
2682
- // AI Crawlers
2683
- 'gptbot', 'oai-searchbot', 'chatgpt-user', 'perplexitybot',
2684
- // Uptime-like stuff
2685
- 'better uptime bot', 'sentryuptimebot', 'uptimerobot',
2686
- // headless browsers
2687
- 'headlesschrome', 'cypress',
2688
- // we don't block electron here, as many customers use posthog-js in electron apps
2689
- // a whole bunch of goog-specific crawlers
2690
- // https://developers.google.com/search/docs/advanced/crawling/overview-google-crawlers
2691
- 'google-hoteladsverifier', 'adsbot-google', 'apis-google', 'duplexweb-google', 'feedfetcher-google', 'google favicon', 'google web preview', 'google-read-aloud', 'googlebot', 'googleother', 'google-cloudvertexbot', 'googleweblight', 'mediapartners-google', 'storebot-google', 'google-inspectiontool', 'bytespider'];
2692
- /**
2693
- * Block various web spiders from executing our JS and sending false capturing data
2694
- */
2695
- const isBlockedUA = function (ua, customBlockedUserAgents) {
2696
- if (!ua) {
2697
- return false;
2698
- }
2699
- const uaLower = ua.toLowerCase();
2700
- return DEFAULT_BLOCKED_UA_STRS.concat(customBlockedUserAgents || []).some(blockedUA => {
2701
- const blockedUaLower = blockedUA.toLowerCase();
2702
- // can't use includes because IE 11 :/
2703
- return uaLower.indexOf(blockedUaLower) !== -1;
2704
- });
2705
- };
2706
- const isLikelyBot = function (navigator, customBlockedUserAgents) {
2707
- if (!navigator) {
2708
- return false;
2709
- }
2710
- const ua = navigator.userAgent;
2711
- if (ua) {
2712
- if (isBlockedUA(ua, customBlockedUserAgents)) {
2713
- return true;
2714
- }
2715
- }
2716
- try {
2717
- // eslint-disable-next-line compat/compat
2718
- const uaData = navigator?.userAgentData;
2719
- if (uaData?.brands && uaData.brands.some(brandObj => isBlockedUA(brandObj?.brand, customBlockedUserAgents))) {
2720
- return true;
2721
- }
2722
- } catch {
2723
- // ignore the error, we were using experimental browser features
2724
- }
2725
- return !!navigator.webdriver;
2726
- // There's some more enhancements we could make in this area, e.g. it's possible to check if Chrome dev tools are
2727
- // open, which will detect some bots that are trying to mask themselves and might get past the checks above.
2728
- // However, this would give false positives for actual humans who have dev tools open.
2729
- // We could also use the data in navigator.userAgentData.getHighEntropyValues() to detect bots, but we should wait
2730
- // until this stops being experimental. The MDN docs imply that this might eventually require user permission.
2731
- // See https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData/getHighEntropyValues
2732
- // It would be very bad if posthog-js caused a permission prompt to appear on every page load.
2733
- };
2734
-
2735
- const defaultConfig = () => ({
2736
- host: 'https://i.leanbase.co',
2737
- token: '',
2738
- autocapture: true,
2739
- rageclick: true,
2740
- persistence: 'localStorage+cookie',
2741
- capture_pageview: 'history_change',
2742
- capture_pageleave: 'if_capture_pageview',
2743
- persistence_name: '',
2744
- mask_all_element_attributes: false,
2745
- cookie_expiration: 365,
2746
- cross_subdomain_cookie: isCrossDomainCookie(document?.location),
2747
- custom_campaign_params: [],
2748
- custom_personal_data_properties: [],
2749
- disable_persistence: false,
2750
- mask_personal_data_properties: false,
2751
- secure_cookie: window?.location?.protocol === 'https:',
2752
- mask_all_text: false,
2753
- bootstrap: {},
2754
- session_idle_timeout_seconds: 30 * 60,
2755
- save_campaign_params: true,
2756
- save_referrer: true,
2757
- opt_out_useragent_filter: false,
2758
- properties_string_max_length: 65535,
2759
- loaded: () => {}
2760
- });
2761
- class Leanbase extends PostHogCore {
2762
- constructor(token, config) {
2763
- const mergedConfig = extend(defaultConfig(), config || {}, {
2764
- token
2765
- });
2766
- super(token, mergedConfig);
2767
- this.personProcessingSetOncePropertiesSent = false;
2768
- this.isLoaded = false;
2769
- this.config = mergedConfig;
2770
- this.visibilityStateListener = null;
2771
- this.initialPageviewCaptured = false;
2772
- this.scrollManager = new ScrollManager(this);
2773
- this.pageViewManager = new PageViewManager(this);
2774
- this.init(token, mergedConfig);
2775
- }
2776
- init(token, config) {
2777
- this.setConfig(extend(defaultConfig(), config, {
2778
- token
2779
- }));
2780
- this.isLoaded = true;
2781
- this.persistence = new LeanbasePersistence(this.config);
2782
- this.replayAutocapture = new Autocapture(this);
2783
- this.replayAutocapture.startIfEnabled();
2784
- if (this.config.preloadFeatureFlags !== false) {
2785
- this.reloadFeatureFlags();
2786
- }
2787
- this.config.loaded?.(this);
2788
- if (this.config.capture_pageview) {
2789
- setTimeout(() => {
2790
- if (this.config.cookieless_mode === 'always') {
2791
- this.captureInitialPageview();
2792
- }
2793
- }, 1);
2794
- }
2795
- addEventListener(document, 'DOMContentLoaded', () => {
2796
- this.loadRemoteConfig();
2797
- });
2798
- addEventListener(window, 'onpagehide' in self ? 'pagehide' : 'unload', this.capturePageLeave.bind(this), {
2799
- passive: false
2800
- });
2801
- }
2802
- captureInitialPageview() {
2803
- if (!document) {
2804
- return;
2805
- }
2806
- if (document.visibilityState !== 'visible') {
2807
- if (!this.visibilityStateListener) {
2808
- this.visibilityStateListener = this.captureInitialPageview.bind(this);
2809
- addEventListener(document, 'visibilitychange', this.visibilityStateListener);
2810
- }
2811
- return;
2812
- }
2813
- if (!this.initialPageviewCaptured) {
2814
- this.initialPageviewCaptured = true;
2815
- this.capture('$pageview', {
2816
- title: document.title
2817
- });
2818
- if (this.visibilityStateListener) {
2819
- document.removeEventListener('visibilitychange', this.visibilityStateListener);
2820
- this.visibilityStateListener = null;
2821
- }
2822
- }
2823
- }
2824
- capturePageLeave() {
2825
- const {
2826
- capture_pageleave,
2827
- capture_pageview
2828
- } = this.config;
2829
- if (capture_pageleave === true || capture_pageleave === 'if_capture_pageview' && (capture_pageview === true || capture_pageview === 'history_change')) {
2830
- this.capture('$pageleave');
2831
- }
2832
- }
2833
- async loadRemoteConfig() {
2834
- if (!this.isRemoteConfigLoaded) {
2835
- const remoteConfig = await this.reloadRemoteConfigAsync();
2836
- if (remoteConfig) {
2837
- this.onRemoteConfig(remoteConfig);
2838
- }
2839
- }
2840
- }
2841
- onRemoteConfig(config) {
2842
- if (!(document && document.body)) {
2843
- setTimeout(() => {
2844
- this.onRemoteConfig(config);
2845
- }, 500);
2846
- return;
2847
- }
2848
- this.isRemoteConfigLoaded = true;
2849
- this.replayAutocapture?.onRemoteConfig(config);
2850
- }
2851
- fetch(url, options) {
2852
- const fetchFn = getFetch();
2853
- if (!fetchFn) {
2854
- return Promise.reject(new Error('Fetch API is not available in this environment.'));
2855
- }
2856
- return fetchFn(url, options);
2857
- }
2858
- setConfig(config) {
2859
- const oldConfig = {
2860
- ...this.config
2861
- };
2862
- if (isObject(config)) {
2863
- extend(this.config, config);
2864
- this.persistence?.update_config(this.config, oldConfig);
2865
- this.replayAutocapture?.startIfEnabled();
2866
- }
2867
- const isTempStorage = this.config.persistence === 'sessionStorage' || this.config.persistence === 'memory';
2868
- this.sessionPersistence = isTempStorage ? this.persistence : new LeanbasePersistence({
2869
- ...this.config,
2870
- persistence: 'sessionStorage'
2871
- });
2872
- }
2873
- getLibraryId() {
2874
- return 'leanbase';
2875
- }
2876
- getLibraryVersion() {
2877
- return Config.LIB_VERSION;
2878
- }
2879
- getCustomUserAgent() {
2880
- return;
2881
- }
2882
- getPersistedProperty(key) {
2883
- return this.persistence?.get_property(key);
2884
- }
2885
- setPersistedProperty(key, value) {
2886
- this.persistence?.set_property(key, value);
2887
- }
2888
- calculateEventProperties(eventName, eventProperties, timestamp, uuid, readOnly) {
2889
- if (!this.persistence || !this.sessionPersistence) {
2890
- return eventProperties;
2891
- }
2892
- timestamp = timestamp || new Date();
2893
- const startTimestamp = readOnly ? undefined : this.persistence?.remove_event_timer(eventName);
2894
- let properties = {
2895
- ...eventProperties
2896
- };
2897
- properties['token'] = this.config.token;
2898
- if (this.config.cookieless_mode == 'always' || this.config.cookieless_mode == 'on_reject') {
2899
- properties[COOKIELESS_MODE_FLAG_PROPERTY] = true;
2900
- }
2901
- if (eventName === '$snapshot') {
2902
- const persistenceProps = {
2903
- ...this.persistence.properties()
2904
- };
2905
- properties['distinct_id'] = persistenceProps.distinct_id;
2906
- if (!(isString(properties['distinct_id']) || isNumber(properties['distinct_id'])) || isEmptyString(properties['distinct_id'])) {
2907
- logger.error('Invalid distinct_id for replay event. This indicates a bug in your implementation');
2908
- }
2909
- return properties;
2910
- }
2911
- const infoProperties = getEventProperties(this.config.mask_personal_data_properties, this.config.custom_personal_data_properties);
2912
- if (this.sessionManager) {
2913
- const {
2914
- sessionId,
2915
- windowId
2916
- } = this.sessionManager.checkAndGetSessionAndWindowId(readOnly, timestamp.getTime());
2917
- properties['$session_id'] = sessionId;
2918
- properties['$window_id'] = windowId;
2919
- }
2920
- if (this.sessionPropsManager) {
2921
- extend(properties, this.sessionPropsManager.getSessionProps());
2922
- }
2923
- let pageviewProperties = this.pageViewManager.doEvent();
2924
- if (eventName === '$pageview' && !readOnly) {
2925
- pageviewProperties = this.pageViewManager.doPageView(timestamp, uuid);
2926
- }
2927
- if (eventName === '$pageleave' && !readOnly) {
2928
- pageviewProperties = this.pageViewManager.doPageLeave(timestamp);
2929
- }
2930
- properties = extend(properties, pageviewProperties);
2931
- if (eventName === '$pageview' && document) {
2932
- properties['title'] = document.title;
2933
- }
2934
- if (!isUndefined(startTimestamp)) {
2935
- const duration_in_ms = timestamp.getTime() - startTimestamp;
2936
- properties['$duration'] = parseFloat((duration_in_ms / 1000).toFixed(3));
2937
- }
2938
- if (userAgent && this.config.opt_out_useragent_filter) {
2939
- properties['$browser_type'] = isLikelyBot(navigator$1, []) ? 'bot' : 'browser';
2940
- }
2941
- properties = extend({}, infoProperties, this.persistence.properties(), this.sessionPersistence.properties(), properties);
2942
- properties['$is_identified'] = this.isIdentified();
2943
- return properties;
2944
- }
2945
- isIdentified() {
2946
- return this.persistence?.get_property(USER_STATE) === 'identified' || this.sessionPersistence?.get_property(USER_STATE) === 'identified';
2947
- }
2948
- /**
2949
- * Add additional set_once properties to the event when creating a person profile. This allows us to create the
2950
- * profile with mostly-accurate properties, despite earlier events not setting them. We do this by storing them in
2951
- * persistence.
2952
- * @param dataSetOnce
2953
- */
2954
- calculateSetOnceProperties(dataSetOnce) {
2955
- if (!this.persistence) {
2956
- return dataSetOnce;
2957
- }
2958
- if (this.personProcessingSetOncePropertiesSent) {
2959
- return dataSetOnce;
2960
- }
2961
- const initialProps = this.persistence.get_initial_props();
2962
- const sessionProps = this.sessionPropsManager?.getSetOnceProps();
2963
- const setOnceProperties = extend({}, initialProps, sessionProps || {}, dataSetOnce || {});
2964
- this.personProcessingSetOncePropertiesSent = true;
2965
- if (isEmptyObject(setOnceProperties)) {
2966
- return undefined;
2967
- }
2968
- return setOnceProperties;
2969
- }
2970
- capture(event, properties, options) {
2971
- if (!this.isLoaded || !this.sessionPersistence || !this.persistence) {
2972
- return;
2973
- }
2974
- if (isUndefined(event) || !isString(event)) {
2975
- logger.error('No event name provided to posthog.capture');
2976
- return;
2977
- }
2978
- if (properties?.$current_url && !isString(properties?.$current_url)) {
2979
- logger.error('Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value.');
2980
- delete properties?.$current_url;
2981
- }
2982
- this.sessionPersistence.update_search_keyword();
2983
- if (this.config.save_campaign_params) {
2984
- this.sessionPersistence.update_campaign_params();
2985
- }
2986
- if (this.config.save_referrer) {
2987
- this.sessionPersistence.update_referrer_info();
2988
- }
2989
- if (this.config.save_campaign_params || this.config.save_referrer) {
2990
- this.persistence.set_initial_person_info();
2991
- }
2992
- const systemTime = new Date();
2993
- const timestamp = options?.timestamp || systemTime;
2994
- const uuid = uuidv7();
2995
- let data = {
2996
- uuid,
2997
- event,
2998
- properties: this.calculateEventProperties(event, properties || {}, timestamp, uuid)
2999
- };
3000
- const setProperties = options?.$set;
3001
- if (setProperties) {
3002
- data.$set = options?.$set;
3003
- }
3004
- const setOnceProperties = this.calculateSetOnceProperties(options?.$set_once);
3005
- if (setOnceProperties) {
3006
- data.$set_once = setOnceProperties;
3007
- }
3008
- data = copyAndTruncateStrings(data, options?._noTruncate ? null : this.config.properties_string_max_length);
3009
- data.timestamp = timestamp;
3010
- if (!isUndefined(options?.timestamp)) {
3011
- data.properties['$event_time_override_provided'] = true;
3012
- data.properties['$event_time_override_system_time'] = systemTime;
3013
- }
3014
- const finalSet = {
3015
- ...data.properties['$set'],
3016
- ...data['$set']
3017
- };
3018
- if (!isEmptyObject(finalSet)) {
3019
- this.setPersonPropertiesForFlags(finalSet);
3020
- }
3021
- super.capture(data.event, data.properties, options);
3022
- }
3023
- identify(distinctId, properties, options) {
3024
- super.identify(distinctId, properties, options);
3025
- }
3026
- destroy() {
3027
- this.persistence?.clear();
3028
- }
3029
- }
3030
-
3031
- export { Leanbase };
3032
- //# sourceMappingURL=index.mjs.map