@posthog/core 1.0.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 (43) hide show
  1. package/dist/eventemitter.d.ts +9 -0
  2. package/dist/eventemitter.d.ts.map +1 -0
  3. package/dist/eventemitter.js +52 -0
  4. package/dist/eventemitter.mjs +18 -0
  5. package/dist/featureFlagUtils.d.ts +35 -0
  6. package/dist/featureFlagUtils.d.ts.map +1 -0
  7. package/dist/featureFlagUtils.js +193 -0
  8. package/dist/featureFlagUtils.mjs +138 -0
  9. package/dist/gzip.d.ts +10 -0
  10. package/dist/gzip.d.ts.map +1 -0
  11. package/dist/gzip.js +56 -0
  12. package/dist/gzip.mjs +19 -0
  13. package/dist/index.d.ts +261 -0
  14. package/dist/index.d.ts.map +1 -0
  15. package/dist/index.js +1305 -0
  16. package/dist/index.mjs +1198 -0
  17. package/dist/testing/PostHogCoreTestClient.d.ts +24 -0
  18. package/dist/testing/PostHogCoreTestClient.d.ts.map +1 -0
  19. package/dist/testing/PostHogCoreTestClient.js +95 -0
  20. package/dist/testing/PostHogCoreTestClient.mjs +58 -0
  21. package/dist/testing/index.d.ts +3 -0
  22. package/dist/testing/index.d.ts.map +1 -0
  23. package/dist/testing/index.js +69 -0
  24. package/dist/testing/index.mjs +2 -0
  25. package/dist/testing/test-utils.d.ts +6 -0
  26. package/dist/testing/test-utils.d.ts.map +1 -0
  27. package/dist/testing/test-utils.js +75 -0
  28. package/dist/testing/test-utils.mjs +29 -0
  29. package/dist/types.d.ts +441 -0
  30. package/dist/types.d.ts.map +1 -0
  31. package/dist/types.js +163 -0
  32. package/dist/types.mjs +99 -0
  33. package/dist/utils.d.ts +24 -0
  34. package/dist/utils.d.ts.map +1 -0
  35. package/dist/utils.js +115 -0
  36. package/dist/utils.mjs +51 -0
  37. package/dist/vendor/uuidv7.d.ts +180 -0
  38. package/dist/vendor/uuidv7.d.ts.map +1 -0
  39. package/dist/vendor/uuidv7.js +223 -0
  40. package/dist/vendor/uuidv7.js.LICENSE.txt +7 -0
  41. package/dist/vendor/uuidv7.mjs +174 -0
  42. package/dist/vendor/uuidv7.mjs.LICENSE.txt +7 -0
  43. package/package.json +52 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,1198 @@
