posthog-js-lite 4.11.0 → 4.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,376 +1,294 @@
1
- import { detectBrowserVersion, stripUrlHash, detectBrowser, currentTimestamp, PostHogCore, getFetch } from '@posthog/core';
2
-
3
- const version = "4.11.0";
4
-
1
+ import { PostHogCore, currentTimestamp, detectBrowser, detectBrowserVersion, detectWebviewApp, getFetch, stripUrlHash } from "@posthog/core";
2
+ //#region src/version.ts
3
+ const version = "4.12.0";
4
+ //#endregion
5
+ //#region src/context.ts
5
6
  function getContext(window, disableCaptureUrlHashes = false) {
6
- let context = {};
7
- if (window?.navigator) {
8
- const userAgent = window.navigator.userAgent;
9
- const osValue = os(window);
10
- context = {
11
- ...context,
12
- ...(osValue !== undefined && {
13
- $os: osValue
14
- }),
15
- $browser: detectBrowser(userAgent, window.navigator.vendor),
16
- $referrer: window.document.referrer,
17
- $referring_domain: referringDomain(window.document.referrer),
18
- $device: device(userAgent),
19
- $current_url: disableCaptureUrlHashes ? stripUrlHash(window.location.href) : window.location.href,
20
- $host: window.location.host,
21
- $pathname: window.location.pathname,
22
- $browser_version: detectBrowserVersion(userAgent, window.navigator.vendor),
23
- $screen_height: window.screen.height,
24
- $screen_width: window.screen.width,
25
- $screen_dpr: window.devicePixelRatio
26
- };
27
- }
28
- context = {
29
- ...context,
30
- $lib: 'js',
31
- $lib_version: version,
32
- $insert_id: Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10),
33
- $time: currentTimestamp() / 1000 // epoch time in seconds
34
- };
35
- return context; // TODO: strip empty props?
7
+ let context = {};
8
+ if (window?.navigator) {
9
+ const userAgent = window.navigator.userAgent;
10
+ const osValue = os(window);
11
+ const [webviewApp, webviewAppVersion] = detectWebviewApp(userAgent);
12
+ context = {
13
+ ...context,
14
+ ...osValue !== void 0 && { $os: osValue },
15
+ $browser: detectBrowser(userAgent, window.navigator.vendor),
16
+ ...webviewApp && { $webview_app: webviewApp },
17
+ ...webviewAppVersion && { $webview_app_version: webviewAppVersion },
18
+ $referrer: window.document.referrer,
19
+ $referring_domain: referringDomain(window.document.referrer),
20
+ $device: device(userAgent),
21
+ $current_url: disableCaptureUrlHashes ? stripUrlHash(window.location.href) : window.location.href,
22
+ $host: window.location.host,
23
+ $pathname: window.location.pathname,
24
+ $browser_version: detectBrowserVersion(userAgent, window.navigator.vendor),
25
+ $screen_height: window.screen.height,
26
+ $screen_width: window.screen.width,
27
+ $screen_dpr: window.devicePixelRatio
28
+ };
29
+ }
30
+ context = {
31
+ ...context,
32
+ $lib: "js",
33
+ $lib_version: version,
34
+ $insert_id: Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10),
35
+ $time: currentTimestamp() / 1e3
36
+ };
37
+ return context;
36
38
  }
