@posthog/browser 0.1.1 → 0.3.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 (73) hide show
  1. package/ARCHITECTURE.md +28 -22
  2. package/README.md +94 -29
  3. package/dist/analytics-api.d.ts +32 -0
  4. package/dist/analytics-api.js +18 -0
  5. package/dist/analytics-api.mjs +1 -0
  6. package/dist/analytics-buffer.d.ts +3 -3
  7. package/dist/analytics-buffer.js +2 -161
  8. package/dist/analytics-buffer.mjs +2 -161
  9. package/dist/analytics-extension.d.ts +87 -0
  10. package/dist/analytics-extension.js +649 -0
  11. package/dist/analytics-extension.mjs +611 -0
  12. package/dist/analytics-internal.d.ts +33 -18
  13. package/dist/analytics-options.d.ts +7 -2
  14. package/dist/analytics-options.js +38 -1
  15. package/dist/analytics-options.mjs +17 -1
  16. package/dist/analytics-properties.d.ts +12 -0
  17. package/dist/analytics-properties.js +88 -0
  18. package/dist/analytics-properties.mjs +46 -0
  19. package/dist/analytics-session-properties.d.ts +12 -0
  20. package/dist/analytics-session-properties.js +84 -0
  21. package/dist/analytics-session-properties.mjs +46 -0
  22. package/dist/analytics.d.ts +4 -3
  23. package/dist/autocapture.d.ts +2 -2
  24. package/dist/autocapture.js +21 -10
  25. package/dist/autocapture.mjs +21 -10
  26. package/dist/automatic-analytics.d.ts +2 -2
  27. package/dist/browser-client.d.ts +44 -4
  28. package/dist/capture-properties.d.ts +15 -0
  29. package/dist/capture-properties.js +101 -0
  30. package/dist/capture-properties.mjs +57 -0
  31. package/dist/capture-v1.js +7 -19
  32. package/dist/capture-v1.mjs +1 -13
  33. package/dist/core.d.ts +7 -5
  34. package/dist/extensions/registry.d.ts +42 -7
  35. package/dist/extensions/registry.js +194 -37
  36. package/dist/extensions/registry.mjs +194 -37
  37. package/dist/flags-token.d.ts +4 -4
  38. package/dist/flags.js +15 -2
  39. package/dist/flags.mjs +15 -2
  40. package/dist/immutable.d.ts +1 -0
  41. package/dist/immutable.js +46 -0
  42. package/dist/immutable.mjs +8 -0
  43. package/dist/index.d.ts +7 -5
  44. package/dist/index.js +3 -67
  45. package/dist/index.mjs +3 -67
  46. package/dist/key-value-store.d.ts +21 -0
  47. package/dist/key-value-store.js +117 -0
  48. package/dist/key-value-store.mjs +72 -0
  49. package/dist/logs-internal.d.ts +2 -2
  50. package/dist/logs.js +5 -2
  51. package/dist/logs.mjs +5 -2
  52. package/dist/person-processing.d.ts +11 -0
  53. package/dist/person-processing.js +84 -0
  54. package/dist/person-processing.mjs +37 -0
  55. package/dist/posthog.d.ts +4 -3
  56. package/dist/posthog.js +154 -353
  57. package/dist/posthog.mjs +154 -353
  58. package/dist/root-composition.d.ts +11 -0
  59. package/dist/root-composition.js +138 -0
  60. package/dist/root-composition.mjs +100 -0
  61. package/dist/state.d.ts +6 -0
  62. package/dist/state.js +50 -56
  63. package/dist/state.mjs +50 -56
  64. package/dist/surveys-extension.js +11 -6
  65. package/dist/surveys-extension.mjs +11 -6
  66. package/dist/surveys-internal.d.ts +3 -2
  67. package/dist/types.d.ts +13 -19
  68. package/dist/utf8.d.ts +1 -0
  69. package/dist/utf8.js +52 -0
  70. package/dist/utf8.mjs +14 -0
  71. package/dist/version.js +1 -1
  72. package/dist/version.mjs +1 -1
  73. package/package.json +3 -3
