@posthog/browser 0.4.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/ARCHITECTURE.md +36 -48
  2. package/README.md +97 -69
  3. package/dist/composition/npm/core.d.ts +3 -4
  4. package/dist/composition/npm/core.js +2 -1
  5. package/dist/composition/npm/core.mjs +2 -1
  6. package/dist/composition/npm/index.d.ts +4 -5
  7. package/dist/composition/npm/index.js +2 -1
  8. package/dist/composition/npm/index.mjs +2 -1
  9. package/dist/composition/npm/root-composition.d.ts +4 -4
  10. package/dist/composition/npm/root-composition.js +0 -16
  11. package/dist/composition/npm/root-composition.mjs +0 -16
  12. package/dist/core/context/browser-client.d.ts +4 -35
  13. package/dist/core/extensions/registry.d.ts +15 -36
  14. package/dist/core/extensions/registry.js +67 -198
  15. package/dist/core/extensions/registry.mjs +67 -198
  16. package/dist/core/posthog.d.ts +3 -2
  17. package/dist/core/posthog.js +190 -173
  18. package/dist/core/posthog.mjs +191 -174
  19. package/dist/core/state/state.d.ts +33 -3
  20. package/dist/core/state/state.js +122 -27
  21. package/dist/core/state/state.mjs +107 -27
  22. package/dist/core/types.d.ts +134 -14
  23. package/dist/persistence/cookie.d.ts +19 -0
  24. package/dist/persistence/cookie.js +273 -0
  25. package/dist/persistence/cookie.mjs +235 -0
  26. package/dist/platform/logger.d.ts +5 -1
  27. package/dist/platform/logger.js +3 -3
  28. package/dist/platform/logger.mjs +3 -3
  29. package/dist/primitives/id.d.ts +5 -0
  30. package/dist/primitives/id.js +10 -2
  31. package/dist/primitives/id.mjs +6 -1
  32. package/dist/primitives/version.js +1 -1
  33. package/dist/primitives/version.mjs +1 -1
  34. package/dist/products/analytics/analytics-core.d.ts +89 -0
  35. package/dist/products/analytics/analytics-core.js +563 -0
  36. package/dist/products/analytics/analytics-core.mjs +516 -0
  37. package/dist/products/analytics/analytics-internal.d.ts +16 -37
  38. package/dist/products/analytics/analytics-internal.js +2 -10
  39. package/dist/products/analytics/analytics-internal.mjs +1 -3
  40. package/dist/products/analytics/analytics-options.d.ts +0 -9
  41. package/dist/products/analytics/analytics-options.js +1 -38
  42. package/dist/products/analytics/analytics-options.mjs +1 -17
  43. package/dist/products/analytics/delivery/analytics-delivery.js +1 -1
  44. package/dist/products/analytics/delivery/analytics-delivery.mjs +1 -1
  45. package/dist/products/analytics/delivery/lane.d.ts +8 -1
  46. package/dist/products/analytics/delivery/lane.js +16 -4
  47. package/dist/products/analytics/delivery/lane.mjs +16 -4
  48. package/dist/products/analytics/groups.d.ts +8 -0
  49. package/dist/products/analytics/groups.js +84 -0
  50. package/dist/products/analytics/groups.mjs +40 -0
  51. package/dist/products/analytics/person.d.ts +11 -0
  52. package/dist/products/analytics/person.js +91 -0
  53. package/dist/products/analytics/person.mjs +41 -0
  54. package/dist/products/analytics/properties/analytics-properties.d.ts +1 -0
  55. package/dist/products/analytics/properties/analytics-properties.js +3 -0
  56. package/dist/products/analytics/properties/analytics-properties.mjs +1 -1
  57. package/dist/products/autocapture/autocapture.js +2 -6
  58. package/dist/products/autocapture/autocapture.mjs +2 -6
  59. package/dist/products/flags/flags-internal.d.ts +4 -2
  60. package/dist/products/flags/flags-options.d.ts +16 -2
  61. package/dist/products/flags/flags-token.d.ts +31 -4
  62. package/dist/products/flags/flags.d.ts +1 -1
  63. package/dist/products/flags/flags.js +112 -11
  64. package/dist/products/flags/flags.mjs +112 -11
  65. package/dist/products/logs/logs.js +2 -5
  66. package/dist/products/logs/logs.mjs +2 -5
  67. package/dist/products/surveys/surveys-extension.js +78 -46
  68. package/dist/products/surveys/surveys-extension.mjs +80 -48
  69. package/dist/products/surveys/surveys-internal.d.ts +6 -0
  70. package/package.json +7 -7
  71. package/dist/products/analytics/analytics-api.d.ts +0 -32
  72. package/dist/products/analytics/analytics-api.js +0 -18
  73. package/dist/products/analytics/analytics-api.mjs +0 -1
  74. package/dist/products/analytics/analytics-buffer.d.ts +0 -4
  75. package/dist/products/analytics/analytics-buffer.js +0 -41
  76. package/dist/products/analytics/analytics-buffer.mjs +0 -3
  77. package/dist/products/analytics/analytics-extension.d.ts +0 -87
  78. package/dist/products/analytics/analytics-extension.js +0 -649
  79. package/dist/products/analytics/analytics-extension.mjs +0 -611
  80. package/dist/products/analytics/analytics.d.ts +0 -6
  81. package/dist/products/analytics/analytics.js +0 -42
  82. package/dist/products/analytics/analytics.mjs +0 -4
  83. package/dist/products/analytics/automatic-analytics.d.ts +0 -3
  84. package/dist/products/analytics/automatic-analytics.js +0 -44
  85. package/dist/products/analytics/automatic-analytics.mjs +0 -6
