@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
@@ -1,611 +0,0 @@
1
- import { Analytics, MAX_ANALYTICS_BATCH_EVENTS, MAX_ANALYTICS_BYTES } from "./analytics-internal.mjs";
2
- import { EventBuffer } from "./admission/event-buffer.mjs";
3
- import { EMPTY_CAPTURE_SUMMARY, captureFailure } from "./admission/capture-summary.mjs";
4
- import { createId } from "../../primitives/id.mjs";
5
- import { deepFreeze } from "../../primitives/immutable.mjs";
6
- import { ClientRateLimiter } from "./admission/rate-limiter.mjs";
7
- import { applySessionProperties, snapshotCaptureProperties, unavoidableProperties } from "./admission/capture-properties.mjs";
8
- import { SessionRegisteredProperties } from "./properties/analytics-session-properties.mjs";
9
- import { RegisteredProperties, snapshotRegisteredProperties } from "./properties/analytics-properties.mjs";
10
- import { personPropertyNames, shouldProcessPerson, snapshotPersonProfileMode, snapshotPersonProperties } from "./properties/person-processing.mjs";
11
- import { version } from "../../primitives/version.mjs";
12
- import { utf8Bytes } from "../../primitives/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,6 +0,0 @@
1
- import type { IAnalytics } from './analytics-api';
2
- import type { AnalyticsOptions } from './analytics-options';
3
- export type { IAnalytics } from './analytics-api';
4
- export type { AnalyticsOptions, PersonProfileMode } from './analytics-options';
5
- /** Creates analytics with its buffer and Capture V1 delivery statically included. */
6
- export declare const analytics: (options?: AnalyticsOptions) => IAnalytics;
@@ -1,42 +0,0 @@
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
- });
33
- const external_analytics_buffer_js_namespaceObject = require("./analytics-buffer.js");
34
- const analytics_delivery_js_namespaceObject = require("./delivery/analytics-delivery.js");
35
- const analytics = (options = {})=>(0, external_analytics_buffer_js_namespaceObject.createAnalyticsExtension)(options, void 0, analytics_delivery_js_namespaceObject.createAnalyticsDelivery);
36
- exports.analytics = __webpack_exports__.analytics;
37
- for(var __rspack_i in __webpack_exports__)if (-1 === [
38
- "analytics"
39
- ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
40
- Object.defineProperty(exports, '__esModule', {
41
- value: true
42
- });
@@ -1,4 +0,0 @@
1
- import { createAnalyticsExtension } from "./analytics-buffer.mjs";
2
- import { createAnalyticsDelivery } from "./delivery/analytics-delivery.mjs";
3
- const analytics = (options = {})=>createAnalyticsExtension(options, void 0, createAnalyticsDelivery);
4
- export { analytics };
@@ -1,3 +0,0 @@
1
- import type { IAnalyticsExtension } from './analytics-internal';
2
- import type { AutomaticAnalyticsOptions } from './analytics-options';
3
- export declare const analytics: (options: AutomaticAnalyticsOptions) => IAnalyticsExtension;