@@ -0,0 +1,611 @@
1
+ import { Analytics, MAX_ANALYTICS_BATCH_EVENTS, MAX_ANALYTICS_BYTES } from "./analytics-internal.mjs";
2
+ import { EventBuffer } from "./event-buffer.mjs";
3
+ import { EMPTY_CAPTURE_SUMMARY, captureFailure } from "./capture-summary.mjs";
4
+ import { createId } from "./id.mjs";
5
+ import { deepFreeze } from "./immutable.mjs";
6
+ import { ClientRateLimiter } from "./rate-limiter.mjs";
7
+ import { applySessionProperties, snapshotCaptureProperties, unavoidableProperties } from "./capture-properties.mjs";
8
+ import { SessionRegisteredProperties } from "./analytics-session-properties.mjs";
9
+ import { RegisteredProperties, snapshotRegisteredProperties } from "./analytics-properties.mjs";
10
+ import { personPropertyNames, shouldProcessPerson, snapshotPersonProfileMode, snapshotPersonProperties } from "./person-processing.mjs";
11
+ import { version } from "./version.mjs";
12
+ import { utf8Bytes } from "./utf8.mjs";
13
+ const numberOption = (read, fallback, minimum, maximum)=>{
14
+ try {
15
+ const value = read();
16
+ return Math.max(minimum, Math.min(maximum, Math.floor('number' == typeof value && Number.isFinite(value) ? value : fallback)));
17
+ } catch {
18
+ return fallback;
19
+ }
20
+ };
21
+ const CLIENT_RATE_LIMIT_WARNING = '$$client_ingestion_warning';
22
+ const isNonEmptyString = (value)=>'string' == typeof value && value.trim().length > 0;
23
+ const isValidDistinctId = (value)=>isNonEmptyString(value) && ![
24
+ '$posthog_cookieless',
25
+ 'distinct_id',
26
+ 'distinctid',
27
+ 'undefined',
28
+ 'null'
29
+ ].includes(value.toLowerCase());
30
+ const isValidGroupKey = (value)=>isNonEmptyString(value) || Number.isFinite(value);
31
+ const eventTimestamp = (timestamp)=>{
32
+ try {
33
+ return (timestamp ?? new Date()).toISOString();
34
+ } catch {
35
+ return new Date().toISOString();
36
+ }
37
+ };
38
+ class analytics_extension_Analytics {
39
+ constructor(options = {}, load, deliveryFactory){
40
+ this.name = Analytics;
41
+ this._disposed = false;
42
+ this._isTearingDown = false;
43
+ this._failures = 0;
44
+ this._dynamicEventProperties = [];
45
+ this._disposalWaiters = new Set();
46
+ this._teardownCallbacks = new Set();
47
+ this.bindCaptureHost = (host)=>{
48
+ this._host = host;
49
+ this._sessionProperties = new SessionRegisteredProperties(host.sessionKv);
50
+ };
51
+ this.setup = (value)=>{
52
+ this._client = value.sharedClient;
53
+ this._kv = value.kv;
54
+ this._registeredProperties = new RegisteredProperties(value.kv);
55
+ };
56
+ this.initialize = (host)=>{
57
+ this._deliveryHost = host;
58
+ if (this._deliveryFactory) this._driver = this._deliveryFactory(this._buffer, this._client, host, this._scheduling, this._beforeTeardown);
59
+ };
60
+ this.start = ()=>this._eager ? this._ensureDelivery('eager') : Promise.resolve();
61
+ this.onBeforeTeardown = (callback)=>{
62
+ if (!this._disposed) this._teardownCallbacks.add(callback);
63
+ const instance = this;
64
+ return {
65
+ get deliveryAvailable () {
66
+ return !instance._disposed && !!instance._driver;
67
+ },
68
+ dispose: ()=>{
69
+ this._teardownCallbacks.delete(callback);
70
+ }
71
+ };
72
+ };
73
+ this.flush = async (reason = 'flush')=>{
74
+ if (this._disposed) return;
75
+ if ('shutdown' === reason && this._loading) await this._loading;
76
+ else if (this._buffer.hasPending()) await this._ensureDelivery(reason);
77
+ await this._driver?.flush();
78
+ };
79
+ this.purge = ()=>this._buffer.purge();
80
+ this.dispose = ()=>{
81
+ this._disposed = true;
82
+ this._registeredProperties = void 0;
83
+ this._sessionProperties = void 0;
84
+ this._dynamicEventProperties.splice(0);
85
+ for (const release of this._disposalWaiters)release();
86
+ this._disposalWaiters.clear();
87
+ this._teardownCallbacks.clear();
88
+ if (this._driver) return this._driver.dispose();
89
+ this._buffer.dispose();
90
+ };
91
+ this._beforeTeardown = ()=>{
92
+ this._isTearingDown = true;
93
+ try {
94
+ for (const callback of this._teardownCallbacks)try {
95
+ callback();
96
+ } catch (error) {
97
+ try {
98
+ this._deliveryHost.reportFailure(error);
99
+ } catch {}
100
+ }
101
+ } finally{
102
+ this._isTearingDown = false;
103
+ }
104
+ };
105
+ this.onEvent = (listener)=>!this._disposed && this._host?.onEvent(listener) || {
106
+ dispose () {}
107
+ };
108
+ this.captureInitialPageview = ()=>this._capture('$pageview');
109
+ this.capture = (event, properties = null, options = {})=>{
110
+ try {
111
+ if ('unload' === options.delivery && !this._isTearingDown) return this._captureUnload(event, properties, options);
112
+ } catch (error) {
113
+ this._host?.logger.error('Unload capture failed', error);
114
+ return true;
115
+ }
116
+ return this._capture(event, properties, options) || !this._rateLimiter.limited;
117
+ };
118
+ this.captureImmediate = async (event, properties = null, options = {})=>{
119
+ try {
120
+ const authority = this._host?.authority();
121
+ const message = this._admitCapture(event, properties, options, false, true);
122
+ if (!message) return EMPTY_CAPTURE_SUMMARY;
123
+ return await this._deliverImmediate(message, ()=>this._host?.authority() === authority);
124
+ } catch (error) {
125
+ return captureFailure(error);
126
+ }
127
+ };
128
+ this.createPersonProfile = ()=>{
129
+ const host = this._host;
130
+ if (this._disposed || !host?.canMutate()) return;
131
+ host.state.prepare();
132
+ if (this._hasPersonProcessing()) return;
133
+ const properties = snapshotPersonProperties(host.state.distinctId, {}, {});
134
+ if (properties) this._setPersonProperties(properties);
135
+ };
136
+ this.setPersonProperties = (set, setOnce)=>{
137
+ const host = this._host;
138
+ if (this._disposed || !host?.canMutate()) return;
139
+ host.state.prepare();
140
+ const properties = snapshotPersonProperties(host.state.distinctId, set, setOnce);
141
+ if (!properties) return void host.logger.warn('Person properties must be JSON-serializable objects');
142
+ if (!(Object.keys(properties.set).length || Object.keys(properties.setOnce).length)) return;
143
+ this._setPersonProperties(properties);
144
+ };
145
+ this.unsetPersonProperties = (names)=>{
146
+ const host = this._host;
147
+ if (this._disposed || !host?.canMutate()) return;
148
+ const properties = personPropertyNames(names);
149
+ if (!properties.length || !this._requirePersonProcessing()) return;
150
+ host.state.prepare();
151
+ this._lastPersonProperties = void 0;
152
+ host.publishChangeProperties({
153
+ unset: properties
154
+ });
155
+ this._capture('$set', {
156
+ $unset: properties
157
+ }, {}, false, {
158
+ signature: void 0
159
+ });
160
+ };
161
+ this.setInternalOrTestUser = ()=>{
162
+ this.setPersonProperties({
163
+ $internal_or_test_user: true
164
+ });
165
+ };
166
+ this.identify = async (distinctId, set, setOnce)=>{
167
+ const host = this._host;
168
+ if (!isValidDistinctId(distinctId) || this._disposed || !host?.canMutate()) return;
169
+ host.state.prepare();
170
+ if (!this._requirePersonProcessing()) return;
171
+ const previousDistinctId = host.state.distinctId;
172
+ const wasIdentified = host.state.isIdentified;
173
+ const hasProperties = !!set || !!setOnce;
174
+ if (distinctId !== previousDistinctId || !wasIdentified) host.state.identify(distinctId);
175
+ const properties = snapshotPersonProperties(distinctId, set, setOnce);
176
+ if (!properties) {
177
+ host.logger.warn('Person properties must be JSON-serializable objects');
178
+ if (distinctId !== previousDistinctId || !wasIdentified || hasProperties) host.publishIdentify({
179
+ distinctId,
180
+ previousDistinctId,
181
+ wasIdentified,
182
+ set,
183
+ setOnce
184
+ });
185
+ return;
186
+ }
187
+ const options = this._identifyOptions(properties, !!set, !!setOnce);
188
+ if (distinctId === previousDistinctId && wasIdentified) {
189
+ if (hasProperties) this._setPersonProperties(properties, options, {
190
+ distinctId,
191
+ previousDistinctId,
192
+ wasIdentified,
193
+ set: options.set,
194
+ setOnce: options.setOnce
195
+ });
196
+ return;
197
+ }
198
+ this._lastPersonProperties = void 0;
199
+ if (hasProperties) host.publishChangeProperties({
200
+ set: options.set,
201
+ setOnce: options.setOnce
202
+ });
203
+ host.publishIdentify({
204
+ distinctId,
205
+ previousDistinctId,
206
+ wasIdentified,
207
+ set: options.set,
208
+ setOnce: options.setOnce
209
+ });
210
+ this._captureIdentification(distinctId, previousDistinctId, wasIdentified, properties, options, hasProperties);
211
+ };
212
+ this.alias = (alias)=>{
213
+ const host = this._host;
214
+ if (!isValidDistinctId(alias) || this._disposed || !host?.canCapture() || !host.state.prepare()) return;
215
+ if (!this._requirePersonProcessing()) return;
216
+ this._capture('$create_alias', {
217
+ alias
218
+ });
219
+ };
220
+ this.group = async (type, key, properties)=>{
221
+ if (!isNonEmptyString(type) || !isNonEmptyString(key) || this._disposed || !this._host?.canMutate() || 'never' === this._personProfiles) return;
222
+ this._host.state.prepare();
223
+ const changed = this._host.state.group(type, key);
224
+ if (!changed && !properties) return;
225
+ this._host.publishGroup({
226
+ type,
227
+ key,
228
+ changed,
229
+ properties
230
+ });
231
+ if (!this._hasPersonProcessing()) return;
232
+ this.capture('$groupidentify', {
233
+ $group_type: type,
234
+ $group_key: key,
235
+ ...properties ? {
236
+ $group_set: properties
237
+ } : {}
238
+ });
239
+ };
240
+ this.groupIdentify = (type, key, properties = {}, options = {})=>{
241
+ const host = this._host;
242
+ if (this._disposed || !host?.canCapture()) return;
243
+ if (!isNonEmptyString(type) || !isValidGroupKey(key)) return void host.logger.warn('Group identify requires a non-empty type and a string or finite numeric key');
244
+ if (!host.state.prepare() || !this._requirePersonProcessing()) return;
245
+ this.capture('$groupidentify', {
246
+ $group_type: type,
247
+ $group_key: key,
248
+ $group_set: properties
249
+ }, options);
250
+ };
251
+ this.resetGroups = ()=>{
252
+ const host = this._host;
253
+ if (this._disposed || !host?.canMutate()) return;
254
+ host.state.prepare();
255
+ host.state.resetGroups();
256
+ host.publishGroupsReset();
257
+ };
258
+ this.reset = ()=>{
259
+ if (this._disposed || !this._host?.canMutate()) return;
260
+ this._host.state.prepare();
261
+ this._host.state.reset();
262
+ this._lastPersonProperties = void 0;
263
+ this._sessionProperties?.clear();
264
+ this._host.publishReset(void 0);
265
+ };
266
+ this.register = (properties)=>{
267
+ const registration = this._prepareRegistration(properties);
268
+ registration?.store.register(registration.properties);
269
+ };
270
+ this.registerOnce = (properties, defaultValue = 'None')=>{
271
+ const registration = this._prepareRegistration(properties);
272
+ registration?.store.registerOnce(registration.properties, defaultValue);
273
+ };
274
+ this.registerForSession = (properties)=>{
275
+ const registration = this._prepareRegistration(properties);
276
+ if (registration) this._sessionProperties?.register(registration.properties, this._host?.state.activeSessionId);
277
+ };
278
+ this.unregisterForSession = (property)=>{
279
+ if (this._propertyStore()) this._sessionProperties?.unregister(property, this._host?.state.activeSessionId);
280
+ };
281
+ this.unregister = (property)=>{
282
+ this._propertyStore()?.unregister(property);
283
+ };
284
+ this.getProperty = (property)=>this._propertyStore()?.get(property);
285
+ this.registerDynamicEventProperties = (producer)=>{
286
+ if (this._disposed || !this._host || this._host.isDisposed()) return {
287
+ dispose () {}
288
+ };
289
+ this._dynamicEventProperties.push(producer);
290
+ let active = true;
291
+ return {
292
+ dispose: ()=>{
293
+ if (!active) return;
294
+ active = false;
295
+ const index = this._dynamicEventProperties.indexOf(producer);
296
+ if (-1 !== index) this._dynamicEventProperties.splice(index, 1);
297
+ }
298
+ };
299
+ };
300
+ this._load = load;
301
+ this._deliveryFactory = deliveryFactory;
302
+ let eager = false;
303
+ if (load) try {
304
+ eager = 'eager' === options.load;
305
+ } catch {}
306
+ this._eager = eager;
307
+ this._scheduling = {
308
+ flushAt: numberOption(()=>options.flushAt, 20, 1, MAX_ANALYTICS_BATCH_EVENTS),
309
+ flushInterval: numberOption(()=>options.flushInterval, 3000, 0, Number.MAX_SAFE_INTEGER)
310
+ };
311
+ 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);
312
+ this._personProfiles = snapshotPersonProfileMode(()=>options.personProfiles);
313
+ this._rateLimiter = new ClientRateLimiter();
314
+ Object.defineProperty(this, 'isRateLimited', {
315
+ configurable: true,
316
+ enumerable: true,
317
+ get: ()=>this._rateLimiter.wouldLimit
318
+ });
319
+ }
320
+ async _ensureDelivery(reason, retryAfterPending = true) {
321
+ const load = this._load;
322
+ if (!load || this._disposed || this._driver) return;
323
+ if (this._loading) {
324
+ if ('capture' === reason || !retryAfterPending) return this._loading;
325
+ const previousFailures = this._failures;
326
+ await this._loading;
327
+ if (this._failures > previousFailures && this._buffer.hasPending()) await this._ensureDelivery(reason, false);
328
+ return;
329
+ }
330
+ if ('capture' === reason && this._failures > 0) return;
331
+ const loadDelivery = async ()=>{
332
+ await Promise.resolve();
333
+ try {
334
+ const createDelivery = await load();
335
+ if (this._disposed) return;
336
+ this._driver = createDelivery(this._buffer, this._client, this._deliveryHost, this._scheduling, this._beforeTeardown);
337
+ } catch (error) {
338
+ if (!this._driver) {
339
+ this._failures++;
340
+ this._client.logger.error('Automatic analytics loading failed', error);
341
+ }
342
+ } finally{
343
+ if (this._loading === pending) this._loading = void 0;
344
+ }
345
+ };
346
+ const pending = loadDelivery();
347
+ this._loading = pending;
348
+ return pending;
349
+ }
350
+ async _deliverImmediate(message, canContinue) {
351
+ let release;
352
+ const disposal = new Promise((resolve)=>{
353
+ release = resolve;
354
+ this._disposalWaiters.add(resolve);
355
+ });
356
+ try {
357
+ await Promise.race([
358
+ this._ensureDelivery('immediate'),
359
+ disposal
360
+ ]);
361
+ } finally{
362
+ this._disposalWaiters.delete(release);
363
+ }
364
+ let deliverImmediate;
365
+ try {
366
+ deliverImmediate = this._driver?.deliverImmediate;
367
+ } catch {
368
+ deliverImmediate = void 0;
369
+ }
370
+ if (!canContinue()) return captureFailure(new Error('Immediate analytics delivery was cancelled'));
371
+ if (!this._driver || 'function' != typeof deliverImmediate || this._disposed) return captureFailure(new Error('Immediate analytics delivery is unavailable'));
372
+ return deliverImmediate.call(this._driver, [
373
+ message
374
+ ], canContinue);
375
+ }
376
+ _deliverUnload(message, canContinue) {
377
+ const send = ()=>{
378
+ if (this._disposed || !canContinue()) return;
379
+ try {
380
+ this._driver?.deliverUnload([
381
+ message
382
+ ]);
383
+ } catch (error) {
384
+ this._deliveryHost.reportFailure(error);
385
+ }
386
+ };
387
+ if (this._driver) send();
388
+ else this._ensureDelivery('immediate').then(send, (error)=>this._deliveryHost.reportFailure(error));
389
+ }
390
+ _captureUnload(event, properties, options) {
391
+ const authority = this._host?.authority();
392
+ const message = this._admitCapture(event, properties, options, false, true);
393
+ if (message) this._deliverUnload(message, ()=>this._host?.authority() === authority);
394
+ return !!message || !this._rateLimiter.limited;
395
+ }
396
+ _capture(event, properties = null, options = {}, skipRateLimit = false, personProperties) {
397
+ return void 0 !== this._admitCapture(event, properties, options, skipRateLimit, false, personProperties);
398
+ }
399
+ _admitCapture(event, properties, options, skipRateLimit, immediate, personProperties) {
400
+ if (!isNonEmptyString(event) || this._disposed || !this._host?.canCapture() || !this._host.state.prepare()) return;
401
+ if (!this._acceptRateLimit(skipRateLimit)) return;
402
+ const snapshot = this._snapshotProperties(properties, options);
403
+ if (!snapshot) return;
404
+ const candidate = this._prepareCapture(event, snapshot, this._host);
405
+ return candidate ? this._commitCapture(candidate, immediate, this._host, personProperties) : void 0;
406
+ }
407
+ _acceptRateLimit(skipRateLimit) {
408
+ if (skipRateLimit) return true;
409
+ const rateLimit = this._rateLimiter.consume();
410
+ if (rateLimit.allowed) return true;
411
+ if (void 0 !== rateLimit.reportDropped) this._reportRateLimit(rateLimit.reportDropped);
412
+ return false;
413
+ }
414
+ _reportRateLimit(dropped) {
415
+ const warning = `${dropped} event(s) dropped since the last warning. Client limit is 10 events per second with a burst of 100.`;
416
+ this._host?.logger.warn(`PostHog client rate limited: ${warning}`);
417
+ if (this._capture(CLIENT_RATE_LIMIT_WARNING, {
418
+ $$client_ingestion_warning_message: `posthog-js client rate limited: ${warning}`
419
+ }, {}, true)) this._rateLimiter.reported();
420
+ }
421
+ _dynamicProperties() {
422
+ const properties = {};
423
+ for (const producer of this._dynamicEventProperties.slice())try {
424
+ Object.assign(properties, producer());
425
+ } catch (error) {
426
+ this._host?.logger.error('An event property producer failed', error);
427
+ }
428
+ return properties;
429
+ }
430
+ _snapshotProperties(properties, options) {
431
+ const dynamic = this._dynamicProperties();
432
+ try {
433
+ return snapshotCaptureProperties(this._registeredProperties?.values(), dynamic, properties, options);
434
+ } catch (error) {
435
+ this._host?.logger.error('Event properties are not JSON-serializable', error);
436
+ return;
437
+ }
438
+ }
439
+ _prepareCapture(event, snapshot, host) {
440
+ const processPersonProfile = this._hasPersonProcessing();
441
+ if (processPersonProfile) this._requirePersonProcessing();
442
+ const preparedSession = host.state.prepareSessionForEvent();
443
+ const session = preparedSession.context;
444
+ const distinctId = host.state.distinctId;
445
+ const deviceId = host.state.deviceId;
446
+ const groups = host.state.groups;
447
+ const metadata = {
448
+ token: host.projectToken,
449
+ distinct_id: distinctId,
450
+ $device_id: deviceId,
451
+ $groups: groups,
452
+ $session_id: session.sessionId,
453
+ $window_id: session.windowId,
454
+ $lib: 'web',
455
+ $lib_version: version,
456
+ $process_person_profile: processPersonProfile
457
+ };
458
+ const message = {
459
+ uuid: snapshot.uuid ?? createId(),
460
+ event,
461
+ distinct_id: distinctId,
462
+ properties: {
463
+ ...snapshot.message,
464
+ ...metadata
465
+ },
466
+ timestamp: eventTimestamp(snapshot.timestamp)
467
+ };
468
+ const bytes = this._enrichAndMeasure(message, snapshot, metadata, session.sessionId);
469
+ if (void 0 === bytes) return;
470
+ return {
471
+ message,
472
+ bytes,
473
+ preparedSession,
474
+ observedProperties: {
475
+ ...snapshot.observed,
476
+ ...metadata,
477
+ $groups: {
478
+ ...groups
479
+ }
480
+ }
481
+ };
482
+ }
483
+ _enrichAndMeasure(message, snapshot, metadata, sessionId) {
484
+ try {
485
+ let bytes = utf8Bytes(JSON.stringify(message));
486
+ if (!this._fitsUnavoidableProperties(message, snapshot, metadata, bytes)) return;
487
+ const changed = applySessionProperties(snapshot, this._sessionProperties?.values(sessionId) ?? {});
488
+ message.properties = {
489
+ ...snapshot.message,
490
+ ...metadata
491
+ };
492
+ if (changed) bytes = utf8Bytes(JSON.stringify(message));
493
+ return bytes;
494
+ } catch (error) {
495
+ this._host?.logger.error('The finalized event could not be measured', error);
496
+ return;
497
+ }
498
+ }
499
+ _fitsUnavoidableProperties(message, snapshot, metadata, bytes) {
500
+ if (bytes <= MAX_ANALYTICS_BYTES) return true;
501
+ const minimum = utf8Bytes(JSON.stringify({
502
+ ...message,
503
+ properties: unavoidableProperties(snapshot, metadata)
504
+ }));
505
+ if (minimum <= MAX_ANALYTICS_BYTES) return true;
506
+ this._warnOversized(message.event, bytes);
507
+ return false;
508
+ }
509
+ _warnOversized(event, bytes) {
510
+ this._host?.logger.warn(`Event "${event}" (${bytes} bytes) exceeds the local analytics limit and was dropped`);
511
+ }
512
+ _enqueueCapture(candidate, immediate) {
513
+ const { message, bytes } = candidate;
514
+ if (immediate ? bytes > MAX_ANALYTICS_BYTES : !this._buffer.enqueue(message, bytes)) {
515
+ if (bytes > MAX_ANALYTICS_BYTES) this._warnOversized(message.event, bytes);
516
+ return false;
517
+ }
518
+ return true;
519
+ }
520
+ _commitCapture(candidate, immediate, host, personProperties) {
521
+ if (!this._enqueueCapture(candidate, immediate)) return;
522
+ if (!host.state.sessionAdmitted(candidate.preparedSession)) {
523
+ if (!immediate) this._buffer.discardQueued(candidate.message);
524
+ return;
525
+ }
526
+ if (personProperties) this._lastPersonProperties = personProperties.signature;
527
+ else if (Object.hasOwn(candidate.message.properties, '$set') || Object.hasOwn(candidate.message.properties, '$set_once') || Object.hasOwn(candidate.message.properties, '$unset')) this._lastPersonProperties = void 0;
528
+ this._sessionProperties?.admitted(candidate.preparedSession.context.sessionId);
529
+ this._publishCapture(candidate, host);
530
+ if (!immediate) this._ensureDelivery('capture');
531
+ return candidate.message;
532
+ }
533
+ _publishCapture(candidate, host) {
534
+ const { preparedSession, message, observedProperties } = candidate;
535
+ const session = preparedSession.context;
536
+ if (preparedSession.reason) host.publishNewSession({
537
+ ...session,
538
+ reason: preparedSession.reason
539
+ });
540
+ host.publishEvent(deepFreeze({
541
+ event: message.event,
542
+ properties: observedProperties
543
+ }));
544
+ }
545
+ _hasPersonProcessing() {
546
+ const host = this._host;
547
+ if (!host) return false;
548
+ const enabled = this._kv?.get('personProcessingEnabled') === true;
549
+ return shouldProcessPerson(this._personProfiles, host.state.isIdentified, Object.keys(host.state.groups).length > 0, enabled);
550
+ }
551
+ _requirePersonProcessing() {
552
+ if ('never' === this._personProfiles) {
553
+ this._host?.logger.warn('Person processing is disabled by analytics configuration');
554
+ return false;
555
+ }
556
+ if (this._kv?.get('personProcessingEnabled') !== true) this._kv?.set('personProcessingEnabled', true);
557
+ return true;
558
+ }
559
+ _setPersonProperties(properties, options = {
560
+ set: properties.set,
561
+ setOnce: properties.setOnce
562
+ }, identification) {
563
+ const host = this._host;
564
+ if (!host || !this._requirePersonProcessing() || this._lastPersonProperties === properties.signature) return;
565
+ this._lastPersonProperties = void 0;
566
+ host.publishChangeProperties({
567
+ set: options.set,
568
+ setOnce: options.setOnce
569
+ });
570
+ if (identification) host.publishIdentify(identification);
571
+ this._capture('$set', null, options, false, {
572
+ signature: properties.signature
573
+ });
574
+ }
575
+ _identifyOptions(properties, hasSet, hasSetOnce) {
576
+ const options = {};
577
+ if (hasSet) options.set = properties.set;
578
+ if (hasSetOnce) options.setOnce = properties.setOnce;
579
+ return options;
580
+ }
581
+ _captureIdentification(distinctId, previousDistinctId, wasIdentified, properties, options, hasProperties) {
582
+ const personProperties = {
583
+ signature: properties.signature
584
+ };
585
+ if (!wasIdentified && distinctId !== previousDistinctId) return this._capture('$identify', {
586
+ $anon_distinct_id: previousDistinctId
587
+ }, options, false, personProperties);
588
+ if (distinctId === previousDistinctId) return this._capture('$set', null, {
589
+ set: properties.set,
590
+ setOnce: properties.setOnce
591
+ }, false, personProperties);
592
+ return hasProperties ? this._capture('$set', null, options, false, personProperties) : false;
593
+ }
594
+ _propertyStore() {
595
+ const host = this._host;
596
+ if (this._disposed || !host?.canMutate() || !host.state.prepare()) return;
597
+ return this._registeredProperties;
598
+ }
599
+ _prepareRegistration(properties) {
600
+ const store = this._propertyStore();
601
+ if (!store) return;
602
+ const snapshot = snapshotRegisteredProperties(properties);
603
+ if (this._propertyStore() !== store) return;
604
+ if (!snapshot) return void this._host?.logger.warn('Super properties must serialize to an object');
605
+ return {
606
+ store,
607
+ properties: snapshot
608
+ };
609
+ }
610
+ }
611
+ export { analytics_extension_Analytics as Analytics };
@@ -1,4 +1,8 @@
1
- import type { Client, Extension, ExtensionToken } from '@posthog/browser-common';
1
+ import type { Client, CapturedEventInfo, ExtensionToken, Listener } from '@posthog/browser-common';
2
+ import type { BrowserExtension, ChangePropertiesInfo, GroupInfo, IdentifyInfo } from './browser-client';
3
+ import type { IAnalytics } from './analytics-api';
4
+ import type { BrowserState } from './state';
5
+ import type { NewSessionInfo } from './types';
2
6
  import type { AnalyticsOptions } from './analytics-options';
