@posthog/core 1.1.0 → 1.2.1

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 (128) hide show
  1. package/dist/error-tracking/chunk-ids.js +1 -1
  2. package/dist/error-tracking/chunk-ids.mjs +1 -1
  3. package/dist/error-tracking/coercers/error-event-coercer.js +4 -5
  4. package/dist/error-tracking/coercers/error-event-coercer.mjs +4 -5
  5. package/dist/error-tracking/coercers/event-coercer.js +1 -2
  6. package/dist/error-tracking/coercers/event-coercer.mjs +1 -2
  7. package/dist/error-tracking/coercers/object-coercer.js +1 -2
  8. package/dist/error-tracking/coercers/object-coercer.mjs +1 -2
  9. package/dist/error-tracking/coercers/primitive-coercer.js +1 -2
  10. package/dist/error-tracking/coercers/primitive-coercer.mjs +1 -2
  11. package/dist/error-tracking/coercers/promise-rejection-event.js +4 -5
  12. package/dist/error-tracking/coercers/promise-rejection-event.mjs +4 -5
  13. package/dist/error-tracking/coercers/string-coercer.js +3 -4
  14. package/dist/error-tracking/coercers/string-coercer.mjs +3 -4
  15. package/dist/error-tracking/coercers/utils.js +2 -4
  16. package/dist/error-tracking/coercers/utils.mjs +2 -4
  17. package/dist/error-tracking/error-properties-builder.d.ts +6 -6
  18. package/dist/error-tracking/error-properties-builder.d.ts.map +1 -1
  19. package/dist/error-tracking/error-properties-builder.js +17 -27
  20. package/dist/error-tracking/error-properties-builder.mjs +16 -26
  21. package/dist/error-tracking/parsers/index.js +2 -4
  22. package/dist/error-tracking/parsers/index.mjs +2 -4
  23. package/dist/error-tracking/parsers/node.js +3 -5
  24. package/dist/error-tracking/parsers/node.mjs +3 -5
  25. package/dist/error-tracking/utils.js +4 -4
  26. package/dist/error-tracking/utils.mjs +4 -4
  27. package/dist/eventemitter.js +4 -4
  28. package/dist/eventemitter.mjs +4 -4
  29. package/dist/featureFlagUtils.js +20 -45
  30. package/dist/featureFlagUtils.mjs +20 -45
  31. package/dist/gzip.js +1 -2
  32. package/dist/gzip.mjs +1 -2
  33. package/dist/index.d.ts +4 -366
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +54 -1225
  36. package/dist/index.mjs +5 -1190
  37. package/dist/posthog-core-stateless.d.ts +204 -0
  38. package/dist/posthog-core-stateless.d.ts.map +1 -0
  39. package/dist/posthog-core-stateless.js +675 -0
  40. package/dist/posthog-core-stateless.mjs +632 -0
  41. package/dist/posthog-core.d.ts +171 -0
  42. package/dist/posthog-core.d.ts.map +1 -0
  43. package/dist/posthog-core.js +554 -0
  44. package/dist/posthog-core.mjs +520 -0
  45. package/dist/testing/PostHogCoreTestClient.d.ts +2 -1
  46. package/dist/testing/PostHogCoreTestClient.d.ts.map +1 -1
  47. package/dist/testing/PostHogCoreTestClient.js +9 -11
  48. package/dist/testing/PostHogCoreTestClient.mjs +8 -10
  49. package/dist/testing/test-utils.js +1 -1
  50. package/dist/testing/test-utils.mjs +1 -1
  51. package/dist/utils/bucketed-rate-limiter.js +8 -12
  52. package/dist/utils/bucketed-rate-limiter.mjs +8 -12
  53. package/dist/utils/index.js +3 -3
  54. package/dist/utils/index.mjs +3 -3
  55. package/dist/utils/type-utils.js +1 -1
  56. package/dist/utils/type-utils.mjs +1 -1
  57. package/dist/vendor/uuidv7.js +12 -16
  58. package/dist/vendor/uuidv7.mjs +12 -16
  59. package/package.json +3 -2
  60. package/src/__tests__/featureFlagUtils.spec.ts +427 -0
  61. package/src/__tests__/gzip.spec.ts +69 -0
  62. package/src/__tests__/posthog.ai.spec.ts +110 -0
  63. package/src/__tests__/posthog.capture.spec.ts +91 -0
  64. package/src/__tests__/posthog.core.spec.ts +135 -0
  65. package/src/__tests__/posthog.debug.spec.ts +36 -0
  66. package/src/__tests__/posthog.enqueue.spec.ts +93 -0
  67. package/src/__tests__/posthog.featureflags.spec.ts +1106 -0
  68. package/src/__tests__/posthog.featureflags.v1.spec.ts +922 -0
  69. package/src/__tests__/posthog.flush.spec.ts +237 -0
  70. package/src/__tests__/posthog.gdpr.spec.ts +50 -0
  71. package/src/__tests__/posthog.groups.spec.ts +96 -0
  72. package/src/__tests__/posthog.identify.spec.ts +194 -0
  73. package/src/__tests__/posthog.init.spec.ts +110 -0
  74. package/src/__tests__/posthog.listeners.spec.ts +51 -0
  75. package/src/__tests__/posthog.register.spec.ts +47 -0
  76. package/src/__tests__/posthog.reset.spec.ts +76 -0
  77. package/src/__tests__/posthog.sessions.spec.ts +63 -0
  78. package/src/__tests__/posthog.setProperties.spec.ts +102 -0
  79. package/src/__tests__/posthog.shutdown.spec.ts +88 -0
  80. package/src/__tests__/utils.spec.ts +36 -0
  81. package/src/error-tracking/chunk-ids.ts +58 -0
  82. package/src/error-tracking/coercers/dom-exception-coercer.ts +38 -0
  83. package/src/error-tracking/coercers/error-coercer.ts +36 -0
  84. package/src/error-tracking/coercers/error-event-coercer.ts +24 -0
  85. package/src/error-tracking/coercers/event-coercer.ts +19 -0
  86. package/src/error-tracking/coercers/index.ts +8 -0
  87. package/src/error-tracking/coercers/object-coercer.ts +76 -0
  88. package/src/error-tracking/coercers/primitive-coercer.ts +19 -0
  89. package/src/error-tracking/coercers/promise-rejection-event.spec.ts +77 -0
  90. package/src/error-tracking/coercers/promise-rejection-event.ts +53 -0
  91. package/src/error-tracking/coercers/string-coercer.spec.ts +26 -0
  92. package/src/error-tracking/coercers/string-coercer.ts +31 -0
  93. package/src/error-tracking/coercers/utils.ts +33 -0
  94. package/src/error-tracking/error-properties-builder.coerce.spec.ts +202 -0
  95. package/src/error-tracking/error-properties-builder.parse.spec.ts +30 -0
  96. package/src/error-tracking/error-properties-builder.ts +167 -0
  97. package/src/error-tracking/index.ts +5 -0
  98. package/src/error-tracking/parsers/base.ts +29 -0
  99. package/src/error-tracking/parsers/chrome.ts +53 -0
  100. package/src/error-tracking/parsers/gecko.ts +38 -0
  101. package/src/error-tracking/parsers/index.ts +104 -0
  102. package/src/error-tracking/parsers/node.ts +111 -0
  103. package/src/error-tracking/parsers/opera.ts +18 -0
  104. package/src/error-tracking/parsers/react-native.ts +0 -0
  105. package/src/error-tracking/parsers/safari.ts +33 -0
  106. package/src/error-tracking/parsers/winjs.ts +12 -0
  107. package/src/error-tracking/types.ts +107 -0
  108. package/src/error-tracking/utils.ts +39 -0
  109. package/src/eventemitter.ts +27 -0
  110. package/src/featureFlagUtils.ts +192 -0
  111. package/src/gzip.ts +29 -0
  112. package/src/index.ts +8 -0
  113. package/src/posthog-core-stateless.ts +1226 -0
  114. package/src/posthog-core.ts +958 -0
  115. package/src/testing/PostHogCoreTestClient.ts +91 -0
  116. package/src/testing/index.ts +2 -0
  117. package/src/testing/test-utils.ts +47 -0
  118. package/src/types.ts +544 -0
  119. package/src/utils/bucketed-rate-limiter.spec.ts +33 -0
  120. package/src/utils/bucketed-rate-limiter.ts +85 -0
  121. package/src/utils/index.ts +98 -0
  122. package/src/utils/number-utils.spec.ts +89 -0
  123. package/src/utils/number-utils.ts +30 -0
  124. package/src/utils/promise-queue.spec.ts +55 -0
  125. package/src/utils/promise-queue.ts +30 -0
  126. package/src/utils/string-utils.ts +23 -0
  127. package/src/utils/type-utils.ts +134 -0
  128. package/src/vendor/uuidv7.ts +479 -0
