@posthog/browser 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/ARCHITECTURE.md +17 -17
  2. package/README.md +42 -7
  3. package/dist/composition/npm/core.d.ts +1 -1
  4. package/dist/composition/npm/index.d.ts +2 -2
  5. package/dist/core/posthog.js +88 -14
  6. package/dist/core/posthog.mjs +88 -14
  7. package/dist/core/state/state.d.ts +32 -3
  8. package/dist/core/state/state.js +117 -25
  9. package/dist/core/state/state.mjs +105 -25
  10. package/dist/core/types.d.ts +87 -5
  11. package/dist/persistence/cookie.d.ts +19 -0
  12. package/dist/persistence/cookie.js +273 -0
  13. package/dist/persistence/cookie.mjs +235 -0
  14. package/dist/platform/logger.d.ts +5 -1
  15. package/dist/platform/logger.js +3 -3
  16. package/dist/platform/logger.mjs +3 -3
  17. package/dist/primitives/id.d.ts +5 -0
  18. package/dist/primitives/id.js +10 -2
  19. package/dist/primitives/id.mjs +6 -1
  20. package/dist/primitives/version.js +1 -1
  21. package/dist/primitives/version.mjs +1 -1
  22. package/dist/products/analytics/analytics-core.d.ts +17 -4
  23. package/dist/products/analytics/analytics-core.js +101 -10
  24. package/dist/products/analytics/analytics-core.mjs +101 -10
  25. package/dist/products/analytics/analytics-internal.d.ts +3 -2
  26. package/dist/products/analytics/delivery/analytics-delivery.js +1 -1
  27. package/dist/products/analytics/delivery/analytics-delivery.mjs +1 -1
  28. package/dist/products/analytics/delivery/lane.d.ts +8 -1
  29. package/dist/products/analytics/delivery/lane.js +16 -4
  30. package/dist/products/analytics/delivery/lane.mjs +16 -4
  31. package/dist/products/analytics/groups.js +1 -1
  32. package/dist/products/analytics/groups.mjs +1 -1
  33. package/dist/products/analytics/person.js +1 -1
  34. package/dist/products/analytics/person.mjs +1 -1
  35. package/dist/products/analytics/properties/analytics-properties.d.ts +1 -0
  36. package/dist/products/analytics/properties/analytics-properties.js +3 -0
  37. package/dist/products/analytics/properties/analytics-properties.mjs +1 -1
  38. package/dist/products/flags/flags-internal.d.ts +3 -0
  39. package/dist/products/flags/flags-options.d.ts +16 -2
  40. package/dist/products/flags/flags-token.d.ts +28 -2
  41. package/dist/products/flags/flags.d.ts +1 -1
  42. package/dist/products/flags/flags.js +110 -4
  43. package/dist/products/flags/flags.mjs +110 -4
  44. package/dist/products/surveys/surveys-extension.js +75 -26
  45. package/dist/products/surveys/surveys-extension.mjs +77 -28
  46. package/dist/products/surveys/surveys-internal.d.ts +6 -0
  47. package/package.json +9 -4
@@ -1,7 +1,8 @@
1
- import { createId } from "../../primitives/id.mjs";
1
+ import { createId, createTimeId } from "../../primitives/id.mjs";
2
2
  import { TabValues, createKeyValueStore } from "./key-value-store.mjs";
3
3
  const CLIENT_KV_NAMESPACE = 'core';
4
4
  const STORED_GROUP_PROPERTIES_KEY = '$stored_group_properties';
5
+ const SESSION_MAX_LENGTH_MS = 86400000;
5
6
  const emptyRecord = ()=>Object.create(null);
6
7
  const isRecord = (value)=>'object' == typeof value && null !== value && !Array.isArray(value);
7
8
  const readGroups = (value)=>{
@@ -16,7 +17,7 @@ const sessionExpiryReason = (session, now)=>{
16
17
  if (!session) return;
17
18
  const safeNow = isTimestamp(now) ? now : 0;
18
19
  if (Math.abs(safeNow - session.lastActivityTimestamp) > 1800000) return 'idleTimeout';
19
- if (Math.abs(safeNow - session.sessionStartTimestamp) > 86400000) return 'maxLength';
20
+ if (Math.abs(safeNow - session.sessionStartTimestamp) > SESSION_MAX_LENGTH_MS) return 'maxLength';
20
21
  };
21
22
  const readRevision = (value, fallback)=>{
22
23
  if ('string' == typeof value && /^(0|[1-9]\d*)$/.test(value)) return value;
@@ -65,12 +66,23 @@ const readExtensionData = (value)=>{
65
66
  });
66
67
  return extensionData;
67
68
  };
