posthog-node 5.0.0-alpha.1 → 5.1.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 (65) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/lib/edge/index.cjs +3455 -0
  3. package/lib/edge/index.cjs.map +1 -0
  4. package/lib/edge/index.mjs +3429 -0
  5. package/lib/edge/index.mjs.map +1 -0
  6. package/lib/index.d.ts +938 -810
  7. package/lib/{index.cjs.js → node/index.cjs} +2910 -3107
  8. package/lib/node/index.cjs.map +1 -0
  9. package/lib/{index.esm.js → node/index.mjs} +2911 -3105
  10. package/lib/node/index.mjs.map +1 -0
  11. package/package.json +33 -6
  12. package/index.ts +0 -3
  13. package/lib/index.cjs.js.map +0 -1
  14. package/lib/index.esm.js.map +0 -1
  15. package/lib/posthog-core/src/eventemitter.d.ts +0 -8
  16. package/lib/posthog-core/src/featureFlagUtils.d.ts +0 -34
  17. package/lib/posthog-core/src/index.d.ts +0 -242
  18. package/lib/posthog-core/src/lz-string.d.ts +0 -8
  19. package/lib/posthog-core/src/storage-memory.d.ts +0 -6
  20. package/lib/posthog-core/src/types.d.ts +0 -422
  21. package/lib/posthog-core/src/utils.d.ts +0 -19
  22. package/lib/posthog-core/src/vendor/uuidv7.d.ts +0 -179
  23. package/lib/posthog-node/index.d.ts +0 -3
  24. package/lib/posthog-node/src/crypto-helpers.d.ts +0 -3
  25. package/lib/posthog-node/src/crypto.d.ts +0 -2
  26. package/lib/posthog-node/src/error-tracking.d.ts +0 -12
  27. package/lib/posthog-node/src/extensions/error-tracking/autocapture.d.ts +0 -3
  28. package/lib/posthog-node/src/extensions/error-tracking/context-lines.d.ts +0 -6
  29. package/lib/posthog-node/src/extensions/error-tracking/error-conversion.d.ts +0 -2
  30. package/lib/posthog-node/src/extensions/error-tracking/reduceable-cache.d.ts +0 -12
  31. package/lib/posthog-node/src/extensions/error-tracking/stack-trace.d.ts +0 -15
  32. package/lib/posthog-node/src/extensions/error-tracking/type-checking.d.ts +0 -7
  33. package/lib/posthog-node/src/extensions/error-tracking/types.d.ts +0 -57
  34. package/lib/posthog-node/src/extensions/express.d.ts +0 -17
  35. package/lib/posthog-node/src/extensions/sentry-integration.d.ts +0 -51
  36. package/lib/posthog-node/src/feature-flags.d.ts +0 -84
  37. package/lib/posthog-node/src/lazy.d.ts +0 -23
  38. package/lib/posthog-node/src/posthog-node.d.ts +0 -91
  39. package/lib/posthog-node/src/types.d.ts +0 -203
  40. package/lib/posthog-node/test/test-utils.d.ts +0 -17
  41. package/src/crypto-helpers.ts +0 -36
  42. package/src/crypto.ts +0 -22
  43. package/src/error-tracking.ts +0 -67
  44. package/src/extensions/error-tracking/autocapture.ts +0 -65
  45. package/src/extensions/error-tracking/context-lines.ts +0 -425
  46. package/src/extensions/error-tracking/error-conversion.ts +0 -262
  47. package/src/extensions/error-tracking/reduceable-cache.ts +0 -39
  48. package/src/extensions/error-tracking/stack-trace.ts +0 -269
  49. package/src/extensions/error-tracking/type-checking.ts +0 -40
  50. package/src/extensions/error-tracking/types.ts +0 -65
  51. package/src/extensions/express.ts +0 -37
  52. package/src/extensions/sentry-integration.ts +0 -196
  53. package/src/feature-flags.ts +0 -863
  54. package/src/lazy.ts +0 -55
  55. package/src/posthog-node.ts +0 -567
  56. package/src/types.ts +0 -231
  57. package/test/crypto.spec.ts +0 -36
  58. package/test/extensions/error-conversion.spec.ts +0 -44
  59. package/test/extensions/sentry-integration.spec.ts +0 -162
  60. package/test/feature-flags.decide.spec.ts +0 -378
  61. package/test/feature-flags.spec.ts +0 -4681
  62. package/test/lazy.spec.ts +0 -71
  63. package/test/posthog-node.spec.ts +0 -1341
  64. package/test/test-utils.ts +0 -106
  65. package/tsconfig.json +0 -7
