import { LDFlagValue, LDEvaluationReason, LDFlagSet, LDContext, LDClientContext, LDEvaluationDetail, internal, LDLogger, VoidFunction, subsystem, LDEvaluationDetailTyped, AttributeReference, LDFileDataSourceError, LDPluginEnvironmentMetadata, Platform, DefaultBackoff, EventSource, EventSourceInitDict } from '@launchdarkly/js-sdk-common'; export * from '@launchdarkly/js-sdk-common'; import * as jsSdkCommon from '@launchdarkly/js-sdk-common'; export { jsSdkCommon as platform }; /** * The return type of {@link BigSegmentStore.getUserMembership}, describing which Big Segments a * specific user is included in or excluded from. * * This object may be cached by the SDK, so it should not be modified after it is created. It * is a snapshot of the segment membership state at one point in time. */ interface BigSegmentStoreMembership { /** * Each property key in this object is a "segment reference", which is how segments are * identified in Big Segment data. This string is not identical to the segment key-- the SDK * will add other information. The store implementation should not be concerned with the * format of the string. * * A true value means that the user is explicitly included in the segment. A false value * means that the user is explicitly excluded from the segment-- and is not also explicitly * included (that is, if both an include and an exclude existed in the data, the include would * take precedence). If the user's status in a particular segment is undefined, there should * be no key or value for that segment. */ [segmentRef: string]: boolean; } /** * Values returned by BigSegmentStore.getMetadata(). */ interface BigSegmentStoreMetadata { /** * The Unix epoch millisecond timestamp of the last update to the BigSegmentStore. It is * undefined if the store has never been updated. */ lastUpToDate?: number; } /** * A read-only data store that allows querying of user membership in Big Segments. * * Big Segments are a specific type of user segments. For more information, read the LaunchDarkly * documentation: https://docs.launchdarkly.com/home/users/big-segments */ interface BigSegmentStore { /** * Queries information about the overall state of the store. * * The resolved value of the Promise should always be a {@link BigSegmentStoreMetadata} object. * If the store is accessible but contains no metadata, the object's `lastUpToDate` property can * be undefined. If the store is not accessible due to a database error, the method can throw an * exception/reject the promise. * * This method will be called only when the SDK needs the latest state, so it should not be * cached. * * @returns a Promise for the result of the query */ getMetadata(): Promise; /** * Queries the store for a snapshot of the current segment state for a specific user. * * The userHash is a base64-encoded string produced by hashing the user key as defined by * the Big Segments specification; the store implementation does not need to know the details * of how this is done, because it deals only with already-hashed keys, but the string can be * assumed to only contain characters that are valid in base64. * * The resolved value of the Promise should be either a {@link BigSegmentStoreMembership}, or * undefined if the user is not referenced in any Big Segments (this is equivalent to a * {@link BigSegmentStoreMembership} that has no properties). * * @param userHash identifies the user * @returns a Promise for the result of the query. */ getUserMembership(userHash: string): Promise; /** * Releases any resources being used by the store. */ close(): void; } /** * Information about the status of a Big Segment store, provided by * {@link BigSegmentStoreStatusProvider}. * * Big Segments are a specific type of user segments. For more information, read the LaunchDarkly * documentation: https://docs.launchdarkly.com/home/users/big-segments */ interface BigSegmentStoreStatus { /** * True if the Big Segment store is able to respond to queries, so that the SDK can * evaluate whether a user is in a segment or not. * * If this property is false, the store is not able to make queries (for instance, it may not have * a valid database connection). In this case, the SDK will treat any reference to a Big Segment * as if no users are included in that segment. Also, the {@link LDEvaluationReason} associated * with any flag evaluation that references a Big Segment when the store is not available will * have a `bigSegmentsStatus` of `"STORE_ERROR"`. */ available: boolean; /** * True if the Big Segment store is available, but has not been updated within the amount of time * specified by {@link LDBigSegmentsOptions.staleAfter}. * * This may indicate that the LaunchDarkly Relay Proxy, which populates the store, has stopped * running or has become unable to receive fresh data from LaunchDarkly. Any feature flag * evaluations that reference a Big Segment will be using the last known data, which may be out * of date. */ stale: boolean; } /** * Used internally to describe the type of data being queried or updated, such as feature flags or * user segments. */ interface DataKind { /** * A string such as `"features"` or `"segments"` which can be used in keys to distinguish this * kind of data from other kinds. */ namespace: string; } /** * Used internally for data store implementations that require items in an ordered list rather * than as object properties. */ interface DataCollection { /** * Describes the kind of items, such as feature flags or user segments. */ kind: DataKind; /** * An ordered list of items of this kind. */ items: Array; } /** * Used internally to describe a set of stored data items of the same kind, such as feature flags * or user segments. The string key for each item is the same as the item's `key` property. */ type KeyedItems$1 = Record; /** * Used internally to describe a full set of environment data, which can include both feature * flags and user segments. The string key for each item is the `namespace` property of a * {@link interfaces.DataKind}. */ type FullDataSet = Record>; /** * Used internally to describe the basic properties of stored data such as feature flags or user * segments. * * This is the actual type of parameters and return values in `LDFeatureStore` methods that refer * to a flag or segment item. Those methods still use the `object` type for backward compatibility. */ interface VersionedData { /** * The item's unique key, such as a feature flag key. */ key: string; /** * A version number that LaunchDarkly will increment each time this item is changed. */ version: number; /** * True if this is a deleted item placeholder (tombstone). */ deleted?: boolean; } /** * An interface for querying the status of a Big Segment store. * * The Big Segment store is the component that receives information about Big Segments, normally * from a database populated by the LaunchDarkly Relay Proxy. Big Segments are a specific type of * user segments. For more information, read the LaunchDarkly documentation: * https://docs.launchdarkly.com/home/users/big-segments * * An implementation of this interface is returned by * {@link LDClient.bigSegmentStoreStatusProvider}. Application code never needs to implement this * interface. */ interface BigSegmentStoreStatusProvider { /** * Gets the current status of the store, if known. * * @returns a {@link BigSegmentStoreStatus}, or `undefined` if the SDK has not yet queried the * Big Segment store status */ getStatus(): BigSegmentStoreStatus | undefined; /** * Gets the current status of the store, querying it if the status has not already been queried. * * @returns a Promise for the status of the store */ requireStatus(): Promise; } /** * A versioned item (or placeholder). Used for interoperability between persistent stores and the * SDK. The persistent store should generally operate on {@link SerializedItemDescriptor}s, but * aside from a special case described in {@link PersistentDataStore}. */ interface ItemDescriptor { /** * The version of the data, provided by the SDK. */ readonly version: number; /** * The data item, or null is this is a placeholder. */ readonly item: any; } /** * Represents a key-item pair. This is for use where associative data needs to * be represented as a list, such as maintaining the order of the items. */ interface KeyedItem { key: KeyType; item: ItemType; } /** * Represents a separately namespaced collection of storable data items. * The SDK passes instances of this type to the persistent data store to specify whether it is * referring to a feature flag, a user segment, etc. The data store implementation should not look * for a specific data kind (such as feature flags), but should treat all data kinds generically. */ interface PersistentStoreDataKind { readonly namespace: string; /** * Creates an item of this kind from its serialized representation. * * The SDK uses this function to translate data that is returned by a {@link PersistentDataStore}. * Store implementations do not normally need to call it, but there is a special case described in * the documentation for {@link PersistentDataStore}, regarding updates. * * The returned {@link ItemDescriptor} has two properties: {@link ItemDescriptor#item}, which * is the deserialized object or a `null` value for a deleted item placeholder, and * {@link ItemDescriptor#version}, which provides the object's version number regardless of * whether it is deleted or not. * * @param data the serialized representation * @return an {@link ItemDescriptor} describing the deserialized object or null if the item could * not be deserialized */ deserialize(data: string): ItemDescriptor | undefined; } /** * A versioned item (or placeholder) storable in a [PersistentDataStore]. */ interface SerializedItemDescriptor { /** * The version of the data. */ readonly version: number; /** * True if this a placeholder (tombstone) for a deleted item. * * If so, {@link #serializedItem} will still contain a string representing the deleted item, but * the persistent store implementation has the option of not storing it if it can represent the * placeholder in a more efficient way. */ readonly deleted?: boolean; /** * Returns the data item's serialized representation. This will never be null when storing an * item; for a deleted item placeholder, it will contain a special value that can be stored if * necessary. When reading an item from a store this could be null. * (see {@link #deleted()}). */ readonly serializedItem?: string; } type KeyedItems = KeyedItem[]; type KindKeyedStore = KeyedItems>; /** * This interface should be used for database integrations, or any other data store * implementation that stores data in some external service. The SDK will take care of * converting between its own internal data model and a serialized string form; the data * store interacts only with the serialized form. The SDK will also provide its own caching * layer on top of the persistent data store; the data store implementation should not * provide caching, but simply do every query or update that the SDK tells it to do. * * Conceptually, each item in the store is a {@link SerializedItemDescriptor} which always has * a version number, and can represent either a serialized object or a placeholder (tombstone) * for a deleted item. There are two approaches a persistent store implementation can use for * persisting this data: * * 1. Preferably, it should store the version number and the * {@link SerializedItemDescriptor#deleted} state separately so that the object does not need to be * fully deserialized to read them. In this case, deleted item placeholders can ignore the value of * {@link SerializedItemDescriptor#item} on writes and can set it to undefined on reads. The store * should never call {@link DataKind#deserialize}. * * 2. If that isn't possible, then the store should simply persist the exact string from * {@link SerializedItemDescriptor#serializedItem} on writes, and return the persisted * string on reads (returning zero for the version and false for * {@link SerializedItemDescriptor#deleted}). The string is guaranteed to provide the SDK with * enough information to infer the version and the deleted state. On updates, the store must call * {@link PersistentStoreDataKind#deserialize} in order to inspect the version number of the * existing item if any. */ interface PersistentDataStore { /** * Overwrites the store's contents with a set of items for each collection. * * All previous data should be discarded, regardless of versioning. * * The update should be done atomically. If it cannot be done atomically, then the store * must first add or update each item in the same order that they are given in the input * data, and then delete any previously stored items that were not in the input data. * * @param allData a list of {@link PersistentStoreDataKind} instances and their corresponding data * sets * @param callback will be called when the init completes. If the store could not apply the * data, then it may be called with an error. Implementations are not required to report * errors. */ init(allData: KindKeyedStore, callback: (err?: Error) => void): void; /** * Retrieves an item from the specified collection, if available. * * If the key is not known at all, the callback should be invoked with undefined. Otherwise, it * should be invoked with a {@link SerializedItemDescriptor} as follows: * * 1. If the version number and deletion state can be determined without fully deserializing * the item, then the store should set those properties in the {@link SerializedItemDescriptor} * (and can set {@link SerializedItemDescriptor#serializedItem} to undefined for deleted items). * * 2. Otherwise, it should simply set {@link SerializedItemDescriptor#serializedItem} to * the exact string that was persisted, and can leave the other properties as zero/false. See * comments on {@link PersistentDataStore} for more about this. * * If the store cannot be read, the callback should be invoked with undefined and the error. * The SDK caches a missing item until the cache TTL expires, but it does not cache a failed * read. A store that does not pass the error has its failed reads cached as missing items. * * @param kind specifies which collection to use * @param key the unique key of the item within that collection * @param callback a callback which will be invoked on completion of the get */ get(kind: PersistentStoreDataKind, key: string, callback: (descriptor: SerializedItemDescriptor | undefined, err?: Error) => void): void; /** * Retrieves all items from the specified collection. * * If the store contains placeholders for deleted items, it should include them in the results, * not filter them out. See {@link #get} for how to set the properties of the * {@link SerializedItemDescriptor} for each item. * * @param kind specifies which collection to use * @param callback method that will be invoked with the results of the operation. */ getAll(kind: PersistentStoreDataKind, callback: (descriptors: KeyedItem[] | undefined) => void): void; /** * Updates or inserts an item in the specified collection. * * If the given key already exists in that collection, the store must check the version number * of the existing item (even if it is a deleted item placeholder); if that version is greater * than or equal to the version of the new item, the update fails and the method returns false. * If the store is not able to determine the version number of an existing item without fully * deserializing the existing item, then it is allowed to call * {@link PersistentStoreDataKind#deserialize} for that purpose. * * If the item's {@link SerializedItemDescriptor#deleted} method returns true, this is a * deleted item placeholder. The store must persist this, rather than simply removing the key * from the store. The SDK will provide a string in * {@link SerializedItemDescriptor#serializedItem} which the store can persist for this purpose; * or, if the store is capable of persisting the version number and deleted state without storing * anything else, it should do so. * * @param kind specifies which collection to use * @param key the unique key for the item within that collection * @param descriptor the item to insert or update * @param callback will be called with `true` if the item was inserted, or `false` if the version * was not newer than the existing item. */ upsert(kind: PersistentStoreDataKind, key: string, descriptor: SerializedItemDescriptor, callback: (err?: Error, updatedDescriptor?: SerializedItemDescriptor) => void): void; /** * Tests whether the store is initialized. * * "Initialized" means that the store has been populated with data, either by the client * having called {@link #init} within this process, or by another process (if this is a shared * database). * * @param callback * Will be called back with the boolean result. */ initialized(callback: (isInitialized: boolean) => void): void; /** * Check if the underlying storage can be accessed. * * The check must be inexpensive, for example a read of a single key. It must not write * any data. The SDK can call this method at a fixed interval while the store is in an * error state. * * @param callback * Will be called with true when the storage responds to the check, or with false when * it does not. */ isStoreAvailable?(callback: (isAvailable: boolean) => void): void; /** * Releases any resources being used by the feature store. */ close(): void; /** * Get a description of the feature store. */ getDescription(): string; } type index$3_BigSegmentStore = BigSegmentStore; type index$3_BigSegmentStoreMembership = BigSegmentStoreMembership; type index$3_BigSegmentStoreMetadata = BigSegmentStoreMetadata; type index$3_BigSegmentStoreStatus = BigSegmentStoreStatus; type index$3_BigSegmentStoreStatusProvider = BigSegmentStoreStatusProvider; type index$3_DataCollection = DataCollection; type index$3_DataKind = DataKind; type index$3_FullDataSet = FullDataSet; type index$3_ItemDescriptor = ItemDescriptor; type index$3_KeyedItem = KeyedItem; type index$3_KindKeyedStore = KindKeyedStore; type index$3_PersistentDataStore = PersistentDataStore; type index$3_PersistentStoreDataKind = PersistentStoreDataKind; type index$3_SerializedItemDescriptor = SerializedItemDescriptor; type index$3_VersionedData = VersionedData; declare namespace index$3 { export type { index$3_BigSegmentStore as BigSegmentStore, index$3_BigSegmentStoreMembership as BigSegmentStoreMembership, index$3_BigSegmentStoreMetadata as BigSegmentStoreMetadata, index$3_BigSegmentStoreStatus as BigSegmentStoreStatus, index$3_BigSegmentStoreStatusProvider as BigSegmentStoreStatusProvider, index$3_DataCollection as DataCollection, index$3_DataKind as DataKind, index$3_FullDataSet as FullDataSet, index$3_ItemDescriptor as ItemDescriptor, index$3_KeyedItem as KeyedItem, KeyedItems$1 as KeyedItems, index$3_KindKeyedStore as KindKeyedStore, index$3_PersistentDataStore as PersistentDataStore, index$3_PersistentStoreDataKind as PersistentStoreDataKind, index$3_SerializedItemDescriptor as SerializedItemDescriptor, index$3_VersionedData as VersionedData }; } /** * @ignore */ declare class BigSegmentStoreStatusProviderImpl implements BigSegmentStoreStatusProvider { private readonly _onRequestStatus; private _lastStatus; private _listener?; constructor(_onRequestStatus: () => Promise); /** * Gets the current status of the store, if known. * * @returns a {@link BigSegmentStoreStatus}, or `undefined` if the SDK has not yet queried the * Big Segment store status */ getStatus(): BigSegmentStoreStatus | undefined; /** * Gets the current status of the store, querying it if the status has not already been queried. * * @returns a Promise for the status of the store */ requireStatus(): Promise; notify(): void; setListener(listener: (status: BigSegmentStoreStatus) => void): void; setStatus(status: BigSegmentStoreStatus): void; } /** * Optional settings that can be passed to `LDClient.allFlagsState`. */ interface LDFlagsStateOptions { /** * True if the state should include only flags that have been marked for use with the * client-side SDK. By default, all flags are included. */ clientSideOnly?: boolean; /** * True if evaluation reason data should be captured in the state object (see * LDClient.variationDetail). By default, it is not. */ withReasons?: boolean; /** * True if any flag metadata that is normally only used for event generation-- such as flag * versions and evaluation reasons-- should be omitted for any flag that does not have event * tracking or debugging turned on. This reduces the size of the JSON data if you are passing the * flag state to the front end. */ detailsOnlyForTrackedFlags?: boolean; } /** * An object that contains the state of all feature flags, generated by `LDClient.allFlagsState`. */ interface LDFlagsState { /** * True if this object contains a valid snapshot of feature flag state, or false if the * state could not be computed (for instance, because the client was offline or there * was no user). */ valid: boolean; /** * Returns the value of an individual feature flag at the time the state was recorded. * It will be null if the flag returned the default value, or if there was no such flag. * * @param key * The flag key. */ getFlagValue(key: string): LDFlagValue; /** * Returns the evaluation reason for a feature flag at the time the state was recorded. * It will be null if reasons were not recorded, or if there was no such flag. * * @param key * The flag key. */ getFlagReason(key: string): LDEvaluationReason | null; /** * Returns a map of feature flag keys to values. If a flag would have evaluated to the * default value, its value will be null. * * Do not use this method if you are passing data to the front end to "bootstrap" the * JavaScript client. Instead, use {@link toJSON}. */ allValues(): LDFlagSet; /** * Returns a Javascript representation of the entire state map, in the format used by * the Javascript SDK. Use this method if you are passing data to the front end in * order to "bootstrap" the JavaScript client. * * Do not rely on the exact shape of this data, as it may change in future to support * the needs of the JavaScript client. */ toJSON(): object; } /** * Stage denotes one of six possible stages a technology migration could be a * part of, progressing through the following order. * * Off -> DualWrite -> Shadow -> Live -> RampDown -> Complete */ declare enum LDMigrationStage { /** * Off - migration hasn't started, "old" is authoritative for reads and writes */ Off = "off", /** * DualWrite - write to both "old" and "new", "old" is authoritative for reads */ DualWrite = "dualwrite", /** * Shadow - both "new" and "old" versions run with a preference for "old" */ Shadow = "shadow", /** * Live - both "new" and "old" versions run with a preference for "new" */ Live = "live", /** * RampDown - only read from "new", write to "old" and "new" */ RampDown = "rampdown", /** * Complete - migration is done */ Complete = "complete" } /** * Check if the given string is a migration stage. * @param value The string to check. * @returns True if the string is a migration stage. */ declare function IsMigrationStage(value: string): boolean; type LDMigrationOp = 'read' | 'write'; /** * Component of an LDMigrationOpEvent which tracks information about the * evaluation of the migration flag. */ interface LDMigrationEvaluation { key: string; value: LDMigrationStage; default: LDMigrationStage; variation?: number; version?: number; reason: LDEvaluationReason; } interface LDMigrationConsistencyMeasurement { key: 'consistent'; value: boolean; samplingRatio: number; } interface LDMigrationLatencyMeasurement { key: 'latency_ms'; values: { old?: number; new?: number; }; } interface LDMigrationErrorMeasurement { key: 'error'; values: { old?: boolean; new?: boolean; }; } interface LDMigrationInvokedMeasurement { key: 'invoked'; values: { old?: boolean; new?: boolean; }; } /** * Types of measurements supported by an LDMigrationOpEvent. */ type LDMigrationMeasurement = LDMigrationLatencyMeasurement | LDMigrationErrorMeasurement | LDMigrationConsistencyMeasurement | LDMigrationInvokedMeasurement; /** * Event used to track information about a migration operation. * * Generally this event should not be created directly and instead an * LDMigrationOpTracker should be used to generate it. */ interface LDMigrationOpEvent { kind: 'migration_op'; operation: LDMigrationOp; creationDate: number; /** * @deprecated Use 'context' instead. */ contextKeys?: Record; context?: LDContext; evaluation: LDMigrationEvaluation; measurements: LDMigrationMeasurement[]; samplingRatio: number; } /** * Specifies the origin of the result or error. * * Results from `readOld` or `writeOld` will be 'old'. * Results from `readNew` or `writeNew` will be 'new'. */ type LDMigrationOrigin = 'old' | 'new'; /** * Result of a component of an LDMigration. * * Should not need to be used by a consumer of this API directly. */ type LDMigrationResult = { success: true; origin: LDMigrationOrigin; result: TResult; } | { success: false; origin: LDMigrationOrigin; error: any; }; /** * Result of a migration read operation. */ type LDMigrationReadResult = LDMigrationResult; /** * Result of a migration write operation. * * Authoritative writes are done before non-authoritative, so the authoritative * field should contain either an error or a result. * * If the authoritative write fails, then the non-authoritative operation will * not be executed. When this happens the nonAuthoritative field will not be * populated. * * When the non-authoritative operation is executed, then it will result in * either a result or an error and the field will be populated as such. */ type LDMigrationWriteResult = { authoritative: LDMigrationResult; nonAuthoritative?: LDMigrationResult; }; /** * Interface representing a migration. */ interface LDMigration { /** * Perform a read using the migration. * * @param key The key of the flag controlling the migration. * @param context The context requesting the flag. The client will generate an analytics event to * register this context with LaunchDarkly if the context does not already exist. * @param defaultValue The default migration step. Used if the value is not available from * LaunchDarkly. */ read(key: string, context: LDContext, defaultValue: LDMigrationStage, payload?: TMigrationReadInput): Promise>; /** * Perform a write using the migration. * * @param key The key of the flag controlling the migration. * @param context The context requesting the flag. The client will generate an analytics event to * register this context with LaunchDarkly if the context does not already exist. * @param defaultValue The default migration step. Used if the value is not available from * LaunchDarkly. */ write(key: string, context: LDContext, defaultValue: LDMigrationStage, payload?: TMigrationWriteInput): Promise>; } /** * Used for reporting the state of a consistency check. */ declare enum LDConsistencyCheck { Inconsistent = 0, Consistent = 1, NotChecked = 2 } /** * Used to track information related to a migration operation. */ interface LDMigrationTracker { /** * Sets the migration related operation associated with these tracking measurements. * * @param op The operation being tracked. */ op(op: LDMigrationOp): void; /** * Report that an error has occurred for the specified origin. * * @param origin The origin of the error. */ error(origin: LDMigrationOrigin): void; /** * Check the consistency of a read result. This method should be invoked if the `check` function * is defined for the migration and both reads ("new"/"old") were done. * * The function will use the checkRatio to determine if the check should be executed, and it * will record the result. * * Example calling the check function from the migration config. * ``` * context.tracker.consistency(() => config.check!(oldValue.result, newValue.result)); * ``` * * If the consistency check function throws an exception, then the consistency check result * will not be included in the generated event. * * @param check The function which executes the check. This is not the `check` function from the * migration options, but instead should be a parameter-less function that calls that function. */ consistency(check: () => boolean): void; /** * Call this to report that an origin was invoked (executed). There are some situations where the * expectation is that both the old and new implementation will be used, but with writes * it is possible that the non-authoritative will not execute. Reporting the execution allows * for more accurate analytics. * * @param origin The origin that was invoked. */ invoked(origin: LDMigrationOrigin): void; /** * Report the latency of an operation. * * @param origin The origin the latency is being reported for. * @param value The latency, in milliseconds, of the operation. */ latency(origin: LDMigrationOrigin, value: number): void; /** * Create a migration op event. If the event could not be created, because of a missing * operation, then undefined is returned. */ createEvent(): LDMigrationOpEvent | undefined; } /** * Migration value and tracker. */ interface LDMigrationVariation { /** * The result of the flag evaluation. This will be either one of the flag's variations or * the default value that was passed to `LDClient.migrationVariation`. */ value: LDMigrationStage; /** * A tracker which can be used to generate analytics for the migration. */ tracker: LDMigrationTracker; } /** * Additional parameters for configuring the SDK's Big Segments behavior. * * Big Segments are a specific type of user segments. For more information, read the LaunchDarkly * documentation: https://docs.launchdarkly.com/home/users/big-segments * * @see {@link LDOptions.bigSegments} */ interface LDBigSegmentsOptions { /** * Specifies the storage component that provides Big Segments data. * * This property is mandatory. It must be obtained from one of the SDK's database integrations, * such as https://github.com/launchdarkly/node-server-sdk-redis. You will normally specify a * database implementation that matches how the LaunchDarkly Relay Proxy is configured, since the * Relay Proxy manages the Big Segment data. */ store: (clientContext: LDClientContext) => BigSegmentStore; /** * The maximum number of users whose Big Segment state will be cached by the SDK at any given * time. * * To reduce database traffic, the SDK maintains a least-recently-used cache by user key. When a * feature flag that references a Big Segment is evaluated for some user who is not currently in * the cache, the SDK queries the database for all Big Segment memberships of that user, and * stores them together in a single cache entry. If the cache is full, the oldest entry is * dropped. * * A higher value for `userCacheSize` means that database queries for Big Segments will be done * less often for recently-referenced users, if the application has many users, at the cost of * increased memory used by the cache. * * Cache entries can also expire based on the setting of {@link userCacheTime}. * * If not specified, the default value is 1000. */ userCacheSize?: number; /** * The maximum length of time that the Big Segment state for a user will be cached by the SDK, * in seconds. * * See {@link userCacheSize} for more about this cache. A higher value for `userCacheTime` means * that database queries for the Big Segment state of any given user will be done less often, but * that changes to segment membership may not be detected as soon. * * If not specified, the default value is 5. Negative values are changed to the default. */ userCacheTime?: number; /** * The interval at which the SDK will poll the Big Segment store to make sure it is available * and to determine how long ago it was updated, in seconds. * * If not specified, the default value is 5. Zero or negative values are changed to the default. */ statusPollInterval?: number; /** * The maximum length of time between updates of the Big Segments data before the data is * considered out of date, in seconds. * * Normally, the LaunchDarkly Relay Proxy updates a timestamp in the Big Segment store at * intervals to confirm that it is still in sync with the LaunchDarkly data, even if there have * been no changes to the store. * If the timestamp falls behind the current time by the amount specified in `staleAfter`, the * SDK assumes that something is not working correctly in this process and that the data may not * be accurate. * * While in a stale state, the SDK will still continue using the last known data, but the status * from * {@link interfaces.BigSegmentStoreStatusProvider.getStatus} will have `stale: true`, and any * {@link LDEvaluationReason} generated from a feature flag that references a Big Segment will * have a `bigSegmentsStatus` of `"STALE"`. * * If not specified, the default value is 120 (two minutes). Zero or negative values are changed * to the default. */ staleAfter?: number; } /** * Contextual information provided to evaluation stages. */ interface EvaluationSeriesContext { readonly flagKey: string; readonly context: LDContext; readonly defaultValue: unknown; readonly method: string; readonly environmentId?: string; } /** * Implementation specific hook data for evaluation stages. * * Hook implementations can use this to store data needed between stages. */ interface EvaluationSeriesData { readonly [index: string]: unknown; } /** * Meta-data about a hook implementation. */ interface HookMetadata { readonly name: string; } /** * Interface for extending SDK functionality via hooks. */ interface Hook { /** * Get metadata about the hook implementation. */ getMetadata(): HookMetadata; /** * The before method is called during the execution of a variation method * before the flag value has been determined. The method is executed synchronously. * * @param hookContext Contains information about the evaluation being performed. This is not * mutable. * @param data A record associated with each stage of hook invocations. Each stage is called with * the data of the previous stage for a series. The input record should not be modified. * @returns Data to use when executing the next state of the hook in the evaluation series. It is * recommended to expand the previous input into the return. This helps ensure your stage remains * compatible moving forward as more stages are added. * ```js * return {...data, "my-new-field": /*my data/*} * ``` */ beforeEvaluation?(hookContext: EvaluationSeriesContext, data: EvaluationSeriesData): EvaluationSeriesData; /** * The after method is called during the execution of the variation method * after the flag value has been determined. The method is executed synchronously. * * @param hookContext Contains read-only information about the evaluation * being performed. * @param data A record associated with each stage of hook invocations. Each * stage is called with the data of the previous stage for a series. * @param detail The result of the evaluation. This value should not be * modified. * @returns Data to use when executing the next state of the hook in the evaluation series. It is * recommended to expand the previous input into the return. This helps ensure your stage remains * compatible moving forward as more stages are added. * ```js * return {...data, "my-new-field": /*my data/*} * ``` */ afterEvaluation?(hookContext: EvaluationSeriesContext, data: EvaluationSeriesData, detail: LDEvaluationDetail): EvaluationSeriesData; } type InitMetadata$2 = internal.InitMetadata; /** * Represents an item which can be stored in the feature store. */ interface LDFeatureStoreItem { deleted?: boolean; version: number; [attribute: string]: any; } /** * When upserting an item it must contain a key. */ interface LDKeyedFeatureStoreItem extends LDFeatureStoreItem { key: string; } /** * Represents the storage for a single kind of data. e.g. 'flag' or 'segment'. */ interface LDFeatureStoreKindData { [key: string]: LDFeatureStoreItem; } /** * Represents the storage for the full data store. */ interface LDFeatureStoreDataStorage { [namespace: string]: LDFeatureStoreKindData; } /** * Interface for a feature store component. * * The feature store is what the client uses to store feature flag data that has been received * from LaunchDarkly. By default, it uses an in-memory implementation; database integrations are * also available. Read the [SDK features guide](https://docs.launchdarkly.com/sdk/concepts/data-stores). * You will not need to use this interface unless you are writing your own implementation. * * Feature store methods can and should call their callbacks directly whenever possible, rather * than deferring them with setImmediate() or process.nextTick(). This means that if for any * reason you are updating or querying a feature store directly in your application code (which * is not part of normal use of the SDK) you should be aware that the callback may be executed * immediately. */ interface LDFeatureStore { /** * Get an entity from the store. * * The store should treat any entity with the property `deleted: true` as "not found". * * @param kind * The type of data to be accessed. The store should not make any assumptions about the format * of the data, but just return a JSON object. The actual type of this parameter is * {@link interfaces.DataKind}. * * @param key * The unique key of the entity within the specified collection. * * @param callback * Will be called with the retrieved entity, or null if not found. The actual type of the result * value is {@link interfaces.VersionedData}. */ get(kind: DataKind, key: string, callback: (res: LDFeatureStoreItem | null) => void): void; /** * Get all entities from a collection. * * The store should filter out any entities with the property `deleted: true`. * * @param kind * The type of data to be accessed. The store should not make any assumptions about the format * of the data, but just return an object in which each key is the `key` property of an entity * and the value is the entity. The actual type of this parameter is * {@link interfaces.DataKind}. * * @param callback * Will be called with the resulting map. The actual type of the result value is * `interfaces.KeyedItems`. */ all(kind: DataKind, callback: (res: LDFeatureStoreKindData) => void): void; /** * Initialize the store, overwriting any existing data. * * @param allData * An object in which each key is the "namespace" of a collection (e.g. `"features"`) and * the value is an object that maps keys to entities. The actual type of this parameter is * `interfaces.FullDataSet`. * * @param callback * Will be called when the store has been initialized. If the store could not apply the * data, then it may be called with an error. Implementations are not required to report * errors. * * @param initMetadata * Optional metadata to initialize the feature store with. */ init(allData: LDFeatureStoreDataStorage, callback: (err?: Error) => void, initMetadata?: InitMetadata$2): void; /** * Delete an entity from the store. * * Deletion should be implemented by storing a placeholder object with the property * `deleted: true` and a `version` property equal to the provided version. In other words, * it should be exactly the same as calling `upsert` with such an object. * * @param kind * The type of data to be accessed. The actual type of this parameter is * {@link interfaces.DataKind}. * * @param key * The unique key of the entity within the specified collection. * * @param version * A number that must be greater than the `version` property of the existing entity in * order for it to be deleted. If it is less than or equal to the existing version, the * method should do nothing. * * @param callback * Will be called when the delete operation is complete. */ delete(kind: DataKind, key: string, version: number, callback: () => void): void; /** * Add an entity or update an existing entity. * * @param kind * The type of data to be accessed. The actual type of this parameter is * {@link interfaces.DataKind}. * * @param data * The contents of the entity, as an object that can be converted to JSON. The store * should check the `version` property of this object, and should *not* overwrite any * existing data if the existing `version` is greater than or equal to that value. * The actual type of this parameter is {@link interfaces.VersionedData}. * * @param callback * Will be called after the upsert operation is complete. If the store could not apply * the update, then it may be called with an error. Implementations are not required to * report errors. */ upsert(kind: DataKind, data: LDKeyedFeatureStoreItem, callback: (err?: Error) => void): void; /** * Tests whether the store is initialized. * * "Initialized" means that the store has been populated with data, either by the client * having called `init()` within this process, or by another process (if this is a shared * database). * * @param callback * Will be called back with the boolean result. */ initialized(callback: (isInitialized: boolean) => void): void; /** * Check if the underlying storage can be accessed. * * The check must be inexpensive, for example a read of a single key. It must not write * any data. The SDK can call this method at a fixed interval while the store is in an * error state. * * @param callback * Will be called with true when the storage responds to the check, or with false when * it does not. */ isStoreAvailable?(callback: (isAvailable: boolean) => void): void; /** * Releases any resources being used by the feature store. */ close(): void; /** * Get a description of the store. */ getDescription?(): string; /** * Get the initialization metadata of the store. */ getInitMetaData?(): InitMetadata$2 | undefined; } type InitMetadata$1 = internal.InitMetadata; /** * Interface that a data source implementation will use to push data into the SDK. * * The data source interacts with this object, rather than manipulating the data store directly, so * that the SDK can perform any other necessary operations that must happen when data is updated. */ interface LDDataSourceUpdates { /** * Completely overwrites the current contents of the data store with a set of items for each * collection. * * @param allData * An object in which each key is the "namespace" of a collection (e.g. `"features"`) and * the value is an object that maps keys to entities. The actual type of this parameter is * `interfaces.FullDataSet`. * * @param callback * Will be called when the store has been initialized. * * @param initMetadata * Optional metadata to initialize the data source with. */ init(allData: LDFeatureStoreDataStorage, callback: () => void, initMetadata?: InitMetadata$1): void; /** * Updates or inserts an item in the specified collection. For updates, the object will only be * updated if the existing version is less than the new version. * * @param kind * The type of data to be accessed. The actual type of this parameter is * {@link interfaces.DataKind}. * * @param data * The contents of the entity, as an object that can be converted to JSON. The store * should check the `version` property of this object, and should *not* overwrite any * existing data if the existing `version` is greater than or equal to that value. * The actual type of this parameter is {@link interfaces.VersionedData}. * * @param callback * Will be called after the upsert operation is complete. */ upsert(kind: DataKind, data: LDKeyedFeatureStoreItem, callback: () => void): void; } /** * The LaunchDarkly client feature flag requestor * * The client uses this internally to retrieve feature flags from LaunchDarkly. * * @param cb The callback invoked with the result of the request. The fourth argument, * `fallbackToFDv1`, is `true` when the response carried the `x-ld-fd-fallback: true` * header, regardless of whether the response was otherwise successful. Callers must * apply any accompanying body/headers before honoring the fallback signal. * @param queryParams Additional query params that will be included with the request. Values passed into this * function should already be encoded as this function will not perform encoding. * @ignore */ interface LDFeatureRequestor { requestAllData: (cb: (err: any, body: any, headers: any, fallbackToFDv1?: boolean) => void, queryParams?: { key: string; value: string; }[]) => void; } /** * Receives the contents of the SDK's flag and segment override layer. The SDK implements this * interface and passes it to {@link LDOverrideSource.start}. Override sources call it. They do * not implement it. * * @experimental Flag overrides are currently experimental and subject to change. */ interface LDOverrideSink { /** * Replaces the entire override layer with the given flag and segment definitions. Each call is * a full snapshot. Entries absent from the call are removed from the layer, and empty arrays * clear the layer. * * The definitions are plain objects in the flag and segment data model, in the form in which * LaunchDarkly delivers them. The SDK copies them, prepares the copies for evaluation, and * marks the copies as override entries. It never modifies the objects it was given. A * definition that does not have the shape the SDK requires, for example a flag without a * `variations` array, is rejected with an error that names the kind, the key, and the field, * and no part of the snapshot is applied: the layer keeps its previous contents. * * The new contents are visible to evaluations when the call returns. Flag change notifications * for the affected flags follow. * * @param flags The full flag definitions of the layer. * @param segments The full segment definitions of the layer. */ setOverrides(flags: LDKeyedFeatureStoreItem[], segments: LDKeyedFeatureStoreItem[]): void; } /** * Supplies flag and segment overrides that take precedence over LaunchDarkly data at evaluation * time, on a per-key basis. Overrides exist for resilience during an incident. They let an * operator force one or more flags to a known state on a running client, whether or not the * client can reach LaunchDarkly. * * An override source is not a data source. It takes no part in the data system's initializer and * synchronizer pipeline. The override layer it populates has no effect on the client's * initialization status or data source status. * * Configure an override source with the `overrides` property of the data system options. * * @experimental Flag overrides are currently experimental and subject to change. */ interface LDOverrideSource { /** * Starts supplying overrides to the sink. An implementation performs its initial load and then * pushes a full replacement snapshot to the sink whenever its backing data changes, until * {@link close} is called. A failed load leaves the previously supplied layer untouched by not * calling the sink. * * The SDK calls this method once, when the client is created. When the initial load is * asynchronous, return a promise that settles when the load completes. The load is part of * starting the client: the promise that `waitForInitialization` returns resolves after it, so * an override that is present at startup takes effect by the time initialization is awaited. * Evaluation never waits for the load; an evaluation made before it completes reads the layer * as it is at that moment. * * @param sink The sink that receives the snapshots. */ start(sink: LDOverrideSink): void | Promise; /** * Stops the source and releases any resources it holds. The SDK calls this method when the * client is closed. */ close(): void; } /** * Transactional version of {@link LDDataSourceUpdates} with support for {@link applyChanges} */ interface LDTransactionalDataSourceUpdates extends LDDataSourceUpdates { /** * @param basis If true, completely overwrites the current contents of the data store * with the provided data. If false, upserts the items in the provided data. Upserts * are made only if provided items have newer versions than existing items. * @param data An object in which each key is the "namespace" of a collection (e.g. `"features"`) and * the value is an object that maps keys to entities. The actual type of this parameter is * `interfaces.FullDataSet`. * @param callback Will be called after the changes are applied. * @param initMetadata Optional metadata to initialize the data source with. * @param selector opaque string that uniquely identifies the state that contains the changes */ applyChanges(basis: boolean, data: LDFeatureStoreDataStorage, callback: () => void, initMetadata?: internal.InitMetadata, selector?: string): void; } /** * Transactional version of {@link LDFeatureStore} with support for {@link applyChanges} */ interface LDTransactionalFeatureStore extends LDFeatureStore { /** * Applies the provided data onto the existing data, replacing all data or upserting depending * on the basis parameter. Must call {@link applyChanges} providing basis before calling {@link applyChanges} * that is not a basis. * * @param basis If true, completely overwrites the current contents of the data store * with the provided data. If false, upserts the items in the provided data. Upserts * are made only if provided items have newer versions than existing items. * @param data An object in which each key is the "namespace" of a collection (e.g. `"features"`) and * the value is an object that maps keys to entities. The actual type of this parameter is * `interfaces.FullDataSet`. * @param callback Will be called after the changes are applied. * @param initMetadata Optional metadata to initialize the feature store with. * @param selector opaque string that uniquely identifies the state that contains the changes */ applyChanges(basis: boolean, data: LDFeatureStoreDataStorage, callback: () => void, initMetadata?: internal.InitMetadata, selector?: string): void; /** * Gets the selector for the currently stored data. */ getSelector?(): string | undefined; } type index$2_LDDataSourceUpdates = LDDataSourceUpdates; type index$2_LDFeatureRequestor = LDFeatureRequestor; type index$2_LDFeatureStore = LDFeatureStore; type index$2_LDFeatureStoreDataStorage = LDFeatureStoreDataStorage; type index$2_LDFeatureStoreItem = LDFeatureStoreItem; type index$2_LDFeatureStoreKindData = LDFeatureStoreKindData; type index$2_LDKeyedFeatureStoreItem = LDKeyedFeatureStoreItem; type index$2_LDOverrideSink = LDOverrideSink; type index$2_LDOverrideSource = LDOverrideSource; type index$2_LDTransactionalDataSourceUpdates = LDTransactionalDataSourceUpdates; type index$2_LDTransactionalFeatureStore = LDTransactionalFeatureStore; declare namespace index$2 { export type { index$2_LDDataSourceUpdates as LDDataSourceUpdates, index$2_LDFeatureRequestor as LDFeatureRequestor, index$2_LDFeatureStore as LDFeatureStore, index$2_LDFeatureStoreDataStorage as LDFeatureStoreDataStorage, index$2_LDFeatureStoreItem as LDFeatureStoreItem, index$2_LDFeatureStoreKindData as LDFeatureStoreKindData, index$2_LDKeyedFeatureStoreItem as LDKeyedFeatureStoreItem, index$2_LDOverrideSink as LDOverrideSink, index$2_LDOverrideSource as LDOverrideSource, index$2_LDTransactionalDataSourceUpdates as LDTransactionalDataSourceUpdates, index$2_LDTransactionalFeatureStore as LDTransactionalFeatureStore }; } /** * Configuration options for the Data System that the SDK uses to get and maintain flags and other * data from LaunchDarkly and other sources. * * Example (Recommended): * ```typescript * let dataSystemOptions = { * dataSource: { * dataSourceOptionsType: 'standard'; * }, * } * * Example (Polling with DynamoDB Persistent Store): * ```typescript * import { DynamoDBFeatureStore } from '@launchdarkly/node-server-sdk-dynamodb'; * * let dataSystemOptions = { * dataSource: { * dataSourceOptionsType: 'pollingOnly'; * pollInterval: 300; * }, * persistentStore: DynamoDBFeatureStore('your-table', { cacheTTL: 30 }); * } * const client = init('my-sdk-key', { hooks: [new TracingHook()] }); * ``` */ interface LDDataSystemOptions { /** * Configuration options for the Data Source that the SDK uses to get flags and other * data from the LaunchDarkly servers. Choose one of {@link StandardDataSourceOptions}, * {@link StreamingDataSourceOptions}, {@link PollingDataSourceOptions}, or {@link CustomDataSourceOptions}; setting the * type and the optional fields you want to customize. * * If not specified, this defaults to using the {@link StandardDataSourceOptions} which * performs a combination of streaming and polling. * * See {@link LDDataSystemOptions} documentation for examples. */ dataSource?: DataSourceOptions; /** * Before data has arrived from LaunchDarkly, the SDK is able to evaluate flags using * data from the persistent store. Once fresh data has arrived from LaunchDarkly, the * SDK will no longer read from the persistent store, although it will keep it up-to-date * for future startups. * * Some implementations provide the store implementation object itself, while others * provide a factory function that creates the store implementation based on the SDK * configuration; this property accepts either. * * @param clientContext whose properties may be used to influence creation of the persistent store. */ persistentStore?: LDFeatureStore | ((clientContext: LDClientContext) => LDFeatureStore); /** * Whether you are using the LaunchDarkly relay proxy in daemon mode. * * In this configuration, the client will not connect to LaunchDarkly to get feature flags, * but will instead get feature state from a database (Redis or another supported feature * store integration) that is populated by the relay. By default, this is false. */ useLdd?: boolean; /** * Configuration for the SDK's FDv1 Fallback Synchronizer. * * The FDv1 Fallback Synchronizer is engaged only in response to a server-directed FDv1 * Fallback Directive (the `x-ld-fd-fallback: true` response header) -- it is independent * of the FDv2 initializer/synchronizer chain configured via {@link dataSource}. * * If omitted, the SDK uses sensible defaults derived from the rest of the configuration. * If explicitly set to `null`, no FDv1 fallback synchronizer is configured and the SDK * will transition to a terminal Closed state when the directive is received. */ fdv1Fallback?: FDv1FallbackConfiguration | null; /** * Configures an override source. * * The source supplies flag and segment definitions that take precedence over data received * from LaunchDarkly on a per-key basis. Overrides let an operator force one or more flags to a * known state on a running client, whether or not the client can reach LaunchDarkly. Flags not * present in the override data are unaffected. * * The override source is not a data source. It has no effect on the client's initialization * status or data source status. Configuring it changes nothing until the source supplies an * override. At most one override source can be configured. * * When the client is offline, the source is not built or started: no overrides are served, and * a configuration error in the source is not reported. The SDK logs a warning instead. * * Some implementations provide the source object itself, while others provide a factory * function that creates the source based on the SDK configuration. This property accepts * either. * * @experimental Flag overrides are currently experimental and subject to change. */ overrides?: LDOverrideSourceOptions; } /** * Configuration of the file-based override source. * * The source reads flag and segment overrides from one or more local files and reloads them as * the files change. The files use the same document format as the file data source: a JSON or * YAML document with optional `flags`, `flagValues`, and `segments` members. `flagValues` entries * expand into full flag definitions that return the given value for every context. A `flagValues` * entry is not available to client-side SDKs, so `allFlagsState` with `clientSideOnly` leaves it * out, even when the flag it overrides is available to them. To override such a flag, define it * in `flags` with `"clientSideAvailability": { "usingEnvironmentId": true }`. * * A configured file that does not exist contributes no overrides. It can be created later, and * deleting it removes its overrides. A file that exists but cannot be read or parsed fails that * reload: the previously loaded overrides stay in effect, the failure is logged, and the source * retries. Every applied change is logged at Info level with the overrides in effect and what * each file supplied. * * @example * ```typescript * const client = init(sdkKey, { * dataSystem: { * overrides: { type: 'file', paths: ['/etc/launchdarkly/overrides.json'] }, * }, * }); * ``` * * @experimental Flag overrides are currently experimental and subject to change. */ interface FileOverrideSourceOptions { type: 'file'; /** * The paths of the files to read, in precedence order. At least one path is required. The * order decides which file wins under the duplicate keys handling when the same key appears in * more than one file. */ paths: string[]; /** * What to do when the same flag or segment key appears in more than one file. `fail`, the * default, treats the reload as failed and keeps the previously loaded overrides. `ignore` * keeps the entry from the first configured file that defines the key and discards the others. */ duplicateKeysHandling?: 'fail' | 'ignore'; /** * How the source detects file changes. The two modes are alternatives. * * `polling`, the default, examines the files on a fixed interval and reloads when the * modification time or the size of a file changes. It works on every filesystem, including * network mounts and directories whose contents are swapped through symbolic links. * * `watching` reloads in response to filesystem change notifications for the directories that * contain the files. It reacts faster than polling. It depends on notifications, which some * filesystems do not deliver reliably. */ changeDetection?: 'polling' | 'watching'; /** * The interval between examinations of the files in polling mode, in seconds. The default is * 1. An interval below 1 is raised to 1. A value that is not a finite number, or that exceeds * 2147483 seconds, is invalid and the default is used. Watching mode ignores it. */ pollInterval?: number; /** * A YAML parser for YAML files. The SDK does not include one; to read YAML files, supply a * parser that produces the same structure as `JSON.parse`, for example the `parse` function * of the `yaml` package. A YAML file configured without a parser fails client construction. */ yamlParser?: (data: string) => any; } /** * The ways an override source can be configured: the file-based source, a source object, or a * factory function that creates a source from the client context. * * @experimental Flag overrides are currently experimental and subject to change. */ type LDOverrideSourceOptions = FileOverrideSourceOptions | LDOverrideSource | ((clientContext: LDClientContext) => LDOverrideSource); declare function isFileOverrideSourceOptions(u: any): u is FileOverrideSourceOptions; /** * Configuration options for the FDv1 Fallback Synchronizer. */ interface FDv1FallbackConfiguration { /** * Override the polling base URI used by the FDv1 Fallback Synchronizer. Defaults to the * SDK's configured polling base URI. */ baseUri?: string; /** * The interval between polls, in seconds. Defaults to the SDK's configured pollInterval. */ pollInterval?: number; } type DataSourceOptions = StandardDataSourceOptions | StreamingDataSourceOptions | PollingDataSourceOptions | CustomDataSourceOptions; type DataSourceConfiguration = FileSystemDataSourceConfiguration | StreamingDataSourceConfiguration | PollingDataSourceConfiguration; interface FileSystemDataSourceConfiguration { type: 'file'; /** * The paths to the files to read data from. */ paths: Array; /** * A function to parse the data from the file. */ yamlParser?: (data: string) => any; } interface StreamingDataSourceConfiguration { type: 'streaming'; /** * Optional per-source base URI for this streaming data source. When set, this source * connects to the given URI instead of the SDK's shared streaming service endpoint. * Defaults to the SDK's configured streaming base URI. */ baseUri?: string; /** * Sets the initial reconnect delay for the streaming connection, in seconds. Default if omitted. * * The streaming service uses a backoff algorithm (with jitter) every time the connection needs * to be reestablished. The delay for the first reconnection will start near this value, and then * increase exponentially up to a maximum for any subsequent connection failures. * * The default value is 1. */ streamInitialReconnectDelay?: number; } interface PollingDataSourceConfiguration { type: 'polling'; /** * Optional per-source base URI for this polling data source. When set, this source * polls the given URI instead of the SDK's shared polling service endpoint. * Defaults to the SDK's configured polling base URI. */ baseUri?: string; /** * The time between polling requests, in seconds. Default if omitted. */ pollInterval?: number; } /** * This standard data source is the recommended datasource for most customers. It will use * a combination of streaming and polling to initialize the SDK, provide real time updates, * and can switch between streaming and polling automatically to provide redundancy. */ interface StandardDataSourceOptions extends Omit, Omit { dataSourceOptionsType: 'standard'; } /** * This data source will make best effort to maintain a streaming connection to LaunchDarkly services * to provide real time data updates. */ interface StreamingDataSourceOptions extends Omit { dataSourceOptionsType: 'streamingOnly'; } /** * This data source will periodically make a request to LaunchDarkly services to retrieve updated data. */ interface PollingDataSourceOptions extends Omit { dataSourceOptionsType: 'pollingOnly'; } /** * Initializer configuration options */ type InitializerDataSource = FileSystemDataSourceConfiguration | PollingDataSourceConfiguration; /** * Synchronizer configuration options */ type SynchronizerDataSource = PollingDataSourceConfiguration | StreamingDataSourceConfiguration; /** * This data source will allow developers to define their own composite data source. * * The following example is roughly equivilent to using the {@link StandardDataSourceOptions} with the default values. * @example * ```typescript * dataSource: { * dataSourceOptionsType: 'custom', * initializers: [ * { * type: 'polling' * }, * ], * synchronizers: [ * { * type: 'streaming', * }, * { * type: 'polling', * } * ], * } */ interface CustomDataSourceOptions { dataSourceOptionsType: 'custom'; /** * Ordered list of {@link InitializerDataSource} that will run in order. The first * initializer that successfully returns a valid payload will transition the sdk * out of intialization stage into the synchronization stage. */ initializers: Array; /** * Order list of {@link SynchronizerDataSource} in priority order. Datasources will * failover to the next datasource in this array until there are no datasources left * to run. */ synchronizers: Array; } declare function isStandardOptions(u: any): u is StandardDataSourceOptions; declare function isStreamingOnlyOptions(u: any): u is StreamingDataSourceOptions; declare function isPollingOnlyOptions(u: any): u is PollingDataSourceOptions; declare function isCustomOptions(u: any): u is CustomDataSourceOptions; interface LDProxyOptions { /** * Allows you to specify a host for an optional HTTP proxy. */ host?: string; /** * Allows you to specify a port for an optional HTTP proxy. * * Both the host and port must be specified to enable proxy support. */ port?: number; /** * When using an HTTP proxy, specifies whether it is accessed via `http` or `https`. */ scheme?: string; /** * Allows you to specify basic authentication parameters for an optional HTTP proxy. * Usually of the form `username:password`. */ auth?: string; } /** * The Node `Buffer` type when `@types/node` declares it as a global `var`, and `never` otherwise. * * This package is also used on edge runtimes, where consumers do not have `@types/node`. * A direct `Buffer` reference would not resolve for those consumers. * * The type comes from the `Buffer.isBuffer` type guard, which every `@types/node` version declares * as `obj is Buffer`. Inferring it from the constructor would pick up the last `new` overload, which * returns `Buffer` in some versions. That narrower type rejects a plain `Buffer`. * * Known limit: `typeof globalThis` only sees `var` declarations. `@types/node` versions older than * 16.3.3 declare `Buffer` as a `const` or a `class`, so they also resolve to `never`. */ type GlobalBuffer = typeof globalThis extends { Buffer: { isBuffer(obj: any): obj is infer T; }; } ? T : never; /** * Additional parameters to pass to the Node HTTPS API for secure requests. These can include any * of the TLS-related parameters supported by `https.request()`, such as `ca`, `cert`, and `key`. * * For more information, see the Node documentation for `https.request()` and `tls.connect()`. */ interface LDTLSOptions { ca?: string | string[] | GlobalBuffer | GlobalBuffer[]; cert?: string | string[] | GlobalBuffer | GlobalBuffer[]; checkServerIdentity?: (servername: string, cert: any) => Error | undefined; ciphers?: string; pfx?: string | string[] | GlobalBuffer | GlobalBuffer[] | object[]; key?: string | string[] | GlobalBuffer | GlobalBuffer[] | object[]; passphrase?: string; rejectUnauthorized?: boolean; secureProtocol?: string; servername?: string; } /** * LaunchDarkly initialization options. */ interface LDOptions { /** * The base URI for the LaunchDarkly server. * * Most users should use the default value. */ baseUri?: string; /** * The base URI for the LaunchDarkly streaming server. * * Most users should use the default value. */ streamUri?: string; /** * The base URI for the LaunchDarkly events server. * * Most users should use the default value. */ eventsUri?: string; /** * The connection timeout, in seconds. */ timeout?: number; /** * The capacity of the analytics events queue. * * The client buffers up to this many events in memory before flushing. If the capacity is * exceeded before the buffer is flushed, events will be discarded. */ capacity?: number; /** * Configures a logger for warnings and errors generated by the SDK. * * The logger can be any object that conforms to the {@link LDLogger} interface. * For a simple implementation that lets you filter by log level, see * {@link basicLogger}. You can also use an instance of `winston.Logger` from * the Winston logging package. * * If you do not set this property, the SDK uses {@link basicLogger} with a * minimum level of `info`. */ logger?: LDLogger; /** * A component that stores feature flags and related data received from LaunchDarkly. * * If you specify the {@link LDOptions#dataSystem}, this setting will be ignored. * * By default, this is an in-memory data structure. Database integrations are also * available, as described in the * [SDK features guide](https://docs.launchdarkly.com/sdk/concepts/data-stores). * * Some implementations provide the store implementation object itself, while others * provide a factory function that creates the store implementation based on the SDK * configuration; this property accepts either. */ featureStore?: LDFeatureStore | ((clientContext: LDClientContext) => LDFeatureStore); /** * Configuration options for the Data System that the SDK uses to get and maintain flags and other * data from LaunchDarkly and other sources. * * Setting this option supersedes * * Example (Recommended): * ```typescript * let dataSystemOptions = { * dataSource: { * type: 'standard'; * // options can be customized here, though defaults are recommended * }, * } * * Example (Polling with DynamoDB Persistent Store): * ```typescript * import { DynamoDBFeatureStore } from '@launchdarkly/node-server-sdk-dynamodb'; * * let dataSystemOptions = { * dataSource: { * type: 'pollingOnly'; * pollInterval: 300; * }, * persistentStore: DynamoDBFeatureStore('your-table', { cacheTTL: 30 }); * } * const client = init('my-sdk-key', { hooks: [new TracingHook()] }); * ``` */ dataSystem?: LDDataSystemOptions; /** * Additional parameters for configuring the SDK's Big Segments behavior. * * Big Segments are a specific type of user segments. For more information, read the * LaunchDarkly documentation: https://docs.launchdarkly.com/home/users/big-segments * * By default, there is no configuration and Big Segments cannot be evaluated. In this * case, any flag evaluation that references a Big Segment will behave as if no users * are included in any Big Segments, and the {@link LDEvaluationReason} associated with any * such flag evaluation will have a `bigSegmentsStatus` of `"NOT_CONFIGURED"`. */ bigSegments?: LDBigSegmentsOptions; /** * A component that obtains feature flag data and puts it in the feature store. * * If you specify the {@link LDOptions#dataSystem}, this setting will be ignored. */ updateProcessor?: object | ((clientContext: LDClientContext, dataSourceUpdates: LDDataSourceUpdates, initSuccessHandler: VoidFunction, errorHandler?: (e: Error) => void) => subsystem.LDStreamProcessor); /** * The interval in between flushes of the analytics events queue, in seconds. */ flushInterval?: number; /** * The time between polling requests, in seconds. Ignored in streaming mode. * * If you specify the {@link LDOptions#dataSystem}, this setting will be ignored. */ pollInterval?: number; /** * Allows you to specify configuration for an optional HTTP proxy. */ proxyOptions?: LDProxyOptions; /** * Whether the client should be initialized in offline mode. */ offline?: boolean; /** * Whether streaming mode should be used to receive flag updates. * * If you specify the {@link LDOptions#dataSystem}, this setting will be ignored. * * This is true by default. If you set it to false, the client will use polling. * Streaming should only be disabled on the advice of LaunchDarkly support. */ stream?: boolean; /** * Sets the initial reconnect delay for the streaming connection, in seconds. * * If you specify the {@link LDOptions#dataSystem}, this setting will be ignored. * * The streaming service uses a backoff algorithm (with jitter) every time the connection needs * to be reestablished. The delay for the first reconnection will start near this value, and then * increase exponentially for any subsequent connection failures. * * The default value is 1. */ streamInitialReconnectDelay?: number; /** * Whether you are using the LaunchDarkly relay proxy in daemon mode. * * If you specify the {@link LDOptions#dataSystem}, this setting will be ignored. * * In this configuration, the client will not connect to LaunchDarkly to get feature flags, * but will instead get feature state from a database (Redis or another supported feature * store integration) that is populated by the relay. By default, this is false. */ useLdd?: boolean; /** * Whether to send analytics events back to LaunchDarkly. By default, this is true. */ sendEvents?: boolean; /** * Whether all context attributes (except the context key) should be marked as private, and * not sent to LaunchDarkly. * * By default, this is false. */ allAttributesPrivate?: boolean; /** * The names of any context attributes that should be marked as private, and not sent * to LaunchDarkly. */ privateAttributes?: Array; /** * The number of context keys that the event processor can remember at any one time, * so that duplicate context details will not be sent in analytics events. * * Defaults to 1000. */ contextKeysCapacity?: number; /** * The interval (in seconds) at which the event processor will reset its set of * known context keys. * * Defaults to 300. */ contextKeysFlushInterval?: number; /** * Additional parameters to pass to the Node HTTPS API for secure requests. These can include any * of the TLS-related parameters supported by `https.request()`, such as `ca`, `cert`, and `key`. * * These parameters also apply when the SDK connects through a proxy configured with * {@link proxyOptions}. They apply to each request on the tunneled connection to * LaunchDarkly, and to the connection to the proxy itself when the proxy uses TLS. * * For more information, see the Node documentation for * [`https.request()`](https://nodejs.org/api/https.html#httpsrequestoptions-callback) and * [`tls.connect()`](https://nodejs.org/api/tls.html#tlsconnectoptions-callback). */ tlsParams?: LDTLSOptions; /** * Set to true to opt out of sending diagnostics data. * * Unless the `diagnosticOptOut` field is set to true, the client will send some diagnostics data * to the LaunchDarkly servers in order to assist in the development of future SDK improvements. * These diagnostics consist of an initial payload containing some details of SDK in use, the * SDK's configuration, and the platform the SDK is being run on, as well as payloads sent * periodically with information on irregular occurrences such as dropped events. */ diagnosticOptOut?: boolean; /** * The interval at which periodic diagnostic data is sent, in seconds. * * The default is 900 (every 15 minutes) and the minimum value is 60 (every minute). */ diagnosticRecordingInterval?: number; /** * For use by wrapper libraries to set an identifying name for the wrapper being used. * * This will be sent in User-Agent headers during requests to the LaunchDarkly servers to allow * recording metrics on the usage of these wrapper libraries. */ wrapperName?: string; /** * For use by wrapper libraries to report the version of the library in use. * * If `wrapperName` is not set, this field will be ignored. Otherwise the version string will be * included in the User-Agent headers along with the `wrapperName` during requests to the * LaunchDarkly servers. */ wrapperVersion?: string; /** * Information about the application where the LaunchDarkly SDK is running. * * Note that this config option may be renamed to applicationInfo in a future major version * to be consistent with other SDKs. */ application?: { /** * A unique identifier representing the application where the LaunchDarkly SDK is running. * * This can be specified as any string value as long as it only uses the following characters: * ASCII letters, ASCII digits, period, hyphen, underscore. A string containing any other * characters will be ignored. * * Example: `authentication-service` */ id?: string; /** * A unique identifier representing the version of the application where the LaunchDarkly SDK is * running. * * This can be specified as any string value as long as it only uses the following characters: * ASCII letters, ASCII digits, period, hyphen, underscore. A string containing any other * characters will be ignored. * * Example: `1.0.0` (standard version string) or `abcdef` (sha prefix) */ version?: string; /** * A human-friendly application name representing the application where the LaunchDarkly SDK is running. * * This can be specified as any string value as long as it only uses the following characters: ASCII letters, * ASCII digits, period, hyphen, underscore. A string containing any other characters will be ignored. */ name?: string; /** * A human-friendly name representing the version of the application where the LaunchDarkly SDK is running. * * This can be specified as any string value as long as it only uses the following characters: ASCII letters, * ASCII digits, period, hyphen, underscore. A string containing any other characters will be ignored. */ versionName?: string; }; /** * LaunchDarkly Server SDKs historically downloaded all flag configuration and segments for a particular environment * during initialization. * * For some customers, this is an unacceptably large amount of data, and has contributed to performance issues * within their products. * * Filtered environments aim to solve this problem. By allowing customers to specify subsets of an environment's * flags using a filter key, SDKs will initialize faster and use less memory. * * This feature is releasing through a closed alpha and beta pipeline and may not be available for your account * until public release. * * This payload filter key only applies to the default streaming and polling data sources. It will not affect * TestData or FileData data sources, nor will it be applied to any data source provided through the featureStore * config property. * * Payload filtering is not supported with the FDv2 data system, so this key has no effect on requests made by * FDv2 data sources. */ payloadFilterKey?: string; /** * Initial set of hooks for the client. * * Hooks provide entrypoints which allow for observation of SDK functions. * * LaunchDarkly provides integration packages, and most applications will not * need to implement their own hooks. Refer to the `@launchdarkly/node-server-sdk-otel` * for instrumentation for the `@launchdarkly/node-server-sdk`. * * Example: * ```typescript * import { init } from '@launchdarkly/node-server-sdk'; * import { TracingHook } from '@launchdarkly/node-server-sdk-otel'; * * const client = init('my-sdk-key', { hooks: [new TracingHook()] }); * ``` */ hooks?: Hook[]; /** * Set to true to opt in to compressing event payloads if the SDK supports it, since the * compression library may not be supported in the underlying SDK framework. If the compression * library is not supported then event payloads will not be compressed even if this option * is enabled. * * Defaults to false. */ enableEventCompression?: boolean; } /** * When execution is sequential this enum is used to control if execution * should be in a fixed or random order. */ declare enum LDExecutionOrdering { Fixed = 0, Random = 1 } /** * Tag used to determine if execution should be serial or concurrent. * Callers should not need to use this directly. */ declare enum LDExecution { /** * Execution will be serial. One read method will be executed fully before * the other read method. */ Serial = 0, /** * Execution will be concurrent. The execution of the read methods will be * started and then resolved concurrently. */ Concurrent = 1 } /** * Migration methods may return an LDMethodResult. * The implementation includes methods for creating results conveniently. * * An implementation may also throw an exception to represent an error. */ type LDMethodResult = { success: true; result: TResult; } | { success: false; error: any; }; /** * Configuration class for configuring serial execution of a migration. */ declare class LDSerialExecution { readonly ordering: LDExecutionOrdering; readonly type: LDExecution; constructor(ordering: LDExecutionOrdering); } /** * Configuration class for configuring concurrent execution of a migration. */ declare class LDConcurrentExecution { readonly type: LDExecution; } /** * Configuration for a migration. */ interface LDMigrationOptions { /** * Configure how the migration should execute. If omitted the execution will * be concurrent. */ execution?: LDSerialExecution | LDConcurrentExecution; /** * Configure the latency tracking for the migration. * * Defaults to {@link true}. */ latencyTracking?: boolean; /** * Configure the error tracking for the migration. * * Defaults to {@link true}. */ errorTracking?: boolean; /** * Implementation which provides a read from the "new" source. * * Users are required to provide two different read methods -- one to read from the old migration source, and one to * read from the new source. Additionally, customers can opt-in to consistency tracking by providing a `check` * function. * * Depending on the migration stage, one or both of these read methods may be called. * * Throwing an exception from this method will be treated as an error. * * @param payload An optional payload. The payload is provided when calling the `read` method on the migration. * @returns The result of the operation. Use {@link LDMigrationSuccess} or {@link LDMigrationError} to create a suitable return value. */ readNew: (payload?: TMigrationReadInput) => Promise>; /** * Implementation which provides a write to the "new" source. * * Users are required to provide two different write methods -- one to write to the old migration source, and one to * write to the new source. Not every stage requires * * * Depending on the migration stage, one or both of these write methods may be called. * * Throwing an exception from this method will be treated as an error. * * @param payload An optional payload. The payload is provided when calling the `read` method on the migration. * @returns The result of the operation. Use {@link LDMigrationSuccess} or {@link LDMigrationError} to create a suitable return value. */ writeNew: (payload?: TMigrationWriteInput) => Promise>; /** * Implementation which provides a read from the "old" source. * * Users are required to provide two different read methods -- one to read from the old migration source, and one to * read from the new source. Additionally, customers can opt-in to consistency tracking by providing a `check` * function. * * Depending on the migration stage, one or both of these read methods may be called. * * Throwing an exception from this method will be treated as an error. * */ readOld: (payload?: TMigrationReadInput) => Promise>; /** * Implementation which provides a write to the "old" source. * * Users are required to provide two different write methods -- one to write to the old migration source, and one to * write to the new source. Not every stage requires * * Depending on the migration stage, one or both of these write methods may be called. * * Throwing an exception from this method will be treated as an error. * * @param payload An optional payload. The payload is provided when calling the `read` method on the migration. * @returns The result of the operation. Use {@link LDMigrationSuccess} or {@link LDMigrationError} to create a suitable return value. */ writeOld: (payload?: TMigrationWriteInput) => Promise>; /** * Method used to do consistency checks for read operations. After a read operation, during which both data sources * are read from, a check of read consistency may be done using this method. */ check?: (a: TMigrationRead, b: TMigrationRead) => boolean; } /** * Options for the waitForInitialization method. */ interface LDWaitForInitializationOptions { /** * The amount of time, in seconds, to wait for initialization before rejecting the promise. * * If no options are specified on the `waitForInitialization`, then the promise will resolve * only when initialization completes successfully or encounters a failure. * * Using a high timeout, or no timeout, is not recommended because it could result in a long * delay when conditions prevent successful initialization. * * A value of 0 will cause the promise to resolve without waiting. In that scenario it would be * more effective to not call `waitForInitialization`. */ timeout: number; } /** * The LaunchDarkly SDK client object. * * Create this object with {@link init}. Applications should configure the client at startup time * and continue to use it throughout the lifetime of the application, rather than creating instances * on the fly. * */ interface LDClient { /** * Tests whether the client has completed initialization. * * If this returns false, it means that the client has not yet successfully connected to * LaunchDarkly. It might still be in the process of starting up, or it might be attempting to * reconnect after an unsuccessful attempt, or it might have received an unrecoverable error (such * as an invalid SDK key) and given up. * * @returns * True if the client has successfully initialized. */ initialized(): boolean; /** * Returns a Promise that tracks the client's initialization state. * * The Promise will be resolved if the client successfully initializes, or rejected if client * initialization has failed unrecoverably (for instance, if it detects that the SDK key is * invalid). Keep in mind that unhandled Promise rejections can be fatal in Node, so if you call * this method, be sure to attach a rejection handler to it (or, if using `async`/`await`, a catch * block). * * Note that you can also use event listeners ({@link on}) for the same purpose: the event * `"ready"` indicates success, and `"failed"` indicates failure. * * This method takes an optional parameters which include a timeout. The timeout controls how long * a specific call to waitForInitialization will wait before rejecting its promise. If a * subsequent call is made to waitForInitialization with a timeout, then it will again wait up to * that maximum time. * * Regardless of whether you continue to wait, the SDK will still retry all connection failures * indefinitely unless it gets an unrecoverable error as described above. * * Waiting indefinitely, or depending only on the "ready" or "failed" events can result in an * application waiting indefinitely. It is recommended to use a timeout which is reasonable * for your application. * * @param options Options which control the behavior of `waitForInitialization`. * * @returns * A Promise that will be resolved if the client initializes successfully, or rejected if it * fails. If successful, the result is the same client object. It is not recommended to use the * returned client object. It will be removed in a future version. * * @example * This example shows use of Promise chaining methods for specifying handlers: * ```javascript * client.waitForInitialization({timeoutSeconds: 10}).then(() => { * // do whatever is appropriate if initialization has succeeded * }).catch(err => { * // do whatever is appropriate if initialization has failed or timed out * }) * ``` * * @example * This example shows use of `async`/`await` syntax for specifying handlers: * ```javascript * try { * await client.waitForInitialization({timeoutSeconds: 10}); * // do whatever is appropriate if initialization has succeeded * } catch (err) { * // do whatever is appropriate if initialization has failed or timed out * } * ``` */ waitForInitialization(options?: LDWaitForInitializationOptions): Promise; /** * Determines the variation of a feature flag for a context. * * @param key The unique key of the feature flag. * @param context The context requesting the flag. The client will generate an analytics event to * register this context with LaunchDarkly if the context does not already exist. * @param defaultValue The default value of the flag, to be used if the value is not available * from LaunchDarkly. * @param callback A Node-style callback to receive the result value. If omitted, you will receive * a Promise instead. * @returns * If you provided a callback, then nothing. Otherwise, a Promise which will be resolved with * the result value. */ variation(key: string, context: LDContext, defaultValue: LDFlagValue, callback?: (err: any, res: LDFlagValue) => void): Promise; /** * Determines the variation of a feature flag for a context, along with information about how it * was calculated. * * The `reason` property of the result will also be included in analytics events, if you are * capturing detailed event data for this flag. * * For more information, see the [SDK reference * guide](https://docs.launchdarkly.com/sdk/features/evaluation-reasons#nodejs-server-side). * * @param key The unique key of the feature flag. * @param context The context requesting the flag. The client will generate an analytics event to * register this context with LaunchDarkly if the context does not already exist. * @param defaultValue The default value of the flag, to be used if the value is not available * from LaunchDarkly. * @param callback A Node-style callback to receive the result (as an {@link LDEvaluationDetail}). * If omitted, you will receive a Promise instead. * @returns * If you provided a callback, then nothing. Otherwise, a Promise which will be resolved with * the result (as an{@link LDEvaluationDetail}). */ variationDetail(key: string, context: LDContext, defaultValue: LDFlagValue, callback?: (err: any, res: LDEvaluationDetail) => void): Promise; /** * Returns the migration stage of the migration feature flag for the given * evaluation context. * * If the evaluated value of the flag cannot be converted to an LDMigrationStage, then the default * value will be returned and error will be logged. * * @param key The unique key of the feature flag. * @param context The context requesting the flag. The client will generate an analytics event to * register this context with LaunchDarkly if the context does not already exist. * @param defaultValue The default value of the flag, to be used if the value is not available * from LaunchDarkly. * @returns * A Promise which will be resolved with the result (as an{@link LDMigrationVariation}). */ migrationVariation(key: string, context: LDContext, defaultValue: LDMigrationStage): Promise; /** * Determines the boolean variation of a feature flag for a context. * * If the flag variation does not have a boolean value, defaultValue is returned. * * @param key The unique key of the feature flag. * @param context The context requesting the flag. The client will generate an analytics event to * register this context with LaunchDarkly if the context does not already exist. * @param defaultValue The default value of the flag, to be used if the value is not available * from LaunchDarkly. * @returns * A Promise which will be resolved with the result value. */ boolVariation(key: string, context: LDContext, defaultValue: boolean): Promise; /** * Determines the numeric variation of a feature flag for a context. * * If the flag variation does not have a numeric value, defaultValue is returned. * * @param key The unique key of the feature flag. * @param context The context requesting the flag. The client will generate an analytics event to * register this context with LaunchDarkly if the context does not already exist. * @param defaultValue The default value of the flag, to be used if the value is not available * from LaunchDarkly. * @returns * A Promise which will be resolved with the result value. */ numberVariation(key: string, context: LDContext, defaultValue: number): Promise; /** * Determines the string variation of a feature flag for a context. * * If the flag variation does not have a string value, defaultValue is returned. * * @param key The unique key of the feature flag. * @param context The context requesting the flag. The client will generate an analytics event to * register this context with LaunchDarkly if the context does not already exist. * @param defaultValue The default value of the flag, to be used if the value is not available * from LaunchDarkly. * @returns * A Promise which will be resolved with the result value. */ stringVariation(key: string, context: LDContext, defaultValue: string): Promise; /** * Determines the variation of a feature flag for a context. * * This version may be favored in TypeScript versus `variation` because it returns * an `unknown` type instead of `any`. `unknown` will require a cast before usage. * * @param key The unique key of the feature flag. * @param context The context requesting the flag. The client will generate an analytics event to * register this context with LaunchDarkly if the context does not already exist. * @param defaultValue The default value of the flag, to be used if the value is not available * from LaunchDarkly. * @returns * A Promise which will be resolved with the result value. */ jsonVariation(key: string, context: LDContext, defaultValue: unknown): Promise; /** * Determines the boolean variation of a feature flag for a context, along with information about * how it was calculated. * * The `reason` property of the result will also be included in analytics events, if you are * capturing detailed event data for this flag. * * If the flag variation does not have a boolean value, defaultValue is returned. The reason will * indicate an error of the type `WRONG_KIND` in this case. * * For more information, see the [SDK reference * guide](https://docs.launchdarkly.com/sdk/features/evaluation-reasons#nodejs-server-side). * * @param key The unique key of the feature flag. * @param context The context requesting the flag. The client will generate an analytics event to * register this context with LaunchDarkly if the context does not already exist. * @param defaultValue The default value of the flag, to be used if the value is not available * from LaunchDarkly. * @returns * A Promise which will be resolved with the result * (as an {@link LDEvaluationDetailTyped}). */ boolVariationDetail(key: string, context: LDContext, defaultValue: boolean): Promise>; /** * Determines the numeric variation of a feature flag for a context, along with information about * how it was calculated. * * The `reason` property of the result will also be included in analytics events, if you are * capturing detailed event data for this flag. * * If the flag variation does not have a numeric value, defaultValue is returned. The reason will * indicate an error of the type `WRONG_KIND` in this case. * * For more information, see the [SDK reference * guide](https://docs.launchdarkly.com/sdk/features/evaluation-reasons#nodejs-server-side). * * @param key The unique key of the feature flag. * @param context The context requesting the flag. The client will generate an analytics event to * register this context with LaunchDarkly if the context does not already exist. * @param defaultValue The default value of the flag, to be used if the value is not available * from LaunchDarkly. * @returns * A Promise which will be resolved with the result * (as an {@link LDEvaluationDetailTyped}). */ numberVariationDetail(key: string, context: LDContext, defaultValue: number): Promise>; /** * Determines the string variation of a feature flag for a context, along with information about * how it was calculated. * * The `reason` property of the result will also be included in analytics events, if you are * capturing detailed event data for this flag. * * If the flag variation does not have a string value, defaultValue is returned. The reason will * indicate an error of the type `WRONG_KIND` in this case. * * For more information, see the [SDK reference * guide](https://docs.launchdarkly.com/sdk/features/evaluation-reasons#nodejs-server-side). * * @param key The unique key of the feature flag. * @param context The context requesting the flag. The client will generate an analytics event to * register this context with LaunchDarkly if the context does not already exist. * @param defaultValue The default value of the flag, to be used if the value is not available * from LaunchDarkly. * @returns * A Promise which will be resolved with the result * (as an {@link LDEvaluationDetailTyped}). */ stringVariationDetail(key: string, context: LDContext, defaultValue: string): Promise>; /** * Determines the variation of a feature flag for a context, along with information about how it * was calculated. * * The `reason` property of the result will also be included in analytics events, if you are * capturing detailed event data for this flag. * * This version may be favored in TypeScript versus `variation` because it returns * an `unknown` type instead of `any`. `unknown` will require a cast before usage. * * For more information, see the [SDK reference * guide](https://docs.launchdarkly.com/sdk/features/evaluation-reasons#nodejs-server-side). * * @param key The unique key of the feature flag. * @param context The context requesting the flag. The client will generate an analytics event to * register this context with LaunchDarkly if the context does not already exist. * @param defaultValue The default value of the flag, to be used if the value is not available * from LaunchDarkly. * @param callback A Node-style callback to receive the result (as an {@link LDEvaluationDetail}). * If omitted, you will receive a Promise instead. * @returns * If you provided a callback, then nothing. Otherwise, a Promise which will be resolved with * the result (as an{@link LDEvaluationDetailTyped}). */ jsonVariationDetail(key: string, context: LDContext, defaultValue: unknown): Promise>; /** * Builds an object that encapsulates the state of all feature flags for a given context. * This includes the flag values and also metadata that can be used on the front end. This * method does not send analytics events back to LaunchDarkly. * * The most common use case for this method is to bootstrap a set of client-side * feature flags from a back-end service. Call the `toJSON()` method of the returned object * to convert it to the data structure used by the client-side SDK. * * @param context * The context requesting the feature flags. * @param options * Optional {@link LDFlagsStateOptions} to determine how the state is computed. * @param callback * A Node-style callback to receive the result (as an {@link LDFlagsState}). If omitted, you * will receive a Promise instead. * @returns * If you provided a callback, then nothing. Otherwise, a Promise which will be resolved * with the result as an {@link LDFlagsState}. */ allFlagsState(context: LDContext, options?: LDFlagsStateOptions, callback?: (err: Error | null, res: LDFlagsState | null) => void): Promise; /** * Computes an HMAC signature of a context signed with the client's SDK key. * * For more information, see the JavaScript SDK Reference Guide on * [Secure mode](https://github.com/launchdarkly/js-client#secure-mode). * * @param context * The context properties. * * @returns * The hash string. */ secureModeHash(context: LDContext): string; /** * Discards all network connections, background tasks, and other resources held by the client. * * Do not attempt to use the client after calling this method. */ close(): void; /** * Tests whether the client is configured in offline mode. * * @returns * True if the `offline` property is true in your {@link LDOptions}. */ isOffline(): boolean; /** * Tracks that a context performed an event. * * LaunchDarkly automatically tracks pageviews and clicks that are specified in the Metrics section * of the dashboard. This can be used to track custom metrics (goals) or other events that do not currently * have metrics. * * Note that event delivery is asynchronous, so the event may not actually be sent until later; * see {@link flush}. * * If the context is omitted or has no key, the client will log a warning and will not send an * event. * * @param key The name of the event, which may correspond to a metric in Experimentation. * @param context The context to track. * @param data Optional additional information to associate with the event. * @param metricValue A numeric value used by the LaunchDarkly experimentation feature in numeric * custom metrics. Can be omitted if this event is used by only non-numeric metrics. This field * will also be returned as part of the custom event for Data Export. */ track(key: string, context: LDContext, data?: any, metricValue?: number): void; /** * Track the details of a migration. * * @param event Event containing information about the migration operation. */ trackMigration(event: LDMigrationOpEvent): void; /** * Identifies a context to LaunchDarkly. * * This simply creates an analytics event that will transmit the given user properties to * LaunchDarkly, so that the context will be visible on your dashboard even if you have not * evaluated any flags for that user. It has no other effect. * * If the context is omitted or has no key, the client will log a warning * and will not send an event. * * @param context * The context properties. Must contain at least the `key` property. */ identify(context: LDContext): void; /** * Flushes all pending analytics events. * * Normally, batches of events are delivered in the background at intervals determined by the * `flushInterval` property of {@link LDOptions}. Calling `flush()` triggers an immediate * delivery. However, like Node I/O in general, this is still an asynchronous operation so you * must still use Promise chaining, a callback, or `async`/`await` to detect when it has finished * or failed. * * @param callback * A function which will be called when the flush completes (meaning that all pending events * have been delivered to LaunchDarkly). If omitted, you will receive a Promise instead. * * @returns * If you provided a callback, then nothing. Otherwise, a Promise which resolves once * flushing is finished. Note that the Promise will be rejected if the HTTP request * fails, so be sure to attach a rejection handler to it. */ flush(callback?: (err: Error | null, res: boolean) => void): Promise; /** * Add a hook to the client. In order to register a hook before the client * starts, please use the `hooks` property of {@link LDOptions}. * * Hooks provide entrypoints which allow for observation of SDK functions. * * @param Hook The hook to add. */ addHook?(hook: Hook): void; /** * Get the logger used by this LDClient instance. * * For all platforms that support logging the logger should be present. */ get logger(): LDLogger | undefined; } /** * Configuration for {@link FileDataSource}. */ interface FileDataSourceOptions { /** * The path(s) of the file(s) that FileDataSource will read. */ paths: Array; /** * True if FileDataSource should reload flags whenever one of the data files is modified. * This feature uses Node's `fs.watch()` API on the directories that contain the files, so it * is subject to the limitations described * [here](https://nodejs.org/docs/latest/api/fs.html#fs_fs_watch_filename_options_listener). * A file that is replaced by a rename, or deleted and created again, is detected. A load * that fails, for example because a file was read while it was written, is retried after a * short delay and the previously loaded data stays in effect until it succeeds. * A change to another entry in a directory causes a reload only when the metadata of a * configured file changed, read through any symbolic link, which is how a mounted ConfigMap * or Secret is updated. * Each configured file is also watched directly, so a path that is a symbolic link to a file * in another directory is followed, and that watch is set up again after each change so it * survives the file being replaced. * A directory that cannot be watched, because it does not exist yet or because of its * permissions, is logged at error level and watched once it can be, with an attempt every * second. Its files are still read on every load; a file that cannot be read fails the load, * which is reported through the error handler and retried. */ autoUpdate?: boolean; /** * Configures a logger for warnings and errors. This can be a custom logger or an instance of. * By default, it uses the same logger as the rest of the SDK. */ logger?: LDLogger; /** * The SDK can support yaml if provided with a parser. The parser must output * objects which are equivalent to the standard JSON parser. The parser of the * `yaml` package can be used. */ yamlParser?: (data: string) => any; } interface ClientSideAvailability { usingMobileKey?: boolean; usingEnvironmentId?: boolean; } type Op = 'in' | 'startsWith' | 'endsWith' | 'contains' | 'matches' | 'lessThan' | 'lessThanOrEqual' | 'greaterThan' | 'greaterThanOrEqual' | 'before' | 'after' | 'segmentMatch' | 'semVerEqual' | 'semVerGreaterThan' | 'semVerLessThan'; interface Clause { attribute: string; negate?: boolean; op: Op; values: any[]; contextKind?: string; attributeReference: AttributeReference; } interface WeightedVariation { variation: number; weight: number; untracked?: boolean; } type RolloutKind = 'rollout' | 'experiment'; interface Rollout { kind?: RolloutKind; contextKind?: string; bucketBy?: string; variations: WeightedVariation[]; seed?: number; bucketByAttributeReference?: AttributeReference; } interface VariationOrRollout$1 { variation?: number; rollout?: Rollout; } interface FlagRule extends VariationOrRollout$1 { id: string; variation?: number; rollout?: Rollout; trackEvents?: boolean; clauses?: Clause[]; } /** * The override marker is carried on flag and segment definitions under a reserved, namespaced * key, so it cannot collide with a current or future data model field. Only this module names * the key. Other code reads and strips the marker through these functions. * * Flag overrides are currently experimental and subject to change. */ /** * An entity that can carry the override marker. The interface is part of the Flag and Segment * types and so of the emitted typings; the marker itself is only ever set by the SDK. */ interface OverrideMarkable { /** * True when this definition was supplied by an override source rather than by LaunchDarkly. * * This field is not part of the data model, and the SDK's serializers leave it out. Only the * SDK's override store sets it, on the entries it holds. Evaluation reads it to mark the * evaluations that read the definition. Other readers can treat a marked definition the same * as any other. */ _sdk_override?: boolean; } interface Prerequisite { key: string; variation: number; } interface Target { contextKind?: string; values: string[]; variation: number; } /** * Common interface for flags/segments. Versioned data we store. */ interface Versioned { key: string; version: number; } interface VariationOrRollout { variation?: number; rollout?: Rollout; } interface Flag extends Versioned, OverrideMarkable { on: boolean; prerequisites?: Prerequisite[]; targets?: Omit[]; contextTargets?: Target[]; rules?: FlagRule[]; fallthrough: VariationOrRollout; offVariation?: number; variations: any[]; clientSide?: boolean; clientSideAvailability?: ClientSideAvailability; salt?: string; trackEvents?: boolean; trackEventsFallthrough?: boolean; debugEventsUntilDate?: number; excludeFromSummaries?: boolean; samplingRatio?: number; migration?: { checkRatio?: number; }; } type FileDataSourceErrorHandler = (err: LDFileDataSourceError) => void; /** * Class for creating file data sources. */ declare class FileDataSourceFactory { private readonly _options; constructor(_options: FileDataSourceOptions); getFactory(): (ldClientContext: LDClientContext, featureStore: LDFeatureStore, initSuccessHandler?: VoidFunction, errorHandler?: FileDataSourceErrorHandler) => subsystem.LDStreamProcessor; } /** * A builder for feature flag rules to be used with {@link TestDataFlagBuilder}. * * In the LaunchDarkly model, a flag can have any number of rules, and * a rule can have any number of clauses. A clause is an individual test * such as "name is 'X'". A rule matches a user if all of the rule's * clauses match the user. * * To start defining a rule, use one of the flag builder's matching methods * such as `ifMatch`. This defines the first clause for the rule. Optionally, * you may add more clauses with the rule builder's methods such as `andMatch`. * Finally, call `thenReturn` to finish defining the rule. */ declare class TestDataRuleBuilder { private readonly _flagBuilder; private _clauses; private _variation?; /** * Adds another clause using the "is one of" operator. * * For example, this creates a rule that returns `true` if the name is * "Patsy" and the country is "gb": * * testData.flag('flag') * .ifMatch('name', 'Patsy') * .andMatch('country', 'gb') * .thenReturn(true) * * @param contextKind the kind of the context * @param attribute the user attribute to match against * @param values values to compare to * @return the flag rule builder */ andMatch(contextKind: string, attribute: string, ...values: any): TestDataRuleBuilder; /** * Adds another clause using the "is not one of" operator. * * For example, this creates a rule that returns `true` if the name is * "Patsy" and the country is not "gb": * * testData.flag('flag') * .ifMatch('name', 'Patsy') * .andNotMatch('country', 'gb') * .thenReturn(true) * * @param contextKind the kind of the context * @param attribute the user attribute to match against * @param values values to compare to * @return the flag rule builder */ andNotMatch(contextKind: string, attribute: string, ...values: any): TestDataRuleBuilder; /** * Finishes defining the rule, specifying the result value as either a boolean or an index * * If the variation is a boolean value and the flag was not already a boolean * flag, this also changes it to be a boolean flag. * * If the variation is an integer, it specifies a variation out of whatever * variation values have already been defined. * * @param variation * either `true` or `false` or the index of the desired variation: * 0 for the first, 1 for the second, etc. * @return the flag rule builder */ thenReturn(variation: number | boolean): BuilderType; } /** * A builder for feature flag configurations to be used with {@link TestData}. */ declare class TestDataFlagBuilder { private readonly _key; private _data; private get _isBooleanFlag(); /** * A shortcut for setting the flag to use the standard boolean configuration. * * This is the default for all new flags created with {@link TestData.flag}. The * flag will have two variations, `true` and `false` (in that order). It * will return `false` whenever targeting is off and `true` when targeting * is on unless other settings specify otherwise. * * @return the flag builder */ booleanFlag(): TestDataFlagBuilder; /** * Sets the allowable variation values for the flag. * * The values may be of any JSON-compatible type: boolean, number, string, array, * or object. For instance, a boolean flag normally has `variations(true, false)`; * a string-valued flag might have `variations("red", "green")`; etc. * * @param values any number of variation values * @return the flag builder */ variations(...values: any[]): TestDataFlagBuilder; /** * Sets targeting to be on or off for this flag. * * The effect of this depends on the rest of the flag configuration, just * as it does on the real LaunchDarkly dashboard. In the default configuration * that you get from calling {@link TestData.flag} with a new flag key, the flag * will return `false` whenever targeting is off and `true` when targeting * is on. * * @param targetingOn true if targeting should be on * @return the flag builder */ on(targetingOn: boolean): TestDataFlagBuilder; /** * Specifies the fallthrough variation for a flag. The fallthrough is * the value that is returned if targeting is on and the user was not * matched by a more specific target or rule. * * If a boolean is supplied, and the flag was previously configured with * other variations, this also changes it to a boolean flag. * * @param variation * either `true` or `false` or the index of the desired fallthrough * variation: 0 for the first, 1 for the second, etc. * @return the flag builder */ fallthroughVariation(variation: number | boolean): TestDataFlagBuilder; /** * Specifies the off variation for a flag. This is the variation that is * returned whenever targeting is off. * * If a boolean is supplied, and the flag was previously configured with * other variations, this also changes it to a boolean flag. * * @param variation * either `true` or `false` or the index of the desired off * variation: 0 for the first, 1 for the second, etc. * @return the flag builder */ offVariation(variation: number | boolean): TestDataFlagBuilder; /** * Sets the flag to always return the specified variation for all contexts. * * Targeting is switched on, any existing targets or rules are removed, * and the fallthrough variation is set to the specified value. The off * variation is left unchanged. * * If a boolean is supplied, and the flag was previously configured with * other variations, this also changes it to a boolean flag. * * @param varation * either `true` or `false` or the index of the desired variation: * 0 for the first, 1 for the second, etc. * @return the flag builder */ variationForAll(variation: number | boolean): TestDataFlagBuilder; /** * Sets the flag to always return the specified variation value for all contexts. * * The value may be of any valid JSON type. This method changes the flag to have * only a single variation, which is this value, and to return the same variation * regardless of whether targeting is on or off. Any existing targets or rules * are removed. * * @param value The desired value to be returned for all contexts. * @return the flag builder */ valueForAll(value: any): TestDataFlagBuilder; /** * Sets the flag to return the specified variation for a specific context key * when targeting is on. The context kind for contexts created with this method * will be 'user'. * * This has no effect when targeting is turned off for the flag. * * If the variation is a boolean value and the flag was not already a boolean * flag, this also changes it to be a boolean flag. * * If the variation is an integer, it specifies a variation out of whatever * variation values have already been defined. * * @param contextKey a context key * @param variation * either `true` or `false` or the index of the desired variation: * 0 for the first, 1 for the second, etc. * @return the flag builder */ variationForUser(contextKey: string, variation: number | boolean): TestDataFlagBuilder; /** * Sets the flag to return the specified variation for a specific context key * when targeting is on. * * This has no effect when targeting is turned off for the flag. * * If the variation is a boolean value and the flag was not already a boolean * flag, this also changes it to be a boolean flag. * * If the variation is an integer, it specifies a variation out of whatever * variation values have already been defined. * * @param contextKind a context kind * @param contextKey a context key * @param variation * either `true` or `false` or the index of the desired variation: * 0 for the first, 1 for the second, etc. * @return the flag builder */ variationForContext(contextKind: string, contextKey: string, variation: number | boolean): TestDataFlagBuilder; /** * Removes any existing rules from the flag. This undoes the effect of methods * like {@link ifMatch}. * * @return the same flag builder */ clearRules(): TestDataFlagBuilder; /** * Removes any existing targets from the flag. This undoes the effect of * methods like {@link variationForContext}. * * @return the same flag builder */ clearAllTargets(): TestDataFlagBuilder; /** * Starts defining a flag rule using the "is one of" operator. * * For example, this creates a rule that returnes `true` if the name is * "Patsy" or "Edina": * * testData.flag('flag') * .ifMatch('user', name', 'Patsy', 'Edina') * .thenReturn(true) * * @param contextKind the kind of the context * @param attribute the context attribute to match against * @param values values to compare to * @return * a flag rule builder; call `thenReturn` to finish the rule * or add more tests with another method like `andMatch` */ ifMatch(contextKind: string, attribute: string, ...values: any): TestDataRuleBuilder; /** * Starts defining a flag rule using the "is not one of" operator. * * For example, this creates a rule that returns `true` if the name is * neither "Saffron" nor "Bubble": * * testData.flag('flag') * .ifNotMatch('user', 'name', 'Saffron', 'Bubble') * .thenReturn(true) * * @param contextKind the kind of the context * @param attribute the user attribute to match against * @param values values to compare to * @return * a flag rule builder; call `thenReturn` to finish the rule * or add more tests with another method like `andNotMatch` */ ifNotMatch(contextKind: string, attribute: string, ...values: any): TestDataRuleBuilder; checkRatio(ratio: number): TestDataFlagBuilder; samplingRatio(ratio: number): TestDataFlagBuilder; } /** * A mechanism for providing dynamically updatable feature flag state in a simplified form to an SDK * client in test scenarios. * * Unlike `FileData`, this mechanism does not use any external resources. It provides only the * data that the application has put into it using the {@link TestData.update} method. * * ``` * // Import TestData from the integrations package of the SDK you are using. * // This is a common implementation and may be used in multiple SDKs. * * const td = TestData(); * testData.update(td.flag("flag-key-1").booleanFlag().variationForAll(true)); * // Use the initialization mechanism specified by your SDK. * const client = LDClient.init(sdkKey, { updateProcessor: td.getFactory() }); * * // flags can be updated at any time: * td.update(td.flag("flag-key-2") * .variationForContext("user", "some-user-key", true) * .fallthroughVariation(false)); * ``` * * The above example uses a simple boolean flag, but more complex configurations are possible using * the methods of the {@link TestDataFlagBuilder} that is returned by {@link TestData.flag}. * {@link TestDataFlagBuilder} supports many of the ways a flag can be configured on the * LaunchDarkly dashboard, but does not currently support * 1. rule operators other than "in" and "not in", or * 2. percentage rollouts. * * If the same `TestData` instance is used to configure multiple `LDClient` instances, * any changes made to the data will propagate to all of the `LDClient`s. */ declare class TestData { private _currentFlags; private _currentSegments; private _dataSources; private _flagBuilders; /** * Get a factory for update processors that will be attached to this TestData instance. * @returns An update processor factory. */ getFactory(): (clientContext: LDClientContext, featureStore: LDFeatureStore, initSuccessHandler: VoidFunction, errorHandler?: (e: Error) => void) => subsystem.LDStreamProcessor; /** * Creates or copies a {@link TestDataFlagBuilder} for building a test flag configuration. * * If the flag key has already been defined in this `TestData` instance, * then the builder starts with the same configuration that was last * provided for this flag. * * Otherwise, it starts with a new default configuration in which the flag * has `true` and `false` variations, is `true` for all users when targeting * is turned on and `false` otherwise, and currently has targeting turned on. * You can change any of those properties and provide more complex behavior * using the `TestDataFlagBuilder` methods. * * Once you have set the desired configuration, pass the builder to * {@link TestData.update}. * * @param key the flag key * @returns a flag configuration builder * */ flag(key: string): TestDataFlagBuilder; /** * Updates the test data with the specified flag configuration. * * This has the same effect as if a flag were added or modified in the * LaunchDarkly dashboard. It immediately propagates the flag changes to * any `LDClient` instance(s) that you have already configured to use * this `TestData`. If no `LDClient` has been started yet, it simply adds * this flag to the test data which will be provided to any `LDClient` * that you subsequently configure. * * Any subsequent changes to this `TestDataFlagBuilder` instance do not affect * the test data unless you call `update` again. * * @param flagBuilder a flag configuration builder * @return a promise that will resolve when the feature stores are updated */ update(flagBuilder: TestDataFlagBuilder): Promise; /** * Copies a full feature flag data model object into the test data. * * It immediately propagates the flag change to any `LDClient` instance(s) that you have already * configured to use this `TestData`. If no `LDClient` has been started yet, it simply adds this * flag to the test data which will be provided to any LDClient that you subsequently configure. * * Use this method if you need to use advanced flag configuration properties that are not * supported by the simplified {@link TestDataFlagBuilder} API. Otherwise it is recommended to use * the regular {@link flag}/{@link update} mechanism to avoid dependencies on details of the data * model. * * You cannot make incremental changes with {@link flag}/{@link update} to a flag that has been * added in this way; you can only replace it with an entirely new flag configuration. * * @param flagConfig the flag configuration as a JSON object * @return a promise that will resolve when the feature stores are updated */ usePreconfiguredFlag(inConfig: any): Promise; /** * Copies a full segment data model object into the test data. * * It immediately propagates the change to any `LDClient` instance(s) that you have already * configured to use this `TestData`. If no `LDClient` has been started yet, it simply adds * this segment to the test data which will be provided to any LDClient that you subsequently * configure. * * This method is currently the only way to inject segment data, since there is no builder * API for segments. It is mainly intended for the SDK's own tests of segment functionality, * since application tests that need to produce a desired evaluation state could do so more easily * by just setting flag values. * * @param segmentConfig the segment configuration as a JSON object * @return a promise that will resolve when the feature stores are updated */ usePreconfiguredSegment(inConfig: any): Promise; } type index$1_EvaluationSeriesContext = EvaluationSeriesContext; type index$1_EvaluationSeriesData = EvaluationSeriesData; type index$1_FileDataSourceFactory = FileDataSourceFactory; declare const index$1_FileDataSourceFactory: typeof FileDataSourceFactory; type index$1_FileDataSourceOptions = FileDataSourceOptions; type index$1_Hook = Hook; type index$1_HookMetadata = HookMetadata; type index$1_TestData = TestData; declare const index$1_TestData: typeof TestData; type index$1_TestDataFlagBuilder = TestDataFlagBuilder; declare const index$1_TestDataFlagBuilder: typeof TestDataFlagBuilder; type index$1_TestDataRuleBuilder = TestDataRuleBuilder; declare const index$1_TestDataRuleBuilder: typeof TestDataRuleBuilder; declare namespace index$1 { export { type index$1_EvaluationSeriesContext as EvaluationSeriesContext, type index$1_EvaluationSeriesData as EvaluationSeriesData, index$1_FileDataSourceFactory as FileDataSourceFactory, type index$1_FileDataSourceOptions as FileDataSourceOptions, type index$1_Hook as Hook, type index$1_HookMetadata as HookMetadata, index$1_TestData as TestData, index$1_TestDataFlagBuilder as TestDataFlagBuilder, index$1_TestDataRuleBuilder as TestDataRuleBuilder }; } interface ServerInternalOptions extends internal.LDInternalOptions { getImplementationHooks?: (environmentMetadata: LDPluginEnvironmentMetadata) => Hook[]; /** * Per-SDK-instance identifier sent as the `X-LaunchDarkly-Instance-Id` header on every * outbound request. The SDK that owns instance-id generation (e.g. the Node server SDK) * supplies this; SDKs that do not advertise instance-id support (edge SDKs) leave it * undefined and the header is omitted. */ instanceId?: string; /** * When true, the event processor is constructed without starting its periodic * background work (the flush and context-deduplication interval timers, and the * diagnostic timer when diagnostics are enabled). Events are still recorded and * are delivered only via explicit flush() calls. * * This is intended for per-request edge SDKs that flush explicitly (for example * via a runtime's waitUntil) and must not leave interval timers running. A live * interval timer keeps the runtime event loop alive and roots the whole client * graph in memory, which for a per-request client is a leak. */ disableBackgroundEventFlush?: boolean; } interface LDClientCallbacks { onError: (err: Error) => void; onFailed: (err: Error) => void; onReady: () => void; onUpdate: (key: string) => void; hasEventListeners: () => boolean; } /** * @ignore */ declare class LDClientImpl implements LDClient { private _sdkKey; private _platform; private _initState; private _lastKnownValuesWarningLogged; private _allFlagsStateLastKnownValuesWarningLogged; private _allFlagsStateOverridesOnlyWarningLogged; private _featureStore; private _readStore; private _overrideLayer?; private _overrideSink?; private _overrideSource?; private _overridesReady?; private _updateProcessor?; private _dataSource?; private _eventFactoryDefault; private _eventFactoryWithReasons; private _eventProcessor; private _evaluator; private _initResolve?; private _initReject?; private _rejectionReason; private _initializedPromise?; private _logger?; private _config; private _bigSegmentsManager; private _onError; private _onFailed; private _onReady; private _hookRunner; /** * Derived classes need to use this data to register plugins. */ protected environmentMetadata: LDPluginEnvironmentMetadata; get logger(): LDLogger | undefined; /** * Intended for use by platform specific client implementations. * * It is not included in the main interface because it requires the use of * a platform event system. For node this would be an EventEmitter, for other * platforms it would likely be an EventTarget. */ protected bigSegmentStatusProviderInternal: BigSegmentStoreStatusProviderImpl; constructor(_sdkKey: string, _platform: Platform, options: LDOptions, callbacks: LDClientCallbacks, internalOptions?: ServerInternalOptions); initialized(): boolean; waitForInitialization(options?: LDWaitForInitializationOptions): Promise; /** * Extends the initialization promise with the override source's initial load, when that load * is still in progress. The initial load is part of starting the client, so the start handle * that waitForInitialization returns settles after it, whether initialization succeeded or * failed: an application that handles a failed start and evaluates anyway sees the overrides * that were present at startup. The load never rejects this promise: a failed load is logged * and the client runs without overrides. */ private _withOverridesLoaded; variation(key: string, context: LDContext, defaultValue: any, callback?: (err: any, res: any) => void): Promise; variationDetail(key: string, context: LDContext, defaultValue: any, callback?: (err: any, res: LDEvaluationDetail) => void): Promise; private _typedEval; boolVariation(key: string, context: LDContext, defaultValue: boolean): Promise; numberVariation(key: string, context: LDContext, defaultValue: number): Promise; stringVariation(key: string, context: LDContext, defaultValue: string): Promise; jsonVariation(key: string, context: LDContext, defaultValue: unknown): Promise; boolVariationDetail(key: string, context: LDContext, defaultValue: boolean): Promise>; numberVariationDetail(key: string, context: LDContext, defaultValue: number): Promise>; stringVariationDetail(key: string, context: LDContext, defaultValue: string): Promise>; jsonVariationDetail(key: string, context: LDContext, defaultValue: unknown): Promise>; private _migrationVariationInternal; migrationVariation(key: string, context: LDContext, defaultValue: LDMigrationStage): Promise; allFlagsState(context: LDContext, options?: LDFlagsStateOptions, callback?: (err: Error | null, res: LDFlagsState) => void): Promise; secureModeHash(context: LDContext): string; close(): void; isOffline(): boolean; track(key: string, context: LDContext, data?: any, metricValue?: number): void; trackMigration(event: LDMigrationOpEvent): void; identify(context: LDContext): void; flush(callback?: (err: Error | null, res: boolean) => void): Promise; addHook(hook: Hook): void; private _variationInternal; private _sendEvalEvent; private _evaluateIfPossible; /** * Starts the override source. The returned promise settles when the source's initial load has * completed, also when it failed, and never rejects. A failure never prevents the client from * operating: the layer stays as it was and the failure is logged. The load is part of starting * the client, so waitForInitialization awaits this promise; evaluation does not. */ private _startOverrideSource; private _dataSourceErrorHandler; private _initSuccess; /** * Apply a timeout promise to a base promise. This is for use with waitForInitialization. * Currently it returns a LDClient. In the future it should return a status. * * The client isn't always the expected type of the consumer. It returns an LDClient interface * which is less capable than, for example, the node client interface. * * @param basePromise The promise to race against a timeout. * @param timeout The timeout in seconds. * @param logger A logger to log when the timeout expires. * @returns */ private _clientWithTimeout; } /** * Report a successful migration operation from `readNew`, `readOld`, `writeNew` or `writeOld`. * * ``` * readNew: async () => { * const myResult = doMyOldRead(); * if(myResult.wasGood) { * return LDMigrationSuccess(myResult); * } * return LDMigrationError(myResult.error) * } * ``` * * @param result The result of the operation. * @returns An {@link LDMethodResult} */ declare function LDMigrationSuccess(result: TResult): LDMethodResult; /** * Report a failed migration operation from `readNew`, `readOld`, `writeNew` or `writeOld`. * * ``` * readNew: async () => { * const myResult = doMyOldRead(); * if(myResult.wasGood) { * return LDMigrationSuccess(myResult); * } * return LDMigrationError(myResult.error) * } * ``` * * @param result The result of the operations. * @returns An {@link LDMethodResult} */ declare function LDMigrationError(error: Error): { success: false; error: Error; }; declare function createMigration(client: LDClient, config: LDMigrationOptions): LDMigration; type InitMetadata = internal.InitMetadata; /** * Provides an async interface to a feature store. * * This allows for using a store using async/await instead of callbacks. * */ declare class AsyncStoreFacade { private _store; constructor(store: LDFeatureStore); get(kind: DataKind, key: string): Promise; all(kind: DataKind): Promise; init(allData: LDFeatureStoreDataStorage, initMetadata?: InitMetadata): Promise; delete(kind: DataKind, key: string, version: number): Promise; upsert(kind: DataKind, data: LDKeyedFeatureStoreItem): Promise; initialized(): Promise; close(): void; getInitMetadata?(): InitMetadata | undefined; } /** * Provides an async interface to a feature store. * * This allows for using a store using async/await instead of callbacks. * */ declare class AsyncTransactionalStoreFacade { private _store; constructor(store: LDTransactionalFeatureStore); get(kind: DataKind, key: string): Promise; all(kind: DataKind): Promise; init(allData: LDFeatureStoreDataStorage, initMetadata?: internal.InitMetadata): Promise; delete(kind: DataKind, key: string, version: number): Promise; upsert(kind: DataKind, data: LDKeyedFeatureStoreItem): Promise; initialized(): Promise; applyChanges(basis: boolean, data: LDFeatureStoreDataStorage, initMetadata?: internal.InitMetadata, selector?: string): Promise; close(): void; getInitMetadata?(): internal.InitMetadata | undefined; } /** * Internal implementation of {@link LDFeatureStore} that delegates the basic functionality to an * instance of {@link PersistentDataStore}. It provides optional caching behavior and other logic * that would otherwise be repeated in every data store implementation. This makes it easier to * create new database integrations by implementing only the database-specific logic. */ declare class PersistentDataStoreWrapper implements LDFeatureStore { private readonly _core; private readonly _logger?; private _isInitialized; private _lastErrorLogMs; /** * Cache for storing individual items. */ private _itemCache; /** * Counts the changes that init and upsert make to the item cache. A read caches its result * only if this count did not change while the read was in flight. Otherwise a late read could * replace newer data in the cache. */ private _itemCacheWrites; /** * Cache for storing all items of a type. */ private _allItemsCache; /** * Used to preserve order of operations of async requests. */ private _queue; /** * Check if the underlying storage can be accessed. * * This method is only present when the {@link PersistentDataStore} used by this * wrapper implements it. */ isStoreAvailable?: (callback: (isAvailable: boolean) => void) => void; constructor(_core: PersistentDataStore, ttl: number, _logger?: LDLogger | undefined); init(allData: LDFeatureStoreDataStorage, callback: (err?: Error) => void): void; get(kind: DataKind, key: string, callback: (res: LDFeatureStoreItem | null) => void): void; initialized(callback: (isInitialized: boolean) => void): void; all(kind: DataKind, callback: (res: LDFeatureStoreKindData) => void): void; upsert(kind: DataKind, data: LDKeyedFeatureStoreItem, callback: (err?: Error) => void): void; delete(kind: DataKind, key: string, version: number, callback: () => void): void; /** * Logs a store write error, at error level at most once per interval and at * debug level otherwise, so a store that fails every write cannot flood the log. */ private _logStoreError; close(): void; getDescription(): string; } interface SegmentRule { id: string; clauses: Clause[]; weight?: number; bucketBy?: string; rolloutContextKind?: string; bucketByAttributeReference?: AttributeReference; } interface SegmentTarget { contextKind: string; values: string[]; generated_valuesSet?: Set; } interface Segment extends Versioned, OverrideMarkable { included?: string[]; excluded?: string[]; includedContexts?: SegmentTarget[]; excludedContexts?: SegmentTarget[]; rules?: SegmentRule[]; salt?: string; unbounded?: boolean; unboundedContextKind?: string; generation?: number; bucketByAttributeReference?: AttributeReference; generated_includedSet?: Set; generated_excludedSet?: Set; } interface FlagsAndSegments { flags: { [name: string]: Flag; }; segments: { [name: string]: Segment; }; } /** * This function is intended for usage inside LaunchDarkly SDKs. * This function should NOT be used by customer applications. * This function may be changed or removed without a major version. * * @param payload Payload data from launchdarkly. * @returns The revived and processed data. */ declare function reviveFullPayload(payload: Record): FlagsAndSegments; /** * This function is intended for usage inside LaunchDarkly SDKs. * This function should NOT be used by customer applications. * This function may be changed or removed without a major version. * * @param data String data from launchdarkly. * @returns The parsed and processed data. */ declare function deserializePoll(data: string): FlagsAndSegments | undefined; /** * Wraps a non-transactional {@link LDFeatureStore} and makes it transactional through * an in-memory store acting as a cache. * * It also monitors the mirrored writes to the persistence store. A failed write marks * the store unavailable. When the store recovers, this writes the full in-memory data * set back to it. * * At most one full-store write is in flight at a time: a new write-back starts * only after the previous write-back's store call has answered. A write-back is * never abandoned. Its answer, however late, decides the outcome. */ declare class TransactionalFeatureStore implements LDTransactionalFeatureStore { private readonly _basePersistenceStore; private readonly _logger?; private readonly _backoff; private _memoryStore; private _activeStore; private _persistenceAvailable; private _probe; private _writeBackOp; private _writeBackEmbargoUntil; private _writeFailedDuringWriteBack; private _writeBackCallOutstanding; private _failureLoggedThisOutage; private _slowWriteBackWarnedThisOutage; private _closed; private _pollHandle?; private _embargoRetryHandle?; private _slowWriteBackWarningHandle?; constructor(_basePersistenceStore: LDFeatureStore, _logger?: LDLogger | undefined, _backoff?: Pick); get(kind: DataKind, key: string, callback: (res: LDFeatureStoreItem | null) => void): void; all(kind: DataKind, callback: (res: LDFeatureStoreKindData) => void): void; init(allData: LDFeatureStoreDataStorage, callback: () => void): void; delete(kind: DataKind, key: string, version: number, callback: () => void): void; upsert(kind: DataKind, data: LDKeyedFeatureStoreItem, callback: () => void): void; applyChanges(basis: boolean, data: LDFeatureStoreDataStorage, callback: () => void, initMetadata?: internal.InitMetadata, selector?: string): void; initialized(callback: (isInitialized: boolean) => void): void; close(): void; getDescription(): string; getInitMetaData(): internal.InitMetadata | undefined; getSelector(): string | undefined; /** * Record the result of a mirrored write to the persistence store. * * The first failed write marks the store unavailable. A successful write while the * store is unavailable starts recovery. * * A basis write already wrote the full data set, so it recovers directly. Any * other write starts a write-back of the full in-memory data set instead. */ private _handleWriteResult; private _markUnavailable; private _markAvailable; /** * Poll the persistence store availability check, when it has one, until the store * recovers. Stores without an availability check recover through the next successful * mirrored write instead. The check is read-only. A write is never used as a check. */ private _startRecoveryPolling; private _stopRecoveryPolling; /** * Schedules the next write-back attempt at the embargo deadline. * * Without this timer, a recovery signal that arrived during the embargo, or a * failed write-back with no follow-up write, could leave no later trigger: a * store without an availability check has no poller, and a poller's probe can * disagree with the write path. At most one timer runs. Recovery and close * cancel it. A duplicate trigger with the poll tick is harmless: whichever * fires second finds the attempt already in flight or the store recovered. */ private _scheduleEmbargoRetry; private _cancelEmbargoRetry; /** * Arms a one-shot timer that warns when the write-back's store call is slow to * answer. The call is never abandoned: recovery waits for its answer, however * long it takes. The timer only logs. It changes no state. */ private _armSlowWriteBackWarning; private _cancelSlowWriteBackWarning; /** * Abandons the outstanding availability probe once it is past its deadline. * * Bumps the generation so a late answer is ignored, and clears the in-flight flag * so a fresh probe can be issued. Returns whether it was released. */ private _releaseProbeIfHung; private _attemptRecovery; /** * Write the full in-memory data set, including tombstones, to the persistence store. * The caller must begin the attempt on _writeBackOp and pass its generation. */ private _writeBack; /** * Backs off the next write-back attempt after a failed one, and schedules that * attempt at the backoff deadline. */ private _armFailureEmbargo; /** * Records a failed write-back attempt: backs off the next attempt and logs. * * Only the first failure of an outage logs at error level. Later failures in the * same outage log at debug level, so an unhealthy store cannot flood the log * every poll tick. */ private _handleWriteBackFailure; } declare class NullEventSource implements EventSource { handlers: Record void>; closed: boolean; url: string; options: EventSourceInitDict; constructor(url: string, options: EventSourceInitDict); onclose: (() => void) | undefined; onerror: (() => void) | undefined; onopen: (() => void) | undefined; onretrying: ((e: { delayMillis: number; }) => void) | undefined; addEventListener(type: string, listener: (event?: { data?: any; }) => void): void; close(): void; simulateError(error: { status: number; message: string; }): void; } /** * Options for the TTL cache. */ interface TtlCacheOptions { /** * The TTL for all items in seconds. */ ttl: number; /** * Time, in seconds, to check for expired items and purge them from the cache. */ checkInterval: number; } /** * A basic TTL cache with configurable TTL and check interval. */ declare class TtlCache { private readonly _options; private _storage; private _checkIntervalHandle; constructor(_options: TtlCacheOptions); /** * Get a value from the cache. * @param key The key to get a value for. * @returns The value for the key, or undefined if the key was not added, or * if the value has expired. */ get(key: string): any; /** * Set an item in the cache. It will expire after the TTL specified * in the cache configuration. * @param key The key for the value. * @param value The value to set. */ set(key: string, value: any): void; /** * Delete the item with the specific key. If the item does not exist, * then there will be no change to the cache. * @param key The key of the value to delete. */ delete(key: string): void; /** * Clear the items that are in the cache. */ clear(): void; /** * Indicate that you are no longer going to use the cache. The cache will be * cleared and it will stop checking for stale items. */ close(): void; private _purgeStale; } type index_TtlCache = TtlCache; declare const index_TtlCache: typeof TtlCache; type index_TtlCacheOptions = TtlCacheOptions; declare namespace index { export { index_TtlCache as TtlCache, type index_TtlCacheOptions as TtlCacheOptions }; } export { AsyncStoreFacade, AsyncTransactionalStoreFacade, BigSegmentStoreStatusProviderImpl, type CustomDataSourceOptions, type DataKind, type DataSourceConfiguration, type DataSourceOptions, type FDv1FallbackConfiguration, FileDataSourceFactory, type FileOverrideSourceOptions, type FileSystemDataSourceConfiguration, type InitializerDataSource, IsMigrationStage, type LDBigSegmentsOptions, type LDClient, LDClientImpl, LDConcurrentExecution, LDConsistencyCheck, type LDDataSystemOptions, LDExecution, LDExecutionOrdering, type LDFeatureStore, type LDFeatureStoreDataStorage, type LDFeatureStoreItem, type LDFeatureStoreKindData, type LDFlagsState, type LDFlagsStateOptions, type LDKeyedFeatureStoreItem, type LDMethodResult, type LDMigration, type LDMigrationConsistencyMeasurement, LDMigrationError, type LDMigrationErrorMeasurement, type LDMigrationEvaluation, type LDMigrationInvokedMeasurement, type LDMigrationLatencyMeasurement, type LDMigrationMeasurement, type LDMigrationOp, type LDMigrationOpEvent, type LDMigrationOptions, type LDMigrationOrigin, type LDMigrationReadResult, type LDMigrationResult, LDMigrationStage, LDMigrationSuccess, type LDMigrationTracker, type LDMigrationVariation, type LDMigrationWriteResult, type LDOptions, type LDOverrideSink, type LDOverrideSource, type LDOverrideSourceOptions, type LDProxyOptions, LDSerialExecution, type LDTLSOptions, type LDTransactionalFeatureStore, type LDWaitForInitializationOptions, NullEventSource, PersistentDataStoreWrapper, type PollingDataSourceConfiguration, type PollingDataSourceOptions, type ServerInternalOptions, type StandardDataSourceOptions, type StreamingDataSourceConfiguration, type StreamingDataSourceOptions, type SynchronizerDataSource, TestData, TestDataFlagBuilder, TestDataRuleBuilder, TransactionalFeatureStore, createMigration, deserializePoll, index$1 as integrations, index$3 as interfaces, index as internalServer, isCustomOptions, isFileOverrideSourceOptions, isPollingOnlyOptions, isStandardOptions, isStreamingOnlyOptions, reviveFullPayload, index$2 as subsystems };