@posthog/browser 0.4.2 → 0.5.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 (65) hide show
  1. package/ARCHITECTURE.md +34 -46
  2. package/README.md +56 -63
  3. package/dist/composition/npm/core.d.ts +2 -3
  4. package/dist/composition/npm/core.js +2 -1
  5. package/dist/composition/npm/core.mjs +2 -1
  6. package/dist/composition/npm/index.d.ts +3 -4
  7. package/dist/composition/npm/index.js +2 -1
  8. package/dist/composition/npm/index.mjs +2 -1
  9. package/dist/composition/npm/root-composition.d.ts +4 -4
  10. package/dist/composition/npm/root-composition.js +0 -16
  11. package/dist/composition/npm/root-composition.mjs +0 -16
  12. package/dist/core/context/browser-client.d.ts +4 -35
  13. package/dist/core/extensions/registry.d.ts +15 -36
  14. package/dist/core/extensions/registry.js +67 -198
  15. package/dist/core/extensions/registry.mjs +67 -198
  16. package/dist/core/posthog.d.ts +3 -2
  17. package/dist/core/posthog.js +104 -161
  18. package/dist/core/posthog.mjs +105 -162
  19. package/dist/core/state/state.d.ts +1 -0
  20. package/dist/core/state/state.js +5 -2
  21. package/dist/core/state/state.mjs +3 -3
  22. package/dist/core/types.d.ts +50 -12
  23. package/dist/primitives/version.js +1 -1
  24. package/dist/primitives/version.mjs +1 -1
  25. package/dist/products/analytics/analytics-core.d.ts +76 -0
  26. package/dist/products/analytics/analytics-core.js +472 -0
  27. package/dist/products/analytics/analytics-core.mjs +425 -0
  28. package/dist/products/analytics/analytics-internal.d.ts +14 -36
  29. package/dist/products/analytics/analytics-internal.js +2 -10
  30. package/dist/products/analytics/analytics-internal.mjs +1 -3
  31. package/dist/products/analytics/analytics-options.d.ts +0 -9
  32. package/dist/products/analytics/analytics-options.js +1 -38
  33. package/dist/products/analytics/analytics-options.mjs +1 -17
  34. package/dist/products/analytics/groups.d.ts +8 -0
  35. package/dist/products/analytics/groups.js +84 -0
  36. package/dist/products/analytics/groups.mjs +40 -0
  37. package/dist/products/analytics/person.d.ts +11 -0
  38. package/dist/products/analytics/person.js +91 -0
  39. package/dist/products/analytics/person.mjs +41 -0
  40. package/dist/products/autocapture/autocapture.js +2 -6
  41. package/dist/products/autocapture/autocapture.mjs +2 -6
  42. package/dist/products/flags/flags-internal.d.ts +1 -2
  43. package/dist/products/flags/flags-token.d.ts +3 -2
  44. package/dist/products/flags/flags.js +2 -7
  45. package/dist/products/flags/flags.mjs +2 -7
  46. package/dist/products/logs/logs.js +2 -5
  47. package/dist/products/logs/logs.mjs +2 -5
  48. package/dist/products/surveys/surveys-extension.js +4 -21
  49. package/dist/products/surveys/surveys-extension.mjs +4 -21
  50. package/package.json +4 -9
  51. package/dist/products/analytics/analytics-api.d.ts +0 -32
  52. package/dist/products/analytics/analytics-api.js +0 -18
  53. package/dist/products/analytics/analytics-api.mjs +0 -1
  54. package/dist/products/analytics/analytics-buffer.d.ts +0 -4
  55. package/dist/products/analytics/analytics-buffer.js +0 -41
  56. package/dist/products/analytics/analytics-buffer.mjs +0 -3
  57. package/dist/products/analytics/analytics-extension.d.ts +0 -87
  58. package/dist/products/analytics/analytics-extension.js +0 -649
  59. package/dist/products/analytics/analytics-extension.mjs +0 -611
  60. package/dist/products/analytics/analytics.d.ts +0 -6
  61. package/dist/products/analytics/analytics.js +0 -42
  62. package/dist/products/analytics/analytics.mjs +0 -4
  63. package/dist/products/analytics/automatic-analytics.d.ts +0 -3
  64. package/dist/products/analytics/automatic-analytics.js +0 -44
  65. package/dist/products/analytics/automatic-analytics.mjs +0 -6
@@ -32,7 +32,9 @@ __webpack_require__.d(__webpack_exports__, {
32
32
  });
33
33
  const external_remote_config_js_namespaceObject = require("./remote-config.js");
