@posthog/browser 0.4.2 → 0.6.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 (85) hide show
  1. package/ARCHITECTURE.md +36 -48
  2. package/README.md +97 -69
  3. package/dist/composition/npm/core.d.ts +3 -4
  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 +4 -5
  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 +190 -173
  18. package/dist/core/posthog.mjs +191 -174
  19. package/dist/core/state/state.d.ts +33 -3
  20. package/dist/core/state/state.js +122 -27
  21. package/dist/core/state/state.mjs +107 -27
  22. package/dist/core/types.d.ts +134 -14
  23. package/dist/persistence/cookie.d.ts +19 -0
  24. package/dist/persistence/cookie.js +273 -0
  25. package/dist/persistence/cookie.mjs +235 -0
  26. package/dist/platform/logger.d.ts +5 -1
  27. package/dist/platform/logger.js +3 -3
  28. package/dist/platform/logger.mjs +3 -3
  29. package/dist/primitives/id.d.ts +5 -0
  30. package/dist/primitives/id.js +10 -2
  31. package/dist/primitives/id.mjs +6 -1
  32. package/dist/primitives/version.js +1 -1
  33. package/dist/primitives/version.mjs +1 -1
  34. package/dist/products/analytics/analytics-core.d.ts +89 -0
  35. package/dist/products/analytics/analytics-core.js +563 -0
  36. package/dist/products/analytics/analytics-core.mjs +516 -0
  37. package/dist/products/analytics/analytics-internal.d.ts +16 -37
  38. package/dist/products/analytics/analytics-internal.js +2 -10
  39. package/dist/products/analytics/analytics-internal.mjs +1 -3
  40. package/dist/products/analytics/analytics-options.d.ts +0 -9
  41. package/dist/products/analytics/analytics-options.js +1 -38
  42. package/dist/products/analytics/analytics-options.mjs +1 -17
  43. package/dist/products/analytics/delivery/analytics-delivery.js +1 -1
  44. package/dist/products/analytics/delivery/analytics-delivery.mjs +1 -1
  45. package/dist/products/analytics/delivery/lane.d.ts +8 -1
  46. package/dist/products/analytics/delivery/lane.js +16 -4
  47. package/dist/products/analytics/delivery/lane.mjs +16 -4
  48. package/dist/products/analytics/groups.d.ts +8 -0
  49. package/dist/products/analytics/groups.js +84 -0
  50. package/dist/products/analytics/groups.mjs +40 -0
  51. package/dist/products/analytics/person.d.ts +11 -0
  52. package/dist/products/analytics/person.js +91 -0
  53. package/dist/products/analytics/person.mjs +41 -0
  54. package/dist/products/analytics/properties/analytics-properties.d.ts +1 -0
  55. package/dist/products/analytics/properties/analytics-properties.js +3 -0
  56. package/dist/products/analytics/properties/analytics-properties.mjs +1 -1
  57. package/dist/products/autocapture/autocapture.js +2 -6
  58. package/dist/products/autocapture/autocapture.mjs +2 -6
  59. package/dist/products/flags/flags-internal.d.ts +4 -2
  60. package/dist/products/flags/flags-options.d.ts +16 -2
  61. package/dist/products/flags/flags-token.d.ts +31 -4
  62. package/dist/products/flags/flags.d.ts +1 -1
  63. package/dist/products/flags/flags.js +112 -11
  64. package/dist/products/flags/flags.mjs +112 -11
  65. package/dist/products/logs/logs.js +2 -5
  66. package/dist/products/logs/logs.mjs +2 -5
  67. package/dist/products/surveys/surveys-extension.js +78 -46
  68. package/dist/products/surveys/surveys-extension.mjs +80 -48
  69. package/dist/products/surveys/surveys-internal.d.ts +6 -0
  70. package/package.json +7 -7
  71. package/dist/products/analytics/analytics-api.d.ts +0 -32
  72. package/dist/products/analytics/analytics-api.js +0 -18
  73. package/dist/products/analytics/analytics-api.mjs +0 -1
  74. package/dist/products/analytics/analytics-buffer.d.ts +0 -4
  75. package/dist/products/analytics/analytics-buffer.js +0 -41
  76. package/dist/products/analytics/analytics-buffer.mjs +0 -3
  77. package/dist/products/analytics/analytics-extension.d.ts +0 -87
  78. package/dist/products/analytics/analytics-extension.js +0 -649
  79. package/dist/products/analytics/analytics-extension.mjs +0 -611
  80. package/dist/products/analytics/analytics.d.ts +0 -6
  81. package/dist/products/analytics/analytics.js +0 -42
  82. package/dist/products/analytics/analytics.mjs +0 -4
  83. package/dist/products/analytics/automatic-analytics.d.ts +0 -3
  84. package/dist/products/analytics/automatic-analytics.js +0 -44
  85. package/dist/products/analytics/automatic-analytics.mjs +0 -6
