/* eslint-disable @typescript-eslint/no-explicit-any */ import type { GrowthBook, GrowthBookClient, StickyBucketService, UserScopedGrowthBook, } from ".."; import { AttributePath, ConditionInterface, ParentConditionInterface, } from "./mongrule"; declare global { interface Window { _growthbook?: GrowthBook; } } export type VariationMeta = { passthrough?: boolean; key?: string; name?: string; }; export type FeatureRule = { id?: string; condition?: ConditionInterface; parentConditions?: ParentConditionInterface[]; force?: T; variations?: T[]; weights?: number[]; key?: string; hashAttribute?: AttributeKey; fallbackAttribute?: AttributeKey; hashVersion?: number; disableStickyBucketing?: boolean; bucketVersion?: number; minBucketVersion?: number; range?: VariationRange; coverage?: number; /** @deprecated */ namespace?: [string, number, number]; ranges?: VariationRange[]; meta?: VariationMeta[]; filters?: Filter[]; seed?: string; name?: string; phase?: string; tracks?: Array<{ experiment: Experiment; result: Result; }>; contextualBanditRef?: string; contextualVariations?: T[]; metadata?: PayloadMetadata; }; export type ContextualBanditDefinition = { banditVersion?: number; contexts: { leafId: number; condition: Record; weights: number[]; }[]; }; export type ContextualBanditDefinitions = Record< string, ContextualBanditDefinition >; export type InterleavingDefinition = { trackingKey: string; // Carried here, not read off the pseudo flag's rule: remote evaluation // replaces rules with a forced defaultValue, so the rule is gone client-side. hashAttribute: AttributeKey; seed: string; variations: { key: string; config: Record }[]; }; export type InterleavingDefinitions = Record< string, InterleavingDefinition >; export interface FeatureDefinition { defaultValue?: T; rules?: FeatureRule[]; metadata?: PayloadMetadata; } /** * Sent when the SDK Connection opts in. A feature in every project has * `allProjects` instead of `projects`, and one in no project has neither. */ export type PayloadMetadata = { projects?: string[]; allProjects?: boolean; tags?: string[]; customFields?: Record; }; export type FeatureResultSource = | "unknownFeature" | "defaultValue" | "force" | "override" | "experiment" | "prerequisite" | "cyclicPrerequisite"; export interface FeatureResult { value: T | null; source: FeatureResultSource; on: boolean; off: boolean; ruleId: string; experiment?: Experiment; experimentResult?: Result; } /** @deprecated */ export type ExperimentStatus = "draft" | "running" | "stopped"; export type UrlTargetType = "regex" | "simple"; export type UrlTarget = { include: boolean; type: UrlTargetType; pattern: string; }; export type Experiment = { key: string; variations: [T, T, ...T[]]; ranges?: VariationRange[]; meta?: VariationMeta[]; filters?: Filter[]; seed?: string; name?: string; phase?: string; urlPatterns?: UrlTarget[]; weights?: number[]; condition?: ConditionInterface; parentConditions?: ParentConditionInterface[]; coverage?: number; include?: () => boolean; /** @deprecated */ namespace?: [string, number, number]; force?: number; hashAttribute?: AttributeKey; fallbackAttribute?: AttributeKey; hashVersion?: number; disableStickyBucketing?: boolean; bucketVersion?: number; minBucketVersion?: number; active?: boolean; persistQueryString?: boolean; contextualBandit?: CBContext; /** @deprecated */ status?: ExperimentStatus; /** @deprecated */ url?: RegExp; /** @deprecated */ groups?: string[]; }; export type AutoExperimentChangeType = "redirect" | "visual" | "unknown"; export type AutoExperiment< T = AutoExperimentVariation, A extends Attributes = any, > = Experiment & { changeId?: string; // If true, require the experiment to be manually triggered manual?: boolean; metadata?: PayloadMetadata; contextualBanditRef?: string; }; export type ExperimentOverride = { condition?: ConditionInterface; weights?: number[]; active?: boolean; status?: ExperimentStatus; force?: number; coverage?: number; groups?: string[]; namespace?: [string, number, number]; url?: RegExp | string; }; export interface Result { value: T; variationId: number; key: string; name?: string; bucket?: number; passthrough?: boolean; inExperiment: boolean; hashUsed?: boolean; hashAttribute: string; hashValue: string; featureId: string | null; stickyBucketUsed?: boolean; leafId?: number; variationWeights?: number[]; banditVersion?: number; } export type CBContext = { leafId: number; variationWeights: number[]; banditVersion?: number; }; export type Attributes = Record; // The types below that take attributes default to `any`, not `Attributes`, so // that one checked against an app's attributes is still assignable to the // unchecked type that `init`, `setPayload` and the rest accept. // The attributes a user can be hashed on: ones that can hold a string or a // number. Unlike conditions, hashing doesn't look inside object attributes. export type AttributeKey = string extends keyof A ? string : { [K in keyof A & string]: unknown extends A[K] ? K : [Extract] extends [never] ? never : K; }[keyof A & string]; /** * Register your app's feature and attribute types once and every GrowthBook * instance and React hook is typed with no generics: * * declare module "@growthbook/growthbook" { * interface Register { * features: AppFeatures; * attributes: AppAttributes; * } * } * * Register `events` (event name -> properties) to check `logEvent` calls: * * events: { * start_checkout: { plan: "pro" | "enterprise" }; * button_click: { button: string }; * }; */ // eslint-disable-next-line @typescript-eslint/no-empty-object-type export interface Register {} export type RegisteredFeatures = Register extends { features: infer F } ? F : Record; export type RegisteredAttributes = Register extends { attributes: infer A } ? A : Attributes; export type RegisteredEvents = Register extends { events: infer E } ? E : Record; // The arguments after the event name: properties can be left out for an event // that has no required ones export type EventArgs

= Record extends P ? [properties?: P] : [properties: P]; // Stops an argument from being used to infer T, which would override the // registered default (the built-in NoInfer needs TypeScript 5.4+) export type NoInferType = [T][T extends unknown ? 0 : never]; // Loosely typed attributes: callbacks are not tied to one instance's types, so // the registered types would be wrong for an instance with its own generics export type TrackingUserContext = Pick< UserContext, "attributes" | "url" >; export interface TrackingData { experiment: Experiment; result: Result; user?: TrackingUserContext; } export interface TrackingDataWithUser { experiment: Experiment; result: Result; user: TrackingUserContext; } export type TrackingCallback = ( experiment: Experiment, result: Result, user?: TrackingUserContext, ) => Promise | void; export type TrackingCallbackWithUser = ( experiment: Experiment, result: Result, user: TrackingUserContext, ) => Promise | void; export type FeatureUsageCallback = ( key: string, result: FeatureResult, ) => void; export type FeatureUsageCallbackWithUser = ( key: string, result: FeatureResult, user: TrackingUserContext, ) => void; // Callback types for internal plugin subscriptions (e.g. session replay). // Must be synchronous — async callbacks are not awaited and rejected promises won't be caught. export type FeatureUsageSubCallback = ( key: string, result: Readonly>, ) => void; export type CustomEventSubCallback = ( eventName: string, properties: Readonly>, ) => void; export type ExperimentViewedSubCallback = ( experiment: Readonly>, result: Readonly>, user: TrackingUserContext, ) => void; export type Plugin = ( gb: GrowthBook | UserScopedGrowthBook | GrowthBookClient, ) => void; export type EventProperties = Record; export type EventLogger = ( eventName: string, properties: EventProperties, userContext: TrackingUserContext, ) => void | Promise; export type NavigateCallback = (url: string) => void | Promise; export type ApplyDomChangesCallback = ( changes: AutoExperimentVariation, ) => () => void; export type RenderFunction = () => void; // Constructor Options export type Options = { enabled?: boolean; attributes?: AppAttributes; /** The user's remote saved groups; wins over a `__gb_remoteGroupIds` attribute. */ remoteGroupIds?: string[]; url?: string; features?: Record; experiments?: AutoExperiment[]; forcedVariations?: Record; forcedFeatureValues?: Map; attributeOverrides?: Partial; blockedChangeIds?: string[]; disableVisualExperiments?: boolean; disableJsInjection?: boolean; jsInjectionNonce?: string; disableUrlRedirectExperiments?: boolean; disableCrossOriginUrlRedirectExperiments?: boolean; disableExperimentsOnLoad?: boolean; stickyBucketAssignmentDocs?: Record< StickyAttributeKey, StickyAssignmentsDocument >; stickyBucketService?: StickyBucketService; debug?: boolean; log?: (msg: string, ctx: any) => void; qaMode?: boolean; /** @deprecated */ backgroundSync?: boolean; /** @deprecated */ subscribeToChanges?: boolean; /** * The hash version for percentage rollouts and experiments that don't set * their own `hashVersion`. Defaults to 1, which is slightly biased. Changing * it reassigns the users of those rollouts and experiments. */ defaultHashVersion?: number; enableDevMode?: boolean; disableCache?: boolean; /** @deprecated */ disableDevTools?: boolean; trackingCallback?: TrackingCallback; onFeatureUsage?: FeatureUsageCallback; eventLogger?: EventLogger; cacheKeyAttributes?: (keyof Attributes)[]; /** @deprecated */ user?: { id?: string; anonId?: string; [key: string]: string | undefined; }; /** @deprecated */ overrides?: Record; /** @deprecated */ groups?: Record; apiHost?: string; streamingHost?: string; apiHostRequestHeaders?: Record; streamingHostRequestHeaders?: Record; clientKey?: string; renderer?: null | RenderFunction; decryptionKey?: string; remoteEval?: boolean; navigate?: NavigateCallback; navigateDelay?: number; maxNavigateDelay?: number; /** @deprecated */ antiFlicker?: boolean; /** @deprecated */ antiFlickerTimeout?: number; applyDomChangesCallback?: ApplyDomChangesCallback; savedGroups?: SavedGroupsPayload; contextualBandits?: ContextualBanditDefinitions; plugins?: Plugin[]; }; export type ClientOptions< AppAttributes extends Attributes = RegisteredAttributes, > = { enabled?: boolean; debug?: boolean; globalAttributes?: Partial; forcedVariations?: Record; forcedFeatureValues?: Map; log?: (msg: string, ctx: any) => void; qaMode?: boolean; /** * The hash version for percentage rollouts and experiments that don't set * their own `hashVersion`. Defaults to 1, which is slightly biased. Changing * it reassigns the users of those rollouts and experiments. */ defaultHashVersion?: number; disableCache?: boolean; trackingCallback?: TrackingCallbackWithUser; onFeatureUsage?: ( key: string, result: FeatureResult, user: TrackingUserContext, ) => void; eventLogger?: EventLogger; apiHost?: string; streamingHost?: string; apiHostRequestHeaders?: Record; streamingHostRequestHeaders?: Record; clientKey?: string; decryptionKey?: string; savedGroups?: SavedGroupsPayload; contextualBandits?: ContextualBanditDefinitions; plugins?: Plugin[]; }; // Contexts export type GlobalContext = { log: (msg: string, ctx: any) => void; debug?: boolean; features?: FeatureDefinitions; experiments?: AutoExperiment[]; enabled?: boolean; qaMode?: boolean; defaultHashVersion?: number; savedGroups?: SavedGroupsPayload; contextualBandits?: ContextualBanditDefinitions; forcedVariations?: Record; forcedFeatureValues?: Map; trackingCallback?: TrackingCallbackWithUser; onFeatureUsage?: FeatureUsageCallbackWithUser; onExperimentEval?: (experiment: Experiment, result: Result) => void; saveDeferredTrack?: (data: TrackingData) => void; recordChangeId?: (changeId: string) => void; eventLogger?: EventLogger; /** @deprecated */ overrides?: Record; /** @deprecated */ groups?: Record; /** @deprecated */ user?: { id?: string; anonId?: string; [key: string]: string | undefined; }; }; // Some global fields can be overridden by the user, others are always user-level export type UserContext< AppAttributes extends Attributes = RegisteredAttributes, > = { enabled?: boolean; qaMode?: boolean; enableDevMode?: boolean; attributes?: AppAttributes; /** The user's remote saved groups; wins over a `__gb_remoteGroupIds` attribute. */ remoteGroupIds?: string[]; url?: string; blockedChangeIds?: string[]; stickyBucketAssignmentDocs?: Record< StickyAttributeKey, StickyAssignmentsDocument >; saveStickyBucketAssignmentDoc?: ( doc: StickyAssignmentsDocument, ) => Promise; forcedVariations?: Record; forcedFeatureValues?: Map; attributeOverrides?: Partial; trackingCallback?: TrackingCallback; onFeatureUsage?: FeatureUsageCallback; trackedExperiments?: Set; trackedFeatureUsage?: Record; devLogs?: LogUnion[]; featureUsageSubs?: Set; experimentViewedSubs?: Set; }; export type StackContext = { id?: string; evaluatedFeatures: Set; }; export type EvalContext = { global: GlobalContext; user: UserContext; stack: StackContext; }; export type PrefetchOptions = Pick< Options, | "decryptionKey" | "apiHost" | "apiHostRequestHeaders" | "streamingHost" | "streamingHostRequestHeaders" > & { clientKey: string; streaming?: boolean; skipCache?: boolean; }; export type SubscriptionFunction = ( experiment: Experiment, result: Result, ) => void; export type VariationRange = [number, number]; export interface InitResponse { // If a payload was set success: boolean; // Where the payload came from, if set source: "init" | "cache" | "network" | "error" | "timeout"; // If the payload could not be set (success = false), this will hold the fetch error error?: Error; } export interface FetchResponse { data: FeatureApiResponse | null; success: boolean; source: "cache" | "network" | "error" | "timeout"; error?: Error; } export type JSONValue = | null | number | string | boolean | Array | Record | { [key: string]: JSONValue }; export type WidenPrimitives = T extends string ? string : T extends number ? number : T extends boolean ? boolean : T; // What `getFeatureValue` returns: the fallback's type, or with a `null` // fallback, the feature's type or null export type FeatureValueOrFallback = [V] extends [null] ? T | null : WidenPrimitives; export type DOMMutation = { selector: string; action: string; attribute: string; value?: string; parentSelector?: string; insertBeforeSelector?: string; }; export type AutoExperimentVariation = { domMutations?: DOMMutation[]; css?: string; js?: string; urlRedirect?: string; }; // With AppFeatures, a payload written in code is checked against it: unknown // keys and values of the wrong type are errors. Features may be left out, // since a payload omits the ones that are toggled off. Without AppFeatures // (the default) any payload is accepted, as is one typed `FeatureApiResponse`. export type FeatureDefinitions< AppFeatures extends Record = Record, AppAttributes extends Attributes = any, > = string extends keyof AppFeatures ? Record> : { [K in keyof AppFeatures]?: FeatureDefinition< AppFeatures[K], AppAttributes >; }; export type FeatureApiResponse< AppFeatures extends Record = Record, AppAttributes extends Attributes = any, > = { features?: FeatureDefinitions; dateUpdated?: string; encryptedFeatures?: string; experiments?: AutoExperiment[]; encryptedExperiments?: string; savedGroups?: SavedGroupsPayload; encryptedSavedGroups?: string; contextualBandits?: ContextualBanditDefinitions; encryptedContextualBandits?: string; interleavings?: InterleavingDefinitions; encryptedInterleavings?: string; }; // Alias export type GrowthBookPayload = FeatureApiResponse; /** * A payload written in code, such as the `fallbackPayload` given to `init`, * checked against your attributes as well as your features. Targeting * conditions, hash attributes and saved groups must use real attributes, with * operators and values that fit each attribute's type. * * const fallbackPayload: Payload = {...}; * * Uses the registered features and attributes when none are given. */ export type Payload< AppFeatures extends Record = RegisteredFeatures, AppAttributes extends Attributes = RegisteredAttributes, > = FeatureApiResponse; /** A rule in `LocalFeatures`. A percentage rollout needs a `hashAttribute`. */ export type LocalFeatureRule = { force: T; condition?: ConditionInterface; } & ( | { coverage: number; hashAttribute: AttributeKey; /** Hashed with the user instead of the feature key */ seed?: string; } | { coverage?: never; hashAttribute?: never; seed?: never } ); /** * Feature flags hard-coded in a local file and passed to `initSync` as the * payload's `features`. Stricter than `Payload`: every feature must be defined * with a `defaultValue`, and rules are limited to `force`, `condition` and * percentage rollouts. A feature that's optional in your features type may be * left out. * * export const features: LocalFeatures = {...}; * new GrowthBook().initSync({ payload: { features } }); * * Uses the registered features and attributes when none are given. */ export type LocalFeatures< AppFeatures extends Record = RegisteredFeatures, AppAttributes extends Attributes = RegisteredAttributes, > = { [K in keyof AppFeatures]: { defaultValue: Exclude; rules?: LocalFeatureRule< Exclude, AppAttributes >[]; }; }; /** Each filter is an array, and any one of its values is enough */ export type PayloadFilters = { projects?: string[]; tags?: string[]; customFields?: Record; }; export type ReducePayloadOptions = { userContext?: UserContext; /** Keep only the features and auto experiments that match every filter */ include?: PayloadFilters; /** Remove the features and auto experiments that match any filter */ exclude?: PayloadFilters; /** * "keep" (default) sends the prerequisites of what is kept even when the * filters remove them, so the client evaluates the same as the full payload. * "filter" applies the filters to them too. */ prerequisites?: "keep" | "filter"; }; // Polyfills required for non-standard browser environments (ReactNative, Node, etc.) // These are typed as `any` since polyfills like `node-fetch` are not 100% compatible with native types export type Polyfills = { fetch: any; SubtleCrypto: any; EventSource: any; localStorage?: LocalStorageCompat; }; export type Helpers = { fetchFeaturesCall: ({ host, clientKey, headers, }: { host: string; clientKey: string; headers?: Record; }) => Promise; fetchRemoteEvalCall: ({ host, clientKey, payload, headers, }: { host: string; clientKey: string; payload: any; headers?: Record; }) => Promise; eventSourceCall: ({ host, clientKey, headers, }: { host: string; clientKey: string; headers?: Record; }) => EventSource; startIdleListener: () => (() => void) | void; stopIdleListener: () => void; }; export interface LocalStorageCompat { getItem(key: string): string | null | Promise; setItem(key: string, value: string): void | Promise; } export type CacheSettings = { backgroundSync: boolean; cacheKey: string; staleTTL: number; maxAge: number; maxEntries: number; disableIdleStreams: boolean; idleStreamInterval: number; disableCache: boolean; }; export type ApiHost = string; export type ClientKey = string; export type InitOptions< AppFeatures extends Record = Record, > = { timeout?: number; skipCache?: boolean; payload?: FeatureApiResponse; /** Used when the fetch fails or times out and there is no cached payload, e.g. a copy bundled at build time. */ fallbackPayload?: FeatureApiResponse; streaming?: boolean; /** Refresh the payload on this interval (ms). Ignored when streaming is active. */ pollingInterval?: number; cacheSettings?: CacheSettings; }; export type InitSyncOptions< AppFeatures extends Record = Record, > = { payload: FeatureApiResponse; streaming?: boolean; /** Refresh the payload on this interval (ms). Ignored when streaming is active. */ pollingInterval?: number; }; export type LoadFeaturesOptions = { /** @deprecated */ autoRefresh?: boolean; timeout?: number; skipCache?: boolean; }; export type RefreshFeaturesOptions = { timeout?: number; skipCache?: boolean; }; export type DestroyOptions = { destroyAllStreams?: boolean; }; export interface Filter { // Override the hashAttribute used for this filter attribute?: AttributeKey; // The hash seed seed: string; // The hashing version to use hashVersion: number; // Only include these resulting ranges ranges: VariationRange[]; } export type StickyAttributeKey = string; // `${attributeName}||${attributeValue}` export type StickyExperimentKey = string; // `${experimentId}__{version}` export type StickyAssignments = Record; export interface StickyAssignmentsDocument { attributeName: string; attributeValue: string; assignments: StickyAssignments; } /** The v1 shape: an ID list's values. New code should use SavedGroupsPayload. */ export type SavedGroupsValues = Record; /** The savedGroupReferencesV2 shape of one saved group, of any type. */ export type SavedGroupPayloadEntry = | { type: "list"; attributeKey: AttributePath; values: (string | number)[]; } | { type: "condition"; condition: ConditionInterface } // IDs live outside the payload; see `SavedGroupResolver` | { type: "remote"; attributeKey: AttributePath; /** * Set on a derived group (ID `:`): the remote group * whose IDs `attributeKey`'s value is looked up in. */ valuesFrom?: string; }; /** A remote saved group from the payload, as a resolver sees it. */ export type RemoteSavedGroup = { id: string; attributeKey: string; /** For a derived group, the remote group whose IDs it checks. */ valuesFrom?: string; }; /** * Looks up which of `groups` a user is in, from their `attributes` (only the * ones remote groups use). Returns the group IDs. */ export type SavedGroupResolver = (args: { attributes: Attributes; groups: RemoteSavedGroup[]; }) => Promise; /** The `savedGroups` payload field. Entries may use either shape above. */ export type SavedGroupsPayload = Record< string, (string | number)[] | SavedGroupPayloadEntry >; export type BaseLog = { timestamp: string; }; export type EventLog = BaseLog & { logType: "event"; eventName: string; properties?: Record; }; export type ExperimentLog = BaseLog & { logType: "experiment"; experiment: Experiment; result: Result; }; export type FeatureLog = BaseLog & { logType: "feature"; featureKey: string; result: FeatureResult; }; export type LogUnion = EventLog | ExperimentLog | FeatureLog;