@@ -29,13 +29,19 @@ var __webpack_exports__ = {};
29
29
  __webpack_require__.r(__webpack_exports__);
30
30
  __webpack_require__.d(__webpack_exports__, {
31
31
  BrowserState: ()=>BrowserState,
32
+ CLIENT_KV_NAMESPACE: ()=>CLIENT_KV_NAMESPACE,
32
33
  getDefaultSessionStorage: ()=>getDefaultSessionStorage,
33
- getDefaultStorage: ()=>getDefaultStorage
34
+ getDefaultStorage: ()=>getDefaultStorage,
35
+ incrementRevision: ()=>incrementRevision,
36
+ isRecord: ()=>isRecord,
37
+ isTimestamp: ()=>isTimestamp,
38
+ readBootstrapSession: ()=>readBootstrapSession
34
39
  });
35
40
  const id_js_namespaceObject = require("../../primitives/id.js");
36
41
  const external_key_value_store_js_namespaceObject = require("./key-value-store.js");
37
- const FEATURE_FLAGS_EXTENSION = 'featureFlags';
42
+ const CLIENT_KV_NAMESPACE = 'core';
38
43
  const STORED_GROUP_PROPERTIES_KEY = '$stored_group_properties';
44
+ const SESSION_MAX_LENGTH_MS = 86400000;
39
45
  const emptyRecord = ()=>Object.create(null);
40
46
  const isRecord = (value)=>'object' == typeof value && null !== value && !Array.isArray(value);
41
47
  const readGroups = (value)=>{
@@ -50,7 +56,7 @@ const sessionExpiryReason = (session, now)=>{
50
56
  if (!session) return;
51
57
  const safeNow = isTimestamp(now) ? now : 0;
52
58
  if (Math.abs(safeNow - session.lastActivityTimestamp) > 1800000) return 'idleTimeout';
53
- if (Math.abs(safeNow - session.sessionStartTimestamp) > 86400000) return 'maxLength';
59
+ if (Math.abs(safeNow - session.sessionStartTimestamp) > SESSION_MAX_LENGTH_MS) return 'maxLength';
54
60
  };
55
61
  const readRevision = (value, fallback)=>{
56
62
  if ('string' == typeof value && /^(0|[1-9]\d*)$/.test(value)) return value;
@@ -99,12 +105,23 @@ const readExtensionData = (value)=>{
99
105
  });
100
106
  return extensionData;
101
107
  };
