@posthog/browser 0.1.1 → 0.2.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 (64) hide show
  1. package/ARCHITECTURE.md +28 -22
  2. package/README.md +65 -29
  3. package/dist/analytics-api.d.ts +26 -0
  4. package/dist/analytics-api.js +18 -0
  5. package/dist/analytics-api.mjs +1 -0
  6. package/dist/analytics-buffer.d.ts +3 -3
  7. package/dist/analytics-buffer.js +2 -161
  8. package/dist/analytics-buffer.mjs +2 -161
  9. package/dist/analytics-extension.d.ts +76 -0
  10. package/dist/analytics-extension.js +589 -0
  11. package/dist/analytics-extension.mjs +551 -0
  12. package/dist/analytics-internal.d.ts +32 -18
  13. package/dist/analytics-options.d.ts +7 -2
  14. package/dist/analytics-options.js +38 -1
  15. package/dist/analytics-options.mjs +17 -1
  16. package/dist/analytics.d.ts +4 -3
  17. package/dist/autocapture.d.ts +2 -2
  18. package/dist/autocapture.js +21 -10
  19. package/dist/autocapture.mjs +21 -10
  20. package/dist/automatic-analytics.d.ts +2 -2
  21. package/dist/browser-client.d.ts +44 -4
  22. package/dist/capture-properties.d.ts +9 -0
  23. package/dist/capture-properties.js +68 -0
  24. package/dist/capture-properties.mjs +30 -0
  25. package/dist/capture-v1.js +7 -19
  26. package/dist/capture-v1.mjs +1 -13
  27. package/dist/core.d.ts +7 -5
  28. package/dist/extensions/registry.d.ts +42 -7
  29. package/dist/extensions/registry.js +194 -37
  30. package/dist/extensions/registry.mjs +194 -37
  31. package/dist/flags-token.d.ts +4 -4
  32. package/dist/flags.js +15 -2
  33. package/dist/flags.mjs +15 -2
  34. package/dist/immutable.d.ts +1 -0
  35. package/dist/immutable.js +46 -0
  36. package/dist/immutable.mjs +8 -0
  37. package/dist/index.d.ts +7 -5
  38. package/dist/index.js +3 -67
  39. package/dist/index.mjs +3 -67
  40. package/dist/logs-internal.d.ts +2 -2
  41. package/dist/logs.js +5 -2
  42. package/dist/logs.mjs +5 -2
  43. package/dist/person-processing.d.ts +11 -0
  44. package/dist/person-processing.js +84 -0
  45. package/dist/person-processing.mjs +37 -0
  46. package/dist/posthog.d.ts +4 -3
  47. package/dist/posthog.js +153 -353
  48. package/dist/posthog.mjs +153 -353
  49. package/dist/root-composition.d.ts +11 -0
  50. package/dist/root-composition.js +138 -0
  51. package/dist/root-composition.mjs +100 -0
  52. package/dist/state.d.ts +1 -0
  53. package/dist/state.js +4 -0
  54. package/dist/state.mjs +4 -0
  55. package/dist/surveys-extension.js +11 -6
  56. package/dist/surveys-extension.mjs +11 -6
  57. package/dist/surveys-internal.d.ts +3 -2
  58. package/dist/types.d.ts +13 -19
  59. package/dist/utf8.d.ts +1 -0
  60. package/dist/utf8.js +52 -0
  61. package/dist/utf8.mjs +14 -0
  62. package/dist/version.js +1 -1
  63. package/dist/version.mjs +1 -1
  64. package/package.json +5 -5
package/dist/posthog.js CHANGED
@@ -32,22 +32,16 @@ __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 external_analytics_buffer_js_namespaceObject = require("./analytics-buffer.js");
36
35
  const external_analytics_internal_js_namespaceObject = require("./analytics-internal.js");
37
36
  const external_bot_filter_js_namespaceObject = require("./bot-filter.js");
38
- const external_capture_summary_js_namespaceObject = require("./capture-summary.js");
39
37
  const registry_js_namespaceObject = require("./extensions/registry.js");
40
- const external_id_js_namespaceObject = require("./id.js");
38
+ const external_immutable_js_namespaceObject = require("./immutable.js");
41
39
  const external_logger_js_namespaceObject = require("./logger.js");
42
- const external_rate_limiter_js_namespaceObject = require("./rate-limiter.js");
43
40
  const external_request_js_namespaceObject = require("./request.js");