@@ -1,15 +0,0 @@
1
- import { StackFrame, StackLineParser, StackLineParserFn, StackParser } from './types';
2
- type GetModuleFn = (filename: string | undefined) => string | undefined;
3
- /** Node Stack line parser */
4
- export declare function node(getModule?: GetModuleFn): StackLineParserFn;
5
- /**
6
- * Does this filename look like it's part of the app code?
7
- */
8
- export declare function filenameIsInApp(filename: string, isNative?: boolean): boolean;
9
- export declare function nodeStackLineParser(getModule?: GetModuleFn): StackLineParser;
10
- export declare const defaultStackParser: StackParser;
11
- /** Creates a function that gets the module name from a filename */
12
- export declare function createGetModuleFromFilename(basePath?: string, isWindows?: boolean): (filename: string | undefined) => string | undefined;
13
- export declare function createStackParser(...parsers: StackLineParser[]): StackParser;
14
- export declare function reverseAndStripFrames(stack: ReadonlyArray<StackFrame>): StackFrame[];
15
- export {};
@@ -1,7 +0,0 @@
1
- import { PolymorphicEvent } from './types';
2
- export declare function isEvent(candidate: unknown): candidate is PolymorphicEvent;
3
- export declare function isPlainObject(candidate: unknown): candidate is Record<string, unknown>;
4
- export declare function isError(candidate: unknown): candidate is Error;
5
- export declare function isInstanceOf(candidate: unknown, base: any): boolean;
6
- export declare function isErrorEvent(event: unknown): boolean;
7
- export declare function isBuiltin(candidate: unknown, className: string): boolean;
@@ -1,57 +0,0 @@
1
- export declare const severityLevels: readonly ["fatal", "error", "warning", "log", "info", "debug"];
2
- export declare type SeverityLevel = (typeof severityLevels)[number];
3
- export interface PolymorphicEvent {
4
- [key: string]: unknown;
5
- readonly type: string;
6
- readonly target?: unknown;
7
- readonly currentTarget?: unknown;
8
- }
9
- export interface EventHint {
10
- mechanism?: Partial<Mechanism>;
11
- syntheticException?: Error | null;
12
- }
13
- export interface ErrorProperties {
14
- $exception_list: Exception[];
15
- $exception_level?: SeverityLevel;
16
- $exception_DOMException_code?: string;
17
- $exception_personURL?: string;
18
- }
19
- export interface Exception {
20
- type?: string;
21
- value?: string;
22
- mechanism?: Mechanism;
23
- module?: string;
24
- thread_id?: number;
25
- stacktrace?: {
26
- frames?: StackFrame[];
27
- type: 'raw';
28
- };
29
- }
30
- export interface Mechanism {
31
- handled?: boolean;
32
- type?: string;
33
- source?: string;
34
- synthetic?: boolean;
35
- }
36
- export type StackParser = (stack: string, skipFirstLines?: number) => StackFrame[];
37
- export type StackLineParserFn = (line: string) => StackFrame | undefined;
38
- export type StackLineParser = [number, StackLineParserFn];
39
- export interface StackFrame {
40
- platform: string;
41
- filename?: string;
42
- function?: string;
43
- module?: string;
44
- lineno?: number;
45
- colno?: number;
46
- abs_path?: string;
47
- context_line?: string;
48
- pre_context?: string[];
49
- post_context?: string[];
50
- in_app?: boolean;
51
- instruction_addr?: string;
52
- addr_mode?: string;
53
- vars?: {
54
- [key: string]: any;
55
- };
56
- debug_id?: string;
57
- }
@@ -1,17 +0,0 @@
1
- /// <reference types="node" />
2
- import type * as http from 'node:http';
3
- import { PostHog } from '../posthog-node';
4
- type ExpressMiddleware = (req: http.IncomingMessage, res: http.ServerResponse, next: () => void) => void;
5
- type ExpressErrorMiddleware = (error: MiddlewareError, req: http.IncomingMessage, res: http.ServerResponse, next: (error: MiddlewareError) => void) => void;
6
- interface MiddlewareError extends Error {
7
- status?: number | string;
8
- statusCode?: number | string;
9
- status_code?: number | string;
10
- output?: {
11
- statusCode?: number | string;
12
- };
13
- }
14
- export declare function setupExpressErrorHandler(_posthog: PostHog, app: {
15
- use: (middleware: ExpressMiddleware | ExpressErrorMiddleware) => unknown;
16
- }): void;
17
- export {};
@@ -1,51 +0,0 @@
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
- */
24
- import { SeverityLevel } from 'posthog-node/src/extensions/error-tracking/types';
25
- import { type PostHog } from '../posthog-node';
26
- type _SentryEvent = any;
27
- type _SentryEventProcessor = any;
28
- type _SentryHub = any;
29
- interface _SentryIntegration {
30
- name: string;
31
- processEvent(event: _SentryEvent): _SentryEvent;
32
- }
33
- interface _SentryIntegrationClass {
34
- name: string;
35
- setupOnce(addGlobalEventProcessor: (callback: _SentryEventProcessor) => void, getCurrentHub: () => _SentryHub): void;
36
- }
37
- export type SentryIntegrationOptions = {
38
- organization?: string;
39
- projectId?: number;
40
- prefix?: string;
41
- severityAllowList?: SeverityLevel[] | '*';
42
- };
43
- export declare function createEventProcessor(_posthog: PostHog, { organization, projectId, prefix, severityAllowList }?: SentryIntegrationOptions): (event: _SentryEvent) => _SentryEvent;
44
- export declare function sentryIntegration(_posthog: PostHog, options?: SentryIntegrationOptions): _SentryIntegration;
45
- export declare class PostHogSentryIntegration implements _SentryIntegrationClass {
46
- readonly name = "posthog-node";
47
- static readonly POSTHOG_ID_TAG = "posthog_distinct_id";
48
- setupOnce: (addGlobalEventProcessor: (callback: _SentryEventProcessor) => void, getCurrentHub: () => _SentryHub) => void;
49
- constructor(_posthog: PostHog, organization?: string, prefix?: string, severityAllowList?: SeverityLevel[] | '*');
50
- }
51
- export {};
@@ -1,84 +0,0 @@
1
- /// <reference types="node" />
2
- import { FeatureFlagCondition, PostHogFeatureFlag, PropertyGroup } from './types';
3
- import { FeatureFlagValue, JsonType, PostHogFetchOptions, PostHogFetchResponse } from 'posthog-core/src';
4
- declare class ClientError extends Error {
5
- constructor(message: string);
6
- }
7
- declare class InconclusiveMatchError extends Error {
8
- constructor(message: string);
9
- }
10
- type FeatureFlagsPollerOptions = {
11
- personalApiKey: string;
12
- projectApiKey: string;
13
- host: string;
14
- pollingInterval: number;
15
- timeout?: number;
16
- fetch?: (url: string, options: PostHogFetchOptions) => Promise<PostHogFetchResponse>;
17
- onError?: (error: Error) => void;
18
- onLoad?: (count: number) => void;
19
- customHeaders?: {
20
- [key: string]: string;
21
- };
22
- };
23
- declare class FeatureFlagsPoller {
24
- pollingInterval: number;
25
- personalApiKey: string;
26
- projectApiKey: string;
27
- featureFlags: Array<PostHogFeatureFlag>;
28
- featureFlagsByKey: Record<string, PostHogFeatureFlag>;
29
- groupTypeMapping: Record<string, string>;
30
- cohorts: Record<string, PropertyGroup>;
31
- loadedSuccessfullyOnce: boolean;
32
- timeout?: number;
33
- host: FeatureFlagsPollerOptions['host'];
34
- poller?: NodeJS.Timeout;
35
- fetch: (url: string, options: PostHogFetchOptions) => Promise<PostHogFetchResponse>;
36
- debugMode: boolean;
37
- onError?: (error: Error) => void;
38
- customHeaders?: {
39
- [key: string]: string;
40
- };
41
- shouldBeginExponentialBackoff: boolean;
42
- backOffCount: number;
43
- onLoad?: (count: number) => void;
44
- constructor({ pollingInterval, personalApiKey, projectApiKey, timeout, host, customHeaders, ...options }: FeatureFlagsPollerOptions);
45
- debug(enabled?: boolean): void;
46
- private logMsgIfDebug;
47
- getFeatureFlag(key: string, distinctId: string, groups?: Record<string, string>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>): Promise<FeatureFlagValue | undefined>;
48
- computeFeatureFlagPayloadLocally(key: string, matchValue: FeatureFlagValue): Promise<JsonType | undefined>;
49
- getAllFlagsAndPayloads(distinctId: string, groups?: Record<string, string>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>): Promise<{
50
- response: Record<string, FeatureFlagValue>;
51
- payloads: Record<string, JsonType>;
52
- fallbackToDecide: boolean;
53
- }>;
54
- computeFlagLocally(flag: PostHogFeatureFlag, distinctId: string, groups?: Record<string, string>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>): Promise<FeatureFlagValue>;
55
- matchFeatureFlagProperties(flag: PostHogFeatureFlag, distinctId: string, properties: Record<string, string>): Promise<FeatureFlagValue>;
56
- isConditionMatch(flag: PostHogFeatureFlag, distinctId: string, condition: FeatureFlagCondition, properties: Record<string, string>): Promise<boolean>;
57
- getMatchingVariant(flag: PostHogFeatureFlag, distinctId: string): Promise<FeatureFlagValue | undefined>;
58
- variantLookupTable(flag: PostHogFeatureFlag): {
59
- valueMin: number;
60
- valueMax: number;
61
- key: string;
62
- }[];
63
- loadFeatureFlags(forceReload?: boolean): Promise<void>;
64
- /**
65
- * Returns true if the feature flags poller has loaded successfully at least once and has more than 0 feature flags.
66
- * This is useful to check if local evaluation is ready before calling getFeatureFlag.
67
- */
68
- isLocalEvaluationReady(): boolean;
69
- /**
70
- * If a client is misconfigured with an invalid or improper API key, the polling interval is doubled each time
71
- * until a successful request is made, up to a maximum of 60 seconds.
72
- *
73
- * @returns The polling interval to use for the next request.
74
- */
75
- private getPollingInterval;
76
- _loadFeatureFlags(): Promise<void>;
77
- private getPersonalApiKeyRequestOptions;
78
- _requestFeatureFlagDefinitions(): Promise<PostHogFetchResponse>;
79
- stopPoller(): void;
80
- _requestRemoteConfigPayload(flagKey: string): Promise<PostHogFetchResponse>;
81
- }
82
- declare function matchProperty(property: FeatureFlagCondition['properties'][number], propertyValues: Record<string, any>, warnFunction?: (msg: string) => void): boolean;
83
- declare function relativeDateParseForFeatureFlagMatching(value: string): Date | null;
84
- export { FeatureFlagsPoller, matchProperty, relativeDateParseForFeatureFlagMatching, InconclusiveMatchError, ClientError, };
@@ -1,23 +0,0 @@
1
- /**
2
- * A lazy value that is only computed when needed. Inspired by C#'s Lazy<T> class.
3
- */
4
- export declare class Lazy<T> {
5
- private value;
6
- private factory;
7
- private initializationPromise;
8
- constructor(factory: () => Promise<T>);
9
- /**
10
- * Gets the value, initializing it if necessary.
11
- * Multiple concurrent calls will share the same initialization promise.
12
- */
13
- getValue(): Promise<T>;
14
- /**
15
- * Returns true if the value has been initialized.
16
- */
17
- isInitialized(): boolean;
18
- /**
19
- * Returns a promise that resolves when the value is initialized.
20
- * If already initialized, resolves immediately.
21
- */
22
- waitForInitialization(): Promise<void>;
23
- }
@@ -1,91 +0,0 @@
1
- import { JsonType, PostHogCoreOptions, PostHogCoreStateless, PostHogFetchOptions, PostHogFetchResponse, PostHogFlagsAndPayloadsResponse, PostHogPersistedProperty } from '../../posthog-core/src';
2
- import { EventMessage, GroupIdentifyMessage, IdentifyMessage, PostHogNodeV1 } from './types';
3
- import { FeatureFlagValue } from '../../posthog-core/src/types';
4
- import ErrorTracking from './error-tracking';
5
- export type PostHogOptions = PostHogCoreOptions & {
6
- persistence?: 'memory';
7
- personalApiKey?: string;
8
- privacyMode?: boolean;
9
- enableExceptionAutocapture?: boolean;
10
- featureFlagsPollingInterval?: number;
11
- maxCacheSize?: number;
12
- fetch?: (url: string, options: PostHogFetchOptions) => Promise<PostHogFetchResponse>;
13
- };
14
- export declare const MINIMUM_POLLING_INTERVAL = 100;
15
- export declare const THIRTY_SECONDS: number;
16
- export declare const SIXTY_SECONDS: number;
17
- export declare class PostHog extends PostHogCoreStateless implements PostHogNodeV1 {
18
- private _memoryStorage;
19
- private featureFlagsPoller?;
20
- protected errorTracking: ErrorTracking;
21
- private maxCacheSize;
22
- readonly options: PostHogOptions;
23
- distinctIdHasSentFlagCalls: Record<string, string[]>;
24
- constructor(apiKey: string, options?: PostHogOptions);
25
- getPersistedProperty(key: PostHogPersistedProperty): any | undefined;
26
- setPersistedProperty(key: PostHogPersistedProperty, value: any | null): void;
27
- fetch(url: string, options: PostHogFetchOptions): Promise<PostHogFetchResponse>;
28
- getLibraryId(): string;
29
- getLibraryVersion(): string;
30
- getCustomUserAgent(): string;
31
- enable(): Promise<void>;
32
- disable(): Promise<void>;
33
- debug(enabled?: boolean): void;
34
- capture(props: EventMessage): void;
35
- identify({ distinctId, properties, disableGeoip }: IdentifyMessage): void;
36
- alias(data: {
37
- distinctId: string;
38
- alias: string;
39
- disableGeoip?: boolean;
40
- }): void;
41
- isLocalEvaluationReady(): boolean;
42
- waitForLocalEvaluationReady(timeoutMs?: number): Promise<boolean>;
43
- getFeatureFlag(key: string, distinctId: string, options?: {
44
- groups?: Record<string, string>;
45
- personProperties?: Record<string, string>;
46
- groupProperties?: Record<string, Record<string, string>>;
47
- onlyEvaluateLocally?: boolean;
48
- sendFeatureFlagEvents?: boolean;
49
- disableGeoip?: boolean;
50
- }): Promise<FeatureFlagValue | undefined>;
51
- getFeatureFlagPayload(key: string, distinctId: string, matchValue?: FeatureFlagValue, options?: {
52
- groups?: Record<string, string>;
53
- personProperties?: Record<string, string>;
54
- groupProperties?: Record<string, Record<string, string>>;
55
- onlyEvaluateLocally?: boolean;
56
- sendFeatureFlagEvents?: boolean;
57
- disableGeoip?: boolean;
58
- }): Promise<JsonType | undefined>;
59
- getRemoteConfigPayload(flagKey: string): Promise<JsonType | undefined>;
60
- isFeatureEnabled(key: string, distinctId: string, options?: {
61
- groups?: Record<string, string>;
62
- personProperties?: Record<string, string>;
63
- groupProperties?: Record<string, Record<string, string>>;
64
- onlyEvaluateLocally?: boolean;
65
- sendFeatureFlagEvents?: boolean;
66
- disableGeoip?: boolean;
67
- }): Promise<boolean | undefined>;
68
- getAllFlags(distinctId: string, options?: {
69
- groups?: Record<string, string>;
70
- personProperties?: Record<string, string>;
71
- groupProperties?: Record<string, Record<string, string>>;
72
- onlyEvaluateLocally?: boolean;
73
- disableGeoip?: boolean;
74
- }): Promise<Record<string, FeatureFlagValue>>;
75
- getAllFlagsAndPayloads(distinctId: string, options?: {
76
- groups?: Record<string, string>;
77
- personProperties?: Record<string, string>;
78
- groupProperties?: Record<string, Record<string, string>>;
79
- onlyEvaluateLocally?: boolean;
80
- disableGeoip?: boolean;
81
- }): Promise<PostHogFlagsAndPayloadsResponse>;
82
- groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }: GroupIdentifyMessage): void;
83
- /**
84
- * Reloads the feature flag definitions from the server for local evaluation.
85
- * This is useful to call if you want to ensure that the feature flags are up to date before calling getFeatureFlag.
86
- */
87
- reloadFeatureFlags(): Promise<void>;
88
- shutdown(shutdownTimeoutMs?: number): Promise<void>;
89
- private addLocalPersonAndGroupProperties;
90
- captureException(error: unknown, distinctId?: string, additionalProperties?: Record<string | number, any>): void;
91
- }
@@ -1,203 +0,0 @@
1
- import { FeatureFlagValue, JsonType } from '../../posthog-core/src';
2
- export interface IdentifyMessage {
3
- distinctId: string;
4
- properties?: Record<string | number, any>;
5
- disableGeoip?: boolean;
6
- }
7
- export interface EventMessage extends IdentifyMessage {
8
- event: string;
9
- groups?: Record<string, string | number>;
10
- sendFeatureFlags?: boolean;
11
- timestamp?: Date;
12
- uuid?: string;
13
- }
14
- export interface GroupIdentifyMessage {
15
- groupType: string;
16
- groupKey: string;
17
- properties?: Record<string | number, any>;
18
- distinctId?: string;
19
- disableGeoip?: boolean;
20
- }
21
- export type PropertyGroup = {
22
- type: 'AND' | 'OR';
23
- values: PropertyGroup[] | FlagProperty[];
24
- };
25
- export type FlagProperty = {
26
- key: string;
27
- type?: string;
28
- value: string | number | (string | number)[];
29
- operator?: string;
30
- negation?: boolean;
31
- };
32
- export type FeatureFlagCondition = {
33
- properties: FlagProperty[];
34
- rollout_percentage?: number;
35
- variant?: string;
36
- };
37
- export type PostHogFeatureFlag = {
38
- id: number;
39
- name: string;
40
- key: string;
41
- filters?: {
42
- aggregation_group_type_index?: number;
43
- groups?: FeatureFlagCondition[];
44
- multivariate?: {
45
- variants: {
46
- key: string;
47
- rollout_percentage: number;
48
- }[];
49
- };
50
- payloads?: Record<string, string>;
51
- };
52
- deleted: boolean;
53
- active: boolean;
54
- /** @deprecated This field will be removed in a future version. **/
55
- is_simple_flag: boolean;
56
- rollout_percentage: null | number;
57
- ensure_experience_continuity: boolean;
58
- experiment_set: number[];
59
- };
60
- export type PostHogNodeV1 = {
61
- /**
62
- * @description Capture allows you to capture anything a user does within your system,
63
- * which you can later use in PostHog to find patterns in usage,
64
- * work out which features to improve or where people are giving up.
65
- * A capture call requires:
66
- * @param distinctId which uniquely identifies your user
67
- * @param event We recommend using [verb] [noun], like movie played or movie updated to easily identify what your events mean later on.
68
- * @param properties OPTIONAL | which can be a object with any information you'd like to add
69
- * @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.
70
- * @param sendFeatureFlags OPTIONAL | Used with experiments. Determines whether to send feature flag values with the event.
71
- */
72
- capture({ distinctId, event, properties, groups, sendFeatureFlags }: EventMessage): void;
73
- /**
74
- * @description Identify lets you add metadata on your users so you can more easily identify who they are in PostHog,
75
- * and even do things like segment users by these properties.
76
- * An identify call requires:
77
- * @param distinctId which uniquely identifies your user
78
- * @param properties with a dict with any key: value pairs
79
- */
80
- identify({ distinctId, properties }: IdentifyMessage): void;
81
- /**
82
- * @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.
83
- * This will allow you to answer questions like "Which marketing channels leads to users churning after a month?"
84
- * or "What do users do on our website before signing up?"
85
- * 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.
86
- * Then, when that users signs up, you want to do an alias call with the session ID and the newly created user ID.
87
- * The same concept applies for when a user logs in. If you're using PostHog in the front-end and back-end,
88
- * doing the identify call in the frontend will be enough.:
89
- * @param distinctId the current unique id
90
- * @param alias the unique ID of the user before
91
- */
92
- alias(data: {
93
- distinctId: string;
94
- alias: string;
95
- }): void;
96
- /**
97
- * @description PostHog feature flags (https://posthog.com/docs/features/feature-flags)
98
- * allow you to safely deploy and roll back new features. Once you've created a feature flag in PostHog,
99
- * you can use this method to check if the flag is on for a given user, allowing you to create logic to turn
100
- * features on and off for different user groups or individual users.
101
- * @param key the unique key of your feature flag
102
- * @param distinctId the current unique id
103
- * @param options: dict with optional parameters below
104
- * @param groups optional - what groups are currently active (group analytics). Required if the flag depends on groups.
105
- * @param personProperties optional - what person properties are known. Used to compute flags locally, if personalApiKey is present.
106
- * @param groupProperties optional - what group properties are known. Used to compute flags locally, if personalApiKey is present.
107
- * @param onlyEvaluateLocally optional - whether to only evaluate the flag locally. Defaults to false.
108
- * @param sendFeatureFlagEvents optional - whether to send feature flag events. Used for Experiments. Defaults to true.
109
- *
110
- * @returns true if the flag is on, false if the flag is off, undefined if there was an error.
111
- */
112
- isFeatureEnabled(key: string, distinctId: string, options?: {
113
- groups?: Record<string, string>;
114
- personProperties?: Record<string, string>;
115
- groupProperties?: Record<string, Record<string, string>>;
116
- onlyEvaluateLocally?: boolean;
117
- sendFeatureFlagEvents?: boolean;
118
- }): Promise<boolean | undefined>;
119
- /**
120
- * @description PostHog feature flags (https://posthog.com/docs/features/feature-flags)
121
- * allow you to safely deploy and roll back new features. Once you've created a feature flag in PostHog,
122
- * you can use this method to check if the flag is on for a given user, allowing you to create logic to turn
123
- * features on and off for different user groups or individual users.
124
- * @param key the unique key of your feature flag
125
- * @param distinctId the current unique id
126
- * @param options: dict with optional parameters below
127
- * @param groups optional - what groups are currently active (group analytics). Required if the flag depends on groups.
128
- * @param personProperties optional - what person properties are known. Used to compute flags locally, if personalApiKey is present.
129
- * @param groupProperties optional - what group properties are known. Used to compute flags locally, if personalApiKey is present.
130
- * @param onlyEvaluateLocally optional - whether to only evaluate the flag locally. Defaults to false.
131
- * @param sendFeatureFlagEvents optional - whether to send feature flag events. Used for Experiments. Defaults to true.
132
- *
133
- * @returns true or string(for multivariates) if the flag is on, false if the flag is off, undefined if there was an error.
134
- */
135
- getFeatureFlag(key: string, distinctId: string, options?: {
136
- groups?: Record<string, string>;
137
- personProperties?: Record<string, string>;
138
- groupProperties?: Record<string, Record<string, string>>;
139
- onlyEvaluateLocally?: boolean;
140
- sendFeatureFlagEvents?: boolean;
141
- }): Promise<FeatureFlagValue | undefined>;
142
- /**
143
- * @description Retrieves payload associated with the specified flag and matched value that is passed in.
144
- *
145
- * IMPORTANT: The `matchValue` parameter should be the value you previously obtained from `getFeatureFlag()`.
146
- * If matchValue isn't passed (or is undefined), this method will automatically call `getFeatureFlag()`
147
- * internally to fetch the flag value, which could result in a network call to the PostHog server if this flag can
148
- * not be evaluated locally. This means that omitting `matchValue` will potentially:
149
- * - Bypass local evaluation
150
- * - Count as an additional flag evaluation against your quota
151
- * - Impact performance due to the extra network request
152
- *
153
- * Example usage:
154
- * ```js
155
- * const flagValue = await client.getFeatureFlag('my-flag', distinctId);
156
- * const payload = await client.getFeatureFlagPayload('my-flag', distinctId, flagValue);
157
- * ```
158
- *
159
- * @param key the unique key of your feature flag
160
- * @param distinctId the current unique id
161
- * @param matchValue The flag value previously obtained from calling `getFeatureFlag()`. Can be a string or boolean.
162
- * To avoid extra network calls, pass this parameter when you can.
163
- * @param options: dict with optional parameters below
164
- * @param onlyEvaluateLocally optional - whether to only evaluate the flag locally. Defaults to false.
165
- *
166
- * @returns payload of a json type object
167
- */
168
- getFeatureFlagPayload(key: string, distinctId: string, matchValue?: FeatureFlagValue, options?: {
169
- onlyEvaluateLocally?: boolean;
170
- }): Promise<JsonType | undefined>;
171
- /**
172
- * @description Sets a groups properties, which allows asking questions like "Who are the most active companies"
173
- * using my product in PostHog.
174
- *
175
- * @param groupType Type of group (ex: 'company'). Limited to 5 per project
176
- * @param groupKey Unique identifier for that type of group (ex: 'id:5')
177
- * @param properties OPTIONAL | which can be a object with any information you'd like to add
178
- */
179
- groupIdentify({ groupType, groupKey, properties }: GroupIdentifyMessage): void;
180
- /**
181
- * @description Force an immediate reload of the polled feature flags. Please note that they are
182
- * already polled automatically at a regular interval.
183
- */
184
- reloadFeatureFlags(): Promise<void>;
185
- /**
186
- * @description Flushes the events still in the queue and clears the feature flags poller to allow for
187
- * a clean shutdown.
188
- *
189
- * @param shutdownTimeoutMs The shutdown timeout, in milliseconds. Defaults to 30000 (30s).
190
- */
191
- shutdown(shutdownTimeoutMs?: number): void;
192
- /**
193
- * @description Waits for local evaluation to be ready, with an optional timeout.
194
- * @param timeoutMs - Maximum time to wait in milliseconds. Defaults to 30 seconds.
195
- * @returns A promise that resolves to true if local evaluation is ready, false if the timeout was reached.
196
- */
197
- waitForLocalEvaluationReady(timeoutMs?: number): Promise<boolean>;
198
- /**
199
- * @description Returns true if local evaluation is ready, false if it's not.
200
- * @returns true if local evaluation is ready, false if it's not.
201
- */
202
- isLocalEvaluationReady(): boolean;
203
- };
@@ -1,17 +0,0 @@
1
- import { PostHogV4DecideResponse } from 'posthog-core/src/types';
2
- type ErrorResponse = {
3
- status: number;
4
- json: () => Promise<any>;
5
- };
6
- export declare const apiImplementationV4: (decideResponse: PostHogV4DecideResponse | ErrorResponse) => (url: any) => Promise<any>;
7
- export declare const apiImplementation: ({ localFlags, decideFlags, decideFlagPayloads, decideStatus, localFlagsStatus, errorsWhileComputingFlags, }: {
8
- localFlags?: any;
9
- decideFlags?: any;
10
- decideFlagPayloads?: any;
11
- decideStatus?: number | undefined;
12
- localFlagsStatus?: number | undefined;
13
- errorsWhileComputingFlags?: boolean | undefined;
14
- }) => (url: any) => Promise<any>;
15
- export declare const anyLocalEvalCall: any[];
16
- export declare const anyDecideCall: any[];
17
- export {};
@@ -1,36 +0,0 @@
1
- /// <reference lib="dom" />
2
- import { Lazy } from 'posthog-node/src/lazy'
3
-
4
- const nodeCrypto = new Lazy(async () => {
5
- try {
6
- return await import('crypto')
7
- } catch {
8
- return undefined
9
- }
10
- })
11
-
12
- export async function getNodeCrypto(): Promise<typeof import('crypto') | undefined> {
13
- return await nodeCrypto.getValue()
14
- }
15
-
16
- const webCrypto = new Lazy(async (): Promise<SubtleCrypto | undefined> => {
17
- if (typeof globalThis.crypto?.subtle !== 'undefined') {
18
- return globalThis.crypto.subtle
19
- }
20
-
21
- try {
22
- // Node.js: use built-in webcrypto and assign it if needed
23
- const crypto = await nodeCrypto.getValue()
24
- if (crypto?.webcrypto?.subtle) {
25
- return crypto.webcrypto.subtle as SubtleCrypto
26
- }
27
- } catch {
28
- // Ignore if not available
29
- }
30
-
31
- return undefined
32
- })
33
-
34
- export async function getWebCrypto(): Promise<SubtleCrypto | undefined> {
35
- return await webCrypto.getValue()
36
- }
package/src/crypto.ts DELETED
@@ -1,22 +0,0 @@
1
- /// <reference lib="dom" />
2
-
3
- import { getNodeCrypto, getWebCrypto } from './crypto-helpers'
4
-
5
- export async function hashSHA1(text: string): Promise<string> {
6
- // Try Node.js crypto first
7
- const nodeCrypto = await getNodeCrypto()
8
- if (nodeCrypto) {
9
- return nodeCrypto.createHash('sha1').update(text).digest('hex')
10
- }
11
-
12
- const webCrypto = await getWebCrypto()
13
-
14
- // Fall back to Web Crypto API
15
- if (webCrypto) {
16
- const hashBuffer = await webCrypto.digest('SHA-1', new TextEncoder().encode(text))
17
- const hashArray = Array.from(new Uint8Array(hashBuffer))
18
- return hashArray.map((byte) => byte.toString(16).padStart(2, '0')).join('')
19
- }
20
-
21
- throw new Error('No crypto implementation available. Tried Node Crypto API and Web SubtleCrypto API')
22
- }