Fix dependencies: Add flag-icons, tailwind directives, and postcss config

This commit is contained in:
MivoDev
2026-01-18 11:16:21 +07:00
commit 266a4b1296
10758 changed files with 1547435 additions and 0 deletions

21
node_modules/@algolia/abtesting/LICENSE generated vendored Normal file
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
node_modules/@algolia/abtesting/README.md generated vendored Normal file
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.12.3
# or
npm install @algolia/abtesting@1.12.3
# or
pnpm add @algolia/abtesting@1.12.3
```
### 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.12.3/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
node_modules/@algolia/abtesting/dist/browser.d.ts generated vendored Normal file
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.12.3";
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
node_modules/@algolia/abtesting/dist/builds/browser.js generated vendored Normal file
View File

@@ -0,0 +1,434 @@
// builds/browser.ts
import { createXhrRequester } from "@algolia/requester-browser-xhr";
import {
createBrowserLocalStorageCache,
createFallbackableCache,
createMemoryCache,
createNullLogger
} from "@algolia/client-common";
// src/abtestingV3Client.ts
import { createAuth, createTransporter, getAlgoliaAgent } from "@algolia/client-common";
var apiClientVersion = "1.12.3";
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
node_modules/@algolia/abtesting/dist/builds/fetch.js generated vendored Normal file
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.12.3";
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
node_modules/@algolia/abtesting/dist/builds/node.cjs generated vendored Normal file
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_requester_node_http = require("@algolia/requester-node-http");
var import_client_common2 = require("@algolia/client-common");
// src/abtestingV3Client.ts
var import_client_common = require("@algolia/client-common");
var apiClientVersion = "1.12.3";
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
node_modules/@algolia/abtesting/dist/builds/node.js generated vendored Normal file
View File

@@ -0,0 +1,428 @@
// builds/node.ts
import { createHttpRequester } from "@algolia/requester-node-http";
import { createMemoryCache, createNullCache, createNullLogger } from "@algolia/client-common";
// src/abtestingV3Client.ts
import { createAuth, createTransporter, getAlgoliaAgent } from "@algolia/client-common";
var apiClientVersion = "1.12.3";
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
node_modules/@algolia/abtesting/dist/builds/worker.js generated vendored Normal file
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.12.3";
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
node_modules/@algolia/abtesting/dist/fetch.d.ts generated vendored Normal file
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.12.3";
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
node_modules/@algolia/abtesting/dist/node.d.cts generated vendored Normal file
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.12.3";
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
node_modules/@algolia/abtesting/dist/node.d.ts generated vendored Normal file
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.12.3";
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 };

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.12.3";
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

View File

@@ -0,0 +1,393 @@
// src/abtestingV3Client.ts
import { createAuth, createTransporter, getAlgoliaAgent } from "@algolia/client-common";
var apiClientVersion = "1.12.3";
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
node_modules/@algolia/abtesting/dist/worker.d.ts generated vendored Normal file
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.12.3";
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
node_modules/@algolia/abtesting/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export * from './dist/node';

1
node_modules/@algolia/abtesting/index.js generated vendored Normal file
View File

@@ -0,0 +1 @@
module.exports = require('./dist/builds/node.cjs');

69
node_modules/@algolia/abtesting/package.json generated vendored Normal file
View File

@@ -0,0 +1,69 @@
{
"version": "1.12.3",
"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.46.3",
"@algolia/requester-browser-xhr": "5.46.3",
"@algolia/requester-fetch": "5.46.3",
"@algolia/requester-node-http": "5.46.3"
},
"devDependencies": {
"@arethetypeswrong/cli": "0.18.2",
"@types/node": "25.0.6",
"publint": "0.3.16",
"rollup": "4.55.1",
"tsup": "8.5.1",
"typescript": "5.9.3"
},
"engines": {
"node": ">= 14.0.0"
},
"gitHead": "5be82d3f2ae7cd97f5d42c3451e966daa53fd06a"
}

17
node_modules/@algolia/autocomplete-core/README.md generated vendored Normal file
View File

@@ -0,0 +1,17 @@
# @algolia/autocomplete-core
The [`autocomplete-core`](https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-core/createAutocomplete) package is the foundation of Autocomplete. It exposes primitives to build an autocomplete experience.
You likely dont need to use this package directly unless youre building a [renderer](https://www.algolia.com/doc/ui-libraries/autocomplete/guides/creating-a-renderer).
## Installation
```sh
yarn add @algolia/autocomplete-core
# or
npm install @algolia/autocomplete-core
```
## Documentation
See [**Documentation**](https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-core).

View File

@@ -0,0 +1,2 @@
import { AutocompleteOptions, BaseItem } from './types';
export declare function checkOptions<TItem extends BaseItem>(options: AutocompleteOptions<TItem>): void;

View File

@@ -0,0 +1,4 @@
import { warn } from '@algolia/autocomplete-shared';
export function checkOptions(options) {
process.env.NODE_ENV !== 'production' ? warn(!options.debug, 'The `debug` option is meant for development debugging and should not be used in production.') : void 0;
}

View File

@@ -0,0 +1,8 @@
import { AutocompleteApi, AutocompleteOptions as AutocompleteCoreOptions, BaseItem } from './types';
export interface AutocompleteOptionsWithMetadata<TItem extends BaseItem> extends AutocompleteCoreOptions<TItem> {
/**
* @internal
*/
__autocomplete_metadata?: Record<string, unknown>;
}
export declare function createAutocomplete<TItem extends BaseItem, TEvent = Event, TMouseEvent = MouseEvent, TKeyboardEvent = KeyboardEvent>(options: AutocompleteOptionsWithMetadata<TItem>): AutocompleteApi<TItem, TEvent, TMouseEvent, TKeyboardEvent>;

View File

@@ -0,0 +1,106 @@
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
import { createAlgoliaInsightsPlugin } from '@algolia/autocomplete-plugin-algolia-insights';
import { checkOptions } from './checkOptions';
import { createStore } from './createStore';
import { getAutocompleteSetters } from './getAutocompleteSetters';
import { getDefaultProps } from './getDefaultProps';
import { getPropGetters } from './getPropGetters';
import { getMetadata, injectMetadata } from './metadata';
import { onInput } from './onInput';
import { stateReducer } from './stateReducer';
export function createAutocomplete(options) {
checkOptions(options);
var subscribers = [];
var props = getDefaultProps(options, subscribers);
var store = createStore(stateReducer, props, onStoreStateChange);
var setters = getAutocompleteSetters({
store: store
});
var propGetters = getPropGetters(_objectSpread({
props: props,
refresh: refresh,
store: store,
navigator: props.navigator
}, setters));
function onStoreStateChange(_ref) {
var _state$context, _state$context$algoli;
var prevState = _ref.prevState,
state = _ref.state;
props.onStateChange(_objectSpread({
prevState: prevState,
state: state,
refresh: refresh,
navigator: props.navigator
}, setters));
if (!isAlgoliaInsightsPluginEnabled() && (_state$context = state.context) !== null && _state$context !== void 0 && (_state$context$algoli = _state$context.algoliaInsightsPlugin) !== null && _state$context$algoli !== void 0 && _state$context$algoli.__automaticInsights && props.insights !== false) {
var plugin = createAlgoliaInsightsPlugin({
__autocomplete_clickAnalytics: false
});
props.plugins.push(plugin);
subscribePlugins([plugin]);
}
}
function refresh() {
return onInput(_objectSpread({
event: new Event('input'),
nextState: {
isOpen: store.getState().isOpen
},
props: props,
navigator: props.navigator,
query: store.getState().query,
refresh: refresh,
store: store
}, setters));
}
function subscribePlugins(plugins) {
plugins.forEach(function (plugin) {
var _plugin$subscribe;
return (_plugin$subscribe = plugin.subscribe) === null || _plugin$subscribe === void 0 ? void 0 : _plugin$subscribe.call(plugin, _objectSpread(_objectSpread({}, setters), {}, {
navigator: props.navigator,
refresh: refresh,
onSelect: function onSelect(fn) {
subscribers.push({
onSelect: fn
});
},
onActive: function onActive(fn) {
subscribers.push({
onActive: fn
});
},
onResolve: function onResolve(fn) {
subscribers.push({
onResolve: fn
});
}
}));
});
}
function isAlgoliaInsightsPluginEnabled() {
return props.plugins.some(function (plugin) {
return plugin.name === 'aa.algoliaInsightsPlugin';
});
}
if (props.insights && !isAlgoliaInsightsPluginEnabled()) {
var insightsParams = typeof props.insights === 'boolean' ? {} : props.insights;
props.plugins.push(createAlgoliaInsightsPlugin(insightsParams));
}
subscribePlugins(props.plugins);
injectMetadata({
metadata: getMetadata({
plugins: props.plugins,
options: options
}),
environment: props.environment
});
return _objectSpread(_objectSpread({
refresh: refresh,
navigator: props.navigator
}, propGetters), setters);
}

View File

@@ -0,0 +1,7 @@
import { AutocompleteState, AutocompleteStore, BaseItem, InternalAutocompleteOptions, Reducer } from './types';
declare type OnStoreStateChange<TItem extends BaseItem> = ({ prevState, state, }: {
prevState: AutocompleteState<TItem>;
state: AutocompleteState<TItem>;
}) => void;
export declare function createStore<TItem extends BaseItem>(reducer: Reducer, props: InternalAutocompleteOptions<TItem>, onStoreStateChange: OnStoreStateChange<TItem>): AutocompleteStore<TItem>;
export {};

View File

@@ -0,0 +1,28 @@
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
import { createCancelablePromiseList } from './utils';
export function createStore(reducer, props, onStoreStateChange) {
var state = props.initialState;
return {
getState: function getState() {
return state;
},
dispatch: function dispatch(action, payload) {
var prevState = _objectSpread({}, state);
state = reducer(state, {
type: action,
props: props,
payload: payload
});
onStoreStateChange({
state: state,
prevState: prevState
});
},
pendingRequests: createCancelablePromiseList()
};
}

View File

@@ -0,0 +1,13 @@
import { AutocompleteCollection, AutocompleteStore, BaseItem } from './types';
interface GetAutocompleteSettersOptions<TItem extends BaseItem> {
store: AutocompleteStore<TItem>;
}
export declare function getAutocompleteSetters<TItem extends BaseItem>({ store, }: GetAutocompleteSettersOptions<TItem>): {
setActiveItemId: import("@algolia/autocomplete-shared/dist/esm/core/AutocompleteSetters").StateUpdater<number | null>;
setQuery: import("@algolia/autocomplete-shared/dist/esm/core/AutocompleteSetters").StateUpdater<string>;
setCollections: import("@algolia/autocomplete-shared/dist/esm/core/AutocompleteSetters").StateUpdater<(AutocompleteCollection<TItem> | import("@algolia/autocomplete-shared/dist/esm/core/AutocompleteCollection").AutocompleteCollectionItemsArray<TItem>)[]>;
setIsOpen: import("@algolia/autocomplete-shared/dist/esm/core/AutocompleteSetters").StateUpdater<boolean>;
setStatus: import("@algolia/autocomplete-shared/dist/esm/core/AutocompleteSetters").StateUpdater<"idle" | "loading" | "stalled" | "error">;
setContext: import("@algolia/autocomplete-shared/dist/esm/core/AutocompleteSetters").StateUpdater<import("@algolia/autocomplete-shared/dist/esm/core/AutocompleteContext").AutocompleteContext>;
};
export {};

View File

@@ -0,0 +1,48 @@
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
import { flatten } from '@algolia/autocomplete-shared';
export function getAutocompleteSetters(_ref) {
var store = _ref.store;
var setActiveItemId = function setActiveItemId(value) {
store.dispatch('setActiveItemId', value);
};
var setQuery = function setQuery(value) {
store.dispatch('setQuery', value);
};
var setCollections = function setCollections(rawValue) {
var baseItemId = 0;
var value = rawValue.map(function (collection) {
return _objectSpread(_objectSpread({}, collection), {}, {
// We flatten the stored items to support calling `getAlgoliaResults`
// from the source itself.
items: flatten(collection.items).map(function (item) {
return _objectSpread(_objectSpread({}, item), {}, {
__autocomplete_id: baseItemId++
});
})
});
});
store.dispatch('setCollections', value);
};
var setIsOpen = function setIsOpen(value) {
store.dispatch('setIsOpen', value);
};
var setStatus = function setStatus(value) {
store.dispatch('setStatus', value);
};
var setContext = function setContext(value) {
store.dispatch('setContext', value);
};
return {
setActiveItemId: setActiveItemId,
setQuery: setQuery,
setCollections: setCollections,
setIsOpen: setIsOpen,
setStatus: setStatus,
setContext: setContext
};
}

View File

@@ -0,0 +1,6 @@
import { AutocompleteState, BaseItem } from './types';
interface GetCompletionProps<TItem extends BaseItem> {
state: AutocompleteState<TItem>;
}
export declare function getCompletion<TItem extends BaseItem>({ state, }: GetCompletionProps<TItem>): string | null;
export {};

View File

@@ -0,0 +1,9 @@
import { getActiveItem } from './utils';
export function getCompletion(_ref) {
var _getActiveItem;
var state = _ref.state;
if (state.isOpen === false || state.activeItemId === null) {
return null;
}
return ((_getActiveItem = getActiveItem(state)) === null || _getActiveItem === void 0 ? void 0 : _getActiveItem.itemInputValue) || null;
}

View File

@@ -0,0 +1,2 @@
import { AutocompleteOptions, AutocompleteSubscribers, BaseItem, InternalAutocompleteOptions } from './types';
export declare function getDefaultProps<TItem extends BaseItem>(props: AutocompleteOptions<TItem>, pluginSubscribers: AutocompleteSubscribers<TItem>): InternalAutocompleteOptions<TItem>;

View File

@@ -0,0 +1,130 @@
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
import { getItemsCount, generateAutocompleteId, flatten } from '@algolia/autocomplete-shared';
import { getNormalizedSources } from './utils';
export function getDefaultProps(props, pluginSubscribers) {
var _props$id;
/* eslint-disable no-restricted-globals */
var environment = typeof window !== 'undefined' ? window : {};
/* eslint-enable no-restricted-globals */
var plugins = props.plugins || [];
return _objectSpread(_objectSpread({
debug: false,
openOnFocus: false,
enterKeyHint: undefined,
ignoreCompositionEvents: false,
placeholder: '',
autoFocus: false,
defaultActiveItemId: null,
stallThreshold: 300,
insights: undefined,
environment: environment,
shouldPanelOpen: function shouldPanelOpen(_ref) {
var state = _ref.state;
return getItemsCount(state) > 0;
},
reshape: function reshape(_ref2) {
var sources = _ref2.sources;
return sources;
}
}, props), {}, {
// Since `generateAutocompleteId` triggers a side effect (it increments
// an internal counter), we don't want to execute it if unnecessary.
id: (_props$id = props.id) !== null && _props$id !== void 0 ? _props$id : generateAutocompleteId(),
plugins: plugins,
// The following props need to be deeply defaulted.
initialState: _objectSpread({
activeItemId: null,
query: '',
completion: null,
collections: [],
isOpen: false,
status: 'idle',
context: {}
}, props.initialState),
onStateChange: function onStateChange(params) {
var _props$onStateChange;
(_props$onStateChange = props.onStateChange) === null || _props$onStateChange === void 0 ? void 0 : _props$onStateChange.call(props, params);
plugins.forEach(function (x) {
var _x$onStateChange;
return (_x$onStateChange = x.onStateChange) === null || _x$onStateChange === void 0 ? void 0 : _x$onStateChange.call(x, params);
});
},
onSubmit: function onSubmit(params) {
var _props$onSubmit;
(_props$onSubmit = props.onSubmit) === null || _props$onSubmit === void 0 ? void 0 : _props$onSubmit.call(props, params);
plugins.forEach(function (x) {
var _x$onSubmit;
return (_x$onSubmit = x.onSubmit) === null || _x$onSubmit === void 0 ? void 0 : _x$onSubmit.call(x, params);
});
},
onReset: function onReset(params) {
var _props$onReset;
(_props$onReset = props.onReset) === null || _props$onReset === void 0 ? void 0 : _props$onReset.call(props, params);
plugins.forEach(function (x) {
var _x$onReset;
return (_x$onReset = x.onReset) === null || _x$onReset === void 0 ? void 0 : _x$onReset.call(x, params);
});
},
getSources: function getSources(params) {
return Promise.all([].concat(_toConsumableArray(plugins.map(function (plugin) {
return plugin.getSources;
})), [props.getSources]).filter(Boolean).map(function (getSources) {
return getNormalizedSources(getSources, params);
})).then(function (nested) {
return flatten(nested);
}).then(function (sources) {
return sources.map(function (source) {
return _objectSpread(_objectSpread({}, source), {}, {
onSelect: function onSelect(params) {
source.onSelect(params);
pluginSubscribers.forEach(function (x) {
var _x$onSelect;
return (_x$onSelect = x.onSelect) === null || _x$onSelect === void 0 ? void 0 : _x$onSelect.call(x, params);
});
},
onActive: function onActive(params) {
source.onActive(params);
pluginSubscribers.forEach(function (x) {
var _x$onActive;
return (_x$onActive = x.onActive) === null || _x$onActive === void 0 ? void 0 : _x$onActive.call(x, params);
});
},
onResolve: function onResolve(params) {
source.onResolve(params);
pluginSubscribers.forEach(function (x) {
var _x$onResolve;
return (_x$onResolve = x.onResolve) === null || _x$onResolve === void 0 ? void 0 : _x$onResolve.call(x, params);
});
}
});
});
});
},
navigator: _objectSpread({
navigate: function navigate(_ref3) {
var itemUrl = _ref3.itemUrl;
environment.location.assign(itemUrl);
},
navigateNewTab: function navigateNewTab(_ref4) {
var itemUrl = _ref4.itemUrl;
var windowReference = environment.open(itemUrl, '_blank', 'noopener');
windowReference === null || windowReference === void 0 ? void 0 : windowReference.focus();
},
navigateNewWindow: function navigateNewWindow(_ref5) {
var itemUrl = _ref5.itemUrl;
environment.open(itemUrl, '_blank', 'noopener');
}
}, props.navigator)
});
}

View File

@@ -0,0 +1,16 @@
import { AutocompleteScopeApi, AutocompleteStore, BaseItem, GetEnvironmentProps, GetFormProps, GetInputProps, GetItemProps, GetLabelProps, GetListProps, GetPanelProps, GetRootProps, InternalAutocompleteOptions } from './types';
interface GetPropGettersOptions<TItem extends BaseItem> extends AutocompleteScopeApi<TItem> {
store: AutocompleteStore<TItem>;
props: InternalAutocompleteOptions<TItem>;
}
export declare function getPropGetters<TItem extends BaseItem, TEvent, TMouseEvent, TKeyboardEvent>({ props, refresh, store, ...setters }: GetPropGettersOptions<TItem>): {
getEnvironmentProps: GetEnvironmentProps;
getRootProps: GetRootProps;
getFormProps: GetFormProps<TEvent>;
getLabelProps: GetLabelProps;
getInputProps: GetInputProps<TEvent, TMouseEvent, TKeyboardEvent>;
getPanelProps: GetPanelProps<TMouseEvent>;
getListProps: GetListProps;
getItemProps: GetItemProps<any, TMouseEvent>;
};
export {};

View File

@@ -0,0 +1,335 @@
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
var _excluded = ["props", "refresh", "store"],
_excluded2 = ["inputElement", "formElement", "panelElement"],
_excluded3 = ["inputElement"],
_excluded4 = ["inputElement", "maxLength"],
_excluded5 = ["source"],
_excluded6 = ["item", "source"];
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
import { noop } from '@algolia/autocomplete-shared';
import { onInput } from './onInput';
import { onKeyDown as _onKeyDown } from './onKeyDown';
import { getActiveItem, getAutocompleteElementId, isOrContainsNode, isSamsung, getNativeEvent } from './utils';
export function getPropGetters(_ref) {
var props = _ref.props,
refresh = _ref.refresh,
store = _ref.store,
setters = _objectWithoutProperties(_ref, _excluded);
var getEnvironmentProps = function getEnvironmentProps(providedProps) {
var inputElement = providedProps.inputElement,
formElement = providedProps.formElement,
panelElement = providedProps.panelElement,
rest = _objectWithoutProperties(providedProps, _excluded2);
function onMouseDownOrTouchStart(event) {
// The `onTouchStart`/`onMouseDown` events shouldn't trigger the `blur`
// handler when it's not an interaction with Autocomplete.
// We detect it with the following heuristics:
// - the panel is closed AND there are no pending requests
// (no interaction with the autocomplete, no future state updates)
// - OR the touched target is the input element (should open the panel)
var isAutocompleteInteraction = store.getState().isOpen || !store.pendingRequests.isEmpty();
if (!isAutocompleteInteraction || event.target === inputElement) {
return;
}
// @TODO: support cases where there are multiple Autocomplete instances.
// Right now, a second instance makes this computation return false.
var isTargetWithinAutocomplete = [formElement, panelElement].some(function (contextNode) {
return isOrContainsNode(contextNode, event.target);
});
if (isTargetWithinAutocomplete === false) {
store.dispatch('blur', null);
// If requests are still pending when the user closes the panel, they
// could reopen the panel once they resolve.
// We want to prevent any subsequent query from reopening the panel
// because it would result in an unsolicited UI behavior.
if (!props.debug) {
store.pendingRequests.cancelAll();
}
}
}
return _objectSpread({
// We do not rely on the native `blur` event of the input to close the
// panel, but rather on a custom `touchstart`/`mousedown` event outside
// of the autocomplete elements.
// This ensures we don't mistakenly interpret interactions within the
// autocomplete (but outside of the input) as a signal to close the panel.
// For example, clicking reset button causes an input blur, but if
// `openOnFocus=true`, it shouldn't close the panel.
// On touch devices, scrolling results (`touchmove`) causes an input blur
// but shouldn't close the panel.
onTouchStart: onMouseDownOrTouchStart,
onMouseDown: onMouseDownOrTouchStart,
// When scrolling on touch devices (mobiles, tablets, etc.), we want to
// mimic the native platform behavior where the input is blurred to
// hide the virtual keyboard. This gives more vertical space to
// discover all the suggestions showing up in the panel.
onTouchMove: function onTouchMove(event) {
if (store.getState().isOpen === false || inputElement !== props.environment.document.activeElement || event.target === inputElement) {
return;
}
inputElement.blur();
}
}, rest);
};
var getRootProps = function getRootProps(rest) {
return _objectSpread({
role: 'combobox',
'aria-expanded': store.getState().isOpen,
'aria-haspopup': 'listbox',
'aria-controls': store.getState().isOpen ? store.getState().collections.map(function (_ref2) {
var source = _ref2.source;
return getAutocompleteElementId(props.id, 'list', source);
}).join(' ') : undefined,
'aria-labelledby': getAutocompleteElementId(props.id, 'label')
}, rest);
};
var getFormProps = function getFormProps(providedProps) {
var inputElement = providedProps.inputElement,
rest = _objectWithoutProperties(providedProps, _excluded3);
return _objectSpread({
action: '',
noValidate: true,
role: 'search',
onSubmit: function onSubmit(event) {
var _providedProps$inputE;
event.preventDefault();
props.onSubmit(_objectSpread({
event: event,
refresh: refresh,
state: store.getState()
}, setters));
store.dispatch('submit', null);
(_providedProps$inputE = providedProps.inputElement) === null || _providedProps$inputE === void 0 ? void 0 : _providedProps$inputE.blur();
},
onReset: function onReset(event) {
var _providedProps$inputE2;
event.preventDefault();
props.onReset(_objectSpread({
event: event,
refresh: refresh,
state: store.getState()
}, setters));
store.dispatch('reset', null);
(_providedProps$inputE2 = providedProps.inputElement) === null || _providedProps$inputE2 === void 0 ? void 0 : _providedProps$inputE2.focus();
}
}, rest);
};
var getInputProps = function getInputProps(providedProps) {
var _props$environment$na;
function onFocus(event) {
// We want to trigger a query when `openOnFocus` is true
// because the panel should open with the current query.
if (props.openOnFocus || Boolean(store.getState().query)) {
onInput(_objectSpread({
event: event,
props: props,
query: store.getState().completion || store.getState().query,
refresh: refresh,
store: store
}, setters));
}
store.dispatch('focus', null);
}
var _ref3 = providedProps || {},
inputElement = _ref3.inputElement,
_ref3$maxLength = _ref3.maxLength,
maxLength = _ref3$maxLength === void 0 ? 512 : _ref3$maxLength,
rest = _objectWithoutProperties(_ref3, _excluded4);
var activeItem = getActiveItem(store.getState());
var userAgent = ((_props$environment$na = props.environment.navigator) === null || _props$environment$na === void 0 ? void 0 : _props$environment$na.userAgent) || '';
var shouldFallbackKeyHint = isSamsung(userAgent);
var enterKeyHint = props.enterKeyHint || (activeItem !== null && activeItem !== void 0 && activeItem.itemUrl && !shouldFallbackKeyHint ? 'go' : 'search');
return _objectSpread({
'aria-autocomplete': 'both',
'aria-activedescendant': store.getState().isOpen && store.getState().activeItemId !== null ? getAutocompleteElementId(props.id, "item-".concat(store.getState().activeItemId), activeItem === null || activeItem === void 0 ? void 0 : activeItem.source) : undefined,
'aria-controls': store.getState().isOpen ? store.getState().collections.map(function (_ref4) {
var source = _ref4.source;
return getAutocompleteElementId(props.id, 'list', source);
}).join(' ') : undefined,
'aria-labelledby': getAutocompleteElementId(props.id, 'label'),
value: store.getState().completion || store.getState().query,
id: getAutocompleteElementId(props.id, 'input'),
autoComplete: 'off',
autoCorrect: 'off',
autoCapitalize: 'off',
enterKeyHint: enterKeyHint,
spellCheck: 'false',
autoFocus: props.autoFocus,
placeholder: props.placeholder,
maxLength: maxLength,
type: 'search',
onChange: function onChange(event) {
var value = event.currentTarget.value;
if (props.ignoreCompositionEvents && getNativeEvent(event).isComposing) {
setters.setQuery(value);
return;
}
onInput(_objectSpread({
event: event,
props: props,
query: value.slice(0, maxLength),
refresh: refresh,
store: store
}, setters));
},
onCompositionEnd: function onCompositionEnd(event) {
onInput(_objectSpread({
event: event,
props: props,
query: event.currentTarget.value.slice(0, maxLength),
refresh: refresh,
store: store
}, setters));
},
onKeyDown: function onKeyDown(event) {
if (getNativeEvent(event).isComposing) {
return;
}
_onKeyDown(_objectSpread({
event: event,
props: props,
refresh: refresh,
store: store
}, setters));
},
onFocus: onFocus,
// We don't rely on the `blur` event.
// See explanation in `onTouchStart`/`onMouseDown`.
// @MAJOR See if we need to keep this handler.
onBlur: noop,
onClick: function onClick(event) {
// When the panel is closed and you click on the input while
// the input is focused, the `onFocus` event is not triggered
// (default browser behavior).
// In an autocomplete context, it makes sense to open the panel in this
// case.
// We mimic this event by catching the `onClick` event which
// triggers the `onFocus` for the panel to open.
if (providedProps.inputElement === props.environment.document.activeElement && !store.getState().isOpen) {
onFocus(event);
}
}
}, rest);
};
var getLabelProps = function getLabelProps(rest) {
return _objectSpread({
htmlFor: getAutocompleteElementId(props.id, 'input'),
id: getAutocompleteElementId(props.id, 'label')
}, rest);
};
var getListProps = function getListProps(providedProps) {
var _ref5 = providedProps || {},
source = _ref5.source,
rest = _objectWithoutProperties(_ref5, _excluded5);
return _objectSpread({
role: 'listbox',
'aria-labelledby': getAutocompleteElementId(props.id, 'label'),
id: getAutocompleteElementId(props.id, 'list', source)
}, rest);
};
var getPanelProps = function getPanelProps(rest) {
return _objectSpread({
onMouseDown: function onMouseDown(event) {
// Prevents the `activeElement` from being changed to the panel so
// that the blur event is not triggered, otherwise it closes the
// panel.
event.preventDefault();
},
onMouseLeave: function onMouseLeave() {
store.dispatch('mouseleave', null);
}
}, rest);
};
var getItemProps = function getItemProps(providedProps) {
var item = providedProps.item,
source = providedProps.source,
rest = _objectWithoutProperties(providedProps, _excluded6);
return _objectSpread({
id: getAutocompleteElementId(props.id, "item-".concat(item.__autocomplete_id), source),
role: 'option',
'aria-selected': store.getState().activeItemId === item.__autocomplete_id,
onMouseMove: function onMouseMove(event) {
if (item.__autocomplete_id === store.getState().activeItemId) {
return;
}
store.dispatch('mousemove', item.__autocomplete_id);
var activeItem = getActiveItem(store.getState());
if (store.getState().activeItemId !== null && activeItem) {
var _item = activeItem.item,
itemInputValue = activeItem.itemInputValue,
itemUrl = activeItem.itemUrl,
_source = activeItem.source;
_source.onActive(_objectSpread({
event: event,
item: _item,
itemInputValue: itemInputValue,
itemUrl: itemUrl,
refresh: refresh,
source: _source,
state: store.getState()
}, setters));
}
},
onMouseDown: function onMouseDown(event) {
// Prevents the `activeElement` from being changed to the item so it
// can remain with the current `activeElement`.
event.preventDefault();
},
onClick: function onClick(event) {
var itemInputValue = source.getItemInputValue({
item: item,
state: store.getState()
});
var itemUrl = source.getItemUrl({
item: item,
state: store.getState()
});
// If `getItemUrl` is provided, it means that the suggestion
// is a link, not plain text that aims at updating the query.
// We can therefore skip the state change because it will update
// the `activeItemId`, resulting in a UI flash, especially
// noticeable on mobile.
var runPreCommand = itemUrl ? Promise.resolve() : onInput(_objectSpread({
event: event,
nextState: {
isOpen: false
},
props: props,
query: itemInputValue,
refresh: refresh,
store: store
}, setters));
runPreCommand.then(function () {
source.onSelect(_objectSpread({
event: event,
item: item,
itemInputValue: itemInputValue,
itemUrl: itemUrl,
refresh: refresh,
source: source,
state: store.getState()
}, setters));
});
}
}, rest);
};
return {
getEnvironmentProps: getEnvironmentProps,
getRootProps: getRootProps,
getFormProps: getFormProps,
getLabelProps: getLabelProps,
getInputProps: getInputProps,
getPanelProps: getPanelProps,
getListProps: getListProps,
getItemProps: getItemProps
};
}

View File

@@ -0,0 +1,3 @@
export * from './createAutocomplete';
export * from './getDefaultProps';
export * from './types';

View File

@@ -0,0 +1,3 @@
export * from './createAutocomplete';
export * from './getDefaultProps';
export * from './types';

View File

@@ -0,0 +1,33 @@
import { UserAgent } from '@algolia/autocomplete-shared';
import { AutocompleteEnvironment, AutocompleteOptionsWithMetadata, AutocompletePlugin, BaseItem } from '.';
declare type AutocompleteMetadata = {
plugins: Array<{
name: string | undefined;
options: string[];
}>;
options: Record<string, string[]>;
ua: UserAgent[];
};
declare type GetMetadataParams<TItem extends BaseItem, TData = unknown> = {
plugins: Array<AutocompletePlugin<TItem, TData>>;
options: AutocompleteOptionsWithMetadata<TItem>;
};
export declare function getMetadata<TItem extends BaseItem, TData = unknown>({ plugins, options, }: GetMetadataParams<TItem, TData>): {
plugins: {
name: string | undefined;
options: string[];
}[];
options: {
'autocomplete-core': string[];
};
ua: {
segment: string;
version: string;
}[];
};
declare type InlineMetadataParams = {
metadata: AutocompleteMetadata;
environment: AutocompleteEnvironment;
};
export declare function injectMetadata({ metadata, environment, }: InlineMetadataParams): void;
export {};

View File

@@ -0,0 +1,41 @@
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
import { userAgents } from '@algolia/autocomplete-shared';
export function getMetadata(_ref) {
var _, _options$__autocomple, _options$__autocomple2, _options$__autocomple3;
var plugins = _ref.plugins,
options = _ref.options;
var optionsKey = (_ = (((_options$__autocomple = options.__autocomplete_metadata) === null || _options$__autocomple === void 0 ? void 0 : _options$__autocomple.userAgents) || [])[0]) === null || _ === void 0 ? void 0 : _.segment;
var extraOptions = optionsKey ? _defineProperty({}, optionsKey, Object.keys(((_options$__autocomple2 = options.__autocomplete_metadata) === null || _options$__autocomple2 === void 0 ? void 0 : _options$__autocomple2.options) || {})) : {};
return {
plugins: plugins.map(function (plugin) {
return {
name: plugin.name,
options: Object.keys(plugin.__autocomplete_pluginOptions || [])
};
}),
options: _objectSpread({
'autocomplete-core': Object.keys(options)
}, extraOptions),
ua: userAgents.concat(((_options$__autocomple3 = options.__autocomplete_metadata) === null || _options$__autocomple3 === void 0 ? void 0 : _options$__autocomple3.userAgents) || [])
};
}
export function injectMetadata(_ref3) {
var _environment$navigato, _environment$navigato2;
var metadata = _ref3.metadata,
environment = _ref3.environment;
var isMetadataEnabled = (_environment$navigato = environment.navigator) === null || _environment$navigato === void 0 ? void 0 : (_environment$navigato2 = _environment$navigato.userAgent) === null || _environment$navigato2 === void 0 ? void 0 : _environment$navigato2.includes('Algolia Crawler');
if (isMetadataEnabled) {
var metadataContainer = environment.document.createElement('meta');
var headRef = environment.document.querySelector('head');
metadataContainer.name = 'algolia:metadata';
setTimeout(function () {
metadataContainer.content = JSON.stringify(metadata);
headRef.appendChild(metadataContainer);
}, 0);
}
}

View File

@@ -0,0 +1,18 @@
import { AutocompleteScopeApi, AutocompleteState, AutocompleteStore, BaseItem, InternalAutocompleteOptions } from './types';
import { CancelablePromise } from './utils';
interface OnInputParams<TItem extends BaseItem> extends AutocompleteScopeApi<TItem> {
event: any;
/**
* The next partial state to apply after the function is called.
*
* This is useful when we call `onInput` in a different scenario than an
* actual input. For example, we use `onInput` when we click on an item,
* but we want to close the panel in that case.
*/
nextState?: Partial<AutocompleteState<TItem>>;
props: InternalAutocompleteOptions<TItem>;
query: string;
store: AutocompleteStore<TItem>;
}
export declare function onInput<TItem extends BaseItem>({ event, nextState, props, query, refresh, store, ...setters }: OnInputParams<TItem>): CancelablePromise<void>;
export {};

View File

@@ -0,0 +1,143 @@
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
var _excluded = ["event", "nextState", "props", "query", "refresh", "store"];
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
import { reshape } from './reshape';
import { preResolve, resolve, postResolve } from './resolve';
import { cancelable, createConcurrentSafePromise, getActiveItem } from './utils';
var lastStalledId = null;
var runConcurrentSafePromise = createConcurrentSafePromise();
export function onInput(_ref) {
var event = _ref.event,
_ref$nextState = _ref.nextState,
nextState = _ref$nextState === void 0 ? {} : _ref$nextState,
props = _ref.props,
query = _ref.query,
refresh = _ref.refresh,
store = _ref.store,
setters = _objectWithoutProperties(_ref, _excluded);
if (lastStalledId) {
props.environment.clearTimeout(lastStalledId);
}
var setCollections = setters.setCollections,
setIsOpen = setters.setIsOpen,
setQuery = setters.setQuery,
setActiveItemId = setters.setActiveItemId,
setStatus = setters.setStatus,
setContext = setters.setContext;
setQuery(query);
setActiveItemId(props.defaultActiveItemId);
if (!query && props.openOnFocus === false) {
var _nextState$isOpen;
var collections = store.getState().collections.map(function (collection) {
return _objectSpread(_objectSpread({}, collection), {}, {
items: []
});
});
setStatus('idle');
setCollections(collections);
setIsOpen((_nextState$isOpen = nextState.isOpen) !== null && _nextState$isOpen !== void 0 ? _nextState$isOpen : props.shouldPanelOpen({
state: store.getState()
}));
// We make sure to update the latest resolved value of the tracked
// promises to keep late resolving promises from "cancelling" the state
// updates performed in this code path.
// We chain with a void promise to respect `onInput`'s expected return type.
var _request = cancelable(runConcurrentSafePromise(collections).then(function () {
return Promise.resolve();
}));
return store.pendingRequests.add(_request);
}
setStatus('loading');
lastStalledId = props.environment.setTimeout(function () {
setStatus('stalled');
}, props.stallThreshold);
// We track the entire promise chain triggered by `onInput` before mutating
// the Autocomplete state to make sure that any state manipulation is based on
// fresh data regardless of when promises individually resolve.
// We don't track nested promises and only rely on the full chain resolution,
// meaning we should only ever manipulate the state once this concurrent-safe
// promise is resolved.
var request = cancelable(runConcurrentSafePromise(props.getSources(_objectSpread({
query: query,
refresh: refresh,
state: store.getState()
}, setters)).then(function (sources) {
return Promise.all(sources.map(function (source) {
return Promise.resolve(source.getItems(_objectSpread({
query: query,
refresh: refresh,
state: store.getState()
}, setters))).then(function (itemsOrDescription) {
return preResolve(itemsOrDescription, source.sourceId, store.getState());
});
})).then(resolve).then(function (responses) {
var __automaticInsights = responses.some(function (_ref2) {
var items = _ref2.items;
return isSearchResponseWithAutomaticInsightsFlag(items);
});
// No need to pollute the context if `__automaticInsights=false`
if (__automaticInsights) {
var _store$getState$conte;
setContext({
algoliaInsightsPlugin: _objectSpread(_objectSpread({}, ((_store$getState$conte = store.getState().context) === null || _store$getState$conte === void 0 ? void 0 : _store$getState$conte.algoliaInsightsPlugin) || {}), {}, {
__automaticInsights: __automaticInsights
})
});
}
return postResolve(responses, sources, store);
}).then(function (collections) {
return reshape({
collections: collections,
props: props,
state: store.getState()
});
});
}))).then(function (collections) {
var _nextState$isOpen2;
// Parameters passed to `onInput` could be stale when the following code
// executes, because `onInput` calls may not resolve in order.
// If it becomes a problem we'll need to save the last passed parameters.
// See: https://codesandbox.io/s/agitated-cookies-y290z
setStatus('idle');
setCollections(collections);
var isPanelOpen = props.shouldPanelOpen({
state: store.getState()
});
setIsOpen((_nextState$isOpen2 = nextState.isOpen) !== null && _nextState$isOpen2 !== void 0 ? _nextState$isOpen2 : props.openOnFocus && !query && isPanelOpen || isPanelOpen);
var highlightedItem = getActiveItem(store.getState());
if (store.getState().activeItemId !== null && highlightedItem) {
var item = highlightedItem.item,
itemInputValue = highlightedItem.itemInputValue,
itemUrl = highlightedItem.itemUrl,
source = highlightedItem.source;
source.onActive(_objectSpread({
event: event,
item: item,
itemInputValue: itemInputValue,
itemUrl: itemUrl,
refresh: refresh,
source: source,
state: store.getState()
}, setters));
}
}).finally(function () {
setStatus('idle');
if (lastStalledId) {
props.environment.clearTimeout(lastStalledId);
}
});
return store.pendingRequests.add(request);
}
function isSearchResponseWithAutomaticInsightsFlag(items) {
return !Array.isArray(items) && Boolean(items === null || items === void 0 ? void 0 : items._automaticInsights);
}

View File

@@ -0,0 +1,8 @@
import { AutocompleteScopeApi, AutocompleteStore, BaseItem, InternalAutocompleteOptions } from './types';
interface OnKeyDownOptions<TItem extends BaseItem> extends AutocompleteScopeApi<TItem> {
event: KeyboardEvent;
props: InternalAutocompleteOptions<TItem>;
store: AutocompleteStore<TItem>;
}
export declare function onKeyDown<TItem extends BaseItem>({ event, props, refresh, store, ...setters }: OnKeyDownOptions<TItem>): void;
export {};

View File

@@ -0,0 +1,196 @@
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
var _excluded = ["event", "props", "refresh", "store"];
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
import { onInput } from './onInput';
import { getActiveItem, getAutocompleteElementId } from './utils';
export function onKeyDown(_ref) {
var event = _ref.event,
props = _ref.props,
refresh = _ref.refresh,
store = _ref.store,
setters = _objectWithoutProperties(_ref, _excluded);
if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
// eslint-disable-next-line no-inner-declarations
var triggerScrollIntoView = function triggerScrollIntoView() {
var highlightedItem = getActiveItem(store.getState());
var nodeItem = props.environment.document.getElementById(getAutocompleteElementId(props.id, "item-".concat(store.getState().activeItemId), highlightedItem === null || highlightedItem === void 0 ? void 0 : highlightedItem.source));
if (nodeItem) {
if (nodeItem.scrollIntoViewIfNeeded) {
nodeItem.scrollIntoViewIfNeeded(false);
} else {
nodeItem.scrollIntoView(false);
}
}
}; // eslint-disable-next-line no-inner-declarations
var triggerOnActive = function triggerOnActive() {
var highlightedItem = getActiveItem(store.getState());
if (store.getState().activeItemId !== null && highlightedItem) {
var item = highlightedItem.item,
itemInputValue = highlightedItem.itemInputValue,
itemUrl = highlightedItem.itemUrl,
source = highlightedItem.source;
source.onActive(_objectSpread({
event: event,
item: item,
itemInputValue: itemInputValue,
itemUrl: itemUrl,
refresh: refresh,
source: source,
state: store.getState()
}, setters));
}
}; // Default browser behavior changes the caret placement on ArrowUp and
// ArrowDown.
event.preventDefault();
// When re-opening the panel, we need to split the logic to keep the actions
// synchronized as `onInput` returns a promise.
if (store.getState().isOpen === false && (props.openOnFocus || Boolean(store.getState().query))) {
onInput(_objectSpread({
event: event,
props: props,
query: store.getState().query,
refresh: refresh,
store: store
}, setters)).then(function () {
store.dispatch(event.key, {
nextActiveItemId: props.defaultActiveItemId
});
triggerOnActive();
// Since we rely on the DOM, we need to wait for all the micro tasks to
// finish (which include re-opening the panel) to make sure all the
// elements are available.
setTimeout(triggerScrollIntoView, 0);
});
} else {
store.dispatch(event.key, {});
triggerOnActive();
triggerScrollIntoView();
}
} else if (event.key === 'Escape') {
// This prevents the default browser behavior on `input[type="search"]`
// from removing the query right away because we first want to close the
// panel.
event.preventDefault();
store.dispatch(event.key, null);
// Hitting the `Escape` key signals the end of a user interaction with the
// autocomplete. At this point, we should ignore any requests that are still
// pending and could reopen the panel once they resolve, because that would
// result in an unsolicited UI behavior.
store.pendingRequests.cancelAll();
} else if (event.key === 'Tab') {
store.dispatch('blur', null);
// Hitting the `Tab` key signals the end of a user interaction with the
// autocomplete. At this point, we should ignore any requests that are still
// pending and could reopen the panel once they resolve, because that would
// result in an unsolicited UI behavior.
store.pendingRequests.cancelAll();
} else if (event.key === 'Enter') {
// No active item, so we let the browser handle the native `onSubmit` form
// event.
if (store.getState().activeItemId === null || store.getState().collections.every(function (collection) {
return collection.items.length === 0;
})) {
// If requests are still pending when the panel closes, they could reopen
// the panel once they resolve.
// We want to prevent any subsequent query from reopening the panel
// because it would result in an unsolicited UI behavior.
if (!props.debug) {
store.pendingRequests.cancelAll();
}
return;
}
// This prevents the `onSubmit` event to be sent because an item is
// highlighted.
event.preventDefault();
var _ref2 = getActiveItem(store.getState()),
item = _ref2.item,
itemInputValue = _ref2.itemInputValue,
itemUrl = _ref2.itemUrl,
source = _ref2.source;
if (event.metaKey || event.ctrlKey) {
if (itemUrl !== undefined) {
source.onSelect(_objectSpread({
event: event,
item: item,
itemInputValue: itemInputValue,
itemUrl: itemUrl,
refresh: refresh,
source: source,
state: store.getState()
}, setters));
props.navigator.navigateNewTab({
itemUrl: itemUrl,
item: item,
state: store.getState()
});
}
} else if (event.shiftKey) {
if (itemUrl !== undefined) {
source.onSelect(_objectSpread({
event: event,
item: item,
itemInputValue: itemInputValue,
itemUrl: itemUrl,
refresh: refresh,
source: source,
state: store.getState()
}, setters));
props.navigator.navigateNewWindow({
itemUrl: itemUrl,
item: item,
state: store.getState()
});
}
} else if (event.altKey) {
// Keep native browser behavior
} else {
if (itemUrl !== undefined) {
source.onSelect(_objectSpread({
event: event,
item: item,
itemInputValue: itemInputValue,
itemUrl: itemUrl,
refresh: refresh,
source: source,
state: store.getState()
}, setters));
props.navigator.navigate({
itemUrl: itemUrl,
item: item,
state: store.getState()
});
return;
}
onInput(_objectSpread({
event: event,
nextState: {
isOpen: false
},
props: props,
query: itemInputValue,
refresh: refresh,
store: store
}, setters)).then(function () {
source.onSelect(_objectSpread({
event: event,
item: item,
itemInputValue: itemInputValue,
itemUrl: itemUrl,
refresh: refresh,
source: source,
state: store.getState()
}, setters));
});
}
}
}

View File

@@ -0,0 +1,11 @@
import { AutocompleteCollection, AutocompleteState, BaseItem, InternalAutocompleteOptions } from './types';
declare type ReshapeParams<TItem extends BaseItem> = {
collections: Array<AutocompleteCollection<any>>;
props: InternalAutocompleteOptions<TItem>;
state: AutocompleteState<TItem>;
};
export declare function reshape<TItem extends BaseItem>({ collections, props, state, }: ReshapeParams<TItem>): {
source: import("@algolia/autocomplete-shared/dist/esm/core/AutocompleteReshape").AutocompleteReshapeSource<TItem>;
items: TItem[];
}[];
export {};

View File

@@ -0,0 +1,45 @@
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
import { flatten } from '@algolia/autocomplete-shared';
export function reshape(_ref) {
var collections = _ref.collections,
props = _ref.props,
state = _ref.state;
// Sources are grouped by `sourceId` to conveniently pick them via destructuring.
// Example: `const { recentSearchesPlugin } = sourcesBySourceId`
var originalSourcesBySourceId = collections.reduce(function (acc, collection) {
return _objectSpread(_objectSpread({}, acc), {}, _defineProperty({}, collection.source.sourceId, _objectSpread(_objectSpread({}, collection.source), {}, {
getItems: function getItems() {
// We provide the resolved items from the collection to the `reshape` prop.
return flatten(collection.items);
}
})));
}, {});
var _props$plugins$reduce = props.plugins.reduce(function (acc, plugin) {
if (plugin.reshape) {
return plugin.reshape(acc);
}
return acc;
}, {
sourcesBySourceId: originalSourcesBySourceId,
state: state
}),
sourcesBySourceId = _props$plugins$reduce.sourcesBySourceId;
var reshapeSources = props.reshape({
sourcesBySourceId: sourcesBySourceId,
sources: Object.values(sourcesBySourceId),
state: state
});
// We reconstruct the collections with the items modified by the `reshape` prop.
return flatten(reshapeSources).filter(Boolean).map(function (source) {
return {
source: source,
items: source.getItems()
};
});
}

View File

@@ -0,0 +1,43 @@
import type { ExecuteResponse, RequesterDescription, TransformResponse } from '@algolia/autocomplete-preset-algolia';
import type { SearchResponse } from '@algolia/autocomplete-shared';
import { MultipleQueriesQuery, SearchForFacetValuesResponse } from '@algolia/client-search';
import { AutocompleteState, AutocompleteStore, BaseItem, InternalAutocompleteSource } from './types';
declare type RequestDescriptionPreResolved<TItem extends BaseItem> = Pick<RequesterDescription<TItem>, 'execute' | 'requesterId' | 'searchClient' | 'transformResponse'> & {
requests: Array<{
query: MultipleQueriesQuery;
sourceId: string;
transformResponse: TransformResponse<TItem>;
}>;
};
declare type RequestDescriptionPreResolvedCustom<TItem extends BaseItem> = {
items: TItem[] | TItem[][];
sourceId: string;
transformResponse?: undefined;
};
export declare function preResolve<TItem extends BaseItem>(itemsOrDescription: TItem[] | TItem[][] | RequesterDescription<TItem>, sourceId: string, state: AutocompleteState<TItem>): RequestDescriptionPreResolved<TItem> | RequestDescriptionPreResolvedCustom<TItem>;
export declare function resolve<TItem extends BaseItem>(items: Array<RequestDescriptionPreResolved<TItem> | RequestDescriptionPreResolvedCustom<TItem>>): Promise<(RequestDescriptionPreResolvedCustom<TItem> | {
items: SearchForFacetValuesResponse | SearchResponse<TItem>;
sourceId: string;
transformResponse: TransformResponse<TItem>;
})[]>;
export declare function postResolve<TItem extends BaseItem>(responses: Array<RequestDescriptionPreResolvedCustom<TItem> | ExecuteResponse<TItem>[0]>, sources: Array<InternalAutocompleteSource<TItem>>, store: AutocompleteStore<TItem>): {
source: InternalAutocompleteSource<TItem>;
items: {
label: string;
count: number;
_highlightResult: {
label: {
value: string;
};
};
}[][] | {
label: string;
count: number;
_highlightResult: {
label: {
value: string;
};
};
}[] | import("@algolia/client-search").Hit<TItem>[] | (SearchForFacetValuesResponse | SearchResponse<TItem> | TItem[] | TItem[][])[];
}[];
export {};

View File

@@ -0,0 +1,114 @@
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
import { decycle, flatten, invariant } from '@algolia/autocomplete-shared';
import { mapToAlgoliaResponse } from './utils';
function isDescription(item) {
return Boolean(item.execute);
}
function isRequesterDescription(description) {
return Boolean(description === null || description === void 0 ? void 0 : description.execute);
}
export function preResolve(itemsOrDescription, sourceId, state) {
if (isRequesterDescription(itemsOrDescription)) {
var contextParameters = itemsOrDescription.requesterId === 'algolia' ? Object.assign.apply(Object, [{}].concat(_toConsumableArray(Object.keys(state.context).map(function (key) {
var _state$context$key;
return (_state$context$key = state.context[key]) === null || _state$context$key === void 0 ? void 0 : _state$context$key.__algoliaSearchParameters;
})))) : {};
return _objectSpread(_objectSpread({}, itemsOrDescription), {}, {
requests: itemsOrDescription.queries.map(function (query) {
return {
query: itemsOrDescription.requesterId === 'algolia' ? _objectSpread(_objectSpread({}, query), {}, {
params: _objectSpread(_objectSpread({}, contextParameters), query.params)
}) : query,
sourceId: sourceId,
transformResponse: itemsOrDescription.transformResponse
};
})
});
}
return {
items: itemsOrDescription,
sourceId: sourceId
};
}
export function resolve(items) {
var packed = items.reduce(function (acc, current) {
if (!isDescription(current)) {
acc.push(current);
return acc;
}
var searchClient = current.searchClient,
execute = current.execute,
requesterId = current.requesterId,
requests = current.requests;
var container = acc.find(function (item) {
return isDescription(current) && isDescription(item) && item.searchClient === searchClient && Boolean(requesterId) && item.requesterId === requesterId;
});
if (container) {
var _container$items;
(_container$items = container.items).push.apply(_container$items, _toConsumableArray(requests));
} else {
var request = {
execute: execute,
requesterId: requesterId,
items: requests,
searchClient: searchClient
};
acc.push(request);
}
return acc;
}, []);
var values = packed.map(function (maybeDescription) {
if (!isDescription(maybeDescription)) {
return Promise.resolve(maybeDescription);
}
var _ref = maybeDescription,
execute = _ref.execute,
items = _ref.items,
searchClient = _ref.searchClient;
return execute({
searchClient: searchClient,
requests: items
});
});
return Promise.all(values).then(function (responses) {
return flatten(responses);
});
}
export function postResolve(responses, sources, store) {
return sources.map(function (source) {
var matches = responses.filter(function (response) {
return response.sourceId === source.sourceId;
});
var results = matches.map(function (_ref2) {
var items = _ref2.items;
return items;
});
var transform = matches[0].transformResponse;
var items = transform ? transform(mapToAlgoliaResponse(results)) : results;
source.onResolve({
source: source,
results: results,
items: items,
state: store.getState()
});
invariant(Array.isArray(items), function () {
return "The `getItems` function from source \"".concat(source.sourceId, "\" must return an array of items but returned type ").concat(JSON.stringify(_typeof(items)), ":\n\n").concat(JSON.stringify(decycle(items), null, 2), ".\n\nSee: https://www.algolia.com/doc/ui-libraries/autocomplete/core-concepts/sources/#param-getitems");
});
invariant(items.every(Boolean), "The `getItems` function from source \"".concat(source.sourceId, "\" must return an array of items but returned ").concat(JSON.stringify(undefined), ".\n\nDid you forget to return items?\n\nSee: https://www.algolia.com/doc/ui-libraries/autocomplete/core-concepts/sources/#param-getitems"));
return {
source: source,
items: items
};
});
}

View File

@@ -0,0 +1,2 @@
import { Reducer } from './types';
export declare const stateReducer: Reducer;

View File

@@ -0,0 +1,145 @@
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
import { getItemsCount, invariant } from '@algolia/autocomplete-shared';
import { getCompletion } from './getCompletion';
import { getNextActiveItemId } from './utils';
export var stateReducer = function stateReducer(state, action) {
switch (action.type) {
case 'setActiveItemId':
{
return _objectSpread(_objectSpread({}, state), {}, {
activeItemId: action.payload
});
}
case 'setQuery':
{
return _objectSpread(_objectSpread({}, state), {}, {
query: action.payload,
completion: null
});
}
case 'setCollections':
{
return _objectSpread(_objectSpread({}, state), {}, {
collections: action.payload
});
}
case 'setIsOpen':
{
return _objectSpread(_objectSpread({}, state), {}, {
isOpen: action.payload
});
}
case 'setStatus':
{
return _objectSpread(_objectSpread({}, state), {}, {
status: action.payload
});
}
case 'setContext':
{
return _objectSpread(_objectSpread({}, state), {}, {
context: _objectSpread(_objectSpread({}, state.context), action.payload)
});
}
case 'ArrowDown':
{
var nextState = _objectSpread(_objectSpread({}, state), {}, {
activeItemId: action.payload.hasOwnProperty('nextActiveItemId') ? action.payload.nextActiveItemId : getNextActiveItemId(1, state.activeItemId, getItemsCount(state), action.props.defaultActiveItemId)
});
return _objectSpread(_objectSpread({}, nextState), {}, {
completion: getCompletion({
state: nextState
})
});
}
case 'ArrowUp':
{
var _nextState = _objectSpread(_objectSpread({}, state), {}, {
activeItemId: getNextActiveItemId(-1, state.activeItemId, getItemsCount(state), action.props.defaultActiveItemId)
});
return _objectSpread(_objectSpread({}, _nextState), {}, {
completion: getCompletion({
state: _nextState
})
});
}
case 'Escape':
{
if (state.isOpen) {
return _objectSpread(_objectSpread({}, state), {}, {
activeItemId: null,
isOpen: false,
completion: null
});
}
return _objectSpread(_objectSpread({}, state), {}, {
activeItemId: null,
query: '',
status: 'idle',
collections: []
});
}
case 'submit':
{
return _objectSpread(_objectSpread({}, state), {}, {
activeItemId: null,
isOpen: false,
status: 'idle'
});
}
case 'reset':
{
return _objectSpread(_objectSpread({}, state), {}, {
activeItemId:
// Since we open the panel on reset when openOnFocus=true
// we need to restore the highlighted index to the defaultActiveItemId. (DocSearch use-case)
// Since we close the panel when openOnFocus=false
// we lose track of the highlighted index. (Query-suggestions use-case)
action.props.openOnFocus === true ? action.props.defaultActiveItemId : null,
status: 'idle',
completion: null,
query: ''
});
}
case 'focus':
{
return _objectSpread(_objectSpread({}, state), {}, {
activeItemId: action.props.defaultActiveItemId,
isOpen: (action.props.openOnFocus || Boolean(state.query)) && action.props.shouldPanelOpen({
state: state
})
});
}
case 'blur':
{
if (action.props.debug) {
return state;
}
return _objectSpread(_objectSpread({}, state), {}, {
isOpen: false,
activeItemId: null
});
}
case 'mousemove':
{
return _objectSpread(_objectSpread({}, state), {}, {
activeItemId: action.payload
});
}
case 'mouseleave':
{
return _objectSpread(_objectSpread({}, state), {}, {
activeItemId: action.props.defaultActiveItemId
});
}
default:
invariant(false, "The reducer action ".concat(JSON.stringify(action.type), " is not supported."));
return state;
}
};

View File

@@ -0,0 +1,15 @@
import { CancelablePromiseList } from '../utils';
import { BaseItem, InternalAutocompleteOptions, AutocompleteState } from './';
export interface AutocompleteStore<TItem extends BaseItem> {
getState(): AutocompleteState<TItem>;
dispatch(action: ActionType, payload: any): void;
pendingRequests: CancelablePromiseList<void>;
}
export declare type Reducer = <TItem extends BaseItem>(state: AutocompleteState<TItem>, action: Action<TItem, any>) => AutocompleteState<TItem>;
declare type Action<TItem extends BaseItem, TPayload> = {
type: ActionType;
props: InternalAutocompleteOptions<TItem>;
payload: TPayload;
};
export declare type ActionType = 'setActiveItemId' | 'setQuery' | 'setCollections' | 'setIsOpen' | 'setStatus' | 'setContext' | 'ArrowUp' | 'ArrowDown' | 'Escape' | 'Enter' | 'submit' | 'reset' | 'focus' | 'blur' | 'mousemove' | 'mouseleave' | 'click';
export {};

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,7 @@
import { BaseItem, OnActiveParams, OnResolveParams, OnSelectParams } from './';
export declare type AutocompleteSubscriber<TItem extends BaseItem> = {
onSelect(params: OnSelectParams<TItem>): void;
onActive(params: OnActiveParams<TItem>): void;
onResolve(params: OnResolveParams<TItem>): void;
};
export declare type AutocompleteSubscribers<TItem extends BaseItem> = Array<Partial<AutocompleteSubscriber<TItem>>>;

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,22 @@
export * from '@algolia/autocomplete-shared/dist/esm/core';
export * from './AutocompleteStore';
export * from './AutocompleteSubscribers';
import { CreateAlgoliaInsightsPluginParams, AutocompleteInsightsApi as _AutocompleteInsightsApi, AlgoliaInsightsHit as _AlgoliaInsightsHit } from '@algolia/autocomplete-plugin-algolia-insights';
import { AutocompleteOptions as _AutocompleteOptions, InternalAutocompleteOptions as _InternalAutocompleteOptions, BaseItem } from '@algolia/autocomplete-shared/dist/esm/core';
export declare type AutocompleteInsightsApi = _AutocompleteInsightsApi;
export declare type AlgoliaInsightsHit = _AlgoliaInsightsHit;
declare type InsightsOption = {
/**
* Whether to enable the Insights plugin and load the Insights library if it has not been loaded yet.
*
* See [**autocomplete-plugin-algolia-insights**](https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-algolia-insights/) for more information.
*
* @default undefined
* @link https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-js/autocomplete/#param-insights
*/
insights?: CreateAlgoliaInsightsPluginParams | boolean | undefined;
};
export interface AutocompleteOptions<TItem extends BaseItem> extends _AutocompleteOptions<TItem>, InsightsOption {
}
export interface InternalAutocompleteOptions<TItem extends BaseItem> extends _InternalAutocompleteOptions<TItem>, InsightsOption {
}

View File

@@ -0,0 +1,4 @@
export * from '@algolia/autocomplete-shared/dist/esm/core';
export * from './AutocompleteStore';
export * from './AutocompleteSubscribers';
export {};

View File

@@ -0,0 +1,15 @@
declare type PromiseExecutor<TValue> = (resolve: (value: TValue | PromiseLike<TValue>) => void, reject: (reason?: any) => void) => void;
export declare type CancelablePromise<TValue> = {
then<TResultFulfilled = TValue, TResultRejected = never>(onfulfilled?: ((value: TValue) => TResultFulfilled | PromiseLike<TResultFulfilled> | CancelablePromise<TResultFulfilled>) | undefined | null, onrejected?: ((reason: any) => TResultRejected | PromiseLike<TResultRejected> | CancelablePromise<TResultRejected>) | undefined | null): CancelablePromise<TResultFulfilled | TResultRejected>;
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult> | CancelablePromise<TResult>) | undefined | null): CancelablePromise<TValue | TResult>;
finally(onfinally?: (() => void) | undefined | null): CancelablePromise<TValue>;
cancel(): void;
isCanceled(): boolean;
};
export declare function createCancelablePromise<TValue>(executor: PromiseExecutor<TValue>): CancelablePromise<TValue>;
export declare namespace createCancelablePromise {
var resolve: <TValue>(value?: TValue | PromiseLike<TValue> | CancelablePromise<TValue> | undefined) => CancelablePromise<TValue | CancelablePromise<TValue> | undefined>;
var reject: (reason?: any) => CancelablePromise<never>;
}
export declare function cancelable<TValue>(promise: Promise<TValue>): CancelablePromise<TValue>;
export {};

View File

@@ -0,0 +1,62 @@
function createInternalCancelablePromise(promise, initialState) {
var state = initialState;
return {
then: function then(onfulfilled, onrejected) {
return createInternalCancelablePromise(promise.then(createCallback(onfulfilled, state, promise), createCallback(onrejected, state, promise)), state);
},
catch: function _catch(onrejected) {
return createInternalCancelablePromise(promise.catch(createCallback(onrejected, state, promise)), state);
},
finally: function _finally(onfinally) {
if (onfinally) {
state.onCancelList.push(onfinally);
}
return createInternalCancelablePromise(promise.finally(createCallback(onfinally && function () {
state.onCancelList = [];
return onfinally();
}, state, promise)), state);
},
cancel: function cancel() {
state.isCanceled = true;
var callbacks = state.onCancelList;
state.onCancelList = [];
callbacks.forEach(function (callback) {
callback();
});
},
isCanceled: function isCanceled() {
return state.isCanceled === true;
}
};
}
export function createCancelablePromise(executor) {
return createInternalCancelablePromise(new Promise(function (resolve, reject) {
return executor(resolve, reject);
}), {
isCanceled: false,
onCancelList: []
});
}
createCancelablePromise.resolve = function (value) {
return cancelable(Promise.resolve(value));
};
createCancelablePromise.reject = function (reason) {
return cancelable(Promise.reject(reason));
};
export function cancelable(promise) {
return createInternalCancelablePromise(promise, {
isCanceled: false,
onCancelList: []
});
}
function createCallback(onResult, state, fallback) {
if (!onResult) {
return fallback;
}
return function callback(arg) {
if (state.isCanceled) {
return arg;
}
return onResult(arg);
};
}

View File

@@ -0,0 +1,21 @@
import { CancelablePromise } from '.';
export declare type CancelablePromiseList<TValue> = {
/**
* Add a cancelable promise to the list.
*
* @param cancelablePromise The cancelable promise to add.
*/
add(cancelablePromise: CancelablePromise<TValue>): CancelablePromise<TValue>;
/**
* Cancel all pending promises.
*
* Requests aren't actually stopped. All pending promises will settle, but
* attached handlers won't run.
*/
cancelAll(): void;
/**
* Whether there are pending promises in the list.
*/
isEmpty(): boolean;
};
export declare function createCancelablePromiseList<TValue>(): CancelablePromiseList<TValue>;

View File

@@ -0,0 +1,21 @@
export function createCancelablePromiseList() {
var list = [];
return {
add: function add(cancelablePromise) {
list.push(cancelablePromise);
return cancelablePromise.finally(function () {
list = list.filter(function (item) {
return item !== cancelablePromise;
});
});
},
cancelAll: function cancelAll() {
list.forEach(function (promise) {
return promise.cancel();
});
},
isEmpty: function isEmpty() {
return list.length === 0;
}
};
}

View File

@@ -0,0 +1,8 @@
import { MaybePromise } from '@algolia/autocomplete-shared';
/**
* Creates a runner that executes promises in a concurrent-safe way.
*
* This is useful to prevent older promises to resolve after a newer promise,
* otherwise resulting in stale resolved values.
*/
export declare function createConcurrentSafePromise(): <TValue>(promise: MaybePromise<TValue>) => Promise<TValue>;

View File

@@ -0,0 +1,36 @@
/**
* Creates a runner that executes promises in a concurrent-safe way.
*
* This is useful to prevent older promises to resolve after a newer promise,
* otherwise resulting in stale resolved values.
*/
export function createConcurrentSafePromise() {
var basePromiseId = -1;
var latestResolvedId = -1;
var latestResolvedValue = undefined;
return function runConcurrentSafePromise(promise) {
basePromiseId++;
var currentPromiseId = basePromiseId;
return Promise.resolve(promise).then(function (x) {
// The promise might take too long to resolve and get outdated. This would
// result in resolving stale values.
// When this happens, we ignore the promise value and return the one
// coming from the latest resolved value.
//
// +----------------------------------+
// | 100ms |
// | run(1) +---> R1 |
// | 300ms |
// | run(2) +-------------> R2 (SKIP) |
// | 200ms |
// | run(3) +--------> R3 |
// +----------------------------------+
if (latestResolvedValue && currentPromiseId < latestResolvedId) {
return latestResolvedValue;
}
latestResolvedId = currentPromiseId;
latestResolvedValue = x;
return x;
});
};
}

View File

@@ -0,0 +1,7 @@
import { AutocompleteState, BaseItem } from '../types';
export declare function getActiveItem<TItem extends BaseItem>(state: AutocompleteState<TItem>): {
item: TItem;
itemInputValue: string;
itemUrl: string | undefined;
source: import("@algolia/autocomplete-shared/dist/esm/core/AutocompleteSource").InternalAutocompleteSource<TItem>;
} | null;

View File

@@ -0,0 +1,77 @@
// We don't have access to the autocomplete source when we call `onKeyDown`
// or `onClick` because those are native browser events.
// However, we can get the source from the suggestion index.
function getCollectionFromActiveItemId(state) {
// Given 3 sources with respectively 1, 2 and 3 suggestions: [1, 2, 3]
// We want to get the accumulated counts:
// [1, 1 + 2, 1 + 2 + 3] = [1, 3, 3 + 3] = [1, 3, 6]
var accumulatedCollectionsCount = state.collections.map(function (collections) {
return collections.items.length;
}).reduce(function (acc, collectionsCount, index) {
var previousValue = acc[index - 1] || 0;
var nextValue = previousValue + collectionsCount;
acc.push(nextValue);
return acc;
}, []);
// Based on the accumulated counts, we can infer the index of the suggestion.
var collectionIndex = accumulatedCollectionsCount.reduce(function (acc, current) {
if (current <= state.activeItemId) {
return acc + 1;
}
return acc;
}, 0);
return state.collections[collectionIndex];
}
/**
* Gets the highlighted index relative to a suggestion object (not the absolute
* highlighted index).
*
* Example:
* [['a', 'b'], ['c', 'd', 'e'], ['f']]
* ↑
* (absolute: 3, relative: 1)
*/
function getRelativeActiveItemId(_ref) {
var state = _ref.state,
collection = _ref.collection;
var isOffsetFound = false;
var counter = 0;
var previousItemsOffset = 0;
while (isOffsetFound === false) {
var currentCollection = state.collections[counter];
if (currentCollection === collection) {
isOffsetFound = true;
break;
}
previousItemsOffset += currentCollection.items.length;
counter++;
}
return state.activeItemId - previousItemsOffset;
}
export function getActiveItem(state) {
var collection = getCollectionFromActiveItemId(state);
if (!collection) {
return null;
}
var item = collection.items[getRelativeActiveItemId({
state: state,
collection: collection
})];
var source = collection.source;
var itemInputValue = source.getItemInputValue({
item: item,
state: state
});
var itemUrl = source.getItemUrl({
item: item,
state: state
});
return {
item: item,
itemInputValue: itemInputValue,
itemUrl: itemUrl,
source: source
};
}

View File

@@ -0,0 +1,9 @@
import type { InternalAutocompleteSource } from '../types';
/**
* Returns a full element id for an autocomplete element.
*
* @param autocompleteInstanceId The id of the autocomplete instance
* @param elementId The specific element id
* @param source The source of the element, when it needs to be scoped
*/
export declare function getAutocompleteElementId(autocompleteInstanceId: string, elementId: string, source?: InternalAutocompleteSource<any>): string;

View File

@@ -0,0 +1,10 @@
/**
* Returns a full element id for an autocomplete element.
*
* @param autocompleteInstanceId The id of the autocomplete instance
* @param elementId The specific element id
* @param source The source of the element, when it needs to be scoped
*/
export function getAutocompleteElementId(autocompleteInstanceId, elementId, source) {
return [autocompleteInstanceId, source === null || source === void 0 ? void 0 : source.sourceId, elementId].filter(Boolean).join('-').replace(/\s/g, '');
}

View File

@@ -0,0 +1 @@
export declare function getNativeEvent<TEvent>(event: TEvent): TEvent;

View File

@@ -0,0 +1,3 @@
export function getNativeEvent(event) {
return event.nativeEvent || event;
}

View File

@@ -0,0 +1,17 @@
/**
* Returns the next active item ID from the current state.
*
* We allow circular keyboard navigation from the base index.
* The base index can either be `null` (nothing is highlighted) or `0`
* (the first item is highlighted).
* The base index is allowed to get assigned `null` only if
* `props.defaultActiveItemId` is `null`. This pattern allows to "stop"
* by the actual query before navigating to other suggestions as seen on
* Google or Amazon.
*
* @param moveAmount The offset to increment (or decrement) the last index
* @param baseIndex The current index to compute the next index from
* @param itemCount The number of items
* @param defaultActiveItemId The default active index to fallback to
*/
export declare function getNextActiveItemId(moveAmount: number, baseIndex: number | null, itemCount: number, defaultActiveItemId: number | null): number | null;

View File

@@ -0,0 +1,29 @@
/**
* Returns the next active item ID from the current state.
*
* We allow circular keyboard navigation from the base index.
* The base index can either be `null` (nothing is highlighted) or `0`
* (the first item is highlighted).
* The base index is allowed to get assigned `null` only if
* `props.defaultActiveItemId` is `null`. This pattern allows to "stop"
* by the actual query before navigating to other suggestions as seen on
* Google or Amazon.
*
* @param moveAmount The offset to increment (or decrement) the last index
* @param baseIndex The current index to compute the next index from
* @param itemCount The number of items
* @param defaultActiveItemId The default active index to fallback to
*/
export function getNextActiveItemId(moveAmount, baseIndex, itemCount, defaultActiveItemId) {
if (!itemCount) {
return null;
}
if (moveAmount < 0 && (baseIndex === null || defaultActiveItemId !== null && baseIndex === 0)) {
return itemCount + moveAmount;
}
var numericIndex = (baseIndex === null ? -1 : baseIndex) + moveAmount;
if (numericIndex <= -1 || numericIndex >= itemCount) {
return defaultActiveItemId === null ? null : 0;
}
return numericIndex;
}

View File

@@ -0,0 +1,2 @@
import { BaseItem, GetSources, GetSourcesParams, InternalGetSources } from '../types';
export declare function getNormalizedSources<TItem extends BaseItem>(getSources: GetSources<TItem>, params: GetSourcesParams<TItem>): ReturnType<InternalGetSources<TItem>>;

View File

@@ -0,0 +1,48 @@
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
import { invariant, decycle, noop } from '@algolia/autocomplete-shared';
export function getNormalizedSources(getSources, params) {
var seenSourceIds = [];
return Promise.resolve(getSources(params)).then(function (sources) {
invariant(Array.isArray(sources), function () {
return "The `getSources` function must return an array of sources but returned type ".concat(JSON.stringify(_typeof(sources)), ":\n\n").concat(JSON.stringify(decycle(sources), null, 2));
});
return Promise.all(sources
// We allow `undefined` and `false` sources to allow users to use
// `Boolean(query) && source` (=> `false`).
// We need to remove these values at this point.
.filter(function (maybeSource) {
return Boolean(maybeSource);
}).map(function (source) {
invariant(typeof source.sourceId === 'string', 'A source must provide a `sourceId` string.');
if (seenSourceIds.includes(source.sourceId)) {
throw new Error("[Autocomplete] The `sourceId` ".concat(JSON.stringify(source.sourceId), " is not unique."));
}
seenSourceIds.push(source.sourceId);
var defaultSource = {
getItemInputValue: function getItemInputValue(_ref) {
var state = _ref.state;
return state.query;
},
getItemUrl: function getItemUrl() {
return undefined;
},
onSelect: function onSelect(_ref2) {
var setIsOpen = _ref2.setIsOpen;
setIsOpen(false);
},
onActive: noop,
onResolve: noop
};
Object.keys(defaultSource).forEach(function (key) {
defaultSource[key].__default = true;
});
var normalizedSource = _objectSpread(_objectSpread({}, defaultSource), source);
return Promise.resolve(normalizedSource);
}));
});
}

View File

@@ -0,0 +1,11 @@
export * from './createCancelablePromise';
export * from './createCancelablePromiseList';
export * from './createConcurrentSafePromise';
export * from './getNextActiveItemId';
export * from './getNormalizedSources';
export * from './getActiveItem';
export * from './getAutocompleteElementId';
export * from './isOrContainsNode';
export * from './isSamsung';
export * from './mapToAlgoliaResponse';
export * from './getNativeEvent';

View File

@@ -0,0 +1,11 @@
export * from './createCancelablePromise';
export * from './createCancelablePromiseList';
export * from './createConcurrentSafePromise';
export * from './getNextActiveItemId';
export * from './getNormalizedSources';
export * from './getActiveItem';
export * from './getAutocompleteElementId';
export * from './isOrContainsNode';
export * from './isSamsung';
export * from './mapToAlgoliaResponse';
export * from './getNativeEvent';

View File

@@ -0,0 +1 @@
export declare function isOrContainsNode(parent: Node, child: Node): boolean;

View File

@@ -0,0 +1,3 @@
export function isOrContainsNode(parent, child) {
return parent === child || parent.contains(child);
}

View File

@@ -0,0 +1 @@
export declare function isSamsung(userAgent: string): boolean;

View File

@@ -0,0 +1,4 @@
var regex = /((gt|sm)-|galaxy nexus)|samsung[- ]|samsungbrowser/i;
export function isSamsung(userAgent) {
return Boolean(userAgent && userAgent.match(regex));
}

View File

@@ -0,0 +1,15 @@
import type { SearchResponse } from '@algolia/autocomplete-shared';
import type { SearchForFacetValuesResponse } from '@algolia/client-search';
export declare function mapToAlgoliaResponse<THit>(rawResults: Array<SearchResponse<THit> | SearchForFacetValuesResponse>): {
results: (SearchResponse<THit> | SearchForFacetValuesResponse)[];
hits: import("@algolia/client-search").Hit<THit>[][];
facetHits: {
label: string;
count: number;
_highlightResult: {
label: {
value: string;
};
};
}[][];
};

View File

@@ -0,0 +1,23 @@
export function mapToAlgoliaResponse(rawResults) {
return {
results: rawResults,
hits: rawResults.map(function (result) {
return result.hits;
}).filter(Boolean),
facetHits: rawResults.map(function (result) {
var _facetHits;
return (_facetHits = result.facetHits) === null || _facetHits === void 0 ? void 0 : _facetHits.map(function (facetHit) {
// Bring support for the highlighting components.
return {
label: facetHit.value,
count: facetHit.count,
_highlightResult: {
label: {
value: facetHit.highlighted
}
}
};
});
}).filter(Boolean)
};
}

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

42
node_modules/@algolia/autocomplete-core/package.json generated vendored Normal file
View File

@@ -0,0 +1,42 @@
{
"name": "@algolia/autocomplete-core",
"description": "Core primitives for building autocomplete experiences.",
"version": "1.17.7",
"license": "MIT",
"homepage": "https://github.com/algolia/autocomplete",
"repository": "algolia/autocomplete",
"author": {
"name": "Algolia, Inc.",
"url": "https://www.algolia.com"
},
"source": "src/index.ts",
"types": "dist/esm/index.d.ts",
"module": "dist/esm/index.js",
"main": "dist/umd/index.production.js",
"umd:main": "dist/umd/index.production.js",
"unpkg": "dist/umd/index.production.js",
"jsdelivr": "dist/umd/index.production.js",
"sideEffects": false,
"files": [
"dist/"
],
"scripts": {
"build:clean": "rm -rf ./dist",
"build:esm": "babel src --root-mode upward --extensions '.ts,.tsx' --out-dir dist/esm --ignore '**/*/__tests__/'",
"build:types": "tsc -p ./tsconfig.declaration.json --outDir ./dist/esm",
"build:umd": "rollup --config",
"build": "yarn build:clean && yarn build:umd && yarn build:esm && yarn build:types",
"on:change": "concurrently \"yarn build:esm\" \"yarn build:types\"",
"prepare": "yarn build:esm && yarn build:types",
"watch": "watch \"yarn on:change\" --ignoreDirectoryPattern \"/dist/\""
},
"dependencies": {
"@algolia/autocomplete-plugin-algolia-insights": "1.17.7",
"@algolia/autocomplete-shared": "1.17.7"
},
"devDependencies": {
"@algolia/autocomplete-preset-algolia": "1.17.7",
"@algolia/client-search": "4.16.0",
"algoliasearch": "4.16.0"
}
}

View File

@@ -0,0 +1,15 @@
# @algolia/autocomplete-plugin-algolia-insights
The Algolia Insights plugin automatically sends click and conversion events to the [Algolia Insights API](https://www.algolia.com/doc/rest-api/insights]) whenever a user interacts with the autocomplete.
## Installation
```sh
yarn add @algolia/autocomplete-plugin-algolia-insights
# or
npm install @algolia/autocomplete-plugin-algolia-insights
```
## Documentation
See [**Documentation**](https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-algolia-insights).

View File

@@ -0,0 +1,47 @@
import { AutocompletePlugin } from '@algolia/autocomplete-shared';
import { InsightsClient, InsightsMethodMap, OnActiveParams, OnItemsChangeParams, OnSelectParams } from './types';
export declare type CreateAlgoliaInsightsPluginParams = {
/**
* The initialized Search Insights client.
*
* @link https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-algolia-insights/createAlgoliaInsightsPlugin/#param-insightsclient
*/
insightsClient?: InsightsClient;
/**
* Insights parameters to forward to the Insights clients init method.
*
* @link https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-algolia-insights/createAlgoliaInsightsPlugin/#param-insightsinitparams
*/
insightsInitParams?: Partial<InsightsMethodMap['init'][0]>;
/**
* Hook to send an Insights event when the items change.
*
* By default, it sends a `viewedObjectIDs` event.
*
* In as-you-type experiences, items change as the user types. This hook is debounced every 400ms to reflect actual items that users notice and avoid generating too many events for items matching "in progress" queries.
*
* @link https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-algolia-insights/createAlgoliaInsightsPlugin/#param-onitemschange
*/
onItemsChange?(params: OnItemsChangeParams): void;
/**
* Hook to send an Insights event when an item is selected.
*
* By default, it sends a clickedObjectIDsAfterSearch event.
*
* @link https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-algolia-insights/createAlgoliaInsightsPlugin/#param-onselect
*/
onSelect?(params: OnSelectParams): void;
/**
* Hook to send an Insights event when an item is active.
*
* By default, it doesn't send any events.
*
* @link https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-algolia-insights/createAlgoliaInsightsPlugin/#param-onactive
*/
onActive?(params: OnActiveParams): void;
/**
* @internal
*/
__autocomplete_clickAnalytics?: boolean;
};
export declare function createAlgoliaInsightsPlugin(options: CreateAlgoliaInsightsPluginParams): AutocompletePlugin<any, undefined>;

View File

@@ -0,0 +1,269 @@
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
import { createRef, debounce, isEqual, noop, safelyRunOnBrowser } from '@algolia/autocomplete-shared';
import { createClickedEvent } from './createClickedEvent';
import { createSearchInsightsApi } from './createSearchInsightsApi';
import { createViewedEvents } from './createViewedEvents';
import { isAlgoliaInsightsHit } from './isAlgoliaInsightsHit';
var VIEW_EVENT_DELAY = 400;
var ALGOLIA_INSIGHTS_VERSION = '2.15.0';
var ALGOLIA_INSIGHTS_SRC = "https://cdn.jsdelivr.net/npm/search-insights@".concat(ALGOLIA_INSIGHTS_VERSION, "/dist/search-insights.min.js");
var sendViewedObjectIDs = debounce(function (_ref) {
var onItemsChange = _ref.onItemsChange,
items = _ref.items,
insights = _ref.insights,
state = _ref.state;
onItemsChange({
insights: insights,
insightsEvents: createViewedEvents({
items: items
}).map(function (event) {
return _objectSpread({
eventName: 'Items Viewed'
}, event);
}),
state: state
});
}, VIEW_EVENT_DELAY);
export function createAlgoliaInsightsPlugin(options) {
var _getOptions = getOptions(options),
providedInsightsClient = _getOptions.insightsClient,
insightsInitParams = _getOptions.insightsInitParams,
onItemsChange = _getOptions.onItemsChange,
onSelectEvent = _getOptions.onSelect,
onActiveEvent = _getOptions.onActive,
__autocomplete_clickAnalytics = _getOptions.__autocomplete_clickAnalytics;
var insightsClient = providedInsightsClient;
if (!providedInsightsClient) {
safelyRunOnBrowser(function (_ref2) {
var window = _ref2.window;
var pointer = window.AlgoliaAnalyticsObject || 'aa';
if (typeof pointer === 'string') {
insightsClient = window[pointer];
}
if (!insightsClient) {
window.AlgoliaAnalyticsObject = pointer;
if (!window[pointer]) {
window[pointer] = function () {
if (!window[pointer].queue) {
window[pointer].queue = [];
}
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
window[pointer].queue.push(args);
};
}
window[pointer].version = ALGOLIA_INSIGHTS_VERSION;
insightsClient = window[pointer];
loadInsights(window);
}
});
}
// We return an empty plugin if `insightsClient` is still undefined at
// this stage, which can happen in server environments.
if (!insightsClient) {
return {};
}
if (insightsInitParams) {
insightsClient('init', _objectSpread({
partial: true
}, insightsInitParams));
}
var insights = createSearchInsightsApi(insightsClient);
var previousItems = createRef([]);
var debouncedOnStateChange = debounce(function (_ref3) {
var state = _ref3.state;
if (!state.isOpen) {
return;
}
var items = state.collections.reduce(function (acc, current) {
return [].concat(_toConsumableArray(acc), _toConsumableArray(current.items));
}, []).filter(isAlgoliaInsightsHit);
if (!isEqual(previousItems.current.map(function (x) {
return x.objectID;
}), items.map(function (x) {
return x.objectID;
}))) {
previousItems.current = items;
if (items.length > 0) {
sendViewedObjectIDs({
onItemsChange: onItemsChange,
items: items,
insights: insights,
state: state
});
}
}
}, 0);
return {
name: 'aa.algoliaInsightsPlugin',
subscribe: function subscribe(_ref4) {
var setContext = _ref4.setContext,
onSelect = _ref4.onSelect,
onActive = _ref4.onActive;
var isAuthenticatedToken = false;
function setInsightsContext(userToken) {
setContext({
algoliaInsightsPlugin: {
__algoliaSearchParameters: _objectSpread(_objectSpread({}, __autocomplete_clickAnalytics ? {
clickAnalytics: true
} : {}), userToken ? {
userToken: normalizeUserToken(userToken)
} : {}),
insights: insights
}
});
}
insightsClient('addAlgoliaAgent', 'insights-plugin');
setInsightsContext();
// Handles user token changes
insightsClient('onUserTokenChange', function (userToken) {
if (!isAuthenticatedToken) {
setInsightsContext(userToken);
}
});
insightsClient('getUserToken', null, function (_error, userToken) {
if (!isAuthenticatedToken) {
setInsightsContext(userToken);
}
});
// Handles authenticated user token changes
insightsClient('onAuthenticatedUserTokenChange', function (authenticatedUserToken) {
if (authenticatedUserToken) {
isAuthenticatedToken = true;
setInsightsContext(authenticatedUserToken);
} else {
isAuthenticatedToken = false;
insightsClient('getUserToken', null, function (_error, userToken) {
return setInsightsContext(userToken);
});
}
});
insightsClient('getAuthenticatedUserToken', null, function (_error, authenticatedUserToken) {
if (authenticatedUserToken) {
isAuthenticatedToken = true;
setInsightsContext(authenticatedUserToken);
}
});
onSelect(function (_ref5) {
var item = _ref5.item,
state = _ref5.state,
event = _ref5.event,
source = _ref5.source;
if (!isAlgoliaInsightsHit(item)) {
return;
}
onSelectEvent({
state: state,
event: event,
insights: insights,
item: item,
insightsEvents: [_objectSpread({
eventName: 'Item Selected'
}, createClickedEvent({
item: item,
items: source.getItems().filter(isAlgoliaInsightsHit)
}))]
});
});
onActive(function (_ref6) {
var item = _ref6.item,
source = _ref6.source,
state = _ref6.state,
event = _ref6.event;
if (!isAlgoliaInsightsHit(item)) {
return;
}
onActiveEvent({
state: state,
event: event,
insights: insights,
item: item,
insightsEvents: [_objectSpread({
eventName: 'Item Active'
}, createClickedEvent({
item: item,
items: source.getItems().filter(isAlgoliaInsightsHit)
}))]
});
});
},
onStateChange: function onStateChange(_ref7) {
var state = _ref7.state;
debouncedOnStateChange({
state: state
});
},
__autocomplete_pluginOptions: options
};
}
function getAlgoliaSources() {
var _context$algoliaInsig;
var algoliaSourceBase = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var context = arguments.length > 1 ? arguments[1] : undefined;
return [].concat(_toConsumableArray(algoliaSourceBase), ['autocomplete-internal'], _toConsumableArray((_context$algoliaInsig = context.algoliaInsightsPlugin) !== null && _context$algoliaInsig !== void 0 && _context$algoliaInsig.__automaticInsights ? ['autocomplete-automatic'] : []));
}
function getOptions(options) {
return _objectSpread({
onItemsChange: function onItemsChange(_ref8) {
var insights = _ref8.insights,
insightsEvents = _ref8.insightsEvents,
state = _ref8.state;
insights.viewedObjectIDs.apply(insights, _toConsumableArray(insightsEvents.map(function (event) {
return _objectSpread(_objectSpread({}, event), {}, {
algoliaSource: getAlgoliaSources(event.algoliaSource, state.context)
});
})));
},
onSelect: function onSelect(_ref9) {
var insights = _ref9.insights,
insightsEvents = _ref9.insightsEvents,
state = _ref9.state;
insights.clickedObjectIDsAfterSearch.apply(insights, _toConsumableArray(insightsEvents.map(function (event) {
return _objectSpread(_objectSpread({}, event), {}, {
algoliaSource: getAlgoliaSources(event.algoliaSource, state.context)
});
})));
},
onActive: noop,
__autocomplete_clickAnalytics: true
}, options);
}
function loadInsights(environment) {
var errorMessage = "[Autocomplete]: Could not load search-insights.js. Please load it manually following https://alg.li/insights-autocomplete";
try {
var script = environment.document.createElement('script');
script.async = true;
script.src = ALGOLIA_INSIGHTS_SRC;
script.onerror = function () {
// eslint-disable-next-line no-console
console.error(errorMessage);
};
document.body.appendChild(script);
} catch (cause) {
// eslint-disable-next-line no-console
console.error(errorMessage);
}
}
/**
* While `search-insights` supports both string and number user tokens,
* the Search API only accepts strings. This function normalizes the user token.
*/
function normalizeUserToken(userToken) {
return typeof userToken === 'number' ? userToken.toString() : userToken;
}

View File

@@ -0,0 +1,9 @@
import type { AlgoliaInsightsHit, ClickedObjectIDsAfterSearchParams, InsightsParamsWithItems } from './types';
declare type CreateClickedEventParams = {
item: AlgoliaInsightsHit;
items: AlgoliaInsightsHit[];
};
export declare function createClickedEvent({ item, items, }: CreateClickedEventParams): Omit<InsightsParamsWithItems<ClickedObjectIDsAfterSearchParams>, 'eventName'> & {
algoliaSource?: string[];
};
export {};

View File

@@ -0,0 +1,14 @@
export function createClickedEvent(_ref) {
var item = _ref.item,
_ref$items = _ref.items,
items = _ref$items === void 0 ? [] : _ref$items;
return {
index: item.__autocomplete_indexName,
items: [item],
positions: [1 + items.findIndex(function (x) {
return x.objectID === item.objectID;
})],
queryID: item.__autocomplete_queryID,
algoliaSource: ['autocomplete']
};
}

View File

@@ -0,0 +1,66 @@
import { ClickedFiltersParams, ClickedObjectIDsAfterSearchParams, ClickedObjectIDsParams, ConvertedFiltersParams, ConvertedObjectIDsAfterSearchParams, ConvertedObjectIDsParams, InsightsClient, WithArbitraryParams, InsightsParamsWithItems, ViewedFiltersParams, ViewedObjectIDsParams } from './types';
export declare function createSearchInsightsApi(searchInsights: InsightsClient): {
/**
* Initializes Insights with Algolia credentials.
*/
init(appId: string, apiKey: string): void;
/**
* Sets the authenticated user token to attach to events.
* Unsets the authenticated token by passing `undefined`.
*
* @link https://www.algolia.com/doc/api-reference/api-methods/set-authenticated-user-token/
*/
setAuthenticatedUserToken(authenticatedUserToken: string | undefined): void;
/**
* Sets the user token to attach to events.
*/
setUserToken(userToken: string): void;
/**
* Sends click events to capture a query and its clicked items and positions.
*
* @link https://www.algolia.com/doc/api-reference/api-methods/clicked-object-ids-after-search/
*/
clickedObjectIDsAfterSearch(...params: Array<WithArbitraryParams<InsightsParamsWithItems<ClickedObjectIDsAfterSearchParams>>>): void;
/**
* Sends click events to capture clicked items.
*
* @link https://www.algolia.com/doc/api-reference/api-methods/clicked-object-ids/
*/
clickedObjectIDs(...params: Array<WithArbitraryParams<InsightsParamsWithItems<ClickedObjectIDsParams>>>): void;
/**
* Sends click events to capture the filters a user clicks on.
*
* @link https://www.algolia.com/doc/api-reference/api-methods/clicked-filters/
*/
clickedFilters(...params: Array<WithArbitraryParams<ClickedFiltersParams>>): void;
/**
* Sends conversion events to capture a query and its clicked items.
*
* @link https://www.algolia.com/doc/api-reference/api-methods/converted-object-ids-after-search/
*/
convertedObjectIDsAfterSearch(...params: Array<WithArbitraryParams<InsightsParamsWithItems<ConvertedObjectIDsAfterSearchParams>>>): void;
/**
* Sends conversion events to capture clicked items.
*
* @link https://www.algolia.com/doc/api-reference/api-methods/converted-object-ids/
*/
convertedObjectIDs(...params: Array<WithArbitraryParams<InsightsParamsWithItems<ConvertedObjectIDsParams>>>): void;
/**
* Sends conversion events to capture the filters a user uses when converting.
*
* @link https://www.algolia.com/doc/api-reference/api-methods/converted-filters/
*/
convertedFilters(...params: Array<WithArbitraryParams<ConvertedFiltersParams>>): void;
/**
* Sends view events to capture clicked items.
*
* @link https://www.algolia.com/doc/api-reference/api-methods/viewed-object-ids/
*/
viewedObjectIDs(...params: Array<WithArbitraryParams<InsightsParamsWithItems<ViewedObjectIDsParams>>>): void;
/**
* Sends view events to capture the filters a user uses when viewing.
*
* @link https://www.algolia.com/doc/api-reference/api-methods/viewed-filters/
*/
viewedFilters(...params: Array<WithArbitraryParams<ViewedFiltersParams>>): void;
};

View File

@@ -0,0 +1,206 @@
var _excluded = ["items"],
_excluded2 = ["items"];
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
import { isModernInsightsClient } from './isModernInsightsClient';
function chunk(item) {
var chunkSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 20;
var chunks = [];
for (var i = 0; i < item.objectIDs.length; i += chunkSize) {
chunks.push(_objectSpread(_objectSpread({}, item), {}, {
objectIDs: item.objectIDs.slice(i, i + chunkSize)
}));
}
return chunks;
}
function mapToInsightsParamsApi(params) {
return params.map(function (_ref) {
var items = _ref.items,
param = _objectWithoutProperties(_ref, _excluded);
return _objectSpread(_objectSpread({}, param), {}, {
objectIDs: (items === null || items === void 0 ? void 0 : items.map(function (_ref2) {
var objectID = _ref2.objectID;
return objectID;
})) || param.objectIDs
});
});
}
export function createSearchInsightsApi(searchInsights) {
var canSendHeaders = isModernInsightsClient(searchInsights);
function sendToInsights(method, payloads, items) {
if (canSendHeaders && typeof items !== 'undefined') {
var _items$0$__autocomple = items[0].__autocomplete_algoliaCredentials,
appId = _items$0$__autocomple.appId,
apiKey = _items$0$__autocomple.apiKey;
var headers = {
'X-Algolia-Application-Id': appId,
'X-Algolia-API-Key': apiKey
};
searchInsights.apply(void 0, [method].concat(_toConsumableArray(payloads), [{
headers: headers
}]));
} else {
searchInsights.apply(void 0, [method].concat(_toConsumableArray(payloads)));
}
}
return {
/**
* Initializes Insights with Algolia credentials.
*/
init: function init(appId, apiKey) {
searchInsights('init', {
appId: appId,
apiKey: apiKey
});
},
/**
* Sets the authenticated user token to attach to events.
* Unsets the authenticated token by passing `undefined`.
*
* @link https://www.algolia.com/doc/api-reference/api-methods/set-authenticated-user-token/
*/
setAuthenticatedUserToken: function setAuthenticatedUserToken(authenticatedUserToken) {
searchInsights('setAuthenticatedUserToken', authenticatedUserToken);
},
/**
* Sets the user token to attach to events.
*/
setUserToken: function setUserToken(userToken) {
searchInsights('setUserToken', userToken);
},
/**
* Sends click events to capture a query and its clicked items and positions.
*
* @link https://www.algolia.com/doc/api-reference/api-methods/clicked-object-ids-after-search/
*/
clickedObjectIDsAfterSearch: function clickedObjectIDsAfterSearch() {
for (var _len = arguments.length, params = new Array(_len), _key = 0; _key < _len; _key++) {
params[_key] = arguments[_key];
}
if (params.length > 0) {
sendToInsights('clickedObjectIDsAfterSearch', mapToInsightsParamsApi(params), params[0].items);
}
},
/**
* Sends click events to capture clicked items.
*
* @link https://www.algolia.com/doc/api-reference/api-methods/clicked-object-ids/
*/
clickedObjectIDs: function clickedObjectIDs() {
for (var _len2 = arguments.length, params = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
params[_key2] = arguments[_key2];
}
if (params.length > 0) {
sendToInsights('clickedObjectIDs', mapToInsightsParamsApi(params), params[0].items);
}
},
/**
* Sends click events to capture the filters a user clicks on.
*
* @link https://www.algolia.com/doc/api-reference/api-methods/clicked-filters/
*/
clickedFilters: function clickedFilters() {
for (var _len3 = arguments.length, params = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
params[_key3] = arguments[_key3];
}
if (params.length > 0) {
searchInsights.apply(void 0, ['clickedFilters'].concat(params));
}
},
/**
* Sends conversion events to capture a query and its clicked items.
*
* @link https://www.algolia.com/doc/api-reference/api-methods/converted-object-ids-after-search/
*/
convertedObjectIDsAfterSearch: function convertedObjectIDsAfterSearch() {
for (var _len4 = arguments.length, params = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
params[_key4] = arguments[_key4];
}
if (params.length > 0) {
sendToInsights('convertedObjectIDsAfterSearch', mapToInsightsParamsApi(params), params[0].items);
}
},
/**
* Sends conversion events to capture clicked items.
*
* @link https://www.algolia.com/doc/api-reference/api-methods/converted-object-ids/
*/
convertedObjectIDs: function convertedObjectIDs() {
for (var _len5 = arguments.length, params = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
params[_key5] = arguments[_key5];
}
if (params.length > 0) {
sendToInsights('convertedObjectIDs', mapToInsightsParamsApi(params), params[0].items);
}
},
/**
* Sends conversion events to capture the filters a user uses when converting.
*
* @link https://www.algolia.com/doc/api-reference/api-methods/converted-filters/
*/
convertedFilters: function convertedFilters() {
for (var _len6 = arguments.length, params = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
params[_key6] = arguments[_key6];
}
if (params.length > 0) {
searchInsights.apply(void 0, ['convertedFilters'].concat(params));
}
},
/**
* Sends view events to capture clicked items.
*
* @link https://www.algolia.com/doc/api-reference/api-methods/viewed-object-ids/
*/
viewedObjectIDs: function viewedObjectIDs() {
for (var _len7 = arguments.length, params = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
params[_key7] = arguments[_key7];
}
if (params.length > 0) {
params.reduce(function (acc, _ref3) {
var items = _ref3.items,
param = _objectWithoutProperties(_ref3, _excluded2);
return [].concat(_toConsumableArray(acc), _toConsumableArray(chunk(_objectSpread(_objectSpread({}, param), {}, {
objectIDs: (items === null || items === void 0 ? void 0 : items.map(function (_ref4) {
var objectID = _ref4.objectID;
return objectID;
})) || param.objectIDs
})).map(function (payload) {
return {
items: items,
payload: payload
};
})));
}, []).forEach(function (_ref5) {
var items = _ref5.items,
payload = _ref5.payload;
return sendToInsights('viewedObjectIDs', [payload], items);
});
}
},
/**
* Sends view events to capture the filters a user uses when viewing.
*
* @link https://www.algolia.com/doc/api-reference/api-methods/viewed-filters/
*/
viewedFilters: function viewedFilters() {
for (var _len8 = arguments.length, params = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
params[_key8] = arguments[_key8];
}
if (params.length > 0) {
searchInsights.apply(void 0, ['viewedFilters'].concat(params));
}
}
};
}

View File

@@ -0,0 +1,6 @@
import { AlgoliaInsightsHit, InsightsParamsWithItems, ViewedObjectIDsParams } from './types';
declare type CreateViewedEventsParams = {
items: AlgoliaInsightsHit[];
};
export declare function createViewedEvents({ items, }: CreateViewedEventsParams): Array<Omit<InsightsParamsWithItems<ViewedObjectIDsParams>, 'eventName'>>;
export {};

View File

@@ -0,0 +1,16 @@
export function createViewedEvents(_ref) {
var items = _ref.items;
var itemsByIndexName = items.reduce(function (acc, current) {
var _acc$current$__autoco;
acc[current.__autocomplete_indexName] = ((_acc$current$__autoco = acc[current.__autocomplete_indexName]) !== null && _acc$current$__autoco !== void 0 ? _acc$current$__autoco : []).concat(current);
return acc;
}, {});
return Object.keys(itemsByIndexName).map(function (indexName) {
var items = itemsByIndexName[indexName];
return {
index: indexName,
items: items,
algoliaSource: ['autocomplete']
};
});
}

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