34
34
  const pubsub_namespaceObject = require("@posthog/browser-common/pubsub");
35
- const analytics_internal_js_namespaceObject = require("../products/analytics/analytics-internal.js");
35
+ const analytics_core_js_namespaceObject = require("../products/analytics/analytics-core.js");
36
+ const groups_js_namespaceObject = require("../products/analytics/groups.js");
37
+ const person_js_namespaceObject = require("../products/analytics/person.js");
36
38
  const bot_filter_js_namespaceObject = require("./state/bot-filter.js");
37
39
  const registry_js_namespaceObject = require("./extensions/registry.js");
38
40
  const immutable_js_namespaceObject = require("../primitives/immutable.js");
@@ -72,10 +74,10 @@ const getDefaultNavigator = ()=>{
72
74
  }
73
75
  };
74
76
  class PostHog {
75
- static create(options, loaders) {
76
- return new PostHog(options, loaders);
77
+ static create(options, createDelivery, loaders) {
78
+ return new PostHog(options, createDelivery, loaders);
77
79
  }
78
- constructor(options, loaders){
80
+ constructor(options, createDelivery, loaders){
79
81
  this.library = Object.freeze({
80
82
  name: 'web',
81
83
  version: version_js_namespaceObject.version
@@ -100,13 +102,6 @@ class PostHog {
100
102
  this.initialPersonProperties = Object.freeze({});
101
103
  }
102
104
  this._remoteConfigPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A remote configuration listener failed', error));
103
- this._eventPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('An event listener failed', error));
104
- this._identifyPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('An identify listener failed', error));
105
- this._changePropertiesPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A person-property listener failed', error));
106
- this._groupPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A group listener failed', error));
107
- this._groupsResetPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A group reset listener failed', error));
108
- this._resetPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A reset listener failed', error));
109
- this._newSessionPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A session listener failed', error));
110
105
  this._consentChangePublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A consent change listener failed', error));
111
106
  const browserNavigator = false === options.navigator ? void 0 : options.navigator ?? getDefaultNavigator();
112
107
  const browserFetch = false === options.fetch ? void 0 : options.fetch ?? getDefaultFetch();
@@ -137,7 +132,8 @@ class PostHog {
137
132
  ];
138
133
  this._remoteConfig = options.remoteConfig;
139
134
  this._remoteConfigTimeoutMs = void 0 !== options.remoteConfigTimeoutMs && Number.isFinite(options.remoteConfigTimeoutMs) ? Math.max(0, options.remoteConfigTimeoutMs) : 10000;
140
- this.kv = this._state.keyValueStore('core', ()=>!this._closing && !this._disposed && this._state.prepare());
135
+ this.kv = this._state.keyValueStore(state_js_namespaceObject.CLIENT_KV_NAMESPACE, ()=>this._canMutate() && this._state.prepare());
136
+ this._sessionKv = this._state.tabKeyValueStore('analytics', ()=>this._canMutate() && this._state.prepare());
141
137
  this._latestRemoteConfigResult = this._remoteConfig ? {
142
138
  ok: true,
143
139
  config: this._remoteConfig
@@ -155,15 +151,22 @@ class PostHog {
155
151
  else if (!this._closing && !this._disposed) this.getRemoteConfig();
156
152
  return subscription;
157
153
  };
158
- this.onIdentify = this._identifyPublisher.listener;
159
- this.onGroup = this._groupPublisher.listener;
160
- this.onGroupsReset = this._groupsResetPublisher.listener;
161
- this.onReset = this._resetPublisher.listener;
154
+ let analyticsOptions = {};
155
+ try {
156
+ analyticsOptions = options.analytics ?? {};
157
+ if (false === analyticsOptions) this.logger.warn('The `analytics: false` option was removed in this version, so events are captured. Set `capturePageview: false` to skip the initial $pageview and, on the root entrypoint, `autocapture: false` to turn off autocapture.');
158
+ } catch {}
159
+ this._analytics = new analytics_core_js_namespaceObject.Analytics(this, analyticsOptions, createDelivery);
160
+ this.onEvent = this._analytics._eventPublisher.listener;
161
+ this.onIdentify = this._analytics._identifyPublisher.listener;
162
+ this.onChangeProperties = this._analytics._changePropertiesPublisher.listener;
163
+ this.onGroup = this._analytics._groupPublisher.listener;
164
+ this.onGroupsReset = this._analytics._groupsResetPublisher.listener;
165
+ this.onReset = this._analytics._resetPublisher.listener;
166
+ this.onNewSession = this._analytics._newSessionPublisher.listener;
162
167
  this.onConsentChange = this._consentChangePublisher.listener;
163
- this.onNewSession = this._newSessionPublisher.listener;
164
168
  this.onSession = (listener)=>this.onNewSession((session)=>listener(session.sessionId));
165
- this._registry = new registry_js_namespaceObject.ExtensionRegistry((extensionName, resolve)=>this._createExtensionClient(extensionName, resolve), this.logger, loaders, (extension, host)=>this._setupExtension(extension, host), ()=>!this._closing && !this._disposed);
166
- this._registry.expose(this);
169
+ this._registry = new registry_js_namespaceObject.ExtensionRegistry(this, this.logger, loaders, ()=>this._canMutate());
167
170
  }
168
171
  get distinctId() {
169
172
  this._state.prepare();
@@ -191,8 +194,74 @@ class PostHog {
191
194
  get canCapture() {
192
195
  return !this._closing && !this._disposed && !this._blocked && !this.hasOptedOut() && this._state.prepare();
193
196
  }
197
+ get isRateLimited() {
198
+ return this._analytics.isRateLimited;
199
+ }
200
+ capture(event, properties, options) {
201
+ return this._analytics.capture(event, properties, options);
202
+ }
203
+ captureImmediate(event, properties, options) {
204
+ return this._analytics.captureImmediate(event, properties, options);
205
+ }
206
+ identify(distinctId, set, setOnce) {
207
+ this._analytics.identify(distinctId, set, setOnce);
208
+ }
209
+ reset() {
210
+ this._analytics.reset();
211
+ }
212
+ register(properties) {
213
+ this._analytics.register(properties);
214
+ }
215
+ registerOnce(properties, defaultValue) {
216
+ this._analytics.registerOnce(properties, defaultValue);
217
+ }
218
+ unregister(property) {
219
+ this._analytics.unregister(property);
220
+ }
221
+ getProperty(property) {
222
+ return this._analytics.getProperty(property);
223
+ }
224
+ registerForSession(properties) {
225
+ this._analytics.registerForSession(properties);
226
+ }
227
+ unregisterForSession(property) {
228
+ this._analytics.unregisterForSession(property);
229
+ }
230
+ alias(aliasId) {
231
+ person_js_namespaceObject.alias(this, aliasId);
232
+ }
233
+ group(type, key, properties) {
234
+ groups_js_namespaceObject.group(this, type, key, properties);
235
+ }
236
+ groupIdentify(type, key, properties, options) {
237
+ groups_js_namespaceObject.groupIdentify(this, type, key, properties, options);
238
+ }
239
+ resetGroups() {
240
+ groups_js_namespaceObject.resetGroups(this);
241
+ }
242
+ createPersonProfile() {
243
+ person_js_namespaceObject.createPersonProfile(this);
244
+ }
245
+ setPersonProperties(set, setOnce) {
246
+ person_js_namespaceObject.setPersonProperties(this, set, setOnce);
247
+ }
248
+ unsetPersonProperties(names) {
249
+ person_js_namespaceObject.unsetPersonProperties(this, names);
250
+ }
251
+ setInternalOrTestUser() {
252
+ person_js_namespaceObject.setInternalOrTestUser(this);
253
+ }
254
+ registerDynamicEventProperties(producer) {
255
+ return this._analytics.registerDynamicEventProperties(producer);
256
+ }
257
+ getExtension(name) {
258
+ return this._registry.get(name);
259
+ }
194
260
  async flush() {
195
- await this._registry.flush();
261
+ await Promise.all([
262
+ this._registry.flush(),
263
+ this._analytics.flush()
264
+ ]);
196
265
  }
197
266
  optIn() {
198
267
  if (this._disposed) return;
@@ -286,7 +355,10 @@ class PostHog {
286
355
  shutdown(shutdownTimeoutMs = DEFAULT_SHUTDOWN_TIMEOUT_MS) {
287
356
  if (!this._shutdownPromise) {
288
357
  this._closing = true;
289
- const extensionFlush = this._registry.flush('shutdown');
358
+ const extensionFlush = Promise.all([
359
+ this._registry.flush('shutdown'),
360
+ this._analytics.flush()
361
+ ]).then(()=>void 0);
290
362
  this._removePageviewListener();
291
363
  try {
292
364
  this._consentObservation.dispose();
@@ -327,17 +399,12 @@ class PostHog {
327
399
  } catch (error) {
328
400
  this.logger.error('Failed to dispose browser state', error);
329
401
  }
330
- this._analytics = void 0;
331
- const cleanup = this._registry.dispose().catch((error)=>this.logger.error('Failed to dispose extensions', error));
402
+ const cleanup = Promise.all([
403
+ this._registry.dispose(),
404
+ this._analytics.dispose()
405
+ ]).catch((error)=>this.logger.error('Failed to dispose extensions', error));
332
406
  this._remoteConfigPublisher.dispose();
333
- this._eventPublisher.dispose();
334
- this._identifyPublisher.dispose();
335
- this._changePropertiesPublisher.dispose();
336
- this._groupPublisher.dispose();
337
- this._groupsResetPublisher.dispose();
338
- this._resetPublisher.dispose();
339
407
  this._consentChangePublisher.dispose();
340
- this._newSessionPublisher.dispose();
341
408
  await Promise.race([
342
409
  cleanup,
343
410
  timeout
@@ -351,16 +418,13 @@ class PostHog {
351
418
  } catch {}
352
419
  }
353
420
  }
354
- async _completeInitialization() {
355
- await this._analytics?.start();
421
+ _completeInitialization() {
356
422
  this._ready = true;
357
423
  this._startInitialPageview();
358
- await this._pageviewLoading;
359
424
  }
360
425
  _startInitialPageview() {
361
426
  if (!this._ready || !this._capturePageview || !this._initialPageviewPending || this._closing || this._disposed || !this._pageviewIsVisible()) return;
362
427
  this._removePageviewListener();
363
- if (!this._analytics) return void this._loadInitialPageviewAnalytics();
364
428
  this._initialPageviewPending = false;
365
429
  if (!this._analytics.captureInitialPageview()) this._initialPageviewPending = !this._disposed && !this._blocked;
366
430
  }
@@ -402,13 +466,6 @@ class PostHog {
402
466
  this._removePageviewListener();
403
467
  this._initialPageviewPending = false;
404
468
  }
405
- _loadInitialPageviewAnalytics() {
406
- if (this._pageviewLoading || this._blocked || this.hasOptedOut()) return;
407
- this._pageviewLoading = this.resolveExtension('analytics').then(()=>{
408
- this._pageviewLoading = void 0;
409
- if (this._analytics) this._startInitialPageview();
410
- });
411
- }
412
469
  _removePageviewListener() {
413
470
  const listener = this._pageviewListener;
414
471
  this._pageviewListener = void 0;
@@ -477,121 +534,8 @@ class PostHog {
477
534
  }));
478
535
  } catch {}
479
536
  }
480
- _createSharedExtensionClient(extensionName) {
481
- const host = this;
482
- const logger = this.logger.createLogger(extensionName);
483
- const kv = this._state.keyValueStore(extensionName, ()=>!this._closing && !this._disposed && this._state.prepare());
484
- return {
485
- get distinctId () {
486
- return host.distinctId;
487
- },
488
- get anonymousId () {
489
- return host.anonymousId;
490
- },
491
- get deviceId () {
492
- return host.deviceId;
493
- },
494
- get library () {
495
- return host.library;
496
- },
497
- get initialPersonProperties () {
498
- return host.initialPersonProperties;
499
- },
500
- get groups () {
501
- return host.groups;
502
- },
503
- get session () {
504
- return host.session;
505
- },
506
- get isOptedOut () {
507
- return host.isOptedOut;
508
- },
509
- get canCapture () {
510
- return host.canCapture;
511
- },
512
- get isRateLimited () {
513
- return host._analytics?.isRateLimited ?? false;
514
- },
515
- capture: (event, properties, options)=>host._analytics?.capture(event, properties, options) ?? true,
516
- registerDynamicEventProperties: (producer)=>host._analytics?.registerDynamicEventProperties(producer) ?? {
517
- dispose () {}
518
- },
519
- getExtension: (name)=>host._registry.getShared(name),
520
- get projectToken () {
521
- return host.projectToken;
522
- },
523
- sendRequest: (path, init)=>host.sendRequest(path, init),
524
- onRemoteConfig: host.onRemoteConfig,
525
- onEvent: host._eventPublisher.listener,
526
- onSession: host.onSession,
527
- kv,
528
- logger
529
- };
530
- }
531
- _createExtensionClient(extensionName, resolve) {
532
- const host = this;
533
- const sharedClient = this._createSharedExtensionClient(extensionName);
534
- const { getExtension: _lookup, capture: _capture, registerDynamicEventProperties: _registration, isRateLimited: _rateLimit, ...capabilities } = Object.getOwnPropertyDescriptors(sharedClient);
535
- const browserClient = Object.defineProperties({
536
- sharedClient,
537
- resolveExtension: (name)=>this._closing || this._disposed ? Promise.resolve(void 0) : resolve(name),
538
- onConsentChange: host.onConsentChange,
539
- onIdentify: host.onIdentify,
540
- onChangeProperties: host._changePropertiesPublisher.listener,
541
- onGroup: host.onGroup,
542
- onGroupsReset: host.onGroupsReset,
543
- onReset: host.onReset
544
- }, capabilities);
545
- this._registry.expose(browserClient);
546
- return browserClient;
547
- }
548
- async _setupExtension(extension, host) {
549
- if (this._closing || this._disposed) throw new Error('The browser client is closing');
550
- if (!(0, analytics_internal_js_namespaceObject.isAnalyticsExtension)(extension)) {
551
- await extension.setup(host);
552
- if (this._closing || this._disposed) throw new Error('The browser client is closing');
553
- return;
554
- }
555
- this._analytics = extension;
556
- try {
557
- extension.bindCaptureHost(this._analyticsCaptureHost(extension));
558
- await extension.setup(host);
559
- if (this._closing || this._disposed) throw new Error('The browser client is closing');
560
- extension.initialize({
561
- runtime: this._requestRuntime,
562
- canRetry: ()=>this._canDeliver(),
563
- reportFailure: (error)=>this.logger.error('Event delivery failed', error),
564
- reportWarning: (message)=>this.logger.warn(message),
565
- onAvailable: ()=>this._startInitialPageview()
566
- });
567
- } catch (error) {
568
- if (this._analytics === extension) this._analytics = void 0;
569
- throw error;
570
- }
571
- }
572
- _canUseAnalytics(owner) {
573
- return this._analytics === owner && !this._closing && !this._disposed;
574
- }
575
- _analyticsCaptureHost(owner) {
576
- const canMutate = ()=>this._canUseAnalytics(owner);
577
- return {
578
- projectToken: this.projectToken,
579
- logger: this.logger,
580
- sessionKv: this._state.tabKeyValueStore('analytics', ()=>canMutate() && this._state.prepare()),
581
- state: this._state,
582
- canCapture: ()=>canMutate() && !this._blocked && !this.hasOptedOut(),
583
- canMutate,
584
- isDisposed: ()=>this._disposed,
585
- authority: ()=>this._immediateAuthority,
586
- onEvent: this._eventPublisher.listener,
587
- publishEvent: (event)=>this._eventPublisher.publish(event),
588
- publishNewSession: (session)=>this._newSessionPublisher.publish(session),
589
- publishIdentify: (info)=>this._identifyPublisher.publish(info),
590
- publishChangeProperties: (info)=>this._changePropertiesPublisher.publish(info),
591
- publishGroup: (info)=>this._groupPublisher.publish(info),
592
- publishGroupsReset: ()=>this._groupsResetPublisher.publish(void 0),
593
- publishReset: ()=>this._resetPublisher.publish(void 0)
594
- };
537
+ _canMutate() {
538
+ return !this._closing && !this._disposed;
595
539
  }
596
540
  _canDeliver() {
597
541
  return !this._disposed && !this._blocked && !this.hasOptedOut();
@@ -602,7 +546,7 @@ const selectConfiguredExtensions = (configured)=>{
602
546
  for (const extension of configured)if (!selected.has(extension.name)) selected.set(extension.name, extension);
603
547
  return selected;
604
548
  };
605
- const createPostHogCore = async (options, configured = options?.extensions ?? [], automaticLoaders = {}, automatic = [])=>{
549
+ const createPostHogCore = async (options, createDelivery, configured = options?.extensions ?? [], automaticLoaders = {}, automatic = [])=>{
606
550
  const selected = selectConfiguredExtensions(configured);
607
551
  const loaders = Object.fromEntries([
608
552
  ...Object.entries(automaticLoaders),
@@ -613,12 +557,11 @@ const createPostHogCore = async (options, configured = options?.extensions ?? []
613
557
  ]);
614
558
  const client = PostHog.create(options ?? {
615
559
  projectToken: ''
616
- }, loaders);
560
+ }, createDelivery, loaders);
617
561
  client.getRemoteConfig();
618
- if (selected.has('analytics')) await client.resolveExtension('analytics');
619
- for (const name of selected.keys())if ('analytics' !== name) await client.resolveExtension(name);
562
+ for (const name of selected.keys())await client.resolveExtension(name);
620
563
  for (const extension of automatic)await client._registry.activate(extension);
621
- await client._completeInitialization();
564
+ client._completeInitialization();
622
565
  return client;
623
566
  };
624
567
  exports.createPostHogCore = __webpack_exports__.createPostHogCore;