@posthog/browser 0.0.0-stage → 0.1.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 (121) hide show
  1. package/ARCHITECTURE.md +559 -0
  2. package/LICENSE +417 -0
  3. package/README.md +302 -2
  4. package/dist/analytics-buffer.d.ts +4 -0
  5. package/dist/analytics-buffer.js +200 -0
  6. package/dist/analytics-buffer.mjs +162 -0
  7. package/dist/analytics-delivery.d.ts +3 -0
  8. package/dist/analytics-delivery.js +231 -0
  9. package/dist/analytics-delivery.mjs +193 -0
  10. package/dist/analytics-internal.d.ts +64 -0
  11. package/dist/analytics-internal.js +52 -0
  12. package/dist/analytics-internal.mjs +5 -0
  13. package/dist/analytics-options.d.ts +14 -0
  14. package/dist/analytics-options.js +18 -0
  15. package/dist/analytics-options.mjs +1 -0
  16. package/dist/analytics.d.ts +5 -0
  17. package/dist/analytics.js +42 -0
  18. package/dist/analytics.mjs +4 -0
  19. package/dist/autocapture-options.d.ts +32 -0
  20. package/dist/autocapture-options.js +49 -0
  21. package/dist/autocapture-options.mjs +11 -0
  22. package/dist/autocapture.d.ts +5 -0
  23. package/dist/autocapture.js +108 -0
  24. package/dist/autocapture.mjs +70 -0
  25. package/dist/automatic-analytics.d.ts +3 -0
  26. package/dist/automatic-analytics.js +44 -0
  27. package/dist/automatic-analytics.mjs +6 -0
  28. package/dist/automatic-surveys.d.ts +2 -0
  29. package/dist/automatic-surveys.js +41 -0
  30. package/dist/automatic-surveys.mjs +3 -0
  31. package/dist/bot-filter.d.ts +2 -0
  32. package/dist/bot-filter.js +87 -0
  33. package/dist/bot-filter.mjs +49 -0
  34. package/dist/browser-client.d.ts +30 -0
  35. package/dist/browser-client.js +18 -0
  36. package/dist/browser-client.mjs +1 -0
  37. package/dist/capture-summary.d.ts +3 -0
  38. package/dist/capture-summary.js +63 -0
  39. package/dist/capture-summary.mjs +22 -0
  40. package/dist/capture-v1.d.ts +105 -0
  41. package/dist/capture-v1.js +781 -0
  42. package/dist/capture-v1.mjs +722 -0
  43. package/dist/core.d.ts +7 -0
  44. package/dist/core.js +49 -0
  45. package/dist/core.mjs +5 -0
  46. package/dist/event-buffer.d.ts +41 -0
  47. package/dist/event-buffer.js +158 -0
  48. package/dist/event-buffer.mjs +120 -0
  49. package/dist/extensions/registry.d.ts +16 -0
  50. package/dist/extensions/registry.js +128 -0
  51. package/dist/extensions/registry.mjs +90 -0
  52. package/dist/flags-internal.d.ts +8 -0
  53. package/dist/flags-internal.js +18 -0
  54. package/dist/flags-internal.mjs +1 -0
  55. package/dist/flags-options.d.ts +22 -0
  56. package/dist/flags-options.js +18 -0
  57. package/dist/flags-options.mjs +1 -0
  58. package/dist/flags-token.d.ts +15 -0
  59. package/dist/flags-token.js +40 -0
  60. package/dist/flags-token.mjs +2 -0
  61. package/dist/flags.d.ts +6 -0
  62. package/dist/flags.js +163 -0
  63. package/dist/flags.mjs +122 -0
  64. package/dist/id.d.ts +1 -0
  65. package/dist/id.js +61 -0
  66. package/dist/id.mjs +23 -0
  67. package/dist/index.d.ts +11 -0
  68. package/dist/index.js +119 -0
  69. package/dist/index.mjs +75 -0
  70. package/dist/lane.d.ts +57 -0
  71. package/dist/lane.js +363 -0
  72. package/dist/lane.mjs +325 -0
  73. package/dist/logger.d.ts +4 -0
  74. package/dist/logger.js +57 -0
  75. package/dist/logger.mjs +19 -0
  76. package/dist/logs-internal.d.ts +7 -0
  77. package/dist/logs-internal.js +18 -0
  78. package/dist/logs-internal.mjs +1 -0
  79. package/dist/logs-options.d.ts +11 -0
  80. package/dist/logs-options.js +57 -0
  81. package/dist/logs-options.mjs +19 -0
  82. package/dist/logs.d.ts +6 -0
  83. package/dist/logs.js +140 -0
  84. package/dist/logs.mjs +102 -0
  85. package/dist/named-error.d.ts +7 -0
  86. package/dist/named-error.js +49 -0
  87. package/dist/named-error.mjs +11 -0
  88. package/dist/posthog.d.ts +3 -0
  89. package/dist/posthog.js +823 -0
  90. package/dist/posthog.mjs +785 -0
  91. package/dist/rate-limiter.d.ts +19 -0
  92. package/dist/rate-limiter.js +89 -0
  93. package/dist/rate-limiter.mjs +51 -0
  94. package/dist/remote-config.d.ts +3 -0
  95. package/dist/remote-config.js +47 -0
  96. package/dist/remote-config.mjs +9 -0
  97. package/dist/request.d.ts +14 -0
  98. package/dist/request.js +130 -0
  99. package/dist/request.mjs +89 -0
  100. package/dist/state.d.ts +82 -0
  101. package/dist/state.js +625 -0
  102. package/dist/state.mjs +581 -0
  103. package/dist/surveys-extension.d.ts +9 -0
  104. package/dist/surveys-extension.js +272 -0
  105. package/dist/surveys-extension.mjs +234 -0
  106. package/dist/surveys-internal.d.ts +12 -0
  107. package/dist/surveys-internal.js +18 -0
  108. package/dist/surveys-internal.mjs +1 -0
  109. package/dist/surveys-options.d.ts +18 -0
  110. package/dist/surveys-options.js +42 -0
  111. package/dist/surveys-options.mjs +4 -0
  112. package/dist/surveys.d.ts +7 -0
  113. package/dist/surveys.js +48 -0
  114. package/dist/surveys.mjs +7 -0
  115. package/dist/types.d.ts +114 -0
  116. package/dist/types.js +18 -0
  117. package/dist/types.mjs +1 -0
  118. package/dist/version.d.ts +1 -0
  119. package/dist/version.js +40 -0
  120. package/dist/version.mjs +2 -0
  121. package/package.json +88 -3