@@ -0,0 +1,675 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, definition)=>{
5
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
6
+ enumerable: true,
7
+ get: definition[key]
8
+ });
9
+ };
10
+ })();
11
+ (()=>{
12
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
13
+ })();
14
+ (()=>{
15
+ __webpack_require__.r = (exports1)=>{
16
+ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
17
+ value: 'Module'
18
+ });
19
+ Object.defineProperty(exports1, '__esModule', {
20
+ value: true
21
+ });
22
+ };
23
+ })();
24
+ var __webpack_exports__ = {};
25
+ __webpack_require__.r(__webpack_exports__);
26
+ __webpack_require__.d(__webpack_exports__, {
27
+ maybeAdd: ()=>maybeAdd,
28
+ logFlushError: ()=>logFlushError,
29
+ PostHogCoreStateless: ()=>PostHogCoreStateless,
30
+ QuotaLimitedFeature: ()=>posthog_core_stateless_QuotaLimitedFeature
31
+ });
32
+ const external_eventemitter_js_namespaceObject = require("./eventemitter.js");
33
+ const external_featureFlagUtils_js_namespaceObject = require("./featureFlagUtils.js");
34
+ const external_gzip_js_namespaceObject = require("./gzip.js");
35
+ const external_types_js_namespaceObject = require("./types.js");
36
+ const index_js_namespaceObject = require("./utils/index.js");
37
+ const uuidv7_js_namespaceObject = require("./vendor/uuidv7.js");
38
+ class PostHogFetchHttpError extends Error {
39
+ constructor(response, reqByteLength){
40
+ super('HTTP error while fetching PostHog: status=' + response.status + ', reqByteLength=' + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.name = 'PostHogFetchHttpError';
41
+ }
42
+ get status() {
43
+ return this.response.status;
44
+ }
45
+ get text() {
46
+ return this.response.text();
47
+ }
48
+ get json() {
49
+ return this.response.json();
50
+ }
51
+ }
52
+ class PostHogFetchNetworkError extends Error {
53
+ constructor(error){
54
+ super('Network error while fetching PostHog', error instanceof Error ? {
55
+ cause: error
56
+ } : {}), this.error = error, this.name = 'PostHogFetchNetworkError';
57
+ }
58
+ }
59
+ const maybeAdd = (key, value)=>void 0 !== value ? {
60
+ [key]: value
61
+ } : {};
62
+ async function logFlushError(err) {
63
+ if (err instanceof PostHogFetchHttpError) {
64
+ let text = '';
65
+ try {
66
+ text = await err.text;
67
+ } catch {}
68
+ console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err);
69
+ } else console.error('Error while flushing PostHog', err);
70
+ return Promise.resolve();
71
+ }
72
+ function isPostHogFetchError(err) {
73
+ return 'object' == typeof err && (err instanceof PostHogFetchHttpError || err instanceof PostHogFetchNetworkError);
74
+ }
75
+ function isPostHogFetchContentTooLargeError(err) {
76
+ return 'object' == typeof err && err instanceof PostHogFetchHttpError && 413 === err.status;
77
+ }
78
+ var posthog_core_stateless_QuotaLimitedFeature = /*#__PURE__*/ function(QuotaLimitedFeature) {
79
+ QuotaLimitedFeature["FeatureFlags"] = "feature_flags";
80
+ QuotaLimitedFeature["Recordings"] = "recordings";
81
+ return QuotaLimitedFeature;
82
+ }({});
83
+ class PostHogCoreStateless {
84
+ constructor(apiKey, options){
85
+ this.flushPromise = null;
86
+ this.shutdownPromise = null;
87
+ this.promiseQueue = new index_js_namespaceObject.PromiseQueue();
88
+ this._events = new external_eventemitter_js_namespaceObject.SimpleEventEmitter();
89
+ this._isInitialized = false;
90
+ (0, index_js_namespaceObject.assert)(apiKey, "You must pass your PostHog project's api key.");
91
+ this.apiKey = apiKey;
92
+ this.host = (0, index_js_namespaceObject.removeTrailingSlash)(options?.host || 'https://us.i.posthog.com');
93
+ this.flushAt = options?.flushAt ? Math.max(options?.flushAt, 1) : 20;
94
+ this.maxBatchSize = Math.max(this.flushAt, options?.maxBatchSize ?? 100);
95
+ this.maxQueueSize = Math.max(this.flushAt, options?.maxQueueSize ?? 1000);
96
+ this.flushInterval = options?.flushInterval ?? 10000;
97
+ this.preloadFeatureFlags = options?.preloadFeatureFlags ?? true;
98
+ this.defaultOptIn = options?.defaultOptIn ?? true;
99
+ this.disableSurveys = options?.disableSurveys ?? false;
100
+ this._retryOptions = {
101
+ retryCount: options?.fetchRetryCount ?? 3,
102
+ retryDelay: options?.fetchRetryDelay ?? 3000,
103
+ retryCheck: isPostHogFetchError
104
+ };
105
+ this.requestTimeout = options?.requestTimeout ?? 10000;
106
+ this.featureFlagsRequestTimeoutMs = options?.featureFlagsRequestTimeoutMs ?? 3000;
107
+ this.remoteConfigRequestTimeoutMs = options?.remoteConfigRequestTimeoutMs ?? 3000;
108
+ this.disableGeoip = options?.disableGeoip ?? true;
109
+ this.disabled = options?.disabled ?? false;
110
+ this.historicalMigration = options?.historicalMigration ?? false;
111
+ this._initPromise = Promise.resolve();
112
+ this._isInitialized = true;
113
+ this.disableCompression = !(0, external_gzip_js_namespaceObject.isGzipSupported)() || (options?.disableCompression ?? false);
114
+ }
115
+ logMsgIfDebug(fn) {
116
+ if (this.isDebug) fn();
117
+ }
118
+ wrap(fn) {
119
+ if (this.disabled) return void this.logMsgIfDebug(()=>console.warn('[PostHog] The client is disabled'));
120
+ if (this._isInitialized) return fn();
121
+ this._initPromise.then(()=>fn());
122
+ }
123
+ getCommonEventProperties() {
124
+ return {
125
+ $lib: this.getLibraryId(),
126
+ $lib_version: this.getLibraryVersion()
127
+ };
128
+ }
129
+ get optedOut() {
130
+ return this.getPersistedProperty(external_types_js_namespaceObject.PostHogPersistedProperty.OptedOut) ?? !this.defaultOptIn;
131
+ }
132
+ async optIn() {
133
+ this.wrap(()=>{
134
+ this.setPersistedProperty(external_types_js_namespaceObject.PostHogPersistedProperty.OptedOut, false);
135
+ });
136
+ }
137
+ async optOut() {
138
+ this.wrap(()=>{
139
+ this.setPersistedProperty(external_types_js_namespaceObject.PostHogPersistedProperty.OptedOut, true);
140
+ });
141
+ }
142
+ on(event, cb) {
143
+ return this._events.on(event, cb);
144
+ }
145
+ debug(enabled = true) {
146
+ this.removeDebugCallback?.();
147
+ if (enabled) {
148
+ const removeDebugCallback = this.on('*', (event, payload)=>console.log('PostHog Debug', event, payload));
149
+ this.removeDebugCallback = ()=>{
150
+ removeDebugCallback();
151
+ this.removeDebugCallback = void 0;
152
+ };
153
+ }
154
+ }
155
+ get isDebug() {
156
+ return !!this.removeDebugCallback;
157
+ }
158
+ get isDisabled() {
159
+ return this.disabled;
160
+ }
161
+ buildPayload(payload) {
162
+ return {
163
+ distinct_id: payload.distinct_id,
164
+ event: payload.event,
165
+ properties: {
166
+ ...payload.properties || {},
167
+ ...this.getCommonEventProperties()
168
+ }
169
+ };
170
+ }
171
+ addPendingPromise(promise) {
172
+ return this.promiseQueue.add(promise);
173
+ }
174
+ identifyStateless(distinctId, properties, options) {
175
+ this.wrap(()=>{
176
+ const payload = {
177
+ ...this.buildPayload({
178
+ distinct_id: distinctId,
179
+ event: '$identify',
180
+ properties
181
+ })
182
+ };
183
+ this.enqueue('identify', payload, options);
184
+ });
185
+ }
186
+ async identifyStatelessImmediate(distinctId, properties, options) {
187
+ const payload = {
188
+ ...this.buildPayload({
189
+ distinct_id: distinctId,
190
+ event: '$identify',
191
+ properties
192
+ })
193
+ };
194
+ await this.sendImmediate('identify', payload, options);
195
+ }
196
+ captureStateless(distinctId, event, properties, options) {
197
+ this.wrap(()=>{
198
+ const payload = this.buildPayload({
199
+ distinct_id: distinctId,
200
+ event,
201
+ properties
202
+ });
203
+ this.enqueue('capture', payload, options);
204
+ });
205
+ }
206
+ async captureStatelessImmediate(distinctId, event, properties, options) {
207
+ const payload = this.buildPayload({
208
+ distinct_id: distinctId,
209
+ event,
210
+ properties
211
+ });
212
+ await this.sendImmediate('capture', payload, options);
213
+ }
214
+ aliasStateless(alias, distinctId, properties, options) {
215
+ this.wrap(()=>{
216
+ const payload = this.buildPayload({
217
+ event: '$create_alias',
218
+ distinct_id: distinctId,
219
+ properties: {
220
+ ...properties || {},
221
+ distinct_id: distinctId,
222
+ alias
223
+ }
224
+ });
225
+ this.enqueue('alias', payload, options);
226
+ });
227
+ }
228
+ async aliasStatelessImmediate(alias, distinctId, properties, options) {
229
+ const payload = this.buildPayload({
230
+ event: '$create_alias',
231
+ distinct_id: distinctId,
232
+ properties: {
233
+ ...properties || {},
234
+ distinct_id: distinctId,
235
+ alias
236
+ }
237
+ });
238
+ await this.sendImmediate('alias', payload, options);
239
+ }
240
+ groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
241
+ this.wrap(()=>{
242
+ const payload = this.buildPayload({
243
+ distinct_id: distinctId || `$${groupType}_${groupKey}`,
244
+ event: '$groupidentify',
245
+ properties: {
246
+ $group_type: groupType,
247
+ $group_key: groupKey,
248
+ $group_set: groupProperties || {},
249
+ ...eventProperties || {}
250
+ }
251
+ });
252
+ this.enqueue('capture', payload, options);
253
+ });
254
+ }
255
+ async getRemoteConfig() {
256
+ await this._initPromise;
257
+ let host = this.host;
258
+ if ('https://us.i.posthog.com' === host) host = 'https://us-assets.i.posthog.com';
259
+ else if ('https://eu.i.posthog.com' === host) host = 'https://eu-assets.i.posthog.com';
260
+ const url = `${host}/array/${this.apiKey}/config`;
261
+ const fetchOptions = {
262
+ method: 'GET',
263
+ headers: {
264
+ ...this.getCustomHeaders(),
265
+ 'Content-Type': 'application/json'
266
+ }
267
+ };
268
+ return this.fetchWithRetry(url, fetchOptions, {
269
+ retryCount: 0
270
+ }, this.remoteConfigRequestTimeoutMs).then((response)=>response.json()).catch((error)=>{
271
+ this.logMsgIfDebug(()=>console.error('Remote config could not be loaded', error));
272
+ this._events.emit('error', error);
273
+ });
274
+ }
275
+ async getFlags(distinctId, groups = {}, personProperties = {}, groupProperties = {}, extraPayload = {}) {
276
+ await this._initPromise;
277
+ const url = `${this.host}/flags/?v=2&config=true`;
278
+ const fetchOptions = {
279
+ method: 'POST',
280
+ headers: {
281
+ ...this.getCustomHeaders(),
282
+ 'Content-Type': 'application/json'
283
+ },
284
+ body: JSON.stringify({
285
+ token: this.apiKey,
286
+ distinct_id: distinctId,
287
+ groups,
288
+ person_properties: personProperties,
289
+ group_properties: groupProperties,
290
+ ...extraPayload
291
+ })
292
+ };
293
+ this.logMsgIfDebug(()=>console.log('PostHog Debug', 'Flags URL', url));
294
+ return this.fetchWithRetry(url, fetchOptions, {
295
+ retryCount: 0
296
+ }, this.featureFlagsRequestTimeoutMs).then((response)=>response.json()).then((response)=>(0, external_featureFlagUtils_js_namespaceObject.normalizeFlagsResponse)(response)).catch((error)=>{
297
+ this._events.emit('error', error);
298
+ });
299
+ }
300
+ async getFeatureFlagStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
301
+ await this._initPromise;
302
+ const flagDetailResponse = await this.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
303
+ if (void 0 === flagDetailResponse) return {
304
+ response: void 0,
305
+ requestId: void 0
306
+ };
307
+ let response = (0, external_featureFlagUtils_js_namespaceObject.getFeatureFlagValue)(flagDetailResponse.response);
308
+ if (void 0 === response) response = false;
309
+ return {
310
+ response,
311
+ requestId: flagDetailResponse.requestId
312
+ };
313
+ }
314
+ async getFeatureFlagDetailStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
315
+ await this._initPromise;
316
+ const flagsResponse = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [
317
+ key
318
+ ]);
319
+ if (void 0 === flagsResponse) return;
320
+ const featureFlags = flagsResponse.flags;
321
+ const flagDetail = featureFlags[key];
322
+ return {
323
+ response: flagDetail,
324
+ requestId: flagsResponse.requestId
325
+ };
326
+ }
327
+ async getFeatureFlagPayloadStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
328
+ await this._initPromise;
329
+ const payloads = await this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [
330
+ key
331
+ ]);
332
+ if (!payloads) return;
333
+ const response = payloads[key];
334
+ if (void 0 === response) return null;
335
+ return response;
336
+ }
337
+ async getFeatureFlagPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
338
+ await this._initPromise;
339
+ const payloads = (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate)).payloads;
340
+ return payloads;
341
+ }
342
+ async getFeatureFlagsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
343
+ await this._initPromise;
344
+ return await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
345
+ }
346
+ async getFeatureFlagsAndPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
347
+ await this._initPromise;
348
+ const featureFlagDetails = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
349
+ if (!featureFlagDetails) return {
350
+ flags: void 0,
351
+ payloads: void 0,
352
+ requestId: void 0
353
+ };
354
+ return {
355
+ flags: featureFlagDetails.featureFlags,
356
+ payloads: featureFlagDetails.featureFlagPayloads,
357
+ requestId: featureFlagDetails.requestId
358
+ };
359
+ }
360
+ async getFeatureFlagDetailsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
361
+ await this._initPromise;
362
+ const extraPayload = {};
363
+ if (disableGeoip ?? this.disableGeoip) extraPayload['geoip_disable'] = true;
364
+ if (flagKeysToEvaluate) extraPayload['flag_keys_to_evaluate'] = flagKeysToEvaluate;
365
+ const flagsResponse = await this.getFlags(distinctId, groups, personProperties, groupProperties, extraPayload);
366
+ if (void 0 === flagsResponse) return;
367
+ 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');
368
+ if (flagsResponse.quotaLimited?.includes("feature_flags")) {
369
+ 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');
370
+ return {
371
+ flags: {},
372
+ featureFlags: {},
373
+ featureFlagPayloads: {},
374
+ requestId: flagsResponse?.requestId
375
+ };
376
+ }
377
+ return flagsResponse;
378
+ }
379
+ async getSurveysStateless() {
380
+ await this._initPromise;
381
+ if (true === this.disableSurveys) {
382
+ this.logMsgIfDebug(()=>console.log('PostHog Debug', 'Loading surveys is disabled.'));
383
+ return [];
384
+ }
385
+ const url = `${this.host}/api/surveys/?token=${this.apiKey}`;
386
+ const fetchOptions = {
387
+ method: 'GET',
388
+ headers: {
389
+ ...this.getCustomHeaders(),
390
+ 'Content-Type': 'application/json'
391
+ }
392
+ };
393
+ const response = await this.fetchWithRetry(url, fetchOptions).then((response)=>{
394
+ if (200 !== response.status || !response.json) {
395
+ const msg = `Surveys API could not be loaded: ${response.status}`;
396
+ const error = new Error(msg);
397
+ this.logMsgIfDebug(()=>console.error(error));
398
+ this._events.emit('error', new Error(msg));
399
+ return;
400
+ }
401
+ return response.json();
402
+ }).catch((error)=>{
403
+ this.logMsgIfDebug(()=>console.error('Surveys API could not be loaded', error));
404
+ this._events.emit('error', error);
405
+ });
406
+ const newSurveys = response?.surveys;
407
+ if (newSurveys) this.logMsgIfDebug(()=>console.log('PostHog Debug', 'Surveys fetched from API: ', JSON.stringify(newSurveys)));
408
+ return newSurveys ?? [];
409
+ }
410
+ get props() {
411
+ if (!this._props) this._props = this.getPersistedProperty(external_types_js_namespaceObject.PostHogPersistedProperty.Props);
412
+ return this._props || {};
413
+ }
414
+ set props(val) {
415
+ this._props = val;
416
+ }
417
+ async register(properties) {
418
+ this.wrap(()=>{
419
+ this.props = {
420
+ ...this.props,
421
+ ...properties
422
+ };
423
+ this.setPersistedProperty(external_types_js_namespaceObject.PostHogPersistedProperty.Props, this.props);
424
+ });
425
+ }
426
+ async unregister(property) {
427
+ this.wrap(()=>{
428
+ delete this.props[property];
429
+ this.setPersistedProperty(external_types_js_namespaceObject.PostHogPersistedProperty.Props, this.props);
430
+ });
431
+ }
432
+ enqueue(type, _message, options) {
433
+ this.wrap(()=>{
434
+ if (this.optedOut) return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
435
+ const message = this.prepareMessage(type, _message, options);
436
+ const queue = this.getPersistedProperty(external_types_js_namespaceObject.PostHogPersistedProperty.Queue) || [];
437
+ if (queue.length >= this.maxQueueSize) {
438
+ queue.shift();
439
+ this.logMsgIfDebug(()=>console.info('Queue is full, the oldest event is dropped.'));
440
+ }
441
+ queue.push({
442
+ message
443
+ });
444
+ this.setPersistedProperty(external_types_js_namespaceObject.PostHogPersistedProperty.Queue, queue);
445
+ this._events.emit(type, message);
446
+ if (queue.length >= this.flushAt) this.flushBackground();
447
+ if (this.flushInterval && !this._flushTimer) this._flushTimer = (0, index_js_namespaceObject.safeSetTimeout)(()=>this.flushBackground(), this.flushInterval);
448
+ });
449
+ }
450
+ async sendImmediate(type, _message, options) {
451
+ if (this.disabled) return void this.logMsgIfDebug(()=>console.warn('[PostHog] The client is disabled'));
452
+ if (!this._isInitialized) await this._initPromise;
453
+ if (this.optedOut) return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
454
+ const data = {
455
+ api_key: this.apiKey,
456
+ batch: [
457
+ this.prepareMessage(type, _message, options)
458
+ ],
459
+ sent_at: (0, index_js_namespaceObject.currentISOTime)()
460
+ };
461
+ if (this.historicalMigration) data.historical_migration = true;
462
+ const payload = JSON.stringify(data);
463
+ const url = `${this.host}/batch/`;
464
+ const gzippedPayload = this.disableCompression ? null : await (0, external_gzip_js_namespaceObject.gzipCompress)(payload, this.isDebug);
465
+ const fetchOptions = {
466
+ method: 'POST',
467
+ headers: {
468
+ ...this.getCustomHeaders(),
469
+ 'Content-Type': 'application/json',
470
+ ...null !== gzippedPayload && {
471
+ 'Content-Encoding': 'gzip'
472
+ }
473
+ },
474
+ body: gzippedPayload || payload
475
+ };
476
+ try {
477
+ await this.fetchWithRetry(url, fetchOptions);
478
+ } catch (err) {
479
+ this._events.emit('error', err);
480
+ }
481
+ }
482
+ prepareMessage(type, _message, options) {
483
+ const message = {
484
+ ..._message,
485
+ type: type,
486
+ library: this.getLibraryId(),
487
+ library_version: this.getLibraryVersion(),
488
+ timestamp: options?.timestamp ? options?.timestamp : (0, index_js_namespaceObject.currentISOTime)(),
489
+ uuid: options?.uuid ? options.uuid : (0, uuidv7_js_namespaceObject.uuidv7)()
490
+ };
491
+ const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;
492
+ if (addGeoipDisableProperty) {
493
+ if (!message.properties) message.properties = {};
494
+ message['properties']['$geoip_disable'] = true;
495
+ }
496
+ if (message.distinctId) {
497
+ message.distinct_id = message.distinctId;
498
+ delete message.distinctId;
499
+ }
500
+ return message;
501
+ }
502
+ clearFlushTimer() {
503
+ if (this._flushTimer) {
504
+ clearTimeout(this._flushTimer);
505
+ this._flushTimer = void 0;
506
+ }
507
+ }
508
+ flushBackground() {
509
+ this.flush().catch(async (err)=>{
510
+ await logFlushError(err);
511
+ });
512
+ }
513
+ async flush() {
514
+ const nextFlushPromise = (0, index_js_namespaceObject.allSettled)([
515
+ this.flushPromise
516
+ ]).then(()=>this._flush());
517
+ this.flushPromise = nextFlushPromise;
518
+ this.addPendingPromise(nextFlushPromise);
519
+ (0, index_js_namespaceObject.allSettled)([
520
+ nextFlushPromise
521
+ ]).then(()=>{
522
+ if (this.flushPromise === nextFlushPromise) this.flushPromise = null;
523
+ });
524
+ return nextFlushPromise;
525
+ }
526
+ getCustomHeaders() {
527
+ const customUserAgent = this.getCustomUserAgent();
528
+ const headers = {};
529
+ if (customUserAgent && '' !== customUserAgent) headers['User-Agent'] = customUserAgent;
530
+ return headers;
531
+ }
532
+ async _flush() {
533
+ this.clearFlushTimer();
534
+ await this._initPromise;
535
+ let queue = this.getPersistedProperty(external_types_js_namespaceObject.PostHogPersistedProperty.Queue) || [];
536
+ if (!queue.length) return;
537
+ const sentMessages = [];
538
+ const originalQueueLength = queue.length;
539
+ while(queue.length > 0 && sentMessages.length < originalQueueLength){
540
+ const batchItems = queue.slice(0, this.maxBatchSize);
541
+ const batchMessages = batchItems.map((item)=>item.message);
542
+ const persistQueueChange = ()=>{
543
+ const refreshedQueue = this.getPersistedProperty(external_types_js_namespaceObject.PostHogPersistedProperty.Queue) || [];
544
+ const newQueue = refreshedQueue.slice(batchItems.length);
545
+ this.setPersistedProperty(external_types_js_namespaceObject.PostHogPersistedProperty.Queue, newQueue);
546
+ queue = newQueue;
547
+ };
548
+ const data = {
549
+ api_key: this.apiKey,
550
+ batch: batchMessages,
551
+ sent_at: (0, index_js_namespaceObject.currentISOTime)()
552
+ };
553
+ if (this.historicalMigration) data.historical_migration = true;
554
+ const payload = JSON.stringify(data);
555
+ const url = `${this.host}/batch/`;
556
+ const gzippedPayload = this.disableCompression ? null : await (0, external_gzip_js_namespaceObject.gzipCompress)(payload, this.isDebug);
557
+ const fetchOptions = {
558
+ method: 'POST',
559
+ headers: {
560
+ ...this.getCustomHeaders(),
561
+ 'Content-Type': 'application/json',
562
+ ...null !== gzippedPayload && {
563
+ 'Content-Encoding': 'gzip'
564
+ }
565
+ },
566
+ body: gzippedPayload || payload
567
+ };
568
+ const retryOptions = {
569
+ retryCheck: (err)=>{
570
+ if (isPostHogFetchContentTooLargeError(err)) return false;
571
+ return isPostHogFetchError(err);
572
+ }
573
+ };
574
+ try {
575
+ await this.fetchWithRetry(url, fetchOptions, retryOptions);
576
+ } catch (err) {
577
+ if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {
578
+ this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));
579
+ this.logMsgIfDebug(()=>console.warn(`Received 413 when sending batch of size ${batchMessages.length}, reducing batch size to ${this.maxBatchSize}`));
580
+ continue;
581
+ }
582
+ if (!(err instanceof PostHogFetchNetworkError)) persistQueueChange();
583
+ this._events.emit('error', err);
584
+ throw err;
585
+ }
586
+ persistQueueChange();
587
+ sentMessages.push(...batchMessages);
588
+ }
589
+ this._events.emit('flush', sentMessages);
590
+ }
591
+ async fetchWithRetry(url, options, retryOptions, requestTimeout) {
592
+ AbortSignal.timeout ??= function(ms) {
593
+ const ctrl = new AbortController();
594
+ setTimeout(()=>ctrl.abort(), ms);
595
+ return ctrl.signal;
596
+ };
597
+ const body = options.body ? options.body : '';
598
+ let reqByteLength = -1;
599
+ try {
600
+ reqByteLength = body instanceof Blob ? body.size : Buffer.byteLength(body, index_js_namespaceObject.STRING_FORMAT);
601
+ } catch {
602
+ if (body instanceof Blob) reqByteLength = body.size;
603
+ else {
604
+ const encoded = new TextEncoder().encode(body);
605
+ reqByteLength = encoded.length;
606
+ }
607
+ }
608
+ return await (0, index_js_namespaceObject.retriable)(async ()=>{
609
+ let res = null;
610
+ try {
611
+ res = await this.fetch(url, {
612
+ signal: AbortSignal.timeout(requestTimeout ?? this.requestTimeout),
613
+ ...options
614
+ });
615
+ } catch (e) {
616
+ throw new PostHogFetchNetworkError(e);
617
+ }
618
+ const isNoCors = 'no-cors' === options.mode;
619
+ if (!isNoCors && (res.status < 200 || res.status >= 400)) throw new PostHogFetchHttpError(res, reqByteLength);
620
+ return res;
621
+ }, {
622
+ ...this._retryOptions,
623
+ ...retryOptions
624
+ });
625
+ }
626
+ async _shutdown(shutdownTimeoutMs = 30000) {
627
+ await this._initPromise;
628
+ let hasTimedOut = false;
629
+ this.clearFlushTimer();
630
+ const doShutdown = async ()=>{
631
+ try {
632
+ await this.promiseQueue.join();
633
+ while(true){
634
+ const queue = this.getPersistedProperty(external_types_js_namespaceObject.PostHogPersistedProperty.Queue) || [];
635
+ if (0 === queue.length) break;
636
+ await this.flush();
637
+ if (hasTimedOut) break;
638
+ }
639
+ } catch (e) {
640
+ if (!isPostHogFetchError(e)) throw e;
641
+ await logFlushError(e);
642
+ }
643
+ };
644
+ return Promise.race([
645
+ new Promise((_, reject)=>{
646
+ (0, index_js_namespaceObject.safeSetTimeout)(()=>{
647
+ this.logMsgIfDebug(()=>console.error('Timed out while shutting down PostHog'));
648
+ hasTimedOut = true;
649
+ reject('Timeout while shutting down PostHog. Some events may not have been sent.');
650
+ }, shutdownTimeoutMs);
651
+ }),
652
+ doShutdown()
653
+ ]);
654
+ }
655
+ async shutdown(shutdownTimeoutMs = 30000) {
656
+ 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'));
657
+ else this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(()=>{
658
+ this.shutdownPromise = null;
659
+ });
660
+ return this.shutdownPromise;
661
+ }
662
+ }
663
+ exports.PostHogCoreStateless = __webpack_exports__.PostHogCoreStateless;
664
+ exports.QuotaLimitedFeature = __webpack_exports__.QuotaLimitedFeature;
665
+ exports.logFlushError = __webpack_exports__.logFlushError;
666
+ exports.maybeAdd = __webpack_exports__.maybeAdd;
667
+ for(var __webpack_i__ in __webpack_exports__)if (-1 === [
668
+ "PostHogCoreStateless",
669
+ "QuotaLimitedFeature",
670
+ "logFlushError",
671
+ "maybeAdd"
672
+ ].indexOf(__webpack_i__)) exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
673
+ Object.defineProperty(exports, '__esModule', {
674
+ value: true
675
+ });