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