@posthog/browser 0.1.0 → 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 +29 -23
- package/README.md +66 -30
- 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 +16 -2
- package/dist/flags.mjs +16 -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/lane.js +1 -1
- package/dist/lane.mjs +1 -1
- 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 +155 -349
- package/dist/posthog.mjs +155 -349
- package/dist/rate-limiter.d.ts +5 -0
- package/dist/rate-limiter.js +14 -8
- package/dist/rate-limiter.mjs +14 -8
- 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/surveys.d.ts +0 -1
- package/dist/surveys.js +1 -4
- package/dist/surveys.mjs +1 -4
- 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 +3 -3
package/dist/posthog.js
CHANGED
|
@@ -32,22 +32,16 @@ __webpack_require__.d(__webpack_exports__, {
|
|
|
32
32
|
});
|
|
33
33
|
const external_remote_config_js_namespaceObject = require("./remote-config.js");
|
|
34
34
|
const pubsub_namespaceObject = require("@posthog/browser-common/pubsub");
|
|
35
|
-
const external_analytics_buffer_js_namespaceObject = require("./analytics-buffer.js");
|
|
36
35
|
const external_analytics_internal_js_namespaceObject = require("./analytics-internal.js");
|
|
37
36
|
const external_bot_filter_js_namespaceObject = require("./bot-filter.js");
|
|
38
|
-
const external_capture_summary_js_namespaceObject = require("./capture-summary.js");
|
|
39
37
|
const registry_js_namespaceObject = require("./extensions/registry.js");
|
|
40
|
-
const
|
|
38
|
+
const external_immutable_js_namespaceObject = require("./immutable.js");
|
|
41
39
|
const external_logger_js_namespaceObject = require("./logger.js");
|
|
42
|
-
const external_rate_limiter_js_namespaceObject = require("./rate-limiter.js");
|
|
43
40
|
const external_request_js_namespaceObject = require("./request.js");
|
|
44
41
|
const external_state_js_namespaceObject = require("./state.js");
|
|
45
42
|
const external_version_js_namespaceObject = require("./version.js");
|
|
46
43
|
const CONSENT_CHANGE_EVENT = '__posthog_browser_consent_change__';
|
|
47
44
|
const DEFAULT_SHUTDOWN_TIMEOUT_MS = 30000;
|
|
48
|
-
const CLIENT_RATE_LIMIT_WARNING = '$$client_ingestion_warning';
|
|
49
|
-
const isNonEmptyString = (value)=>'string' == typeof value && value.trim().length > 0;
|
|
50
|
-
const isRecord = (value)=>'object' == typeof value && null !== value && !Array.isArray(value);
|
|
51
45
|
const normalizeHost = (host)=>{
|
|
52
46
|
let end = host.length;
|
|
53
47
|
while(end > 0 && 47 === host.charCodeAt(end - 1))end--;
|
|
@@ -63,20 +57,6 @@ const getAssetsHost = (apiHost)=>{
|
|
|
63
57
|
} catch {}
|
|
64
58
|
return apiHost;
|
|
65
59
|
};
|
|
66
|
-
const isValidDistinctId = (value)=>isNonEmptyString(value) && ![
|
|
67
|
-
'$posthog_cookieless',
|
|
68
|
-
'distinct_id',
|
|
69
|
-
'distinctid',
|
|
70
|
-
'undefined',
|
|
71
|
-
'null'
|
|
72
|
-
].includes(value.toLowerCase());
|
|
73
|
-
const deepFreeze = (value)=>{
|
|
74
|
-
if (value && 'object' == typeof value) {
|
|
75
|
-
Object.values(value).forEach(deepFreeze);
|
|
76
|
-
Object.freeze(value);
|
|
77
|
-
}
|
|
78
|
-
return value;
|
|
79
|
-
};
|
|
80
60
|
const getDefaultFetch = ()=>{
|
|
81
61
|
try {
|
|
82
62
|
return globalThis.fetch?.bind(globalThis);
|
|
@@ -91,41 +71,20 @@ const getDefaultNavigator = ()=>{
|
|
|
91
71
|
return;
|
|
92
72
|
}
|
|
93
73
|
};
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
return
|
|
97
|
-
} catch {
|
|
98
|
-
return new Date().toISOString();
|
|
74
|
+
class PostHog {
|
|
75
|
+
static create(options, loaders) {
|
|
76
|
+
return new PostHog(options, loaders);
|
|
99
77
|
}
|
|
100
|
-
|
|
101
|
-
const utf8Bytes = (value)=>{
|
|
102
|
-
let bytes = 0;
|
|
103
|
-
for(let index = 0; index < value.length; index++){
|
|
104
|
-
const code = value.charCodeAt(index);
|
|
105
|
-
if (code < 0x80) bytes++;
|
|
106
|
-
else if (code < 0x800) bytes += 2;
|
|
107
|
-
else if (code >= 0xd800 && code <= 0xdbff && value.charCodeAt(index + 1) >= 0xdc00) {
|
|
108
|
-
bytes += 4;
|
|
109
|
-
index++;
|
|
110
|
-
} else bytes += 3;
|
|
111
|
-
}
|
|
112
|
-
return bytes;
|
|
113
|
-
};
|
|
114
|
-
class PostHogBrowserClient {
|
|
115
|
-
static create(options, capture) {
|
|
116
|
-
return new PostHogBrowserClient(options, capture);
|
|
117
|
-
}
|
|
118
|
-
constructor(options, capture){
|
|
78
|
+
constructor(options, loaders){
|
|
119
79
|
this.library = Object.freeze({
|
|
120
80
|
name: 'web',
|
|
121
81
|
version: external_version_js_namespaceObject.version
|
|
122
82
|
});
|
|
123
|
-
this._dynamicEventProperties = [];
|
|
124
|
-
this._rateLimiter = new external_rate_limiter_js_namespaceObject.ClientRateLimiter();
|
|
125
83
|
this._immediateAuthority = {};
|
|
126
84
|
this._closing = false;
|
|
127
85
|
this._disposed = false;
|
|
128
86
|
this._initialPageviewPending = true;
|
|
87
|
+
this._ready = false;
|
|
129
88
|
let projectToken = '';
|
|
130
89
|
try {
|
|
131
90
|
projectToken = options.projectToken ?? '';
|
|
@@ -136,14 +95,16 @@ class PostHogBrowserClient {
|
|
|
136
95
|
if (!projectToken) this.logger.error('A PostHog project token is required');
|
|
137
96
|
const initialPersonProperties = options.initialPersonProperties;
|
|
138
97
|
try {
|
|
139
|
-
this.initialPersonProperties = initialPersonProperties ? deepFreeze(JSON.parse(JSON.stringify(initialPersonProperties))) : Object.freeze({});
|
|
98
|
+
this.initialPersonProperties = initialPersonProperties ? (0, external_immutable_js_namespaceObject.deepFreeze)(JSON.parse(JSON.stringify(initialPersonProperties))) : Object.freeze({});
|
|
140
99
|
} catch {
|
|
141
100
|
this.initialPersonProperties = Object.freeze({});
|
|
142
101
|
}
|
|
143
102
|
this._remoteConfigPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A remote configuration listener failed', error));
|
|
144
103
|
this._eventPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('An event listener failed', error));
|
|
145
104
|
this._identifyPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('An identify listener failed', error));
|
|
105
|
+
this._changePropertiesPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A person-property listener failed', error));
|
|
146
106
|
this._groupPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A group listener failed', error));
|
|
107
|
+
this._groupsResetPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A group reset listener failed', error));
|
|
147
108
|
this._resetPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A reset listener failed', error));
|
|
148
109
|
this._newSessionPublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A session listener failed', error));
|
|
149
110
|
this._consentChangePublisher = new pubsub_namespaceObject.Publisher((error)=>this.logger.error('A consent change listener failed', error));
|
|
@@ -155,7 +116,7 @@ class PostHogBrowserClient {
|
|
|
155
116
|
this._state = new external_state_js_namespaceObject.BrowserState(projectToken, storage, options.persistenceKey, options.consentPersistenceName, options.optOutByDefault ?? false, !this._blocked && void 0 === options.storage && void 0 !== requestedStorage ? external_state_js_namespaceObject.getDefaultSessionStorage : void 0, (consent, previous)=>{
|
|
156
117
|
if ('denied' === consent) {
|
|
157
118
|
this._immediateAuthority = {};
|
|
158
|
-
this.
|
|
119
|
+
this._analytics?.purge();
|
|
159
120
|
}
|
|
160
121
|
this._consentChangePublisher.publish({
|
|
161
122
|
current: consent,
|
|
@@ -194,15 +155,15 @@ class PostHogBrowserClient {
|
|
|
194
155
|
else if (!this._closing && !this._disposed) this.getRemoteConfig();
|
|
195
156
|
return subscription;
|
|
196
157
|
};
|
|
197
|
-
this.onEvent = this._eventPublisher.listener;
|
|
198
158
|
this.onIdentify = this._identifyPublisher.listener;
|
|
199
159
|
this.onGroup = this._groupPublisher.listener;
|
|
160
|
+
this.onGroupsReset = this._groupsResetPublisher.listener;
|
|
200
161
|
this.onReset = this._resetPublisher.listener;
|
|
201
162
|
this.onConsentChange = this._consentChangePublisher.listener;
|
|
202
163
|
this.onNewSession = this._newSessionPublisher.listener;
|
|
203
164
|
this.onSession = (listener)=>this.onNewSession((session)=>listener(session.sessionId));
|
|
204
|
-
this._registry = new registry_js_namespaceObject.ExtensionRegistry((extensionName)=>this._createExtensionClient(extensionName), this.logger);
|
|
205
|
-
this.
|
|
165
|
+
this._registry = new registry_js_namespaceObject.ExtensionRegistry((extensionName, resolve)=>this._createExtensionClient(extensionName, resolve), this.logger, loaders, (extension, host)=>this._setupExtension(extension, host), ()=>!this._closing && !this._disposed);
|
|
166
|
+
this._registry.expose(this);
|
|
206
167
|
}
|
|
207
168
|
get distinctId() {
|
|
208
169
|
this._state.prepare();
|
|
@@ -230,220 +191,6 @@ class PostHogBrowserClient {
|
|
|
230
191
|
get canCapture() {
|
|
231
192
|
return !this._closing && !this._disposed && !this._blocked && !this.hasOptedOut() && this._state.prepare();
|
|
232
193
|
}
|
|
233
|
-
capture(event, properties = null, options = {}) {
|
|
234
|
-
try {
|
|
235
|
-
if ('unload' === options.delivery && !this._captureSink?.isTearingDown) {
|
|
236
|
-
const authority = this._immediateAuthority;
|
|
237
|
-
const message = this._admitCapture(event, properties, options, false, true);
|
|
238
|
-
if (message) this._captureSink?.deliverUnload(message, ()=>this._immediateAuthority === authority);
|
|
239
|
-
return;
|
|
240
|
-
}
|
|
241
|
-
} catch (error) {
|
|
242
|
-
this.logger.error('Unload capture failed', error);
|
|
243
|
-
return;
|
|
244
|
-
}
|
|
245
|
-
this._capture(event, properties, options);
|
|
246
|
-
}
|
|
247
|
-
async captureImmediate(event, properties = null, options = {}) {
|
|
248
|
-
try {
|
|
249
|
-
const authority = this._immediateAuthority;
|
|
250
|
-
const message = this._admitCapture(event, properties, options, false, true);
|
|
251
|
-
if (!message) return external_capture_summary_js_namespaceObject.EMPTY_CAPTURE_SUMMARY;
|
|
252
|
-
const capture = this._captureSink;
|
|
253
|
-
if (!capture) return (0, external_capture_summary_js_namespaceObject.captureFailure)(new Error('Immediate analytics delivery is unavailable'));
|
|
254
|
-
return await capture.deliverImmediate(message, ()=>this._immediateAuthority === authority);
|
|
255
|
-
} catch (error) {
|
|
256
|
-
return (0, external_capture_summary_js_namespaceObject.captureFailure)(error);
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
_capture(event, properties = null, options = {}, skipRateLimit = false) {
|
|
260
|
-
return void 0 !== this._admitCapture(event, properties, options, skipRateLimit, false);
|
|
261
|
-
}
|
|
262
|
-
_admitCapture(event, properties, options, skipRateLimit, immediate) {
|
|
263
|
-
if (!isNonEmptyString(event) || this._closing || this._disposed || this._blocked || this.hasOptedOut() || !this._state.prepare()) return;
|
|
264
|
-
if (!skipRateLimit) {
|
|
265
|
-
const rateLimit = this._rateLimiter.consume();
|
|
266
|
-
if (!rateLimit.allowed) {
|
|
267
|
-
if (void 0 !== rateLimit.reportDropped) {
|
|
268
|
-
const warning = `${rateLimit.reportDropped} event(s) dropped since the last warning. Client limit is 10 events per second with a burst of 100.`;
|
|
269
|
-
this.logger.warn(`PostHog client rate limited: ${warning}`);
|
|
270
|
-
if (this._capture(CLIENT_RATE_LIMIT_WARNING, {
|
|
271
|
-
$$client_ingestion_warning_message: `posthog-js client rate limited: ${warning}`
|
|
272
|
-
}, {}, true)) this._rateLimiter.reported();
|
|
273
|
-
}
|
|
274
|
-
return;
|
|
275
|
-
}
|
|
276
|
-
}
|
|
277
|
-
const dynamicProperties = {};
|
|
278
|
-
for (const producer of this._dynamicEventProperties.slice())try {
|
|
279
|
-
Object.assign(dynamicProperties, producer());
|
|
280
|
-
} catch (error) {
|
|
281
|
-
this.logger.error('An event property producer failed', error);
|
|
282
|
-
}
|
|
283
|
-
let messageProperties;
|
|
284
|
-
let observedProperties;
|
|
285
|
-
let uuid;
|
|
286
|
-
let timestamp;
|
|
287
|
-
try {
|
|
288
|
-
const callerProperties = {
|
|
289
|
-
...dynamicProperties,
|
|
290
|
-
...properties ?? {}
|
|
291
|
-
};
|
|
292
|
-
const set = options.set;
|
|
293
|
-
const setOnce = options.setOnce;
|
|
294
|
-
uuid = options.uuid;
|
|
295
|
-
timestamp = options.timestamp;
|
|
296
|
-
if (set) callerProperties['$set'] = set;
|
|
297
|
-
if (setOnce) callerProperties['$set_once'] = setOnce;
|
|
298
|
-
const serializedProperties = JSON.stringify(callerProperties);
|
|
299
|
-
const parsedMessageProperties = JSON.parse(serializedProperties, function(_key, value) {
|
|
300
|
-
return null !== value || Array.isArray(this) ? value : void 0;
|
|
301
|
-
});
|
|
302
|
-
const parsedObservedProperties = JSON.parse(serializedProperties);
|
|
303
|
-
if (!isRecord(parsedMessageProperties) || !isRecord(parsedObservedProperties)) throw new Error('Event properties must serialize to an object');
|
|
304
|
-
messageProperties = parsedMessageProperties;
|
|
305
|
-
observedProperties = parsedObservedProperties;
|
|
306
|
-
} catch (error) {
|
|
307
|
-
this.logger.error('Event properties are not JSON-serializable', error);
|
|
308
|
-
return;
|
|
309
|
-
}
|
|
310
|
-
const preparedSession = this._state.prepareSessionForEvent();
|
|
311
|
-
const session = preparedSession.context;
|
|
312
|
-
const distinctId = this._state.distinctId;
|
|
313
|
-
const deviceId = this._state.deviceId;
|
|
314
|
-
const groups = this._state.groups;
|
|
315
|
-
Object.assign(messageProperties, {
|
|
316
|
-
token: this.projectToken,
|
|
317
|
-
distinct_id: distinctId,
|
|
318
|
-
$device_id: deviceId,
|
|
319
|
-
$groups: groups,
|
|
320
|
-
$session_id: session.sessionId,
|
|
321
|
-
$window_id: session.windowId,
|
|
322
|
-
$lib: 'web',
|
|
323
|
-
$lib_version: external_version_js_namespaceObject.version
|
|
324
|
-
});
|
|
325
|
-
Object.assign(observedProperties, {
|
|
326
|
-
token: this.projectToken,
|
|
327
|
-
distinct_id: distinctId,
|
|
328
|
-
$device_id: deviceId,
|
|
329
|
-
$groups: {
|
|
330
|
-
...groups
|
|
331
|
-
},
|
|
332
|
-
$session_id: session.sessionId,
|
|
333
|
-
$window_id: session.windowId,
|
|
334
|
-
$lib: 'web',
|
|
335
|
-
$lib_version: external_version_js_namespaceObject.version
|
|
336
|
-
});
|
|
337
|
-
const message = {
|
|
338
|
-
uuid: uuid ?? (0, external_id_js_namespaceObject.createId)(),
|
|
339
|
-
event,
|
|
340
|
-
distinct_id: distinctId,
|
|
341
|
-
properties: messageProperties,
|
|
342
|
-
timestamp: eventTimestamp(timestamp)
|
|
343
|
-
};
|
|
344
|
-
let bytes;
|
|
345
|
-
try {
|
|
346
|
-
bytes = utf8Bytes(JSON.stringify(message));
|
|
347
|
-
} catch (error) {
|
|
348
|
-
this.logger.error('The finalized event could not be measured', error);
|
|
349
|
-
return;
|
|
350
|
-
}
|
|
351
|
-
const capture = this._captureSink;
|
|
352
|
-
if (immediate ? bytes > external_analytics_internal_js_namespaceObject.MAX_ANALYTICS_BYTES : !capture?.enqueue(message, bytes)) {
|
|
353
|
-
if (bytes > external_analytics_internal_js_namespaceObject.MAX_ANALYTICS_BYTES) this.logger.warn(`Event "${event}" (${bytes} bytes) exceeds the local analytics limit and was dropped`);
|
|
354
|
-
return;
|
|
355
|
-
}
|
|
356
|
-
if (!this._state.sessionAdmitted(preparedSession)) {
|
|
357
|
-
if (!immediate) capture?.discardQueued(message);
|
|
358
|
-
return;
|
|
359
|
-
}
|
|
360
|
-
if (preparedSession.reason) this._newSessionPublisher.publish({
|
|
361
|
-
...session,
|
|
362
|
-
reason: preparedSession.reason
|
|
363
|
-
});
|
|
364
|
-
this._eventPublisher.publish(deepFreeze({
|
|
365
|
-
event,
|
|
366
|
-
properties: observedProperties
|
|
367
|
-
}));
|
|
368
|
-
if (!immediate) capture?.admitted();
|
|
369
|
-
return message;
|
|
370
|
-
}
|
|
371
|
-
async identify(distinctId, set, setOnce) {
|
|
372
|
-
if (!isValidDistinctId(distinctId) || this._closing || this._disposed) return;
|
|
373
|
-
this._state.prepare();
|
|
374
|
-
const previousDistinctId = this._state.distinctId;
|
|
375
|
-
const wasIdentified = this._state.isIdentified;
|
|
376
|
-
const captureOptions = {};
|
|
377
|
-
if (set) captureOptions.set = set;
|
|
378
|
-
if (setOnce) captureOptions.setOnce = setOnce;
|
|
379
|
-
const hasPersonProperties = !!set || !!setOnce;
|
|
380
|
-
if (distinctId === previousDistinctId) {
|
|
381
|
-
if (wasIdentified) {
|
|
382
|
-
if (hasPersonProperties) {
|
|
383
|
-
this._identifyPublisher.publish({
|
|
384
|
-
distinctId,
|
|
385
|
-
previousDistinctId,
|
|
386
|
-
wasIdentified,
|
|
387
|
-
set,
|
|
388
|
-
setOnce
|
|
389
|
-
});
|
|
390
|
-
this.capture('$set', null, captureOptions);
|
|
391
|
-
}
|
|
392
|
-
} else {
|
|
393
|
-
this._state.identify(distinctId);
|
|
394
|
-
this._identifyPublisher.publish({
|
|
395
|
-
distinctId,
|
|
396
|
-
previousDistinctId,
|
|
397
|
-
wasIdentified,
|
|
398
|
-
set,
|
|
399
|
-
setOnce
|
|
400
|
-
});
|
|
401
|
-
this.capture('$set', null, {
|
|
402
|
-
set: set ?? {},
|
|
403
|
-
setOnce: setOnce ?? {}
|
|
404
|
-
});
|
|
405
|
-
}
|
|
406
|
-
return;
|
|
407
|
-
}
|
|
408
|
-
this._state.identify(distinctId);
|
|
409
|
-
this._identifyPublisher.publish({
|
|
410
|
-
distinctId,
|
|
411
|
-
previousDistinctId,
|
|
412
|
-
wasIdentified,
|
|
413
|
-
set,
|
|
414
|
-
setOnce
|
|
415
|
-
});
|
|
416
|
-
if (wasIdentified) {
|
|
417
|
-
if (hasPersonProperties) this.capture('$set', null, captureOptions);
|
|
418
|
-
} else this.capture('$identify', {
|
|
419
|
-
$anon_distinct_id: previousDistinctId
|
|
420
|
-
}, captureOptions);
|
|
421
|
-
}
|
|
422
|
-
async group(type, key, properties) {
|
|
423
|
-
if (!isNonEmptyString(type) || !isNonEmptyString(key) || this._closing || this._disposed) return;
|
|
424
|
-
this._state.prepare();
|
|
425
|
-
const changed = this._state.group(type, key);
|
|
426
|
-
if (!changed && !properties) return;
|
|
427
|
-
this._groupPublisher.publish({
|
|
428
|
-
type,
|
|
429
|
-
key,
|
|
430
|
-
changed,
|
|
431
|
-
properties
|
|
432
|
-
});
|
|
433
|
-
this.capture('$groupidentify', {
|
|
434
|
-
$group_type: type,
|
|
435
|
-
$group_key: key,
|
|
436
|
-
...properties ? {
|
|
437
|
-
$group_set: properties
|
|
438
|
-
} : {}
|
|
439
|
-
});
|
|
440
|
-
}
|
|
441
|
-
reset() {
|
|
442
|
-
if (this._closing || this._disposed) return;
|
|
443
|
-
this._state.prepare();
|
|
444
|
-
this._state.reset();
|
|
445
|
-
this._resetPublisher.publish(void 0);
|
|
446
|
-
}
|
|
447
194
|
async flush() {
|
|
448
195
|
await this._registry.flush();
|
|
449
196
|
}
|
|
@@ -458,21 +205,6 @@ class PostHogBrowserClient {
|
|
|
458
205
|
hasOptedOut() {
|
|
459
206
|
return 'denied' === this._state.consent;
|
|
460
207
|
}
|
|
461
|
-
registerDynamicEventProperties(producer) {
|
|
462
|
-
if (this._disposed) return {
|
|
463
|
-
dispose () {}
|
|
464
|
-
};
|
|
465
|
-
this._dynamicEventProperties.push(producer);
|
|
466
|
-
let active = true;
|
|
467
|
-
return {
|
|
468
|
-
dispose: ()=>{
|
|
469
|
-
if (!active) return;
|
|
470
|
-
active = false;
|
|
471
|
-
const index = this._dynamicEventProperties.indexOf(producer);
|
|
472
|
-
if (-1 !== index) this._dynamicEventProperties.splice(index, 1);
|
|
473
|
-
}
|
|
474
|
-
};
|
|
475
|
-
}
|
|
476
208
|
sendRequest(path, init) {
|
|
477
209
|
return (0, external_request_js_namespaceObject.sendRequest)(this._requestRuntime, path, init, ()=>!this._blocked && !this.hasOptedOut());
|
|
478
210
|
}
|
|
@@ -548,8 +280,8 @@ class PostHogBrowserClient {
|
|
|
548
280
|
}
|
|
549
281
|
return this._remoteConfigPromise;
|
|
550
282
|
}
|
|
551
|
-
|
|
552
|
-
return this._registry.
|
|
283
|
+
resolveExtension(name) {
|
|
284
|
+
return this._closing || this._disposed ? Promise.resolve(void 0) : this._registry.resolve(name);
|
|
553
285
|
}
|
|
554
286
|
shutdown(shutdownTimeoutMs = DEFAULT_SHUTDOWN_TIMEOUT_MS) {
|
|
555
287
|
if (!this._shutdownPromise) {
|
|
@@ -595,16 +327,17 @@ class PostHogBrowserClient {
|
|
|
595
327
|
} catch (error) {
|
|
596
328
|
this.logger.error('Failed to dispose browser state', error);
|
|
597
329
|
}
|
|
598
|
-
this.
|
|
330
|
+
this._analytics = void 0;
|
|
599
331
|
const cleanup = this._registry.dispose().catch((error)=>this.logger.error('Failed to dispose extensions', error));
|
|
600
332
|
this._remoteConfigPublisher.dispose();
|
|
601
333
|
this._eventPublisher.dispose();
|
|
602
334
|
this._identifyPublisher.dispose();
|
|
335
|
+
this._changePropertiesPublisher.dispose();
|
|
603
336
|
this._groupPublisher.dispose();
|
|
337
|
+
this._groupsResetPublisher.dispose();
|
|
604
338
|
this._resetPublisher.dispose();
|
|
605
339
|
this._consentChangePublisher.dispose();
|
|
606
340
|
this._newSessionPublisher.dispose();
|
|
607
|
-
this._dynamicEventProperties.splice(0);
|
|
608
341
|
await Promise.race([
|
|
609
342
|
cleanup,
|
|
610
343
|
timeout
|
|
@@ -618,43 +351,63 @@ class PostHogBrowserClient {
|
|
|
618
351
|
} catch {}
|
|
619
352
|
}
|
|
620
353
|
}
|
|
354
|
+
async _completeInitialization() {
|
|
355
|
+
await this._analytics?.start();
|
|
356
|
+
this._ready = true;
|
|
357
|
+
this._startInitialPageview();
|
|
358
|
+
await this._pageviewLoading;
|
|
359
|
+
}
|
|
621
360
|
_startInitialPageview() {
|
|
622
|
-
if (!this._capturePageview || !this._initialPageviewPending || this._closing || this._disposed) return;
|
|
361
|
+
if (!this._ready || !this._capturePageview || !this._initialPageviewPending || this._closing || this._disposed || !this._pageviewIsVisible()) return;
|
|
362
|
+
this._removePageviewListener();
|
|
363
|
+
if (!this._analytics) return void this._loadInitialPageviewAnalytics();
|
|
364
|
+
this._initialPageviewPending = false;
|
|
365
|
+
if (!this._analytics.captureInitialPageview()) this._initialPageviewPending = !this._disposed && !this._blocked;
|
|
366
|
+
}
|
|
367
|
+
_pageviewIsVisible() {
|
|
623
368
|
let document;
|
|
624
369
|
let visibility;
|
|
625
370
|
try {
|
|
626
371
|
document = globalThis.document;
|
|
627
372
|
visibility = document?.visibilityState;
|
|
628
373
|
} catch {
|
|
629
|
-
this.
|
|
630
|
-
|
|
631
|
-
return;
|
|
374
|
+
this._cancelInitialPageview();
|
|
375
|
+
return false;
|
|
632
376
|
}
|
|
633
377
|
if (!document || void 0 === visibility) {
|
|
634
|
-
this.
|
|
635
|
-
|
|
636
|
-
return;
|
|
378
|
+
this._cancelInitialPageview();
|
|
379
|
+
return false;
|
|
637
380
|
}
|
|
638
381
|
if ('visible' !== visibility) {
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
const listener = ()=>this._startInitialPageview();
|
|
642
|
-
this._pageviewListener = [
|
|
643
|
-
document,
|
|
644
|
-
listener
|
|
645
|
-
];
|
|
646
|
-
try {
|
|
647
|
-
document.addEventListener('visibilitychange', listener);
|
|
648
|
-
} catch {
|
|
649
|
-
this._removePageviewListener();
|
|
650
|
-
this._initialPageviewPending = false;
|
|
651
|
-
}
|
|
652
|
-
}
|
|
653
|
-
return;
|
|
382
|
+
this._watchPageviewVisibility(document);
|
|
383
|
+
return false;
|
|
654
384
|
}
|
|
385
|
+
return true;
|
|
386
|
+
}
|
|
387
|
+
_watchPageviewVisibility(document) {
|
|
388
|
+
if (this._pageviewListener?.[0] !== document) this._removePageviewListener();
|
|
389
|
+
if (this._pageviewListener) return;
|
|
390
|
+
const listener = ()=>this._startInitialPageview();
|
|
391
|
+
this._pageviewListener = [
|
|
392
|
+
document,
|
|
393
|
+
listener
|
|
394
|
+
];
|
|
395
|
+
try {
|
|
396
|
+
document.addEventListener('visibilitychange', listener);
|
|
397
|
+
} catch {
|
|
398
|
+
this._cancelInitialPageview();
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
_cancelInitialPageview() {
|
|
655
402
|
this._removePageviewListener();
|
|
656
403
|
this._initialPageviewPending = false;
|
|
657
|
-
|
|
404
|
+
}
|
|
405
|
+
_loadInitialPageviewAnalytics() {
|
|
406
|
+
if (this._pageviewLoading || this._blocked || this.hasOptedOut()) return;
|
|
407
|
+
this._pageviewLoading = this.resolveExtension('analytics').then(()=>{
|
|
408
|
+
this._pageviewLoading = void 0;
|
|
409
|
+
if (this._analytics) this._startInitialPageview();
|
|
410
|
+
});
|
|
658
411
|
}
|
|
659
412
|
_removePageviewListener() {
|
|
660
413
|
const listener = this._pageviewListener;
|
|
@@ -724,7 +477,7 @@ class PostHogBrowserClient {
|
|
|
724
477
|
}));
|
|
725
478
|
} catch {}
|
|
726
479
|
}
|
|
727
|
-
|
|
480
|
+
_createSharedExtensionClient(extensionName) {
|
|
728
481
|
const host = this;
|
|
729
482
|
const logger = this.logger.createLogger(extensionName);
|
|
730
483
|
const kv = this._state.keyValueStore(extensionName, ()=>!this._closing && !this._disposed && this._state.prepare());
|
|
@@ -756,62 +509,115 @@ class PostHogBrowserClient {
|
|
|
756
509
|
get canCapture () {
|
|
757
510
|
return host.canCapture;
|
|
758
511
|
},
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
512
|
+
get isRateLimited () {
|
|
513
|
+
return host._analytics?.isRateLimited ?? false;
|
|
514
|
+
},
|
|
515
|
+
capture: (event, properties, options)=>host._analytics?.capture(event, properties, options) ?? true,
|
|
516
|
+
registerDynamicEventProperties: (producer)=>host._analytics?.registerDynamicEventProperties(producer) ?? {
|
|
517
|
+
dispose () {}
|
|
518
|
+
},
|
|
519
|
+
getExtension: (name)=>host._registry.getShared(name),
|
|
762
520
|
get projectToken () {
|
|
763
521
|
return host.projectToken;
|
|
764
522
|
},
|
|
765
523
|
sendRequest: (path, init)=>host.sendRequest(path, init),
|
|
766
|
-
onConsentChange: host.onConsentChange,
|
|
767
524
|
onRemoteConfig: host.onRemoteConfig,
|
|
768
|
-
onEvent: host.
|
|
769
|
-
onIdentify: host.onIdentify,
|
|
770
|
-
onGroup: host.onGroup,
|
|
771
|
-
onReset: host.onReset,
|
|
525
|
+
onEvent: host._eventPublisher.listener,
|
|
772
526
|
onSession: host.onSession,
|
|
773
527
|
kv,
|
|
774
528
|
logger
|
|
775
529
|
};
|
|
776
530
|
}
|
|
531
|
+
_createExtensionClient(extensionName, resolve) {
|
|
532
|
+
const host = this;
|
|
533
|
+
const sharedClient = this._createSharedExtensionClient(extensionName);
|
|
534
|
+
const { getExtension: _lookup, capture: _capture, registerDynamicEventProperties: _registration, isRateLimited: _rateLimit, ...capabilities } = Object.getOwnPropertyDescriptors(sharedClient);
|
|
535
|
+
const browserClient = Object.defineProperties({
|
|
536
|
+
sharedClient,
|
|
537
|
+
resolveExtension: (name)=>this._closing || this._disposed ? Promise.resolve(void 0) : resolve(name),
|
|
538
|
+
onConsentChange: host.onConsentChange,
|
|
539
|
+
onIdentify: host.onIdentify,
|
|
540
|
+
onChangeProperties: host._changePropertiesPublisher.listener,
|
|
541
|
+
onGroup: host.onGroup,
|
|
542
|
+
onGroupsReset: host.onGroupsReset,
|
|
543
|
+
onReset: host.onReset
|
|
544
|
+
}, capabilities);
|
|
545
|
+
this._registry.expose(browserClient);
|
|
546
|
+
return browserClient;
|
|
547
|
+
}
|
|
548
|
+
async _setupExtension(extension, host) {
|
|
549
|
+
if (this._closing || this._disposed) throw new Error('The browser client is closing');
|
|
550
|
+
if (!(0, external_analytics_internal_js_namespaceObject.isAnalyticsExtension)(extension)) {
|
|
551
|
+
await extension.setup(host);
|
|
552
|
+
if (this._closing || this._disposed) throw new Error('The browser client is closing');
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
this._analytics = extension;
|
|
556
|
+
try {
|
|
557
|
+
extension.bindCaptureHost(this._analyticsCaptureHost(extension));
|
|
558
|
+
await extension.setup(host);
|
|
559
|
+
if (this._closing || this._disposed) throw new Error('The browser client is closing');
|
|
560
|
+
extension.initialize({
|
|
561
|
+
runtime: this._requestRuntime,
|
|
562
|
+
canRetry: ()=>this._canDeliver(),
|
|
563
|
+
reportFailure: (error)=>this.logger.error('Event delivery failed', error),
|
|
564
|
+
reportWarning: (message)=>this.logger.warn(message),
|
|
565
|
+
onAvailable: ()=>this._startInitialPageview()
|
|
566
|
+
});
|
|
567
|
+
} catch (error) {
|
|
568
|
+
if (this._analytics === extension) this._analytics = void 0;
|
|
569
|
+
throw error;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
_canUseAnalytics(owner) {
|
|
573
|
+
return this._analytics === owner && !this._closing && !this._disposed;
|
|
574
|
+
}
|
|
575
|
+
_analyticsCaptureHost(owner) {
|
|
576
|
+
const canMutate = ()=>this._canUseAnalytics(owner);
|
|
577
|
+
return {
|
|
578
|
+
projectToken: this.projectToken,
|
|
579
|
+
logger: this.logger,
|
|
580
|
+
state: this._state,
|
|
581
|
+
canCapture: ()=>canMutate() && !this._blocked && !this.hasOptedOut(),
|
|
582
|
+
canMutate,
|
|
583
|
+
isDisposed: ()=>this._disposed,
|
|
584
|
+
authority: ()=>this._immediateAuthority,
|
|
585
|
+
onEvent: this._eventPublisher.listener,
|
|
586
|
+
publishEvent: (event)=>this._eventPublisher.publish(event),
|
|
587
|
+
publishNewSession: (session)=>this._newSessionPublisher.publish(session),
|
|
588
|
+
publishIdentify: (info)=>this._identifyPublisher.publish(info),
|
|
589
|
+
publishChangeProperties: (info)=>this._changePropertiesPublisher.publish(info),
|
|
590
|
+
publishGroup: (info)=>this._groupPublisher.publish(info),
|
|
591
|
+
publishGroupsReset: ()=>this._groupsResetPublisher.publish(void 0),
|
|
592
|
+
publishReset: ()=>this._resetPublisher.publish(void 0)
|
|
593
|
+
};
|
|
594
|
+
}
|
|
777
595
|
_canDeliver() {
|
|
778
596
|
return !this._disposed && !this._blocked && !this.hasOptedOut();
|
|
779
597
|
}
|
|
780
598
|
}
|
|
781
|
-
const
|
|
782
|
-
const
|
|
783
|
-
const
|
|
784
|
-
|
|
599
|
+
const selectConfiguredExtensions = (configured)=>{
|
|
600
|
+
const selected = new Map();
|
|
601
|
+
for (const extension of configured)if (!selected.has(extension.name)) selected.set(extension.name, extension);
|
|
602
|
+
return selected;
|
|
603
|
+
};
|
|
604
|
+
const createPostHogCore = async (options, configured = options?.extensions ?? [], automaticLoaders = {}, automatic = [])=>{
|
|
605
|
+
const selected = selectConfiguredExtensions(configured);
|
|
606
|
+
const loaders = Object.fromEntries([
|
|
607
|
+
...Object.entries(automaticLoaders),
|
|
608
|
+
...Array.from(selected, ([name, extension])=>[
|
|
609
|
+
name,
|
|
610
|
+
()=>extension
|
|
611
|
+
])
|
|
612
|
+
]);
|
|
613
|
+
const client = PostHog.create(options ?? {
|
|
785
614
|
projectToken: ''
|
|
786
|
-
},
|
|
615
|
+
}, loaders);
|
|
787
616
|
client.getRemoteConfig();
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
runtime: client._requestRuntime,
|
|
793
|
-
canRetry: ()=>client._canDeliver(),
|
|
794
|
-
reportFailure: (error)=>client.logger.error('Event delivery failed', error),
|
|
795
|
-
reportWarning: (message)=>client.logger.warn(message),
|
|
796
|
-
onAvailable: ()=>client._startInitialPageview()
|
|
797
|
-
});
|
|
798
|
-
analyticsReady = true;
|
|
799
|
-
} catch (error) {
|
|
800
|
-
client._captureSink = void 0;
|
|
801
|
-
try {
|
|
802
|
-
await client._registry.rollback(analytics);
|
|
803
|
-
} catch (cleanupError) {
|
|
804
|
-
client.logger.error(`Failed to dispose disabled extension "${analytics.name}"`, cleanupError);
|
|
805
|
-
}
|
|
806
|
-
client.logger.error(`Failed to install configured extension "${analytics.name}"`, error);
|
|
807
|
-
}
|
|
808
|
-
for (const extension of extensions)try {
|
|
809
|
-
await client._registry.install(extension);
|
|
810
|
-
} catch (error) {
|
|
811
|
-
client.logger.error(`Failed to install configured extension "${extension.name}"`, error);
|
|
812
|
-
}
|
|
813
|
-
if (analyticsReady) await analytics.start();
|
|
814
|
-
client._startInitialPageview();
|
|
617
|
+
if (selected.has('analytics')) await client.resolveExtension('analytics');
|
|
618
|
+
for (const name of selected.keys())if ('analytics' !== name) await client.resolveExtension(name);
|
|
619
|
+
for (const extension of automatic)await client._registry.activate(extension);
|
|
620
|
+
await client._completeInitialization();
|
|
815
621
|
return client;
|
|
816
622
|
};
|
|
817
623
|
exports.createPostHogCore = __webpack_exports__.createPostHogCore;
|