{"version":3,"file":"index.cjs","sources":["../../src/extensions/sentry-integration.ts","../../../posthog-core/src/vendor/uuidv7.ts","../../src/extensions/error-tracking/autocapture.ts","../../src/extensions/error-tracking/chunk-ids.ts","../../src/extensions/error-tracking/type-checking.ts","../../src/extensions/error-tracking/error-conversion.ts","../../src/extensions/error-tracking/index.ts","../../src/extensions/express.ts","../../../posthog-core/src/types.ts","../../../posthog-core/src/featureFlagUtils.ts","../../../posthog-core/src/utils.ts","../../../posthog-core/src/gzip.ts","../../../posthog-core/src/eventemitter.ts","../../../posthog-core/src/index.ts","../../src/extensions/feature-flags/lazy.ts","../../src/extensions/feature-flags/crypto-helpers.ts","../../src/extensions/feature-flags/crypto.ts","../../src/extensions/feature-flags/feature-flags.ts","../../src/storage-memory.ts","../../src/client.ts","../../src/extensions/error-tracking/stack-parser.ts","../../src/entrypoints/index.edge.ts"],"sourcesContent":["/**\n * @file Adapted from [posthog-js](https://github.com/PostHog/posthog-js/blob/8157df935a4d0e71d2fefef7127aa85ee51c82d1/src/extensions/sentry-integration.ts) with modifications for the Node SDK.\n */\n/**\n * Integrate Sentry with PostHog. This will add a direct link to the person in Sentry, and an $exception event in PostHog.\n *\n * ### Usage\n *\n *     Sentry.init({\n *          dsn: 'https://example',\n *          integrations: [\n *              new PostHogSentryIntegration(posthog)\n *          ]\n *     })\n *\n *     Sentry.setTag(PostHogSentryIntegration.POSTHOG_ID_TAG, 'some distinct id');\n *\n * @param {Object} [posthog] The posthog object\n * @param {string} [organization] Optional: The Sentry organization, used to send a direct link from PostHog to Sentry\n * @param {Number} [projectId] Optional: The Sentry project id, used to send a direct link from PostHog to Sentry\n * @param {string} [prefix] Optional: Url of a self-hosted sentry instance (default: https://sentry.io/organizations/)\n * @param {SeverityLevel[] | '*'} [severityAllowList] Optional: send events matching the provided levels. Use '*' to send all events (default: ['error'])\n */\n\nimport { SeverityLevel } from './error-tracking/types'\nimport { type PostHogBackendClient } from '../client'\n\n// NOTE - we can't import from @sentry/types because it changes frequently and causes clashes\n// We only use a small subset of the types, so we can just define the integration overall and use any for the rest\n\n// import {\n//     Event as _SentryEvent,\n//     EventProcessor as _SentryEventProcessor,\n//     Exception as _SentryException,\n//     Hub as _SentryHub,\n//     Primitive as _SentryPrimitive,\n//     Integration as _SentryIntegration,\n//     IntegrationClass as _SentryIntegrationClass,\n// } from '@sentry/types'\n\n// Uncomment the above and comment the below to get type checking for development\n\ntype _SentryEvent = any\ntype _SentryEventProcessor = any\ntype _SentryException = any\ntype _SentryHub = any\ntype _SentryPrimitive = any\n\ninterface _SentryIntegration {\n  name: string\n  processEvent(event: _SentryEvent): _SentryEvent\n}\n\ninterface _SentryIntegrationClass {\n  name: string\n  setupOnce(addGlobalEventProcessor: (callback: _SentryEventProcessor) => void, getCurrentHub: () => _SentryHub): void\n}\n\ninterface SentryExceptionProperties {\n  $sentry_event_id?: string\n  $sentry_exception?: { values?: _SentryException[] }\n  $sentry_exception_message?: string\n  $sentry_exception_type?: string\n  $sentry_tags: { [key: string]: _SentryPrimitive }\n  $sentry_url?: string\n}\n\nexport type SentryIntegrationOptions = {\n  organization?: string\n  projectId?: number\n  prefix?: string\n  severityAllowList?: SeverityLevel[] | '*'\n}\n\nconst NAME = 'posthog-node'\n\nexport function createEventProcessor(\n  _posthog: PostHogBackendClient,\n  { organization, projectId, prefix, severityAllowList = ['error'] }: SentryIntegrationOptions = {}\n): (event: _SentryEvent) => _SentryEvent {\n  return (event) => {\n    const shouldProcessLevel = severityAllowList === '*' || severityAllowList.includes(event.level)\n    if (!shouldProcessLevel) {\n      return event\n    }\n    if (!event.tags) {\n      event.tags = {}\n    }\n\n    // Get the PostHog user ID from a specific tag, which users can set on their Sentry scope as they need.\n    const userId = event.tags[PostHogSentryIntegration.POSTHOG_ID_TAG]\n    if (userId === undefined) {\n      // If we can't find a user ID, don't bother linking the event. We won't be able to send anything meaningful to PostHog without it.\n      return event\n    }\n\n    const uiHost = _posthog.options.host ?? 'https://us.i.posthog.com'\n    const personUrl = new URL(`/project/${_posthog.apiKey}/person/${userId}`, uiHost).toString()\n\n    event.tags['PostHog Person URL'] = personUrl\n\n    const exceptions: _SentryException[] = event.exception?.values || []\n\n    const exceptionList = exceptions.map((exception) => ({\n      ...exception,\n      stacktrace: exception.stacktrace\n        ? {\n            ...exception.stacktrace,\n            type: 'raw',\n            frames: (exception.stacktrace.frames || []).map((frame: any) => {\n              return { ...frame, platform: 'node:javascript' }\n            }),\n          }\n        : undefined,\n    }))\n\n    const properties: SentryExceptionProperties & {\n      // two properties added to match any exception auto-capture\n      // added manually to avoid any dependency on the lazily loaded content\n      $exception_message: any\n      $exception_type: any\n      $exception_list: any\n      $exception_personURL: string\n      $exception_level: SeverityLevel\n    } = {\n      // PostHog Exception Properties,\n      $exception_message: exceptions[0]?.value || event.message,\n      $exception_type: exceptions[0]?.type,\n      $exception_personURL: personUrl,\n      $exception_level: event.level,\n      $exception_list: exceptionList,\n      // Sentry Exception Properties\n      $sentry_event_id: event.event_id,\n      $sentry_exception: event.exception,\n      $sentry_exception_message: exceptions[0]?.value || event.message,\n      $sentry_exception_type: exceptions[0]?.type,\n      $sentry_tags: event.tags,\n    }\n\n    if (organization && projectId) {\n      properties['$sentry_url'] =\n        (prefix || 'https://sentry.io/organizations/') +\n        organization +\n        '/issues/?project=' +\n        projectId +\n        '&query=' +\n        event.event_id\n    }\n\n    _posthog.capture({ event: '$exception', distinctId: userId, properties })\n\n    return event\n  }\n}\n\n// V8 integration - function based\nexport function sentryIntegration(\n  _posthog: PostHogBackendClient,\n  options?: SentryIntegrationOptions\n): _SentryIntegration {\n  const processor = createEventProcessor(_posthog, options)\n  return {\n    name: NAME,\n    processEvent(event) {\n      return processor(event)\n    },\n  }\n}\n\n// V7 integration - class based\nexport class PostHogSentryIntegration implements _SentryIntegrationClass {\n  public readonly name = NAME\n\n  public static readonly POSTHOG_ID_TAG = 'posthog_distinct_id'\n\n  public setupOnce: (\n    addGlobalEventProcessor: (callback: _SentryEventProcessor) => void,\n    getCurrentHub: () => _SentryHub\n  ) => void\n\n  constructor(\n    _posthog: PostHogBackendClient,\n    organization?: string,\n    prefix?: string,\n    severityAllowList?: SeverityLevel[] | '*'\n  ) {\n    // setupOnce gets called by Sentry when it intializes the plugin\n    this.name = NAME\n    this.setupOnce = function (\n      addGlobalEventProcessor: (callback: _SentryEventProcessor) => void,\n      getCurrentHub: () => _SentryHub\n    ) {\n      const projectId = getCurrentHub()?.getClient()?.getDsn()?.projectId\n      addGlobalEventProcessor(\n        createEventProcessor(_posthog, {\n          organization,\n          projectId,\n          prefix,\n          severityAllowList,\n        })\n      )\n    }\n  }\n}\n","// vendor from: https://github.com/LiosK/uuidv7/blob/f30b7a7faff73afbce0b27a46c638310f96912ba/src/index.ts\n// https://github.com/LiosK/uuidv7#license\n\n/**\n * uuidv7: An experimental implementation of the proposed UUID Version 7\n *\n * @license Apache-2.0\n * @copyright 2021-2023 LiosK\n * @packageDocumentation\n */\n\nconst DIGITS = \"0123456789abcdef\";\n\n/** Represents a UUID as a 16-byte byte array. */\nexport class UUID {\n  /** @param bytes - The 16-byte byte array representation. */\n  private constructor(readonly bytes: Readonly<Uint8Array>) {}\n\n  /**\n   * Creates an object from the internal representation, a 16-byte byte array\n   * containing the binary UUID representation in the big-endian byte order.\n   *\n   * This method does NOT shallow-copy the argument, and thus the created object\n   * holds the reference to the underlying buffer.\n   *\n   * @throws TypeError if the length of the argument is not 16.\n   */\n  static ofInner(bytes: Readonly<Uint8Array>): UUID {\n    if (bytes.length !== 16) {\n      throw new TypeError(\"not 128-bit length\");\n    } else {\n      return new UUID(bytes);\n    }\n  }\n\n  /**\n   * Builds a byte array from UUIDv7 field values.\n   *\n   * @param unixTsMs - A 48-bit `unix_ts_ms` field value.\n   * @param randA - A 12-bit `rand_a` field value.\n   * @param randBHi - The higher 30 bits of 62-bit `rand_b` field value.\n   * @param randBLo - The lower 32 bits of 62-bit `rand_b` field value.\n   * @throws RangeError if any field value is out of the specified range.\n   */\n  static fromFieldsV7(\n    unixTsMs: number,\n    randA: number,\n    randBHi: number,\n    randBLo: number,\n  ): UUID {\n    if (\n      !Number.isInteger(unixTsMs) ||\n      !Number.isInteger(randA) ||\n      !Number.isInteger(randBHi) ||\n      !Number.isInteger(randBLo) ||\n      unixTsMs < 0 ||\n      randA < 0 ||\n      randBHi < 0 ||\n      randBLo < 0 ||\n      unixTsMs > 0xffff_ffff_ffff ||\n      randA > 0xfff ||\n      randBHi > 0x3fff_ffff ||\n      randBLo > 0xffff_ffff\n    ) {\n      throw new RangeError(\"invalid field value\");\n    }\n\n    const bytes = new Uint8Array(16);\n    bytes[0] = unixTsMs / 2 ** 40;\n    bytes[1] = unixTsMs / 2 ** 32;\n    bytes[2] = unixTsMs / 2 ** 24;\n    bytes[3] = unixTsMs / 2 ** 16;\n    bytes[4] = unixTsMs / 2 ** 8;\n    bytes[5] = unixTsMs;\n    bytes[6] = 0x70 | (randA >>> 8);\n    bytes[7] = randA;\n    bytes[8] = 0x80 | (randBHi >>> 24);\n    bytes[9] = randBHi >>> 16;\n    bytes[10] = randBHi >>> 8;\n    bytes[11] = randBHi;\n    bytes[12] = randBLo >>> 24;\n    bytes[13] = randBLo >>> 16;\n    bytes[14] = randBLo >>> 8;\n    bytes[15] = randBLo;\n    return new UUID(bytes);\n  }\n\n  /**\n   * Builds a byte array from a string representation.\n   *\n   * This method accepts the following formats:\n   *\n   * - 32-digit hexadecimal format without hyphens: `0189dcd553117d408db09496a2eef37b`\n   * - 8-4-4-4-12 hyphenated format: `0189dcd5-5311-7d40-8db0-9496a2eef37b`\n   * - Hyphenated format with surrounding braces: `{0189dcd5-5311-7d40-8db0-9496a2eef37b}`\n   * - RFC 4122 URN format: `urn:uuid:0189dcd5-5311-7d40-8db0-9496a2eef37b`\n   *\n   * Leading and trailing whitespaces represents an error.\n   *\n   * @throws SyntaxError if the argument could not parse as a valid UUID string.\n   */\n  static parse(uuid: string): UUID {\n    let hex: string | undefined = undefined;\n    switch (uuid.length) {\n      case 32:\n        hex = /^[0-9a-f]{32}$/i.exec(uuid)?.[0];\n        break;\n      case 36:\n        hex =\n          /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i\n            .exec(uuid)\n            ?.slice(1, 6)\n            .join(\"\");\n        break;\n      case 38:\n        hex =\n          /^\\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\\}$/i\n            .exec(uuid)\n            ?.slice(1, 6)\n            .join(\"\");\n        break;\n      case 45:\n        hex =\n          /^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i\n            .exec(uuid)\n            ?.slice(1, 6)\n            .join(\"\");\n        break;\n      default:\n        break;\n    }\n\n    if (hex) {\n      const inner = new Uint8Array(16);\n      for (let i = 0; i < 16; i += 4) {\n        const n = parseInt(hex.substring(2 * i, 2 * i + 8), 16);\n        inner[i + 0] = n >>> 24;\n        inner[i + 1] = n >>> 16;\n        inner[i + 2] = n >>> 8;\n        inner[i + 3] = n;\n      }\n      return new UUID(inner);\n    } else {\n      throw new SyntaxError(\"could not parse UUID string\");\n    }\n  }\n\n  /**\n   * @returns The 8-4-4-4-12 canonical hexadecimal string representation\n   * (`0189dcd5-5311-7d40-8db0-9496a2eef37b`).\n   */\n  toString(): string {\n    let text = \"\";\n    for (let i = 0; i < this.bytes.length; i++) {\n      text += DIGITS.charAt(this.bytes[i] >>> 4);\n      text += DIGITS.charAt(this.bytes[i] & 0xf);\n      if (i === 3 || i === 5 || i === 7 || i === 9) {\n        text += \"-\";\n      }\n    }\n    return text;\n  }\n\n  /**\n   * @returns The 32-digit hexadecimal representation without hyphens\n   * (`0189dcd553117d408db09496a2eef37b`).\n   */\n  toHex(): string {\n    let text = \"\";\n    for (let i = 0; i < this.bytes.length; i++) {\n      text += DIGITS.charAt(this.bytes[i] >>> 4);\n      text += DIGITS.charAt(this.bytes[i] & 0xf);\n    }\n    return text;\n  }\n\n  /** @returns The 8-4-4-4-12 canonical hexadecimal string representation. */\n  toJSON(): string {\n    return this.toString();\n  }\n\n  /**\n   * Reports the variant field value of the UUID or, if appropriate, \"NIL\" or\n   * \"MAX\".\n   *\n   * For convenience, this method reports \"NIL\" or \"MAX\" if `this` represents\n   * the Nil or Max UUID, although the Nil and Max UUIDs are technically\n   * subsumed under the variants `0b0` and `0b111`, respectively.\n   */\n  getVariant():\n    | \"VAR_0\"\n    | \"VAR_10\"\n    | \"VAR_110\"\n    | \"VAR_RESERVED\"\n    | \"NIL\"\n    | \"MAX\" {\n    const n = this.bytes[8] >>> 4;\n    if (n < 0) {\n      throw new Error(\"unreachable\");\n    } else if (n <= 0b0111) {\n      return this.bytes.every((e) => e === 0) ? \"NIL\" : \"VAR_0\";\n    } else if (n <= 0b1011) {\n      return \"VAR_10\";\n    } else if (n <= 0b1101) {\n      return \"VAR_110\";\n    } else if (n <= 0b1111) {\n      return this.bytes.every((e) => e === 0xff) ? \"MAX\" : \"VAR_RESERVED\";\n    } else {\n      throw new Error(\"unreachable\");\n    }\n  }\n\n  /**\n   * Returns the version field value of the UUID or `undefined` if the UUID does\n   * not have the variant field value of `0b10`.\n   */\n  getVersion(): number | undefined {\n    return this.getVariant() === \"VAR_10\" ? this.bytes[6] >>> 4 : undefined;\n  }\n\n  /** Creates an object from `this`. */\n  clone(): UUID {\n    return new UUID(this.bytes.slice(0));\n  }\n\n  /** Returns true if `this` is equivalent to `other`. */\n  equals(other: UUID): boolean {\n    return this.compareTo(other) === 0;\n  }\n\n  /**\n   * Returns a negative integer, zero, or positive integer if `this` is less\n   * than, equal to, or greater than `other`, respectively.\n   */\n  compareTo(other: UUID): number {\n    for (let i = 0; i < 16; i++) {\n      const diff = this.bytes[i] - other.bytes[i];\n      if (diff !== 0) {\n        return Math.sign(diff);\n      }\n    }\n    return 0;\n  }\n}\n\n/**\n * Encapsulates the monotonic counter state.\n *\n * This class provides APIs to utilize a separate counter state from that of the\n * global generator used by {@link uuidv7} and {@link uuidv7obj}. In addition to\n * the default {@link generate} method, this class has {@link generateOrAbort}\n * that is useful to absolutely guarantee the monotonically increasing order of\n * generated UUIDs. See their respective documentation for details.\n */\nexport class V7Generator {\n  private timestamp = 0;\n  private counter = 0;\n\n  /** The random number generator used by the generator. */\n  private readonly random: { nextUint32(): number };\n\n  /**\n   * Creates a generator object with the default random number generator, or\n   * with the specified one if passed as an argument. The specified random\n   * number generator should be cryptographically strong and securely seeded.\n   */\n  constructor(randomNumberGenerator?: {\n    /** Returns a 32-bit random unsigned integer. */\n    nextUint32(): number;\n  }) {\n    this.random = randomNumberGenerator ?? getDefaultRandom();\n  }\n\n  /**\n   * Generates a new UUIDv7 object from the current timestamp, or resets the\n   * generator upon significant timestamp rollback.\n   *\n   * This method returns a monotonically increasing UUID by reusing the previous\n   * timestamp even if the up-to-date timestamp is smaller than the immediately\n   * preceding UUID's. However, when such a clock rollback is considered\n   * significant (i.e., by more than ten seconds), this method resets the\n   * generator and returns a new UUID based on the given timestamp, breaking the\n   * increasing order of UUIDs.\n   *\n   * See {@link generateOrAbort} for the other mode of generation and\n   * {@link generateOrResetCore} for the low-level primitive.\n   */\n  generate(): UUID {\n    return this.generateOrResetCore(Date.now(), 10_000);\n  }\n\n  /**\n   * Generates a new UUIDv7 object from the current timestamp, or returns\n   * `undefined` upon significant timestamp rollback.\n   *\n   * This method returns a monotonically increasing UUID by reusing the previous\n   * timestamp even if the up-to-date timestamp is smaller than the immediately\n   * preceding UUID's. However, when such a clock rollback is considered\n   * significant (i.e., by more than ten seconds), this method aborts and\n   * returns `undefined` immediately.\n   *\n   * See {@link generate} for the other mode of generation and\n   * {@link generateOrAbortCore} for the low-level primitive.\n   */\n  generateOrAbort(): UUID | undefined {\n    return this.generateOrAbortCore(Date.now(), 10_000);\n  }\n\n  /**\n   * Generates a new UUIDv7 object from the `unixTsMs` passed, or resets the\n   * generator upon significant timestamp rollback.\n   *\n   * This method is equivalent to {@link generate} except that it takes a custom\n   * timestamp and clock rollback allowance.\n   *\n   * @param rollbackAllowance - The amount of `unixTsMs` rollback that is\n   * considered significant. A suggested value is `10_000` (milliseconds).\n   * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.\n   */\n  generateOrResetCore(unixTsMs: number, rollbackAllowance: number): UUID {\n    let value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);\n    if (value === undefined) {\n      // reset state and resume\n      this.timestamp = 0;\n      value = this.generateOrAbortCore(unixTsMs, rollbackAllowance)!;\n    }\n    return value;\n  }\n\n  /**\n   * Generates a new UUIDv7 object from the `unixTsMs` passed, or returns\n   * `undefined` upon significant timestamp rollback.\n   *\n   * This method is equivalent to {@link generateOrAbort} except that it takes a\n   * custom timestamp and clock rollback allowance.\n   *\n   * @param rollbackAllowance - The amount of `unixTsMs` rollback that is\n   * considered significant. A suggested value is `10_000` (milliseconds).\n   * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.\n   */\n  generateOrAbortCore(\n    unixTsMs: number,\n    rollbackAllowance: number,\n  ): UUID | undefined {\n    const MAX_COUNTER = 0x3ff_ffff_ffff;\n\n    if (\n      !Number.isInteger(unixTsMs) ||\n      unixTsMs < 1 ||\n      unixTsMs > 0xffff_ffff_ffff\n    ) {\n      throw new RangeError(\"`unixTsMs` must be a 48-bit positive integer\");\n    } else if (rollbackAllowance < 0 || rollbackAllowance > 0xffff_ffff_ffff) {\n      throw new RangeError(\"`rollbackAllowance` out of reasonable range\");\n    }\n\n    if (unixTsMs > this.timestamp) {\n      this.timestamp = unixTsMs;\n      this.resetCounter();\n    } else if (unixTsMs + rollbackAllowance >= this.timestamp) {\n      // go on with previous timestamp if new one is not much smaller\n      this.counter++;\n      if (this.counter > MAX_COUNTER) {\n        // increment timestamp at counter overflow\n        this.timestamp++;\n        this.resetCounter();\n      }\n    } else {\n      // abort if clock went backwards to unbearable extent\n      return undefined;\n    }\n\n    return UUID.fromFieldsV7(\n      this.timestamp,\n      Math.trunc(this.counter / 2 ** 30),\n      this.counter & (2 ** 30 - 1),\n      this.random.nextUint32(),\n    );\n  }\n\n  /** Initializes the counter at a 42-bit random integer. */\n  private resetCounter(): void {\n    this.counter =\n      this.random.nextUint32() * 0x400 + (this.random.nextUint32() & 0x3ff);\n  }\n\n  /**\n   * Generates a new UUIDv4 object utilizing the random number generator inside.\n   *\n   * @internal\n   */\n  generateV4(): UUID {\n    const bytes = new Uint8Array(\n      Uint32Array.of(\n        this.random.nextUint32(),\n        this.random.nextUint32(),\n        this.random.nextUint32(),\n        this.random.nextUint32(),\n      ).buffer,\n    );\n    bytes[6] = 0x40 | (bytes[6] >>> 4);\n    bytes[8] = 0x80 | (bytes[8] >>> 2);\n    return UUID.ofInner(bytes);\n  }\n}\n\n/** A global flag to force use of cryptographically strong RNG. */\n// declare const UUIDV7_DENY_WEAK_RNG: boolean;\n\n/** Returns the default random number generator available in the environment. */\nconst getDefaultRandom = (): { nextUint32(): number } => {\n// fix: crypto isn't available in react-native, always use Math.random\n\n//   // detect Web Crypto API\n//   if (\n//     typeof crypto !== \"undefined\" &&\n//     typeof crypto.getRandomValues !== \"undefined\"\n//   ) {\n//     return new BufferedCryptoRandom();\n//   } else {\n//     // fall back on Math.random() unless the flag is set to true\n//     if (typeof UUIDV7_DENY_WEAK_RNG !== \"undefined\" && UUIDV7_DENY_WEAK_RNG) {\n//       throw new Error(\"no cryptographically strong RNG available\");\n//     }\n//     return {\n//       nextUint32: (): number =>\n//         Math.trunc(Math.random() * 0x1_0000) * 0x1_0000 +\n//         Math.trunc(Math.random() * 0x1_0000),\n//     };\n//   }\n  return {\n    nextUint32: (): number =>\n      Math.trunc(Math.random() * 0x1_0000) * 0x1_0000 +\n      Math.trunc(Math.random() * 0x1_0000),\n  };\n};\n\n// /**\n//  * Wraps `crypto.getRandomValues()` to enable buffering; this uses a small\n//  * buffer by default to avoid both unbearable throughput decline in some\n//  * environments and the waste of time and space for unused values.\n//  */\n// class BufferedCryptoRandom {\n//   private readonly buffer = new Uint32Array(8);\n//   private cursor = 0xffff;\n//   nextUint32(): number {\n//     if (this.cursor >= this.buffer.length) {\n//       crypto.getRandomValues(this.buffer);\n//       this.cursor = 0;\n//     }\n//     return this.buffer[this.cursor++];\n//   }\n// }\n\nlet defaultGenerator: V7Generator | undefined;\n\n/**\n * Generates a UUIDv7 string.\n *\n * @returns The 8-4-4-4-12 canonical hexadecimal string representation\n * (\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\").\n */\nexport const uuidv7 = (): string => uuidv7obj().toString();\n\n/** Generates a UUIDv7 object. */\nexport const uuidv7obj = (): UUID =>\n  (defaultGenerator || (defaultGenerator = new V7Generator())).generate();\n\n/**\n * Generates a UUIDv4 string.\n *\n * @returns The 8-4-4-4-12 canonical hexadecimal string representation\n * (\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\").\n */\nexport const uuidv4 = (): string => uuidv4obj().toString();\n\n/** Generates a UUIDv4 object. */\nexport const uuidv4obj = (): UUID =>\n  (defaultGenerator || (defaultGenerator = new V7Generator())).generateV4();\n","// Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry\n// Licensed under the MIT License\n\nimport { EventHint } from './types'\n\ntype ErrorHandler = { _posthogErrorHandler: boolean } & ((error: Error) => void)\n\nfunction makeUncaughtExceptionHandler(\n  captureFn: (exception: Error, hint: EventHint) => void,\n  onFatalFn: () => void\n): ErrorHandler {\n  let calledFatalError: boolean = false\n\n  return Object.assign(\n    (error: Error): void => {\n      // Attaching a listener to `uncaughtException` will prevent the node process from exiting. We generally do not\n      // want to alter this behaviour so we check for other listeners that users may have attached themselves and adjust\n      // exit behaviour of the SDK accordingly:\n      // - If other listeners are attached, do not exit.\n      // - If the only listener attached is ours, exit.\n      const userProvidedListenersCount = global.process.listeners('uncaughtException').filter((listener) => {\n        // There are 2 listeners we ignore:\n        return (\n          // as soon as we're using domains this listener is attached by node itself\n          listener.name !== 'domainUncaughtExceptionClear' &&\n          // the handler we register in this integration\n          (listener as ErrorHandler)._posthogErrorHandler !== true\n        )\n      }).length\n\n      const processWouldExit = userProvidedListenersCount === 0\n\n      captureFn(error, {\n        mechanism: {\n          type: 'onuncaughtexception',\n          handled: false,\n        },\n      })\n\n      if (!calledFatalError && processWouldExit) {\n        calledFatalError = true\n        onFatalFn()\n      }\n    },\n    { _posthogErrorHandler: true }\n  )\n}\n\nexport function addUncaughtExceptionListener(\n  captureFn: (exception: Error, hint: EventHint) => void,\n  onFatalFn: () => void\n): void {\n  global.process.on('uncaughtException', makeUncaughtExceptionHandler(captureFn, onFatalFn))\n}\n\nexport function addUnhandledRejectionListener(captureFn: (exception: unknown, hint: EventHint) => void): void {\n  global.process.on('unhandledRejection', (reason: unknown) => {\n    captureFn(reason, {\n      mechanism: {\n        type: 'onunhandledrejection',\n        handled: false,\n      },\n    })\n  })\n}\n","// Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry\n// Licensed under the MIT License\n\nimport type { StackParser } from './types'\n\ntype StackString = string\ntype CachedResult = [string, string]\n\ntype ChunkIdMapType = Record<string, string>\n\nlet parsedStackResults: Record<StackString, CachedResult> | undefined\nlet lastKeysCount: number | undefined\nlet cachedFilenameChunkIds: ChunkIdMapType | undefined\n\nexport function getFilenameToChunkIdMap(stackParser: StackParser): ChunkIdMapType {\n  const chunkIdMap = (globalThis as any)._posthogChunkIds as ChunkIdMapType | undefined\n  if (!chunkIdMap) {\n    console.error('No chunk id map found')\n    return {}\n  }\n\n  const chunkIdKeys = Object.keys(chunkIdMap)\n\n  if (cachedFilenameChunkIds && chunkIdKeys.length === lastKeysCount) {\n    return cachedFilenameChunkIds\n  }\n\n  lastKeysCount = chunkIdKeys.length\n\n  cachedFilenameChunkIds = chunkIdKeys.reduce<Record<string, string>>((acc, stackKey) => {\n    if (!parsedStackResults) {\n      parsedStackResults = {}\n    }\n\n    const result = parsedStackResults[stackKey]\n\n    if (result) {\n      acc[result[0]] = result[1]\n    } else {\n      const parsedStack = stackParser(stackKey)\n\n      for (let i = parsedStack.length - 1; i >= 0; i--) {\n        const stackFrame = parsedStack[i]\n        const filename = stackFrame?.filename\n        const chunkId = chunkIdMap[stackKey]\n\n        if (filename && chunkId) {\n          acc[filename] = chunkId\n          parsedStackResults[stackKey] = [filename, chunkId]\n          break\n        }\n      }\n    }\n\n    return acc\n  }, {})\n\n  return cachedFilenameChunkIds\n}\n","// Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry\n// Licensed under the MIT License\n\nimport { PolymorphicEvent } from './types'\n\nexport function isEvent(candidate: unknown): candidate is PolymorphicEvent {\n  return typeof Event !== 'undefined' && isInstanceOf(candidate, Event)\n}\n\nexport function isPlainObject(candidate: unknown): candidate is Record<string, unknown> {\n  return isBuiltin(candidate, 'Object')\n}\n\nexport function isError(candidate: unknown): candidate is Error {\n  switch (Object.prototype.toString.call(candidate)) {\n    case '[object Error]':\n    case '[object Exception]':\n    case '[object DOMException]':\n    case '[object WebAssembly.Exception]':\n      return true\n    default:\n      return isInstanceOf(candidate, Error)\n  }\n}\n\nexport function isInstanceOf(candidate: unknown, base: any): boolean {\n  try {\n    return candidate instanceof base\n  } catch {\n    return false\n  }\n}\n\nexport function isErrorEvent(event: unknown): boolean {\n  return isBuiltin(event, 'ErrorEvent')\n}\n\nexport function isBuiltin(candidate: unknown, className: string): boolean {\n  return Object.prototype.toString.call(candidate) === `[object ${className}]`\n}\n","// Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry\n// Licensed under the MIT License\n\nimport { getFilenameToChunkIdMap } from './chunk-ids'\nimport { isError, isErrorEvent, isEvent, isPlainObject } from './type-checking'\nimport {\n  ErrorProperties,\n  EventHint,\n  Exception,\n  Mechanism,\n  StackFrame,\n  StackFrameModifierFn,\n  StackParser,\n} from './types'\n\nexport async function propertiesFromUnknownInput(\n  stackParser: StackParser,\n  frameModifiers: StackFrameModifierFn[],\n  input: unknown,\n  hint?: EventHint\n): Promise<ErrorProperties> {\n  const providedMechanism = hint && hint.mechanism\n  const mechanism = providedMechanism || {\n    handled: true,\n    type: 'generic',\n  }\n\n  const errorList = getErrorList(mechanism, input, hint)\n  const exceptionList = await Promise.all(\n    errorList.map(async (error) => {\n      const exception = await exceptionFromError(stackParser, frameModifiers, error)\n      exception.value = exception.value || ''\n      exception.type = exception.type || 'Error'\n      exception.mechanism = mechanism\n      return exception\n    })\n  )\n\n  const properties = { $exception_list: exceptionList }\n  return properties\n}\n\n// Flatten error causes into a list of errors\n// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause\nfunction getErrorList(mechanism: Mechanism, input: unknown, hint?: EventHint): Error[] {\n  const error = getError(mechanism, input, hint)\n  if (error.cause) {\n    return [error, ...getErrorList(mechanism, error.cause, hint)]\n  }\n  return [error]\n}\n\nfunction getError(mechanism: Mechanism, exception: unknown, hint?: EventHint): Error {\n  if (isError(exception)) {\n    return exception\n  }\n\n  mechanism.synthetic = true\n\n  if (isPlainObject(exception)) {\n    const errorFromProp = getErrorPropertyFromObject(exception)\n    if (errorFromProp) {\n      return errorFromProp\n    }\n\n    const message = getMessageForObject(exception)\n    const ex = hint?.syntheticException || new Error(message)\n    ex.message = message\n\n    return ex\n  }\n\n  // This handles when someone does: `throw \"something awesome\";`\n  // We use synthesized Error here so we can extract a (rough) stack trace.\n  const ex = hint?.syntheticException || new Error(exception as string)\n  ex.message = `${exception}`\n\n  return ex\n}\n\n/** If a plain object has a property that is an `Error`, return this error. */\nfunction getErrorPropertyFromObject(obj: Record<string, unknown>): Error | undefined {\n  for (const prop in obj) {\n    if (Object.prototype.hasOwnProperty.call(obj, prop)) {\n      const value = obj[prop]\n      if (isError(value)) {\n        return value\n      }\n    }\n  }\n\n  return undefined\n}\n\nfunction getMessageForObject(exception: Record<string, unknown>): string {\n  if ('name' in exception && typeof exception.name === 'string') {\n    let message = `'${exception.name}' captured as exception`\n\n    if ('message' in exception && typeof exception.message === 'string') {\n      message += ` with message '${exception.message}'`\n    }\n\n    return message\n  } else if ('message' in exception && typeof exception.message === 'string') {\n    return exception.message\n  }\n\n  const keys = extractExceptionKeysForMessage(exception)\n\n  // Some ErrorEvent instances do not have an `error` property, which is why they are not handled before\n  // We still want to try to get a decent message for these cases\n  if (isErrorEvent(exception)) {\n    return `Event \\`ErrorEvent\\` captured as exception with message \\`${exception.message}\\``\n  }\n\n  const className = getObjectClassName(exception)\n\n  return `${className && className !== 'Object' ? `'${className}'` : 'Object'} captured as exception with keys: ${keys}`\n}\n\nfunction getObjectClassName(obj: unknown): string | undefined | void {\n  try {\n    const prototype: unknown | null = Object.getPrototypeOf(obj)\n    return prototype ? prototype.constructor.name : undefined\n  } catch (e) {\n    // ignore errors here\n  }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nfunction extractExceptionKeysForMessage(exception: Record<string, unknown>, maxLength: number = 40): string {\n  const keys = Object.keys(convertToPlainObject(exception))\n  keys.sort()\n\n  const firstKey = keys[0]\n\n  if (!firstKey) {\n    return '[object has no keys]'\n  }\n\n  if (firstKey.length >= maxLength) {\n    return truncate(firstKey, maxLength)\n  }\n\n  for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n    const serialized = keys.slice(0, includedKeys).join(', ')\n    if (serialized.length > maxLength) {\n      continue\n    }\n    if (includedKeys === keys.length) {\n      return serialized\n    }\n    return truncate(serialized, maxLength)\n  }\n\n  return ''\n}\n\nfunction truncate(str: string, max: number = 0): string {\n  if (typeof str !== 'string' || max === 0) {\n    return str\n  }\n  return str.length <= max ? str : `${str.slice(0, max)}...`\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argument itself, when value is neither an Event nor\n *  an Error.\n */\nfunction convertToPlainObject<V>(value: V):\n  | {\n      [ownProps: string]: unknown\n      type: string\n      target: string\n      currentTarget: string\n      detail?: unknown\n    }\n  | {\n      [ownProps: string]: unknown\n      message: string\n      name: string\n      stack?: string\n    }\n  | V {\n  if (isError(value)) {\n    return {\n      message: value.message,\n      name: value.name,\n      stack: value.stack,\n      ...getOwnProperties(value),\n    }\n  } else if (isEvent(value)) {\n    const newObj: {\n      [ownProps: string]: unknown\n      type: string\n      target: string\n      currentTarget: string\n      detail?: unknown\n    } = {\n      type: value.type,\n      target: serializeEventTarget(value.target),\n      currentTarget: serializeEventTarget(value.currentTarget),\n      ...getOwnProperties(value),\n    }\n\n    // TODO: figure out why this fails typing (I think CustomEvent is only supported in Node 19 onwards)\n    // if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n    //   newObj.detail = (value as unknown as CustomEvent).detail\n    // }\n\n    return newObj\n  } else {\n    return value\n  }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj: unknown): { [key: string]: unknown } {\n  if (typeof obj === 'object' && obj !== null) {\n    const extractedProps: { [key: string]: unknown } = {}\n    for (const property in obj) {\n      if (Object.prototype.hasOwnProperty.call(obj, property)) {\n        extractedProps[property] = (obj as Record<string, unknown>)[property]\n      }\n    }\n    return extractedProps\n  } else {\n    return {}\n  }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target: unknown): string {\n  try {\n    return Object.prototype.toString.call(target)\n  } catch (_oO) {\n    return '<unknown>'\n  }\n}\n\n/**\n * Extracts stack frames from the error and builds an Exception\n */\nasync function exceptionFromError(\n  stackParser: StackParser,\n  frameModifiers: StackFrameModifierFn[],\n  error: Error\n): Promise<Exception> {\n  const exception: Exception = {\n    type: error.name || error.constructor.name,\n    value: error.message,\n  }\n\n  let frames = parseStackFrames(stackParser, error)\n\n  for (const modifier of frameModifiers) {\n    frames = await modifier(frames)\n  }\n\n  if (frames.length) {\n    exception.stacktrace = { frames, type: 'raw' }\n  }\n\n  return exception\n}\n\n/**\n * Extracts stack frames from the error.stack string\n */\nfunction parseStackFrames(stackParser: StackParser, error: Error): StackFrame[] {\n  return applyChunkIds(stackParser(error.stack || '', 1), stackParser)\n}\n\nexport function applyChunkIds(frames: StackFrame[], parser: StackParser): StackFrame[] {\n  const filenameChunkIdMap = getFilenameToChunkIdMap(parser)\n  frames.forEach((frame) => {\n    if (frame.filename) {\n      frame.chunk_id = filenameChunkIdMap[frame.filename]\n    }\n  })\n\n  return frames\n}\n","import { EventHint, StackFrameModifierFn, StackParser } from './types'\nimport { addUncaughtExceptionListener, addUnhandledRejectionListener } from './autocapture'\nimport { PostHogBackendClient } from '../../client'\nimport { uuidv7 } from 'posthog-core/src/vendor/uuidv7'\nimport { propertiesFromUnknownInput } from './error-conversion'\nimport { EventMessage, PostHogOptions } from '../../types'\n\nconst SHUTDOWN_TIMEOUT = 2000\n\nexport default class ErrorTracking {\n  private client: PostHogBackendClient\n  private _exceptionAutocaptureEnabled: boolean\n\n  static stackParser: StackParser\n  static frameModifiers: StackFrameModifierFn[]\n\n  static async captureException(\n    client: PostHogBackendClient,\n    error: unknown,\n    hint: EventHint,\n    distinctId?: string,\n    additionalProperties?: Record<string | number, any>\n  ): Promise<void> {\n    const properties: EventMessage['properties'] = { ...additionalProperties }\n\n    // Given stateless nature of Node SDK we capture exceptions using personless processing when no\n    // user can be determined because a distinct_id is not provided e.g. exception autocapture\n    if (!distinctId) {\n      properties.$process_person_profile = false\n    }\n\n    const exceptionProperties = await propertiesFromUnknownInput(this.stackParser, this.frameModifiers, error, hint)\n\n    client.capture({\n      event: '$exception',\n      distinctId: distinctId || uuidv7(),\n      properties: {\n        ...exceptionProperties,\n        ...properties,\n      },\n    })\n  }\n\n  constructor(client: PostHogBackendClient, options: PostHogOptions) {\n    this.client = client\n    this._exceptionAutocaptureEnabled = options.enableExceptionAutocapture || false\n\n    this.startAutocaptureIfEnabled()\n  }\n\n  private startAutocaptureIfEnabled(): void {\n    if (this.isEnabled()) {\n      addUncaughtExceptionListener(this.onException.bind(this), this.onFatalError.bind(this))\n      addUnhandledRejectionListener(this.onException.bind(this))\n    }\n  }\n\n  private onException(exception: unknown, hint: EventHint): void {\n    ErrorTracking.captureException(this.client, exception, hint)\n  }\n\n  private async onFatalError(): Promise<void> {\n    await this.client.shutdown(SHUTDOWN_TIMEOUT)\n  }\n\n  isEnabled(): boolean {\n    return !this.client.isDisabled && this._exceptionAutocaptureEnabled\n  }\n}\n","import type * as http from 'node:http'\nimport { uuidv7 } from 'posthog-core/src/vendor/uuidv7'\nimport ErrorTracking from './error-tracking'\nimport { PostHogBackendClient } from '../client'\n\ntype ExpressMiddleware = (req: http.IncomingMessage, res: http.ServerResponse, next: () => void) => void\n\ntype ExpressErrorMiddleware = (\n  error: MiddlewareError,\n  req: http.IncomingMessage,\n  res: http.ServerResponse,\n  next: (error: MiddlewareError) => void\n) => void\n\ninterface MiddlewareError extends Error {\n  status?: number | string\n  statusCode?: number | string\n  status_code?: number | string\n  output?: {\n    statusCode?: number | string\n  }\n}\n\nexport function setupExpressErrorHandler(\n  _posthog: PostHogBackendClient,\n  app: {\n    use: (middleware: ExpressMiddleware | ExpressErrorMiddleware) => unknown\n  }\n): void {\n  app.use((error: MiddlewareError, _, __, next: (error: MiddlewareError) => void): void => {\n    const hint = { mechanism: { type: 'middleware', handled: false } }\n    // Given stateless nature of Node SDK we capture exceptions using personless processing\n    // when no user can be determined e.g. in the case of exception autocapture\n    ErrorTracking.captureException(_posthog, error, hint, uuidv7(), { $process_person_profile: false })\n    next(error)\n  })\n}\n","export type PostHogCoreOptions = {\n  /** PostHog API host, usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com' */\n  host?: string\n  /** The number of events to queue before sending to PostHog (flushing) */\n  flushAt?: number\n  /** The interval in milliseconds between periodic flushes */\n  flushInterval?: number\n  /** The maximum number of queued messages to be flushed as part of a single batch (must be higher than `flushAt`) */\n  maxBatchSize?: number\n  /** The maximum number of cached messages either in memory or on the local storage.\n   * Defaults to 1000, (must be higher than `flushAt`)\n   */\n  maxQueueSize?: number\n  /** If set to true the SDK is essentially disabled (useful for local environments where you don't want to track anything) */\n  disabled?: boolean\n  /** If set to false the SDK will not track until the `optIn` function is called. */\n  defaultOptIn?: boolean\n  /** Whether to track that `getFeatureFlag` was called (used by Experiments) */\n  sendFeatureFlagEvent?: boolean\n  /** Whether to load feature flags when initialized or not */\n  preloadFeatureFlags?: boolean\n  /**\n   * Whether to load remote config when initialized or not\n   * Experimental support\n   * Default: false - Remote config is loaded by default\n   */\n  disableRemoteConfig?: boolean\n  /**\n   * Whether to load surveys when initialized or not\n   * Experimental support\n   * Default: false - Surveys are loaded by default, but requires the `PostHogSurveyProvider` to be used\n   */\n  disableSurveys?: boolean\n  /** Option to bootstrap the library with given distinctId and feature flags */\n  bootstrap?: {\n    distinctId?: string\n    isIdentifiedId?: boolean\n    featureFlags?: Record<string, FeatureFlagValue>\n    featureFlagPayloads?: Record<string, JsonType>\n  }\n  /** How many times we will retry HTTP requests. Defaults to 3. */\n  fetchRetryCount?: number\n  /** The delay between HTTP request retries, Defaults to 3 seconds. */\n  fetchRetryDelay?: number\n  /** Timeout in milliseconds for any calls. Defaults to 10 seconds. */\n  requestTimeout?: number\n  /** Timeout in milliseconds for feature flag calls. Defaults to 10 seconds for stateful clients, and 3 seconds for stateless. */\n  featureFlagsRequestTimeoutMs?: number\n  /** Timeout in milliseconds for remote config calls. Defaults to 3 seconds. */\n  remoteConfigRequestTimeoutMs?: number\n  /** For Session Analysis how long before we expire a session (defaults to 30 mins) */\n  sessionExpirationTimeSeconds?: number\n  /** Whether to disable GZIP compression */\n  disableCompression?: boolean\n  disableGeoip?: boolean\n  /** Special flag to indicate ingested data is for a historical migration. */\n  historicalMigration?: boolean\n}\n\nexport enum PostHogPersistedProperty {\n  AnonymousId = 'anonymous_id',\n  DistinctId = 'distinct_id',\n  Props = 'props',\n  FeatureFlagDetails = 'feature_flag_details',\n  FeatureFlags = 'feature_flags',\n  FeatureFlagPayloads = 'feature_flag_payloads',\n  BootstrapFeatureFlagDetails = 'bootstrap_feature_flag_details',\n  BootstrapFeatureFlags = 'bootstrap_feature_flags',\n  BootstrapFeatureFlagPayloads = 'bootstrap_feature_flag_payloads',\n  OverrideFeatureFlags = 'override_feature_flags',\n  Queue = 'queue',\n  OptedOut = 'opted_out',\n  SessionId = 'session_id',\n  SessionStartTimestamp = 'session_start_timestamp',\n  SessionLastTimestamp = 'session_timestamp',\n  PersonProperties = 'person_properties',\n  GroupProperties = 'group_properties',\n  InstalledAppBuild = 'installed_app_build', // only used by posthog-react-native\n  InstalledAppVersion = 'installed_app_version', // only used by posthog-react-native\n  SessionReplay = 'session_replay', // only used by posthog-react-native\n  SurveyLastSeenDate = 'survey_last_seen_date', // only used by posthog-react-native\n  SurveysSeen = 'surveys_seen', // only used by posthog-react-native\n  Surveys = 'surveys', // only used by posthog-react-native\n  RemoteConfig = 'remote_config',\n  FlagsEndpointWasHit = 'flags_endpoint_was_hit', // only used by posthog-react-native\n}\n\nexport type PostHogFetchOptions = {\n  method: 'GET' | 'POST' | 'PUT' | 'PATCH'\n  mode?: 'no-cors'\n  credentials?: 'omit'\n  headers: { [key: string]: string }\n  body?: string | Blob\n  signal?: AbortSignal\n}\n\n// Check out posthog-js for these additional options and try to keep them in sync\nexport type PostHogCaptureOptions = {\n  /** If provided overrides the auto-generated event ID */\n  uuid?: string\n  /** If provided overrides the auto-generated timestamp */\n  timestamp?: Date\n  disableGeoip?: boolean\n}\n\nexport type PostHogFetchResponse = {\n  status: number\n  text: () => Promise<string>\n  json: () => Promise<any>\n}\n\nexport type PostHogQueueItem = {\n  message: any\n  callback?: (err: any) => void\n}\n\nexport type PostHogEventProperties = {\n  [key: string]: JsonType\n}\n\nexport type PostHogGroupProperties = {\n  [type: string]: string | number\n}\n\nexport type PostHogAutocaptureElement = {\n  $el_text?: string\n  tag_name: string\n  href?: string\n  nth_child?: number\n  nth_of_type?: number\n  order?: number\n} & PostHogEventProperties\n// Any key prefixed with `attr__` can be added\n\nexport enum Compression {\n  GZipJS = 'gzip-js',\n  Base64 = 'base64',\n}\n\nexport type PostHogRemoteConfig = {\n  sessionRecording?:\n    | boolean\n    | {\n        [key: string]: JsonType\n      }\n\n  /**\n   * Supported compression algorithms\n   */\n  supportedCompression?: Compression[]\n\n  /**\n   * Whether surveys are enabled\n   */\n  surveys?: boolean | Survey[]\n\n  /**\n   * Indicates if the team has any flags enabled (if not we don't need to load them)\n   */\n  hasFeatureFlags?: boolean\n}\n\nexport type FeatureFlagValue = string | boolean\n\nexport type PostHogFlagsResponse = Omit<PostHogRemoteConfig, 'surveys' | 'hasFeatureFlags'> & {\n  featureFlags: {\n    [key: string]: FeatureFlagValue\n  }\n  featureFlagPayloads: {\n    [key: string]: JsonType\n  }\n  flags: {\n    [key: string]: FeatureFlagDetail\n  }\n  errorsWhileComputingFlags: boolean\n  sessionRecording?:\n    | boolean\n    | {\n        [key: string]: JsonType\n      }\n  quotaLimited?: string[]\n  requestId?: string\n}\n\nexport type PostHogFeatureFlagsResponse = PartialWithRequired<\n  PostHogFlagsResponse,\n  'flags' | 'featureFlags' | 'featureFlagPayloads' | 'requestId'\n>\n\n/**\n * Creates a type with all properties of T, but makes only K properties required while the rest remain optional.\n *\n * @template T - The base type containing all properties\n * @template K - Union type of keys from T that should be required\n *\n * @example\n * interface User {\n *   id: number;\n *   name: string;\n *   email?: string;\n *   age?: number;\n * }\n *\n * // Makes 'id' and 'name' required, but 'email' and 'age' optional\n * type RequiredUser = PartialWithRequired<User, 'id' | 'name'>;\n *\n * const user: RequiredUser = {\n *   id: 1,      // Must be provided\n *   name: \"John\" // Must be provided\n *   // email and age are optional\n * };\n */\nexport type PartialWithRequired<T, K extends keyof T> = {\n  [P in K]: T[P] // Required fields\n} & {\n  [P in Exclude<keyof T, K>]?: T[P] // Optional fields\n}\n\n/**\n * These are the fields we care about from PostHogFlagsResponse for feature flags.\n */\nexport type PostHogFeatureFlagDetails = PartialWithRequired<\n  PostHogFlagsResponse,\n  'flags' | 'featureFlags' | 'featureFlagPayloads' | 'requestId'\n>\n\n/**\n * Models the response from the v1 `/flags` endpoint.\n */\nexport type PostHogV1FlagsResponse = Omit<PostHogFlagsResponse, 'flags'>\n\n/**\n * Models the response from the v2 `/flags` endpoint.\n */\nexport type PostHogV2FlagsResponse = Omit<PostHogFlagsResponse, 'featureFlags' | 'featureFlagPayloads'>\n\n/**\n * The format of the flags object in persisted storage\n *\n * When we pull flags from persistence, we can normalize them to PostHogFeatureFlagDetails\n * so that we can support v1 and v2 of the API.\n */\nexport type PostHogFlagsStorageFormat = Pick<PostHogFeatureFlagDetails, 'flags'>\n\n/**\n * Models legacy flags and payloads return type for many public methods.\n */\nexport type PostHogFlagsAndPayloadsResponse = Partial<\n  Pick<PostHogFlagsResponse, 'featureFlags' | 'featureFlagPayloads'>\n>\n\nexport type JsonType = string | number | boolean | null | { [key: string]: JsonType } | Array<JsonType> | JsonType[]\n\nexport type FetchLike = (url: string, options: PostHogFetchOptions) => Promise<PostHogFetchResponse>\n\nexport type FeatureFlagDetail = {\n  key: string\n  enabled: boolean\n  variant: string | undefined\n  reason: EvaluationReason | undefined\n  metadata: FeatureFlagMetadata | undefined\n}\n\nexport type FeatureFlagMetadata = {\n  id: number | undefined\n  version: number | undefined\n  description: string | undefined\n  // Payloads in the response are always JSON encoded as a string\n  payload: string | undefined\n}\n\nexport type EvaluationReason = {\n  code: string | undefined\n  condition_index: number | undefined\n  description: string | undefined\n}\n\n// survey types\nexport type SurveyAppearance = {\n  // keep in sync with frontend/src/types.ts -> SurveyAppearance\n  backgroundColor?: string\n  submitButtonColor?: string\n  // deprecate submit button text eventually\n  submitButtonText?: string\n  submitButtonTextColor?: string\n  ratingButtonColor?: string\n  ratingButtonActiveColor?: string\n  autoDisappear?: boolean\n  displayThankYouMessage?: boolean\n  thankYouMessageHeader?: string\n  thankYouMessageDescription?: string\n  thankYouMessageDescriptionContentType?: SurveyQuestionDescriptionContentType\n  thankYouMessageCloseButtonText?: string\n  borderColor?: string\n  position?: SurveyPosition\n  placeholder?: string\n  shuffleQuestions?: boolean\n  surveyPopupDelaySeconds?: number\n  // widget options\n  widgetType?: SurveyWidgetType\n  widgetSelector?: string\n  widgetLabel?: string\n  widgetColor?: string\n}\n\nexport enum SurveyPosition {\n  Left = 'left',\n  Right = 'right',\n  Center = 'center',\n}\n\nexport enum SurveyWidgetType {\n  Button = 'button',\n  Tab = 'tab',\n  Selector = 'selector',\n}\n\nexport enum SurveyType {\n  Popover = 'popover',\n  API = 'api',\n  Widget = 'widget',\n}\n\nexport type SurveyQuestion = BasicSurveyQuestion | LinkSurveyQuestion | RatingSurveyQuestion | MultipleSurveyQuestion\n\nexport enum SurveyQuestionDescriptionContentType {\n  Html = 'html',\n  Text = 'text',\n}\n\ntype SurveyQuestionBase = {\n  question: string\n  id?: string // TODO: use this for the question id\n  description?: string\n  descriptionContentType?: SurveyQuestionDescriptionContentType\n  optional?: boolean\n  buttonText?: string\n  originalQuestionIndex: number\n  branching?: NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranching\n}\n\nexport type BasicSurveyQuestion = SurveyQuestionBase & {\n  type: SurveyQuestionType.Open\n}\n\nexport type LinkSurveyQuestion = SurveyQuestionBase & {\n  type: SurveyQuestionType.Link\n  link?: string\n}\n\nexport type RatingSurveyQuestion = SurveyQuestionBase & {\n  type: SurveyQuestionType.Rating\n  display: SurveyRatingDisplay\n  scale: 3 | 5 | 7 | 10\n  lowerBoundLabel: string\n  upperBoundLabel: string\n}\n\nexport enum SurveyRatingDisplay {\n  Number = 'number',\n  Emoji = 'emoji',\n}\n\nexport type MultipleSurveyQuestion = SurveyQuestionBase & {\n  type: SurveyQuestionType.SingleChoice | SurveyQuestionType.MultipleChoice\n  choices: string[]\n  hasOpenChoice?: boolean\n  shuffleOptions?: boolean\n}\n\nexport enum SurveyQuestionType {\n  Open = 'open',\n  MultipleChoice = 'multiple_choice',\n  SingleChoice = 'single_choice',\n  Rating = 'rating',\n  Link = 'link',\n}\n\nexport enum SurveyQuestionBranchingType {\n  NextQuestion = 'next_question',\n  End = 'end',\n  ResponseBased = 'response_based',\n  SpecificQuestion = 'specific_question',\n}\n\nexport type NextQuestionBranching = {\n  type: SurveyQuestionBranchingType.NextQuestion\n}\n\nexport type EndBranching = {\n  type: SurveyQuestionBranchingType.End\n}\n\nexport type ResponseBasedBranching = {\n  type: SurveyQuestionBranchingType.ResponseBased\n  responseValues: Record<string, any>\n}\n\nexport type SpecificQuestionBranching = {\n  type: SurveyQuestionBranchingType.SpecificQuestion\n  index: number\n}\n\nexport type SurveyResponse = {\n  surveys: Survey[]\n}\n\nexport type SurveyCallback = (surveys: Survey[]) => void\n\nexport enum SurveyMatchType {\n  Regex = 'regex',\n  NotRegex = 'not_regex',\n  Exact = 'exact',\n  IsNot = 'is_not',\n  Icontains = 'icontains',\n  NotIcontains = 'not_icontains',\n}\n\nexport type SurveyElement = {\n  text?: string\n  $el_text?: string\n  tag_name?: string\n  href?: string\n  attr_id?: string\n  attr_class?: string[]\n  nth_child?: number\n  nth_of_type?: number\n  attributes?: Record<string, any>\n  event_id?: number\n  order?: number\n  group_id?: number\n}\nexport type SurveyRenderReason = {\n  visible: boolean\n  disabledReason?: string\n}\n\nexport type Survey = {\n  // Sync this with the backend's SurveyAPISerializer!\n  id: string\n  name: string\n  description?: string\n  type: SurveyType\n  feature_flag_keys?:\n    | {\n        key: string\n        value?: string\n      }[]\n  linked_flag_key?: string\n  targeting_flag_key?: string\n  internal_targeting_flag_key?: string\n  questions: SurveyQuestion[]\n  appearance?: SurveyAppearance\n  conditions?: {\n    url?: string\n    selector?: string\n    seenSurveyWaitPeriodInDays?: number\n    urlMatchType?: SurveyMatchType\n    events?: {\n      repeatedActivation?: boolean\n      values?: {\n        name: string\n      }[]\n    }\n    actions?: {\n      values: SurveyActionType[]\n    }\n    deviceTypes?: string[]\n    deviceTypesMatchType?: SurveyMatchType\n  }\n  start_date?: string\n  end_date?: string\n  current_iteration?: number\n  current_iteration_start_date?: string\n}\n\nexport type SurveyActionType = {\n  id: number\n  name?: string\n  steps?: ActionStepType[]\n}\n\n/** Sync with plugin-server/src/types.ts */\nexport enum ActionStepStringMatching {\n  Contains = 'contains',\n  Exact = 'exact',\n  Regex = 'regex',\n}\n\nexport type ActionStepType = {\n  event?: string\n  selector?: string\n  text?: string\n  /** @default StringMatching.Exact */\n  text_matching?: ActionStepStringMatching\n  href?: string\n  /** @default ActionStepStringMatching.Exact */\n  href_matching?: ActionStepStringMatching\n  url?: string\n  /** @default StringMatching.Contains */\n  url_matching?: ActionStepStringMatching\n}\n","import {\n  FeatureFlagDetail,\n  FeatureFlagValue,\n  JsonType,\n  PostHogFlagsResponse,\n  PostHogV1FlagsResponse,\n  PostHogV2FlagsResponse,\n  PostHogFlagsAndPayloadsResponse,\n  PartialWithRequired,\n  PostHogFeatureFlagsResponse,\n} from './types'\n\nexport const normalizeFlagsResponse = (\n  flagsResponse:\n    | PartialWithRequired<PostHogV2FlagsResponse, 'flags'>\n    | PartialWithRequired<PostHogV1FlagsResponse, 'featureFlags' | 'featureFlagPayloads'>\n): PostHogFeatureFlagsResponse => {\n  if ('flags' in flagsResponse) {\n    // Convert v2 format to v1 format\n    const featureFlags = getFlagValuesFromFlags(flagsResponse.flags)\n    const featureFlagPayloads = getPayloadsFromFlags(flagsResponse.flags)\n\n    return {\n      ...flagsResponse,\n      featureFlags,\n      featureFlagPayloads,\n    }\n  } else {\n    // Convert v1 format to v2 format\n    const featureFlags = flagsResponse.featureFlags ?? {}\n    const featureFlagPayloads = Object.fromEntries(\n      Object.entries(flagsResponse.featureFlagPayloads || {}).map(([k, v]) => [k, parsePayload(v)])\n    )\n\n    const flags = Object.fromEntries(\n      Object.entries(featureFlags).map(([key, value]) => [\n        key,\n        getFlagDetailFromFlagAndPayload(key, value, featureFlagPayloads[key]),\n      ])\n    )\n\n    return {\n      ...flagsResponse,\n      featureFlags,\n      featureFlagPayloads,\n      flags,\n    }\n  }\n}\n\nfunction getFlagDetailFromFlagAndPayload(\n  key: string,\n  value: FeatureFlagValue,\n  payload: JsonType | undefined\n): FeatureFlagDetail {\n  return {\n    key: key,\n    enabled: typeof value === 'string' ? true : value,\n    variant: typeof value === 'string' ? value : undefined,\n    reason: undefined,\n    metadata: {\n      id: undefined,\n      version: undefined,\n      payload: payload ? JSON.stringify(payload) : undefined,\n      description: undefined,\n    },\n  }\n}\n\n/**\n * Get the flag values from the flags v4 response.\n * @param flags - The flags\n * @returns The flag values\n */\nexport const getFlagValuesFromFlags = (flags: PostHogFlagsResponse['flags']): PostHogFlagsResponse['featureFlags'] => {\n  return Object.fromEntries(\n    Object.entries(flags ?? {})\n      .map(([key, detail]) => [key, getFeatureFlagValue(detail)])\n      .filter(([, value]): boolean => value !== undefined)\n  )\n}\n\n/**\n * Get the payloads from the flags v4 response.\n * @param flags - The flags\n * @returns The payloads\n */\nexport const getPayloadsFromFlags = (\n  flags: PostHogFlagsResponse['flags']\n): PostHogFlagsResponse['featureFlagPayloads'] => {\n  const safeFlags = flags ?? {}\n  return Object.fromEntries(\n    Object.keys(safeFlags)\n      .filter((flag) => {\n        const details = safeFlags[flag]\n        return details.enabled && details.metadata && details.metadata.payload !== undefined\n      })\n      .map((flag) => {\n        const payload = safeFlags[flag].metadata?.payload as string\n        return [flag, payload ? parsePayload(payload) : undefined]\n      })\n  )\n}\n\n/**\n * Get the flag details from the legacy v1 flags and payloads. As such, it will lack the reason, id, version, and description.\n * @param flagsResponse - The flags response\n * @returns The flag details\n */\nexport const getFlagDetailsFromFlagsAndPayloads = (\n  flagsResponse: PostHogFeatureFlagsResponse\n): PostHogFlagsResponse['flags'] => {\n  const flags = flagsResponse.featureFlags ?? {}\n  const payloads = flagsResponse.featureFlagPayloads ?? {}\n  return Object.fromEntries(\n    Object.entries(flags).map(([key, value]) => [\n      key,\n      {\n        key: key,\n        enabled: typeof value === 'string' ? true : value,\n        variant: typeof value === 'string' ? value : undefined,\n        reason: undefined,\n        metadata: {\n          id: undefined,\n          version: undefined,\n          payload: payloads?.[key] ? JSON.stringify(payloads[key]) : undefined,\n          description: undefined,\n        },\n      },\n    ])\n  )\n}\n\nexport const getFeatureFlagValue = (detail: FeatureFlagDetail | undefined): FeatureFlagValue | undefined => {\n  return detail === undefined ? undefined : detail.variant ?? detail.enabled\n}\n\nexport const parsePayload = (response: any): any => {\n  if (typeof response !== 'string') {\n    return response\n  }\n\n  try {\n    return JSON.parse(response)\n  } catch {\n    return response\n  }\n}\n\n/**\n * Get the normalized flag details from the flags and payloads.\n * This is used to convert things like boostrap and stored feature flags and payloads to the v4 format.\n * This helps us ensure backwards compatibility.\n * If a key exists in the featureFlagPayloads that is not in the featureFlags, we treat it as a true feature flag.\n *\n * @param featureFlags - The feature flags\n * @param featureFlagPayloads - The feature flag payloads\n * @returns The normalized flag details\n */\nexport const createFlagsResponseFromFlagsAndPayloads = (\n  featureFlags: PostHogV1FlagsResponse['featureFlags'],\n  featureFlagPayloads: PostHogV1FlagsResponse['featureFlagPayloads']\n): PostHogFeatureFlagsResponse => {\n  // If a feature flag payload key is not in the feature flags, we treat it as true feature flag.\n  const allKeys = [...new Set([...Object.keys(featureFlags ?? {}), ...Object.keys(featureFlagPayloads ?? {})])]\n  const enabledFlags = allKeys\n    .filter((flag) => !!featureFlags[flag] || !!featureFlagPayloads[flag])\n    .reduce((res: Record<string, FeatureFlagValue>, key) => ((res[key] = featureFlags[key] ?? true), res), {})\n\n  const flagDetails: PostHogFlagsAndPayloadsResponse = {\n    featureFlags: enabledFlags,\n    featureFlagPayloads: featureFlagPayloads ?? {},\n  }\n\n  return normalizeFlagsResponse(flagDetails as PostHogV1FlagsResponse)\n}\n\nexport const updateFlagValue = (flag: FeatureFlagDetail, value: FeatureFlagValue): FeatureFlagDetail => {\n  return {\n    ...flag,\n    enabled: getEnabledFromValue(value),\n    variant: getVariantFromValue(value),\n  }\n}\n\nfunction getEnabledFromValue(value: FeatureFlagValue): boolean {\n  return typeof value === 'string' ? true : value\n}\n\nfunction getVariantFromValue(value: FeatureFlagValue): string | undefined {\n  return typeof value === 'string' ? value : undefined\n}\n","import { FetchLike } from './types'\n\nexport const STRING_FORMAT = 'utf8'\n\nexport function assert(truthyValue: any, message: string): void {\n  if (!truthyValue || typeof truthyValue !== 'string' || isEmpty(truthyValue)) {\n    throw new Error(message)\n  }\n}\n\nfunction isEmpty(truthyValue: string): boolean {\n  if (truthyValue.trim().length === 0) {\n    return true\n  }\n  return false\n}\n\nexport function removeTrailingSlash(url: string): string {\n  return url?.replace(/\\/+$/, '')\n}\n\nexport interface RetriableOptions {\n  retryCount: number\n  retryDelay: number\n  retryCheck: (err: unknown) => boolean\n}\n\nexport async function retriable<T>(fn: () => Promise<T>, props: RetriableOptions): Promise<T> {\n  let lastError = null\n\n  for (let i = 0; i < props.retryCount + 1; i++) {\n    if (i > 0) {\n      // don't wait when it's the last try\n      await new Promise<void>((r) => setTimeout(r, props.retryDelay))\n    }\n\n    try {\n      const res = await fn()\n      return res\n    } catch (e) {\n      lastError = e\n      if (!props.retryCheck(e)) {\n        throw e\n      }\n    }\n  }\n\n  throw lastError\n}\n\nexport function currentTimestamp(): number {\n  return new Date().getTime()\n}\n\nexport function currentISOTime(): string {\n  return new Date().toISOString()\n}\n\nexport function safeSetTimeout(fn: () => void, timeout: number): any {\n  // NOTE: we use this so rarely that it is totally fine to do `safeSetTimeout(fn, 0)``\n  // rather than setImmediate.\n  const t = setTimeout(fn, timeout) as any\n  // We unref if available to prevent Node.js hanging on exit\n  t?.unref && t?.unref()\n  return t\n}\n\n// NOTE: We opt for this slightly imperfect check as the global \"Promise\" object can get mutated in certain environments\nexport const isPromise = (obj: any): obj is Promise<any> => {\n  return obj && typeof obj.then === 'function'\n}\n\nexport const isError = (x: unknown): x is Error => {\n  return x instanceof Error\n}\n\nexport function getFetch(): FetchLike | undefined {\n  return typeof fetch !== 'undefined' ? fetch : typeof globalThis.fetch !== 'undefined' ? globalThis.fetch : undefined\n}\n\nexport function allSettled<T>(\n  promises: (Promise<T> | null | undefined)[]\n): Promise<({ status: 'fulfilled'; value: T } | { status: 'rejected'; reason: any })[]> {\n  return Promise.all(\n    promises.map((p) =>\n      (p ?? Promise.resolve()).then(\n        (value: any) => ({ status: 'fulfilled' as const, value }),\n        (reason: any) => ({ status: 'rejected' as const, reason })\n      )\n    )\n  )\n}\n","/**\n * Older browsers and some runtimes don't support this yet\n * This API (as of 2025-05-07) is not available on React Native.\n */\nexport function isGzipSupported(): boolean {\n  return 'CompressionStream' in globalThis\n}\n\n/**\n * Gzip a string using Compression Streams API if it's available\n */\nexport async function gzipCompress(input: string, isDebug = true): Promise<Blob | null> {\n  try {\n    // Turn the string into a stream using a Blob, and then compress it\n    const dataStream = new Blob([input], {\n      type: 'text/plain',\n    }).stream()\n\n    const compressedStream = dataStream.pipeThrough(new CompressionStream('gzip'))\n\n    // Using a Response to easily extract the readablestream value. Decoding into a string for fetch\n    return await new Response(compressedStream).blob()\n  } catch (error) {\n    if (isDebug) {\n      console.error('Failed to gzip compress data', error)\n    }\n    return null\n  }\n}\n","export class SimpleEventEmitter {\n  events: { [key: string]: ((...args: any[]) => void)[] } = {}\n\n  constructor() {\n    this.events = {}\n  }\n\n  on(event: string, listener: (...args: any[]) => void): () => void {\n    if (!this.events[event]) {\n      this.events[event] = []\n    }\n    this.events[event].push(listener)\n\n    return () => {\n      this.events[event] = this.events[event].filter((x) => x !== listener)\n    }\n  }\n\n  emit(event: string, payload: any): void {\n    for (const listener of this.events[event] || []) {\n      listener(payload)\n    }\n    for (const listener of this.events['*'] || []) {\n      listener(event, payload)\n    }\n  }\n}\n","import {\n  PostHogFetchOptions,\n  PostHogFetchResponse,\n  PostHogQueueItem,\n  PostHogAutocaptureElement,\n  PostHogFlagsResponse,\n  PostHogCoreOptions,\n  PostHogEventProperties,\n  PostHogPersistedProperty,\n  PostHogCaptureOptions,\n  JsonType,\n  PostHogRemoteConfig,\n  FeatureFlagValue,\n  PostHogV2FlagsResponse,\n  PostHogV1FlagsResponse,\n  PostHogFeatureFlagDetails,\n  PostHogFlagsStorageFormat,\n  FeatureFlagDetail,\n  Survey,\n  SurveyResponse,\n  PostHogGroupProperties,\n  Compression,\n} from './types'\nimport {\n  createFlagsResponseFromFlagsAndPayloads,\n  getFeatureFlagValue,\n  getFlagValuesFromFlags,\n  getPayloadsFromFlags,\n  normalizeFlagsResponse,\n  updateFlagValue,\n} from './featureFlagUtils'\nimport {\n  allSettled,\n  assert,\n  currentISOTime,\n  isError,\n  removeTrailingSlash,\n  retriable,\n  RetriableOptions,\n  safeSetTimeout,\n  STRING_FORMAT,\n} from './utils'\nimport { isGzipSupported, gzipCompress } from './gzip'\nimport { SimpleEventEmitter } from './eventemitter'\nimport { uuidv7 } from './vendor/uuidv7'\n\nexport { safeSetTimeout } from './utils'\nexport { getFetch } from './utils'\nexport { getFeatureFlagValue } from './featureFlagUtils'\nexport * as utils from './utils'\n\nclass PostHogFetchHttpError extends Error {\n  name = 'PostHogFetchHttpError'\n\n  constructor(public response: PostHogFetchResponse, public reqByteLength: number) {\n    super('HTTP error while fetching PostHog: status=' + response.status + ', reqByteLength=' + reqByteLength)\n  }\n\n  get status(): number {\n    return this.response.status\n  }\n\n  get text(): Promise<string> {\n    return this.response.text()\n  }\n\n  get json(): Promise<any> {\n    return this.response.json()\n  }\n}\n\nclass PostHogFetchNetworkError extends Error {\n  name = 'PostHogFetchNetworkError'\n\n  constructor(public error: unknown) {\n    // TRICKY: \"cause\" is a newer property but is just ignored otherwise. Cast to any to ignore the type issue.\n    // eslint-disable-next-line @typescript-eslint/prefer-ts-expect-error\n    // @ts-ignore\n    super('Network error while fetching PostHog', error instanceof Error ? { cause: error } : {})\n  }\n}\n\nexport const maybeAdd = (key: string, value: JsonType | undefined): Record<string, JsonType> =>\n  value !== undefined ? { [key]: value } : {}\n\nexport async function logFlushError(err: any): Promise<void> {\n  if (err instanceof PostHogFetchHttpError) {\n    let text = ''\n    try {\n      text = await err.text\n    } catch {}\n\n    console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err)\n  } else {\n    console.error('Error while flushing PostHog', err)\n  }\n  return Promise.resolve()\n}\n\nfunction isPostHogFetchError(err: unknown): err is PostHogFetchHttpError | PostHogFetchNetworkError {\n  return typeof err === 'object' && (err instanceof PostHogFetchHttpError || err instanceof PostHogFetchNetworkError)\n}\n\nfunction isPostHogFetchContentTooLargeError(err: unknown): err is PostHogFetchHttpError & { status: 413 } {\n  return typeof err === 'object' && err instanceof PostHogFetchHttpError && err.status === 413\n}\n\nenum QuotaLimitedFeature {\n  FeatureFlags = 'feature_flags',\n  Recordings = 'recordings',\n}\n\nexport abstract class PostHogCoreStateless {\n  // options\n  readonly apiKey: string\n  readonly host: string\n  readonly flushAt: number\n  readonly preloadFeatureFlags: boolean\n  readonly disableSurveys: boolean\n  private maxBatchSize: number\n  private maxQueueSize: number\n  private flushInterval: number\n  private flushPromise: Promise<any> | null = null\n  private shutdownPromise: Promise<void> | null = null\n  private requestTimeout: number\n  private featureFlagsRequestTimeoutMs: number\n  private remoteConfigRequestTimeoutMs: number\n  private removeDebugCallback?: () => void\n  private disableGeoip: boolean\n  private historicalMigration: boolean\n  protected disabled\n  protected disableCompression: boolean\n\n  private defaultOptIn: boolean\n  private pendingPromises: Record<string, Promise<any>> = {}\n\n  // internal\n  protected _events = new SimpleEventEmitter()\n  protected _flushTimer?: any\n  protected _retryOptions: RetriableOptions\n  protected _initPromise: Promise<void>\n  protected _isInitialized: boolean = false\n  protected _remoteConfigResponsePromise?: Promise<PostHogRemoteConfig | undefined>\n\n  // Abstract methods to be overridden by implementations\n  abstract fetch(url: string, options: PostHogFetchOptions): Promise<PostHogFetchResponse>\n  abstract getLibraryId(): string\n  abstract getLibraryVersion(): string\n  abstract getCustomUserAgent(): string | void\n\n  // This is our abstracted storage. Each implementation should handle its own\n  abstract getPersistedProperty<T>(key: PostHogPersistedProperty): T | undefined\n  abstract setPersistedProperty<T>(key: PostHogPersistedProperty, value: T | null): void\n\n  constructor(apiKey: string, options?: PostHogCoreOptions) {\n    assert(apiKey, \"You must pass your PostHog project's api key.\")\n\n    this.apiKey = apiKey\n    this.host = removeTrailingSlash(options?.host || 'https://us.i.posthog.com')\n    this.flushAt = options?.flushAt ? Math.max(options?.flushAt, 1) : 20\n    this.maxBatchSize = Math.max(this.flushAt, options?.maxBatchSize ?? 100)\n    this.maxQueueSize = Math.max(this.flushAt, options?.maxQueueSize ?? 1000)\n    this.flushInterval = options?.flushInterval ?? 10000\n    this.preloadFeatureFlags = options?.preloadFeatureFlags ?? true\n    // If enable is explicitly set to false we override the optout\n    this.defaultOptIn = options?.defaultOptIn ?? true\n    this.disableSurveys = options?.disableSurveys ?? false\n\n    this._retryOptions = {\n      retryCount: options?.fetchRetryCount ?? 3,\n      retryDelay: options?.fetchRetryDelay ?? 3000, // 3 seconds\n      retryCheck: isPostHogFetchError,\n    }\n    this.requestTimeout = options?.requestTimeout ?? 10000 // 10 seconds\n    this.featureFlagsRequestTimeoutMs = options?.featureFlagsRequestTimeoutMs ?? 3000 // 3 seconds\n    this.remoteConfigRequestTimeoutMs = options?.remoteConfigRequestTimeoutMs ?? 3000 // 3 seconds\n    this.disableGeoip = options?.disableGeoip ?? true\n    this.disabled = options?.disabled ?? false\n    this.historicalMigration = options?.historicalMigration ?? false\n    // Init promise allows the derived class to block calls until it is ready\n    this._initPromise = Promise.resolve()\n    this._isInitialized = true\n    this.disableCompression = !isGzipSupported() || (options?.disableCompression ?? false)\n  }\n\n  protected logMsgIfDebug(fn: () => void): void {\n    if (this.isDebug) {\n      fn()\n    }\n  }\n\n  protected wrap(fn: () => void): void {\n    if (this.disabled) {\n      this.logMsgIfDebug(() => console.warn('[PostHog] The client is disabled'))\n      return\n    }\n\n    if (this._isInitialized) {\n      // NOTE: We could also check for the \"opt in\" status here...\n      return fn()\n    }\n\n    this._initPromise.then(() => fn())\n  }\n\n  protected getCommonEventProperties(): PostHogEventProperties {\n    return {\n      $lib: this.getLibraryId(),\n      $lib_version: this.getLibraryVersion(),\n    }\n  }\n\n  public get optedOut(): boolean {\n    return this.getPersistedProperty(PostHogPersistedProperty.OptedOut) ?? !this.defaultOptIn\n  }\n\n  async optIn(): Promise<void> {\n    this.wrap(() => {\n      this.setPersistedProperty(PostHogPersistedProperty.OptedOut, false)\n    })\n  }\n\n  async optOut(): Promise<void> {\n    this.wrap(() => {\n      this.setPersistedProperty(PostHogPersistedProperty.OptedOut, true)\n    })\n  }\n\n  on(event: string, cb: (...args: any[]) => void): () => void {\n    return this._events.on(event, cb)\n  }\n\n  debug(enabled: boolean = true): void {\n    this.removeDebugCallback?.()\n\n    if (enabled) {\n      const removeDebugCallback = this.on('*', (event, payload) => console.log('PostHog Debug', event, payload))\n      this.removeDebugCallback = () => {\n        removeDebugCallback()\n        this.removeDebugCallback = undefined\n      }\n    }\n  }\n\n  get isDebug(): boolean {\n    return !!this.removeDebugCallback\n  }\n\n  get isDisabled(): boolean {\n    return this.disabled\n  }\n\n  private buildPayload(payload: {\n    distinct_id: string\n    event: string\n    properties?: PostHogEventProperties\n  }): PostHogEventProperties {\n    return {\n      distinct_id: payload.distinct_id,\n      event: payload.event,\n      properties: {\n        ...(payload.properties || {}),\n        ...this.getCommonEventProperties(), // Common PH props\n      },\n    }\n  }\n\n  protected addPendingPromise<T>(promise: Promise<T>): Promise<T> {\n    const promiseUUID = uuidv7()\n    this.pendingPromises[promiseUUID] = promise\n    promise\n      .catch(() => {})\n      .finally(() => {\n        delete this.pendingPromises[promiseUUID]\n      })\n\n    return promise\n  }\n\n  /***\n   *** TRACKING\n   ***/\n  protected identifyStateless(\n    distinctId: string,\n    properties?: PostHogEventProperties,\n    options?: PostHogCaptureOptions\n  ): void {\n    this.wrap(() => {\n      // The properties passed to identifyStateless are event properties.\n      // To add person properties, pass in all person properties to the `$set` and `$set_once` keys.\n\n      const payload = {\n        ...this.buildPayload({\n          distinct_id: distinctId,\n          event: '$identify',\n          properties,\n        }),\n      }\n\n      this.enqueue('identify', payload, options)\n    })\n  }\n\n  protected async identifyStatelessImmediate(\n    distinctId: string,\n    properties?: PostHogEventProperties,\n    options?: PostHogCaptureOptions\n  ): Promise<void> {\n    const payload = {\n      ...this.buildPayload({\n        distinct_id: distinctId,\n        event: '$identify',\n        properties,\n      }),\n    }\n\n    await this.sendImmediate('identify', payload, options)\n  }\n\n  protected captureStateless(\n    distinctId: string,\n    event: string,\n    properties?: PostHogEventProperties,\n    options?: PostHogCaptureOptions\n  ): void {\n    this.wrap(() => {\n      const payload = this.buildPayload({ distinct_id: distinctId, event, properties })\n      this.enqueue('capture', payload, options)\n    })\n  }\n\n  protected async captureStatelessImmediate(\n    distinctId: string,\n    event: string,\n    properties?: PostHogEventProperties,\n    options?: PostHogCaptureOptions\n  ): Promise<void> {\n    const payload = this.buildPayload({ distinct_id: distinctId, event, properties })\n    await this.sendImmediate('capture', payload, options)\n  }\n\n  protected aliasStateless(\n    alias: string,\n    distinctId: string,\n    properties?: PostHogEventProperties,\n    options?: PostHogCaptureOptions\n  ): void {\n    this.wrap(() => {\n      const payload = this.buildPayload({\n        event: '$create_alias',\n        distinct_id: distinctId,\n        properties: {\n          ...(properties || {}),\n          distinct_id: distinctId,\n          alias,\n        },\n      })\n\n      this.enqueue('alias', payload, options)\n    })\n  }\n\n  protected async aliasStatelessImmediate(\n    alias: string,\n    distinctId: string,\n    properties?: PostHogEventProperties,\n    options?: PostHogCaptureOptions\n  ): Promise<void> {\n    const payload = this.buildPayload({\n      event: '$create_alias',\n      distinct_id: distinctId,\n      properties: {\n        ...(properties || {}),\n        distinct_id: distinctId,\n        alias,\n      },\n    })\n\n    await this.sendImmediate('alias', payload, options)\n  }\n\n  /***\n   *** GROUPS\n   ***/\n  protected groupIdentifyStateless(\n    groupType: string,\n    groupKey: string | number,\n    groupProperties?: PostHogEventProperties,\n    options?: PostHogCaptureOptions,\n    distinctId?: string,\n    eventProperties?: PostHogEventProperties\n  ): void {\n    this.wrap(() => {\n      const payload = this.buildPayload({\n        distinct_id: distinctId || `$${groupType}_${groupKey}`,\n        event: '$groupidentify',\n        properties: {\n          $group_type: groupType,\n          $group_key: groupKey,\n          $group_set: groupProperties || {},\n          ...(eventProperties || {}),\n        },\n      })\n\n      this.enqueue('capture', payload, options)\n    })\n  }\n\n  protected async getRemoteConfig(): Promise<PostHogRemoteConfig | undefined> {\n    await this._initPromise\n\n    let host = this.host\n\n    if (host === 'https://us.i.posthog.com') {\n      host = 'https://us-assets.i.posthog.com'\n    } else if (host === 'https://eu.i.posthog.com') {\n      host = 'https://eu-assets.i.posthog.com'\n    }\n\n    const url = `${host}/array/${this.apiKey}/config`\n    const fetchOptions: PostHogFetchOptions = {\n      method: 'GET',\n      headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/json' },\n    }\n    // Don't retry remote config API calls\n    return this.fetchWithRetry(url, fetchOptions, { retryCount: 0 }, this.remoteConfigRequestTimeoutMs)\n      .then((response) => response.json() as Promise<PostHogRemoteConfig>)\n      .catch((error) => {\n        this.logMsgIfDebug(() => console.error('Remote config could not be loaded', error))\n        this._events.emit('error', error)\n        return undefined\n      })\n  }\n\n  /***\n   *** FEATURE FLAGS\n   ***/\n\n  protected async getFlags(\n    distinctId: string,\n    groups: Record<string, string | number> = {},\n    personProperties: Record<string, string> = {},\n    groupProperties: Record<string, Record<string, string>> = {},\n    extraPayload: Record<string, any> = {}\n  ): Promise<PostHogFlagsResponse | undefined> {\n    await this._initPromise\n\n    const url = `${this.host}/flags/?v=2&config=true`\n    const fetchOptions: PostHogFetchOptions = {\n      method: 'POST',\n      headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/json' },\n      body: JSON.stringify({\n        token: this.apiKey,\n        distinct_id: distinctId,\n        groups,\n        person_properties: personProperties,\n        group_properties: groupProperties,\n        ...extraPayload,\n      }),\n    }\n\n    this.logMsgIfDebug(() => console.log('PostHog Debug', 'Flags URL', url))\n\n    // Don't retry /flags API calls\n    return this.fetchWithRetry(url, fetchOptions, { retryCount: 0 }, this.featureFlagsRequestTimeoutMs)\n      .then((response) => response.json() as Promise<PostHogV1FlagsResponse | PostHogV2FlagsResponse>)\n      .then((response) => normalizeFlagsResponse(response))\n      .catch((error) => {\n        this._events.emit('error', error)\n        return undefined\n      }) as Promise<PostHogFlagsResponse | undefined>\n  }\n\n  protected async getFeatureFlagStateless(\n    key: string,\n    distinctId: string,\n    groups: Record<string, string> = {},\n    personProperties: Record<string, string> = {},\n    groupProperties: Record<string, Record<string, string>> = {},\n    disableGeoip?: boolean\n  ): Promise<{\n    response: FeatureFlagValue | undefined\n    requestId: string | undefined\n  }> {\n    await this._initPromise\n\n    const flagDetailResponse = await this.getFeatureFlagDetailStateless(\n      key,\n      distinctId,\n      groups,\n      personProperties,\n      groupProperties,\n      disableGeoip\n    )\n\n    if (flagDetailResponse === undefined) {\n      // If we haven't loaded flags yet, or errored out, we respond with undefined\n      return {\n        response: undefined,\n        requestId: undefined,\n      }\n    }\n\n    let response = getFeatureFlagValue(flagDetailResponse.response)\n\n    if (response === undefined) {\n      // For cases where the flag is unknown, return false\n      response = false\n    }\n\n    // If we have flags we either return the value (true or string) or false\n    return {\n      response,\n      requestId: flagDetailResponse.requestId,\n    }\n  }\n\n  protected async getFeatureFlagDetailStateless(\n    key: string,\n    distinctId: string,\n    groups: Record<string, string> = {},\n    personProperties: Record<string, string> = {},\n    groupProperties: Record<string, Record<string, string>> = {},\n    disableGeoip?: boolean\n  ): Promise<\n    | {\n        response: FeatureFlagDetail | undefined\n        requestId: string | undefined\n      }\n    | undefined\n  > {\n    await this._initPromise\n\n    const flagsResponse = await this.getFeatureFlagDetailsStateless(\n      distinctId,\n      groups,\n      personProperties,\n      groupProperties,\n      disableGeoip,\n      [key]\n    )\n\n    if (flagsResponse === undefined) {\n      return undefined\n    }\n\n    const featureFlags = flagsResponse.flags\n\n    const flagDetail = featureFlags[key]\n\n    return {\n      response: flagDetail,\n      requestId: flagsResponse.requestId,\n    }\n  }\n\n  protected async getFeatureFlagPayloadStateless(\n    key: string,\n    distinctId: string,\n    groups: Record<string, string> = {},\n    personProperties: Record<string, string> = {},\n    groupProperties: Record<string, Record<string, string>> = {},\n    disableGeoip?: boolean\n  ): Promise<JsonType | undefined> {\n    await this._initPromise\n\n    const payloads = await this.getFeatureFlagPayloadsStateless(\n      distinctId,\n      groups,\n      personProperties,\n      groupProperties,\n      disableGeoip,\n      [key]\n    )\n\n    if (!payloads) {\n      return undefined\n    }\n\n    const response = payloads[key]\n\n    // Undefined means a loading or missing data issue. Null means evaluation happened and there was no match\n    if (response === undefined) {\n      return null\n    }\n\n    return response\n  }\n\n  protected async getFeatureFlagPayloadsStateless(\n    distinctId: string,\n    groups: Record<string, string> = {},\n    personProperties: Record<string, string> = {},\n    groupProperties: Record<string, Record<string, string>> = {},\n    disableGeoip?: boolean,\n    flagKeysToEvaluate?: string[]\n  ): Promise<PostHogFlagsResponse['featureFlagPayloads'] | undefined> {\n    await this._initPromise\n\n    const payloads = (\n      await this.getFeatureFlagsAndPayloadsStateless(\n        distinctId,\n        groups,\n        personProperties,\n        groupProperties,\n        disableGeoip,\n        flagKeysToEvaluate\n      )\n    ).payloads\n\n    return payloads\n  }\n\n  protected async getFeatureFlagsStateless(\n    distinctId: string,\n    groups: Record<string, string | number> = {},\n    personProperties: Record<string, string> = {},\n    groupProperties: Record<string, Record<string, string>> = {},\n    disableGeoip?: boolean,\n    flagKeysToEvaluate?: string[]\n  ): Promise<{\n    flags: PostHogFlagsResponse['featureFlags'] | undefined\n    payloads: PostHogFlagsResponse['featureFlagPayloads'] | undefined\n    requestId: PostHogFlagsResponse['requestId'] | undefined\n  }> {\n    await this._initPromise\n\n    return await this.getFeatureFlagsAndPayloadsStateless(\n      distinctId,\n      groups,\n      personProperties,\n      groupProperties,\n      disableGeoip,\n      flagKeysToEvaluate\n    )\n  }\n\n  protected async getFeatureFlagsAndPayloadsStateless(\n    distinctId: string,\n    groups: Record<string, string | number> = {},\n    personProperties: Record<string, string> = {},\n    groupProperties: Record<string, Record<string, string>> = {},\n    disableGeoip?: boolean,\n    flagKeysToEvaluate?: string[]\n  ): Promise<{\n    flags: PostHogFlagsResponse['featureFlags'] | undefined\n    payloads: PostHogFlagsResponse['featureFlagPayloads'] | undefined\n    requestId: PostHogFlagsResponse['requestId'] | undefined\n  }> {\n    await this._initPromise\n\n    const featureFlagDetails = await this.getFeatureFlagDetailsStateless(\n      distinctId,\n      groups,\n      personProperties,\n      groupProperties,\n      disableGeoip,\n      flagKeysToEvaluate\n    )\n\n    if (!featureFlagDetails) {\n      return {\n        flags: undefined,\n        payloads: undefined,\n        requestId: undefined,\n      }\n    }\n\n    return {\n      flags: featureFlagDetails.featureFlags,\n      payloads: featureFlagDetails.featureFlagPayloads,\n      requestId: featureFlagDetails.requestId,\n    }\n  }\n\n  protected async getFeatureFlagDetailsStateless(\n    distinctId: string,\n    groups: Record<string, string | number> = {},\n    personProperties: Record<string, string> = {},\n    groupProperties: Record<string, Record<string, string>> = {},\n    disableGeoip?: boolean,\n    flagKeysToEvaluate?: string[]\n  ): Promise<PostHogFeatureFlagDetails | undefined> {\n    await this._initPromise\n\n    const extraPayload: Record<string, any> = {}\n    if (disableGeoip ?? this.disableGeoip) {\n      extraPayload['geoip_disable'] = true\n    }\n    if (flagKeysToEvaluate) {\n      extraPayload['flag_keys_to_evaluate'] = flagKeysToEvaluate\n    }\n    const flagsResponse = await this.getFlags(distinctId, groups, personProperties, groupProperties, extraPayload)\n\n    if (flagsResponse === undefined) {\n      // We probably errored out, so return undefined\n      return undefined\n    }\n\n    // if there's an error on the flagsResponse, log a console error, but don't throw an error\n    if (flagsResponse.errorsWhileComputingFlags) {\n      console.error(\n        '[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'\n      )\n    }\n\n    // Add check for quota limitation on feature flags\n    if (flagsResponse.quotaLimited?.includes(QuotaLimitedFeature.FeatureFlags)) {\n      console.warn(\n        '[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts'\n      )\n      return {\n        flags: {},\n        featureFlags: {},\n        featureFlagPayloads: {},\n        requestId: flagsResponse?.requestId,\n      }\n    }\n\n    return flagsResponse\n  }\n\n  /***\n   *** SURVEYS\n   ***/\n\n  public async getSurveysStateless(): Promise<SurveyResponse['surveys']> {\n    await this._initPromise\n\n    if (this.disableSurveys === true) {\n      this.logMsgIfDebug(() => console.log('PostHog Debug', 'Loading surveys is disabled.'))\n      return []\n    }\n\n    const url = `${this.host}/api/surveys/?token=${this.apiKey}`\n    const fetchOptions: PostHogFetchOptions = {\n      method: 'GET',\n      headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/json' },\n    }\n\n    const response = await this.fetchWithRetry(url, fetchOptions)\n      .then((response) => {\n        if (response.status !== 200 || !response.json) {\n          const msg = `Surveys API could not be loaded: ${response.status}`\n          const error = new Error(msg)\n          this.logMsgIfDebug(() => console.error(error))\n\n          this._events.emit('error', new Error(msg))\n          return undefined\n        }\n\n        return response.json() as Promise<SurveyResponse>\n      })\n      .catch((error) => {\n        this.logMsgIfDebug(() => console.error('Surveys API could not be loaded', error))\n\n        this._events.emit('error', error)\n        return undefined\n      })\n\n    const newSurveys = response?.surveys\n\n    if (newSurveys) {\n      this.logMsgIfDebug(() => console.log('PostHog Debug', 'Surveys fetched from API: ', JSON.stringify(newSurveys)))\n    }\n\n    return newSurveys ?? []\n  }\n\n  /***\n   *** SUPER PROPERTIES\n   ***/\n  private _props: PostHogEventProperties | undefined\n\n  protected get props(): PostHogEventProperties {\n    if (!this._props) {\n      this._props = this.getPersistedProperty<PostHogEventProperties>(PostHogPersistedProperty.Props)\n    }\n    return this._props || {}\n  }\n\n  protected set props(val: PostHogEventProperties | undefined) {\n    this._props = val\n  }\n\n  async register(properties: PostHogEventProperties): Promise<void> {\n    this.wrap(() => {\n      this.props = {\n        ...this.props,\n        ...properties,\n      }\n      this.setPersistedProperty<PostHogEventProperties>(PostHogPersistedProperty.Props, this.props)\n    })\n  }\n\n  async unregister(property: string): Promise<void> {\n    this.wrap(() => {\n      delete this.props[property]\n      this.setPersistedProperty<PostHogEventProperties>(PostHogPersistedProperty.Props, this.props)\n    })\n  }\n\n  /***\n   *** QUEUEING AND FLUSHING\n   ***/\n  protected enqueue(type: string, _message: any, options?: PostHogCaptureOptions): void {\n    this.wrap(() => {\n      if (this.optedOut) {\n        this._events.emit(type, `Library is disabled. Not sending event. To re-enable, call posthog.optIn()`)\n        return\n      }\n\n      const message = this.prepareMessage(type, _message, options)\n\n      const queue = this.getPersistedProperty<PostHogQueueItem[]>(PostHogPersistedProperty.Queue) || []\n\n      if (queue.length >= this.maxQueueSize) {\n        queue.shift()\n        this.logMsgIfDebug(() => console.info('Queue is full, the oldest event is dropped.'))\n      }\n\n      queue.push({ message })\n      this.setPersistedProperty<PostHogQueueItem[]>(PostHogPersistedProperty.Queue, queue)\n\n      this._events.emit(type, message)\n\n      // Flush queued events if we meet the flushAt length\n      if (queue.length >= this.flushAt) {\n        this.flushBackground()\n      }\n\n      if (this.flushInterval && !this._flushTimer) {\n        this._flushTimer = safeSetTimeout(() => this.flushBackground(), this.flushInterval)\n      }\n    })\n  }\n\n  protected async sendImmediate(type: string, _message: any, options?: PostHogCaptureOptions): Promise<void> {\n    if (this.disabled) {\n      this.logMsgIfDebug(() => console.warn('[PostHog] The client is disabled'))\n      return\n    }\n\n    if (!this._isInitialized) {\n      await this._initPromise\n    }\n\n    if (this.optedOut) {\n      this._events.emit(type, `Library is disabled. Not sending event. To re-enable, call posthog.optIn()`)\n      return\n    }\n\n    const data: Record<string, any> = {\n      api_key: this.apiKey,\n      batch: [this.prepareMessage(type, _message, options)],\n      sent_at: currentISOTime(),\n    }\n\n    if (this.historicalMigration) {\n      data.historical_migration = true\n    }\n\n    const payload = JSON.stringify(data)\n\n    const url = `${this.host}/batch/`\n\n    const gzippedPayload = !this.disableCompression ? await gzipCompress(payload, this.isDebug) : null\n    const fetchOptions: PostHogFetchOptions = {\n      method: 'POST',\n      headers: {\n        ...this.getCustomHeaders(),\n        'Content-Type': 'application/json',\n        ...(gzippedPayload !== null && { 'Content-Encoding': 'gzip' }),\n      },\n      body: gzippedPayload || payload,\n    }\n\n    try {\n      await this.fetchWithRetry(url, fetchOptions)\n    } catch (err) {\n      this._events.emit('error', err)\n    }\n  }\n\n  private prepareMessage(type: string, _message: any, options?: PostHogCaptureOptions): PostHogEventProperties {\n    const message = {\n      ..._message,\n      type: type,\n      library: this.getLibraryId(),\n      library_version: this.getLibraryVersion(),\n      timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),\n      uuid: options?.uuid ? options.uuid : uuidv7(),\n    }\n\n    const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip\n    if (addGeoipDisableProperty) {\n      if (!message.properties) {\n        message.properties = {}\n      }\n      message['properties']['$geoip_disable'] = true\n    }\n\n    if (message.distinctId) {\n      message.distinct_id = message.distinctId\n      delete message.distinctId\n    }\n\n    return message\n  }\n\n  private clearFlushTimer(): void {\n    if (this._flushTimer) {\n      clearTimeout(this._flushTimer)\n      this._flushTimer = undefined\n    }\n  }\n\n  /**\n   * Helper for flushing the queue in the background\n   * Avoids unnecessary promise errors\n   */\n  private flushBackground(): void {\n    void this.flush().catch(async (err) => {\n      await logFlushError(err)\n    })\n  }\n\n  /**\n   * Flushes the queue\n   *\n   * This function will return a promise that will resolve when the flush is complete,\n   * or reject if there was an error (for example if the server or network is down).\n   *\n   * If there is already a flush in progress, this function will wait for that flush to complete.\n   *\n   * It's recommended to do error handling in the callback of the promise.\n   *\n   * @example\n   * posthog.flush().then(() => {\n   *   console.log('Flush complete')\n   * }).catch((err) => {\n   *   console.error('Flush failed', err)\n   * })\n   *\n   *\n   * @throws PostHogFetchHttpError\n   * @throws PostHogFetchNetworkError\n   * @throws Error\n   */\n  async flush(): Promise<void> {\n    // Wait for the current flush operation to finish (regardless of success or failure), then try to flush again.\n    // Use allSettled instead of finally to be defensive around flush throwing errors immediately rather than rejecting.\n    // Use a custom allSettled implementation to avoid issues with patching Promise on RN\n    const nextFlushPromise = allSettled([this.flushPromise]).then(() => {\n      return this._flush()\n    })\n\n    this.flushPromise = nextFlushPromise\n    void this.addPendingPromise(nextFlushPromise)\n\n    allSettled([nextFlushPromise]).then(() => {\n      // If there are no others waiting to flush, clear the promise.\n      // We don't strictly need to do this, but it could make debugging easier\n      if (this.flushPromise === nextFlushPromise) {\n        this.flushPromise = null\n      }\n    })\n\n    return nextFlushPromise\n  }\n\n  protected getCustomHeaders(): { [key: string]: string } {\n    // Don't set the user agent if we're not on a browser. The latest spec allows\n    // the User-Agent header (see https://fetch.spec.whatwg.org/#terminology-headers\n    // and https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader),\n    // but browsers such as Chrome and Safari have not caught up.\n    const customUserAgent = this.getCustomUserAgent()\n    const headers: { [key: string]: string } = {}\n    if (customUserAgent && customUserAgent !== '') {\n      headers['User-Agent'] = customUserAgent\n    }\n    return headers\n  }\n\n  private async _flush(): Promise<void> {\n    this.clearFlushTimer()\n    await this._initPromise\n\n    let queue = this.getPersistedProperty<PostHogQueueItem[]>(PostHogPersistedProperty.Queue) || []\n\n    if (!queue.length) {\n      return\n    }\n\n    const sentMessages: any[] = []\n    const originalQueueLength = queue.length\n\n    while (queue.length > 0 && sentMessages.length < originalQueueLength) {\n      const batchItems = queue.slice(0, this.maxBatchSize)\n      const batchMessages = batchItems.map((item) => item.message)\n\n      const persistQueueChange = (): void => {\n        const refreshedQueue = this.getPersistedProperty<PostHogQueueItem[]>(PostHogPersistedProperty.Queue) || []\n        const newQueue = refreshedQueue.slice(batchItems.length)\n        this.setPersistedProperty<PostHogQueueItem[]>(PostHogPersistedProperty.Queue, newQueue)\n        queue = newQueue\n      }\n\n      const data: Record<string, any> = {\n        api_key: this.apiKey,\n        batch: batchMessages,\n        sent_at: currentISOTime(),\n      }\n\n      if (this.historicalMigration) {\n        data.historical_migration = true\n      }\n\n      const payload = JSON.stringify(data)\n\n      const url = `${this.host}/batch/`\n\n      const gzippedPayload = !this.disableCompression ? await gzipCompress(payload, this.isDebug) : null\n      const fetchOptions: PostHogFetchOptions = {\n        method: 'POST',\n        headers: {\n          ...this.getCustomHeaders(),\n          'Content-Type': 'application/json',\n          ...(gzippedPayload !== null && { 'Content-Encoding': 'gzip' }),\n        },\n        body: gzippedPayload || payload,\n      }\n\n      const retryOptions: Partial<RetriableOptions> = {\n        retryCheck: (err) => {\n          // don't automatically retry on 413 errors, we want to reduce the batch size first\n          if (isPostHogFetchContentTooLargeError(err)) {\n            return false\n          }\n          // otherwise, retry on network errors\n          return isPostHogFetchError(err)\n        },\n      }\n\n      try {\n        await this.fetchWithRetry(url, fetchOptions, retryOptions)\n      } catch (err) {\n        if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {\n          // if we get a 413 error, we want to reduce the batch size and try again\n          this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2))\n          this.logMsgIfDebug(() =>\n            console.warn(\n              `Received 413 when sending batch of size ${batchMessages.length}, reducing batch size to ${this.maxBatchSize}`\n            )\n          )\n          // do not persist the queue change, we want to retry the same batch\n          continue\n        }\n\n        // depending on the error type, eg a malformed JSON or broken queue, it'll always return an error\n        // and this will be an endless loop, in this case, if the error isn't a network issue, we always remove the items from the queue\n        if (!(err instanceof PostHogFetchNetworkError)) {\n          persistQueueChange()\n        }\n        this._events.emit('error', err)\n\n        throw err\n      }\n\n      persistQueueChange()\n\n      sentMessages.push(...batchMessages)\n    }\n    this._events.emit('flush', sentMessages)\n  }\n\n  private async fetchWithRetry(\n    url: string,\n    options: PostHogFetchOptions,\n    retryOptions?: Partial<RetriableOptions>,\n    requestTimeout?: number\n  ): Promise<PostHogFetchResponse> {\n    ;(AbortSignal as any).timeout ??= function timeout(ms: number) {\n      const ctrl = new AbortController()\n      setTimeout(() => ctrl.abort(), ms)\n      return ctrl.signal\n    }\n\n    const body = options.body ? options.body : ''\n    let reqByteLength = -1\n    try {\n      if (body instanceof Blob) {\n        reqByteLength = body.size\n      } else {\n        reqByteLength = Buffer.byteLength(body, STRING_FORMAT)\n      }\n    } catch {\n      if (body instanceof Blob) {\n        reqByteLength = body.size\n      } else {\n        const encoded = new TextEncoder().encode(body)\n        reqByteLength = encoded.length\n      }\n    }\n\n    return await retriable(\n      async () => {\n        let res: PostHogFetchResponse | null = null\n        try {\n          res = await this.fetch(url, {\n            signal: (AbortSignal as any).timeout(requestTimeout ?? this.requestTimeout),\n            ...options,\n          })\n        } catch (e) {\n          // fetch will only throw on network errors or on timeouts\n          throw new PostHogFetchNetworkError(e)\n        }\n        // If we're in no-cors mode, we can't access the response status\n        // We only throw on HTTP errors if we're not in no-cors mode\n        // https://developer.mozilla.org/en-US/docs/Web/API/Request/mode#no-cors\n        const isNoCors = options.mode === 'no-cors'\n        if (!isNoCors && (res.status < 200 || res.status >= 400)) {\n          throw new PostHogFetchHttpError(res, reqByteLength)\n        }\n        return res\n      },\n      { ...this._retryOptions, ...retryOptions }\n    )\n  }\n\n  async _shutdown(shutdownTimeoutMs: number = 30000): Promise<void> {\n    // A little tricky - we want to have a max shutdown time and enforce it, even if that means we have some\n    // dangling promises. We'll keep track of the timeout and resolve/reject based on that.\n\n    await this._initPromise\n    let hasTimedOut = false\n    this.clearFlushTimer()\n\n    const doShutdown = async (): Promise<void> => {\n      try {\n        await Promise.all(Object.values(this.pendingPromises))\n\n        while (true) {\n          const queue = this.getPersistedProperty<PostHogQueueItem[]>(PostHogPersistedProperty.Queue) || []\n\n          if (queue.length === 0) {\n            break\n          }\n\n          // flush again to make sure we send all events, some of which might've been added\n          // while we were waiting for the pending promises to resolve\n          // For example, see sendFeatureFlags in posthog-node/src/posthog-node.ts::capture\n          await this.flush()\n\n          if (hasTimedOut) {\n            break\n          }\n        }\n      } catch (e) {\n        if (!isPostHogFetchError(e)) {\n          throw e\n        }\n\n        await logFlushError(e)\n      }\n    }\n\n    return Promise.race([\n      new Promise<void>((_, reject) => {\n        safeSetTimeout(() => {\n          this.logMsgIfDebug(() => console.error('Timed out while shutting down PostHog'))\n          hasTimedOut = true\n          reject('Timeout while shutting down PostHog. Some events may not have been sent.')\n        }, shutdownTimeoutMs)\n      }),\n      doShutdown(),\n    ])\n  }\n\n  /**\n   *  Call shutdown() once before the node process exits, so ensure that all events have been sent and all promises\n   *  have resolved. Do not use this function if you intend to keep using this PostHog instance after calling it.\n   * @param shutdownTimeoutMs\n   */\n  async shutdown(shutdownTimeoutMs: number = 30000): Promise<void> {\n    if (this.shutdownPromise) {\n      this.logMsgIfDebug(() =>\n        console.warn(\n          'shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup'\n        )\n      )\n    } else {\n      this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(() => {\n        this.shutdownPromise = null\n      })\n    }\n    return this.shutdownPromise\n  }\n}\n\nexport abstract class PostHogCore extends PostHogCoreStateless {\n  // options\n  private sendFeatureFlagEvent: boolean\n  private flagCallReported: { [key: string]: boolean } = {}\n\n  // internal\n  protected _flagsResponsePromise?: Promise<PostHogFlagsResponse | undefined> // TODO: come back to this, fix typing\n  protected _sessionExpirationTimeSeconds: number\n  private _sessionMaxLengthSeconds: number = 24 * 60 * 60 // 24 hours\n  protected sessionProps: PostHogEventProperties = {}\n\n  constructor(apiKey: string, options?: PostHogCoreOptions) {\n    // Default for stateful mode is to not disable geoip. Only override if explicitly set\n    const disableGeoipOption = options?.disableGeoip ?? false\n\n    // Default for stateful mode is to timeout at 10s. Only override if explicitly set\n    const featureFlagsRequestTimeoutMs = options?.featureFlagsRequestTimeoutMs ?? 10000 // 10 seconds\n\n    super(apiKey, { ...options, disableGeoip: disableGeoipOption, featureFlagsRequestTimeoutMs })\n\n    this.sendFeatureFlagEvent = options?.sendFeatureFlagEvent ?? true\n    this._sessionExpirationTimeSeconds = options?.sessionExpirationTimeSeconds ?? 1800 // 30 minutes\n  }\n\n  protected setupBootstrap(options?: Partial<PostHogCoreOptions>): void {\n    const bootstrap = options?.bootstrap\n    if (!bootstrap) {\n      return\n    }\n\n    // bootstrap options are only set if no persisted values are found\n    // this is to prevent overwriting existing values\n    if (bootstrap.distinctId) {\n      if (bootstrap.isIdentifiedId) {\n        const distinctId = this.getPersistedProperty(PostHogPersistedProperty.DistinctId)\n\n        if (!distinctId) {\n          this.setPersistedProperty(PostHogPersistedProperty.DistinctId, bootstrap.distinctId)\n        }\n      } else {\n        const anonymousId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId)\n\n        if (!anonymousId) {\n          this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, bootstrap.distinctId)\n        }\n      }\n    }\n\n    const bootstrapFeatureFlags = bootstrap.featureFlags\n    const bootstrapFeatureFlagPayloads = bootstrap.featureFlagPayloads ?? {}\n    if (bootstrapFeatureFlags && Object.keys(bootstrapFeatureFlags).length) {\n      const normalizedBootstrapFeatureFlagDetails = createFlagsResponseFromFlagsAndPayloads(\n        bootstrapFeatureFlags,\n        bootstrapFeatureFlagPayloads\n      )\n\n      if (Object.keys(normalizedBootstrapFeatureFlagDetails.flags).length > 0) {\n        this.setBootstrappedFeatureFlagDetails(normalizedBootstrapFeatureFlagDetails)\n\n        const currentFeatureFlagDetails = this.getKnownFeatureFlagDetails() || { flags: {}, requestId: undefined }\n        const newFeatureFlagDetails = {\n          flags: {\n            ...normalizedBootstrapFeatureFlagDetails.flags,\n            ...currentFeatureFlagDetails.flags,\n          },\n          requestId: normalizedBootstrapFeatureFlagDetails.requestId,\n        }\n\n        this.setKnownFeatureFlagDetails(newFeatureFlagDetails)\n      }\n    }\n  }\n\n  private clearProps(): void {\n    this.props = undefined\n    this.sessionProps = {}\n    this.flagCallReported = {}\n  }\n\n  on(event: string, cb: (...args: any[]) => void): () => void {\n    return this._events.on(event, cb)\n  }\n\n  reset(propertiesToKeep?: PostHogPersistedProperty[]): void {\n    this.wrap(() => {\n      const allPropertiesToKeep = [PostHogPersistedProperty.Queue, ...(propertiesToKeep || [])]\n\n      // clean up props\n      this.clearProps()\n\n      for (const key of <(keyof typeof PostHogPersistedProperty)[]>Object.keys(PostHogPersistedProperty)) {\n        if (!allPropertiesToKeep.includes(PostHogPersistedProperty[key])) {\n          this.setPersistedProperty((PostHogPersistedProperty as any)[key], null)\n        }\n      }\n\n      this.reloadFeatureFlags()\n    })\n  }\n\n  protected getCommonEventProperties(): PostHogEventProperties {\n    const featureFlags = this.getFeatureFlags()\n\n    const featureVariantProperties: Record<string, FeatureFlagValue> = {}\n    if (featureFlags) {\n      for (const [feature, variant] of Object.entries(featureFlags)) {\n        featureVariantProperties[`$feature/${feature}`] = variant\n      }\n    }\n    return {\n      ...maybeAdd('$active_feature_flags', featureFlags ? Object.keys(featureFlags) : undefined),\n      ...featureVariantProperties,\n      ...super.getCommonEventProperties(),\n    }\n  }\n\n  private enrichProperties(properties?: PostHogEventProperties): PostHogEventProperties {\n    return {\n      ...this.props, // Persisted properties first\n      ...this.sessionProps, // Followed by session properties\n      ...(properties || {}), // Followed by user specified properties\n      ...this.getCommonEventProperties(), // Followed by FF props\n      $session_id: this.getSessionId(),\n    }\n  }\n\n  /**\n   * * @returns {string} The stored session ID for the current session. This may be an empty string if the client is not yet fully initialized.\n   */\n  getSessionId(): string {\n    if (!this._isInitialized) {\n      return ''\n    }\n\n    let sessionId = this.getPersistedProperty<string>(PostHogPersistedProperty.SessionId)\n    const sessionLastTimestamp = this.getPersistedProperty<number>(PostHogPersistedProperty.SessionLastTimestamp) || 0\n    const sessionStartTimestamp = this.getPersistedProperty<number>(PostHogPersistedProperty.SessionStartTimestamp) || 0\n    const now = Date.now()\n    const sessionLastDif = now - sessionLastTimestamp\n    const sessionStartDif = now - sessionStartTimestamp\n    if (\n      !sessionId ||\n      sessionLastDif > this._sessionExpirationTimeSeconds * 1000 ||\n      sessionStartDif > this._sessionMaxLengthSeconds * 1000\n    ) {\n      sessionId = uuidv7()\n      this.setPersistedProperty(PostHogPersistedProperty.SessionId, sessionId)\n      this.setPersistedProperty(PostHogPersistedProperty.SessionStartTimestamp, now)\n    }\n    this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, now)\n\n    return sessionId\n  }\n\n  resetSessionId(): void {\n    this.wrap(() => {\n      this.setPersistedProperty(PostHogPersistedProperty.SessionId, null)\n      this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, null)\n      this.setPersistedProperty(PostHogPersistedProperty.SessionStartTimestamp, null)\n    })\n  }\n\n  /**\n   * * @returns {string} The stored anonymous ID. This may be an empty string if the client is not yet fully initialized.\n   */\n  getAnonymousId(): string {\n    if (!this._isInitialized) {\n      return ''\n    }\n\n    let anonId = this.getPersistedProperty<string>(PostHogPersistedProperty.AnonymousId)\n    if (!anonId) {\n      anonId = uuidv7()\n      this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, anonId)\n    }\n    return anonId\n  }\n\n  /**\n   * * @returns {string} The stored distinct ID. This may be an empty string if the client is not yet fully initialized.\n   */\n  getDistinctId(): string {\n    if (!this._isInitialized) {\n      return ''\n    }\n\n    return this.getPersistedProperty<string>(PostHogPersistedProperty.DistinctId) || this.getAnonymousId()\n  }\n\n  registerForSession(properties: PostHogEventProperties): void {\n    this.sessionProps = {\n      ...this.sessionProps,\n      ...properties,\n    }\n  }\n\n  unregisterForSession(property: string): void {\n    delete this.sessionProps[property]\n  }\n\n  /***\n   *** TRACKING\n   ***/\n  identify(distinctId?: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): void {\n    this.wrap(() => {\n      const previousDistinctId = this.getDistinctId()\n      distinctId = distinctId || previousDistinctId\n\n      if (properties?.$groups) {\n        this.groups(properties.$groups as PostHogGroupProperties)\n      }\n\n      // promote $set and $set_once to top level\n      const userPropsOnce = properties?.$set_once\n      delete properties?.$set_once\n\n      // if no $set is provided we assume all properties are $set\n      const userProps = properties?.$set || properties\n\n      const allProperties = this.enrichProperties({\n        $anon_distinct_id: this.getAnonymousId(),\n        ...maybeAdd('$set', userProps),\n        ...maybeAdd('$set_once', userPropsOnce),\n      })\n\n      if (distinctId !== previousDistinctId) {\n        // We keep the AnonymousId to be used by flags calls and identify to link the previousId\n        this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, previousDistinctId)\n        this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId)\n        this.reloadFeatureFlags()\n      }\n\n      super.identifyStateless(distinctId, allProperties, options)\n    })\n  }\n\n  capture(event: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): void {\n    this.wrap(() => {\n      const distinctId = this.getDistinctId()\n\n      if (properties?.$groups) {\n        this.groups(properties.$groups as PostHogGroupProperties)\n      }\n\n      const allProperties = this.enrichProperties(properties)\n\n      super.captureStateless(distinctId, event, allProperties, options)\n    })\n  }\n\n  alias(alias: string): void {\n    this.wrap(() => {\n      const distinctId = this.getDistinctId()\n      const allProperties = this.enrichProperties({})\n\n      super.aliasStateless(alias, distinctId, allProperties)\n    })\n  }\n\n  autocapture(\n    eventType: string,\n    elements: PostHogAutocaptureElement[],\n    properties: PostHogEventProperties = {},\n    options?: PostHogCaptureOptions\n  ): void {\n    this.wrap(() => {\n      const distinctId = this.getDistinctId()\n      const payload = {\n        distinct_id: distinctId,\n        event: '$autocapture',\n        properties: {\n          ...this.enrichProperties(properties),\n          $event_type: eventType,\n          $elements: elements,\n        },\n      }\n\n      this.enqueue('autocapture', payload, options)\n    })\n  }\n\n  /***\n   *** GROUPS\n   ***/\n\n  groups(groups: PostHogGroupProperties): void {\n    this.wrap(() => {\n      // Get persisted groups\n      const existingGroups = this.props.$groups || {}\n\n      this.register({\n        $groups: {\n          ...(existingGroups as PostHogGroupProperties),\n          ...groups,\n        },\n      })\n\n      if (Object.keys(groups).find((type) => existingGroups[type as keyof typeof existingGroups] !== groups[type])) {\n        this.reloadFeatureFlags()\n      }\n    })\n  }\n\n  group(\n    groupType: string,\n    groupKey: string | number,\n    groupProperties?: PostHogEventProperties,\n    options?: PostHogCaptureOptions\n  ): void {\n    this.wrap(() => {\n      this.groups({\n        [groupType]: groupKey,\n      })\n\n      if (groupProperties) {\n        this.groupIdentify(groupType, groupKey, groupProperties, options)\n      }\n    })\n  }\n\n  groupIdentify(\n    groupType: string,\n    groupKey: string | number,\n    groupProperties?: PostHogEventProperties,\n    options?: PostHogCaptureOptions\n  ): void {\n    this.wrap(() => {\n      const distinctId = this.getDistinctId()\n      const eventProperties = this.enrichProperties({})\n      super.groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties)\n    })\n  }\n\n  /***\n   * PROPERTIES\n   ***/\n  setPersonPropertiesForFlags(properties: { [type: string]: string }): void {\n    this.wrap(() => {\n      // Get persisted person properties\n      const existingProperties =\n        this.getPersistedProperty<Record<string, string>>(PostHogPersistedProperty.PersonProperties) || {}\n\n      this.setPersistedProperty<PostHogEventProperties>(PostHogPersistedProperty.PersonProperties, {\n        ...existingProperties,\n        ...properties,\n      })\n    })\n  }\n\n  resetPersonPropertiesForFlags(): void {\n    this.wrap(() => {\n      this.setPersistedProperty<PostHogEventProperties>(PostHogPersistedProperty.PersonProperties, null)\n    })\n  }\n\n  setGroupPropertiesForFlags(properties: { [type: string]: Record<string, string> }): void {\n    this.wrap(() => {\n      // Get persisted group properties\n      const existingProperties =\n        this.getPersistedProperty<Record<string, Record<string, string>>>(PostHogPersistedProperty.GroupProperties) ||\n        {}\n\n      if (Object.keys(existingProperties).length !== 0) {\n        Object.keys(existingProperties).forEach((groupType) => {\n          existingProperties[groupType] = {\n            ...existingProperties[groupType],\n            ...properties[groupType],\n          }\n          delete properties[groupType]\n        })\n      }\n\n      this.setPersistedProperty<PostHogEventProperties>(PostHogPersistedProperty.GroupProperties, {\n        ...existingProperties,\n        ...properties,\n      })\n    })\n  }\n\n  resetGroupPropertiesForFlags(): void {\n    this.wrap(() => {\n      this.setPersistedProperty<PostHogEventProperties>(PostHogPersistedProperty.GroupProperties, null)\n    })\n  }\n\n  private async remoteConfigAsync(): Promise<PostHogRemoteConfig | undefined> {\n    await this._initPromise\n    if (this._remoteConfigResponsePromise) {\n      return this._remoteConfigResponsePromise\n    }\n    return this._remoteConfigAsync()\n  }\n\n  /***\n   *** FEATURE FLAGS\n   ***/\n  private async flagsAsync(sendAnonDistinctId: boolean = true): Promise<PostHogFlagsResponse | undefined> {\n    await this._initPromise\n    if (this._flagsResponsePromise) {\n      return this._flagsResponsePromise\n    }\n    return this._flagsAsync(sendAnonDistinctId)\n  }\n\n  private cacheSessionReplay(source: string, response?: PostHogRemoteConfig): void {\n    const sessionReplay = response?.sessionRecording\n    if (sessionReplay) {\n      this.setPersistedProperty(PostHogPersistedProperty.SessionReplay, sessionReplay)\n      this.logMsgIfDebug(() =>\n        console.log('PostHog Debug', `Session replay config from ${source}: `, JSON.stringify(sessionReplay))\n      )\n    } else if (typeof sessionReplay === 'boolean' && sessionReplay === false) {\n      // if session replay is disabled, we don't need to cache it\n      // we need to check for this because the response might be undefined (/flags does not return sessionRecording yet)\n      this.logMsgIfDebug(() => console.info('PostHog Debug', `Session replay config from ${source} disabled.`))\n      this.setPersistedProperty(PostHogPersistedProperty.SessionReplay, null)\n    }\n  }\n\n  private async _remoteConfigAsync(): Promise<PostHogRemoteConfig | undefined> {\n    this._remoteConfigResponsePromise = this._initPromise\n      .then(() => {\n        let remoteConfig = this.getPersistedProperty<Omit<PostHogRemoteConfig, 'surveys'>>(\n          PostHogPersistedProperty.RemoteConfig\n        )\n\n        this.logMsgIfDebug(() => console.log('PostHog Debug', 'Cached remote config: ', JSON.stringify(remoteConfig)))\n\n        return super.getRemoteConfig().then((response) => {\n          if (response) {\n            const remoteConfigWithoutSurveys = { ...response }\n            delete remoteConfigWithoutSurveys.surveys\n\n            this.logMsgIfDebug(() =>\n              console.log('PostHog Debug', 'Fetched remote config: ', JSON.stringify(remoteConfigWithoutSurveys))\n            )\n\n            if (this.disableSurveys === false) {\n              const surveys = response.surveys\n\n              let hasSurveys = true\n\n              if (!Array.isArray(surveys)) {\n                // If surveys is not an array, it means there are no surveys (its a boolean instead)\n                this.logMsgIfDebug(() => console.log('PostHog Debug', 'There are no surveys.'))\n                hasSurveys = false\n              } else {\n                this.logMsgIfDebug(() =>\n                  console.log('PostHog Debug', 'Surveys fetched from remote config: ', JSON.stringify(surveys))\n                )\n              }\n\n              if (hasSurveys) {\n                this.setPersistedProperty<SurveyResponse['surveys']>(\n                  PostHogPersistedProperty.Surveys,\n                  surveys as Survey[]\n                )\n              } else {\n                this.setPersistedProperty<SurveyResponse['surveys']>(PostHogPersistedProperty.Surveys, null)\n              }\n            } else {\n              this.setPersistedProperty<SurveyResponse['surveys']>(PostHogPersistedProperty.Surveys, null)\n            }\n            // we cache the surveys in its own storage key\n            this.setPersistedProperty<Omit<PostHogRemoteConfig, 'surveys'>>(\n              PostHogPersistedProperty.RemoteConfig,\n              remoteConfigWithoutSurveys\n            )\n\n            this.cacheSessionReplay('remote config', response)\n\n            // we only dont load flags if the remote config has no feature flags\n            if (response.hasFeatureFlags === false) {\n              // resetting flags to empty object\n              this.setKnownFeatureFlagDetails({ flags: {} })\n\n              this.logMsgIfDebug(() => console.warn('Remote config has no feature flags, will not load feature flags.'))\n            } else if (this.preloadFeatureFlags !== false) {\n              this.reloadFeatureFlags()\n            }\n\n            if (!response.supportedCompression?.includes(Compression.GZipJS)) {\n              this.disableCompression = true\n            }\n\n            remoteConfig = response\n          }\n\n          return remoteConfig\n        })\n      })\n      .finally(() => {\n        this._remoteConfigResponsePromise = undefined\n      })\n    return this._remoteConfigResponsePromise\n  }\n\n  private async _flagsAsync(sendAnonDistinctId: boolean = true): Promise<PostHogFlagsResponse | undefined> {\n    this._flagsResponsePromise = this._initPromise\n      .then(async () => {\n        const distinctId = this.getDistinctId()\n        const groups = this.props.$groups || {}\n        const personProperties =\n          this.getPersistedProperty<Record<string, string>>(PostHogPersistedProperty.PersonProperties) || {}\n        const groupProperties =\n          this.getPersistedProperty<Record<string, Record<string, string>>>(PostHogPersistedProperty.GroupProperties) ||\n          {}\n\n        const extraProperties = {\n          $anon_distinct_id: sendAnonDistinctId ? this.getAnonymousId() : undefined,\n        }\n\n        const res = await super.getFlags(\n          distinctId,\n          groups as PostHogGroupProperties,\n          personProperties,\n          groupProperties,\n          extraProperties\n        )\n        // Add check for quota limitation on feature flags\n        if (res?.quotaLimited?.includes(QuotaLimitedFeature.FeatureFlags)) {\n          // Unset all feature flags by setting to null\n          this.setKnownFeatureFlagDetails(null)\n          console.warn(\n            '[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts'\n          )\n          return res\n        }\n        if (res?.featureFlags) {\n          // clear flag call reported if we have new flags since they might have changed\n          if (this.sendFeatureFlagEvent) {\n            this.flagCallReported = {}\n          }\n\n          let newFeatureFlagDetails = res\n          if (res.errorsWhileComputingFlags) {\n            // if not all flags were computed, we upsert flags instead of replacing them\n            const currentFlagDetails = this.getKnownFeatureFlagDetails()\n            this.logMsgIfDebug(() =>\n              console.log('PostHog Debug', 'Cached feature flags: ', JSON.stringify(currentFlagDetails))\n            )\n\n            newFeatureFlagDetails = {\n              ...res,\n              flags: { ...currentFlagDetails?.flags, ...res.flags },\n            }\n          }\n          this.setKnownFeatureFlagDetails(newFeatureFlagDetails)\n          // Mark that we hit the /flags endpoint so we can capture this in the $feature_flag_called event\n          this.setPersistedProperty(PostHogPersistedProperty.FlagsEndpointWasHit, true)\n          this.cacheSessionReplay('flags', res)\n        }\n        return res\n      })\n      .finally(() => {\n        this._flagsResponsePromise = undefined\n      })\n    return this._flagsResponsePromise\n  }\n\n  // We only store the flags and request id in the feature flag details storage key\n  private setKnownFeatureFlagDetails(flagsResponse: PostHogFlagsStorageFormat | null): void {\n    this.wrap(() => {\n      this.setPersistedProperty<PostHogFlagsStorageFormat>(PostHogPersistedProperty.FeatureFlagDetails, flagsResponse)\n\n      this._events.emit('featureflags', getFlagValuesFromFlags(flagsResponse?.flags ?? {}))\n    })\n  }\n\n  private getKnownFeatureFlagDetails(): PostHogFeatureFlagDetails | undefined {\n    const storedDetails = this.getPersistedProperty<PostHogFlagsStorageFormat>(\n      PostHogPersistedProperty.FeatureFlagDetails\n    )\n    if (!storedDetails) {\n      // Rebuild from the stored feature flags and feature flag payloads\n      const featureFlags = this.getPersistedProperty<PostHogFlagsResponse['featureFlags']>(\n        PostHogPersistedProperty.FeatureFlags\n      )\n      const featureFlagPayloads = this.getPersistedProperty<PostHogFlagsResponse['featureFlagPayloads']>(\n        PostHogPersistedProperty.FeatureFlagPayloads\n      )\n\n      if (featureFlags === undefined && featureFlagPayloads === undefined) {\n        return undefined\n      }\n\n      return createFlagsResponseFromFlagsAndPayloads(featureFlags ?? {}, featureFlagPayloads ?? {})\n    }\n\n    return normalizeFlagsResponse(\n      storedDetails as PostHogV1FlagsResponse | PostHogV2FlagsResponse\n    ) as PostHogFeatureFlagDetails\n  }\n\n  protected getKnownFeatureFlags(): PostHogFlagsResponse['featureFlags'] | undefined {\n    const featureFlagDetails = this.getKnownFeatureFlagDetails()\n    if (!featureFlagDetails) {\n      return undefined\n    }\n    return getFlagValuesFromFlags(featureFlagDetails.flags)\n  }\n\n  private getKnownFeatureFlagPayloads(): PostHogFlagsResponse['featureFlagPayloads'] | undefined {\n    const featureFlagDetails = this.getKnownFeatureFlagDetails()\n    if (!featureFlagDetails) {\n      return undefined\n    }\n    return getPayloadsFromFlags(featureFlagDetails.flags)\n  }\n\n  private getBootstrappedFeatureFlagDetails(): PostHogFeatureFlagDetails | undefined {\n    const details = this.getPersistedProperty<PostHogFeatureFlagDetails>(\n      PostHogPersistedProperty.BootstrapFeatureFlagDetails\n    )\n    if (!details) {\n      return undefined\n    }\n    return details\n  }\n\n  private setBootstrappedFeatureFlagDetails(details: PostHogFeatureFlagDetails): void {\n    this.setPersistedProperty<PostHogFeatureFlagDetails>(PostHogPersistedProperty.BootstrapFeatureFlagDetails, details)\n  }\n\n  private getBootstrappedFeatureFlags(): PostHogFlagsResponse['featureFlags'] | undefined {\n    const details = this.getBootstrappedFeatureFlagDetails()\n    if (!details) {\n      return undefined\n    }\n    return getFlagValuesFromFlags(details.flags)\n  }\n\n  private getBootstrappedFeatureFlagPayloads(): PostHogFlagsResponse['featureFlagPayloads'] | undefined {\n    const details = this.getBootstrappedFeatureFlagDetails()\n    if (!details) {\n      return undefined\n    }\n    return getPayloadsFromFlags(details.flags)\n  }\n\n  getFeatureFlag(key: string): FeatureFlagValue | undefined {\n    const details = this.getFeatureFlagDetails()\n\n    if (!details) {\n      // If we haven't loaded flags yet, or errored out, we respond with undefined\n      return undefined\n    }\n\n    const featureFlag = details.flags[key]\n\n    let response = getFeatureFlagValue(featureFlag)\n\n    if (response === undefined) {\n      // For cases where the flag is unknown, return false\n      response = false\n    }\n\n    if (this.sendFeatureFlagEvent && !this.flagCallReported[key]) {\n      const bootstrappedResponse = this.getBootstrappedFeatureFlags()?.[key]\n      const bootstrappedPayload = this.getBootstrappedFeatureFlagPayloads()?.[key]\n\n      this.flagCallReported[key] = true\n      this.capture('$feature_flag_called', {\n        $feature_flag: key,\n        $feature_flag_response: response,\n        ...maybeAdd('$feature_flag_id', featureFlag?.metadata?.id),\n        ...maybeAdd('$feature_flag_version', featureFlag?.metadata?.version),\n        ...maybeAdd('$feature_flag_reason', featureFlag?.reason?.description ?? featureFlag?.reason?.code),\n        ...maybeAdd('$feature_flag_bootstrapped_response', bootstrappedResponse),\n        ...maybeAdd('$feature_flag_bootstrapped_payload', bootstrappedPayload),\n        // If we haven't yet received a response from the /flags endpoint, we must have used the bootstrapped value\n        $used_bootstrap_value: !this.getPersistedProperty(PostHogPersistedProperty.FlagsEndpointWasHit),\n        ...maybeAdd('$feature_flag_request_id', details.requestId),\n      })\n    }\n\n    // If we have flags we either return the value (true or string) or false\n    return response\n  }\n\n  getFeatureFlagPayload(key: string): JsonType | undefined {\n    const payloads = this.getFeatureFlagPayloads()\n\n    if (!payloads) {\n      return undefined\n    }\n\n    const response = payloads[key]\n\n    // Undefined means a loading or missing data issue. Null means evaluation happened and there was no match\n    if (response === undefined) {\n      return null\n    }\n\n    return response\n  }\n\n  getFeatureFlagPayloads(): PostHogFlagsResponse['featureFlagPayloads'] | undefined {\n    return this.getFeatureFlagDetails()?.featureFlagPayloads\n  }\n\n  getFeatureFlags(): PostHogFlagsResponse['featureFlags'] | undefined {\n    // NOTE: We don't check for _initPromise here as the function is designed to be\n    // callable before the state being loaded anyways\n    return this.getFeatureFlagDetails()?.featureFlags\n  }\n\n  getFeatureFlagDetails(): PostHogFeatureFlagDetails | undefined {\n    // NOTE: We don't check for _initPromise here as the function is designed to be\n    // callable before the state being loaded anyways\n    let details = this.getKnownFeatureFlagDetails()\n    const overriddenFlags = this.getPersistedProperty<PostHogFlagsResponse['featureFlags']>(\n      PostHogPersistedProperty.OverrideFeatureFlags\n    )\n\n    if (!overriddenFlags) {\n      return details\n    }\n\n    details = details ?? { featureFlags: {}, featureFlagPayloads: {}, flags: {} }\n\n    const flags: Record<string, FeatureFlagDetail> = details.flags ?? {}\n\n    for (const key in overriddenFlags) {\n      if (!overriddenFlags[key]) {\n        delete flags[key]\n      } else {\n        flags[key] = updateFlagValue(flags[key], overriddenFlags[key])\n      }\n    }\n\n    const result = {\n      ...details,\n      flags,\n    }\n\n    return normalizeFlagsResponse(result) as PostHogFeatureFlagDetails\n  }\n\n  getFeatureFlagsAndPayloads(): {\n    flags: PostHogFlagsResponse['featureFlags'] | undefined\n    payloads: PostHogFlagsResponse['featureFlagPayloads'] | undefined\n  } {\n    const flags = this.getFeatureFlags()\n    const payloads = this.getFeatureFlagPayloads()\n\n    return {\n      flags,\n      payloads,\n    }\n  }\n\n  isFeatureEnabled(key: string): boolean | undefined {\n    const response = this.getFeatureFlag(key)\n    if (response === undefined) {\n      return undefined\n    }\n    return !!response\n  }\n\n  // Used when we want to trigger the reload but we don't care about the result\n  reloadFeatureFlags(options?: { cb?: (err?: Error, flags?: PostHogFlagsResponse['featureFlags']) => void }): void {\n    this.flagsAsync(true)\n      .then((res) => {\n        options?.cb?.(undefined, res?.featureFlags)\n      })\n      .catch((e) => {\n        options?.cb?.(e, undefined)\n        if (!options?.cb) {\n          this.logMsgIfDebug(() => console.log('PostHog Debug', 'Error reloading feature flags', e))\n        }\n      })\n  }\n\n  async reloadRemoteConfigAsync(): Promise<PostHogRemoteConfig | undefined> {\n    return await this.remoteConfigAsync()\n  }\n\n  async reloadFeatureFlagsAsync(\n    sendAnonDistinctId?: boolean\n  ): Promise<PostHogFlagsResponse['featureFlags'] | undefined> {\n    return (await this.flagsAsync(sendAnonDistinctId ?? true))?.featureFlags\n  }\n\n  onFeatureFlags(cb: (flags: PostHogFlagsResponse['featureFlags']) => void): () => void {\n    return this.on('featureflags', async () => {\n      const flags = this.getFeatureFlags()\n      if (flags) {\n        cb(flags)\n      }\n    })\n  }\n\n  onFeatureFlag(key: string, cb: (value: FeatureFlagValue) => void): () => void {\n    return this.on('featureflags', async () => {\n      const flagResponse = this.getFeatureFlag(key)\n      if (flagResponse !== undefined) {\n        cb(flagResponse)\n      }\n    })\n  }\n\n  async overrideFeatureFlag(flags: PostHogFlagsResponse['featureFlags'] | null): Promise<void> {\n    this.wrap(() => {\n      if (flags === null) {\n        return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, null)\n      }\n      return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, flags)\n    })\n  }\n\n  /***\n   *** ERROR TRACKING\n   ***/\n  captureException(error: unknown, additionalProperties?: PostHogEventProperties): void {\n    const properties: { [key: string]: any } = {\n      $exception_level: 'error',\n      $exception_list: [\n        {\n          type: isError(error) ? error.name : 'Error',\n          value: isError(error) ? error.message : error,\n          mechanism: {\n            handled: true,\n            synthetic: false,\n          },\n        },\n      ],\n      ...additionalProperties,\n    }\n\n    properties.$exception_personURL = new URL(\n      `/project/${this.apiKey}/person/${this.getDistinctId()}`,\n      this.host\n    ).toString()\n\n    this.capture('$exception', properties)\n  }\n\n  /**\n   * Capture written user feedback for a LLM trace. Numeric values are converted to strings.\n   * @param traceId The trace ID to capture feedback for.\n   * @param userFeedback The feedback to capture.\n   */\n  captureTraceFeedback(traceId: string | number, userFeedback: string): void {\n    this.capture('$ai_feedback', {\n      $ai_feedback_text: userFeedback,\n      $ai_trace_id: String(traceId),\n    })\n  }\n\n  /**\n   * Capture a metric for a LLM trace. Numeric values are converted to strings.\n   * @param traceId The trace ID to capture the metric for.\n   * @param metricName The name of the metric to capture.\n   * @param metricValue The value of the metric to capture.\n   */\n  captureTraceMetric(traceId: string | number, metricName: string, metricValue: string | number | boolean): void {\n    this.capture('$ai_metric', {\n      $ai_metric_name: metricName,\n      $ai_metric_value: String(metricValue),\n      $ai_trace_id: String(traceId),\n    })\n  }\n}\n\nexport * from './types'\n","/**\n * A lazy value that is only computed when needed. Inspired by C#'s Lazy<T> class.\n */\nexport class Lazy<T> {\n  private value: T | undefined\n  private factory: () => Promise<T>\n  private initializationPromise: Promise<T> | undefined\n\n  constructor(factory: () => Promise<T>) {\n    this.factory = factory\n  }\n\n  /**\n   * Gets the value, initializing it if necessary.\n   * Multiple concurrent calls will share the same initialization promise.\n   */\n  async getValue(): Promise<T> {\n    if (this.value !== undefined) {\n      return this.value\n    }\n\n    if (this.initializationPromise === undefined) {\n      this.initializationPromise = (async () => {\n        try {\n          const result = await this.factory()\n          this.value = result\n          return result\n        } finally {\n          // Clear the promise so we can retry if needed\n          this.initializationPromise = undefined\n        }\n      })()\n    }\n\n    return this.initializationPromise\n  }\n\n  /**\n   * Returns true if the value has been initialized.\n   */\n  isInitialized(): boolean {\n    return this.value !== undefined\n  }\n\n  /**\n   * Returns a promise that resolves when the value is initialized.\n   * If already initialized, resolves immediately.\n   */\n  async waitForInitialization(): Promise<void> {\n    if (this.isInitialized()) {\n      return\n    }\n    await this.getValue()\n  }\n}\n","/// <reference lib=\"dom\" />\nimport { Lazy } from './lazy'\n\nconst nodeCrypto = new Lazy(async () => {\n  try {\n    return await import('crypto')\n  } catch {\n    return undefined\n  }\n})\n\nexport async function getNodeCrypto(): Promise<typeof import('crypto') | undefined> {\n  return await nodeCrypto.getValue()\n}\n\nconst webCrypto = new Lazy(async (): Promise<SubtleCrypto | undefined> => {\n  if (typeof globalThis.crypto?.subtle !== 'undefined') {\n    return globalThis.crypto.subtle\n  }\n\n  try {\n    // Node.js: use built-in webcrypto and assign it if needed\n    const crypto = await nodeCrypto.getValue()\n    if (crypto?.webcrypto?.subtle) {\n      return crypto.webcrypto.subtle as SubtleCrypto\n    }\n  } catch {\n    // Ignore if not available\n  }\n\n  return undefined\n})\n\nexport async function getWebCrypto(): Promise<SubtleCrypto | undefined> {\n  return await webCrypto.getValue()\n}\n","/// <reference lib=\"dom\" />\n\nimport { getNodeCrypto, getWebCrypto } from './crypto-helpers'\n\nexport async function hashSHA1(text: string): Promise<string> {\n  // Try Node.js crypto first\n  const nodeCrypto = await getNodeCrypto()\n  if (nodeCrypto) {\n    return nodeCrypto.createHash('sha1').update(text).digest('hex')\n  }\n\n  const webCrypto = await getWebCrypto()\n\n  // Fall back to Web Crypto API\n  if (webCrypto) {\n    const hashBuffer = await webCrypto.digest('SHA-1', new TextEncoder().encode(text))\n    const hashArray = Array.from(new Uint8Array(hashBuffer))\n    return hashArray.map((byte) => byte.toString(16).padStart(2, '0')).join('')\n  }\n\n  throw new Error('No crypto implementation available. Tried Node Crypto API and Web SubtleCrypto API')\n}\n","import { FeatureFlagCondition, FlagProperty, PostHogFeatureFlag, PropertyGroup } from '../../types'\nimport type { FeatureFlagValue, JsonType, PostHogFetchOptions, PostHogFetchResponse } from 'posthog-core'\nimport { safeSetTimeout } from 'posthog-core'\nimport { hashSHA1 } from './crypto'\n\nconst SIXTY_SECONDS = 60 * 1000\n\n// eslint-disable-next-line\nconst LONG_SCALE = 0xfffffffffffffff\n\nconst NULL_VALUES_ALLOWED_OPERATORS = ['is_not']\nclass ClientError extends Error {\n  constructor(message: string) {\n    super()\n    Error.captureStackTrace(this, this.constructor)\n    this.name = 'ClientError'\n    this.message = message\n    Object.setPrototypeOf(this, ClientError.prototype)\n  }\n}\n\nclass InconclusiveMatchError extends Error {\n  constructor(message: string) {\n    super(message)\n    this.name = this.constructor.name\n    Error.captureStackTrace(this, this.constructor)\n    // instanceof doesn't work in ES3 or ES5\n    // https://www.dannyguo.com/blog/how-to-fix-instanceof-not-working-for-custom-errors-in-typescript/\n    // this is the workaround\n    Object.setPrototypeOf(this, InconclusiveMatchError.prototype)\n  }\n}\n\ntype FeatureFlagsPollerOptions = {\n  personalApiKey: string\n  projectApiKey: string\n  host: string\n  pollingInterval: number\n  timeout?: number\n  fetch?: (url: string, options: PostHogFetchOptions) => Promise<PostHogFetchResponse>\n  onError?: (error: Error) => void\n  onLoad?: (count: number) => void\n  customHeaders?: { [key: string]: string }\n}\n\nclass FeatureFlagsPoller {\n  pollingInterval: number\n  personalApiKey: string\n  projectApiKey: string\n  featureFlags: Array<PostHogFeatureFlag>\n  featureFlagsByKey: Record<string, PostHogFeatureFlag>\n  groupTypeMapping: Record<string, string>\n  cohorts: Record<string, PropertyGroup>\n  loadedSuccessfullyOnce: boolean\n  timeout?: number\n  host: FeatureFlagsPollerOptions['host']\n  poller?: NodeJS.Timeout\n  fetch: (url: string, options: PostHogFetchOptions) => Promise<PostHogFetchResponse>\n  debugMode: boolean = false\n  onError?: (error: Error) => void\n  customHeaders?: { [key: string]: string }\n  shouldBeginExponentialBackoff: boolean = false\n  backOffCount: number = 0\n  onLoad?: (count: number) => void\n\n  constructor({\n    pollingInterval,\n    personalApiKey,\n    projectApiKey,\n    timeout,\n    host,\n    customHeaders,\n    ...options\n  }: FeatureFlagsPollerOptions) {\n    this.pollingInterval = pollingInterval\n    this.personalApiKey = personalApiKey\n    this.featureFlags = []\n    this.featureFlagsByKey = {}\n    this.groupTypeMapping = {}\n    this.cohorts = {}\n    this.loadedSuccessfullyOnce = false\n    this.timeout = timeout\n    this.projectApiKey = projectApiKey\n    this.host = host\n    this.poller = undefined\n    this.fetch = options.fetch || fetch\n    this.onError = options.onError\n    this.customHeaders = customHeaders\n    this.onLoad = options.onLoad\n    void this.loadFeatureFlags()\n  }\n\n  debug(enabled: boolean = true): void {\n    this.debugMode = enabled\n  }\n\n  private logMsgIfDebug(fn: () => void): void {\n    if (this.debugMode) {\n      fn()\n    }\n  }\n\n  async getFeatureFlag(\n    key: string,\n    distinctId: string,\n    groups: Record<string, string> = {},\n    personProperties: Record<string, string> = {},\n    groupProperties: Record<string, Record<string, string>> = {}\n  ): Promise<FeatureFlagValue | undefined> {\n    await this.loadFeatureFlags()\n\n    let response: FeatureFlagValue | undefined = undefined\n    let featureFlag = undefined\n\n    if (!this.loadedSuccessfullyOnce) {\n      return response\n    }\n\n    for (const flag of this.featureFlags) {\n      if (key === flag.key) {\n        featureFlag = flag\n        break\n      }\n    }\n\n    if (featureFlag !== undefined) {\n      try {\n        response = await this.computeFlagLocally(featureFlag, distinctId, groups, personProperties, groupProperties)\n        this.logMsgIfDebug(() => console.debug(`Successfully computed flag locally: ${key} -> ${response}`))\n      } catch (e) {\n        if (e instanceof InconclusiveMatchError) {\n          this.logMsgIfDebug(() => console.debug(`InconclusiveMatchError when computing flag locally: ${key}: ${e}`))\n        } else if (e instanceof Error) {\n          this.onError?.(new Error(`Error computing flag locally: ${key}: ${e}`))\n        }\n      }\n    }\n\n    return response\n  }\n\n  async computeFeatureFlagPayloadLocally(key: string, matchValue: FeatureFlagValue): Promise<JsonType | undefined> {\n    await this.loadFeatureFlags()\n\n    let response = undefined\n\n    if (!this.loadedSuccessfullyOnce) {\n      return undefined\n    }\n\n    if (typeof matchValue == 'boolean') {\n      response = this.featureFlagsByKey?.[key]?.filters?.payloads?.[matchValue.toString()]\n    } else if (typeof matchValue == 'string') {\n      response = this.featureFlagsByKey?.[key]?.filters?.payloads?.[matchValue]\n    }\n\n    // Undefined means a loading or missing data issue. Null means evaluation happened and there was no match\n    if (response === undefined || response === null) {\n      return null\n    }\n\n    try {\n      return JSON.parse(response)\n    } catch {\n      return response\n    }\n  }\n\n  async getAllFlagsAndPayloads(\n    distinctId: string,\n    groups: Record<string, string> = {},\n    personProperties: Record<string, string> = {},\n    groupProperties: Record<string, Record<string, string>> = {}\n  ): Promise<{\n    response: Record<string, FeatureFlagValue>\n    payloads: Record<string, JsonType>\n    fallbackToFlags: boolean\n  }> {\n    await this.loadFeatureFlags()\n\n    const response: Record<string, FeatureFlagValue> = {}\n    const payloads: Record<string, JsonType> = {}\n    let fallbackToFlags = this.featureFlags.length == 0\n\n    await Promise.all(\n      this.featureFlags.map(async (flag) => {\n        try {\n          const matchValue = await this.computeFlagLocally(flag, distinctId, groups, personProperties, groupProperties)\n          response[flag.key] = matchValue\n          const matchPayload = await this.computeFeatureFlagPayloadLocally(flag.key, matchValue)\n          if (matchPayload) {\n            payloads[flag.key] = matchPayload\n          }\n        } catch (e) {\n          if (e instanceof InconclusiveMatchError) {\n            // do nothing\n          } else if (e instanceof Error) {\n            this.onError?.(new Error(`Error computing flag locally: ${flag.key}: ${e}`))\n          }\n          fallbackToFlags = true\n        }\n      })\n    )\n\n    return { response, payloads, fallbackToFlags }\n  }\n\n  async computeFlagLocally(\n    flag: PostHogFeatureFlag,\n    distinctId: string,\n    groups: Record<string, string> = {},\n    personProperties: Record<string, string> = {},\n    groupProperties: Record<string, Record<string, string>> = {}\n  ): Promise<FeatureFlagValue> {\n    if (flag.ensure_experience_continuity) {\n      throw new InconclusiveMatchError('Flag has experience continuity enabled')\n    }\n\n    if (!flag.active) {\n      return false\n    }\n\n    const flagFilters = flag.filters || {}\n    const aggregation_group_type_index = flagFilters.aggregation_group_type_index\n\n    if (aggregation_group_type_index != undefined) {\n      const groupName = this.groupTypeMapping[String(aggregation_group_type_index)]\n\n      if (!groupName) {\n        this.logMsgIfDebug(() =>\n          console.warn(\n            `[FEATURE FLAGS] Unknown group type index ${aggregation_group_type_index} for feature flag ${flag.key}`\n          )\n        )\n        throw new InconclusiveMatchError('Flag has unknown group type index')\n      }\n\n      if (!(groupName in groups)) {\n        this.logMsgIfDebug(() =>\n          console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${flag.key} without group names passed in`)\n        )\n        return false\n      }\n\n      const focusedGroupProperties = groupProperties[groupName]\n      return await this.matchFeatureFlagProperties(flag, groups[groupName], focusedGroupProperties)\n    } else {\n      return await this.matchFeatureFlagProperties(flag, distinctId, personProperties)\n    }\n  }\n\n  async matchFeatureFlagProperties(\n    flag: PostHogFeatureFlag,\n    distinctId: string,\n    properties: Record<string, string>\n  ): Promise<FeatureFlagValue> {\n    const flagFilters = flag.filters || {}\n    const flagConditions = flagFilters.groups || []\n    let isInconclusive = false\n    let result = undefined\n\n    // # Stable sort conditions with variant overrides to the top. This ensures that if overrides are present, they are\n    // # evaluated first, and the variant override is applied to the first matching condition.\n    const sortedFlagConditions = [...flagConditions].sort((conditionA, conditionB) => {\n      const AHasVariantOverride = !!conditionA.variant\n      const BHasVariantOverride = !!conditionB.variant\n\n      if (AHasVariantOverride && BHasVariantOverride) {\n        return 0\n      } else if (AHasVariantOverride) {\n        return -1\n      } else if (BHasVariantOverride) {\n        return 1\n      } else {\n        return 0\n      }\n    })\n\n    for (const condition of sortedFlagConditions) {\n      try {\n        if (await this.isConditionMatch(flag, distinctId, condition, properties)) {\n          const variantOverride = condition.variant\n          const flagVariants = flagFilters.multivariate?.variants || []\n          if (variantOverride && flagVariants.some((variant) => variant.key === variantOverride)) {\n            result = variantOverride\n          } else {\n            result = (await this.getMatchingVariant(flag, distinctId)) || true\n          }\n          break\n        }\n      } catch (e) {\n        if (e instanceof InconclusiveMatchError) {\n          isInconclusive = true\n        } else {\n          throw e\n        }\n      }\n    }\n\n    if (result !== undefined) {\n      return result\n    } else if (isInconclusive) {\n      throw new InconclusiveMatchError(\"Can't determine if feature flag is enabled or not with given properties\")\n    }\n\n    // We can only return False when all conditions are False\n    return false\n  }\n\n  async isConditionMatch(\n    flag: PostHogFeatureFlag,\n    distinctId: string,\n    condition: FeatureFlagCondition,\n    properties: Record<string, string>\n  ): Promise<boolean> {\n    const rolloutPercentage = condition.rollout_percentage\n    const warnFunction = (msg: string): void => {\n      this.logMsgIfDebug(() => console.warn(msg))\n    }\n    if ((condition.properties || []).length > 0) {\n      for (const prop of condition.properties) {\n        const propertyType = prop.type\n        let matches = false\n\n        if (propertyType === 'cohort') {\n          matches = matchCohort(prop, properties, this.cohorts, this.debugMode)\n        } else {\n          matches = matchProperty(prop, properties, warnFunction)\n        }\n\n        if (!matches) {\n          return false\n        }\n      }\n\n      if (rolloutPercentage == undefined) {\n        return true\n      }\n    }\n\n    if (rolloutPercentage != undefined && (await _hash(flag.key, distinctId)) > rolloutPercentage / 100.0) {\n      return false\n    }\n\n    return true\n  }\n\n  async getMatchingVariant(flag: PostHogFeatureFlag, distinctId: string): Promise<FeatureFlagValue | undefined> {\n    const hashValue = await _hash(flag.key, distinctId, 'variant')\n    const matchingVariant = this.variantLookupTable(flag).find((variant) => {\n      return hashValue >= variant.valueMin && hashValue < variant.valueMax\n    })\n\n    if (matchingVariant) {\n      return matchingVariant.key\n    }\n    return undefined\n  }\n\n  variantLookupTable(flag: PostHogFeatureFlag): { valueMin: number; valueMax: number; key: string }[] {\n    const lookupTable: { valueMin: number; valueMax: number; key: string }[] = []\n    let valueMin = 0\n    let valueMax = 0\n    const flagFilters = flag.filters || {}\n    const multivariates: {\n      key: string\n      rollout_percentage: number\n    }[] = flagFilters.multivariate?.variants || []\n\n    multivariates.forEach((variant) => {\n      valueMax = valueMin + variant.rollout_percentage / 100.0\n      lookupTable.push({ valueMin, valueMax, key: variant.key })\n      valueMin = valueMax\n    })\n    return lookupTable\n  }\n\n  async loadFeatureFlags(forceReload = false): Promise<void> {\n    if (!this.loadedSuccessfullyOnce || forceReload) {\n      await this._loadFeatureFlags()\n    }\n  }\n\n  /**\n   * Returns true if the feature flags poller has loaded successfully at least once and has more than 0 feature flags.\n   * This is useful to check if local evaluation is ready before calling getFeatureFlag.\n   */\n  isLocalEvaluationReady(): boolean {\n    return (this.loadedSuccessfullyOnce ?? false) && (this.featureFlags?.length ?? 0) > 0\n  }\n\n  /**\n   * If a client is misconfigured with an invalid or improper API key, the polling interval is doubled each time\n   * until a successful request is made, up to a maximum of 60 seconds.\n   *\n   * @returns The polling interval to use for the next request.\n   */\n  private getPollingInterval(): number {\n    if (!this.shouldBeginExponentialBackoff) {\n      return this.pollingInterval\n    }\n\n    return Math.min(SIXTY_SECONDS, this.pollingInterval * 2 ** this.backOffCount)\n  }\n\n  async _loadFeatureFlags(): Promise<void> {\n    if (this.poller) {\n      clearTimeout(this.poller)\n      this.poller = undefined\n    }\n\n    this.poller = setTimeout(() => this._loadFeatureFlags(), this.getPollingInterval())\n\n    try {\n      const res = await this._requestFeatureFlagDefinitions()\n\n      // Handle undefined res case, this shouldn't happen, but it doesn't hurt to handle it anyway\n      if (!res) {\n        // Don't override existing flags when something goes wrong\n        return\n      }\n\n      // NB ON ERROR HANDLING & `loadedSuccessfullyOnce`:\n      //\n      // `loadedSuccessfullyOnce` indicates we've successfully loaded a valid set of flags at least once.\n      // If we set it to `true` in an error scenario (e.g. 402 Over Quota, 401 Invalid Key, etc.),\n      // any manual call to `loadFeatureFlags()` (without forceReload) will skip refetching entirely,\n      // leaving us stuck with zero or outdated flags. The poller does keep running, but we also want\n      // manual reloads to be possible as soon as the error condition is resolved.\n      //\n      // Therefore, on error statuses, we do *not* set `loadedSuccessfullyOnce = true`, ensuring that\n      // both the background poller and any subsequent manual calls can keep trying to load flags\n      // once the issue (quota, permission, rate limit, etc.) is resolved.\n      switch (res.status) {\n        case 401:\n          // Invalid API key\n          this.shouldBeginExponentialBackoff = true\n          this.backOffCount += 1\n          throw new ClientError(\n            `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`\n          )\n\n        case 402:\n          // Quota exceeded - clear all flags\n          console.warn(\n            '[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts'\n          )\n          this.featureFlags = []\n          this.featureFlagsByKey = {}\n          this.groupTypeMapping = {}\n          this.cohorts = {}\n          return\n\n        case 403:\n          // Permissions issue\n          this.shouldBeginExponentialBackoff = true\n          this.backOffCount += 1\n          throw new ClientError(\n            `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`\n          )\n\n        case 429:\n          // Rate limited\n          this.shouldBeginExponentialBackoff = true\n          this.backOffCount += 1\n          throw new ClientError(\n            `You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`\n          )\n\n        case 200: {\n          // Process successful response\n          const responseJson = ((await res.json()) as { [key: string]: any }) ?? {}\n          if (!('flags' in responseJson)) {\n            this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(responseJson)}`))\n            return\n          }\n\n          this.featureFlags = (responseJson.flags as PostHogFeatureFlag[]) ?? []\n          this.featureFlagsByKey = this.featureFlags.reduce(\n            (acc, curr) => ((acc[curr.key] = curr), acc),\n            <Record<string, PostHogFeatureFlag>>{}\n          )\n          this.groupTypeMapping = (responseJson.group_type_mapping as Record<string, string>) || {}\n          this.cohorts = (responseJson.cohorts as Record<string, PropertyGroup>) || {}\n          this.loadedSuccessfullyOnce = true\n          this.shouldBeginExponentialBackoff = false\n          this.backOffCount = 0\n          this.onLoad?.(this.featureFlags.length)\n          break\n        }\n\n        default:\n          // Something else went wrong, or the server is down.\n          // In this case, don't override existing flags\n          return\n      }\n    } catch (err) {\n      if (err instanceof ClientError) {\n        this.onError?.(err)\n      }\n    }\n  }\n\n  private getPersonalApiKeyRequestOptions(method: 'GET' | 'POST' | 'PUT' | 'PATCH' = 'GET'): PostHogFetchOptions {\n    return {\n      method,\n      headers: {\n        ...this.customHeaders,\n        'Content-Type': 'application/json',\n        Authorization: `Bearer ${this.personalApiKey}`,\n      },\n    }\n  }\n\n  async _requestFeatureFlagDefinitions(): Promise<PostHogFetchResponse> {\n    const url = `${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`\n\n    const options = this.getPersonalApiKeyRequestOptions()\n\n    let abortTimeout = null\n\n    if (this.timeout && typeof this.timeout === 'number') {\n      const controller = new AbortController()\n      abortTimeout = safeSetTimeout(() => {\n        controller.abort()\n      }, this.timeout)\n      options.signal = controller.signal\n    }\n\n    try {\n      return await this.fetch(url, options)\n    } finally {\n      clearTimeout(abortTimeout)\n    }\n  }\n\n  stopPoller(): void {\n    clearTimeout(this.poller)\n  }\n\n  _requestRemoteConfigPayload(flagKey: string): Promise<PostHogFetchResponse> {\n    const url = `${this.host}/api/projects/@current/feature_flags/${flagKey}/remote_config/`\n\n    const options = this.getPersonalApiKeyRequestOptions()\n\n    let abortTimeout = null\n    if (this.timeout && typeof this.timeout === 'number') {\n      const controller = new AbortController()\n      abortTimeout = safeSetTimeout(() => {\n        controller.abort()\n      }, this.timeout)\n      options.signal = controller.signal\n    }\n    try {\n      return this.fetch(url, options)\n    } finally {\n      clearTimeout(abortTimeout)\n    }\n  }\n}\n\n// # This function takes a distinct_id and a feature flag key and returns a float between 0 and 1.\n// # Given the same distinct_id and key, it'll always return the same float. These floats are\n// # uniformly distributed between 0 and 1, so if we want to show this feature to 20% of traffic\n// # we can do _hash(key, distinct_id) < 0.2\nasync function _hash(key: string, distinctId: string, salt: string = ''): Promise<number> {\n  const hashString = await hashSHA1(`${key}.${distinctId}${salt}`)\n  return parseInt(hashString.slice(0, 15), 16) / LONG_SCALE\n}\n\nfunction matchProperty(\n  property: FeatureFlagCondition['properties'][number],\n  propertyValues: Record<string, any>,\n  warnFunction?: (msg: string) => void\n): boolean {\n  const key = property.key\n  const value = property.value\n  const operator = property.operator || 'exact'\n\n  if (!(key in propertyValues)) {\n    throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`)\n  } else if (operator === 'is_not_set') {\n    throw new InconclusiveMatchError(`Operator is_not_set is not supported`)\n  }\n\n  const overrideValue = propertyValues[key]\n  if (overrideValue == null && !NULL_VALUES_ALLOWED_OPERATORS.includes(operator)) {\n    // if the value is null, just fail the feature flag comparison\n    // this isn't an InconclusiveMatchError because the property value was provided.\n    if (warnFunction) {\n      warnFunction(`Property ${key} cannot have a value of null/undefined with the ${operator} operator`)\n    }\n\n    return false\n  }\n\n  function computeExactMatch(value: any, overrideValue: any): boolean {\n    if (Array.isArray(value)) {\n      return value.map((val) => String(val).toLowerCase()).includes(String(overrideValue).toLowerCase())\n    }\n    return String(value).toLowerCase() === String(overrideValue).toLowerCase()\n  }\n\n  function compare(lhs: any, rhs: any, operator: string): boolean {\n    if (operator === 'gt') {\n      return lhs > rhs\n    } else if (operator === 'gte') {\n      return lhs >= rhs\n    } else if (operator === 'lt') {\n      return lhs < rhs\n    } else if (operator === 'lte') {\n      return lhs <= rhs\n    } else {\n      throw new Error(`Invalid operator: ${operator}`)\n    }\n  }\n\n  switch (operator) {\n    case 'exact':\n      return computeExactMatch(value, overrideValue)\n    case 'is_not':\n      return !computeExactMatch(value, overrideValue)\n    case 'is_set':\n      return key in propertyValues\n    case 'icontains':\n      return String(overrideValue).toLowerCase().includes(String(value).toLowerCase())\n    case 'not_icontains':\n      return !String(overrideValue).toLowerCase().includes(String(value).toLowerCase())\n    case 'regex':\n      return isValidRegex(String(value)) && String(overrideValue).match(String(value)) !== null\n    case 'not_regex':\n      return isValidRegex(String(value)) && String(overrideValue).match(String(value)) === null\n    case 'gt':\n    case 'gte':\n    case 'lt':\n    case 'lte': {\n      // :TRICKY: We adjust comparison based on the override value passed in,\n      // to make sure we handle both numeric and string comparisons appropriately.\n      let parsedValue = typeof value === 'number' ? value : null\n\n      if (typeof value === 'string') {\n        try {\n          parsedValue = parseFloat(value)\n        } catch (err) {\n          // pass\n        }\n      }\n\n      if (parsedValue != null && overrideValue != null) {\n        // check both null and undefined\n        if (typeof overrideValue === 'string') {\n          return compare(overrideValue, String(value), operator)\n        } else {\n          return compare(overrideValue, parsedValue, operator)\n        }\n      } else {\n        return compare(String(overrideValue), String(value), operator)\n      }\n    }\n    case 'is_date_after':\n    case 'is_date_before': {\n      let parsedDate = relativeDateParseForFeatureFlagMatching(String(value))\n      if (parsedDate == null) {\n        parsedDate = convertToDateTime(value)\n      }\n\n      if (parsedDate == null) {\n        throw new InconclusiveMatchError(`Invalid date: ${value}`)\n      }\n      const overrideDate = convertToDateTime(overrideValue)\n      if (['is_date_before'].includes(operator)) {\n        return overrideDate < parsedDate\n      }\n      return overrideDate > parsedDate\n    }\n    default:\n      throw new InconclusiveMatchError(`Unknown operator: ${operator}`)\n  }\n}\n\nfunction matchCohort(\n  property: FeatureFlagCondition['properties'][number],\n  propertyValues: Record<string, any>,\n  cohortProperties: FeatureFlagsPoller['cohorts'],\n  debugMode: boolean = false\n): boolean {\n  const cohortId = String(property.value)\n  if (!(cohortId in cohortProperties)) {\n    throw new InconclusiveMatchError(\"can't match cohort without a given cohort property value\")\n  }\n\n  const propertyGroup = cohortProperties[cohortId]\n  return matchPropertyGroup(propertyGroup, propertyValues, cohortProperties, debugMode)\n}\n\nfunction matchPropertyGroup(\n  propertyGroup: PropertyGroup,\n  propertyValues: Record<string, any>,\n  cohortProperties: FeatureFlagsPoller['cohorts'],\n  debugMode: boolean = false\n): boolean {\n  if (!propertyGroup) {\n    return true\n  }\n\n  const propertyGroupType = propertyGroup.type\n  const properties = propertyGroup.values\n\n  if (!properties || properties.length === 0) {\n    // empty groups are no-ops, always match\n    return true\n  }\n\n  let errorMatchingLocally = false\n\n  if ('values' in properties[0]) {\n    // a nested property group\n    for (const prop of properties as PropertyGroup[]) {\n      try {\n        const matches = matchPropertyGroup(prop, propertyValues, cohortProperties, debugMode)\n        if (propertyGroupType === 'AND') {\n          if (!matches) {\n            return false\n          }\n        } else {\n          // OR group\n          if (matches) {\n            return true\n          }\n        }\n      } catch (err) {\n        if (err instanceof InconclusiveMatchError) {\n          if (debugMode) {\n            console.debug(`Failed to compute property ${prop} locally: ${err}`)\n          }\n          errorMatchingLocally = true\n        } else {\n          throw err\n        }\n      }\n    }\n\n    if (errorMatchingLocally) {\n      throw new InconclusiveMatchError(\"Can't match cohort without a given cohort property value\")\n    }\n    // if we get here, all matched in AND case, or none matched in OR case\n    return propertyGroupType === 'AND'\n  } else {\n    for (const prop of properties as FlagProperty[]) {\n      try {\n        let matches: boolean\n        if (prop.type === 'cohort') {\n          matches = matchCohort(prop, propertyValues, cohortProperties, debugMode)\n        } else {\n          matches = matchProperty(prop, propertyValues)\n        }\n\n        const negation = prop.negation || false\n\n        if (propertyGroupType === 'AND') {\n          // if negated property, do the inverse\n          if (!matches && !negation) {\n            return false\n          }\n          if (matches && negation) {\n            return false\n          }\n        } else {\n          // OR group\n          if (matches && !negation) {\n            return true\n          }\n          if (!matches && negation) {\n            return true\n          }\n        }\n      } catch (err) {\n        if (err instanceof InconclusiveMatchError) {\n          if (debugMode) {\n            console.debug(`Failed to compute property ${prop} locally: ${err}`)\n          }\n          errorMatchingLocally = true\n        } else {\n          throw err\n        }\n      }\n    }\n\n    if (errorMatchingLocally) {\n      throw new InconclusiveMatchError(\"can't match cohort without a given cohort property value\")\n    }\n\n    // if we get here, all matched in AND case, or none matched in OR case\n    return propertyGroupType === 'AND'\n  }\n}\n\nfunction isValidRegex(regex: string): boolean {\n  try {\n    new RegExp(regex)\n    return true\n  } catch (err) {\n    return false\n  }\n}\n\nfunction convertToDateTime(value: string | number | (string | number)[] | Date): Date {\n  if (value instanceof Date) {\n    return value\n  } else if (typeof value === 'string' || typeof value === 'number') {\n    const date = new Date(value)\n    if (!isNaN(date.valueOf())) {\n      return date\n    }\n    throw new InconclusiveMatchError(`${value} is in an invalid date format`)\n  } else {\n    throw new InconclusiveMatchError(`The date provided ${value} must be a string, number, or date object`)\n  }\n}\n\nfunction relativeDateParseForFeatureFlagMatching(value: string): Date | null {\n  const regex = /^-?(?<number>[0-9]+)(?<interval>[a-z])$/\n  const match = value.match(regex)\n  const parsedDt = new Date(new Date().toISOString())\n\n  if (match) {\n    if (!match.groups) {\n      return null\n    }\n\n    const number = parseInt(match.groups['number'])\n\n    if (number >= 10000) {\n      // Guard against overflow, disallow numbers greater than 10_000\n      return null\n    }\n    const interval = match.groups['interval']\n    if (interval == 'h') {\n      parsedDt.setUTCHours(parsedDt.getUTCHours() - number)\n    } else if (interval == 'd') {\n      parsedDt.setUTCDate(parsedDt.getUTCDate() - number)\n    } else if (interval == 'w') {\n      parsedDt.setUTCDate(parsedDt.getUTCDate() - number * 7)\n    } else if (interval == 'm') {\n      parsedDt.setUTCMonth(parsedDt.getUTCMonth() - number)\n    } else if (interval == 'y') {\n      parsedDt.setUTCFullYear(parsedDt.getUTCFullYear() - number)\n    } else {\n      return null\n    }\n\n    return parsedDt\n  } else {\n    return null\n  }\n}\n\nexport {\n  FeatureFlagsPoller,\n  matchProperty,\n  relativeDateParseForFeatureFlagMatching,\n  InconclusiveMatchError,\n  ClientError,\n}\n","import { PostHogPersistedProperty } from 'posthog-core'\n\nexport class PostHogMemoryStorage {\n  private _memoryStorage: { [key: string]: any | undefined } = {}\n\n  getProperty(key: PostHogPersistedProperty): any | undefined {\n    return this._memoryStorage[key]\n  }\n\n  setProperty(key: PostHogPersistedProperty, value: any | null): void {\n    this._memoryStorage[key] = value !== null ? value : undefined\n  }\n}\n","import { version } from '../package.json'\n\nimport {\n  JsonType,\n  PostHogCoreStateless,\n  PostHogFlagsResponse,\n  PostHogFetchOptions,\n  PostHogFetchResponse,\n  PostHogFlagsAndPayloadsResponse,\n  PostHogPersistedProperty,\n} from 'posthog-core'\nimport { EventMessage, GroupIdentifyMessage, IdentifyMessage, IPostHog, PostHogOptions } from './types'\nimport { FeatureFlagDetail, FeatureFlagValue } from 'posthog-core'\nimport { FeatureFlagsPoller } from './extensions/feature-flags/feature-flags'\nimport ErrorTracking from './extensions/error-tracking'\nimport { getFeatureFlagValue } from 'posthog-core'\nimport { PostHogMemoryStorage } from './storage-memory'\n\n// Standard local evaluation rate limit is 600 per minute (10 per second),\n// so the fastest a poller should ever be set is 100ms.\nconst MINIMUM_POLLING_INTERVAL = 100\nconst THIRTY_SECONDS = 30 * 1000\nconst MAX_CACHE_SIZE = 50 * 1000\n\n// The actual exported Nodejs API.\nexport abstract class PostHogBackendClient extends PostHogCoreStateless implements IPostHog {\n  private _memoryStorage = new PostHogMemoryStorage()\n\n  private featureFlagsPoller?: FeatureFlagsPoller\n  protected errorTracking: ErrorTracking\n  private maxCacheSize: number\n  public readonly options: PostHogOptions\n\n  distinctIdHasSentFlagCalls: Record<string, string[]>\n\n  constructor(apiKey: string, options: PostHogOptions = {}) {\n    super(apiKey, options)\n\n    this.options = options\n\n    this.options.featureFlagsPollingInterval =\n      typeof options.featureFlagsPollingInterval === 'number'\n        ? Math.max(options.featureFlagsPollingInterval, MINIMUM_POLLING_INTERVAL)\n        : THIRTY_SECONDS\n\n    if (options.personalApiKey) {\n      if (options.personalApiKey.includes('phc_')) {\n        throw new Error(\n          'Your Personal API key is invalid. These keys are prefixed with \"phx_\" and can be created in PostHog project settings.'\n        )\n      }\n\n      this.featureFlagsPoller = new FeatureFlagsPoller({\n        pollingInterval: this.options.featureFlagsPollingInterval,\n        personalApiKey: options.personalApiKey,\n        projectApiKey: apiKey,\n        timeout: options.requestTimeout ?? 10000, // 10 seconds\n        host: this.host,\n        fetch: options.fetch,\n        onError: (err: Error) => {\n          this._events.emit('error', err)\n        },\n        onLoad: (count: number) => {\n          this._events.emit('localEvaluationFlagsLoaded', count)\n        },\n        customHeaders: this.getCustomHeaders(),\n      })\n    }\n    this.errorTracking = new ErrorTracking(this, options)\n    this.distinctIdHasSentFlagCalls = {}\n    this.maxCacheSize = options.maxCacheSize || MAX_CACHE_SIZE\n  }\n\n  getPersistedProperty(key: PostHogPersistedProperty): any | undefined {\n    return this._memoryStorage.getProperty(key)\n  }\n\n  setPersistedProperty(key: PostHogPersistedProperty, value: any | null): void {\n    return this._memoryStorage.setProperty(key, value)\n  }\n\n  fetch(url: string, options: PostHogFetchOptions): Promise<PostHogFetchResponse> {\n    return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options)\n  }\n  getLibraryVersion(): string {\n    return version\n  }\n  getCustomUserAgent(): string {\n    return `${this.getLibraryId()}/${this.getLibraryVersion()}`\n  }\n\n  enable(): Promise<void> {\n    return super.optIn()\n  }\n\n  disable(): Promise<void> {\n    return super.optOut()\n  }\n\n  debug(enabled: boolean = true): void {\n    super.debug(enabled)\n    this.featureFlagsPoller?.debug(enabled)\n  }\n\n  capture(props: EventMessage): void {\n    if (typeof props === 'string') {\n      this.logMsgIfDebug(() =>\n        console.warn('Called capture() with a string as the first argument when an object was expected.')\n      )\n    }\n    const { distinctId, event, properties, groups, sendFeatureFlags, timestamp, disableGeoip, uuid }: EventMessage =\n      props\n    const _capture = (props: EventMessage['properties']): void => {\n      super.captureStateless(distinctId, event, props, { timestamp, disableGeoip, uuid })\n    }\n\n    const _getFlags = async (\n      distinctId: EventMessage['distinctId'],\n      groups: EventMessage['groups'],\n      disableGeoip: EventMessage['disableGeoip']\n    ): Promise<PostHogFlagsResponse['featureFlags'] | undefined> => {\n      return (await super.getFeatureFlagsStateless(distinctId, groups, undefined, undefined, disableGeoip)).flags\n    }\n\n    // :TRICKY: If we flush, or need to shut down, to not lose events we want this promise to resolve before we flush\n    const capturePromise = Promise.resolve()\n      .then(async () => {\n        if (sendFeatureFlags) {\n          // If we are sending feature flags, we need to make sure we have the latest flags\n          // return await super.getFeatureFlagsStateless(distinctId, groups, undefined, undefined, disableGeoip)\n          return await _getFlags(distinctId, groups, disableGeoip)\n        }\n\n        if (event === '$feature_flag_called') {\n          // If we're capturing a $feature_flag_called event, we don't want to enrich the event with cached flags that may be out of date.\n          return {}\n        }\n\n        if ((this.featureFlagsPoller?.featureFlags?.length || 0) > 0) {\n          // Otherwise we may as well check for the flags locally and include them if they are already loaded\n          const groupsWithStringValues: Record<string, string> = {}\n          for (const [key, value] of Object.entries(groups || {})) {\n            groupsWithStringValues[key] = String(value)\n          }\n\n          return await this.getAllFlags(distinctId, {\n            groups: groupsWithStringValues,\n            disableGeoip,\n            onlyEvaluateLocally: true,\n          })\n        }\n        return {}\n      })\n      .then((flags) => {\n        // Derive the relevant flag properties to add\n        const additionalProperties: Record<string, any> = {}\n        if (flags) {\n          for (const [feature, variant] of Object.entries(flags)) {\n            additionalProperties[`$feature/${feature}`] = variant\n          }\n        }\n        const activeFlags = Object.keys(flags || {})\n          .filter((flag) => flags?.[flag] !== false)\n          .sort()\n        if (activeFlags.length > 0) {\n          additionalProperties['$active_feature_flags'] = activeFlags\n        }\n\n        return additionalProperties\n      })\n      .catch(() => {\n        // Something went wrong getting the flag info - we should capture the event anyways\n        return {}\n      })\n      .then((additionalProperties) => {\n        // No matter what - capture the event\n        _capture({ ...additionalProperties, ...properties, $groups: groups })\n      })\n\n    this.addPendingPromise(capturePromise)\n  }\n\n  async captureImmediate(props: EventMessage): Promise<void> {\n    if (typeof props === 'string') {\n      this.logMsgIfDebug(() =>\n        console.warn('Called capture() with a string as the first argument when an object was expected.')\n      )\n    }\n    const { distinctId, event, properties, groups, sendFeatureFlags, timestamp, disableGeoip, uuid }: EventMessage =\n      props\n\n    const _capture = (props: EventMessage['properties']): Promise<void> => {\n      return super.captureStatelessImmediate(distinctId, event, props, { timestamp, disableGeoip, uuid })\n    }\n\n    const _getFlags = async (\n      distinctId: EventMessage['distinctId'],\n      groups: EventMessage['groups'],\n      disableGeoip: EventMessage['disableGeoip']\n    ): Promise<PostHogFlagsResponse['featureFlags'] | undefined> => {\n      return (await super.getFeatureFlagsStateless(distinctId, groups, undefined, undefined, disableGeoip)).flags\n    }\n\n    const capturePromise = Promise.resolve()\n      .then(async () => {\n        if (sendFeatureFlags) {\n          // If we are sending feature flags, we need to make sure we have the latest flags\n          // return await super.getFeatureFlagsStateless(distinctId, groups, undefined, undefined, disableGeoip)\n          return await _getFlags(distinctId, groups, disableGeoip)\n        }\n\n        if (event === '$feature_flag_called') {\n          // If we're capturing a $feature_flag_called event, we don't want to enrich the event with cached flags that may be out of date.\n          return {}\n        }\n\n        if ((this.featureFlagsPoller?.featureFlags?.length || 0) > 0) {\n          // Otherwise we may as well check for the flags locally and include them if they are already loaded\n          const groupsWithStringValues: Record<string, string> = {}\n          for (const [key, value] of Object.entries(groups || {})) {\n            groupsWithStringValues[key] = String(value)\n          }\n\n          return await this.getAllFlags(distinctId, {\n            groups: groupsWithStringValues,\n            disableGeoip,\n            onlyEvaluateLocally: true,\n          })\n        }\n        return {}\n      })\n      .then((flags) => {\n        // Derive the relevant flag properties to add\n        const additionalProperties: Record<string, any> = {}\n        if (flags) {\n          for (const [feature, variant] of Object.entries(flags)) {\n            additionalProperties[`$feature/${feature}`] = variant\n          }\n        }\n        const activeFlags = Object.keys(flags || {})\n          .filter((flag) => flags?.[flag] !== false)\n          .sort()\n        if (activeFlags.length > 0) {\n          additionalProperties['$active_feature_flags'] = activeFlags\n        }\n\n        return additionalProperties\n      })\n      .catch(() => {\n        // Something went wrong getting the flag info - we should capture the event anyways\n        return {}\n      })\n      .then((additionalProperties) => {\n        // No matter what - capture the event\n        _capture({ ...additionalProperties, ...properties, $groups: groups })\n      })\n\n    await capturePromise\n  }\n\n  identify({ distinctId, properties, disableGeoip }: IdentifyMessage): void {\n    // Catch properties passed as $set and move them to the top level\n\n    // promote $set and $set_once to top level\n    const userPropsOnce = properties?.$set_once\n    delete properties?.$set_once\n\n    // if no $set is provided we assume all properties are $set\n    const userProps = properties?.$set || properties\n\n    super.identifyStateless(\n      distinctId,\n      {\n        $set: userProps,\n        $set_once: userPropsOnce,\n      },\n      { disableGeoip }\n    )\n  }\n\n  async identifyImmediate({ distinctId, properties, disableGeoip }: IdentifyMessage): Promise<void> {\n    // promote $set and $set_once to top level\n    const userPropsOnce = properties?.$set_once\n    delete properties?.$set_once\n\n    // if no $set is provided we assume all properties are $set\n    const userProps = properties?.$set || properties\n\n    await super.identifyStatelessImmediate(\n      distinctId,\n      {\n        $set: userProps,\n        $set_once: userPropsOnce,\n      },\n      { disableGeoip }\n    )\n  }\n\n  alias(data: { distinctId: string; alias: string; disableGeoip?: boolean }): void {\n    super.aliasStateless(data.alias, data.distinctId, undefined, { disableGeoip: data.disableGeoip })\n  }\n\n  async aliasImmediate(data: { distinctId: string; alias: string; disableGeoip?: boolean }): Promise<void> {\n    await super.aliasStatelessImmediate(data.alias, data.distinctId, undefined, { disableGeoip: data.disableGeoip })\n  }\n\n  isLocalEvaluationReady(): boolean {\n    return this.featureFlagsPoller?.isLocalEvaluationReady() ?? false\n  }\n\n  async waitForLocalEvaluationReady(timeoutMs: number = THIRTY_SECONDS): Promise<boolean> {\n    if (this.isLocalEvaluationReady()) {\n      return true\n    }\n\n    if (this.featureFlagsPoller === undefined) {\n      return false\n    }\n\n    return new Promise((resolve) => {\n      const timeout = setTimeout(() => {\n        cleanup()\n        resolve(false)\n      }, timeoutMs)\n\n      const cleanup = this._events.on('localEvaluationFlagsLoaded', (count: number) => {\n        clearTimeout(timeout)\n        cleanup()\n        resolve(count > 0)\n      })\n    })\n  }\n\n  async getFeatureFlag(\n    key: string,\n    distinctId: string,\n    options?: {\n      groups?: Record<string, string>\n      personProperties?: Record<string, string>\n      groupProperties?: Record<string, Record<string, string>>\n      onlyEvaluateLocally?: boolean\n      sendFeatureFlagEvents?: boolean\n      disableGeoip?: boolean\n    }\n  ): Promise<FeatureFlagValue | undefined> {\n    const { groups, disableGeoip } = options || {}\n    let { onlyEvaluateLocally, sendFeatureFlagEvents, personProperties, groupProperties } = options || {}\n\n    const adjustedProperties = this.addLocalPersonAndGroupProperties(\n      distinctId,\n      groups,\n      personProperties,\n      groupProperties\n    )\n\n    personProperties = adjustedProperties.allPersonProperties\n    groupProperties = adjustedProperties.allGroupProperties\n\n    // set defaults\n    if (onlyEvaluateLocally == undefined) {\n      onlyEvaluateLocally = false\n    }\n    if (sendFeatureFlagEvents == undefined) {\n      sendFeatureFlagEvents = true\n    }\n\n    let response = await this.featureFlagsPoller?.getFeatureFlag(\n      key,\n      distinctId,\n      groups,\n      personProperties,\n      groupProperties\n    )\n\n    const flagWasLocallyEvaluated = response !== undefined\n    let requestId = undefined\n    let flagDetail: FeatureFlagDetail | undefined = undefined\n    if (!flagWasLocallyEvaluated && !onlyEvaluateLocally) {\n      const remoteResponse = await super.getFeatureFlagDetailStateless(\n        key,\n        distinctId,\n        groups,\n        personProperties,\n        groupProperties,\n        disableGeoip\n      )\n\n      if (remoteResponse === undefined) {\n        return undefined\n      }\n\n      flagDetail = remoteResponse.response\n      response = getFeatureFlagValue(flagDetail)\n      requestId = remoteResponse?.requestId\n    }\n\n    const featureFlagReportedKey = `${key}_${response}`\n\n    if (\n      sendFeatureFlagEvents &&\n      (!(distinctId in this.distinctIdHasSentFlagCalls) ||\n        !this.distinctIdHasSentFlagCalls[distinctId].includes(featureFlagReportedKey))\n    ) {\n      if (Object.keys(this.distinctIdHasSentFlagCalls).length >= this.maxCacheSize) {\n        this.distinctIdHasSentFlagCalls = {}\n      }\n      if (Array.isArray(this.distinctIdHasSentFlagCalls[distinctId])) {\n        this.distinctIdHasSentFlagCalls[distinctId].push(featureFlagReportedKey)\n      } else {\n        this.distinctIdHasSentFlagCalls[distinctId] = [featureFlagReportedKey]\n      }\n      this.capture({\n        distinctId,\n        event: '$feature_flag_called',\n        properties: {\n          $feature_flag: key,\n          $feature_flag_response: response,\n          $feature_flag_id: flagDetail?.metadata?.id,\n          $feature_flag_version: flagDetail?.metadata?.version,\n          $feature_flag_reason: flagDetail?.reason?.description ?? flagDetail?.reason?.code,\n          locally_evaluated: flagWasLocallyEvaluated,\n          [`$feature/${key}`]: response,\n          $feature_flag_request_id: requestId,\n        },\n        groups,\n        disableGeoip,\n      })\n    }\n    return response\n  }\n\n  async getFeatureFlagPayload(\n    key: string,\n    distinctId: string,\n    matchValue?: FeatureFlagValue,\n    options?: {\n      groups?: Record<string, string>\n      personProperties?: Record<string, string>\n      groupProperties?: Record<string, Record<string, string>>\n      onlyEvaluateLocally?: boolean\n      sendFeatureFlagEvents?: boolean\n      disableGeoip?: boolean\n    }\n  ): Promise<JsonType | undefined> {\n    const { groups, disableGeoip } = options || {}\n    let { onlyEvaluateLocally, sendFeatureFlagEvents, personProperties, groupProperties } = options || {}\n\n    const adjustedProperties = this.addLocalPersonAndGroupProperties(\n      distinctId,\n      groups,\n      personProperties,\n      groupProperties\n    )\n\n    personProperties = adjustedProperties.allPersonProperties\n    groupProperties = adjustedProperties.allGroupProperties\n\n    let response = undefined\n\n    const localEvaluationEnabled = this.featureFlagsPoller !== undefined\n    if (localEvaluationEnabled) {\n      // Try to get match value locally if not provided\n      if (!matchValue) {\n        matchValue = await this.getFeatureFlag(key, distinctId, {\n          ...options,\n          onlyEvaluateLocally: true,\n          sendFeatureFlagEvents: false,\n        })\n      }\n\n      if (matchValue) {\n        response = await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(key, matchValue)\n      }\n    }\n    //}\n\n    // set defaults\n    if (onlyEvaluateLocally == undefined) {\n      onlyEvaluateLocally = false\n    }\n    if (sendFeatureFlagEvents == undefined) {\n      sendFeatureFlagEvents = true\n    }\n\n    // set defaults\n    if (onlyEvaluateLocally == undefined) {\n      onlyEvaluateLocally = false\n    }\n\n    const payloadWasLocallyEvaluated = response !== undefined\n\n    if (!payloadWasLocallyEvaluated && !onlyEvaluateLocally) {\n      response = await super.getFeatureFlagPayloadStateless(\n        key,\n        distinctId,\n        groups,\n        personProperties,\n        groupProperties,\n        disableGeoip\n      )\n    }\n    return response\n  }\n\n  async getRemoteConfigPayload(flagKey: string): Promise<JsonType | undefined> {\n    const response = await this.featureFlagsPoller?._requestRemoteConfigPayload(flagKey)\n    if (!response) {\n      return undefined\n    }\n\n    const parsed = await response.json()\n    // The payload from the endpoint is stored as a JSON encoded string. So when we return\n    // it, it's effectively double encoded. As far as we know, we should never get single-encoded\n    // JSON, but we'll be defensive here just in case.\n    if (typeof parsed === 'string') {\n      try {\n        // If the parsed value is a string, try parsing it again to handle double-encoded JSON\n        return JSON.parse(parsed)\n      } catch (e) {\n        // If second parse fails, return the string as is\n        return parsed\n      }\n    }\n    return parsed\n  }\n\n  async isFeatureEnabled(\n    key: string,\n    distinctId: string,\n    options?: {\n      groups?: Record<string, string>\n      personProperties?: Record<string, string>\n      groupProperties?: Record<string, Record<string, string>>\n      onlyEvaluateLocally?: boolean\n      sendFeatureFlagEvents?: boolean\n      disableGeoip?: boolean\n    }\n  ): Promise<boolean | undefined> {\n    const feat = await this.getFeatureFlag(key, distinctId, options)\n    if (feat === undefined) {\n      return undefined\n    }\n    return !!feat || false\n  }\n\n  async getAllFlags(\n    distinctId: string,\n    options?: {\n      groups?: Record<string, string>\n      personProperties?: Record<string, string>\n      groupProperties?: Record<string, Record<string, string>>\n      onlyEvaluateLocally?: boolean\n      disableGeoip?: boolean\n    }\n  ): Promise<Record<string, FeatureFlagValue>> {\n    const response = await this.getAllFlagsAndPayloads(distinctId, options)\n    return response.featureFlags || {}\n  }\n\n  async getAllFlagsAndPayloads(\n    distinctId: string,\n    options?: {\n      groups?: Record<string, string>\n      personProperties?: Record<string, string>\n      groupProperties?: Record<string, Record<string, string>>\n      onlyEvaluateLocally?: boolean\n      disableGeoip?: boolean\n    }\n  ): Promise<PostHogFlagsAndPayloadsResponse> {\n    const { groups, disableGeoip } = options || {}\n    let { onlyEvaluateLocally, personProperties, groupProperties } = options || {}\n\n    const adjustedProperties = this.addLocalPersonAndGroupProperties(\n      distinctId,\n      groups,\n      personProperties,\n      groupProperties\n    )\n\n    personProperties = adjustedProperties.allPersonProperties\n    groupProperties = adjustedProperties.allGroupProperties\n\n    // set defaults\n    if (onlyEvaluateLocally == undefined) {\n      onlyEvaluateLocally = false\n    }\n\n    const localEvaluationResult = await this.featureFlagsPoller?.getAllFlagsAndPayloads(\n      distinctId,\n      groups,\n      personProperties,\n      groupProperties\n    )\n\n    let featureFlags = {}\n    let featureFlagPayloads = {}\n    let fallbackToFlags = true\n    if (localEvaluationResult) {\n      featureFlags = localEvaluationResult.response\n      featureFlagPayloads = localEvaluationResult.payloads\n      fallbackToFlags = localEvaluationResult.fallbackToFlags\n    }\n\n    if (fallbackToFlags && !onlyEvaluateLocally) {\n      const remoteEvaluationResult = await super.getFeatureFlagsAndPayloadsStateless(\n        distinctId,\n        groups,\n        personProperties,\n        groupProperties,\n        disableGeoip\n      )\n      featureFlags = {\n        ...featureFlags,\n        ...(remoteEvaluationResult.flags || {}),\n      }\n      featureFlagPayloads = {\n        ...featureFlagPayloads,\n        ...(remoteEvaluationResult.payloads || {}),\n      }\n    }\n\n    return { featureFlags, featureFlagPayloads }\n  }\n\n  groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }: GroupIdentifyMessage): void {\n    super.groupIdentifyStateless(groupType, groupKey, properties, { disableGeoip }, distinctId)\n  }\n\n  /**\n   * Reloads the feature flag definitions from the server for local evaluation.\n   * This is useful to call if you want to ensure that the feature flags are up to date before calling getFeatureFlag.\n   */\n  async reloadFeatureFlags(): Promise<void> {\n    await this.featureFlagsPoller?.loadFeatureFlags(true)\n  }\n\n  async _shutdown(shutdownTimeoutMs?: number): Promise<void> {\n    this.featureFlagsPoller?.stopPoller()\n    return super._shutdown(shutdownTimeoutMs)\n  }\n\n  private addLocalPersonAndGroupProperties(\n    distinctId: string,\n    groups?: Record<string, string>,\n    personProperties?: Record<string, string>,\n    groupProperties?: Record<string, Record<string, string>>\n  ): { allPersonProperties: Record<string, string>; allGroupProperties: Record<string, Record<string, string>> } {\n    const allPersonProperties = { distinct_id: distinctId, ...(personProperties || {}) }\n\n    const allGroupProperties: Record<string, Record<string, string>> = {}\n    if (groups) {\n      for (const groupName of Object.keys(groups)) {\n        allGroupProperties[groupName] = {\n          $group_key: groups[groupName],\n          ...(groupProperties?.[groupName] || {}),\n        }\n      }\n    }\n\n    return { allPersonProperties, allGroupProperties }\n  }\n\n  captureException(error: unknown, distinctId?: string, additionalProperties?: Record<string | number, any>): void {\n    const syntheticException = new Error('PostHog syntheticException')\n    ErrorTracking.captureException(this, error, { syntheticException }, distinctId, additionalProperties)\n  }\n}\n","// Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry\n// Licensed under the MIT License\n\nimport { GetModuleFn, StackFrame, StackLineParser, StackLineParserFn, StackParser } from './types'\n\n// This was originally forked from https://github.com/csnover/TraceKit, and was largely\n// re-written as part of raven - js.\n//\n// This code was later copied to the JavaScript mono - repo and further modified and\n// refactored over the years.\n\n// Copyright (c) 2013 Onur Can Cakmak onur.cakmak@gmail.com and all TraceKit contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this\n// software and associated documentation files(the 'Software'), to deal in the Software\n// without restriction, including without limitation the rights to use, copy, modify,\n// merge, publish, distribute, sublicense, and / or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following\n// conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies\n// or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\n// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\n// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/\nconst STACKTRACE_FRAME_LIMIT = 50\n\nconst UNKNOWN_FUNCTION = '?'\n\n/** Node Stack line parser */\nfunction node(getModule?: GetModuleFn): StackLineParserFn {\n  const FILENAME_MATCH = /^\\s*[-]{4,}$/\n  const FULL_MATCH = /at (?:async )?(?:(.+?)\\s+\\()?(?:(.+):(\\d+):(\\d+)?|([^)]+))\\)?/\n\n  return (line: string) => {\n    const lineMatch = line.match(FULL_MATCH)\n\n    if (lineMatch) {\n      let object: string | undefined\n      let method: string | undefined\n      let functionName: string | undefined\n      let typeName: string | undefined\n      let methodName: string | undefined\n\n      if (lineMatch[1]) {\n        functionName = lineMatch[1]\n\n        let methodStart = functionName.lastIndexOf('.')\n        if (functionName[methodStart - 1] === '.') {\n          methodStart--\n        }\n\n        if (methodStart > 0) {\n          object = functionName.slice(0, methodStart)\n          method = functionName.slice(methodStart + 1)\n          const objectEnd = object.indexOf('.Module')\n          if (objectEnd > 0) {\n            functionName = functionName.slice(objectEnd + 1)\n            object = object.slice(0, objectEnd)\n          }\n        }\n        typeName = undefined\n      }\n\n      if (method) {\n        typeName = object\n        methodName = method\n      }\n\n      if (method === '<anonymous>') {\n        methodName = undefined\n        functionName = undefined\n      }\n\n      if (functionName === undefined) {\n        methodName = methodName || UNKNOWN_FUNCTION\n        functionName = typeName ? `${typeName}.${methodName}` : methodName\n      }\n\n      let filename = lineMatch[2]?.startsWith('file://') ? lineMatch[2].slice(7) : lineMatch[2]\n      const isNative = lineMatch[5] === 'native'\n\n      // If it's a Windows path, trim the leading slash so that `/C:/foo` becomes `C:/foo`\n      if (filename?.match(/\\/[A-Z]:/)) {\n        filename = filename.slice(1)\n      }\n\n      if (!filename && lineMatch[5] && !isNative) {\n        filename = lineMatch[5]\n      }\n\n      return {\n        filename: filename ? decodeURI(filename) : undefined,\n        module: getModule ? getModule(filename) : undefined,\n        function: functionName,\n        lineno: _parseIntOrUndefined(lineMatch[3]),\n        colno: _parseIntOrUndefined(lineMatch[4]),\n        in_app: filenameIsInApp(filename || '', isNative),\n        platform: 'node:javascript',\n      }\n    }\n\n    if (line.match(FILENAME_MATCH)) {\n      return {\n        filename: line,\n        platform: 'node:javascript',\n      }\n    }\n\n    return undefined\n  }\n}\n\n/**\n * Does this filename look like it's part of the app code?\n */\nfunction filenameIsInApp(filename: string, isNative: boolean = false): boolean {\n  const isInternal =\n    isNative ||\n    (filename &&\n      // It's not internal if it's an absolute linux path\n      !filename.startsWith('/') &&\n      // It's not internal if it's an absolute windows path\n      !filename.match(/^[A-Z]:/) &&\n      // It's not internal if the path is starting with a dot\n      !filename.startsWith('.') &&\n      // It's not internal if the frame has a protocol. In node, this is usually the case if the file got pre-processed with a bundler like webpack\n      !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\\-+])*:\\/\\//)) // Schema from: https://stackoverflow.com/a/3641782\n\n  // in_app is all that's not an internal Node function or a module within node_modules\n  // note that isNative appears to return true even for node core libraries\n  // see https://github.com/getsentry/raven-node/issues/176\n\n  return !isInternal && filename !== undefined && !filename.includes('node_modules/')\n}\n\nfunction _parseIntOrUndefined(input: string | undefined): number | undefined {\n  return parseInt(input || '', 10) || undefined\n}\n\nfunction nodeStackLineParser(getModule?: GetModuleFn): StackLineParser {\n  return [90, node(getModule)]\n}\n\nexport function createStackParser(getModule?: GetModuleFn): StackParser {\n  const parsers = [nodeStackLineParser(getModule)]\n  const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map((p) => p[1])\n\n  return (stack: string, skipFirstLines: number = 0): StackFrame[] => {\n    const frames: StackFrame[] = []\n    const lines = stack.split('\\n')\n\n    for (let i = skipFirstLines; i < lines.length; i++) {\n      const line = lines[i] as string\n      // Ignore lines over 1kb as they are unlikely to be stack frames.\n      if (line.length > 1024) {\n        continue\n      }\n\n      // https://github.com/getsentry/sentry-javascript/issues/5459\n      // Remove webpack (error: *) wrappers\n      const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line\n\n      // https://github.com/getsentry/sentry-javascript/issues/7813\n      // Skip Error: lines\n      if (cleanedLine.match(/\\S*Error: /)) {\n        continue\n      }\n\n      for (const parser of sortedParsers) {\n        const frame = parser(cleanedLine)\n\n        if (frame) {\n          frames.push(frame)\n          break\n        }\n      }\n\n      if (frames.length >= STACKTRACE_FRAME_LIMIT) {\n        break\n      }\n    }\n\n    return reverseAndStripFrames(frames)\n  }\n}\n\nfunction reverseAndStripFrames(stack: ReadonlyArray<StackFrame>): StackFrame[] {\n  if (!stack.length) {\n    return []\n  }\n\n  const localStack = Array.from(stack)\n\n  localStack.reverse()\n\n  return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({\n    ...frame,\n    filename: frame.filename || getLastStackFrame(localStack).filename,\n    function: frame.function || UNKNOWN_FUNCTION,\n  }))\n}\n\nfunction getLastStackFrame(arr: StackFrame[]): StackFrame {\n  return arr[arr.length - 1] || {}\n}\n","export * from '../exports'\n\nimport ErrorTracking from '../extensions/error-tracking'\n\nimport { PostHogBackendClient } from '../client'\nimport { createStackParser } from '../extensions/error-tracking/stack-parser'\n\nErrorTracking.stackParser = createStackParser()\nErrorTracking.frameModifiers = []\n\nexport class PostHog extends PostHogBackendClient {\n  getLibraryId(): string {\n    return 'posthog-edge'\n  }\n}\n"],"names":["NAME","createEventProcessor","_posthog","organization","projectId","prefix","severityAllowList","event","shouldProcessLevel","includes","level","tags","userId","PostHogSentryIntegration","POSTHOG_ID_TAG","undefined","uiHost","options","host","personUrl","URL","apiKey","toString","exceptions","exception","values","exceptionList","map","stacktrace","type","frames","frame","platform","properties","$exception_message","value","message","$exception_type","$exception_personURL","$exception_level","$exception_list","$sentry_event_id","event_id","$sentry_exception","$sentry_exception_message","$sentry_exception_type","$sentry_tags","capture","distinctId","sentryIntegration","processor","name","processEvent","constructor","setupOnce","addGlobalEventProcessor","getCurrentHub","getClient","getDsn","makeUncaughtExceptionHandler","captureFn","onFatalFn","calledFatalError","Object","assign","error","userProvidedListenersCount","global","process","listeners","filter","listener","_posthogErrorHandler","length","processWouldExit","mechanism","handled","addUncaughtExceptionListener","on","addUnhandledRejectionListener","reason","parsedStackResults","lastKeysCount","cachedFilenameChunkIds","getFilenameToChunkIdMap","stackParser","chunkIdMap","globalThis","_posthogChunkIds","console","chunkIdKeys","keys","reduce","acc","stackKey","result","parsedStack","i","stackFrame","filename","chunkId","isEvent","candidate","Event","isInstanceOf","isPlainObject","isBuiltin","isError","prototype","call","Error","base","isErrorEvent","className","propertiesFromUnknownInput","frameModifiers","input","hint","providedMechanism","errorList","getErrorList","Promise","all","exceptionFromError","getError","cause","synthetic","errorFromProp","getErrorPropertyFromObject","getMessageForObject","ex","syntheticException","obj","prop","hasOwnProperty","extractExceptionKeysForMessage","getObjectClassName","getPrototypeOf","e","maxLength","convertToPlainObject","sort","firstKey","truncate","includedKeys","serialized","slice","join","str","max","stack","getOwnProperties","newObj","target","serializeEventTarget","currentTarget","extractedProps","property","_oO","parseStackFrames","modifier","applyChunkIds","parser","filenameChunkIdMap","forEach","chunk_id","SHUTDOWN_TIMEOUT","ErrorTracking","captureException","client","additionalProperties","$process_person_profile","exceptionProperties","uuidv7","_exceptionAutocaptureEnabled","enableExceptionAutocapture","startAutocaptureIfEnabled","isEnabled","onException","bind","onFatalError","shutdown","isDisabled","setupExpressErrorHandler","app","use","_","__","next","Lazy","factory","getValue","initializationPromise","isInitialized","waitForInitialization","nodeCrypto","getNodeCrypto","webCrypto","crypto","subtle","webcrypto","getWebCrypto","hashSHA1","text","createHash","update","digest","hashBuffer","TextEncoder","encode","hashArray","Array","from","Uint8Array","byte","padStart","SIXTY_SECONDS","LONG_SCALE","NULL_VALUES_ALLOWED_OPERATORS","ClientError","captureStackTrace","setPrototypeOf","InconclusiveMatchError","FeatureFlagsPoller","pollingInterval","personalApiKey","projectApiKey","timeout","customHeaders","debugMode","shouldBeginExponentialBackoff","backOffCount","featureFlags","featureFlagsByKey","groupTypeMapping","cohorts","loadedSuccessfullyOnce","poller","fetch","onError","onLoad","loadFeatureFlags","debug","enabled","logMsgIfDebug","fn","getFeatureFlag","key","groups","personProperties","groupProperties","response","featureFlag","flag","computeFlagLocally","computeFeatureFlagPayloadLocally","matchValue","filters","payloads","JSON","parse","getAllFlagsAndPayloads","fallbackToFlags","matchPayload","ensure_experience_continuity","active","flagFilters","aggregation_group_type_index","groupName","String","warn","focusedGroupProperties","matchFeatureFlagProperties","flagConditions","isInconclusive","sortedFlagConditions","conditionA","conditionB","AHasVariantOverride","variant","BHasVariantOverride","condition","isConditionMatch","variantOverride","flagVariants","multivariate","variants","some","getMatchingVariant","rolloutPercentage","rollout_percentage","warnFunction","msg","propertyType","matches","matchCohort","matchProperty","_hash","hashValue","matchingVariant","variantLookupTable","find","valueMin","valueMax","lookupTable","multivariates","push","forceReload","_loadFeatureFlags","isLocalEvaluationReady","getPollingInterval","Math","min","clearTimeout","setTimeout","res","_requestFeatureFlagDefinitions","status","responseJson","json","stringify","flags","curr","group_type_mapping","err","getPersonalApiKeyRequestOptions","method","headers","Authorization","url","abortTimeout","controller","AbortController","safeSetTimeout","abort","signal","stopPoller","_requestRemoteConfigPayload","flagKey","salt","hashString","parseInt","propertyValues","operator","overrideValue","computeExactMatch","isArray","val","toLowerCase","compare","lhs","rhs","isValidRegex","match","parsedValue","parseFloat","parsedDate","relativeDateParseForFeatureFlagMatching","convertToDateTime","overrideDate","cohortProperties","cohortId","propertyGroup","matchPropertyGroup","propertyGroupType","errorMatchingLocally","negation","regex","RegExp","Date","date","isNaN","valueOf","parsedDt","toISOString","number","interval","setUTCHours","getUTCHours","setUTCDate","getUTCDate","setUTCMonth","getUTCMonth","setUTCFullYear","getUTCFullYear","PostHogMemoryStorage","_memoryStorage","getProperty","setProperty","MINIMUM_POLLING_INTERVAL","THIRTY_SECONDS","MAX_CACHE_SIZE","PostHogBackendClient","PostHogCoreStateless","featureFlagsPollingInterval","featureFlagsPoller","requestTimeout","_events","emit","count","getCustomHeaders","errorTracking","distinctIdHasSentFlagCalls","maxCacheSize","getPersistedProperty","setPersistedProperty","getLibraryVersion","version","getCustomUserAgent","getLibraryId","enable","optIn","disable","optOut","props","sendFeatureFlags","timestamp","disableGeoip","uuid","_capture","captureStateless","_getFlags","getFeatureFlagsStateless","capturePromise","resolve","then","groupsWithStringValues","entries","getAllFlags","onlyEvaluateLocally","feature","activeFlags","catch","$groups","addPendingPromise","captureImmediate","captureStatelessImmediate","identify","userPropsOnce","$set_once","userProps","$set","identifyStateless","identifyImmediate","identifyStatelessImmediate","alias","data","aliasStateless","aliasImmediate","aliasStatelessImmediate","waitForLocalEvaluationReady","timeoutMs","cleanup","sendFeatureFlagEvents","adjustedProperties","addLocalPersonAndGroupProperties","allPersonProperties","allGroupProperties","flagWasLocallyEvaluated","requestId","flagDetail","remoteResponse","getFeatureFlagDetailStateless","getFeatureFlagValue","featureFlagReportedKey","$feature_flag","$feature_flag_response","$feature_flag_id","metadata","id","$feature_flag_version","$feature_flag_reason","description","code","locally_evaluated","$feature_flag_request_id","getFeatureFlagPayload","localEvaluationEnabled","payloadWasLocallyEvaluated","getFeatureFlagPayloadStateless","getRemoteConfigPayload","parsed","isFeatureEnabled","feat","localEvaluationResult","featureFlagPayloads","remoteEvaluationResult","getFeatureFlagsAndPayloadsStateless","groupIdentify","groupType","groupKey","groupIdentifyStateless","reloadFeatureFlags","_shutdown","shutdownTimeoutMs","distinct_id","$group_key","WEBPACK_ERROR_REGEXP","STACKTRACE_FRAME_LIMIT","UNKNOWN_FUNCTION","node","getModule","FILENAME_MATCH","FULL_MATCH","line","lineMatch","object","functionName","typeName","methodName","methodStart","lastIndexOf","objectEnd","indexOf","startsWith","isNative","decodeURI","module","function","lineno","_parseIntOrUndefined","colno","in_app","filenameIsInApp","isInternal","nodeStackLineParser","createStackParser","parsers","sortedParsers","a","b","p","skipFirstLines","lines","split","cleanedLine","test","replace","reverseAndStripFrames","localStack","reverse","getLastStackFrame","arr","PostHog"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;;AAEG;AACH;;;;;;;;;;;;;;;;;;;AAmBG;AAoDH,MAAMA,IAAI,GAAG,cAAc,CAAA;SAEXC,oBAAoBA,CAClCC,QAA8B,EAC9B;EAAEC,YAAY;EAAEC,SAAS;EAAEC,MAAM;EAAEC,iBAAiB,GAAG,CAAC,OAAO,CAAA;IAAgC,EAAE,EAAA;AAEjG,EAAA,OAAQC,KAAK,IAAI;AACf,IAAA,MAAMC,kBAAkB,GAAGF,iBAAiB,KAAK,GAAG,IAAIA,iBAAiB,CAACG,QAAQ,CAACF,KAAK,CAACG,KAAK,CAAC,CAAA;IAC/F,IAAI,CAACF,kBAAkB,EAAE;AACvB,MAAA,OAAOD,KAAK,CAAA;AACb,KAAA;AACD,IAAA,IAAI,CAACA,KAAK,CAACI,IAAI,EAAE;AACfJ,MAAAA,KAAK,CAAC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