44
41
  const external_state_js_namespaceObject = require("./state.js");
45
42
  const external_version_js_namespaceObject = require("./version.js");
46
43
  const CONSENT_CHANGE_EVENT = '__posthog_browser_consent_change__';
47
44
  const DEFAULT_SHUTDOWN_TIMEOUT_MS = 30000;
48
- const CLIENT_RATE_LIMIT_WARNING = '$$client_ingestion_warning';
49
- const isNonEmptyString = (value)=>'string' == typeof value && value.trim().length > 0;
50
- const isRecord = (value)=>'object' == typeof value && null !== value && !Array.isArray(value);
51
45
  const normalizeHost = (host)=>{
52
46
  let end = host.length;
53
47
  while(end > 0 && 47 === host.charCodeAt(end - 1))end--;
@@ -63,20 +57,6 @@ const getAssetsHost = (apiHost)=>{
63
57
  } catch {}
64
58
  return apiHost;
65
59
  };
66
- const isValidDistinctId = (value)=>isNonEmptyString(value) && ![
67
- '$posthog_cookieless',
68
- 'distinct_id',
69
- 'distinctid',
70
- 'undefined',
71
- 'null'
72
- ].includes(value.toLowerCase());
73
- const deepFreeze = (value)=>{
74
- if (value && 'object' == typeof value) {
75
- Object.values(value).forEach(deepFreeze);
76
- Object.freeze(value);
77
- }
78
- return value;
79
- };
80
60
  const getDefaultFetch = ()=>{
81
61
  try {
82
62
  return globalThis.fetch?.bind(globalThis);
@@ -91,41 +71,20 @@ const getDefaultNavigator = ()=>{
91
71
  return;
92
72
  }
93
73
  };
94
- const eventTimestamp = (timestamp)=>{
95
- try {
96
- return (timestamp ?? new Date()).toISOString();
97
- } catch {
98
- return new Date().toISOString();
74
+ class PostHog {
75
+ static create(options, loaders) {
76
+ return new PostHog(options, loaders);
99
77
  }
100
- };
101
- const utf8Bytes = (value)=>{
102
- let bytes = 0;
103
- for(let index = 0; index < value.length; index++){
104
- const code = value.charCodeAt(index);
105
- if (code < 0x80) bytes++;
106
- else if (code < 0x800) bytes += 2;
107
- else if (code >= 0xd800 && code <= 0xdbff && value.charCodeAt(index + 1) >= 0xdc00) {
108
- bytes += 4;
109
- index++;
110
- } else bytes += 3;
111
- }
112
- return bytes;
113
- };
114
- class PostHogBrowserClient {
115
- static create(options, capture) {
116
- return new PostHogBrowserClient(options, capture);
117
- }
118
- constructor(options, capture){
78
+ constructor(options, loaders){
119
79
  this.library = Object.freeze({
120
80
  name: 'web',
121
81
  version: external_version_js_namespaceObject.version
122
82
  });
123
- this._dynamicEventProperties = [];
124
- this._rateLimiter = new external_rate_limiter_js_namespaceObject.ClientRateLimiter();
125
83
  this._immediateAuthority = {};
126
84
  this._closing = false;
127
85
  this._disposed = false;
128
86
  this._initialPageviewPending = true;
87
+ this._ready = false;
129
88
  let projectToken = '';
130
89
  try {
131
90
  projectToken = options.projectToken ?? '';
@@ -136,14 +95,16 @@ class PostHogBrowserClient {
136
95
  if (!projectToken) this.logger.error('A PostHog project token is required');
137
96
  const initialPersonProperties = options.initialPersonProperties;
138
97
  try {
139
- this.initialPersonProperties = initialPersonProperties ? deepFreeze(JSON.parse(JSON.stringify(initialPersonProperties))) : Object.freeze({});
98
+ this.initialPersonProperties = initialPersonProperties ? (0, external_immutable_js_namespaceObject.deepFreeze)(JSON.parse(JSON.stringify(initialPersonProperties))) : Object.freeze({});
140
99
  } catch {
141
100
  this.initialPersonProperties = Object.freeze({});
142
101
  }
143
102
  this._remoteConfigPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A remote configuration listener failed', error));
144
103
  this._eventPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('An event listener failed', error));
145
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));
146
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));
147
108
  this._resetPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A reset listener failed', error));
148
109
  this._newSessionPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A session listener failed', error));
149
110
  this._consentChangePublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A consent change listener failed', error));
@@ -155,7 +116,7 @@ class PostHogBrowserClient {
155
116
  this._state = new external_state_js_namespaceObject.BrowserState(projectToken, storage, options.persistenceKey, options.consentPersistenceName, options.optOutByDefault ?? false, !this._blocked && void 0 === options.storage && void 0 !== requestedStorage ? external_state_js_namespaceObject.getDefaultSessionStorage : void 0, (consent, previous)=>{
156
117
  if ('denied' === consent) {
157
118
  this._immediateAuthority = {};
158
- this._captureSink?.purge();
119
+ this._analytics?.purge();
159
120
  }
160
121
  this._consentChangePublisher.publish({
161
122
  current: consent,
@@ -194,15 +155,15 @@ class PostHogBrowserClient {
194
155
  else if (!this._closing && !this._disposed) this.getRemoteConfig();
195
156
  return subscription;
196
157
  };
197
- this.onEvent = this._eventPublisher.listener;
198
158
  this.onIdentify = this._identifyPublisher.listener;
199
159
  this.onGroup = this._groupPublisher.listener;
160
+ this.onGroupsReset = this._groupsResetPublisher.listener;
200
161
  this.onReset = this._resetPublisher.listener;
201
162
  this.onConsentChange = this._consentChangePublisher.listener;
202
163
  this.onNewSession = this._newSessionPublisher.listener;
203
164
  this.onSession = (listener)=>this.onNewSession((session)=>listener(session.sessionId));
204
- this._registry = new registry_js_namespaceObject.ExtensionRegistry((extensionName)=>this._createExtensionClient(extensionName), this.logger);
205
- this._captureSink = capture;
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);
206
167
  }
207
168
  get distinctId() {
208
169
  this._state.prepare();
@@ -230,223 +191,6 @@ class PostHogBrowserClient {
230
191
  get canCapture() {
231
192
  return !this._closing && !this._disposed && !this._blocked && !this.hasOptedOut() && this._state.prepare();
232
193
  }
233
- get isRateLimited() {
234
- return this._rateLimiter.wouldLimit;
235
- }
236
- capture(event, properties = null, options = {}) {
237
- try {
238
- if ('unload' === options.delivery && !this._captureSink?.isTearingDown) {
239
- const authority = this._immediateAuthority;
240
- const message = this._admitCapture(event, properties, options, false, true);
241
- if (message) this._captureSink?.deliverUnload(message, ()=>this._immediateAuthority === authority);
242
- return !!message || !this._rateLimiter.limited;
243
- }
244
- } catch (error) {
245
- this.logger.error('Unload capture failed', error);
246
- return true;
247
- }
248
- return this._capture(event, properties, options) || !this._rateLimiter.limited;
249
- }
250
- async captureImmediate(event, properties = null, options = {}) {
251
- try {
252
- const authority = this._immediateAuthority;
253
- const message = this._admitCapture(event, properties, options, false, true);
254
- if (!message) return external_capture_summary_js_namespaceObject.EMPTY_CAPTURE_SUMMARY;
255
- const capture = this._captureSink;
256
- if (!capture) return (0, external_capture_summary_js_namespaceObject.captureFailure)(new Error('Immediate analytics delivery is unavailable'));
257
- return await capture.deliverImmediate(message, ()=>this._immediateAuthority === authority);
258
- } catch (error) {
259
- return (0, external_capture_summary_js_namespaceObject.captureFailure)(error);
260
- }
261
- }
262
- _capture(event, properties = null, options = {}, skipRateLimit = false) {
263
- return void 0 !== this._admitCapture(event, properties, options, skipRateLimit, false);
264
- }
265
- _admitCapture(event, properties, options, skipRateLimit, immediate) {
266
- if (!isNonEmptyString(event) || this._closing || this._disposed || this._blocked || this.hasOptedOut() || !this._state.prepare()) return;
267
- if (!skipRateLimit) {
268
- const rateLimit = this._rateLimiter.consume();
269
- if (!rateLimit.allowed) {
270
- if (void 0 !== rateLimit.reportDropped) {
271
- const warning = `${rateLimit.reportDropped} event(s) dropped since the last warning. Client limit is 10 events per second with a burst of 100.`;
272
- this.logger.warn(`PostHog client rate limited: ${warning}`);
273
- if (this._capture(CLIENT_RATE_LIMIT_WARNING, {
274
- $$client_ingestion_warning_message: `posthog-js client rate limited: ${warning}`
275
- }, {}, true)) this._rateLimiter.reported();
276
- }
277
- return;
278
- }
279
- }
280
- const dynamicProperties = {};
281
- for (const producer of this._dynamicEventProperties.slice())try {
282
- Object.assign(dynamicProperties, producer());
283
- } catch (error) {
284
- this.logger.error('An event property producer failed', error);
285
- }
286
- let messageProperties;
287
- let observedProperties;
288
- let uuid;
289
- let timestamp;
290
- try {
291
- const callerProperties = {
292
- ...dynamicProperties,
293
- ...properties ?? {}
294
- };
295
- const set = options.set;
296
- const setOnce = options.setOnce;
297
- uuid = options.uuid;
298
- timestamp = options.timestamp;
299
- if (set) callerProperties['$set'] = set;
300
- if (setOnce) callerProperties['$set_once'] = setOnce;
301
- const serializedProperties = JSON.stringify(callerProperties);
302
- const parsedMessageProperties = JSON.parse(serializedProperties, function(_key, value) {
303
- return null !== value || Array.isArray(this) ? value : void 0;
304
- });
305
- const parsedObservedProperties = JSON.parse(serializedProperties);
306
- if (!isRecord(parsedMessageProperties) || !isRecord(parsedObservedProperties)) throw new Error('Event properties must serialize to an object');
307
- messageProperties = parsedMessageProperties;
308
- observedProperties = parsedObservedProperties;
309
- } catch (error) {
310
- this.logger.error('Event properties are not JSON-serializable', error);
311
- return;
312
- }
313
- const preparedSession = this._state.prepareSessionForEvent();
314
- const session = preparedSession.context;
315
- const distinctId = this._state.distinctId;
316
- const deviceId = this._state.deviceId;
317
- const groups = this._state.groups;
318
- Object.assign(messageProperties, {
319
- token: this.projectToken,
320
- distinct_id: distinctId,
321
- $device_id: deviceId,
322
- $groups: groups,
323
- $session_id: session.sessionId,
324
- $window_id: session.windowId,
325
- $lib: 'web',
326
- $lib_version: external_version_js_namespaceObject.version
327
- });
328
- Object.assign(observedProperties, {
329
- token: this.projectToken,
330
- distinct_id: distinctId,
331
- $device_id: deviceId,
332
- $groups: {
333
- ...groups
334
- },
335
- $session_id: session.sessionId,
336
- $window_id: session.windowId,
337
- $lib: 'web',
338
- $lib_version: external_version_js_namespaceObject.version
339
- });
340
- const message = {
341
- uuid: uuid ?? (0, external_id_js_namespaceObject.createId)(),
342
- event,
343
- distinct_id: distinctId,
344
- properties: messageProperties,
345
- timestamp: eventTimestamp(timestamp)
346
- };
347
- let bytes;
348
- try {
349
- bytes = utf8Bytes(JSON.stringify(message));
350
- } catch (error) {
351
- this.logger.error('The finalized event could not be measured', error);
352
- return;
353
- }
354
- const capture = this._captureSink;
355
- if (immediate ? bytes > external_analytics_internal_js_namespaceObject.MAX_ANALYTICS_BYTES : !capture?.enqueue(message, bytes)) {
356
- if (bytes > external_analytics_internal_js_namespaceObject.MAX_ANALYTICS_BYTES) this.logger.warn(`Event "${event}" (${bytes} bytes) exceeds the local analytics limit and was dropped`);
357
- return;
358
- }
359
- if (!this._state.sessionAdmitted(preparedSession)) {
360
- if (!immediate) capture?.discardQueued(message);
361
- return;
362
- }
363
- if (preparedSession.reason) this._newSessionPublisher.publish({
364
- ...session,
365
- reason: preparedSession.reason
366
- });
367
- this._eventPublisher.publish(deepFreeze({
368
- event,
369
- properties: observedProperties
370
- }));
371
- if (!immediate) capture?.admitted();
372
- return message;
373
- }
374
- async identify(distinctId, set, setOnce) {
375
- if (!isValidDistinctId(distinctId) || this._closing || this._disposed) return;
376
- this._state.prepare();
377
- const previousDistinctId = this._state.distinctId;
378
- const wasIdentified = this._state.isIdentified;
379
- const captureOptions = {};
380
- if (set) captureOptions.set = set;
381
- if (setOnce) captureOptions.setOnce = setOnce;
382
- const hasPersonProperties = !!set || !!setOnce;
383
- if (distinctId === previousDistinctId) {
384
- if (wasIdentified) {
385
- if (hasPersonProperties) {
386
- this._identifyPublisher.publish({
387
- distinctId,
388
- previousDistinctId,
389
- wasIdentified,
390
- set,
391
- setOnce
392
- });
393
- this.capture('$set', null, captureOptions);
394
- }
395
- } else {
396
- this._state.identify(distinctId);
397
- this._identifyPublisher.publish({
398
- distinctId,
399
- previousDistinctId,
400
- wasIdentified,
401
- set,
402
- setOnce
403
- });
404
- this.capture('$set', null, {
405
- set: set ?? {},
406
- setOnce: setOnce ?? {}
407
- });
408
- }
409
- return;
410
- }
411
- this._state.identify(distinctId);
412
- this._identifyPublisher.publish({
413
- distinctId,
414
- previousDistinctId,
415
- wasIdentified,
416
- set,
417
- setOnce
418
- });
419
- if (wasIdentified) {
420
- if (hasPersonProperties) this.capture('$set', null, captureOptions);
421
- } else this.capture('$identify', {
422
- $anon_distinct_id: previousDistinctId
423
- }, captureOptions);
424
- }
425
- async group(type, key, properties) {
426
- if (!isNonEmptyString(type) || !isNonEmptyString(key) || this._closing || this._disposed) return;
427
- this._state.prepare();
428
- const changed = this._state.group(type, key);
429
- if (!changed && !properties) return;
430
- this._groupPublisher.publish({
431
- type,
432
- key,
433
- changed,
434
- properties
435
- });
436
- this.capture('$groupidentify', {
437
- $group_type: type,
438
- $group_key: key,
439
- ...properties ? {
440
- $group_set: properties
441
- } : {}
442
- });
443
- }
444
- reset() {
445
- if (this._closing || this._disposed) return;
446
- this._state.prepare();
447
- this._state.reset();
448
- this._resetPublisher.publish(void 0);
449
- }
450
194
  async flush() {
451
195
  await this._registry.flush();
452
196
  }
@@ -461,21 +205,6 @@ class PostHogBrowserClient {
461
205
  hasOptedOut() {
462
206
  return 'denied' === this._state.consent;
463
207
  }
464
- registerDynamicEventProperties(producer) {
465
- if (this._disposed) return {
466
- dispose () {}
467
- };
468
- this._dynamicEventProperties.push(producer);
469
- let active = true;
470
- return {
471
- dispose: ()=>{
472
- if (!active) return;
473
- active = false;
474
- const index = this._dynamicEventProperties.indexOf(producer);
475
- if (-1 !== index) this._dynamicEventProperties.splice(index, 1);
476
- }
477
- };
478
- }
479
208
  sendRequest(path, init) {
480
209
  return (0, external_request_js_namespaceObject.sendRequest)(this._requestRuntime, path, init, ()=>!this._blocked && !this.hasOptedOut());
481
210
  }
@@ -551,8 +280,8 @@ class PostHogBrowserClient {
551
280
  }
552
281
  return this._remoteConfigPromise;
553
282
  }
554
- getExtension(name) {
555
- return this._registry.get(name);
283
+ resolveExtension(name) {
284
+ return this._closing || this._disposed ? Promise.resolve(void 0) : this._registry.resolve(name);
556
285
  }
557
286
  shutdown(shutdownTimeoutMs = DEFAULT_SHUTDOWN_TIMEOUT_MS) {
558
287
  if (!this._shutdownPromise) {
@@ -598,16 +327,17 @@ class PostHogBrowserClient {
598
327
  } catch (error) {
599
328
  this.logger.error('Failed to dispose browser state', error);
600
329
  }
601
- this._captureSink = void 0;
330
+ this._analytics = void 0;
602
331
  const cleanup = this._registry.dispose().catch((error)=>this.logger.error('Failed to dispose extensions', error));
603
332
  this._remoteConfigPublisher.dispose();
604
333
  this._eventPublisher.dispose();
605
334
  this._identifyPublisher.dispose();
335
+ this._changePropertiesPublisher.dispose();
606
336
  this._groupPublisher.dispose();
337
+ this._groupsResetPublisher.dispose();
607
338
  this._resetPublisher.dispose();
608
339
  this._consentChangePublisher.dispose();
609
340
  this._newSessionPublisher.dispose();
610
- this._dynamicEventProperties.splice(0);
611
341
  await Promise.race([
612
342
  cleanup,
613
343
  timeout
@@ -621,43 +351,63 @@ class PostHogBrowserClient {
621
351
  } catch {}
622
352
  }
623
353
  }
354
+ async _completeInitialization() {
355
+ await this._analytics?.start();
356
+ this._ready = true;
357
+ this._startInitialPageview();
358
+ await this._pageviewLoading;
359
+ }
624
360
  _startInitialPageview() {
625
- if (!this._capturePageview || !this._initialPageviewPending || this._closing || this._disposed) return;
361
+ if (!this._ready || !this._capturePageview || !this._initialPageviewPending || this._closing || this._disposed || !this._pageviewIsVisible()) return;
362
+ this._removePageviewListener();
363
+ if (!this._analytics) return void this._loadInitialPageviewAnalytics();
364
+ this._initialPageviewPending = false;
365
+ if (!this._analytics.captureInitialPageview()) this._initialPageviewPending = !this._disposed && !this._blocked;
366
+ }
367
+ _pageviewIsVisible() {
626
368
  let document;
627
369
  let visibility;
628
370
  try {
629
371
  document = globalThis.document;
630
372
  visibility = document?.visibilityState;
631
373
  } catch {
632
- this._removePageviewListener();
633
- this._initialPageviewPending = false;
634
- return;
374
+ this._cancelInitialPageview();
375
+ return false;
635
376
  }
636
377
  if (!document || void 0 === visibility) {
637
- this._removePageviewListener();
638
- this._initialPageviewPending = false;
639
- return;
378
+ this._cancelInitialPageview();
379
+ return false;
640
380
  }
641
381
  if ('visible' !== visibility) {
642
- if (this._pageviewListener?.[0] !== document) this._removePageviewListener();
643
- if (!this._pageviewListener) {
644
- const listener = ()=>this._startInitialPageview();
645
- this._pageviewListener = [
646
- document,
647
- listener
648
- ];
649
- try {
650
- document.addEventListener('visibilitychange', listener);
651
- } catch {
652
- this._removePageviewListener();
653
- this._initialPageviewPending = false;
654
- }
655
- }
656
- return;
382
+ this._watchPageviewVisibility(document);
383
+ return false;
657
384
  }
385
+ return true;
386
+ }
387
+ _watchPageviewVisibility(document) {
388
+ if (this._pageviewListener?.[0] !== document) this._removePageviewListener();
389
+ if (this._pageviewListener) return;
390
+ const listener = ()=>this._startInitialPageview();
391
+ this._pageviewListener = [
392
+ document,
393
+ listener
394
+ ];
395
+ try {
396
+ document.addEventListener('visibilitychange', listener);
397
+ } catch {
398
+ this._cancelInitialPageview();
399
+ }
400
+ }
401
+ _cancelInitialPageview() {
658
402
  this._removePageviewListener();
659
403
  this._initialPageviewPending = false;
660
- if (!this._capture('$pageview')) this._initialPageviewPending = !this._disposed && !this._blocked;
404
+ }
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
+ });
661
411
  }
662
412
  _removePageviewListener() {
663
413
  const listener = this._pageviewListener;
@@ -727,7 +477,7 @@ class PostHogBrowserClient {
727
477
  }));
728
478
  } catch {}
729
479
  }
730
- _createExtensionClient(extensionName) {
480
+ _createSharedExtensionClient(extensionName) {
731
481
  const host = this;
732
482
  const logger = this.logger.createLogger(extensionName);
733
483
  const kv = this._state.keyValueStore(extensionName, ()=>!this._closing && !this._disposed && this._state.prepare());
@@ -760,64 +510,114 @@ class PostHogBrowserClient {
760
510
  return host.canCapture;
761
511
  },
762
512
  get isRateLimited () {
763
- return host.isRateLimited;
513
+ return host._analytics?.isRateLimited ?? false;
764
514
  },
765
- capture: (event, properties, options)=>host.capture(event, properties, options),
766
- registerDynamicEventProperties: (producer)=>host.registerDynamicEventProperties(producer),
767
- getExtension: (name)=>host.getExtension(name),
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),
768
520
  get projectToken () {
769
521
  return host.projectToken;
770
522
  },
771
523
  sendRequest: (path, init)=>host.sendRequest(path, init),
772
- onConsentChange: host.onConsentChange,
773
524
  onRemoteConfig: host.onRemoteConfig,
774
- onEvent: host.onEvent,
775
- onIdentify: host.onIdentify,
776
- onGroup: host.onGroup,
777
- onReset: host.onReset,
525
+ onEvent: host._eventPublisher.listener,
778
526
  onSession: host.onSession,
779
527
  kv,
780
528
  logger
781
529
  };
782
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, external_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
+ state: this._state,
581
+ canCapture: ()=>canMutate() && !this._blocked && !this.hasOptedOut(),
582
+ canMutate,
583
+ isDisposed: ()=>this._disposed,
584
+ authority: ()=>this._immediateAuthority,
585
+ onEvent: this._eventPublisher.listener,
586
+ publishEvent: (event)=>this._eventPublisher.publish(event),
587
+ publishNewSession: (session)=>this._newSessionPublisher.publish(session),
588
+ publishIdentify: (info)=>this._identifyPublisher.publish(info),
589
+ publishChangeProperties: (info)=>this._changePropertiesPublisher.publish(info),
590
+ publishGroup: (info)=>this._groupPublisher.publish(info),
591
+ publishGroupsReset: ()=>this._groupsResetPublisher.publish(void 0),
592
+ publishReset: ()=>this._resetPublisher.publish(void 0)
593
+ };
594
+ }
783
595
  _canDeliver() {
784
596
  return !this._disposed && !this._blocked && !this.hasOptedOut();
785
597
  }
786
598
  }
787
- const createPostHogCore = async (options, configured = options?.extensions ?? [])=>{
788
- const analytics = configured.find(external_analytics_internal_js_namespaceObject.isAnalyticsExtension) ?? (0, external_analytics_buffer_js_namespaceObject.createAnalyticsExtension)();
789
- const extensions = configured.filter((extension)=>extension !== analytics);
790
- const client = PostHogBrowserClient.create(options ?? {
599
+ const selectConfiguredExtensions = (configured)=>{
600
+ const selected = new Map();
601
+ for (const extension of configured)if (!selected.has(extension.name)) selected.set(extension.name, extension);
602
+ return selected;
603
+ };
604
+ const createPostHogCore = async (options, configured = options?.extensions ?? [], automaticLoaders = {}, automatic = [])=>{
605
+ const selected = selectConfiguredExtensions(configured);
606
+ const loaders = Object.fromEntries([
607
+ ...Object.entries(automaticLoaders),
608
+ ...Array.from(selected, ([name, extension])=>[
609
+ name,
610
+ ()=>extension
611
+ ])
612
+ ]);
613
+ const client = PostHog.create(options ?? {
791
614
  projectToken: ''
792
- }, analytics);
615
+ }, loaders);
793
616
  client.getRemoteConfig();
794
- let analyticsReady = false;
795
- try {
796
- await client._registry.install(analytics);
797
- analytics.initialize({
798
- runtime: client._requestRuntime,
799
- canRetry: ()=>client._canDeliver(),
800
- reportFailure: (error)=>client.logger.error('Event delivery failed', error),
801
- reportWarning: (message)=>client.logger.warn(message),
802
- onAvailable: ()=>client._startInitialPageview()
803
- });
804
- analyticsReady = true;
805
- } catch (error) {
806
- client._captureSink = void 0;
807
- try {
808
- await client._registry.rollback(analytics);
809
- } catch (cleanupError) {
810
- client.logger.error(`Failed to dispose disabled extension "${analytics.name}"`, cleanupError);
811
- }
812
- client.logger.error(`Failed to install configured extension "${analytics.name}"`, error);
813
- }
814
- for (const extension of extensions)try {
815
- await client._registry.install(extension);
816
- } catch (error) {
817
- client.logger.error(`Failed to install configured extension "${extension.name}"`, error);
818
- }
819
- if (analyticsReady) await analytics.start();
820
- client._startInitialPageview();
617
+ if (selected.has('analytics')) await client.resolveExtension('analytics');
618
+ for (const name of selected.keys())if ('analytics' !== name) await client.resolveExtension(name);
619
+ for (const extension of automatic)await client._registry.activate(extension);
620
+ await client._completeInitialization();
821
621
  return client;
822
622
  };
823
623
  exports.createPostHogCore = __webpack_exports__.createPostHogCore;