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