@@ -0,0 +1,563 @@
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
+ Analytics: ()=>Analytics,
32
+ analyticsOf: ()=>analyticsOf,
33
+ isNonEmptyString: ()=>isNonEmptyString,
34
+ isValidDistinctId: ()=>isValidDistinctId
35
+ });
36
+ const pubsub_namespaceObject = require("@posthog/browser-common/pubsub");
37
+ const external_analytics_internal_js_namespaceObject = require("./analytics-internal.js");
38
+ const state_js_namespaceObject = require("../../core/state/state.js");
39
+ const event_buffer_js_namespaceObject = require("./admission/event-buffer.js");
40
+ const capture_summary_js_namespaceObject = require("./admission/capture-summary.js");
41
+ const id_js_namespaceObject = require("../../primitives/id.js");
42
+ const immutable_js_namespaceObject = require("../../primitives/immutable.js");
43
+ const rate_limiter_js_namespaceObject = require("./admission/rate-limiter.js");
44
+ const capture_properties_js_namespaceObject = require("./admission/capture-properties.js");
45
+ const analytics_session_properties_js_namespaceObject = require("./properties/analytics-session-properties.js");
46
+ const analytics_properties_js_namespaceObject = require("./properties/analytics-properties.js");
47
+ const person_processing_js_namespaceObject = require("./properties/person-processing.js");
48
+ const version_js_namespaceObject = require("../../primitives/version.js");
49
+ const utf8_js_namespaceObject = require("../../primitives/utf8.js");
50
+ const numberOption = (read, fallback, minimum, maximum)=>{
51
+ try {
52
+ const value = read();
53
+ return Math.max(minimum, Math.min(maximum, Math.floor('number' == typeof value && Number.isFinite(value) ? value : fallback)));
54
+ } catch {
55
+ return fallback;
56
+ }
57
+ };
58
+ const CLIENT_RATE_LIMIT_WARNING = '$$client_ingestion_warning';
59
+ const isNonEmptyString = (value)=>'string' == typeof value && value.trim().length > 0;
60
+ const isValidDistinctId = (value)=>isNonEmptyString(value) && ![
61
+ '$posthog_cookieless',
62
+ 'distinct_id',
63
+ 'distinctid',
64
+ 'undefined',
65
+ 'null'
66
+ ].includes(value.toLowerCase());
67
+ const eventTimestamp = (timestamp)=>{
68
+ try {
69
+ return (timestamp ?? new Date()).toISOString();
70
+ } catch {
71
+ return new Date().toISOString();
72
+ }
73
+ };
74
+ const snapshotOptions = (options)=>{
75
+ try {
76
+ const snapshot = JSON.parse(JSON.stringify(options ?? {}));
77
+ return 'object' == typeof snapshot && null !== snapshot ? snapshot : {};
78
+ } catch {
79
+ return {};
80
+ }
81
+ };
82
+ class Analytics {
83
+ constructor(_core, options, createDelivery){
84
+ this._core = _core;
85
+ this._disposed = false;
86
+ this._isTearingDown = false;
87
+ this._dynamicEventProperties = [];
88
+ this._teardownCallbacks = new Set();
89
+ this._beforeTeardown = ()=>{
90
+ this._isTearingDown = true;
91
+ try {
92
+ for (const callback of this._teardownCallbacks)try {
93
+ callback();
94
+ } catch (error) {
95
+ try {
96
+ this._deliveryHost.reportFailure(error);
97
+ } catch {}
98
+ }
99
+ } finally{
100
+ this._isTearingDown = false;
101
+ }
102
+ };
103
+ const report = (label)=>(error)=>_core.logger.error(`${label} listener failed`, error);
104
+ this._eventPublisher = new pubsub_namespaceObject.Publisher(report('An event'));
105
+ this._newSessionPublisher = new pubsub_namespaceObject.Publisher(report('A session'));
106
+ this._sessionIdPublisher = new pubsub_namespaceObject.Publisher(report('A session ID'));
107
+ this._identifyPublisher = new pubsub_namespaceObject.Publisher(report('An identify'));
108
+ this._changePropertiesPublisher = new pubsub_namespaceObject.Publisher(report('A person-property'));
109
+ this._groupPublisher = new pubsub_namespaceObject.Publisher(report('A group'));
110
+ this._groupsResetPublisher = new pubsub_namespaceObject.Publisher(report('A group reset'));
111
+ this._resetPublisher = new pubsub_namespaceObject.Publisher(report('A reset'));
112
+ this._personProfiles = (0, person_processing_js_namespaceObject.snapshotPersonProfileMode)(()=>options.personProfiles);
113
+ this._rateLimiter = new rate_limiter_js_namespaceObject.ClientRateLimiter();
114
+ this._registeredProperties = new analytics_properties_js_namespaceObject.RegisteredProperties(_core.kv);
115
+ this._sessionProperties = new analytics_session_properties_js_namespaceObject.SessionRegisteredProperties(_core._sessionKv);
116
+ this._deliveryHost = {
117
+ runtime: _core._requestRuntime,
118
+ canRetry: ()=>_core._canDeliver(),
119
+ reportFailure: (error)=>_core.logger.error('Event delivery failed', error),
120
+ reportWarning: (message)=>_core.logger.warn(message),
121
+ onAvailable: ()=>_core._startInitialPageview()
122
+ };
123
+ this._buffer = new event_buffer_js_namespaceObject.EventBuffer(1000, (total, count = 1, reason = 'overflow')=>this._deliveryHost.reportWarning(`Analytics queue dropped ${count} ${reason} event${1 === count ? '' : 's'} (${total} total)`), external_analytics_internal_js_namespaceObject.MAX_ANALYTICS_BYTES, 3600000);
124
+ try {
125
+ this._driver = createDelivery(this._buffer, _core, this._deliveryHost, {
126
+ flushAt: numberOption(()=>options.flushAt, 20, 1, external_analytics_internal_js_namespaceObject.MAX_ANALYTICS_BATCH_EVENTS),
127
+ flushInterval: numberOption(()=>options.flushInterval, 3000, 0, Number.MAX_SAFE_INTEGER)
128
+ }, this._beforeTeardown);
129
+ } catch (error) {
130
+ _core.logger.error('Event delivery is unavailable', error);
131
+ }
132
+ }
133
+ get isRateLimited() {
134
+ return this._rateLimiter.wouldLimit;
135
+ }
136
+ onBeforeTeardown(callback) {
137
+ if (!this._disposed) this._teardownCallbacks.add(callback);
138
+ const instance = this;
139
+ return {
140
+ get deliveryAvailable () {
141
+ return !instance._disposed && !!instance._driver;
142
+ },
143
+ dispose: ()=>{
144
+ this._teardownCallbacks.delete(callback);
145
+ }
146
+ };
147
+ }
148
+ async flush() {
149
+ if (!this._disposed) await this._driver?.flush();
150
+ }
151
+ purge() {
152
+ this._buffer.purge();
153
+ }
154
+ dispose() {
155
+ this._disposed = true;
156
+ this._dynamicEventProperties.splice(0);
157
+ this._teardownCallbacks.clear();
158
+ for (const publisher of [
159
+ this._eventPublisher,
160
+ this._newSessionPublisher,
161
+ this._sessionIdPublisher,
162
+ this._identifyPublisher,
163
+ this._changePropertiesPublisher,
164
+ this._groupPublisher,
165
+ this._groupsResetPublisher,
166
+ this._resetPublisher
167
+ ])publisher.dispose();
168
+ if (this._driver) return this._driver.dispose();
169
+ this._buffer.dispose();
170
+ }
171
+ captureInitialPageview() {
172
+ return this._capture('$pageview');
173
+ }
174
+ capture(event, properties = null, options = {}) {
175
+ let delivery;
176
+ try {
177
+ delivery = options.delivery;
178
+ if ('unload' === delivery && !this._isTearingDown) {
179
+ const authority = this._core._immediateAuthority;
180
+ const message = this._admitCapture(event, properties, options, false, true);
181
+ if (message && !this._disposed && this._core._immediateAuthority === authority) this._driver?.deliverUnload([
182
+ message
183
+ ]);
184
+ return !!message || !this._rateLimiter.limited;
185
+ }
186
+ } catch (error) {
187
+ this._core.logger.error('Unload capture failed', error);
188
+ return true;
189
+ }
190
+ if (!this._capture(event, properties, options)) return !this._rateLimiter.limited;
191
+ if ('immediate' === delivery && !this._isTearingDown) this._driver?.flush(true).catch(this._deliveryHost.reportFailure);
192
+ return true;
193
+ }
194
+ async captureImmediate(event, properties = null, options = {}) {
195
+ try {
196
+ const deliver = this._driver?.deliverImmediate;
197
+ if (!deliver || this._disposed) return (0, capture_summary_js_namespaceObject.captureFailure)(new Error('Immediate analytics delivery is unavailable'));
198
+ const authority = this._core._immediateAuthority;
199
+ const message = this._admitCapture(event, properties, options, false, true);
200
+ if (!message) return capture_summary_js_namespaceObject.EMPTY_CAPTURE_SUMMARY;
201
+ if (this._disposed || !this._core._canMutate()) return (0, capture_summary_js_namespaceObject.captureFailure)(new Error('Immediate analytics delivery is unavailable'));
202
+ return await deliver.call(this._driver, [
203
+ message
204
+ ], ()=>this._core._immediateAuthority === authority);
205
+ } catch (error) {
206
+ return (0, capture_summary_js_namespaceObject.captureFailure)(error);
207
+ }
208
+ }
209
+ _capture(event, properties = null, options = {}, skipRateLimit = false, personProperties) {
210
+ return void 0 !== this._admitCapture(event, properties, options, skipRateLimit, false, personProperties);
211
+ }
212
+ _admitCapture(event, properties, options, skipRateLimit, immediate, personProperties) {
213
+ if (!isNonEmptyString(event) || this._disposed || !this._core.canCapture) return;
214
+ if (!this._acceptRateLimit(skipRateLimit)) return;
215
+ this._adoptStoredIdentity();
216
+ const snapshot = this._snapshotProperties(properties, options);
217
+ if (!snapshot) return;
218
+ const candidate = this._prepareCapture(event, snapshot);
219
+ return candidate ? this._commitCapture(candidate, immediate, personProperties) : void 0;
220
+ }
221
+ _acceptRateLimit(skipRateLimit) {
222
+ if (skipRateLimit) return true;
223
+ const rateLimit = this._rateLimiter.consume();
224
+ if (rateLimit.allowed) return true;
225
+ if (void 0 !== rateLimit.reportDropped) this._reportRateLimit(rateLimit.reportDropped);
226
+ return false;
227
+ }
228
+ _reportRateLimit(dropped) {
229
+ const warning = `${dropped} event(s) dropped since the last warning. Client limit is 10 events per second with a burst of 100.`;
230
+ this._core.logger.warn(`PostHog client rate limited: ${warning}`);
231
+ if (this._capture(CLIENT_RATE_LIMIT_WARNING, {
232
+ $$client_ingestion_warning_message: `posthog-js client rate limited: ${warning}`
233
+ }, {}, true)) this._rateLimiter.reported();
234
+ }
235
+ _snapshotProperties(properties, options) {
236
+ const dynamic = {};
237
+ for (const producer of this._dynamicEventProperties.slice())try {
238
+ Object.assign(dynamic, producer());
239
+ } catch (error) {
240
+ this._core.logger.error('An event property producer failed', error);
241
+ }
242
+ try {
243
+ return (0, capture_properties_js_namespaceObject.snapshotCaptureProperties)(this._registeredProperties.values(), dynamic, properties, options);
244
+ } catch (error) {
245
+ this._core.logger.error('Event properties are not JSON-serializable', error);
246
+ return;
247
+ }
248
+ }
249
+ _prepareCapture(event, snapshot) {
250
+ const state = this._core._state;
251
+ const processPersonProfile = this._hasPersonProcessing();
252
+ if (processPersonProfile) this._requirePersonProcessing();
253
+ const preparedSession = state.prepareSessionForEvent();
254
+ const session = preparedSession.context;
255
+ const distinctId = state.distinctId;
256
+ const groups = state.groups;
257
+ const uuid = snapshot.uuid ?? (0, id_js_namespaceObject.createId)();
258
+ const activePageviewId = this._pageviewIdFor(session.sessionId);
259
+ const isPageview = '$pageview' === event;
260
+ const pageviewId = isPageview ? uuid : activePageviewId;
261
+ const defaults = {};
262
+ if (pageviewId && !snapshot.overrides.has('$pageview_id')) defaults.$pageview_id = pageviewId;
263
+ if (activePageviewId && (isPageview || '$pageleave' === event) && !snapshot.overrides.has('$prev_pageview_id')) defaults.$prev_pageview_id = activePageviewId;
264
+ const metadata = {
265
+ token: this._core.projectToken,
266
+ distinct_id: distinctId,
267
+ $device_id: state.deviceId,
268
+ $groups: groups,
269
+ $session_id: session.sessionId,
270
+ $window_id: session.windowId,
271
+ $lib: 'web',
272
+ $lib_version: version_js_namespaceObject.version,
273
+ $process_person_profile: processPersonProfile
274
+ };
275
+ const message = {
276
+ uuid,
277
+ event,
278
+ distinct_id: distinctId,
279
+ properties: {
280
+ ...defaults,
281
+ ...snapshot.message,
282
+ ...metadata
283
+ },
284
+ timestamp: eventTimestamp(snapshot.timestamp)
285
+ };
286
+ try {
287
+ let bytes = (0, utf8_js_namespaceObject.utf8Bytes)(JSON.stringify(message));
288
+ if (bytes > external_analytics_internal_js_namespaceObject.MAX_ANALYTICS_BYTES) {
289
+ const minimum = (0, utf8_js_namespaceObject.utf8Bytes)(JSON.stringify({
290
+ ...message,
291
+ properties: {
292
+ ...defaults,
293
+ ...(0, capture_properties_js_namespaceObject.unavoidableProperties)(snapshot, metadata)
294
+ }
295
+ }));
296
+ if (minimum > external_analytics_internal_js_namespaceObject.MAX_ANALYTICS_BYTES) return void this._warnOversized(event, bytes);
297
+ }
298
+ const changed = (0, capture_properties_js_namespaceObject.applySessionProperties)(snapshot, this._sessionProperties.values(session.sessionId));
299
+ message.properties = {
300
+ ...defaults,
301
+ ...snapshot.message,
302
+ ...metadata
303
+ };
304
+ if (changed) bytes = (0, utf8_js_namespaceObject.utf8Bytes)(JSON.stringify(message));
305
+ return {
306
+ message,
307
+ bytes,
308
+ preparedSession,
309
+ observedProperties: {
310
+ ...defaults,
311
+ ...snapshot.observed,
312
+ ...metadata,
313
+ $groups: {
314
+ ...groups
315
+ }
316
+ }
317
+ };
318
+ } catch (error) {
319
+ this._core.logger.error('The finalized event could not be measured', error);
320
+ return;
321
+ }
322
+ }
323
+ _warnOversized(event, bytes) {
324
+ this._core.logger.warn(`Event "${event}" (${bytes} bytes) exceeds the local analytics limit and was dropped`);
325
+ }
326
+ _commitCapture(candidate, immediate, personProperties) {
327
+ const { message, bytes, preparedSession, observedProperties } = candidate;
328
+ if (immediate ? bytes > external_analytics_internal_js_namespaceObject.MAX_ANALYTICS_BYTES : !this._buffer.enqueue(message, bytes)) {
329
+ if (bytes > external_analytics_internal_js_namespaceObject.MAX_ANALYTICS_BYTES) this._warnOversized(message.event, bytes);
330
+ return;
331
+ }
332
+ const previous = this._core._state.session;
333
+ if (!this._core._state.sessionAdmitted(preparedSession)) {
334
+ if (!immediate) this._buffer.discardQueued(message);
335
+ return;
336
+ }
337
+ if (personProperties) this._lastPersonProperties = personProperties.signature;
338
+ else if (Object.hasOwn(message.properties, '$set') || Object.hasOwn(message.properties, '$set_once') || Object.hasOwn(message.properties, '$unset')) this._lastPersonProperties = void 0;
339
+ const session = preparedSession.context;
340
+ if ('$pageview' === message.event) this._pageview = [
341
+ message.uuid,
342
+ session.sessionId
343
+ ];
344
+ else if (this._pageview?.[1] !== session.sessionId) this._pageview = void 0;
345
+ this._sessionProperties.admitted(session.sessionId);
346
+ if (previous?.sessionId !== session.sessionId || previous.windowId !== session.windowId) this._sessionIdPublisher.publish({
347
+ ...session
348
+ });
349
+ if (preparedSession.reason) this._newSessionPublisher.publish({
350
+ ...session,
351
+ reason: preparedSession.reason
352
+ });
353
+ this._eventPublisher.publish((0, immutable_js_namespaceObject.deepFreeze)({
354
+ event: message.event,
355
+ properties: observedProperties
356
+ }));
357
+ return message;
358
+ }
359
+ _pageviewIdFor(sessionId) {
360
+ const pageview = this._pageview;
361
+ return pageview && pageview[1] === sessionId ? pageview[0] : void 0;
362
+ }
363
+ _hasPersonProcessing() {
364
+ const state = this._core._state;
365
+ return (0, person_processing_js_namespaceObject.shouldProcessPerson)(this._personProfiles, state.isIdentified, Object.keys(state.groups).length > 0, true === this._core.kv.get('personProcessingEnabled'));
366
+ }
367
+ _requirePersonProcessing() {
368
+ if ('never' === this._personProfiles) {
369
+ this._core.logger.warn('Person processing is disabled by analytics configuration');
370
+ return false;
371
+ }
372
+ if (true !== this._core.kv.get('personProcessingEnabled')) this._core.kv.set('personProcessingEnabled', true);
373
+ return true;
374
+ }
375
+ _canMutate() {
376
+ if (this._disposed || !this._core._canMutate()) return false;
377
+ this._core._state.prepare();
378
+ this._adoptStoredIdentity();
379
+ return true;
380
+ }
381
+ _adoptStoredIdentity() {
382
+ const state = this._core._state;
383
+ const previousDistinctId = state.distinctId;
384
+ const wasIdentified = state.isIdentified;
385
+ if (!state.adoptStoredIdentity()) return;
386
+ if (!state.isIdentified) return this._resetIdentityState();
387
+ this._lastPersonProperties = void 0;
388
+ this._identifyPublisher.publish({
389
+ distinctId: state.distinctId,
390
+ previousDistinctId,
391
+ wasIdentified,
392
+ set: void 0,
393
+ setOnce: void 0
394
+ });
395
+ }
396
+ _resetIdentityState() {
397
+ this._lastPersonProperties = void 0;
398
+ this._pageview = void 0;
399
+ this._sessionProperties.clear();
400
+ this._resetPublisher.publish(void 0);
401
+ }
402
+ _canUseProperties() {
403
+ return !this._disposed && this._core._canMutate() && this._core._state.prepare();
404
+ }
405
+ _setPersonProperties(properties, options = {
406
+ set: properties.set,
407
+ setOnce: properties.setOnce
408
+ }, identification) {
409
+ if (!this._requirePersonProcessing() || this._lastPersonProperties === properties.signature) return;
410
+ this._lastPersonProperties = void 0;
411
+ this._changePropertiesPublisher.publish({
412
+ set: options.set,
413
+ setOnce: options.setOnce
414
+ });
415
+ if (identification) this._identifyPublisher.publish(identification);
416
+ this._capture('$set', null, options, false, {
417
+ signature: properties.signature
418
+ });
419
+ }
420
+ identify(distinctId, set, setOnce) {
421
+ if (!isValidDistinctId(distinctId) || !this._canMutate() || !this._requirePersonProcessing()) return;
422
+ const state = this._core._state;
423
+ const previousDistinctId = state.distinctId;
424
+ const wasIdentified = state.isIdentified;
425
+ const hasProperties = !!set || !!setOnce;
426
+ if (distinctId !== previousDistinctId || !wasIdentified) state.identify(distinctId);
427
+ const properties = (0, person_processing_js_namespaceObject.snapshotPersonProperties)(distinctId, set, setOnce);
428
+ if (!properties) {
429
+ this._core.logger.warn('Person properties must be JSON-serializable objects');
430
+ if (distinctId !== previousDistinctId || !wasIdentified || hasProperties) this._identifyPublisher.publish({
431
+ distinctId,
432
+ previousDistinctId,
433
+ wasIdentified,
434
+ set,
435
+ setOnce
436
+ });
437
+ return;
438
+ }
439
+ const options = {};
440
+ if (set) options.set = properties.set;
441
+ if (setOnce) options.setOnce = properties.setOnce;
442
+ const info = {
443
+ distinctId,
444
+ previousDistinctId,
445
+ wasIdentified,
446
+ set: options.set,
447
+ setOnce: options.setOnce
448
+ };
449
+ const signature = {
450
+ signature: properties.signature
451
+ };
452
+ if (distinctId === previousDistinctId && wasIdentified) {
453
+ if (hasProperties) this._setPersonProperties(properties, options, info);
454
+ return;
455
+ }
456
+ this._lastPersonProperties = void 0;
457
+ if (hasProperties) this._changePropertiesPublisher.publish({
458
+ set: options.set,
459
+ setOnce: options.setOnce
460
+ });
461
+ this._identifyPublisher.publish(info);
462
+ if (wasIdentified || distinctId === previousDistinctId) {
463
+ if (distinctId === previousDistinctId) this._capture('$set', null, {
464
+ set: properties.set,
465
+ setOnce: properties.setOnce
466
+ }, false, signature);
467
+ else if (hasProperties) this._capture('$set', null, options, false, signature);
468
+ } else this._capture('$identify', {
469
+ $anon_distinct_id: previousDistinctId
470
+ }, options, false, signature);
471
+ }
472
+ reset(options) {
473
+ if (this._disposed || !this._core._canMutate()) return;
474
+ this._core._state.prepare();
475
+ const { resetDeviceId, bootstrap } = true === options || false === options ? {
476
+ resetDeviceId: options
477
+ } : snapshotOptions(options);
478
+ const { distinctId, isIdentifiedId } = bootstrap ?? {};
479
+ this._core._state.reset(true === resetDeviceId, isValidDistinctId(distinctId) ? [
480
+ distinctId,
481
+ true === isIdentifiedId
482
+ ] : void 0, this._bootstrapSession(bootstrap));
483
+ this._resetIdentityState();
484
+ return bootstrap;
485
+ }
486
+ bootstrap(options) {
487
+ const bootstrap = snapshotOptions(options);
488
+ const { distinctId, isIdentifiedId } = bootstrap;
489
+ const session = this._bootstrapSession(bootstrap);
490
+ if (session) this._core._state.bootstrapSession(session);
491
+ if (!isValidDistinctId(distinctId) || !this._canMutate()) return;
492
+ const state = this._core._state;
493
+ if (state.generated) return state.bootstrapIdentity(distinctId, true === isIdentifiedId);
494
+ if (true !== isIdentifiedId) return;
495
+ if (distinctId === state.distinctId) state.identify(distinctId);
496
+ else if (state.isIdentified) this._core.logger.warn('Ignored the bootstrap distinct ID of a different identified user');
497
+ else this.identify(distinctId);
498
+ }
499
+ _bootstrapSession(bootstrap) {
500
+ const sessionId = bootstrap?.sessionId;
501
+ if (void 0 === sessionId) return;
502
+ const session = (0, state_js_namespaceObject.readBootstrapSession)(sessionId);
503
+ if (!session) this._core.logger.error('Ignored the bootstrap session ID: not a past UUIDv7');
504
+ return session;
505
+ }
506
+ _registration(properties) {
507
+ if (!this._canUseProperties()) return;
508
+ const snapshot = (0, analytics_properties_js_namespaceObject.snapshotRegisteredProperties)(properties);
509
+ if (!this._canUseProperties()) return;
510
+ if (!snapshot) this._core.logger.warn('Super properties must serialize to an object');
511
+ return snapshot;
512
+ }
513
+ register(properties) {
514
+ const snapshot = this._registration(properties);
515
+ if (snapshot) this._registeredProperties.register(snapshot);
516
+ }
517
+ registerOnce(properties, defaultValue = 'None') {
518
+ const snapshot = this._registration(properties);
519
+ if (snapshot) this._registeredProperties.registerOnce(snapshot, defaultValue);
520
+ }
521
+ registerForSession(properties) {
522
+ const snapshot = this._registration(properties);
523
+ if (snapshot) this._sessionProperties.register(snapshot, this._core._state.activeSessionId);
524
+ }
525
+ unregisterForSession(property) {
526
+ if (this._canUseProperties()) this._sessionProperties.unregister(property, this._core._state.activeSessionId);
527
+ }
528
+ unregister(property) {
529
+ if (this._canUseProperties()) this._registeredProperties.unregister(property);
530
+ }
531
+ getProperty(property) {
532
+ return this._canUseProperties() ? this._registeredProperties.get(property) : void 0;
533
+ }
534
+ registerDynamicEventProperties(producer) {
535
+ if (this._disposed || this._core._disposed) return {
536
+ dispose () {}
537
+ };
538
+ this._dynamicEventProperties.push(producer);
539
+ let active = true;
540
+ return {
541
+ dispose: ()=>{
542
+ if (!active) return;
543
+ active = false;
544
+ const index = this._dynamicEventProperties.indexOf(producer);
545
+ if (-1 !== index) this._dynamicEventProperties.splice(index, 1);
546
+ }
547
+ };
548
+ }
549
+ }
550
+ const analyticsOf = (posthog)=>posthog._analytics;
551
+ exports.Analytics = __webpack_exports__.Analytics;
552
+ exports.analyticsOf = __webpack_exports__.analyticsOf;
553
+ exports.isNonEmptyString = __webpack_exports__.isNonEmptyString;
554
+ exports.isValidDistinctId = __webpack_exports__.isValidDistinctId;
555
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
556
+ "Analytics",
557
+ "analyticsOf",
558
+ "isNonEmptyString",
559
+ "isValidDistinctId"
560
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
561
+ Object.defineProperty(exports, '__esModule', {
562
+ value: true
563
+ });