68
- const createSession = (now, revision)=>({
69
- sessionId: createId(),
70
- sessionStartTimestamp: now,
69
+ const createSession = (now, revision, [sessionId, sessionStartTimestamp] = [
70
+ createTimeId(now),
71
+ now
72
+ ])=>({
73
+ sessionId,
74
+ sessionStartTimestamp,
71
75
  lastActivityTimestamp: now,
72
76
  revision
73
77
  });
78
+ const readBootstrapSession = (sessionId, now = Date.now())=>{
79
+ const hex = 'string' == typeof sessionId ? sessionId.replace(/-/g, '') : '';
80
+ const start = /^[0-9a-f]{12}7[0-9a-f]{19}$/i.test(hex) ? parseInt(hex.slice(0, 12), 16) : 0 / 0;
81
+ return start <= now + 60000 ? [
82
+ sessionId,
83
+ start
84
+ ] : void 0;
85
+ };
74
86
  const authorityRevision = (state)=>state?.session?.revision ?? state?.sessionReset;
75
87
  const persistedAuthorityWins = (persisted, local)=>{
76
88
  const persistedRevision = authorityRevision(persisted);
@@ -104,6 +116,16 @@ const createInitialState = (deviceId = createId(), anonymousId = deviceId)=>({
104
116
  groups: emptyRecord(),
105
117
  extensionData: emptyRecord()
106
118
  });
119
+ const identityOf = (state)=>JSON.stringify([
120
+ state.distinctId,
121
+ state.isIdentified,
122
+ state.deviceId
123
+ ]);
124
+ const seedIdentity = (state, distinctId, identified)=>{
125
+ state.distinctId = distinctId;
126
+ if (identified) state.isIdentified = true;
127
+ else state.anonymousId = distinctId;
128
+ };
107
129
  const decodeConsent = (value)=>{
108
130
  const normalized = 'string' == typeof value ? value.trim().toLowerCase() : value;
109
131
  return true === normalized || 1 === normalized || '1' === normalized || 'true' === normalized || 'yes' === normalized ? 'granted' : false === normalized || 0 === normalized || '0' === normalized || 'false' === normalized || 'no' === normalized ? 'denied' : void 0;
@@ -155,7 +177,7 @@ const getDefaultSessionStorage = ()=>{
155
177
  }
156
178
  };
157
179
  class BrowserState {
158
- constructor(projectToken, storage, persistenceKey, consentPersistenceName, optOutByDefault, windowStorageFactory, onConsentChange){
180
+ constructor(projectToken, storage, persistenceKey, consentPersistenceName, optOutByDefault, windowStorageFactory, onConsentChange, cookie){
159
181
  this._windowId = '';
160
182
  this._windowStorageInitialized = false;
161
183
  this._windowListenerInstalled = false;
@@ -167,9 +189,14 @@ class BrowserState {
167
189
  this._flushSession();
168
190
  this._windowRemove(this._primaryWindowKey);
169
191
  };
170
- this._storage = storage;
171
- this._windowStorageFactory = windowStorageFactory;
172
192
  this._stateKey = persistenceKey ?? `ph_${projectToken}_posthog_browser_v2`;
193
+ try {
194
+ this._storage = storage && cookie ? cookie.wrap(storage, this._stateKey, projectToken) : storage;
195
+ } catch {
196
+ this._storage = storage;
197
+ }
198
+ this._sharesIdentity = this._storage !== storage;
199
+ this._windowStorageFactory = windowStorageFactory;
173
200
  const windowPrefix = persistenceKey ?? `ph_${projectToken}`;
174
201
  this._windowKey = `${windowPrefix}_window_id`;
175
202
  this._primaryWindowKey = `${windowPrefix}_primary_window_exists`;
@@ -180,13 +207,19 @@ class BrowserState {
180
207
  const [consentRead, storedConsent] = this._read(this.consentKey);
181
208
  if (consentRead) {
182
209
  this._lastConsentValue = storedConsent;
183
- this._consent = decodeConsent(storedConsent) ?? this._defaultConsent;
210
+ this._consentChoice = decodeConsent(storedConsent);
211
+ this._consent = this._consentChoice ?? this._defaultConsent;
184
212
  }
185
213
  const [stateRead, storedState] = this._read(this._stateKey);
186
- this._state = parseState('string' == typeof storedState ? storedState : null) ?? createInitialState();
214
+ const persisted = parseState('string' == typeof storedState ? storedState : null);
215
+ this._generated = !persisted;
216
+ this._state = persisted ?? createInitialState();
187
217
  this._lastActivityWriteTimestamp = this._state.session?.lastActivityTimestamp ?? 0;
188
218
  this._stateReadPending = !stateRead;
189
- if (stateRead) this._save();
219
+ if (stateRead) {
220
+ this._save();
221
+ this._storedIdentity = identityOf(this._state);
222
+ }
190
223
  }
191
224
  prepare() {
192
225
  if (!this._stateReadPending) return true;
@@ -196,10 +229,30 @@ class BrowserState {
196
229
  const persisted = parseState('string' == typeof storedState ? storedState : null);
197
230
  if (persisted) {
198
231
  this._state = persisted;
232
+ this._generated = false;
199
233
  this._lastActivityWriteTimestamp = persisted.session?.lastActivityTimestamp ?? 0;
200
234
  } else this._save(false);
235
+ this._storedIdentity = identityOf(this._state);
236
+ return true;
237
+ }
238
+ adoptStoredIdentity() {
239
+ const known = this._storedIdentity;
240
+ const [, stored] = this._sharesIdentity && known ? this._readPersistedState() : [];
241
+ if (!stored) return false;
242
+ this._storedIdentity = identityOf(stored);
243
+ if (this._storedIdentity === identityOf(this._state)) {
244
+ if (stored.extensionData[CLIENT_KV_NAMESPACE]?.personProcessingEnabled === true) (this._state.extensionData[CLIENT_KV_NAMESPACE] ??= emptyRecord()).personProcessingEnabled = true;
245
+ return false;
246
+ }
247
+ if (this._storedIdentity === known) return false;
248
+ copyAuthority(stored, this._state);
249
+ this._state = stored;
250
+ this._save();
201
251
  return true;
202
252
  }
253
+ get generated() {
254
+ return this._generated;
255
+ }
203
256
  get deviceId() {
204
257
  return this._state.deviceId;
205
258
  }
@@ -238,6 +291,10 @@ class BrowserState {
238
291
  get consent() {
239
292
  return this.refreshConsent();
240
293
  }
294
+ get consentChoice() {
295
+ this.refreshConsent();
296
+ return this._consentChoice;
297
+ }
241
298
  refreshConsent() {
242
299
  const [read, value] = this._read(this.consentKey);
243
300
  return read ? this.observeConsent(value) : this._consent;
@@ -246,7 +303,8 @@ class BrowserState {
246
303
  if (this._hasIgnoredConsentValue && value === this._ignoredConsentValue) return this._consent;
247
304
  this._hasIgnoredConsentValue = false;
248
305
  this._lastConsentValue = value;
249
- this._applyConsent(decodeConsent(value) ?? this._defaultConsent);
306
+ this._consentChoice = decodeConsent(value);
307
+ this._applyConsent(this._consentChoice ?? this._defaultConsent);
250
308
  return this._consent;
251
309
  }
252
310
  identify(distinctId) {
@@ -254,6 +312,14 @@ class BrowserState {
254
312
  this._state.isIdentified = true;
255
313
  this._save();
256
314
  }
315
+ bootstrapIdentity(distinctId, identified) {
316
+ seedIdentity(this._state, distinctId, identified);
317
+ if (!identified) this._state.deviceId = distinctId;
318
+ this._save();
319
+ }
320
+ bootstrapSession(session) {
321
+ this._bootstrapSession = session;
322
+ }
257
323
  group(type, key) {
258
324
  if (this._state.groups[type] === key) return false;
259
325
  this._state.groups[type] = key;
@@ -271,13 +337,14 @@ class BrowserState {
271
337
  const { external, session, lastActivityWriteTimestamp, adoptedAfterReset } = this._readSessionAuthority();
272
338
  const pendingReason = this._pendingSessionReason;
273
339
  const expiry = sessionExpiryReason(session, safeNow);
274
- const rotated = !!(pendingReason || !session || expiry);
340
+ const bootstrap = this._bootstrapSession && safeNow - this._bootstrapSession[1] <= SESSION_MAX_LENGTH_MS ? this._bootstrapSession : void 0;
341
+ const rotated = !!(pendingReason || !session || expiry || bootstrap && bootstrap[0] !== session.sessionId);
275
342
  const reason = adoptedAfterReset ? 'reset' : pendingReason ?? expiry;
276
- const preparedSession = rotated ? createSession(safeNow, nextRevision(safeNow, this._state, external)) : {
343
+ const preparedSession = rotated ? createSession(safeNow, nextRevision(safeNow, this._state, external), bootstrap) : {
277
344
  ...session,
278
345
  lastActivityTimestamp: Math.max(safeNow, session.lastActivityTimestamp)
279
346
  };
280
- const window = this._prepareWindow(rotated);
347
+ const window = this._prepareWindow(rotated, safeNow);
281
348
  return {
282
349
  context: {
283
350
  sessionId: preparedSession.sessionId,
@@ -326,17 +393,20 @@ class BrowserState {
326
393
  else this._clearWindow(true);
327
394
  return false;
328
395
  }
396
+ this._bootstrapSession = void 0;
329
397
  return true;
330
398
  }
331
- reset() {
399
+ reset(resetDeviceId = false, bootstrap, bootstrapSession) {
332
400
  const [, external] = this._readPersistedState();
333
401
  const now = Date.now();
334
402
  const safeNow = isTimestamp(now) ? now : 0;
335
403
  const resetRevision = nextRevision(safeNow, this._state, external);
336
- this._state = createInitialState(this._state.deviceId, createId());
404
+ this._state = createInitialState(resetDeviceId ? createId() : this._state.deviceId, createId());
405
+ if (bootstrap) seedIdentity(this._state, ...bootstrap);
337
406
  this._state.sessionReset = resetRevision;
338
407
  this._lastActivityWriteTimestamp = 0;
339
408
  this._pendingSessionReason = 'reset';
409
+ this._bootstrapSession = bootstrapSession;
340
410
  this._clearWindow(true);
341
411
  this._save(false);
342
412
  }
@@ -346,14 +416,23 @@ class BrowserState {
346
416
  this._windowRemove(this._primaryWindowKey);
347
417
  }
348
418
  optIn() {
349
- this._applyConsent('granted');
419
+ this._consentChoice = 'granted';
350
420
  const written = this._writeConsent('1');
421
+ this._applyConsent('granted');
351
422
  this._save();
352
423
  return written;
353
424
  }
354
425
  optOut() {
426
+ this._consentChoice = 'denied';
427
+ const written = this._writeConsent('0');
355
428
  this._applyConsent('denied');
356
- return this._writeConsent('0');
429
+ return written;
430
+ }
431
+ clearConsent() {
432
+ this._consentChoice = void 0;
433
+ const written = this._writeConsent(null);
434
+ this._applyConsent(this._defaultConsent);
435
+ return written;
357
436
  }
358
437
  keyValueStore(namespace, canAccess = ()=>true) {
359
438
  return createKeyValueStore({
@@ -406,9 +485,9 @@ class BrowserState {
406
485
  adoptedAfterReset: adopted && void 0 !== session && 'reset' === this._pendingSessionReason
407
486
  };
408
487
  }
409
- _prepareWindow(rotated) {
488
+ _prepareWindow(rotated, now) {
410
489
  if (rotated || this._windowId) return {
411
- windowId: rotated ? createId() : this._windowId,
490
+ windowId: rotated ? createTimeId(now) : this._windowId,
412
491
  storage: void 0,
413
492
  storageResolved: false
414
493
  };
@@ -428,7 +507,7 @@ class BrowserState {
428
507
  } catch {}
429
508
  const reusable = lastWindowId && (!primaryWindowExists || this._isReload()) ? lastWindowId : void 0;
430
509
  return {
431
- windowId: reusable ?? createId(),
510
+ windowId: reusable ?? createTimeId(now),
432
511
  storage,
433
512
  storageResolved: true
434
513
  };
@@ -522,7 +601,7 @@ class BrowserState {
522
601
  const previousConsent = this._consent;
523
602
  this._consent = consent;
524
603
  try {
525
- this._onConsentChange(consent, previousConsent);
604
+ this._onConsentChange(consent, previousConsent, void 0 !== this._consentChoice);
526
605
  } catch {}
527
606
  }
528
607
  _save(preserveSession = true) {
@@ -548,7 +627,8 @@ class BrowserState {
548
627
  return false;
549
628
  }
550
629
  try {
551
- this._storage.setItem(this.consentKey, value);
630
+ if (null === value) this._storage.removeItem(this.consentKey);
631
+ else this._storage.setItem(this.consentKey, value);
552
632
  this._lastConsentValue = value;
553
633
  this._hasIgnoredConsentValue = false;
554
634
  return true;
@@ -576,4 +656,4 @@ class BrowserState {
576
656
  }
577
657
  }
578
658
  }
579
- export { BrowserState, CLIENT_KV_NAMESPACE, getDefaultSessionStorage, getDefaultStorage };
659
+ export { BrowserState, CLIENT_KV_NAMESPACE, getDefaultSessionStorage, getDefaultStorage, incrementRevision, isRecord, isTimestamp, readBootstrapSession };
@@ -1,4 +1,4 @@
1
- import type { FlagsConfiguration } from '../products/flags/flags-options';
1
+ import type { FlagsConfiguration, FlagsOptions } from '../products/flags/flags-options';
2
2
  import type { BrowserExtension as Extension, BrowserProducts, ChangePropertiesInfo, ConsentChangeInfo, GroupInfo, IdentifyInfo } from './context/browser-client';
3
3
  import type { LogsConfiguration } from '../products/logs/logs-options';
4
4
  import type { SurveysConfiguration } from '../products/surveys/surveys-options';
@@ -23,6 +23,38 @@ export type NewSessionReason = 'idleTimeout' | 'maxLength' | 'reset';
23
23
  export interface NewSessionInfo extends SessionContext {
24
24
  readonly reason: NewSessionReason;
25
25
  }
26
+ /** Whether the user explicitly opted in, explicitly opted out, or has not chosen. */
27
+ export type ExplicitConsentStatus = 'granted' | 'denied' | 'pending';
28
+ /** Identity and session values to use instead of generated ones. */
29
+ export interface BootstrapOptions {
30
+ /** Distinct ID to use when no identity is stored. An identified ID also identifies a stored anonymous user. */
31
+ distinctId?: string;
32
+ /** Whether `distinctId` identifies a known person rather than an anonymous user. */
33
+ isIdentifiedId?: boolean;
34
+ /**
35
+ * UUIDv7 session ID to continue, such as one passed from another domain. Like a generated session, it starts with
36
+ * the first admitted event, so `session` and `onSessionId` report it from then on.
37
+ */
38
+ sessionId?: string;
39
+ }
40
+ export interface ResetOptions {
41
+ /** Also replace the device ID. */
42
+ resetDeviceId?: boolean;
43
+ /**
44
+ * Seed the new identity and next session instead of generating them. With feature flags, `featureFlags` and
45
+ * `featureFlagPayloads` are served for the new identity until flags load.
46
+ */
47
+ bootstrap?: BootstrapOptions & FlagsOptions['bootstrap'];
48
+ }
49
+ /**
50
+ * Shares identity and session state through a cookie. Create one with `cookiePersistence()` from
51
+ * `@posthog/browser/persistence/cookie`; only instances it returns are supported. `wrap` and the state record it
52
+ * reads and writes are internal, so their shape can change in any release.
53
+ */
54
+ export interface CookiePersistence {
55
+ /** Wraps the state storage so the identity record also reads from and writes to the cookie. */
56
+ wrap(storage: StorageLike, stateKey: string, projectToken: string): StorageLike;
57
+ }
26
58
  export interface PostHogOptions {
27
59
  /** PostHog project token. */
28
60
  projectToken: string;
@@ -34,13 +66,20 @@ export interface PostHogOptions {
34
66
  storage?: StorageLike | false;
35
67
  /** Override the storage key. */
36
68
  persistenceKey?: string;
69
+ /** Also persist identity and session state in a cookie, sharing them across subdomains. */
70
+ cookie?: CookiePersistence;
71
+ /**
72
+ * Identity and session values to use instead of generated ones. A stored identity takes precedence, except that an
73
+ * identified bootstrap ID identifies a stored anonymous user, as in posthog-js.
74
+ */
75
+ bootstrap?: BootstrapOptions;
37
76
  /** Override the consent key verbatim. Defaults to `__ph_opt_in_out_<projectToken>`. */
38
77
  consentPersistenceName?: string;
39
78
  /** Fetch implementation. Pass `false` to disable network requests. */
40
79
  fetch?: BrowserFetch | false;
41
80
  /** Navigator implementation. Pass `false` to disable navigator capabilities. */
42
81
  navigator?: BrowserNavigator | false;
43
- /** Start with capture disabled until `optIn()` runs. */
82
+ /** Start with capture disabled until `optIn()` runs. Feature flags still load, as in posthog-js. */
44
83
  optOutByDefault?: boolean;
45
84
  /** Capture one initial `$pageview` after configured extensions install. Defaults to `true`. */
46
85
  capturePageview?: boolean;
@@ -69,6 +108,16 @@ export interface PostHogOptions {
69
108
  /** Install extensions before the factory resolves. Explicit instances take precedence over automatic product options. */
70
109
  extensions?: readonly Extension[];
71
110
  }
111
+ /** Options that `setConfig()` can change after creation. Omitted options keep their current values. */
112
+ export interface RuntimeOptions {
113
+ /** Enable or disable SDK diagnostic logs, including loggers that extensions already created. */
114
+ debug?: boolean;
115
+ /**
116
+ * Analytics policy applied to subsequent captures. As in `posthog-js`, downgrading `personProfiles` from `'always'`
117
+ * to `'identified_only'` keeps person processing for a visitor whose events were already processed; `'never'` stops it.
118
+ */
119
+ analytics?: Pick<AnalyticsOptions, 'personProfiles'>;
120
+ }
72
121
  /** Options for the manually composed `@posthog/browser/core` entrypoint. */
73
122
  export type CorePostHogOptions = Omit<PostHogOptions, 'flags' | 'logs' | 'surveys' | 'autocapture'>;
74
123
  /** Capture V1's terminal verdict for one reported event. */
@@ -96,11 +145,22 @@ export interface IPostHog extends Client, Readonly<Partial<BrowserProducts>>, Di
96
145
  readonly isRateLimited: boolean;
97
146
  captureImmediate(event: string, properties?: Record<string, unknown> | null, options?: CaptureOptions): Promise<CaptureSummary>;
98
147
  identify(distinctId: string, set?: Record<string, unknown>, setOnce?: Record<string, unknown>): void;
99
- reset(): void;
148
+ /**
149
+ * Starts a new anonymous identity and session, and forgets the stored consent choice. Pass `true`, as in
150
+ * posthog-js, or `{ resetDeviceId: true }` to also replace the device ID.
151
+ *
152
+ * With `optOutByDefault`, capture returns to the default (opted out), so calling `reset()` after `optIn()` stops
153
+ * capture. Reset first, then opt in again if needed: `posthog.reset(); posthog.optIn()`. Events captured before
154
+ * the reset, in this or another tab, are still delivered. Consent listeners hear of the forgotten choice after the
155
+ * new identity is in place and `onReset` listeners have run.
156
+ */
157
+ reset(options?: boolean | ResetOptions): void;
100
158
  register(properties: Record<string, unknown>): void;
101
159
  registerOnce(properties: Record<string, unknown>, defaultValue?: unknown): void;
102
160
  unregister(property: string): void;
103
161
  getProperty(property: string): unknown;
162
+ /** The UUID of the last `$pageview` captured in the current session, sent on events as `$pageview_id`. */
163
+ getPageViewId(): string | undefined;
104
164
  registerForSession(properties: Record<string, unknown>): void;
105
165
  unregisterForSession(property: string): void;
106
166
  /** Links another distinct ID to the current person without changing the current identity. */
@@ -120,9 +180,17 @@ export interface IPostHog extends Client, Readonly<Partial<BrowserProducts>>, Di
120
180
  /** Marks the current person as an internal or test user. */
121
181
  setInternalOrTestUser(): void;
122
182
  readonly onNewSession: Listener<NewSessionInfo>;
183
+ /**
184
+ * Fires with the current session immediately when one exists, then whenever this tab's session or window ID
185
+ * changes, including when it adopts a sibling tab's session. Sessions start with admitted events, not subscriptions.
186
+ */
187
+ readonly onSessionId: Listener<SessionContext>;
123
188
  /** Fires when consent changes, including changes observed from another tab. Does not replay. */
124
189
  readonly onConsentChange: Listener<ConsentChangeInfo>;
125
- /** Fires after identification, independently of capture consent. Does not replay. */
190
+ /**
191
+ * Fires after identification, independently of capture consent, including an identification this client adopts
192
+ * from another subdomain through cookie persistence. Does not replay.
193
+ */
126
194
  readonly onIdentify: Listener<IdentifyInfo>;
127
195
  /** Local person-property changes, independently of capture consent. Does not replay. */
128
196
  readonly onChangeProperties: Listener<ChangePropertiesInfo>;
@@ -130,7 +198,10 @@ export interface IPostHog extends Client, Readonly<Partial<BrowserProducts>>, Di
130
198
  readonly onGroup: Listener<GroupInfo>;
131
199
  /** Fires after group-only reset clears local membership. Does not replay. */
132
200
  readonly onGroupsReset: Listener<void>;
133
- /** Fires after local identity and persisted extension state are reset. Does not replay. */
201
+ /**
202
+ * Fires after local identity and persisted extension state are reset, including a reset this client adopts from
203
+ * another subdomain through cookie persistence. Does not replay.
204
+ */
134
205
  readonly onReset: Listener<void>;
135
206
  resolveExtension<T extends Extension>(token: ExtensionToken<T>): Promise<T | undefined>;
136
207
  resolveExtension<Name extends keyof BrowserProducts>(name: Name): Promise<BrowserProducts[Name] | undefined>;
@@ -141,6 +212,17 @@ export interface IPostHog extends Client, Readonly<Partial<BrowserProducts>>, Di
141
212
  optIn(): void;
142
213
  optOut(): void;
143
214
  hasOptedOut(): boolean;
215
+ /** The stored opt-in or opt-out choice, independently of `optOutByDefault`. */
216
+ getExplicitConsentStatus(): ExplicitConsentStatus;
217
+ /**
218
+ * Forgets the stored opt-in or opt-out choice, returning consent to the configured default. Events captured before
219
+ * the call are still delivered.
220
+ */
221
+ clearOptInOut(): void;
144
222
  getRemoteConfig(): Promise<RemoteConfig | undefined>;
223
+ /** Change the options in `RuntimeOptions`. Other creation options are fixed for the client's lifetime. */
224
+ setConfig(options: RuntimeOptions): void;
225
+ /** Enable SDK diagnostic logs, or disable them with `debug(false)`. Equivalent to `setConfig({ debug })`. */
226
+ debug(enabled?: boolean): void;
145
227
  }
146
228
  export type { AnalyticsOptions, PersonProfileMode, ApiResponse, CaptureOptions, Disposable, Extension, RemoteConfig, SendRequestInit, SessionContext, };
@@ -0,0 +1,19 @@
1
+ import type { CookiePersistence } from '../core/types';
2
+ export type { CookiePersistence };
3
+ export interface CookiePersistenceOptions {
4
+ /** Share the cookie with every subdomain of the site. Defaults to `true`, except on herokuapp.com, vercel.app and netlify.app. */
5
+ crossSubdomain?: boolean;
6
+ /** Send the cookie only over HTTPS. Defaults to `true` on HTTPS pages. */
7
+ secure?: boolean;
8
+ /** Days until the cookie expires. Each write renews it. Defaults to 365. */
9
+ expirationDays?: number;
10
+ /** Cookie name. Defaults to `ph_<project token>_posthog`, the name `posthog-js` uses. */
11
+ name?: string;
12
+ }
13
+ /**
14
+ * Persists identity and session state in a cookie as well as local storage, so subdomains of a site share one
15
+ * identity. An open page adopts an identify or reset from another subdomain before its next event or identity
16
+ * operation. The cookie uses the `posthog-js` name and keys, so identities continue across a migration and between
17
+ * sites that use either SDK. Consent stays in local storage, as in `posthog-js`.
18
+ */
19
+ export declare const cookiePersistence: (options?: CookiePersistenceOptions) => CookiePersistence;