@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.
- package/ARCHITECTURE.md +36 -48
- package/README.md +97 -69
- package/dist/composition/npm/core.d.ts +3 -4
- package/dist/composition/npm/core.js +2 -1
- package/dist/composition/npm/core.mjs +2 -1
- package/dist/composition/npm/index.d.ts +4 -5
- package/dist/composition/npm/index.js +2 -1
- package/dist/composition/npm/index.mjs +2 -1
- package/dist/composition/npm/root-composition.d.ts +4 -4
- package/dist/composition/npm/root-composition.js +0 -16
- package/dist/composition/npm/root-composition.mjs +0 -16
- package/dist/core/context/browser-client.d.ts +4 -35
- package/dist/core/extensions/registry.d.ts +15 -36
- package/dist/core/extensions/registry.js +67 -198
- package/dist/core/extensions/registry.mjs +67 -198
- package/dist/core/posthog.d.ts +3 -2
- package/dist/core/posthog.js +190 -173
- package/dist/core/posthog.mjs +191 -174
- package/dist/core/state/state.d.ts +33 -3
- package/dist/core/state/state.js +122 -27
- package/dist/core/state/state.mjs +107 -27
- package/dist/core/types.d.ts +134 -14
- package/dist/persistence/cookie.d.ts +19 -0
- package/dist/persistence/cookie.js +273 -0
- package/dist/persistence/cookie.mjs +235 -0
- package/dist/platform/logger.d.ts +5 -1
- package/dist/platform/logger.js +3 -3
- package/dist/platform/logger.mjs +3 -3
- package/dist/primitives/id.d.ts +5 -0
- package/dist/primitives/id.js +10 -2
- package/dist/primitives/id.mjs +6 -1
- package/dist/primitives/version.js +1 -1
- package/dist/primitives/version.mjs +1 -1
- package/dist/products/analytics/analytics-core.d.ts +89 -0
- package/dist/products/analytics/analytics-core.js +563 -0
- package/dist/products/analytics/analytics-core.mjs +516 -0
- package/dist/products/analytics/analytics-internal.d.ts +16 -37
- package/dist/products/analytics/analytics-internal.js +2 -10
- package/dist/products/analytics/analytics-internal.mjs +1 -3
- package/dist/products/analytics/analytics-options.d.ts +0 -9
- package/dist/products/analytics/analytics-options.js +1 -38
- package/dist/products/analytics/analytics-options.mjs +1 -17
- package/dist/products/analytics/delivery/analytics-delivery.js +1 -1
- package/dist/products/analytics/delivery/analytics-delivery.mjs +1 -1
- package/dist/products/analytics/delivery/lane.d.ts +8 -1
- package/dist/products/analytics/delivery/lane.js +16 -4
- package/dist/products/analytics/delivery/lane.mjs +16 -4
- package/dist/products/analytics/groups.d.ts +8 -0
- package/dist/products/analytics/groups.js +84 -0
- package/dist/products/analytics/groups.mjs +40 -0
- package/dist/products/analytics/person.d.ts +11 -0
- package/dist/products/analytics/person.js +91 -0
- package/dist/products/analytics/person.mjs +41 -0
- package/dist/products/analytics/properties/analytics-properties.d.ts +1 -0
- package/dist/products/analytics/properties/analytics-properties.js +3 -0
- package/dist/products/analytics/properties/analytics-properties.mjs +1 -1
- package/dist/products/autocapture/autocapture.js +2 -6
- package/dist/products/autocapture/autocapture.mjs +2 -6
- package/dist/products/flags/flags-internal.d.ts +4 -2
- package/dist/products/flags/flags-options.d.ts +16 -2
- package/dist/products/flags/flags-token.d.ts +31 -4
- package/dist/products/flags/flags.d.ts +1 -1
- package/dist/products/flags/flags.js +112 -11
- package/dist/products/flags/flags.mjs +112 -11
- package/dist/products/logs/logs.js +2 -5
- package/dist/products/logs/logs.mjs +2 -5
- package/dist/products/surveys/surveys-extension.js +78 -46
- package/dist/products/surveys/surveys-extension.mjs +80 -48
- package/dist/products/surveys/surveys-internal.d.ts +6 -0
- package/package.json +7 -7
- package/dist/products/analytics/analytics-api.d.ts +0 -32
- package/dist/products/analytics/analytics-api.js +0 -18
- package/dist/products/analytics/analytics-api.mjs +0 -1
- package/dist/products/analytics/analytics-buffer.d.ts +0 -4
- package/dist/products/analytics/analytics-buffer.js +0 -41
- package/dist/products/analytics/analytics-buffer.mjs +0 -3
- package/dist/products/analytics/analytics-extension.d.ts +0 -87
- package/dist/products/analytics/analytics-extension.js +0 -649
- package/dist/products/analytics/analytics-extension.mjs +0 -611
- package/dist/products/analytics/analytics.d.ts +0 -6
- package/dist/products/analytics/analytics.js +0 -42
- package/dist/products/analytics/analytics.mjs +0 -4
- package/dist/products/analytics/automatic-analytics.d.ts +0 -3
- package/dist/products/analytics/automatic-analytics.js +0 -44
- package/dist/products/analytics/automatic-analytics.mjs +0 -6
package/dist/core/posthog.mjs
CHANGED
|
@@ -1,15 +1,28 @@
|
|
|
1
1
|
import { loadRemoteConfig } from "./remote-config.mjs";
|
|
2
2
|
import { Publisher } from "@posthog/browser-common/pubsub";
|
|
3
|
-
import {
|
|
3
|
+
import { Analytics } from "../products/analytics/analytics-core.mjs";
|
|
4
4
|
import { isLikelyBot } from "./state/bot-filter.mjs";
|
|
5
5
|
import { ExtensionRegistry } from "./extensions/registry.mjs";
|
|
6
6
|
import { deepFreeze } from "../primitives/immutable.mjs";
|
|
7
7
|
import { createLogger } from "../platform/logger.mjs";
|
|
8
|
+
import { snapshotPersonProfileMode } from "../products/analytics/properties/person-processing.mjs";
|
|
8
9
|
import { sendRequest } from "../platform/request.mjs";
|
|
9
|
-
import { BrowserState, getDefaultSessionStorage, getDefaultStorage } from "./state/state.mjs";
|
|
10
|
+
import { BrowserState, CLIENT_KV_NAMESPACE, getDefaultSessionStorage, getDefaultStorage } from "./state/state.mjs";
|
|
10
11
|
import { version } from "../primitives/version.mjs";
|
|
12
|
+
import * as __rspack_external__products_analytics_groups_mjs_441733a9 from "../products/analytics/groups.mjs";
|
|
13
|
+
import * as __rspack_external__products_analytics_person_mjs_3dfa168e from "../products/analytics/person.mjs";
|
|
11
14
|
const CONSENT_CHANGE_EVENT = '__posthog_browser_consent_change__';
|
|
12
15
|
const DEFAULT_SHUTDOWN_TIMEOUT_MS = 30000;
|
|
16
|
+
const EARLY_ACCESS_CATALOGUE_PATH = /^\/api\/early_access_features\/\?token=[^&#]*(&stage=(concept|alpha|beta|general-availability))*&?$/;
|
|
17
|
+
const resolveRequestPath = (host, path)=>{
|
|
18
|
+
try {
|
|
19
|
+
const base = new URL(`${host}/`);
|
|
20
|
+
const { pathname } = new URL(`.${path}`, base);
|
|
21
|
+
return pathname.startsWith(base.pathname) ? pathname.slice(base.pathname.length - 1) : void 0;
|
|
22
|
+
} catch {
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
};
|
|
13
26
|
const normalizeHost = (host)=>{
|
|
14
27
|
let end = host.length;
|
|
15
28
|
while(end > 0 && 47 === host.charCodeAt(end - 1))end--;
|
|
@@ -40,15 +53,16 @@ const getDefaultNavigator = ()=>{
|
|
|
40
53
|
}
|
|
41
54
|
};
|
|
42
55
|
class PostHog {
|
|
43
|
-
static create(options, loaders) {
|
|
44
|
-
return new PostHog(options, loaders);
|
|
56
|
+
static create(options, createDelivery, loaders) {
|
|
57
|
+
return new PostHog(options, createDelivery, loaders);
|
|
45
58
|
}
|
|
46
|
-
constructor(options, loaders){
|
|
59
|
+
constructor(options, createDelivery, loaders){
|
|
47
60
|
this.library = Object.freeze({
|
|
48
61
|
name: 'web',
|
|
49
62
|
version: version
|
|
50
63
|
});
|
|
51
64
|
this._immediateAuthority = {};
|
|
65
|
+
this._clearedChoiceRetainsWork = false;
|
|
52
66
|
this._closing = false;
|
|
53
67
|
this._disposed = false;
|
|
54
68
|
this._initialPageviewPending = true;
|
|
@@ -59,7 +73,10 @@ class PostHog {
|
|
|
59
73
|
} catch {}
|
|
60
74
|
this.projectToken = projectToken;
|
|
61
75
|
this._capturePageview = options.capturePageview ?? true;
|
|
62
|
-
this.
|
|
76
|
+
this._logState = {
|
|
77
|
+
enabled: options.debug ?? false
|
|
78
|
+
};
|
|
79
|
+
this.logger = createLogger('[PostHog]', this._logState);
|
|
63
80
|
if (!projectToken) this.logger.error('A PostHog project token is required');
|
|
64
81
|
const initialPersonProperties = options.initialPersonProperties;
|
|
65
82
|
try {
|
|
@@ -68,29 +85,25 @@ class PostHog {
|
|
|
68
85
|
this.initialPersonProperties = Object.freeze({});
|
|
69
86
|
}
|
|
70
87
|
this._remoteConfigPublisher = new Publisher((error)=>this.logger.error('A remote configuration listener failed', error));
|
|
71
|
-
this._eventPublisher = new Publisher((error)=>this.logger.error('An event listener failed', error));
|
|
72
|
-
this._identifyPublisher = new Publisher((error)=>this.logger.error('An identify listener failed', error));
|
|
73
|
-
this._changePropertiesPublisher = new Publisher((error)=>this.logger.error('A person-property listener failed', error));
|
|
74
|
-
this._groupPublisher = new Publisher((error)=>this.logger.error('A group listener failed', error));
|
|
75
|
-
this._groupsResetPublisher = new Publisher((error)=>this.logger.error('A group reset listener failed', error));
|
|
76
|
-
this._resetPublisher = new Publisher((error)=>this.logger.error('A reset listener failed', error));
|
|
77
|
-
this._newSessionPublisher = new Publisher((error)=>this.logger.error('A session listener failed', error));
|
|
78
88
|
this._consentChangePublisher = new Publisher((error)=>this.logger.error('A consent change listener failed', error));
|
|
79
89
|
const browserNavigator = false === options.navigator ? void 0 : options.navigator ?? getDefaultNavigator();
|
|
80
90
|
const browserFetch = false === options.fetch ? void 0 : options.fetch ?? getDefaultFetch();
|
|
81
91
|
this._blocked = !projectToken || !(options.disableBotDetection ?? false) && isLikelyBot(browserNavigator, options.blockedUserAgents ?? []);
|
|
82
92
|
const requestedStorage = false === options.storage ? void 0 : options.storage ?? getDefaultStorage();
|
|
83
93
|
const storage = this._blocked ? void 0 : requestedStorage;
|
|
84
|
-
this._state = new BrowserState(projectToken, storage, options.persistenceKey, options.consentPersistenceName, options.optOutByDefault ?? false, !this._blocked && void 0 === options.storage && void 0 !== requestedStorage ? getDefaultSessionStorage : void 0, (consent, previous)=>{
|
|
85
|
-
if ('denied'
|
|
86
|
-
this.
|
|
87
|
-
this.
|
|
88
|
-
}
|
|
89
|
-
this.
|
|
94
|
+
this._state = new BrowserState(projectToken, storage, options.persistenceKey, options.consentPersistenceName, options.optOutByDefault ?? false, !this._blocked && void 0 === options.storage && void 0 !== requestedStorage ? getDefaultSessionStorage : void 0, (consent, previous, explicit)=>{
|
|
95
|
+
if ('denied' !== consent) {
|
|
96
|
+
if (this._clearedChoiceRetainsWork) Promise.resolve().then(()=>this._analytics?.flush());
|
|
97
|
+
this._clearedChoiceRetainsWork = false;
|
|
98
|
+
} else if (explicit) this._revokeAdmittedWork();
|
|
99
|
+
else this._clearedChoiceRetainsWork = true;
|
|
100
|
+
const change = {
|
|
90
101
|
current: consent,
|
|
91
102
|
previous
|
|
92
|
-
}
|
|
93
|
-
|
|
103
|
+
};
|
|
104
|
+
if (this._heldConsentChanges) this._heldConsentChanges.push(change);
|
|
105
|
+
else this._consentChangePublisher.publish(change);
|
|
106
|
+
}, options.cookie);
|
|
94
107
|
this._consentObservation = this._observeConsent(storage, !this._blocked && void 0 === options.storage && void 0 !== requestedStorage);
|
|
95
108
|
const apiHost = normalizeHost(options.apiHost ?? 'https://us.i.posthog.com');
|
|
96
109
|
this._requestRuntime = [
|
|
@@ -105,7 +118,8 @@ class PostHog {
|
|
|
105
118
|
];
|
|
106
119
|
this._remoteConfig = options.remoteConfig;
|
|
107
120
|
this._remoteConfigTimeoutMs = void 0 !== options.remoteConfigTimeoutMs && Number.isFinite(options.remoteConfigTimeoutMs) ? Math.max(0, options.remoteConfigTimeoutMs) : 10000;
|
|
108
|
-
this.kv = this._state.keyValueStore(
|
|
121
|
+
this.kv = this._state.keyValueStore(CLIENT_KV_NAMESPACE, ()=>this._canMutate() && this._state.prepare());
|
|
122
|
+
this._sessionKv = this._state.tabKeyValueStore('analytics', ()=>this._canMutate() && this._state.prepare());
|
|
109
123
|
this._latestRemoteConfigResult = this._remoteConfig ? {
|
|
110
124
|
ok: true,
|
|
111
125
|
config: this._remoteConfig
|
|
@@ -123,15 +137,33 @@ class PostHog {
|
|
|
123
137
|
else if (!this._closing && !this._disposed) this.getRemoteConfig();
|
|
124
138
|
return subscription;
|
|
125
139
|
};
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
140
|
+
let analyticsOptions = {};
|
|
141
|
+
try {
|
|
142
|
+
analyticsOptions = options.analytics ?? {};
|
|
143
|
+
if (false === analyticsOptions) this.logger.warn('The `analytics: false` option was removed in this version, so events are captured. Set `capturePageview: false` to skip the initial $pageview and, on the root entrypoint, `autocapture: false` to turn off autocapture.');
|
|
144
|
+
} catch {}
|
|
145
|
+
this._analytics = new Analytics(this, analyticsOptions, createDelivery);
|
|
146
|
+
this.onEvent = this._analytics._eventPublisher.listener;
|
|
147
|
+
this.onIdentify = this._analytics._identifyPublisher.listener;
|
|
148
|
+
this.onChangeProperties = this._analytics._changePropertiesPublisher.listener;
|
|
149
|
+
this.onGroup = this._analytics._groupPublisher.listener;
|
|
150
|
+
this.onGroupsReset = this._analytics._groupsResetPublisher.listener;
|
|
151
|
+
this.onReset = this._analytics._resetPublisher.listener;
|
|
152
|
+
this.onNewSession = this._analytics._newSessionPublisher.listener;
|
|
130
153
|
this.onConsentChange = this._consentChangePublisher.listener;
|
|
131
|
-
this.onNewSession = this._newSessionPublisher.listener;
|
|
132
154
|
this.onSession = (listener)=>this.onNewSession((session)=>listener(session.sessionId));
|
|
133
|
-
this.
|
|
134
|
-
|
|
155
|
+
this.onSessionId = (handler)=>{
|
|
156
|
+
const subscription = this._analytics._sessionIdPublisher.listener(handler);
|
|
157
|
+
const session = this._canMutate() ? this.session : void 0;
|
|
158
|
+
if (session) try {
|
|
159
|
+
handler(session);
|
|
160
|
+
} catch (error) {
|
|
161
|
+
this.logger.error('A session ID listener failed', error);
|
|
162
|
+
}
|
|
163
|
+
return subscription;
|
|
164
|
+
};
|
|
165
|
+
this._registry = new ExtensionRegistry(this, this.logger, loaders, ()=>this._canMutate());
|
|
166
|
+
if (options.bootstrap) this._analytics.bootstrap(options.bootstrap);
|
|
135
167
|
}
|
|
136
168
|
get distinctId() {
|
|
137
169
|
this._state.prepare();
|
|
@@ -159,8 +191,87 @@ class PostHog {
|
|
|
159
191
|
get canCapture() {
|
|
160
192
|
return !this._closing && !this._disposed && !this._blocked && !this.hasOptedOut() && this._state.prepare();
|
|
161
193
|
}
|
|
194
|
+
get isRateLimited() {
|
|
195
|
+
return this._analytics.isRateLimited;
|
|
196
|
+
}
|
|
197
|
+
capture(event, properties, options) {
|
|
198
|
+
return this._analytics.capture(event, properties, options);
|
|
199
|
+
}
|
|
200
|
+
captureImmediate(event, properties, options) {
|
|
201
|
+
return this._analytics.captureImmediate(event, properties, options);
|
|
202
|
+
}
|
|
203
|
+
identify(distinctId, set, setOnce) {
|
|
204
|
+
this._analytics.identify(distinctId, set, setOnce);
|
|
205
|
+
}
|
|
206
|
+
reset(options) {
|
|
207
|
+
if (!this._canMutate()) return;
|
|
208
|
+
const held = this._heldConsentChanges = [];
|
|
209
|
+
let bootstrap;
|
|
210
|
+
try {
|
|
211
|
+
this.clearOptInOut();
|
|
212
|
+
bootstrap = this._analytics.reset(options);
|
|
213
|
+
} finally{
|
|
214
|
+
this._heldConsentChanges = void 0;
|
|
215
|
+
}
|
|
216
|
+
for (const change of held)this._consentChangePublisher.publish(change);
|
|
217
|
+
if (bootstrap) this.featureFlags?.bootstrap?.(bootstrap);
|
|
218
|
+
}
|
|
219
|
+
register(properties) {
|
|
220
|
+
this._analytics.register(properties);
|
|
221
|
+
}
|
|
222
|
+
registerOnce(properties, defaultValue) {
|
|
223
|
+
this._analytics.registerOnce(properties, defaultValue);
|
|
224
|
+
}
|
|
225
|
+
unregister(property) {
|
|
226
|
+
this._analytics.unregister(property);
|
|
227
|
+
}
|
|
228
|
+
getProperty(property) {
|
|
229
|
+
return this._analytics.getProperty(property);
|
|
230
|
+
}
|
|
231
|
+
registerForSession(properties) {
|
|
232
|
+
this._analytics.registerForSession(properties);
|
|
233
|
+
}
|
|
234
|
+
unregisterForSession(property) {
|
|
235
|
+
this._analytics.unregisterForSession(property);
|
|
236
|
+
}
|
|
237
|
+
alias(aliasId) {
|
|
238
|
+
__rspack_external__products_analytics_person_mjs_3dfa168e.alias(this, aliasId);
|
|
239
|
+
}
|
|
240
|
+
group(type, key, properties) {
|
|
241
|
+
__rspack_external__products_analytics_groups_mjs_441733a9.group(this, type, key, properties);
|
|
242
|
+
}
|
|
243
|
+
groupIdentify(type, key, properties, options) {
|
|
244
|
+
__rspack_external__products_analytics_groups_mjs_441733a9.groupIdentify(this, type, key, properties, options);
|
|
245
|
+
}
|
|
246
|
+
resetGroups() {
|
|
247
|
+
__rspack_external__products_analytics_groups_mjs_441733a9.resetGroups(this);
|
|
248
|
+
}
|
|
249
|
+
createPersonProfile() {
|
|
250
|
+
__rspack_external__products_analytics_person_mjs_3dfa168e.createPersonProfile(this);
|
|
251
|
+
}
|
|
252
|
+
setPersonProperties(set, setOnce) {
|
|
253
|
+
__rspack_external__products_analytics_person_mjs_3dfa168e.setPersonProperties(this, set, setOnce);
|
|
254
|
+
}
|
|
255
|
+
unsetPersonProperties(names) {
|
|
256
|
+
__rspack_external__products_analytics_person_mjs_3dfa168e.unsetPersonProperties(this, names);
|
|
257
|
+
}
|
|
258
|
+
setInternalOrTestUser() {
|
|
259
|
+
__rspack_external__products_analytics_person_mjs_3dfa168e.setInternalOrTestUser(this);
|
|
260
|
+
}
|
|
261
|
+
registerDynamicEventProperties(producer) {
|
|
262
|
+
return this._analytics.registerDynamicEventProperties(producer);
|
|
263
|
+
}
|
|
264
|
+
getPageViewId() {
|
|
265
|
+
return this._analytics._pageviewIdFor(this._state.activeSessionId);
|
|
266
|
+
}
|
|
267
|
+
getExtension(name) {
|
|
268
|
+
return this._registry.get(name);
|
|
269
|
+
}
|
|
162
270
|
async flush() {
|
|
163
|
-
await
|
|
271
|
+
await Promise.all([
|
|
272
|
+
this._registry.flush(),
|
|
273
|
+
this._analytics.flush()
|
|
274
|
+
]);
|
|
164
275
|
}
|
|
165
276
|
optIn() {
|
|
166
277
|
if (this._disposed) return;
|
|
@@ -168,13 +279,25 @@ class PostHog {
|
|
|
168
279
|
this._startInitialPageview();
|
|
169
280
|
}
|
|
170
281
|
optOut() {
|
|
171
|
-
if (
|
|
282
|
+
if (this._disposed) return;
|
|
283
|
+
if (this._clearedChoiceRetainsWork) this._revokeAdmittedWork();
|
|
284
|
+
if (this._state.optOut()) this._dispatchConsentChange();
|
|
172
285
|
}
|
|
173
286
|
hasOptedOut() {
|
|
174
287
|
return 'denied' === this._state.consent;
|
|
175
288
|
}
|
|
289
|
+
getExplicitConsentStatus() {
|
|
290
|
+
return this._state.consentChoice ?? 'pending';
|
|
291
|
+
}
|
|
292
|
+
clearOptInOut() {
|
|
293
|
+
if (this._disposed) return;
|
|
294
|
+
if (this._state.clearConsent()) this._dispatchConsentChange();
|
|
295
|
+
}
|
|
176
296
|
sendRequest(path, init) {
|
|
177
|
-
|
|
297
|
+
const options = init ?? {};
|
|
298
|
+
const resolvedPath = resolveRequestPath(this._requestRuntime[0][options.target ?? 'api'], path);
|
|
299
|
+
const allowedWhileOptedOut = ('flags' === options.target ? '/flags/' === resolvedPath : EARLY_ACCESS_CATALOGUE_PATH.test(path) && (options.method ?? 'GET') === 'GET' && void 0 === options.body) && !options.query && !options.headers;
|
|
300
|
+
return sendRequest(this._requestRuntime, path, options, ()=>!this._blocked && (allowedWhileOptedOut || !this.hasOptedOut()));
|
|
178
301
|
}
|
|
179
302
|
async getRemoteConfig() {
|
|
180
303
|
if (this._closing || this._disposed) return;
|
|
@@ -248,13 +371,31 @@ class PostHog {
|
|
|
248
371
|
}
|
|
249
372
|
return this._remoteConfigPromise;
|
|
250
373
|
}
|
|
374
|
+
setConfig(options) {
|
|
375
|
+
try {
|
|
376
|
+
const debug = options.debug;
|
|
377
|
+
if ('boolean' == typeof debug) this._logState.enabled = debug;
|
|
378
|
+
const personProfiles = options.analytics?.personProfiles;
|
|
379
|
+
if (void 0 !== personProfiles) this._analytics._personProfiles = snapshotPersonProfileMode(()=>personProfiles);
|
|
380
|
+
} catch (error) {
|
|
381
|
+
this.logger.error('Configuration update failed', error);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
debug(enabled = true) {
|
|
385
|
+
this.setConfig({
|
|
386
|
+
debug: enabled
|
|
387
|
+
});
|
|
388
|
+
}
|
|
251
389
|
resolveExtension(name) {
|
|
252
390
|
return this._closing || this._disposed ? Promise.resolve(void 0) : this._registry.resolve(name);
|
|
253
391
|
}
|
|
254
392
|
shutdown(shutdownTimeoutMs = DEFAULT_SHUTDOWN_TIMEOUT_MS) {
|
|
255
393
|
if (!this._shutdownPromise) {
|
|
256
394
|
this._closing = true;
|
|
257
|
-
const extensionFlush =
|
|
395
|
+
const extensionFlush = Promise.all([
|
|
396
|
+
this._registry.flush('shutdown'),
|
|
397
|
+
this._analytics.flush()
|
|
398
|
+
]).then(()=>void 0);
|
|
258
399
|
this._removePageviewListener();
|
|
259
400
|
try {
|
|
260
401
|
this._consentObservation.dispose();
|
|
@@ -295,17 +436,12 @@ class PostHog {
|
|
|
295
436
|
} catch (error) {
|
|
296
437
|
this.logger.error('Failed to dispose browser state', error);
|
|
297
438
|
}
|
|
298
|
-
|
|
299
|
-
|
|
439
|
+
const cleanup = Promise.all([
|
|
440
|
+
this._registry.dispose(),
|
|
441
|
+
this._analytics.dispose()
|
|
442
|
+
]).catch((error)=>this.logger.error('Failed to dispose extensions', error));
|
|
300
443
|
this._remoteConfigPublisher.dispose();
|
|
301
|
-
this._eventPublisher.dispose();
|
|
302
|
-
this._identifyPublisher.dispose();
|
|
303
|
-
this._changePropertiesPublisher.dispose();
|
|
304
|
-
this._groupPublisher.dispose();
|
|
305
|
-
this._groupsResetPublisher.dispose();
|
|
306
|
-
this._resetPublisher.dispose();
|
|
307
444
|
this._consentChangePublisher.dispose();
|
|
308
|
-
this._newSessionPublisher.dispose();
|
|
309
445
|
await Promise.race([
|
|
310
446
|
cleanup,
|
|
311
447
|
timeout
|
|
@@ -319,16 +455,13 @@ class PostHog {
|
|
|
319
455
|
} catch {}
|
|
320
456
|
}
|
|
321
457
|
}
|
|
322
|
-
|
|
323
|
-
await this._analytics?.start();
|
|
458
|
+
_completeInitialization() {
|
|
324
459
|
this._ready = true;
|
|
325
460
|
this._startInitialPageview();
|
|
326
|
-
await this._pageviewLoading;
|
|
327
461
|
}
|
|
328
462
|
_startInitialPageview() {
|
|
329
463
|
if (!this._ready || !this._capturePageview || !this._initialPageviewPending || this._closing || this._disposed || !this._pageviewIsVisible()) return;
|
|
330
464
|
this._removePageviewListener();
|
|
331
|
-
if (!this._analytics) return void this._loadInitialPageviewAnalytics();
|
|
332
465
|
this._initialPageviewPending = false;
|
|
333
466
|
if (!this._analytics.captureInitialPageview()) this._initialPageviewPending = !this._disposed && !this._blocked;
|
|
334
467
|
}
|
|
@@ -370,13 +503,6 @@ class PostHog {
|
|
|
370
503
|
this._removePageviewListener();
|
|
371
504
|
this._initialPageviewPending = false;
|
|
372
505
|
}
|
|
373
|
-
_loadInitialPageviewAnalytics() {
|
|
374
|
-
if (this._pageviewLoading || this._blocked || this.hasOptedOut()) return;
|
|
375
|
-
this._pageviewLoading = this.resolveExtension('analytics').then(()=>{
|
|
376
|
-
this._pageviewLoading = void 0;
|
|
377
|
-
if (this._analytics) this._startInitialPageview();
|
|
378
|
-
});
|
|
379
|
-
}
|
|
380
506
|
_removePageviewListener() {
|
|
381
507
|
const listener = this._pageviewListener;
|
|
382
508
|
this._pageviewListener = void 0;
|
|
@@ -445,124 +571,16 @@ class PostHog {
|
|
|
445
571
|
}));
|
|
446
572
|
} catch {}
|
|
447
573
|
}
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
const logger = this.logger.createLogger(extensionName);
|
|
451
|
-
const kv = this._state.keyValueStore(extensionName, ()=>!this._closing && !this._disposed && this._state.prepare());
|
|
452
|
-
return {
|
|
453
|
-
get distinctId () {
|
|
454
|
-
return host.distinctId;
|
|
455
|
-
},
|
|
456
|
-
get anonymousId () {
|
|
457
|
-
return host.anonymousId;
|
|
458
|
-
},
|
|
459
|
-
get deviceId () {
|
|
460
|
-
return host.deviceId;
|
|
461
|
-
},
|
|
462
|
-
get library () {
|
|
463
|
-
return host.library;
|
|
464
|
-
},
|
|
465
|
-
get initialPersonProperties () {
|
|
466
|
-
return host.initialPersonProperties;
|
|
467
|
-
},
|
|
468
|
-
get groups () {
|
|
469
|
-
return host.groups;
|
|
470
|
-
},
|
|
471
|
-
get session () {
|
|
472
|
-
return host.session;
|
|
473
|
-
},
|
|
474
|
-
get isOptedOut () {
|
|
475
|
-
return host.isOptedOut;
|
|
476
|
-
},
|
|
477
|
-
get canCapture () {
|
|
478
|
-
return host.canCapture;
|
|
479
|
-
},
|
|
480
|
-
get isRateLimited () {
|
|
481
|
-
return host._analytics?.isRateLimited ?? false;
|
|
482
|
-
},
|
|
483
|
-
capture: (event, properties, options)=>host._analytics?.capture(event, properties, options) ?? true,
|
|
484
|
-
registerDynamicEventProperties: (producer)=>host._analytics?.registerDynamicEventProperties(producer) ?? {
|
|
485
|
-
dispose () {}
|
|
486
|
-
},
|
|
487
|
-
getExtension: (name)=>host._registry.getShared(name),
|
|
488
|
-
get projectToken () {
|
|
489
|
-
return host.projectToken;
|
|
490
|
-
},
|
|
491
|
-
sendRequest: (path, init)=>host.sendRequest(path, init),
|
|
492
|
-
onRemoteConfig: host.onRemoteConfig,
|
|
493
|
-
onEvent: host._eventPublisher.listener,
|
|
494
|
-
onSession: host.onSession,
|
|
495
|
-
kv,
|
|
496
|
-
logger
|
|
497
|
-
};
|
|
498
|
-
}
|
|
499
|
-
_createExtensionClient(extensionName, resolve) {
|
|
500
|
-
const host = this;
|
|
501
|
-
const sharedClient = this._createSharedExtensionClient(extensionName);
|
|
502
|
-
const { getExtension: _lookup, capture: _capture, registerDynamicEventProperties: _registration, isRateLimited: _rateLimit, ...capabilities } = Object.getOwnPropertyDescriptors(sharedClient);
|
|
503
|
-
const browserClient = Object.defineProperties({
|
|
504
|
-
sharedClient,
|
|
505
|
-
resolveExtension: (name)=>this._closing || this._disposed ? Promise.resolve(void 0) : resolve(name),
|
|
506
|
-
onConsentChange: host.onConsentChange,
|
|
507
|
-
onIdentify: host.onIdentify,
|
|
508
|
-
onChangeProperties: host._changePropertiesPublisher.listener,
|
|
509
|
-
onGroup: host.onGroup,
|
|
510
|
-
onGroupsReset: host.onGroupsReset,
|
|
511
|
-
onReset: host.onReset
|
|
512
|
-
}, capabilities);
|
|
513
|
-
this._registry.expose(browserClient);
|
|
514
|
-
return browserClient;
|
|
515
|
-
}
|
|
516
|
-
async _setupExtension(extension, host) {
|
|
517
|
-
if (this._closing || this._disposed) throw new Error('The browser client is closing');
|
|
518
|
-
if (!isAnalyticsExtension(extension)) {
|
|
519
|
-
await extension.setup(host);
|
|
520
|
-
if (this._closing || this._disposed) throw new Error('The browser client is closing');
|
|
521
|
-
return;
|
|
522
|
-
}
|
|
523
|
-
this._analytics = extension;
|
|
524
|
-
try {
|
|
525
|
-
extension.bindCaptureHost(this._analyticsCaptureHost(extension));
|
|
526
|
-
await extension.setup(host);
|
|
527
|
-
if (this._closing || this._disposed) throw new Error('The browser client is closing');
|
|
528
|
-
extension.initialize({
|
|
529
|
-
runtime: this._requestRuntime,
|
|
530
|
-
canRetry: ()=>this._canDeliver(),
|
|
531
|
-
reportFailure: (error)=>this.logger.error('Event delivery failed', error),
|
|
532
|
-
reportWarning: (message)=>this.logger.warn(message),
|
|
533
|
-
onAvailable: ()=>this._startInitialPageview()
|
|
534
|
-
});
|
|
535
|
-
} catch (error) {
|
|
536
|
-
if (this._analytics === extension) this._analytics = void 0;
|
|
537
|
-
throw error;
|
|
538
|
-
}
|
|
539
|
-
}
|
|
540
|
-
_canUseAnalytics(owner) {
|
|
541
|
-
return this._analytics === owner && !this._closing && !this._disposed;
|
|
542
|
-
}
|
|
543
|
-
_analyticsCaptureHost(owner) {
|
|
544
|
-
const canMutate = ()=>this._canUseAnalytics(owner);
|
|
545
|
-
return {
|
|
546
|
-
projectToken: this.projectToken,
|
|
547
|
-
logger: this.logger,
|
|
548
|
-
sessionKv: this._state.tabKeyValueStore('analytics', ()=>canMutate() && this._state.prepare()),
|
|
549
|
-
state: this._state,
|
|
550
|
-
canCapture: ()=>canMutate() && !this._blocked && !this.hasOptedOut(),
|
|
551
|
-
canMutate,
|
|
552
|
-
isDisposed: ()=>this._disposed,
|
|
553
|
-
authority: ()=>this._immediateAuthority,
|
|
554
|
-
onEvent: this._eventPublisher.listener,
|
|
555
|
-
publishEvent: (event)=>this._eventPublisher.publish(event),
|
|
556
|
-
publishNewSession: (session)=>this._newSessionPublisher.publish(session),
|
|
557
|
-
publishIdentify: (info)=>this._identifyPublisher.publish(info),
|
|
558
|
-
publishChangeProperties: (info)=>this._changePropertiesPublisher.publish(info),
|
|
559
|
-
publishGroup: (info)=>this._groupPublisher.publish(info),
|
|
560
|
-
publishGroupsReset: ()=>this._groupsResetPublisher.publish(void 0),
|
|
561
|
-
publishReset: ()=>this._resetPublisher.publish(void 0)
|
|
562
|
-
};
|
|
574
|
+
_canMutate() {
|
|
575
|
+
return !this._closing && !this._disposed;
|
|
563
576
|
}
|
|
564
577
|
_canDeliver() {
|
|
565
|
-
return !this._disposed && !this._blocked && !this.hasOptedOut();
|
|
578
|
+
return !this._disposed && !this._blocked && (!this.hasOptedOut() || this._clearedChoiceRetainsWork && void 0 === this._state.consentChoice);
|
|
579
|
+
}
|
|
580
|
+
_revokeAdmittedWork() {
|
|
581
|
+
this._clearedChoiceRetainsWork = false;
|
|
582
|
+
this._immediateAuthority = {};
|
|
583
|
+
this._analytics?.purge();
|
|
566
584
|
}
|
|
567
585
|
}
|
|
568
586
|
const selectConfiguredExtensions = (configured)=>{
|
|
@@ -570,7 +588,7 @@ const selectConfiguredExtensions = (configured)=>{
|
|
|
570
588
|
for (const extension of configured)if (!selected.has(extension.name)) selected.set(extension.name, extension);
|
|
571
589
|
return selected;
|
|
572
590
|
};
|
|
573
|
-
const createPostHogCore = async (options, configured = options?.extensions ?? [], automaticLoaders = {}, automatic = [])=>{
|
|
591
|
+
const createPostHogCore = async (options, createDelivery, configured = options?.extensions ?? [], automaticLoaders = {}, automatic = [])=>{
|
|
574
592
|
const selected = selectConfiguredExtensions(configured);
|
|
575
593
|
const loaders = Object.fromEntries([
|
|
576
594
|
...Object.entries(automaticLoaders),
|
|
@@ -581,12 +599,11 @@ const createPostHogCore = async (options, configured = options?.extensions ?? []
|
|
|
581
599
|
]);
|
|
582
600
|
const client = PostHog.create(options ?? {
|
|
583
601
|
projectToken: ''
|
|
584
|
-
}, loaders);
|
|
602
|
+
}, createDelivery, loaders);
|
|
585
603
|
client.getRemoteConfig();
|
|
586
|
-
|
|
587
|
-
for (const name of selected.keys())if ('analytics' !== name) await client.resolveExtension(name);
|
|
604
|
+
for (const name of selected.keys())await client.resolveExtension(name);
|
|
588
605
|
for (const extension of automatic)await client._registry.activate(extension);
|
|
589
|
-
|
|
606
|
+
client._completeInitialization();
|
|
590
607
|
return client;
|
|
591
608
|
};
|
|
592
609
|
export { createPostHogCore };
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { KeyValueStore, SessionContext } from '@posthog/browser-common';
|
|
2
|
-
import type { NewSessionReason, StorageLike } from '../types';
|
|
2
|
+
import type { CookiePersistence, NewSessionReason, StorageLike } from '../types';
|
|
3
|
+
export declare const CLIENT_KV_NAMESPACE = "core";
|
|
3
4
|
export type ConsentState = 'implicit' | 'granted' | 'denied';
|
|
5
|
+
type ConsentChoice = Exclude<ConsentState, 'implicit'>;
|
|
4
6
|
interface PersistedSession {
|
|
5
7
|
sessionId: string;
|
|
6
8
|
sessionStartTimestamp: number;
|
|
@@ -19,11 +21,19 @@ interface PreparedSession {
|
|
|
19
21
|
readonly previousWindowStorageInitialized: boolean;
|
|
20
22
|
readonly previousPendingReason: 'reset' | undefined;
|
|
21
23
|
}
|
|
24
|
+
export declare const isRecord: (value: unknown) => value is Record<string, unknown>;
|
|
25
|
+
export declare const isTimestamp: (value: unknown) => value is number;
|
|
26
|
+
export declare const incrementRevision: (revision: string) => string;
|
|
27
|
+
/** A caller-supplied session ID and the start time encoded in it. */
|
|
28
|
+
type BootstrapSession = [sessionId: string, sessionStartTimestamp: number];
|
|
29
|
+
/** Reads a UUIDv7 session ID's start time, rejecting IDs more than a minute in the future. */
|
|
30
|
+
export declare const readBootstrapSession: (sessionId: unknown, now?: number) => BootstrapSession | undefined;
|
|
22
31
|
export declare const getDefaultStorage: () => StorageLike | undefined;
|
|
23
32
|
export declare const getDefaultSessionStorage: () => StorageLike | undefined;
|
|
24
33
|
export declare class BrowserState {
|
|
25
34
|
private _state;
|
|
26
35
|
private _consent;
|
|
36
|
+
private _consentChoice;
|
|
27
37
|
private readonly _stateKey;
|
|
28
38
|
readonly consentKey: string;
|
|
29
39
|
private readonly _windowKey;
|
|
@@ -34,7 +44,12 @@ export declare class BrowserState {
|
|
|
34
44
|
private _windowListenerInstalled;
|
|
35
45
|
private _lastActivityWriteTimestamp;
|
|
36
46
|
private _pendingSessionReason;
|
|
47
|
+
private _bootstrapSession;
|
|
37
48
|
private _stateReadPending;
|
|
49
|
+
private _generated;
|
|
50
|
+
private readonly _sharesIdentity;
|
|
51
|
+
/** The stored identity this context last read, which a sibling subdomain's change replaces. */
|
|
52
|
+
private _storedIdentity;
|
|
38
53
|
private _lastConsentValue;
|
|
39
54
|
private _ignoredConsentValue;
|
|
40
55
|
private _hasIgnoredConsentValue;
|
|
@@ -43,8 +58,15 @@ export declare class BrowserState {
|
|
|
43
58
|
private readonly _defaultConsent;
|
|
44
59
|
private readonly _onConsentChange;
|
|
45
60
|
private readonly _beforeUnload;
|
|
46
|
-
constructor(projectToken: string, storage: StorageLike | undefined, persistenceKey: string | undefined, consentPersistenceName: string | undefined, optOutByDefault: boolean, windowStorageFactory: (() => StorageLike | undefined) | undefined, onConsentChange: (consent: ConsentState, previousConsent: ConsentState) => void);
|
|
61
|
+
constructor(projectToken: string, storage: StorageLike | undefined, persistenceKey: string | undefined, consentPersistenceName: string | undefined, optOutByDefault: boolean, windowStorageFactory: (() => StorageLike | undefined) | undefined, onConsentChange: (consent: ConsentState, previousConsent: ConsentState, explicit: boolean) => void, cookie?: CookiePersistence);
|
|
47
62
|
prepare(): boolean;
|
|
63
|
+
/**
|
|
64
|
+
* Adopts an identity that another subdomain stored since this context last read it, as posthog-js does before
|
|
65
|
+
* each identity operation and event. Session authority still follows revisions. Returns whether it changed.
|
|
66
|
+
*/
|
|
67
|
+
adoptStoredIdentity(): boolean;
|
|
68
|
+
/** Whether this identity was generated rather than read from storage, including a later successful read. */
|
|
69
|
+
get generated(): boolean;
|
|
48
70
|
get deviceId(): string;
|
|
49
71
|
get anonymousId(): string;
|
|
50
72
|
get distinctId(): string;
|
|
@@ -54,17 +76,25 @@ export declare class BrowserState {
|
|
|
54
76
|
get activeSessionId(): string | undefined;
|
|
55
77
|
get session(): SessionContext | undefined;
|
|
56
78
|
get consent(): ConsentState;
|
|
79
|
+
/** The persisted opt-in or opt-out choice, independently of `optOutByDefault`. */
|
|
80
|
+
get consentChoice(): ConsentChoice | undefined;
|
|
57
81
|
refreshConsent(): ConsentState;
|
|
58
82
|
observeConsent(value: unknown): ConsentState;
|
|
59
83
|
identify(distinctId: string): void;
|
|
84
|
+
/** Seeds a generated identity. An anonymous ID also becomes the device ID, as in posthog-js. */
|
|
85
|
+
bootstrapIdentity(distinctId: string, identified: boolean): void;
|
|
86
|
+
/** Uses the session for the next admitted event unless it has exceeded the maximum session length by then. */
|
|
87
|
+
bootstrapSession(session: BootstrapSession): void;
|
|
60
88
|
group(type: string, key: string): boolean;
|
|
61
89
|
resetGroups(): void;
|
|
62
90
|
prepareSessionForEvent(now?: number): PreparedSession;
|
|
63
91
|
sessionAdmitted(prepared: PreparedSession): boolean;
|
|
64
|
-
reset(): void;
|
|
92
|
+
reset(resetDeviceId?: boolean, bootstrap?: readonly [distinctId: string, identified: boolean], bootstrapSession?: BootstrapSession): void;
|
|
65
93
|
dispose(): void;
|
|
66
94
|
optIn(): boolean;
|
|
67
95
|
optOut(): boolean;
|
|
96
|
+
/** Forgets the persisted choice, returning consent to the configured default. */
|
|
97
|
+
clearConsent(): boolean;
|
|
68
98
|
keyValueStore(namespace: string, canAccess?: () => boolean): KeyValueStore;
|
|
69
99
|
tabKeyValueStore(namespace: string, canAccess: () => boolean): KeyValueStore;
|
|
70
100
|
private _tabStorage;
|