102
- const createSession = (now, revision)=>({
103
- sessionId: (0, id_js_namespaceObject.createId)(),
104
- sessionStartTimestamp: now,
108
+ const createSession = (now, revision, [sessionId, sessionStartTimestamp] = [
109
+ (0, id_js_namespaceObject.createTimeId)(now),
110
+ now
111
+ ])=>({
112
+ sessionId,
113
+ sessionStartTimestamp,
105
114
  lastActivityTimestamp: now,
106
115
  revision
107
116
  });
117
+ const readBootstrapSession = (sessionId, now = Date.now())=>{
118
+ const hex = 'string' == typeof sessionId ? sessionId.replace(/-/g, '') : '';
119
+ const start = /^[0-9a-f]{12}7[0-9a-f]{19}$/i.test(hex) ? parseInt(hex.slice(0, 12), 16) : 0 / 0;
120
+ return start <= now + 60000 ? [
121
+ sessionId,
122
+ start
123
+ ] : void 0;
124
+ };
108
125
  const authorityRevision = (state)=>state?.session?.revision ?? state?.sessionReset;
109
126
  const persistedAuthorityWins = (persisted, local)=>{
110
127
  const persistedRevision = authorityRevision(persisted);
@@ -138,6 +155,16 @@ const createInitialState = (deviceId = (0, id_js_namespaceObject.createId)(), an
138
155
  groups: emptyRecord(),
139
156
  extensionData: emptyRecord()
140
157
  });
158
+ const identityOf = (state)=>JSON.stringify([
159
+ state.distinctId,
160
+ state.isIdentified,
161
+ state.deviceId
162
+ ]);
163
+ const seedIdentity = (state, distinctId, identified)=>{
164
+ state.distinctId = distinctId;
165
+ if (identified) state.isIdentified = true;
166
+ else state.anonymousId = distinctId;
167
+ };
141
168
  const decodeConsent = (value)=>{
142
169
  const normalized = 'string' == typeof value ? value.trim().toLowerCase() : value;
143
170
  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;
@@ -189,7 +216,7 @@ const getDefaultSessionStorage = ()=>{
189
216
  }
190
217
  };
191
218
  class BrowserState {
192
- constructor(projectToken, storage, persistenceKey, consentPersistenceName, optOutByDefault, windowStorageFactory, onConsentChange){
219
+ constructor(projectToken, storage, persistenceKey, consentPersistenceName, optOutByDefault, windowStorageFactory, onConsentChange, cookie){
193
220
  this._windowId = '';
194
221
  this._windowStorageInitialized = false;
195
222
  this._windowListenerInstalled = false;
@@ -201,9 +228,14 @@ class BrowserState {
201
228
  this._flushSession();
202
229
  this._windowRemove(this._primaryWindowKey);
203
230
  };
204
- this._storage = storage;
205
- this._windowStorageFactory = windowStorageFactory;
206
231
  this._stateKey = persistenceKey ?? `ph_${projectToken}_posthog_browser_v2`;
232
+ try {
233
+ this._storage = storage && cookie ? cookie.wrap(storage, this._stateKey, projectToken) : storage;
234
+ } catch {
235
+ this._storage = storage;
236
+ }
237
+ this._sharesIdentity = this._storage !== storage;
238
+ this._windowStorageFactory = windowStorageFactory;
207
239
  const windowPrefix = persistenceKey ?? `ph_${projectToken}`;
208
240
  this._windowKey = `${windowPrefix}_window_id`;
209
241
  this._primaryWindowKey = `${windowPrefix}_primary_window_exists`;
@@ -214,13 +246,19 @@ class BrowserState {
214
246
  const [consentRead, storedConsent] = this._read(this.consentKey);
215
247
  if (consentRead) {
216
248
  this._lastConsentValue = storedConsent;
217
- this._consent = decodeConsent(storedConsent) ?? this._defaultConsent;
249
+ this._consentChoice = decodeConsent(storedConsent);
250
+ this._consent = this._consentChoice ?? this._defaultConsent;
218
251
  }
219
252
  const [stateRead, storedState] = this._read(this._stateKey);
220
- this._state = parseState('string' == typeof storedState ? storedState : null) ?? createInitialState();
253
+ const persisted = parseState('string' == typeof storedState ? storedState : null);
254
+ this._generated = !persisted;
255
+ this._state = persisted ?? createInitialState();
221
256
  this._lastActivityWriteTimestamp = this._state.session?.lastActivityTimestamp ?? 0;
222
257
  this._stateReadPending = !stateRead;
223
- if (stateRead) this._save();
258
+ if (stateRead) {
259
+ this._save();
260
+ this._storedIdentity = identityOf(this._state);
261
+ }
224
262
  }
225
263
  prepare() {
226
264
  if (!this._stateReadPending) return true;
@@ -230,10 +268,30 @@ class BrowserState {
230
268
  const persisted = parseState('string' == typeof storedState ? storedState : null);
231
269
  if (persisted) {
232
270
  this._state = persisted;
271
+ this._generated = false;
233
272
  this._lastActivityWriteTimestamp = persisted.session?.lastActivityTimestamp ?? 0;
234
273
  } else this._save(false);
274
+ this._storedIdentity = identityOf(this._state);
275
+ return true;
276
+ }
277
+ adoptStoredIdentity() {
278
+ const known = this._storedIdentity;
279
+ const [, stored] = this._sharesIdentity && known ? this._readPersistedState() : [];
280
+ if (!stored) return false;
281
+ this._storedIdentity = identityOf(stored);
282
+ if (this._storedIdentity === identityOf(this._state)) {
283
+ if (stored.extensionData[CLIENT_KV_NAMESPACE]?.personProcessingEnabled === true) (this._state.extensionData[CLIENT_KV_NAMESPACE] ??= emptyRecord()).personProcessingEnabled = true;
284
+ return false;
285
+ }
286
+ if (this._storedIdentity === known) return false;
287
+ copyAuthority(stored, this._state);
288
+ this._state = stored;
289
+ this._save();
235
290
  return true;
236
291
  }
292
+ get generated() {
293
+ return this._generated;
294
+ }
237
295
  get deviceId() {
238
296
  return this._state.deviceId;
239
297
  }
@@ -272,6 +330,10 @@ class BrowserState {
272
330
  get consent() {
273
331
  return this.refreshConsent();
274
332
  }
333
+ get consentChoice() {
334
+ this.refreshConsent();
335
+ return this._consentChoice;
336
+ }
275
337
  refreshConsent() {
276
338
  const [read, value] = this._read(this.consentKey);
277
339
  return read ? this.observeConsent(value) : this._consent;
@@ -280,7 +342,8 @@ class BrowserState {
280
342
  if (this._hasIgnoredConsentValue && value === this._ignoredConsentValue) return this._consent;
281
343
  this._hasIgnoredConsentValue = false;
282
344
  this._lastConsentValue = value;
283
- this._applyConsent(decodeConsent(value) ?? this._defaultConsent);
345
+ this._consentChoice = decodeConsent(value);
346
+ this._applyConsent(this._consentChoice ?? this._defaultConsent);
284
347
  return this._consent;
285
348
  }
286
349
  identify(distinctId) {
@@ -288,6 +351,14 @@ class BrowserState {
288
351
  this._state.isIdentified = true;
289
352
  this._save();
290
353
  }
354
+ bootstrapIdentity(distinctId, identified) {
355
+ seedIdentity(this._state, distinctId, identified);
356
+ if (!identified) this._state.deviceId = distinctId;
357
+ this._save();
358
+ }
359
+ bootstrapSession(session) {
360
+ this._bootstrapSession = session;
361
+ }
291
362
  group(type, key) {
292
363
  if (this._state.groups[type] === key) return false;
293
364
  this._state.groups[type] = key;
@@ -296,7 +367,7 @@ class BrowserState {
296
367
  }
297
368
  resetGroups() {
298
369
  this._state.groups = emptyRecord();
299
- const flagsData = this._state.extensionData[FEATURE_FLAGS_EXTENSION];
370
+ const flagsData = this._state.extensionData[CLIENT_KV_NAMESPACE];
300
371
  if (flagsData && STORED_GROUP_PROPERTIES_KEY in flagsData) delete flagsData[STORED_GROUP_PROPERTIES_KEY];
301
372
  this._save();
302
373
  }
@@ -305,13 +376,14 @@ class BrowserState {
305
376
  const { external, session, lastActivityWriteTimestamp, adoptedAfterReset } = this._readSessionAuthority();
306
377
  const pendingReason = this._pendingSessionReason;
307
378
  const expiry = sessionExpiryReason(session, safeNow);
308
- const rotated = !!(pendingReason || !session || expiry);
379
+ const bootstrap = this._bootstrapSession && safeNow - this._bootstrapSession[1] <= SESSION_MAX_LENGTH_MS ? this._bootstrapSession : void 0;
380
+ const rotated = !!(pendingReason || !session || expiry || bootstrap && bootstrap[0] !== session.sessionId);
309
381
  const reason = adoptedAfterReset ? 'reset' : pendingReason ?? expiry;
310
- const preparedSession = rotated ? createSession(safeNow, nextRevision(safeNow, this._state, external)) : {
382
+ const preparedSession = rotated ? createSession(safeNow, nextRevision(safeNow, this._state, external), bootstrap) : {
311
383
  ...session,
312
384
  lastActivityTimestamp: Math.max(safeNow, session.lastActivityTimestamp)
313
385
  };
314
- const window = this._prepareWindow(rotated);
386
+ const window = this._prepareWindow(rotated, safeNow);
315
387
  return {
316
388
  context: {
317
389
  sessionId: preparedSession.sessionId,
@@ -360,17 +432,20 @@ class BrowserState {
360
432
  else this._clearWindow(true);
361
433
  return false;
362
434
  }
435
+ this._bootstrapSession = void 0;
363
436
  return true;
364
437
  }
365
- reset() {
438
+ reset(resetDeviceId = false, bootstrap, bootstrapSession) {
366
439
  const [, external] = this._readPersistedState();
367
440
  const now = Date.now();
368
441
  const safeNow = isTimestamp(now) ? now : 0;
369
442
  const resetRevision = nextRevision(safeNow, this._state, external);
370
- this._state = createInitialState(this._state.deviceId, (0, id_js_namespaceObject.createId)());
443
+ this._state = createInitialState(resetDeviceId ? (0, id_js_namespaceObject.createId)() : this._state.deviceId, (0, id_js_namespaceObject.createId)());
444
+ if (bootstrap) seedIdentity(this._state, ...bootstrap);
371
445
  this._state.sessionReset = resetRevision;
372
446
  this._lastActivityWriteTimestamp = 0;
373
447
  this._pendingSessionReason = 'reset';
448
+ this._bootstrapSession = bootstrapSession;
374
449
  this._clearWindow(true);
375
450
  this._save(false);
376
451
  }
@@ -380,14 +455,23 @@ class BrowserState {
380
455
  this._windowRemove(this._primaryWindowKey);
381
456
  }
382
457
  optIn() {
383
- this._applyConsent('granted');
458
+ this._consentChoice = 'granted';
384
459
  const written = this._writeConsent('1');
460
+ this._applyConsent('granted');
385
461
  this._save();
386
462
  return written;
387
463
  }
388
464
  optOut() {
465
+ this._consentChoice = 'denied';
466
+ const written = this._writeConsent('0');
389
467
  this._applyConsent('denied');
390
- return this._writeConsent('0');
468
+ return written;
469
+ }
470
+ clearConsent() {
471
+ this._consentChoice = void 0;
472
+ const written = this._writeConsent(null);
473
+ this._applyConsent(this._defaultConsent);
474
+ return written;
391
475
  }
392
476
  keyValueStore(namespace, canAccess = ()=>true) {
393
477
  return (0, external_key_value_store_js_namespaceObject.createKeyValueStore)({
@@ -440,9 +524,9 @@ class BrowserState {
440
524
  adoptedAfterReset: adopted && void 0 !== session && 'reset' === this._pendingSessionReason
441
525
  };
442
526
  }
443
- _prepareWindow(rotated) {
527
+ _prepareWindow(rotated, now) {
444
528
  if (rotated || this._windowId) return {
445
- windowId: rotated ? (0, id_js_namespaceObject.createId)() : this._windowId,
529
+ windowId: rotated ? (0, id_js_namespaceObject.createTimeId)(now) : this._windowId,
446
530
  storage: void 0,
447
531
  storageResolved: false
448
532
  };
@@ -462,7 +546,7 @@ class BrowserState {
462
546
  } catch {}
463
547
  const reusable = lastWindowId && (!primaryWindowExists || this._isReload()) ? lastWindowId : void 0;
464
548
  return {
465
- windowId: reusable ?? (0, id_js_namespaceObject.createId)(),
549
+ windowId: reusable ?? (0, id_js_namespaceObject.createTimeId)(now),
466
550
  storage,
467
551
  storageResolved: true
468
552
  };
@@ -556,7 +640,7 @@ class BrowserState {
556
640
  const previousConsent = this._consent;
557
641
  this._consent = consent;
558
642
  try {
559
- this._onConsentChange(consent, previousConsent);
643
+ this._onConsentChange(consent, previousConsent, void 0 !== this._consentChoice);
560
644
  } catch {}
561
645
  }
562
646
  _save(preserveSession = true) {
@@ -582,7 +666,8 @@ class BrowserState {
582
666
  return false;
583
667
  }
584
668
  try {
585
- this._storage.setItem(this.consentKey, value);
669
+ if (null === value) this._storage.removeItem(this.consentKey);
670
+ else this._storage.setItem(this.consentKey, value);
586
671
  this._lastConsentValue = value;
587
672
  this._hasIgnoredConsentValue = false;
588
673
  return true;
@@ -611,12 +696,22 @@ class BrowserState {
611
696
  }
612
697
  }
613
698
  exports.BrowserState = __webpack_exports__.BrowserState;
699
+ exports.CLIENT_KV_NAMESPACE = __webpack_exports__.CLIENT_KV_NAMESPACE;
614
700
  exports.getDefaultSessionStorage = __webpack_exports__.getDefaultSessionStorage;
615
701
  exports.getDefaultStorage = __webpack_exports__.getDefaultStorage;
702
+ exports.incrementRevision = __webpack_exports__.incrementRevision;
703
+ exports.isRecord = __webpack_exports__.isRecord;
704
+ exports.isTimestamp = __webpack_exports__.isTimestamp;
705
+ exports.readBootstrapSession = __webpack_exports__.readBootstrapSession;
616
706
  for(var __rspack_i in __webpack_exports__)if (-1 === [
617
707
  "BrowserState",
708
+ "CLIENT_KV_NAMESPACE",
618
709
  "getDefaultSessionStorage",
619
- "getDefaultStorage"
710
+ "getDefaultStorage",
711
+ "incrementRevision",
712
+ "isRecord",
713
+ "isTimestamp",
714
+ "readBootstrapSession"
620
715
  ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
621
716
  Object.defineProperty(exports, '__esModule', {
622
717
  value: true
@@ -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
- const FEATURE_FLAGS_EXTENSION = 'featureFlags';
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;
@@ -262,7 +328,7 @@ class BrowserState {
262
328
  }
263
329
  resetGroups() {
264
330
  this._state.groups = emptyRecord();
265
- const flagsData = this._state.extensionData[FEATURE_FLAGS_EXTENSION];
331
+ const flagsData = this._state.extensionData[CLIENT_KV_NAMESPACE];
266
332
  if (flagsData && STORED_GROUP_PROPERTIES_KEY in flagsData) delete flagsData[STORED_GROUP_PROPERTIES_KEY];
267
333
  this._save();
268
334
  }
@@ -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, getDefaultSessionStorage, getDefaultStorage };
659
+ export { BrowserState, CLIENT_KV_NAMESPACE, getDefaultSessionStorage, getDefaultStorage, incrementRevision, isRecord, isTimestamp, readBootstrapSession };