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