1
+ import { Compression, PostHogPersistedProperty } from "./types.mjs";
2
+ import { createFlagsResponseFromFlagsAndPayloads, getFeatureFlagValue, getFlagValuesFromFlags, getPayloadsFromFlags, normalizeFlagsResponse, updateFlagValue } from "./featureFlagUtils.mjs";
3
+ import { gzipCompress, isGzipSupported } from "./gzip.mjs";
4
+ import { SimpleEventEmitter } from "./eventemitter.mjs";
5
+ import { uuidv7 } from "./vendor/uuidv7.mjs";
6
+ export * from "./types.mjs";
7
+ import * as __WEBPACK_EXTERNAL_MODULE__utils_mjs_25ece7d1__ from "./utils.mjs";
8
+ class PostHogFetchHttpError extends Error {
9
+ get status() {
10
+ return this.response.status;
11
+ }
12
+ get text() {
13
+ return this.response.text();
14
+ }
15
+ get json() {
16
+ return this.response.json();
17
+ }
18
+ constructor(response, reqByteLength){
19
+ super('HTTP error while fetching PostHog: status=' + response.status + ', reqByteLength=' + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.name = 'PostHogFetchHttpError';
20
+ }
21
+ }
22
+ class PostHogFetchNetworkError extends Error {
23
+ constructor(error){
24
+ super('Network error while fetching PostHog', error instanceof Error ? {
25
+ cause: error
26
+ } : {}), this.error = error, this.name = 'PostHogFetchNetworkError';
27
+ }
28
+ }
29
+ const maybeAdd = (key, value)=>void 0 !== value ? {
30
+ [key]: value
31
+ } : {};
32
+ async function logFlushError(err) {
33
+ if (err instanceof PostHogFetchHttpError) {
34
+ let text = '';
35
+ try {
36
+ text = await err.text;
37
+ } catch (e) {}
38
+ console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err);
39
+ } else console.error('Error while flushing PostHog', err);
40
+ return Promise.resolve();
41
+ }
42
+ function isPostHogFetchError(err) {
43
+ return 'object' == typeof err && (err instanceof PostHogFetchHttpError || err instanceof PostHogFetchNetworkError);
44
+ }
45
+ function isPostHogFetchContentTooLargeError(err) {
46
+ return 'object' == typeof err && err instanceof PostHogFetchHttpError && 413 === err.status;
47
+ }
48
+ class PostHogCoreStateless {
49
+ logMsgIfDebug(fn) {
50
+ if (this.isDebug) fn();
51
+ }
52
+ wrap(fn) {
53
+ if (this.disabled) return void this.logMsgIfDebug(()=>console.warn('[PostHog] The client is disabled'));
54
+ if (this._isInitialized) return fn();
55
+ this._initPromise.then(()=>fn());
56
+ }
57
+ getCommonEventProperties() {
58
+ return {
59
+ $lib: this.getLibraryId(),
60
+ $lib_version: this.getLibraryVersion()
61
+ };
62
+ }
63
+ get optedOut() {
64
+ var _this_getPersistedProperty;
65
+ return null != (_this_getPersistedProperty = this.getPersistedProperty(PostHogPersistedProperty.OptedOut)) ? _this_getPersistedProperty : !this.defaultOptIn;
66
+ }
67
+ async optIn() {
68
+ this.wrap(()=>{
69
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, false);
70
+ });
71
+ }
72
+ async optOut() {
73
+ this.wrap(()=>{
74
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, true);
75
+ });
76
+ }
77
+ on(event, cb) {
78
+ return this._events.on(event, cb);
79
+ }
80
+ debug() {
81
+ let enabled = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : true;
82
+ var _this_removeDebugCallback, _this;
83
+ null == (_this_removeDebugCallback = (_this = this).removeDebugCallback) || _this_removeDebugCallback.call(_this);
84
+ if (enabled) {
85
+ const removeDebugCallback = this.on('*', (event, payload)=>console.log('PostHog Debug', event, payload));
86
+ this.removeDebugCallback = ()=>{
87
+ removeDebugCallback();
88
+ this.removeDebugCallback = void 0;
89
+ };
90
+ }
91
+ }
92
+ get isDebug() {
93
+ return !!this.removeDebugCallback;
94
+ }
95
+ get isDisabled() {
96
+ return this.disabled;
97
+ }
98
+ buildPayload(payload) {
99
+ return {
100
+ distinct_id: payload.distinct_id,
101
+ event: payload.event,
102
+ properties: {
103
+ ...payload.properties || {},
104
+ ...this.getCommonEventProperties()
105
+ }
106
+ };
107
+ }
108
+ addPendingPromise(promise) {
109
+ const promiseUUID = uuidv7();
110
+ this.pendingPromises[promiseUUID] = promise;
111
+ promise.catch(()=>{}).finally(()=>{
112
+ delete this.pendingPromises[promiseUUID];
113
+ });
114
+ return promise;
115
+ }
116
+ identifyStateless(distinctId, properties, options) {
117
+ this.wrap(()=>{
118
+ const payload = {
119
+ ...this.buildPayload({
120
+ distinct_id: distinctId,
121
+ event: '$identify',
122
+ properties
123
+ })
124
+ };
125
+ this.enqueue('identify', payload, options);
126
+ });
127
+ }
128
+ async identifyStatelessImmediate(distinctId, properties, options) {
129
+ const payload = {
130
+ ...this.buildPayload({
131
+ distinct_id: distinctId,
132
+ event: '$identify',
133
+ properties
134
+ })
135
+ };
136
+ await this.sendImmediate('identify', payload, options);
137
+ }
138
+ captureStateless(distinctId, event, properties, options) {
139
+ this.wrap(()=>{
140
+ const payload = this.buildPayload({
141
+ distinct_id: distinctId,
142
+ event,
143
+ properties
144
+ });
145
+ this.enqueue('capture', payload, options);
146
+ });
147
+ }
148
+ async captureStatelessImmediate(distinctId, event, properties, options) {
149
+ const payload = this.buildPayload({
150
+ distinct_id: distinctId,
151
+ event,
152
+ properties
153
+ });
154
+ await this.sendImmediate('capture', payload, options);
155
+ }
156
+ aliasStateless(alias, distinctId, properties, options) {
157
+ this.wrap(()=>{
158
+ const payload = this.buildPayload({
159
+ event: '$create_alias',
160
+ distinct_id: distinctId,
161
+ properties: {
162
+ ...properties || {},
163
+ distinct_id: distinctId,
164
+ alias
165
+ }
166
+ });
167
+ this.enqueue('alias', payload, options);
168
+ });
169
+ }
170
+ async aliasStatelessImmediate(alias, distinctId, properties, options) {
171
+ const payload = this.buildPayload({
172
+ event: '$create_alias',
173
+ distinct_id: distinctId,
174
+ properties: {
175
+ ...properties || {},
176
+ distinct_id: distinctId,
177
+ alias
178
+ }
179
+ });
180
+ await this.sendImmediate('alias', payload, options);
181
+ }
182
+ groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
183
+ this.wrap(()=>{
184
+ const payload = this.buildPayload({
185
+ distinct_id: distinctId || `$${groupType}_${groupKey}`,
186
+ event: '$groupidentify',
187
+ properties: {
188
+ $group_type: groupType,
189
+ $group_key: groupKey,
190
+ $group_set: groupProperties || {},
191
+ ...eventProperties || {}
192
+ }
193
+ });
194
+ this.enqueue('capture', payload, options);
195
+ });
196
+ }
197
+ async getRemoteConfig() {
198
+ await this._initPromise;
199
+ let host = this.host;
200
+ if ('https://us.i.posthog.com' === host) host = 'https://us-assets.i.posthog.com';
201
+ else if ('https://eu.i.posthog.com' === host) host = 'https://eu-assets.i.posthog.com';
202
+ const url = `${host}/array/${this.apiKey}/config`;
203
+ const fetchOptions = {
204
+ method: 'GET',
205
+ headers: {
206
+ ...this.getCustomHeaders(),
207
+ 'Content-Type': 'application/json'
208
+ }
209
+ };
210
+ return this.fetchWithRetry(url, fetchOptions, {
211
+ retryCount: 0
212
+ }, this.remoteConfigRequestTimeoutMs).then((response)=>response.json()).catch((error)=>{
213
+ this.logMsgIfDebug(()=>console.error('Remote config could not be loaded', error));
214
+ this._events.emit('error', error);
215
+ });
216
+ }
217
+ async getFlags(distinctId) {
218
+ let groups = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}, personProperties = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, groupProperties = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}, extraPayload = arguments.length > 4 && void 0 !== arguments[4] ? arguments[4] : {};
219
+ await this._initPromise;
220
+ const url = `${this.host}/flags/?v=2&config=true`;
221
+ const fetchOptions = {
222
+ method: 'POST',
223
+ headers: {
224
+ ...this.getCustomHeaders(),
225
+ 'Content-Type': 'application/json'
226
+ },
227
+ body: JSON.stringify({
228
+ token: this.apiKey,
229
+ distinct_id: distinctId,
230
+ groups,
231
+ person_properties: personProperties,
232
+ group_properties: groupProperties,
233
+ ...extraPayload
234
+ })
235
+ };
236
+ this.logMsgIfDebug(()=>console.log('PostHog Debug', 'Flags URL', url));
237
+ return this.fetchWithRetry(url, fetchOptions, {
238
+ retryCount: 0
239
+ }, this.featureFlagsRequestTimeoutMs).then((response)=>response.json()).then((response)=>normalizeFlagsResponse(response)).catch((error)=>{
240
+ this._events.emit('error', error);
241
+ });
242
+ }
243
+ async getFeatureFlagStateless(key, distinctId) {
244
+ let groups = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, personProperties = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}, groupProperties = arguments.length > 4 && void 0 !== arguments[4] ? arguments[4] : {}, disableGeoip = arguments.length > 5 ? arguments[5] : void 0;
245
+ await this._initPromise;
246
+ const flagDetailResponse = await this.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
247
+ if (void 0 === flagDetailResponse) return {
248
+ response: void 0,
249
+ requestId: void 0
250
+ };
251
+ let response = getFeatureFlagValue(flagDetailResponse.response);
252
+ if (void 0 === response) response = false;
253
+ return {
254
+ response,
255
+ requestId: flagDetailResponse.requestId
256
+ };
257
+ }
258
+ async getFeatureFlagDetailStateless(key, distinctId) {
259
+ let groups = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, personProperties = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}, groupProperties = arguments.length > 4 && void 0 !== arguments[4] ? arguments[4] : {}, disableGeoip = arguments.length > 5 ? arguments[5] : void 0;
260
+ await this._initPromise;
261
+ const flagsResponse = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [
262
+ key
263
+ ]);
264
+ if (void 0 === flagsResponse) return;
265
+ const featureFlags = flagsResponse.flags;
266
+ const flagDetail = featureFlags[key];
267
+ return {
268
+ response: flagDetail,
269
+ requestId: flagsResponse.requestId
270
+ };
271
+ }
272
+ async getFeatureFlagPayloadStateless(key, distinctId) {
273
+ let groups = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, personProperties = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}, groupProperties = arguments.length > 4 && void 0 !== arguments[4] ? arguments[4] : {}, disableGeoip = arguments.length > 5 ? arguments[5] : void 0;
274
+ await this._initPromise;
275
+ const payloads = await this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [
276
+ key
277
+ ]);
278
+ if (!payloads) return;
279
+ const response = payloads[key];
280
+ if (void 0 === response) return null;
281
+ return response;
282
+ }
283
+ async getFeatureFlagPayloadsStateless(distinctId) {
284
+ let groups = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}, personProperties = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, groupProperties = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}, disableGeoip = arguments.length > 4 ? arguments[4] : void 0, flagKeysToEvaluate = arguments.length > 5 ? arguments[5] : void 0;
285
+ await this._initPromise;
286
+ const payloads = (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate)).payloads;
287
+ return payloads;
288
+ }
289
+ async getFeatureFlagsStateless(distinctId) {
290
+ let groups = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}, personProperties = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, groupProperties = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}, disableGeoip = arguments.length > 4 ? arguments[4] : void 0, flagKeysToEvaluate = arguments.length > 5 ? arguments[5] : void 0;
291
+ await this._initPromise;
292
+ return await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
293
+ }
294
+ async getFeatureFlagsAndPayloadsStateless(distinctId) {
295
+ let groups = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}, personProperties = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, groupProperties = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}, disableGeoip = arguments.length > 4 ? arguments[4] : void 0, flagKeysToEvaluate = arguments.length > 5 ? arguments[5] : void 0;
296
+ await this._initPromise;
297
+ const featureFlagDetails = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
298
+ if (!featureFlagDetails) return {
299
+ flags: void 0,
300
+ payloads: void 0,
301
+ requestId: void 0
302
+ };
303
+ return {
304
+ flags: featureFlagDetails.featureFlags,
305
+ payloads: featureFlagDetails.featureFlagPayloads,
306
+ requestId: featureFlagDetails.requestId
307
+ };
308
+ }
309
+ async getFeatureFlagDetailsStateless(distinctId) {
310
+ let groups = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}, personProperties = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, groupProperties = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}, disableGeoip = arguments.length > 4 ? arguments[4] : void 0, flagKeysToEvaluate = arguments.length > 5 ? arguments[5] : void 0;
311
+ var _flagsResponse_quotaLimited;
312
+ await this._initPromise;
313
+ const extraPayload = {};
314
+ if (null != disableGeoip ? disableGeoip : this.disableGeoip) extraPayload['geoip_disable'] = true;
315
+ if (flagKeysToEvaluate) extraPayload['flag_keys_to_evaluate'] = flagKeysToEvaluate;
316
+ const flagsResponse = await this.getFlags(distinctId, groups, personProperties, groupProperties, extraPayload);
317
+ if (void 0 === flagsResponse) return;
318
+ if (flagsResponse.errorsWhileComputingFlags) console.error('[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices');
319
+ if (null == (_flagsResponse_quotaLimited = flagsResponse.quotaLimited) ? void 0 : _flagsResponse_quotaLimited.includes("feature_flags")) {
320
+ console.warn('[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts');
321
+ return {
322
+ flags: {},
323
+ featureFlags: {},
324
+ featureFlagPayloads: {},
325
+ requestId: null == flagsResponse ? void 0 : flagsResponse.requestId
326
+ };
327
+ }
328
+ return flagsResponse;
329
+ }
330
+ async getSurveysStateless() {
331
+ await this._initPromise;
332
+ if (true === this.disableSurveys) {
333
+ this.logMsgIfDebug(()=>console.log('PostHog Debug', 'Loading surveys is disabled.'));
334
+ return [];
335
+ }
336
+ const url = `${this.host}/api/surveys/?token=${this.apiKey}`;
337
+ const fetchOptions = {
338
+ method: 'GET',
339
+ headers: {
340
+ ...this.getCustomHeaders(),
341
+ 'Content-Type': 'application/json'
342
+ }
343
+ };
344
+ const response = await this.fetchWithRetry(url, fetchOptions).then((response)=>{
345
+ if (200 !== response.status || !response.json) {
346
+ const msg = `Surveys API could not be loaded: ${response.status}`;
347
+ const error = new Error(msg);
348
+ this.logMsgIfDebug(()=>console.error(error));
349
+ this._events.emit('error', new Error(msg));
350
+ return;
351
+ }
352
+ return response.json();
353
+ }).catch((error)=>{
354
+ this.logMsgIfDebug(()=>console.error('Surveys API could not be loaded', error));
355
+ this._events.emit('error', error);
356
+ });
357
+ const newSurveys = null == response ? void 0 : response.surveys;
358
+ if (newSurveys) this.logMsgIfDebug(()=>console.log('PostHog Debug', 'Surveys fetched from API: ', JSON.stringify(newSurveys)));
359
+ return null != newSurveys ? newSurveys : [];
360
+ }
361
+ get props() {
362
+ if (!this._props) this._props = this.getPersistedProperty(PostHogPersistedProperty.Props);
363
+ return this._props || {};
364
+ }
365
+ set props(val) {
366
+ this._props = val;
367
+ }
368
+ async register(properties) {
369
+ this.wrap(()=>{
370
+ this.props = {
371
+ ...this.props,
372
+ ...properties
373
+ };
374
+ this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
375
+ });
376
+ }
377
+ async unregister(property) {
378
+ this.wrap(()=>{
379
+ delete this.props[property];
380
+ this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
381
+ });
382
+ }
383
+ enqueue(type, _message, options) {
384
+ this.wrap(()=>{
385
+ if (this.optedOut) return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
386
+ const message = this.prepareMessage(type, _message, options);
387
+ const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
388
+ if (queue.length >= this.maxQueueSize) {
389
+ queue.shift();
390
+ this.logMsgIfDebug(()=>console.info('Queue is full, the oldest event is dropped.'));
391
+ }
392
+ queue.push({
393
+ message
394
+ });
395
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
396
+ this._events.emit(type, message);
397
+ if (queue.length >= this.flushAt) this.flushBackground();
398
+ if (this.flushInterval && !this._flushTimer) this._flushTimer = (0, __WEBPACK_EXTERNAL_MODULE__utils_mjs_25ece7d1__.safeSetTimeout)(()=>this.flushBackground(), this.flushInterval);
399
+ });
400
+ }
401
+ async sendImmediate(type, _message, options) {
402
+ if (this.disabled) return void this.logMsgIfDebug(()=>console.warn('[PostHog] The client is disabled'));
403
+ if (!this._isInitialized) await this._initPromise;
404
+ if (this.optedOut) return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
405
+ const data = {
406
+ api_key: this.apiKey,
407
+ batch: [
408
+ this.prepareMessage(type, _message, options)
409
+ ],
410
+ sent_at: (0, __WEBPACK_EXTERNAL_MODULE__utils_mjs_25ece7d1__.currentISOTime)()
411
+ };
412
+ if (this.historicalMigration) data.historical_migration = true;
413
+ const payload = JSON.stringify(data);
414
+ const url = `${this.host}/batch/`;
415
+ const gzippedPayload = this.disableCompression ? null : await gzipCompress(payload, this.isDebug);
416
+ const fetchOptions = {
417
+ method: 'POST',
418
+ headers: {
419
+ ...this.getCustomHeaders(),
420
+ 'Content-Type': 'application/json',
421
+ ...null !== gzippedPayload && {
422
+ 'Content-Encoding': 'gzip'
423
+ }
424
+ },
425
+ body: gzippedPayload || payload
426
+ };
427
+ try {
428
+ await this.fetchWithRetry(url, fetchOptions);
429
+ } catch (err) {
430
+ this._events.emit('error', err);
431
+ }
432
+ }
433
+ prepareMessage(type, _message, options) {
434
+ const message = {
435
+ ..._message,
436
+ type: type,
437
+ library: this.getLibraryId(),
438
+ library_version: this.getLibraryVersion(),
439
+ timestamp: (null == options ? void 0 : options.timestamp) ? null == options ? void 0 : options.timestamp : (0, __WEBPACK_EXTERNAL_MODULE__utils_mjs_25ece7d1__.currentISOTime)(),
440
+ uuid: (null == options ? void 0 : options.uuid) ? options.uuid : uuidv7()
441
+ };
442
+ var _options_disableGeoip;
443
+ const addGeoipDisableProperty = null != (_options_disableGeoip = null == options ? void 0 : options.disableGeoip) ? _options_disableGeoip : this.disableGeoip;
444
+ if (addGeoipDisableProperty) {
445
+ if (!message.properties) message.properties = {};
446
+ message['properties']['$geoip_disable'] = true;
447
+ }
448
+ if (message.distinctId) {
449
+ message.distinct_id = message.distinctId;
450
+ delete message.distinctId;
451
+ }
452
+ return message;
453
+ }
454
+ clearFlushTimer() {
455
+ if (this._flushTimer) {
456
+ clearTimeout(this._flushTimer);
457
+ this._flushTimer = void 0;
458
+ }
459
+ }
460
+ flushBackground() {
461
+ this.flush().catch(async (err)=>{
462
+ await logFlushError(err);
463
+ });
464
+ }
465
+ async flush() {
466
+ const nextFlushPromise = (0, __WEBPACK_EXTERNAL_MODULE__utils_mjs_25ece7d1__.allSettled)([
467
+ this.flushPromise
468
+ ]).then(()=>this._flush());
469
+ this.flushPromise = nextFlushPromise;
470
+ this.addPendingPromise(nextFlushPromise);
471
+ (0, __WEBPACK_EXTERNAL_MODULE__utils_mjs_25ece7d1__.allSettled)([
472
+ nextFlushPromise
473
+ ]).then(()=>{
474
+ if (this.flushPromise === nextFlushPromise) this.flushPromise = null;
475
+ });
476
+ return nextFlushPromise;
477
+ }
478
+ getCustomHeaders() {
479
+ const customUserAgent = this.getCustomUserAgent();
480
+ const headers = {};
481
+ if (customUserAgent && '' !== customUserAgent) headers['User-Agent'] = customUserAgent;
482
+ return headers;
483
+ }
484
+ async _flush() {
485
+ this.clearFlushTimer();
486
+ await this._initPromise;
487
+ let queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
488
+ if (!queue.length) return;
489
+ const sentMessages = [];
490
+ const originalQueueLength = queue.length;
491
+ while(queue.length > 0 && sentMessages.length < originalQueueLength){
492
+ const batchItems = queue.slice(0, this.maxBatchSize);
493
+ const batchMessages = batchItems.map((item)=>item.message);
494
+ const persistQueueChange = ()=>{
495
+ const refreshedQueue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
496
+ const newQueue = refreshedQueue.slice(batchItems.length);
497
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, newQueue);
498
+ queue = newQueue;
499
+ };
500
+ const data = {
501
+ api_key: this.apiKey,
502
+ batch: batchMessages,
503
+ sent_at: (0, __WEBPACK_EXTERNAL_MODULE__utils_mjs_25ece7d1__.currentISOTime)()
504
+ };
505
+ if (this.historicalMigration) data.historical_migration = true;
506
+ const payload = JSON.stringify(data);
507
+ const url = `${this.host}/batch/`;
508
+ const gzippedPayload = this.disableCompression ? null : await gzipCompress(payload, this.isDebug);
509
+ const fetchOptions = {
510
+ method: 'POST',
511
+ headers: {
512
+ ...this.getCustomHeaders(),
513
+ 'Content-Type': 'application/json',
514
+ ...null !== gzippedPayload && {
515
+ 'Content-Encoding': 'gzip'
516
+ }
517
+ },
518
+ body: gzippedPayload || payload
519
+ };
520
+ const retryOptions = {
521
+ retryCheck: (err)=>{
522
+ if (isPostHogFetchContentTooLargeError(err)) return false;
523
+ return isPostHogFetchError(err);
524
+ }
525
+ };
526
+ try {
527
+ await this.fetchWithRetry(url, fetchOptions, retryOptions);
528
+ } catch (err) {
529
+ if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {
530
+ this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));
531
+ this.logMsgIfDebug(()=>console.warn(`Received 413 when sending batch of size ${batchMessages.length}, reducing batch size to ${this.maxBatchSize}`));
532
+ continue;
533
+ }
534
+ if (!(err instanceof PostHogFetchNetworkError)) persistQueueChange();
535
+ this._events.emit('error', err);
536
+ throw err;
537
+ }
538
+ persistQueueChange();
539
+ sentMessages.push(...batchMessages);
540
+ }
541
+ this._events.emit('flush', sentMessages);
542
+ }
543
+ async fetchWithRetry(url, options, retryOptions, requestTimeout) {
544
+ var _AbortSignal;
545
+ null != (_AbortSignal = AbortSignal).timeout || (_AbortSignal.timeout = function(ms) {
546
+ const ctrl = new AbortController();
547
+ setTimeout(()=>ctrl.abort(), ms);
548
+ return ctrl.signal;
549
+ });
550
+ const body = options.body ? options.body : '';
551
+ let reqByteLength = -1;
552
+ try {
553
+ reqByteLength = body instanceof Blob ? body.size : Buffer.byteLength(body, __WEBPACK_EXTERNAL_MODULE__utils_mjs_25ece7d1__.STRING_FORMAT);
554
+ } catch (e) {
555
+ if (body instanceof Blob) reqByteLength = body.size;
556
+ else {
557
+ const encoded = new TextEncoder().encode(body);
558
+ reqByteLength = encoded.length;
559
+ }
560
+ }
561
+ return await (0, __WEBPACK_EXTERNAL_MODULE__utils_mjs_25ece7d1__.retriable)(async ()=>{
562
+ let res = null;
563
+ try {
564
+ res = await this.fetch(url, {
565
+ signal: AbortSignal.timeout(null != requestTimeout ? requestTimeout : this.requestTimeout),
566
+ ...options
567
+ });
568
+ } catch (e) {
569
+ throw new PostHogFetchNetworkError(e);
570
+ }
571
+ const isNoCors = 'no-cors' === options.mode;
572
+ if (!isNoCors && (res.status < 200 || res.status >= 400)) throw new PostHogFetchHttpError(res, reqByteLength);
573
+ return res;
574
+ }, {
575
+ ...this._retryOptions,
576
+ ...retryOptions
577
+ });
578
+ }
579
+ async _shutdown() {
580
+ let shutdownTimeoutMs = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 30000;
581
+ await this._initPromise;
582
+ let hasTimedOut = false;
583
+ this.clearFlushTimer();
584
+ const doShutdown = async ()=>{
585
+ try {
586
+ await Promise.all(Object.values(this.pendingPromises));
587
+ while(true){
588
+ const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
589
+ if (0 === queue.length) break;
590
+ await this.flush();
591
+ if (hasTimedOut) break;
592
+ }
593
+ } catch (e) {
594
+ if (!isPostHogFetchError(e)) throw e;
595
+ await logFlushError(e);
596
+ }
597
+ };
598
+ return Promise.race([
599
+ new Promise((_, reject)=>{
600
+ (0, __WEBPACK_EXTERNAL_MODULE__utils_mjs_25ece7d1__.safeSetTimeout)(()=>{
601
+ this.logMsgIfDebug(()=>console.error('Timed out while shutting down PostHog'));
602
+ hasTimedOut = true;
603
+ reject('Timeout while shutting down PostHog. Some events may not have been sent.');
604
+ }, shutdownTimeoutMs);
605
+ }),
606
+ doShutdown()
607
+ ]);
608
+ }
609
+ async shutdown() {
610
+ let shutdownTimeoutMs = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 30000;
611
+ if (this.shutdownPromise) this.logMsgIfDebug(()=>console.warn('shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup'));
612
+ else this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(()=>{
613
+ this.shutdownPromise = null;
614
+ });
615
+ return this.shutdownPromise;
616
+ }
617
+ constructor(apiKey, options){
618
+ this.flushPromise = null;
619
+ this.shutdownPromise = null;
620
+ this.pendingPromises = {};
621
+ this._events = new SimpleEventEmitter();
622
+ this._isInitialized = false;
623
+ (0, __WEBPACK_EXTERNAL_MODULE__utils_mjs_25ece7d1__.assert)(apiKey, "You must pass your PostHog project's api key.");
624
+ this.apiKey = apiKey;
625
+ this.host = (0, __WEBPACK_EXTERNAL_MODULE__utils_mjs_25ece7d1__.removeTrailingSlash)((null == options ? void 0 : options.host) || 'https://us.i.posthog.com');
626
+ this.flushAt = (null == options ? void 0 : options.flushAt) ? Math.max(null == options ? void 0 : options.flushAt, 1) : 20;
627
+ var _options_maxBatchSize;
628
+ this.maxBatchSize = Math.max(this.flushAt, null != (_options_maxBatchSize = null == options ? void 0 : options.maxBatchSize) ? _options_maxBatchSize : 100);
629
+ var _options_maxQueueSize;
630
+ this.maxQueueSize = Math.max(this.flushAt, null != (_options_maxQueueSize = null == options ? void 0 : options.maxQueueSize) ? _options_maxQueueSize : 1000);
631
+ var _options_flushInterval;
632
+ this.flushInterval = null != (_options_flushInterval = null == options ? void 0 : options.flushInterval) ? _options_flushInterval : 10000;
633
+ var _options_preloadFeatureFlags;
634
+ this.preloadFeatureFlags = null != (_options_preloadFeatureFlags = null == options ? void 0 : options.preloadFeatureFlags) ? _options_preloadFeatureFlags : true;
635
+ var _options_defaultOptIn;
636
+ this.defaultOptIn = null != (_options_defaultOptIn = null == options ? void 0 : options.defaultOptIn) ? _options_defaultOptIn : true;
637
+ var _options_disableSurveys;
638
+ this.disableSurveys = null != (_options_disableSurveys = null == options ? void 0 : options.disableSurveys) ? _options_disableSurveys : false;
639
+ var _options_fetchRetryCount, _options_fetchRetryDelay;
640
+ this._retryOptions = {
641
+ retryCount: null != (_options_fetchRetryCount = null == options ? void 0 : options.fetchRetryCount) ? _options_fetchRetryCount : 3,
642
+ retryDelay: null != (_options_fetchRetryDelay = null == options ? void 0 : options.fetchRetryDelay) ? _options_fetchRetryDelay : 3000,
643
+ retryCheck: isPostHogFetchError
644
+ };
645
+ var _options_requestTimeout;
646
+ this.requestTimeout = null != (_options_requestTimeout = null == options ? void 0 : options.requestTimeout) ? _options_requestTimeout : 10000;
647
+ var _options_featureFlagsRequestTimeoutMs;
648
+ this.featureFlagsRequestTimeoutMs = null != (_options_featureFlagsRequestTimeoutMs = null == options ? void 0 : options.featureFlagsRequestTimeoutMs) ? _options_featureFlagsRequestTimeoutMs : 3000;
649
+ var _options_remoteConfigRequestTimeoutMs;
650
+ this.remoteConfigRequestTimeoutMs = null != (_options_remoteConfigRequestTimeoutMs = null == options ? void 0 : options.remoteConfigRequestTimeoutMs) ? _options_remoteConfigRequestTimeoutMs : 3000;
651
+ var _options_disableGeoip;
652
+ this.disableGeoip = null != (_options_disableGeoip = null == options ? void 0 : options.disableGeoip) ? _options_disableGeoip : true;
653
+ var _options_disabled;
654
+ this.disabled = null != (_options_disabled = null == options ? void 0 : options.disabled) ? _options_disabled : false;
655
+ var _options_historicalMigration;
656
+ this.historicalMigration = null != (_options_historicalMigration = null == options ? void 0 : options.historicalMigration) ? _options_historicalMigration : false;
657
+ this._initPromise = Promise.resolve();
658
+ this._isInitialized = true;
659
+ var _options_disableCompression;
660
+ this.disableCompression = !isGzipSupported() || (null != (_options_disableCompression = null == options ? void 0 : options.disableCompression) ? _options_disableCompression : false);
661
+ }
662
+ }
663
+ class PostHogCore extends PostHogCoreStateless {
664
+ setupBootstrap(options) {
665
+ const bootstrap = null == options ? void 0 : options.bootstrap;
666
+ if (!bootstrap) return;
667
+ if (bootstrap.distinctId) if (bootstrap.isIdentifiedId) {
668
+ const distinctId = this.getPersistedProperty(PostHogPersistedProperty.DistinctId);
669
+ if (!distinctId) this.setPersistedProperty(PostHogPersistedProperty.DistinctId, bootstrap.distinctId);
670
+ } else {
671
+ const anonymousId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);
672
+ if (!anonymousId) this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, bootstrap.distinctId);
673
+ }
674
+ const bootstrapFeatureFlags = bootstrap.featureFlags;
675
+ var _bootstrap_featureFlagPayloads;
676
+ const bootstrapFeatureFlagPayloads = null != (_bootstrap_featureFlagPayloads = bootstrap.featureFlagPayloads) ? _bootstrap_featureFlagPayloads : {};
677
+ if (bootstrapFeatureFlags && Object.keys(bootstrapFeatureFlags).length) {
678
+ const normalizedBootstrapFeatureFlagDetails = createFlagsResponseFromFlagsAndPayloads(bootstrapFeatureFlags, bootstrapFeatureFlagPayloads);
679
+ if (Object.keys(normalizedBootstrapFeatureFlagDetails.flags).length > 0) {
680
+ this.setBootstrappedFeatureFlagDetails(normalizedBootstrapFeatureFlagDetails);
681
+ const currentFeatureFlagDetails = this.getKnownFeatureFlagDetails() || {
682
+ flags: {},
683
+ requestId: void 0
684
+ };
685
+ const newFeatureFlagDetails = {
686
+ flags: {
687
+ ...normalizedBootstrapFeatureFlagDetails.flags,
688
+ ...currentFeatureFlagDetails.flags
689
+ },
690
+ requestId: normalizedBootstrapFeatureFlagDetails.requestId
691
+ };
692
+ this.setKnownFeatureFlagDetails(newFeatureFlagDetails);
693
+ }
694
+ }
695
+ }
696
+ clearProps() {
697
+ this.props = void 0;
698
+ this.sessionProps = {};
699
+ this.flagCallReported = {};
700
+ }
701
+ on(event, cb) {
702
+ return this._events.on(event, cb);
703
+ }
704
+ reset(propertiesToKeep) {
705
+ this.wrap(()=>{
706
+ const allPropertiesToKeep = [
707
+ PostHogPersistedProperty.Queue,
708
+ ...propertiesToKeep || []
709
+ ];
710
+ this.clearProps();
711
+ for (const key of Object.keys(PostHogPersistedProperty))if (!allPropertiesToKeep.includes(PostHogPersistedProperty[key])) this.setPersistedProperty(PostHogPersistedProperty[key], null);
712
+ this.reloadFeatureFlags();
713
+ });
714
+ }
715
+ getCommonEventProperties() {
716
+ const featureFlags = this.getFeatureFlags();
717
+ const featureVariantProperties = {};
718
+ if (featureFlags) for (const [feature, variant] of Object.entries(featureFlags))featureVariantProperties[`$feature/${feature}`] = variant;
719
+ return {
720
+ ...maybeAdd('$active_feature_flags', featureFlags ? Object.keys(featureFlags) : void 0),
721
+ ...featureVariantProperties,
722
+ ...super.getCommonEventProperties()
723
+ };
724
+ }
725
+ enrichProperties(properties) {
726
+ return {
727
+ ...this.props,
728
+ ...this.sessionProps,
729
+ ...properties || {},
730
+ ...this.getCommonEventProperties(),
731
+ $session_id: this.getSessionId()
732
+ };
733
+ }
734
+ getSessionId() {
735
+ if (!this._isInitialized) return '';
736
+ let sessionId = this.getPersistedProperty(PostHogPersistedProperty.SessionId);
737
+ const sessionLastTimestamp = this.getPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp) || 0;
738
+ const sessionStartTimestamp = this.getPersistedProperty(PostHogPersistedProperty.SessionStartTimestamp) || 0;
739
+ const now = Date.now();
740
+ const sessionLastDif = now - sessionLastTimestamp;
741
+ const sessionStartDif = now - sessionStartTimestamp;
742
+ if (!sessionId || sessionLastDif > 1000 * this._sessionExpirationTimeSeconds || sessionStartDif > 1000 * this._sessionMaxLengthSeconds) {
743
+ sessionId = uuidv7();
744
+ this.setPersistedProperty(PostHogPersistedProperty.SessionId, sessionId);
745
+ this.setPersistedProperty(PostHogPersistedProperty.SessionStartTimestamp, now);
746
+ }
747
+ this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, now);
748
+ return sessionId;
749
+ }
750
+ resetSessionId() {
751
+ this.wrap(()=>{
752
+ this.setPersistedProperty(PostHogPersistedProperty.SessionId, null);
753
+ this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, null);
754
+ this.setPersistedProperty(PostHogPersistedProperty.SessionStartTimestamp, null);
755
+ });
756
+ }
757
+ getAnonymousId() {
758
+ if (!this._isInitialized) return '';
759
+ let anonId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);
760
+ if (!anonId) {
761
+ anonId = uuidv7();
762
+ this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, anonId);
763
+ }
764
+ return anonId;
765
+ }
766
+ getDistinctId() {
767
+ if (!this._isInitialized) return '';
768
+ return this.getPersistedProperty(PostHogPersistedProperty.DistinctId) || this.getAnonymousId();
769
+ }
770
+ registerForSession(properties) {
771
+ this.sessionProps = {
772
+ ...this.sessionProps,
773
+ ...properties
774
+ };
775
+ }
776
+ unregisterForSession(property) {
777
+ delete this.sessionProps[property];
778
+ }
779
+ identify(distinctId, properties, options) {
780
+ this.wrap(()=>{
781
+ const previousDistinctId = this.getDistinctId();
782
+ distinctId = distinctId || previousDistinctId;
783
+ if (null == properties ? void 0 : properties.$groups) this.groups(properties.$groups);
784
+ const userPropsOnce = null == properties ? void 0 : properties.$set_once;
785
+ null == properties || delete properties.$set_once;
786
+ const userProps = (null == properties ? void 0 : properties.$set) || properties;
787
+ const allProperties = this.enrichProperties({
788
+ $anon_distinct_id: this.getAnonymousId(),
789
+ ...maybeAdd('$set', userProps),
790
+ ...maybeAdd('$set_once', userPropsOnce)
791
+ });
792
+ if (distinctId !== previousDistinctId) {
793
+ this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, previousDistinctId);
794
+ this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);
795
+ this.reloadFeatureFlags();
796
+ }
797
+ super.identifyStateless(distinctId, allProperties, options);
798
+ });
799
+ }
800
+ capture(event, properties, options) {
801
+ this.wrap(()=>{
802
+ const distinctId = this.getDistinctId();
803
+ if (null == properties ? void 0 : properties.$groups) this.groups(properties.$groups);
804
+ const allProperties = this.enrichProperties(properties);
805
+ super.captureStateless(distinctId, event, allProperties, options);
806
+ });
807
+ }
808
+ alias(alias) {
809
+ this.wrap(()=>{
810
+ const distinctId = this.getDistinctId();
811
+ const allProperties = this.enrichProperties({});
812
+ super.aliasStateless(alias, distinctId, allProperties);
813
+ });
814
+ }
815
+ autocapture(eventType, elements) {
816
+ let properties = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, options = arguments.length > 3 ? arguments[3] : void 0;
817
+ this.wrap(()=>{
818
+ const distinctId = this.getDistinctId();
819
+ const payload = {
820
+ distinct_id: distinctId,
821
+ event: '$autocapture',
822
+ properties: {
823
+ ...this.enrichProperties(properties),
824
+ $event_type: eventType,
825
+ $elements: elements
826
+ }
827
+ };
828
+ this.enqueue('autocapture', payload, options);
829
+ });
830
+ }
831
+ groups(groups) {
832
+ this.wrap(()=>{
833
+ const existingGroups = this.props.$groups || {};
834
+ this.register({
835
+ $groups: {
836
+ ...existingGroups,
837
+ ...groups
838
+ }
839
+ });
840
+ if (Object.keys(groups).find((type)=>existingGroups[type] !== groups[type])) this.reloadFeatureFlags();
841
+ });
842
+ }
843
+ group(groupType, groupKey, groupProperties, options) {
844
+ this.wrap(()=>{
845
+ this.groups({
846
+ [groupType]: groupKey
847
+ });
848
+ if (groupProperties) this.groupIdentify(groupType, groupKey, groupProperties, options);
849
+ });
850
+ }
851
+ groupIdentify(groupType, groupKey, groupProperties, options) {
852
+ this.wrap(()=>{
853
+ const distinctId = this.getDistinctId();
854
+ const eventProperties = this.enrichProperties({});
855
+ super.groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties);
856
+ });
857
+ }
858
+ setPersonPropertiesForFlags(properties) {
859
+ this.wrap(()=>{
860
+ const existingProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};
861
+ this.setPersistedProperty(PostHogPersistedProperty.PersonProperties, {
862
+ ...existingProperties,
863
+ ...properties
864
+ });
865
+ });
866
+ }
867
+ resetPersonPropertiesForFlags() {
868
+ this.wrap(()=>{
869
+ this.setPersistedProperty(PostHogPersistedProperty.PersonProperties, null);
870
+ });
871
+ }
872
+ setGroupPropertiesForFlags(properties) {
873
+ this.wrap(()=>{
874
+ const existingProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) || {};
875
+ if (0 !== Object.keys(existingProperties).length) Object.keys(existingProperties).forEach((groupType)=>{
876
+ existingProperties[groupType] = {
877
+ ...existingProperties[groupType],
878
+ ...properties[groupType]
879
+ };
880
+ delete properties[groupType];
881
+ });
882
+ this.setPersistedProperty(PostHogPersistedProperty.GroupProperties, {
883
+ ...existingProperties,
884
+ ...properties
885
+ });
886
+ });
887
+ }
888
+ resetGroupPropertiesForFlags() {
889
+ this.wrap(()=>{
890
+ this.setPersistedProperty(PostHogPersistedProperty.GroupProperties, null);
891
+ });
892
+ }
893
+ async remoteConfigAsync() {
894
+ await this._initPromise;
895
+ if (this._remoteConfigResponsePromise) return this._remoteConfigResponsePromise;
896
+ return this._remoteConfigAsync();
897
+ }
898
+ async flagsAsync() {
899
+ let sendAnonDistinctId = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : true;
900
+ await this._initPromise;
901
+ if (this._flagsResponsePromise) return this._flagsResponsePromise;
902
+ return this._flagsAsync(sendAnonDistinctId);
903
+ }
904
+ cacheSessionReplay(source, response) {
905
+ const sessionReplay = null == response ? void 0 : response.sessionRecording;
906
+ if (sessionReplay) {
907
+ this.setPersistedProperty(PostHogPersistedProperty.SessionReplay, sessionReplay);
908
+ this.logMsgIfDebug(()=>console.log('PostHog Debug', `Session replay config from ${source}: `, JSON.stringify(sessionReplay)));
909
+ } else if ('boolean' == typeof sessionReplay && false === sessionReplay) {
910
+ this.logMsgIfDebug(()=>console.info('PostHog Debug', `Session replay config from ${source} disabled.`));
911
+ this.setPersistedProperty(PostHogPersistedProperty.SessionReplay, null);
912
+ }
913
+ }
914
+ async _remoteConfigAsync() {
915
+ this._remoteConfigResponsePromise = this._initPromise.then(()=>{
916
+ let remoteConfig = this.getPersistedProperty(PostHogPersistedProperty.RemoteConfig);
917
+ this.logMsgIfDebug(()=>console.log('PostHog Debug', 'Cached remote config: ', JSON.stringify(remoteConfig)));
918
+ return super.getRemoteConfig().then((response)=>{
919
+ if (response) {
920
+ var _response_supportedCompression;
921
+ const remoteConfigWithoutSurveys = {
922
+ ...response
923
+ };
924
+ delete remoteConfigWithoutSurveys.surveys;
925
+ this.logMsgIfDebug(()=>console.log('PostHog Debug', 'Fetched remote config: ', JSON.stringify(remoteConfigWithoutSurveys)));
926
+ if (false === this.disableSurveys) {
927
+ const surveys = response.surveys;
928
+ let hasSurveys = true;
929
+ if (Array.isArray(surveys)) this.logMsgIfDebug(()=>console.log('PostHog Debug', 'Surveys fetched from remote config: ', JSON.stringify(surveys)));
930
+ else {
931
+ this.logMsgIfDebug(()=>console.log('PostHog Debug', 'There are no surveys.'));
932
+ hasSurveys = false;
933
+ }
934
+ if (hasSurveys) this.setPersistedProperty(PostHogPersistedProperty.Surveys, surveys);
935
+ else this.setPersistedProperty(PostHogPersistedProperty.Surveys, null);
936
+ } else this.setPersistedProperty(PostHogPersistedProperty.Surveys, null);
937
+ this.setPersistedProperty(PostHogPersistedProperty.RemoteConfig, remoteConfigWithoutSurveys);
938
+ this.cacheSessionReplay('remote config', response);
939
+ if (false === response.hasFeatureFlags) {
940
+ this.setKnownFeatureFlagDetails({
941
+ flags: {}
942
+ });
943
+ this.logMsgIfDebug(()=>console.warn('Remote config has no feature flags, will not load feature flags.'));
944
+ } else if (false !== this.preloadFeatureFlags) this.reloadFeatureFlags();
945
+ if (!(null == (_response_supportedCompression = response.supportedCompression) ? void 0 : _response_supportedCompression.includes(Compression.GZipJS))) this.disableCompression = true;
946
+ remoteConfig = response;
947
+ }
948
+ return remoteConfig;
949
+ });
950
+ }).finally(()=>{
951
+ this._remoteConfigResponsePromise = void 0;
952
+ });
953
+ return this._remoteConfigResponsePromise;
954
+ }
955
+ async _flagsAsync() {
956
+ let sendAnonDistinctId = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : true;
957
+ this._flagsResponsePromise = this._initPromise.then(async ()=>{
958
+ var _res_quotaLimited;
959
+ const distinctId = this.getDistinctId();
960
+ const groups = this.props.$groups || {};
961
+ const personProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};
962
+ const groupProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) || {};
963
+ const extraProperties = {
964
+ $anon_distinct_id: sendAnonDistinctId ? this.getAnonymousId() : void 0
965
+ };
966
+ const res = await super.getFlags(distinctId, groups, personProperties, groupProperties, extraProperties);
967
+ if (null == res ? void 0 : null == (_res_quotaLimited = res.quotaLimited) ? void 0 : _res_quotaLimited.includes("feature_flags")) {
968
+ this.setKnownFeatureFlagDetails(null);
969
+ console.warn('[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts');
970
+ return res;
971
+ }
972
+ if (null == res ? void 0 : res.featureFlags) {
973
+ if (this.sendFeatureFlagEvent) this.flagCallReported = {};
974
+ let newFeatureFlagDetails = res;
975
+ if (res.errorsWhileComputingFlags) {
976
+ const currentFlagDetails = this.getKnownFeatureFlagDetails();
977
+ this.logMsgIfDebug(()=>console.log('PostHog Debug', 'Cached feature flags: ', JSON.stringify(currentFlagDetails)));
978
+ newFeatureFlagDetails = {
979
+ ...res,
980
+ flags: {
981
+ ...null == currentFlagDetails ? void 0 : currentFlagDetails.flags,
982
+ ...res.flags
983
+ }
984
+ };
985
+ }
986
+ this.setKnownFeatureFlagDetails(newFeatureFlagDetails);
987
+ this.setPersistedProperty(PostHogPersistedProperty.FlagsEndpointWasHit, true);
988
+ this.cacheSessionReplay('flags', res);
989
+ }
990
+ return res;
991
+ }).finally(()=>{
992
+ this._flagsResponsePromise = void 0;
993
+ });
994
+ return this._flagsResponsePromise;
995
+ }
996
+ setKnownFeatureFlagDetails(flagsResponse) {
997
+ this.wrap(()=>{
998
+ this.setPersistedProperty(PostHogPersistedProperty.FeatureFlagDetails, flagsResponse);
999
+ var _flagsResponse_flags;
1000
+ this._events.emit('featureflags', getFlagValuesFromFlags(null != (_flagsResponse_flags = null == flagsResponse ? void 0 : flagsResponse.flags) ? _flagsResponse_flags : {}));
1001
+ });
1002
+ }
1003
+ getKnownFeatureFlagDetails() {
1004
+ const storedDetails = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlagDetails);
1005
+ if (!storedDetails) {
1006
+ const featureFlags = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags);
1007
+ const featureFlagPayloads = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlagPayloads);
1008
+ if (void 0 === featureFlags && void 0 === featureFlagPayloads) return;
1009
+ return createFlagsResponseFromFlagsAndPayloads(null != featureFlags ? featureFlags : {}, null != featureFlagPayloads ? featureFlagPayloads : {});
1010
+ }
1011
+ return normalizeFlagsResponse(storedDetails);
1012
+ }
1013
+ getKnownFeatureFlags() {
1014
+ const featureFlagDetails = this.getKnownFeatureFlagDetails();
1015
+ if (!featureFlagDetails) return;
1016
+ return getFlagValuesFromFlags(featureFlagDetails.flags);
1017
+ }
1018
+ getKnownFeatureFlagPayloads() {
1019
+ const featureFlagDetails = this.getKnownFeatureFlagDetails();
1020
+ if (!featureFlagDetails) return;
1021
+ return getPayloadsFromFlags(featureFlagDetails.flags);
1022
+ }
1023
+ getBootstrappedFeatureFlagDetails() {
1024
+ const details = this.getPersistedProperty(PostHogPersistedProperty.BootstrapFeatureFlagDetails);
1025
+ if (!details) return;
1026
+ return details;
1027
+ }
1028
+ setBootstrappedFeatureFlagDetails(details) {
1029
+ this.setPersistedProperty(PostHogPersistedProperty.BootstrapFeatureFlagDetails, details);
1030
+ }
1031
+ getBootstrappedFeatureFlags() {
1032
+ const details = this.getBootstrappedFeatureFlagDetails();
1033
+ if (!details) return;
1034
+ return getFlagValuesFromFlags(details.flags);
1035
+ }
1036
+ getBootstrappedFeatureFlagPayloads() {
1037
+ const details = this.getBootstrappedFeatureFlagDetails();
1038
+ if (!details) return;
1039
+ return getPayloadsFromFlags(details.flags);
1040
+ }
1041
+ getFeatureFlag(key) {
1042
+ const details = this.getFeatureFlagDetails();
1043
+ if (!details) return;
1044
+ const featureFlag = details.flags[key];
1045
+ let response = getFeatureFlagValue(featureFlag);
1046
+ if (void 0 === response) response = false;
1047
+ if (this.sendFeatureFlagEvent && !this.flagCallReported[key]) {
1048
+ var _this_getBootstrappedFeatureFlags, _this_getBootstrappedFeatureFlagPayloads, _featureFlag_metadata, _featureFlag_metadata1, _featureFlag_reason, _featureFlag_reason1;
1049
+ const bootstrappedResponse = null == (_this_getBootstrappedFeatureFlags = this.getBootstrappedFeatureFlags()) ? void 0 : _this_getBootstrappedFeatureFlags[key];
1050
+ const bootstrappedPayload = null == (_this_getBootstrappedFeatureFlagPayloads = this.getBootstrappedFeatureFlagPayloads()) ? void 0 : _this_getBootstrappedFeatureFlagPayloads[key];
1051
+ this.flagCallReported[key] = true;
1052
+ var _featureFlag_reason_description;
1053
+ this.capture('$feature_flag_called', {
1054
+ $feature_flag: key,
1055
+ $feature_flag_response: response,
1056
+ ...maybeAdd('$feature_flag_id', null == featureFlag ? void 0 : null == (_featureFlag_metadata = featureFlag.metadata) ? void 0 : _featureFlag_metadata.id),
1057
+ ...maybeAdd('$feature_flag_version', null == featureFlag ? void 0 : null == (_featureFlag_metadata1 = featureFlag.metadata) ? void 0 : _featureFlag_metadata1.version),
1058
+ ...maybeAdd('$feature_flag_reason', null != (_featureFlag_reason_description = null == featureFlag ? void 0 : null == (_featureFlag_reason = featureFlag.reason) ? void 0 : _featureFlag_reason.description) ? _featureFlag_reason_description : null == featureFlag ? void 0 : null == (_featureFlag_reason1 = featureFlag.reason) ? void 0 : _featureFlag_reason1.code),
1059
+ ...maybeAdd('$feature_flag_bootstrapped_response', bootstrappedResponse),
1060
+ ...maybeAdd('$feature_flag_bootstrapped_payload', bootstrappedPayload),
1061
+ $used_bootstrap_value: !this.getPersistedProperty(PostHogPersistedProperty.FlagsEndpointWasHit),
1062
+ ...maybeAdd('$feature_flag_request_id', details.requestId)
1063
+ });
1064
+ }
1065
+ return response;
1066
+ }
1067
+ getFeatureFlagPayload(key) {
1068
+ const payloads = this.getFeatureFlagPayloads();
1069
+ if (!payloads) return;
1070
+ const response = payloads[key];
1071
+ if (void 0 === response) return null;
1072
+ return response;
1073
+ }
1074
+ getFeatureFlagPayloads() {
1075
+ var _this_getFeatureFlagDetails;
1076
+ return null == (_this_getFeatureFlagDetails = this.getFeatureFlagDetails()) ? void 0 : _this_getFeatureFlagDetails.featureFlagPayloads;
1077
+ }
1078
+ getFeatureFlags() {
1079
+ var _this_getFeatureFlagDetails;
1080
+ return null == (_this_getFeatureFlagDetails = this.getFeatureFlagDetails()) ? void 0 : _this_getFeatureFlagDetails.featureFlags;
1081
+ }
1082
+ getFeatureFlagDetails() {
1083
+ let details = this.getKnownFeatureFlagDetails();
1084
+ const overriddenFlags = this.getPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags);
1085
+ if (!overriddenFlags) return details;
1086
+ details = null != details ? details : {
1087
+ featureFlags: {},
1088
+ featureFlagPayloads: {},
1089
+ flags: {}
1090
+ };
1091
+ var _details_flags;
1092
+ const flags = null != (_details_flags = details.flags) ? _details_flags : {};
1093
+ for(const key in overriddenFlags)if (overriddenFlags[key]) flags[key] = updateFlagValue(flags[key], overriddenFlags[key]);
1094
+ else delete flags[key];
1095
+ const result = {
1096
+ ...details,
1097
+ flags
1098
+ };
1099
+ return normalizeFlagsResponse(result);
1100
+ }
1101
+ getFeatureFlagsAndPayloads() {
1102
+ const flags = this.getFeatureFlags();
1103
+ const payloads = this.getFeatureFlagPayloads();
1104
+ return {
1105
+ flags,
1106
+ payloads
1107
+ };
1108
+ }
1109
+ isFeatureEnabled(key) {
1110
+ const response = this.getFeatureFlag(key);
1111
+ if (void 0 === response) return;
1112
+ return !!response;
1113
+ }
1114
+ reloadFeatureFlags(options) {
1115
+ this.flagsAsync(true).then((res)=>{
1116
+ var _options_cb;
1117
+ null == options || null == (_options_cb = options.cb) || _options_cb.call(options, void 0, null == res ? void 0 : res.featureFlags);
1118
+ }).catch((e)=>{
1119
+ var _options_cb;
1120
+ null == options || null == (_options_cb = options.cb) || _options_cb.call(options, e, void 0);
1121
+ if (!(null == options ? void 0 : options.cb)) this.logMsgIfDebug(()=>console.log('PostHog Debug', 'Error reloading feature flags', e));
1122
+ });
1123
+ }
1124
+ async reloadRemoteConfigAsync() {
1125
+ return await this.remoteConfigAsync();
1126
+ }
1127
+ async reloadFeatureFlagsAsync(sendAnonDistinctId) {
1128
+ var _this;
1129
+ return null == (_this = await this.flagsAsync(null != sendAnonDistinctId ? sendAnonDistinctId : true)) ? void 0 : _this.featureFlags;
1130
+ }
1131
+ onFeatureFlags(cb) {
1132
+ return this.on('featureflags', async ()=>{
1133
+ const flags = this.getFeatureFlags();
1134
+ if (flags) cb(flags);
1135
+ });
1136
+ }
1137
+ onFeatureFlag(key, cb) {
1138
+ return this.on('featureflags', async ()=>{
1139
+ const flagResponse = this.getFeatureFlag(key);
1140
+ if (void 0 !== flagResponse) cb(flagResponse);
1141
+ });
1142
+ }
1143
+ async overrideFeatureFlag(flags) {
1144
+ this.wrap(()=>{
1145
+ if (null === flags) return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, null);
1146
+ return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, flags);
1147
+ });
1148
+ }
1149
+ captureException(error, additionalProperties) {
1150
+ const properties = {
1151
+ $exception_level: 'error',
1152
+ $exception_list: [
1153
+ {
1154
+ type: (0, __WEBPACK_EXTERNAL_MODULE__utils_mjs_25ece7d1__.isError)(error) ? error.name : 'Error',
1155
+ value: (0, __WEBPACK_EXTERNAL_MODULE__utils_mjs_25ece7d1__.isError)(error) ? error.message : error,
1156
+ mechanism: {
1157
+ handled: true,
1158
+ synthetic: false
1159
+ }
1160
+ }
1161
+ ],
1162
+ ...additionalProperties
1163
+ };
1164
+ properties.$exception_personURL = new URL(`/project/${this.apiKey}/person/${this.getDistinctId()}`, this.host).toString();
1165
+ this.capture('$exception', properties);
1166
+ }
1167
+ captureTraceFeedback(traceId, userFeedback) {
1168
+ this.capture('$ai_feedback', {
1169
+ $ai_feedback_text: userFeedback,
1170
+ $ai_trace_id: String(traceId)
1171
+ });
1172
+ }
1173
+ captureTraceMetric(traceId, metricName, metricValue) {
1174
+ this.capture('$ai_metric', {
1175
+ $ai_metric_name: metricName,
1176
+ $ai_metric_value: String(metricValue),
1177
+ $ai_trace_id: String(traceId)
1178
+ });
1179
+ }
1180
+ constructor(apiKey, options){
1181
+ var _options_disableGeoip;
1182
+ const disableGeoipOption = null != (_options_disableGeoip = null == options ? void 0 : options.disableGeoip) ? _options_disableGeoip : false;
1183
+ var _options_featureFlagsRequestTimeoutMs;
1184
+ const featureFlagsRequestTimeoutMs = null != (_options_featureFlagsRequestTimeoutMs = null == options ? void 0 : options.featureFlagsRequestTimeoutMs) ? _options_featureFlagsRequestTimeoutMs : 10000;
1185
+ super(apiKey, {
1186
+ ...options,
1187
+ disableGeoip: disableGeoipOption,
1188
+ featureFlagsRequestTimeoutMs
1189
+ }), this.flagCallReported = {}, this._sessionMaxLengthSeconds = 86400, this.sessionProps = {};
1190
+ var _options_sendFeatureFlagEvent;
1191
+ this.sendFeatureFlagEvent = null != (_options_sendFeatureFlagEvent = null == options ? void 0 : options.sendFeatureFlagEvent) ? _options_sendFeatureFlagEvent : true;
1192
+ var _options_sessionExpirationTimeSeconds;
1193
+ this._sessionExpirationTimeSeconds = null != (_options_sessionExpirationTimeSeconds = null == options ? void 0 : options.sessionExpirationTimeSeconds) ? _options_sessionExpirationTimeSeconds : 1800;
1194
+ }
1195
+ }
1196
+ var __webpack_exports__getFetch = __WEBPACK_EXTERNAL_MODULE__utils_mjs_25ece7d1__.getFetch;
1197
+ var __webpack_exports__safeSetTimeout = __WEBPACK_EXTERNAL_MODULE__utils_mjs_25ece7d1__.safeSetTimeout;
1198
+ export { PostHogCore, PostHogCoreStateless, getFeatureFlagValue, logFlushError, maybeAdd, __WEBPACK_EXTERNAL_MODULE__utils_mjs_25ece7d1__ as utils, __webpack_exports__getFetch as getFetch, __webpack_exports__safeSetTimeout as safeSetTimeout };