37
39
  function os(window) {
38
- if (!window?.navigator) {
39
- return undefined;
40
- }
41
- const a = window.navigator.userAgent;
42
- if (/Windows/i.test(a)) {
43
- if (/Phone/.test(a) || /WPDesktop/.test(a)) {
44
- return 'Windows Phone';
45
- }
46
- return 'Windows';
47
- } else if (/(iPhone|iPad|iPod)/.test(a)) {
48
- return 'iOS';
49
- } else if (/Android/.test(a)) {
50
- return 'Android';
51
- } else if (/(BlackBerry|PlayBook|BB10)/i.test(a)) {
52
- return 'BlackBerry';
53
- } else if (/Mac/i.test(a)) {
54
- return 'Mac OS X';
55
- } else if (/Linux/.test(a)) {
56
- return 'Linux';
57
- } else if (/CrOS/.test(a)) {
58
- return 'Chrome OS';
59
- } else {
60
- return undefined;
61
- }
40
+ if (!window?.navigator) return;
41
+ const a = window.navigator.userAgent;
42
+ if (/Windows/i.test(a)) {
43
+ if (/Phone/.test(a) || /WPDesktop/.test(a)) return "Windows Phone";
44
+ return "Windows";
45
+ } else if (/(iPhone|iPad|iPod)/.test(a)) return "iOS";
46
+ else if (/Android/.test(a)) return "Android";
47
+ else if (/(BlackBerry|PlayBook|BB10)/i.test(a)) return "BlackBerry";
48
+ else if (/Mac/i.test(a)) return "Mac OS X";
49
+ else if (/Linux/.test(a)) return "Linux";
50
+ else if (/CrOS/.test(a)) return "Chrome OS";
51
+ else return;
62
52
  }
63
53
  function device(userAgent) {
64
- if (/Windows Phone/i.test(userAgent) || /WPDesktop/.test(userAgent)) {
65
- return 'Windows Phone';
66
- } else if (/iPad/.test(userAgent)) {
67
- return 'iPad';
68
- } else if (/iPod/.test(userAgent)) {
69
- return 'iPod Touch';
70
- } else if (/iPhone/.test(userAgent)) {
71
- return 'iPhone';
72
- } else if (/(BlackBerry|PlayBook|BB10)/i.test(userAgent)) {
73
- return 'BlackBerry';
74
- } else if (/Android/.test(userAgent)) {
75
- return 'Android';
76
- } else {
77
- return '';
78
- }
54
+ if (/Windows Phone/i.test(userAgent) || /WPDesktop/.test(userAgent)) return "Windows Phone";
55
+ else if (/iPad/.test(userAgent)) return "iPad";
56
+ else if (/iPod/.test(userAgent)) return "iPod Touch";
57
+ else if (/iPhone/.test(userAgent)) return "iPhone";
58
+ else if (/(BlackBerry|PlayBook|BB10)/i.test(userAgent)) return "BlackBerry";
59
+ else if (/Android/.test(userAgent)) return "Android";
60
+ else return "";
79
61
  }
80
62
  function referringDomain(referrer) {
81
- const split = referrer.split('/');
82
- if (split.length >= 3) {
83
- return split[2];
84
- }
85
- return '';
63
+ const split = referrer.split("/");
64
+ if (split.length >= 3) return split[2];
65
+ return "";
86
66
  }
87
-
88
- // Methods partially borrowed from quirksmode.org/js/cookies.html
67
+ //#endregion
68
+ //#region src/storage.ts
89
69
  const cookieStore = {
90
- getItem(key) {
91
- try {
92
- const nameEQ = key + '=';
93
- const ca = document.cookie.split(';');
94
- for (let i = 0; i < ca.length; i++) {
95
- let c = ca[i];
96
- while (c.charAt(0) == ' ') {
97
- c = c.substring(1, c.length);
98
- }
99
- if (c.indexOf(nameEQ) === 0) {
100
- return decodeURIComponent(c.substring(nameEQ.length, c.length));
101
- }
102
- }
103
- } catch (err) {}
104
- return null;
105
- },
106
- setItem(key, value) {
107
- try {
108
- const cdomain = '',
109
- expires = '',
110
- secure = '';
111
- const new_cookie_val = key + '=' + encodeURIComponent(value) + expires + '; path=/' + cdomain + secure;
112
- document.cookie = new_cookie_val;
113
- } catch (err) {
114
- return;
115
- }
116
- },
117
- removeItem(name) {
118
- try {
119
- cookieStore.setItem(name, '');
120
- } catch (err) {
121
- return;
122
- }
123
- },
124
- clear() {
125
- document.cookie = '';
126
- },
127
- getAllKeys() {
128
- const ca = document.cookie.split(';');
129
- const keys = [];
130
- for (let i = 0; i < ca.length; i++) {
131
- let c = ca[i];
132
- while (c.charAt(0) == ' ') {
133
- c = c.substring(1, c.length);
134
- }
135
- keys.push(c.split('=')[0]);
136
- }
137
- return keys;
138
- }
70
+ getItem(key) {
71
+ try {
72
+ const nameEQ = key + "=";
73
+ const ca = document.cookie.split(";");
74
+ for (let i = 0; i < ca.length; i++) {
75
+ let c = ca[i];
76
+ while (c.charAt(0) == " ") c = c.substring(1, c.length);
77
+ if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
78
+ }
79
+ } catch (err) {}
80
+ return null;
81
+ },
82
+ setItem(key, value) {
83
+ try {
84
+ const new_cookie_val = key + "=" + encodeURIComponent(value) + "; path=/";
85
+ document.cookie = new_cookie_val;
86
+ } catch (err) {
87
+ return;
88
+ }
89
+ },
90
+ removeItem(name) {
91
+ try {
92
+ cookieStore.setItem(name, "");
93
+ } catch (err) {
94
+ return;
95
+ }
96
+ },
97
+ clear() {
98
+ document.cookie = "";
99
+ },
100
+ getAllKeys() {
101
+ const ca = document.cookie.split(";");
102
+ const keys = [];
103
+ for (let i = 0; i < ca.length; i++) {
104
+ let c = ca[i];
105
+ while (c.charAt(0) == " ") c = c.substring(1, c.length);
106
+ keys.push(c.split("=")[0]);
107
+ }
108
+ return keys;
109
+ }
139
110
  };
