posthog-node 5.8.8 → 5.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/dist/{index.d.ts → client.d.ts} +7 -378
  2. package/dist/client.d.ts.map +1 -0
  3. package/dist/client.js +481 -0
  4. package/dist/client.mjs +437 -0
  5. package/dist/entrypoints/index.edge.d.ts +6 -0
  6. package/dist/entrypoints/index.edge.d.ts.map +1 -0
  7. package/dist/entrypoints/index.edge.js +89 -0
  8. package/dist/entrypoints/index.edge.mjs +12 -0
  9. package/dist/entrypoints/index.node.d.ts +6 -0
  10. package/dist/entrypoints/index.node.d.ts.map +1 -0
  11. package/dist/entrypoints/index.node.js +99 -0
  12. package/dist/entrypoints/index.node.mjs +16 -0
  13. package/dist/exports.d.ts +4 -0
  14. package/dist/exports.d.ts.map +1 -0
  15. package/dist/exports.js +78 -0
  16. package/dist/exports.mjs +3 -0
  17. package/dist/extensions/error-tracking/autocapture.d.ts +4 -0
  18. package/dist/extensions/error-tracking/autocapture.d.ts.map +1 -0
  19. package/dist/extensions/error-tracking/autocapture.js +68 -0
  20. package/dist/extensions/error-tracking/autocapture.mjs +31 -0
  21. package/dist/extensions/error-tracking/chunk-ids.d.ts +5 -0
  22. package/dist/extensions/error-tracking/chunk-ids.d.ts.map +1 -0
  23. package/dist/extensions/error-tracking/chunk-ids.js +68 -0
  24. package/dist/extensions/error-tracking/chunk-ids.mjs +34 -0
  25. package/dist/extensions/error-tracking/context-lines.node.d.ts +5 -0
  26. package/dist/extensions/error-tracking/context-lines.node.d.ts.map +1 -0
  27. package/dist/extensions/error-tracking/context-lines.node.js +227 -0
  28. package/dist/extensions/error-tracking/context-lines.node.mjs +187 -0
  29. package/dist/extensions/error-tracking/error-conversion.d.ts +4 -0
  30. package/dist/extensions/error-tracking/error-conversion.d.ts.map +1 -0
  31. package/dist/extensions/error-tracking/error-conversion.js +183 -0
  32. package/dist/extensions/error-tracking/error-conversion.mjs +146 -0
  33. package/dist/extensions/error-tracking/get-module.node.d.ts +3 -0
  34. package/dist/extensions/error-tracking/get-module.node.d.ts.map +1 -0
  35. package/dist/extensions/error-tracking/get-module.node.js +57 -0
  36. package/dist/extensions/error-tracking/get-module.node.mjs +23 -0
  37. package/dist/extensions/error-tracking/index.d.ts +20 -0
  38. package/dist/extensions/error-tracking/index.d.ts.map +1 -0
  39. package/dist/extensions/error-tracking/index.js +97 -0
  40. package/dist/extensions/error-tracking/index.mjs +63 -0
  41. package/dist/extensions/error-tracking/reduceable-cache.d.ts +13 -0
  42. package/dist/extensions/error-tracking/reduceable-cache.d.ts.map +1 -0
  43. package/dist/extensions/error-tracking/reduceable-cache.js +57 -0
  44. package/dist/extensions/error-tracking/reduceable-cache.mjs +23 -0
  45. package/dist/extensions/error-tracking/stack-parser.d.ts +3 -0
  46. package/dist/extensions/error-tracking/stack-parser.d.ts.map +1 -0
  47. package/dist/extensions/error-tracking/stack-parser.js +148 -0
  48. package/dist/extensions/error-tracking/stack-parser.mjs +114 -0
  49. package/dist/extensions/error-tracking/type-checking.d.ts +8 -0
  50. package/dist/extensions/error-tracking/type-checking.d.ts.map +1 -0
  51. package/dist/extensions/error-tracking/type-checking.js +80 -0
  52. package/dist/extensions/error-tracking/type-checking.mjs +31 -0
  53. package/dist/extensions/error-tracking/types.d.ts +61 -0
  54. package/dist/extensions/error-tracking/types.d.ts.map +1 -0
  55. package/dist/extensions/error-tracking/types.js +43 -0
  56. package/dist/extensions/error-tracking/types.mjs +9 -0
  57. package/dist/extensions/express.d.ts +17 -0
  58. package/dist/extensions/express.d.ts.map +1 -0
  59. package/dist/extensions/express.js +61 -0
  60. package/dist/extensions/express.mjs +17 -0
  61. package/dist/extensions/feature-flags/crypto-helpers.d.ts +3 -0
  62. package/dist/extensions/feature-flags/crypto-helpers.d.ts.map +1 -0
  63. package/dist/extensions/feature-flags/crypto-helpers.js +77 -0
  64. package/dist/extensions/feature-flags/crypto-helpers.mjs +22 -0
  65. package/dist/extensions/feature-flags/crypto.d.ts +2 -0
  66. package/dist/extensions/feature-flags/crypto.d.ts.map +1 -0
  67. package/dist/extensions/feature-flags/crypto.js +47 -0
  68. package/dist/extensions/feature-flags/crypto.mjs +13 -0
  69. package/dist/extensions/feature-flags/feature-flags.d.ts +89 -0
  70. package/dist/extensions/feature-flags/feature-flags.d.ts.map +1 -0
  71. package/dist/extensions/feature-flags/feature-flags.js +529 -0
  72. package/dist/extensions/feature-flags/feature-flags.mjs +483 -0
  73. package/dist/extensions/feature-flags/lazy.d.ts +24 -0
  74. package/dist/extensions/feature-flags/lazy.d.ts.map +1 -0
  75. package/dist/extensions/feature-flags/lazy.js +60 -0
  76. package/dist/extensions/feature-flags/lazy.mjs +26 -0
  77. package/dist/extensions/sentry-integration.d.ts +54 -0
  78. package/dist/extensions/sentry-integration.d.ts.map +1 -0
  79. package/dist/extensions/sentry-integration.js +113 -0
  80. package/dist/extensions/sentry-integration.mjs +73 -0
  81. package/dist/storage-memory.d.ts +7 -0
  82. package/dist/storage-memory.d.ts.map +1 -0
  83. package/dist/storage-memory.js +46 -0
  84. package/dist/storage-memory.mjs +12 -0
  85. package/dist/types.d.ts +253 -0
  86. package/dist/types.d.ts.map +1 -0
  87. package/dist/types.js +18 -0
  88. package/dist/types.mjs +0 -0
  89. package/dist/utils/logger.d.ts +3 -0
  90. package/dist/utils/logger.d.ts.map +1 -0
  91. package/dist/utils/logger.js +63 -0
  92. package/dist/utils/logger.mjs +29 -0
  93. package/dist/version.d.ts +2 -0
  94. package/dist/version.d.ts.map +1 -0
  95. package/dist/version.js +36 -0
  96. package/dist/version.mjs +2 -0
  97. package/package.json +32 -31
  98. package/src/client.ts +1532 -0
  99. package/src/entrypoints/index.edge.ts +15 -0
  100. package/src/entrypoints/index.node.ts +17 -0
  101. package/src/exports.ts +3 -0
  102. package/src/extensions/error-tracking/autocapture.ts +65 -0
  103. package/src/extensions/error-tracking/chunk-ids.ts +58 -0
  104. package/src/extensions/error-tracking/context-lines.node.ts +392 -0
  105. package/src/extensions/error-tracking/error-conversion.ts +291 -0
  106. package/src/extensions/error-tracking/get-module.node.ts +57 -0
  107. package/src/extensions/error-tracking/index.ts +103 -0
  108. package/src/extensions/error-tracking/reduceable-cache.ts +39 -0
  109. package/src/extensions/error-tracking/stack-parser.ts +212 -0
  110. package/src/extensions/error-tracking/type-checking.ts +40 -0
  111. package/src/extensions/error-tracking/types.ts +71 -0
  112. package/src/extensions/express.ts +39 -0
  113. package/src/extensions/feature-flags/crypto-helpers.ts +36 -0
  114. package/src/extensions/feature-flags/crypto.ts +22 -0
  115. package/src/extensions/feature-flags/feature-flags.ts +1003 -0
  116. package/src/extensions/feature-flags/lazy.ts +55 -0
  117. package/src/extensions/sentry-integration.ts +216 -0
  118. package/src/storage-memory.ts +13 -0
  119. package/src/types.ts +294 -0
  120. package/src/utils/logger.ts +39 -0
  121. package/src/version.ts +1 -0
  122. package/dist/edge/index.cjs +0 -3150
  123. package/dist/edge/index.cjs.map +0 -1
  124. package/dist/edge/index.mjs +0 -3144
  125. package/dist/edge/index.mjs.map +0 -1
  126. package/dist/node/index.cjs +0 -3556
  127. package/dist/node/index.cjs.map +0 -1
  128. package/dist/node/index.mjs +0 -3550
  129. package/dist/node/index.mjs.map +0 -1
