Primeiro commit do projeto Angular

This commit is contained in:
2026-03-14 20:41:55 +00:00
parent 9bebe1de72
commit 94f4f46395
22413 changed files with 3221690 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2013-Present Algolia
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+76
View File
@@ -0,0 +1,76 @@
<p align="center">
<a href="https://www.algolia.com">
<img alt="Algolia for JavaScript" src="https://raw.githubusercontent.com/algolia/algoliasearch-client-common/master/banners/javascript.png" >
</a>
<h4 align="center">The perfect starting point to integrate <a href="https://algolia.com" target="_blank">Algolia</a> within your JavaScript project</h4>
<p align="center">
<a href="https://npmjs.com/package/@algolia/abtesting"><img src="https://img.shields.io/npm/v/@algolia/abtesting.svg?style=flat-square" alt="NPM version"></img></a>
<a href="http://npm-stat.com/charts.html?package=@algolia/abtesting"><img src="https://img.shields.io/npm/dm/@algolia/abtesting.svg?style=flat-square" alt="NPM downloads"></a>
<a href="https://www.jsdelivr.com/package/npm/@algolia/abtesting"><img src="https://data.jsdelivr.com/v1/package/npm/@algolia/abtesting/badge" alt="jsDelivr Downloads"></img></a>
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-green.svg?style=flat-square" alt="License"></a>
</p>
</p>
<p align="center">
<a href="https://www.algolia.com/doc/libraries/sdk/install#javascript" target="_blank">Documentation</a> •
<a href="https://www.algolia.com/doc/guides/building-search-ui/what-is-instantsearch/js/" target="_blank">InstantSearch</a> •
<a href="https://discourse.algolia.com" target="_blank">Community Forum</a> •
<a href="http://stackoverflow.com/questions/tagged/algolia" target="_blank">Stack Overflow</a> •
<a href="https://github.com/algolia/algoliasearch-client-javascript/issues" target="_blank">Report a bug</a> •
<a href="https://alg.li/support" target="_blank">Support</a>
</p>
## ✨ Features
- Thin & **minimal low-level HTTP client** to interact with Algolia's API
- Works both on the **browser** and **node.js**
- **UMD and ESM compatible**, you can use it with any module loader
- Built with TypeScript
## 💡 Getting Started
> [!TIP]
> This API client is already a dependency of [the algoliasearch client](https://www.npmjs.com/package/algoliasearch), you don't need to manually install `@algolia/abtesting` if you already have `algoliasearch` installed.
To get started, you first need to install @algolia/abtesting (or any other available API client package).
All of our clients comes with type definition, and are available for both browser and node environments.
### With a package manager
```bash
yarn add @algolia/abtesting@1.14.1
# or
npm install @algolia/abtesting@1.14.1
# or
pnpm add @algolia/abtesting@1.14.1
```
### Without a package manager
Add the following JavaScript snippet to the <head> of your website:
```html
<script src="https://cdn.jsdelivr.net/npm/@algolia/abtesting@1.14.1/dist/builds/browser.umd.js"></script>
```
### Usage
You can now import the Algolia API client in your project and play with it.
```js
import { abtestingV3Client } from '@algolia/abtesting';
const client = abtestingV3Client('YOUR_APP_ID', 'YOUR_API_KEY');
```
For full documentation, visit the **[Algolia JavaScript API Client](https://www.algolia.com/doc/libraries/sdk/methods/abtesting-v3/)**.
## ❓ Troubleshooting
Encountering an issue? Before reaching out to support, we recommend heading to our [FAQ](https://support.algolia.com/hc/en-us/sections/15061037630609-API-Client-FAQs) where you will find answers for the most common issues and gotchas with the client. You can also open [a GitHub issue](https://github.com/algolia/api-clients-automation/issues/new?assignees=&labels=&projects=&template=Bug_report.md)
## 📄 License
The Algolia JavaScript API Client is an open-sourced software licensed under the [MIT license](LICENSE).
+676
View File
@@ -0,0 +1,676 @@
import * as _algolia_client_common from '@algolia/client-common';
import { CreateClientOptions, RequestOptions, ClientOptions } from '@algolia/client-common';
/**
* Multiple-testing correction method applied when evaluating metric significance.
*/
type ErrorCorrectionType = 'bonferroni' | 'benjamini-hochberg';
/**
* Boolean filter applied to the A/B test population. Each filter targets a boolean metric and decides whether to include (true) or exclude (false) matching records.
*/
type MetricsFilter = {
/**
* Metric domain (for example `abtesting`, `personalization`).
*/
domain: string;
/**
* Public metric name.
*/
name: string;
/**
* Whether the experiment should record the effects of this filter.
*/
trackEffects?: boolean | undefined;
/**
* If true, keep items that match the filter; if false, exclude them.
*/
includes?: boolean | undefined;
};
/**
* Metric for which you want to detect the smallest relative difference.
*/
type EffectMetric = 'addToCartRate' | 'clickThroughRate' | 'conversionRate' | 'purchaseRate' | 'noResultsRate';
/**
* Configuration for the smallest difference between test variants you want to detect.
*/
type MinimumDetectableEffect = {
/**
* Smallest difference in an observable metric between variants. For example, to detect a 10% difference between variants, set this value to 0.1.
*/
size: number;
metric: EffectMetric;
};
/**
* A/B test configuration.
*/
type ABTestConfiguration = {
minimumDetectableEffect?: MinimumDetectableEffect | undefined;
/**
* List of metric filters applied to the test population.
*/
filters?: Array<MetricsFilter> | undefined;
errorCorrection?: ErrorCorrectionType | undefined;
};
/**
* A/B test status. - `active`. The A/B test is live and search traffic is split between the two variants. - `stopped`. You stopped the A/B test. The A/B test data is still available for analysis. - `expired`. The A/B test was automatically stopped after reaching its end date. - `failed`. Creating the A/B test failed.
*/
type Status = 'active' | 'stopped' | 'expired' | 'failed';
/**
* Metric specific metadata.
*/
type MetricMetadata = {
/**
* Only present in case the metric is \'revenue\'. It is the amount exceeding the 95th percentile of global revenue transactions involved in the AB Test. This amount is not considered when calculating statistical significance. It is tied to a per revenue-currency pair contrary to other global filter effects (such as outliers and empty search count).
*/
winsorizedValue?: number | undefined;
/**
* Mean value for this metric.
*/
mean?: number | undefined;
};
type MetricResult = {
name: string;
/**
* Date and time when the metric was last updated, in RFC 3339 format.
*/
updatedAt: string;
value: number;
/**
* The upper bound of the 95% confidence interval for the metric value. The confidence interval is calculated using either the relative ratio or relative difference between the metric values for the control and the variant. Relative ratio is used for metrics that are ratios (e.g., click-through rate, conversion rate), while relative difference is used for continuous metrics (e.g., revenue).
*/
valueCIHigh?: number | undefined;
/**
* The lower bound of the 95% confidence interval for the metric value. The confidence interval is calculated using either the relative ratio or relative difference between the metric values for the control and the variant. Relative ratio is used for metrics that are ratios (e.g., click-through rate, conversion rate), while relative difference is used for continuous metrics (e.g., revenue).
*/
valueCILow?: number | undefined;
/**
* PValue for the first variant (control) will always be 0. For the other variants, pValue is calculated for the current variant based on the control.
*/
pValue: number;
/**
* Dimension defined during test creation.
*/
dimension?: string | undefined;
metadata?: MetricMetadata | undefined;
/**
* The value that was computed during error correction. It is used to determine significance of the metric pValue. The critical value is calculated using Bonferroni or Benjamini-Hochberg corrections, based on the given configuration during the A/B test creation.
*/
criticalValue?: number | undefined;
/**
* Whether the pValue is significant or not based on the critical value and the error correction algorithm used.
*/
significant?: boolean | undefined;
};
/**
* Empty searches removed from the A/B test as a result of configuration settings.
*/
type EmptySearchFilter = {
/**
* Number of users removed from the A/B test.
*/
usersCount?: number | undefined;
/**
* Number of tracked searches removed from the A/B test.
*/
trackedSearchesCount?: number | undefined;
};
/**
* Outliers removed from the A/B test as a result of configuration settings.
*/
type OutliersFilter = {
/**
* Number of users removed from the A/B test.
*/
usersCount?: number | undefined;
/**
* Number of tracked searches removed from the A/B test.
*/
trackedSearchesCount?: number | undefined;
};
/**
* A/B test filter effects resulting from configuration settings.
*/
type FilterEffects = {
outliers?: OutliersFilter | undefined;
emptySearch?: EmptySearchFilter | undefined;
};
/**
* Variant specific metadata.
*/
type VariantMetadata = {
filterEffects?: FilterEffects | undefined;
};
type Variant = {
/**
* Description for this variant.
*/
description: string;
/**
* Estimated number of searches required to achieve the desired statistical significance. The A/B test configuration must include a `minimumDetectableEffect` setting for this number to be included in the response.
*/
estimatedSampleSize?: number | undefined;
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Percentage of search requests each variant receives.
*/
trafficPercentage: number;
/**
* All ABTest metrics that were defined during test creation.
*/
metrics: Array<MetricResult>;
metadata?: VariantMetadata | undefined;
/**
* Search parameters applied to this variant when the same index is used for multiple variants. Only present if custom search parameters were provided during test creation.
*/
customSearchParameters?: Record<string, unknown> | undefined;
};
type ABTest = {
/**
* Unique A/B test identifier.
*/
abTestID: number;
/**
* Date and time when the A/B test was last updated, in RFC 3339 format.
*/
updatedAt: string;
/**
* Date and time when the A/B test was created, in RFC 3339 format.
*/
createdAt: string;
/**
* End date and time of the A/B test, in RFC 3339 format.
*/
endAt: string;
/**
* Date and time when the A/B test was stopped, in RFC 3339 format.
*/
stoppedAt?: string | null | undefined;
/**
* A/B test name.
*/
name: string;
status: Status;
/**
* A/B test variants. The first variant is your _control_ index, typically your production index. All of the additional variants are indexes with changed settings that you want to test against the control.
*/
variants: Array<Variant>;
configuration?: ABTestConfiguration | undefined;
/**
* Unique migrated A/B test identifier.
*/
migratedAbTestID?: number | undefined;
};
type ABTestResponse = {
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Unique A/B test identifier.
*/
abTestID: number;
/**
* Unique identifier of a task. A successful API response means that a task was added to a queue. It might not run immediately. You can check the task\'s progress with the [`task` operation](https://www.algolia.com/doc/rest-api/search/get-task) and this task ID.
*/
taskID: number;
};
type AbTestsVariant = {
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Percentage of search requests each variant receives.
*/
trafficPercentage: number;
/**
* Description for this variant.
*/
description?: string | undefined;
};
/**
* Search parameters to add to the test variant. Only use this parameter if the two variants use the same index.
*/
type CustomSearchParams = {
customSearchParameters: Record<string, unknown>;
};
type AbTestsVariantSearchParams = AbTestsVariant & CustomSearchParams;
type AddABTestsVariant = AbTestsVariant | AbTestsVariantSearchParams;
/**
* Defines a metric to be retrieved during an A/B test.
*/
type CreateMetric = {
/**
* Name of the metric.
*/
name: string;
/**
* Dimension of the metric, for example, in case of a revenue metric it could be USD, EUR...
*/
dimension?: string | undefined;
};
type AddABTestsRequest = {
/**
* A/B test name.
*/
name: string;
/**
* A/B test variants.
*/
variants: Array<AddABTestsVariant>;
/**
* A/B test metrics involved in the test. Only these metrics will be considered when calculating results.
*/
metrics: Array<CreateMetric>;
configuration?: ABTestConfiguration | undefined;
/**
* End date and time of the A/B test, in RFC 3339 format.
*/
endAt: string;
};
/**
* A/B test configuration for estimating the sample size and duration using minimum detectable effect.
*/
type EstimateConfiguration = {
/**
* List of metric filters applied to the test population.
*/
filters?: Array<MetricsFilter> | undefined;
minimumDetectableEffect: MinimumDetectableEffect;
};
type EstimateABTestRequest = {
configuration: EstimateConfiguration;
/**
* A/B test variants.
*/
variants: Array<AddABTestsVariant>;
};
type EstimateABTestResponse = {
/**
* Estimated number of days needed to reach the sample sizes required for detecting the configured effect. This value is based on historical traffic.
*/
durationDays?: number | undefined;
/**
* Sample size estimates for each variant. The first element is the control variant. Each element is the estimated number of searches required to achieve the desired statistical significance.
*/
sampleSizes?: Array<number> | undefined;
};
type ListABTestsResponse = {
/**
* A/B tests.
*/
abtests: Array<ABTest> | null;
/**
* Number of A/B tests.
*/
count: number;
/**
* Number of retrievable A/B tests.
*/
total: number;
};
type MetricDate = {
/**
* Date where the metric was updated, in RFC 3339 format.
*/
date?: string | undefined;
/**
* All ABTest metrics that were defined during test creation.
*/
metrics?: Array<MetricResult> | undefined;
};
type TimeseriesVariant = {
dates?: Array<MetricDate> | undefined;
};
type Timeseries = {
/**
* Unique A/B test identifier.
*/
abTestID: number;
/**
* A/B test timeseries variants. The first variant is your _control_ index, typically your production index. All of the additional variants are indexes with changed settings that you want to test against the control.
*/
variants: Array<TimeseriesVariant>;
};
/**
* Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
*/
type Direction = 'asc' | 'desc';
type MetricName = 'search_count' | 'tracked_search_count' | 'user_count' | 'tracked_user_count' | 'no_result_count' | 'add_to_cart_count' | 'purchase_count' | 'clicked_search_count' | 'converted_search_count' | 'click_through_rate' | 'conversion_rate' | 'add_to_cart_rate' | 'purchase_rate' | 'average_click_position' | 'revenue';
/**
* Properties for the `customDelete` method.
*/
type CustomDeleteProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customGet` method.
*/
type CustomGetProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customPost` method.
*/
type CustomPostProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `customPut` method.
*/
type CustomPutProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `deleteABTest` method.
*/
type DeleteABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
/**
* Properties for the `getABTest` method.
*/
type GetABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
/**
* Properties for the `getTimeseries` method.
*/
type GetTimeseriesProps = {
/**
* Unique A/B test identifier.
*/
id: number;
/**
* Start date of the period to analyze, in `YYYY-MM-DD` format.
*/
startDate?: string | undefined;
/**
* End date of the period to analyze, in `YYYY-MM-DD` format.
*/
endDate?: string | undefined;
/**
* List of metrics to retrieve. If not specified, all metrics are returned.
*/
metric?: Array<MetricName> | undefined;
};
/**
* Properties for the `listABTests` method.
*/
type ListABTestsProps = {
/**
* Position of the first item to return.
*/
offset?: number | undefined;
/**
* Number of items to return.
*/
limit?: number | undefined;
/**
* Index name prefix. Only A/B tests for indices starting with this string are included in the response.
*/
indexPrefix?: string | undefined;
/**
* Index name suffix. Only A/B tests for indices ending with this string are included in the response.
*/
indexSuffix?: string | undefined;
/**
* Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
*/
direction?: Direction | undefined;
};
/**
* Properties for the `stopABTest` method.
*/
type StopABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
declare const apiClientVersion = "1.14.1";
declare const REGIONS: readonly ["de", "us"];
type Region = (typeof REGIONS)[number];
type RegionOptions = {
region?: Region | undefined;
};
declare function createAbtestingV3Client({ appId: appIdOption, apiKey: apiKeyOption, authMode, algoliaAgents, region: regionOption, ...options }: CreateClientOptions & RegionOptions): {
transporter: _algolia_client_common.Transporter;
/**
* The `appId` currently in use.
*/
appId: string;
/**
* The `apiKey` currently in use.
*/
apiKey: string;
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache(): Promise<void>;
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
readonly _ua: string;
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment: string, version?: string | undefined): void;
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }: {
apiKey: string;
}): void;
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest: AddABTestsRequest, requestOptions?: RequestOptions): Promise<ABTestResponse>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }: CustomDeleteProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }: CustomGetProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }: CustomPostProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }: CustomPutProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }: DeleteABTestProps, requestOptions?: RequestOptions): Promise<ABTestResponse>;
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest: EstimateABTestRequest, requestOptions?: RequestOptions): Promise<EstimateABTestResponse>;
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }: GetABTestProps, requestOptions?: RequestOptions): Promise<ABTest>;
/**
* Retrieves timeseries for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getTimeseries - The getTimeseries object.
* @param getTimeseries.id - Unique A/B test identifier.
* @param getTimeseries.startDate - Start date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.endDate - End date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.metric - List of metrics to retrieve. If not specified, all metrics are returned.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getTimeseries({ id, startDate, endDate, metric }: GetTimeseriesProps, requestOptions?: RequestOptions): Promise<Timeseries>;
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param listABTests.direction - Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix, direction }?: ListABTestsProps, requestOptions?: RequestOptions | undefined): Promise<ListABTestsResponse>;
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }: StopABTestProps, requestOptions?: RequestOptions): Promise<ABTestResponse>;
};
/**
* Error.
*/
type ErrorBase = Record<string, any> & {
message?: string | undefined;
};
declare function abtestingV3Client(appId: string, apiKey: string, region?: Region | undefined, options?: ClientOptions | undefined): AbtestingV3Client;
type AbtestingV3Client = ReturnType<typeof createAbtestingV3Client>;
export { type ABTest, type ABTestConfiguration, type ABTestResponse, type AbTestsVariant, type AbTestsVariantSearchParams, type AbtestingV3Client, type AddABTestsRequest, type AddABTestsVariant, type CreateMetric, type CustomDeleteProps, type CustomGetProps, type CustomPostProps, type CustomPutProps, type CustomSearchParams, type DeleteABTestProps, type Direction, type EffectMetric, type EmptySearchFilter, type ErrorBase, type ErrorCorrectionType, type EstimateABTestRequest, type EstimateABTestResponse, type EstimateConfiguration, type FilterEffects, type GetABTestProps, type GetTimeseriesProps, type ListABTestsProps, type ListABTestsResponse, type MetricDate, type MetricMetadata, type MetricName, type MetricResult, type MetricsFilter, type MinimumDetectableEffect, type OutliersFilter, type Region, type RegionOptions, type Status, type StopABTestProps, type Timeseries, type TimeseriesVariant, type Variant, type VariantMetadata, abtestingV3Client, apiClientVersion };
+434
View File
@@ -0,0 +1,434 @@
// builds/browser.ts
import {
createBrowserLocalStorageCache,
createFallbackableCache,
createMemoryCache,
createNullLogger
} from "@algolia/client-common";
import { createXhrRequester } from "@algolia/requester-browser-xhr";
// src/abtestingV3Client.ts
import { createAuth, createTransporter, getAlgoliaAgent } from "@algolia/client-common";
var apiClientVersion = "1.14.1";
var REGIONS = ["de", "us"];
function getDefaultHosts(region) {
const url = !region ? "analytics.algolia.com" : "analytics.{region}.algolia.com".replace("{region}", region);
return [{ url, accept: "readWrite", protocol: "https" }];
}
function createAbtestingV3Client({
appId: appIdOption,
apiKey: apiKeyOption,
authMode,
algoliaAgents,
region: regionOption,
...options
}) {
const auth = createAuth(appIdOption, apiKeyOption, authMode);
const transporter = createTransporter({
hosts: getDefaultHosts(regionOption),
...options,
algoliaAgent: getAlgoliaAgent({
algoliaAgents,
client: "AbtestingV3",
version: apiClientVersion
}),
baseHeaders: {
"content-type": "text/plain",
...auth.headers(),
...options.baseHeaders
},
baseQueryParameters: {
...auth.queryParameters(),
...options.baseQueryParameters
}
});
return {
transporter,
/**
* The `appId` currently in use.
*/
appId: appIdOption,
/**
* The `apiKey` currently in use.
*/
apiKey: apiKeyOption,
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache() {
return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => void 0);
},
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
get _ua() {
return transporter.algoliaAgent.value;
},
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment, version) {
transporter.algoliaAgent.add({ segment, version });
},
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }) {
if (!authMode || authMode === "WithinHeaders") {
transporter.baseHeaders["x-algolia-api-key"] = apiKey;
} else {
transporter.baseQueryParameters["x-algolia-api-key"] = apiKey;
}
},
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest, requestOptions) {
if (!addABTestsRequest) {
throw new Error("Parameter `addABTestsRequest` is required when calling `addABTests`.");
}
if (!addABTestsRequest.name) {
throw new Error("Parameter `addABTestsRequest.name` is required when calling `addABTests`.");
}
if (!addABTestsRequest.variants) {
throw new Error("Parameter `addABTestsRequest.variants` is required when calling `addABTests`.");
}
if (!addABTestsRequest.metrics) {
throw new Error("Parameter `addABTestsRequest.metrics` is required when calling `addABTests`.");
}
if (!addABTestsRequest.endAt) {
throw new Error("Parameter `addABTestsRequest.endAt` is required when calling `addABTests`.");
}
const requestPath = "/3/abtests";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: addABTestsRequest
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customDelete`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customGet`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPost`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPut`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "PUT",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `deleteABTest`.");
}
const requestPath = "/3/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest, requestOptions) {
if (!estimateABTestRequest) {
throw new Error("Parameter `estimateABTestRequest` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.configuration) {
throw new Error("Parameter `estimateABTestRequest.configuration` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.variants) {
throw new Error("Parameter `estimateABTestRequest.variants` is required when calling `estimateABTest`.");
}
const requestPath = "/3/abtests/estimate";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: estimateABTestRequest
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `getABTest`.");
}
const requestPath = "/3/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves timeseries for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getTimeseries - The getTimeseries object.
* @param getTimeseries.id - Unique A/B test identifier.
* @param getTimeseries.startDate - Start date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.endDate - End date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.metric - List of metrics to retrieve. If not specified, all metrics are returned.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getTimeseries({ id, startDate, endDate, metric }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `getTimeseries`.");
}
const requestPath = "/3/abtests/{id}/timeseries".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
if (startDate !== void 0) {
queryParameters["startDate"] = startDate.toString();
}
if (endDate !== void 0) {
queryParameters["endDate"] = endDate.toString();
}
if (metric !== void 0) {
queryParameters["metric"] = metric.toString();
}
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param listABTests.direction - Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix, direction } = {}, requestOptions = void 0) {
const requestPath = "/3/abtests";
const headers = {};
const queryParameters = {};
if (offset !== void 0) {
queryParameters["offset"] = offset.toString();
}
if (limit !== void 0) {
queryParameters["limit"] = limit.toString();
}
if (indexPrefix !== void 0) {
queryParameters["indexPrefix"] = indexPrefix.toString();
}
if (indexSuffix !== void 0) {
queryParameters["indexSuffix"] = indexSuffix.toString();
}
if (direction !== void 0) {
queryParameters["direction"] = direction.toString();
}
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `stopABTest`.");
}
const requestPath = "/3/abtests/{id}/stop".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
}
};
}
// builds/browser.ts
function abtestingV3Client(appId, apiKey, region, options) {
if (!appId || typeof appId !== "string") {
throw new Error("`appId` is missing.");
}
if (!apiKey || typeof apiKey !== "string") {
throw new Error("`apiKey` is missing.");
}
if (region && (typeof region !== "string" || !REGIONS.includes(region))) {
throw new Error(`\`region\` must be one of the following: ${REGIONS.join(", ")}`);
}
return createAbtestingV3Client({
appId,
apiKey,
region,
timeouts: {
connect: 1e3,
read: 2e3,
write: 3e4
},
logger: createNullLogger(),
requester: createXhrRequester(),
algoliaAgents: [{ segment: "Browser" }],
authMode: "WithinQueryParameters",
responsesCache: createMemoryCache(),
requestsCache: createMemoryCache({ serializable: false }),
hostsCache: createFallbackableCache({
caches: [createBrowserLocalStorageCache({ key: `${apiClientVersion}-${appId}` }), createMemoryCache()]
}),
...options
});
}
export {
abtestingV3Client,
apiClientVersion
};
//# sourceMappingURL=browser.js.map
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+428
View File
@@ -0,0 +1,428 @@
// builds/fetch.ts
import { createMemoryCache, createNullCache, createNullLogger } from "@algolia/client-common";
import { createFetchRequester } from "@algolia/requester-fetch";
// src/abtestingV3Client.ts
import { createAuth, createTransporter, getAlgoliaAgent } from "@algolia/client-common";
var apiClientVersion = "1.14.1";
var REGIONS = ["de", "us"];
function getDefaultHosts(region) {
const url = !region ? "analytics.algolia.com" : "analytics.{region}.algolia.com".replace("{region}", region);
return [{ url, accept: "readWrite", protocol: "https" }];
}
function createAbtestingV3Client({
appId: appIdOption,
apiKey: apiKeyOption,
authMode,
algoliaAgents,
region: regionOption,
...options
}) {
const auth = createAuth(appIdOption, apiKeyOption, authMode);
const transporter = createTransporter({
hosts: getDefaultHosts(regionOption),
...options,
algoliaAgent: getAlgoliaAgent({
algoliaAgents,
client: "AbtestingV3",
version: apiClientVersion
}),
baseHeaders: {
"content-type": "text/plain",
...auth.headers(),
...options.baseHeaders
},
baseQueryParameters: {
...auth.queryParameters(),
...options.baseQueryParameters
}
});
return {
transporter,
/**
* The `appId` currently in use.
*/
appId: appIdOption,
/**
* The `apiKey` currently in use.
*/
apiKey: apiKeyOption,
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache() {
return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => void 0);
},
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
get _ua() {
return transporter.algoliaAgent.value;
},
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment, version) {
transporter.algoliaAgent.add({ segment, version });
},
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }) {
if (!authMode || authMode === "WithinHeaders") {
transporter.baseHeaders["x-algolia-api-key"] = apiKey;
} else {
transporter.baseQueryParameters["x-algolia-api-key"] = apiKey;
}
},
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest, requestOptions) {
if (!addABTestsRequest) {
throw new Error("Parameter `addABTestsRequest` is required when calling `addABTests`.");
}
if (!addABTestsRequest.name) {
throw new Error("Parameter `addABTestsRequest.name` is required when calling `addABTests`.");
}
if (!addABTestsRequest.variants) {
throw new Error("Parameter `addABTestsRequest.variants` is required when calling `addABTests`.");
}
if (!addABTestsRequest.metrics) {
throw new Error("Parameter `addABTestsRequest.metrics` is required when calling `addABTests`.");
}
if (!addABTestsRequest.endAt) {
throw new Error("Parameter `addABTestsRequest.endAt` is required when calling `addABTests`.");
}
const requestPath = "/3/abtests";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: addABTestsRequest
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customDelete`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customGet`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPost`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPut`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "PUT",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `deleteABTest`.");
}
const requestPath = "/3/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest, requestOptions) {
if (!estimateABTestRequest) {
throw new Error("Parameter `estimateABTestRequest` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.configuration) {
throw new Error("Parameter `estimateABTestRequest.configuration` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.variants) {
throw new Error("Parameter `estimateABTestRequest.variants` is required when calling `estimateABTest`.");
}
const requestPath = "/3/abtests/estimate";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: estimateABTestRequest
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `getABTest`.");
}
const requestPath = "/3/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves timeseries for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getTimeseries - The getTimeseries object.
* @param getTimeseries.id - Unique A/B test identifier.
* @param getTimeseries.startDate - Start date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.endDate - End date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.metric - List of metrics to retrieve. If not specified, all metrics are returned.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getTimeseries({ id, startDate, endDate, metric }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `getTimeseries`.");
}
const requestPath = "/3/abtests/{id}/timeseries".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
if (startDate !== void 0) {
queryParameters["startDate"] = startDate.toString();
}
if (endDate !== void 0) {
queryParameters["endDate"] = endDate.toString();
}
if (metric !== void 0) {
queryParameters["metric"] = metric.toString();
}
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param listABTests.direction - Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix, direction } = {}, requestOptions = void 0) {
const requestPath = "/3/abtests";
const headers = {};
const queryParameters = {};
if (offset !== void 0) {
queryParameters["offset"] = offset.toString();
}
if (limit !== void 0) {
queryParameters["limit"] = limit.toString();
}
if (indexPrefix !== void 0) {
queryParameters["indexPrefix"] = indexPrefix.toString();
}
if (indexSuffix !== void 0) {
queryParameters["indexSuffix"] = indexSuffix.toString();
}
if (direction !== void 0) {
queryParameters["direction"] = direction.toString();
}
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `stopABTest`.");
}
const requestPath = "/3/abtests/{id}/stop".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
}
};
}
// builds/fetch.ts
function abtestingV3Client(appId, apiKey, region, options) {
if (!appId || typeof appId !== "string") {
throw new Error("`appId` is missing.");
}
if (!apiKey || typeof apiKey !== "string") {
throw new Error("`apiKey` is missing.");
}
if (region && (typeof region !== "string" || !REGIONS.includes(region))) {
throw new Error(`\`region\` must be one of the following: ${REGIONS.join(", ")}`);
}
return {
...createAbtestingV3Client({
appId,
apiKey,
region,
timeouts: {
connect: 2e3,
read: 5e3,
write: 3e4
},
logger: createNullLogger(),
requester: createFetchRequester(),
algoliaAgents: [{ segment: "Fetch" }],
responsesCache: createNullCache(),
requestsCache: createNullCache(),
hostsCache: createMemoryCache(),
...options
})
};
}
export {
abtestingV3Client,
apiClientVersion
};
//# sourceMappingURL=fetch.js.map
File diff suppressed because one or more lines are too long
+454
View File
@@ -0,0 +1,454 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// builds/node.ts
var node_exports = {};
__export(node_exports, {
abtestingV3Client: () => abtestingV3Client,
apiClientVersion: () => apiClientVersion
});
module.exports = __toCommonJS(node_exports);
var import_client_common2 = require("@algolia/client-common");
var import_requester_node_http = require("@algolia/requester-node-http");
// src/abtestingV3Client.ts
var import_client_common = require("@algolia/client-common");
var apiClientVersion = "1.14.1";
var REGIONS = ["de", "us"];
function getDefaultHosts(region) {
const url = !region ? "analytics.algolia.com" : "analytics.{region}.algolia.com".replace("{region}", region);
return [{ url, accept: "readWrite", protocol: "https" }];
}
function createAbtestingV3Client({
appId: appIdOption,
apiKey: apiKeyOption,
authMode,
algoliaAgents,
region: regionOption,
...options
}) {
const auth = (0, import_client_common.createAuth)(appIdOption, apiKeyOption, authMode);
const transporter = (0, import_client_common.createTransporter)({
hosts: getDefaultHosts(regionOption),
...options,
algoliaAgent: (0, import_client_common.getAlgoliaAgent)({
algoliaAgents,
client: "AbtestingV3",
version: apiClientVersion
}),
baseHeaders: {
"content-type": "text/plain",
...auth.headers(),
...options.baseHeaders
},
baseQueryParameters: {
...auth.queryParameters(),
...options.baseQueryParameters
}
});
return {
transporter,
/**
* The `appId` currently in use.
*/
appId: appIdOption,
/**
* The `apiKey` currently in use.
*/
apiKey: apiKeyOption,
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache() {
return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => void 0);
},
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
get _ua() {
return transporter.algoliaAgent.value;
},
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment, version) {
transporter.algoliaAgent.add({ segment, version });
},
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }) {
if (!authMode || authMode === "WithinHeaders") {
transporter.baseHeaders["x-algolia-api-key"] = apiKey;
} else {
transporter.baseQueryParameters["x-algolia-api-key"] = apiKey;
}
},
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest, requestOptions) {
if (!addABTestsRequest) {
throw new Error("Parameter `addABTestsRequest` is required when calling `addABTests`.");
}
if (!addABTestsRequest.name) {
throw new Error("Parameter `addABTestsRequest.name` is required when calling `addABTests`.");
}
if (!addABTestsRequest.variants) {
throw new Error("Parameter `addABTestsRequest.variants` is required when calling `addABTests`.");
}
if (!addABTestsRequest.metrics) {
throw new Error("Parameter `addABTestsRequest.metrics` is required when calling `addABTests`.");
}
if (!addABTestsRequest.endAt) {
throw new Error("Parameter `addABTestsRequest.endAt` is required when calling `addABTests`.");
}
const requestPath = "/3/abtests";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: addABTestsRequest
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customDelete`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customGet`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPost`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPut`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "PUT",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `deleteABTest`.");
}
const requestPath = "/3/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest, requestOptions) {
if (!estimateABTestRequest) {
throw new Error("Parameter `estimateABTestRequest` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.configuration) {
throw new Error("Parameter `estimateABTestRequest.configuration` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.variants) {
throw new Error("Parameter `estimateABTestRequest.variants` is required when calling `estimateABTest`.");
}
const requestPath = "/3/abtests/estimate";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: estimateABTestRequest
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `getABTest`.");
}
const requestPath = "/3/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves timeseries for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getTimeseries - The getTimeseries object.
* @param getTimeseries.id - Unique A/B test identifier.
* @param getTimeseries.startDate - Start date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.endDate - End date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.metric - List of metrics to retrieve. If not specified, all metrics are returned.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getTimeseries({ id, startDate, endDate, metric }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `getTimeseries`.");
}
const requestPath = "/3/abtests/{id}/timeseries".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
if (startDate !== void 0) {
queryParameters["startDate"] = startDate.toString();
}
if (endDate !== void 0) {
queryParameters["endDate"] = endDate.toString();
}
if (metric !== void 0) {
queryParameters["metric"] = metric.toString();
}
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param listABTests.direction - Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix, direction } = {}, requestOptions = void 0) {
const requestPath = "/3/abtests";
const headers = {};
const queryParameters = {};
if (offset !== void 0) {
queryParameters["offset"] = offset.toString();
}
if (limit !== void 0) {
queryParameters["limit"] = limit.toString();
}
if (indexPrefix !== void 0) {
queryParameters["indexPrefix"] = indexPrefix.toString();
}
if (indexSuffix !== void 0) {
queryParameters["indexSuffix"] = indexSuffix.toString();
}
if (direction !== void 0) {
queryParameters["direction"] = direction.toString();
}
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `stopABTest`.");
}
const requestPath = "/3/abtests/{id}/stop".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
}
};
}
// builds/node.ts
function abtestingV3Client(appId, apiKey, region, options) {
if (!appId || typeof appId !== "string") {
throw new Error("`appId` is missing.");
}
if (!apiKey || typeof apiKey !== "string") {
throw new Error("`apiKey` is missing.");
}
if (region && (typeof region !== "string" || !REGIONS.includes(region))) {
throw new Error(`\`region\` must be one of the following: ${REGIONS.join(", ")}`);
}
return {
...createAbtestingV3Client({
appId,
apiKey,
region,
timeouts: {
connect: 2e3,
read: 5e3,
write: 3e4
},
logger: (0, import_client_common2.createNullLogger)(),
requester: (0, import_requester_node_http.createHttpRequester)(),
algoliaAgents: [{ segment: "Node.js", version: process.versions.node }],
responsesCache: (0, import_client_common2.createNullCache)(),
requestsCache: (0, import_client_common2.createNullCache)(),
hostsCache: (0, import_client_common2.createMemoryCache)(),
...options
})
};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
abtestingV3Client,
apiClientVersion
});
//# sourceMappingURL=node.cjs.map
File diff suppressed because one or more lines are too long
+428
View File
@@ -0,0 +1,428 @@
// builds/node.ts
import { createMemoryCache, createNullCache, createNullLogger } from "@algolia/client-common";
import { createHttpRequester } from "@algolia/requester-node-http";
// src/abtestingV3Client.ts
import { createAuth, createTransporter, getAlgoliaAgent } from "@algolia/client-common";
var apiClientVersion = "1.14.1";
var REGIONS = ["de", "us"];
function getDefaultHosts(region) {
const url = !region ? "analytics.algolia.com" : "analytics.{region}.algolia.com".replace("{region}", region);
return [{ url, accept: "readWrite", protocol: "https" }];
}
function createAbtestingV3Client({
appId: appIdOption,
apiKey: apiKeyOption,
authMode,
algoliaAgents,
region: regionOption,
...options
}) {
const auth = createAuth(appIdOption, apiKeyOption, authMode);
const transporter = createTransporter({
hosts: getDefaultHosts(regionOption),
...options,
algoliaAgent: getAlgoliaAgent({
algoliaAgents,
client: "AbtestingV3",
version: apiClientVersion
}),
baseHeaders: {
"content-type": "text/plain",
...auth.headers(),
...options.baseHeaders
},
baseQueryParameters: {
...auth.queryParameters(),
...options.baseQueryParameters
}
});
return {
transporter,
/**
* The `appId` currently in use.
*/
appId: appIdOption,
/**
* The `apiKey` currently in use.
*/
apiKey: apiKeyOption,
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache() {
return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => void 0);
},
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
get _ua() {
return transporter.algoliaAgent.value;
},
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment, version) {
transporter.algoliaAgent.add({ segment, version });
},
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }) {
if (!authMode || authMode === "WithinHeaders") {
transporter.baseHeaders["x-algolia-api-key"] = apiKey;
} else {
transporter.baseQueryParameters["x-algolia-api-key"] = apiKey;
}
},
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest, requestOptions) {
if (!addABTestsRequest) {
throw new Error("Parameter `addABTestsRequest` is required when calling `addABTests`.");
}
if (!addABTestsRequest.name) {
throw new Error("Parameter `addABTestsRequest.name` is required when calling `addABTests`.");
}
if (!addABTestsRequest.variants) {
throw new Error("Parameter `addABTestsRequest.variants` is required when calling `addABTests`.");
}
if (!addABTestsRequest.metrics) {
throw new Error("Parameter `addABTestsRequest.metrics` is required when calling `addABTests`.");
}
if (!addABTestsRequest.endAt) {
throw new Error("Parameter `addABTestsRequest.endAt` is required when calling `addABTests`.");
}
const requestPath = "/3/abtests";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: addABTestsRequest
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customDelete`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customGet`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPost`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPut`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "PUT",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `deleteABTest`.");
}
const requestPath = "/3/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest, requestOptions) {
if (!estimateABTestRequest) {
throw new Error("Parameter `estimateABTestRequest` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.configuration) {
throw new Error("Parameter `estimateABTestRequest.configuration` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.variants) {
throw new Error("Parameter `estimateABTestRequest.variants` is required when calling `estimateABTest`.");
}
const requestPath = "/3/abtests/estimate";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: estimateABTestRequest
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `getABTest`.");
}
const requestPath = "/3/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves timeseries for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getTimeseries - The getTimeseries object.
* @param getTimeseries.id - Unique A/B test identifier.
* @param getTimeseries.startDate - Start date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.endDate - End date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.metric - List of metrics to retrieve. If not specified, all metrics are returned.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getTimeseries({ id, startDate, endDate, metric }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `getTimeseries`.");
}
const requestPath = "/3/abtests/{id}/timeseries".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
if (startDate !== void 0) {
queryParameters["startDate"] = startDate.toString();
}
if (endDate !== void 0) {
queryParameters["endDate"] = endDate.toString();
}
if (metric !== void 0) {
queryParameters["metric"] = metric.toString();
}
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param listABTests.direction - Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix, direction } = {}, requestOptions = void 0) {
const requestPath = "/3/abtests";
const headers = {};
const queryParameters = {};
if (offset !== void 0) {
queryParameters["offset"] = offset.toString();
}
if (limit !== void 0) {
queryParameters["limit"] = limit.toString();
}
if (indexPrefix !== void 0) {
queryParameters["indexPrefix"] = indexPrefix.toString();
}
if (indexSuffix !== void 0) {
queryParameters["indexSuffix"] = indexSuffix.toString();
}
if (direction !== void 0) {
queryParameters["direction"] = direction.toString();
}
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `stopABTest`.");
}
const requestPath = "/3/abtests/{id}/stop".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
}
};
}
// builds/node.ts
function abtestingV3Client(appId, apiKey, region, options) {
if (!appId || typeof appId !== "string") {
throw new Error("`appId` is missing.");
}
if (!apiKey || typeof apiKey !== "string") {
throw new Error("`apiKey` is missing.");
}
if (region && (typeof region !== "string" || !REGIONS.includes(region))) {
throw new Error(`\`region\` must be one of the following: ${REGIONS.join(", ")}`);
}
return {
...createAbtestingV3Client({
appId,
apiKey,
region,
timeouts: {
connect: 2e3,
read: 5e3,
write: 3e4
},
logger: createNullLogger(),
requester: createHttpRequester(),
algoliaAgents: [{ segment: "Node.js", version: process.versions.node }],
responsesCache: createNullCache(),
requestsCache: createNullCache(),
hostsCache: createMemoryCache(),
...options
})
};
}
export {
abtestingV3Client,
apiClientVersion
};
//# sourceMappingURL=node.js.map
File diff suppressed because one or more lines are too long
+428
View File
@@ -0,0 +1,428 @@
// builds/worker.ts
import { createMemoryCache, createNullCache, createNullLogger } from "@algolia/client-common";
import { createFetchRequester } from "@algolia/requester-fetch";
// src/abtestingV3Client.ts
import { createAuth, createTransporter, getAlgoliaAgent } from "@algolia/client-common";
var apiClientVersion = "1.14.1";
var REGIONS = ["de", "us"];
function getDefaultHosts(region) {
const url = !region ? "analytics.algolia.com" : "analytics.{region}.algolia.com".replace("{region}", region);
return [{ url, accept: "readWrite", protocol: "https" }];
}
function createAbtestingV3Client({
appId: appIdOption,
apiKey: apiKeyOption,
authMode,
algoliaAgents,
region: regionOption,
...options
}) {
const auth = createAuth(appIdOption, apiKeyOption, authMode);
const transporter = createTransporter({
hosts: getDefaultHosts(regionOption),
...options,
algoliaAgent: getAlgoliaAgent({
algoliaAgents,
client: "AbtestingV3",
version: apiClientVersion
}),
baseHeaders: {
"content-type": "text/plain",
...auth.headers(),
...options.baseHeaders
},
baseQueryParameters: {
...auth.queryParameters(),
...options.baseQueryParameters
}
});
return {
transporter,
/**
* The `appId` currently in use.
*/
appId: appIdOption,
/**
* The `apiKey` currently in use.
*/
apiKey: apiKeyOption,
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache() {
return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => void 0);
},
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
get _ua() {
return transporter.algoliaAgent.value;
},
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment, version) {
transporter.algoliaAgent.add({ segment, version });
},
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }) {
if (!authMode || authMode === "WithinHeaders") {
transporter.baseHeaders["x-algolia-api-key"] = apiKey;
} else {
transporter.baseQueryParameters["x-algolia-api-key"] = apiKey;
}
},
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest, requestOptions) {
if (!addABTestsRequest) {
throw new Error("Parameter `addABTestsRequest` is required when calling `addABTests`.");
}
if (!addABTestsRequest.name) {
throw new Error("Parameter `addABTestsRequest.name` is required when calling `addABTests`.");
}
if (!addABTestsRequest.variants) {
throw new Error("Parameter `addABTestsRequest.variants` is required when calling `addABTests`.");
}
if (!addABTestsRequest.metrics) {
throw new Error("Parameter `addABTestsRequest.metrics` is required when calling `addABTests`.");
}
if (!addABTestsRequest.endAt) {
throw new Error("Parameter `addABTestsRequest.endAt` is required when calling `addABTests`.");
}
const requestPath = "/3/abtests";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: addABTestsRequest
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customDelete`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customGet`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPost`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPut`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "PUT",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `deleteABTest`.");
}
const requestPath = "/3/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest, requestOptions) {
if (!estimateABTestRequest) {
throw new Error("Parameter `estimateABTestRequest` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.configuration) {
throw new Error("Parameter `estimateABTestRequest.configuration` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.variants) {
throw new Error("Parameter `estimateABTestRequest.variants` is required when calling `estimateABTest`.");
}
const requestPath = "/3/abtests/estimate";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: estimateABTestRequest
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `getABTest`.");
}
const requestPath = "/3/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves timeseries for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getTimeseries - The getTimeseries object.
* @param getTimeseries.id - Unique A/B test identifier.
* @param getTimeseries.startDate - Start date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.endDate - End date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.metric - List of metrics to retrieve. If not specified, all metrics are returned.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getTimeseries({ id, startDate, endDate, metric }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `getTimeseries`.");
}
const requestPath = "/3/abtests/{id}/timeseries".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
if (startDate !== void 0) {
queryParameters["startDate"] = startDate.toString();
}
if (endDate !== void 0) {
queryParameters["endDate"] = endDate.toString();
}
if (metric !== void 0) {
queryParameters["metric"] = metric.toString();
}
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param listABTests.direction - Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix, direction } = {}, requestOptions = void 0) {
const requestPath = "/3/abtests";
const headers = {};
const queryParameters = {};
if (offset !== void 0) {
queryParameters["offset"] = offset.toString();
}
if (limit !== void 0) {
queryParameters["limit"] = limit.toString();
}
if (indexPrefix !== void 0) {
queryParameters["indexPrefix"] = indexPrefix.toString();
}
if (indexSuffix !== void 0) {
queryParameters["indexSuffix"] = indexSuffix.toString();
}
if (direction !== void 0) {
queryParameters["direction"] = direction.toString();
}
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `stopABTest`.");
}
const requestPath = "/3/abtests/{id}/stop".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
}
};
}
// builds/worker.ts
function abtestingV3Client(appId, apiKey, region, options) {
if (!appId || typeof appId !== "string") {
throw new Error("`appId` is missing.");
}
if (!apiKey || typeof apiKey !== "string") {
throw new Error("`apiKey` is missing.");
}
if (region && (typeof region !== "string" || !REGIONS.includes(region))) {
throw new Error(`\`region\` must be one of the following: ${REGIONS.join(", ")}`);
}
return {
...createAbtestingV3Client({
appId,
apiKey,
region,
timeouts: {
connect: 2e3,
read: 5e3,
write: 3e4
},
logger: createNullLogger(),
requester: createFetchRequester(),
algoliaAgents: [{ segment: "Worker" }],
responsesCache: createNullCache(),
requestsCache: createNullCache(),
hostsCache: createMemoryCache(),
...options
})
};
}
export {
abtestingV3Client,
apiClientVersion
};
//# sourceMappingURL=worker.js.map
File diff suppressed because one or more lines are too long
+677
View File
@@ -0,0 +1,677 @@
import * as _algolia_client_common from '@algolia/client-common';
import { CreateClientOptions, RequestOptions, ClientOptions } from '@algolia/client-common';
/**
* Multiple-testing correction method applied when evaluating metric significance.
*/
type ErrorCorrectionType = 'bonferroni' | 'benjamini-hochberg';
/**
* Boolean filter applied to the A/B test population. Each filter targets a boolean metric and decides whether to include (true) or exclude (false) matching records.
*/
type MetricsFilter = {
/**
* Metric domain (for example `abtesting`, `personalization`).
*/
domain: string;
/**
* Public metric name.
*/
name: string;
/**
* Whether the experiment should record the effects of this filter.
*/
trackEffects?: boolean | undefined;
/**
* If true, keep items that match the filter; if false, exclude them.
*/
includes?: boolean | undefined;
};
/**
* Metric for which you want to detect the smallest relative difference.
*/
type EffectMetric = 'addToCartRate' | 'clickThroughRate' | 'conversionRate' | 'purchaseRate' | 'noResultsRate';
/**
* Configuration for the smallest difference between test variants you want to detect.
*/
type MinimumDetectableEffect = {
/**
* Smallest difference in an observable metric between variants. For example, to detect a 10% difference between variants, set this value to 0.1.
*/
size: number;
metric: EffectMetric;
};
/**
* A/B test configuration.
*/
type ABTestConfiguration = {
minimumDetectableEffect?: MinimumDetectableEffect | undefined;
/**
* List of metric filters applied to the test population.
*/
filters?: Array<MetricsFilter> | undefined;
errorCorrection?: ErrorCorrectionType | undefined;
};
/**
* A/B test status. - `active`. The A/B test is live and search traffic is split between the two variants. - `stopped`. You stopped the A/B test. The A/B test data is still available for analysis. - `expired`. The A/B test was automatically stopped after reaching its end date. - `failed`. Creating the A/B test failed.
*/
type Status = 'active' | 'stopped' | 'expired' | 'failed';
/**
* Metric specific metadata.
*/
type MetricMetadata = {
/**
* Only present in case the metric is \'revenue\'. It is the amount exceeding the 95th percentile of global revenue transactions involved in the AB Test. This amount is not considered when calculating statistical significance. It is tied to a per revenue-currency pair contrary to other global filter effects (such as outliers and empty search count).
*/
winsorizedValue?: number | undefined;
/**
* Mean value for this metric.
*/
mean?: number | undefined;
};
type MetricResult = {
name: string;
/**
* Date and time when the metric was last updated, in RFC 3339 format.
*/
updatedAt: string;
value: number;
/**
* The upper bound of the 95% confidence interval for the metric value. The confidence interval is calculated using either the relative ratio or relative difference between the metric values for the control and the variant. Relative ratio is used for metrics that are ratios (e.g., click-through rate, conversion rate), while relative difference is used for continuous metrics (e.g., revenue).
*/
valueCIHigh?: number | undefined;
/**
* The lower bound of the 95% confidence interval for the metric value. The confidence interval is calculated using either the relative ratio or relative difference between the metric values for the control and the variant. Relative ratio is used for metrics that are ratios (e.g., click-through rate, conversion rate), while relative difference is used for continuous metrics (e.g., revenue).
*/
valueCILow?: number | undefined;
/**
* PValue for the first variant (control) will always be 0. For the other variants, pValue is calculated for the current variant based on the control.
*/
pValue: number;
/**
* Dimension defined during test creation.
*/
dimension?: string | undefined;
metadata?: MetricMetadata | undefined;
/**
* The value that was computed during error correction. It is used to determine significance of the metric pValue. The critical value is calculated using Bonferroni or Benjamini-Hochberg corrections, based on the given configuration during the A/B test creation.
*/
criticalValue?: number | undefined;
/**
* Whether the pValue is significant or not based on the critical value and the error correction algorithm used.
*/
significant?: boolean | undefined;
};
/**
* Empty searches removed from the A/B test as a result of configuration settings.
*/
type EmptySearchFilter = {
/**
* Number of users removed from the A/B test.
*/
usersCount?: number | undefined;
/**
* Number of tracked searches removed from the A/B test.
*/
trackedSearchesCount?: number | undefined;
};
/**
* Outliers removed from the A/B test as a result of configuration settings.
*/
type OutliersFilter = {
/**
* Number of users removed from the A/B test.
*/
usersCount?: number | undefined;
/**
* Number of tracked searches removed from the A/B test.
*/
trackedSearchesCount?: number | undefined;
};
/**
* A/B test filter effects resulting from configuration settings.
*/
type FilterEffects = {
outliers?: OutliersFilter | undefined;
emptySearch?: EmptySearchFilter | undefined;
};
/**
* Variant specific metadata.
*/
type VariantMetadata = {
filterEffects?: FilterEffects | undefined;
};
type Variant = {
/**
* Description for this variant.
*/
description: string;
/**
* Estimated number of searches required to achieve the desired statistical significance. The A/B test configuration must include a `minimumDetectableEffect` setting for this number to be included in the response.
*/
estimatedSampleSize?: number | undefined;
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Percentage of search requests each variant receives.
*/
trafficPercentage: number;
/**
* All ABTest metrics that were defined during test creation.
*/
metrics: Array<MetricResult>;
metadata?: VariantMetadata | undefined;
/**
* Search parameters applied to this variant when the same index is used for multiple variants. Only present if custom search parameters were provided during test creation.
*/
customSearchParameters?: Record<string, unknown> | undefined;
};
type ABTest = {
/**
* Unique A/B test identifier.
*/
abTestID: number;
/**
* Date and time when the A/B test was last updated, in RFC 3339 format.
*/
updatedAt: string;
/**
* Date and time when the A/B test was created, in RFC 3339 format.
*/
createdAt: string;
/**
* End date and time of the A/B test, in RFC 3339 format.
*/
endAt: string;
/**
* Date and time when the A/B test was stopped, in RFC 3339 format.
*/
stoppedAt?: string | null | undefined;
/**
* A/B test name.
*/
name: string;
status: Status;
/**
* A/B test variants. The first variant is your _control_ index, typically your production index. All of the additional variants are indexes with changed settings that you want to test against the control.
*/
variants: Array<Variant>;
configuration?: ABTestConfiguration | undefined;
/**
* Unique migrated A/B test identifier.
*/
migratedAbTestID?: number | undefined;
};
type ABTestResponse = {
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Unique A/B test identifier.
*/
abTestID: number;
/**
* Unique identifier of a task. A successful API response means that a task was added to a queue. It might not run immediately. You can check the task\'s progress with the [`task` operation](https://www.algolia.com/doc/rest-api/search/get-task) and this task ID.
*/
taskID: number;
};
type AbTestsVariant = {
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Percentage of search requests each variant receives.
*/
trafficPercentage: number;
/**
* Description for this variant.
*/
description?: string | undefined;
};
/**
* Search parameters to add to the test variant. Only use this parameter if the two variants use the same index.
*/
type CustomSearchParams = {
customSearchParameters: Record<string, unknown>;
};
type AbTestsVariantSearchParams = AbTestsVariant & CustomSearchParams;
type AddABTestsVariant = AbTestsVariant | AbTestsVariantSearchParams;
/**
* Defines a metric to be retrieved during an A/B test.
*/
type CreateMetric = {
/**
* Name of the metric.
*/
name: string;
/**
* Dimension of the metric, for example, in case of a revenue metric it could be USD, EUR...
*/
dimension?: string | undefined;
};
type AddABTestsRequest = {
/**
* A/B test name.
*/
name: string;
/**
* A/B test variants.
*/
variants: Array<AddABTestsVariant>;
/**
* A/B test metrics involved in the test. Only these metrics will be considered when calculating results.
*/
metrics: Array<CreateMetric>;
configuration?: ABTestConfiguration | undefined;
/**
* End date and time of the A/B test, in RFC 3339 format.
*/
endAt: string;
};
/**
* A/B test configuration for estimating the sample size and duration using minimum detectable effect.
*/
type EstimateConfiguration = {
/**
* List of metric filters applied to the test population.
*/
filters?: Array<MetricsFilter> | undefined;
minimumDetectableEffect: MinimumDetectableEffect;
};
type EstimateABTestRequest = {
configuration: EstimateConfiguration;
/**
* A/B test variants.
*/
variants: Array<AddABTestsVariant>;
};
type EstimateABTestResponse = {
/**
* Estimated number of days needed to reach the sample sizes required for detecting the configured effect. This value is based on historical traffic.
*/
durationDays?: number | undefined;
/**
* Sample size estimates for each variant. The first element is the control variant. Each element is the estimated number of searches required to achieve the desired statistical significance.
*/
sampleSizes?: Array<number> | undefined;
};
type ListABTestsResponse = {
/**
* A/B tests.
*/
abtests: Array<ABTest> | null;
/**
* Number of A/B tests.
*/
count: number;
/**
* Number of retrievable A/B tests.
*/
total: number;
};
type MetricDate = {
/**
* Date where the metric was updated, in RFC 3339 format.
*/
date?: string | undefined;
/**
* All ABTest metrics that were defined during test creation.
*/
metrics?: Array<MetricResult> | undefined;
};
type TimeseriesVariant = {
dates?: Array<MetricDate> | undefined;
};
type Timeseries = {
/**
* Unique A/B test identifier.
*/
abTestID: number;
/**
* A/B test timeseries variants. The first variant is your _control_ index, typically your production index. All of the additional variants are indexes with changed settings that you want to test against the control.
*/
variants: Array<TimeseriesVariant>;
};
/**
* Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
*/
type Direction = 'asc' | 'desc';
type MetricName = 'search_count' | 'tracked_search_count' | 'user_count' | 'tracked_user_count' | 'no_result_count' | 'add_to_cart_count' | 'purchase_count' | 'clicked_search_count' | 'converted_search_count' | 'click_through_rate' | 'conversion_rate' | 'add_to_cart_rate' | 'purchase_rate' | 'average_click_position' | 'revenue';
/**
* Properties for the `customDelete` method.
*/
type CustomDeleteProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customGet` method.
*/
type CustomGetProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customPost` method.
*/
type CustomPostProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `customPut` method.
*/
type CustomPutProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `deleteABTest` method.
*/
type DeleteABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
/**
* Properties for the `getABTest` method.
*/
type GetABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
/**
* Properties for the `getTimeseries` method.
*/
type GetTimeseriesProps = {
/**
* Unique A/B test identifier.
*/
id: number;
/**
* Start date of the period to analyze, in `YYYY-MM-DD` format.
*/
startDate?: string | undefined;
/**
* End date of the period to analyze, in `YYYY-MM-DD` format.
*/
endDate?: string | undefined;
/**
* List of metrics to retrieve. If not specified, all metrics are returned.
*/
metric?: Array<MetricName> | undefined;
};
/**
* Properties for the `listABTests` method.
*/
type ListABTestsProps = {
/**
* Position of the first item to return.
*/
offset?: number | undefined;
/**
* Number of items to return.
*/
limit?: number | undefined;
/**
* Index name prefix. Only A/B tests for indices starting with this string are included in the response.
*/
indexPrefix?: string | undefined;
/**
* Index name suffix. Only A/B tests for indices ending with this string are included in the response.
*/
indexSuffix?: string | undefined;
/**
* Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
*/
direction?: Direction | undefined;
};
/**
* Properties for the `stopABTest` method.
*/
type StopABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
declare const apiClientVersion = "1.14.1";
declare const REGIONS: readonly ["de", "us"];
type Region = (typeof REGIONS)[number];
type RegionOptions = {
region?: Region | undefined;
};
declare function createAbtestingV3Client({ appId: appIdOption, apiKey: apiKeyOption, authMode, algoliaAgents, region: regionOption, ...options }: CreateClientOptions & RegionOptions): {
transporter: _algolia_client_common.Transporter;
/**
* The `appId` currently in use.
*/
appId: string;
/**
* The `apiKey` currently in use.
*/
apiKey: string;
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache(): Promise<void>;
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
readonly _ua: string;
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment: string, version?: string | undefined): void;
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }: {
apiKey: string;
}): void;
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest: AddABTestsRequest, requestOptions?: RequestOptions): Promise<ABTestResponse>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }: CustomDeleteProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }: CustomGetProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }: CustomPostProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }: CustomPutProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }: DeleteABTestProps, requestOptions?: RequestOptions): Promise<ABTestResponse>;
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest: EstimateABTestRequest, requestOptions?: RequestOptions): Promise<EstimateABTestResponse>;
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }: GetABTestProps, requestOptions?: RequestOptions): Promise<ABTest>;
/**
* Retrieves timeseries for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getTimeseries - The getTimeseries object.
* @param getTimeseries.id - Unique A/B test identifier.
* @param getTimeseries.startDate - Start date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.endDate - End date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.metric - List of metrics to retrieve. If not specified, all metrics are returned.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getTimeseries({ id, startDate, endDate, metric }: GetTimeseriesProps, requestOptions?: RequestOptions): Promise<Timeseries>;
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param listABTests.direction - Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix, direction }?: ListABTestsProps, requestOptions?: RequestOptions | undefined): Promise<ListABTestsResponse>;
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }: StopABTestProps, requestOptions?: RequestOptions): Promise<ABTestResponse>;
};
/**
* Error.
*/
type ErrorBase = Record<string, any> & {
message?: string | undefined;
};
type AbtestingV3Client = ReturnType<typeof createAbtestingV3Client>;
declare function abtestingV3Client(appId: string, apiKey: string, region?: Region | undefined, options?: ClientOptions | undefined): AbtestingV3Client;
export { type ABTest, type ABTestConfiguration, type ABTestResponse, type AbTestsVariant, type AbTestsVariantSearchParams, type AbtestingV3Client, type AddABTestsRequest, type AddABTestsVariant, type CreateMetric, type CustomDeleteProps, type CustomGetProps, type CustomPostProps, type CustomPutProps, type CustomSearchParams, type DeleteABTestProps, type Direction, type EffectMetric, type EmptySearchFilter, type ErrorBase, type ErrorCorrectionType, type EstimateABTestRequest, type EstimateABTestResponse, type EstimateConfiguration, type FilterEffects, type GetABTestProps, type GetTimeseriesProps, type ListABTestsProps, type ListABTestsResponse, type MetricDate, type MetricMetadata, type MetricName, type MetricResult, type MetricsFilter, type MinimumDetectableEffect, type OutliersFilter, type Region, type RegionOptions, type Status, type StopABTestProps, type Timeseries, type TimeseriesVariant, type Variant, type VariantMetadata, abtestingV3Client, apiClientVersion };
+677
View File
@@ -0,0 +1,677 @@
import * as _algolia_client_common from '@algolia/client-common';
import { CreateClientOptions, RequestOptions, ClientOptions } from '@algolia/client-common';
/**
* Multiple-testing correction method applied when evaluating metric significance.
*/
type ErrorCorrectionType = 'bonferroni' | 'benjamini-hochberg';
/**
* Boolean filter applied to the A/B test population. Each filter targets a boolean metric and decides whether to include (true) or exclude (false) matching records.
*/
type MetricsFilter = {
/**
* Metric domain (for example `abtesting`, `personalization`).
*/
domain: string;
/**
* Public metric name.
*/
name: string;
/**
* Whether the experiment should record the effects of this filter.
*/
trackEffects?: boolean | undefined;
/**
* If true, keep items that match the filter; if false, exclude them.
*/
includes?: boolean | undefined;
};
/**
* Metric for which you want to detect the smallest relative difference.
*/
type EffectMetric = 'addToCartRate' | 'clickThroughRate' | 'conversionRate' | 'purchaseRate' | 'noResultsRate';
/**
* Configuration for the smallest difference between test variants you want to detect.
*/
type MinimumDetectableEffect = {
/**
* Smallest difference in an observable metric between variants. For example, to detect a 10% difference between variants, set this value to 0.1.
*/
size: number;
metric: EffectMetric;
};
/**
* A/B test configuration.
*/
type ABTestConfiguration = {
minimumDetectableEffect?: MinimumDetectableEffect | undefined;
/**
* List of metric filters applied to the test population.
*/
filters?: Array<MetricsFilter> | undefined;
errorCorrection?: ErrorCorrectionType | undefined;
};
/**
* A/B test status. - `active`. The A/B test is live and search traffic is split between the two variants. - `stopped`. You stopped the A/B test. The A/B test data is still available for analysis. - `expired`. The A/B test was automatically stopped after reaching its end date. - `failed`. Creating the A/B test failed.
*/
type Status = 'active' | 'stopped' | 'expired' | 'failed';
/**
* Metric specific metadata.
*/
type MetricMetadata = {
/**
* Only present in case the metric is \'revenue\'. It is the amount exceeding the 95th percentile of global revenue transactions involved in the AB Test. This amount is not considered when calculating statistical significance. It is tied to a per revenue-currency pair contrary to other global filter effects (such as outliers and empty search count).
*/
winsorizedValue?: number | undefined;
/**
* Mean value for this metric.
*/
mean?: number | undefined;
};
type MetricResult = {
name: string;
/**
* Date and time when the metric was last updated, in RFC 3339 format.
*/
updatedAt: string;
value: number;
/**
* The upper bound of the 95% confidence interval for the metric value. The confidence interval is calculated using either the relative ratio or relative difference between the metric values for the control and the variant. Relative ratio is used for metrics that are ratios (e.g., click-through rate, conversion rate), while relative difference is used for continuous metrics (e.g., revenue).
*/
valueCIHigh?: number | undefined;
/**
* The lower bound of the 95% confidence interval for the metric value. The confidence interval is calculated using either the relative ratio or relative difference between the metric values for the control and the variant. Relative ratio is used for metrics that are ratios (e.g., click-through rate, conversion rate), while relative difference is used for continuous metrics (e.g., revenue).
*/
valueCILow?: number | undefined;
/**
* PValue for the first variant (control) will always be 0. For the other variants, pValue is calculated for the current variant based on the control.
*/
pValue: number;
/**
* Dimension defined during test creation.
*/
dimension?: string | undefined;
metadata?: MetricMetadata | undefined;
/**
* The value that was computed during error correction. It is used to determine significance of the metric pValue. The critical value is calculated using Bonferroni or Benjamini-Hochberg corrections, based on the given configuration during the A/B test creation.
*/
criticalValue?: number | undefined;
/**
* Whether the pValue is significant or not based on the critical value and the error correction algorithm used.
*/
significant?: boolean | undefined;
};
/**
* Empty searches removed from the A/B test as a result of configuration settings.
*/
type EmptySearchFilter = {
/**
* Number of users removed from the A/B test.
*/
usersCount?: number | undefined;
/**
* Number of tracked searches removed from the A/B test.
*/
trackedSearchesCount?: number | undefined;
};
/**
* Outliers removed from the A/B test as a result of configuration settings.
*/
type OutliersFilter = {
/**
* Number of users removed from the A/B test.
*/
usersCount?: number | undefined;
/**
* Number of tracked searches removed from the A/B test.
*/
trackedSearchesCount?: number | undefined;
};
/**
* A/B test filter effects resulting from configuration settings.
*/
type FilterEffects = {
outliers?: OutliersFilter | undefined;
emptySearch?: EmptySearchFilter | undefined;
};
/**
* Variant specific metadata.
*/
type VariantMetadata = {
filterEffects?: FilterEffects | undefined;
};
type Variant = {
/**
* Description for this variant.
*/
description: string;
/**
* Estimated number of searches required to achieve the desired statistical significance. The A/B test configuration must include a `minimumDetectableEffect` setting for this number to be included in the response.
*/
estimatedSampleSize?: number | undefined;
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Percentage of search requests each variant receives.
*/
trafficPercentage: number;
/**
* All ABTest metrics that were defined during test creation.
*/
metrics: Array<MetricResult>;
metadata?: VariantMetadata | undefined;
/**
* Search parameters applied to this variant when the same index is used for multiple variants. Only present if custom search parameters were provided during test creation.
*/
customSearchParameters?: Record<string, unknown> | undefined;
};
type ABTest = {
/**
* Unique A/B test identifier.
*/
abTestID: number;
/**
* Date and time when the A/B test was last updated, in RFC 3339 format.
*/
updatedAt: string;
/**
* Date and time when the A/B test was created, in RFC 3339 format.
*/
createdAt: string;
/**
* End date and time of the A/B test, in RFC 3339 format.
*/
endAt: string;
/**
* Date and time when the A/B test was stopped, in RFC 3339 format.
*/
stoppedAt?: string | null | undefined;
/**
* A/B test name.
*/
name: string;
status: Status;
/**
* A/B test variants. The first variant is your _control_ index, typically your production index. All of the additional variants are indexes with changed settings that you want to test against the control.
*/
variants: Array<Variant>;
configuration?: ABTestConfiguration | undefined;
/**
* Unique migrated A/B test identifier.
*/
migratedAbTestID?: number | undefined;
};
type ABTestResponse = {
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Unique A/B test identifier.
*/
abTestID: number;
/**
* Unique identifier of a task. A successful API response means that a task was added to a queue. It might not run immediately. You can check the task\'s progress with the [`task` operation](https://www.algolia.com/doc/rest-api/search/get-task) and this task ID.
*/
taskID: number;
};
type AbTestsVariant = {
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Percentage of search requests each variant receives.
*/
trafficPercentage: number;
/**
* Description for this variant.
*/
description?: string | undefined;
};
/**
* Search parameters to add to the test variant. Only use this parameter if the two variants use the same index.
*/
type CustomSearchParams = {
customSearchParameters: Record<string, unknown>;
};
type AbTestsVariantSearchParams = AbTestsVariant & CustomSearchParams;
type AddABTestsVariant = AbTestsVariant | AbTestsVariantSearchParams;
/**
* Defines a metric to be retrieved during an A/B test.
*/
type CreateMetric = {
/**
* Name of the metric.
*/
name: string;
/**
* Dimension of the metric, for example, in case of a revenue metric it could be USD, EUR...
*/
dimension?: string | undefined;
};
type AddABTestsRequest = {
/**
* A/B test name.
*/
name: string;
/**
* A/B test variants.
*/
variants: Array<AddABTestsVariant>;
/**
* A/B test metrics involved in the test. Only these metrics will be considered when calculating results.
*/
metrics: Array<CreateMetric>;
configuration?: ABTestConfiguration | undefined;
/**
* End date and time of the A/B test, in RFC 3339 format.
*/
endAt: string;
};
/**
* A/B test configuration for estimating the sample size and duration using minimum detectable effect.
*/
type EstimateConfiguration = {
/**
* List of metric filters applied to the test population.
*/
filters?: Array<MetricsFilter> | undefined;
minimumDetectableEffect: MinimumDetectableEffect;
};
type EstimateABTestRequest = {
configuration: EstimateConfiguration;
/**
* A/B test variants.
*/
variants: Array<AddABTestsVariant>;
};
type EstimateABTestResponse = {
/**
* Estimated number of days needed to reach the sample sizes required for detecting the configured effect. This value is based on historical traffic.
*/
durationDays?: number | undefined;
/**
* Sample size estimates for each variant. The first element is the control variant. Each element is the estimated number of searches required to achieve the desired statistical significance.
*/
sampleSizes?: Array<number> | undefined;
};
type ListABTestsResponse = {
/**
* A/B tests.
*/
abtests: Array<ABTest> | null;
/**
* Number of A/B tests.
*/
count: number;
/**
* Number of retrievable A/B tests.
*/
total: number;
};
type MetricDate = {
/**
* Date where the metric was updated, in RFC 3339 format.
*/
date?: string | undefined;
/**
* All ABTest metrics that were defined during test creation.
*/
metrics?: Array<MetricResult> | undefined;
};
type TimeseriesVariant = {
dates?: Array<MetricDate> | undefined;
};
type Timeseries = {
/**
* Unique A/B test identifier.
*/
abTestID: number;
/**
* A/B test timeseries variants. The first variant is your _control_ index, typically your production index. All of the additional variants are indexes with changed settings that you want to test against the control.
*/
variants: Array<TimeseriesVariant>;
};
/**
* Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
*/
type Direction = 'asc' | 'desc';
type MetricName = 'search_count' | 'tracked_search_count' | 'user_count' | 'tracked_user_count' | 'no_result_count' | 'add_to_cart_count' | 'purchase_count' | 'clicked_search_count' | 'converted_search_count' | 'click_through_rate' | 'conversion_rate' | 'add_to_cart_rate' | 'purchase_rate' | 'average_click_position' | 'revenue';
/**
* Properties for the `customDelete` method.
*/
type CustomDeleteProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customGet` method.
*/
type CustomGetProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customPost` method.
*/
type CustomPostProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `customPut` method.
*/
type CustomPutProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `deleteABTest` method.
*/
type DeleteABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
/**
* Properties for the `getABTest` method.
*/
type GetABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
/**
* Properties for the `getTimeseries` method.
*/
type GetTimeseriesProps = {
/**
* Unique A/B test identifier.
*/
id: number;
/**
* Start date of the period to analyze, in `YYYY-MM-DD` format.
*/
startDate?: string | undefined;
/**
* End date of the period to analyze, in `YYYY-MM-DD` format.
*/
endDate?: string | undefined;
/**
* List of metrics to retrieve. If not specified, all metrics are returned.
*/
metric?: Array<MetricName> | undefined;
};
/**
* Properties for the `listABTests` method.
*/
type ListABTestsProps = {
/**
* Position of the first item to return.
*/
offset?: number | undefined;
/**
* Number of items to return.
*/
limit?: number | undefined;
/**
* Index name prefix. Only A/B tests for indices starting with this string are included in the response.
*/
indexPrefix?: string | undefined;
/**
* Index name suffix. Only A/B tests for indices ending with this string are included in the response.
*/
indexSuffix?: string | undefined;
/**
* Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
*/
direction?: Direction | undefined;
};
/**
* Properties for the `stopABTest` method.
*/
type StopABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
declare const apiClientVersion = "1.14.1";
declare const REGIONS: readonly ["de", "us"];
type Region = (typeof REGIONS)[number];
type RegionOptions = {
region?: Region | undefined;
};
declare function createAbtestingV3Client({ appId: appIdOption, apiKey: apiKeyOption, authMode, algoliaAgents, region: regionOption, ...options }: CreateClientOptions & RegionOptions): {
transporter: _algolia_client_common.Transporter;
/**
* The `appId` currently in use.
*/
appId: string;
/**
* The `apiKey` currently in use.
*/
apiKey: string;
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache(): Promise<void>;
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
readonly _ua: string;
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment: string, version?: string | undefined): void;
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }: {
apiKey: string;
}): void;
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest: AddABTestsRequest, requestOptions?: RequestOptions): Promise<ABTestResponse>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }: CustomDeleteProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }: CustomGetProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }: CustomPostProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }: CustomPutProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }: DeleteABTestProps, requestOptions?: RequestOptions): Promise<ABTestResponse>;
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest: EstimateABTestRequest, requestOptions?: RequestOptions): Promise<EstimateABTestResponse>;
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }: GetABTestProps, requestOptions?: RequestOptions): Promise<ABTest>;
/**
* Retrieves timeseries for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getTimeseries - The getTimeseries object.
* @param getTimeseries.id - Unique A/B test identifier.
* @param getTimeseries.startDate - Start date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.endDate - End date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.metric - List of metrics to retrieve. If not specified, all metrics are returned.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getTimeseries({ id, startDate, endDate, metric }: GetTimeseriesProps, requestOptions?: RequestOptions): Promise<Timeseries>;
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param listABTests.direction - Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix, direction }?: ListABTestsProps, requestOptions?: RequestOptions | undefined): Promise<ListABTestsResponse>;
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }: StopABTestProps, requestOptions?: RequestOptions): Promise<ABTestResponse>;
};
/**
* Error.
*/
type ErrorBase = Record<string, any> & {
message?: string | undefined;
};
type AbtestingV3Client = ReturnType<typeof createAbtestingV3Client>;
declare function abtestingV3Client(appId: string, apiKey: string, region?: Region | undefined, options?: ClientOptions | undefined): AbtestingV3Client;
export { type ABTest, type ABTestConfiguration, type ABTestResponse, type AbTestsVariant, type AbTestsVariantSearchParams, type AbtestingV3Client, type AddABTestsRequest, type AddABTestsVariant, type CreateMetric, type CustomDeleteProps, type CustomGetProps, type CustomPostProps, type CustomPutProps, type CustomSearchParams, type DeleteABTestProps, type Direction, type EffectMetric, type EmptySearchFilter, type ErrorBase, type ErrorCorrectionType, type EstimateABTestRequest, type EstimateABTestResponse, type EstimateConfiguration, type FilterEffects, type GetABTestProps, type GetTimeseriesProps, type ListABTestsProps, type ListABTestsResponse, type MetricDate, type MetricMetadata, type MetricName, type MetricResult, type MetricsFilter, type MinimumDetectableEffect, type OutliersFilter, type Region, type RegionOptions, type Status, type StopABTestProps, type Timeseries, type TimeseriesVariant, type Variant, type VariantMetadata, abtestingV3Client, apiClientVersion };
+677
View File
@@ -0,0 +1,677 @@
import * as _algolia_client_common from '@algolia/client-common';
import { CreateClientOptions, RequestOptions, ClientOptions } from '@algolia/client-common';
/**
* Multiple-testing correction method applied when evaluating metric significance.
*/
type ErrorCorrectionType = 'bonferroni' | 'benjamini-hochberg';
/**
* Boolean filter applied to the A/B test population. Each filter targets a boolean metric and decides whether to include (true) or exclude (false) matching records.
*/
type MetricsFilter = {
/**
* Metric domain (for example `abtesting`, `personalization`).
*/
domain: string;
/**
* Public metric name.
*/
name: string;
/**
* Whether the experiment should record the effects of this filter.
*/
trackEffects?: boolean | undefined;
/**
* If true, keep items that match the filter; if false, exclude them.
*/
includes?: boolean | undefined;
};
/**
* Metric for which you want to detect the smallest relative difference.
*/
type EffectMetric = 'addToCartRate' | 'clickThroughRate' | 'conversionRate' | 'purchaseRate' | 'noResultsRate';
/**
* Configuration for the smallest difference between test variants you want to detect.
*/
type MinimumDetectableEffect = {
/**
* Smallest difference in an observable metric between variants. For example, to detect a 10% difference between variants, set this value to 0.1.
*/
size: number;
metric: EffectMetric;
};
/**
* A/B test configuration.
*/
type ABTestConfiguration = {
minimumDetectableEffect?: MinimumDetectableEffect | undefined;
/**
* List of metric filters applied to the test population.
*/
filters?: Array<MetricsFilter> | undefined;
errorCorrection?: ErrorCorrectionType | undefined;
};
/**
* A/B test status. - `active`. The A/B test is live and search traffic is split between the two variants. - `stopped`. You stopped the A/B test. The A/B test data is still available for analysis. - `expired`. The A/B test was automatically stopped after reaching its end date. - `failed`. Creating the A/B test failed.
*/
type Status = 'active' | 'stopped' | 'expired' | 'failed';
/**
* Metric specific metadata.
*/
type MetricMetadata = {
/**
* Only present in case the metric is \'revenue\'. It is the amount exceeding the 95th percentile of global revenue transactions involved in the AB Test. This amount is not considered when calculating statistical significance. It is tied to a per revenue-currency pair contrary to other global filter effects (such as outliers and empty search count).
*/
winsorizedValue?: number | undefined;
/**
* Mean value for this metric.
*/
mean?: number | undefined;
};
type MetricResult = {
name: string;
/**
* Date and time when the metric was last updated, in RFC 3339 format.
*/
updatedAt: string;
value: number;
/**
* The upper bound of the 95% confidence interval for the metric value. The confidence interval is calculated using either the relative ratio or relative difference between the metric values for the control and the variant. Relative ratio is used for metrics that are ratios (e.g., click-through rate, conversion rate), while relative difference is used for continuous metrics (e.g., revenue).
*/
valueCIHigh?: number | undefined;
/**
* The lower bound of the 95% confidence interval for the metric value. The confidence interval is calculated using either the relative ratio or relative difference between the metric values for the control and the variant. Relative ratio is used for metrics that are ratios (e.g., click-through rate, conversion rate), while relative difference is used for continuous metrics (e.g., revenue).
*/
valueCILow?: number | undefined;
/**
* PValue for the first variant (control) will always be 0. For the other variants, pValue is calculated for the current variant based on the control.
*/
pValue: number;
/**
* Dimension defined during test creation.
*/
dimension?: string | undefined;
metadata?: MetricMetadata | undefined;
/**
* The value that was computed during error correction. It is used to determine significance of the metric pValue. The critical value is calculated using Bonferroni or Benjamini-Hochberg corrections, based on the given configuration during the A/B test creation.
*/
criticalValue?: number | undefined;
/**
* Whether the pValue is significant or not based on the critical value and the error correction algorithm used.
*/
significant?: boolean | undefined;
};
/**
* Empty searches removed from the A/B test as a result of configuration settings.
*/
type EmptySearchFilter = {
/**
* Number of users removed from the A/B test.
*/
usersCount?: number | undefined;
/**
* Number of tracked searches removed from the A/B test.
*/
trackedSearchesCount?: number | undefined;
};
/**
* Outliers removed from the A/B test as a result of configuration settings.
*/
type OutliersFilter = {
/**
* Number of users removed from the A/B test.
*/
usersCount?: number | undefined;
/**
* Number of tracked searches removed from the A/B test.
*/
trackedSearchesCount?: number | undefined;
};
/**
* A/B test filter effects resulting from configuration settings.
*/
type FilterEffects = {
outliers?: OutliersFilter | undefined;
emptySearch?: EmptySearchFilter | undefined;
};
/**
* Variant specific metadata.
*/
type VariantMetadata = {
filterEffects?: FilterEffects | undefined;
};
type Variant = {
/**
* Description for this variant.
*/
description: string;
/**
* Estimated number of searches required to achieve the desired statistical significance. The A/B test configuration must include a `minimumDetectableEffect` setting for this number to be included in the response.
*/
estimatedSampleSize?: number | undefined;
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Percentage of search requests each variant receives.
*/
trafficPercentage: number;
/**
* All ABTest metrics that were defined during test creation.
*/
metrics: Array<MetricResult>;
metadata?: VariantMetadata | undefined;
/**
* Search parameters applied to this variant when the same index is used for multiple variants. Only present if custom search parameters were provided during test creation.
*/
customSearchParameters?: Record<string, unknown> | undefined;
};
type ABTest = {
/**
* Unique A/B test identifier.
*/
abTestID: number;
/**
* Date and time when the A/B test was last updated, in RFC 3339 format.
*/
updatedAt: string;
/**
* Date and time when the A/B test was created, in RFC 3339 format.
*/
createdAt: string;
/**
* End date and time of the A/B test, in RFC 3339 format.
*/
endAt: string;
/**
* Date and time when the A/B test was stopped, in RFC 3339 format.
*/
stoppedAt?: string | null | undefined;
/**
* A/B test name.
*/
name: string;
status: Status;
/**
* A/B test variants. The first variant is your _control_ index, typically your production index. All of the additional variants are indexes with changed settings that you want to test against the control.
*/
variants: Array<Variant>;
configuration?: ABTestConfiguration | undefined;
/**
* Unique migrated A/B test identifier.
*/
migratedAbTestID?: number | undefined;
};
type ABTestResponse = {
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Unique A/B test identifier.
*/
abTestID: number;
/**
* Unique identifier of a task. A successful API response means that a task was added to a queue. It might not run immediately. You can check the task\'s progress with the [`task` operation](https://www.algolia.com/doc/rest-api/search/get-task) and this task ID.
*/
taskID: number;
};
type AbTestsVariant = {
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Percentage of search requests each variant receives.
*/
trafficPercentage: number;
/**
* Description for this variant.
*/
description?: string | undefined;
};
/**
* Search parameters to add to the test variant. Only use this parameter if the two variants use the same index.
*/
type CustomSearchParams = {
customSearchParameters: Record<string, unknown>;
};
type AbTestsVariantSearchParams = AbTestsVariant & CustomSearchParams;
type AddABTestsVariant = AbTestsVariant | AbTestsVariantSearchParams;
/**
* Defines a metric to be retrieved during an A/B test.
*/
type CreateMetric = {
/**
* Name of the metric.
*/
name: string;
/**
* Dimension of the metric, for example, in case of a revenue metric it could be USD, EUR...
*/
dimension?: string | undefined;
};
type AddABTestsRequest = {
/**
* A/B test name.
*/
name: string;
/**
* A/B test variants.
*/
variants: Array<AddABTestsVariant>;
/**
* A/B test metrics involved in the test. Only these metrics will be considered when calculating results.
*/
metrics: Array<CreateMetric>;
configuration?: ABTestConfiguration | undefined;
/**
* End date and time of the A/B test, in RFC 3339 format.
*/
endAt: string;
};
/**
* A/B test configuration for estimating the sample size and duration using minimum detectable effect.
*/
type EstimateConfiguration = {
/**
* List of metric filters applied to the test population.
*/
filters?: Array<MetricsFilter> | undefined;
minimumDetectableEffect: MinimumDetectableEffect;
};
type EstimateABTestRequest = {
configuration: EstimateConfiguration;
/**
* A/B test variants.
*/
variants: Array<AddABTestsVariant>;
};
type EstimateABTestResponse = {
/**
* Estimated number of days needed to reach the sample sizes required for detecting the configured effect. This value is based on historical traffic.
*/
durationDays?: number | undefined;
/**
* Sample size estimates for each variant. The first element is the control variant. Each element is the estimated number of searches required to achieve the desired statistical significance.
*/
sampleSizes?: Array<number> | undefined;
};
type ListABTestsResponse = {
/**
* A/B tests.
*/
abtests: Array<ABTest> | null;
/**
* Number of A/B tests.
*/
count: number;
/**
* Number of retrievable A/B tests.
*/
total: number;
};
type MetricDate = {
/**
* Date where the metric was updated, in RFC 3339 format.
*/
date?: string | undefined;
/**
* All ABTest metrics that were defined during test creation.
*/
metrics?: Array<MetricResult> | undefined;
};
type TimeseriesVariant = {
dates?: Array<MetricDate> | undefined;
};
type Timeseries = {
/**
* Unique A/B test identifier.
*/
abTestID: number;
/**
* A/B test timeseries variants. The first variant is your _control_ index, typically your production index. All of the additional variants are indexes with changed settings that you want to test against the control.
*/
variants: Array<TimeseriesVariant>;
};
/**
* Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
*/
type Direction = 'asc' | 'desc';
type MetricName = 'search_count' | 'tracked_search_count' | 'user_count' | 'tracked_user_count' | 'no_result_count' | 'add_to_cart_count' | 'purchase_count' | 'clicked_search_count' | 'converted_search_count' | 'click_through_rate' | 'conversion_rate' | 'add_to_cart_rate' | 'purchase_rate' | 'average_click_position' | 'revenue';
/**
* Properties for the `customDelete` method.
*/
type CustomDeleteProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customGet` method.
*/
type CustomGetProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customPost` method.
*/
type CustomPostProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `customPut` method.
*/
type CustomPutProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `deleteABTest` method.
*/
type DeleteABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
/**
* Properties for the `getABTest` method.
*/
type GetABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
/**
* Properties for the `getTimeseries` method.
*/
type GetTimeseriesProps = {
/**
* Unique A/B test identifier.
*/
id: number;
/**
* Start date of the period to analyze, in `YYYY-MM-DD` format.
*/
startDate?: string | undefined;
/**
* End date of the period to analyze, in `YYYY-MM-DD` format.
*/
endDate?: string | undefined;
/**
* List of metrics to retrieve. If not specified, all metrics are returned.
*/
metric?: Array<MetricName> | undefined;
};
/**
* Properties for the `listABTests` method.
*/
type ListABTestsProps = {
/**
* Position of the first item to return.
*/
offset?: number | undefined;
/**
* Number of items to return.
*/
limit?: number | undefined;
/**
* Index name prefix. Only A/B tests for indices starting with this string are included in the response.
*/
indexPrefix?: string | undefined;
/**
* Index name suffix. Only A/B tests for indices ending with this string are included in the response.
*/
indexSuffix?: string | undefined;
/**
* Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
*/
direction?: Direction | undefined;
};
/**
* Properties for the `stopABTest` method.
*/
type StopABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
declare const apiClientVersion = "1.14.1";
declare const REGIONS: readonly ["de", "us"];
type Region = (typeof REGIONS)[number];
type RegionOptions = {
region?: Region | undefined;
};
declare function createAbtestingV3Client({ appId: appIdOption, apiKey: apiKeyOption, authMode, algoliaAgents, region: regionOption, ...options }: CreateClientOptions & RegionOptions): {
transporter: _algolia_client_common.Transporter;
/**
* The `appId` currently in use.
*/
appId: string;
/**
* The `apiKey` currently in use.
*/
apiKey: string;
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache(): Promise<void>;
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
readonly _ua: string;
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment: string, version?: string | undefined): void;
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }: {
apiKey: string;
}): void;
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest: AddABTestsRequest, requestOptions?: RequestOptions): Promise<ABTestResponse>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }: CustomDeleteProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }: CustomGetProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }: CustomPostProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }: CustomPutProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }: DeleteABTestProps, requestOptions?: RequestOptions): Promise<ABTestResponse>;
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest: EstimateABTestRequest, requestOptions?: RequestOptions): Promise<EstimateABTestResponse>;
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }: GetABTestProps, requestOptions?: RequestOptions): Promise<ABTest>;
/**
* Retrieves timeseries for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getTimeseries - The getTimeseries object.
* @param getTimeseries.id - Unique A/B test identifier.
* @param getTimeseries.startDate - Start date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.endDate - End date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.metric - List of metrics to retrieve. If not specified, all metrics are returned.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getTimeseries({ id, startDate, endDate, metric }: GetTimeseriesProps, requestOptions?: RequestOptions): Promise<Timeseries>;
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param listABTests.direction - Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix, direction }?: ListABTestsProps, requestOptions?: RequestOptions | undefined): Promise<ListABTestsResponse>;
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }: StopABTestProps, requestOptions?: RequestOptions): Promise<ABTestResponse>;
};
/**
* Error.
*/
type ErrorBase = Record<string, any> & {
message?: string | undefined;
};
type AbtestingV3Client = ReturnType<typeof createAbtestingV3Client>;
declare function abtestingV3Client(appId: string, apiKey: string, region?: Region | undefined, options?: ClientOptions | undefined): AbtestingV3Client;
export { type ABTest, type ABTestConfiguration, type ABTestResponse, type AbTestsVariant, type AbTestsVariantSearchParams, type AbtestingV3Client, type AddABTestsRequest, type AddABTestsVariant, type CreateMetric, type CustomDeleteProps, type CustomGetProps, type CustomPostProps, type CustomPutProps, type CustomSearchParams, type DeleteABTestProps, type Direction, type EffectMetric, type EmptySearchFilter, type ErrorBase, type ErrorCorrectionType, type EstimateABTestRequest, type EstimateABTestResponse, type EstimateConfiguration, type FilterEffects, type GetABTestProps, type GetTimeseriesProps, type ListABTestsProps, type ListABTestsResponse, type MetricDate, type MetricMetadata, type MetricName, type MetricResult, type MetricsFilter, type MinimumDetectableEffect, type OutliersFilter, type Region, type RegionOptions, type Status, type StopABTestProps, type Timeseries, type TimeseriesVariant, type Variant, type VariantMetadata, abtestingV3Client, apiClientVersion };
+420
View File
@@ -0,0 +1,420 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/abtestingV3Client.ts
var abtestingV3Client_exports = {};
__export(abtestingV3Client_exports, {
REGIONS: () => REGIONS,
apiClientVersion: () => apiClientVersion,
createAbtestingV3Client: () => createAbtestingV3Client
});
module.exports = __toCommonJS(abtestingV3Client_exports);
var import_client_common = require("@algolia/client-common");
var apiClientVersion = "1.14.1";
var REGIONS = ["de", "us"];
function getDefaultHosts(region) {
const url = !region ? "analytics.algolia.com" : "analytics.{region}.algolia.com".replace("{region}", region);
return [{ url, accept: "readWrite", protocol: "https" }];
}
function createAbtestingV3Client({
appId: appIdOption,
apiKey: apiKeyOption,
authMode,
algoliaAgents,
region: regionOption,
...options
}) {
const auth = (0, import_client_common.createAuth)(appIdOption, apiKeyOption, authMode);
const transporter = (0, import_client_common.createTransporter)({
hosts: getDefaultHosts(regionOption),
...options,
algoliaAgent: (0, import_client_common.getAlgoliaAgent)({
algoliaAgents,
client: "AbtestingV3",
version: apiClientVersion
}),
baseHeaders: {
"content-type": "text/plain",
...auth.headers(),
...options.baseHeaders
},
baseQueryParameters: {
...auth.queryParameters(),
...options.baseQueryParameters
}
});
return {
transporter,
/**
* The `appId` currently in use.
*/
appId: appIdOption,
/**
* The `apiKey` currently in use.
*/
apiKey: apiKeyOption,
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache() {
return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => void 0);
},
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
get _ua() {
return transporter.algoliaAgent.value;
},
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment, version) {
transporter.algoliaAgent.add({ segment, version });
},
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }) {
if (!authMode || authMode === "WithinHeaders") {
transporter.baseHeaders["x-algolia-api-key"] = apiKey;
} else {
transporter.baseQueryParameters["x-algolia-api-key"] = apiKey;
}
},
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest, requestOptions) {
if (!addABTestsRequest) {
throw new Error("Parameter `addABTestsRequest` is required when calling `addABTests`.");
}
if (!addABTestsRequest.name) {
throw new Error("Parameter `addABTestsRequest.name` is required when calling `addABTests`.");
}
if (!addABTestsRequest.variants) {
throw new Error("Parameter `addABTestsRequest.variants` is required when calling `addABTests`.");
}
if (!addABTestsRequest.metrics) {
throw new Error("Parameter `addABTestsRequest.metrics` is required when calling `addABTests`.");
}
if (!addABTestsRequest.endAt) {
throw new Error("Parameter `addABTestsRequest.endAt` is required when calling `addABTests`.");
}
const requestPath = "/3/abtests";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: addABTestsRequest
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customDelete`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customGet`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPost`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPut`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "PUT",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `deleteABTest`.");
}
const requestPath = "/3/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest, requestOptions) {
if (!estimateABTestRequest) {
throw new Error("Parameter `estimateABTestRequest` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.configuration) {
throw new Error("Parameter `estimateABTestRequest.configuration` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.variants) {
throw new Error("Parameter `estimateABTestRequest.variants` is required when calling `estimateABTest`.");
}
const requestPath = "/3/abtests/estimate";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: estimateABTestRequest
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `getABTest`.");
}
const requestPath = "/3/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves timeseries for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getTimeseries - The getTimeseries object.
* @param getTimeseries.id - Unique A/B test identifier.
* @param getTimeseries.startDate - Start date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.endDate - End date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.metric - List of metrics to retrieve. If not specified, all metrics are returned.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getTimeseries({ id, startDate, endDate, metric }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `getTimeseries`.");
}
const requestPath = "/3/abtests/{id}/timeseries".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
if (startDate !== void 0) {
queryParameters["startDate"] = startDate.toString();
}
if (endDate !== void 0) {
queryParameters["endDate"] = endDate.toString();
}
if (metric !== void 0) {
queryParameters["metric"] = metric.toString();
}
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param listABTests.direction - Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix, direction } = {}, requestOptions = void 0) {
const requestPath = "/3/abtests";
const headers = {};
const queryParameters = {};
if (offset !== void 0) {
queryParameters["offset"] = offset.toString();
}
if (limit !== void 0) {
queryParameters["limit"] = limit.toString();
}
if (indexPrefix !== void 0) {
queryParameters["indexPrefix"] = indexPrefix.toString();
}
if (indexSuffix !== void 0) {
queryParameters["indexSuffix"] = indexSuffix.toString();
}
if (direction !== void 0) {
queryParameters["direction"] = direction.toString();
}
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `stopABTest`.");
}
const requestPath = "/3/abtests/{id}/stop".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
}
};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
REGIONS,
apiClientVersion,
createAbtestingV3Client
});
//# sourceMappingURL=abtestingV3Client.cjs.map
File diff suppressed because one or more lines are too long
+393
View File
@@ -0,0 +1,393 @@
// src/abtestingV3Client.ts
import { createAuth, createTransporter, getAlgoliaAgent } from "@algolia/client-common";
var apiClientVersion = "1.14.1";
var REGIONS = ["de", "us"];
function getDefaultHosts(region) {
const url = !region ? "analytics.algolia.com" : "analytics.{region}.algolia.com".replace("{region}", region);
return [{ url, accept: "readWrite", protocol: "https" }];
}
function createAbtestingV3Client({
appId: appIdOption,
apiKey: apiKeyOption,
authMode,
algoliaAgents,
region: regionOption,
...options
}) {
const auth = createAuth(appIdOption, apiKeyOption, authMode);
const transporter = createTransporter({
hosts: getDefaultHosts(regionOption),
...options,
algoliaAgent: getAlgoliaAgent({
algoliaAgents,
client: "AbtestingV3",
version: apiClientVersion
}),
baseHeaders: {
"content-type": "text/plain",
...auth.headers(),
...options.baseHeaders
},
baseQueryParameters: {
...auth.queryParameters(),
...options.baseQueryParameters
}
});
return {
transporter,
/**
* The `appId` currently in use.
*/
appId: appIdOption,
/**
* The `apiKey` currently in use.
*/
apiKey: apiKeyOption,
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache() {
return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => void 0);
},
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
get _ua() {
return transporter.algoliaAgent.value;
},
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment, version) {
transporter.algoliaAgent.add({ segment, version });
},
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }) {
if (!authMode || authMode === "WithinHeaders") {
transporter.baseHeaders["x-algolia-api-key"] = apiKey;
} else {
transporter.baseQueryParameters["x-algolia-api-key"] = apiKey;
}
},
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest, requestOptions) {
if (!addABTestsRequest) {
throw new Error("Parameter `addABTestsRequest` is required when calling `addABTests`.");
}
if (!addABTestsRequest.name) {
throw new Error("Parameter `addABTestsRequest.name` is required when calling `addABTests`.");
}
if (!addABTestsRequest.variants) {
throw new Error("Parameter `addABTestsRequest.variants` is required when calling `addABTests`.");
}
if (!addABTestsRequest.metrics) {
throw new Error("Parameter `addABTestsRequest.metrics` is required when calling `addABTests`.");
}
if (!addABTestsRequest.endAt) {
throw new Error("Parameter `addABTestsRequest.endAt` is required when calling `addABTests`.");
}
const requestPath = "/3/abtests";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: addABTestsRequest
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customDelete`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customGet`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPost`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPut`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "PUT",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `deleteABTest`.");
}
const requestPath = "/3/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest, requestOptions) {
if (!estimateABTestRequest) {
throw new Error("Parameter `estimateABTestRequest` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.configuration) {
throw new Error("Parameter `estimateABTestRequest.configuration` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.variants) {
throw new Error("Parameter `estimateABTestRequest.variants` is required when calling `estimateABTest`.");
}
const requestPath = "/3/abtests/estimate";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: estimateABTestRequest
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `getABTest`.");
}
const requestPath = "/3/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves timeseries for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getTimeseries - The getTimeseries object.
* @param getTimeseries.id - Unique A/B test identifier.
* @param getTimeseries.startDate - Start date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.endDate - End date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.metric - List of metrics to retrieve. If not specified, all metrics are returned.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getTimeseries({ id, startDate, endDate, metric }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `getTimeseries`.");
}
const requestPath = "/3/abtests/{id}/timeseries".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
if (startDate !== void 0) {
queryParameters["startDate"] = startDate.toString();
}
if (endDate !== void 0) {
queryParameters["endDate"] = endDate.toString();
}
if (metric !== void 0) {
queryParameters["metric"] = metric.toString();
}
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param listABTests.direction - Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix, direction } = {}, requestOptions = void 0) {
const requestPath = "/3/abtests";
const headers = {};
const queryParameters = {};
if (offset !== void 0) {
queryParameters["offset"] = offset.toString();
}
if (limit !== void 0) {
queryParameters["limit"] = limit.toString();
}
if (indexPrefix !== void 0) {
queryParameters["indexPrefix"] = indexPrefix.toString();
}
if (indexSuffix !== void 0) {
queryParameters["indexSuffix"] = indexSuffix.toString();
}
if (direction !== void 0) {
queryParameters["direction"] = direction.toString();
}
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `stopABTest`.");
}
const requestPath = "/3/abtests/{id}/stop".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
}
};
}
export {
REGIONS,
apiClientVersion,
createAbtestingV3Client
};
//# sourceMappingURL=abtestingV3Client.js.map
File diff suppressed because one or more lines are too long
+677
View File
@@ -0,0 +1,677 @@
import * as _algolia_client_common from '@algolia/client-common';
import { CreateClientOptions, RequestOptions, ClientOptions } from '@algolia/client-common';
/**
* Multiple-testing correction method applied when evaluating metric significance.
*/
type ErrorCorrectionType = 'bonferroni' | 'benjamini-hochberg';
/**
* Boolean filter applied to the A/B test population. Each filter targets a boolean metric and decides whether to include (true) or exclude (false) matching records.
*/
type MetricsFilter = {
/**
* Metric domain (for example `abtesting`, `personalization`).
*/
domain: string;
/**
* Public metric name.
*/
name: string;
/**
* Whether the experiment should record the effects of this filter.
*/
trackEffects?: boolean | undefined;
/**
* If true, keep items that match the filter; if false, exclude them.
*/
includes?: boolean | undefined;
};
/**
* Metric for which you want to detect the smallest relative difference.
*/
type EffectMetric = 'addToCartRate' | 'clickThroughRate' | 'conversionRate' | 'purchaseRate' | 'noResultsRate';
/**
* Configuration for the smallest difference between test variants you want to detect.
*/
type MinimumDetectableEffect = {
/**
* Smallest difference in an observable metric between variants. For example, to detect a 10% difference between variants, set this value to 0.1.
*/
size: number;
metric: EffectMetric;
};
/**
* A/B test configuration.
*/
type ABTestConfiguration = {
minimumDetectableEffect?: MinimumDetectableEffect | undefined;
/**
* List of metric filters applied to the test population.
*/
filters?: Array<MetricsFilter> | undefined;
errorCorrection?: ErrorCorrectionType | undefined;
};
/**
* A/B test status. - `active`. The A/B test is live and search traffic is split between the two variants. - `stopped`. You stopped the A/B test. The A/B test data is still available for analysis. - `expired`. The A/B test was automatically stopped after reaching its end date. - `failed`. Creating the A/B test failed.
*/
type Status = 'active' | 'stopped' | 'expired' | 'failed';
/**
* Metric specific metadata.
*/
type MetricMetadata = {
/**
* Only present in case the metric is \'revenue\'. It is the amount exceeding the 95th percentile of global revenue transactions involved in the AB Test. This amount is not considered when calculating statistical significance. It is tied to a per revenue-currency pair contrary to other global filter effects (such as outliers and empty search count).
*/
winsorizedValue?: number | undefined;
/**
* Mean value for this metric.
*/
mean?: number | undefined;
};
type MetricResult = {
name: string;
/**
* Date and time when the metric was last updated, in RFC 3339 format.
*/
updatedAt: string;
value: number;
/**
* The upper bound of the 95% confidence interval for the metric value. The confidence interval is calculated using either the relative ratio or relative difference between the metric values for the control and the variant. Relative ratio is used for metrics that are ratios (e.g., click-through rate, conversion rate), while relative difference is used for continuous metrics (e.g., revenue).
*/
valueCIHigh?: number | undefined;
/**
* The lower bound of the 95% confidence interval for the metric value. The confidence interval is calculated using either the relative ratio or relative difference between the metric values for the control and the variant. Relative ratio is used for metrics that are ratios (e.g., click-through rate, conversion rate), while relative difference is used for continuous metrics (e.g., revenue).
*/
valueCILow?: number | undefined;
/**
* PValue for the first variant (control) will always be 0. For the other variants, pValue is calculated for the current variant based on the control.
*/
pValue: number;
/**
* Dimension defined during test creation.
*/
dimension?: string | undefined;
metadata?: MetricMetadata | undefined;
/**
* The value that was computed during error correction. It is used to determine significance of the metric pValue. The critical value is calculated using Bonferroni or Benjamini-Hochberg corrections, based on the given configuration during the A/B test creation.
*/
criticalValue?: number | undefined;
/**
* Whether the pValue is significant or not based on the critical value and the error correction algorithm used.
*/
significant?: boolean | undefined;
};
/**
* Empty searches removed from the A/B test as a result of configuration settings.
*/
type EmptySearchFilter = {
/**
* Number of users removed from the A/B test.
*/
usersCount?: number | undefined;
/**
* Number of tracked searches removed from the A/B test.
*/
trackedSearchesCount?: number | undefined;
};
/**
* Outliers removed from the A/B test as a result of configuration settings.
*/
type OutliersFilter = {
/**
* Number of users removed from the A/B test.
*/
usersCount?: number | undefined;
/**
* Number of tracked searches removed from the A/B test.
*/
trackedSearchesCount?: number | undefined;
};
/**
* A/B test filter effects resulting from configuration settings.
*/
type FilterEffects = {
outliers?: OutliersFilter | undefined;
emptySearch?: EmptySearchFilter | undefined;
};
/**
* Variant specific metadata.
*/
type VariantMetadata = {
filterEffects?: FilterEffects | undefined;
};
type Variant = {
/**
* Description for this variant.
*/
description: string;
/**
* Estimated number of searches required to achieve the desired statistical significance. The A/B test configuration must include a `minimumDetectableEffect` setting for this number to be included in the response.
*/
estimatedSampleSize?: number | undefined;
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Percentage of search requests each variant receives.
*/
trafficPercentage: number;
/**
* All ABTest metrics that were defined during test creation.
*/
metrics: Array<MetricResult>;
metadata?: VariantMetadata | undefined;
/**
* Search parameters applied to this variant when the same index is used for multiple variants. Only present if custom search parameters were provided during test creation.
*/
customSearchParameters?: Record<string, unknown> | undefined;
};
type ABTest = {
/**
* Unique A/B test identifier.
*/
abTestID: number;
/**
* Date and time when the A/B test was last updated, in RFC 3339 format.
*/
updatedAt: string;
/**
* Date and time when the A/B test was created, in RFC 3339 format.
*/
createdAt: string;
/**
* End date and time of the A/B test, in RFC 3339 format.
*/
endAt: string;
/**
* Date and time when the A/B test was stopped, in RFC 3339 format.
*/
stoppedAt?: string | null | undefined;
/**
* A/B test name.
*/
name: string;
status: Status;
/**
* A/B test variants. The first variant is your _control_ index, typically your production index. All of the additional variants are indexes with changed settings that you want to test against the control.
*/
variants: Array<Variant>;
configuration?: ABTestConfiguration | undefined;
/**
* Unique migrated A/B test identifier.
*/
migratedAbTestID?: number | undefined;
};
type ABTestResponse = {
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Unique A/B test identifier.
*/
abTestID: number;
/**
* Unique identifier of a task. A successful API response means that a task was added to a queue. It might not run immediately. You can check the task\'s progress with the [`task` operation](https://www.algolia.com/doc/rest-api/search/get-task) and this task ID.
*/
taskID: number;
};
type AbTestsVariant = {
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Percentage of search requests each variant receives.
*/
trafficPercentage: number;
/**
* Description for this variant.
*/
description?: string | undefined;
};
/**
* Search parameters to add to the test variant. Only use this parameter if the two variants use the same index.
*/
type CustomSearchParams = {
customSearchParameters: Record<string, unknown>;
};
type AbTestsVariantSearchParams = AbTestsVariant & CustomSearchParams;
type AddABTestsVariant = AbTestsVariant | AbTestsVariantSearchParams;
/**
* Defines a metric to be retrieved during an A/B test.
*/
type CreateMetric = {
/**
* Name of the metric.
*/
name: string;
/**
* Dimension of the metric, for example, in case of a revenue metric it could be USD, EUR...
*/
dimension?: string | undefined;
};
type AddABTestsRequest = {
/**
* A/B test name.
*/
name: string;
/**
* A/B test variants.
*/
variants: Array<AddABTestsVariant>;
/**
* A/B test metrics involved in the test. Only these metrics will be considered when calculating results.
*/
metrics: Array<CreateMetric>;
configuration?: ABTestConfiguration | undefined;
/**
* End date and time of the A/B test, in RFC 3339 format.
*/
endAt: string;
};
/**
* A/B test configuration for estimating the sample size and duration using minimum detectable effect.
*/
type EstimateConfiguration = {
/**
* List of metric filters applied to the test population.
*/
filters?: Array<MetricsFilter> | undefined;
minimumDetectableEffect: MinimumDetectableEffect;
};
type EstimateABTestRequest = {
configuration: EstimateConfiguration;
/**
* A/B test variants.
*/
variants: Array<AddABTestsVariant>;
};
type EstimateABTestResponse = {
/**
* Estimated number of days needed to reach the sample sizes required for detecting the configured effect. This value is based on historical traffic.
*/
durationDays?: number | undefined;
/**
* Sample size estimates for each variant. The first element is the control variant. Each element is the estimated number of searches required to achieve the desired statistical significance.
*/
sampleSizes?: Array<number> | undefined;
};
type ListABTestsResponse = {
/**
* A/B tests.
*/
abtests: Array<ABTest> | null;
/**
* Number of A/B tests.
*/
count: number;
/**
* Number of retrievable A/B tests.
*/
total: number;
};
type MetricDate = {
/**
* Date where the metric was updated, in RFC 3339 format.
*/
date?: string | undefined;
/**
* All ABTest metrics that were defined during test creation.
*/
metrics?: Array<MetricResult> | undefined;
};
type TimeseriesVariant = {
dates?: Array<MetricDate> | undefined;
};
type Timeseries = {
/**
* Unique A/B test identifier.
*/
abTestID: number;
/**
* A/B test timeseries variants. The first variant is your _control_ index, typically your production index. All of the additional variants are indexes with changed settings that you want to test against the control.
*/
variants: Array<TimeseriesVariant>;
};
/**
* Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
*/
type Direction = 'asc' | 'desc';
type MetricName = 'search_count' | 'tracked_search_count' | 'user_count' | 'tracked_user_count' | 'no_result_count' | 'add_to_cart_count' | 'purchase_count' | 'clicked_search_count' | 'converted_search_count' | 'click_through_rate' | 'conversion_rate' | 'add_to_cart_rate' | 'purchase_rate' | 'average_click_position' | 'revenue';
/**
* Properties for the `customDelete` method.
*/
type CustomDeleteProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customGet` method.
*/
type CustomGetProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customPost` method.
*/
type CustomPostProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `customPut` method.
*/
type CustomPutProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `deleteABTest` method.
*/
type DeleteABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
/**
* Properties for the `getABTest` method.
*/
type GetABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
/**
* Properties for the `getTimeseries` method.
*/
type GetTimeseriesProps = {
/**
* Unique A/B test identifier.
*/
id: number;
/**
* Start date of the period to analyze, in `YYYY-MM-DD` format.
*/
startDate?: string | undefined;
/**
* End date of the period to analyze, in `YYYY-MM-DD` format.
*/
endDate?: string | undefined;
/**
* List of metrics to retrieve. If not specified, all metrics are returned.
*/
metric?: Array<MetricName> | undefined;
};
/**
* Properties for the `listABTests` method.
*/
type ListABTestsProps = {
/**
* Position of the first item to return.
*/
offset?: number | undefined;
/**
* Number of items to return.
*/
limit?: number | undefined;
/**
* Index name prefix. Only A/B tests for indices starting with this string are included in the response.
*/
indexPrefix?: string | undefined;
/**
* Index name suffix. Only A/B tests for indices ending with this string are included in the response.
*/
indexSuffix?: string | undefined;
/**
* Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
*/
direction?: Direction | undefined;
};
/**
* Properties for the `stopABTest` method.
*/
type StopABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
declare const apiClientVersion = "1.14.1";
declare const REGIONS: readonly ["de", "us"];
type Region = (typeof REGIONS)[number];
type RegionOptions = {
region?: Region | undefined;
};
declare function createAbtestingV3Client({ appId: appIdOption, apiKey: apiKeyOption, authMode, algoliaAgents, region: regionOption, ...options }: CreateClientOptions & RegionOptions): {
transporter: _algolia_client_common.Transporter;
/**
* The `appId` currently in use.
*/
appId: string;
/**
* The `apiKey` currently in use.
*/
apiKey: string;
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache(): Promise<void>;
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
readonly _ua: string;
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment: string, version?: string | undefined): void;
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }: {
apiKey: string;
}): void;
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest: AddABTestsRequest, requestOptions?: RequestOptions): Promise<ABTestResponse>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }: CustomDeleteProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }: CustomGetProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }: CustomPostProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }: CustomPutProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }: DeleteABTestProps, requestOptions?: RequestOptions): Promise<ABTestResponse>;
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest: EstimateABTestRequest, requestOptions?: RequestOptions): Promise<EstimateABTestResponse>;
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }: GetABTestProps, requestOptions?: RequestOptions): Promise<ABTest>;
/**
* Retrieves timeseries for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getTimeseries - The getTimeseries object.
* @param getTimeseries.id - Unique A/B test identifier.
* @param getTimeseries.startDate - Start date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.endDate - End date of the period to analyze, in `YYYY-MM-DD` format.
* @param getTimeseries.metric - List of metrics to retrieve. If not specified, all metrics are returned.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getTimeseries({ id, startDate, endDate, metric }: GetTimeseriesProps, requestOptions?: RequestOptions): Promise<Timeseries>;
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param listABTests.direction - Sort order for A/B tests by start date. Use \'asc\' for ascending or \'desc\' for descending. Active A/B tests are always listed first.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix, direction }?: ListABTestsProps, requestOptions?: RequestOptions | undefined): Promise<ListABTestsResponse>;
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }: StopABTestProps, requestOptions?: RequestOptions): Promise<ABTestResponse>;
};
/**
* Error.
*/
type ErrorBase = Record<string, any> & {
message?: string | undefined;
};
type AbtestingV3Client = ReturnType<typeof createAbtestingV3Client>;
declare function abtestingV3Client(appId: string, apiKey: string, region?: Region | undefined, options?: ClientOptions | undefined): AbtestingV3Client;
export { type ABTest, type ABTestConfiguration, type ABTestResponse, type AbTestsVariant, type AbTestsVariantSearchParams, type AbtestingV3Client, type AddABTestsRequest, type AddABTestsVariant, type CreateMetric, type CustomDeleteProps, type CustomGetProps, type CustomPostProps, type CustomPutProps, type CustomSearchParams, type DeleteABTestProps, type Direction, type EffectMetric, type EmptySearchFilter, type ErrorBase, type ErrorCorrectionType, type EstimateABTestRequest, type EstimateABTestResponse, type EstimateConfiguration, type FilterEffects, type GetABTestProps, type GetTimeseriesProps, type ListABTestsProps, type ListABTestsResponse, type MetricDate, type MetricMetadata, type MetricName, type MetricResult, type MetricsFilter, type MinimumDetectableEffect, type OutliersFilter, type Region, type RegionOptions, type Status, type StopABTestProps, type Timeseries, type TimeseriesVariant, type Variant, type VariantMetadata, abtestingV3Client, apiClientVersion };
+1
View File
@@ -0,0 +1 @@
export * from './dist/node';
+1
View File
@@ -0,0 +1 @@
module.exports = require('./dist/builds/node.cjs');
+69
View File
@@ -0,0 +1,69 @@
{
"version": "1.14.1",
"repository": {
"type": "git",
"url": "git+https://github.com/algolia/algoliasearch-client-javascript.git"
},
"homepage": "https://github.com/algolia/algoliasearch-client-javascript/tree/main/packages/abtesting#readme",
"type": "module",
"license": "MIT",
"author": "Algolia",
"scripts": {
"build": "yarn clean && yarn tsup && yarn rollup -c rollup.config.js",
"clean": "rm -rf ./dist || true",
"test:bundle": "publint . && attw --pack ."
},
"name": "@algolia/abtesting",
"description": "JavaScript client for abtesting",
"exports": {
".": {
"node": {
"types": {
"import": "./dist/node.d.ts",
"module": "./dist/node.d.ts",
"require": "./dist/node.d.cts"
},
"import": "./dist/builds/node.js",
"module": "./dist/builds/node.js",
"require": "./dist/builds/node.cjs"
},
"worker": {
"types": "./dist/worker.d.ts",
"default": "./dist/builds/worker.js"
},
"default": {
"types": "./dist/browser.d.ts",
"module": "./dist/builds/browser.js",
"import": "./dist/builds/browser.js",
"default": "./dist/builds/browser.umd.js"
}
},
"./dist/builds/*": "./dist/builds/*.js"
},
"jsdelivr": "./dist/builds/browser.umd.js",
"unpkg": "./dist/builds/browser.umd.js",
"react-native": "./dist/builds/browser.js",
"files": [
"dist",
"index.js",
"index.d.ts"
],
"dependencies": {
"@algolia/client-common": "5.48.1",
"@algolia/requester-browser-xhr": "5.48.1",
"@algolia/requester-fetch": "5.48.1",
"@algolia/requester-node-http": "5.48.1"
},
"devDependencies": {
"@arethetypeswrong/cli": "0.18.2",
"@types/node": "25.1.0",
"publint": "0.3.17",
"rollup": "4.57.1",
"tsup": "8.5.1",
"typescript": "5.9.3"
},
"engines": {
"node": ">= 14.0.0"
},
"gitHead": "4bbb3ce8d4cb7b7ad454352d4835cffead91ee30"
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2013-Present Algolia
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+76
View File
@@ -0,0 +1,76 @@
<p align="center">
<a href="https://www.algolia.com">
<img alt="Algolia for JavaScript" src="https://raw.githubusercontent.com/algolia/algoliasearch-client-common/master/banners/javascript.png" >
</a>
<h4 align="center">The perfect starting point to integrate <a href="https://algolia.com" target="_blank">Algolia</a> within your JavaScript project</h4>
<p align="center">
<a href="https://npmjs.com/package/@algolia/client-abtesting"><img src="https://img.shields.io/npm/v/@algolia/client-abtesting.svg?style=flat-square" alt="NPM version"></img></a>
<a href="http://npm-stat.com/charts.html?package=@algolia/client-abtesting"><img src="https://img.shields.io/npm/dm/@algolia/client-abtesting.svg?style=flat-square" alt="NPM downloads"></a>
<a href="https://www.jsdelivr.com/package/npm/@algolia/client-abtesting"><img src="https://data.jsdelivr.com/v1/package/npm/@algolia/client-abtesting/badge" alt="jsDelivr Downloads"></img></a>
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-green.svg?style=flat-square" alt="License"></a>
</p>
</p>
<p align="center">
<a href="https://www.algolia.com/doc/libraries/sdk/install#javascript" target="_blank">Documentation</a> •
<a href="https://www.algolia.com/doc/guides/building-search-ui/what-is-instantsearch/js/" target="_blank">InstantSearch</a> •
<a href="https://discourse.algolia.com" target="_blank">Community Forum</a> •
<a href="http://stackoverflow.com/questions/tagged/algolia" target="_blank">Stack Overflow</a> •
<a href="https://github.com/algolia/algoliasearch-client-javascript/issues" target="_blank">Report a bug</a> •
<a href="https://alg.li/support" target="_blank">Support</a>
</p>
## ✨ Features
- Thin & **minimal low-level HTTP client** to interact with Algolia's API
- Works both on the **browser** and **node.js**
- **UMD and ESM compatible**, you can use it with any module loader
- Built with TypeScript
## 💡 Getting Started
> [!TIP]
> This API client is already a dependency of [the algoliasearch client](https://www.npmjs.com/package/algoliasearch), you don't need to manually install `@algolia/client-abtesting` if you already have `algoliasearch` installed.
To get started, you first need to install @algolia/client-abtesting (or any other available API client package).
All of our clients comes with type definition, and are available for both browser and node environments.
### With a package manager
```bash
yarn add @algolia/client-abtesting@5.48.1
# or
npm install @algolia/client-abtesting@5.48.1
# or
pnpm add @algolia/client-abtesting@5.48.1
```
### Without a package manager
Add the following JavaScript snippet to the <head> of your website:
```html
<script src="https://cdn.jsdelivr.net/npm/@algolia/client-abtesting@5.48.1/dist/builds/browser.umd.js"></script>
```
### Usage
You can now import the Algolia API client in your project and play with it.
```js
import { abtestingClient } from '@algolia/client-abtesting';
const client = abtestingClient('YOUR_APP_ID', 'YOUR_API_KEY');
```
For full documentation, visit the **[Algolia JavaScript API Client](https://www.algolia.com/doc/libraries/sdk/methods/abtesting/)**.
## ❓ Troubleshooting
Encountering an issue? Before reaching out to support, we recommend heading to our [FAQ](https://support.algolia.com/hc/en-us/sections/15061037630609-API-Client-FAQs) where you will find answers for the most common issues and gotchas with the client. You can also open [a GitHub issue](https://github.com/algolia/api-clients-automation/issues/new?assignees=&labels=&projects=&template=Bug_report.md)
## 📄 License
The Algolia JavaScript API Client is an open-sourced software licensed under the [MIT license](LICENSE).
+618
View File
@@ -0,0 +1,618 @@
import * as _algolia_client_common from '@algolia/client-common';
import { CreateClientOptions, RequestOptions, ClientOptions } from '@algolia/client-common';
/**
* Configuration for handling empty searches.
*/
type EmptySearch = {
/**
* Whether to exclude empty searches when calculating A/B test results.
*/
exclude?: boolean | undefined;
};
/**
* Configuration of feature-based filters applied to the A/B test population.
*/
type FeatureFilters = {
/**
* Whether to apply Dynamic Re-Ranking feature filters.
*/
dynamicReRanking?: boolean | undefined;
/**
* Whether to apply AI Personalization feature filters.
*/
aiPerso?: boolean | undefined;
/**
* Whether to apply Multi-Signal Re-Ranking feature filters.
*/
multiSignalRanking?: boolean | undefined;
};
/**
* Metric for which you want to detect the smallest relative difference.
*/
type EffectMetric = 'addToCartRate' | 'clickThroughRate' | 'conversionRate' | 'purchaseRate';
/**
* Configuration for the smallest difference between test variants you want to detect.
*/
type MinimumDetectableEffect = {
/**
* Smallest difference in an observable metric between variants. For example, to detect a 10% difference between variants, set this value to 0.1.
*/
size: number;
metric: EffectMetric;
};
/**
* Configuration for handling outliers.
*/
type Outliers = {
/**
* Whether to exclude outliers when calculating A/B test results.
*/
exclude?: boolean | undefined;
};
/**
* A/B test configuration.
*/
type ABTestConfiguration = {
featureFilters?: FeatureFilters | undefined;
outliers?: Outliers | undefined;
emptySearch?: EmptySearch | undefined;
minimumDetectableEffect?: MinimumDetectableEffect | undefined;
};
/**
* A/B test status. - `active`. The A/B test is live and search traffic is split between the two variants. - `stopped`. You stopped the A/B test. The A/B test data is still available for analysis. - `expired`. The A/B test was automatically stopped after reaching its end date. - `failed`. Creating the A/B test failed.
*/
type Status = 'active' | 'stopped' | 'expired' | 'failed';
type Currency = {
/**
* Currency code.
*/
currency?: string | undefined;
/**
* Revenue for this currency.
*/
revenue?: number | undefined;
/**
* Mean for this currency.
*/
mean?: number | undefined;
/**
* Standard deviation for this currency.
*/
standardDeviation?: number | undefined;
/**
* The amount of revenue for this currency that was removed after capping purchase amounts to the 95th percentile.
*/
winsorizedAmount?: number | undefined;
};
/**
* Empty searches removed from the A/B test as a result of configuration settings.
*/
type EmptySearchFilter = {
/**
* Number of users removed from the A/B test.
*/
usersCount?: number | undefined;
/**
* Number of tracked searches removed from the A/B test.
*/
trackedSearchesCount?: number | undefined;
};
/**
* Outliers removed from the A/B test as a result of configuration settings.
*/
type OutliersFilter = {
/**
* Number of users removed from the A/B test.
*/
usersCount?: number | undefined;
/**
* Number of tracked searches removed from the A/B test.
*/
trackedSearchesCount?: number | undefined;
};
/**
* A/B test filter effects resulting from configuration settings.
*/
type FilterEffects = {
outliers?: OutliersFilter | undefined;
emptySearch?: EmptySearchFilter | undefined;
};
type Variant = {
/**
* Number of add-to-cart events for this variant.
*/
addToCartCount: number;
/**
* [Add-to-cart rate](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#add-to-cart-rate) for this variant.
*/
addToCartRate?: number | null | undefined;
/**
* [Average click position](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#click-position) for this variant.
*/
averageClickPosition?: number | null | undefined;
/**
* Number of click events for this variant.
*/
clickCount: number;
/**
* [Click-through rate](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#click-through-rate) for this variant.
*/
clickThroughRate?: number | null | undefined;
/**
* Number of click events for this variant.
*/
conversionCount: number;
/**
* [Conversion rate](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#conversion-rate) for this variant.
*/
conversionRate?: number | null | undefined;
/**
* A/B test currencies.
*/
currencies?: {
[key: string]: Currency;
} | undefined;
/**
* Description for this variant.
*/
description?: string | undefined;
/**
* Estimated number of searches required to achieve the desired statistical significance. The A/B test configuration must include a `mininmumDetectableEffect` setting for this number to be included in the response.
*/
estimatedSampleSize?: number | undefined;
filterEffects?: FilterEffects | undefined;
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Number of [searches without results](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#searches-without-results) for this variant.
*/
noResultCount: number | null;
/**
* Number of purchase events for this variant.
*/
purchaseCount: number;
/**
* [Purchase rate](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#purchase-rate) for this variant.
*/
purchaseRate?: number | null | undefined;
/**
* Number of searches for this variant.
*/
searchCount: number | null;
/**
* Number of tracked searches. Tracked searches are search requests where the `clickAnalytics` parameter is true.
*/
trackedSearchCount?: number | undefined;
/**
* Percentage of search requests each variant receives.
*/
trafficPercentage: number;
/**
* Number of users that made searches to this variant.
*/
userCount: number | null;
/**
* Number of users that made tracked searches to this variant.
*/
trackedUserCount: number | null;
};
type ABTest = {
/**
* Unique A/B test identifier.
*/
abTestID: number;
clickSignificance?: number | null | undefined;
conversionSignificance?: number | null | undefined;
addToCartSignificance?: number | null | undefined;
purchaseSignificance?: number | null | undefined;
revenueSignificance?: {
[key: string]: number;
} | null | undefined;
/**
* Date and time when the A/B test was last updated, in RFC 3339 format.
*/
updatedAt: string;
/**
* Date and time when the A/B test was created, in RFC 3339 format.
*/
createdAt: string;
/**
* End date and time of the A/B test, in RFC 3339 format.
*/
endAt: string;
/**
* Date and time when the A/B test was stopped, in RFC 3339 format.
*/
stoppedAt?: string | null | undefined;
/**
* A/B test name.
*/
name: string;
status: Status;
/**
* A/B test variants. The first variant is your _control_ index, typically your production index. The second variant is an index with changed settings that you want to test against the control.
*/
variants: Array<Variant>;
configuration?: ABTestConfiguration | undefined;
};
type ABTestResponse = {
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Unique A/B test identifier.
*/
abTestID: number;
/**
* Unique identifier of a task. A successful API response means that a task was added to a queue. It might not run immediately. You can check the task\'s progress with the [`task` operation](https://www.algolia.com/doc/rest-api/search/get-task) and this task ID.
*/
taskID: number;
};
type AbTestsVariant = {
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Percentage of search requests each variant receives.
*/
trafficPercentage: number;
/**
* Description for this variant.
*/
description?: string | undefined;
};
/**
* Search parameters to add to the test variant. Only use this parameter if the two variants use the same index.
*/
type CustomSearchParams = {
customSearchParameters: Record<string, unknown>;
};
type AbTestsVariantSearchParams = AbTestsVariant & CustomSearchParams;
type AddABTestsVariant = AbTestsVariant | AbTestsVariantSearchParams;
type AddABTestsRequest = {
/**
* A/B test name.
*/
name: string;
/**
* A/B test variants.
*/
variants: Array<AddABTestsVariant>;
/**
* End date and time of the A/B test, in RFC 3339 format.
*/
endAt: string;
};
/**
* A/B test configuration for estimating the sample size and duration using minimum detectable effect.
*/
type EstimateConfiguration = {
featureFilters?: FeatureFilters | undefined;
outliers?: Outliers | undefined;
emptySearch?: EmptySearch | undefined;
minimumDetectableEffect: MinimumDetectableEffect;
};
type EstimateABTestRequest = {
configuration: EstimateConfiguration;
/**
* A/B test variants.
*/
variants: Array<AddABTestsVariant>;
};
type EstimateABTestResponse = {
/**
* Estimated number of days needed to reach the sample sizes required for detecting the configured effect. This value is based on historical traffic.
*/
durationDays?: number | undefined;
/**
* Sample size estimates for each variant. The first element is the control variant. Each element is the estimated number of searches required to achieve the desired statistical significance.
*/
sampleSizes?: Array<number> | undefined;
};
type ListABTestsResponse = {
/**
* The list of A/B tests, null if no A/B tests are configured for this application.
*/
abtests: Array<ABTest> | null;
/**
* Number of A/B tests.
*/
count: number;
/**
* Number of retrievable A/B tests.
*/
total: number;
};
/**
* Properties for the `customDelete` method.
*/
type CustomDeleteProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customGet` method.
*/
type CustomGetProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customPost` method.
*/
type CustomPostProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `customPut` method.
*/
type CustomPutProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `deleteABTest` method.
*/
type DeleteABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
/**
* Properties for the `getABTest` method.
*/
type GetABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
/**
* Properties for the `listABTests` method.
*/
type ListABTestsProps = {
/**
* Position of the first item to return.
*/
offset?: number | undefined;
/**
* Number of items to return.
*/
limit?: number | undefined;
/**
* Index name prefix. Only A/B tests for indices starting with this string are included in the response.
*/
indexPrefix?: string | undefined;
/**
* Index name suffix. Only A/B tests for indices ending with this string are included in the response.
*/
indexSuffix?: string | undefined;
};
/**
* Properties for the `stopABTest` method.
*/
type StopABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
declare const apiClientVersion = "5.48.1";
declare const REGIONS: readonly ["de", "us"];
type Region = (typeof REGIONS)[number];
type RegionOptions = {
region?: Region | undefined;
};
declare function createAbtestingClient({ appId: appIdOption, apiKey: apiKeyOption, authMode, algoliaAgents, region: regionOption, ...options }: CreateClientOptions & RegionOptions): {
transporter: _algolia_client_common.Transporter;
/**
* The `appId` currently in use.
*/
appId: string;
/**
* The `apiKey` currently in use.
*/
apiKey: string;
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache(): Promise<void>;
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
readonly _ua: string;
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment: string, version?: string | undefined): void;
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }: {
apiKey: string;
}): void;
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest: AddABTestsRequest, requestOptions?: RequestOptions): Promise<ABTestResponse>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }: CustomDeleteProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }: CustomGetProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }: CustomPostProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }: CustomPutProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }: DeleteABTestProps, requestOptions?: RequestOptions): Promise<ABTestResponse>;
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest: EstimateABTestRequest, requestOptions?: RequestOptions): Promise<EstimateABTestResponse>;
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }: GetABTestProps, requestOptions?: RequestOptions): Promise<ABTest>;
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix }?: ListABTestsProps, requestOptions?: RequestOptions | undefined): Promise<ListABTestsResponse>;
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }: StopABTestProps, requestOptions?: RequestOptions): Promise<ABTestResponse>;
};
/**
* Error.
*/
type ErrorBase = Record<string, any> & {
message?: string | undefined;
};
declare function abtestingClient(appId: string, apiKey: string, region?: Region | undefined, options?: ClientOptions | undefined): AbtestingClient;
type AbtestingClient = ReturnType<typeof createAbtestingClient>;
export { type ABTest, type ABTestConfiguration, type ABTestResponse, type AbTestsVariant, type AbTestsVariantSearchParams, type AbtestingClient, type AddABTestsRequest, type AddABTestsVariant, type Currency, type CustomDeleteProps, type CustomGetProps, type CustomPostProps, type CustomPutProps, type CustomSearchParams, type DeleteABTestProps, type EffectMetric, type EmptySearch, type EmptySearchFilter, type ErrorBase, type EstimateABTestRequest, type EstimateABTestResponse, type EstimateConfiguration, type FeatureFilters, type FilterEffects, type GetABTestProps, type ListABTestsProps, type ListABTestsResponse, type MinimumDetectableEffect, type Outliers, type OutliersFilter, type Region, type RegionOptions, type Status, type StopABTestProps, type Variant, abtestingClient, apiClientVersion };
+391
View File
@@ -0,0 +1,391 @@
// builds/browser.ts
import {
createBrowserLocalStorageCache,
createFallbackableCache,
createMemoryCache,
createNullLogger
} from "@algolia/client-common";
import { createXhrRequester } from "@algolia/requester-browser-xhr";
// src/abtestingClient.ts
import { createAuth, createTransporter, getAlgoliaAgent } from "@algolia/client-common";
var apiClientVersion = "5.48.1";
var REGIONS = ["de", "us"];
function getDefaultHosts(region) {
const url = !region ? "analytics.algolia.com" : "analytics.{region}.algolia.com".replace("{region}", region);
return [{ url, accept: "readWrite", protocol: "https" }];
}
function createAbtestingClient({
appId: appIdOption,
apiKey: apiKeyOption,
authMode,
algoliaAgents,
region: regionOption,
...options
}) {
const auth = createAuth(appIdOption, apiKeyOption, authMode);
const transporter = createTransporter({
hosts: getDefaultHosts(regionOption),
...options,
algoliaAgent: getAlgoliaAgent({
algoliaAgents,
client: "Abtesting",
version: apiClientVersion
}),
baseHeaders: {
"content-type": "text/plain",
...auth.headers(),
...options.baseHeaders
},
baseQueryParameters: {
...auth.queryParameters(),
...options.baseQueryParameters
}
});
return {
transporter,
/**
* The `appId` currently in use.
*/
appId: appIdOption,
/**
* The `apiKey` currently in use.
*/
apiKey: apiKeyOption,
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache() {
return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => void 0);
},
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
get _ua() {
return transporter.algoliaAgent.value;
},
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment, version) {
transporter.algoliaAgent.add({ segment, version });
},
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }) {
if (!authMode || authMode === "WithinHeaders") {
transporter.baseHeaders["x-algolia-api-key"] = apiKey;
} else {
transporter.baseQueryParameters["x-algolia-api-key"] = apiKey;
}
},
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest, requestOptions) {
if (!addABTestsRequest) {
throw new Error("Parameter `addABTestsRequest` is required when calling `addABTests`.");
}
if (!addABTestsRequest.name) {
throw new Error("Parameter `addABTestsRequest.name` is required when calling `addABTests`.");
}
if (!addABTestsRequest.variants) {
throw new Error("Parameter `addABTestsRequest.variants` is required when calling `addABTests`.");
}
if (!addABTestsRequest.endAt) {
throw new Error("Parameter `addABTestsRequest.endAt` is required when calling `addABTests`.");
}
const requestPath = "/2/abtests";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: addABTestsRequest
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customDelete`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customGet`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPost`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPut`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "PUT",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `deleteABTest`.");
}
const requestPath = "/2/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest, requestOptions) {
if (!estimateABTestRequest) {
throw new Error("Parameter `estimateABTestRequest` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.configuration) {
throw new Error("Parameter `estimateABTestRequest.configuration` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.variants) {
throw new Error("Parameter `estimateABTestRequest.variants` is required when calling `estimateABTest`.");
}
const requestPath = "/2/abtests/estimate";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: estimateABTestRequest
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `getABTest`.");
}
const requestPath = "/2/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix } = {}, requestOptions = void 0) {
const requestPath = "/2/abtests";
const headers = {};
const queryParameters = {};
if (offset !== void 0) {
queryParameters["offset"] = offset.toString();
}
if (limit !== void 0) {
queryParameters["limit"] = limit.toString();
}
if (indexPrefix !== void 0) {
queryParameters["indexPrefix"] = indexPrefix.toString();
}
if (indexSuffix !== void 0) {
queryParameters["indexSuffix"] = indexSuffix.toString();
}
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `stopABTest`.");
}
const requestPath = "/2/abtests/{id}/stop".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
}
};
}
// builds/browser.ts
function abtestingClient(appId, apiKey, region, options) {
if (!appId || typeof appId !== "string") {
throw new Error("`appId` is missing.");
}
if (!apiKey || typeof apiKey !== "string") {
throw new Error("`apiKey` is missing.");
}
if (region && (typeof region !== "string" || !REGIONS.includes(region))) {
throw new Error(`\`region\` must be one of the following: ${REGIONS.join(", ")}`);
}
return createAbtestingClient({
appId,
apiKey,
region,
timeouts: {
connect: 1e3,
read: 2e3,
write: 3e4
},
logger: createNullLogger(),
requester: createXhrRequester(),
algoliaAgents: [{ segment: "Browser" }],
authMode: "WithinQueryParameters",
responsesCache: createMemoryCache(),
requestsCache: createMemoryCache({ serializable: false }),
hostsCache: createFallbackableCache({
caches: [createBrowserLocalStorageCache({ key: `${apiClientVersion}-${appId}` }), createMemoryCache()]
}),
...options
});
}
export {
abtestingClient,
apiClientVersion
};
//# sourceMappingURL=browser.js.map
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+385
View File
@@ -0,0 +1,385 @@
// builds/fetch.ts
import { createMemoryCache, createNullCache, createNullLogger } from "@algolia/client-common";
import { createFetchRequester } from "@algolia/requester-fetch";
// src/abtestingClient.ts
import { createAuth, createTransporter, getAlgoliaAgent } from "@algolia/client-common";
var apiClientVersion = "5.48.1";
var REGIONS = ["de", "us"];
function getDefaultHosts(region) {
const url = !region ? "analytics.algolia.com" : "analytics.{region}.algolia.com".replace("{region}", region);
return [{ url, accept: "readWrite", protocol: "https" }];
}
function createAbtestingClient({
appId: appIdOption,
apiKey: apiKeyOption,
authMode,
algoliaAgents,
region: regionOption,
...options
}) {
const auth = createAuth(appIdOption, apiKeyOption, authMode);
const transporter = createTransporter({
hosts: getDefaultHosts(regionOption),
...options,
algoliaAgent: getAlgoliaAgent({
algoliaAgents,
client: "Abtesting",
version: apiClientVersion
}),
baseHeaders: {
"content-type": "text/plain",
...auth.headers(),
...options.baseHeaders
},
baseQueryParameters: {
...auth.queryParameters(),
...options.baseQueryParameters
}
});
return {
transporter,
/**
* The `appId` currently in use.
*/
appId: appIdOption,
/**
* The `apiKey` currently in use.
*/
apiKey: apiKeyOption,
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache() {
return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => void 0);
},
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
get _ua() {
return transporter.algoliaAgent.value;
},
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment, version) {
transporter.algoliaAgent.add({ segment, version });
},
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }) {
if (!authMode || authMode === "WithinHeaders") {
transporter.baseHeaders["x-algolia-api-key"] = apiKey;
} else {
transporter.baseQueryParameters["x-algolia-api-key"] = apiKey;
}
},
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest, requestOptions) {
if (!addABTestsRequest) {
throw new Error("Parameter `addABTestsRequest` is required when calling `addABTests`.");
}
if (!addABTestsRequest.name) {
throw new Error("Parameter `addABTestsRequest.name` is required when calling `addABTests`.");
}
if (!addABTestsRequest.variants) {
throw new Error("Parameter `addABTestsRequest.variants` is required when calling `addABTests`.");
}
if (!addABTestsRequest.endAt) {
throw new Error("Parameter `addABTestsRequest.endAt` is required when calling `addABTests`.");
}
const requestPath = "/2/abtests";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: addABTestsRequest
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customDelete`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customGet`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPost`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPut`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "PUT",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `deleteABTest`.");
}
const requestPath = "/2/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest, requestOptions) {
if (!estimateABTestRequest) {
throw new Error("Parameter `estimateABTestRequest` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.configuration) {
throw new Error("Parameter `estimateABTestRequest.configuration` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.variants) {
throw new Error("Parameter `estimateABTestRequest.variants` is required when calling `estimateABTest`.");
}
const requestPath = "/2/abtests/estimate";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: estimateABTestRequest
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `getABTest`.");
}
const requestPath = "/2/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix } = {}, requestOptions = void 0) {
const requestPath = "/2/abtests";
const headers = {};
const queryParameters = {};
if (offset !== void 0) {
queryParameters["offset"] = offset.toString();
}
if (limit !== void 0) {
queryParameters["limit"] = limit.toString();
}
if (indexPrefix !== void 0) {
queryParameters["indexPrefix"] = indexPrefix.toString();
}
if (indexSuffix !== void 0) {
queryParameters["indexSuffix"] = indexSuffix.toString();
}
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `stopABTest`.");
}
const requestPath = "/2/abtests/{id}/stop".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
}
};
}
// builds/fetch.ts
function abtestingClient(appId, apiKey, region, options) {
if (!appId || typeof appId !== "string") {
throw new Error("`appId` is missing.");
}
if (!apiKey || typeof apiKey !== "string") {
throw new Error("`apiKey` is missing.");
}
if (region && (typeof region !== "string" || !REGIONS.includes(region))) {
throw new Error(`\`region\` must be one of the following: ${REGIONS.join(", ")}`);
}
return {
...createAbtestingClient({
appId,
apiKey,
region,
timeouts: {
connect: 2e3,
read: 5e3,
write: 3e4
},
logger: createNullLogger(),
requester: createFetchRequester(),
algoliaAgents: [{ segment: "Fetch" }],
responsesCache: createNullCache(),
requestsCache: createNullCache(),
hostsCache: createMemoryCache(),
...options
})
};
}
export {
abtestingClient,
apiClientVersion
};
//# sourceMappingURL=fetch.js.map
File diff suppressed because one or more lines are too long
+411
View File
@@ -0,0 +1,411 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// builds/node.ts
var node_exports = {};
__export(node_exports, {
abtestingClient: () => abtestingClient,
apiClientVersion: () => apiClientVersion
});
module.exports = __toCommonJS(node_exports);
var import_client_common2 = require("@algolia/client-common");
var import_requester_node_http = require("@algolia/requester-node-http");
// src/abtestingClient.ts
var import_client_common = require("@algolia/client-common");
var apiClientVersion = "5.48.1";
var REGIONS = ["de", "us"];
function getDefaultHosts(region) {
const url = !region ? "analytics.algolia.com" : "analytics.{region}.algolia.com".replace("{region}", region);
return [{ url, accept: "readWrite", protocol: "https" }];
}
function createAbtestingClient({
appId: appIdOption,
apiKey: apiKeyOption,
authMode,
algoliaAgents,
region: regionOption,
...options
}) {
const auth = (0, import_client_common.createAuth)(appIdOption, apiKeyOption, authMode);
const transporter = (0, import_client_common.createTransporter)({
hosts: getDefaultHosts(regionOption),
...options,
algoliaAgent: (0, import_client_common.getAlgoliaAgent)({
algoliaAgents,
client: "Abtesting",
version: apiClientVersion
}),
baseHeaders: {
"content-type": "text/plain",
...auth.headers(),
...options.baseHeaders
},
baseQueryParameters: {
...auth.queryParameters(),
...options.baseQueryParameters
}
});
return {
transporter,
/**
* The `appId` currently in use.
*/
appId: appIdOption,
/**
* The `apiKey` currently in use.
*/
apiKey: apiKeyOption,
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache() {
return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => void 0);
},
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
get _ua() {
return transporter.algoliaAgent.value;
},
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment, version) {
transporter.algoliaAgent.add({ segment, version });
},
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }) {
if (!authMode || authMode === "WithinHeaders") {
transporter.baseHeaders["x-algolia-api-key"] = apiKey;
} else {
transporter.baseQueryParameters["x-algolia-api-key"] = apiKey;
}
},
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest, requestOptions) {
if (!addABTestsRequest) {
throw new Error("Parameter `addABTestsRequest` is required when calling `addABTests`.");
}
if (!addABTestsRequest.name) {
throw new Error("Parameter `addABTestsRequest.name` is required when calling `addABTests`.");
}
if (!addABTestsRequest.variants) {
throw new Error("Parameter `addABTestsRequest.variants` is required when calling `addABTests`.");
}
if (!addABTestsRequest.endAt) {
throw new Error("Parameter `addABTestsRequest.endAt` is required when calling `addABTests`.");
}
const requestPath = "/2/abtests";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: addABTestsRequest
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customDelete`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customGet`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPost`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPut`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "PUT",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `deleteABTest`.");
}
const requestPath = "/2/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest, requestOptions) {
if (!estimateABTestRequest) {
throw new Error("Parameter `estimateABTestRequest` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.configuration) {
throw new Error("Parameter `estimateABTestRequest.configuration` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.variants) {
throw new Error("Parameter `estimateABTestRequest.variants` is required when calling `estimateABTest`.");
}
const requestPath = "/2/abtests/estimate";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: estimateABTestRequest
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `getABTest`.");
}
const requestPath = "/2/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix } = {}, requestOptions = void 0) {
const requestPath = "/2/abtests";
const headers = {};
const queryParameters = {};
if (offset !== void 0) {
queryParameters["offset"] = offset.toString();
}
if (limit !== void 0) {
queryParameters["limit"] = limit.toString();
}
if (indexPrefix !== void 0) {
queryParameters["indexPrefix"] = indexPrefix.toString();
}
if (indexSuffix !== void 0) {
queryParameters["indexSuffix"] = indexSuffix.toString();
}
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `stopABTest`.");
}
const requestPath = "/2/abtests/{id}/stop".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
}
};
}
// builds/node.ts
function abtestingClient(appId, apiKey, region, options) {
if (!appId || typeof appId !== "string") {
throw new Error("`appId` is missing.");
}
if (!apiKey || typeof apiKey !== "string") {
throw new Error("`apiKey` is missing.");
}
if (region && (typeof region !== "string" || !REGIONS.includes(region))) {
throw new Error(`\`region\` must be one of the following: ${REGIONS.join(", ")}`);
}
return {
...createAbtestingClient({
appId,
apiKey,
region,
timeouts: {
connect: 2e3,
read: 5e3,
write: 3e4
},
logger: (0, import_client_common2.createNullLogger)(),
requester: (0, import_requester_node_http.createHttpRequester)(),
algoliaAgents: [{ segment: "Node.js", version: process.versions.node }],
responsesCache: (0, import_client_common2.createNullCache)(),
requestsCache: (0, import_client_common2.createNullCache)(),
hostsCache: (0, import_client_common2.createMemoryCache)(),
...options
})
};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
abtestingClient,
apiClientVersion
});
//# sourceMappingURL=node.cjs.map
File diff suppressed because one or more lines are too long
+385
View File
@@ -0,0 +1,385 @@
// builds/node.ts
import { createMemoryCache, createNullCache, createNullLogger } from "@algolia/client-common";
import { createHttpRequester } from "@algolia/requester-node-http";
// src/abtestingClient.ts
import { createAuth, createTransporter, getAlgoliaAgent } from "@algolia/client-common";
var apiClientVersion = "5.48.1";
var REGIONS = ["de", "us"];
function getDefaultHosts(region) {
const url = !region ? "analytics.algolia.com" : "analytics.{region}.algolia.com".replace("{region}", region);
return [{ url, accept: "readWrite", protocol: "https" }];
}
function createAbtestingClient({
appId: appIdOption,
apiKey: apiKeyOption,
authMode,
algoliaAgents,
region: regionOption,
...options
}) {
const auth = createAuth(appIdOption, apiKeyOption, authMode);
const transporter = createTransporter({
hosts: getDefaultHosts(regionOption),
...options,
algoliaAgent: getAlgoliaAgent({
algoliaAgents,
client: "Abtesting",
version: apiClientVersion
}),
baseHeaders: {
"content-type": "text/plain",
...auth.headers(),
...options.baseHeaders
},
baseQueryParameters: {
...auth.queryParameters(),
...options.baseQueryParameters
}
});
return {
transporter,
/**
* The `appId` currently in use.
*/
appId: appIdOption,
/**
* The `apiKey` currently in use.
*/
apiKey: apiKeyOption,
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache() {
return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => void 0);
},
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
get _ua() {
return transporter.algoliaAgent.value;
},
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment, version) {
transporter.algoliaAgent.add({ segment, version });
},
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }) {
if (!authMode || authMode === "WithinHeaders") {
transporter.baseHeaders["x-algolia-api-key"] = apiKey;
} else {
transporter.baseQueryParameters["x-algolia-api-key"] = apiKey;
}
},
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest, requestOptions) {
if (!addABTestsRequest) {
throw new Error("Parameter `addABTestsRequest` is required when calling `addABTests`.");
}
if (!addABTestsRequest.name) {
throw new Error("Parameter `addABTestsRequest.name` is required when calling `addABTests`.");
}
if (!addABTestsRequest.variants) {
throw new Error("Parameter `addABTestsRequest.variants` is required when calling `addABTests`.");
}
if (!addABTestsRequest.endAt) {
throw new Error("Parameter `addABTestsRequest.endAt` is required when calling `addABTests`.");
}
const requestPath = "/2/abtests";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: addABTestsRequest
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customDelete`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customGet`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPost`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPut`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "PUT",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `deleteABTest`.");
}
const requestPath = "/2/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest, requestOptions) {
if (!estimateABTestRequest) {
throw new Error("Parameter `estimateABTestRequest` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.configuration) {
throw new Error("Parameter `estimateABTestRequest.configuration` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.variants) {
throw new Error("Parameter `estimateABTestRequest.variants` is required when calling `estimateABTest`.");
}
const requestPath = "/2/abtests/estimate";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: estimateABTestRequest
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `getABTest`.");
}
const requestPath = "/2/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix } = {}, requestOptions = void 0) {
const requestPath = "/2/abtests";
const headers = {};
const queryParameters = {};
if (offset !== void 0) {
queryParameters["offset"] = offset.toString();
}
if (limit !== void 0) {
queryParameters["limit"] = limit.toString();
}
if (indexPrefix !== void 0) {
queryParameters["indexPrefix"] = indexPrefix.toString();
}
if (indexSuffix !== void 0) {
queryParameters["indexSuffix"] = indexSuffix.toString();
}
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `stopABTest`.");
}
const requestPath = "/2/abtests/{id}/stop".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
}
};
}
// builds/node.ts
function abtestingClient(appId, apiKey, region, options) {
if (!appId || typeof appId !== "string") {
throw new Error("`appId` is missing.");
}
if (!apiKey || typeof apiKey !== "string") {
throw new Error("`apiKey` is missing.");
}
if (region && (typeof region !== "string" || !REGIONS.includes(region))) {
throw new Error(`\`region\` must be one of the following: ${REGIONS.join(", ")}`);
}
return {
...createAbtestingClient({
appId,
apiKey,
region,
timeouts: {
connect: 2e3,
read: 5e3,
write: 3e4
},
logger: createNullLogger(),
requester: createHttpRequester(),
algoliaAgents: [{ segment: "Node.js", version: process.versions.node }],
responsesCache: createNullCache(),
requestsCache: createNullCache(),
hostsCache: createMemoryCache(),
...options
})
};
}
export {
abtestingClient,
apiClientVersion
};
//# sourceMappingURL=node.js.map
File diff suppressed because one or more lines are too long
+385
View File
@@ -0,0 +1,385 @@
// builds/worker.ts
import { createMemoryCache, createNullCache, createNullLogger } from "@algolia/client-common";
import { createFetchRequester } from "@algolia/requester-fetch";
// src/abtestingClient.ts
import { createAuth, createTransporter, getAlgoliaAgent } from "@algolia/client-common";
var apiClientVersion = "5.48.1";
var REGIONS = ["de", "us"];
function getDefaultHosts(region) {
const url = !region ? "analytics.algolia.com" : "analytics.{region}.algolia.com".replace("{region}", region);
return [{ url, accept: "readWrite", protocol: "https" }];
}
function createAbtestingClient({
appId: appIdOption,
apiKey: apiKeyOption,
authMode,
algoliaAgents,
region: regionOption,
...options
}) {
const auth = createAuth(appIdOption, apiKeyOption, authMode);
const transporter = createTransporter({
hosts: getDefaultHosts(regionOption),
...options,
algoliaAgent: getAlgoliaAgent({
algoliaAgents,
client: "Abtesting",
version: apiClientVersion
}),
baseHeaders: {
"content-type": "text/plain",
...auth.headers(),
...options.baseHeaders
},
baseQueryParameters: {
...auth.queryParameters(),
...options.baseQueryParameters
}
});
return {
transporter,
/**
* The `appId` currently in use.
*/
appId: appIdOption,
/**
* The `apiKey` currently in use.
*/
apiKey: apiKeyOption,
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache() {
return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => void 0);
},
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
get _ua() {
return transporter.algoliaAgent.value;
},
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment, version) {
transporter.algoliaAgent.add({ segment, version });
},
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }) {
if (!authMode || authMode === "WithinHeaders") {
transporter.baseHeaders["x-algolia-api-key"] = apiKey;
} else {
transporter.baseQueryParameters["x-algolia-api-key"] = apiKey;
}
},
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest, requestOptions) {
if (!addABTestsRequest) {
throw new Error("Parameter `addABTestsRequest` is required when calling `addABTests`.");
}
if (!addABTestsRequest.name) {
throw new Error("Parameter `addABTestsRequest.name` is required when calling `addABTests`.");
}
if (!addABTestsRequest.variants) {
throw new Error("Parameter `addABTestsRequest.variants` is required when calling `addABTests`.");
}
if (!addABTestsRequest.endAt) {
throw new Error("Parameter `addABTestsRequest.endAt` is required when calling `addABTests`.");
}
const requestPath = "/2/abtests";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: addABTestsRequest
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customDelete`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customGet`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPost`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPut`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "PUT",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `deleteABTest`.");
}
const requestPath = "/2/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest, requestOptions) {
if (!estimateABTestRequest) {
throw new Error("Parameter `estimateABTestRequest` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.configuration) {
throw new Error("Parameter `estimateABTestRequest.configuration` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.variants) {
throw new Error("Parameter `estimateABTestRequest.variants` is required when calling `estimateABTest`.");
}
const requestPath = "/2/abtests/estimate";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: estimateABTestRequest
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `getABTest`.");
}
const requestPath = "/2/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix } = {}, requestOptions = void 0) {
const requestPath = "/2/abtests";
const headers = {};
const queryParameters = {};
if (offset !== void 0) {
queryParameters["offset"] = offset.toString();
}
if (limit !== void 0) {
queryParameters["limit"] = limit.toString();
}
if (indexPrefix !== void 0) {
queryParameters["indexPrefix"] = indexPrefix.toString();
}
if (indexSuffix !== void 0) {
queryParameters["indexSuffix"] = indexSuffix.toString();
}
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `stopABTest`.");
}
const requestPath = "/2/abtests/{id}/stop".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
}
};
}
// builds/worker.ts
function abtestingClient(appId, apiKey, region, options) {
if (!appId || typeof appId !== "string") {
throw new Error("`appId` is missing.");
}
if (!apiKey || typeof apiKey !== "string") {
throw new Error("`apiKey` is missing.");
}
if (region && (typeof region !== "string" || !REGIONS.includes(region))) {
throw new Error(`\`region\` must be one of the following: ${REGIONS.join(", ")}`);
}
return {
...createAbtestingClient({
appId,
apiKey,
region,
timeouts: {
connect: 2e3,
read: 5e3,
write: 3e4
},
logger: createNullLogger(),
requester: createFetchRequester(),
algoliaAgents: [{ segment: "Worker" }],
responsesCache: createNullCache(),
requestsCache: createNullCache(),
hostsCache: createMemoryCache(),
...options
})
};
}
export {
abtestingClient,
apiClientVersion
};
//# sourceMappingURL=worker.js.map
File diff suppressed because one or more lines are too long
+619
View File
@@ -0,0 +1,619 @@
import * as _algolia_client_common from '@algolia/client-common';
import { CreateClientOptions, RequestOptions, ClientOptions } from '@algolia/client-common';
/**
* Configuration for handling empty searches.
*/
type EmptySearch = {
/**
* Whether to exclude empty searches when calculating A/B test results.
*/
exclude?: boolean | undefined;
};
/**
* Configuration of feature-based filters applied to the A/B test population.
*/
type FeatureFilters = {
/**
* Whether to apply Dynamic Re-Ranking feature filters.
*/
dynamicReRanking?: boolean | undefined;
/**
* Whether to apply AI Personalization feature filters.
*/
aiPerso?: boolean | undefined;
/**
* Whether to apply Multi-Signal Re-Ranking feature filters.
*/
multiSignalRanking?: boolean | undefined;
};
/**
* Metric for which you want to detect the smallest relative difference.
*/
type EffectMetric = 'addToCartRate' | 'clickThroughRate' | 'conversionRate' | 'purchaseRate';
/**
* Configuration for the smallest difference between test variants you want to detect.
*/
type MinimumDetectableEffect = {
/**
* Smallest difference in an observable metric between variants. For example, to detect a 10% difference between variants, set this value to 0.1.
*/
size: number;
metric: EffectMetric;
};
/**
* Configuration for handling outliers.
*/
type Outliers = {
/**
* Whether to exclude outliers when calculating A/B test results.
*/
exclude?: boolean | undefined;
};
/**
* A/B test configuration.
*/
type ABTestConfiguration = {
featureFilters?: FeatureFilters | undefined;
outliers?: Outliers | undefined;
emptySearch?: EmptySearch | undefined;
minimumDetectableEffect?: MinimumDetectableEffect | undefined;
};
/**
* A/B test status. - `active`. The A/B test is live and search traffic is split between the two variants. - `stopped`. You stopped the A/B test. The A/B test data is still available for analysis. - `expired`. The A/B test was automatically stopped after reaching its end date. - `failed`. Creating the A/B test failed.
*/
type Status = 'active' | 'stopped' | 'expired' | 'failed';
type Currency = {
/**
* Currency code.
*/
currency?: string | undefined;
/**
* Revenue for this currency.
*/
revenue?: number | undefined;
/**
* Mean for this currency.
*/
mean?: number | undefined;
/**
* Standard deviation for this currency.
*/
standardDeviation?: number | undefined;
/**
* The amount of revenue for this currency that was removed after capping purchase amounts to the 95th percentile.
*/
winsorizedAmount?: number | undefined;
};
/**
* Empty searches removed from the A/B test as a result of configuration settings.
*/
type EmptySearchFilter = {
/**
* Number of users removed from the A/B test.
*/
usersCount?: number | undefined;
/**
* Number of tracked searches removed from the A/B test.
*/
trackedSearchesCount?: number | undefined;
};
/**
* Outliers removed from the A/B test as a result of configuration settings.
*/
type OutliersFilter = {
/**
* Number of users removed from the A/B test.
*/
usersCount?: number | undefined;
/**
* Number of tracked searches removed from the A/B test.
*/
trackedSearchesCount?: number | undefined;
};
/**
* A/B test filter effects resulting from configuration settings.
*/
type FilterEffects = {
outliers?: OutliersFilter | undefined;
emptySearch?: EmptySearchFilter | undefined;
};
type Variant = {
/**
* Number of add-to-cart events for this variant.
*/
addToCartCount: number;
/**
* [Add-to-cart rate](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#add-to-cart-rate) for this variant.
*/
addToCartRate?: number | null | undefined;
/**
* [Average click position](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#click-position) for this variant.
*/
averageClickPosition?: number | null | undefined;
/**
* Number of click events for this variant.
*/
clickCount: number;
/**
* [Click-through rate](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#click-through-rate) for this variant.
*/
clickThroughRate?: number | null | undefined;
/**
* Number of click events for this variant.
*/
conversionCount: number;
/**
* [Conversion rate](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#conversion-rate) for this variant.
*/
conversionRate?: number | null | undefined;
/**
* A/B test currencies.
*/
currencies?: {
[key: string]: Currency;
} | undefined;
/**
* Description for this variant.
*/
description?: string | undefined;
/**
* Estimated number of searches required to achieve the desired statistical significance. The A/B test configuration must include a `mininmumDetectableEffect` setting for this number to be included in the response.
*/
estimatedSampleSize?: number | undefined;
filterEffects?: FilterEffects | undefined;
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Number of [searches without results](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#searches-without-results) for this variant.
*/
noResultCount: number | null;
/**
* Number of purchase events for this variant.
*/
purchaseCount: number;
/**
* [Purchase rate](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#purchase-rate) for this variant.
*/
purchaseRate?: number | null | undefined;
/**
* Number of searches for this variant.
*/
searchCount: number | null;
/**
* Number of tracked searches. Tracked searches are search requests where the `clickAnalytics` parameter is true.
*/
trackedSearchCount?: number | undefined;
/**
* Percentage of search requests each variant receives.
*/
trafficPercentage: number;
/**
* Number of users that made searches to this variant.
*/
userCount: number | null;
/**
* Number of users that made tracked searches to this variant.
*/
trackedUserCount: number | null;
};
type ABTest = {
/**
* Unique A/B test identifier.
*/
abTestID: number;
clickSignificance?: number | null | undefined;
conversionSignificance?: number | null | undefined;
addToCartSignificance?: number | null | undefined;
purchaseSignificance?: number | null | undefined;
revenueSignificance?: {
[key: string]: number;
} | null | undefined;
/**
* Date and time when the A/B test was last updated, in RFC 3339 format.
*/
updatedAt: string;
/**
* Date and time when the A/B test was created, in RFC 3339 format.
*/
createdAt: string;
/**
* End date and time of the A/B test, in RFC 3339 format.
*/
endAt: string;
/**
* Date and time when the A/B test was stopped, in RFC 3339 format.
*/
stoppedAt?: string | null | undefined;
/**
* A/B test name.
*/
name: string;
status: Status;
/**
* A/B test variants. The first variant is your _control_ index, typically your production index. The second variant is an index with changed settings that you want to test against the control.
*/
variants: Array<Variant>;
configuration?: ABTestConfiguration | undefined;
};
type ABTestResponse = {
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Unique A/B test identifier.
*/
abTestID: number;
/**
* Unique identifier of a task. A successful API response means that a task was added to a queue. It might not run immediately. You can check the task\'s progress with the [`task` operation](https://www.algolia.com/doc/rest-api/search/get-task) and this task ID.
*/
taskID: number;
};
type AbTestsVariant = {
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Percentage of search requests each variant receives.
*/
trafficPercentage: number;
/**
* Description for this variant.
*/
description?: string | undefined;
};
/**
* Search parameters to add to the test variant. Only use this parameter if the two variants use the same index.
*/
type CustomSearchParams = {
customSearchParameters: Record<string, unknown>;
};
type AbTestsVariantSearchParams = AbTestsVariant & CustomSearchParams;
type AddABTestsVariant = AbTestsVariant | AbTestsVariantSearchParams;
type AddABTestsRequest = {
/**
* A/B test name.
*/
name: string;
/**
* A/B test variants.
*/
variants: Array<AddABTestsVariant>;
/**
* End date and time of the A/B test, in RFC 3339 format.
*/
endAt: string;
};
/**
* A/B test configuration for estimating the sample size and duration using minimum detectable effect.
*/
type EstimateConfiguration = {
featureFilters?: FeatureFilters | undefined;
outliers?: Outliers | undefined;
emptySearch?: EmptySearch | undefined;
minimumDetectableEffect: MinimumDetectableEffect;
};
type EstimateABTestRequest = {
configuration: EstimateConfiguration;
/**
* A/B test variants.
*/
variants: Array<AddABTestsVariant>;
};
type EstimateABTestResponse = {
/**
* Estimated number of days needed to reach the sample sizes required for detecting the configured effect. This value is based on historical traffic.
*/
durationDays?: number | undefined;
/**
* Sample size estimates for each variant. The first element is the control variant. Each element is the estimated number of searches required to achieve the desired statistical significance.
*/
sampleSizes?: Array<number> | undefined;
};
type ListABTestsResponse = {
/**
* The list of A/B tests, null if no A/B tests are configured for this application.
*/
abtests: Array<ABTest> | null;
/**
* Number of A/B tests.
*/
count: number;
/**
* Number of retrievable A/B tests.
*/
total: number;
};
/**
* Properties for the `customDelete` method.
*/
type CustomDeleteProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customGet` method.
*/
type CustomGetProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customPost` method.
*/
type CustomPostProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `customPut` method.
*/
type CustomPutProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `deleteABTest` method.
*/
type DeleteABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
/**
* Properties for the `getABTest` method.
*/
type GetABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
/**
* Properties for the `listABTests` method.
*/
type ListABTestsProps = {
/**
* Position of the first item to return.
*/
offset?: number | undefined;
/**
* Number of items to return.
*/
limit?: number | undefined;
/**
* Index name prefix. Only A/B tests for indices starting with this string are included in the response.
*/
indexPrefix?: string | undefined;
/**
* Index name suffix. Only A/B tests for indices ending with this string are included in the response.
*/
indexSuffix?: string | undefined;
};
/**
* Properties for the `stopABTest` method.
*/
type StopABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
declare const apiClientVersion = "5.48.1";
declare const REGIONS: readonly ["de", "us"];
type Region = (typeof REGIONS)[number];
type RegionOptions = {
region?: Region | undefined;
};
declare function createAbtestingClient({ appId: appIdOption, apiKey: apiKeyOption, authMode, algoliaAgents, region: regionOption, ...options }: CreateClientOptions & RegionOptions): {
transporter: _algolia_client_common.Transporter;
/**
* The `appId` currently in use.
*/
appId: string;
/**
* The `apiKey` currently in use.
*/
apiKey: string;
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache(): Promise<void>;
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
readonly _ua: string;
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment: string, version?: string | undefined): void;
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }: {
apiKey: string;
}): void;
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest: AddABTestsRequest, requestOptions?: RequestOptions): Promise<ABTestResponse>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }: CustomDeleteProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }: CustomGetProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }: CustomPostProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }: CustomPutProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }: DeleteABTestProps, requestOptions?: RequestOptions): Promise<ABTestResponse>;
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest: EstimateABTestRequest, requestOptions?: RequestOptions): Promise<EstimateABTestResponse>;
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }: GetABTestProps, requestOptions?: RequestOptions): Promise<ABTest>;
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix }?: ListABTestsProps, requestOptions?: RequestOptions | undefined): Promise<ListABTestsResponse>;
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }: StopABTestProps, requestOptions?: RequestOptions): Promise<ABTestResponse>;
};
/**
* Error.
*/
type ErrorBase = Record<string, any> & {
message?: string | undefined;
};
type AbtestingClient = ReturnType<typeof createAbtestingClient>;
declare function abtestingClient(appId: string, apiKey: string, region?: Region | undefined, options?: ClientOptions | undefined): AbtestingClient;
export { type ABTest, type ABTestConfiguration, type ABTestResponse, type AbTestsVariant, type AbTestsVariantSearchParams, type AbtestingClient, type AddABTestsRequest, type AddABTestsVariant, type Currency, type CustomDeleteProps, type CustomGetProps, type CustomPostProps, type CustomPutProps, type CustomSearchParams, type DeleteABTestProps, type EffectMetric, type EmptySearch, type EmptySearchFilter, type ErrorBase, type EstimateABTestRequest, type EstimateABTestResponse, type EstimateConfiguration, type FeatureFilters, type FilterEffects, type GetABTestProps, type ListABTestsProps, type ListABTestsResponse, type MinimumDetectableEffect, type Outliers, type OutliersFilter, type Region, type RegionOptions, type Status, type StopABTestProps, type Variant, abtestingClient, apiClientVersion };
+619
View File
@@ -0,0 +1,619 @@
import * as _algolia_client_common from '@algolia/client-common';
import { CreateClientOptions, RequestOptions, ClientOptions } from '@algolia/client-common';
/**
* Configuration for handling empty searches.
*/
type EmptySearch = {
/**
* Whether to exclude empty searches when calculating A/B test results.
*/
exclude?: boolean | undefined;
};
/**
* Configuration of feature-based filters applied to the A/B test population.
*/
type FeatureFilters = {
/**
* Whether to apply Dynamic Re-Ranking feature filters.
*/
dynamicReRanking?: boolean | undefined;
/**
* Whether to apply AI Personalization feature filters.
*/
aiPerso?: boolean | undefined;
/**
* Whether to apply Multi-Signal Re-Ranking feature filters.
*/
multiSignalRanking?: boolean | undefined;
};
/**
* Metric for which you want to detect the smallest relative difference.
*/
type EffectMetric = 'addToCartRate' | 'clickThroughRate' | 'conversionRate' | 'purchaseRate';
/**
* Configuration for the smallest difference between test variants you want to detect.
*/
type MinimumDetectableEffect = {
/**
* Smallest difference in an observable metric between variants. For example, to detect a 10% difference between variants, set this value to 0.1.
*/
size: number;
metric: EffectMetric;
};
/**
* Configuration for handling outliers.
*/
type Outliers = {
/**
* Whether to exclude outliers when calculating A/B test results.
*/
exclude?: boolean | undefined;
};
/**
* A/B test configuration.
*/
type ABTestConfiguration = {
featureFilters?: FeatureFilters | undefined;
outliers?: Outliers | undefined;
emptySearch?: EmptySearch | undefined;
minimumDetectableEffect?: MinimumDetectableEffect | undefined;
};
/**
* A/B test status. - `active`. The A/B test is live and search traffic is split between the two variants. - `stopped`. You stopped the A/B test. The A/B test data is still available for analysis. - `expired`. The A/B test was automatically stopped after reaching its end date. - `failed`. Creating the A/B test failed.
*/
type Status = 'active' | 'stopped' | 'expired' | 'failed';
type Currency = {
/**
* Currency code.
*/
currency?: string | undefined;
/**
* Revenue for this currency.
*/
revenue?: number | undefined;
/**
* Mean for this currency.
*/
mean?: number | undefined;
/**
* Standard deviation for this currency.
*/
standardDeviation?: number | undefined;
/**
* The amount of revenue for this currency that was removed after capping purchase amounts to the 95th percentile.
*/
winsorizedAmount?: number | undefined;
};
/**
* Empty searches removed from the A/B test as a result of configuration settings.
*/
type EmptySearchFilter = {
/**
* Number of users removed from the A/B test.
*/
usersCount?: number | undefined;
/**
* Number of tracked searches removed from the A/B test.
*/
trackedSearchesCount?: number | undefined;
};
/**
* Outliers removed from the A/B test as a result of configuration settings.
*/
type OutliersFilter = {
/**
* Number of users removed from the A/B test.
*/
usersCount?: number | undefined;
/**
* Number of tracked searches removed from the A/B test.
*/
trackedSearchesCount?: number | undefined;
};
/**
* A/B test filter effects resulting from configuration settings.
*/
type FilterEffects = {
outliers?: OutliersFilter | undefined;
emptySearch?: EmptySearchFilter | undefined;
};
type Variant = {
/**
* Number of add-to-cart events for this variant.
*/
addToCartCount: number;
/**
* [Add-to-cart rate](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#add-to-cart-rate) for this variant.
*/
addToCartRate?: number | null | undefined;
/**
* [Average click position](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#click-position) for this variant.
*/
averageClickPosition?: number | null | undefined;
/**
* Number of click events for this variant.
*/
clickCount: number;
/**
* [Click-through rate](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#click-through-rate) for this variant.
*/
clickThroughRate?: number | null | undefined;
/**
* Number of click events for this variant.
*/
conversionCount: number;
/**
* [Conversion rate](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#conversion-rate) for this variant.
*/
conversionRate?: number | null | undefined;
/**
* A/B test currencies.
*/
currencies?: {
[key: string]: Currency;
} | undefined;
/**
* Description for this variant.
*/
description?: string | undefined;
/**
* Estimated number of searches required to achieve the desired statistical significance. The A/B test configuration must include a `mininmumDetectableEffect` setting for this number to be included in the response.
*/
estimatedSampleSize?: number | undefined;
filterEffects?: FilterEffects | undefined;
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Number of [searches without results](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#searches-without-results) for this variant.
*/
noResultCount: number | null;
/**
* Number of purchase events for this variant.
*/
purchaseCount: number;
/**
* [Purchase rate](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#purchase-rate) for this variant.
*/
purchaseRate?: number | null | undefined;
/**
* Number of searches for this variant.
*/
searchCount: number | null;
/**
* Number of tracked searches. Tracked searches are search requests where the `clickAnalytics` parameter is true.
*/
trackedSearchCount?: number | undefined;
/**
* Percentage of search requests each variant receives.
*/
trafficPercentage: number;
/**
* Number of users that made searches to this variant.
*/
userCount: number | null;
/**
* Number of users that made tracked searches to this variant.
*/
trackedUserCount: number | null;
};
type ABTest = {
/**
* Unique A/B test identifier.
*/
abTestID: number;
clickSignificance?: number | null | undefined;
conversionSignificance?: number | null | undefined;
addToCartSignificance?: number | null | undefined;
purchaseSignificance?: number | null | undefined;
revenueSignificance?: {
[key: string]: number;
} | null | undefined;
/**
* Date and time when the A/B test was last updated, in RFC 3339 format.
*/
updatedAt: string;
/**
* Date and time when the A/B test was created, in RFC 3339 format.
*/
createdAt: string;
/**
* End date and time of the A/B test, in RFC 3339 format.
*/
endAt: string;
/**
* Date and time when the A/B test was stopped, in RFC 3339 format.
*/
stoppedAt?: string | null | undefined;
/**
* A/B test name.
*/
name: string;
status: Status;
/**
* A/B test variants. The first variant is your _control_ index, typically your production index. The second variant is an index with changed settings that you want to test against the control.
*/
variants: Array<Variant>;
configuration?: ABTestConfiguration | undefined;
};
type ABTestResponse = {
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Unique A/B test identifier.
*/
abTestID: number;
/**
* Unique identifier of a task. A successful API response means that a task was added to a queue. It might not run immediately. You can check the task\'s progress with the [`task` operation](https://www.algolia.com/doc/rest-api/search/get-task) and this task ID.
*/
taskID: number;
};
type AbTestsVariant = {
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Percentage of search requests each variant receives.
*/
trafficPercentage: number;
/**
* Description for this variant.
*/
description?: string | undefined;
};
/**
* Search parameters to add to the test variant. Only use this parameter if the two variants use the same index.
*/
type CustomSearchParams = {
customSearchParameters: Record<string, unknown>;
};
type AbTestsVariantSearchParams = AbTestsVariant & CustomSearchParams;
type AddABTestsVariant = AbTestsVariant | AbTestsVariantSearchParams;
type AddABTestsRequest = {
/**
* A/B test name.
*/
name: string;
/**
* A/B test variants.
*/
variants: Array<AddABTestsVariant>;
/**
* End date and time of the A/B test, in RFC 3339 format.
*/
endAt: string;
};
/**
* A/B test configuration for estimating the sample size and duration using minimum detectable effect.
*/
type EstimateConfiguration = {
featureFilters?: FeatureFilters | undefined;
outliers?: Outliers | undefined;
emptySearch?: EmptySearch | undefined;
minimumDetectableEffect: MinimumDetectableEffect;
};
type EstimateABTestRequest = {
configuration: EstimateConfiguration;
/**
* A/B test variants.
*/
variants: Array<AddABTestsVariant>;
};
type EstimateABTestResponse = {
/**
* Estimated number of days needed to reach the sample sizes required for detecting the configured effect. This value is based on historical traffic.
*/
durationDays?: number | undefined;
/**
* Sample size estimates for each variant. The first element is the control variant. Each element is the estimated number of searches required to achieve the desired statistical significance.
*/
sampleSizes?: Array<number> | undefined;
};
type ListABTestsResponse = {
/**
* The list of A/B tests, null if no A/B tests are configured for this application.
*/
abtests: Array<ABTest> | null;
/**
* Number of A/B tests.
*/
count: number;
/**
* Number of retrievable A/B tests.
*/
total: number;
};
/**
* Properties for the `customDelete` method.
*/
type CustomDeleteProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customGet` method.
*/
type CustomGetProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customPost` method.
*/
type CustomPostProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `customPut` method.
*/
type CustomPutProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `deleteABTest` method.
*/
type DeleteABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
/**
* Properties for the `getABTest` method.
*/
type GetABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
/**
* Properties for the `listABTests` method.
*/
type ListABTestsProps = {
/**
* Position of the first item to return.
*/
offset?: number | undefined;
/**
* Number of items to return.
*/
limit?: number | undefined;
/**
* Index name prefix. Only A/B tests for indices starting with this string are included in the response.
*/
indexPrefix?: string | undefined;
/**
* Index name suffix. Only A/B tests for indices ending with this string are included in the response.
*/
indexSuffix?: string | undefined;
};
/**
* Properties for the `stopABTest` method.
*/
type StopABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
declare const apiClientVersion = "5.48.1";
declare const REGIONS: readonly ["de", "us"];
type Region = (typeof REGIONS)[number];
type RegionOptions = {
region?: Region | undefined;
};
declare function createAbtestingClient({ appId: appIdOption, apiKey: apiKeyOption, authMode, algoliaAgents, region: regionOption, ...options }: CreateClientOptions & RegionOptions): {
transporter: _algolia_client_common.Transporter;
/**
* The `appId` currently in use.
*/
appId: string;
/**
* The `apiKey` currently in use.
*/
apiKey: string;
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache(): Promise<void>;
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
readonly _ua: string;
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment: string, version?: string | undefined): void;
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }: {
apiKey: string;
}): void;
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest: AddABTestsRequest, requestOptions?: RequestOptions): Promise<ABTestResponse>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }: CustomDeleteProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }: CustomGetProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }: CustomPostProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }: CustomPutProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }: DeleteABTestProps, requestOptions?: RequestOptions): Promise<ABTestResponse>;
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest: EstimateABTestRequest, requestOptions?: RequestOptions): Promise<EstimateABTestResponse>;
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }: GetABTestProps, requestOptions?: RequestOptions): Promise<ABTest>;
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix }?: ListABTestsProps, requestOptions?: RequestOptions | undefined): Promise<ListABTestsResponse>;
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }: StopABTestProps, requestOptions?: RequestOptions): Promise<ABTestResponse>;
};
/**
* Error.
*/
type ErrorBase = Record<string, any> & {
message?: string | undefined;
};
type AbtestingClient = ReturnType<typeof createAbtestingClient>;
declare function abtestingClient(appId: string, apiKey: string, region?: Region | undefined, options?: ClientOptions | undefined): AbtestingClient;
export { type ABTest, type ABTestConfiguration, type ABTestResponse, type AbTestsVariant, type AbTestsVariantSearchParams, type AbtestingClient, type AddABTestsRequest, type AddABTestsVariant, type Currency, type CustomDeleteProps, type CustomGetProps, type CustomPostProps, type CustomPutProps, type CustomSearchParams, type DeleteABTestProps, type EffectMetric, type EmptySearch, type EmptySearchFilter, type ErrorBase, type EstimateABTestRequest, type EstimateABTestResponse, type EstimateConfiguration, type FeatureFilters, type FilterEffects, type GetABTestProps, type ListABTestsProps, type ListABTestsResponse, type MinimumDetectableEffect, type Outliers, type OutliersFilter, type Region, type RegionOptions, type Status, type StopABTestProps, type Variant, abtestingClient, apiClientVersion };
+619
View File
@@ -0,0 +1,619 @@
import * as _algolia_client_common from '@algolia/client-common';
import { CreateClientOptions, RequestOptions, ClientOptions } from '@algolia/client-common';
/**
* Configuration for handling empty searches.
*/
type EmptySearch = {
/**
* Whether to exclude empty searches when calculating A/B test results.
*/
exclude?: boolean | undefined;
};
/**
* Configuration of feature-based filters applied to the A/B test population.
*/
type FeatureFilters = {
/**
* Whether to apply Dynamic Re-Ranking feature filters.
*/
dynamicReRanking?: boolean | undefined;
/**
* Whether to apply AI Personalization feature filters.
*/
aiPerso?: boolean | undefined;
/**
* Whether to apply Multi-Signal Re-Ranking feature filters.
*/
multiSignalRanking?: boolean | undefined;
};
/**
* Metric for which you want to detect the smallest relative difference.
*/
type EffectMetric = 'addToCartRate' | 'clickThroughRate' | 'conversionRate' | 'purchaseRate';
/**
* Configuration for the smallest difference between test variants you want to detect.
*/
type MinimumDetectableEffect = {
/**
* Smallest difference in an observable metric between variants. For example, to detect a 10% difference between variants, set this value to 0.1.
*/
size: number;
metric: EffectMetric;
};
/**
* Configuration for handling outliers.
*/
type Outliers = {
/**
* Whether to exclude outliers when calculating A/B test results.
*/
exclude?: boolean | undefined;
};
/**
* A/B test configuration.
*/
type ABTestConfiguration = {
featureFilters?: FeatureFilters | undefined;
outliers?: Outliers | undefined;
emptySearch?: EmptySearch | undefined;
minimumDetectableEffect?: MinimumDetectableEffect | undefined;
};
/**
* A/B test status. - `active`. The A/B test is live and search traffic is split between the two variants. - `stopped`. You stopped the A/B test. The A/B test data is still available for analysis. - `expired`. The A/B test was automatically stopped after reaching its end date. - `failed`. Creating the A/B test failed.
*/
type Status = 'active' | 'stopped' | 'expired' | 'failed';
type Currency = {
/**
* Currency code.
*/
currency?: string | undefined;
/**
* Revenue for this currency.
*/
revenue?: number | undefined;
/**
* Mean for this currency.
*/
mean?: number | undefined;
/**
* Standard deviation for this currency.
*/
standardDeviation?: number | undefined;
/**
* The amount of revenue for this currency that was removed after capping purchase amounts to the 95th percentile.
*/
winsorizedAmount?: number | undefined;
};
/**
* Empty searches removed from the A/B test as a result of configuration settings.
*/
type EmptySearchFilter = {
/**
* Number of users removed from the A/B test.
*/
usersCount?: number | undefined;
/**
* Number of tracked searches removed from the A/B test.
*/
trackedSearchesCount?: number | undefined;
};
/**
* Outliers removed from the A/B test as a result of configuration settings.
*/
type OutliersFilter = {
/**
* Number of users removed from the A/B test.
*/
usersCount?: number | undefined;
/**
* Number of tracked searches removed from the A/B test.
*/
trackedSearchesCount?: number | undefined;
};
/**
* A/B test filter effects resulting from configuration settings.
*/
type FilterEffects = {
outliers?: OutliersFilter | undefined;
emptySearch?: EmptySearchFilter | undefined;
};
type Variant = {
/**
* Number of add-to-cart events for this variant.
*/
addToCartCount: number;
/**
* [Add-to-cart rate](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#add-to-cart-rate) for this variant.
*/
addToCartRate?: number | null | undefined;
/**
* [Average click position](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#click-position) for this variant.
*/
averageClickPosition?: number | null | undefined;
/**
* Number of click events for this variant.
*/
clickCount: number;
/**
* [Click-through rate](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#click-through-rate) for this variant.
*/
clickThroughRate?: number | null | undefined;
/**
* Number of click events for this variant.
*/
conversionCount: number;
/**
* [Conversion rate](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#conversion-rate) for this variant.
*/
conversionRate?: number | null | undefined;
/**
* A/B test currencies.
*/
currencies?: {
[key: string]: Currency;
} | undefined;
/**
* Description for this variant.
*/
description?: string | undefined;
/**
* Estimated number of searches required to achieve the desired statistical significance. The A/B test configuration must include a `mininmumDetectableEffect` setting for this number to be included in the response.
*/
estimatedSampleSize?: number | undefined;
filterEffects?: FilterEffects | undefined;
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Number of [searches without results](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#searches-without-results) for this variant.
*/
noResultCount: number | null;
/**
* Number of purchase events for this variant.
*/
purchaseCount: number;
/**
* [Purchase rate](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#purchase-rate) for this variant.
*/
purchaseRate?: number | null | undefined;
/**
* Number of searches for this variant.
*/
searchCount: number | null;
/**
* Number of tracked searches. Tracked searches are search requests where the `clickAnalytics` parameter is true.
*/
trackedSearchCount?: number | undefined;
/**
* Percentage of search requests each variant receives.
*/
trafficPercentage: number;
/**
* Number of users that made searches to this variant.
*/
userCount: number | null;
/**
* Number of users that made tracked searches to this variant.
*/
trackedUserCount: number | null;
};
type ABTest = {
/**
* Unique A/B test identifier.
*/
abTestID: number;
clickSignificance?: number | null | undefined;
conversionSignificance?: number | null | undefined;
addToCartSignificance?: number | null | undefined;
purchaseSignificance?: number | null | undefined;
revenueSignificance?: {
[key: string]: number;
} | null | undefined;
/**
* Date and time when the A/B test was last updated, in RFC 3339 format.
*/
updatedAt: string;
/**
* Date and time when the A/B test was created, in RFC 3339 format.
*/
createdAt: string;
/**
* End date and time of the A/B test, in RFC 3339 format.
*/
endAt: string;
/**
* Date and time when the A/B test was stopped, in RFC 3339 format.
*/
stoppedAt?: string | null | undefined;
/**
* A/B test name.
*/
name: string;
status: Status;
/**
* A/B test variants. The first variant is your _control_ index, typically your production index. The second variant is an index with changed settings that you want to test against the control.
*/
variants: Array<Variant>;
configuration?: ABTestConfiguration | undefined;
};
type ABTestResponse = {
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Unique A/B test identifier.
*/
abTestID: number;
/**
* Unique identifier of a task. A successful API response means that a task was added to a queue. It might not run immediately. You can check the task\'s progress with the [`task` operation](https://www.algolia.com/doc/rest-api/search/get-task) and this task ID.
*/
taskID: number;
};
type AbTestsVariant = {
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Percentage of search requests each variant receives.
*/
trafficPercentage: number;
/**
* Description for this variant.
*/
description?: string | undefined;
};
/**
* Search parameters to add to the test variant. Only use this parameter if the two variants use the same index.
*/
type CustomSearchParams = {
customSearchParameters: Record<string, unknown>;
};
type AbTestsVariantSearchParams = AbTestsVariant & CustomSearchParams;
type AddABTestsVariant = AbTestsVariant | AbTestsVariantSearchParams;
type AddABTestsRequest = {
/**
* A/B test name.
*/
name: string;
/**
* A/B test variants.
*/
variants: Array<AddABTestsVariant>;
/**
* End date and time of the A/B test, in RFC 3339 format.
*/
endAt: string;
};
/**
* A/B test configuration for estimating the sample size and duration using minimum detectable effect.
*/
type EstimateConfiguration = {
featureFilters?: FeatureFilters | undefined;
outliers?: Outliers | undefined;
emptySearch?: EmptySearch | undefined;
minimumDetectableEffect: MinimumDetectableEffect;
};
type EstimateABTestRequest = {
configuration: EstimateConfiguration;
/**
* A/B test variants.
*/
variants: Array<AddABTestsVariant>;
};
type EstimateABTestResponse = {
/**
* Estimated number of days needed to reach the sample sizes required for detecting the configured effect. This value is based on historical traffic.
*/
durationDays?: number | undefined;
/**
* Sample size estimates for each variant. The first element is the control variant. Each element is the estimated number of searches required to achieve the desired statistical significance.
*/
sampleSizes?: Array<number> | undefined;
};
type ListABTestsResponse = {
/**
* The list of A/B tests, null if no A/B tests are configured for this application.
*/
abtests: Array<ABTest> | null;
/**
* Number of A/B tests.
*/
count: number;
/**
* Number of retrievable A/B tests.
*/
total: number;
};
/**
* Properties for the `customDelete` method.
*/
type CustomDeleteProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customGet` method.
*/
type CustomGetProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customPost` method.
*/
type CustomPostProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `customPut` method.
*/
type CustomPutProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `deleteABTest` method.
*/
type DeleteABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
/**
* Properties for the `getABTest` method.
*/
type GetABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
/**
* Properties for the `listABTests` method.
*/
type ListABTestsProps = {
/**
* Position of the first item to return.
*/
offset?: number | undefined;
/**
* Number of items to return.
*/
limit?: number | undefined;
/**
* Index name prefix. Only A/B tests for indices starting with this string are included in the response.
*/
indexPrefix?: string | undefined;
/**
* Index name suffix. Only A/B tests for indices ending with this string are included in the response.
*/
indexSuffix?: string | undefined;
};
/**
* Properties for the `stopABTest` method.
*/
type StopABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
declare const apiClientVersion = "5.48.1";
declare const REGIONS: readonly ["de", "us"];
type Region = (typeof REGIONS)[number];
type RegionOptions = {
region?: Region | undefined;
};
declare function createAbtestingClient({ appId: appIdOption, apiKey: apiKeyOption, authMode, algoliaAgents, region: regionOption, ...options }: CreateClientOptions & RegionOptions): {
transporter: _algolia_client_common.Transporter;
/**
* The `appId` currently in use.
*/
appId: string;
/**
* The `apiKey` currently in use.
*/
apiKey: string;
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache(): Promise<void>;
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
readonly _ua: string;
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment: string, version?: string | undefined): void;
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }: {
apiKey: string;
}): void;
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest: AddABTestsRequest, requestOptions?: RequestOptions): Promise<ABTestResponse>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }: CustomDeleteProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }: CustomGetProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }: CustomPostProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }: CustomPutProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }: DeleteABTestProps, requestOptions?: RequestOptions): Promise<ABTestResponse>;
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest: EstimateABTestRequest, requestOptions?: RequestOptions): Promise<EstimateABTestResponse>;
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }: GetABTestProps, requestOptions?: RequestOptions): Promise<ABTest>;
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix }?: ListABTestsProps, requestOptions?: RequestOptions | undefined): Promise<ListABTestsResponse>;
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }: StopABTestProps, requestOptions?: RequestOptions): Promise<ABTestResponse>;
};
/**
* Error.
*/
type ErrorBase = Record<string, any> & {
message?: string | undefined;
};
type AbtestingClient = ReturnType<typeof createAbtestingClient>;
declare function abtestingClient(appId: string, apiKey: string, region?: Region | undefined, options?: ClientOptions | undefined): AbtestingClient;
export { type ABTest, type ABTestConfiguration, type ABTestResponse, type AbTestsVariant, type AbTestsVariantSearchParams, type AbtestingClient, type AddABTestsRequest, type AddABTestsVariant, type Currency, type CustomDeleteProps, type CustomGetProps, type CustomPostProps, type CustomPutProps, type CustomSearchParams, type DeleteABTestProps, type EffectMetric, type EmptySearch, type EmptySearchFilter, type ErrorBase, type EstimateABTestRequest, type EstimateABTestResponse, type EstimateConfiguration, type FeatureFilters, type FilterEffects, type GetABTestProps, type ListABTestsProps, type ListABTestsResponse, type MinimumDetectableEffect, type Outliers, type OutliersFilter, type Region, type RegionOptions, type Status, type StopABTestProps, type Variant, abtestingClient, apiClientVersion };
+377
View File
@@ -0,0 +1,377 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/abtestingClient.ts
var abtestingClient_exports = {};
__export(abtestingClient_exports, {
REGIONS: () => REGIONS,
apiClientVersion: () => apiClientVersion,
createAbtestingClient: () => createAbtestingClient
});
module.exports = __toCommonJS(abtestingClient_exports);
var import_client_common = require("@algolia/client-common");
var apiClientVersion = "5.48.1";
var REGIONS = ["de", "us"];
function getDefaultHosts(region) {
const url = !region ? "analytics.algolia.com" : "analytics.{region}.algolia.com".replace("{region}", region);
return [{ url, accept: "readWrite", protocol: "https" }];
}
function createAbtestingClient({
appId: appIdOption,
apiKey: apiKeyOption,
authMode,
algoliaAgents,
region: regionOption,
...options
}) {
const auth = (0, import_client_common.createAuth)(appIdOption, apiKeyOption, authMode);
const transporter = (0, import_client_common.createTransporter)({
hosts: getDefaultHosts(regionOption),
...options,
algoliaAgent: (0, import_client_common.getAlgoliaAgent)({
algoliaAgents,
client: "Abtesting",
version: apiClientVersion
}),
baseHeaders: {
"content-type": "text/plain",
...auth.headers(),
...options.baseHeaders
},
baseQueryParameters: {
...auth.queryParameters(),
...options.baseQueryParameters
}
});
return {
transporter,
/**
* The `appId` currently in use.
*/
appId: appIdOption,
/**
* The `apiKey` currently in use.
*/
apiKey: apiKeyOption,
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache() {
return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => void 0);
},
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
get _ua() {
return transporter.algoliaAgent.value;
},
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment, version) {
transporter.algoliaAgent.add({ segment, version });
},
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }) {
if (!authMode || authMode === "WithinHeaders") {
transporter.baseHeaders["x-algolia-api-key"] = apiKey;
} else {
transporter.baseQueryParameters["x-algolia-api-key"] = apiKey;
}
},
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest, requestOptions) {
if (!addABTestsRequest) {
throw new Error("Parameter `addABTestsRequest` is required when calling `addABTests`.");
}
if (!addABTestsRequest.name) {
throw new Error("Parameter `addABTestsRequest.name` is required when calling `addABTests`.");
}
if (!addABTestsRequest.variants) {
throw new Error("Parameter `addABTestsRequest.variants` is required when calling `addABTests`.");
}
if (!addABTestsRequest.endAt) {
throw new Error("Parameter `addABTestsRequest.endAt` is required when calling `addABTests`.");
}
const requestPath = "/2/abtests";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: addABTestsRequest
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customDelete`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customGet`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPost`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPut`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "PUT",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `deleteABTest`.");
}
const requestPath = "/2/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest, requestOptions) {
if (!estimateABTestRequest) {
throw new Error("Parameter `estimateABTestRequest` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.configuration) {
throw new Error("Parameter `estimateABTestRequest.configuration` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.variants) {
throw new Error("Parameter `estimateABTestRequest.variants` is required when calling `estimateABTest`.");
}
const requestPath = "/2/abtests/estimate";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: estimateABTestRequest
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `getABTest`.");
}
const requestPath = "/2/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix } = {}, requestOptions = void 0) {
const requestPath = "/2/abtests";
const headers = {};
const queryParameters = {};
if (offset !== void 0) {
queryParameters["offset"] = offset.toString();
}
if (limit !== void 0) {
queryParameters["limit"] = limit.toString();
}
if (indexPrefix !== void 0) {
queryParameters["indexPrefix"] = indexPrefix.toString();
}
if (indexSuffix !== void 0) {
queryParameters["indexSuffix"] = indexSuffix.toString();
}
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `stopABTest`.");
}
const requestPath = "/2/abtests/{id}/stop".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
}
};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
REGIONS,
apiClientVersion,
createAbtestingClient
});
//# sourceMappingURL=abtestingClient.cjs.map
File diff suppressed because one or more lines are too long
+350
View File
@@ -0,0 +1,350 @@
// src/abtestingClient.ts
import { createAuth, createTransporter, getAlgoliaAgent } from "@algolia/client-common";
var apiClientVersion = "5.48.1";
var REGIONS = ["de", "us"];
function getDefaultHosts(region) {
const url = !region ? "analytics.algolia.com" : "analytics.{region}.algolia.com".replace("{region}", region);
return [{ url, accept: "readWrite", protocol: "https" }];
}
function createAbtestingClient({
appId: appIdOption,
apiKey: apiKeyOption,
authMode,
algoliaAgents,
region: regionOption,
...options
}) {
const auth = createAuth(appIdOption, apiKeyOption, authMode);
const transporter = createTransporter({
hosts: getDefaultHosts(regionOption),
...options,
algoliaAgent: getAlgoliaAgent({
algoliaAgents,
client: "Abtesting",
version: apiClientVersion
}),
baseHeaders: {
"content-type": "text/plain",
...auth.headers(),
...options.baseHeaders
},
baseQueryParameters: {
...auth.queryParameters(),
...options.baseQueryParameters
}
});
return {
transporter,
/**
* The `appId` currently in use.
*/
appId: appIdOption,
/**
* The `apiKey` currently in use.
*/
apiKey: apiKeyOption,
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache() {
return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => void 0);
},
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
get _ua() {
return transporter.algoliaAgent.value;
},
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment, version) {
transporter.algoliaAgent.add({ segment, version });
},
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }) {
if (!authMode || authMode === "WithinHeaders") {
transporter.baseHeaders["x-algolia-api-key"] = apiKey;
} else {
transporter.baseQueryParameters["x-algolia-api-key"] = apiKey;
}
},
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest, requestOptions) {
if (!addABTestsRequest) {
throw new Error("Parameter `addABTestsRequest` is required when calling `addABTests`.");
}
if (!addABTestsRequest.name) {
throw new Error("Parameter `addABTestsRequest.name` is required when calling `addABTests`.");
}
if (!addABTestsRequest.variants) {
throw new Error("Parameter `addABTestsRequest.variants` is required when calling `addABTests`.");
}
if (!addABTestsRequest.endAt) {
throw new Error("Parameter `addABTestsRequest.endAt` is required when calling `addABTests`.");
}
const requestPath = "/2/abtests";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: addABTestsRequest
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customDelete`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customGet`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPost`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPut`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "PUT",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `deleteABTest`.");
}
const requestPath = "/2/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest, requestOptions) {
if (!estimateABTestRequest) {
throw new Error("Parameter `estimateABTestRequest` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.configuration) {
throw new Error("Parameter `estimateABTestRequest.configuration` is required when calling `estimateABTest`.");
}
if (!estimateABTestRequest.variants) {
throw new Error("Parameter `estimateABTestRequest.variants` is required when calling `estimateABTest`.");
}
const requestPath = "/2/abtests/estimate";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: estimateABTestRequest
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `getABTest`.");
}
const requestPath = "/2/abtests/{id}".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix } = {}, requestOptions = void 0) {
const requestPath = "/2/abtests";
const headers = {};
const queryParameters = {};
if (offset !== void 0) {
queryParameters["offset"] = offset.toString();
}
if (limit !== void 0) {
queryParameters["limit"] = limit.toString();
}
if (indexPrefix !== void 0) {
queryParameters["indexPrefix"] = indexPrefix.toString();
}
if (indexSuffix !== void 0) {
queryParameters["indexSuffix"] = indexSuffix.toString();
}
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }, requestOptions) {
if (!id) {
throw new Error("Parameter `id` is required when calling `stopABTest`.");
}
const requestPath = "/2/abtests/{id}/stop".replace("{id}", encodeURIComponent(id));
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
}
};
}
export {
REGIONS,
apiClientVersion,
createAbtestingClient
};
//# sourceMappingURL=abtestingClient.js.map
File diff suppressed because one or more lines are too long
+619
View File
@@ -0,0 +1,619 @@
import * as _algolia_client_common from '@algolia/client-common';
import { CreateClientOptions, RequestOptions, ClientOptions } from '@algolia/client-common';
/**
* Configuration for handling empty searches.
*/
type EmptySearch = {
/**
* Whether to exclude empty searches when calculating A/B test results.
*/
exclude?: boolean | undefined;
};
/**
* Configuration of feature-based filters applied to the A/B test population.
*/
type FeatureFilters = {
/**
* Whether to apply Dynamic Re-Ranking feature filters.
*/
dynamicReRanking?: boolean | undefined;
/**
* Whether to apply AI Personalization feature filters.
*/
aiPerso?: boolean | undefined;
/**
* Whether to apply Multi-Signal Re-Ranking feature filters.
*/
multiSignalRanking?: boolean | undefined;
};
/**
* Metric for which you want to detect the smallest relative difference.
*/
type EffectMetric = 'addToCartRate' | 'clickThroughRate' | 'conversionRate' | 'purchaseRate';
/**
* Configuration for the smallest difference between test variants you want to detect.
*/
type MinimumDetectableEffect = {
/**
* Smallest difference in an observable metric between variants. For example, to detect a 10% difference between variants, set this value to 0.1.
*/
size: number;
metric: EffectMetric;
};
/**
* Configuration for handling outliers.
*/
type Outliers = {
/**
* Whether to exclude outliers when calculating A/B test results.
*/
exclude?: boolean | undefined;
};
/**
* A/B test configuration.
*/
type ABTestConfiguration = {
featureFilters?: FeatureFilters | undefined;
outliers?: Outliers | undefined;
emptySearch?: EmptySearch | undefined;
minimumDetectableEffect?: MinimumDetectableEffect | undefined;
};
/**
* A/B test status. - `active`. The A/B test is live and search traffic is split between the two variants. - `stopped`. You stopped the A/B test. The A/B test data is still available for analysis. - `expired`. The A/B test was automatically stopped after reaching its end date. - `failed`. Creating the A/B test failed.
*/
type Status = 'active' | 'stopped' | 'expired' | 'failed';
type Currency = {
/**
* Currency code.
*/
currency?: string | undefined;
/**
* Revenue for this currency.
*/
revenue?: number | undefined;
/**
* Mean for this currency.
*/
mean?: number | undefined;
/**
* Standard deviation for this currency.
*/
standardDeviation?: number | undefined;
/**
* The amount of revenue for this currency that was removed after capping purchase amounts to the 95th percentile.
*/
winsorizedAmount?: number | undefined;
};
/**
* Empty searches removed from the A/B test as a result of configuration settings.
*/
type EmptySearchFilter = {
/**
* Number of users removed from the A/B test.
*/
usersCount?: number | undefined;
/**
* Number of tracked searches removed from the A/B test.
*/
trackedSearchesCount?: number | undefined;
};
/**
* Outliers removed from the A/B test as a result of configuration settings.
*/
type OutliersFilter = {
/**
* Number of users removed from the A/B test.
*/
usersCount?: number | undefined;
/**
* Number of tracked searches removed from the A/B test.
*/
trackedSearchesCount?: number | undefined;
};
/**
* A/B test filter effects resulting from configuration settings.
*/
type FilterEffects = {
outliers?: OutliersFilter | undefined;
emptySearch?: EmptySearchFilter | undefined;
};
type Variant = {
/**
* Number of add-to-cart events for this variant.
*/
addToCartCount: number;
/**
* [Add-to-cart rate](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#add-to-cart-rate) for this variant.
*/
addToCartRate?: number | null | undefined;
/**
* [Average click position](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#click-position) for this variant.
*/
averageClickPosition?: number | null | undefined;
/**
* Number of click events for this variant.
*/
clickCount: number;
/**
* [Click-through rate](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#click-through-rate) for this variant.
*/
clickThroughRate?: number | null | undefined;
/**
* Number of click events for this variant.
*/
conversionCount: number;
/**
* [Conversion rate](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#conversion-rate) for this variant.
*/
conversionRate?: number | null | undefined;
/**
* A/B test currencies.
*/
currencies?: {
[key: string]: Currency;
} | undefined;
/**
* Description for this variant.
*/
description?: string | undefined;
/**
* Estimated number of searches required to achieve the desired statistical significance. The A/B test configuration must include a `mininmumDetectableEffect` setting for this number to be included in the response.
*/
estimatedSampleSize?: number | undefined;
filterEffects?: FilterEffects | undefined;
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Number of [searches without results](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#searches-without-results) for this variant.
*/
noResultCount: number | null;
/**
* Number of purchase events for this variant.
*/
purchaseCount: number;
/**
* [Purchase rate](https://www.algolia.com/doc/guides/search-analytics/concepts/metrics/#purchase-rate) for this variant.
*/
purchaseRate?: number | null | undefined;
/**
* Number of searches for this variant.
*/
searchCount: number | null;
/**
* Number of tracked searches. Tracked searches are search requests where the `clickAnalytics` parameter is true.
*/
trackedSearchCount?: number | undefined;
/**
* Percentage of search requests each variant receives.
*/
trafficPercentage: number;
/**
* Number of users that made searches to this variant.
*/
userCount: number | null;
/**
* Number of users that made tracked searches to this variant.
*/
trackedUserCount: number | null;
};
type ABTest = {
/**
* Unique A/B test identifier.
*/
abTestID: number;
clickSignificance?: number | null | undefined;
conversionSignificance?: number | null | undefined;
addToCartSignificance?: number | null | undefined;
purchaseSignificance?: number | null | undefined;
revenueSignificance?: {
[key: string]: number;
} | null | undefined;
/**
* Date and time when the A/B test was last updated, in RFC 3339 format.
*/
updatedAt: string;
/**
* Date and time when the A/B test was created, in RFC 3339 format.
*/
createdAt: string;
/**
* End date and time of the A/B test, in RFC 3339 format.
*/
endAt: string;
/**
* Date and time when the A/B test was stopped, in RFC 3339 format.
*/
stoppedAt?: string | null | undefined;
/**
* A/B test name.
*/
name: string;
status: Status;
/**
* A/B test variants. The first variant is your _control_ index, typically your production index. The second variant is an index with changed settings that you want to test against the control.
*/
variants: Array<Variant>;
configuration?: ABTestConfiguration | undefined;
};
type ABTestResponse = {
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Unique A/B test identifier.
*/
abTestID: number;
/**
* Unique identifier of a task. A successful API response means that a task was added to a queue. It might not run immediately. You can check the task\'s progress with the [`task` operation](https://www.algolia.com/doc/rest-api/search/get-task) and this task ID.
*/
taskID: number;
};
type AbTestsVariant = {
/**
* Index name of the A/B test variant (case-sensitive).
*/
index: string;
/**
* Percentage of search requests each variant receives.
*/
trafficPercentage: number;
/**
* Description for this variant.
*/
description?: string | undefined;
};
/**
* Search parameters to add to the test variant. Only use this parameter if the two variants use the same index.
*/
type CustomSearchParams = {
customSearchParameters: Record<string, unknown>;
};
type AbTestsVariantSearchParams = AbTestsVariant & CustomSearchParams;
type AddABTestsVariant = AbTestsVariant | AbTestsVariantSearchParams;
type AddABTestsRequest = {
/**
* A/B test name.
*/
name: string;
/**
* A/B test variants.
*/
variants: Array<AddABTestsVariant>;
/**
* End date and time of the A/B test, in RFC 3339 format.
*/
endAt: string;
};
/**
* A/B test configuration for estimating the sample size and duration using minimum detectable effect.
*/
type EstimateConfiguration = {
featureFilters?: FeatureFilters | undefined;
outliers?: Outliers | undefined;
emptySearch?: EmptySearch | undefined;
minimumDetectableEffect: MinimumDetectableEffect;
};
type EstimateABTestRequest = {
configuration: EstimateConfiguration;
/**
* A/B test variants.
*/
variants: Array<AddABTestsVariant>;
};
type EstimateABTestResponse = {
/**
* Estimated number of days needed to reach the sample sizes required for detecting the configured effect. This value is based on historical traffic.
*/
durationDays?: number | undefined;
/**
* Sample size estimates for each variant. The first element is the control variant. Each element is the estimated number of searches required to achieve the desired statistical significance.
*/
sampleSizes?: Array<number> | undefined;
};
type ListABTestsResponse = {
/**
* The list of A/B tests, null if no A/B tests are configured for this application.
*/
abtests: Array<ABTest> | null;
/**
* Number of A/B tests.
*/
count: number;
/**
* Number of retrievable A/B tests.
*/
total: number;
};
/**
* Properties for the `customDelete` method.
*/
type CustomDeleteProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customGet` method.
*/
type CustomGetProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customPost` method.
*/
type CustomPostProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `customPut` method.
*/
type CustomPutProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `deleteABTest` method.
*/
type DeleteABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
/**
* Properties for the `getABTest` method.
*/
type GetABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
/**
* Properties for the `listABTests` method.
*/
type ListABTestsProps = {
/**
* Position of the first item to return.
*/
offset?: number | undefined;
/**
* Number of items to return.
*/
limit?: number | undefined;
/**
* Index name prefix. Only A/B tests for indices starting with this string are included in the response.
*/
indexPrefix?: string | undefined;
/**
* Index name suffix. Only A/B tests for indices ending with this string are included in the response.
*/
indexSuffix?: string | undefined;
};
/**
* Properties for the `stopABTest` method.
*/
type StopABTestProps = {
/**
* Unique A/B test identifier.
*/
id: number;
};
declare const apiClientVersion = "5.48.1";
declare const REGIONS: readonly ["de", "us"];
type Region = (typeof REGIONS)[number];
type RegionOptions = {
region?: Region | undefined;
};
declare function createAbtestingClient({ appId: appIdOption, apiKey: apiKeyOption, authMode, algoliaAgents, region: regionOption, ...options }: CreateClientOptions & RegionOptions): {
transporter: _algolia_client_common.Transporter;
/**
* The `appId` currently in use.
*/
appId: string;
/**
* The `apiKey` currently in use.
*/
apiKey: string;
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache(): Promise<void>;
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
readonly _ua: string;
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment: string, version?: string | undefined): void;
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }: {
apiKey: string;
}): void;
/**
* Creates a new A/B test.
*
* Required API Key ACLs:
* - editSettings
* @param addABTestsRequest - The addABTestsRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addABTests(addABTestsRequest: AddABTestsRequest, requestOptions?: RequestOptions): Promise<ABTestResponse>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }: CustomDeleteProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }: CustomGetProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }: CustomPostProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }: CustomPutProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* Deletes an A/B test by its ID.
*
* Required API Key ACLs:
* - editSettings
* @param deleteABTest - The deleteABTest object.
* @param deleteABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteABTest({ id }: DeleteABTestProps, requestOptions?: RequestOptions): Promise<ABTestResponse>;
/**
* Given the traffic percentage and the expected effect size, this endpoint estimates the sample size and duration of an A/B test based on historical traffic.
*
* Required API Key ACLs:
* - analytics
* @param estimateABTestRequest - The estimateABTestRequest object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
estimateABTest(estimateABTestRequest: EstimateABTestRequest, requestOptions?: RequestOptions): Promise<EstimateABTestResponse>;
/**
* Retrieves the details for an A/B test by its ID.
*
* Required API Key ACLs:
* - analytics
* @param getABTest - The getABTest object.
* @param getABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
getABTest({ id }: GetABTestProps, requestOptions?: RequestOptions): Promise<ABTest>;
/**
* Lists all A/B tests you configured for this application.
*
* Required API Key ACLs:
* - analytics
* @param listABTests - The listABTests object.
* @param listABTests.offset - Position of the first item to return.
* @param listABTests.limit - Number of items to return.
* @param listABTests.indexPrefix - Index name prefix. Only A/B tests for indices starting with this string are included in the response.
* @param listABTests.indexSuffix - Index name suffix. Only A/B tests for indices ending with this string are included in the response.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
listABTests({ offset, limit, indexPrefix, indexSuffix }?: ListABTestsProps, requestOptions?: RequestOptions | undefined): Promise<ListABTestsResponse>;
/**
* Stops an A/B test by its ID. You can\'t restart stopped A/B tests.
*
* Required API Key ACLs:
* - editSettings
* @param stopABTest - The stopABTest object.
* @param stopABTest.id - Unique A/B test identifier.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
stopABTest({ id }: StopABTestProps, requestOptions?: RequestOptions): Promise<ABTestResponse>;
};
/**
* Error.
*/
type ErrorBase = Record<string, any> & {
message?: string | undefined;
};
type AbtestingClient = ReturnType<typeof createAbtestingClient>;
declare function abtestingClient(appId: string, apiKey: string, region?: Region | undefined, options?: ClientOptions | undefined): AbtestingClient;
export { type ABTest, type ABTestConfiguration, type ABTestResponse, type AbTestsVariant, type AbTestsVariantSearchParams, type AbtestingClient, type AddABTestsRequest, type AddABTestsVariant, type Currency, type CustomDeleteProps, type CustomGetProps, type CustomPostProps, type CustomPutProps, type CustomSearchParams, type DeleteABTestProps, type EffectMetric, type EmptySearch, type EmptySearchFilter, type ErrorBase, type EstimateABTestRequest, type EstimateABTestResponse, type EstimateConfiguration, type FeatureFilters, type FilterEffects, type GetABTestProps, type ListABTestsProps, type ListABTestsResponse, type MinimumDetectableEffect, type Outliers, type OutliersFilter, type Region, type RegionOptions, type Status, type StopABTestProps, type Variant, abtestingClient, apiClientVersion };
+1
View File
@@ -0,0 +1 @@
export * from './dist/node';
+1
View File
@@ -0,0 +1 @@
module.exports = require('./dist/builds/node.cjs');
+69
View File
@@ -0,0 +1,69 @@
{
"version": "5.48.1",
"repository": {
"type": "git",
"url": "git+https://github.com/algolia/algoliasearch-client-javascript.git"
},
"homepage": "https://github.com/algolia/algoliasearch-client-javascript/tree/main/packages/client-abtesting#readme",
"type": "module",
"license": "MIT",
"author": "Algolia",
"scripts": {
"build": "yarn clean && yarn tsup && yarn rollup -c rollup.config.js",
"clean": "rm -rf ./dist || true",
"test:bundle": "publint . && attw --pack ."
},
"name": "@algolia/client-abtesting",
"description": "JavaScript client for client-abtesting",
"exports": {
".": {
"node": {
"types": {
"import": "./dist/node.d.ts",
"module": "./dist/node.d.ts",
"require": "./dist/node.d.cts"
},
"import": "./dist/builds/node.js",
"module": "./dist/builds/node.js",
"require": "./dist/builds/node.cjs"
},
"worker": {
"types": "./dist/worker.d.ts",
"default": "./dist/builds/worker.js"
},
"default": {
"types": "./dist/browser.d.ts",
"module": "./dist/builds/browser.js",
"import": "./dist/builds/browser.js",
"default": "./dist/builds/browser.umd.js"
}
},
"./dist/builds/*": "./dist/builds/*.js"
},
"jsdelivr": "./dist/builds/browser.umd.js",
"unpkg": "./dist/builds/browser.umd.js",
"react-native": "./dist/builds/browser.js",
"files": [
"dist",
"index.js",
"index.d.ts"
],
"dependencies": {
"@algolia/client-common": "5.48.1",
"@algolia/requester-browser-xhr": "5.48.1",
"@algolia/requester-fetch": "5.48.1",
"@algolia/requester-node-http": "5.48.1"
},
"devDependencies": {
"@arethetypeswrong/cli": "0.18.2",
"@types/node": "25.1.0",
"publint": "0.3.17",
"rollup": "4.57.1",
"tsup": "8.5.1",
"typescript": "5.9.3"
},
"engines": {
"node": ">= 14.0.0"
},
"gitHead": "4bbb3ce8d4cb7b7ad454352d4835cffead91ee30"
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2013-Present Algolia
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+76
View File
@@ -0,0 +1,76 @@
<p align="center">
<a href="https://www.algolia.com">
<img alt="Algolia for JavaScript" src="https://raw.githubusercontent.com/algolia/algoliasearch-client-common/master/banners/javascript.png" >
</a>
<h4 align="center">The perfect starting point to integrate <a href="https://algolia.com" target="_blank">Algolia</a> within your JavaScript project</h4>
<p align="center">
<a href="https://npmjs.com/package/@algolia/client-analytics"><img src="https://img.shields.io/npm/v/@algolia/client-analytics.svg?style=flat-square" alt="NPM version"></img></a>
<a href="http://npm-stat.com/charts.html?package=@algolia/client-analytics"><img src="https://img.shields.io/npm/dm/@algolia/client-analytics.svg?style=flat-square" alt="NPM downloads"></a>
<a href="https://www.jsdelivr.com/package/npm/@algolia/client-analytics"><img src="https://data.jsdelivr.com/v1/package/npm/@algolia/client-analytics/badge" alt="jsDelivr Downloads"></img></a>
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-green.svg?style=flat-square" alt="License"></a>
</p>
</p>
<p align="center">
<a href="https://www.algolia.com/doc/libraries/sdk/install#javascript" target="_blank">Documentation</a> •
<a href="https://www.algolia.com/doc/guides/building-search-ui/what-is-instantsearch/js/" target="_blank">InstantSearch</a> •
<a href="https://discourse.algolia.com" target="_blank">Community Forum</a> •
<a href="http://stackoverflow.com/questions/tagged/algolia" target="_blank">Stack Overflow</a> •
<a href="https://github.com/algolia/algoliasearch-client-javascript/issues" target="_blank">Report a bug</a> •
<a href="https://alg.li/support" target="_blank">Support</a>
</p>
## ✨ Features
- Thin & **minimal low-level HTTP client** to interact with Algolia's API
- Works both on the **browser** and **node.js**
- **UMD and ESM compatible**, you can use it with any module loader
- Built with TypeScript
## 💡 Getting Started
> [!TIP]
> This API client is already a dependency of [the algoliasearch client](https://www.npmjs.com/package/algoliasearch), you don't need to manually install `@algolia/client-analytics` if you already have `algoliasearch` installed.
To get started, you first need to install @algolia/client-analytics (or any other available API client package).
All of our clients comes with type definition, and are available for both browser and node environments.
### With a package manager
```bash
yarn add @algolia/client-analytics@5.48.1
# or
npm install @algolia/client-analytics@5.48.1
# or
pnpm add @algolia/client-analytics@5.48.1
```
### Without a package manager
Add the following JavaScript snippet to the <head> of your website:
```html
<script src="https://cdn.jsdelivr.net/npm/@algolia/client-analytics@5.48.1/dist/builds/browser.umd.js"></script>
```
### Usage
You can now import the Algolia API client in your project and play with it.
```js
import { analyticsClient } from '@algolia/client-analytics';
const client = analyticsClient('YOUR_APP_ID', 'YOUR_API_KEY');
```
For full documentation, visit the **[Algolia JavaScript API Client](https://www.algolia.com/doc/libraries/sdk/methods/analytics/)**.
## ❓ Troubleshooting
Encountering an issue? Before reaching out to support, we recommend heading to our [FAQ](https://support.algolia.com/hc/en-us/sections/15061037630609-API-Client-FAQs) where you will find answers for the most common issues and gotchas with the client. You can also open [a GitHub issue](https://github.com/algolia/api-clients-automation/issues/new?assignees=&labels=&projects=&template=Bug_report.md)
## 📄 License
The Algolia JavaScript API Client is an open-sourced software licensed under the [MIT license](LICENSE).
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
export * from './dist/node';
+1
View File
@@ -0,0 +1 @@
module.exports = require('./dist/builds/node.cjs');
+69
View File
@@ -0,0 +1,69 @@
{
"version": "5.48.1",
"repository": {
"type": "git",
"url": "git+https://github.com/algolia/algoliasearch-client-javascript.git"
},
"homepage": "https://github.com/algolia/algoliasearch-client-javascript/tree/main/packages/client-analytics#readme",
"type": "module",
"license": "MIT",
"author": "Algolia",
"scripts": {
"build": "yarn clean && yarn tsup && yarn rollup -c rollup.config.js",
"clean": "rm -rf ./dist || true",
"test:bundle": "publint . && attw --pack ."
},
"name": "@algolia/client-analytics",
"description": "JavaScript client for client-analytics",
"exports": {
".": {
"node": {
"types": {
"import": "./dist/node.d.ts",
"module": "./dist/node.d.ts",
"require": "./dist/node.d.cts"
},
"import": "./dist/builds/node.js",
"module": "./dist/builds/node.js",
"require": "./dist/builds/node.cjs"
},
"worker": {
"types": "./dist/worker.d.ts",
"default": "./dist/builds/worker.js"
},
"default": {
"types": "./dist/browser.d.ts",
"module": "./dist/builds/browser.js",
"import": "./dist/builds/browser.js",
"default": "./dist/builds/browser.umd.js"
}
},
"./dist/builds/*": "./dist/builds/*.js"
},
"jsdelivr": "./dist/builds/browser.umd.js",
"unpkg": "./dist/builds/browser.umd.js",
"react-native": "./dist/builds/browser.js",
"files": [
"dist",
"index.js",
"index.d.ts"
],
"dependencies": {
"@algolia/client-common": "5.48.1",
"@algolia/requester-browser-xhr": "5.48.1",
"@algolia/requester-fetch": "5.48.1",
"@algolia/requester-node-http": "5.48.1"
},
"devDependencies": {
"@arethetypeswrong/cli": "0.18.2",
"@types/node": "25.1.0",
"publint": "0.3.17",
"rollup": "4.57.1",
"tsup": "8.5.1",
"typescript": "5.9.3"
},
"engines": {
"node": ">= 14.0.0"
},
"gitHead": "4bbb3ce8d4cb7b7ad454352d4835cffead91ee30"
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2013-Present Algolia
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+706
View File
@@ -0,0 +1,706 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
AlgoliaError: () => AlgoliaError,
ApiError: () => ApiError,
DEFAULT_CONNECT_TIMEOUT_BROWSER: () => DEFAULT_CONNECT_TIMEOUT_BROWSER,
DEFAULT_CONNECT_TIMEOUT_NODE: () => DEFAULT_CONNECT_TIMEOUT_NODE,
DEFAULT_READ_TIMEOUT_BROWSER: () => DEFAULT_READ_TIMEOUT_BROWSER,
DEFAULT_READ_TIMEOUT_NODE: () => DEFAULT_READ_TIMEOUT_NODE,
DEFAULT_WRITE_TIMEOUT_BROWSER: () => DEFAULT_WRITE_TIMEOUT_BROWSER,
DEFAULT_WRITE_TIMEOUT_NODE: () => DEFAULT_WRITE_TIMEOUT_NODE,
DeserializationError: () => DeserializationError,
DetailedApiError: () => DetailedApiError,
ErrorWithStackTrace: () => ErrorWithStackTrace,
IndexAlreadyExistsError: () => IndexAlreadyExistsError,
IndexNotFoundError: () => IndexNotFoundError,
IndicesInSameAppError: () => IndicesInSameAppError,
LogLevelEnum: () => LogLevelEnum,
RetryError: () => RetryError,
createAlgoliaAgent: () => createAlgoliaAgent,
createAuth: () => createAuth,
createBrowserLocalStorageCache: () => createBrowserLocalStorageCache,
createFallbackableCache: () => createFallbackableCache,
createIterablePromise: () => createIterablePromise,
createMemoryCache: () => createMemoryCache,
createNullCache: () => createNullCache,
createNullLogger: () => createNullLogger,
createStatefulHost: () => createStatefulHost,
createTransporter: () => createTransporter,
deserializeFailure: () => deserializeFailure,
deserializeSuccess: () => deserializeSuccess,
getAlgoliaAgent: () => getAlgoliaAgent,
isNetworkError: () => isNetworkError,
isRetryable: () => isRetryable,
isSuccess: () => isSuccess,
serializeData: () => serializeData,
serializeHeaders: () => serializeHeaders,
serializeQueryParameters: () => serializeQueryParameters,
serializeUrl: () => serializeUrl,
shuffle: () => shuffle,
stackFrameWithoutCredentials: () => stackFrameWithoutCredentials,
stackTraceWithoutCredentials: () => stackTraceWithoutCredentials
});
module.exports = __toCommonJS(src_exports);
// src/cache/createBrowserLocalStorageCache.ts
function createBrowserLocalStorageCache(options) {
let storage;
const namespaceKey = `algolia-client-js-${options.key}`;
function getStorage() {
if (storage === void 0) {
storage = options.localStorage || window.localStorage;
}
return storage;
}
function getNamespace() {
return JSON.parse(getStorage().getItem(namespaceKey) || "{}");
}
function setNamespace(namespace) {
getStorage().setItem(namespaceKey, JSON.stringify(namespace));
}
function removeOutdatedCacheItems() {
const timeToLive = options.timeToLive ? options.timeToLive * 1e3 : null;
const namespace = getNamespace();
const filteredNamespaceWithoutOldFormattedCacheItems = Object.fromEntries(
Object.entries(namespace).filter(([, cacheItem]) => {
return cacheItem.timestamp !== void 0;
})
);
setNamespace(filteredNamespaceWithoutOldFormattedCacheItems);
if (!timeToLive) {
return;
}
const filteredNamespaceWithoutExpiredItems = Object.fromEntries(
Object.entries(filteredNamespaceWithoutOldFormattedCacheItems).filter(([, cacheItem]) => {
const currentTimestamp = (/* @__PURE__ */ new Date()).getTime();
const isExpired = cacheItem.timestamp + timeToLive < currentTimestamp;
return !isExpired;
})
);
setNamespace(filteredNamespaceWithoutExpiredItems);
}
return {
get(key, defaultValue, events = {
miss: () => Promise.resolve()
}) {
return Promise.resolve().then(() => {
removeOutdatedCacheItems();
return getNamespace()[JSON.stringify(key)];
}).then((value) => {
return Promise.all([value ? value.value : defaultValue(), value !== void 0]);
}).then(([value, exists]) => {
return Promise.all([value, exists || events.miss(value)]);
}).then(([value]) => value);
},
set(key, value) {
return Promise.resolve().then(() => {
const namespace = getNamespace();
namespace[JSON.stringify(key)] = {
timestamp: (/* @__PURE__ */ new Date()).getTime(),
value
};
getStorage().setItem(namespaceKey, JSON.stringify(namespace));
return value;
});
},
delete(key) {
return Promise.resolve().then(() => {
const namespace = getNamespace();
delete namespace[JSON.stringify(key)];
getStorage().setItem(namespaceKey, JSON.stringify(namespace));
});
},
clear() {
return Promise.resolve().then(() => {
getStorage().removeItem(namespaceKey);
});
}
};
}
// src/cache/createNullCache.ts
function createNullCache() {
return {
get(_key, defaultValue, events = {
miss: () => Promise.resolve()
}) {
const value = defaultValue();
return value.then((result) => Promise.all([result, events.miss(result)])).then(([result]) => result);
},
set(_key, value) {
return Promise.resolve(value);
},
delete(_key) {
return Promise.resolve();
},
clear() {
return Promise.resolve();
}
};
}
// src/cache/createFallbackableCache.ts
function createFallbackableCache(options) {
const caches = [...options.caches];
const current = caches.shift();
if (current === void 0) {
return createNullCache();
}
return {
get(key, defaultValue, events = {
miss: () => Promise.resolve()
}) {
return current.get(key, defaultValue, events).catch(() => {
return createFallbackableCache({ caches }).get(key, defaultValue, events);
});
},
set(key, value) {
return current.set(key, value).catch(() => {
return createFallbackableCache({ caches }).set(key, value);
});
},
delete(key) {
return current.delete(key).catch(() => {
return createFallbackableCache({ caches }).delete(key);
});
},
clear() {
return current.clear().catch(() => {
return createFallbackableCache({ caches }).clear();
});
}
};
}
// src/cache/createMemoryCache.ts
function createMemoryCache(options = { serializable: true }) {
let cache = {};
return {
get(key, defaultValue, events = {
miss: () => Promise.resolve()
}) {
const keyAsString = JSON.stringify(key);
if (keyAsString in cache) {
return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]);
}
const promise = defaultValue();
return promise.then((value) => events.miss(value)).then(() => promise);
},
set(key, value) {
cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value;
return Promise.resolve(value);
},
delete(key) {
delete cache[JSON.stringify(key)];
return Promise.resolve();
},
clear() {
cache = {};
return Promise.resolve();
}
};
}
// src/constants.ts
var DEFAULT_CONNECT_TIMEOUT_BROWSER = 1e3;
var DEFAULT_READ_TIMEOUT_BROWSER = 2e3;
var DEFAULT_WRITE_TIMEOUT_BROWSER = 3e4;
var DEFAULT_CONNECT_TIMEOUT_NODE = 2e3;
var DEFAULT_READ_TIMEOUT_NODE = 5e3;
var DEFAULT_WRITE_TIMEOUT_NODE = 3e4;
// src/createAlgoliaAgent.ts
function createAlgoliaAgent(version) {
const algoliaAgent = {
value: `Algolia for JavaScript (${version})`,
add(options) {
const addedAlgoliaAgent = `; ${options.segment}${options.version !== void 0 ? ` (${options.version})` : ""}`;
if (algoliaAgent.value.indexOf(addedAlgoliaAgent) === -1) {
algoliaAgent.value = `${algoliaAgent.value}${addedAlgoliaAgent}`;
}
return algoliaAgent;
}
};
return algoliaAgent;
}
// src/createAuth.ts
function createAuth(appId, apiKey, authMode = "WithinHeaders") {
const credentials = {
"x-algolia-api-key": apiKey,
"x-algolia-application-id": appId
};
return {
headers() {
return authMode === "WithinHeaders" ? credentials : {};
},
queryParameters() {
return authMode === "WithinQueryParameters" ? credentials : {};
}
};
}
// src/createIterablePromise.ts
function createIterablePromise({
func,
validate,
aggregator,
error,
timeout = () => 0
}) {
const retry = (previousResponse) => {
return new Promise((resolve, reject) => {
func(previousResponse).then(async (response) => {
if (aggregator) {
await aggregator(response);
}
if (await validate(response)) {
return resolve(response);
}
if (error && await error.validate(response)) {
return reject(new Error(await error.message(response)));
}
return setTimeout(
() => {
retry(response).then(resolve).catch(reject);
},
await timeout()
);
}).catch((err) => {
reject(err);
});
});
};
return retry();
}
// src/getAlgoliaAgent.ts
function getAlgoliaAgent({ algoliaAgents, client, version }) {
const defaultAlgoliaAgent = createAlgoliaAgent(version).add({
segment: client,
version
});
algoliaAgents.forEach((algoliaAgent) => defaultAlgoliaAgent.add(algoliaAgent));
return defaultAlgoliaAgent;
}
// src/logger/createNullLogger.ts
function createNullLogger() {
return {
debug(_message, _args) {
return Promise.resolve();
},
info(_message, _args) {
return Promise.resolve();
},
error(_message, _args) {
return Promise.resolve();
}
};
}
// src/transporter/createStatefulHost.ts
var EXPIRATION_DELAY = 2 * 60 * 1e3;
function createStatefulHost(host, status = "up") {
const lastUpdate = Date.now();
function isUp() {
return status === "up" || Date.now() - lastUpdate > EXPIRATION_DELAY;
}
function isTimedOut() {
return status === "timed out" && Date.now() - lastUpdate <= EXPIRATION_DELAY;
}
return { ...host, status, lastUpdate, isUp, isTimedOut };
}
// src/transporter/errors.ts
var AlgoliaError = class extends Error {
name = "AlgoliaError";
constructor(message, name) {
super(message);
if (name) {
this.name = name;
}
}
};
var IndexNotFoundError = class extends AlgoliaError {
constructor(indexName) {
super(`${indexName} does not exist`, "IndexNotFoundError");
}
};
var IndicesInSameAppError = class extends AlgoliaError {
constructor() {
super("Indices are in the same application. Use operationIndex instead.", "IndicesInSameAppError");
}
};
var IndexAlreadyExistsError = class extends AlgoliaError {
constructor(indexName) {
super(`${indexName} index already exists.`, "IndexAlreadyExistsError");
}
};
var ErrorWithStackTrace = class extends AlgoliaError {
stackTrace;
constructor(message, stackTrace, name) {
super(message, name);
this.stackTrace = stackTrace;
}
};
var RetryError = class extends ErrorWithStackTrace {
constructor(stackTrace) {
super(
"Unreachable hosts - your application id may be incorrect. If the error persists, please visit our help center https://alg.li/support-unreachable-hosts or reach out to the Algolia Support team: https://alg.li/support",
stackTrace,
"RetryError"
);
}
};
var ApiError = class extends ErrorWithStackTrace {
status;
constructor(message, status, stackTrace, name = "ApiError") {
super(message, stackTrace, name);
this.status = status;
}
};
var DeserializationError = class extends AlgoliaError {
response;
constructor(message, response) {
super(message, "DeserializationError");
this.response = response;
}
};
var DetailedApiError = class extends ApiError {
error;
constructor(message, status, error, stackTrace) {
super(message, status, stackTrace, "DetailedApiError");
this.error = error;
}
};
// src/transporter/helpers.ts
function shuffle(array) {
const shuffledArray = array;
for (let c = array.length - 1; c > 0; c--) {
const b = Math.floor(Math.random() * (c + 1));
const a = array[c];
shuffledArray[c] = array[b];
shuffledArray[b] = a;
}
return shuffledArray;
}
function serializeUrl(host, path, queryParameters) {
const queryParametersAsString = serializeQueryParameters(queryParameters);
let url = `${host.protocol}://${host.url}${host.port ? `:${host.port}` : ""}/${path.charAt(0) === "/" ? path.substring(1) : path}`;
if (queryParametersAsString.length) {
url += `?${queryParametersAsString}`;
}
return url;
}
function serializeQueryParameters(parameters) {
return Object.keys(parameters).filter((key) => parameters[key] !== void 0).sort().map(
(key) => `${key}=${encodeURIComponent(
Object.prototype.toString.call(parameters[key]) === "[object Array]" ? parameters[key].join(",") : parameters[key]
).replace(/\+/g, "%20")}`
).join("&");
}
function serializeData(request, requestOptions) {
if (request.method === "GET" || request.data === void 0 && requestOptions.data === void 0) {
return void 0;
}
const data = Array.isArray(request.data) ? request.data : { ...request.data, ...requestOptions.data };
return JSON.stringify(data);
}
function serializeHeaders(baseHeaders, requestHeaders, requestOptionsHeaders) {
const headers = {
Accept: "application/json",
...baseHeaders,
...requestHeaders,
...requestOptionsHeaders
};
const serializedHeaders = {};
Object.keys(headers).forEach((header) => {
const value = headers[header];
serializedHeaders[header.toLowerCase()] = value;
});
return serializedHeaders;
}
function deserializeSuccess(response) {
try {
return JSON.parse(response.content);
} catch (e) {
throw new DeserializationError(e.message, response);
}
}
function deserializeFailure({ content, status }, stackFrame) {
try {
const parsed = JSON.parse(content);
if ("error" in parsed) {
return new DetailedApiError(parsed.message, status, parsed.error, stackFrame);
}
return new ApiError(parsed.message, status, stackFrame);
} catch {
}
return new ApiError(content, status, stackFrame);
}
// src/transporter/responses.ts
function isNetworkError({ isTimedOut, status }) {
return !isTimedOut && ~~status === 0;
}
function isRetryable({ isTimedOut, status }) {
return isTimedOut || isNetworkError({ isTimedOut, status }) || ~~(status / 100) !== 2 && ~~(status / 100) !== 4;
}
function isSuccess({ status }) {
return ~~(status / 100) === 2;
}
// src/transporter/stackTrace.ts
function stackTraceWithoutCredentials(stackTrace) {
return stackTrace.map((stackFrame) => stackFrameWithoutCredentials(stackFrame));
}
function stackFrameWithoutCredentials(stackFrame) {
const modifiedHeaders = stackFrame.request.headers["x-algolia-api-key"] ? { "x-algolia-api-key": "*****" } : {};
return {
...stackFrame,
request: {
...stackFrame.request,
headers: {
...stackFrame.request.headers,
...modifiedHeaders
}
}
};
}
// src/transporter/createTransporter.ts
function createTransporter({
hosts,
hostsCache,
baseHeaders,
logger,
baseQueryParameters,
algoliaAgent,
timeouts,
requester,
requestsCache,
responsesCache
}) {
async function createRetryableOptions(compatibleHosts) {
const statefulHosts = await Promise.all(
compatibleHosts.map((compatibleHost) => {
return hostsCache.get(compatibleHost, () => {
return Promise.resolve(createStatefulHost(compatibleHost));
});
})
);
const hostsUp = statefulHosts.filter((host) => host.isUp());
const hostsTimedOut = statefulHosts.filter((host) => host.isTimedOut());
const hostsAvailable = [...hostsUp, ...hostsTimedOut];
const compatibleHostsAvailable = hostsAvailable.length > 0 ? hostsAvailable : compatibleHosts;
return {
hosts: compatibleHostsAvailable,
getTimeout(timeoutsCount, baseTimeout) {
const timeoutMultiplier = hostsTimedOut.length === 0 && timeoutsCount === 0 ? 1 : hostsTimedOut.length + 3 + timeoutsCount;
return timeoutMultiplier * baseTimeout;
}
};
}
async function retryableRequest(request, requestOptions, isRead) {
const stackTrace = [];
const data = serializeData(request, requestOptions);
const headers = serializeHeaders(baseHeaders, request.headers, requestOptions.headers);
const dataQueryParameters = request.method === "GET" ? {
...request.data,
...requestOptions.data
} : {};
const queryParameters = {
...baseQueryParameters,
...request.queryParameters,
...dataQueryParameters
};
if (algoliaAgent.value) {
queryParameters["x-algolia-agent"] = algoliaAgent.value;
}
if (requestOptions && requestOptions.queryParameters) {
for (const key of Object.keys(requestOptions.queryParameters)) {
if (!requestOptions.queryParameters[key] || Object.prototype.toString.call(requestOptions.queryParameters[key]) === "[object Object]") {
queryParameters[key] = requestOptions.queryParameters[key];
} else {
queryParameters[key] = requestOptions.queryParameters[key].toString();
}
}
}
let timeoutsCount = 0;
const retry = async (retryableHosts, getTimeout) => {
const host = retryableHosts.pop();
if (host === void 0) {
throw new RetryError(stackTraceWithoutCredentials(stackTrace));
}
const timeout = { ...timeouts, ...requestOptions.timeouts };
const payload = {
data,
headers,
method: request.method,
url: serializeUrl(host, request.path, queryParameters),
connectTimeout: getTimeout(timeoutsCount, timeout.connect),
responseTimeout: getTimeout(timeoutsCount, isRead ? timeout.read : timeout.write)
};
const pushToStackTrace = (response2) => {
const stackFrame = {
request: payload,
response: response2,
host,
triesLeft: retryableHosts.length
};
stackTrace.push(stackFrame);
return stackFrame;
};
const response = await requester.send(payload);
if (isRetryable(response)) {
const stackFrame = pushToStackTrace(response);
if (response.isTimedOut) {
timeoutsCount++;
}
logger.info("Retryable failure", stackFrameWithoutCredentials(stackFrame));
await hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? "timed out" : "down"));
return retry(retryableHosts, getTimeout);
}
if (isSuccess(response)) {
return deserializeSuccess(response);
}
pushToStackTrace(response);
throw deserializeFailure(response, stackTrace);
};
const compatibleHosts = hosts.filter(
(host) => host.accept === "readWrite" || (isRead ? host.accept === "read" : host.accept === "write")
);
const options = await createRetryableOptions(compatibleHosts);
return retry([...options.hosts].reverse(), options.getTimeout);
}
function createRequest(request, requestOptions = {}) {
const createRetryableRequest = () => {
return retryableRequest(request, requestOptions, isRead);
};
const isRead = request.useReadTransporter || request.method === "GET";
const cacheable = requestOptions.cacheable || request.cacheable;
if (cacheable !== true) {
return createRetryableRequest();
}
const key = {
request,
requestOptions,
transporter: {
queryParameters: baseQueryParameters,
headers: baseHeaders
}
};
return responsesCache.get(
key,
() => {
return requestsCache.get(
key,
() => (
/**
* Finally, if there is no request in progress with the same key,
* this `createRetryableRequest()` will actually trigger the
* retryable request.
*/
requestsCache.set(key, createRetryableRequest()).then(
(response) => Promise.all([requestsCache.delete(key), response]),
(err) => Promise.all([requestsCache.delete(key), Promise.reject(err)])
).then(([_, response]) => response)
)
);
},
{
/**
* Of course, once we get this response back from the server, we
* tell response cache to actually store the received response
* to be used later.
*/
miss: (response) => responsesCache.set(key, response)
}
);
}
return {
hostsCache,
requester,
timeouts,
logger,
algoliaAgent,
baseHeaders,
baseQueryParameters,
hosts,
request: createRequest,
requestsCache,
responsesCache
};
}
// src/types/logger.ts
var LogLevelEnum = {
Debug: 1,
Info: 2,
Error: 3
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
AlgoliaError,
ApiError,
DEFAULT_CONNECT_TIMEOUT_BROWSER,
DEFAULT_CONNECT_TIMEOUT_NODE,
DEFAULT_READ_TIMEOUT_BROWSER,
DEFAULT_READ_TIMEOUT_NODE,
DEFAULT_WRITE_TIMEOUT_BROWSER,
DEFAULT_WRITE_TIMEOUT_NODE,
DeserializationError,
DetailedApiError,
ErrorWithStackTrace,
IndexAlreadyExistsError,
IndexNotFoundError,
IndicesInSameAppError,
LogLevelEnum,
RetryError,
createAlgoliaAgent,
createAuth,
createBrowserLocalStorageCache,
createFallbackableCache,
createIterablePromise,
createMemoryCache,
createNullCache,
createNullLogger,
createStatefulHost,
createTransporter,
deserializeFailure,
deserializeSuccess,
getAlgoliaAgent,
isNetworkError,
isRetryable,
isSuccess,
serializeData,
serializeHeaders,
serializeQueryParameters,
serializeUrl,
shuffle,
stackFrameWithoutCredentials,
stackTraceWithoutCredentials
});
//# sourceMappingURL=common.cjs.map
File diff suppressed because one or more lines are too long
+459
View File
@@ -0,0 +1,459 @@
type Cache = {
/**
* Gets the value of the given `key`.
*/
get: <TValue>(key: Record<string, any> | string, defaultValue: () => Promise<TValue>, events?: CacheEvents<TValue> | undefined) => Promise<TValue>;
/**
* Sets the given value with the given `key`.
*/
set: <TValue>(key: Record<string, any> | string, value: TValue) => Promise<TValue>;
/**
* Deletes the given `key`.
*/
delete: (key: Record<string, any> | string) => Promise<void>;
/**
* Clears the cache.
*/
clear: () => Promise<void>;
};
type CacheEvents<TValue> = {
/**
* The callback when the given `key` is missing from the cache.
*/
miss: (value: TValue) => Promise<any>;
};
type MemoryCacheOptions = {
/**
* If keys and values should be serialized using `JSON.stringify`.
*/
serializable?: boolean | undefined;
};
type BrowserLocalStorageOptions = {
/**
* The cache key.
*/
key: string;
/**
* The time to live for each cached item in seconds.
*/
timeToLive?: number | undefined;
/**
* The native local storage implementation.
*/
localStorage?: Storage | undefined;
};
type BrowserLocalStorageCacheItem = {
/**
* The cache item creation timestamp.
*/
timestamp: number;
/**
* The cache item value.
*/
value: any;
};
type FallbackableCacheOptions = {
/**
* List of caches order by priority.
*/
caches: Cache[];
};
type Host = {
/**
* The host URL.
*/
url: string;
/**
* The accepted transporter.
*/
accept: 'read' | 'readWrite' | 'write';
/**
* The protocol of the host URL.
*/
protocol: 'http' | 'https';
/**
* The port of the host URL.
*/
port?: number | undefined;
};
type StatefulHost = Host & {
/**
* The status of the host.
*/
status: 'down' | 'timed out' | 'up';
/**
* The last update of the host status, used to compare with the expiration delay.
*/
lastUpdate: number;
/**
* Returns whether the host is up or not.
*/
isUp: () => boolean;
/**
* Returns whether the host is timed out or not.
*/
isTimedOut: () => boolean;
};
declare const LogLevelEnum: Readonly<Record<string, LogLevelType>>;
type LogLevelType = 1 | 2 | 3;
type Logger = {
/**
* Logs debug messages.
*/
debug: (message: string, args?: any | undefined) => Promise<void>;
/**
* Logs info messages.
*/
info: (message: string, args?: any | undefined) => Promise<void>;
/**
* Logs error messages.
*/
error: (message: string, args?: any | undefined) => Promise<void>;
};
type Headers = Record<string, string>;
type QueryParameters = Record<string, any>;
/**
* The method of the request.
*/
type Method = 'DELETE' | 'GET' | 'PATCH' | 'POST' | 'PUT';
type Request = {
method: Method;
/**
* The path of the REST API to send the request to.
*/
path: string;
queryParameters: QueryParameters;
data?: Array<Record<string, any>> | Record<string, any> | undefined;
headers: Headers;
/**
* If the given request should persist on the cache. Keep in mind,
* that some methods may have this option enabled by default.
*/
cacheable?: boolean | undefined;
/**
* Some POST methods in the Algolia REST API uses the `read` transporter.
* This information is defined at the spec level.
*/
useReadTransporter?: boolean | undefined;
};
type EndRequest = Pick<Request, 'headers' | 'method'> & {
/**
* The full URL of the REST API.
*/
url: string;
/**
* The connection timeout, in milliseconds.
*/
connectTimeout: number;
/**
* The response timeout, in milliseconds.
*/
responseTimeout: number;
data?: string | undefined;
};
type Response = {
/**
* The body of the response.
*/
content: string;
/**
* Whether the API call is timed out or not.
*/
isTimedOut: boolean;
/**
* The HTTP status code of the response.
*/
status: number;
};
type Requester = {
/**
* Sends the given `request` to the server.
*/
send: (request: EndRequest) => Promise<Response>;
};
type RequestOptions = Pick<Request, 'cacheable'> & {
/**
* Custom timeout for the request. Note that, in normal situations
* the given timeout will be applied. But the transporter layer may
* increase this timeout if there is need for it.
*/
timeouts?: Partial<Timeouts> | undefined;
/**
* Custom headers for the request. This headers are
* going to be merged the transporter headers.
*/
headers?: Headers | undefined;
/**
* Custom query parameters for the request. This query parameters are
* going to be merged the transporter query parameters.
*/
queryParameters?: QueryParameters | undefined;
/**
* Custom data for the request. This data is
* going to be merged the transporter data.
*/
data?: Array<Record<string, any>> | Record<string, any> | undefined;
};
type StackFrame = {
request: EndRequest;
response: Response;
host: Host;
triesLeft: number;
};
type AlgoliaAgentOptions = {
/**
* The segment. Usually the integration name.
*/
segment: string;
/**
* The version. Usually the integration version.
*/
version?: string | undefined;
};
type AlgoliaAgent = {
/**
* The raw value of the user agent.
*/
value: string;
/**
* Mutates the current user agent adding the given user agent options.
*/
add: (options: AlgoliaAgentOptions) => AlgoliaAgent;
};
type Timeouts = {
/**
* Timeout in milliseconds before the connection is established.
*/
connect: number;
/**
* Timeout in milliseconds before reading the response on a read request.
*/
read: number;
/**
* Timeout in milliseconds before reading the response on a write request.
*/
write: number;
};
type TransporterOptions = {
/**
* The cache of the hosts. Usually used to persist
* the state of the host when its down.
*/
hostsCache: Cache;
/**
* The logger instance to send events of the transporter.
*/
logger: Logger;
/**
* The underlying requester used. Should differ
* depending of the environment where the client
* will be used.
*/
requester: Requester;
/**
* The cache of the requests. When requests are
* `cacheable`, the returned promised persists
* in this cache to shared in similar requests
* before being resolved.
*/
requestsCache: Cache;
/**
* The cache of the responses. When requests are
* `cacheable`, the returned responses persists
* in this cache to shared in similar requests.
*/
responsesCache: Cache;
/**
* The timeouts used by the requester. The transporter
* layer may increase this timeouts as defined on the
* retry strategy.
*/
timeouts: Timeouts;
/**
* The hosts used by the requester.
*/
hosts: Host[];
/**
* The headers used by the requester. The transporter
* layer may add some extra headers during the request
* for the user agent, and others.
*/
baseHeaders: Headers;
/**
* The query parameters used by the requester. The transporter
* layer may add some extra headers during the request
* for the user agent, and others.
*/
baseQueryParameters: QueryParameters;
/**
* The user agent used. Sent on query parameters.
*/
algoliaAgent: AlgoliaAgent;
};
type Transporter = TransporterOptions & {
/**
* Performs a request.
* The `baseRequest` and `baseRequestOptions` will be merged accordingly.
*/
request: <TResponse>(baseRequest: Request, baseRequestOptions?: RequestOptions) => Promise<TResponse>;
};
type AuthMode = 'WithinHeaders' | 'WithinQueryParameters';
type OverriddenTransporterOptions = 'baseHeaders' | 'baseQueryParameters' | 'hosts';
type CreateClientOptions = Omit<TransporterOptions, OverriddenTransporterOptions | 'algoliaAgent'> & Partial<Pick<TransporterOptions, OverriddenTransporterOptions>> & {
appId: string;
apiKey: string;
authMode?: AuthMode | undefined;
algoliaAgents: AlgoliaAgentOptions[];
};
type ClientOptions = Partial<Omit<CreateClientOptions, 'apiKey' | 'appId'>>;
type IterableOptions<TResponse> = Partial<{
/**
* The function that runs right after the API call has been resolved, allows you to do anything with the response before `validate`.
*/
aggregator: (response: TResponse) => unknown | PromiseLike<unknown>;
/**
* The `validate` condition to throw an error and its message.
*/
error: {
/**
* The function to validate the error condition.
*/
validate: (response: TResponse) => boolean | PromiseLike<boolean>;
/**
* The error message to throw.
*/
message: (response: TResponse) => string | PromiseLike<string>;
};
/**
* The function to decide how long to wait between iterations.
*/
timeout: () => number | PromiseLike<number>;
}>;
type CreateIterablePromise<TResponse> = IterableOptions<TResponse> & {
/**
* The function to run, which returns a promise.
*
* The `previousResponse` parameter (`undefined` on the first call) allows you to build your request with incremental logic, to iterate on `page` or `cursor` for example.
*/
func: (previousResponse?: TResponse | undefined) => Promise<TResponse>;
/**
* The validator function. It receive the resolved return of the API call.
*/
validate: (response: TResponse) => boolean | PromiseLike<boolean>;
};
declare function createBrowserLocalStorageCache(options: BrowserLocalStorageOptions): Cache;
declare function createFallbackableCache(options: FallbackableCacheOptions): Cache;
declare function createMemoryCache(options?: MemoryCacheOptions): Cache;
declare function createNullCache(): Cache;
declare const DEFAULT_CONNECT_TIMEOUT_BROWSER = 1000;
declare const DEFAULT_READ_TIMEOUT_BROWSER = 2000;
declare const DEFAULT_WRITE_TIMEOUT_BROWSER = 30000;
declare const DEFAULT_CONNECT_TIMEOUT_NODE = 2000;
declare const DEFAULT_READ_TIMEOUT_NODE = 5000;
declare const DEFAULT_WRITE_TIMEOUT_NODE = 30000;
declare function createAlgoliaAgent(version: string): AlgoliaAgent;
declare function createAuth(appId: string, apiKey: string, authMode?: AuthMode): {
readonly headers: () => Headers;
readonly queryParameters: () => QueryParameters;
};
/**
* Helper: Returns the promise of a given `func` to iterate on, based on a given `validate` condition.
*
* @param createIterator - The createIterator options.
* @param createIterator.func - The function to run, which returns a promise.
* @param createIterator.validate - The validator function. It receives the resolved return of `func`.
* @param createIterator.aggregator - The function that runs right after the `func` method has been executed, allows you to do anything with the response before `validate`.
* @param createIterator.error - The `validate` condition to throw an error, and its message.
* @param createIterator.timeout - The function to decide how long to wait between iterations.
*/
declare function createIterablePromise<TResponse>({ func, validate, aggregator, error, timeout, }: CreateIterablePromise<TResponse>): Promise<TResponse>;
type GetAlgoliaAgent = {
algoliaAgents: AlgoliaAgentOptions[];
client: string;
version: string;
};
declare function getAlgoliaAgent({ algoliaAgents, client, version }: GetAlgoliaAgent): AlgoliaAgent;
declare function createNullLogger(): Logger;
declare function createStatefulHost(host: Host, status?: StatefulHost['status']): StatefulHost;
declare function createTransporter({ hosts, hostsCache, baseHeaders, logger, baseQueryParameters, algoliaAgent, timeouts, requester, requestsCache, responsesCache, }: TransporterOptions): Transporter;
declare class AlgoliaError extends Error {
name: string;
constructor(message: string, name: string);
}
declare class IndexNotFoundError extends AlgoliaError {
constructor(indexName: string);
}
declare class IndicesInSameAppError extends AlgoliaError {
constructor();
}
declare class IndexAlreadyExistsError extends AlgoliaError {
constructor(indexName: string);
}
declare class ErrorWithStackTrace extends AlgoliaError {
stackTrace: StackFrame[];
constructor(message: string, stackTrace: StackFrame[], name: string);
}
declare class RetryError extends ErrorWithStackTrace {
constructor(stackTrace: StackFrame[]);
}
declare class ApiError extends ErrorWithStackTrace {
status: number;
constructor(message: string, status: number, stackTrace: StackFrame[], name?: string);
}
declare class DeserializationError extends AlgoliaError {
response: Response;
constructor(message: string, response: Response);
}
type DetailedErrorWithMessage = {
message: string;
label: string;
};
type DetailedErrorWithTypeID = {
id: string;
type: string;
name?: string | undefined;
};
type DetailedError = {
code: string;
details?: DetailedErrorWithMessage[] | DetailedErrorWithTypeID[] | undefined;
};
declare class DetailedApiError extends ApiError {
error: DetailedError;
constructor(message: string, status: number, error: DetailedError, stackTrace: StackFrame[]);
}
declare function shuffle<TData>(array: TData[]): TData[];
declare function serializeUrl(host: Host, path: string, queryParameters: QueryParameters): string;
declare function serializeQueryParameters(parameters: QueryParameters): string;
declare function serializeData(request: Request, requestOptions: RequestOptions): string | undefined;
declare function serializeHeaders(baseHeaders: Headers, requestHeaders: Headers, requestOptionsHeaders?: Headers | undefined): Headers;
declare function deserializeSuccess<TObject>(response: Response): TObject;
declare function deserializeFailure({ content, status }: Response, stackFrame: StackFrame[]): Error;
declare function isNetworkError({ isTimedOut, status }: Omit<Response, 'content'>): boolean;
declare function isRetryable({ isTimedOut, status }: Omit<Response, 'content'>): boolean;
declare function isSuccess({ status }: Pick<Response, 'status'>): boolean;
declare function stackTraceWithoutCredentials(stackTrace: StackFrame[]): StackFrame[];
declare function stackFrameWithoutCredentials(stackFrame: StackFrame): StackFrame;
export { type AlgoliaAgent, type AlgoliaAgentOptions, AlgoliaError, ApiError, type AuthMode, type BrowserLocalStorageCacheItem, type BrowserLocalStorageOptions, type Cache, type CacheEvents, type ClientOptions, type CreateClientOptions, type CreateIterablePromise, DEFAULT_CONNECT_TIMEOUT_BROWSER, DEFAULT_CONNECT_TIMEOUT_NODE, DEFAULT_READ_TIMEOUT_BROWSER, DEFAULT_READ_TIMEOUT_NODE, DEFAULT_WRITE_TIMEOUT_BROWSER, DEFAULT_WRITE_TIMEOUT_NODE, DeserializationError, DetailedApiError, type DetailedError, type DetailedErrorWithMessage, type DetailedErrorWithTypeID, type EndRequest, ErrorWithStackTrace, type FallbackableCacheOptions, type GetAlgoliaAgent, type Headers, type Host, IndexAlreadyExistsError, IndexNotFoundError, IndicesInSameAppError, type IterableOptions, LogLevelEnum, type LogLevelType, type Logger, type MemoryCacheOptions, type Method, type QueryParameters, type Request, type RequestOptions, type Requester, type Response, RetryError, type StackFrame, type StatefulHost, type Timeouts, type Transporter, type TransporterOptions, createAlgoliaAgent, createAuth, createBrowserLocalStorageCache, createFallbackableCache, createIterablePromise, createMemoryCache, createNullCache, createNullLogger, createStatefulHost, createTransporter, deserializeFailure, deserializeSuccess, getAlgoliaAgent, isNetworkError, isRetryable, isSuccess, serializeData, serializeHeaders, serializeQueryParameters, serializeUrl, shuffle, stackFrameWithoutCredentials, stackTraceWithoutCredentials };
+459
View File
@@ -0,0 +1,459 @@
type Cache = {
/**
* Gets the value of the given `key`.
*/
get: <TValue>(key: Record<string, any> | string, defaultValue: () => Promise<TValue>, events?: CacheEvents<TValue> | undefined) => Promise<TValue>;
/**
* Sets the given value with the given `key`.
*/
set: <TValue>(key: Record<string, any> | string, value: TValue) => Promise<TValue>;
/**
* Deletes the given `key`.
*/
delete: (key: Record<string, any> | string) => Promise<void>;
/**
* Clears the cache.
*/
clear: () => Promise<void>;
};
type CacheEvents<TValue> = {
/**
* The callback when the given `key` is missing from the cache.
*/
miss: (value: TValue) => Promise<any>;
};
type MemoryCacheOptions = {
/**
* If keys and values should be serialized using `JSON.stringify`.
*/
serializable?: boolean | undefined;
};
type BrowserLocalStorageOptions = {
/**
* The cache key.
*/
key: string;
/**
* The time to live for each cached item in seconds.
*/
timeToLive?: number | undefined;
/**
* The native local storage implementation.
*/
localStorage?: Storage | undefined;
};
type BrowserLocalStorageCacheItem = {
/**
* The cache item creation timestamp.
*/
timestamp: number;
/**
* The cache item value.
*/
value: any;
};
type FallbackableCacheOptions = {
/**
* List of caches order by priority.
*/
caches: Cache[];
};
type Host = {
/**
* The host URL.
*/
url: string;
/**
* The accepted transporter.
*/
accept: 'read' | 'readWrite' | 'write';
/**
* The protocol of the host URL.
*/
protocol: 'http' | 'https';
/**
* The port of the host URL.
*/
port?: number | undefined;
};
type StatefulHost = Host & {
/**
* The status of the host.
*/
status: 'down' | 'timed out' | 'up';
/**
* The last update of the host status, used to compare with the expiration delay.
*/
lastUpdate: number;
/**
* Returns whether the host is up or not.
*/
isUp: () => boolean;
/**
* Returns whether the host is timed out or not.
*/
isTimedOut: () => boolean;
};
declare const LogLevelEnum: Readonly<Record<string, LogLevelType>>;
type LogLevelType = 1 | 2 | 3;
type Logger = {
/**
* Logs debug messages.
*/
debug: (message: string, args?: any | undefined) => Promise<void>;
/**
* Logs info messages.
*/
info: (message: string, args?: any | undefined) => Promise<void>;
/**
* Logs error messages.
*/
error: (message: string, args?: any | undefined) => Promise<void>;
};
type Headers = Record<string, string>;
type QueryParameters = Record<string, any>;
/**
* The method of the request.
*/
type Method = 'DELETE' | 'GET' | 'PATCH' | 'POST' | 'PUT';
type Request = {
method: Method;
/**
* The path of the REST API to send the request to.
*/
path: string;
queryParameters: QueryParameters;
data?: Array<Record<string, any>> | Record<string, any> | undefined;
headers: Headers;
/**
* If the given request should persist on the cache. Keep in mind,
* that some methods may have this option enabled by default.
*/
cacheable?: boolean | undefined;
/**
* Some POST methods in the Algolia REST API uses the `read` transporter.
* This information is defined at the spec level.
*/
useReadTransporter?: boolean | undefined;
};
type EndRequest = Pick<Request, 'headers' | 'method'> & {
/**
* The full URL of the REST API.
*/
url: string;
/**
* The connection timeout, in milliseconds.
*/
connectTimeout: number;
/**
* The response timeout, in milliseconds.
*/
responseTimeout: number;
data?: string | undefined;
};
type Response = {
/**
* The body of the response.
*/
content: string;
/**
* Whether the API call is timed out or not.
*/
isTimedOut: boolean;
/**
* The HTTP status code of the response.
*/
status: number;
};
type Requester = {
/**
* Sends the given `request` to the server.
*/
send: (request: EndRequest) => Promise<Response>;
};
type RequestOptions = Pick<Request, 'cacheable'> & {
/**
* Custom timeout for the request. Note that, in normal situations
* the given timeout will be applied. But the transporter layer may
* increase this timeout if there is need for it.
*/
timeouts?: Partial<Timeouts> | undefined;
/**
* Custom headers for the request. This headers are
* going to be merged the transporter headers.
*/
headers?: Headers | undefined;
/**
* Custom query parameters for the request. This query parameters are
* going to be merged the transporter query parameters.
*/
queryParameters?: QueryParameters | undefined;
/**
* Custom data for the request. This data is
* going to be merged the transporter data.
*/
data?: Array<Record<string, any>> | Record<string, any> | undefined;
};
type StackFrame = {
request: EndRequest;
response: Response;
host: Host;
triesLeft: number;
};
type AlgoliaAgentOptions = {
/**
* The segment. Usually the integration name.
*/
segment: string;
/**
* The version. Usually the integration version.
*/
version?: string | undefined;
};
type AlgoliaAgent = {
/**
* The raw value of the user agent.
*/
value: string;
/**
* Mutates the current user agent adding the given user agent options.
*/
add: (options: AlgoliaAgentOptions) => AlgoliaAgent;
};
type Timeouts = {
/**
* Timeout in milliseconds before the connection is established.
*/
connect: number;
/**
* Timeout in milliseconds before reading the response on a read request.
*/
read: number;
/**
* Timeout in milliseconds before reading the response on a write request.
*/
write: number;
};
type TransporterOptions = {
/**
* The cache of the hosts. Usually used to persist
* the state of the host when its down.
*/
hostsCache: Cache;
/**
* The logger instance to send events of the transporter.
*/
logger: Logger;
/**
* The underlying requester used. Should differ
* depending of the environment where the client
* will be used.
*/
requester: Requester;
/**
* The cache of the requests. When requests are
* `cacheable`, the returned promised persists
* in this cache to shared in similar requests
* before being resolved.
*/
requestsCache: Cache;
/**
* The cache of the responses. When requests are
* `cacheable`, the returned responses persists
* in this cache to shared in similar requests.
*/
responsesCache: Cache;
/**
* The timeouts used by the requester. The transporter
* layer may increase this timeouts as defined on the
* retry strategy.
*/
timeouts: Timeouts;
/**
* The hosts used by the requester.
*/
hosts: Host[];
/**
* The headers used by the requester. The transporter
* layer may add some extra headers during the request
* for the user agent, and others.
*/
baseHeaders: Headers;
/**
* The query parameters used by the requester. The transporter
* layer may add some extra headers during the request
* for the user agent, and others.
*/
baseQueryParameters: QueryParameters;
/**
* The user agent used. Sent on query parameters.
*/
algoliaAgent: AlgoliaAgent;
};
type Transporter = TransporterOptions & {
/**
* Performs a request.
* The `baseRequest` and `baseRequestOptions` will be merged accordingly.
*/
request: <TResponse>(baseRequest: Request, baseRequestOptions?: RequestOptions) => Promise<TResponse>;
};
type AuthMode = 'WithinHeaders' | 'WithinQueryParameters';
type OverriddenTransporterOptions = 'baseHeaders' | 'baseQueryParameters' | 'hosts';
type CreateClientOptions = Omit<TransporterOptions, OverriddenTransporterOptions | 'algoliaAgent'> & Partial<Pick<TransporterOptions, OverriddenTransporterOptions>> & {
appId: string;
apiKey: string;
authMode?: AuthMode | undefined;
algoliaAgents: AlgoliaAgentOptions[];
};
type ClientOptions = Partial<Omit<CreateClientOptions, 'apiKey' | 'appId'>>;
type IterableOptions<TResponse> = Partial<{
/**
* The function that runs right after the API call has been resolved, allows you to do anything with the response before `validate`.
*/
aggregator: (response: TResponse) => unknown | PromiseLike<unknown>;
/**
* The `validate` condition to throw an error and its message.
*/
error: {
/**
* The function to validate the error condition.
*/
validate: (response: TResponse) => boolean | PromiseLike<boolean>;
/**
* The error message to throw.
*/
message: (response: TResponse) => string | PromiseLike<string>;
};
/**
* The function to decide how long to wait between iterations.
*/
timeout: () => number | PromiseLike<number>;
}>;
type CreateIterablePromise<TResponse> = IterableOptions<TResponse> & {
/**
* The function to run, which returns a promise.
*
* The `previousResponse` parameter (`undefined` on the first call) allows you to build your request with incremental logic, to iterate on `page` or `cursor` for example.
*/
func: (previousResponse?: TResponse | undefined) => Promise<TResponse>;
/**
* The validator function. It receive the resolved return of the API call.
*/
validate: (response: TResponse) => boolean | PromiseLike<boolean>;
};
declare function createBrowserLocalStorageCache(options: BrowserLocalStorageOptions): Cache;
declare function createFallbackableCache(options: FallbackableCacheOptions): Cache;
declare function createMemoryCache(options?: MemoryCacheOptions): Cache;
declare function createNullCache(): Cache;
declare const DEFAULT_CONNECT_TIMEOUT_BROWSER = 1000;
declare const DEFAULT_READ_TIMEOUT_BROWSER = 2000;
declare const DEFAULT_WRITE_TIMEOUT_BROWSER = 30000;
declare const DEFAULT_CONNECT_TIMEOUT_NODE = 2000;
declare const DEFAULT_READ_TIMEOUT_NODE = 5000;
declare const DEFAULT_WRITE_TIMEOUT_NODE = 30000;
declare function createAlgoliaAgent(version: string): AlgoliaAgent;
declare function createAuth(appId: string, apiKey: string, authMode?: AuthMode): {
readonly headers: () => Headers;
readonly queryParameters: () => QueryParameters;
};
/**
* Helper: Returns the promise of a given `func` to iterate on, based on a given `validate` condition.
*
* @param createIterator - The createIterator options.
* @param createIterator.func - The function to run, which returns a promise.
* @param createIterator.validate - The validator function. It receives the resolved return of `func`.
* @param createIterator.aggregator - The function that runs right after the `func` method has been executed, allows you to do anything with the response before `validate`.
* @param createIterator.error - The `validate` condition to throw an error, and its message.
* @param createIterator.timeout - The function to decide how long to wait between iterations.
*/
declare function createIterablePromise<TResponse>({ func, validate, aggregator, error, timeout, }: CreateIterablePromise<TResponse>): Promise<TResponse>;
type GetAlgoliaAgent = {
algoliaAgents: AlgoliaAgentOptions[];
client: string;
version: string;
};
declare function getAlgoliaAgent({ algoliaAgents, client, version }: GetAlgoliaAgent): AlgoliaAgent;
declare function createNullLogger(): Logger;
declare function createStatefulHost(host: Host, status?: StatefulHost['status']): StatefulHost;
declare function createTransporter({ hosts, hostsCache, baseHeaders, logger, baseQueryParameters, algoliaAgent, timeouts, requester, requestsCache, responsesCache, }: TransporterOptions): Transporter;
declare class AlgoliaError extends Error {
name: string;
constructor(message: string, name: string);
}
declare class IndexNotFoundError extends AlgoliaError {
constructor(indexName: string);
}
declare class IndicesInSameAppError extends AlgoliaError {
constructor();
}
declare class IndexAlreadyExistsError extends AlgoliaError {
constructor(indexName: string);
}
declare class ErrorWithStackTrace extends AlgoliaError {
stackTrace: StackFrame[];
constructor(message: string, stackTrace: StackFrame[], name: string);
}
declare class RetryError extends ErrorWithStackTrace {
constructor(stackTrace: StackFrame[]);
}
declare class ApiError extends ErrorWithStackTrace {
status: number;
constructor(message: string, status: number, stackTrace: StackFrame[], name?: string);
}
declare class DeserializationError extends AlgoliaError {
response: Response;
constructor(message: string, response: Response);
}
type DetailedErrorWithMessage = {
message: string;
label: string;
};
type DetailedErrorWithTypeID = {
id: string;
type: string;
name?: string | undefined;
};
type DetailedError = {
code: string;
details?: DetailedErrorWithMessage[] | DetailedErrorWithTypeID[] | undefined;
};
declare class DetailedApiError extends ApiError {
error: DetailedError;
constructor(message: string, status: number, error: DetailedError, stackTrace: StackFrame[]);
}
declare function shuffle<TData>(array: TData[]): TData[];
declare function serializeUrl(host: Host, path: string, queryParameters: QueryParameters): string;
declare function serializeQueryParameters(parameters: QueryParameters): string;
declare function serializeData(request: Request, requestOptions: RequestOptions): string | undefined;
declare function serializeHeaders(baseHeaders: Headers, requestHeaders: Headers, requestOptionsHeaders?: Headers | undefined): Headers;
declare function deserializeSuccess<TObject>(response: Response): TObject;
declare function deserializeFailure({ content, status }: Response, stackFrame: StackFrame[]): Error;
declare function isNetworkError({ isTimedOut, status }: Omit<Response, 'content'>): boolean;
declare function isRetryable({ isTimedOut, status }: Omit<Response, 'content'>): boolean;
declare function isSuccess({ status }: Pick<Response, 'status'>): boolean;
declare function stackTraceWithoutCredentials(stackTrace: StackFrame[]): StackFrame[];
declare function stackFrameWithoutCredentials(stackFrame: StackFrame): StackFrame;
export { type AlgoliaAgent, type AlgoliaAgentOptions, AlgoliaError, ApiError, type AuthMode, type BrowserLocalStorageCacheItem, type BrowserLocalStorageOptions, type Cache, type CacheEvents, type ClientOptions, type CreateClientOptions, type CreateIterablePromise, DEFAULT_CONNECT_TIMEOUT_BROWSER, DEFAULT_CONNECT_TIMEOUT_NODE, DEFAULT_READ_TIMEOUT_BROWSER, DEFAULT_READ_TIMEOUT_NODE, DEFAULT_WRITE_TIMEOUT_BROWSER, DEFAULT_WRITE_TIMEOUT_NODE, DeserializationError, DetailedApiError, type DetailedError, type DetailedErrorWithMessage, type DetailedErrorWithTypeID, type EndRequest, ErrorWithStackTrace, type FallbackableCacheOptions, type GetAlgoliaAgent, type Headers, type Host, IndexAlreadyExistsError, IndexNotFoundError, IndicesInSameAppError, type IterableOptions, LogLevelEnum, type LogLevelType, type Logger, type MemoryCacheOptions, type Method, type QueryParameters, type Request, type RequestOptions, type Requester, type Response, RetryError, type StackFrame, type StatefulHost, type Timeouts, type Transporter, type TransporterOptions, createAlgoliaAgent, createAuth, createBrowserLocalStorageCache, createFallbackableCache, createIterablePromise, createMemoryCache, createNullCache, createNullLogger, createStatefulHost, createTransporter, deserializeFailure, deserializeSuccess, getAlgoliaAgent, isNetworkError, isRetryable, isSuccess, serializeData, serializeHeaders, serializeQueryParameters, serializeUrl, shuffle, stackFrameWithoutCredentials, stackTraceWithoutCredentials };
+641
View File
@@ -0,0 +1,641 @@
// src/cache/createBrowserLocalStorageCache.ts
function createBrowserLocalStorageCache(options) {
let storage;
const namespaceKey = `algolia-client-js-${options.key}`;
function getStorage() {
if (storage === void 0) {
storage = options.localStorage || window.localStorage;
}
return storage;
}
function getNamespace() {
return JSON.parse(getStorage().getItem(namespaceKey) || "{}");
}
function setNamespace(namespace) {
getStorage().setItem(namespaceKey, JSON.stringify(namespace));
}
function removeOutdatedCacheItems() {
const timeToLive = options.timeToLive ? options.timeToLive * 1e3 : null;
const namespace = getNamespace();
const filteredNamespaceWithoutOldFormattedCacheItems = Object.fromEntries(
Object.entries(namespace).filter(([, cacheItem]) => {
return cacheItem.timestamp !== void 0;
})
);
setNamespace(filteredNamespaceWithoutOldFormattedCacheItems);
if (!timeToLive) {
return;
}
const filteredNamespaceWithoutExpiredItems = Object.fromEntries(
Object.entries(filteredNamespaceWithoutOldFormattedCacheItems).filter(([, cacheItem]) => {
const currentTimestamp = (/* @__PURE__ */ new Date()).getTime();
const isExpired = cacheItem.timestamp + timeToLive < currentTimestamp;
return !isExpired;
})
);
setNamespace(filteredNamespaceWithoutExpiredItems);
}
return {
get(key, defaultValue, events = {
miss: () => Promise.resolve()
}) {
return Promise.resolve().then(() => {
removeOutdatedCacheItems();
return getNamespace()[JSON.stringify(key)];
}).then((value) => {
return Promise.all([value ? value.value : defaultValue(), value !== void 0]);
}).then(([value, exists]) => {
return Promise.all([value, exists || events.miss(value)]);
}).then(([value]) => value);
},
set(key, value) {
return Promise.resolve().then(() => {
const namespace = getNamespace();
namespace[JSON.stringify(key)] = {
timestamp: (/* @__PURE__ */ new Date()).getTime(),
value
};
getStorage().setItem(namespaceKey, JSON.stringify(namespace));
return value;
});
},
delete(key) {
return Promise.resolve().then(() => {
const namespace = getNamespace();
delete namespace[JSON.stringify(key)];
getStorage().setItem(namespaceKey, JSON.stringify(namespace));
});
},
clear() {
return Promise.resolve().then(() => {
getStorage().removeItem(namespaceKey);
});
}
};
}
// src/cache/createNullCache.ts
function createNullCache() {
return {
get(_key, defaultValue, events = {
miss: () => Promise.resolve()
}) {
const value = defaultValue();
return value.then((result) => Promise.all([result, events.miss(result)])).then(([result]) => result);
},
set(_key, value) {
return Promise.resolve(value);
},
delete(_key) {
return Promise.resolve();
},
clear() {
return Promise.resolve();
}
};
}
// src/cache/createFallbackableCache.ts
function createFallbackableCache(options) {
const caches = [...options.caches];
const current = caches.shift();
if (current === void 0) {
return createNullCache();
}
return {
get(key, defaultValue, events = {
miss: () => Promise.resolve()
}) {
return current.get(key, defaultValue, events).catch(() => {
return createFallbackableCache({ caches }).get(key, defaultValue, events);
});
},
set(key, value) {
return current.set(key, value).catch(() => {
return createFallbackableCache({ caches }).set(key, value);
});
},
delete(key) {
return current.delete(key).catch(() => {
return createFallbackableCache({ caches }).delete(key);
});
},
clear() {
return current.clear().catch(() => {
return createFallbackableCache({ caches }).clear();
});
}
};
}
// src/cache/createMemoryCache.ts
function createMemoryCache(options = { serializable: true }) {
let cache = {};
return {
get(key, defaultValue, events = {
miss: () => Promise.resolve()
}) {
const keyAsString = JSON.stringify(key);
if (keyAsString in cache) {
return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]);
}
const promise = defaultValue();
return promise.then((value) => events.miss(value)).then(() => promise);
},
set(key, value) {
cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value;
return Promise.resolve(value);
},
delete(key) {
delete cache[JSON.stringify(key)];
return Promise.resolve();
},
clear() {
cache = {};
return Promise.resolve();
}
};
}
// src/constants.ts
var DEFAULT_CONNECT_TIMEOUT_BROWSER = 1e3;
var DEFAULT_READ_TIMEOUT_BROWSER = 2e3;
var DEFAULT_WRITE_TIMEOUT_BROWSER = 3e4;
var DEFAULT_CONNECT_TIMEOUT_NODE = 2e3;
var DEFAULT_READ_TIMEOUT_NODE = 5e3;
var DEFAULT_WRITE_TIMEOUT_NODE = 3e4;
// src/createAlgoliaAgent.ts
function createAlgoliaAgent(version) {
const algoliaAgent = {
value: `Algolia for JavaScript (${version})`,
add(options) {
const addedAlgoliaAgent = `; ${options.segment}${options.version !== void 0 ? ` (${options.version})` : ""}`;
if (algoliaAgent.value.indexOf(addedAlgoliaAgent) === -1) {
algoliaAgent.value = `${algoliaAgent.value}${addedAlgoliaAgent}`;
}
return algoliaAgent;
}
};
return algoliaAgent;
}
// src/createAuth.ts
function createAuth(appId, apiKey, authMode = "WithinHeaders") {
const credentials = {
"x-algolia-api-key": apiKey,
"x-algolia-application-id": appId
};
return {
headers() {
return authMode === "WithinHeaders" ? credentials : {};
},
queryParameters() {
return authMode === "WithinQueryParameters" ? credentials : {};
}
};
}
// src/createIterablePromise.ts
function createIterablePromise({
func,
validate,
aggregator,
error,
timeout = () => 0
}) {
const retry = (previousResponse) => {
return new Promise((resolve, reject) => {
func(previousResponse).then(async (response) => {
if (aggregator) {
await aggregator(response);
}
if (await validate(response)) {
return resolve(response);
}
if (error && await error.validate(response)) {
return reject(new Error(await error.message(response)));
}
return setTimeout(
() => {
retry(response).then(resolve).catch(reject);
},
await timeout()
);
}).catch((err) => {
reject(err);
});
});
};
return retry();
}
// src/getAlgoliaAgent.ts
function getAlgoliaAgent({ algoliaAgents, client, version }) {
const defaultAlgoliaAgent = createAlgoliaAgent(version).add({
segment: client,
version
});
algoliaAgents.forEach((algoliaAgent) => defaultAlgoliaAgent.add(algoliaAgent));
return defaultAlgoliaAgent;
}
// src/logger/createNullLogger.ts
function createNullLogger() {
return {
debug(_message, _args) {
return Promise.resolve();
},
info(_message, _args) {
return Promise.resolve();
},
error(_message, _args) {
return Promise.resolve();
}
};
}
// src/transporter/createStatefulHost.ts
var EXPIRATION_DELAY = 2 * 60 * 1e3;
function createStatefulHost(host, status = "up") {
const lastUpdate = Date.now();
function isUp() {
return status === "up" || Date.now() - lastUpdate > EXPIRATION_DELAY;
}
function isTimedOut() {
return status === "timed out" && Date.now() - lastUpdate <= EXPIRATION_DELAY;
}
return { ...host, status, lastUpdate, isUp, isTimedOut };
}
// src/transporter/errors.ts
var AlgoliaError = class extends Error {
name = "AlgoliaError";
constructor(message, name) {
super(message);
if (name) {
this.name = name;
}
}
};
var IndexNotFoundError = class extends AlgoliaError {
constructor(indexName) {
super(`${indexName} does not exist`, "IndexNotFoundError");
}
};
var IndicesInSameAppError = class extends AlgoliaError {
constructor() {
super("Indices are in the same application. Use operationIndex instead.", "IndicesInSameAppError");
}
};
var IndexAlreadyExistsError = class extends AlgoliaError {
constructor(indexName) {
super(`${indexName} index already exists.`, "IndexAlreadyExistsError");
}
};
var ErrorWithStackTrace = class extends AlgoliaError {
stackTrace;
constructor(message, stackTrace, name) {
super(message, name);
this.stackTrace = stackTrace;
}
};
var RetryError = class extends ErrorWithStackTrace {
constructor(stackTrace) {
super(
"Unreachable hosts - your application id may be incorrect. If the error persists, please visit our help center https://alg.li/support-unreachable-hosts or reach out to the Algolia Support team: https://alg.li/support",
stackTrace,
"RetryError"
);
}
};
var ApiError = class extends ErrorWithStackTrace {
status;
constructor(message, status, stackTrace, name = "ApiError") {
super(message, stackTrace, name);
this.status = status;
}
};
var DeserializationError = class extends AlgoliaError {
response;
constructor(message, response) {
super(message, "DeserializationError");
this.response = response;
}
};
var DetailedApiError = class extends ApiError {
error;
constructor(message, status, error, stackTrace) {
super(message, status, stackTrace, "DetailedApiError");
this.error = error;
}
};
// src/transporter/helpers.ts
function shuffle(array) {
const shuffledArray = array;
for (let c = array.length - 1; c > 0; c--) {
const b = Math.floor(Math.random() * (c + 1));
const a = array[c];
shuffledArray[c] = array[b];
shuffledArray[b] = a;
}
return shuffledArray;
}
function serializeUrl(host, path, queryParameters) {
const queryParametersAsString = serializeQueryParameters(queryParameters);
let url = `${host.protocol}://${host.url}${host.port ? `:${host.port}` : ""}/${path.charAt(0) === "/" ? path.substring(1) : path}`;
if (queryParametersAsString.length) {
url += `?${queryParametersAsString}`;
}
return url;
}
function serializeQueryParameters(parameters) {
return Object.keys(parameters).filter((key) => parameters[key] !== void 0).sort().map(
(key) => `${key}=${encodeURIComponent(
Object.prototype.toString.call(parameters[key]) === "[object Array]" ? parameters[key].join(",") : parameters[key]
).replace(/\+/g, "%20")}`
).join("&");
}
function serializeData(request, requestOptions) {
if (request.method === "GET" || request.data === void 0 && requestOptions.data === void 0) {
return void 0;
}
const data = Array.isArray(request.data) ? request.data : { ...request.data, ...requestOptions.data };
return JSON.stringify(data);
}
function serializeHeaders(baseHeaders, requestHeaders, requestOptionsHeaders) {
const headers = {
Accept: "application/json",
...baseHeaders,
...requestHeaders,
...requestOptionsHeaders
};
const serializedHeaders = {};
Object.keys(headers).forEach((header) => {
const value = headers[header];
serializedHeaders[header.toLowerCase()] = value;
});
return serializedHeaders;
}
function deserializeSuccess(response) {
try {
return JSON.parse(response.content);
} catch (e) {
throw new DeserializationError(e.message, response);
}
}
function deserializeFailure({ content, status }, stackFrame) {
try {
const parsed = JSON.parse(content);
if ("error" in parsed) {
return new DetailedApiError(parsed.message, status, parsed.error, stackFrame);
}
return new ApiError(parsed.message, status, stackFrame);
} catch {
}
return new ApiError(content, status, stackFrame);
}
// src/transporter/responses.ts
function isNetworkError({ isTimedOut, status }) {
return !isTimedOut && ~~status === 0;
}
function isRetryable({ isTimedOut, status }) {
return isTimedOut || isNetworkError({ isTimedOut, status }) || ~~(status / 100) !== 2 && ~~(status / 100) !== 4;
}
function isSuccess({ status }) {
return ~~(status / 100) === 2;
}
// src/transporter/stackTrace.ts
function stackTraceWithoutCredentials(stackTrace) {
return stackTrace.map((stackFrame) => stackFrameWithoutCredentials(stackFrame));
}
function stackFrameWithoutCredentials(stackFrame) {
const modifiedHeaders = stackFrame.request.headers["x-algolia-api-key"] ? { "x-algolia-api-key": "*****" } : {};
return {
...stackFrame,
request: {
...stackFrame.request,
headers: {
...stackFrame.request.headers,
...modifiedHeaders
}
}
};
}
// src/transporter/createTransporter.ts
function createTransporter({
hosts,
hostsCache,
baseHeaders,
logger,
baseQueryParameters,
algoliaAgent,
timeouts,
requester,
requestsCache,
responsesCache
}) {
async function createRetryableOptions(compatibleHosts) {
const statefulHosts = await Promise.all(
compatibleHosts.map((compatibleHost) => {
return hostsCache.get(compatibleHost, () => {
return Promise.resolve(createStatefulHost(compatibleHost));
});
})
);
const hostsUp = statefulHosts.filter((host) => host.isUp());
const hostsTimedOut = statefulHosts.filter((host) => host.isTimedOut());
const hostsAvailable = [...hostsUp, ...hostsTimedOut];
const compatibleHostsAvailable = hostsAvailable.length > 0 ? hostsAvailable : compatibleHosts;
return {
hosts: compatibleHostsAvailable,
getTimeout(timeoutsCount, baseTimeout) {
const timeoutMultiplier = hostsTimedOut.length === 0 && timeoutsCount === 0 ? 1 : hostsTimedOut.length + 3 + timeoutsCount;
return timeoutMultiplier * baseTimeout;
}
};
}
async function retryableRequest(request, requestOptions, isRead) {
const stackTrace = [];
const data = serializeData(request, requestOptions);
const headers = serializeHeaders(baseHeaders, request.headers, requestOptions.headers);
const dataQueryParameters = request.method === "GET" ? {
...request.data,
...requestOptions.data
} : {};
const queryParameters = {
...baseQueryParameters,
...request.queryParameters,
...dataQueryParameters
};
if (algoliaAgent.value) {
queryParameters["x-algolia-agent"] = algoliaAgent.value;
}
if (requestOptions && requestOptions.queryParameters) {
for (const key of Object.keys(requestOptions.queryParameters)) {
if (!requestOptions.queryParameters[key] || Object.prototype.toString.call(requestOptions.queryParameters[key]) === "[object Object]") {
queryParameters[key] = requestOptions.queryParameters[key];
} else {
queryParameters[key] = requestOptions.queryParameters[key].toString();
}
}
}
let timeoutsCount = 0;
const retry = async (retryableHosts, getTimeout) => {
const host = retryableHosts.pop();
if (host === void 0) {
throw new RetryError(stackTraceWithoutCredentials(stackTrace));
}
const timeout = { ...timeouts, ...requestOptions.timeouts };
const payload = {
data,
headers,
method: request.method,
url: serializeUrl(host, request.path, queryParameters),
connectTimeout: getTimeout(timeoutsCount, timeout.connect),
responseTimeout: getTimeout(timeoutsCount, isRead ? timeout.read : timeout.write)
};
const pushToStackTrace = (response2) => {
const stackFrame = {
request: payload,
response: response2,
host,
triesLeft: retryableHosts.length
};
stackTrace.push(stackFrame);
return stackFrame;
};
const response = await requester.send(payload);
if (isRetryable(response)) {
const stackFrame = pushToStackTrace(response);
if (response.isTimedOut) {
timeoutsCount++;
}
logger.info("Retryable failure", stackFrameWithoutCredentials(stackFrame));
await hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? "timed out" : "down"));
return retry(retryableHosts, getTimeout);
}
if (isSuccess(response)) {
return deserializeSuccess(response);
}
pushToStackTrace(response);
throw deserializeFailure(response, stackTrace);
};
const compatibleHosts = hosts.filter(
(host) => host.accept === "readWrite" || (isRead ? host.accept === "read" : host.accept === "write")
);
const options = await createRetryableOptions(compatibleHosts);
return retry([...options.hosts].reverse(), options.getTimeout);
}
function createRequest(request, requestOptions = {}) {
const createRetryableRequest = () => {
return retryableRequest(request, requestOptions, isRead);
};
const isRead = request.useReadTransporter || request.method === "GET";
const cacheable = requestOptions.cacheable || request.cacheable;
if (cacheable !== true) {
return createRetryableRequest();
}
const key = {
request,
requestOptions,
transporter: {
queryParameters: baseQueryParameters,
headers: baseHeaders
}
};
return responsesCache.get(
key,
() => {
return requestsCache.get(
key,
() => (
/**
* Finally, if there is no request in progress with the same key,
* this `createRetryableRequest()` will actually trigger the
* retryable request.
*/
requestsCache.set(key, createRetryableRequest()).then(
(response) => Promise.all([requestsCache.delete(key), response]),
(err) => Promise.all([requestsCache.delete(key), Promise.reject(err)])
).then(([_, response]) => response)
)
);
},
{
/**
* Of course, once we get this response back from the server, we
* tell response cache to actually store the received response
* to be used later.
*/
miss: (response) => responsesCache.set(key, response)
}
);
}
return {
hostsCache,
requester,
timeouts,
logger,
algoliaAgent,
baseHeaders,
baseQueryParameters,
hosts,
request: createRequest,
requestsCache,
responsesCache
};
}
// src/types/logger.ts
var LogLevelEnum = {
Debug: 1,
Info: 2,
Error: 3
};
export {
AlgoliaError,
ApiError,
DEFAULT_CONNECT_TIMEOUT_BROWSER,
DEFAULT_CONNECT_TIMEOUT_NODE,
DEFAULT_READ_TIMEOUT_BROWSER,
DEFAULT_READ_TIMEOUT_NODE,
DEFAULT_WRITE_TIMEOUT_BROWSER,
DEFAULT_WRITE_TIMEOUT_NODE,
DeserializationError,
DetailedApiError,
ErrorWithStackTrace,
IndexAlreadyExistsError,
IndexNotFoundError,
IndicesInSameAppError,
LogLevelEnum,
RetryError,
createAlgoliaAgent,
createAuth,
createBrowserLocalStorageCache,
createFallbackableCache,
createIterablePromise,
createMemoryCache,
createNullCache,
createNullLogger,
createStatefulHost,
createTransporter,
deserializeFailure,
deserializeSuccess,
getAlgoliaAgent,
isNetworkError,
isRetryable,
isSuccess,
serializeData,
serializeHeaders,
serializeQueryParameters,
serializeUrl,
shuffle,
stackFrameWithoutCredentials,
stackTraceWithoutCredentials
};
//# sourceMappingURL=common.js.map
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
export * from './dist/common';
+1
View File
@@ -0,0 +1 @@
module.exports = require('./dist/common.cjs');
+51
View File
@@ -0,0 +1,51 @@
{
"name": "@algolia/client-common",
"version": "5.48.1",
"description": "Common package for the Algolia JavaScript API client.",
"repository": {
"type": "git",
"url": "git+https://github.com/algolia/algoliasearch-client-javascript.git"
},
"homepage": "https://github.com/algolia/algoliasearch-client-javascript#readme",
"license": "MIT",
"author": "Algolia",
"type": "module",
"files": [
"dist",
"index.js",
"index.d.ts"
],
"exports": {
".": {
"types": {
"import": "./dist/common.d.ts",
"module": "./dist/common.d.ts",
"require": "./dist/common.d.cts"
},
"import": "./dist/common.js",
"module": "./dist/common.js",
"require": "./dist/common.cjs"
},
"./src/*": "./src/*.ts"
},
"scripts": {
"build": "yarn clean && yarn tsup",
"clean": "rm -rf ./dist || true",
"test": "tsc --noEmit && vitest --run",
"test:bundle": "publint . && attw --pack ."
},
"devDependencies": {
"@arethetypeswrong/cli": "0.18.2",
"@types/node": "24.10.12",
"jsdom": "27.4.0",
"publint": "0.3.17",
"ts-node": "10.9.2",
"tsup": "8.5.1",
"typescript": "5.9.3",
"vitest": "4.0.18"
},
"engines": {
"node": ">= 14.0.0"
},
"gitHead": "4bbb3ce8d4cb7b7ad454352d4835cffead91ee30"
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2013-Present Algolia
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+76
View File
@@ -0,0 +1,76 @@
<p align="center">
<a href="https://www.algolia.com">
<img alt="Algolia for JavaScript" src="https://raw.githubusercontent.com/algolia/algoliasearch-client-common/master/banners/javascript.png" >
</a>
<h4 align="center">The perfect starting point to integrate <a href="https://algolia.com" target="_blank">Algolia</a> within your JavaScript project</h4>
<p align="center">
<a href="https://npmjs.com/package/@algolia/client-insights"><img src="https://img.shields.io/npm/v/@algolia/client-insights.svg?style=flat-square" alt="NPM version"></img></a>
<a href="http://npm-stat.com/charts.html?package=@algolia/client-insights"><img src="https://img.shields.io/npm/dm/@algolia/client-insights.svg?style=flat-square" alt="NPM downloads"></a>
<a href="https://www.jsdelivr.com/package/npm/@algolia/client-insights"><img src="https://data.jsdelivr.com/v1/package/npm/@algolia/client-insights/badge" alt="jsDelivr Downloads"></img></a>
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-green.svg?style=flat-square" alt="License"></a>
</p>
</p>
<p align="center">
<a href="https://www.algolia.com/doc/libraries/sdk/install#javascript" target="_blank">Documentation</a> •
<a href="https://www.algolia.com/doc/guides/building-search-ui/what-is-instantsearch/js/" target="_blank">InstantSearch</a> •
<a href="https://discourse.algolia.com" target="_blank">Community Forum</a> •
<a href="http://stackoverflow.com/questions/tagged/algolia" target="_blank">Stack Overflow</a> •
<a href="https://github.com/algolia/algoliasearch-client-javascript/issues" target="_blank">Report a bug</a> •
<a href="https://alg.li/support" target="_blank">Support</a>
</p>
## ✨ Features
- Thin & **minimal low-level HTTP client** to interact with Algolia's API
- Works both on the **browser** and **node.js**
- **UMD and ESM compatible**, you can use it with any module loader
- Built with TypeScript
## 💡 Getting Started
> [!TIP]
> This API client is already a dependency of [the algoliasearch client](https://www.npmjs.com/package/algoliasearch), you don't need to manually install `@algolia/client-insights` if you already have `algoliasearch` installed.
To get started, you first need to install @algolia/client-insights (or any other available API client package).
All of our clients comes with type definition, and are available for both browser and node environments.
### With a package manager
```bash
yarn add @algolia/client-insights@5.48.1
# or
npm install @algolia/client-insights@5.48.1
# or
pnpm add @algolia/client-insights@5.48.1
```
### Without a package manager
Add the following JavaScript snippet to the <head> of your website:
```html
<script src="https://cdn.jsdelivr.net/npm/@algolia/client-insights@5.48.1/dist/builds/browser.umd.js"></script>
```
### Usage
You can now import the Algolia API client in your project and play with it.
```js
import { insightsClient } from '@algolia/client-insights';
const client = insightsClient('YOUR_APP_ID', 'YOUR_API_KEY');
```
For full documentation, visit the **[Algolia JavaScript API Client](https://www.algolia.com/doc/libraries/sdk/methods/insights/)**.
## ❓ Troubleshooting
Encountering an issue? Before reaching out to support, we recommend heading to our [FAQ](https://support.algolia.com/hc/en-us/sections/15061037630609-API-Client-FAQs) where you will find answers for the most common issues and gotchas with the client. You can also open [a GitHub issue](https://github.com/algolia/api-clients-automation/issues/new?assignees=&labels=&projects=&template=Bug_report.md)
## 📄 License
The Algolia JavaScript API Client is an open-sourced software licensed under the [MIT license](LICENSE).
+682
View File
@@ -0,0 +1,682 @@
import * as _algolia_client_common from '@algolia/client-common';
import { CreateClientOptions, RequestOptions, ClientOptions } from '@algolia/client-common';
/**
* The response of the Insights API.
*/
type EventsResponse = {
/**
* Details about the response, such as error messages.
*/
message?: string | undefined;
/**
* The HTTP status code of the response.
*/
status?: number | undefined;
};
type AddToCartEvent = 'addToCart';
type ConversionEvent = 'conversion';
/**
* Absolute value of the discount for this product, in units of `currency`.
*/
type Discount = number | string;
/**
* Final price of a single product, including any discounts, in units of `currency`.
*/
type Price = number | string;
type ObjectData = {
price?: Price | undefined;
/**
* Quantity of a product that has been purchased or added to the cart. The total purchase value is the sum of `quantity` multiplied with the `price` for each purchased item.
*/
quantity?: number | undefined;
discount?: Discount | undefined;
};
/**
* Total monetary value of this event in units of `currency`. This should be equal to the sum of `price` times `quantity`.
*/
type Value = number | string;
/**
* Use this event to track when users add items to their shopping cart unrelated to a previous Algolia request. For example, if you don\'t use Algolia to build your category pages, use this event. To track add-to-cart events related to Algolia requests, use the \"Added to cart object IDs after search\" event.
*/
type AddedToCartObjectIDs = {
/**
* Event name, up to 64 ASCII characters. Consider naming events consistently—for example, by adopting Segment\'s [object-action](https://segment.com/academy/collecting-data/naming-conventions-for-clean-data/#the-object-action-framework) framework.
*/
eventName: string;
eventType: ConversionEvent;
eventSubtype: AddToCartEvent;
/**
* Index name (case-sensitive) to which the event\'s items belong.
*/
index: string;
/**
* Object IDs of the records that are part of the event.
*/
objectIDs: Array<string>;
/**
* Anonymous or pseudonymous user identifier. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
userToken: string;
/**
* Identifier for authenticated users. When the user signs in, you can get an identifier from your system and send it as `authenticatedUserToken`. This lets you keep using the `userToken` from before the user signed in, while providing a reliable way to identify users across sessions. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
authenticatedUserToken?: string | undefined;
/**
* Three-letter [currency code](https://www.iso.org/iso-4217-currency-codes.html).
*/
currency?: string | undefined;
/**
* Extra information about the records involved in a purchase or add-to-cart event. If specified, it must have the same length as `objectIDs`.
*/
objectData?: Array<ObjectData> | undefined;
/**
* Timestamp of the event, measured in milliseconds since the Unix epoch. Must be no older than 30 days. If not provided, we use the time at which the request was received.
*/
timestamp?: number | undefined;
value?: Value | undefined;
};
type ObjectDataAfterSearch = {
/**
* Unique identifier for a search query, used to track purchase events with multiple records that originate from different searches.
*/
queryID?: string | undefined;
price?: Price | undefined;
/**
* Quantity of a product that has been purchased or added to the cart. The total purchase value is the sum of `quantity` multiplied with the `price` for each purchased item.
*/
quantity?: number | undefined;
discount?: Discount | undefined;
};
/**
* Use this event to track when users add items to their shopping cart after a previous Algolia request. If you\'re building your category pages with Algolia, you\'ll also use this event.
*/
type AddedToCartObjectIDsAfterSearch = {
/**
* Event name, up to 64 ASCII characters. Consider naming events consistently—for example, by adopting Segment\'s [object-action](https://segment.com/academy/collecting-data/naming-conventions-for-clean-data/#the-object-action-framework) framework.
*/
eventName: string;
eventType: ConversionEvent;
eventSubtype: AddToCartEvent;
/**
* Index name (case-sensitive) to which the event\'s items belong.
*/
index: string;
/**
* Unique identifier for a search query. The query ID is required for events related to search or browse requests. If you add `clickAnalytics: true` as a search request parameter, the query ID is included in the API response.
*/
queryID: string;
/**
* Object IDs of the records that are part of the event.
*/
objectIDs: Array<string>;
/**
* Anonymous or pseudonymous user identifier. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
userToken: string;
/**
* Identifier for authenticated users. When the user signs in, you can get an identifier from your system and send it as `authenticatedUserToken`. This lets you keep using the `userToken` from before the user signed in, while providing a reliable way to identify users across sessions. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
authenticatedUserToken?: string | undefined;
/**
* Three-letter [currency code](https://www.iso.org/iso-4217-currency-codes.html).
*/
currency?: string | undefined;
/**
* Extra information about the records involved in a purchase or add-to-cart events. If provided, it must be the same length as `objectIDs`.
*/
objectData?: Array<ObjectDataAfterSearch> | undefined;
/**
* Timestamp of the event, measured in milliseconds since the Unix epoch. Must be no older than 30 days. If not provided, we use the time at which the request was received.
*/
timestamp?: number | undefined;
value?: Value | undefined;
};
type ClickEvent = 'click';
/**
* Use this event to track when users click facet filters in your user interface.
*/
type ClickedFilters = {
/**
* Event name, up to 64 ASCII characters. Consider naming events consistently—for example, by adopting Segment\'s [object-action](https://segment.com/academy/collecting-data/naming-conventions-for-clean-data/#the-object-action-framework) framework.
*/
eventName: string;
eventType: ClickEvent;
/**
* Index name (case-sensitive) to which the event\'s items belong.
*/
index: string;
/**
* Applied facet filters. Facet filters are `facet:value` pairs. Facet values must be URL-encoded, such as, `discount:10%25`.
*/
filters: Array<string>;
/**
* Anonymous or pseudonymous user identifier. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
userToken: string;
/**
* Identifier for authenticated users. When the user signs in, you can get an identifier from your system and send it as `authenticatedUserToken`. This lets you keep using the `userToken` from before the user signed in, while providing a reliable way to identify users across sessions. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
authenticatedUserToken?: string | undefined;
/**
* Timestamp of the event, measured in milliseconds since the Unix epoch. Must be no older than 30 days. If not provided, we use the time at which the request was received.
*/
timestamp?: number | undefined;
};
/**
* Use this event to track when users click items unrelated to a previous Algolia request. For example, if you don\'t use Algolia to build your category pages, use this event. To track click events related to Algolia requests, use the \"Clicked object IDs after search\" event.
*/
type ClickedObjectIDs = {
/**
* Event name, up to 64 ASCII characters. Consider naming events consistently—for example, by adopting Segment\'s [object-action](https://segment.com/academy/collecting-data/naming-conventions-for-clean-data/#the-object-action-framework) framework.
*/
eventName: string;
eventType: ClickEvent;
/**
* Index name (case-sensitive) to which the event\'s items belong.
*/
index: string;
/**
* Object IDs of the records that are part of the event.
*/
objectIDs: Array<string>;
/**
* Anonymous or pseudonymous user identifier. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
userToken: string;
/**
* Identifier for authenticated users. When the user signs in, you can get an identifier from your system and send it as `authenticatedUserToken`. This lets you keep using the `userToken` from before the user signed in, while providing a reliable way to identify users across sessions. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
authenticatedUserToken?: string | undefined;
/**
* Timestamp of the event, measured in milliseconds since the Unix epoch. Must be no older than 30 days. If not provided, we use the time at which the request was received.
*/
timestamp?: number | undefined;
};
/**
* Click event after an Algolia request. Use this event to track when users click items in the search results. If you\'re building your category pages with Algolia, you\'ll also use this event.
*/
type ClickedObjectIDsAfterSearch = {
/**
* Event name, up to 64 ASCII characters. Consider naming events consistently—for example, by adopting Segment\'s [object-action](https://segment.com/academy/collecting-data/naming-conventions-for-clean-data/#the-object-action-framework) framework.
*/
eventName: string;
eventType: ClickEvent;
/**
* Index name (case-sensitive) to which the event\'s items belong.
*/
index: string;
/**
* Object IDs of the records that are part of the event.
*/
objectIDs: Array<string>;
/**
* Position of the clicked item the search results. You must provide 1 `position` for each `objectID`.
*/
positions: Array<number>;
/**
* Unique identifier for a search query. The query ID is required for events related to search or browse requests. If you add `clickAnalytics: true` as a search request parameter, the query ID is included in the API response.
*/
queryID: string;
/**
* Anonymous or pseudonymous user identifier. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
userToken: string;
/**
* Identifier for authenticated users. When the user signs in, you can get an identifier from your system and send it as `authenticatedUserToken`. This lets you keep using the `userToken` from before the user signed in, while providing a reliable way to identify users across sessions. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
authenticatedUserToken?: string | undefined;
/**
* Timestamp of the event, measured in milliseconds since the Unix epoch. Must be no older than 30 days. If not provided, we use the time at which the request was received.
*/
timestamp?: number | undefined;
};
type ConvertedFilters = {
/**
* Event name, up to 64 ASCII characters. Consider naming events consistently—for example, by adopting Segment\'s [object-action](https://segment.com/academy/collecting-data/naming-conventions-for-clean-data/#the-object-action-framework) framework.
*/
eventName: string;
eventType: ConversionEvent;
/**
* Index name (case-sensitive) to which the event\'s items belong.
*/
index: string;
/**
* Applied facet filters. Facet filters are `facet:value` pairs. Facet values must be URL-encoded, such as, `discount:10%25`.
*/
filters: Array<string>;
/**
* Anonymous or pseudonymous user identifier. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
userToken: string;
/**
* Identifier for authenticated users. When the user signs in, you can get an identifier from your system and send it as `authenticatedUserToken`. This lets you keep using the `userToken` from before the user signed in, while providing a reliable way to identify users across sessions. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
authenticatedUserToken?: string | undefined;
/**
* Timestamp of the event, measured in milliseconds since the Unix epoch. Must be no older than 30 days. If not provided, we use the time at which the request was received.
*/
timestamp?: number | undefined;
};
/**
* Use this event to track when users convert on items unrelated to a previous Algolia request. For example, if you don\'t use Algolia to build your category pages, use this event. To track conversion events related to Algolia requests, use the \"Converted object IDs after search\" event.
*/
type ConvertedObjectIDs = {
/**
* Event name, up to 64 ASCII characters. Consider naming events consistently—for example, by adopting Segment\'s [object-action](https://segment.com/academy/collecting-data/naming-conventions-for-clean-data/#the-object-action-framework) framework.
*/
eventName: string;
eventType: ConversionEvent;
/**
* Index name (case-sensitive) to which the event\'s items belong.
*/
index: string;
/**
* Object IDs of the records that are part of the event.
*/
objectIDs: Array<string>;
/**
* Anonymous or pseudonymous user identifier. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
userToken: string;
/**
* Identifier for authenticated users. When the user signs in, you can get an identifier from your system and send it as `authenticatedUserToken`. This lets you keep using the `userToken` from before the user signed in, while providing a reliable way to identify users across sessions. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
authenticatedUserToken?: string | undefined;
/**
* Timestamp of the event, measured in milliseconds since the Unix epoch. Must be no older than 30 days. If not provided, we use the time at which the request was received.
*/
timestamp?: number | undefined;
};
/**
* Use this event to track when users convert after a previous Algolia request. For example, a user clicks on an item in the search results to view the product detail page. Then, the user adds the item to their shopping cart. If you\'re building your category pages with Algolia, you\'ll also use this event.
*/
type ConvertedObjectIDsAfterSearch = {
/**
* Event name, up to 64 ASCII characters. Consider naming events consistently—for example, by adopting Segment\'s [object-action](https://segment.com/academy/collecting-data/naming-conventions-for-clean-data/#the-object-action-framework) framework.
*/
eventName: string;
eventType: ConversionEvent;
/**
* Index name (case-sensitive) to which the event\'s items belong.
*/
index: string;
/**
* Object IDs of the records that are part of the event.
*/
objectIDs: Array<string>;
/**
* Unique identifier for a search query. The query ID is required for events related to search or browse requests. If you add `clickAnalytics: true` as a search request parameter, the query ID is included in the API response.
*/
queryID: string;
/**
* Anonymous or pseudonymous user identifier. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
userToken: string;
/**
* Identifier for authenticated users. When the user signs in, you can get an identifier from your system and send it as `authenticatedUserToken`. This lets you keep using the `userToken` from before the user signed in, while providing a reliable way to identify users across sessions. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
authenticatedUserToken?: string | undefined;
/**
* Timestamp of the event, measured in milliseconds since the Unix epoch. Must be no older than 30 days. If not provided, we use the time at which the request was received.
*/
timestamp?: number | undefined;
};
type PurchaseEvent = 'purchase';
/**
* Use this event to track when users make a purchase unrelated to a previous Algolia request. For example, if you don\'t use Algolia to build your category pages, use this event. To track purchase events related to Algolia requests, use the \"Purchased object IDs after search\" event.
*/
type PurchasedObjectIDs = {
/**
* Event name, up to 64 ASCII characters. Consider naming events consistently—for example, by adopting Segment\'s [object-action](https://segment.com/academy/collecting-data/naming-conventions-for-clean-data/#the-object-action-framework) framework.
*/
eventName: string;
eventType: ConversionEvent;
eventSubtype: PurchaseEvent;
/**
* Index name (case-sensitive) to which the event\'s items belong.
*/
index: string;
/**
* Object IDs of the records that are part of the event.
*/
objectIDs: Array<string>;
/**
* Anonymous or pseudonymous user identifier. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
userToken: string;
/**
* Identifier for authenticated users. When the user signs in, you can get an identifier from your system and send it as `authenticatedUserToken`. This lets you keep using the `userToken` from before the user signed in, while providing a reliable way to identify users across sessions. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
authenticatedUserToken?: string | undefined;
/**
* Three-letter [currency code](https://www.iso.org/iso-4217-currency-codes.html).
*/
currency?: string | undefined;
/**
* Extra information about the records involved in a purchase or add-to-cart event. If specified, it must have the same length as `objectIDs`.
*/
objectData?: Array<ObjectData> | undefined;
/**
* Timestamp of the event, measured in milliseconds since the Unix epoch. Must be no older than 30 days. If not provided, we use the time at which the request was received.
*/
timestamp?: number | undefined;
value?: Value | undefined;
};
/**
* Use this event to track when users make a purchase after a previous Algolia request. If you\'re building your category pages with Algolia, you\'ll also use this event.
*/
type PurchasedObjectIDsAfterSearch = {
/**
* Event name, up to 64 ASCII characters. Consider naming events consistently—for example, by adopting Segment\'s [object-action](https://segment.com/academy/collecting-data/naming-conventions-for-clean-data/#the-object-action-framework) framework.
*/
eventName: string;
eventType: ConversionEvent;
eventSubtype: PurchaseEvent;
/**
* Index name (case-sensitive) to which the event\'s items belong.
*/
index: string;
/**
* Object IDs of the records that are part of the event.
*/
objectIDs: Array<string>;
/**
* Anonymous or pseudonymous user identifier. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
userToken: string;
/**
* Identifier for authenticated users. When the user signs in, you can get an identifier from your system and send it as `authenticatedUserToken`. This lets you keep using the `userToken` from before the user signed in, while providing a reliable way to identify users across sessions. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
authenticatedUserToken?: string | undefined;
/**
* Three-letter [currency code](https://www.iso.org/iso-4217-currency-codes.html).
*/
currency?: string | undefined;
/**
* Extra information about the records involved in a purchase or add-to-cart events. If provided, it must be the same length as `objectIDs`.
*/
objectData: Array<ObjectDataAfterSearch>;
/**
* Timestamp of the event, measured in milliseconds since the Unix epoch. Must be no older than 30 days. If not provided, we use the time at which the request was received.
*/
timestamp?: number | undefined;
value?: Value | undefined;
};
type ViewEvent = 'view';
/**
* Use this method to capture active filters. For example, when browsing a category page, users see content filtered on that specific category.
*/
type ViewedFilters = {
/**
* Event name, up to 64 ASCII characters. Consider naming events consistently—for example, by adopting Segment\'s [object-action](https://segment.com/academy/collecting-data/naming-conventions-for-clean-data/#the-object-action-framework) framework.
*/
eventName: string;
eventType: ViewEvent;
/**
* Index name (case-sensitive) to which the event\'s items belong.
*/
index: string;
/**
* Applied facet filters. Facet filters are `facet:value` pairs. Facet values must be URL-encoded, such as, `discount:10%25`.
*/
filters: Array<string>;
/**
* Anonymous or pseudonymous user identifier. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
userToken: string;
/**
* Identifier for authenticated users. When the user signs in, you can get an identifier from your system and send it as `authenticatedUserToken`. This lets you keep using the `userToken` from before the user signed in, while providing a reliable way to identify users across sessions. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
authenticatedUserToken?: string | undefined;
/**
* Timestamp of the event, measured in milliseconds since the Unix epoch. Must be no older than 30 days. If not provided, we use the time at which the request was received.
*/
timestamp?: number | undefined;
};
/**
* Use this event to track when users viewed items in the search results.
*/
type ViewedObjectIDs = {
/**
* Event name, up to 64 ASCII characters. Consider naming events consistently—for example, by adopting Segment\'s [object-action](https://segment.com/academy/collecting-data/naming-conventions-for-clean-data/#the-object-action-framework) framework.
*/
eventName: string;
eventType: ViewEvent;
/**
* Index name (case-sensitive) to which the event\'s items belong.
*/
index: string;
/**
* Object IDs of the records that are part of the event.
*/
objectIDs: Array<string>;
/**
* Anonymous or pseudonymous user identifier. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
userToken: string;
/**
* Identifier for authenticated users. When the user signs in, you can get an identifier from your system and send it as `authenticatedUserToken`. This lets you keep using the `userToken` from before the user signed in, while providing a reliable way to identify users across sessions. Don\'t use personally identifiable information in user tokens. For more information, see [User token](https://www.algolia.com/doc/guides/sending-events/concepts/usertoken).
*/
authenticatedUserToken?: string | undefined;
/**
* Timestamp of the event, measured in milliseconds since the Unix epoch. Must be no older than 30 days. If not provided, we use the time at which the request was received.
*/
timestamp?: number | undefined;
};
type EventsItems = ClickedObjectIDsAfterSearch | AddedToCartObjectIDsAfterSearch | PurchasedObjectIDsAfterSearch | ConvertedObjectIDsAfterSearch | ClickedObjectIDs | PurchasedObjectIDs | AddedToCartObjectIDs | ConvertedObjectIDs | ClickedFilters | ConvertedFilters | ViewedObjectIDs | ViewedFilters;
type InsightsEvents = {
/**
* Click and conversion events. **All** events must be valid, otherwise the API returns an error.
*/
events: Array<EventsItems>;
};
/**
* Properties for the `customDelete` method.
*/
type CustomDeleteProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customGet` method.
*/
type CustomGetProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
};
/**
* Properties for the `customPost` method.
*/
type CustomPostProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `customPut` method.
*/
type CustomPutProps = {
/**
* Path of the endpoint, for example `1/newFeature`.
*/
path: string;
/**
* Query parameters to apply to the current query.
*/
parameters?: {
[key: string]: any;
} | undefined;
/**
* Parameters to send with the custom request.
*/
body?: Record<string, unknown> | undefined;
};
/**
* Properties for the `deleteUserToken` method.
*/
type DeleteUserTokenProps = {
/**
* User token for which to delete all associated events.
*/
userToken: string;
};
declare const apiClientVersion = "5.48.1";
declare const REGIONS: readonly ["de", "us"];
type Region = (typeof REGIONS)[number];
type RegionOptions = {
region?: Region | undefined;
};
declare function createInsightsClient({ appId: appIdOption, apiKey: apiKeyOption, authMode, algoliaAgents, region: regionOption, ...options }: CreateClientOptions & RegionOptions): {
transporter: _algolia_client_common.Transporter;
/**
* The `appId` currently in use.
*/
appId: string;
/**
* The `apiKey` currently in use.
*/
apiKey: string;
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache(): Promise<void>;
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
readonly _ua: string;
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment: string, version?: string | undefined): void;
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }: {
apiKey: string;
}): void;
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }: CustomDeleteProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }: CustomGetProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }: CustomPostProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }: CustomPutProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>>;
/**
* Deletes all events related to the specified user token from events metrics and analytics. The deletion is asynchronous, and processed within 48 hours. To delete a personalization user profile, see `Delete a user profile` in the Personalization API.
*
* Required API Key ACLs:
* - deleteObject
* @param deleteUserToken - The deleteUserToken object.
* @param deleteUserToken.userToken - User token for which to delete all associated events.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteUserToken({ userToken }: DeleteUserTokenProps, requestOptions?: RequestOptions): Promise<void>;
/**
* Sends a list of events to the Insights API. You can include up to 1,000 events in a single request, but the request body must be smaller than 2&nbsp;MB.
*
* Required API Key ACLs:
* - search
* @param insightsEvents - The insightsEvents object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
pushEvents(insightsEvents: InsightsEvents, requestOptions?: RequestOptions): Promise<EventsResponse>;
};
/**
* Error.
*/
type ErrorBase = Record<string, any> & {
message?: string | undefined;
};
declare function insightsClient(appId: string, apiKey: string, region?: Region | undefined, options?: ClientOptions | undefined): InsightsClient;
type InsightsClient = ReturnType<typeof createInsightsClient>;
export { type AddToCartEvent, type AddedToCartObjectIDs, type AddedToCartObjectIDsAfterSearch, type ClickEvent, type ClickedFilters, type ClickedObjectIDs, type ClickedObjectIDsAfterSearch, type ConversionEvent, type ConvertedFilters, type ConvertedObjectIDs, type ConvertedObjectIDsAfterSearch, type CustomDeleteProps, type CustomGetProps, type CustomPostProps, type CustomPutProps, type DeleteUserTokenProps, type Discount, type ErrorBase, type EventsItems, type EventsResponse, type InsightsClient, type InsightsEvents, type ObjectData, type ObjectDataAfterSearch, type Price, type PurchaseEvent, type PurchasedObjectIDs, type PurchasedObjectIDsAfterSearch, type Region, type RegionOptions, type Value, type ViewEvent, type ViewedFilters, type ViewedObjectIDs, apiClientVersion, insightsClient };
+271
View File
@@ -0,0 +1,271 @@
// builds/browser.ts
import {
createBrowserLocalStorageCache,
createFallbackableCache,
createMemoryCache,
createNullLogger
} from "@algolia/client-common";
import { createXhrRequester } from "@algolia/requester-browser-xhr";
// src/insightsClient.ts
import { createAuth, createTransporter, getAlgoliaAgent } from "@algolia/client-common";
var apiClientVersion = "5.48.1";
var REGIONS = ["de", "us"];
function getDefaultHosts(region) {
const url = !region ? "insights.algolia.io" : "insights.{region}.algolia.io".replace("{region}", region);
return [{ url, accept: "readWrite", protocol: "https" }];
}
function createInsightsClient({
appId: appIdOption,
apiKey: apiKeyOption,
authMode,
algoliaAgents,
region: regionOption,
...options
}) {
const auth = createAuth(appIdOption, apiKeyOption, authMode);
const transporter = createTransporter({
hosts: getDefaultHosts(regionOption),
...options,
algoliaAgent: getAlgoliaAgent({
algoliaAgents,
client: "Insights",
version: apiClientVersion
}),
baseHeaders: {
"content-type": "text/plain",
...auth.headers(),
...options.baseHeaders
},
baseQueryParameters: {
...auth.queryParameters(),
...options.baseQueryParameters
}
});
return {
transporter,
/**
* The `appId` currently in use.
*/
appId: appIdOption,
/**
* The `apiKey` currently in use.
*/
apiKey: apiKeyOption,
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache() {
return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => void 0);
},
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
get _ua() {
return transporter.algoliaAgent.value;
},
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment, version) {
transporter.algoliaAgent.add({ segment, version });
},
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }) {
if (!authMode || authMode === "WithinHeaders") {
transporter.baseHeaders["x-algolia-api-key"] = apiKey;
} else {
transporter.baseQueryParameters["x-algolia-api-key"] = apiKey;
}
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customDelete`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customGet`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPost`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPut`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "PUT",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* Deletes all events related to the specified user token from events metrics and analytics. The deletion is asynchronous, and processed within 48 hours. To delete a personalization user profile, see `Delete a user profile` in the Personalization API.
*
* Required API Key ACLs:
* - deleteObject
* @param deleteUserToken - The deleteUserToken object.
* @param deleteUserToken.userToken - User token for which to delete all associated events.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteUserToken({ userToken }, requestOptions) {
if (!userToken) {
throw new Error("Parameter `userToken` is required when calling `deleteUserToken`.");
}
const requestPath = "/1/usertokens/{userToken}".replace("{userToken}", encodeURIComponent(userToken));
const headers = {};
const queryParameters = {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Sends a list of events to the Insights API. You can include up to 1,000 events in a single request, but the request body must be smaller than 2&nbsp;MB.
*
* Required API Key ACLs:
* - search
* @param insightsEvents - The insightsEvents object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
pushEvents(insightsEvents, requestOptions) {
if (!insightsEvents) {
throw new Error("Parameter `insightsEvents` is required when calling `pushEvents`.");
}
if (!insightsEvents.events) {
throw new Error("Parameter `insightsEvents.events` is required when calling `pushEvents`.");
}
const requestPath = "/1/events";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: insightsEvents
};
return transporter.request(request, requestOptions);
}
};
}
// builds/browser.ts
function insightsClient(appId, apiKey, region, options) {
if (!appId || typeof appId !== "string") {
throw new Error("`appId` is missing.");
}
if (!apiKey || typeof apiKey !== "string") {
throw new Error("`apiKey` is missing.");
}
if (region && (typeof region !== "string" || !REGIONS.includes(region))) {
throw new Error(`\`region\` must be one of the following: ${REGIONS.join(", ")}`);
}
return createInsightsClient({
appId,
apiKey,
region,
timeouts: {
connect: 1e3,
read: 2e3,
write: 3e4
},
logger: createNullLogger(),
requester: createXhrRequester(),
algoliaAgents: [{ segment: "Browser" }],
authMode: "WithinQueryParameters",
responsesCache: createMemoryCache(),
requestsCache: createMemoryCache({ serializable: false }),
hostsCache: createFallbackableCache({
caches: [createBrowserLocalStorageCache({ key: `${apiClientVersion}-${appId}` }), createMemoryCache()]
}),
...options
});
}
export {
apiClientVersion,
insightsClient
};
//# sourceMappingURL=browser.js.map
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+265
View File
@@ -0,0 +1,265 @@
// builds/fetch.ts
import { createMemoryCache, createNullCache, createNullLogger } from "@algolia/client-common";
import { createFetchRequester } from "@algolia/requester-fetch";
// src/insightsClient.ts
import { createAuth, createTransporter, getAlgoliaAgent } from "@algolia/client-common";
var apiClientVersion = "5.48.1";
var REGIONS = ["de", "us"];
function getDefaultHosts(region) {
const url = !region ? "insights.algolia.io" : "insights.{region}.algolia.io".replace("{region}", region);
return [{ url, accept: "readWrite", protocol: "https" }];
}
function createInsightsClient({
appId: appIdOption,
apiKey: apiKeyOption,
authMode,
algoliaAgents,
region: regionOption,
...options
}) {
const auth = createAuth(appIdOption, apiKeyOption, authMode);
const transporter = createTransporter({
hosts: getDefaultHosts(regionOption),
...options,
algoliaAgent: getAlgoliaAgent({
algoliaAgents,
client: "Insights",
version: apiClientVersion
}),
baseHeaders: {
"content-type": "text/plain",
...auth.headers(),
...options.baseHeaders
},
baseQueryParameters: {
...auth.queryParameters(),
...options.baseQueryParameters
}
});
return {
transporter,
/**
* The `appId` currently in use.
*/
appId: appIdOption,
/**
* The `apiKey` currently in use.
*/
apiKey: apiKeyOption,
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache() {
return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => void 0);
},
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
get _ua() {
return transporter.algoliaAgent.value;
},
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment, version) {
transporter.algoliaAgent.add({ segment, version });
},
/**
* Helper method to switch the API key used to authenticate the requests.
*
* @param params - Method params.
* @param params.apiKey - The new API Key to use.
*/
setClientApiKey({ apiKey }) {
if (!authMode || authMode === "WithinHeaders") {
transporter.baseHeaders["x-algolia-api-key"] = apiKey;
} else {
transporter.baseQueryParameters["x-algolia-api-key"] = apiKey;
}
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customDelete - The customDelete object.
* @param customDelete.path - Path of the endpoint, for example `1/newFeature`.
* @param customDelete.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customDelete({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customDelete`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customGet - The customGet object.
* @param customGet.path - Path of the endpoint, for example `1/newFeature`.
* @param customGet.parameters - Query parameters to apply to the current query.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customGet({ path, parameters }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customGet`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "GET",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPost - The customPost object.
* @param customPost.path - Path of the endpoint, for example `1/newFeature`.
* @param customPost.parameters - Query parameters to apply to the current query.
* @param customPost.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPost({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPost`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* This method lets you send requests to the Algolia REST API.
* @param customPut - The customPut object.
* @param customPut.path - Path of the endpoint, for example `1/newFeature`.
* @param customPut.parameters - Query parameters to apply to the current query.
* @param customPut.body - Parameters to send with the custom request.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
customPut({ path, parameters, body }, requestOptions) {
if (!path) {
throw new Error("Parameter `path` is required when calling `customPut`.");
}
const requestPath = "/{path}".replace("{path}", path);
const headers = {};
const queryParameters = parameters ? parameters : {};
const request = {
method: "PUT",
path: requestPath,
queryParameters,
headers,
data: body ? body : {}
};
return transporter.request(request, requestOptions);
},
/**
* Deletes all events related to the specified user token from events metrics and analytics. The deletion is asynchronous, and processed within 48 hours. To delete a personalization user profile, see `Delete a user profile` in the Personalization API.
*
* Required API Key ACLs:
* - deleteObject
* @param deleteUserToken - The deleteUserToken object.
* @param deleteUserToken.userToken - User token for which to delete all associated events.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
deleteUserToken({ userToken }, requestOptions) {
if (!userToken) {
throw new Error("Parameter `userToken` is required when calling `deleteUserToken`.");
}
const requestPath = "/1/usertokens/{userToken}".replace("{userToken}", encodeURIComponent(userToken));
const headers = {};
const queryParameters = {};
const request = {
method: "DELETE",
path: requestPath,
queryParameters,
headers
};
return transporter.request(request, requestOptions);
},
/**
* Sends a list of events to the Insights API. You can include up to 1,000 events in a single request, but the request body must be smaller than 2&nbsp;MB.
*
* Required API Key ACLs:
* - search
* @param insightsEvents - The insightsEvents object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
pushEvents(insightsEvents, requestOptions) {
if (!insightsEvents) {
throw new Error("Parameter `insightsEvents` is required when calling `pushEvents`.");
}
if (!insightsEvents.events) {
throw new Error("Parameter `insightsEvents.events` is required when calling `pushEvents`.");
}
const requestPath = "/1/events";
const headers = {};
const queryParameters = {};
const request = {
method: "POST",
path: requestPath,
queryParameters,
headers,
data: insightsEvents
};
return transporter.request(request, requestOptions);
}
};
}
// builds/fetch.ts
function insightsClient(appId, apiKey, region, options) {
if (!appId || typeof appId !== "string") {
throw new Error("`appId` is missing.");
}
if (!apiKey || typeof apiKey !== "string") {
throw new Error("`apiKey` is missing.");
}
if (region && (typeof region !== "string" || !REGIONS.includes(region))) {
throw new Error(`\`region\` must be one of the following: ${REGIONS.join(", ")}`);
}
return {
...createInsightsClient({
appId,
apiKey,
region,
timeouts: {
connect: 2e3,
read: 5e3,
write: 3e4
},
logger: createNullLogger(),
requester: createFetchRequester(),
algoliaAgents: [{ segment: "Fetch" }],
responsesCache: createNullCache(),
requestsCache: createNullCache(),
hostsCache: createMemoryCache(),
...options
})
};
}
export {
apiClientVersion,
insightsClient
};
//# sourceMappingURL=fetch.js.map

Some files were not shown because too many files have changed in this diff Show More