140
- const createStorageLike = store => {
141
- return {
142
- getItem(key) {
143
- return store.getItem(key);
144
- },
145
- setItem(key, value) {
146
- store.setItem(key, value);
147
- },
148
- removeItem(key) {
149
- store.removeItem(key);
150
- },
151
- clear() {
152
- store.clear();
153
- },
154
- getAllKeys() {
155
- const keys = [];
156
- for (const key in localStorage) {
157
- keys.push(key);
158
- }
159
- return keys;
160
- }
161
- };
111
+ const createStorageLike = (store) => {
112
+ return {
113
+ getItem(key) {
114
+ return store.getItem(key);
115
+ },
116
+ setItem(key, value) {
117
+ store.setItem(key, value);
118
+ },
119
+ removeItem(key) {
120
+ store.removeItem(key);
121
+ },
122
+ clear() {
123
+ store.clear();
124
+ },
125
+ getAllKeys() {
126
+ const keys = [];
127
+ for (const key in localStorage) keys.push(key);
128
+ return keys;
129
+ }
130
+ };
162
131
  };
163
- const checkStoreIsSupported = (storage, key = '__mplssupport__') => {
164
- try {
165
- const val = 'xyz';
166
- storage.setItem(key, val);
167
- if (storage.getItem(key) !== val) {
168
- return false;
169
- }
170
- storage.removeItem(key);
171
- return true;
172
- } catch (err) {
173
- return false;
174
- }
132
+ const checkStoreIsSupported = (storage, key = "__mplssupport__") => {
133
+ try {
134
+ const val = "xyz";
135
+ storage.setItem(key, val);
136
+ if (storage.getItem(key) !== val) return false;
137
+ storage.removeItem(key);
138
+ return true;
139
+ } catch (err) {
140
+ return false;
141
+ }
175
142
  };
176
- let localStore = undefined;
177
- let sessionStore = undefined;
143
+ let localStore = void 0;
144
+ let sessionStore = void 0;
178
145
  const createMemoryStorage = () => {
179
- const _cache = {};
180
- const store = {
181
- getItem(key) {
182
- return _cache[key];
183
- },
184
- setItem(key, value) {
185
- _cache[key] = value !== null ? value : undefined;
186
- },
187
- removeItem(key) {
188
- delete _cache[key];
189
- },
190
- clear() {
191
- for (const key in _cache) {
192
- delete _cache[key];
193
- }
194
- },
195
- getAllKeys() {
196
- const keys = [];
197
- for (const key in _cache) {
198
- keys.push(key);
199
- }
200
- return keys;
201
- }
202
- };
203
- return store;
146
+ const _cache = {};
147
+ return {
148
+ getItem(key) {
149
+ return _cache[key];
150
+ },
151
+ setItem(key, value) {
152
+ _cache[key] = value !== null ? value : void 0;
153
+ },
154
+ removeItem(key) {
155
+ delete _cache[key];
156
+ },
157
+ clear() {
158
+ for (const key in _cache) delete _cache[key];
159
+ },
160
+ getAllKeys() {
161
+ const keys = [];
162
+ for (const key in _cache) keys.push(key);
163
+ return keys;
164
+ }
165
+ };
204
166
  };
205
167
  const getStorage = (type, window) => {
206
- if (window) {
207
- if (!localStore) {
208
- const _localStore = createStorageLike(window.localStorage);
209
- localStore = checkStoreIsSupported(_localStore) ? _localStore : undefined;
210
- }
211
- if (!sessionStore) {
212
- const _sessionStore = createStorageLike(window.sessionStorage);
213
- sessionStore = checkStoreIsSupported(_sessionStore) ? _sessionStore : undefined;
214
- }
215
- }
216
- switch (type) {
217
- case 'cookie':
218
- return cookieStore || localStore || sessionStore || createMemoryStorage();
219
- case 'localStorage':
220
- return localStore || sessionStore || createMemoryStorage();
221
- case 'sessionStorage':
222
- return sessionStore || createMemoryStorage();
223
- case 'memory':
224
- return createMemoryStorage();
225
- default:
226
- return createMemoryStorage();
227
- }
168
+ if (window) {
169
+ if (!localStore) {
170
+ const _localStore = createStorageLike(window.localStorage);
171
+ localStore = checkStoreIsSupported(_localStore) ? _localStore : void 0;
172
+ }
173
+ if (!sessionStore) {
174
+ const _sessionStore = createStorageLike(window.sessionStorage);
175
+ sessionStore = checkStoreIsSupported(_sessionStore) ? _sessionStore : void 0;
176
+ }
177
+ }
178
+ switch (type) {
179
+ case "cookie": return cookieStore || localStore || sessionStore || createMemoryStorage();
180
+ case "localStorage": return localStore || sessionStore || createMemoryStorage();
181
+ case "sessionStorage": return sessionStore || createMemoryStorage();
182
+ case "memory": return createMemoryStorage();
183
+ default: return createMemoryStorage();
184
+ }
228
185
  };
229
-
230
- // Portions of this file are derived from getsentry/sentry-javascript
231
- // Copyright (c) 2012 Functional Software, Inc. dba Sentry
232
- // Licensed under the MIT License: https://github.com/getsentry/sentry-javascript/blob/develop/LICENSE
233
- // import { patch } from 'rrweb/typings/utils'
234
- // copied from: https://github.com/PostHog/posthog-js/blob/main/src/extensions/replay/rrweb-plugins/patch.ts
235
- // which was copied from https://github.com/rrweb-io/rrweb/blob/8aea5b00a4dfe5a6f59bd2ae72bb624f45e51e81/packages/rrweb/src/utils.ts#L129
236
- // copied from: https://github.com/PostHog/posthog-js/blob/main/react/src/utils/type-utils.ts#L4
237
- const isFunction = function (f) {
238
- return typeof f === 'function';
186
+ //#endregion
187
+ //#region src/patch.ts
188
+ const isFunction = function(f) {
189
+ return typeof f === "function";
239
190
  };
240
191
  function patch(source, name, replacement) {
241
- try {
242
- if (!(name in source)) {
243
- return () => {
244
- //
245
- };
246
- }
247
- const original = source[name];
248
- const wrapped = replacement(original);
249
- // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work
250
- // otherwise it'll throw "TypeError: Object.defineProperties called on non-object"
251
- if (isFunction(wrapped)) {
252
- wrapped.prototype = wrapped.prototype || {};
253
- Object.defineProperties(wrapped, {
254
- __posthog_wrapped__: {
255
- enumerable: false,
256
- value: true
257
- }
258
- });
259
- }
260
- source[name] = wrapped;
261
- return () => {
262
- source[name] = original;
263
- };
264
- } catch {
265
- return () => {
266
- //
267
- };
268
- // This can throw when multiple instrumentation layers try to wrap the same global object,
269
- // such as XMLHttpRequest, and redefine the same non-configurable wrapper marker.
270
- }
271
- }
272
-
273
- class PostHog extends PostHogCore {
274
- constructor(apiKey, options) {
275
- super(apiKey, options);
276
- this._lastPathname = '';
277
- // posthog-js stores options in one object on
278
- this._storageKey = options?.persistence_name ? `ph_${options.persistence_name}` : `ph_${apiKey}_posthog`;
279
- this._disableCaptureUrlHashes = options?.disable_capture_url_hashes ?? false;
280
- this._storage = getStorage(options?.persistence || 'localStorage', this.getWindow());
281
- this.setupBootstrap(options);
282
- if (options?.preloadFeatureFlags !== false) {
283
- this.reloadFeatureFlags();
284
- }
285
- if (options?.captureHistoryEvents && typeof window !== 'undefined') {
286
- this._lastPathname = window?.location?.pathname || '';
287
- this.setupHistoryEventTracking();
288
- }
289
- }
290
- getWindow() {
291
- return typeof window !== 'undefined' ? window : undefined;
292
- }
293
- getPersistedProperty(key) {
294
- if (!this._storageCache) {
295
- this._storageCache = JSON.parse(this._storage.getItem(this._storageKey) || '{}') || {};
296
- }
297
- return this._storageCache[key];
298
- }
299
- setPersistedProperty(key, value) {
300
- if (!this._storageCache) {
301
- this._storageCache = JSON.parse(this._storage.getItem(this._storageKey) || '{}') || {};
302
- }
303
- if (value === null) {
304
- delete this._storageCache[key];
305
- } else {
306
- this._storageCache[key] = value;
307
- }
308
- this._storage.setItem(this._storageKey, JSON.stringify(this._storageCache));
309
- }
310
- fetch(url, options) {
311
- const fetchFn = getFetch();
312
- if (!fetchFn) {
313
- // error will be handled by the caller (fetchWithRetry)
314
- return Promise.reject(new Error('Fetch API is not available in this environment.'));
315
- }
316
- return fetchFn(url, options);
317
- }
318
- getLibraryId() {
319
- return 'posthog-js-lite';
320
- }
321
- getLibraryVersion() {
322
- return version;
323
- }
324
- getCustomUserAgent() {
325
- return;
326
- }
327
- getCommonEventProperties() {
328
- return {
329
- ...super.getCommonEventProperties(),
330
- ...getContext(this.getWindow(), this._disableCaptureUrlHashes)
331
- };
332
- }
333
- setupHistoryEventTracking() {
334
- const window = this.getWindow();
335
- if (!window) {
336
- return;
337
- }
338
- // Old fashioned, we could also use arrow functions but I think the closure for a patch is more reliable
339
- const self = this;
340
- patch(window.history, 'pushState', originalPushState => {
341
- return function patchedPushState(state, title, url) {
342
- ;
343
- originalPushState.call(this, state, title, url);
344
- self.captureNavigationEvent('pushState');
345
- };
346
- });
347
- patch(window.history, 'replaceState', originalReplaceState => {
348
- return function patchedReplaceState(state, title, url) {
349
- ;
350
- originalReplaceState.call(this, state, title, url);
351
- self.captureNavigationEvent('replaceState');
352
- };
353
- });
354
- // For popstate we need to listen to the event instead of overriding a method
355
- window.addEventListener('popstate', () => {
356
- this.captureNavigationEvent('popstate');
357
- });
358
- }
359
- captureNavigationEvent(navigationType) {
360
- const window = this.getWindow();
361
- if (!window) {
362
- return;
363
- }
364
- const currentPathname = window.location.pathname;
365
- // Only capture pageview if the pathname has changed
366
- if (currentPathname !== this._lastPathname) {
367
- this.capture('$pageview', {
368
- navigation_type: navigationType
369
- });
370
- this._lastPathname = currentPathname;
371
- }
372
- }
192
+ try {
193
+ if (!(name in source)) return () => {};
194
+ const original = source[name];
195
+ const wrapped = replacement(original);
196
+ if (isFunction(wrapped)) {
197
+ wrapped.prototype = wrapped.prototype || {};
198
+ Object.defineProperties(wrapped, { __posthog_wrapped__: {
199
+ enumerable: false,
200
+ value: true
201
+ } });
202
+ }
203
+ source[name] = wrapped;
204
+ return () => {
205
+ source[name] = original;
206
+ };
207
+ } catch {
208
+ return () => {};
209
+ }
373
210
  }
211
+ //#endregion
212
+ //#region src/posthog-web.ts
213
+ var PostHog = class extends PostHogCore {
214
+ constructor(apiKey, options) {
215
+ super(apiKey, options);
216
+ this._lastPathname = "";
217
+ this._storageKey = options?.persistence_name ? `ph_${options.persistence_name}` : `ph_${apiKey}_posthog`;
218
+ this._disableCaptureUrlHashes = options?.disable_capture_url_hashes ?? false;
219
+ this._storage = getStorage(options?.persistence || "localStorage", this.getWindow());
220
+ this.setupBootstrap(options);
221
+ if (options?.preloadFeatureFlags !== false) this.reloadFeatureFlags();
222
+ if (options?.captureHistoryEvents && typeof window !== "undefined") {
223
+ this._lastPathname = window?.location?.pathname || "";
224
+ this.setupHistoryEventTracking();
225
+ }
226
+ }
227
+ getWindow() {
228
+ return typeof window !== "undefined" ? window : void 0;
229
+ }
230
+ getPersistedProperty(key) {
231
+ if (!this._storageCache) this._storageCache = JSON.parse(this._storage.getItem(this._storageKey) || "{}") || {};
232
+ return this._storageCache[key];
233
+ }
234
+ setPersistedProperty(key, value) {
235
+ if (!this._storageCache) this._storageCache = JSON.parse(this._storage.getItem(this._storageKey) || "{}") || {};
236
+ if (value === null) delete this._storageCache[key];
237
+ else this._storageCache[key] = value;
238
+ this._storage.setItem(this._storageKey, JSON.stringify(this._storageCache));
239
+ }
240
+ fetch(url, options) {
241
+ const fetchFn = getFetch();
242
+ if (!fetchFn) return Promise.reject(/* @__PURE__ */ new Error("Fetch API is not available in this environment."));
243
+ return fetchFn(url, options);
244
+ }
245
+ getLibraryId() {
246
+ return "posthog-js-lite";
247
+ }
248
+ getLibraryVersion() {
249
+ return version;
250
+ }
251
+ getCustomUserAgent() {}
252
+ getCommonEventProperties() {
253
+ return {
254
+ ...super.getCommonEventProperties(),
255
+ ...getContext(this.getWindow(), this._disableCaptureUrlHashes)
256
+ };
257
+ }
258
+ setupHistoryEventTracking() {
259
+ const window = this.getWindow();
260
+ if (!window) return;
261
+ const self = this;
262
+ patch(window.history, "pushState", (originalPushState) => {
263
+ return function patchedPushState(state, title, url) {
264
+ originalPushState.call(this, state, title, url);
265
+ self.captureNavigationEvent("pushState");
266
+ };
267
+ });
268
+ patch(window.history, "replaceState", (originalReplaceState) => {
269
+ return function patchedReplaceState(state, title, url) {
270
+ originalReplaceState.call(this, state, title, url);
271
+ self.captureNavigationEvent("replaceState");
272
+ };
273
+ });
274
+ window.addEventListener("popstate", () => {
275
+ this.captureNavigationEvent("popstate");
276
+ });
277
+ }
278
+ captureNavigationEvent(navigationType) {
279
+ const window = this.getWindow();
280
+ if (!window) return;
281
+ const currentPathname = window.location.pathname;
282
+ if (currentPathname !== this._lastPathname) {
283
+ this.capture("$pageview", { navigation_type: navigationType });
284
+ this._lastPathname = currentPathname;
285
+ }
286
+ }
287
+ };
288
+ //#endregion
289
+ //#region src/index.ts
290
+ var src_default = PostHog;
291
+ //#endregion
292
+ export { PostHog, src_default as default };
374
293
 
375
- export { PostHog, PostHog as default };
376
- //# sourceMappingURL=index.mjs.map
294
+ //# sourceMappingURL=index.mjs.map