@@ -0,0 +1,55 @@
1
+ /**
2
+ * A lazy value that is only computed when needed. Inspired by C#'s Lazy<T> class.
3
+ */
4
+ export class Lazy<T> {
5
+ private value: T | undefined
6
+ private factory: () => Promise<T>
7
+ private initializationPromise: Promise<T> | undefined
8
+
9
+ constructor(factory: () => Promise<T>) {
10
+ this.factory = factory
11
+ }
12
+
13
+ /**
14
+ * Gets the value, initializing it if necessary.
15
+ * Multiple concurrent calls will share the same initialization promise.
16
+ */
17
+ async getValue(): Promise<T> {
18
+ if (this.value !== undefined) {
19
+ return this.value
20
+ }
21
+
22
+ if (this.initializationPromise === undefined) {
23
+ this.initializationPromise = (async () => {
24
+ try {
25
+ const result = await this.factory()
26
+ this.value = result
27
+ return result
28
+ } finally {
29
+ // Clear the promise so we can retry if needed
30
+ this.initializationPromise = undefined
31
+ }
32
+ })()
33
+ }
34
+
35
+ return this.initializationPromise
36
+ }
37
+
38
+ /**
39
+ * Returns true if the value has been initialized.
40
+ */
41
+ isInitialized(): boolean {
42
+ return this.value !== undefined
43
+ }
44
+
45
+ /**
46
+ * Returns a promise that resolves when the value is initialized.
47
+ * If already initialized, resolves immediately.
48
+ */
49
+ async waitForInitialization(): Promise<void> {
50
+ if (this.isInitialized()) {
51
+ return
52
+ }
53
+ await this.getValue()
54
+ }
55
+ }
@@ -0,0 +1,216 @@
1
+ /**
2
+ * @file Adapted from [posthog-js](https://github.com/PostHog/posthog-js/blob/8157df935a4d0e71d2fefef7127aa85ee51c82d1/src/extensions/sentry-integration.ts) with modifications for the Node SDK.
3
+ */
4
+ /**
5
+ * Integrate Sentry with PostHog. This will add a direct link to the person in Sentry, and an $exception event in PostHog.
6
+ *
7
+ * ### Usage
8
+ *
9
+ * Sentry.init({
10
+ * dsn: 'https://example',
11
+ * integrations: [
12
+ * new PostHogSentryIntegration(posthog)
13
+ * ]
14
+ * })
15
+ *
16
+ * Sentry.setTag(PostHogSentryIntegration.POSTHOG_ID_TAG, 'some distinct id');
17
+ *
18
+ * @param {Object} [posthog] The posthog object
19
+ * @param {string} [organization] Optional: The Sentry organization, used to send a direct link from PostHog to Sentry
20
+ * @param {Number} [projectId] Optional: The Sentry project id, used to send a direct link from PostHog to Sentry
21
+ * @param {string} [prefix] Optional: Url of a self-hosted sentry instance (default: https://sentry.io/organizations/)
22
+ * @param {SeverityLevel[] | '*'} [severityAllowList] Optional: send events matching the provided levels. Use '*' to send all events (default: ['error'])
23
+ * @param {boolean} [sendExceptionsToPostHog] Optional: capture exceptions as events in PostHog (default: true)
24
+ */
25
+
26
+ import { SeverityLevel } from './error-tracking/types'
27
+ import { type PostHogBackendClient } from '../client'
28
+
29
+ // NOTE - we can't import from @sentry/types because it changes frequently and causes clashes
30
+ // We only use a small subset of the types, so we can just define the integration overall and use any for the rest
31
+
32
+ // import {
33
+ // Event as _SentryEvent,
34
+ // EventProcessor as _SentryEventProcessor,
35
+ // Exception as _SentryException,
36
+ // Hub as _SentryHub,
37
+ // Primitive as _SentryPrimitive,
38
+ // Integration as _SentryIntegration,
39
+ // IntegrationClass as _SentryIntegrationClass,
40
+ // } from '@sentry/types'
41
+
42
+ // Uncomment the above and comment the below to get type checking for development
43
+
44
+ type _SentryEvent = any
45
+ type _SentryEventProcessor = any
46
+ type _SentryException = any
47
+ type _SentryHub = any
48
+ type _SentryPrimitive = any
49
+
50
+ interface _SentryIntegration {
51
+ name: string
52
+ processEvent(event: _SentryEvent): _SentryEvent
53
+ }
54
+
55
+ interface _SentryIntegrationClass {
56
+ name: string
57
+ setupOnce(addGlobalEventProcessor: (callback: _SentryEventProcessor) => void, getCurrentHub: () => _SentryHub): void
58
+ }
59
+
60
+ interface SentryExceptionProperties {
61
+ $sentry_event_id?: string
62
+ $sentry_exception?: { values?: _SentryException[] }
63
+ $sentry_exception_message?: string
64
+ $sentry_exception_type?: string
65
+ $sentry_tags: { [key: string]: _SentryPrimitive }
66
+ $sentry_url?: string
67
+ }
68
+
69
+ export type SentryIntegrationOptions = {
70
+ organization?: string
71
+ projectId?: number
72
+ prefix?: string
73
+ severityAllowList?: SeverityLevel[] | '*'
74
+ sendExceptionsToPostHog?: boolean
75
+ }
76
+
77
+ const NAME = 'posthog-node'
78
+
79
+ export function createEventProcessor(
80
+ _posthog: PostHogBackendClient,
81
+ {
82
+ organization,
83
+ projectId,
84
+ prefix,
85
+ severityAllowList = ['error'],
86
+ sendExceptionsToPostHog = true,
87
+ }: SentryIntegrationOptions = {}
88
+ ): (event: _SentryEvent) => _SentryEvent {
89
+ return (event) => {
90
+ const shouldProcessLevel = severityAllowList === '*' || severityAllowList.includes(event.level)
91
+ if (!shouldProcessLevel) {
92
+ return event
93
+ }
94
+ if (!event.tags) {
95
+ event.tags = {}
96
+ }
97
+
98
+ // Get the PostHog user ID from a specific tag, which users can set on their Sentry scope as they need.
99
+ const userId = event.tags[PostHogSentryIntegration.POSTHOG_ID_TAG]
100
+ if (userId === undefined) {
101
+ // 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.
102
+ return event
103
+ }
104
+
105
+ const uiHost = _posthog.options.host ?? 'https://us.i.posthog.com'
106
+ const personUrl = new URL(`/project/${_posthog.apiKey}/person/${userId}`, uiHost).toString()
107
+
108
+ event.tags['PostHog Person URL'] = personUrl
109
+
110
+ const exceptions: _SentryException[] = event.exception?.values || []
111
+
112
+ const exceptionList = exceptions.map((exception) => ({
113
+ ...exception,
114
+ stacktrace: exception.stacktrace
115
+ ? {
116
+ ...exception.stacktrace,
117
+ type: 'raw',
118
+ frames: (exception.stacktrace.frames || []).map((frame: any) => {
119
+ return { ...frame, platform: 'node:javascript' }
120
+ }),
121
+ }
122
+ : undefined,
123
+ }))
124
+
125
+ const properties: SentryExceptionProperties & {
126
+ // two properties added to match any exception auto-capture
127
+ // added manually to avoid any dependency on the lazily loaded content
128
+ $exception_message: any
129
+ $exception_type: any
130
+ $exception_list: any
131
+ $exception_personURL: string
132
+ $exception_level: SeverityLevel
133
+ } = {
134
+ // PostHog Exception Properties,
135
+ $exception_message: exceptions[0]?.value || event.message,
136
+ $exception_type: exceptions[0]?.type,
137
+ $exception_personURL: personUrl,
138
+ $exception_level: event.level,
139
+ $exception_list: exceptionList,
140
+ // Sentry Exception Properties
141
+ $sentry_event_id: event.event_id,
142
+ $sentry_exception: event.exception,
143
+ $sentry_exception_message: exceptions[0]?.value || event.message,
144
+ $sentry_exception_type: exceptions[0]?.type,
145
+ $sentry_tags: event.tags,
146
+ }
147
+
148
+ if (organization && projectId) {
149
+ properties['$sentry_url'] =
150
+ (prefix || 'https://sentry.io/organizations/') +
151
+ organization +
152
+ '/issues/?project=' +
153
+ projectId +
154
+ '&query=' +
155
+ event.event_id
156
+ }
157
+
158
+ if (sendExceptionsToPostHog) {
159
+ _posthog.capture({ event: '$exception', distinctId: userId, properties })
160
+ }
161
+
162
+ return event
163
+ }
164
+ }
165
+
166
+ // V8 integration - function based
167
+ export function sentryIntegration(
168
+ _posthog: PostHogBackendClient,
169
+ options?: SentryIntegrationOptions
170
+ ): _SentryIntegration {
171
+ const processor = createEventProcessor(_posthog, options)
172
+ return {
173
+ name: NAME,
174
+ processEvent(event) {
175
+ return processor(event)
176
+ },
177
+ }
178
+ }
179
+
180
+ // V7 integration - class based
181
+ export class PostHogSentryIntegration implements _SentryIntegrationClass {
182
+ public readonly name = NAME
183
+
184
+ public static readonly POSTHOG_ID_TAG = 'posthog_distinct_id'
185
+
186
+ public setupOnce: (
187
+ addGlobalEventProcessor: (callback: _SentryEventProcessor) => void,
188
+ getCurrentHub: () => _SentryHub
189
+ ) => void
190
+
191
+ constructor(
192
+ _posthog: PostHogBackendClient,
193
+ organization?: string,
194
+ prefix?: string,
195
+ severityAllowList?: SeverityLevel[] | '*',
196
+ sendExceptionsToPostHog?: boolean
197
+ ) {
198
+ // setupOnce gets called by Sentry when it intializes the plugin
199
+ this.name = NAME
200
+ this.setupOnce = function (
201
+ addGlobalEventProcessor: (callback: _SentryEventProcessor) => void,
202
+ getCurrentHub: () => _SentryHub
203
+ ) {
204
+ const projectId = getCurrentHub()?.getClient()?.getDsn()?.projectId
205
+ addGlobalEventProcessor(
206
+ createEventProcessor(_posthog, {
207
+ organization,
208
+ projectId,
209
+ prefix,
210
+ severityAllowList,
211
+ sendExceptionsToPostHog: sendExceptionsToPostHog ?? true,
212
+ })
213
+ )
214
+ }
215
+ }
216
+ }
@@ -0,0 +1,13 @@
1
+ import { PostHogPersistedProperty } from '@posthog/core'
2
+
3
+ export class PostHogMemoryStorage {
4
+ private _memoryStorage: { [key: string]: any | undefined } = {}
5
+
6
+ getProperty(key: PostHogPersistedProperty): any | undefined {
7
+ return this._memoryStorage[key]
8
+ }
9
+
10
+ setProperty(key: PostHogPersistedProperty, value: any | null): void {
11
+ this._memoryStorage[key] = value !== null ? value : undefined
12
+ }
13
+ }
package/src/types.ts ADDED
@@ -0,0 +1,294 @@
1
+ import type {
2
+ PostHogCoreOptions,
3
+ FeatureFlagValue,
4
+ JsonType,
5
+ PostHogFetchOptions,
6
+ PostHogFetchResponse,
7
+ } from '@posthog/core'
8
+
9
+ export interface IdentifyMessage {
10
+ distinctId: string
11
+ properties?: Record<string | number, any>
12
+ disableGeoip?: boolean
13
+ }
14
+
15
+ export interface SendFeatureFlagsOptions {
16
+ onlyEvaluateLocally?: boolean
17
+ personProperties?: Record<string, any>
18
+ groupProperties?: Record<string, Record<string, any>>
19
+ flagKeys?: string[]
20
+ }
21
+
22
+ export interface EventMessage extends IdentifyMessage {
23
+ event: string
24
+ groups?: Record<string, string | number> // Mapping of group type to group id
25
+ sendFeatureFlags?: boolean | SendFeatureFlagsOptions
26
+ timestamp?: Date
27
+ uuid?: string
28
+ }
29
+
30
+ export interface GroupIdentifyMessage {
31
+ groupType: string
32
+ groupKey: string // Unique identifier for the group
33
+ properties?: Record<string | number, any>
34
+ distinctId?: string // optional distinctId to associate message with a person
35
+ disableGeoip?: boolean
36
+ }
37
+
38
+ export type PropertyGroup = {
39
+ type: 'AND' | 'OR'
40
+ values: PropertyGroup[] | FlagProperty[]
41
+ }
42
+
43
+ export type FlagProperty = {
44
+ key: string
45
+ type?: string
46
+ value: FlagPropertyValue
47
+ operator?: string
48
+ negation?: boolean
49
+ dependency_chain?: string[]
50
+ }
51
+
52
+ export type FlagPropertyValue = string | number | (string | number)[] | boolean
53
+
54
+ export type FeatureFlagCondition = {
55
+ properties: FlagProperty[]
56
+ rollout_percentage?: number
57
+ variant?: string
58
+ }
59
+
60
+ export type BeforeSendFn = (event: EventMessage | null) => EventMessage | null
61
+
62
+ export type PostHogOptions = PostHogCoreOptions & {
63
+ persistence?: 'memory'
64
+ personalApiKey?: string
65
+ privacyMode?: boolean
66
+ enableExceptionAutocapture?: boolean
67
+ // The interval in milliseconds between polls for refreshing feature flag definitions. Defaults to 30 seconds.
68
+ featureFlagsPollingInterval?: number
69
+ // Maximum size of cache that deduplicates $feature_flag_called calls per user.
70
+ maxCacheSize?: number
71
+ fetch?: (url: string, options: PostHogFetchOptions) => Promise<PostHogFetchResponse>
72
+ // Whether to enable feature flag polling for local evaluation by default. Defaults to true when personalApiKey is provided.
73
+ // We recommend setting this to false if you are only using the personalApiKey for evaluating remote config payloads via `getRemoteConfigPayload` and not using local evaluation.
74
+ enableLocalEvaluation?: boolean
75
+ /**
76
+ * Allows modification or dropping of events before they're sent to PostHog.
77
+ * If an array is provided, the functions are run in order.
78
+ * If a function returns null, the event will be dropped.
79
+ */
80
+ before_send?: BeforeSendFn | BeforeSendFn[]
81
+ }
82
+
83
+ export type PostHogFeatureFlag = {
84
+ id: number
85
+ name: string
86
+ key: string
87
+ filters?: {
88
+ aggregation_group_type_index?: number
89
+ groups?: FeatureFlagCondition[]
90
+ multivariate?: {
91
+ variants: {
92
+ key: string
93
+ rollout_percentage: number
94
+ }[]
95
+ }
96
+ payloads?: Record<string, string>
97
+ }
98
+ deleted: boolean
99
+ active: boolean
100
+ rollout_percentage: null | number
101
+ ensure_experience_continuity: boolean
102
+ experiment_set: number[]
103
+ }
104
+
105
+ export interface IPostHog {
106
+ /**
107
+ * @description Capture allows you to capture anything a user does within your system,
108
+ * which you can later use in PostHog to find patterns in usage,
109
+ * work out which features to improve or where people are giving up.
110
+ * A capture call requires:
111
+ * @param distinctId which uniquely identifies your user
112
+ * @param event We recommend using [verb] [noun], like movie played or movie updated to easily identify what your events mean later on.
113
+ * @param properties OPTIONAL | which can be a object with any information you'd like to add
114
+ * @param groups OPTIONAL | object of what groups are related to this event, example: { company: 'id:5' }. Can be used to analyze companies instead of users.
115
+ * @param sendFeatureFlags OPTIONAL | Used with experiments. Determines whether to send feature flag values with the event.
116
+ */
117
+ capture({ distinctId, event, properties, groups, sendFeatureFlags }: EventMessage): void
118
+
119
+ /**
120
+ * @description Capture an event immediately. Useful for edge environments where the usual queue-based sending is not preferable. Do not mix immediate and non-immediate calls.
121
+ * @param distinctId which uniquely identifies your user
122
+ * @param event We recommend using [verb] [noun], like movie played or movie updated to easily identify what your events mean later on.
123
+ * @param properties OPTIONAL | which can be a object with any information you'd like to add
124
+ * @param groups OPTIONAL | object of what groups are related to this event, example: { company: 'id:5' }. Can be used to analyze companies instead of users.
125
+ * @param sendFeatureFlags OPTIONAL | Used with experiments. Determines whether to send feature flag values with the event.
126
+ */
127
+ captureImmediate({ distinctId, event, properties, groups, sendFeatureFlags }: EventMessage): Promise<void>
128
+
129
+ /**
130
+ * @description Identify lets you add metadata on your users so you can more easily identify who they are in PostHog,
131
+ * and even do things like segment users by these properties.
132
+ * An identify call requires:
133
+ * @param distinctId which uniquely identifies your user
134
+ * @param properties with a dict with any key: value pairs
135
+ */
136
+ identify({ distinctId, properties }: IdentifyMessage): void
137
+
138
+ /**
139
+ * @description Identify lets you add metadata on your users so you can more easily identify who they are in PostHog.
140
+ * Useful for edge environments where the usual queue-based sending is not preferable. Do not mix immediate and non-immediate calls.
141
+ * @param distinctId which uniquely identifies your user
142
+ * @param properties with a dict with any key: value pairs
143
+ */
144
+ identifyImmediate({ distinctId, properties }: IdentifyMessage): Promise<void>
145
+
146
+ /**
147
+ * @description To marry up whatever a user does before they sign up or log in with what they do after you need to make an alias call.
148
+ * This will allow you to answer questions like "Which marketing channels leads to users churning after a month?"
149
+ * or "What do users do on our website before signing up?"
150
+ * In a purely back-end implementation, this means whenever an anonymous user does something, you'll want to send a session ID with the capture call.
151
+ * Then, when that users signs up, you want to do an alias call with the session ID and the newly created user ID.
152
+ * The same concept applies for when a user logs in. If you're using PostHog in the front-end and back-end,
153
+ * doing the identify call in the frontend will be enough.:
154
+ * @param distinctId the current unique id
155
+ * @param alias the unique ID of the user before
156
+ */
157
+ alias(data: { distinctId: string; alias: string }): void
158
+
159
+ /**
160
+ * @description To marry up whatever a user does before they sign up or log in with what they do after you need to make an alias call.
161
+ * Useful for edge environments where the usual queue-based sending is not preferable. Do not mix immediate and non-immediate calls.
162
+ * @param distinctId the current unique id
163
+ * @param alias the unique ID of the user before
164
+ */
165
+ aliasImmediate(data: { distinctId: string; alias: string }): Promise<void>
166
+
167
+ /**
168
+ * @description PostHog feature flags (https://posthog.com/docs/features/feature-flags)
169
+ * allow you to safely deploy and roll back new features. Once you've created a feature flag in PostHog,
170
+ * you can use this method to check if the flag is on for a given user, allowing you to create logic to turn
171
+ * features on and off for different user groups or individual users.
172
+ * @param key the unique key of your feature flag
173
+ * @param distinctId the current unique id
174
+ * @param options: dict with optional parameters below
175
+ * @param groups optional - what groups are currently active (group analytics). Required if the flag depends on groups.
176
+ * @param personProperties optional - what person properties are known. Used to compute flags locally, if personalApiKey is present.
177
+ * @param groupProperties optional - what group properties are known. Used to compute flags locally, if personalApiKey is present.
178
+ * @param onlyEvaluateLocally optional - whether to only evaluate the flag locally. Defaults to false.
179
+ * @param sendFeatureFlagEvents optional - whether to send feature flag events. Used for Experiments. Defaults to true.
180
+ *
181
+ * @returns true if the flag is on, false if the flag is off, undefined if there was an error.
182
+ */
183
+ isFeatureEnabled(
184
+ key: string,
185
+ distinctId: string,
186
+ options?: {
187
+ groups?: Record<string, string>
188
+ personProperties?: Record<string, string>
189
+ groupProperties?: Record<string, Record<string, string>>
190
+ onlyEvaluateLocally?: boolean
191
+ sendFeatureFlagEvents?: boolean
192
+ }
193
+ ): Promise<boolean | undefined>
194
+
195
+ /**
196
+ * @description PostHog feature flags (https://posthog.com/docs/features/feature-flags)
197
+ * allow you to safely deploy and roll back new features. Once you've created a feature flag in PostHog,
198
+ * you can use this method to check if the flag is on for a given user, allowing you to create logic to turn
199
+ * features on and off for different user groups or individual users.
200
+ * @param key the unique key of your feature flag
201
+ * @param distinctId the current unique id
202
+ * @param options: dict with optional parameters below
203
+ * @param groups optional - what groups are currently active (group analytics). Required if the flag depends on groups.
204
+ * @param personProperties optional - what person properties are known. Used to compute flags locally, if personalApiKey is present.
205
+ * @param groupProperties optional - what group properties are known. Used to compute flags locally, if personalApiKey is present.
206
+ * @param onlyEvaluateLocally optional - whether to only evaluate the flag locally. Defaults to false.
207
+ * @param sendFeatureFlagEvents optional - whether to send feature flag events. Used for Experiments. Defaults to true.
208
+ *
209
+ * @returns true or string(for multivariates) if the flag is on, false if the flag is off, undefined if there was an error.
210
+ */
211
+ getFeatureFlag(
212
+ key: string,
213
+ distinctId: string,
214
+ options?: {
215
+ groups?: Record<string, string>
216
+ personProperties?: Record<string, string>
217
+ groupProperties?: Record<string, Record<string, string>>
218
+ onlyEvaluateLocally?: boolean
219
+ sendFeatureFlagEvents?: boolean
220
+ }
221
+ ): Promise<FeatureFlagValue | undefined>
222
+
223
+ /**
224
+ * @description Retrieves payload associated with the specified flag and matched value that is passed in.
225
+ *
226
+ * IMPORTANT: The `matchValue` parameter should be the value you previously obtained from `getFeatureFlag()`.
227
+ * If matchValue isn't passed (or is undefined), this method will automatically call `getFeatureFlag()`
228
+ * internally to fetch the flag value, which could result in a network call to the PostHog server if this flag can
229
+ * not be evaluated locally. This means that omitting `matchValue` will potentially:
230
+ * - Bypass local evaluation
231
+ * - Count as an additional flag evaluation against your quota
232
+ * - Impact performance due to the extra network request
233
+ *
234
+ * Example usage:
235
+ * ```js
236
+ * const flagValue = await client.getFeatureFlag('my-flag', distinctId);
237
+ * const payload = await client.getFeatureFlagPayload('my-flag', distinctId, flagValue);
238
+ * ```
239
+ *
240
+ * @param key the unique key of your feature flag
241
+ * @param distinctId the current unique id
242
+ * @param matchValue The flag value previously obtained from calling `getFeatureFlag()`. Can be a string or boolean.
243
+ * To avoid extra network calls, pass this parameter when you can.
244
+ * @param options: dict with optional parameters below
245
+ * @param onlyEvaluateLocally optional - whether to only evaluate the flag locally. Defaults to false.
246
+ *
247
+ * @returns payload of a json type object
248
+ */
249
+ getFeatureFlagPayload(
250
+ key: string,
251
+ distinctId: string,
252
+ matchValue?: FeatureFlagValue,
253
+ options?: {
254
+ onlyEvaluateLocally?: boolean
255
+ }
256
+ ): Promise<JsonType | undefined>
257
+
258
+ /**
259
+ * @description Sets a groups properties, which allows asking questions like "Who are the most active companies"
260
+ * using my product in PostHog.
261
+ *
262
+ * @param groupType Type of group (ex: 'company'). Limited to 5 per project
263
+ * @param groupKey Unique identifier for that type of group (ex: 'id:5')
264
+ * @param properties OPTIONAL | which can be a object with any information you'd like to add
265
+ */
266
+ groupIdentify({ groupType, groupKey, properties }: GroupIdentifyMessage): void
267
+
268
+ /**
269
+ * @description Force an immediate reload of the polled feature flags. Please note that they are
270
+ * already polled automatically at a regular interval.
271
+ */
272
+ reloadFeatureFlags(): Promise<void>
273
+
274
+ /**
275
+ * @description Flushes the events still in the queue and clears the feature flags poller to allow for
276
+ * a clean shutdown.
277
+ *
278
+ * @param shutdownTimeoutMs The shutdown timeout, in milliseconds. Defaults to 30000 (30s).
279
+ */
280
+ shutdown(shutdownTimeoutMs?: number): void
281
+
282
+ /**
283
+ * @description Waits for local evaluation to be ready, with an optional timeout.
284
+ * @param timeoutMs - Maximum time to wait in milliseconds. Defaults to 30 seconds.
285
+ * @returns A promise that resolves to true if local evaluation is ready, false if the timeout was reached.
286
+ */
287
+ waitForLocalEvaluationReady(timeoutMs?: number): Promise<boolean>
288
+
289
+ /**
290
+ * @description Returns true if local evaluation is ready, false if it's not.
291
+ * @returns true if local evaluation is ready, false if it's not.
292
+ */
293
+ isLocalEvaluationReady(): boolean
294
+ }
@@ -0,0 +1,39 @@
1
+ import { Logger } from '@posthog/core'
2
+
3
+ const _createLogger = (prefix: string, logMsgIfDebug: (fn: () => void) => void): Logger => {
4
+ const logger: Logger = {
5
+ _log: (level: 'log' | 'warn' | 'error', ...args: any[]) => {
6
+ logMsgIfDebug(() => {
7
+ const consoleLog = console[level]
8
+ consoleLog(prefix, ...args)
9
+ })
10
+ },
11
+
12
+ info: (...args: any[]) => {
13
+ logger._log('log', ...args)
14
+ },
15
+
16
+ warn: (...args: any[]) => {
17
+ logger._log('warn', ...args)
18
+ },
19
+
20
+ error: (...args: any[]) => {
21
+ logger._log('error', ...args)
22
+ },
23
+
24
+ critical: (...args: any[]) => {
25
+ // Critical errors are always logged to the console
26
+ // eslint-disable-next-line no-console
27
+ console.error(prefix, ...args)
28
+ },
29
+
30
+ uninitializedWarning: (methodName: string) => {
31
+ logger.error(`You must initialize PostHog before calling ${methodName}`)
32
+ },
33
+
34
+ createLogger: (additionalPrefix: string) => _createLogger(`${prefix} ${additionalPrefix}`, logMsgIfDebug),
35
+ }
36
+ return logger
37
+ }
38
+
39
+ export const createLogger = (logMsgIfDebug: (fn: () => void) => void) => _createLogger('[PostHog.js]', logMsgIfDebug)
package/src/version.ts ADDED
@@ -0,0 +1 @@
1
+ export const version = '5.9.0'