autotel-subscribers 4.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 (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +669 -0
  3. package/dist/amplitude.cjs +2486 -0
  4. package/dist/amplitude.cjs.map +1 -0
  5. package/dist/amplitude.d.cts +49 -0
  6. package/dist/amplitude.d.ts +49 -0
  7. package/dist/amplitude.js +2463 -0
  8. package/dist/amplitude.js.map +1 -0
  9. package/dist/event-subscriber-base-CnF3V56W.d.cts +182 -0
  10. package/dist/event-subscriber-base-CnF3V56W.d.ts +182 -0
  11. package/dist/factories.cjs +16660 -0
  12. package/dist/factories.cjs.map +1 -0
  13. package/dist/factories.d.cts +304 -0
  14. package/dist/factories.d.ts +304 -0
  15. package/dist/factories.js +16624 -0
  16. package/dist/factories.js.map +1 -0
  17. package/dist/index.cjs +16575 -0
  18. package/dist/index.cjs.map +1 -0
  19. package/dist/index.d.cts +179 -0
  20. package/dist/index.d.ts +179 -0
  21. package/dist/index.js +16539 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/middleware.cjs +220 -0
  24. package/dist/middleware.cjs.map +1 -0
  25. package/dist/middleware.d.cts +227 -0
  26. package/dist/middleware.d.ts +227 -0
  27. package/dist/middleware.js +208 -0
  28. package/dist/middleware.js.map +1 -0
  29. package/dist/mixpanel.cjs +2940 -0
  30. package/dist/mixpanel.cjs.map +1 -0
  31. package/dist/mixpanel.d.cts +47 -0
  32. package/dist/mixpanel.d.ts +47 -0
  33. package/dist/mixpanel.js +2932 -0
  34. package/dist/mixpanel.js.map +1 -0
  35. package/dist/posthog.cjs +4115 -0
  36. package/dist/posthog.cjs.map +1 -0
  37. package/dist/posthog.d.cts +299 -0
  38. package/dist/posthog.d.ts +299 -0
  39. package/dist/posthog.js +4113 -0
  40. package/dist/posthog.js.map +1 -0
  41. package/dist/segment.cjs +6822 -0
  42. package/dist/segment.cjs.map +1 -0
  43. package/dist/segment.d.cts +49 -0
  44. package/dist/segment.d.ts +49 -0
  45. package/dist/segment.js +6794 -0
  46. package/dist/segment.js.map +1 -0
  47. package/dist/slack.cjs +368 -0
  48. package/dist/slack.cjs.map +1 -0
  49. package/dist/slack.d.cts +126 -0
  50. package/dist/slack.d.ts +126 -0
  51. package/dist/slack.js +366 -0
  52. package/dist/slack.js.map +1 -0
  53. package/dist/webhook.cjs +100 -0
  54. package/dist/webhook.cjs.map +1 -0
  55. package/dist/webhook.d.cts +53 -0
  56. package/dist/webhook.d.ts +53 -0
  57. package/dist/webhook.js +98 -0
  58. package/dist/webhook.js.map +1 -0
  59. package/examples/quickstart-custom-subscriber.ts +144 -0
  60. package/examples/subscriber-bigquery.ts +219 -0
  61. package/examples/subscriber-databricks.ts +280 -0
  62. package/examples/subscriber-kafka.ts +326 -0
  63. package/examples/subscriber-kinesis.ts +307 -0
  64. package/examples/subscriber-posthog.ts +421 -0
  65. package/examples/subscriber-pubsub.ts +336 -0
  66. package/examples/subscriber-snowflake.ts +232 -0
  67. package/package.json +141 -0
  68. package/src/amplitude.test.ts +231 -0
  69. package/src/amplitude.ts +148 -0
  70. package/src/event-subscriber-base.ts +325 -0
  71. package/src/factories.ts +197 -0
  72. package/src/index.ts +50 -0
  73. package/src/middleware.ts +489 -0
  74. package/src/mixpanel.test.ts +194 -0
  75. package/src/mixpanel.ts +134 -0
  76. package/src/mock-event-subscriber.ts +333 -0
  77. package/src/posthog.test.ts +629 -0
  78. package/src/posthog.ts +530 -0
  79. package/src/segment.test.ts +228 -0
  80. package/src/segment.ts +148 -0
  81. package/src/slack.ts +383 -0
  82. package/src/streaming-event-subscriber.ts +323 -0
  83. package/src/testing/index.ts +37 -0
  84. package/src/testing/mock-webhook-server.ts +242 -0
  85. package/src/testing/subscriber-test-harness.ts +365 -0
  86. package/src/webhook.test.ts +264 -0
  87. package/src/webhook.ts +158 -0
@@ -0,0 +1,4113 @@
1
+ import { dirname, posix, sep } from 'path';
2
+ import { createReadStream } from 'fs';
3
+ import { createInterface } from 'readline';
4
+
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __esm = (fn, res) => function __init() {
8
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
+ };
10
+ var __export = (target, all) => {
11
+ for (var name in all)
12
+ __defProp(target, name, { get: all[name], enumerable: true });
13
+ };
14
+ function createModulerModifier() {
15
+ const getModuleFromFileName = createGetModuleFromFilename();
16
+ return async (frames) => {
17
+ for (const frame of frames) frame.module = getModuleFromFileName(frame.filename);
18
+ return frames;
19
+ };
20
+ }
21
+ function createGetModuleFromFilename(basePath = process.argv[1] ? dirname(process.argv[1]) : process.cwd(), isWindows = "\\" === sep) {
22
+ const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath;
23
+ return (filename) => {
24
+ if (!filename) return;
25
+ const normalizedFilename = isWindows ? normalizeWindowsPath(filename) : filename;
26
+ let { dir, base: file, ext } = posix.parse(normalizedFilename);
27
+ if (".js" === ext || ".mjs" === ext || ".cjs" === ext) file = file.slice(0, -1 * ext.length);
28
+ const decodedFile = decodeURIComponent(file);
29
+ if (!dir) dir = ".";
30
+ const n = dir.lastIndexOf("/node_modules");
31
+ if (n > -1) return `${dir.slice(n + 14).replace(/\//g, ".")}:${decodedFile}`;
32
+ if (dir.startsWith(normalizedBase)) {
33
+ const moduleName = dir.slice(normalizedBase.length + 1).replace(/\//g, ".");
34
+ return moduleName ? `${moduleName}:${decodedFile}` : decodedFile;
35
+ }
36
+ return decodedFile;
37
+ };
38
+ }
39
+ function normalizeWindowsPath(path) {
40
+ return path.replace(/^[A-Z]:/, "").replace(/\\/g, "/");
41
+ }
42
+ var init_module_node = __esm({
43
+ "../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs"() {
44
+ }
45
+ });
46
+
47
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/featureFlagUtils.mjs
48
+ function getFlagDetailFromFlagAndPayload(key, value, payload) {
49
+ return {
50
+ key,
51
+ enabled: "string" == typeof value ? true : value,
52
+ variant: "string" == typeof value ? value : void 0,
53
+ reason: void 0,
54
+ metadata: {
55
+ id: void 0,
56
+ version: void 0,
57
+ payload: payload ? JSON.stringify(payload) : void 0,
58
+ description: void 0
59
+ }
60
+ };
61
+ }
62
+ var normalizeFlagsResponse, getFlagValuesFromFlags, getPayloadsFromFlags, getFeatureFlagValue, parsePayload;
63
+ var init_featureFlagUtils = __esm({
64
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/featureFlagUtils.mjs"() {
65
+ normalizeFlagsResponse = (flagsResponse) => {
66
+ if ("flags" in flagsResponse) {
67
+ const featureFlags = getFlagValuesFromFlags(flagsResponse.flags);
68
+ const featureFlagPayloads = getPayloadsFromFlags(flagsResponse.flags);
69
+ return {
70
+ ...flagsResponse,
71
+ featureFlags,
72
+ featureFlagPayloads
73
+ };
74
+ }
75
+ {
76
+ const featureFlags = flagsResponse.featureFlags ?? {};
77
+ const featureFlagPayloads = Object.fromEntries(Object.entries(flagsResponse.featureFlagPayloads || {}).map(([k, v]) => [
78
+ k,
79
+ parsePayload(v)
80
+ ]));
81
+ const flags = Object.fromEntries(Object.entries(featureFlags).map(([key, value]) => [
82
+ key,
83
+ getFlagDetailFromFlagAndPayload(key, value, featureFlagPayloads[key])
84
+ ]));
85
+ return {
86
+ ...flagsResponse,
87
+ featureFlags,
88
+ featureFlagPayloads,
89
+ flags
90
+ };
91
+ }
92
+ };
93
+ getFlagValuesFromFlags = (flags) => Object.fromEntries(Object.entries(flags ?? {}).map(([key, detail]) => [
94
+ key,
95
+ getFeatureFlagValue(detail)
96
+ ]).filter(([, value]) => void 0 !== value));
97
+ getPayloadsFromFlags = (flags) => {
98
+ const safeFlags = flags ?? {};
99
+ return Object.fromEntries(Object.keys(safeFlags).filter((flag) => {
100
+ const details = safeFlags[flag];
101
+ return details.enabled && details.metadata && void 0 !== details.metadata.payload;
102
+ }).map((flag) => {
103
+ const payload = safeFlags[flag].metadata?.payload;
104
+ return [
105
+ flag,
106
+ payload ? parsePayload(payload) : void 0
107
+ ];
108
+ }));
109
+ };
110
+ getFeatureFlagValue = (detail) => void 0 === detail ? void 0 : detail.variant ?? detail.enabled;
111
+ parsePayload = (response) => {
112
+ if ("string" != typeof response) return response;
113
+ try {
114
+ return JSON.parse(response);
115
+ } catch {
116
+ return response;
117
+ }
118
+ };
119
+ }
120
+ });
121
+
122
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/vendor/uuidv7.mjs
123
+ var DIGITS, UUID, V7Generator, getDefaultRandom, defaultGenerator, uuidv7, uuidv7obj;
124
+ var init_uuidv7 = __esm({
125
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/vendor/uuidv7.mjs"() {
126
+ DIGITS = "0123456789abcdef";
127
+ UUID = class _UUID {
128
+ constructor(bytes) {
129
+ this.bytes = bytes;
130
+ }
131
+ static ofInner(bytes) {
132
+ if (16 === bytes.length) return new _UUID(bytes);
133
+ throw new TypeError("not 128-bit length");
134
+ }
135
+ static fromFieldsV7(unixTsMs, randA, randBHi, randBLo) {
136
+ if (!Number.isInteger(unixTsMs) || !Number.isInteger(randA) || !Number.isInteger(randBHi) || !Number.isInteger(randBLo) || unixTsMs < 0 || randA < 0 || randBHi < 0 || randBLo < 0 || unixTsMs > 281474976710655 || randA > 4095 || randBHi > 1073741823 || randBLo > 4294967295) throw new RangeError("invalid field value");
137
+ const bytes = new Uint8Array(16);
138
+ bytes[0] = unixTsMs / 2 ** 40;
139
+ bytes[1] = unixTsMs / 2 ** 32;
140
+ bytes[2] = unixTsMs / 2 ** 24;
141
+ bytes[3] = unixTsMs / 2 ** 16;
142
+ bytes[4] = unixTsMs / 256;
143
+ bytes[5] = unixTsMs;
144
+ bytes[6] = 112 | randA >>> 8;
145
+ bytes[7] = randA;
146
+ bytes[8] = 128 | randBHi >>> 24;
147
+ bytes[9] = randBHi >>> 16;
148
+ bytes[10] = randBHi >>> 8;
149
+ bytes[11] = randBHi;
150
+ bytes[12] = randBLo >>> 24;
151
+ bytes[13] = randBLo >>> 16;
152
+ bytes[14] = randBLo >>> 8;
153
+ bytes[15] = randBLo;
154
+ return new _UUID(bytes);
155
+ }
156
+ static parse(uuid) {
157
+ let hex;
158
+ switch (uuid.length) {
159
+ case 32:
160
+ hex = /^[0-9a-f]{32}$/i.exec(uuid)?.[0];
161
+ break;
162
+ case 36:
163
+ hex = /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(uuid)?.slice(1, 6).join("");
164
+ break;
165
+ case 38:
166
+ hex = /^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(uuid)?.slice(1, 6).join("");
167
+ break;
168
+ case 45:
169
+ hex = /^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(uuid)?.slice(1, 6).join("");
170
+ break;
171
+ }
172
+ if (hex) {
173
+ const inner = new Uint8Array(16);
174
+ for (let i = 0; i < 16; i += 4) {
175
+ const n = parseInt(hex.substring(2 * i, 2 * i + 8), 16);
176
+ inner[i + 0] = n >>> 24;
177
+ inner[i + 1] = n >>> 16;
178
+ inner[i + 2] = n >>> 8;
179
+ inner[i + 3] = n;
180
+ }
181
+ return new _UUID(inner);
182
+ }
183
+ throw new SyntaxError("could not parse UUID string");
184
+ }
185
+ toString() {
186
+ let text = "";
187
+ for (let i = 0; i < this.bytes.length; i++) {
188
+ text += DIGITS.charAt(this.bytes[i] >>> 4);
189
+ text += DIGITS.charAt(15 & this.bytes[i]);
190
+ if (3 === i || 5 === i || 7 === i || 9 === i) text += "-";
191
+ }
192
+ return text;
193
+ }
194
+ toHex() {
195
+ let text = "";
196
+ for (let i = 0; i < this.bytes.length; i++) {
197
+ text += DIGITS.charAt(this.bytes[i] >>> 4);
198
+ text += DIGITS.charAt(15 & this.bytes[i]);
199
+ }
200
+ return text;
201
+ }
202
+ toJSON() {
203
+ return this.toString();
204
+ }
205
+ getVariant() {
206
+ const n = this.bytes[8] >>> 4;
207
+ if (n < 0) throw new Error("unreachable");
208
+ if (n <= 7) return this.bytes.every((e) => 0 === e) ? "NIL" : "VAR_0";
209
+ if (n <= 11) return "VAR_10";
210
+ if (n <= 13) return "VAR_110";
211
+ if (n <= 15) return this.bytes.every((e) => 255 === e) ? "MAX" : "VAR_RESERVED";
212
+ else throw new Error("unreachable");
213
+ }
214
+ getVersion() {
215
+ return "VAR_10" === this.getVariant() ? this.bytes[6] >>> 4 : void 0;
216
+ }
217
+ clone() {
218
+ return new _UUID(this.bytes.slice(0));
219
+ }
220
+ equals(other) {
221
+ return 0 === this.compareTo(other);
222
+ }
223
+ compareTo(other) {
224
+ for (let i = 0; i < 16; i++) {
225
+ const diff = this.bytes[i] - other.bytes[i];
226
+ if (0 !== diff) return Math.sign(diff);
227
+ }
228
+ return 0;
229
+ }
230
+ };
231
+ V7Generator = class {
232
+ constructor(randomNumberGenerator) {
233
+ this.timestamp = 0;
234
+ this.counter = 0;
235
+ this.random = randomNumberGenerator ?? getDefaultRandom();
236
+ }
237
+ generate() {
238
+ return this.generateOrResetCore(Date.now(), 1e4);
239
+ }
240
+ generateOrAbort() {
241
+ return this.generateOrAbortCore(Date.now(), 1e4);
242
+ }
243
+ generateOrResetCore(unixTsMs, rollbackAllowance) {
244
+ let value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
245
+ if (void 0 === value) {
246
+ this.timestamp = 0;
247
+ value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
248
+ }
249
+ return value;
250
+ }
251
+ generateOrAbortCore(unixTsMs, rollbackAllowance) {
252
+ const MAX_COUNTER = 4398046511103;
253
+ if (!Number.isInteger(unixTsMs) || unixTsMs < 1 || unixTsMs > 281474976710655) throw new RangeError("`unixTsMs` must be a 48-bit positive integer");
254
+ if (rollbackAllowance < 0 || rollbackAllowance > 281474976710655) throw new RangeError("`rollbackAllowance` out of reasonable range");
255
+ if (unixTsMs > this.timestamp) {
256
+ this.timestamp = unixTsMs;
257
+ this.resetCounter();
258
+ } else {
259
+ if (!(unixTsMs + rollbackAllowance >= this.timestamp)) return;
260
+ this.counter++;
261
+ if (this.counter > MAX_COUNTER) {
262
+ this.timestamp++;
263
+ this.resetCounter();
264
+ }
265
+ }
266
+ return UUID.fromFieldsV7(this.timestamp, Math.trunc(this.counter / 2 ** 30), this.counter & 2 ** 30 - 1, this.random.nextUint32());
267
+ }
268
+ resetCounter() {
269
+ this.counter = 1024 * this.random.nextUint32() + (1023 & this.random.nextUint32());
270
+ }
271
+ generateV4() {
272
+ const bytes = new Uint8Array(Uint32Array.of(this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32()).buffer);
273
+ bytes[6] = 64 | bytes[6] >>> 4;
274
+ bytes[8] = 128 | bytes[8] >>> 2;
275
+ return UUID.ofInner(bytes);
276
+ }
277
+ };
278
+ getDefaultRandom = () => ({
279
+ nextUint32: () => 65536 * Math.trunc(65536 * Math.random()) + Math.trunc(65536 * Math.random())
280
+ });
281
+ uuidv7 = () => uuidv7obj().toString();
282
+ uuidv7obj = () => (defaultGenerator || (defaultGenerator = new V7Generator())).generate();
283
+ }
284
+ });
285
+
286
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/utils/bot-detection.mjs
287
+ var DEFAULT_BLOCKED_UA_STRS, isBlockedUA;
288
+ var init_bot_detection = __esm({
289
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/utils/bot-detection.mjs"() {
290
+ DEFAULT_BLOCKED_UA_STRS = [
291
+ "amazonbot",
292
+ "amazonproductbot",
293
+ "app.hypefactors.com",
294
+ "applebot",
295
+ "archive.org_bot",
296
+ "awariobot",
297
+ "backlinksextendedbot",
298
+ "baiduspider",
299
+ "bingbot",
300
+ "bingpreview",
301
+ "chrome-lighthouse",
302
+ "dataforseobot",
303
+ "deepscan",
304
+ "duckduckbot",
305
+ "facebookexternal",
306
+ "facebookcatalog",
307
+ "http://yandex.com/bots",
308
+ "hubspot",
309
+ "ia_archiver",
310
+ "leikibot",
311
+ "linkedinbot",
312
+ "meta-externalagent",
313
+ "mj12bot",
314
+ "msnbot",
315
+ "nessus",
316
+ "petalbot",
317
+ "pinterest",
318
+ "prerender",
319
+ "rogerbot",
320
+ "screaming frog",
321
+ "sebot-wa",
322
+ "sitebulb",
323
+ "slackbot",
324
+ "slurp",
325
+ "trendictionbot",
326
+ "turnitin",
327
+ "twitterbot",
328
+ "vercel-screenshot",
329
+ "vercelbot",
330
+ "yahoo! slurp",
331
+ "yandexbot",
332
+ "zoombot",
333
+ "bot.htm",
334
+ "bot.php",
335
+ "(bot;",
336
+ "bot/",
337
+ "crawler",
338
+ "ahrefsbot",
339
+ "ahrefssiteaudit",
340
+ "semrushbot",
341
+ "siteauditbot",
342
+ "splitsignalbot",
343
+ "gptbot",
344
+ "oai-searchbot",
345
+ "chatgpt-user",
346
+ "perplexitybot",
347
+ "better uptime bot",
348
+ "sentryuptimebot",
349
+ "uptimerobot",
350
+ "headlesschrome",
351
+ "cypress",
352
+ "google-hoteladsverifier",
353
+ "adsbot-google",
354
+ "apis-google",
355
+ "duplexweb-google",
356
+ "feedfetcher-google",
357
+ "google favicon",
358
+ "google web preview",
359
+ "google-read-aloud",
360
+ "googlebot",
361
+ "googleother",
362
+ "google-cloudvertexbot",
363
+ "googleweblight",
364
+ "mediapartners-google",
365
+ "storebot-google",
366
+ "google-inspectiontool",
367
+ "bytespider"
368
+ ];
369
+ isBlockedUA = function(ua, customBlockedUserAgents = []) {
370
+ if (!ua) return false;
371
+ const uaLower = ua.toLowerCase();
372
+ return DEFAULT_BLOCKED_UA_STRS.concat(customBlockedUserAgents).some((blockedUA) => {
373
+ const blockedUaLower = blockedUA.toLowerCase();
374
+ return -1 !== uaLower.indexOf(blockedUaLower);
375
+ });
376
+ };
377
+ }
378
+ });
379
+
380
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/types.mjs
381
+ var types_PostHogPersistedProperty;
382
+ var init_types = __esm({
383
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/types.mjs"() {
384
+ types_PostHogPersistedProperty = /* @__PURE__ */ (function(PostHogPersistedProperty) {
385
+ PostHogPersistedProperty["AnonymousId"] = "anonymous_id";
386
+ PostHogPersistedProperty["DistinctId"] = "distinct_id";
387
+ PostHogPersistedProperty["Props"] = "props";
388
+ PostHogPersistedProperty["FeatureFlagDetails"] = "feature_flag_details";
389
+ PostHogPersistedProperty["FeatureFlags"] = "feature_flags";
390
+ PostHogPersistedProperty["FeatureFlagPayloads"] = "feature_flag_payloads";
391
+ PostHogPersistedProperty["BootstrapFeatureFlagDetails"] = "bootstrap_feature_flag_details";
392
+ PostHogPersistedProperty["BootstrapFeatureFlags"] = "bootstrap_feature_flags";
393
+ PostHogPersistedProperty["BootstrapFeatureFlagPayloads"] = "bootstrap_feature_flag_payloads";
394
+ PostHogPersistedProperty["OverrideFeatureFlags"] = "override_feature_flags";
395
+ PostHogPersistedProperty["Queue"] = "queue";
396
+ PostHogPersistedProperty["OptedOut"] = "opted_out";
397
+ PostHogPersistedProperty["SessionId"] = "session_id";
398
+ PostHogPersistedProperty["SessionStartTimestamp"] = "session_start_timestamp";
399
+ PostHogPersistedProperty["SessionLastTimestamp"] = "session_timestamp";
400
+ PostHogPersistedProperty["PersonProperties"] = "person_properties";
401
+ PostHogPersistedProperty["GroupProperties"] = "group_properties";
402
+ PostHogPersistedProperty["InstalledAppBuild"] = "installed_app_build";
403
+ PostHogPersistedProperty["InstalledAppVersion"] = "installed_app_version";
404
+ PostHogPersistedProperty["SessionReplay"] = "session_replay";
405
+ PostHogPersistedProperty["SurveyLastSeenDate"] = "survey_last_seen_date";
406
+ PostHogPersistedProperty["SurveysSeen"] = "surveys_seen";
407
+ PostHogPersistedProperty["Surveys"] = "surveys";
408
+ PostHogPersistedProperty["RemoteConfig"] = "remote_config";
409
+ PostHogPersistedProperty["FlagsEndpointWasHit"] = "flags_endpoint_was_hit";
410
+ return PostHogPersistedProperty;
411
+ })({});
412
+ }
413
+ });
414
+
415
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/utils/string-utils.mjs
416
+ var init_string_utils = __esm({
417
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/utils/string-utils.mjs"() {
418
+ }
419
+ });
420
+
421
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/utils/type-utils.mjs
422
+ function isInstanceOf(candidate, base) {
423
+ try {
424
+ return candidate instanceof base;
425
+ } catch {
426
+ return false;
427
+ }
428
+ }
429
+ function isPrimitive(value) {
430
+ return null === value || "object" != typeof value;
431
+ }
432
+ function isBuiltin(candidate, className) {
433
+ return Object.prototype.toString.call(candidate) === `[object ${className}]`;
434
+ }
435
+ function isErrorEvent(event) {
436
+ return isBuiltin(event, "ErrorEvent");
437
+ }
438
+ function isEvent(candidate) {
439
+ return !isUndefined(Event) && isInstanceOf(candidate, Event);
440
+ }
441
+ function isPlainObject(candidate) {
442
+ return isBuiltin(candidate, "Object");
443
+ }
444
+ var nativeIsArray, ObjProto, type_utils_toString, isArray, isUndefined, isString, isEmptyString, isNumber, isPlainError;
445
+ var init_type_utils = __esm({
446
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/utils/type-utils.mjs"() {
447
+ init_types();
448
+ init_string_utils();
449
+ nativeIsArray = Array.isArray;
450
+ ObjProto = Object.prototype;
451
+ ObjProto.hasOwnProperty;
452
+ type_utils_toString = ObjProto.toString;
453
+ isArray = nativeIsArray || function(obj) {
454
+ return "[object Array]" === type_utils_toString.call(obj);
455
+ };
456
+ isUndefined = (x) => void 0 === x;
457
+ isString = (x) => "[object String]" == type_utils_toString.call(x);
458
+ isEmptyString = (x) => isString(x) && 0 === x.trim().length;
459
+ isNumber = (x) => "[object Number]" == type_utils_toString.call(x);
460
+ isPlainError = (x) => x instanceof Error;
461
+ }
462
+ });
463
+
464
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/utils/number-utils.mjs
465
+ function clampToRange(value, min, max, logger, fallbackValue) {
466
+ if (min > max) {
467
+ logger.warn("min cannot be greater than max.");
468
+ min = max;
469
+ }
470
+ if (isNumber(value)) if (value > max) {
471
+ logger.warn(" cannot be greater than max: " + max + ". Using max value instead.");
472
+ return max;
473
+ } else {
474
+ if (!(value < min)) return value;
475
+ logger.warn(" cannot be less than min: " + min + ". Using min value instead.");
476
+ return min;
477
+ }
478
+ logger.warn(" must be a number. using max or fallback. max: " + max + ", fallback: " + fallbackValue);
479
+ return clampToRange(max, min, max, logger);
480
+ }
481
+ var init_number_utils = __esm({
482
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/utils/number-utils.mjs"() {
483
+ init_type_utils();
484
+ }
485
+ });
486
+
487
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs
488
+ var ONE_DAY_IN_MS, BucketedRateLimiter;
489
+ var init_bucketed_rate_limiter = __esm({
490
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs"() {
491
+ init_number_utils();
492
+ ONE_DAY_IN_MS = 864e5;
493
+ BucketedRateLimiter = class {
494
+ constructor(options) {
495
+ this._buckets = {};
496
+ this._onBucketRateLimited = options._onBucketRateLimited;
497
+ this._bucketSize = clampToRange(options.bucketSize, 0, 100, options._logger);
498
+ this._refillRate = clampToRange(options.refillRate, 0, this._bucketSize, options._logger);
499
+ this._refillInterval = clampToRange(options.refillInterval, 0, ONE_DAY_IN_MS, options._logger);
500
+ }
501
+ _applyRefill(bucket, now) {
502
+ const elapsedMs = now - bucket.lastAccess;
503
+ const refillIntervals = Math.floor(elapsedMs / this._refillInterval);
504
+ if (refillIntervals > 0) {
505
+ const tokensToAdd = refillIntervals * this._refillRate;
506
+ bucket.tokens = Math.min(bucket.tokens + tokensToAdd, this._bucketSize);
507
+ bucket.lastAccess = bucket.lastAccess + refillIntervals * this._refillInterval;
508
+ }
509
+ }
510
+ consumeRateLimit(key) {
511
+ const now = Date.now();
512
+ const keyStr = String(key);
513
+ let bucket = this._buckets[keyStr];
514
+ if (bucket) this._applyRefill(bucket, now);
515
+ else {
516
+ bucket = {
517
+ tokens: this._bucketSize,
518
+ lastAccess: now
519
+ };
520
+ this._buckets[keyStr] = bucket;
521
+ }
522
+ if (0 === bucket.tokens) return true;
523
+ bucket.tokens--;
524
+ if (0 === bucket.tokens) this._onBucketRateLimited?.(key);
525
+ return 0 === bucket.tokens;
526
+ }
527
+ stop() {
528
+ this._buckets = {};
529
+ }
530
+ };
531
+ }
532
+ });
533
+
534
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/utils/promise-queue.mjs
535
+ var PromiseQueue;
536
+ var init_promise_queue = __esm({
537
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/utils/promise-queue.mjs"() {
538
+ init_uuidv7();
539
+ PromiseQueue = class {
540
+ add(promise) {
541
+ const promiseUUID = uuidv7();
542
+ this.promiseByIds[promiseUUID] = promise;
543
+ promise.catch(() => {
544
+ }).finally(() => {
545
+ delete this.promiseByIds[promiseUUID];
546
+ });
547
+ return promise;
548
+ }
549
+ async join() {
550
+ let promises = Object.values(this.promiseByIds);
551
+ let length = promises.length;
552
+ while (length > 0) {
553
+ await Promise.all(promises);
554
+ promises = Object.values(this.promiseByIds);
555
+ length = promises.length;
556
+ }
557
+ }
558
+ get length() {
559
+ return Object.keys(this.promiseByIds).length;
560
+ }
561
+ constructor() {
562
+ this.promiseByIds = {};
563
+ }
564
+ };
565
+ }
566
+ });
567
+
568
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/utils/logger.mjs
569
+ function createConsole(consoleLike = console) {
570
+ const lockedMethods = {
571
+ log: consoleLike.log.bind(consoleLike),
572
+ warn: consoleLike.warn.bind(consoleLike),
573
+ error: consoleLike.error.bind(consoleLike),
574
+ debug: consoleLike.debug.bind(consoleLike)
575
+ };
576
+ return lockedMethods;
577
+ }
578
+ function createLogger(prefix, maybeCall = passThrough) {
579
+ return _createLogger(prefix, maybeCall, createConsole());
580
+ }
581
+ var _createLogger, passThrough;
582
+ var init_logger = __esm({
583
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/utils/logger.mjs"() {
584
+ _createLogger = (prefix, maybeCall, consoleLike) => {
585
+ function _log(level, ...args) {
586
+ maybeCall(() => {
587
+ const consoleMethod = consoleLike[level];
588
+ consoleMethod(prefix, ...args);
589
+ });
590
+ }
591
+ const logger = {
592
+ info: (...args) => {
593
+ _log("log", ...args);
594
+ },
595
+ warn: (...args) => {
596
+ _log("warn", ...args);
597
+ },
598
+ error: (...args) => {
599
+ _log("error", ...args);
600
+ },
601
+ critical: (...args) => {
602
+ consoleLike["error"](prefix, ...args);
603
+ },
604
+ createLogger: (additionalPrefix) => _createLogger(`${prefix} ${additionalPrefix}`, maybeCall, consoleLike)
605
+ };
606
+ return logger;
607
+ };
608
+ passThrough = (fn) => fn();
609
+ }
610
+ });
611
+
612
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/utils/index.mjs
613
+ function assert(truthyValue, message) {
614
+ if (!truthyValue || "string" != typeof truthyValue || isEmpty(truthyValue)) throw new Error(message);
615
+ }
616
+ function isEmpty(truthyValue) {
617
+ if (0 === truthyValue.trim().length) return true;
618
+ return false;
619
+ }
620
+ function removeTrailingSlash(url) {
621
+ return url?.replace(/\/+$/, "");
622
+ }
623
+ async function retriable(fn, props) {
624
+ let lastError = null;
625
+ for (let i = 0; i < props.retryCount + 1; i++) {
626
+ if (i > 0) await new Promise((r) => setTimeout(r, props.retryDelay));
627
+ try {
628
+ const res = await fn();
629
+ return res;
630
+ } catch (e) {
631
+ lastError = e;
632
+ if (!props.retryCheck(e)) throw e;
633
+ }
634
+ }
635
+ throw lastError;
636
+ }
637
+ function currentISOTime() {
638
+ return (/* @__PURE__ */ new Date()).toISOString();
639
+ }
640
+ function safeSetTimeout(fn, timeout) {
641
+ const t = setTimeout(fn, timeout);
642
+ t?.unref && t?.unref();
643
+ return t;
644
+ }
645
+ function allSettled(promises) {
646
+ return Promise.all(promises.map((p) => (p ?? Promise.resolve()).then((value) => ({
647
+ status: "fulfilled",
648
+ value
649
+ }), (reason) => ({
650
+ status: "rejected",
651
+ reason
652
+ }))));
653
+ }
654
+ var STRING_FORMAT, isError;
655
+ var init_utils = __esm({
656
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/utils/index.mjs"() {
657
+ init_bot_detection();
658
+ init_bucketed_rate_limiter();
659
+ init_number_utils();
660
+ init_string_utils();
661
+ init_type_utils();
662
+ init_promise_queue();
663
+ init_logger();
664
+ STRING_FORMAT = "utf8";
665
+ isError = (x) => x instanceof Error;
666
+ }
667
+ });
668
+
669
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/eventemitter.mjs
670
+ var SimpleEventEmitter;
671
+ var init_eventemitter = __esm({
672
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/eventemitter.mjs"() {
673
+ SimpleEventEmitter = class {
674
+ constructor() {
675
+ this.events = {};
676
+ this.events = {};
677
+ }
678
+ on(event, listener) {
679
+ if (!this.events[event]) this.events[event] = [];
680
+ this.events[event].push(listener);
681
+ return () => {
682
+ this.events[event] = this.events[event].filter((x) => x !== listener);
683
+ };
684
+ }
685
+ emit(event, payload) {
686
+ for (const listener of this.events[event] || []) listener(payload);
687
+ for (const listener of this.events["*"] || []) listener(event, payload);
688
+ }
689
+ };
690
+ }
691
+ });
692
+
693
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/gzip.mjs
694
+ function isGzipSupported() {
695
+ return "CompressionStream" in globalThis;
696
+ }
697
+ async function gzipCompress(input, isDebug = true) {
698
+ try {
699
+ const dataStream = new Blob([
700
+ input
701
+ ], {
702
+ type: "text/plain"
703
+ }).stream();
704
+ const compressedStream = dataStream.pipeThrough(new CompressionStream("gzip"));
705
+ return await new Response(compressedStream).blob();
706
+ } catch (error) {
707
+ if (isDebug) console.error("Failed to gzip compress data", error);
708
+ return null;
709
+ }
710
+ }
711
+ var init_gzip = __esm({
712
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/gzip.mjs"() {
713
+ }
714
+ });
715
+
716
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/posthog-core-stateless.mjs
717
+ async function logFlushError(err) {
718
+ if (err instanceof PostHogFetchHttpError) {
719
+ let text = "";
720
+ try {
721
+ text = await err.text;
722
+ } catch {
723
+ }
724
+ console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err);
725
+ } else console.error("Error while flushing PostHog", err);
726
+ return Promise.resolve();
727
+ }
728
+ function isPostHogFetchError(err) {
729
+ return "object" == typeof err && (err instanceof PostHogFetchHttpError || err instanceof PostHogFetchNetworkError);
730
+ }
731
+ function isPostHogFetchContentTooLargeError(err) {
732
+ return "object" == typeof err && err instanceof PostHogFetchHttpError && 413 === err.status;
733
+ }
734
+ var PostHogFetchHttpError, PostHogFetchNetworkError, PostHogCoreStateless;
735
+ var init_posthog_core_stateless = __esm({
736
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/posthog-core-stateless.mjs"() {
737
+ init_eventemitter();
738
+ init_featureFlagUtils();
739
+ init_gzip();
740
+ init_types();
741
+ init_utils();
742
+ init_uuidv7();
743
+ PostHogFetchHttpError = class extends Error {
744
+ constructor(response, reqByteLength) {
745
+ super("HTTP error while fetching PostHog: status=" + response.status + ", reqByteLength=" + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.name = "PostHogFetchHttpError";
746
+ }
747
+ get status() {
748
+ return this.response.status;
749
+ }
750
+ get text() {
751
+ return this.response.text();
752
+ }
753
+ get json() {
754
+ return this.response.json();
755
+ }
756
+ };
757
+ PostHogFetchNetworkError = class extends Error {
758
+ constructor(error) {
759
+ super("Network error while fetching PostHog", error instanceof Error ? {
760
+ cause: error
761
+ } : {}), this.error = error, this.name = "PostHogFetchNetworkError";
762
+ }
763
+ };
764
+ PostHogCoreStateless = class {
765
+ constructor(apiKey, options = {}) {
766
+ this.flushPromise = null;
767
+ this.shutdownPromise = null;
768
+ this.promiseQueue = new PromiseQueue();
769
+ this._events = new SimpleEventEmitter();
770
+ this._isInitialized = false;
771
+ assert(apiKey, "You must pass your PostHog project's api key.");
772
+ this.apiKey = apiKey;
773
+ this.host = removeTrailingSlash(options.host || "https://us.i.posthog.com");
774
+ this.flushAt = options.flushAt ? Math.max(options.flushAt, 1) : 20;
775
+ this.maxBatchSize = Math.max(this.flushAt, options.maxBatchSize ?? 100);
776
+ this.maxQueueSize = Math.max(this.flushAt, options.maxQueueSize ?? 1e3);
777
+ this.flushInterval = options.flushInterval ?? 1e4;
778
+ this.preloadFeatureFlags = options.preloadFeatureFlags ?? true;
779
+ this.defaultOptIn = options.defaultOptIn ?? true;
780
+ this.disableSurveys = options.disableSurveys ?? false;
781
+ this._retryOptions = {
782
+ retryCount: options.fetchRetryCount ?? 3,
783
+ retryDelay: options.fetchRetryDelay ?? 3e3,
784
+ retryCheck: isPostHogFetchError
785
+ };
786
+ this.requestTimeout = options.requestTimeout ?? 1e4;
787
+ this.featureFlagsRequestTimeoutMs = options.featureFlagsRequestTimeoutMs ?? 3e3;
788
+ this.remoteConfigRequestTimeoutMs = options.remoteConfigRequestTimeoutMs ?? 3e3;
789
+ this.disableGeoip = options.disableGeoip ?? true;
790
+ this.disabled = options.disabled ?? false;
791
+ this.historicalMigration = options?.historicalMigration ?? false;
792
+ this.evaluationEnvironments = options?.evaluationEnvironments;
793
+ this._initPromise = Promise.resolve();
794
+ this._isInitialized = true;
795
+ this._logger = createLogger("[PostHog]", this.logMsgIfDebug.bind(this));
796
+ this.disableCompression = !isGzipSupported() || (options?.disableCompression ?? false);
797
+ }
798
+ logMsgIfDebug(fn) {
799
+ if (this.isDebug) fn();
800
+ }
801
+ wrap(fn) {
802
+ if (this.disabled) return void this._logger.warn("The client is disabled");
803
+ if (this._isInitialized) return fn();
804
+ this._initPromise.then(() => fn());
805
+ }
806
+ getCommonEventProperties() {
807
+ return {
808
+ $lib: this.getLibraryId(),
809
+ $lib_version: this.getLibraryVersion()
810
+ };
811
+ }
812
+ get optedOut() {
813
+ return this.getPersistedProperty(types_PostHogPersistedProperty.OptedOut) ?? !this.defaultOptIn;
814
+ }
815
+ async optIn() {
816
+ this.wrap(() => {
817
+ this.setPersistedProperty(types_PostHogPersistedProperty.OptedOut, false);
818
+ });
819
+ }
820
+ async optOut() {
821
+ this.wrap(() => {
822
+ this.setPersistedProperty(types_PostHogPersistedProperty.OptedOut, true);
823
+ });
824
+ }
825
+ on(event, cb) {
826
+ return this._events.on(event, cb);
827
+ }
828
+ debug(enabled = true) {
829
+ this.removeDebugCallback?.();
830
+ if (enabled) {
831
+ const removeDebugCallback = this.on("*", (event, payload) => this._logger.info(event, payload));
832
+ this.removeDebugCallback = () => {
833
+ removeDebugCallback();
834
+ this.removeDebugCallback = void 0;
835
+ };
836
+ }
837
+ }
838
+ get isDebug() {
839
+ return !!this.removeDebugCallback;
840
+ }
841
+ get isDisabled() {
842
+ return this.disabled;
843
+ }
844
+ buildPayload(payload) {
845
+ return {
846
+ distinct_id: payload.distinct_id,
847
+ event: payload.event,
848
+ properties: {
849
+ ...payload.properties || {},
850
+ ...this.getCommonEventProperties()
851
+ }
852
+ };
853
+ }
854
+ addPendingPromise(promise) {
855
+ return this.promiseQueue.add(promise);
856
+ }
857
+ identifyStateless(distinctId, properties, options) {
858
+ this.wrap(() => {
859
+ const payload = {
860
+ ...this.buildPayload({
861
+ distinct_id: distinctId,
862
+ event: "$identify",
863
+ properties
864
+ })
865
+ };
866
+ this.enqueue("identify", payload, options);
867
+ });
868
+ }
869
+ async identifyStatelessImmediate(distinctId, properties, options) {
870
+ const payload = {
871
+ ...this.buildPayload({
872
+ distinct_id: distinctId,
873
+ event: "$identify",
874
+ properties
875
+ })
876
+ };
877
+ await this.sendImmediate("identify", payload, options);
878
+ }
879
+ captureStateless(distinctId, event, properties, options) {
880
+ this.wrap(() => {
881
+ const payload = this.buildPayload({
882
+ distinct_id: distinctId,
883
+ event,
884
+ properties
885
+ });
886
+ this.enqueue("capture", payload, options);
887
+ });
888
+ }
889
+ async captureStatelessImmediate(distinctId, event, properties, options) {
890
+ const payload = this.buildPayload({
891
+ distinct_id: distinctId,
892
+ event,
893
+ properties
894
+ });
895
+ await this.sendImmediate("capture", payload, options);
896
+ }
897
+ aliasStateless(alias, distinctId, properties, options) {
898
+ this.wrap(() => {
899
+ const payload = this.buildPayload({
900
+ event: "$create_alias",
901
+ distinct_id: distinctId,
902
+ properties: {
903
+ ...properties || {},
904
+ distinct_id: distinctId,
905
+ alias
906
+ }
907
+ });
908
+ this.enqueue("alias", payload, options);
909
+ });
910
+ }
911
+ async aliasStatelessImmediate(alias, distinctId, properties, options) {
912
+ const payload = this.buildPayload({
913
+ event: "$create_alias",
914
+ distinct_id: distinctId,
915
+ properties: {
916
+ ...properties || {},
917
+ distinct_id: distinctId,
918
+ alias
919
+ }
920
+ });
921
+ await this.sendImmediate("alias", payload, options);
922
+ }
923
+ groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
924
+ this.wrap(() => {
925
+ const payload = this.buildPayload({
926
+ distinct_id: distinctId || `$${groupType}_${groupKey}`,
927
+ event: "$groupidentify",
928
+ properties: {
929
+ $group_type: groupType,
930
+ $group_key: groupKey,
931
+ $group_set: groupProperties || {},
932
+ ...eventProperties || {}
933
+ }
934
+ });
935
+ this.enqueue("capture", payload, options);
936
+ });
937
+ }
938
+ async getRemoteConfig() {
939
+ await this._initPromise;
940
+ let host = this.host;
941
+ if ("https://us.i.posthog.com" === host) host = "https://us-assets.i.posthog.com";
942
+ else if ("https://eu.i.posthog.com" === host) host = "https://eu-assets.i.posthog.com";
943
+ const url = `${host}/array/${this.apiKey}/config`;
944
+ const fetchOptions = {
945
+ method: "GET",
946
+ headers: {
947
+ ...this.getCustomHeaders(),
948
+ "Content-Type": "application/json"
949
+ }
950
+ };
951
+ return this.fetchWithRetry(url, fetchOptions, {
952
+ retryCount: 0
953
+ }, this.remoteConfigRequestTimeoutMs).then((response) => response.json()).catch((error) => {
954
+ this._logger.error("Remote config could not be loaded", error);
955
+ this._events.emit("error", error);
956
+ });
957
+ }
958
+ async getFlags(distinctId, groups = {}, personProperties = {}, groupProperties = {}, extraPayload = {}, fetchConfig = true) {
959
+ await this._initPromise;
960
+ const configParam = fetchConfig ? "&config=true" : "";
961
+ const url = `${this.host}/flags/?v=2${configParam}`;
962
+ const requestData = {
963
+ token: this.apiKey,
964
+ distinct_id: distinctId,
965
+ groups,
966
+ person_properties: personProperties,
967
+ group_properties: groupProperties,
968
+ ...extraPayload
969
+ };
970
+ if (this.evaluationEnvironments && this.evaluationEnvironments.length > 0) requestData.evaluation_environments = this.evaluationEnvironments;
971
+ const fetchOptions = {
972
+ method: "POST",
973
+ headers: {
974
+ ...this.getCustomHeaders(),
975
+ "Content-Type": "application/json"
976
+ },
977
+ body: JSON.stringify(requestData)
978
+ };
979
+ this._logger.info("Flags URL", url);
980
+ return this.fetchWithRetry(url, fetchOptions, {
981
+ retryCount: 0
982
+ }, this.featureFlagsRequestTimeoutMs).then((response) => response.json()).then((response) => normalizeFlagsResponse(response)).catch((error) => {
983
+ this._events.emit("error", error);
984
+ });
985
+ }
986
+ async getFeatureFlagStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
987
+ await this._initPromise;
988
+ const flagDetailResponse = await this.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
989
+ if (void 0 === flagDetailResponse) return {
990
+ response: void 0,
991
+ requestId: void 0
992
+ };
993
+ let response = getFeatureFlagValue(flagDetailResponse.response);
994
+ if (void 0 === response) response = false;
995
+ return {
996
+ response,
997
+ requestId: flagDetailResponse.requestId
998
+ };
999
+ }
1000
+ async getFeatureFlagDetailStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1001
+ await this._initPromise;
1002
+ const flagsResponse = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [
1003
+ key
1004
+ ]);
1005
+ if (void 0 === flagsResponse) return;
1006
+ const featureFlags = flagsResponse.flags;
1007
+ const flagDetail = featureFlags[key];
1008
+ return {
1009
+ response: flagDetail,
1010
+ requestId: flagsResponse.requestId
1011
+ };
1012
+ }
1013
+ async getFeatureFlagPayloadStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1014
+ await this._initPromise;
1015
+ const payloads = await this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [
1016
+ key
1017
+ ]);
1018
+ if (!payloads) return;
1019
+ const response = payloads[key];
1020
+ if (void 0 === response) return null;
1021
+ return response;
1022
+ }
1023
+ async getFeatureFlagPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
1024
+ await this._initPromise;
1025
+ const payloads = (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate)).payloads;
1026
+ return payloads;
1027
+ }
1028
+ async getFeatureFlagsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
1029
+ await this._initPromise;
1030
+ return await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
1031
+ }
1032
+ async getFeatureFlagsAndPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
1033
+ await this._initPromise;
1034
+ const featureFlagDetails = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
1035
+ if (!featureFlagDetails) return {
1036
+ flags: void 0,
1037
+ payloads: void 0,
1038
+ requestId: void 0
1039
+ };
1040
+ return {
1041
+ flags: featureFlagDetails.featureFlags,
1042
+ payloads: featureFlagDetails.featureFlagPayloads,
1043
+ requestId: featureFlagDetails.requestId
1044
+ };
1045
+ }
1046
+ async getFeatureFlagDetailsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
1047
+ await this._initPromise;
1048
+ const extraPayload = {};
1049
+ if (disableGeoip ?? this.disableGeoip) extraPayload["geoip_disable"] = true;
1050
+ if (flagKeysToEvaluate) extraPayload["flag_keys_to_evaluate"] = flagKeysToEvaluate;
1051
+ const flagsResponse = await this.getFlags(distinctId, groups, personProperties, groupProperties, extraPayload);
1052
+ if (void 0 === flagsResponse) return;
1053
+ 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");
1054
+ if (flagsResponse.quotaLimited?.includes("feature_flags")) {
1055
+ 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");
1056
+ return {
1057
+ flags: {},
1058
+ featureFlags: {},
1059
+ featureFlagPayloads: {},
1060
+ requestId: flagsResponse?.requestId
1061
+ };
1062
+ }
1063
+ return flagsResponse;
1064
+ }
1065
+ async getSurveysStateless() {
1066
+ await this._initPromise;
1067
+ if (true === this.disableSurveys) {
1068
+ this._logger.info("Loading surveys is disabled.");
1069
+ return [];
1070
+ }
1071
+ const url = `${this.host}/api/surveys/?token=${this.apiKey}`;
1072
+ const fetchOptions = {
1073
+ method: "GET",
1074
+ headers: {
1075
+ ...this.getCustomHeaders(),
1076
+ "Content-Type": "application/json"
1077
+ }
1078
+ };
1079
+ const response = await this.fetchWithRetry(url, fetchOptions).then((response2) => {
1080
+ if (200 !== response2.status || !response2.json) {
1081
+ const msg = `Surveys API could not be loaded: ${response2.status}`;
1082
+ const error = new Error(msg);
1083
+ this._logger.error(error);
1084
+ this._events.emit("error", new Error(msg));
1085
+ return;
1086
+ }
1087
+ return response2.json();
1088
+ }).catch((error) => {
1089
+ this._logger.error("Surveys API could not be loaded", error);
1090
+ this._events.emit("error", error);
1091
+ });
1092
+ const newSurveys = response?.surveys;
1093
+ if (newSurveys) this._logger.info("Surveys fetched from API: ", JSON.stringify(newSurveys));
1094
+ return newSurveys ?? [];
1095
+ }
1096
+ get props() {
1097
+ if (!this._props) this._props = this.getPersistedProperty(types_PostHogPersistedProperty.Props);
1098
+ return this._props || {};
1099
+ }
1100
+ set props(val) {
1101
+ this._props = val;
1102
+ }
1103
+ async register(properties) {
1104
+ this.wrap(() => {
1105
+ this.props = {
1106
+ ...this.props,
1107
+ ...properties
1108
+ };
1109
+ this.setPersistedProperty(types_PostHogPersistedProperty.Props, this.props);
1110
+ });
1111
+ }
1112
+ async unregister(property) {
1113
+ this.wrap(() => {
1114
+ delete this.props[property];
1115
+ this.setPersistedProperty(types_PostHogPersistedProperty.Props, this.props);
1116
+ });
1117
+ }
1118
+ enqueue(type, _message, options) {
1119
+ this.wrap(() => {
1120
+ if (this.optedOut) return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
1121
+ const message = this.prepareMessage(type, _message, options);
1122
+ const queue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
1123
+ if (queue.length >= this.maxQueueSize) {
1124
+ queue.shift();
1125
+ this._logger.info("Queue is full, the oldest event is dropped.");
1126
+ }
1127
+ queue.push({
1128
+ message
1129
+ });
1130
+ this.setPersistedProperty(types_PostHogPersistedProperty.Queue, queue);
1131
+ this._events.emit(type, message);
1132
+ if (queue.length >= this.flushAt) this.flushBackground();
1133
+ if (this.flushInterval && !this._flushTimer) this._flushTimer = safeSetTimeout(() => this.flushBackground(), this.flushInterval);
1134
+ });
1135
+ }
1136
+ async sendImmediate(type, _message, options) {
1137
+ if (this.disabled) return void this._logger.warn("The client is disabled");
1138
+ if (!this._isInitialized) await this._initPromise;
1139
+ if (this.optedOut) return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
1140
+ const data = {
1141
+ api_key: this.apiKey,
1142
+ batch: [
1143
+ this.prepareMessage(type, _message, options)
1144
+ ],
1145
+ sent_at: currentISOTime()
1146
+ };
1147
+ if (this.historicalMigration) data.historical_migration = true;
1148
+ const payload = JSON.stringify(data);
1149
+ const url = `${this.host}/batch/`;
1150
+ const gzippedPayload = this.disableCompression ? null : await gzipCompress(payload, this.isDebug);
1151
+ const fetchOptions = {
1152
+ method: "POST",
1153
+ headers: {
1154
+ ...this.getCustomHeaders(),
1155
+ "Content-Type": "application/json",
1156
+ ...null !== gzippedPayload && {
1157
+ "Content-Encoding": "gzip"
1158
+ }
1159
+ },
1160
+ body: gzippedPayload || payload
1161
+ };
1162
+ try {
1163
+ await this.fetchWithRetry(url, fetchOptions);
1164
+ } catch (err) {
1165
+ this._events.emit("error", err);
1166
+ }
1167
+ }
1168
+ prepareMessage(type, _message, options) {
1169
+ const message = {
1170
+ ..._message,
1171
+ type,
1172
+ library: this.getLibraryId(),
1173
+ library_version: this.getLibraryVersion(),
1174
+ timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),
1175
+ uuid: options?.uuid ? options.uuid : uuidv7()
1176
+ };
1177
+ const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;
1178
+ if (addGeoipDisableProperty) {
1179
+ if (!message.properties) message.properties = {};
1180
+ message["properties"]["$geoip_disable"] = true;
1181
+ }
1182
+ if (message.distinctId) {
1183
+ message.distinct_id = message.distinctId;
1184
+ delete message.distinctId;
1185
+ }
1186
+ return message;
1187
+ }
1188
+ clearFlushTimer() {
1189
+ if (this._flushTimer) {
1190
+ clearTimeout(this._flushTimer);
1191
+ this._flushTimer = void 0;
1192
+ }
1193
+ }
1194
+ flushBackground() {
1195
+ this.flush().catch(async (err) => {
1196
+ await logFlushError(err);
1197
+ });
1198
+ }
1199
+ async flush() {
1200
+ const nextFlushPromise = allSettled([
1201
+ this.flushPromise
1202
+ ]).then(() => this._flush());
1203
+ this.flushPromise = nextFlushPromise;
1204
+ this.addPendingPromise(nextFlushPromise);
1205
+ allSettled([
1206
+ nextFlushPromise
1207
+ ]).then(() => {
1208
+ if (this.flushPromise === nextFlushPromise) this.flushPromise = null;
1209
+ });
1210
+ return nextFlushPromise;
1211
+ }
1212
+ getCustomHeaders() {
1213
+ const customUserAgent = this.getCustomUserAgent();
1214
+ const headers = {};
1215
+ if (customUserAgent && "" !== customUserAgent) headers["User-Agent"] = customUserAgent;
1216
+ return headers;
1217
+ }
1218
+ async _flush() {
1219
+ this.clearFlushTimer();
1220
+ await this._initPromise;
1221
+ let queue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
1222
+ if (!queue.length) return;
1223
+ const sentMessages = [];
1224
+ const originalQueueLength = queue.length;
1225
+ while (queue.length > 0 && sentMessages.length < originalQueueLength) {
1226
+ const batchItems = queue.slice(0, this.maxBatchSize);
1227
+ const batchMessages = batchItems.map((item) => item.message);
1228
+ const persistQueueChange = () => {
1229
+ const refreshedQueue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
1230
+ const newQueue = refreshedQueue.slice(batchItems.length);
1231
+ this.setPersistedProperty(types_PostHogPersistedProperty.Queue, newQueue);
1232
+ queue = newQueue;
1233
+ };
1234
+ const data = {
1235
+ api_key: this.apiKey,
1236
+ batch: batchMessages,
1237
+ sent_at: currentISOTime()
1238
+ };
1239
+ if (this.historicalMigration) data.historical_migration = true;
1240
+ const payload = JSON.stringify(data);
1241
+ const url = `${this.host}/batch/`;
1242
+ const gzippedPayload = this.disableCompression ? null : await gzipCompress(payload, this.isDebug);
1243
+ const fetchOptions = {
1244
+ method: "POST",
1245
+ headers: {
1246
+ ...this.getCustomHeaders(),
1247
+ "Content-Type": "application/json",
1248
+ ...null !== gzippedPayload && {
1249
+ "Content-Encoding": "gzip"
1250
+ }
1251
+ },
1252
+ body: gzippedPayload || payload
1253
+ };
1254
+ const retryOptions = {
1255
+ retryCheck: (err) => {
1256
+ if (isPostHogFetchContentTooLargeError(err)) return false;
1257
+ return isPostHogFetchError(err);
1258
+ }
1259
+ };
1260
+ try {
1261
+ await this.fetchWithRetry(url, fetchOptions, retryOptions);
1262
+ } catch (err) {
1263
+ if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {
1264
+ this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));
1265
+ this._logger.warn(`Received 413 when sending batch of size ${batchMessages.length}, reducing batch size to ${this.maxBatchSize}`);
1266
+ continue;
1267
+ }
1268
+ if (!(err instanceof PostHogFetchNetworkError)) persistQueueChange();
1269
+ this._events.emit("error", err);
1270
+ throw err;
1271
+ }
1272
+ persistQueueChange();
1273
+ sentMessages.push(...batchMessages);
1274
+ }
1275
+ this._events.emit("flush", sentMessages);
1276
+ }
1277
+ async fetchWithRetry(url, options, retryOptions, requestTimeout) {
1278
+ AbortSignal.timeout ??= function(ms) {
1279
+ const ctrl = new AbortController();
1280
+ setTimeout(() => ctrl.abort(), ms);
1281
+ return ctrl.signal;
1282
+ };
1283
+ const body = options.body ? options.body : "";
1284
+ let reqByteLength = -1;
1285
+ try {
1286
+ reqByteLength = body instanceof Blob ? body.size : Buffer.byteLength(body, STRING_FORMAT);
1287
+ } catch {
1288
+ if (body instanceof Blob) reqByteLength = body.size;
1289
+ else {
1290
+ const encoded = new TextEncoder().encode(body);
1291
+ reqByteLength = encoded.length;
1292
+ }
1293
+ }
1294
+ return await retriable(async () => {
1295
+ let res = null;
1296
+ try {
1297
+ res = await this.fetch(url, {
1298
+ signal: AbortSignal.timeout(requestTimeout ?? this.requestTimeout),
1299
+ ...options
1300
+ });
1301
+ } catch (e) {
1302
+ throw new PostHogFetchNetworkError(e);
1303
+ }
1304
+ const isNoCors = "no-cors" === options.mode;
1305
+ if (!isNoCors && (res.status < 200 || res.status >= 400)) throw new PostHogFetchHttpError(res, reqByteLength);
1306
+ return res;
1307
+ }, {
1308
+ ...this._retryOptions,
1309
+ ...retryOptions
1310
+ });
1311
+ }
1312
+ async _shutdown(shutdownTimeoutMs = 3e4) {
1313
+ await this._initPromise;
1314
+ let hasTimedOut = false;
1315
+ this.clearFlushTimer();
1316
+ const doShutdown = async () => {
1317
+ try {
1318
+ await this.promiseQueue.join();
1319
+ while (true) {
1320
+ const queue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
1321
+ if (0 === queue.length) break;
1322
+ await this.flush();
1323
+ if (hasTimedOut) break;
1324
+ }
1325
+ } catch (e) {
1326
+ if (!isPostHogFetchError(e)) throw e;
1327
+ await logFlushError(e);
1328
+ }
1329
+ };
1330
+ return Promise.race([
1331
+ new Promise((_, reject) => {
1332
+ safeSetTimeout(() => {
1333
+ this._logger.error("Timed out while shutting down PostHog");
1334
+ hasTimedOut = true;
1335
+ reject("Timeout while shutting down PostHog. Some events may not have been sent.");
1336
+ }, shutdownTimeoutMs);
1337
+ }),
1338
+ doShutdown()
1339
+ ]);
1340
+ }
1341
+ async shutdown(shutdownTimeoutMs = 3e4) {
1342
+ if (this.shutdownPromise) this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");
1343
+ else this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(() => {
1344
+ this.shutdownPromise = null;
1345
+ });
1346
+ return this.shutdownPromise;
1347
+ }
1348
+ };
1349
+ }
1350
+ });
1351
+
1352
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/posthog-core.mjs
1353
+ var init_posthog_core = __esm({
1354
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/posthog-core.mjs"() {
1355
+ init_featureFlagUtils();
1356
+ init_types();
1357
+ init_posthog_core_stateless();
1358
+ init_uuidv7();
1359
+ init_utils();
1360
+ }
1361
+ });
1362
+
1363
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs
1364
+ function getFilenameToChunkIdMap(stackParser) {
1365
+ const chunkIdMap = globalThis._posthogChunkIds;
1366
+ if (!chunkIdMap) return;
1367
+ const chunkIdKeys = Object.keys(chunkIdMap);
1368
+ if (cachedFilenameChunkIds && chunkIdKeys.length === lastKeysCount) return cachedFilenameChunkIds;
1369
+ lastKeysCount = chunkIdKeys.length;
1370
+ cachedFilenameChunkIds = chunkIdKeys.reduce((acc, stackKey) => {
1371
+ if (!parsedStackResults) parsedStackResults = {};
1372
+ const result = parsedStackResults[stackKey];
1373
+ if (result) acc[result[0]] = result[1];
1374
+ else {
1375
+ const parsedStack = stackParser(stackKey);
1376
+ for (let i = parsedStack.length - 1; i >= 0; i--) {
1377
+ const stackFrame = parsedStack[i];
1378
+ const filename = stackFrame?.filename;
1379
+ const chunkId = chunkIdMap[stackKey];
1380
+ if (filename && chunkId) {
1381
+ acc[filename] = chunkId;
1382
+ parsedStackResults[stackKey] = [
1383
+ filename,
1384
+ chunkId
1385
+ ];
1386
+ break;
1387
+ }
1388
+ }
1389
+ }
1390
+ return acc;
1391
+ }, {});
1392
+ return cachedFilenameChunkIds;
1393
+ }
1394
+ var parsedStackResults, lastKeysCount, cachedFilenameChunkIds;
1395
+ var init_chunk_ids = __esm({
1396
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs"() {
1397
+ }
1398
+ });
1399
+
1400
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs
1401
+ var MAX_CAUSE_RECURSION, ErrorPropertiesBuilder;
1402
+ var init_error_properties_builder = __esm({
1403
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs"() {
1404
+ init_utils();
1405
+ init_chunk_ids();
1406
+ MAX_CAUSE_RECURSION = 4;
1407
+ ErrorPropertiesBuilder = class {
1408
+ constructor(coercers, stackParser, modifiers = []) {
1409
+ this.coercers = coercers;
1410
+ this.stackParser = stackParser;
1411
+ this.modifiers = modifiers;
1412
+ }
1413
+ buildFromUnknown(input, hint = {}) {
1414
+ const providedMechanism = hint && hint.mechanism;
1415
+ const mechanism = providedMechanism || {
1416
+ handled: true,
1417
+ type: "generic"
1418
+ };
1419
+ const coercingContext = this.buildCoercingContext(mechanism, hint, 0);
1420
+ const exceptionWithCause = coercingContext.apply(input);
1421
+ const parsingContext = this.buildParsingContext();
1422
+ const exceptionWithStack = this.parseStacktrace(exceptionWithCause, parsingContext);
1423
+ const exceptionList = this.convertToExceptionList(exceptionWithStack, mechanism);
1424
+ return {
1425
+ $exception_list: exceptionList,
1426
+ $exception_level: "error"
1427
+ };
1428
+ }
1429
+ async modifyFrames(exceptionList) {
1430
+ for (const exc of exceptionList) if (exc.stacktrace && exc.stacktrace.frames && isArray(exc.stacktrace.frames)) exc.stacktrace.frames = await this.applyModifiers(exc.stacktrace.frames);
1431
+ return exceptionList;
1432
+ }
1433
+ coerceFallback(ctx) {
1434
+ return {
1435
+ type: "Error",
1436
+ value: "Unknown error",
1437
+ stack: ctx.syntheticException?.stack,
1438
+ synthetic: true
1439
+ };
1440
+ }
1441
+ parseStacktrace(err, ctx) {
1442
+ let cause;
1443
+ if (null != err.cause) cause = this.parseStacktrace(err.cause, ctx);
1444
+ let stack;
1445
+ if ("" != err.stack && null != err.stack) stack = this.applyChunkIds(this.stackParser(err.stack, err.synthetic ? 1 : 0), ctx.chunkIdMap);
1446
+ return {
1447
+ ...err,
1448
+ cause,
1449
+ stack
1450
+ };
1451
+ }
1452
+ applyChunkIds(frames, chunkIdMap) {
1453
+ return frames.map((frame) => {
1454
+ if (frame.filename && chunkIdMap) frame.chunk_id = chunkIdMap[frame.filename];
1455
+ return frame;
1456
+ });
1457
+ }
1458
+ applyCoercers(input, ctx) {
1459
+ for (const adapter of this.coercers) if (adapter.match(input)) return adapter.coerce(input, ctx);
1460
+ return this.coerceFallback(ctx);
1461
+ }
1462
+ async applyModifiers(frames) {
1463
+ let newFrames = frames;
1464
+ for (const modifier of this.modifiers) newFrames = await modifier(newFrames);
1465
+ return newFrames;
1466
+ }
1467
+ convertToExceptionList(exceptionWithStack, mechanism) {
1468
+ const currentException = {
1469
+ type: exceptionWithStack.type,
1470
+ value: exceptionWithStack.value,
1471
+ mechanism: {
1472
+ type: mechanism.type ?? "generic",
1473
+ handled: mechanism.handled ?? true,
1474
+ synthetic: exceptionWithStack.synthetic ?? false
1475
+ }
1476
+ };
1477
+ if (exceptionWithStack.stack) currentException.stacktrace = {
1478
+ type: "raw",
1479
+ frames: exceptionWithStack.stack
1480
+ };
1481
+ const exceptionList = [
1482
+ currentException
1483
+ ];
1484
+ if (null != exceptionWithStack.cause) exceptionList.push(...this.convertToExceptionList(exceptionWithStack.cause, {
1485
+ ...mechanism,
1486
+ handled: true
1487
+ }));
1488
+ return exceptionList;
1489
+ }
1490
+ buildParsingContext() {
1491
+ const context = {
1492
+ chunkIdMap: getFilenameToChunkIdMap(this.stackParser)
1493
+ };
1494
+ return context;
1495
+ }
1496
+ buildCoercingContext(mechanism, hint, depth = 0) {
1497
+ const coerce = (input, depth2) => {
1498
+ if (!(depth2 <= MAX_CAUSE_RECURSION)) return;
1499
+ {
1500
+ const ctx = this.buildCoercingContext(mechanism, hint, depth2);
1501
+ return this.applyCoercers(input, ctx);
1502
+ }
1503
+ };
1504
+ const context = {
1505
+ ...hint,
1506
+ syntheticException: 0 == depth ? hint.syntheticException : void 0,
1507
+ mechanism,
1508
+ apply: (input) => coerce(input, depth),
1509
+ next: (input) => coerce(input, depth + 1)
1510
+ };
1511
+ return context;
1512
+ }
1513
+ };
1514
+ }
1515
+ });
1516
+
1517
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs
1518
+ function createFrame(platform, filename, func, lineno, colno) {
1519
+ const frame = {
1520
+ platform,
1521
+ filename,
1522
+ function: "<anonymous>" === func ? UNKNOWN_FUNCTION : func,
1523
+ in_app: true
1524
+ };
1525
+ if (!isUndefined(lineno)) frame.lineno = lineno;
1526
+ if (!isUndefined(colno)) frame.colno = colno;
1527
+ return frame;
1528
+ }
1529
+ var UNKNOWN_FUNCTION;
1530
+ var init_base = __esm({
1531
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs"() {
1532
+ init_utils();
1533
+ UNKNOWN_FUNCTION = "?";
1534
+ }
1535
+ });
1536
+
1537
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs
1538
+ var extractSafariExtensionDetails;
1539
+ var init_safari = __esm({
1540
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs"() {
1541
+ init_base();
1542
+ extractSafariExtensionDetails = (func, filename) => {
1543
+ const isSafariExtension = -1 !== func.indexOf("safari-extension");
1544
+ const isSafariWebExtension = -1 !== func.indexOf("safari-web-extension");
1545
+ return isSafariExtension || isSafariWebExtension ? [
1546
+ -1 !== func.indexOf("@") ? func.split("@")[0] : UNKNOWN_FUNCTION,
1547
+ isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`
1548
+ ] : [
1549
+ func,
1550
+ filename
1551
+ ];
1552
+ };
1553
+ }
1554
+ });
1555
+
1556
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs
1557
+ var chromeRegexNoFnName, chromeRegex, chromeEvalRegex, chromeStackLineParser;
1558
+ var init_chrome = __esm({
1559
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs"() {
1560
+ init_base();
1561
+ init_safari();
1562
+ chromeRegexNoFnName = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i;
1563
+ chromeRegex = /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
1564
+ chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/;
1565
+ chromeStackLineParser = (line, platform) => {
1566
+ const noFnParts = chromeRegexNoFnName.exec(line);
1567
+ if (noFnParts) {
1568
+ const [, filename, line2, col] = noFnParts;
1569
+ return createFrame(platform, filename, UNKNOWN_FUNCTION, +line2, +col);
1570
+ }
1571
+ const parts = chromeRegex.exec(line);
1572
+ if (parts) {
1573
+ const isEval = parts[2] && 0 === parts[2].indexOf("eval");
1574
+ if (isEval) {
1575
+ const subMatch = chromeEvalRegex.exec(parts[2]);
1576
+ if (subMatch) {
1577
+ parts[2] = subMatch[1];
1578
+ parts[3] = subMatch[2];
1579
+ parts[4] = subMatch[3];
1580
+ }
1581
+ }
1582
+ const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);
1583
+ return createFrame(platform, filename, func, parts[3] ? +parts[3] : void 0, parts[4] ? +parts[4] : void 0);
1584
+ }
1585
+ };
1586
+ }
1587
+ });
1588
+
1589
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/parsers/winjs.mjs
1590
+ var winjsRegex, winjsStackLineParser;
1591
+ var init_winjs = __esm({
1592
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/parsers/winjs.mjs"() {
1593
+ init_base();
1594
+ winjsRegex = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1595
+ winjsStackLineParser = (line, platform) => {
1596
+ const parts = winjsRegex.exec(line);
1597
+ return parts ? createFrame(platform, parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : void 0) : void 0;
1598
+ };
1599
+ }
1600
+ });
1601
+
1602
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs
1603
+ var geckoREgex, geckoEvalRegex, geckoStackLineParser;
1604
+ var init_gecko = __esm({
1605
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs"() {
1606
+ init_base();
1607
+ init_safari();
1608
+ geckoREgex = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i;
1609
+ geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
1610
+ geckoStackLineParser = (line, platform) => {
1611
+ const parts = geckoREgex.exec(line);
1612
+ if (parts) {
1613
+ const isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
1614
+ if (isEval) {
1615
+ const subMatch = geckoEvalRegex.exec(parts[3]);
1616
+ if (subMatch) {
1617
+ parts[1] = parts[1] || "eval";
1618
+ parts[3] = subMatch[1];
1619
+ parts[4] = subMatch[2];
1620
+ parts[5] = "";
1621
+ }
1622
+ }
1623
+ let filename = parts[3];
1624
+ let func = parts[1] || UNKNOWN_FUNCTION;
1625
+ [func, filename] = extractSafariExtensionDetails(func, filename);
1626
+ return createFrame(platform, filename, func, parts[4] ? +parts[4] : void 0, parts[5] ? +parts[5] : void 0);
1627
+ }
1628
+ };
1629
+ }
1630
+ });
1631
+
1632
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/parsers/opera.mjs
1633
+ var opera10Regex, opera10StackLineParser, opera11Regex, opera11StackLineParser;
1634
+ var init_opera = __esm({
1635
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/parsers/opera.mjs"() {
1636
+ init_base();
1637
+ opera10Regex = / line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i;
1638
+ opera10StackLineParser = (line, platform) => {
1639
+ const parts = opera10Regex.exec(line);
1640
+ return parts ? createFrame(platform, parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : void 0;
1641
+ };
1642
+ opera11Regex = / line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i;
1643
+ opera11StackLineParser = (line, platform) => {
1644
+ const parts = opera11Regex.exec(line);
1645
+ return parts ? createFrame(platform, parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : void 0;
1646
+ };
1647
+ }
1648
+ });
1649
+
1650
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs
1651
+ function filenameIsInApp(filename, isNative = false) {
1652
+ const isInternal = isNative || filename && !filename.startsWith("/") && !filename.match(/^[A-Z]:/) && !filename.startsWith(".") && !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//);
1653
+ return !isInternal && void 0 !== filename && !filename.includes("node_modules/");
1654
+ }
1655
+ function _parseIntOrUndefined(input) {
1656
+ return parseInt(input || "", 10) || void 0;
1657
+ }
1658
+ var FILENAME_MATCH, FULL_MATCH, nodeStackLineParser;
1659
+ var init_node = __esm({
1660
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs"() {
1661
+ init_base();
1662
+ FILENAME_MATCH = /^\s*[-]{4,}$/;
1663
+ FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
1664
+ nodeStackLineParser = (line, platform) => {
1665
+ const lineMatch = line.match(FULL_MATCH);
1666
+ if (lineMatch) {
1667
+ let object;
1668
+ let method;
1669
+ let functionName;
1670
+ let typeName;
1671
+ let methodName;
1672
+ if (lineMatch[1]) {
1673
+ functionName = lineMatch[1];
1674
+ let methodStart = functionName.lastIndexOf(".");
1675
+ if ("." === functionName[methodStart - 1]) methodStart--;
1676
+ if (methodStart > 0) {
1677
+ object = functionName.slice(0, methodStart);
1678
+ method = functionName.slice(methodStart + 1);
1679
+ const objectEnd = object.indexOf(".Module");
1680
+ if (objectEnd > 0) {
1681
+ functionName = functionName.slice(objectEnd + 1);
1682
+ object = object.slice(0, objectEnd);
1683
+ }
1684
+ }
1685
+ typeName = void 0;
1686
+ }
1687
+ if (method) {
1688
+ typeName = object;
1689
+ methodName = method;
1690
+ }
1691
+ if ("<anonymous>" === method) {
1692
+ methodName = void 0;
1693
+ functionName = void 0;
1694
+ }
1695
+ if (void 0 === functionName) {
1696
+ methodName = methodName || UNKNOWN_FUNCTION;
1697
+ functionName = typeName ? `${typeName}.${methodName}` : methodName;
1698
+ }
1699
+ let filename = lineMatch[2]?.startsWith("file://") ? lineMatch[2].slice(7) : lineMatch[2];
1700
+ const isNative = "native" === lineMatch[5];
1701
+ if (filename?.match(/\/[A-Z]:/)) filename = filename.slice(1);
1702
+ if (!filename && lineMatch[5] && !isNative) filename = lineMatch[5];
1703
+ return {
1704
+ filename: filename ? decodeURI(filename) : void 0,
1705
+ module: void 0,
1706
+ function: functionName,
1707
+ lineno: _parseIntOrUndefined(lineMatch[3]),
1708
+ colno: _parseIntOrUndefined(lineMatch[4]),
1709
+ in_app: filenameIsInApp(filename || "", isNative),
1710
+ platform
1711
+ };
1712
+ }
1713
+ if (line.match(FILENAME_MATCH)) return {
1714
+ filename: line,
1715
+ platform
1716
+ };
1717
+ };
1718
+ }
1719
+ });
1720
+
1721
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs
1722
+ function reverseAndStripFrames(stack) {
1723
+ if (!stack.length) return [];
1724
+ const localStack = Array.from(stack);
1725
+ localStack.reverse();
1726
+ return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({
1727
+ ...frame,
1728
+ filename: frame.filename || getLastStackFrame(localStack).filename,
1729
+ function: frame.function || UNKNOWN_FUNCTION
1730
+ }));
1731
+ }
1732
+ function getLastStackFrame(arr) {
1733
+ return arr[arr.length - 1] || {};
1734
+ }
1735
+ function createStackParser(platform, ...parsers) {
1736
+ return (stack, skipFirstLines = 0) => {
1737
+ const frames = [];
1738
+ const lines = stack.split("\n");
1739
+ for (let i = skipFirstLines; i < lines.length; i++) {
1740
+ const line = lines[i];
1741
+ if (line.length > 1024) continue;
1742
+ const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, "$1") : line;
1743
+ if (!cleanedLine.match(/\S*Error: /)) {
1744
+ for (const parser of parsers) {
1745
+ const frame = parser(cleanedLine, platform);
1746
+ if (frame) {
1747
+ frames.push(frame);
1748
+ break;
1749
+ }
1750
+ }
1751
+ if (frames.length >= STACKTRACE_FRAME_LIMIT) break;
1752
+ }
1753
+ }
1754
+ return reverseAndStripFrames(frames);
1755
+ };
1756
+ }
1757
+ var WEBPACK_ERROR_REGEXP, STACKTRACE_FRAME_LIMIT;
1758
+ var init_parsers = __esm({
1759
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs"() {
1760
+ init_base();
1761
+ init_chrome();
1762
+ init_winjs();
1763
+ init_gecko();
1764
+ init_opera();
1765
+ init_node();
1766
+ WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
1767
+ STACKTRACE_FRAME_LIMIT = 50;
1768
+ }
1769
+ });
1770
+
1771
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/coercers/dom-exception-coercer.mjs
1772
+ var DOMExceptionCoercer;
1773
+ var init_dom_exception_coercer = __esm({
1774
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/coercers/dom-exception-coercer.mjs"() {
1775
+ init_utils();
1776
+ DOMExceptionCoercer = class {
1777
+ match(err) {
1778
+ return this.isDOMException(err) || this.isDOMError(err);
1779
+ }
1780
+ coerce(err, ctx) {
1781
+ const hasStack = isString(err.stack);
1782
+ return {
1783
+ type: this.getType(err),
1784
+ value: this.getValue(err),
1785
+ stack: hasStack ? err.stack : void 0,
1786
+ cause: err.cause ? ctx.next(err.cause) : void 0,
1787
+ synthetic: false
1788
+ };
1789
+ }
1790
+ getType(candidate) {
1791
+ return this.isDOMError(candidate) ? "DOMError" : "DOMException";
1792
+ }
1793
+ getValue(err) {
1794
+ const name = err.name || (this.isDOMError(err) ? "DOMError" : "DOMException");
1795
+ const message = err.message ? `${name}: ${err.message}` : name;
1796
+ return message;
1797
+ }
1798
+ isDOMException(err) {
1799
+ return isBuiltin(err, "DOMException");
1800
+ }
1801
+ isDOMError(err) {
1802
+ return isBuiltin(err, "DOMError");
1803
+ }
1804
+ };
1805
+ }
1806
+ });
1807
+
1808
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs
1809
+ var ErrorCoercer;
1810
+ var init_error_coercer = __esm({
1811
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs"() {
1812
+ init_utils();
1813
+ ErrorCoercer = class {
1814
+ match(err) {
1815
+ return isPlainError(err);
1816
+ }
1817
+ coerce(err, ctx) {
1818
+ return {
1819
+ type: this.getType(err),
1820
+ value: this.getMessage(err, ctx),
1821
+ stack: this.getStack(err),
1822
+ cause: err.cause ? ctx.next(err.cause) : void 0,
1823
+ synthetic: false
1824
+ };
1825
+ }
1826
+ getType(err) {
1827
+ return err.name || err.constructor.name;
1828
+ }
1829
+ getMessage(err, _ctx) {
1830
+ const message = err.message;
1831
+ if (message.error && "string" == typeof message.error.message) return String(message.error.message);
1832
+ return String(message);
1833
+ }
1834
+ getStack(err) {
1835
+ return err.stacktrace || err.stack || void 0;
1836
+ }
1837
+ };
1838
+ }
1839
+ });
1840
+
1841
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/coercers/error-event-coercer.mjs
1842
+ var ErrorEventCoercer;
1843
+ var init_error_event_coercer = __esm({
1844
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/coercers/error-event-coercer.mjs"() {
1845
+ init_utils();
1846
+ ErrorEventCoercer = class {
1847
+ constructor() {
1848
+ }
1849
+ match(err) {
1850
+ return isErrorEvent(err) && void 0 != err.error;
1851
+ }
1852
+ coerce(err, ctx) {
1853
+ const exceptionLike = ctx.apply(err.error);
1854
+ if (!exceptionLike) return {
1855
+ type: "ErrorEvent",
1856
+ value: err.message,
1857
+ stack: ctx.syntheticException?.stack,
1858
+ synthetic: true
1859
+ };
1860
+ return exceptionLike;
1861
+ }
1862
+ };
1863
+ }
1864
+ });
1865
+
1866
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs
1867
+ var ERROR_TYPES_PATTERN, StringCoercer;
1868
+ var init_string_coercer = __esm({
1869
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs"() {
1870
+ ERROR_TYPES_PATTERN = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;
1871
+ StringCoercer = class {
1872
+ match(input) {
1873
+ return "string" == typeof input;
1874
+ }
1875
+ coerce(input, ctx) {
1876
+ const [type, value] = this.getInfos(input);
1877
+ return {
1878
+ type: type ?? "Error",
1879
+ value: value ?? input,
1880
+ stack: ctx.syntheticException?.stack,
1881
+ synthetic: true
1882
+ };
1883
+ }
1884
+ getInfos(candidate) {
1885
+ let type = "Error";
1886
+ let value = candidate;
1887
+ const groups = candidate.match(ERROR_TYPES_PATTERN);
1888
+ if (groups) {
1889
+ type = groups[1];
1890
+ value = groups[2];
1891
+ }
1892
+ return [
1893
+ type,
1894
+ value
1895
+ ];
1896
+ }
1897
+ };
1898
+ }
1899
+ });
1900
+
1901
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/types.mjs
1902
+ var severityLevels;
1903
+ var init_types2 = __esm({
1904
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/types.mjs"() {
1905
+ severityLevels = [
1906
+ "fatal",
1907
+ "error",
1908
+ "warning",
1909
+ "log",
1910
+ "info",
1911
+ "debug"
1912
+ ];
1913
+ }
1914
+ });
1915
+
1916
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs
1917
+ function extractExceptionKeysForMessage(err, maxLength = 40) {
1918
+ const keys = Object.keys(err);
1919
+ keys.sort();
1920
+ if (!keys.length) return "[object has no keys]";
1921
+ for (let i = keys.length; i > 0; i--) {
1922
+ const serialized = keys.slice(0, i).join(", ");
1923
+ if (!(serialized.length > maxLength)) {
1924
+ if (i === keys.length) return serialized;
1925
+ return serialized.length <= maxLength ? serialized : `${serialized.slice(0, maxLength)}...`;
1926
+ }
1927
+ }
1928
+ return "";
1929
+ }
1930
+ var init_utils2 = __esm({
1931
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs"() {
1932
+ }
1933
+ });
1934
+
1935
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs
1936
+ var ObjectCoercer;
1937
+ var init_object_coercer = __esm({
1938
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs"() {
1939
+ init_utils();
1940
+ init_types2();
1941
+ init_utils2();
1942
+ ObjectCoercer = class {
1943
+ match(candidate) {
1944
+ return "object" == typeof candidate && null !== candidate;
1945
+ }
1946
+ coerce(candidate, ctx) {
1947
+ const errorProperty = this.getErrorPropertyFromObject(candidate);
1948
+ if (errorProperty) return ctx.apply(errorProperty);
1949
+ return {
1950
+ type: this.getType(candidate),
1951
+ value: this.getValue(candidate),
1952
+ stack: ctx.syntheticException?.stack,
1953
+ level: this.isSeverityLevel(candidate.level) ? candidate.level : "error",
1954
+ synthetic: true
1955
+ };
1956
+ }
1957
+ getType(err) {
1958
+ return isEvent(err) ? err.constructor.name : "Error";
1959
+ }
1960
+ getValue(err) {
1961
+ if ("name" in err && "string" == typeof err.name) {
1962
+ let message = `'${err.name}' captured as exception`;
1963
+ if ("message" in err && "string" == typeof err.message) message += ` with message: '${err.message}'`;
1964
+ return message;
1965
+ }
1966
+ if ("message" in err && "string" == typeof err.message) return err.message;
1967
+ const className = this.getObjectClassName(err);
1968
+ const keys = extractExceptionKeysForMessage(err);
1969
+ return `${className && "Object" !== className ? `'${className}'` : "Object"} captured as exception with keys: ${keys}`;
1970
+ }
1971
+ isSeverityLevel(x) {
1972
+ return isString(x) && !isEmptyString(x) && severityLevels.indexOf(x) >= 0;
1973
+ }
1974
+ getErrorPropertyFromObject(obj) {
1975
+ for (const prop in obj) if (Object.prototype.hasOwnProperty.call(obj, prop)) {
1976
+ const value = obj[prop];
1977
+ if (isError(value)) return value;
1978
+ }
1979
+ }
1980
+ getObjectClassName(obj) {
1981
+ try {
1982
+ const prototype = Object.getPrototypeOf(obj);
1983
+ return prototype ? prototype.constructor.name : void 0;
1984
+ } catch (e) {
1985
+ return;
1986
+ }
1987
+ }
1988
+ };
1989
+ }
1990
+ });
1991
+
1992
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs
1993
+ var EventCoercer;
1994
+ var init_event_coercer = __esm({
1995
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs"() {
1996
+ init_utils();
1997
+ init_utils2();
1998
+ EventCoercer = class {
1999
+ match(err) {
2000
+ return isEvent(err);
2001
+ }
2002
+ coerce(evt, ctx) {
2003
+ const constructorName = evt.constructor.name;
2004
+ return {
2005
+ type: constructorName,
2006
+ value: `${constructorName} captured as exception with keys: ${extractExceptionKeysForMessage(evt)}`,
2007
+ stack: ctx.syntheticException?.stack,
2008
+ synthetic: true
2009
+ };
2010
+ }
2011
+ };
2012
+ }
2013
+ });
2014
+
2015
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs
2016
+ var PrimitiveCoercer;
2017
+ var init_primitive_coercer = __esm({
2018
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs"() {
2019
+ init_utils();
2020
+ PrimitiveCoercer = class {
2021
+ match(candidate) {
2022
+ return isPrimitive(candidate);
2023
+ }
2024
+ coerce(value, ctx) {
2025
+ return {
2026
+ type: "Error",
2027
+ value: `Primitive value captured as exception: ${String(value)}`,
2028
+ stack: ctx.syntheticException?.stack,
2029
+ synthetic: true
2030
+ };
2031
+ }
2032
+ };
2033
+ }
2034
+ });
2035
+
2036
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/coercers/promise-rejection-event.mjs
2037
+ var PromiseRejectionEventCoercer;
2038
+ var init_promise_rejection_event = __esm({
2039
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/coercers/promise-rejection-event.mjs"() {
2040
+ init_utils();
2041
+ PromiseRejectionEventCoercer = class {
2042
+ match(err) {
2043
+ return isBuiltin(err, "PromiseRejectionEvent");
2044
+ }
2045
+ coerce(err, ctx) {
2046
+ const reason = this.getUnhandledRejectionReason(err);
2047
+ if (isPrimitive(reason)) return {
2048
+ type: "UnhandledRejection",
2049
+ value: `Non-Error promise rejection captured with value: ${String(reason)}`,
2050
+ stack: ctx.syntheticException?.stack,
2051
+ synthetic: true
2052
+ };
2053
+ return ctx.apply(reason);
2054
+ }
2055
+ getUnhandledRejectionReason(error) {
2056
+ if (isPrimitive(error)) return error;
2057
+ try {
2058
+ if ("reason" in error) return error.reason;
2059
+ if ("detail" in error && "reason" in error.detail) return error.detail.reason;
2060
+ } catch {
2061
+ }
2062
+ return error;
2063
+ }
2064
+ };
2065
+ }
2066
+ });
2067
+
2068
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/coercers/index.mjs
2069
+ var init_coercers = __esm({
2070
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/coercers/index.mjs"() {
2071
+ init_dom_exception_coercer();
2072
+ init_error_coercer();
2073
+ init_error_event_coercer();
2074
+ init_string_coercer();
2075
+ init_object_coercer();
2076
+ init_event_coercer();
2077
+ init_primitive_coercer();
2078
+ init_promise_rejection_event();
2079
+ }
2080
+ });
2081
+
2082
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/utils.mjs
2083
+ var ReduceableCache;
2084
+ var init_utils3 = __esm({
2085
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/utils.mjs"() {
2086
+ ReduceableCache = class {
2087
+ constructor(_maxSize) {
2088
+ this._maxSize = _maxSize;
2089
+ this._cache = /* @__PURE__ */ new Map();
2090
+ }
2091
+ get(key) {
2092
+ const value = this._cache.get(key);
2093
+ if (void 0 === value) return;
2094
+ this._cache.delete(key);
2095
+ this._cache.set(key, value);
2096
+ return value;
2097
+ }
2098
+ set(key, value) {
2099
+ this._cache.set(key, value);
2100
+ }
2101
+ reduce() {
2102
+ while (this._cache.size >= this._maxSize) {
2103
+ const value = this._cache.keys().next().value;
2104
+ if (value) this._cache.delete(value);
2105
+ }
2106
+ }
2107
+ };
2108
+ }
2109
+ });
2110
+
2111
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/index.mjs
2112
+ var error_tracking_exports = {};
2113
+ __export(error_tracking_exports, {
2114
+ DOMExceptionCoercer: () => DOMExceptionCoercer,
2115
+ ErrorCoercer: () => ErrorCoercer,
2116
+ ErrorEventCoercer: () => ErrorEventCoercer,
2117
+ ErrorPropertiesBuilder: () => ErrorPropertiesBuilder,
2118
+ EventCoercer: () => EventCoercer,
2119
+ ObjectCoercer: () => ObjectCoercer,
2120
+ PrimitiveCoercer: () => PrimitiveCoercer,
2121
+ PromiseRejectionEventCoercer: () => PromiseRejectionEventCoercer,
2122
+ ReduceableCache: () => ReduceableCache,
2123
+ StringCoercer: () => StringCoercer,
2124
+ chromeStackLineParser: () => chromeStackLineParser,
2125
+ createStackParser: () => createStackParser,
2126
+ geckoStackLineParser: () => geckoStackLineParser,
2127
+ nodeStackLineParser: () => nodeStackLineParser,
2128
+ opera10StackLineParser: () => opera10StackLineParser,
2129
+ opera11StackLineParser: () => opera11StackLineParser,
2130
+ reverseAndStripFrames: () => reverseAndStripFrames,
2131
+ winjsStackLineParser: () => winjsStackLineParser
2132
+ });
2133
+ var init_error_tracking = __esm({
2134
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/error-tracking/index.mjs"() {
2135
+ init_error_properties_builder();
2136
+ init_parsers();
2137
+ init_coercers();
2138
+ init_utils3();
2139
+ }
2140
+ });
2141
+
2142
+ // ../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/index.mjs
2143
+ var init_dist = __esm({
2144
+ "../../node_modules/.pnpm/@posthog+core@1.6.0/node_modules/@posthog/core/dist/index.mjs"() {
2145
+ init_featureFlagUtils();
2146
+ init_uuidv7();
2147
+ init_utils();
2148
+ init_posthog_core();
2149
+ init_posthog_core_stateless();
2150
+ init_types();
2151
+ init_error_tracking();
2152
+ }
2153
+ });
2154
+ async function addSourceContext(frames) {
2155
+ const filesToLines = {};
2156
+ for (let i = frames.length - 1; i >= 0; i--) {
2157
+ const frame = frames[i];
2158
+ const filename = frame?.filename;
2159
+ if (!frame || "string" != typeof filename || "number" != typeof frame.lineno || shouldSkipContextLinesForFile(filename) || shouldSkipContextLinesForFrame(frame)) continue;
2160
+ const filesToLinesOutput = filesToLines[filename];
2161
+ if (!filesToLinesOutput) filesToLines[filename] = [];
2162
+ filesToLines[filename].push(frame.lineno);
2163
+ }
2164
+ const files = Object.keys(filesToLines);
2165
+ if (0 == files.length) return frames;
2166
+ const readlinePromises = [];
2167
+ for (const file of files) {
2168
+ if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(file)) continue;
2169
+ const filesToLineRanges = filesToLines[file];
2170
+ if (!filesToLineRanges) continue;
2171
+ filesToLineRanges.sort((a, b) => a - b);
2172
+ const ranges = makeLineReaderRanges(filesToLineRanges);
2173
+ if (ranges.every((r) => rangeExistsInContentCache(file, r))) continue;
2174
+ const cache = emplace(LRU_FILE_CONTENTS_CACHE, file, {});
2175
+ readlinePromises.push(getContextLinesFromFile(file, ranges, cache));
2176
+ }
2177
+ await Promise.all(readlinePromises).catch(() => {
2178
+ });
2179
+ if (frames && frames.length > 0) addSourceContextToFrames(frames, LRU_FILE_CONTENTS_CACHE);
2180
+ LRU_FILE_CONTENTS_CACHE.reduce();
2181
+ return frames;
2182
+ }
2183
+ function getContextLinesFromFile(path, ranges, output) {
2184
+ return new Promise((resolve) => {
2185
+ const stream = createReadStream(path);
2186
+ const lineReaded = createInterface({
2187
+ input: stream
2188
+ });
2189
+ function destroyStreamAndResolve() {
2190
+ stream.destroy();
2191
+ resolve();
2192
+ }
2193
+ let lineNumber = 0;
2194
+ let currentRangeIndex = 0;
2195
+ const range = ranges[currentRangeIndex];
2196
+ if (void 0 === range) return void destroyStreamAndResolve();
2197
+ let rangeStart = range[0];
2198
+ let rangeEnd = range[1];
2199
+ function onStreamError() {
2200
+ LRU_FILE_CONTENTS_FS_READ_FAILED.set(path, 1);
2201
+ lineReaded.close();
2202
+ lineReaded.removeAllListeners();
2203
+ destroyStreamAndResolve();
2204
+ }
2205
+ stream.on("error", onStreamError);
2206
+ lineReaded.on("error", onStreamError);
2207
+ lineReaded.on("close", destroyStreamAndResolve);
2208
+ lineReaded.on("line", (line) => {
2209
+ lineNumber++;
2210
+ if (lineNumber < rangeStart) return;
2211
+ output[lineNumber] = snipLine(line, 0);
2212
+ if (lineNumber >= rangeEnd) {
2213
+ if (currentRangeIndex === ranges.length - 1) {
2214
+ lineReaded.close();
2215
+ lineReaded.removeAllListeners();
2216
+ return;
2217
+ }
2218
+ currentRangeIndex++;
2219
+ const range2 = ranges[currentRangeIndex];
2220
+ if (void 0 === range2) {
2221
+ lineReaded.close();
2222
+ lineReaded.removeAllListeners();
2223
+ return;
2224
+ }
2225
+ rangeStart = range2[0];
2226
+ rangeEnd = range2[1];
2227
+ }
2228
+ });
2229
+ });
2230
+ }
2231
+ function addSourceContextToFrames(frames, cache) {
2232
+ for (const frame of frames) if (frame.filename && void 0 === frame.context_line && "number" == typeof frame.lineno) {
2233
+ const contents = cache.get(frame.filename);
2234
+ if (void 0 === contents) continue;
2235
+ addContextToFrame(frame.lineno, frame, contents);
2236
+ }
2237
+ }
2238
+ function addContextToFrame(lineno, frame, contents) {
2239
+ if (void 0 === frame.lineno || void 0 === contents) return;
2240
+ frame.pre_context = [];
2241
+ for (let i = makeRangeStart(lineno); i < lineno; i++) {
2242
+ const line = contents[i];
2243
+ if (void 0 === line) return void clearLineContext(frame);
2244
+ frame.pre_context.push(line);
2245
+ }
2246
+ if (void 0 === contents[lineno]) return void clearLineContext(frame);
2247
+ frame.context_line = contents[lineno];
2248
+ const end = makeRangeEnd(lineno);
2249
+ frame.post_context = [];
2250
+ for (let i = lineno + 1; i <= end; i++) {
2251
+ const line = contents[i];
2252
+ if (void 0 === line) break;
2253
+ frame.post_context.push(line);
2254
+ }
2255
+ }
2256
+ function clearLineContext(frame) {
2257
+ delete frame.pre_context;
2258
+ delete frame.context_line;
2259
+ delete frame.post_context;
2260
+ }
2261
+ function shouldSkipContextLinesForFile(path) {
2262
+ return path.startsWith("node:") || path.endsWith(".min.js") || path.endsWith(".min.cjs") || path.endsWith(".min.mjs") || path.startsWith("data:");
2263
+ }
2264
+ function shouldSkipContextLinesForFrame(frame) {
2265
+ if (void 0 !== frame.lineno && frame.lineno > MAX_CONTEXTLINES_LINENO) return true;
2266
+ if (void 0 !== frame.colno && frame.colno > MAX_CONTEXTLINES_COLNO) return true;
2267
+ return false;
2268
+ }
2269
+ function rangeExistsInContentCache(file, range) {
2270
+ const contents = LRU_FILE_CONTENTS_CACHE.get(file);
2271
+ if (void 0 === contents) return false;
2272
+ for (let i = range[0]; i <= range[1]; i++) if (void 0 === contents[i]) return false;
2273
+ return true;
2274
+ }
2275
+ function makeLineReaderRanges(lines) {
2276
+ if (!lines.length) return [];
2277
+ let i = 0;
2278
+ const line = lines[0];
2279
+ if ("number" != typeof line) return [];
2280
+ let current = makeContextRange(line);
2281
+ const out = [];
2282
+ while (true) {
2283
+ if (i === lines.length - 1) {
2284
+ out.push(current);
2285
+ break;
2286
+ }
2287
+ const next = lines[i + 1];
2288
+ if ("number" != typeof next) break;
2289
+ if (next <= current[1]) current[1] = next + DEFAULT_LINES_OF_CONTEXT;
2290
+ else {
2291
+ out.push(current);
2292
+ current = makeContextRange(next);
2293
+ }
2294
+ i++;
2295
+ }
2296
+ return out;
2297
+ }
2298
+ function makeContextRange(line) {
2299
+ return [
2300
+ makeRangeStart(line),
2301
+ makeRangeEnd(line)
2302
+ ];
2303
+ }
2304
+ function makeRangeStart(line) {
2305
+ return Math.max(1, line - DEFAULT_LINES_OF_CONTEXT);
2306
+ }
2307
+ function makeRangeEnd(line) {
2308
+ return line + DEFAULT_LINES_OF_CONTEXT;
2309
+ }
2310
+ function emplace(map, key, contents) {
2311
+ const value = map.get(key);
2312
+ if (void 0 === value) {
2313
+ map.set(key, contents);
2314
+ return contents;
2315
+ }
2316
+ return value;
2317
+ }
2318
+ function snipLine(line, colno) {
2319
+ let newLine = line;
2320
+ const lineLength = newLine.length;
2321
+ if (lineLength <= 150) return newLine;
2322
+ if (colno > lineLength) colno = lineLength;
2323
+ let start = Math.max(colno - 60, 0);
2324
+ if (start < 5) start = 0;
2325
+ let end = Math.min(start + 140, lineLength);
2326
+ if (end > lineLength - 5) end = lineLength;
2327
+ if (end === lineLength) start = Math.max(end - 140, 0);
2328
+ newLine = newLine.slice(start, end);
2329
+ if (start > 0) newLine = `...${newLine}`;
2330
+ if (end < lineLength) newLine += "...";
2331
+ return newLine;
2332
+ }
2333
+ var LRU_FILE_CONTENTS_CACHE, LRU_FILE_CONTENTS_FS_READ_FAILED, DEFAULT_LINES_OF_CONTEXT, MAX_CONTEXTLINES_COLNO, MAX_CONTEXTLINES_LINENO;
2334
+ var init_context_lines_node = __esm({
2335
+ "../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs"() {
2336
+ init_dist();
2337
+ LRU_FILE_CONTENTS_CACHE = new error_tracking_exports.ReduceableCache(25);
2338
+ LRU_FILE_CONTENTS_FS_READ_FAILED = new error_tracking_exports.ReduceableCache(20);
2339
+ DEFAULT_LINES_OF_CONTEXT = 7;
2340
+ MAX_CONTEXTLINES_COLNO = 1e3;
2341
+ MAX_CONTEXTLINES_LINENO = 1e4;
2342
+ }
2343
+ });
2344
+
2345
+ // ../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs
2346
+ function makeUncaughtExceptionHandler(captureFn, onFatalFn) {
2347
+ let calledFatalError = false;
2348
+ return Object.assign((error) => {
2349
+ const userProvidedListenersCount = global.process.listeners("uncaughtException").filter((listener) => "domainUncaughtExceptionClear" !== listener.name && true !== listener._posthogErrorHandler).length;
2350
+ const processWouldExit = 0 === userProvidedListenersCount;
2351
+ captureFn(error, {
2352
+ mechanism: {
2353
+ type: "onuncaughtexception",
2354
+ handled: false
2355
+ }
2356
+ });
2357
+ if (!calledFatalError && processWouldExit) {
2358
+ calledFatalError = true;
2359
+ onFatalFn(error);
2360
+ }
2361
+ }, {
2362
+ _posthogErrorHandler: true
2363
+ });
2364
+ }
2365
+ function addUncaughtExceptionListener(captureFn, onFatalFn) {
2366
+ global.process.on("uncaughtException", makeUncaughtExceptionHandler(captureFn, onFatalFn));
2367
+ }
2368
+ function addUnhandledRejectionListener(captureFn) {
2369
+ global.process.on("unhandledRejection", (reason) => captureFn(reason, {
2370
+ mechanism: {
2371
+ type: "onunhandledrejection",
2372
+ handled: false
2373
+ }
2374
+ }));
2375
+ }
2376
+ var init_autocapture = __esm({
2377
+ "../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs"() {
2378
+ }
2379
+ });
2380
+
2381
+ // ../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/extensions/error-tracking/index.mjs
2382
+ var SHUTDOWN_TIMEOUT, ErrorTracking;
2383
+ var init_error_tracking2 = __esm({
2384
+ "../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/extensions/error-tracking/index.mjs"() {
2385
+ init_autocapture();
2386
+ init_dist();
2387
+ SHUTDOWN_TIMEOUT = 2e3;
2388
+ ErrorTracking = class _ErrorTracking {
2389
+ constructor(client, options, _logger) {
2390
+ this.client = client;
2391
+ this._exceptionAutocaptureEnabled = options.enableExceptionAutocapture || false;
2392
+ this._logger = _logger;
2393
+ this._rateLimiter = new BucketedRateLimiter({
2394
+ refillRate: 1,
2395
+ bucketSize: 10,
2396
+ refillInterval: 1e4,
2397
+ _logger: this._logger
2398
+ });
2399
+ this.startAutocaptureIfEnabled();
2400
+ }
2401
+ static async buildEventMessage(error, hint, distinctId, additionalProperties) {
2402
+ const properties = {
2403
+ ...additionalProperties
2404
+ };
2405
+ if (!distinctId) properties.$process_person_profile = false;
2406
+ const exceptionProperties = this.errorPropertiesBuilder.buildFromUnknown(error, hint);
2407
+ exceptionProperties.$exception_list = await this.errorPropertiesBuilder.modifyFrames(exceptionProperties.$exception_list);
2408
+ return {
2409
+ event: "$exception",
2410
+ distinctId: distinctId || uuidv7(),
2411
+ properties: {
2412
+ ...exceptionProperties,
2413
+ ...properties
2414
+ }
2415
+ };
2416
+ }
2417
+ startAutocaptureIfEnabled() {
2418
+ if (this.isEnabled()) {
2419
+ addUncaughtExceptionListener(this.onException.bind(this), this.onFatalError.bind(this));
2420
+ addUnhandledRejectionListener(this.onException.bind(this));
2421
+ }
2422
+ }
2423
+ onException(exception, hint) {
2424
+ this.client.addPendingPromise((async () => {
2425
+ const eventMessage = await _ErrorTracking.buildEventMessage(exception, hint);
2426
+ const exceptionProperties = eventMessage.properties;
2427
+ const exceptionType = exceptionProperties?.$exception_list[0]?.type ?? "Exception";
2428
+ const isRateLimited = this._rateLimiter.consumeRateLimit(exceptionType);
2429
+ if (isRateLimited) return void this._logger.info("Skipping exception capture because of client rate limiting.", {
2430
+ exception: exceptionType
2431
+ });
2432
+ return this.client.capture(eventMessage);
2433
+ })());
2434
+ }
2435
+ async onFatalError(exception) {
2436
+ console.error(exception);
2437
+ await this.client.shutdown(SHUTDOWN_TIMEOUT);
2438
+ process.exit(1);
2439
+ }
2440
+ isEnabled() {
2441
+ return !this.client.isDisabled && this._exceptionAutocaptureEnabled;
2442
+ }
2443
+ shutdown() {
2444
+ this._rateLimiter.stop();
2445
+ }
2446
+ };
2447
+ }
2448
+ });
2449
+
2450
+ // ../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/version.mjs
2451
+ var version;
2452
+ var init_version = __esm({
2453
+ "../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/version.mjs"() {
2454
+ version = "5.14.0";
2455
+ }
2456
+ });
2457
+
2458
+ // ../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/extensions/feature-flags/crypto.mjs
2459
+ async function hashSHA1(text) {
2460
+ const subtle = globalThis.crypto?.subtle;
2461
+ if (!subtle) throw new Error("SubtleCrypto API not available");
2462
+ const hashBuffer = await subtle.digest("SHA-1", new TextEncoder().encode(text));
2463
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
2464
+ return hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
2465
+ }
2466
+ var init_crypto = __esm({
2467
+ "../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/extensions/feature-flags/crypto.mjs"() {
2468
+ }
2469
+ });
2470
+
2471
+ // ../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs
2472
+ async function _hash(key, distinctId, salt = "") {
2473
+ const hashString = await hashSHA1(`${key}.${distinctId}${salt}`);
2474
+ return parseInt(hashString.slice(0, 15), 16) / LONG_SCALE;
2475
+ }
2476
+ function matchProperty(property, propertyValues, warnFunction) {
2477
+ const key = property.key;
2478
+ const value = property.value;
2479
+ const operator = property.operator || "exact";
2480
+ if (key in propertyValues) {
2481
+ if ("is_not_set" === operator) throw new InconclusiveMatchError("Operator is_not_set is not supported");
2482
+ } else throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`);
2483
+ const overrideValue = propertyValues[key];
2484
+ if (null == overrideValue && !NULL_VALUES_ALLOWED_OPERATORS.includes(operator)) {
2485
+ if (warnFunction) warnFunction(`Property ${key} cannot have a value of null/undefined with the ${operator} operator`);
2486
+ return false;
2487
+ }
2488
+ function computeExactMatch(value2, overrideValue2) {
2489
+ if (Array.isArray(value2)) return value2.map((val) => String(val).toLowerCase()).includes(String(overrideValue2).toLowerCase());
2490
+ return String(value2).toLowerCase() === String(overrideValue2).toLowerCase();
2491
+ }
2492
+ function compare(lhs, rhs, operator2) {
2493
+ if ("gt" === operator2) return lhs > rhs;
2494
+ if ("gte" === operator2) return lhs >= rhs;
2495
+ if ("lt" === operator2) return lhs < rhs;
2496
+ if ("lte" === operator2) return lhs <= rhs;
2497
+ throw new Error(`Invalid operator: ${operator2}`);
2498
+ }
2499
+ switch (operator) {
2500
+ case "exact":
2501
+ return computeExactMatch(value, overrideValue);
2502
+ case "is_not":
2503
+ return !computeExactMatch(value, overrideValue);
2504
+ case "is_set":
2505
+ return key in propertyValues;
2506
+ case "icontains":
2507
+ return String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
2508
+ case "not_icontains":
2509
+ return !String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
2510
+ case "regex":
2511
+ return isValidRegex(String(value)) && null !== String(overrideValue).match(String(value));
2512
+ case "not_regex":
2513
+ return isValidRegex(String(value)) && null === String(overrideValue).match(String(value));
2514
+ case "gt":
2515
+ case "gte":
2516
+ case "lt":
2517
+ case "lte": {
2518
+ let parsedValue = "number" == typeof value ? value : null;
2519
+ if ("string" == typeof value) try {
2520
+ parsedValue = parseFloat(value);
2521
+ } catch (err) {
2522
+ }
2523
+ if (null == parsedValue || null == overrideValue) return compare(String(overrideValue), String(value), operator);
2524
+ if ("string" == typeof overrideValue) return compare(overrideValue, String(value), operator);
2525
+ return compare(overrideValue, parsedValue, operator);
2526
+ }
2527
+ case "is_date_after":
2528
+ case "is_date_before": {
2529
+ if ("boolean" == typeof value) throw new InconclusiveMatchError("Date operations cannot be performed on boolean values");
2530
+ let parsedDate = relativeDateParseForFeatureFlagMatching(String(value));
2531
+ if (null == parsedDate) parsedDate = convertToDateTime(value);
2532
+ if (null == parsedDate) throw new InconclusiveMatchError(`Invalid date: ${value}`);
2533
+ const overrideDate = convertToDateTime(overrideValue);
2534
+ if ([
2535
+ "is_date_before"
2536
+ ].includes(operator)) return overrideDate < parsedDate;
2537
+ return overrideDate > parsedDate;
2538
+ }
2539
+ default:
2540
+ throw new InconclusiveMatchError(`Unknown operator: ${operator}`);
2541
+ }
2542
+ }
2543
+ function checkCohortExists(cohortId, cohortProperties) {
2544
+ if (!(cohortId in cohortProperties)) throw new RequiresServerEvaluation(`cohort ${cohortId} not found in local cohorts - likely a static cohort that requires server evaluation`);
2545
+ }
2546
+ function matchCohort(property, propertyValues, cohortProperties, debugMode = false) {
2547
+ const cohortId = String(property.value);
2548
+ checkCohortExists(cohortId, cohortProperties);
2549
+ const propertyGroup = cohortProperties[cohortId];
2550
+ return matchPropertyGroup(propertyGroup, propertyValues, cohortProperties, debugMode);
2551
+ }
2552
+ function matchPropertyGroup(propertyGroup, propertyValues, cohortProperties, debugMode = false) {
2553
+ if (!propertyGroup) return true;
2554
+ const propertyGroupType = propertyGroup.type;
2555
+ const properties = propertyGroup.values;
2556
+ if (!properties || 0 === properties.length) return true;
2557
+ let errorMatchingLocally = false;
2558
+ if ("values" in properties[0]) {
2559
+ for (const prop of properties) try {
2560
+ const matches = matchPropertyGroup(prop, propertyValues, cohortProperties, debugMode);
2561
+ if ("AND" === propertyGroupType) {
2562
+ if (!matches) return false;
2563
+ } else if (matches) return true;
2564
+ } catch (err) {
2565
+ if (err instanceof RequiresServerEvaluation) throw err;
2566
+ if (err instanceof InconclusiveMatchError) {
2567
+ if (debugMode) console.debug(`Failed to compute property ${prop} locally: ${err}`);
2568
+ errorMatchingLocally = true;
2569
+ } else throw err;
2570
+ }
2571
+ if (errorMatchingLocally) throw new InconclusiveMatchError("Can't match cohort without a given cohort property value");
2572
+ return "AND" === propertyGroupType;
2573
+ }
2574
+ for (const prop of properties) try {
2575
+ let matches;
2576
+ if ("cohort" === prop.type) matches = matchCohort(prop, propertyValues, cohortProperties, debugMode);
2577
+ else if ("flag" === prop.type) {
2578
+ if (debugMode) console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${prop.key || "unknown"}'`);
2579
+ continue;
2580
+ } else matches = matchProperty(prop, propertyValues);
2581
+ const negation = prop.negation || false;
2582
+ if ("AND" === propertyGroupType) {
2583
+ if (!matches && !negation) return false;
2584
+ if (matches && negation) return false;
2585
+ } else {
2586
+ if (matches && !negation) return true;
2587
+ if (!matches && negation) return true;
2588
+ }
2589
+ } catch (err) {
2590
+ if (err instanceof RequiresServerEvaluation) throw err;
2591
+ if (err instanceof InconclusiveMatchError) {
2592
+ if (debugMode) console.debug(`Failed to compute property ${prop} locally: ${err}`);
2593
+ errorMatchingLocally = true;
2594
+ } else throw err;
2595
+ }
2596
+ if (errorMatchingLocally) throw new InconclusiveMatchError("can't match cohort without a given cohort property value");
2597
+ return "AND" === propertyGroupType;
2598
+ }
2599
+ function isValidRegex(regex) {
2600
+ try {
2601
+ new RegExp(regex);
2602
+ return true;
2603
+ } catch (err) {
2604
+ return false;
2605
+ }
2606
+ }
2607
+ function convertToDateTime(value) {
2608
+ if (value instanceof Date) return value;
2609
+ if ("string" == typeof value || "number" == typeof value) {
2610
+ const date = new Date(value);
2611
+ if (!isNaN(date.valueOf())) return date;
2612
+ throw new InconclusiveMatchError(`${value} is in an invalid date format`);
2613
+ }
2614
+ throw new InconclusiveMatchError(`The date provided ${value} must be a string, number, or date object`);
2615
+ }
2616
+ function relativeDateParseForFeatureFlagMatching(value) {
2617
+ const regex = /^-?(?<number>[0-9]+)(?<interval>[a-z])$/;
2618
+ const match = value.match(regex);
2619
+ const parsedDt = new Date((/* @__PURE__ */ new Date()).toISOString());
2620
+ if (!match) return null;
2621
+ {
2622
+ if (!match.groups) return null;
2623
+ const number = parseInt(match.groups["number"]);
2624
+ if (number >= 1e4) return null;
2625
+ const interval = match.groups["interval"];
2626
+ if ("h" == interval) parsedDt.setUTCHours(parsedDt.getUTCHours() - number);
2627
+ else if ("d" == interval) parsedDt.setUTCDate(parsedDt.getUTCDate() - number);
2628
+ else if ("w" == interval) parsedDt.setUTCDate(parsedDt.getUTCDate() - 7 * number);
2629
+ else if ("m" == interval) parsedDt.setUTCMonth(parsedDt.getUTCMonth() - number);
2630
+ else {
2631
+ if ("y" != interval) return null;
2632
+ parsedDt.setUTCFullYear(parsedDt.getUTCFullYear() - number);
2633
+ }
2634
+ return parsedDt;
2635
+ }
2636
+ }
2637
+ var SIXTY_SECONDS, LONG_SCALE, NULL_VALUES_ALLOWED_OPERATORS, ClientError, InconclusiveMatchError, RequiresServerEvaluation, FeatureFlagsPoller;
2638
+ var init_feature_flags = __esm({
2639
+ "../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs"() {
2640
+ init_dist();
2641
+ init_crypto();
2642
+ SIXTY_SECONDS = 6e4;
2643
+ LONG_SCALE = 1152921504606847e3;
2644
+ NULL_VALUES_ALLOWED_OPERATORS = [
2645
+ "is_not"
2646
+ ];
2647
+ ClientError = class _ClientError extends Error {
2648
+ constructor(message) {
2649
+ super();
2650
+ Error.captureStackTrace(this, this.constructor);
2651
+ this.name = "ClientError";
2652
+ this.message = message;
2653
+ Object.setPrototypeOf(this, _ClientError.prototype);
2654
+ }
2655
+ };
2656
+ InconclusiveMatchError = class _InconclusiveMatchError extends Error {
2657
+ constructor(message) {
2658
+ super(message);
2659
+ this.name = this.constructor.name;
2660
+ Error.captureStackTrace(this, this.constructor);
2661
+ Object.setPrototypeOf(this, _InconclusiveMatchError.prototype);
2662
+ }
2663
+ };
2664
+ RequiresServerEvaluation = class _RequiresServerEvaluation extends Error {
2665
+ constructor(message) {
2666
+ super(message);
2667
+ this.name = this.constructor.name;
2668
+ Error.captureStackTrace(this, this.constructor);
2669
+ Object.setPrototypeOf(this, _RequiresServerEvaluation.prototype);
2670
+ }
2671
+ };
2672
+ FeatureFlagsPoller = class {
2673
+ constructor({ pollingInterval, personalApiKey, projectApiKey, timeout, host, customHeaders, ...options }) {
2674
+ this.debugMode = false;
2675
+ this.shouldBeginExponentialBackoff = false;
2676
+ this.backOffCount = 0;
2677
+ this.hasAttemptedCacheLoad = false;
2678
+ this.pollingInterval = pollingInterval;
2679
+ this.personalApiKey = personalApiKey;
2680
+ this.featureFlags = [];
2681
+ this.featureFlagsByKey = {};
2682
+ this.groupTypeMapping = {};
2683
+ this.cohorts = {};
2684
+ this.loadedSuccessfullyOnce = false;
2685
+ this.timeout = timeout;
2686
+ this.projectApiKey = projectApiKey;
2687
+ this.host = host;
2688
+ this.poller = void 0;
2689
+ this.fetch = options.fetch || fetch;
2690
+ this.onError = options.onError;
2691
+ this.customHeaders = customHeaders;
2692
+ this.onLoad = options.onLoad;
2693
+ this.cacheProvider = options.cacheProvider;
2694
+ this.loadFeatureFlags();
2695
+ }
2696
+ debug(enabled = true) {
2697
+ this.debugMode = enabled;
2698
+ }
2699
+ logMsgIfDebug(fn) {
2700
+ if (this.debugMode) fn();
2701
+ }
2702
+ async getFeatureFlag(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}) {
2703
+ await this.loadFeatureFlags();
2704
+ let response;
2705
+ let featureFlag;
2706
+ if (!this.loadedSuccessfullyOnce) return response;
2707
+ featureFlag = this.featureFlagsByKey[key];
2708
+ if (void 0 !== featureFlag) try {
2709
+ const result = await this.computeFlagAndPayloadLocally(featureFlag, distinctId, groups, personProperties, groupProperties);
2710
+ response = result.value;
2711
+ this.logMsgIfDebug(() => console.debug(`Successfully computed flag locally: ${key} -> ${response}`));
2712
+ } catch (e) {
2713
+ if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError) this.logMsgIfDebug(() => console.debug(`${e.name} when computing flag locally: ${key}: ${e.message}`));
2714
+ else if (e instanceof Error) this.onError?.(new Error(`Error computing flag locally: ${key}: ${e}`));
2715
+ }
2716
+ return response;
2717
+ }
2718
+ async getAllFlagsAndPayloads(distinctId, groups = {}, personProperties = {}, groupProperties = {}, flagKeysToExplicitlyEvaluate) {
2719
+ await this.loadFeatureFlags();
2720
+ const response = {};
2721
+ const payloads = {};
2722
+ let fallbackToFlags = 0 == this.featureFlags.length;
2723
+ const flagsToEvaluate = flagKeysToExplicitlyEvaluate ? flagKeysToExplicitlyEvaluate.map((key) => this.featureFlagsByKey[key]).filter(Boolean) : this.featureFlags;
2724
+ const sharedEvaluationCache = {};
2725
+ await Promise.all(flagsToEvaluate.map(async (flag) => {
2726
+ try {
2727
+ const { value: matchValue, payload: matchPayload } = await this.computeFlagAndPayloadLocally(flag, distinctId, groups, personProperties, groupProperties, void 0, sharedEvaluationCache);
2728
+ response[flag.key] = matchValue;
2729
+ if (matchPayload) payloads[flag.key] = matchPayload;
2730
+ } catch (e) {
2731
+ if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError) this.logMsgIfDebug(() => console.debug(`${e.name} when computing flag locally: ${flag.key}: ${e.message}`));
2732
+ else if (e instanceof Error) this.onError?.(new Error(`Error computing flag locally: ${flag.key}: ${e}`));
2733
+ fallbackToFlags = true;
2734
+ }
2735
+ }));
2736
+ return {
2737
+ response,
2738
+ payloads,
2739
+ fallbackToFlags
2740
+ };
2741
+ }
2742
+ async computeFlagAndPayloadLocally(flag, distinctId, groups = {}, personProperties = {}, groupProperties = {}, matchValue, evaluationCache, skipLoadCheck = false) {
2743
+ if (!skipLoadCheck) await this.loadFeatureFlags();
2744
+ if (!this.loadedSuccessfullyOnce) return {
2745
+ value: false,
2746
+ payload: null
2747
+ };
2748
+ let flagValue;
2749
+ flagValue = void 0 !== matchValue ? matchValue : await this.computeFlagValueLocally(flag, distinctId, groups, personProperties, groupProperties, evaluationCache);
2750
+ const payload = this.getFeatureFlagPayload(flag.key, flagValue);
2751
+ return {
2752
+ value: flagValue,
2753
+ payload
2754
+ };
2755
+ }
2756
+ async computeFlagValueLocally(flag, distinctId, groups = {}, personProperties = {}, groupProperties = {}, evaluationCache = {}) {
2757
+ if (flag.ensure_experience_continuity) throw new InconclusiveMatchError("Flag has experience continuity enabled");
2758
+ if (!flag.active) return false;
2759
+ const flagFilters = flag.filters || {};
2760
+ const aggregation_group_type_index = flagFilters.aggregation_group_type_index;
2761
+ if (void 0 == aggregation_group_type_index) return await this.matchFeatureFlagProperties(flag, distinctId, personProperties, evaluationCache);
2762
+ {
2763
+ const groupName = this.groupTypeMapping[String(aggregation_group_type_index)];
2764
+ if (!groupName) {
2765
+ this.logMsgIfDebug(() => console.warn(`[FEATURE FLAGS] Unknown group type index ${aggregation_group_type_index} for feature flag ${flag.key}`));
2766
+ throw new InconclusiveMatchError("Flag has unknown group type index");
2767
+ }
2768
+ if (!(groupName in groups)) {
2769
+ this.logMsgIfDebug(() => console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${flag.key} without group names passed in`));
2770
+ return false;
2771
+ }
2772
+ const focusedGroupProperties = groupProperties[groupName];
2773
+ return await this.matchFeatureFlagProperties(flag, groups[groupName], focusedGroupProperties, evaluationCache);
2774
+ }
2775
+ }
2776
+ getFeatureFlagPayload(key, flagValue) {
2777
+ let payload = null;
2778
+ if (false !== flagValue && null != flagValue) {
2779
+ if ("boolean" == typeof flagValue) payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue.toString()] || null;
2780
+ else if ("string" == typeof flagValue) payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue] || null;
2781
+ if (null != payload) {
2782
+ if ("object" == typeof payload) return payload;
2783
+ if ("string" == typeof payload) try {
2784
+ return JSON.parse(payload);
2785
+ } catch {
2786
+ }
2787
+ return payload;
2788
+ }
2789
+ }
2790
+ return null;
2791
+ }
2792
+ async evaluateFlagDependency(property, distinctId, properties, evaluationCache) {
2793
+ const targetFlagKey = property.key;
2794
+ if (!this.featureFlagsByKey) throw new InconclusiveMatchError("Feature flags not available for dependency evaluation");
2795
+ if (!("dependency_chain" in property)) throw new InconclusiveMatchError(`Flag dependency property for '${targetFlagKey}' is missing required 'dependency_chain' field`);
2796
+ const dependencyChain = property.dependency_chain;
2797
+ if (!Array.isArray(dependencyChain)) throw new InconclusiveMatchError(`Flag dependency property for '${targetFlagKey}' has an invalid 'dependency_chain' (expected array, got ${typeof dependencyChain})`);
2798
+ if (0 === dependencyChain.length) throw new InconclusiveMatchError(`Circular dependency detected for flag '${targetFlagKey}' (empty dependency chain)`);
2799
+ for (const depFlagKey of dependencyChain) {
2800
+ if (!(depFlagKey in evaluationCache)) {
2801
+ const depFlag = this.featureFlagsByKey[depFlagKey];
2802
+ if (depFlag) if (depFlag.active) try {
2803
+ const depResult = await this.matchFeatureFlagProperties(depFlag, distinctId, properties, evaluationCache);
2804
+ evaluationCache[depFlagKey] = depResult;
2805
+ } catch (error) {
2806
+ throw new InconclusiveMatchError(`Error evaluating flag dependency '${depFlagKey}' for flag '${targetFlagKey}': ${error}`);
2807
+ }
2808
+ else evaluationCache[depFlagKey] = false;
2809
+ else throw new InconclusiveMatchError(`Missing flag dependency '${depFlagKey}' for flag '${targetFlagKey}'`);
2810
+ }
2811
+ const cachedResult = evaluationCache[depFlagKey];
2812
+ if (null == cachedResult) throw new InconclusiveMatchError(`Dependency '${depFlagKey}' could not be evaluated`);
2813
+ }
2814
+ const targetFlagValue = evaluationCache[targetFlagKey];
2815
+ return this.flagEvaluatesToExpectedValue(property.value, targetFlagValue);
2816
+ }
2817
+ flagEvaluatesToExpectedValue(expectedValue, flagValue) {
2818
+ if ("boolean" == typeof expectedValue) return expectedValue === flagValue || "string" == typeof flagValue && "" !== flagValue && true === expectedValue;
2819
+ if ("string" == typeof expectedValue) return flagValue === expectedValue;
2820
+ return false;
2821
+ }
2822
+ async matchFeatureFlagProperties(flag, distinctId, properties, evaluationCache = {}) {
2823
+ const flagFilters = flag.filters || {};
2824
+ const flagConditions = flagFilters.groups || [];
2825
+ let isInconclusive = false;
2826
+ let result;
2827
+ for (const condition of flagConditions) try {
2828
+ if (await this.isConditionMatch(flag, distinctId, condition, properties, evaluationCache)) {
2829
+ const variantOverride = condition.variant;
2830
+ const flagVariants = flagFilters.multivariate?.variants || [];
2831
+ result = variantOverride && flagVariants.some((variant) => variant.key === variantOverride) ? variantOverride : await this.getMatchingVariant(flag, distinctId) || true;
2832
+ break;
2833
+ }
2834
+ } catch (e) {
2835
+ if (e instanceof RequiresServerEvaluation) throw e;
2836
+ if (e instanceof InconclusiveMatchError) isInconclusive = true;
2837
+ else throw e;
2838
+ }
2839
+ if (void 0 !== result) return result;
2840
+ if (isInconclusive) throw new InconclusiveMatchError("Can't determine if feature flag is enabled or not with given properties");
2841
+ return false;
2842
+ }
2843
+ async isConditionMatch(flag, distinctId, condition, properties, evaluationCache = {}) {
2844
+ const rolloutPercentage = condition.rollout_percentage;
2845
+ const warnFunction = (msg) => {
2846
+ this.logMsgIfDebug(() => console.warn(msg));
2847
+ };
2848
+ if ((condition.properties || []).length > 0) {
2849
+ for (const prop of condition.properties) {
2850
+ const propertyType = prop.type;
2851
+ let matches = false;
2852
+ matches = "cohort" === propertyType ? matchCohort(prop, properties, this.cohorts, this.debugMode) : "flag" === propertyType ? await this.evaluateFlagDependency(prop, distinctId, properties, evaluationCache) : matchProperty(prop, properties, warnFunction);
2853
+ if (!matches) return false;
2854
+ }
2855
+ if (void 0 == rolloutPercentage) return true;
2856
+ }
2857
+ if (void 0 != rolloutPercentage && await _hash(flag.key, distinctId) > rolloutPercentage / 100) return false;
2858
+ return true;
2859
+ }
2860
+ async getMatchingVariant(flag, distinctId) {
2861
+ const hashValue = await _hash(flag.key, distinctId, "variant");
2862
+ const matchingVariant = this.variantLookupTable(flag).find((variant) => hashValue >= variant.valueMin && hashValue < variant.valueMax);
2863
+ if (matchingVariant) return matchingVariant.key;
2864
+ }
2865
+ variantLookupTable(flag) {
2866
+ const lookupTable = [];
2867
+ let valueMin = 0;
2868
+ let valueMax = 0;
2869
+ const flagFilters = flag.filters || {};
2870
+ const multivariates = flagFilters.multivariate?.variants || [];
2871
+ multivariates.forEach((variant) => {
2872
+ valueMax = valueMin + variant.rollout_percentage / 100;
2873
+ lookupTable.push({
2874
+ valueMin,
2875
+ valueMax,
2876
+ key: variant.key
2877
+ });
2878
+ valueMin = valueMax;
2879
+ });
2880
+ return lookupTable;
2881
+ }
2882
+ updateFlagState(flagData) {
2883
+ this.featureFlags = flagData.flags;
2884
+ this.featureFlagsByKey = flagData.flags.reduce((acc, curr) => (acc[curr.key] = curr, acc), {});
2885
+ this.groupTypeMapping = flagData.groupTypeMapping;
2886
+ this.cohorts = flagData.cohorts;
2887
+ this.loadedSuccessfullyOnce = true;
2888
+ }
2889
+ async loadFromCache(debugMessage) {
2890
+ if (!this.cacheProvider) return false;
2891
+ try {
2892
+ const cached = await this.cacheProvider.getFlagDefinitions();
2893
+ if (cached) {
2894
+ this.updateFlagState(cached);
2895
+ this.logMsgIfDebug(() => console.debug(`[FEATURE FLAGS] ${debugMessage} (${cached.flags.length} flags)`));
2896
+ this.onLoad?.(this.featureFlags.length);
2897
+ return true;
2898
+ }
2899
+ return false;
2900
+ } catch (err) {
2901
+ this.onError?.(new Error(`Failed to load from cache: ${err}`));
2902
+ return false;
2903
+ }
2904
+ }
2905
+ async loadFeatureFlags(forceReload = false) {
2906
+ if (this.cacheProvider && !this.hasAttemptedCacheLoad) {
2907
+ this.hasAttemptedCacheLoad = true;
2908
+ await this.loadFromCache("Loaded flags from cache");
2909
+ }
2910
+ if (this.loadingPromise) return this.loadingPromise;
2911
+ if (!this.loadedSuccessfullyOnce || forceReload) {
2912
+ this.loadingPromise = this._loadFeatureFlags();
2913
+ await this.loadingPromise;
2914
+ }
2915
+ }
2916
+ isLocalEvaluationReady() {
2917
+ return (this.loadedSuccessfullyOnce ?? false) && (this.featureFlags?.length ?? 0) > 0;
2918
+ }
2919
+ getPollingInterval() {
2920
+ if (!this.shouldBeginExponentialBackoff) return this.pollingInterval;
2921
+ return Math.min(SIXTY_SECONDS, this.pollingInterval * 2 ** this.backOffCount);
2922
+ }
2923
+ async _loadFeatureFlags() {
2924
+ if (this.poller) {
2925
+ clearTimeout(this.poller);
2926
+ this.poller = void 0;
2927
+ }
2928
+ this.poller = setTimeout(() => this._loadFeatureFlags(), this.getPollingInterval());
2929
+ try {
2930
+ let shouldFetch = true;
2931
+ if (this.cacheProvider) try {
2932
+ shouldFetch = await this.cacheProvider.shouldFetchFlagDefinitions();
2933
+ } catch (err) {
2934
+ this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${err}`));
2935
+ }
2936
+ if (!shouldFetch) {
2937
+ const loaded = await this.loadFromCache("Loaded flags from cache (skipped fetch)");
2938
+ if (loaded) return;
2939
+ if (this.loadedSuccessfullyOnce) return;
2940
+ }
2941
+ const res = await this._requestFeatureFlagDefinitions();
2942
+ if (!res) return;
2943
+ switch (res.status) {
2944
+ case 401:
2945
+ this.shouldBeginExponentialBackoff = true;
2946
+ this.backOffCount += 1;
2947
+ throw new ClientError(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);
2948
+ case 402:
2949
+ console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts");
2950
+ this.featureFlags = [];
2951
+ this.featureFlagsByKey = {};
2952
+ this.groupTypeMapping = {};
2953
+ this.cohorts = {};
2954
+ return;
2955
+ case 403:
2956
+ this.shouldBeginExponentialBackoff = true;
2957
+ this.backOffCount += 1;
2958
+ throw new ClientError(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);
2959
+ case 429:
2960
+ this.shouldBeginExponentialBackoff = true;
2961
+ this.backOffCount += 1;
2962
+ throw new ClientError(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);
2963
+ case 200: {
2964
+ const responseJson = await res.json() ?? {};
2965
+ if (!("flags" in responseJson)) return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(responseJson)}`));
2966
+ const flagData = {
2967
+ flags: responseJson.flags ?? [],
2968
+ groupTypeMapping: responseJson.group_type_mapping || {},
2969
+ cohorts: responseJson.cohorts || {}
2970
+ };
2971
+ this.updateFlagState(flagData);
2972
+ this.shouldBeginExponentialBackoff = false;
2973
+ this.backOffCount = 0;
2974
+ if (this.cacheProvider && shouldFetch) try {
2975
+ await this.cacheProvider.onFlagDefinitionsReceived(flagData);
2976
+ } catch (err) {
2977
+ this.onError?.(new Error(`Failed to store in cache: ${err}`));
2978
+ }
2979
+ this.onLoad?.(this.featureFlags.length);
2980
+ break;
2981
+ }
2982
+ default:
2983
+ return;
2984
+ }
2985
+ } catch (err) {
2986
+ if (err instanceof ClientError) this.onError?.(err);
2987
+ } finally {
2988
+ this.loadingPromise = void 0;
2989
+ }
2990
+ }
2991
+ getPersonalApiKeyRequestOptions(method = "GET") {
2992
+ return {
2993
+ method,
2994
+ headers: {
2995
+ ...this.customHeaders,
2996
+ "Content-Type": "application/json",
2997
+ Authorization: `Bearer ${this.personalApiKey}`
2998
+ }
2999
+ };
3000
+ }
3001
+ _requestFeatureFlagDefinitions() {
3002
+ const url = `${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`;
3003
+ const options = this.getPersonalApiKeyRequestOptions();
3004
+ let abortTimeout = null;
3005
+ if (this.timeout && "number" == typeof this.timeout) {
3006
+ const controller = new AbortController();
3007
+ abortTimeout = safeSetTimeout(() => {
3008
+ controller.abort();
3009
+ }, this.timeout);
3010
+ options.signal = controller.signal;
3011
+ }
3012
+ try {
3013
+ const fetch1 = this.fetch;
3014
+ return fetch1(url, options);
3015
+ } finally {
3016
+ clearTimeout(abortTimeout);
3017
+ }
3018
+ }
3019
+ async stopPoller(timeoutMs = 3e4) {
3020
+ clearTimeout(this.poller);
3021
+ if (this.cacheProvider) try {
3022
+ const shutdownResult = this.cacheProvider.shutdown();
3023
+ if (shutdownResult instanceof Promise) await Promise.race([
3024
+ shutdownResult,
3025
+ new Promise((_, reject) => setTimeout(() => reject(new Error(`Cache shutdown timeout after ${timeoutMs}ms`)), timeoutMs))
3026
+ ]);
3027
+ } catch (err) {
3028
+ this.onError?.(new Error(`Error during cache shutdown: ${err}`));
3029
+ }
3030
+ }
3031
+ };
3032
+ }
3033
+ });
3034
+
3035
+ // ../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/storage-memory.mjs
3036
+ var PostHogMemoryStorage;
3037
+ var init_storage_memory = __esm({
3038
+ "../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/storage-memory.mjs"() {
3039
+ PostHogMemoryStorage = class {
3040
+ getProperty(key) {
3041
+ return this._memoryStorage[key];
3042
+ }
3043
+ setProperty(key, value) {
3044
+ this._memoryStorage[key] = null !== value ? value : void 0;
3045
+ }
3046
+ constructor() {
3047
+ this._memoryStorage = {};
3048
+ }
3049
+ };
3050
+ }
3051
+ });
3052
+
3053
+ // ../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/client.mjs
3054
+ var MINIMUM_POLLING_INTERVAL, THIRTY_SECONDS, MAX_CACHE_SIZE, PostHogBackendClient;
3055
+ var init_client = __esm({
3056
+ "../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/client.mjs"() {
3057
+ init_version();
3058
+ init_dist();
3059
+ init_feature_flags();
3060
+ init_error_tracking2();
3061
+ init_storage_memory();
3062
+ MINIMUM_POLLING_INTERVAL = 100;
3063
+ THIRTY_SECONDS = 3e4;
3064
+ MAX_CACHE_SIZE = 5e4;
3065
+ PostHogBackendClient = class extends PostHogCoreStateless {
3066
+ constructor(apiKey, options = {}) {
3067
+ super(apiKey, options), this._memoryStorage = new PostHogMemoryStorage();
3068
+ this.options = options;
3069
+ this.options.featureFlagsPollingInterval = "number" == typeof options.featureFlagsPollingInterval ? Math.max(options.featureFlagsPollingInterval, MINIMUM_POLLING_INTERVAL) : THIRTY_SECONDS;
3070
+ if (options.personalApiKey) {
3071
+ if (options.personalApiKey.includes("phc_")) throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');
3072
+ const shouldEnableLocalEvaluation = false !== options.enableLocalEvaluation;
3073
+ if (shouldEnableLocalEvaluation) this.featureFlagsPoller = new FeatureFlagsPoller({
3074
+ pollingInterval: this.options.featureFlagsPollingInterval,
3075
+ personalApiKey: options.personalApiKey,
3076
+ projectApiKey: apiKey,
3077
+ timeout: options.requestTimeout ?? 1e4,
3078
+ host: this.host,
3079
+ fetch: options.fetch,
3080
+ onError: (err) => {
3081
+ this._events.emit("error", err);
3082
+ },
3083
+ onLoad: (count) => {
3084
+ this._events.emit("localEvaluationFlagsLoaded", count);
3085
+ },
3086
+ customHeaders: this.getCustomHeaders(),
3087
+ cacheProvider: options.flagDefinitionCacheProvider
3088
+ });
3089
+ }
3090
+ this.errorTracking = new ErrorTracking(this, options, this._logger);
3091
+ this.distinctIdHasSentFlagCalls = {};
3092
+ this.maxCacheSize = options.maxCacheSize || MAX_CACHE_SIZE;
3093
+ }
3094
+ getPersistedProperty(key) {
3095
+ return this._memoryStorage.getProperty(key);
3096
+ }
3097
+ setPersistedProperty(key, value) {
3098
+ return this._memoryStorage.setProperty(key, value);
3099
+ }
3100
+ fetch(url, options) {
3101
+ return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options);
3102
+ }
3103
+ getLibraryVersion() {
3104
+ return version;
3105
+ }
3106
+ getCustomUserAgent() {
3107
+ return `${this.getLibraryId()}/${this.getLibraryVersion()}`;
3108
+ }
3109
+ enable() {
3110
+ return super.optIn();
3111
+ }
3112
+ disable() {
3113
+ return super.optOut();
3114
+ }
3115
+ debug(enabled = true) {
3116
+ super.debug(enabled);
3117
+ this.featureFlagsPoller?.debug(enabled);
3118
+ }
3119
+ capture(props) {
3120
+ if ("string" == typeof props) this._logger.warn("Called capture() with a string as the first argument when an object was expected.");
3121
+ this.addPendingPromise(this.prepareEventMessage(props).then(({ distinctId, event, properties, options }) => super.captureStateless(distinctId, event, properties, {
3122
+ timestamp: options.timestamp,
3123
+ disableGeoip: options.disableGeoip,
3124
+ uuid: options.uuid
3125
+ })).catch((err) => {
3126
+ if (err) console.error(err);
3127
+ }));
3128
+ }
3129
+ async captureImmediate(props) {
3130
+ if ("string" == typeof props) this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected.");
3131
+ return this.addPendingPromise(this.prepareEventMessage(props).then(({ distinctId, event, properties, options }) => super.captureStatelessImmediate(distinctId, event, properties, {
3132
+ timestamp: options.timestamp,
3133
+ disableGeoip: options.disableGeoip,
3134
+ uuid: options.uuid
3135
+ })).catch((err) => {
3136
+ if (err) console.error(err);
3137
+ }));
3138
+ }
3139
+ identify({ distinctId, properties, disableGeoip }) {
3140
+ const userPropsOnce = properties?.$set_once;
3141
+ delete properties?.$set_once;
3142
+ const userProps = properties?.$set || properties;
3143
+ super.identifyStateless(distinctId, {
3144
+ $set: userProps,
3145
+ $set_once: userPropsOnce
3146
+ }, {
3147
+ disableGeoip
3148
+ });
3149
+ }
3150
+ async identifyImmediate({ distinctId, properties, disableGeoip }) {
3151
+ const userPropsOnce = properties?.$set_once;
3152
+ delete properties?.$set_once;
3153
+ const userProps = properties?.$set || properties;
3154
+ await super.identifyStatelessImmediate(distinctId, {
3155
+ $set: userProps,
3156
+ $set_once: userPropsOnce
3157
+ }, {
3158
+ disableGeoip
3159
+ });
3160
+ }
3161
+ alias(data) {
3162
+ super.aliasStateless(data.alias, data.distinctId, void 0, {
3163
+ disableGeoip: data.disableGeoip
3164
+ });
3165
+ }
3166
+ async aliasImmediate(data) {
3167
+ await super.aliasStatelessImmediate(data.alias, data.distinctId, void 0, {
3168
+ disableGeoip: data.disableGeoip
3169
+ });
3170
+ }
3171
+ isLocalEvaluationReady() {
3172
+ return this.featureFlagsPoller?.isLocalEvaluationReady() ?? false;
3173
+ }
3174
+ async waitForLocalEvaluationReady(timeoutMs = THIRTY_SECONDS) {
3175
+ if (this.isLocalEvaluationReady()) return true;
3176
+ if (void 0 === this.featureFlagsPoller) return false;
3177
+ return new Promise((resolve) => {
3178
+ const timeout = setTimeout(() => {
3179
+ cleanup();
3180
+ resolve(false);
3181
+ }, timeoutMs);
3182
+ const cleanup = this._events.on("localEvaluationFlagsLoaded", (count) => {
3183
+ clearTimeout(timeout);
3184
+ cleanup();
3185
+ resolve(count > 0);
3186
+ });
3187
+ });
3188
+ }
3189
+ async getFeatureFlag(key, distinctId, options) {
3190
+ const { groups, disableGeoip } = options || {};
3191
+ let { onlyEvaluateLocally, sendFeatureFlagEvents, personProperties, groupProperties } = options || {};
3192
+ const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);
3193
+ personProperties = adjustedProperties.allPersonProperties;
3194
+ groupProperties = adjustedProperties.allGroupProperties;
3195
+ if (void 0 == onlyEvaluateLocally) onlyEvaluateLocally = false;
3196
+ if (void 0 == sendFeatureFlagEvents) sendFeatureFlagEvents = this.options.sendFeatureFlagEvent ?? true;
3197
+ let response = await this.featureFlagsPoller?.getFeatureFlag(key, distinctId, groups, personProperties, groupProperties);
3198
+ const flagWasLocallyEvaluated = void 0 !== response;
3199
+ let requestId;
3200
+ let flagDetail;
3201
+ if (!flagWasLocallyEvaluated && !onlyEvaluateLocally) {
3202
+ const remoteResponse = await super.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
3203
+ if (void 0 === remoteResponse) return;
3204
+ flagDetail = remoteResponse.response;
3205
+ response = getFeatureFlagValue(flagDetail);
3206
+ requestId = remoteResponse?.requestId;
3207
+ }
3208
+ const featureFlagReportedKey = `${key}_${response}`;
3209
+ if (sendFeatureFlagEvents && (!(distinctId in this.distinctIdHasSentFlagCalls) || !this.distinctIdHasSentFlagCalls[distinctId].includes(featureFlagReportedKey))) {
3210
+ if (Object.keys(this.distinctIdHasSentFlagCalls).length >= this.maxCacheSize) this.distinctIdHasSentFlagCalls = {};
3211
+ if (Array.isArray(this.distinctIdHasSentFlagCalls[distinctId])) this.distinctIdHasSentFlagCalls[distinctId].push(featureFlagReportedKey);
3212
+ else this.distinctIdHasSentFlagCalls[distinctId] = [
3213
+ featureFlagReportedKey
3214
+ ];
3215
+ this.capture({
3216
+ distinctId,
3217
+ event: "$feature_flag_called",
3218
+ properties: {
3219
+ $feature_flag: key,
3220
+ $feature_flag_response: response,
3221
+ $feature_flag_id: flagDetail?.metadata?.id,
3222
+ $feature_flag_version: flagDetail?.metadata?.version,
3223
+ $feature_flag_reason: flagDetail?.reason?.description ?? flagDetail?.reason?.code,
3224
+ locally_evaluated: flagWasLocallyEvaluated,
3225
+ [`$feature/${key}`]: response,
3226
+ $feature_flag_request_id: requestId
3227
+ },
3228
+ groups,
3229
+ disableGeoip
3230
+ });
3231
+ }
3232
+ return response;
3233
+ }
3234
+ async getFeatureFlagPayload(key, distinctId, matchValue, options) {
3235
+ const { groups, disableGeoip } = options || {};
3236
+ let { onlyEvaluateLocally, personProperties, groupProperties } = options || {};
3237
+ const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);
3238
+ personProperties = adjustedProperties.allPersonProperties;
3239
+ groupProperties = adjustedProperties.allGroupProperties;
3240
+ let response;
3241
+ const localEvaluationEnabled = void 0 !== this.featureFlagsPoller;
3242
+ if (localEvaluationEnabled) {
3243
+ await this.featureFlagsPoller?.loadFeatureFlags();
3244
+ const flag = this.featureFlagsPoller?.featureFlagsByKey[key];
3245
+ if (flag) try {
3246
+ const result = await this.featureFlagsPoller?.computeFlagAndPayloadLocally(flag, distinctId, groups, personProperties, groupProperties, matchValue);
3247
+ if (result) {
3248
+ matchValue = result.value;
3249
+ response = result.payload;
3250
+ }
3251
+ } catch (e) {
3252
+ if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError) this._logger?.info(`${e.name} when computing flag locally: ${flag.key}: ${e.message}`);
3253
+ else throw e;
3254
+ }
3255
+ }
3256
+ if (void 0 == onlyEvaluateLocally) onlyEvaluateLocally = false;
3257
+ const payloadWasLocallyEvaluated = void 0 !== response;
3258
+ if (!payloadWasLocallyEvaluated && !onlyEvaluateLocally) response = await super.getFeatureFlagPayloadStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
3259
+ return response;
3260
+ }
3261
+ async getRemoteConfigPayload(flagKey) {
3262
+ if (!this.options.personalApiKey) throw new Error("Personal API key is required for remote config payload decryption");
3263
+ const response = await this._requestRemoteConfigPayload(flagKey);
3264
+ if (!response) return;
3265
+ const parsed = await response.json();
3266
+ if ("string" == typeof parsed) try {
3267
+ return JSON.parse(parsed);
3268
+ } catch (e) {
3269
+ }
3270
+ return parsed;
3271
+ }
3272
+ async isFeatureEnabled(key, distinctId, options) {
3273
+ const feat = await this.getFeatureFlag(key, distinctId, options);
3274
+ if (void 0 === feat) return;
3275
+ return !!feat || false;
3276
+ }
3277
+ async getAllFlags(distinctId, options) {
3278
+ const response = await this.getAllFlagsAndPayloads(distinctId, options);
3279
+ return response.featureFlags || {};
3280
+ }
3281
+ async getAllFlagsAndPayloads(distinctId, options) {
3282
+ const { groups, disableGeoip, flagKeys } = options || {};
3283
+ let { onlyEvaluateLocally, personProperties, groupProperties } = options || {};
3284
+ const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);
3285
+ personProperties = adjustedProperties.allPersonProperties;
3286
+ groupProperties = adjustedProperties.allGroupProperties;
3287
+ if (void 0 == onlyEvaluateLocally) onlyEvaluateLocally = false;
3288
+ const localEvaluationResult = await this.featureFlagsPoller?.getAllFlagsAndPayloads(distinctId, groups, personProperties, groupProperties, flagKeys);
3289
+ let featureFlags = {};
3290
+ let featureFlagPayloads = {};
3291
+ let fallbackToFlags = true;
3292
+ if (localEvaluationResult) {
3293
+ featureFlags = localEvaluationResult.response;
3294
+ featureFlagPayloads = localEvaluationResult.payloads;
3295
+ fallbackToFlags = localEvaluationResult.fallbackToFlags;
3296
+ }
3297
+ if (fallbackToFlags && !onlyEvaluateLocally) {
3298
+ const remoteEvaluationResult = await super.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeys);
3299
+ featureFlags = {
3300
+ ...featureFlags,
3301
+ ...remoteEvaluationResult.flags || {}
3302
+ };
3303
+ featureFlagPayloads = {
3304
+ ...featureFlagPayloads,
3305
+ ...remoteEvaluationResult.payloads || {}
3306
+ };
3307
+ }
3308
+ return {
3309
+ featureFlags,
3310
+ featureFlagPayloads
3311
+ };
3312
+ }
3313
+ groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }) {
3314
+ super.groupIdentifyStateless(groupType, groupKey, properties, {
3315
+ disableGeoip
3316
+ }, distinctId);
3317
+ }
3318
+ async reloadFeatureFlags() {
3319
+ await this.featureFlagsPoller?.loadFeatureFlags(true);
3320
+ }
3321
+ async _shutdown(shutdownTimeoutMs) {
3322
+ this.featureFlagsPoller?.stopPoller(shutdownTimeoutMs);
3323
+ this.errorTracking.shutdown();
3324
+ return super._shutdown(shutdownTimeoutMs);
3325
+ }
3326
+ async _requestRemoteConfigPayload(flagKey) {
3327
+ if (!this.options.personalApiKey) return;
3328
+ const url = `${this.host}/api/projects/@current/feature_flags/${flagKey}/remote_config?token=${encodeURIComponent(this.apiKey)}`;
3329
+ const options = {
3330
+ method: "GET",
3331
+ headers: {
3332
+ ...this.getCustomHeaders(),
3333
+ "Content-Type": "application/json",
3334
+ Authorization: `Bearer ${this.options.personalApiKey}`
3335
+ }
3336
+ };
3337
+ let abortTimeout = null;
3338
+ if (this.options.requestTimeout && "number" == typeof this.options.requestTimeout) {
3339
+ const controller = new AbortController();
3340
+ abortTimeout = safeSetTimeout(() => {
3341
+ controller.abort();
3342
+ }, this.options.requestTimeout);
3343
+ options.signal = controller.signal;
3344
+ }
3345
+ try {
3346
+ return await this.fetch(url, options);
3347
+ } catch (error) {
3348
+ this._events.emit("error", error);
3349
+ return;
3350
+ } finally {
3351
+ if (abortTimeout) clearTimeout(abortTimeout);
3352
+ }
3353
+ }
3354
+ extractPropertiesFromEvent(eventProperties, groups) {
3355
+ if (!eventProperties) return {
3356
+ personProperties: {},
3357
+ groupProperties: {}
3358
+ };
3359
+ const personProperties = {};
3360
+ const groupProperties = {};
3361
+ for (const [key, value] of Object.entries(eventProperties)) if (isPlainObject(value) && groups && key in groups) {
3362
+ const groupProps = {};
3363
+ for (const [groupKey, groupValue] of Object.entries(value)) groupProps[String(groupKey)] = String(groupValue);
3364
+ groupProperties[String(key)] = groupProps;
3365
+ } else personProperties[String(key)] = String(value);
3366
+ return {
3367
+ personProperties,
3368
+ groupProperties
3369
+ };
3370
+ }
3371
+ async getFeatureFlagsForEvent(distinctId, groups, disableGeoip, sendFeatureFlagsOptions) {
3372
+ const finalPersonProperties = sendFeatureFlagsOptions?.personProperties || {};
3373
+ const finalGroupProperties = sendFeatureFlagsOptions?.groupProperties || {};
3374
+ const flagKeys = sendFeatureFlagsOptions?.flagKeys;
3375
+ const onlyEvaluateLocally = sendFeatureFlagsOptions?.onlyEvaluateLocally ?? false;
3376
+ if (onlyEvaluateLocally) if (!((this.featureFlagsPoller?.featureFlags?.length || 0) > 0)) return {};
3377
+ else {
3378
+ const groupsWithStringValues = {};
3379
+ for (const [key, value] of Object.entries(groups || {})) groupsWithStringValues[key] = String(value);
3380
+ return await this.getAllFlags(distinctId, {
3381
+ groups: groupsWithStringValues,
3382
+ personProperties: finalPersonProperties,
3383
+ groupProperties: finalGroupProperties,
3384
+ disableGeoip,
3385
+ onlyEvaluateLocally: true,
3386
+ flagKeys
3387
+ });
3388
+ }
3389
+ if ((this.featureFlagsPoller?.featureFlags?.length || 0) > 0) {
3390
+ const groupsWithStringValues = {};
3391
+ for (const [key, value] of Object.entries(groups || {})) groupsWithStringValues[key] = String(value);
3392
+ return await this.getAllFlags(distinctId, {
3393
+ groups: groupsWithStringValues,
3394
+ personProperties: finalPersonProperties,
3395
+ groupProperties: finalGroupProperties,
3396
+ disableGeoip,
3397
+ onlyEvaluateLocally: true,
3398
+ flagKeys
3399
+ });
3400
+ }
3401
+ return (await super.getFeatureFlagsStateless(distinctId, groups, finalPersonProperties, finalGroupProperties, disableGeoip)).flags;
3402
+ }
3403
+ addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties) {
3404
+ const allPersonProperties = {
3405
+ distinct_id: distinctId,
3406
+ ...personProperties || {}
3407
+ };
3408
+ const allGroupProperties = {};
3409
+ if (groups) for (const groupName of Object.keys(groups)) allGroupProperties[groupName] = {
3410
+ $group_key: groups[groupName],
3411
+ ...groupProperties?.[groupName] || {}
3412
+ };
3413
+ return {
3414
+ allPersonProperties,
3415
+ allGroupProperties
3416
+ };
3417
+ }
3418
+ captureException(error, distinctId, additionalProperties) {
3419
+ const syntheticException = new Error("PostHog syntheticException");
3420
+ this.addPendingPromise(ErrorTracking.buildEventMessage(error, {
3421
+ syntheticException
3422
+ }, distinctId, additionalProperties).then((msg) => this.capture(msg)));
3423
+ }
3424
+ async captureExceptionImmediate(error, distinctId, additionalProperties) {
3425
+ const syntheticException = new Error("PostHog syntheticException");
3426
+ this.addPendingPromise(ErrorTracking.buildEventMessage(error, {
3427
+ syntheticException
3428
+ }, distinctId, additionalProperties).then((msg) => this.captureImmediate(msg)));
3429
+ }
3430
+ async prepareEventMessage(props) {
3431
+ const { distinctId, event, properties, groups, sendFeatureFlags, timestamp, disableGeoip, uuid } = props;
3432
+ const eventMessage = this._runBeforeSend({
3433
+ distinctId,
3434
+ event,
3435
+ properties,
3436
+ groups,
3437
+ sendFeatureFlags,
3438
+ timestamp,
3439
+ disableGeoip,
3440
+ uuid
3441
+ });
3442
+ if (!eventMessage) return Promise.reject(null);
3443
+ const eventProperties = await Promise.resolve().then(async () => {
3444
+ if (sendFeatureFlags) {
3445
+ const sendFeatureFlagsOptions = "object" == typeof sendFeatureFlags ? sendFeatureFlags : void 0;
3446
+ return await this.getFeatureFlagsForEvent(distinctId, groups, disableGeoip, sendFeatureFlagsOptions);
3447
+ }
3448
+ return {};
3449
+ }).then((flags) => {
3450
+ const additionalProperties = {};
3451
+ if (flags) for (const [feature, variant] of Object.entries(flags)) additionalProperties[`$feature/${feature}`] = variant;
3452
+ const activeFlags = Object.keys(flags || {}).filter((flag) => flags?.[flag] !== false).sort();
3453
+ if (activeFlags.length > 0) additionalProperties["$active_feature_flags"] = activeFlags;
3454
+ return additionalProperties;
3455
+ }).catch(() => ({})).then((additionalProperties) => {
3456
+ const props2 = {
3457
+ ...additionalProperties,
3458
+ ...eventMessage.properties || {},
3459
+ $groups: eventMessage.groups || groups
3460
+ };
3461
+ return props2;
3462
+ });
3463
+ if ("$pageview" === eventMessage.event && this.options.__preview_capture_bot_pageviews && "string" == typeof eventProperties.$raw_user_agent) {
3464
+ if (isBlockedUA(eventProperties.$raw_user_agent, this.options.custom_blocked_useragents || [])) {
3465
+ eventMessage.event = "$bot_pageview";
3466
+ eventProperties.$browser_type = "bot";
3467
+ }
3468
+ }
3469
+ return {
3470
+ distinctId: eventMessage.distinctId,
3471
+ event: eventMessage.event,
3472
+ properties: eventProperties,
3473
+ options: {
3474
+ timestamp: eventMessage.timestamp,
3475
+ disableGeoip: eventMessage.disableGeoip,
3476
+ uuid: eventMessage.uuid
3477
+ }
3478
+ };
3479
+ }
3480
+ _runBeforeSend(eventMessage) {
3481
+ const beforeSend = this.options.before_send;
3482
+ if (!beforeSend) return eventMessage;
3483
+ const fns = Array.isArray(beforeSend) ? beforeSend : [
3484
+ beforeSend
3485
+ ];
3486
+ let result = eventMessage;
3487
+ for (const fn of fns) {
3488
+ result = fn(result);
3489
+ if (!result) {
3490
+ this._logger.info(`Event '${eventMessage.event}' was rejected in beforeSend function`);
3491
+ return null;
3492
+ }
3493
+ if (!result.properties || 0 === Object.keys(result.properties).length) {
3494
+ const message = `Event '${result.event}' has no properties after beforeSend function, this is likely an error.`;
3495
+ this._logger.warn(message);
3496
+ }
3497
+ }
3498
+ return result;
3499
+ }
3500
+ };
3501
+ }
3502
+ });
3503
+
3504
+ // ../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/extensions/sentry-integration.mjs
3505
+ function createEventProcessor(_posthog, { organization, projectId, prefix, severityAllowList = [
3506
+ "error"
3507
+ ], sendExceptionsToPostHog = true } = {}) {
3508
+ return (event) => {
3509
+ const shouldProcessLevel = "*" === severityAllowList || severityAllowList.includes(event.level);
3510
+ if (!shouldProcessLevel) return event;
3511
+ if (!event.tags) event.tags = {};
3512
+ const userId = event.tags[PostHogSentryIntegration.POSTHOG_ID_TAG];
3513
+ if (void 0 === userId) return event;
3514
+ const uiHost = _posthog.options.host ?? "https://us.i.posthog.com";
3515
+ const personUrl = new URL(`/project/${_posthog.apiKey}/person/${userId}`, uiHost).toString();
3516
+ event.tags["PostHog Person URL"] = personUrl;
3517
+ const exceptions = event.exception?.values || [];
3518
+ const exceptionList = exceptions.map((exception) => ({
3519
+ ...exception,
3520
+ stacktrace: exception.stacktrace ? {
3521
+ ...exception.stacktrace,
3522
+ type: "raw",
3523
+ frames: (exception.stacktrace.frames || []).map((frame) => ({
3524
+ ...frame,
3525
+ platform: "node:javascript"
3526
+ }))
3527
+ } : void 0
3528
+ }));
3529
+ const properties = {
3530
+ $exception_message: exceptions[0]?.value || event.message,
3531
+ $exception_type: exceptions[0]?.type,
3532
+ $exception_level: event.level,
3533
+ $exception_list: exceptionList,
3534
+ $sentry_event_id: event.event_id,
3535
+ $sentry_exception: event.exception,
3536
+ $sentry_exception_message: exceptions[0]?.value || event.message,
3537
+ $sentry_exception_type: exceptions[0]?.type,
3538
+ $sentry_tags: event.tags
3539
+ };
3540
+ if (organization && projectId) properties["$sentry_url"] = (prefix || "https://sentry.io/organizations/") + organization + "/issues/?project=" + projectId + "&query=" + event.event_id;
3541
+ if (sendExceptionsToPostHog) _posthog.capture({
3542
+ event: "$exception",
3543
+ distinctId: userId,
3544
+ properties
3545
+ });
3546
+ return event;
3547
+ };
3548
+ }
3549
+ function sentryIntegration(_posthog, options) {
3550
+ const processor = createEventProcessor(_posthog, options);
3551
+ return {
3552
+ name: NAME,
3553
+ processEvent(event) {
3554
+ return processor(event);
3555
+ }
3556
+ };
3557
+ }
3558
+ var NAME, PostHogSentryIntegration;
3559
+ var init_sentry_integration = __esm({
3560
+ "../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/extensions/sentry-integration.mjs"() {
3561
+ NAME = "posthog-node";
3562
+ PostHogSentryIntegration = class {
3563
+ static #_ = this.POSTHOG_ID_TAG = "posthog_distinct_id";
3564
+ constructor(_posthog, organization, prefix, severityAllowList, sendExceptionsToPostHog) {
3565
+ this.name = NAME;
3566
+ this.name = NAME;
3567
+ this.setupOnce = function(addGlobalEventProcessor, getCurrentHub) {
3568
+ const projectId = getCurrentHub()?.getClient()?.getDsn()?.projectId;
3569
+ addGlobalEventProcessor(createEventProcessor(_posthog, {
3570
+ organization,
3571
+ projectId,
3572
+ prefix,
3573
+ severityAllowList,
3574
+ sendExceptionsToPostHog: sendExceptionsToPostHog ?? true
3575
+ }));
3576
+ };
3577
+ }
3578
+ };
3579
+ }
3580
+ });
3581
+
3582
+ // ../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/extensions/express.mjs
3583
+ function setupExpressErrorHandler(_posthog, app) {
3584
+ app.use((error, _, __, next) => {
3585
+ const hint = {
3586
+ mechanism: {
3587
+ type: "middleware",
3588
+ handled: false
3589
+ }
3590
+ };
3591
+ ErrorTracking.buildEventMessage(error, hint, uuidv7(), {
3592
+ $process_person_profile: false
3593
+ }).then((msg) => _posthog.capture(msg));
3594
+ next(error);
3595
+ });
3596
+ }
3597
+ var init_express = __esm({
3598
+ "../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/extensions/express.mjs"() {
3599
+ init_dist();
3600
+ init_error_tracking2();
3601
+ }
3602
+ });
3603
+
3604
+ // ../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/types.mjs
3605
+ var init_types3 = __esm({
3606
+ "../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/types.mjs"() {
3607
+ }
3608
+ });
3609
+
3610
+ // ../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/exports.mjs
3611
+ var init_exports = __esm({
3612
+ "../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/exports.mjs"() {
3613
+ init_sentry_integration();
3614
+ init_express();
3615
+ init_types3();
3616
+ }
3617
+ });
3618
+
3619
+ // ../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/entrypoints/index.node.mjs
3620
+ var index_node_exports = {};
3621
+ __export(index_node_exports, {
3622
+ PostHog: () => PostHog,
3623
+ PostHogSentryIntegration: () => PostHogSentryIntegration,
3624
+ createEventProcessor: () => createEventProcessor,
3625
+ sentryIntegration: () => sentryIntegration,
3626
+ setupExpressErrorHandler: () => setupExpressErrorHandler
3627
+ });
3628
+ var PostHog;
3629
+ var init_index_node = __esm({
3630
+ "../../node_modules/.pnpm/posthog-node@5.14.0/node_modules/posthog-node/dist/entrypoints/index.node.mjs"() {
3631
+ init_module_node();
3632
+ init_context_lines_node();
3633
+ init_error_tracking2();
3634
+ init_client();
3635
+ init_dist();
3636
+ init_exports();
3637
+ ErrorTracking.errorPropertiesBuilder = new error_tracking_exports.ErrorPropertiesBuilder([
3638
+ new error_tracking_exports.EventCoercer(),
3639
+ new error_tracking_exports.ErrorCoercer(),
3640
+ new error_tracking_exports.ObjectCoercer(),
3641
+ new error_tracking_exports.StringCoercer(),
3642
+ new error_tracking_exports.PrimitiveCoercer()
3643
+ ], error_tracking_exports.createStackParser("node:javascript", error_tracking_exports.nodeStackLineParser), [
3644
+ createModulerModifier(),
3645
+ addSourceContext
3646
+ ]);
3647
+ PostHog = class extends PostHogBackendClient {
3648
+ getLibraryId() {
3649
+ return "posthog-node";
3650
+ }
3651
+ };
3652
+ }
3653
+ });
3654
+
3655
+ // src/event-subscriber-base.ts
3656
+ var EventSubscriber = class {
3657
+ /**
3658
+ * Subscriber version (optional)
3659
+ */
3660
+ version;
3661
+ /**
3662
+ * Enable/disable the subscriber (default: true)
3663
+ */
3664
+ enabled = true;
3665
+ /**
3666
+ * Track pending requests for graceful shutdown
3667
+ */
3668
+ pendingRequests = /* @__PURE__ */ new Set();
3669
+ /**
3670
+ * Optional: Handle errors
3671
+ *
3672
+ * Override this to customize error handling (logging, retries, etc.).
3673
+ * Default behavior: log to console.error
3674
+ *
3675
+ * @param error - Error that occurred
3676
+ * @param payload - Event payload that failed
3677
+ */
3678
+ handleError(error, payload) {
3679
+ console.error(
3680
+ `[${this.name}] Failed to send ${payload.type}:`,
3681
+ error,
3682
+ payload
3683
+ );
3684
+ }
3685
+ /**
3686
+ * Track an event
3687
+ */
3688
+ async trackEvent(name, attributes) {
3689
+ if (!this.enabled) return;
3690
+ const payload = {
3691
+ type: "event",
3692
+ name,
3693
+ attributes,
3694
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
3695
+ };
3696
+ await this.send(payload);
3697
+ }
3698
+ /**
3699
+ * Track a funnel step
3700
+ */
3701
+ async trackFunnelStep(funnelName, step, attributes) {
3702
+ if (!this.enabled) return;
3703
+ const payload = {
3704
+ type: "funnel",
3705
+ name: `${funnelName}.${step}`,
3706
+ funnel: funnelName,
3707
+ step,
3708
+ attributes,
3709
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
3710
+ };
3711
+ await this.send(payload);
3712
+ }
3713
+ /**
3714
+ * Track an outcome
3715
+ */
3716
+ async trackOutcome(operationName, outcome, attributes) {
3717
+ if (!this.enabled) return;
3718
+ const payload = {
3719
+ type: "outcome",
3720
+ name: `${operationName}.${outcome}`,
3721
+ operation: operationName,
3722
+ outcome,
3723
+ attributes,
3724
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
3725
+ };
3726
+ await this.send(payload);
3727
+ }
3728
+ /**
3729
+ * Track a value/metric
3730
+ */
3731
+ async trackValue(name, value, attributes) {
3732
+ if (!this.enabled) return;
3733
+ const payload = {
3734
+ type: "value",
3735
+ name,
3736
+ value,
3737
+ attributes,
3738
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
3739
+ };
3740
+ await this.send(payload);
3741
+ }
3742
+ /**
3743
+ * Flush pending requests and clean up
3744
+ *
3745
+ * CRITICAL: Prevents race condition during shutdown
3746
+ * 1. Disables subscriber to stop new events
3747
+ * 2. Drains all pending requests (with retry logic)
3748
+ * 3. Ensures flush guarantee
3749
+ *
3750
+ * Override this if you need custom cleanup logic (close connections, flush buffers, etc.),
3751
+ * but ALWAYS call super.shutdown() first to drain pending requests.
3752
+ */
3753
+ async shutdown() {
3754
+ this.enabled = false;
3755
+ const maxDrainAttempts = 10;
3756
+ const drainIntervalMs = 50;
3757
+ for (let attempt = 0; attempt < maxDrainAttempts; attempt++) {
3758
+ if (this.pendingRequests.size === 0) {
3759
+ break;
3760
+ }
3761
+ await Promise.allSettled(this.pendingRequests);
3762
+ if (this.pendingRequests.size > 0 && attempt < maxDrainAttempts - 1) {
3763
+ await new Promise((resolve) => setTimeout(resolve, drainIntervalMs));
3764
+ }
3765
+ }
3766
+ if (this.pendingRequests.size > 0) {
3767
+ console.warn(
3768
+ `[${this.name}] Shutdown completed with ${this.pendingRequests.size} pending requests still in-flight. This may indicate a bug in the subscriber or extremely slow destination.`
3769
+ );
3770
+ }
3771
+ }
3772
+ /**
3773
+ * Internal: Send payload and track request
3774
+ */
3775
+ async send(payload) {
3776
+ const request = this.sendWithErrorHandling(payload);
3777
+ this.pendingRequests.add(request);
3778
+ void request.finally(() => {
3779
+ this.pendingRequests.delete(request);
3780
+ });
3781
+ return request;
3782
+ }
3783
+ /**
3784
+ * Internal: Send with error handling
3785
+ */
3786
+ async sendWithErrorHandling(payload) {
3787
+ try {
3788
+ await this.sendToDestination(payload);
3789
+ } catch (error) {
3790
+ this.handleError(error, payload);
3791
+ }
3792
+ }
3793
+ };
3794
+
3795
+ // src/posthog.ts
3796
+ var PostHogSubscriber = class extends EventSubscriber {
3797
+ name = "PostHogSubscriber";
3798
+ version = "2.0.0";
3799
+ posthog = null;
3800
+ config;
3801
+ initPromise = null;
3802
+ constructor(config) {
3803
+ super();
3804
+ if (!config.apiKey && !config.client) {
3805
+ throw new Error("PostHogSubscriber requires either apiKey or client to be provided");
3806
+ }
3807
+ this.enabled = config.enabled ?? true;
3808
+ this.config = config;
3809
+ if (this.enabled) {
3810
+ this.initPromise = this.initialize();
3811
+ }
3812
+ }
3813
+ async initialize() {
3814
+ try {
3815
+ if (this.config.client) {
3816
+ this.posthog = this.config.client;
3817
+ this.setupErrorHandling();
3818
+ return;
3819
+ }
3820
+ const { PostHog: PostHog2 } = await Promise.resolve().then(() => (init_index_node(), index_node_exports));
3821
+ this.posthog = new PostHog2(this.config.apiKey, {
3822
+ host: this.config.host || "https://us.i.posthog.com",
3823
+ flushAt: this.config.flushAt,
3824
+ flushInterval: this.config.flushInterval,
3825
+ requestTimeout: this.config.requestTimeout,
3826
+ disableGeoip: this.config.disableGeoip,
3827
+ sendFeatureFlagEvent: this.config.sendFeatureFlags
3828
+ });
3829
+ this.setupErrorHandling();
3830
+ } catch (error) {
3831
+ console.error(
3832
+ "PostHog subscriber failed to initialize. Install posthog-node: pnpm add posthog-node",
3833
+ error
3834
+ );
3835
+ this.enabled = false;
3836
+ this.config.onError?.(error);
3837
+ }
3838
+ }
3839
+ setupErrorHandling() {
3840
+ if (this.config.debug) {
3841
+ this.posthog?.debug();
3842
+ }
3843
+ if (this.config.onError && this.posthog?.on) {
3844
+ this.posthog.on("error", this.config.onError);
3845
+ }
3846
+ }
3847
+ async ensureInitialized() {
3848
+ if (this.initPromise) {
3849
+ await this.initPromise;
3850
+ this.initPromise = null;
3851
+ }
3852
+ }
3853
+ extractDistinctId(attributes) {
3854
+ return attributes?.userId || attributes?.user_id || "anonymous";
3855
+ }
3856
+ /**
3857
+ * Send payload to PostHog
3858
+ */
3859
+ async sendToDestination(payload) {
3860
+ await this.ensureInitialized();
3861
+ let properties = payload.attributes;
3862
+ if (payload.value !== void 0) {
3863
+ properties = { ...payload.attributes, value: payload.value };
3864
+ }
3865
+ const capturePayload = {
3866
+ distinctId: this.extractDistinctId(payload.attributes),
3867
+ event: payload.name,
3868
+ properties
3869
+ };
3870
+ if (payload.attributes?.groups) {
3871
+ capturePayload.groups = payload.attributes.groups;
3872
+ }
3873
+ this.posthog?.capture(capturePayload);
3874
+ }
3875
+ // Feature Flag Methods
3876
+ /**
3877
+ * Check if a feature flag is enabled for a user
3878
+ *
3879
+ * @param flagKey - Feature flag key
3880
+ * @param distinctId - User ID or anonymous ID
3881
+ * @param options - Feature flag evaluation options
3882
+ * @returns true if enabled, false otherwise
3883
+ *
3884
+ * @example
3885
+ * ```typescript
3886
+ * const isEnabled = await subscriber.isFeatureEnabled('new-checkout', 'user-123');
3887
+ *
3888
+ * // With groups
3889
+ * const isEnabled = await subscriber.isFeatureEnabled('beta-features', 'user-123', {
3890
+ * groups: { company: 'acme-corp' }
3891
+ * });
3892
+ * ```
3893
+ */
3894
+ async isFeatureEnabled(flagKey, distinctId, options) {
3895
+ if (!this.enabled) return false;
3896
+ await this.ensureInitialized();
3897
+ try {
3898
+ return await this.posthog?.isFeatureEnabled(flagKey, distinctId, options) ?? false;
3899
+ } catch (error) {
3900
+ this.config.onError?.(error);
3901
+ return false;
3902
+ }
3903
+ }
3904
+ /**
3905
+ * Get feature flag value for a user
3906
+ *
3907
+ * @param flagKey - Feature flag key
3908
+ * @param distinctId - User ID or anonymous ID
3909
+ * @param options - Feature flag evaluation options
3910
+ * @returns Flag value (string, boolean, or undefined)
3911
+ *
3912
+ * @example
3913
+ * ```typescript
3914
+ * const variant = await subscriber.getFeatureFlag('experiment-variant', 'user-123');
3915
+ * // Returns: 'control' | 'test' | 'test-2' | undefined
3916
+ *
3917
+ * // With person properties
3918
+ * const variant = await subscriber.getFeatureFlag('premium-feature', 'user-123', {
3919
+ * personProperties: { plan: 'premium' }
3920
+ * });
3921
+ * ```
3922
+ */
3923
+ async getFeatureFlag(flagKey, distinctId, options) {
3924
+ if (!this.enabled) return void 0;
3925
+ await this.ensureInitialized();
3926
+ try {
3927
+ return await this.posthog?.getFeatureFlag(flagKey, distinctId, options);
3928
+ } catch (error) {
3929
+ this.config.onError?.(error);
3930
+ return void 0;
3931
+ }
3932
+ }
3933
+ /**
3934
+ * Get all feature flags for a user
3935
+ *
3936
+ * @param distinctId - User ID or anonymous ID
3937
+ * @param options - Feature flag evaluation options
3938
+ * @returns Object mapping flag keys to their values
3939
+ *
3940
+ * @example
3941
+ * ```typescript
3942
+ * const flags = await subscriber.getAllFlags('user-123');
3943
+ * // Returns: { 'new-checkout': true, 'experiment-variant': 'test', ... }
3944
+ * ```
3945
+ */
3946
+ async getAllFlags(distinctId, options) {
3947
+ if (!this.enabled) return {};
3948
+ await this.ensureInitialized();
3949
+ try {
3950
+ const flags = await this.posthog?.getAllFlags(distinctId, options);
3951
+ return flags ?? {};
3952
+ } catch (error) {
3953
+ this.config.onError?.(error);
3954
+ return {};
3955
+ }
3956
+ }
3957
+ /**
3958
+ * Reload feature flags from PostHog server
3959
+ *
3960
+ * Call this to refresh feature flag definitions without restarting.
3961
+ *
3962
+ * @example
3963
+ * ```typescript
3964
+ * await subscriber.reloadFeatureFlags();
3965
+ * ```
3966
+ */
3967
+ async reloadFeatureFlags() {
3968
+ if (!this.enabled) return;
3969
+ await this.ensureInitialized();
3970
+ try {
3971
+ await this.posthog?.reloadFeatureFlags();
3972
+ } catch (error) {
3973
+ this.config.onError?.(error);
3974
+ }
3975
+ }
3976
+ // Person and Group Events
3977
+ /**
3978
+ * Identify a user and set their properties
3979
+ *
3980
+ * @param distinctId - User ID
3981
+ * @param properties - Person properties ($set, $set_once, or custom properties)
3982
+ *
3983
+ * @example
3984
+ * ```typescript
3985
+ * // Set properties (will update existing values)
3986
+ * await subscriber.identify('user-123', {
3987
+ * $set: {
3988
+ * email: 'user@example.com',
3989
+ * plan: 'premium'
3990
+ * }
3991
+ * });
3992
+ *
3993
+ * // Set properties only once (won't update if already exists)
3994
+ * await subscriber.identify('user-123', {
3995
+ * $set_once: {
3996
+ * signup_date: '2025-01-17'
3997
+ * }
3998
+ * });
3999
+ * ```
4000
+ */
4001
+ async identify(distinctId, properties) {
4002
+ if (!this.enabled) return;
4003
+ await this.ensureInitialized();
4004
+ try {
4005
+ this.posthog?.identify({
4006
+ distinctId,
4007
+ properties
4008
+ });
4009
+ } catch (error) {
4010
+ this.config.onError?.(error);
4011
+ }
4012
+ }
4013
+ /**
4014
+ * Identify a group and set its properties
4015
+ *
4016
+ * Groups are useful for B2B SaaS to track organizations, teams, or accounts.
4017
+ *
4018
+ * @param groupType - Type of group (e.g., 'company', 'organization', 'team')
4019
+ * @param groupKey - Unique identifier for the group
4020
+ * @param properties - Group properties
4021
+ *
4022
+ * @example
4023
+ * ```typescript
4024
+ * await subscriber.groupIdentify('company', 'acme-corp', {
4025
+ * $set: {
4026
+ * name: 'Acme Corporation',
4027
+ * industry: 'saas',
4028
+ * employees: 500,
4029
+ * plan: 'enterprise'
4030
+ * }
4031
+ * });
4032
+ * ```
4033
+ */
4034
+ async groupIdentify(groupType, groupKey, properties) {
4035
+ if (!this.enabled) return;
4036
+ await this.ensureInitialized();
4037
+ try {
4038
+ this.posthog?.groupIdentify({
4039
+ groupType,
4040
+ groupKey: String(groupKey),
4041
+ // Convert to string for PostHog SDK
4042
+ properties
4043
+ });
4044
+ } catch (error) {
4045
+ this.config.onError?.(error);
4046
+ }
4047
+ }
4048
+ /**
4049
+ * Track an event with group context
4050
+ *
4051
+ * Use this to associate events with groups (e.g., organizations).
4052
+ *
4053
+ * @param name - Event name
4054
+ * @param attributes - Event attributes
4055
+ * @param groups - Group context (e.g., { company: 'acme-corp' })
4056
+ *
4057
+ * @example
4058
+ * ```typescript
4059
+ * await subscriber.trackEventWithGroups('feature.used', {
4060
+ * userId: 'user-123',
4061
+ * feature: 'advanced-events'
4062
+ * }, {
4063
+ * company: 'acme-corp'
4064
+ * });
4065
+ * ```
4066
+ */
4067
+ async trackEventWithGroups(name, attributes, groups) {
4068
+ if (!this.enabled) return;
4069
+ await this.ensureInitialized();
4070
+ const eventAttributes = { ...attributes };
4071
+ if (groups) {
4072
+ eventAttributes.groups = groups;
4073
+ }
4074
+ await this.trackEvent(name, eventAttributes);
4075
+ }
4076
+ /**
4077
+ * Flush pending events and clean up resources
4078
+ */
4079
+ async shutdown() {
4080
+ await super.shutdown();
4081
+ await this.ensureInitialized();
4082
+ if (this.posthog) {
4083
+ try {
4084
+ await this.posthog.shutdown();
4085
+ } catch (error) {
4086
+ this.config.onError?.(error);
4087
+ }
4088
+ }
4089
+ }
4090
+ /**
4091
+ * Handle errors with custom error handler
4092
+ */
4093
+ handleError(error, payload) {
4094
+ this.config.onError?.(error);
4095
+ super.handleError(error, payload);
4096
+ }
4097
+ };
4098
+ /*! Bundled license information:
4099
+
4100
+ @posthog/core/dist/vendor/uuidv7.mjs:
4101
+ (*! For license information please see uuidv7.mjs.LICENSE.txt *)
4102
+ (**
4103
+ * uuidv7: An experimental implementation of the proposed UUID Version 7
4104
+ *
4105
+ * @license Apache-2.0
4106
+ * @copyright 2021-2023 LiosK
4107
+ * @packageDocumentation
4108
+ *)
4109
+ */
4110
+
4111
+ export { PostHogSubscriber };
4112
+ //# sourceMappingURL=posthog.js.map
4113
+ //# sourceMappingURL=posthog.js.map