3
7
  import type { EventBuffer } from './event-buffer';
4
8
  import type { LaneDelivery } from './lane';
@@ -13,7 +17,7 @@ export interface AnalyticsMessage {
13
17
  }
14
18
  export declare const MAX_ANALYTICS_BYTES: number;
15
19
  export declare const MAX_ANALYTICS_BATCH_EVENTS = 100;
16
- export declare const Analytics: ExtensionToken<AnalyticsExtension>;
20
+ export declare const Analytics: ExtensionToken<IAnalyticsExtension>;
17
21
  /** Browser capabilities supplied to capture delivery, independent of its queue. */
18
22
  export interface CaptureHost {
19
23
  runtime: RequestRuntime;
@@ -38,27 +42,38 @@ export interface AnalyticsDriver {
38
42
  deliverUnload(messages: readonly AnalyticsMessage[]): void;
39
43
  dispose(): Promise<void>;
40
44
  }
41
- export type AnalyticsDeliveryFactory = (buffer: EventBuffer<AnalyticsMessage>, client: Client, host: CaptureHost, options: Readonly<Required<AnalyticsOptions>>, beforeTeardown?: () => void) => AnalyticsDriver;
42
- /** The capture operations required by core, independent of extension setup or loading. */
43
- export interface CaptureSink {
44
- readonly isTearingDown: boolean;
45
- enqueue(message: AnalyticsMessage, bytes: number): boolean;
46
- discardQueued(message: AnalyticsMessage): void;
47
- admitted(): void;
48
- flush(reason?: 'flush' | 'shutdown'): Promise<void>;
49
- deliverImmediate(message: AnalyticsMessage, canContinue: () => boolean): Promise<CaptureSummary>;
50
- deliverUnload(message: AnalyticsMessage, canContinue: () => boolean): void;
51
- purge(): void;
52
- }
45
+ export type AnalyticsDeliveryFactory = (buffer: EventBuffer<AnalyticsMessage>, client: Pick<Client, 'library' | 'onRemoteConfig'>, host: CaptureHost, options: Readonly<Required<Pick<AnalyticsOptions, 'flushAt' | 'flushInterval'>>>, beforeTeardown?: () => void) => AnalyticsDriver;
53
46
  export interface AnalyticsTeardownSubscription {
54
47
  readonly deliveryAvailable: boolean;
55
48
  dispose(): void;
56
49
  }
57
- /** First-party analytics is both a configured extension and the client's capture sink. */
58
- export interface AnalyticsExtension extends Extension, CaptureSink {
59
- flush: CaptureSink['flush'];
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;
68
+ }
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;
60
75
  initialize(host: CaptureHost): void;
61
76
  start(): Promise<void>;
62
77
  onBeforeTeardown?(callback: () => void): AnalyticsTeardownSubscription;
63
78
  }
64
- export declare const isAnalyticsExtension: (extension: Extension) => extension is AnalyticsExtension;
79
+ export declare const isAnalyticsExtension: (extension: BrowserExtension) => extension is IAnalyticsExtension;