@@ -0,0 +1,823 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, getters, values)=>{
5
+ var define = (defs, kind)=>{
6
+ for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
7
+ enumerable: true,
8
+ [kind]: defs[key]
9
+ });
10
+ };
11
+ define(getters, "get");
12
+ define(values, "value");
13
+ };
14
+ })();
15
+ (()=>{
16
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
17
+ })();
18
+ (()=>{
19
+ __webpack_require__.r = (exports1)=>{
20
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
21
+ value: 'Module'
22
+ });
23
+ Object.defineProperty(exports1, '__esModule', {
24
+ value: true
25
+ });
26
+ };
27
+ })();
28
+ var __webpack_exports__ = {};
29
+ __webpack_require__.r(__webpack_exports__);
30
+ __webpack_require__.d(__webpack_exports__, {
31
+ createPostHogCore: ()=>createPostHogCore
32
+ });
33
+ const external_remote_config_js_namespaceObject = require("./remote-config.js");
34
+ const pubsub_namespaceObject = require("@posthog/browser-common/pubsub");
35
+ const external_analytics_buffer_js_namespaceObject = require("./analytics-buffer.js");
36
+ const external_analytics_internal_js_namespaceObject = require("./analytics-internal.js");
37
+ const external_bot_filter_js_namespaceObject = require("./bot-filter.js");
38
+ const external_capture_summary_js_namespaceObject = require("./capture-summary.js");
39
+ const registry_js_namespaceObject = require("./extensions/registry.js");
40
+ const external_id_js_namespaceObject = require("./id.js");
41
+ const external_logger_js_namespaceObject = require("./logger.js");
42
+ const external_rate_limiter_js_namespaceObject = require("./rate-limiter.js");
43
+ const external_request_js_namespaceObject = require("./request.js");
44
+ const external_state_js_namespaceObject = require("./state.js");
45
+ const external_version_js_namespaceObject = require("./version.js");
46
+ const CONSENT_CHANGE_EVENT = '__posthog_browser_consent_change__';
47
+ 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
+ const normalizeHost = (host)=>{
52
+ let end = host.length;
53
+ while(end > 0 && 47 === host.charCodeAt(end - 1))end--;
54
+ return end === host.length ? host : host.slice(0, end);
55
+ };
56
+ const getAssetsHost = (apiHost)=>{
57
+ try {
58
+ const url = new URL(apiHost);
59
+ if ('https:' === url.protocol) {
60
+ const region = /^(app|us|us-assets|eu|eu-assets)(\.i)?\.posthog\.com$/.exec(url.hostname)?.[1];
61
+ if (region) return `https://${region.startsWith('eu') ? 'eu' : 'us'}-assets.i.posthog.com`;
62
+ }
63
+ } catch {}
64
+ return apiHost;
65
+ };
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
+ const getDefaultFetch = ()=>{
81
+ try {
82
+ return globalThis.fetch?.bind(globalThis);
83
+ } catch {
84
+ return;
85
+ }
86
+ };
87
+ const getDefaultNavigator = ()=>{
88
+ try {
89
+ return globalThis.navigator;
90
+ } catch {
91
+ return;
92
+ }
93
+ };
94
+ const eventTimestamp = (timestamp)=>{
95
+ try {
96
+ return (timestamp ?? new Date()).toISOString();
97
+ } catch {
98
+ return new Date().toISOString();
99
+ }
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){
119
+ this.library = Object.freeze({
120
+ name: 'web',
121
+ version: external_version_js_namespaceObject.version
122
+ });
123
+ this._dynamicEventProperties = [];
124
+ this._rateLimiter = new external_rate_limiter_js_namespaceObject.ClientRateLimiter();
125
+ this._immediateAuthority = {};
126
+ this._closing = false;
127
+ this._disposed = false;
128
+ this._initialPageviewPending = true;
129
+ let projectToken = '';
130
+ try {
131
+ projectToken = options.projectToken ?? '';
132
+ } catch {}
133
+ this.projectToken = projectToken;
134
+ this._capturePageview = options.capturePageview ?? true;
135
+ this.logger = (0, external_logger_js_namespaceObject.createLogger)('[PostHog]', options.debug ?? false);
136
+ if (!projectToken) this.logger.error('A PostHog project token is required');
137
+ const initialPersonProperties = options.initialPersonProperties;
138
+ try {
139
+ this.initialPersonProperties = initialPersonProperties ? deepFreeze(JSON.parse(JSON.stringify(initialPersonProperties))) : Object.freeze({});
140
+ } catch {
141
+ this.initialPersonProperties = Object.freeze({});
142
+ }
143
+ this._remoteConfigPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A remote configuration listener failed', error));
144
+ this._eventPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('An event listener failed', error));
145
+ this._identifyPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('An identify listener failed', error));
146
+ this._groupPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A group listener failed', error));
147
+ this._resetPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A reset listener failed', error));
148
+ this._newSessionPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A session listener failed', error));
149
+ this._consentChangePublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A consent change listener failed', error));
150
+ const browserNavigator = false === options.navigator ? void 0 : options.navigator ?? getDefaultNavigator();
151
+ const browserFetch = false === options.fetch ? void 0 : options.fetch ?? getDefaultFetch();
152
+ this._blocked = !projectToken || !(options.disableBotDetection ?? false) && (0, external_bot_filter_js_namespaceObject.isLikelyBot)(browserNavigator, options.blockedUserAgents ?? []);
153
+ const requestedStorage = false === options.storage ? void 0 : options.storage ?? (0, external_state_js_namespaceObject.getDefaultStorage)();
154
+ const storage = this._blocked ? void 0 : requestedStorage;
155
+ 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
+ if ('denied' === consent) {
157
+ this._immediateAuthority = {};
158
+ this._captureSink?.purge();
159
+ }
160
+ this._consentChangePublisher.publish({
161
+ current: consent,
162
+ previous
163
+ });
164
+ });
165
+ this._consentObservation = this._observeConsent(storage, !this._blocked && void 0 === options.storage && void 0 !== requestedStorage);
166
+ const apiHost = normalizeHost(options.apiHost ?? 'https://us.i.posthog.com');
167
+ this._requestRuntime = [
168
+ {
169
+ api: apiHost,
170
+ flags: normalizeHost(options.flagsHost ?? apiHost),
171
+ assets: getAssetsHost(apiHost)
172
+ },
173
+ projectToken,
174
+ browserFetch,
175
+ browserNavigator
176
+ ];
177
+ this._remoteConfig = options.remoteConfig;
178
+ this._remoteConfigTimeoutMs = void 0 !== options.remoteConfigTimeoutMs && Number.isFinite(options.remoteConfigTimeoutMs) ? Math.max(0, options.remoteConfigTimeoutMs) : 10000;
179
+ this.kv = this._state.keyValueStore('core', ()=>!this._closing && !this._disposed && this._state.prepare());
180
+ this._latestRemoteConfigResult = this._remoteConfig ? {
181
+ ok: true,
182
+ config: this._remoteConfig
183
+ } : void 0;
184
+ this.onRemoteConfig = (handler)=>{
185
+ if (this._closing || this._disposed) return {
186
+ dispose () {}
187
+ };
188
+ const subscription = this._remoteConfigPublisher.listener(handler);
189
+ if (this._latestRemoteConfigResult) try {
190
+ handler(this._latestRemoteConfigResult);
191
+ } catch (error) {
192
+ this.logger.error('A remote configuration listener failed', error);
193
+ }
194
+ else if (!this._closing && !this._disposed) this.getRemoteConfig();
195
+ return subscription;
196
+ };
197
+ this.onEvent = this._eventPublisher.listener;
198
+ this.onIdentify = this._identifyPublisher.listener;
199
+ this.onGroup = this._groupPublisher.listener;
200
+ this.onReset = this._resetPublisher.listener;
201
+ this.onConsentChange = this._consentChangePublisher.listener;
202
+ this.onNewSession = this._newSessionPublisher.listener;
203
+ 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;
206
+ }
207
+ get distinctId() {
208
+ this._state.prepare();
209
+ return this._state.distinctId;
210
+ }
211
+ get anonymousId() {
212
+ this._state.prepare();
213
+ return this._state.anonymousId;
214
+ }
215
+ get deviceId() {
216
+ this._state.prepare();
217
+ return this._state.deviceId;
218
+ }
219
+ get groups() {
220
+ this._state.prepare();
221
+ return this._state.groups;
222
+ }
223
+ get session() {
224
+ this._state.prepare();
225
+ return this._state.session;
226
+ }
227
+ get isOptedOut() {
228
+ return this.hasOptedOut();
229
+ }
230
+ get canCapture() {
231
+ return !this._closing && !this._disposed && !this._blocked && !this.hasOptedOut() && this._state.prepare();
232
+ }
233
+ capture(event, properties = null, options = {}) {
234
+ try {
235
+ if ('unload' === options.delivery && !this._captureSink?.isTearingDown) {
236
+ const authority = this._immediateAuthority;
237
+ const message = this._admitCapture(event, properties, options, false, true);
238
+ if (message) this._captureSink?.deliverUnload(message, ()=>this._immediateAuthority === authority);
239
+ return;
240
+ }
241
+ } catch (error) {
242
+ this.logger.error('Unload capture failed', error);
243
+ return;
244
+ }
245
+ this._capture(event, properties, options);
246
+ }
247
+ async captureImmediate(event, properties = null, options = {}) {
248
+ try {
249
+ const authority = this._immediateAuthority;
250
+ const message = this._admitCapture(event, properties, options, false, true);
251
+ if (!message) return external_capture_summary_js_namespaceObject.EMPTY_CAPTURE_SUMMARY;
252
+ const capture = this._captureSink;
253
+ if (!capture) return (0, external_capture_summary_js_namespaceObject.captureFailure)(new Error('Immediate analytics delivery is unavailable'));
254
+ return await capture.deliverImmediate(message, ()=>this._immediateAuthority === authority);
255
+ } catch (error) {
256
+ return (0, external_capture_summary_js_namespaceObject.captureFailure)(error);
257
+ }
258
+ }
259
+ _capture(event, properties = null, options = {}, skipRateLimit = false) {
260
+ return void 0 !== this._admitCapture(event, properties, options, skipRateLimit, false);
261
+ }
262
+ _admitCapture(event, properties, options, skipRateLimit, immediate) {
263
+ if (!isNonEmptyString(event) || this._closing || this._disposed || this._blocked || this.hasOptedOut() || !this._state.prepare()) return;
264
+ if (!skipRateLimit) {
265
+ const rateLimit = this._rateLimiter.consume();
266
+ if (!rateLimit.allowed) {
267
+ if (void 0 !== rateLimit.reportDropped) {
268
+ const warning = `${rateLimit.reportDropped} event(s) dropped since the last warning. Client limit is 10 events per second with a burst of 100.`;
269
+ this.logger.warn(`PostHog client rate limited: ${warning}`);
270
+ if (this._capture(CLIENT_RATE_LIMIT_WARNING, {
271
+ $$client_ingestion_warning_message: `posthog-js client rate limited: ${warning}`
272
+ }, {}, true)) this._rateLimiter.reported();
273
+ }
274
+ return;
275
+ }
276
+ }
277
+ const dynamicProperties = {};
278
+ for (const producer of this._dynamicEventProperties.slice())try {
279
+ Object.assign(dynamicProperties, producer());
280
+ } catch (error) {
281
+ this.logger.error('An event property producer failed', error);
282
+ }
283
+ let messageProperties;
284
+ let observedProperties;
285
+ let uuid;
286
+ let timestamp;
287
+ try {
288
+ const callerProperties = {
289
+ ...dynamicProperties,
290
+ ...properties ?? {}
291
+ };
292
+ const set = options.set;
293
+ const setOnce = options.setOnce;
294
+ uuid = options.uuid;
295
+ timestamp = options.timestamp;
296
+ if (set) callerProperties['$set'] = set;
297
+ if (setOnce) callerProperties['$set_once'] = setOnce;
298
+ const serializedProperties = JSON.stringify(callerProperties);
299
+ const parsedMessageProperties = JSON.parse(serializedProperties, function(_key, value) {
300
+ return null !== value || Array.isArray(this) ? value : void 0;
301
+ });
302
+ const parsedObservedProperties = JSON.parse(serializedProperties);
303
+ if (!isRecord(parsedMessageProperties) || !isRecord(parsedObservedProperties)) throw new Error('Event properties must serialize to an object');
304
+ messageProperties = parsedMessageProperties;
305
+ observedProperties = parsedObservedProperties;
306
+ } catch (error) {
307
+ this.logger.error('Event properties are not JSON-serializable', error);
308
+ return;
309
+ }
310
+ const preparedSession = this._state.prepareSessionForEvent();
311
+ const session = preparedSession.context;
312
+ const distinctId = this._state.distinctId;
313
+ const deviceId = this._state.deviceId;
314
+ const groups = this._state.groups;
315
+ Object.assign(messageProperties, {
316
+ token: this.projectToken,
317
+ distinct_id: distinctId,
318
+ $device_id: deviceId,
319
+ $groups: groups,
320
+ $session_id: session.sessionId,
321
+ $window_id: session.windowId,
322
+ $lib: 'web',
323
+ $lib_version: external_version_js_namespaceObject.version
324
+ });
325
+ Object.assign(observedProperties, {
326
+ token: this.projectToken,
327
+ distinct_id: distinctId,
328
+ $device_id: deviceId,
329
+ $groups: {
330
+ ...groups
331
+ },
332
+ $session_id: session.sessionId,
333
+ $window_id: session.windowId,
334
+ $lib: 'web',
335
+ $lib_version: external_version_js_namespaceObject.version
336
+ });
337
+ const message = {
338
+ uuid: uuid ?? (0, external_id_js_namespaceObject.createId)(),
339
+ event,
340
+ distinct_id: distinctId,
341
+ properties: messageProperties,
342
+ timestamp: eventTimestamp(timestamp)
343
+ };
344
+ let bytes;
345
+ try {
346
+ bytes = utf8Bytes(JSON.stringify(message));
347
+ } catch (error) {
348
+ this.logger.error('The finalized event could not be measured', error);
349
+ return;
350
+ }
351
+ const capture = this._captureSink;
352
+ if (immediate ? bytes > external_analytics_internal_js_namespaceObject.MAX_ANALYTICS_BYTES : !capture?.enqueue(message, bytes)) {
353
+ 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`);
354
+ return;
355
+ }
356
+ if (!this._state.sessionAdmitted(preparedSession)) {
357
+ if (!immediate) capture?.discardQueued(message);
358
+ return;
359
+ }
360
+ if (preparedSession.reason) this._newSessionPublisher.publish({
361
+ ...session,
362
+ reason: preparedSession.reason
363
+ });
364
+ this._eventPublisher.publish(deepFreeze({
365
+ event,
366
+ properties: observedProperties
367
+ }));
368
+ if (!immediate) capture?.admitted();
369
+ return message;
370
+ }
371
+ async identify(distinctId, set, setOnce) {
372
+ if (!isValidDistinctId(distinctId) || this._closing || this._disposed) return;
373
+ this._state.prepare();
374
+ const previousDistinctId = this._state.distinctId;
375
+ const wasIdentified = this._state.isIdentified;
376
+ const captureOptions = {};
377
+ if (set) captureOptions.set = set;
378
+ if (setOnce) captureOptions.setOnce = setOnce;
379
+ const hasPersonProperties = !!set || !!setOnce;
380
+ if (distinctId === previousDistinctId) {
381
+ if (wasIdentified) {
382
+ if (hasPersonProperties) {
383
+ this._identifyPublisher.publish({
384
+ distinctId,
385
+ previousDistinctId,
386
+ wasIdentified,
387
+ set,
388
+ setOnce
389
+ });
390
+ this.capture('$set', null, captureOptions);
391
+ }
392
+ } else {
393
+ this._state.identify(distinctId);
394
+ this._identifyPublisher.publish({
395
+ distinctId,
396
+ previousDistinctId,
397
+ wasIdentified,
398
+ set,
399
+ setOnce
400
+ });
401
+ this.capture('$set', null, {
402
+ set: set ?? {},
403
+ setOnce: setOnce ?? {}
404
+ });
405
+ }
406
+ return;
407
+ }
408
+ this._state.identify(distinctId);
409
+ this._identifyPublisher.publish({
410
+ distinctId,
411
+ previousDistinctId,
412
+ wasIdentified,
413
+ set,
414
+ setOnce
415
+ });
416
+ if (wasIdentified) {
417
+ if (hasPersonProperties) this.capture('$set', null, captureOptions);
418
+ } else this.capture('$identify', {
419
+ $anon_distinct_id: previousDistinctId
420
+ }, captureOptions);
421
+ }
422
+ async group(type, key, properties) {
423
+ if (!isNonEmptyString(type) || !isNonEmptyString(key) || this._closing || this._disposed) return;
424
+ this._state.prepare();
425
+ const changed = this._state.group(type, key);
426
+ if (!changed && !properties) return;
427
+ this._groupPublisher.publish({
428
+ type,
429
+ key,
430
+ changed,
431
+ properties
432
+ });
433
+ this.capture('$groupidentify', {
434
+ $group_type: type,
435
+ $group_key: key,
436
+ ...properties ? {
437
+ $group_set: properties
438
+ } : {}
439
+ });
440
+ }
441
+ reset() {
442
+ if (this._closing || this._disposed) return;
443
+ this._state.prepare();
444
+ this._state.reset();
445
+ this._resetPublisher.publish(void 0);
446
+ }
447
+ async flush() {
448
+ await this._registry.flush();
449
+ }
450
+ optIn() {
451
+ if (this._disposed) return;
452
+ if (this._state.optIn()) this._dispatchConsentChange();
453
+ this._startInitialPageview();
454
+ }
455
+ optOut() {
456
+ if (!this._disposed && this._state.optOut()) this._dispatchConsentChange();
457
+ }
458
+ hasOptedOut() {
459
+ return 'denied' === this._state.consent;
460
+ }
461
+ registerDynamicEventProperties(producer) {
462
+ if (this._disposed) return {
463
+ dispose () {}
464
+ };
465
+ this._dynamicEventProperties.push(producer);
466
+ let active = true;
467
+ return {
468
+ dispose: ()=>{
469
+ if (!active) return;
470
+ active = false;
471
+ const index = this._dynamicEventProperties.indexOf(producer);
472
+ if (-1 !== index) this._dynamicEventProperties.splice(index, 1);
473
+ }
474
+ };
475
+ }
476
+ sendRequest(path, init) {
477
+ return (0, external_request_js_namespaceObject.sendRequest)(this._requestRuntime, path, init, ()=>!this._blocked && !this.hasOptedOut());
478
+ }
479
+ async getRemoteConfig() {
480
+ if (this._closing || this._disposed) return;
481
+ if (void 0 !== this._remoteConfig) return this._remoteConfig;
482
+ if (!this._remoteConfigPromise) {
483
+ let timeout;
484
+ let invalidated = false;
485
+ let controller;
486
+ let cancelWait;
487
+ const timeoutResult = new Promise((resolve)=>{
488
+ cancelWait = ()=>{
489
+ if (void 0 !== timeout) {
490
+ try {
491
+ globalThis.clearTimeout(timeout);
492
+ } catch {}
493
+ timeout = void 0;
494
+ }
495
+ resolve(void 0);
496
+ };
497
+ this._cancelRemoteConfigWait = cancelWait;
498
+ try {
499
+ timeout = globalThis.setTimeout(cancelWait, this._remoteConfigTimeoutMs);
500
+ } catch {
501
+ cancelWait();
502
+ }
503
+ });
504
+ this._remoteConfigPromise = Promise.race([
505
+ Promise.resolve().then(()=>{
506
+ if (this._closing || this._disposed) {
507
+ invalidated = true;
508
+ return;
509
+ }
510
+ controller = 'function' == typeof globalThis.AbortController ? new globalThis.AbortController() : void 0;
511
+ return (0, external_remote_config_js_namespaceObject.loadRemoteConfig)(this._requestRuntime, controller?.signal, ()=>!this._closing && !this._disposed && !this._blocked);
512
+ }),
513
+ timeoutResult
514
+ ]).then((remoteConfig)=>{
515
+ if (this._closing || this._disposed) {
516
+ invalidated = true;
517
+ return;
518
+ }
519
+ this._latestRemoteConfigResult = remoteConfig ? {
520
+ ok: true,
521
+ config: remoteConfig
522
+ } : {
523
+ ok: false
524
+ };
525
+ if (remoteConfig) this._remoteConfig = remoteConfig;
526
+ this._remoteConfigPublisher.publish(this._latestRemoteConfigResult);
527
+ return remoteConfig;
528
+ }).catch((error)=>{
529
+ if (this._closing || this._disposed) {
530
+ invalidated = true;
531
+ return;
532
+ }
533
+ this.logger.error('Remote configuration failed', error);
534
+ this._latestRemoteConfigResult = {
535
+ ok: false
536
+ };
537
+ this._remoteConfigPublisher.publish(this._latestRemoteConfigResult);
538
+ }).finally(()=>{
539
+ try {
540
+ controller?.abort();
541
+ } catch {}
542
+ if (void 0 !== timeout) try {
543
+ globalThis.clearTimeout(timeout);
544
+ } catch {}
545
+ if (this._cancelRemoteConfigWait === cancelWait) this._cancelRemoteConfigWait = void 0;
546
+ if (invalidated) this._remoteConfigPromise = void 0;
547
+ });
548
+ }
549
+ return this._remoteConfigPromise;
550
+ }
551
+ getExtension(name) {
552
+ return this._registry.get(name);
553
+ }
554
+ shutdown(shutdownTimeoutMs = DEFAULT_SHUTDOWN_TIMEOUT_MS) {
555
+ if (!this._shutdownPromise) {
556
+ this._closing = true;
557
+ const extensionFlush = this._registry.flush('shutdown');
558
+ this._removePageviewListener();
559
+ try {
560
+ this._consentObservation.dispose();
561
+ } catch {}
562
+ try {
563
+ this._cancelRemoteConfigWait?.();
564
+ } catch {}
565
+ this._shutdownPromise = this._shutdown(shutdownTimeoutMs, extensionFlush);
566
+ }
567
+ return this._shutdownPromise;
568
+ }
569
+ dispose() {
570
+ return this.shutdown();
571
+ }
572
+ async _shutdown(shutdownTimeoutMs, extensionFlush) {
573
+ const timeoutMs = Math.max(0, Math.floor(Number.isFinite(shutdownTimeoutMs) ? shutdownTimeoutMs : DEFAULT_SHUTDOWN_TIMEOUT_MS));
574
+ let timer;
575
+ let timedOut = false;
576
+ const timeout = new Promise((resolve)=>{
577
+ try {
578
+ timer = globalThis.setTimeout(()=>{
579
+ timedOut = true;
580
+ resolve();
581
+ }, timeoutMs);
582
+ } catch {
583
+ timedOut = true;
584
+ resolve();
585
+ }
586
+ });
587
+ try {
588
+ await Promise.race([
589
+ extensionFlush,
590
+ timeout
591
+ ]);
592
+ this._disposed = true;
593
+ try {
594
+ this._state.dispose();
595
+ } catch (error) {
596
+ this.logger.error('Failed to dispose browser state', error);
597
+ }
598
+ this._captureSink = void 0;
599
+ const cleanup = this._registry.dispose().catch((error)=>this.logger.error('Failed to dispose extensions', error));
600
+ this._remoteConfigPublisher.dispose();
601
+ this._eventPublisher.dispose();
602
+ this._identifyPublisher.dispose();
603
+ this._groupPublisher.dispose();
604
+ this._resetPublisher.dispose();
605
+ this._consentChangePublisher.dispose();
606
+ this._newSessionPublisher.dispose();
607
+ this._dynamicEventProperties.splice(0);
608
+ await Promise.race([
609
+ cleanup,
610
+ timeout
611
+ ]);
612
+ if (timedOut) this.logger.warn(`PostHog shutdown stopped waiting for cleanup after ${timeoutMs}ms`);
613
+ } catch (error) {
614
+ this.logger.error('PostHog shutdown failed', error);
615
+ } finally{
616
+ if (void 0 !== timer) try {
617
+ globalThis.clearTimeout(timer);
618
+ } catch {}
619
+ }
620
+ }
621
+ _startInitialPageview() {
622
+ if (!this._capturePageview || !this._initialPageviewPending || this._closing || this._disposed) return;
623
+ let document;
624
+ let visibility;
625
+ try {
626
+ document = globalThis.document;
627
+ visibility = document?.visibilityState;
628
+ } catch {
629
+ this._removePageviewListener();
630
+ this._initialPageviewPending = false;
631
+ return;
632
+ }
633
+ if (!document || void 0 === visibility) {
634
+ this._removePageviewListener();
635
+ this._initialPageviewPending = false;
636
+ return;
637
+ }
638
+ if ('visible' !== visibility) {
639
+ if (this._pageviewListener?.[0] !== document) this._removePageviewListener();
640
+ if (!this._pageviewListener) {
641
+ const listener = ()=>this._startInitialPageview();
642
+ this._pageviewListener = [
643
+ document,
644
+ listener
645
+ ];
646
+ try {
647
+ document.addEventListener('visibilitychange', listener);
648
+ } catch {
649
+ this._removePageviewListener();
650
+ this._initialPageviewPending = false;
651
+ }
652
+ }
653
+ return;
654
+ }
655
+ this._removePageviewListener();
656
+ this._initialPageviewPending = false;
657
+ if (!this._capture('$pageview')) this._initialPageviewPending = !this._disposed && !this._blocked;
658
+ }
659
+ _removePageviewListener() {
660
+ const listener = this._pageviewListener;
661
+ this._pageviewListener = void 0;
662
+ if (listener) try {
663
+ listener[0].removeEventListener('visibilitychange', listener[1]);
664
+ } catch {}
665
+ }
666
+ _observeConsent(storage, observeNativeStorage) {
667
+ if (!storage) return {
668
+ dispose () {}
669
+ };
670
+ const refresh = ()=>{
671
+ if (!this._disposed) this._state.refreshConsent();
672
+ };
673
+ const storageListener = (event)=>{
674
+ try {
675
+ const storageEvent = event;
676
+ if (storageEvent.storageArea === storage && (null === storageEvent.key || storageEvent.key === this._state.consentKey)) {
677
+ if (!this._disposed) this._state.observeConsent(storageEvent.newValue);
678
+ }
679
+ } catch {}
680
+ };
681
+ const localListener = (event)=>{
682
+ try {
683
+ if (event.detail === this._state.consentKey) refresh();
684
+ } catch {}
685
+ };
686
+ let adapter;
687
+ let storageListening = false;
688
+ let localListening = false;
689
+ if (observeNativeStorage) try {
690
+ globalThis.addEventListener('storage', storageListener);
691
+ storageListening = true;
692
+ } catch {}
693
+ try {
694
+ globalThis.addEventListener(CONSENT_CHANGE_EVENT, localListener);
695
+ localListening = true;
696
+ } catch {}
697
+ try {
698
+ adapter = storage?.subscribe?.(this._state.consentKey, refresh);
699
+ } catch {}
700
+ return {
701
+ dispose: ()=>{
702
+ if (storageListening) {
703
+ try {
704
+ globalThis.removeEventListener('storage', storageListener);
705
+ } catch {}
706
+ storageListening = false;
707
+ }
708
+ if (localListening) {
709
+ try {
710
+ globalThis.removeEventListener(CONSENT_CHANGE_EVENT, localListener);
711
+ } catch {}
712
+ localListening = false;
713
+ }
714
+ try {
715
+ adapter?.dispose();
716
+ } catch {}
717
+ }
718
+ };
719
+ }
720
+ _dispatchConsentChange() {
721
+ try {
722
+ globalThis.dispatchEvent(new CustomEvent(CONSENT_CHANGE_EVENT, {
723
+ detail: this._state.consentKey
724
+ }));
725
+ } catch {}
726
+ }
727
+ _createExtensionClient(extensionName) {
728
+ const host = this;
729
+ const logger = this.logger.createLogger(extensionName);
730
+ const kv = this._state.keyValueStore(extensionName, ()=>!this._closing && !this._disposed && this._state.prepare());
731
+ return {
732
+ get distinctId () {
733
+ return host.distinctId;
734
+ },
735
+ get anonymousId () {
736
+ return host.anonymousId;
737
+ },
738
+ get deviceId () {
739
+ return host.deviceId;
740
+ },
741
+ get library () {
742
+ return host.library;
743
+ },
744
+ get initialPersonProperties () {
745
+ return host.initialPersonProperties;
746
+ },
747
+ get groups () {
748
+ return host.groups;
749
+ },
750
+ get session () {
751
+ return host.session;
752
+ },
753
+ get isOptedOut () {
754
+ return host.isOptedOut;
755
+ },
756
+ get canCapture () {
757
+ return host.canCapture;
758
+ },
759
+ capture: (event, properties, options)=>host.capture(event, properties, options),
760
+ registerDynamicEventProperties: (producer)=>host.registerDynamicEventProperties(producer),
761
+ getExtension: (name)=>host.getExtension(name),
762
+ get projectToken () {
763
+ return host.projectToken;
764
+ },
765
+ sendRequest: (path, init)=>host.sendRequest(path, init),
766
+ onConsentChange: host.onConsentChange,
767
+ onRemoteConfig: host.onRemoteConfig,
768
+ onEvent: host.onEvent,
769
+ onIdentify: host.onIdentify,
770
+ onGroup: host.onGroup,
771
+ onReset: host.onReset,
772
+ onSession: host.onSession,
773
+ kv,
774
+ logger
775
+ };
776
+ }
777
+ _canDeliver() {
778
+ return !this._disposed && !this._blocked && !this.hasOptedOut();
779
+ }
780
+ }
781
+ const createPostHogCore = async (options, configured = options?.extensions ?? [])=>{
782
+ const analytics = configured.find(external_analytics_internal_js_namespaceObject.isAnalyticsExtension) ?? (0, external_analytics_buffer_js_namespaceObject.createAnalyticsExtension)();
783
+ const extensions = configured.filter((extension)=>extension !== analytics);
784
+ const client = PostHogBrowserClient.create(options ?? {
785
+ projectToken: ''
786
+ }, analytics);
787
+ client.getRemoteConfig();
788
+ let analyticsReady = false;
789
+ try {
790
+ await client._registry.install(analytics);
791
+ analytics.initialize({
792
+ runtime: client._requestRuntime,
793
+ canRetry: ()=>client._canDeliver(),
794
+ reportFailure: (error)=>client.logger.error('Event delivery failed', error),
795
+ reportWarning: (message)=>client.logger.warn(message),
796
+ onAvailable: ()=>client._startInitialPageview()
797
+ });
798
+ analyticsReady = true;
799
+ } catch (error) {
800
+ client._captureSink = void 0;
801
+ try {
802
+ await client._registry.rollback(analytics);
803
+ } catch (cleanupError) {
804
+ client.logger.error(`Failed to dispose disabled extension "${analytics.name}"`, cleanupError);
805
+ }
806
+ client.logger.error(`Failed to install configured extension "${analytics.name}"`, error);
807
+ }
808
+ for (const extension of extensions)try {
809
+ await client._registry.install(extension);
810
+ } catch (error) {
811
+ client.logger.error(`Failed to install configured extension "${extension.name}"`, error);
812
+ }
813
+ if (analyticsReady) await analytics.start();
814
+ client._startInitialPageview();
815
+ return client;
816
+ };
817
+ exports.createPostHogCore = __webpack_exports__.createPostHogCore;
818
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
819
+ "createPostHogCore"
820
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
821
+ Object.defineProperty(exports, '__esModule', {
822
+ value: true
823
+ });