@algolia/recommend 5.41.0 → 5.42.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/browser.d.ts +1 -1
- package/dist/builds/browser.js +1 -1
- package/dist/builds/browser.js.map +1 -1
- package/dist/builds/browser.min.js +1 -1
- package/dist/builds/browser.min.js.map +1 -1
- package/dist/builds/browser.umd.js +1 -1
- package/dist/builds/fetch.js +1 -1
- package/dist/builds/fetch.js.map +1 -1
- package/dist/builds/node.cjs +1 -1
- package/dist/builds/node.cjs.map +1 -1
- package/dist/builds/node.js +1 -1
- package/dist/builds/node.js.map +1 -1
- package/dist/builds/worker.js +1 -1
- package/dist/builds/worker.js.map +1 -1
- package/dist/fetch.d.ts +1 -1
- package/dist/node.d.cts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/src/recommendClient.cjs +1 -1
- package/dist/src/recommendClient.cjs.map +1 -1
- package/dist/src/recommendClient.js +1 -1
- package/dist/src/recommendClient.js.map +1 -1
- package/dist/worker.d.ts +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../requester-browser-xhr/src/createXhrRequester.ts","../../../client-common/src/cache/createBrowserLocalStorageCache.ts","../../../client-common/src/cache/createNullCache.ts","../../../client-common/src/cache/createFallbackableCache.ts","../../../client-common/src/cache/createMemoryCache.ts","../../../client-common/src/constants.ts","../../../client-common/src/createAlgoliaAgent.ts","../../../client-common/src/createAuth.ts","../../../client-common/src/createIterablePromise.ts","../../../client-common/src/getAlgoliaAgent.ts","../../../client-common/src/logger/createNullLogger.ts","../../../client-common/src/transporter/createStatefulHost.ts","../../../client-common/src/transporter/errors.ts","../../../client-common/src/transporter/helpers.ts","../../../client-common/src/transporter/responses.ts","../../../client-common/src/transporter/stackTrace.ts","../../../client-common/src/transporter/createTransporter.ts","../../../client-common/src/types/logger.ts","../../src/recommendClient.ts","../../builds/browser.ts"],"sourcesContent":["import type { EndRequest, Requester, Response } from '@algolia/client-common';\n\ntype Timeout = ReturnType<typeof setTimeout>;\n\nexport function createXhrRequester(): Requester {\n function send(request: EndRequest): Promise<Response> {\n return new Promise((resolve) => {\n const baseRequester = new XMLHttpRequest();\n baseRequester.open(request.method, request.url, true);\n\n Object.keys(request.headers).forEach((key) => baseRequester.setRequestHeader(key, request.headers[key]));\n\n const createTimeout = (timeout: number, content: string): Timeout => {\n return setTimeout(() => {\n baseRequester.abort();\n\n resolve({\n status: 0,\n content,\n isTimedOut: true,\n });\n }, timeout);\n };\n\n const connectTimeout = createTimeout(request.connectTimeout, 'Connection timeout');\n\n let responseTimeout: Timeout | undefined;\n\n baseRequester.onreadystatechange = (): void => {\n if (baseRequester.readyState > baseRequester.OPENED && responseTimeout === undefined) {\n clearTimeout(connectTimeout);\n\n responseTimeout = createTimeout(request.responseTimeout, 'Socket timeout');\n }\n };\n\n baseRequester.onerror = (): void => {\n // istanbul ignore next\n if (baseRequester.status === 0) {\n clearTimeout(connectTimeout);\n clearTimeout(responseTimeout!);\n\n resolve({\n content: baseRequester.responseText || 'Network request failed',\n status: baseRequester.status,\n isTimedOut: false,\n });\n }\n };\n\n baseRequester.onload = (): void => {\n clearTimeout(connectTimeout);\n clearTimeout(responseTimeout!);\n\n resolve({\n content: baseRequester.responseText,\n status: baseRequester.status,\n isTimedOut: false,\n });\n };\n\n baseRequester.send(request.data);\n });\n }\n\n return { send };\n}\n","import type { BrowserLocalStorageCacheItem, BrowserLocalStorageOptions, Cache, CacheEvents } from '../types';\n\nexport function createBrowserLocalStorageCache(options: BrowserLocalStorageOptions): Cache {\n let storage: Storage;\n // We've changed the namespace to avoid conflicts with v4, as this version is a huge breaking change\n const namespaceKey = `algolia-client-js-${options.key}`;\n\n function getStorage(): Storage {\n if (storage === undefined) {\n storage = options.localStorage || window.localStorage;\n }\n\n return storage;\n }\n\n function getNamespace<TValue>(): Record<string, TValue> {\n return JSON.parse(getStorage().getItem(namespaceKey) || '{}');\n }\n\n function setNamespace(namespace: Record<string, any>): void {\n getStorage().setItem(namespaceKey, JSON.stringify(namespace));\n }\n\n function removeOutdatedCacheItems(): void {\n const timeToLive = options.timeToLive ? options.timeToLive * 1000 : null;\n const namespace = getNamespace<BrowserLocalStorageCacheItem>();\n\n const filteredNamespaceWithoutOldFormattedCacheItems = Object.fromEntries(\n Object.entries(namespace).filter(([, cacheItem]) => {\n return cacheItem.timestamp !== undefined;\n }),\n );\n\n setNamespace(filteredNamespaceWithoutOldFormattedCacheItems);\n\n if (!timeToLive) {\n return;\n }\n\n const filteredNamespaceWithoutExpiredItems = Object.fromEntries(\n Object.entries(filteredNamespaceWithoutOldFormattedCacheItems).filter(([, cacheItem]) => {\n const currentTimestamp = new Date().getTime();\n const isExpired = cacheItem.timestamp + timeToLive < currentTimestamp;\n\n return !isExpired;\n }),\n );\n\n setNamespace(filteredNamespaceWithoutExpiredItems);\n }\n\n return {\n get<TValue>(\n key: Record<string, any> | string,\n defaultValue: () => Promise<TValue>,\n events: CacheEvents<TValue> = {\n miss: () => Promise.resolve(),\n },\n ): Promise<TValue> {\n return Promise.resolve()\n .then(() => {\n removeOutdatedCacheItems();\n\n return getNamespace<Promise<BrowserLocalStorageCacheItem>>()[JSON.stringify(key)];\n })\n .then((value) => {\n return Promise.all([value ? value.value : defaultValue(), value !== undefined]);\n })\n .then(([value, exists]) => {\n return Promise.all([value, exists || events.miss(value)]);\n })\n .then(([value]) => value);\n },\n\n set<TValue>(key: Record<string, any> | string, value: TValue): Promise<TValue> {\n return Promise.resolve().then(() => {\n const namespace = getNamespace();\n\n namespace[JSON.stringify(key)] = {\n timestamp: new Date().getTime(),\n value,\n };\n\n getStorage().setItem(namespaceKey, JSON.stringify(namespace));\n\n return value;\n });\n },\n\n delete(key: Record<string, any> | string): Promise<void> {\n return Promise.resolve().then(() => {\n const namespace = getNamespace();\n\n delete namespace[JSON.stringify(key)];\n\n getStorage().setItem(namespaceKey, JSON.stringify(namespace));\n });\n },\n\n clear(): Promise<void> {\n return Promise.resolve().then(() => {\n getStorage().removeItem(namespaceKey);\n });\n },\n };\n}\n","import type { Cache, CacheEvents } from '../types';\n\nexport function createNullCache(): Cache {\n return {\n get<TValue>(\n _key: Record<string, any> | string,\n defaultValue: () => Promise<TValue>,\n events: CacheEvents<TValue> = {\n miss: (): Promise<void> => Promise.resolve(),\n },\n ): Promise<TValue> {\n const value = defaultValue();\n\n return value.then((result) => Promise.all([result, events.miss(result)])).then(([result]) => result);\n },\n\n set<TValue>(_key: Record<string, any> | string, value: TValue): Promise<TValue> {\n return Promise.resolve(value);\n },\n\n delete(_key: Record<string, any> | string): Promise<void> {\n return Promise.resolve();\n },\n\n clear(): Promise<void> {\n return Promise.resolve();\n },\n };\n}\n","import type { Cache, CacheEvents, FallbackableCacheOptions } from '../types';\nimport { createNullCache } from './createNullCache';\n\nexport function createFallbackableCache(options: FallbackableCacheOptions): Cache {\n const caches = [...options.caches];\n const current = caches.shift();\n\n if (current === undefined) {\n return createNullCache();\n }\n\n return {\n get<TValue>(\n key: Record<string, any> | string,\n defaultValue: () => Promise<TValue>,\n events: CacheEvents<TValue> = {\n miss: (): Promise<void> => Promise.resolve(),\n },\n ): Promise<TValue> {\n return current.get(key, defaultValue, events).catch(() => {\n return createFallbackableCache({ caches }).get(key, defaultValue, events);\n });\n },\n\n set<TValue>(key: Record<string, any> | string, value: TValue): Promise<TValue> {\n return current.set(key, value).catch(() => {\n return createFallbackableCache({ caches }).set(key, value);\n });\n },\n\n delete(key: Record<string, any> | string): Promise<void> {\n return current.delete(key).catch(() => {\n return createFallbackableCache({ caches }).delete(key);\n });\n },\n\n clear(): Promise<void> {\n return current.clear().catch(() => {\n return createFallbackableCache({ caches }).clear();\n });\n },\n };\n}\n","import type { Cache, CacheEvents, MemoryCacheOptions } from '../types';\n\nexport function createMemoryCache(options: MemoryCacheOptions = { serializable: true }): Cache {\n let cache: Record<string, any> = {};\n\n return {\n get<TValue>(\n key: Record<string, any> | string,\n defaultValue: () => Promise<TValue>,\n events: CacheEvents<TValue> = {\n miss: (): Promise<void> => Promise.resolve(),\n },\n ): Promise<TValue> {\n const keyAsString = JSON.stringify(key);\n\n if (keyAsString in cache) {\n return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]);\n }\n\n const promise = defaultValue();\n\n return promise.then((value: TValue) => events.miss(value)).then(() => promise);\n },\n\n set<TValue>(key: Record<string, any> | string, value: TValue): Promise<TValue> {\n cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value;\n\n return Promise.resolve(value);\n },\n\n delete(key: Record<string, unknown> | string): Promise<void> {\n delete cache[JSON.stringify(key)];\n\n return Promise.resolve();\n },\n\n clear(): Promise<void> {\n cache = {};\n\n return Promise.resolve();\n },\n };\n}\n","export const DEFAULT_CONNECT_TIMEOUT_BROWSER = 1000;\nexport const DEFAULT_READ_TIMEOUT_BROWSER = 2000;\nexport const DEFAULT_WRITE_TIMEOUT_BROWSER = 30000;\n\nexport const DEFAULT_CONNECT_TIMEOUT_NODE = 2000;\nexport const DEFAULT_READ_TIMEOUT_NODE = 5000;\nexport const DEFAULT_WRITE_TIMEOUT_NODE = 30000;\n","import type { AlgoliaAgent, AlgoliaAgentOptions } from './types';\n\nexport function createAlgoliaAgent(version: string): AlgoliaAgent {\n const algoliaAgent = {\n value: `Algolia for JavaScript (${version})`,\n add(options: AlgoliaAgentOptions): AlgoliaAgent {\n const addedAlgoliaAgent = `; ${options.segment}${options.version !== undefined ? ` (${options.version})` : ''}`;\n\n if (algoliaAgent.value.indexOf(addedAlgoliaAgent) === -1) {\n algoliaAgent.value = `${algoliaAgent.value}${addedAlgoliaAgent}`;\n }\n\n return algoliaAgent;\n },\n };\n\n return algoliaAgent;\n}\n","import type { AuthMode, Headers, QueryParameters } from './types';\n\nexport function createAuth(\n appId: string,\n apiKey: string,\n authMode: AuthMode = 'WithinHeaders',\n): {\n readonly headers: () => Headers;\n readonly queryParameters: () => QueryParameters;\n} {\n const credentials = {\n 'x-algolia-api-key': apiKey,\n 'x-algolia-application-id': appId,\n };\n\n return {\n headers(): Headers {\n return authMode === 'WithinHeaders' ? credentials : {};\n },\n\n queryParameters(): QueryParameters {\n return authMode === 'WithinQueryParameters' ? credentials : {};\n },\n };\n}\n","import type { CreateIterablePromise } from './types/createIterablePromise';\n\n/**\n * Helper: Returns the promise of a given `func` to iterate on, based on a given `validate` condition.\n *\n * @param createIterator - The createIterator options.\n * @param createIterator.func - The function to run, which returns a promise.\n * @param createIterator.validate - The validator function. It receives the resolved return of `func`.\n * @param createIterator.aggregator - The function that runs right after the `func` method has been executed, allows you to do anything with the response before `validate`.\n * @param createIterator.error - The `validate` condition to throw an error, and its message.\n * @param createIterator.timeout - The function to decide how long to wait between iterations.\n */\nexport function createIterablePromise<TResponse>({\n func,\n validate,\n aggregator,\n error,\n timeout = (): number => 0,\n}: CreateIterablePromise<TResponse>): Promise<TResponse> {\n const retry = (previousResponse?: TResponse | undefined): Promise<TResponse> => {\n return new Promise<TResponse>((resolve, reject) => {\n func(previousResponse)\n .then(async (response) => {\n if (aggregator) {\n await aggregator(response);\n }\n\n if (await validate(response)) {\n return resolve(response);\n }\n\n if (error && (await error.validate(response))) {\n return reject(new Error(await error.message(response)));\n }\n\n return setTimeout(\n () => {\n retry(response).then(resolve).catch(reject);\n },\n await timeout(),\n );\n })\n .catch((err) => {\n reject(err);\n });\n });\n };\n\n return retry();\n}\n","import { createAlgoliaAgent } from './createAlgoliaAgent';\nimport type { AlgoliaAgent, AlgoliaAgentOptions } from './types';\n\nexport type GetAlgoliaAgent = {\n algoliaAgents: AlgoliaAgentOptions[];\n client: string;\n version: string;\n};\n\nexport function getAlgoliaAgent({ algoliaAgents, client, version }: GetAlgoliaAgent): AlgoliaAgent {\n const defaultAlgoliaAgent = createAlgoliaAgent(version).add({\n segment: client,\n version,\n });\n\n algoliaAgents.forEach((algoliaAgent) => defaultAlgoliaAgent.add(algoliaAgent));\n\n return defaultAlgoliaAgent;\n}\n","import type { Logger } from '../types/logger';\n\nexport function createNullLogger(): Logger {\n return {\n debug(_message: string, _args?: any | undefined): Promise<void> {\n return Promise.resolve();\n },\n info(_message: string, _args?: any | undefined): Promise<void> {\n return Promise.resolve();\n },\n error(_message: string, _args?: any | undefined): Promise<void> {\n return Promise.resolve();\n },\n };\n}\n","import type { Host, StatefulHost } from '../types';\n\n// By default, API Clients at Algolia have expiration delay of 5 mins.\n// In the JavaScript client, we have 2 mins.\nconst EXPIRATION_DELAY = 2 * 60 * 1000;\n\nexport function createStatefulHost(host: Host, status: StatefulHost['status'] = 'up'): StatefulHost {\n const lastUpdate = Date.now();\n\n function isUp(): boolean {\n return status === 'up' || Date.now() - lastUpdate > EXPIRATION_DELAY;\n }\n\n function isTimedOut(): boolean {\n return status === 'timed out' && Date.now() - lastUpdate <= EXPIRATION_DELAY;\n }\n\n return { ...host, status, lastUpdate, isUp, isTimedOut };\n}\n","import type { Response, StackFrame } from '../types';\n\nexport class AlgoliaError extends Error {\n override name: string = 'AlgoliaError';\n\n constructor(message: string, name: string) {\n super(message);\n\n if (name) {\n this.name = name;\n }\n }\n}\n\nexport class IndexNotFoundError extends AlgoliaError {\n constructor(indexName: string) {\n super(`${indexName} does not exist`, 'IndexNotFoundError');\n }\n}\n\nexport class IndicesInSameAppError extends AlgoliaError {\n constructor() {\n super('Indices are in the same application. Use operationIndex instead.', 'IndicesInSameAppError');\n }\n}\n\nexport class IndexAlreadyExistsError extends AlgoliaError {\n constructor(indexName: string) {\n super(`${indexName} index already exists.`, 'IndexAlreadyExistsError');\n }\n}\n\nexport class ErrorWithStackTrace extends AlgoliaError {\n stackTrace: StackFrame[];\n\n constructor(message: string, stackTrace: StackFrame[], name: string) {\n super(message, name);\n // the array and object should be frozen to reflect the stackTrace at the time of the error\n this.stackTrace = stackTrace;\n }\n}\n\nexport class RetryError extends ErrorWithStackTrace {\n constructor(stackTrace: StackFrame[]) {\n super(\n 'Unreachable hosts - your application id may be incorrect. If the error persists, please visit our help center https://alg.li/support-unreachable-hosts or reach out to the Algolia Support team: https://alg.li/support',\n stackTrace,\n 'RetryError',\n );\n }\n}\n\nexport class ApiError extends ErrorWithStackTrace {\n status: number;\n\n constructor(message: string, status: number, stackTrace: StackFrame[], name = 'ApiError') {\n super(message, stackTrace, name);\n this.status = status;\n }\n}\n\nexport class DeserializationError extends AlgoliaError {\n response: Response;\n\n constructor(message: string, response: Response) {\n super(message, 'DeserializationError');\n this.response = response;\n }\n}\n\nexport type DetailedErrorWithMessage = {\n message: string;\n label: string;\n};\n\nexport type DetailedErrorWithTypeID = {\n id: string;\n type: string;\n name?: string | undefined;\n};\n\nexport type DetailedError = {\n code: string;\n details?: DetailedErrorWithMessage[] | DetailedErrorWithTypeID[] | undefined;\n};\n\n// DetailedApiError is only used by the ingestion client to return more informative error, other clients will use ApiClient.\nexport class DetailedApiError extends ApiError {\n error: DetailedError;\n\n constructor(message: string, status: number, error: DetailedError, stackTrace: StackFrame[]) {\n super(message, status, stackTrace, 'DetailedApiError');\n this.error = error;\n }\n}\n","import type { Headers, Host, QueryParameters, Request, RequestOptions, Response, StackFrame } from '../types';\nimport { ApiError, DeserializationError, DetailedApiError } from './errors';\n\nexport function shuffle<TData>(array: TData[]): TData[] {\n const shuffledArray = array;\n\n for (let c = array.length - 1; c > 0; c--) {\n const b = Math.floor(Math.random() * (c + 1));\n const a = array[c];\n\n shuffledArray[c] = array[b];\n shuffledArray[b] = a;\n }\n\n return shuffledArray;\n}\n\nexport function serializeUrl(host: Host, path: string, queryParameters: QueryParameters): string {\n const queryParametersAsString = serializeQueryParameters(queryParameters);\n let url = `${host.protocol}://${host.url}${host.port ? `:${host.port}` : ''}/${\n path.charAt(0) === '/' ? path.substring(1) : path\n }`;\n\n if (queryParametersAsString.length) {\n url += `?${queryParametersAsString}`;\n }\n\n return url;\n}\n\nexport function serializeQueryParameters(parameters: QueryParameters): string {\n return Object.keys(parameters)\n .filter((key) => parameters[key] !== undefined)\n .sort()\n .map(\n (key) =>\n `${key}=${encodeURIComponent(\n Object.prototype.toString.call(parameters[key]) === '[object Array]'\n ? parameters[key].join(',')\n : parameters[key],\n ).replace(/\\+/g, '%20')}`,\n )\n .join('&');\n}\n\nexport function serializeData(request: Request, requestOptions: RequestOptions): string | undefined {\n if (request.method === 'GET' || (request.data === undefined && requestOptions.data === undefined)) {\n return undefined;\n }\n\n const data = Array.isArray(request.data) ? request.data : { ...request.data, ...requestOptions.data };\n\n return JSON.stringify(data);\n}\n\nexport function serializeHeaders(\n baseHeaders: Headers,\n requestHeaders: Headers,\n requestOptionsHeaders?: Headers | undefined,\n): Headers {\n const headers: Headers = {\n Accept: 'application/json',\n ...baseHeaders,\n ...requestHeaders,\n ...requestOptionsHeaders,\n };\n const serializedHeaders: Headers = {};\n\n Object.keys(headers).forEach((header) => {\n const value = headers[header];\n serializedHeaders[header.toLowerCase()] = value;\n });\n\n return serializedHeaders;\n}\n\nexport function deserializeSuccess<TObject>(response: Response): TObject {\n try {\n return JSON.parse(response.content);\n } catch (e) {\n throw new DeserializationError((e as Error).message, response);\n }\n}\n\nexport function deserializeFailure({ content, status }: Response, stackFrame: StackFrame[]): Error {\n try {\n const parsed = JSON.parse(content);\n if ('error' in parsed) {\n return new DetailedApiError(parsed.message, status, parsed.error, stackFrame);\n }\n return new ApiError(parsed.message, status, stackFrame);\n } catch {\n // ..\n }\n return new ApiError(content, status, stackFrame);\n}\n","import type { Response } from '../types';\n\nexport function isNetworkError({ isTimedOut, status }: Omit<Response, 'content'>): boolean {\n return !isTimedOut && ~~status === 0;\n}\n\nexport function isRetryable({ isTimedOut, status }: Omit<Response, 'content'>): boolean {\n return isTimedOut || isNetworkError({ isTimedOut, status }) || (~~(status / 100) !== 2 && ~~(status / 100) !== 4);\n}\n\nexport function isSuccess({ status }: Pick<Response, 'status'>): boolean {\n return ~~(status / 100) === 2;\n}\n","import type { Headers, StackFrame } from '../types';\n\nexport function stackTraceWithoutCredentials(stackTrace: StackFrame[]): StackFrame[] {\n return stackTrace.map((stackFrame) => stackFrameWithoutCredentials(stackFrame));\n}\n\nexport function stackFrameWithoutCredentials(stackFrame: StackFrame): StackFrame {\n const modifiedHeaders: Headers = stackFrame.request.headers['x-algolia-api-key']\n ? { 'x-algolia-api-key': '*****' }\n : {};\n\n return {\n ...stackFrame,\n request: {\n ...stackFrame.request,\n headers: {\n ...stackFrame.request.headers,\n ...modifiedHeaders,\n },\n },\n };\n}\n","import type {\n EndRequest,\n Host,\n QueryParameters,\n Request,\n RequestOptions,\n Response,\n StackFrame,\n Transporter,\n TransporterOptions,\n} from '../types';\nimport { createStatefulHost } from './createStatefulHost';\nimport { RetryError } from './errors';\nimport { deserializeFailure, deserializeSuccess, serializeData, serializeHeaders, serializeUrl } from './helpers';\nimport { isRetryable, isSuccess } from './responses';\nimport { stackFrameWithoutCredentials, stackTraceWithoutCredentials } from './stackTrace';\n\ntype RetryableOptions = {\n hosts: Host[];\n getTimeout: (retryCount: number, timeout: number) => number;\n};\n\nexport function createTransporter({\n hosts,\n hostsCache,\n baseHeaders,\n logger,\n baseQueryParameters,\n algoliaAgent,\n timeouts,\n requester,\n requestsCache,\n responsesCache,\n}: TransporterOptions): Transporter {\n async function createRetryableOptions(compatibleHosts: Host[]): Promise<RetryableOptions> {\n const statefulHosts = await Promise.all(\n compatibleHosts.map((compatibleHost) => {\n return hostsCache.get(compatibleHost, () => {\n return Promise.resolve(createStatefulHost(compatibleHost));\n });\n }),\n );\n const hostsUp = statefulHosts.filter((host) => host.isUp());\n const hostsTimedOut = statefulHosts.filter((host) => host.isTimedOut());\n\n // Note, we put the hosts that previously timed out on the end of the list.\n const hostsAvailable = [...hostsUp, ...hostsTimedOut];\n const compatibleHostsAvailable = hostsAvailable.length > 0 ? hostsAvailable : compatibleHosts;\n\n return {\n hosts: compatibleHostsAvailable,\n getTimeout(timeoutsCount: number, baseTimeout: number): number {\n /**\n * Imagine that you have 4 hosts, if timeouts will increase\n * on the following way: 1 (timed out) > 4 (timed out) > 5 (200).\n *\n * Note that, the very next request, we start from the previous timeout.\n *\n * 5 (timed out) > 6 (timed out) > 7 ...\n *\n * This strategy may need to be reviewed, but is the strategy on the our\n * current v3 version.\n */\n const timeoutMultiplier =\n hostsTimedOut.length === 0 && timeoutsCount === 0 ? 1 : hostsTimedOut.length + 3 + timeoutsCount;\n\n return timeoutMultiplier * baseTimeout;\n },\n };\n }\n\n async function retryableRequest<TResponse>(\n request: Request,\n requestOptions: RequestOptions,\n isRead = true,\n ): Promise<TResponse> {\n const stackTrace: StackFrame[] = [];\n\n /**\n * First we prepare the payload that do not depend from hosts.\n */\n const data = serializeData(request, requestOptions);\n const headers = serializeHeaders(baseHeaders, request.headers, requestOptions.headers);\n\n // On `GET`, the data is proxied to query parameters.\n const dataQueryParameters: QueryParameters =\n request.method === 'GET'\n ? {\n ...request.data,\n ...requestOptions.data,\n }\n : {};\n\n const queryParameters: QueryParameters = {\n ...baseQueryParameters,\n ...request.queryParameters,\n ...dataQueryParameters,\n };\n\n if (algoliaAgent.value) {\n queryParameters['x-algolia-agent'] = algoliaAgent.value;\n }\n\n if (requestOptions && requestOptions.queryParameters) {\n for (const key of Object.keys(requestOptions.queryParameters)) {\n // We want to keep `undefined` and `null` values,\n // but also avoid stringifying `object`s, as they are\n // handled in the `serializeUrl` step right after.\n if (\n !requestOptions.queryParameters[key] ||\n Object.prototype.toString.call(requestOptions.queryParameters[key]) === '[object Object]'\n ) {\n queryParameters[key] = requestOptions.queryParameters[key];\n } else {\n queryParameters[key] = requestOptions.queryParameters[key].toString();\n }\n }\n }\n\n let timeoutsCount = 0;\n\n const retry = async (\n retryableHosts: Host[],\n getTimeout: (timeoutsCount: number, timeout: number) => number,\n ): Promise<TResponse> => {\n /**\n * We iterate on each host, until there is no host left.\n */\n const host = retryableHosts.pop();\n if (host === undefined) {\n throw new RetryError(stackTraceWithoutCredentials(stackTrace));\n }\n\n const timeout = { ...timeouts, ...requestOptions.timeouts };\n\n const payload: EndRequest = {\n data,\n headers,\n method: request.method,\n url: serializeUrl(host, request.path, queryParameters),\n connectTimeout: getTimeout(timeoutsCount, timeout.connect),\n responseTimeout: getTimeout(timeoutsCount, isRead ? timeout.read : timeout.write),\n };\n\n /**\n * The stackFrame is pushed to the stackTrace so we\n * can have information about onRetry and onFailure\n * decisions.\n */\n const pushToStackTrace = (response: Response): StackFrame => {\n const stackFrame: StackFrame = {\n request: payload,\n response,\n host,\n triesLeft: retryableHosts.length,\n };\n\n stackTrace.push(stackFrame);\n\n return stackFrame;\n };\n\n const response = await requester.send(payload);\n\n if (isRetryable(response)) {\n const stackFrame = pushToStackTrace(response);\n\n // If response is a timeout, we increase the number of timeouts so we can increase the timeout later.\n if (response.isTimedOut) {\n timeoutsCount++;\n }\n /**\n * Failures are individually sent to the logger, allowing\n * the end user to debug / store stack frames even\n * when a retry error does not happen.\n */\n logger.info('Retryable failure', stackFrameWithoutCredentials(stackFrame));\n\n /**\n * We also store the state of the host in failure cases. If the host, is\n * down it will remain down for the next 2 minutes. In a timeout situation,\n * this host will be added end of the list of hosts on the next request.\n */\n await hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? 'timed out' : 'down'));\n\n return retry(retryableHosts, getTimeout);\n }\n\n if (isSuccess(response)) {\n return deserializeSuccess(response);\n }\n\n pushToStackTrace(response);\n throw deserializeFailure(response, stackTrace);\n };\n\n /**\n * Finally, for each retryable host perform request until we got a non\n * retryable response. Some notes here:\n *\n * 1. The reverse here is applied so we can apply a `pop` later on => more performant.\n * 2. We also get from the retryable options a timeout multiplier that is tailored\n * for the current context.\n */\n const compatibleHosts = hosts.filter(\n (host) => host.accept === 'readWrite' || (isRead ? host.accept === 'read' : host.accept === 'write'),\n );\n const options = await createRetryableOptions(compatibleHosts);\n\n return retry([...options.hosts].reverse(), options.getTimeout);\n }\n\n function createRequest<TResponse>(request: Request, requestOptions: RequestOptions = {}): Promise<TResponse> {\n /**\n * A read request is either a `GET` request, or a request that we make\n * via the `read` transporter (e.g. `search`).\n */\n const isRead = request.useReadTransporter || request.method === 'GET';\n if (!isRead) {\n /**\n * On write requests, no cache mechanisms are applied, and we\n * proxy the request immediately to the requester.\n */\n return retryableRequest<TResponse>(request, requestOptions, isRead);\n }\n\n const createRetryableRequest = (): Promise<TResponse> => {\n /**\n * Then, we prepare a function factory that contains the construction of\n * the retryable request. At this point, we may *not* perform the actual\n * request. But we want to have the function factory ready.\n */\n return retryableRequest<TResponse>(request, requestOptions);\n };\n\n /**\n * Once we have the function factory ready, we need to determine of the\n * request is \"cacheable\" - should be cached. Note that, once again,\n * the user can force this option.\n */\n const cacheable = requestOptions.cacheable || request.cacheable;\n\n /**\n * If is not \"cacheable\", we immediately trigger the retryable request, no\n * need to check cache implementations.\n */\n if (cacheable !== true) {\n return createRetryableRequest();\n }\n\n /**\n * If the request is \"cacheable\", we need to first compute the key to ask\n * the cache implementations if this request is on progress or if the\n * response already exists on the cache.\n */\n const key = {\n request,\n requestOptions,\n transporter: {\n queryParameters: baseQueryParameters,\n headers: baseHeaders,\n },\n };\n\n /**\n * With the computed key, we first ask the responses cache\n * implementation if this request was been resolved before.\n */\n return responsesCache.get(\n key,\n () => {\n /**\n * If the request has never resolved before, we actually ask if there\n * is a current request with the same key on progress.\n */\n return requestsCache.get(key, () =>\n /**\n * Finally, if there is no request in progress with the same key,\n * this `createRetryableRequest()` will actually trigger the\n * retryable request.\n */\n requestsCache\n .set(key, createRetryableRequest())\n .then(\n (response) => Promise.all([requestsCache.delete(key), response]),\n (err) => Promise.all([requestsCache.delete(key), Promise.reject(err)]),\n )\n .then(([_, response]) => response),\n );\n },\n {\n /**\n * Of course, once we get this response back from the server, we\n * tell response cache to actually store the received response\n * to be used later.\n */\n miss: (response) => responsesCache.set(key, response),\n },\n );\n }\n\n return {\n hostsCache,\n requester,\n timeouts,\n logger,\n algoliaAgent,\n baseHeaders,\n baseQueryParameters,\n hosts,\n request: createRequest,\n requestsCache,\n responsesCache,\n };\n}\n","export const LogLevelEnum: Readonly<Record<string, LogLevelType>> = {\n Debug: 1,\n Info: 2,\n Error: 3,\n};\n\nexport type LogLevelType = 1 | 2 | 3;\n\nexport type Logger = {\n /**\n * Logs debug messages.\n */\n debug: (message: string, args?: any | undefined) => Promise<void>;\n\n /**\n * Logs info messages.\n */\n info: (message: string, args?: any | undefined) => Promise<void>;\n\n /**\n * Logs error messages.\n */\n error: (message: string, args?: any | undefined) => Promise<void>;\n};\n","// Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT.\n\nimport type {\n CreateClientOptions,\n Headers,\n Host,\n QueryParameters,\n Request,\n RequestOptions,\n} from '@algolia/client-common';\nimport { createAuth, createTransporter, getAlgoliaAgent, shuffle } from '@algolia/client-common';\n\nimport type { DeletedAtResponse } from '../model/deletedAtResponse';\n\nimport type { GetRecommendTaskResponse } from '../model/getRecommendTaskResponse';\nimport type { GetRecommendationsParams } from '../model/getRecommendationsParams';\nimport type { GetRecommendationsResponse } from '../model/getRecommendationsResponse';\n\nimport type { RecommendRule } from '../model/recommendRule';\nimport type { RecommendUpdatedAtResponse } from '../model/recommendUpdatedAtResponse';\n\nimport type { SearchRecommendRulesResponse } from '../model/searchRecommendRulesResponse';\n\nimport type {\n BatchRecommendRulesProps,\n CustomDeleteProps,\n CustomGetProps,\n CustomPostProps,\n CustomPutProps,\n DeleteRecommendRuleProps,\n GetRecommendRuleProps,\n GetRecommendStatusProps,\n LegacyGetRecommendationsParams,\n SearchRecommendRulesProps,\n} from '../model/clientMethodProps';\n\nexport const apiClientVersion = '5.41.0';\n\nfunction getDefaultHosts(appId: string): Host[] {\n return (\n [\n {\n url: `${appId}-dsn.algolia.net`,\n accept: 'read',\n protocol: 'https',\n },\n {\n url: `${appId}.algolia.net`,\n accept: 'write',\n protocol: 'https',\n },\n ] as Host[]\n ).concat(\n shuffle([\n {\n url: `${appId}-1.algolianet.com`,\n accept: 'readWrite',\n protocol: 'https',\n },\n {\n url: `${appId}-2.algolianet.com`,\n accept: 'readWrite',\n protocol: 'https',\n },\n {\n url: `${appId}-3.algolianet.com`,\n accept: 'readWrite',\n protocol: 'https',\n },\n ]),\n );\n}\n\nexport function createRecommendClient({\n appId: appIdOption,\n apiKey: apiKeyOption,\n authMode,\n algoliaAgents,\n ...options\n}: CreateClientOptions) {\n const auth = createAuth(appIdOption, apiKeyOption, authMode);\n const transporter = createTransporter({\n hosts: getDefaultHosts(appIdOption),\n ...options,\n algoliaAgent: getAlgoliaAgent({\n algoliaAgents,\n client: 'Recommend',\n version: apiClientVersion,\n }),\n baseHeaders: {\n 'content-type': 'text/plain',\n ...auth.headers(),\n ...options.baseHeaders,\n },\n baseQueryParameters: {\n ...auth.queryParameters(),\n ...options.baseQueryParameters,\n },\n });\n\n return {\n transporter,\n\n /**\n * The `appId` currently in use.\n */\n appId: appIdOption,\n\n /**\n * The `apiKey` currently in use.\n */\n apiKey: apiKeyOption,\n\n /**\n * Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.\n */\n clearCache(): Promise<void> {\n return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => undefined);\n },\n\n /**\n * Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.\n */\n get _ua(): string {\n return transporter.algoliaAgent.value;\n },\n\n /**\n * Adds a `segment` to the `x-algolia-agent` sent with every requests.\n *\n * @param segment - The algolia agent (user-agent) segment to add.\n * @param version - The version of the agent.\n */\n addAlgoliaAgent(segment: string, version?: string | undefined): void {\n transporter.algoliaAgent.add({ segment, version });\n },\n\n /**\n * Helper method to switch the API key used to authenticate the requests.\n *\n * @param params - Method params.\n * @param params.apiKey - The new API Key to use.\n */\n setClientApiKey({ apiKey }: { apiKey: string }): void {\n if (!authMode || authMode === 'WithinHeaders') {\n transporter.baseHeaders['x-algolia-api-key'] = apiKey;\n } else {\n transporter.baseQueryParameters['x-algolia-api-key'] = apiKey;\n }\n },\n\n /**\n * Create or update a batch of Recommend Rules Each Recommend Rule is created or updated, depending on whether a Recommend Rule with the same `objectID` already exists. You may also specify `true` for `clearExistingRules`, in which case the batch will atomically replace all the existing Recommend Rules. Recommend Rules are similar to Search Rules, except that the conditions and consequences apply to a [source item](/doc/guides/algolia-recommend/overview/#recommend-models) instead of a query. The main differences are the following: - Conditions `pattern` and `anchoring` are unavailable. - Condition `filters` triggers if the source item matches the specified filters. - Condition `filters` accepts numeric filters. - Consequence `params` only covers filtering parameters. - Consequence `automaticFacetFilters` doesn\\'t require a facet value placeholder (it tries to match the data source item\\'s attributes instead).\n *\n * Required API Key ACLs:\n * - editSettings\n * @param batchRecommendRules - The batchRecommendRules object.\n * @param batchRecommendRules.indexName - Name of the index on which to perform the operation.\n * @param batchRecommendRules.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).\n * @param batchRecommendRules.recommendRule - The recommendRule object.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n batchRecommendRules(\n { indexName, model, recommendRule }: BatchRecommendRulesProps,\n requestOptions?: RequestOptions,\n ): Promise<RecommendUpdatedAtResponse> {\n if (!indexName) {\n throw new Error('Parameter `indexName` is required when calling `batchRecommendRules`.');\n }\n\n if (!model) {\n throw new Error('Parameter `model` is required when calling `batchRecommendRules`.');\n }\n\n const requestPath = '/1/indexes/{indexName}/{model}/recommend/rules/batch'\n .replace('{indexName}', encodeURIComponent(indexName))\n .replace('{model}', encodeURIComponent(model));\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'POST',\n path: requestPath,\n queryParameters,\n headers,\n data: recommendRule ? recommendRule : {},\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * This method lets you send requests to the Algolia REST API.\n * @param customDelete - The customDelete object.\n * @param customDelete.path - Path of the endpoint, for example `1/newFeature`.\n * @param customDelete.parameters - Query parameters to apply to the current query.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n customDelete(\n { path, parameters }: CustomDeleteProps,\n requestOptions?: RequestOptions,\n ): Promise<Record<string, unknown>> {\n if (!path) {\n throw new Error('Parameter `path` is required when calling `customDelete`.');\n }\n\n const requestPath = '/{path}'.replace('{path}', path);\n const headers: Headers = {};\n const queryParameters: QueryParameters = parameters ? parameters : {};\n\n const request: Request = {\n method: 'DELETE',\n path: requestPath,\n queryParameters,\n headers,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * This method lets you send requests to the Algolia REST API.\n * @param customGet - The customGet object.\n * @param customGet.path - Path of the endpoint, for example `1/newFeature`.\n * @param customGet.parameters - Query parameters to apply to the current query.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n customGet({ path, parameters }: CustomGetProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>> {\n if (!path) {\n throw new Error('Parameter `path` is required when calling `customGet`.');\n }\n\n const requestPath = '/{path}'.replace('{path}', path);\n const headers: Headers = {};\n const queryParameters: QueryParameters = parameters ? parameters : {};\n\n const request: Request = {\n method: 'GET',\n path: requestPath,\n queryParameters,\n headers,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * This method lets you send requests to the Algolia REST API.\n * @param customPost - The customPost object.\n * @param customPost.path - Path of the endpoint, for example `1/newFeature`.\n * @param customPost.parameters - Query parameters to apply to the current query.\n * @param customPost.body - Parameters to send with the custom request.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n customPost(\n { path, parameters, body }: CustomPostProps,\n requestOptions?: RequestOptions,\n ): Promise<Record<string, unknown>> {\n if (!path) {\n throw new Error('Parameter `path` is required when calling `customPost`.');\n }\n\n const requestPath = '/{path}'.replace('{path}', path);\n const headers: Headers = {};\n const queryParameters: QueryParameters = parameters ? parameters : {};\n\n const request: Request = {\n method: 'POST',\n path: requestPath,\n queryParameters,\n headers,\n data: body ? body : {},\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * This method lets you send requests to the Algolia REST API.\n * @param customPut - The customPut object.\n * @param customPut.path - Path of the endpoint, for example `1/newFeature`.\n * @param customPut.parameters - Query parameters to apply to the current query.\n * @param customPut.body - Parameters to send with the custom request.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n customPut(\n { path, parameters, body }: CustomPutProps,\n requestOptions?: RequestOptions,\n ): Promise<Record<string, unknown>> {\n if (!path) {\n throw new Error('Parameter `path` is required when calling `customPut`.');\n }\n\n const requestPath = '/{path}'.replace('{path}', path);\n const headers: Headers = {};\n const queryParameters: QueryParameters = parameters ? parameters : {};\n\n const request: Request = {\n method: 'PUT',\n path: requestPath,\n queryParameters,\n headers,\n data: body ? body : {},\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * Deletes a Recommend rule from a recommendation scenario.\n *\n * Required API Key ACLs:\n * - editSettings\n * @param deleteRecommendRule - The deleteRecommendRule object.\n * @param deleteRecommendRule.indexName - Name of the index on which to perform the operation.\n * @param deleteRecommendRule.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).\n * @param deleteRecommendRule.objectID - Unique record identifier.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n deleteRecommendRule(\n { indexName, model, objectID }: DeleteRecommendRuleProps,\n requestOptions?: RequestOptions,\n ): Promise<DeletedAtResponse> {\n if (!indexName) {\n throw new Error('Parameter `indexName` is required when calling `deleteRecommendRule`.');\n }\n\n if (!model) {\n throw new Error('Parameter `model` is required when calling `deleteRecommendRule`.');\n }\n\n if (!objectID) {\n throw new Error('Parameter `objectID` is required when calling `deleteRecommendRule`.');\n }\n\n const requestPath = '/1/indexes/{indexName}/{model}/recommend/rules/{objectID}'\n .replace('{indexName}', encodeURIComponent(indexName))\n .replace('{model}', encodeURIComponent(model))\n .replace('{objectID}', encodeURIComponent(objectID));\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'DELETE',\n path: requestPath,\n queryParameters,\n headers,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * Retrieves a Recommend rule that you previously created in the Algolia dashboard.\n *\n * Required API Key ACLs:\n * - settings\n * @param getRecommendRule - The getRecommendRule object.\n * @param getRecommendRule.indexName - Name of the index on which to perform the operation.\n * @param getRecommendRule.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).\n * @param getRecommendRule.objectID - Unique record identifier.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n getRecommendRule(\n { indexName, model, objectID }: GetRecommendRuleProps,\n requestOptions?: RequestOptions,\n ): Promise<RecommendRule> {\n if (!indexName) {\n throw new Error('Parameter `indexName` is required when calling `getRecommendRule`.');\n }\n\n if (!model) {\n throw new Error('Parameter `model` is required when calling `getRecommendRule`.');\n }\n\n if (!objectID) {\n throw new Error('Parameter `objectID` is required when calling `getRecommendRule`.');\n }\n\n const requestPath = '/1/indexes/{indexName}/{model}/recommend/rules/{objectID}'\n .replace('{indexName}', encodeURIComponent(indexName))\n .replace('{model}', encodeURIComponent(model))\n .replace('{objectID}', encodeURIComponent(objectID));\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'GET',\n path: requestPath,\n queryParameters,\n headers,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * Checks the status of a given task. Deleting a Recommend rule is asynchronous. When you delete a rule, a task is created on a queue and completed depending on the load on the server. The API response includes a task ID that you can use to check the status.\n *\n * Required API Key ACLs:\n * - editSettings\n * @param getRecommendStatus - The getRecommendStatus object.\n * @param getRecommendStatus.indexName - Name of the index on which to perform the operation.\n * @param getRecommendStatus.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).\n * @param getRecommendStatus.taskID - Unique task identifier.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n getRecommendStatus(\n { indexName, model, taskID }: GetRecommendStatusProps,\n requestOptions?: RequestOptions,\n ): Promise<GetRecommendTaskResponse> {\n if (!indexName) {\n throw new Error('Parameter `indexName` is required when calling `getRecommendStatus`.');\n }\n\n if (!model) {\n throw new Error('Parameter `model` is required when calling `getRecommendStatus`.');\n }\n\n if (!taskID) {\n throw new Error('Parameter `taskID` is required when calling `getRecommendStatus`.');\n }\n\n const requestPath = '/1/indexes/{indexName}/{model}/task/{taskID}'\n .replace('{indexName}', encodeURIComponent(indexName))\n .replace('{model}', encodeURIComponent(model))\n .replace('{taskID}', encodeURIComponent(taskID));\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'GET',\n path: requestPath,\n queryParameters,\n headers,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * Retrieves recommendations from selected AI models.\n *\n * Required API Key ACLs:\n * - search\n * @param getRecommendationsParams - The getRecommendationsParams object.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n getRecommendations(\n getRecommendationsParams: GetRecommendationsParams | LegacyGetRecommendationsParams,\n requestOptions?: RequestOptions,\n ): Promise<GetRecommendationsResponse> {\n if (getRecommendationsParams && Array.isArray(getRecommendationsParams)) {\n const newSignatureRequest: GetRecommendationsParams = {\n requests: getRecommendationsParams,\n };\n\n getRecommendationsParams = newSignatureRequest;\n }\n\n if (!getRecommendationsParams) {\n throw new Error('Parameter `getRecommendationsParams` is required when calling `getRecommendations`.');\n }\n\n if (!getRecommendationsParams.requests) {\n throw new Error('Parameter `getRecommendationsParams.requests` is required when calling `getRecommendations`.');\n }\n\n const requestPath = '/1/indexes/*/recommendations';\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'POST',\n path: requestPath,\n queryParameters,\n headers,\n data: getRecommendationsParams,\n useReadTransporter: true,\n cacheable: true,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * Searches for Recommend rules. Use an empty query to list all rules for this recommendation scenario.\n *\n * Required API Key ACLs:\n * - settings\n * @param searchRecommendRules - The searchRecommendRules object.\n * @param searchRecommendRules.indexName - Name of the index on which to perform the operation.\n * @param searchRecommendRules.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).\n * @param searchRecommendRules.searchRecommendRulesParams - The searchRecommendRulesParams object.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n searchRecommendRules(\n { indexName, model, searchRecommendRulesParams }: SearchRecommendRulesProps,\n requestOptions?: RequestOptions,\n ): Promise<SearchRecommendRulesResponse> {\n if (!indexName) {\n throw new Error('Parameter `indexName` is required when calling `searchRecommendRules`.');\n }\n\n if (!model) {\n throw new Error('Parameter `model` is required when calling `searchRecommendRules`.');\n }\n\n const requestPath = '/1/indexes/{indexName}/{model}/recommend/rules/search'\n .replace('{indexName}', encodeURIComponent(indexName))\n .replace('{model}', encodeURIComponent(model));\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'POST',\n path: requestPath,\n queryParameters,\n headers,\n data: searchRecommendRulesParams ? searchRecommendRulesParams : {},\n useReadTransporter: true,\n cacheable: true,\n };\n\n return transporter.request(request, requestOptions);\n },\n };\n}\n","// Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT.\n\nimport { createXhrRequester } from '@algolia/requester-browser-xhr';\n\nimport {\n createBrowserLocalStorageCache,\n createFallbackableCache,\n createMemoryCache,\n createNullLogger,\n} from '@algolia/client-common';\n\nimport type { ClientOptions } from '@algolia/client-common';\n\nimport { apiClientVersion, createRecommendClient } from '../src/recommendClient';\n\nexport { apiClientVersion } from '../src/recommendClient';\n\nexport * from '../model';\n\nexport function recommendClient(appId: string, apiKey: string, options?: ClientOptions | undefined): RecommendClient {\n if (!appId || typeof appId !== 'string') {\n throw new Error('`appId` is missing.');\n }\n\n if (!apiKey || typeof apiKey !== 'string') {\n throw new Error('`apiKey` is missing.');\n }\n\n return createRecommendClient({\n appId,\n apiKey,\n timeouts: {\n connect: 1000,\n read: 2000,\n write: 30000,\n },\n logger: createNullLogger(),\n requester: createXhrRequester(),\n algoliaAgents: [{ segment: 'Browser' }],\n authMode: 'WithinQueryParameters',\n responsesCache: createMemoryCache(),\n requestsCache: createMemoryCache({ serializable: false }),\n hostsCache: createFallbackableCache({\n caches: [createBrowserLocalStorageCache({ key: `${apiClientVersion}-${appId}` }), createMemoryCache()],\n }),\n ...options,\n });\n}\n\nexport type RecommendClient = ReturnType<typeof createRecommendClient>;\n"],"mappings":"AAIO,SAASA,GAAgC,CAC9C,SAASC,EAAKC,EAAwC,CACpD,OAAO,IAAI,QAASC,GAAY,CAC9B,IAAMC,EAAgB,IAAI,eAC1BA,EAAc,KAAKF,EAAQ,OAAQA,EAAQ,IAAK,EAAI,EAEpD,OAAO,KAAKA,EAAQ,OAAO,EAAE,QAASG,GAAQD,EAAc,iBAAiBC,EAAKH,EAAQ,QAAQG,CAAG,CAAC,CAAC,EAEvG,IAAMC,EAAgB,CAACC,EAAiBC,IAC/B,WAAW,IAAM,CACtBJ,EAAc,MAAM,EAEpBD,EAAQ,CACN,OAAQ,EACR,QAAAK,EACA,WAAY,EACd,CAAC,CACH,EAAGD,CAAO,EAGNE,EAAiBH,EAAcJ,EAAQ,eAAgB,oBAAoB,EAE7EQ,EAEJN,EAAc,mBAAqB,IAAY,CACzCA,EAAc,WAAaA,EAAc,QAAUM,IAAoB,SACzE,aAAaD,CAAc,EAE3BC,EAAkBJ,EAAcJ,EAAQ,gBAAiB,gBAAgB,EAE7E,EAEAE,EAAc,QAAU,IAAY,CAE9BA,EAAc,SAAW,IAC3B,aAAaK,CAAc,EAC3B,aAAaC,CAAgB,EAE7BP,EAAQ,CACN,QAASC,EAAc,cAAgB,yBACvC,OAAQA,EAAc,OACtB,WAAY,EACd,CAAC,EAEL,EAEAA,EAAc,OAAS,IAAY,CACjC,aAAaK,CAAc,EAC3B,aAAaC,CAAgB,EAE7BP,EAAQ,CACN,QAASC,EAAc,aACvB,OAAQA,EAAc,OACtB,WAAY,EACd,CAAC,CACH,EAEAA,EAAc,KAAKF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AO,2BAAAU,CAA2B,EAC/CR,EACuC,CACvC,GAAI,CAACH,EACH,MAAM,IAAI,MAAM,wEAAwE,EAG1F,GAAI,CAACC,EACH,MAAM,IAAI,MAAM,oEAAoE,EAStF,IAAMG,EAAmB,CACvB,OAAQ,OACR,KARkB,wDACjB,QAAQ,cAAe,mBAAmBJ,CAAS,CAAC,EACpD,QAAQ,UAAW,mBAAmBC,CAAK,CAAC,EAO7C,gBALuC,CAAC,EAMxC,QAPuB,CAAC,EAQxB,KAAMU,GAA0D,CAAC,EACjE,mBAAoB,GACpB,UAAW,EACb,EAEA,OAAOjB,EAAY,QAAQU,EAASD,CAAc,CACpD,CACF,CACF,CC5fO,SAASS,GAAgBC,EAAeC,EAAgBC,EAAsD,CACnH,GAAI,CAACF,GAAS,OAAOA,GAAU,SAC7B,MAAM,IAAI,MAAM,qBAAqB,EAGvC,GAAI,CAACC,GAAU,OAAOA,GAAW,SAC/B,MAAM,IAAI,MAAM,sBAAsB,EAGxC,OAAOE,EAAsB,CAC3B,MAAAH,EACA,OAAAC,EACA,SAAU,CACR,QAAS,IACT,KAAM,IACN,MAAO,GACT,EACA,OAAQG,EAAiB,EACzB,UAAWC,EAAmB,EAC9B,cAAe,CAAC,CAAE,QAAS,SAAU,CAAC,EACtC,SAAU,wBACV,eAAgBC,EAAkB,EAClC,cAAeA,EAAkB,CAAE,aAAc,EAAM,CAAC,EACxD,WAAYC,EAAwB,CAClC,OAAQ,CAACC,EAA+B,CAAE,IAAK,GAAGC,CAAgB,IAAIT,CAAK,EAAG,CAAC,EAAGM,EAAkB,CAAC,CACvG,CAAC,EACD,GAAGJ,CACL,CAAC,CACH","names":["createXhrRequester","send","request","resolve","baseRequester","key","createTimeout","timeout","content","connectTimeout","responseTimeout","createBrowserLocalStorageCache","options","storage","namespaceKey","getStorage","getNamespace","setNamespace","namespace","removeOutdatedCacheItems","timeToLive","filteredNamespaceWithoutOldFormattedCacheItems","cacheItem","filteredNamespaceWithoutExpiredItems","currentTimestamp","key","defaultValue","events","value","exists","createNullCache","_key","result","createFallbackableCache","caches","current","createMemoryCache","cache","keyAsString","promise","createAlgoliaAgent","version","algoliaAgent","options","addedAlgoliaAgent","createAuth","appId","apiKey","authMode","credentials","getAlgoliaAgent","algoliaAgents","client","version","defaultAlgoliaAgent","createAlgoliaAgent","algoliaAgent","createNullLogger","_message","_args","EXPIRATION_DELAY","createStatefulHost","host","status","lastUpdate","isUp","isTimedOut","AlgoliaError","message","name","ErrorWithStackTrace","AlgoliaError","message","stackTrace","name","RetryError","ApiError","status","DeserializationError","response","DetailedApiError","error","shuffle","array","shuffledArray","c","b","serializeUrl","host","path","queryParameters","queryParametersAsString","serializeQueryParameters","url","parameters","key","serializeData","request","requestOptions","data","serializeHeaders","baseHeaders","requestHeaders","requestOptionsHeaders","headers","serializedHeaders","header","value","deserializeSuccess","deserializeFailure","content","stackFrame","parsed","isNetworkError","isTimedOut","isRetryable","isSuccess","stackTraceWithoutCredentials","stackFrameWithoutCredentials","modifiedHeaders","createTransporter","hosts","hostsCache","logger","baseQueryParameters","algoliaAgent","timeouts","requester","requestsCache","responsesCache","createRetryableOptions","compatibleHosts","statefulHosts","compatibleHost","createStatefulHost","hostsUp","hostsTimedOut","hostsAvailable","timeoutsCount","baseTimeout","retryableRequest","isRead","dataQueryParameters","retry","retryableHosts","getTimeout","timeout","payload","pushToStackTrace","options","createRequest","createRetryableRequest","err","_","apiClientVersion","getDefaultHosts","appId","shuffle","createRecommendClient","appIdOption","apiKeyOption","authMode","algoliaAgents","options","auth","createAuth","transporter","createTransporter","getAlgoliaAgent","segment","version","apiKey","indexName","model","recommendRule","requestOptions","request","path","parameters","body","objectID","taskID","getRecommendationsParams","searchRecommendRulesParams","recommendClient","appId","apiKey","options","createRecommendClient","createNullLogger","m","createMemoryCache","createFallbackableCache","createBrowserLocalStorageCache","apiClientVersion"]}
|
|
1
|
+
{"version":3,"sources":["../../../requester-browser-xhr/src/createXhrRequester.ts","../../../client-common/src/cache/createBrowserLocalStorageCache.ts","../../../client-common/src/cache/createNullCache.ts","../../../client-common/src/cache/createFallbackableCache.ts","../../../client-common/src/cache/createMemoryCache.ts","../../../client-common/src/constants.ts","../../../client-common/src/createAlgoliaAgent.ts","../../../client-common/src/createAuth.ts","../../../client-common/src/createIterablePromise.ts","../../../client-common/src/getAlgoliaAgent.ts","../../../client-common/src/logger/createNullLogger.ts","../../../client-common/src/transporter/createStatefulHost.ts","../../../client-common/src/transporter/errors.ts","../../../client-common/src/transporter/helpers.ts","../../../client-common/src/transporter/responses.ts","../../../client-common/src/transporter/stackTrace.ts","../../../client-common/src/transporter/createTransporter.ts","../../../client-common/src/types/logger.ts","../../src/recommendClient.ts","../../builds/browser.ts"],"sourcesContent":["import type { EndRequest, Requester, Response } from '@algolia/client-common';\n\ntype Timeout = ReturnType<typeof setTimeout>;\n\nexport function createXhrRequester(): Requester {\n function send(request: EndRequest): Promise<Response> {\n return new Promise((resolve) => {\n const baseRequester = new XMLHttpRequest();\n baseRequester.open(request.method, request.url, true);\n\n Object.keys(request.headers).forEach((key) => baseRequester.setRequestHeader(key, request.headers[key]));\n\n const createTimeout = (timeout: number, content: string): Timeout => {\n return setTimeout(() => {\n baseRequester.abort();\n\n resolve({\n status: 0,\n content,\n isTimedOut: true,\n });\n }, timeout);\n };\n\n const connectTimeout = createTimeout(request.connectTimeout, 'Connection timeout');\n\n let responseTimeout: Timeout | undefined;\n\n baseRequester.onreadystatechange = (): void => {\n if (baseRequester.readyState > baseRequester.OPENED && responseTimeout === undefined) {\n clearTimeout(connectTimeout);\n\n responseTimeout = createTimeout(request.responseTimeout, 'Socket timeout');\n }\n };\n\n baseRequester.onerror = (): void => {\n // istanbul ignore next\n if (baseRequester.status === 0) {\n clearTimeout(connectTimeout);\n clearTimeout(responseTimeout!);\n\n resolve({\n content: baseRequester.responseText || 'Network request failed',\n status: baseRequester.status,\n isTimedOut: false,\n });\n }\n };\n\n baseRequester.onload = (): void => {\n clearTimeout(connectTimeout);\n clearTimeout(responseTimeout!);\n\n resolve({\n content: baseRequester.responseText,\n status: baseRequester.status,\n isTimedOut: false,\n });\n };\n\n baseRequester.send(request.data);\n });\n }\n\n return { send };\n}\n","import type { BrowserLocalStorageCacheItem, BrowserLocalStorageOptions, Cache, CacheEvents } from '../types';\n\nexport function createBrowserLocalStorageCache(options: BrowserLocalStorageOptions): Cache {\n let storage: Storage;\n // We've changed the namespace to avoid conflicts with v4, as this version is a huge breaking change\n const namespaceKey = `algolia-client-js-${options.key}`;\n\n function getStorage(): Storage {\n if (storage === undefined) {\n storage = options.localStorage || window.localStorage;\n }\n\n return storage;\n }\n\n function getNamespace<TValue>(): Record<string, TValue> {\n return JSON.parse(getStorage().getItem(namespaceKey) || '{}');\n }\n\n function setNamespace(namespace: Record<string, any>): void {\n getStorage().setItem(namespaceKey, JSON.stringify(namespace));\n }\n\n function removeOutdatedCacheItems(): void {\n const timeToLive = options.timeToLive ? options.timeToLive * 1000 : null;\n const namespace = getNamespace<BrowserLocalStorageCacheItem>();\n\n const filteredNamespaceWithoutOldFormattedCacheItems = Object.fromEntries(\n Object.entries(namespace).filter(([, cacheItem]) => {\n return cacheItem.timestamp !== undefined;\n }),\n );\n\n setNamespace(filteredNamespaceWithoutOldFormattedCacheItems);\n\n if (!timeToLive) {\n return;\n }\n\n const filteredNamespaceWithoutExpiredItems = Object.fromEntries(\n Object.entries(filteredNamespaceWithoutOldFormattedCacheItems).filter(([, cacheItem]) => {\n const currentTimestamp = new Date().getTime();\n const isExpired = cacheItem.timestamp + timeToLive < currentTimestamp;\n\n return !isExpired;\n }),\n );\n\n setNamespace(filteredNamespaceWithoutExpiredItems);\n }\n\n return {\n get<TValue>(\n key: Record<string, any> | string,\n defaultValue: () => Promise<TValue>,\n events: CacheEvents<TValue> = {\n miss: () => Promise.resolve(),\n },\n ): Promise<TValue> {\n return Promise.resolve()\n .then(() => {\n removeOutdatedCacheItems();\n\n return getNamespace<Promise<BrowserLocalStorageCacheItem>>()[JSON.stringify(key)];\n })\n .then((value) => {\n return Promise.all([value ? value.value : defaultValue(), value !== undefined]);\n })\n .then(([value, exists]) => {\n return Promise.all([value, exists || events.miss(value)]);\n })\n .then(([value]) => value);\n },\n\n set<TValue>(key: Record<string, any> | string, value: TValue): Promise<TValue> {\n return Promise.resolve().then(() => {\n const namespace = getNamespace();\n\n namespace[JSON.stringify(key)] = {\n timestamp: new Date().getTime(),\n value,\n };\n\n getStorage().setItem(namespaceKey, JSON.stringify(namespace));\n\n return value;\n });\n },\n\n delete(key: Record<string, any> | string): Promise<void> {\n return Promise.resolve().then(() => {\n const namespace = getNamespace();\n\n delete namespace[JSON.stringify(key)];\n\n getStorage().setItem(namespaceKey, JSON.stringify(namespace));\n });\n },\n\n clear(): Promise<void> {\n return Promise.resolve().then(() => {\n getStorage().removeItem(namespaceKey);\n });\n },\n };\n}\n","import type { Cache, CacheEvents } from '../types';\n\nexport function createNullCache(): Cache {\n return {\n get<TValue>(\n _key: Record<string, any> | string,\n defaultValue: () => Promise<TValue>,\n events: CacheEvents<TValue> = {\n miss: (): Promise<void> => Promise.resolve(),\n },\n ): Promise<TValue> {\n const value = defaultValue();\n\n return value.then((result) => Promise.all([result, events.miss(result)])).then(([result]) => result);\n },\n\n set<TValue>(_key: Record<string, any> | string, value: TValue): Promise<TValue> {\n return Promise.resolve(value);\n },\n\n delete(_key: Record<string, any> | string): Promise<void> {\n return Promise.resolve();\n },\n\n clear(): Promise<void> {\n return Promise.resolve();\n },\n };\n}\n","import type { Cache, CacheEvents, FallbackableCacheOptions } from '../types';\nimport { createNullCache } from './createNullCache';\n\nexport function createFallbackableCache(options: FallbackableCacheOptions): Cache {\n const caches = [...options.caches];\n const current = caches.shift();\n\n if (current === undefined) {\n return createNullCache();\n }\n\n return {\n get<TValue>(\n key: Record<string, any> | string,\n defaultValue: () => Promise<TValue>,\n events: CacheEvents<TValue> = {\n miss: (): Promise<void> => Promise.resolve(),\n },\n ): Promise<TValue> {\n return current.get(key, defaultValue, events).catch(() => {\n return createFallbackableCache({ caches }).get(key, defaultValue, events);\n });\n },\n\n set<TValue>(key: Record<string, any> | string, value: TValue): Promise<TValue> {\n return current.set(key, value).catch(() => {\n return createFallbackableCache({ caches }).set(key, value);\n });\n },\n\n delete(key: Record<string, any> | string): Promise<void> {\n return current.delete(key).catch(() => {\n return createFallbackableCache({ caches }).delete(key);\n });\n },\n\n clear(): Promise<void> {\n return current.clear().catch(() => {\n return createFallbackableCache({ caches }).clear();\n });\n },\n };\n}\n","import type { Cache, CacheEvents, MemoryCacheOptions } from '../types';\n\nexport function createMemoryCache(options: MemoryCacheOptions = { serializable: true }): Cache {\n let cache: Record<string, any> = {};\n\n return {\n get<TValue>(\n key: Record<string, any> | string,\n defaultValue: () => Promise<TValue>,\n events: CacheEvents<TValue> = {\n miss: (): Promise<void> => Promise.resolve(),\n },\n ): Promise<TValue> {\n const keyAsString = JSON.stringify(key);\n\n if (keyAsString in cache) {\n return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]);\n }\n\n const promise = defaultValue();\n\n return promise.then((value: TValue) => events.miss(value)).then(() => promise);\n },\n\n set<TValue>(key: Record<string, any> | string, value: TValue): Promise<TValue> {\n cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value;\n\n return Promise.resolve(value);\n },\n\n delete(key: Record<string, unknown> | string): Promise<void> {\n delete cache[JSON.stringify(key)];\n\n return Promise.resolve();\n },\n\n clear(): Promise<void> {\n cache = {};\n\n return Promise.resolve();\n },\n };\n}\n","export const DEFAULT_CONNECT_TIMEOUT_BROWSER = 1000;\nexport const DEFAULT_READ_TIMEOUT_BROWSER = 2000;\nexport const DEFAULT_WRITE_TIMEOUT_BROWSER = 30000;\n\nexport const DEFAULT_CONNECT_TIMEOUT_NODE = 2000;\nexport const DEFAULT_READ_TIMEOUT_NODE = 5000;\nexport const DEFAULT_WRITE_TIMEOUT_NODE = 30000;\n","import type { AlgoliaAgent, AlgoliaAgentOptions } from './types';\n\nexport function createAlgoliaAgent(version: string): AlgoliaAgent {\n const algoliaAgent = {\n value: `Algolia for JavaScript (${version})`,\n add(options: AlgoliaAgentOptions): AlgoliaAgent {\n const addedAlgoliaAgent = `; ${options.segment}${options.version !== undefined ? ` (${options.version})` : ''}`;\n\n if (algoliaAgent.value.indexOf(addedAlgoliaAgent) === -1) {\n algoliaAgent.value = `${algoliaAgent.value}${addedAlgoliaAgent}`;\n }\n\n return algoliaAgent;\n },\n };\n\n return algoliaAgent;\n}\n","import type { AuthMode, Headers, QueryParameters } from './types';\n\nexport function createAuth(\n appId: string,\n apiKey: string,\n authMode: AuthMode = 'WithinHeaders',\n): {\n readonly headers: () => Headers;\n readonly queryParameters: () => QueryParameters;\n} {\n const credentials = {\n 'x-algolia-api-key': apiKey,\n 'x-algolia-application-id': appId,\n };\n\n return {\n headers(): Headers {\n return authMode === 'WithinHeaders' ? credentials : {};\n },\n\n queryParameters(): QueryParameters {\n return authMode === 'WithinQueryParameters' ? credentials : {};\n },\n };\n}\n","import type { CreateIterablePromise } from './types/createIterablePromise';\n\n/**\n * Helper: Returns the promise of a given `func` to iterate on, based on a given `validate` condition.\n *\n * @param createIterator - The createIterator options.\n * @param createIterator.func - The function to run, which returns a promise.\n * @param createIterator.validate - The validator function. It receives the resolved return of `func`.\n * @param createIterator.aggregator - The function that runs right after the `func` method has been executed, allows you to do anything with the response before `validate`.\n * @param createIterator.error - The `validate` condition to throw an error, and its message.\n * @param createIterator.timeout - The function to decide how long to wait between iterations.\n */\nexport function createIterablePromise<TResponse>({\n func,\n validate,\n aggregator,\n error,\n timeout = (): number => 0,\n}: CreateIterablePromise<TResponse>): Promise<TResponse> {\n const retry = (previousResponse?: TResponse | undefined): Promise<TResponse> => {\n return new Promise<TResponse>((resolve, reject) => {\n func(previousResponse)\n .then(async (response) => {\n if (aggregator) {\n await aggregator(response);\n }\n\n if (await validate(response)) {\n return resolve(response);\n }\n\n if (error && (await error.validate(response))) {\n return reject(new Error(await error.message(response)));\n }\n\n return setTimeout(\n () => {\n retry(response).then(resolve).catch(reject);\n },\n await timeout(),\n );\n })\n .catch((err) => {\n reject(err);\n });\n });\n };\n\n return retry();\n}\n","import { createAlgoliaAgent } from './createAlgoliaAgent';\nimport type { AlgoliaAgent, AlgoliaAgentOptions } from './types';\n\nexport type GetAlgoliaAgent = {\n algoliaAgents: AlgoliaAgentOptions[];\n client: string;\n version: string;\n};\n\nexport function getAlgoliaAgent({ algoliaAgents, client, version }: GetAlgoliaAgent): AlgoliaAgent {\n const defaultAlgoliaAgent = createAlgoliaAgent(version).add({\n segment: client,\n version,\n });\n\n algoliaAgents.forEach((algoliaAgent) => defaultAlgoliaAgent.add(algoliaAgent));\n\n return defaultAlgoliaAgent;\n}\n","import type { Logger } from '../types/logger';\n\nexport function createNullLogger(): Logger {\n return {\n debug(_message: string, _args?: any | undefined): Promise<void> {\n return Promise.resolve();\n },\n info(_message: string, _args?: any | undefined): Promise<void> {\n return Promise.resolve();\n },\n error(_message: string, _args?: any | undefined): Promise<void> {\n return Promise.resolve();\n },\n };\n}\n","import type { Host, StatefulHost } from '../types';\n\n// By default, API Clients at Algolia have expiration delay of 5 mins.\n// In the JavaScript client, we have 2 mins.\nconst EXPIRATION_DELAY = 2 * 60 * 1000;\n\nexport function createStatefulHost(host: Host, status: StatefulHost['status'] = 'up'): StatefulHost {\n const lastUpdate = Date.now();\n\n function isUp(): boolean {\n return status === 'up' || Date.now() - lastUpdate > EXPIRATION_DELAY;\n }\n\n function isTimedOut(): boolean {\n return status === 'timed out' && Date.now() - lastUpdate <= EXPIRATION_DELAY;\n }\n\n return { ...host, status, lastUpdate, isUp, isTimedOut };\n}\n","import type { Response, StackFrame } from '../types';\n\nexport class AlgoliaError extends Error {\n override name: string = 'AlgoliaError';\n\n constructor(message: string, name: string) {\n super(message);\n\n if (name) {\n this.name = name;\n }\n }\n}\n\nexport class IndexNotFoundError extends AlgoliaError {\n constructor(indexName: string) {\n super(`${indexName} does not exist`, 'IndexNotFoundError');\n }\n}\n\nexport class IndicesInSameAppError extends AlgoliaError {\n constructor() {\n super('Indices are in the same application. Use operationIndex instead.', 'IndicesInSameAppError');\n }\n}\n\nexport class IndexAlreadyExistsError extends AlgoliaError {\n constructor(indexName: string) {\n super(`${indexName} index already exists.`, 'IndexAlreadyExistsError');\n }\n}\n\nexport class ErrorWithStackTrace extends AlgoliaError {\n stackTrace: StackFrame[];\n\n constructor(message: string, stackTrace: StackFrame[], name: string) {\n super(message, name);\n // the array and object should be frozen to reflect the stackTrace at the time of the error\n this.stackTrace = stackTrace;\n }\n}\n\nexport class RetryError extends ErrorWithStackTrace {\n constructor(stackTrace: StackFrame[]) {\n super(\n 'Unreachable hosts - your application id may be incorrect. If the error persists, please visit our help center https://alg.li/support-unreachable-hosts or reach out to the Algolia Support team: https://alg.li/support',\n stackTrace,\n 'RetryError',\n );\n }\n}\n\nexport class ApiError extends ErrorWithStackTrace {\n status: number;\n\n constructor(message: string, status: number, stackTrace: StackFrame[], name = 'ApiError') {\n super(message, stackTrace, name);\n this.status = status;\n }\n}\n\nexport class DeserializationError extends AlgoliaError {\n response: Response;\n\n constructor(message: string, response: Response) {\n super(message, 'DeserializationError');\n this.response = response;\n }\n}\n\nexport type DetailedErrorWithMessage = {\n message: string;\n label: string;\n};\n\nexport type DetailedErrorWithTypeID = {\n id: string;\n type: string;\n name?: string | undefined;\n};\n\nexport type DetailedError = {\n code: string;\n details?: DetailedErrorWithMessage[] | DetailedErrorWithTypeID[] | undefined;\n};\n\n// DetailedApiError is only used by the ingestion client to return more informative error, other clients will use ApiClient.\nexport class DetailedApiError extends ApiError {\n error: DetailedError;\n\n constructor(message: string, status: number, error: DetailedError, stackTrace: StackFrame[]) {\n super(message, status, stackTrace, 'DetailedApiError');\n this.error = error;\n }\n}\n","import type { Headers, Host, QueryParameters, Request, RequestOptions, Response, StackFrame } from '../types';\nimport { ApiError, DeserializationError, DetailedApiError } from './errors';\n\nexport function shuffle<TData>(array: TData[]): TData[] {\n const shuffledArray = array;\n\n for (let c = array.length - 1; c > 0; c--) {\n const b = Math.floor(Math.random() * (c + 1));\n const a = array[c];\n\n shuffledArray[c] = array[b];\n shuffledArray[b] = a;\n }\n\n return shuffledArray;\n}\n\nexport function serializeUrl(host: Host, path: string, queryParameters: QueryParameters): string {\n const queryParametersAsString = serializeQueryParameters(queryParameters);\n let url = `${host.protocol}://${host.url}${host.port ? `:${host.port}` : ''}/${\n path.charAt(0) === '/' ? path.substring(1) : path\n }`;\n\n if (queryParametersAsString.length) {\n url += `?${queryParametersAsString}`;\n }\n\n return url;\n}\n\nexport function serializeQueryParameters(parameters: QueryParameters): string {\n return Object.keys(parameters)\n .filter((key) => parameters[key] !== undefined)\n .sort()\n .map(\n (key) =>\n `${key}=${encodeURIComponent(\n Object.prototype.toString.call(parameters[key]) === '[object Array]'\n ? parameters[key].join(',')\n : parameters[key],\n ).replace(/\\+/g, '%20')}`,\n )\n .join('&');\n}\n\nexport function serializeData(request: Request, requestOptions: RequestOptions): string | undefined {\n if (request.method === 'GET' || (request.data === undefined && requestOptions.data === undefined)) {\n return undefined;\n }\n\n const data = Array.isArray(request.data) ? request.data : { ...request.data, ...requestOptions.data };\n\n return JSON.stringify(data);\n}\n\nexport function serializeHeaders(\n baseHeaders: Headers,\n requestHeaders: Headers,\n requestOptionsHeaders?: Headers | undefined,\n): Headers {\n const headers: Headers = {\n Accept: 'application/json',\n ...baseHeaders,\n ...requestHeaders,\n ...requestOptionsHeaders,\n };\n const serializedHeaders: Headers = {};\n\n Object.keys(headers).forEach((header) => {\n const value = headers[header];\n serializedHeaders[header.toLowerCase()] = value;\n });\n\n return serializedHeaders;\n}\n\nexport function deserializeSuccess<TObject>(response: Response): TObject {\n try {\n return JSON.parse(response.content);\n } catch (e) {\n throw new DeserializationError((e as Error).message, response);\n }\n}\n\nexport function deserializeFailure({ content, status }: Response, stackFrame: StackFrame[]): Error {\n try {\n const parsed = JSON.parse(content);\n if ('error' in parsed) {\n return new DetailedApiError(parsed.message, status, parsed.error, stackFrame);\n }\n return new ApiError(parsed.message, status, stackFrame);\n } catch {\n // ..\n }\n return new ApiError(content, status, stackFrame);\n}\n","import type { Response } from '../types';\n\nexport function isNetworkError({ isTimedOut, status }: Omit<Response, 'content'>): boolean {\n return !isTimedOut && ~~status === 0;\n}\n\nexport function isRetryable({ isTimedOut, status }: Omit<Response, 'content'>): boolean {\n return isTimedOut || isNetworkError({ isTimedOut, status }) || (~~(status / 100) !== 2 && ~~(status / 100) !== 4);\n}\n\nexport function isSuccess({ status }: Pick<Response, 'status'>): boolean {\n return ~~(status / 100) === 2;\n}\n","import type { Headers, StackFrame } from '../types';\n\nexport function stackTraceWithoutCredentials(stackTrace: StackFrame[]): StackFrame[] {\n return stackTrace.map((stackFrame) => stackFrameWithoutCredentials(stackFrame));\n}\n\nexport function stackFrameWithoutCredentials(stackFrame: StackFrame): StackFrame {\n const modifiedHeaders: Headers = stackFrame.request.headers['x-algolia-api-key']\n ? { 'x-algolia-api-key': '*****' }\n : {};\n\n return {\n ...stackFrame,\n request: {\n ...stackFrame.request,\n headers: {\n ...stackFrame.request.headers,\n ...modifiedHeaders,\n },\n },\n };\n}\n","import type {\n EndRequest,\n Host,\n QueryParameters,\n Request,\n RequestOptions,\n Response,\n StackFrame,\n Transporter,\n TransporterOptions,\n} from '../types';\nimport { createStatefulHost } from './createStatefulHost';\nimport { RetryError } from './errors';\nimport { deserializeFailure, deserializeSuccess, serializeData, serializeHeaders, serializeUrl } from './helpers';\nimport { isRetryable, isSuccess } from './responses';\nimport { stackFrameWithoutCredentials, stackTraceWithoutCredentials } from './stackTrace';\n\ntype RetryableOptions = {\n hosts: Host[];\n getTimeout: (retryCount: number, timeout: number) => number;\n};\n\nexport function createTransporter({\n hosts,\n hostsCache,\n baseHeaders,\n logger,\n baseQueryParameters,\n algoliaAgent,\n timeouts,\n requester,\n requestsCache,\n responsesCache,\n}: TransporterOptions): Transporter {\n async function createRetryableOptions(compatibleHosts: Host[]): Promise<RetryableOptions> {\n const statefulHosts = await Promise.all(\n compatibleHosts.map((compatibleHost) => {\n return hostsCache.get(compatibleHost, () => {\n return Promise.resolve(createStatefulHost(compatibleHost));\n });\n }),\n );\n const hostsUp = statefulHosts.filter((host) => host.isUp());\n const hostsTimedOut = statefulHosts.filter((host) => host.isTimedOut());\n\n // Note, we put the hosts that previously timed out on the end of the list.\n const hostsAvailable = [...hostsUp, ...hostsTimedOut];\n const compatibleHostsAvailable = hostsAvailable.length > 0 ? hostsAvailable : compatibleHosts;\n\n return {\n hosts: compatibleHostsAvailable,\n getTimeout(timeoutsCount: number, baseTimeout: number): number {\n /**\n * Imagine that you have 4 hosts, if timeouts will increase\n * on the following way: 1 (timed out) > 4 (timed out) > 5 (200).\n *\n * Note that, the very next request, we start from the previous timeout.\n *\n * 5 (timed out) > 6 (timed out) > 7 ...\n *\n * This strategy may need to be reviewed, but is the strategy on the our\n * current v3 version.\n */\n const timeoutMultiplier =\n hostsTimedOut.length === 0 && timeoutsCount === 0 ? 1 : hostsTimedOut.length + 3 + timeoutsCount;\n\n return timeoutMultiplier * baseTimeout;\n },\n };\n }\n\n async function retryableRequest<TResponse>(\n request: Request,\n requestOptions: RequestOptions,\n isRead = true,\n ): Promise<TResponse> {\n const stackTrace: StackFrame[] = [];\n\n /**\n * First we prepare the payload that do not depend from hosts.\n */\n const data = serializeData(request, requestOptions);\n const headers = serializeHeaders(baseHeaders, request.headers, requestOptions.headers);\n\n // On `GET`, the data is proxied to query parameters.\n const dataQueryParameters: QueryParameters =\n request.method === 'GET'\n ? {\n ...request.data,\n ...requestOptions.data,\n }\n : {};\n\n const queryParameters: QueryParameters = {\n ...baseQueryParameters,\n ...request.queryParameters,\n ...dataQueryParameters,\n };\n\n if (algoliaAgent.value) {\n queryParameters['x-algolia-agent'] = algoliaAgent.value;\n }\n\n if (requestOptions && requestOptions.queryParameters) {\n for (const key of Object.keys(requestOptions.queryParameters)) {\n // We want to keep `undefined` and `null` values,\n // but also avoid stringifying `object`s, as they are\n // handled in the `serializeUrl` step right after.\n if (\n !requestOptions.queryParameters[key] ||\n Object.prototype.toString.call(requestOptions.queryParameters[key]) === '[object Object]'\n ) {\n queryParameters[key] = requestOptions.queryParameters[key];\n } else {\n queryParameters[key] = requestOptions.queryParameters[key].toString();\n }\n }\n }\n\n let timeoutsCount = 0;\n\n const retry = async (\n retryableHosts: Host[],\n getTimeout: (timeoutsCount: number, timeout: number) => number,\n ): Promise<TResponse> => {\n /**\n * We iterate on each host, until there is no host left.\n */\n const host = retryableHosts.pop();\n if (host === undefined) {\n throw new RetryError(stackTraceWithoutCredentials(stackTrace));\n }\n\n const timeout = { ...timeouts, ...requestOptions.timeouts };\n\n const payload: EndRequest = {\n data,\n headers,\n method: request.method,\n url: serializeUrl(host, request.path, queryParameters),\n connectTimeout: getTimeout(timeoutsCount, timeout.connect),\n responseTimeout: getTimeout(timeoutsCount, isRead ? timeout.read : timeout.write),\n };\n\n /**\n * The stackFrame is pushed to the stackTrace so we\n * can have information about onRetry and onFailure\n * decisions.\n */\n const pushToStackTrace = (response: Response): StackFrame => {\n const stackFrame: StackFrame = {\n request: payload,\n response,\n host,\n triesLeft: retryableHosts.length,\n };\n\n stackTrace.push(stackFrame);\n\n return stackFrame;\n };\n\n const response = await requester.send(payload);\n\n if (isRetryable(response)) {\n const stackFrame = pushToStackTrace(response);\n\n // If response is a timeout, we increase the number of timeouts so we can increase the timeout later.\n if (response.isTimedOut) {\n timeoutsCount++;\n }\n /**\n * Failures are individually sent to the logger, allowing\n * the end user to debug / store stack frames even\n * when a retry error does not happen.\n */\n logger.info('Retryable failure', stackFrameWithoutCredentials(stackFrame));\n\n /**\n * We also store the state of the host in failure cases. If the host, is\n * down it will remain down for the next 2 minutes. In a timeout situation,\n * this host will be added end of the list of hosts on the next request.\n */\n await hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? 'timed out' : 'down'));\n\n return retry(retryableHosts, getTimeout);\n }\n\n if (isSuccess(response)) {\n return deserializeSuccess(response);\n }\n\n pushToStackTrace(response);\n throw deserializeFailure(response, stackTrace);\n };\n\n /**\n * Finally, for each retryable host perform request until we got a non\n * retryable response. Some notes here:\n *\n * 1. The reverse here is applied so we can apply a `pop` later on => more performant.\n * 2. We also get from the retryable options a timeout multiplier that is tailored\n * for the current context.\n */\n const compatibleHosts = hosts.filter(\n (host) => host.accept === 'readWrite' || (isRead ? host.accept === 'read' : host.accept === 'write'),\n );\n const options = await createRetryableOptions(compatibleHosts);\n\n return retry([...options.hosts].reverse(), options.getTimeout);\n }\n\n function createRequest<TResponse>(request: Request, requestOptions: RequestOptions = {}): Promise<TResponse> {\n /**\n * A read request is either a `GET` request, or a request that we make\n * via the `read` transporter (e.g. `search`).\n */\n const isRead = request.useReadTransporter || request.method === 'GET';\n if (!isRead) {\n /**\n * On write requests, no cache mechanisms are applied, and we\n * proxy the request immediately to the requester.\n */\n return retryableRequest<TResponse>(request, requestOptions, isRead);\n }\n\n const createRetryableRequest = (): Promise<TResponse> => {\n /**\n * Then, we prepare a function factory that contains the construction of\n * the retryable request. At this point, we may *not* perform the actual\n * request. But we want to have the function factory ready.\n */\n return retryableRequest<TResponse>(request, requestOptions);\n };\n\n /**\n * Once we have the function factory ready, we need to determine of the\n * request is \"cacheable\" - should be cached. Note that, once again,\n * the user can force this option.\n */\n const cacheable = requestOptions.cacheable || request.cacheable;\n\n /**\n * If is not \"cacheable\", we immediately trigger the retryable request, no\n * need to check cache implementations.\n */\n if (cacheable !== true) {\n return createRetryableRequest();\n }\n\n /**\n * If the request is \"cacheable\", we need to first compute the key to ask\n * the cache implementations if this request is on progress or if the\n * response already exists on the cache.\n */\n const key = {\n request,\n requestOptions,\n transporter: {\n queryParameters: baseQueryParameters,\n headers: baseHeaders,\n },\n };\n\n /**\n * With the computed key, we first ask the responses cache\n * implementation if this request was been resolved before.\n */\n return responsesCache.get(\n key,\n () => {\n /**\n * If the request has never resolved before, we actually ask if there\n * is a current request with the same key on progress.\n */\n return requestsCache.get(key, () =>\n /**\n * Finally, if there is no request in progress with the same key,\n * this `createRetryableRequest()` will actually trigger the\n * retryable request.\n */\n requestsCache\n .set(key, createRetryableRequest())\n .then(\n (response) => Promise.all([requestsCache.delete(key), response]),\n (err) => Promise.all([requestsCache.delete(key), Promise.reject(err)]),\n )\n .then(([_, response]) => response),\n );\n },\n {\n /**\n * Of course, once we get this response back from the server, we\n * tell response cache to actually store the received response\n * to be used later.\n */\n miss: (response) => responsesCache.set(key, response),\n },\n );\n }\n\n return {\n hostsCache,\n requester,\n timeouts,\n logger,\n algoliaAgent,\n baseHeaders,\n baseQueryParameters,\n hosts,\n request: createRequest,\n requestsCache,\n responsesCache,\n };\n}\n","export const LogLevelEnum: Readonly<Record<string, LogLevelType>> = {\n Debug: 1,\n Info: 2,\n Error: 3,\n};\n\nexport type LogLevelType = 1 | 2 | 3;\n\nexport type Logger = {\n /**\n * Logs debug messages.\n */\n debug: (message: string, args?: any | undefined) => Promise<void>;\n\n /**\n * Logs info messages.\n */\n info: (message: string, args?: any | undefined) => Promise<void>;\n\n /**\n * Logs error messages.\n */\n error: (message: string, args?: any | undefined) => Promise<void>;\n};\n","// Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT.\n\nimport type {\n CreateClientOptions,\n Headers,\n Host,\n QueryParameters,\n Request,\n RequestOptions,\n} from '@algolia/client-common';\nimport { createAuth, createTransporter, getAlgoliaAgent, shuffle } from '@algolia/client-common';\n\nimport type { DeletedAtResponse } from '../model/deletedAtResponse';\n\nimport type { GetRecommendTaskResponse } from '../model/getRecommendTaskResponse';\nimport type { GetRecommendationsParams } from '../model/getRecommendationsParams';\nimport type { GetRecommendationsResponse } from '../model/getRecommendationsResponse';\n\nimport type { RecommendRule } from '../model/recommendRule';\nimport type { RecommendUpdatedAtResponse } from '../model/recommendUpdatedAtResponse';\n\nimport type { SearchRecommendRulesResponse } from '../model/searchRecommendRulesResponse';\n\nimport type {\n BatchRecommendRulesProps,\n CustomDeleteProps,\n CustomGetProps,\n CustomPostProps,\n CustomPutProps,\n DeleteRecommendRuleProps,\n GetRecommendRuleProps,\n GetRecommendStatusProps,\n LegacyGetRecommendationsParams,\n SearchRecommendRulesProps,\n} from '../model/clientMethodProps';\n\nexport const apiClientVersion = '5.42.0';\n\nfunction getDefaultHosts(appId: string): Host[] {\n return (\n [\n {\n url: `${appId}-dsn.algolia.net`,\n accept: 'read',\n protocol: 'https',\n },\n {\n url: `${appId}.algolia.net`,\n accept: 'write',\n protocol: 'https',\n },\n ] as Host[]\n ).concat(\n shuffle([\n {\n url: `${appId}-1.algolianet.com`,\n accept: 'readWrite',\n protocol: 'https',\n },\n {\n url: `${appId}-2.algolianet.com`,\n accept: 'readWrite',\n protocol: 'https',\n },\n {\n url: `${appId}-3.algolianet.com`,\n accept: 'readWrite',\n protocol: 'https',\n },\n ]),\n );\n}\n\nexport function createRecommendClient({\n appId: appIdOption,\n apiKey: apiKeyOption,\n authMode,\n algoliaAgents,\n ...options\n}: CreateClientOptions) {\n const auth = createAuth(appIdOption, apiKeyOption, authMode);\n const transporter = createTransporter({\n hosts: getDefaultHosts(appIdOption),\n ...options,\n algoliaAgent: getAlgoliaAgent({\n algoliaAgents,\n client: 'Recommend',\n version: apiClientVersion,\n }),\n baseHeaders: {\n 'content-type': 'text/plain',\n ...auth.headers(),\n ...options.baseHeaders,\n },\n baseQueryParameters: {\n ...auth.queryParameters(),\n ...options.baseQueryParameters,\n },\n });\n\n return {\n transporter,\n\n /**\n * The `appId` currently in use.\n */\n appId: appIdOption,\n\n /**\n * The `apiKey` currently in use.\n */\n apiKey: apiKeyOption,\n\n /**\n * Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.\n */\n clearCache(): Promise<void> {\n return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => undefined);\n },\n\n /**\n * Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.\n */\n get _ua(): string {\n return transporter.algoliaAgent.value;\n },\n\n /**\n * Adds a `segment` to the `x-algolia-agent` sent with every requests.\n *\n * @param segment - The algolia agent (user-agent) segment to add.\n * @param version - The version of the agent.\n */\n addAlgoliaAgent(segment: string, version?: string | undefined): void {\n transporter.algoliaAgent.add({ segment, version });\n },\n\n /**\n * Helper method to switch the API key used to authenticate the requests.\n *\n * @param params - Method params.\n * @param params.apiKey - The new API Key to use.\n */\n setClientApiKey({ apiKey }: { apiKey: string }): void {\n if (!authMode || authMode === 'WithinHeaders') {\n transporter.baseHeaders['x-algolia-api-key'] = apiKey;\n } else {\n transporter.baseQueryParameters['x-algolia-api-key'] = apiKey;\n }\n },\n\n /**\n * Create or update a batch of Recommend Rules Each Recommend Rule is created or updated, depending on whether a Recommend Rule with the same `objectID` already exists. You may also specify `true` for `clearExistingRules`, in which case the batch will atomically replace all the existing Recommend Rules. Recommend Rules are similar to Search Rules, except that the conditions and consequences apply to a [source item](/doc/guides/algolia-recommend/overview/#recommend-models) instead of a query. The main differences are the following: - Conditions `pattern` and `anchoring` are unavailable. - Condition `filters` triggers if the source item matches the specified filters. - Condition `filters` accepts numeric filters. - Consequence `params` only covers filtering parameters. - Consequence `automaticFacetFilters` doesn\\'t require a facet value placeholder (it tries to match the data source item\\'s attributes instead).\n *\n * Required API Key ACLs:\n * - editSettings\n * @param batchRecommendRules - The batchRecommendRules object.\n * @param batchRecommendRules.indexName - Name of the index on which to perform the operation.\n * @param batchRecommendRules.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).\n * @param batchRecommendRules.recommendRule - The recommendRule object.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n batchRecommendRules(\n { indexName, model, recommendRule }: BatchRecommendRulesProps,\n requestOptions?: RequestOptions,\n ): Promise<RecommendUpdatedAtResponse> {\n if (!indexName) {\n throw new Error('Parameter `indexName` is required when calling `batchRecommendRules`.');\n }\n\n if (!model) {\n throw new Error('Parameter `model` is required when calling `batchRecommendRules`.');\n }\n\n const requestPath = '/1/indexes/{indexName}/{model}/recommend/rules/batch'\n .replace('{indexName}', encodeURIComponent(indexName))\n .replace('{model}', encodeURIComponent(model));\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'POST',\n path: requestPath,\n queryParameters,\n headers,\n data: recommendRule ? recommendRule : {},\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * This method lets you send requests to the Algolia REST API.\n * @param customDelete - The customDelete object.\n * @param customDelete.path - Path of the endpoint, for example `1/newFeature`.\n * @param customDelete.parameters - Query parameters to apply to the current query.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n customDelete(\n { path, parameters }: CustomDeleteProps,\n requestOptions?: RequestOptions,\n ): Promise<Record<string, unknown>> {\n if (!path) {\n throw new Error('Parameter `path` is required when calling `customDelete`.');\n }\n\n const requestPath = '/{path}'.replace('{path}', path);\n const headers: Headers = {};\n const queryParameters: QueryParameters = parameters ? parameters : {};\n\n const request: Request = {\n method: 'DELETE',\n path: requestPath,\n queryParameters,\n headers,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * This method lets you send requests to the Algolia REST API.\n * @param customGet - The customGet object.\n * @param customGet.path - Path of the endpoint, for example `1/newFeature`.\n * @param customGet.parameters - Query parameters to apply to the current query.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n customGet({ path, parameters }: CustomGetProps, requestOptions?: RequestOptions): Promise<Record<string, unknown>> {\n if (!path) {\n throw new Error('Parameter `path` is required when calling `customGet`.');\n }\n\n const requestPath = '/{path}'.replace('{path}', path);\n const headers: Headers = {};\n const queryParameters: QueryParameters = parameters ? parameters : {};\n\n const request: Request = {\n method: 'GET',\n path: requestPath,\n queryParameters,\n headers,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * This method lets you send requests to the Algolia REST API.\n * @param customPost - The customPost object.\n * @param customPost.path - Path of the endpoint, for example `1/newFeature`.\n * @param customPost.parameters - Query parameters to apply to the current query.\n * @param customPost.body - Parameters to send with the custom request.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n customPost(\n { path, parameters, body }: CustomPostProps,\n requestOptions?: RequestOptions,\n ): Promise<Record<string, unknown>> {\n if (!path) {\n throw new Error('Parameter `path` is required when calling `customPost`.');\n }\n\n const requestPath = '/{path}'.replace('{path}', path);\n const headers: Headers = {};\n const queryParameters: QueryParameters = parameters ? parameters : {};\n\n const request: Request = {\n method: 'POST',\n path: requestPath,\n queryParameters,\n headers,\n data: body ? body : {},\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * This method lets you send requests to the Algolia REST API.\n * @param customPut - The customPut object.\n * @param customPut.path - Path of the endpoint, for example `1/newFeature`.\n * @param customPut.parameters - Query parameters to apply to the current query.\n * @param customPut.body - Parameters to send with the custom request.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n customPut(\n { path, parameters, body }: CustomPutProps,\n requestOptions?: RequestOptions,\n ): Promise<Record<string, unknown>> {\n if (!path) {\n throw new Error('Parameter `path` is required when calling `customPut`.');\n }\n\n const requestPath = '/{path}'.replace('{path}', path);\n const headers: Headers = {};\n const queryParameters: QueryParameters = parameters ? parameters : {};\n\n const request: Request = {\n method: 'PUT',\n path: requestPath,\n queryParameters,\n headers,\n data: body ? body : {},\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * Deletes a Recommend rule from a recommendation scenario.\n *\n * Required API Key ACLs:\n * - editSettings\n * @param deleteRecommendRule - The deleteRecommendRule object.\n * @param deleteRecommendRule.indexName - Name of the index on which to perform the operation.\n * @param deleteRecommendRule.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).\n * @param deleteRecommendRule.objectID - Unique record identifier.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n deleteRecommendRule(\n { indexName, model, objectID }: DeleteRecommendRuleProps,\n requestOptions?: RequestOptions,\n ): Promise<DeletedAtResponse> {\n if (!indexName) {\n throw new Error('Parameter `indexName` is required when calling `deleteRecommendRule`.');\n }\n\n if (!model) {\n throw new Error('Parameter `model` is required when calling `deleteRecommendRule`.');\n }\n\n if (!objectID) {\n throw new Error('Parameter `objectID` is required when calling `deleteRecommendRule`.');\n }\n\n const requestPath = '/1/indexes/{indexName}/{model}/recommend/rules/{objectID}'\n .replace('{indexName}', encodeURIComponent(indexName))\n .replace('{model}', encodeURIComponent(model))\n .replace('{objectID}', encodeURIComponent(objectID));\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'DELETE',\n path: requestPath,\n queryParameters,\n headers,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * Retrieves a Recommend rule that you previously created in the Algolia dashboard.\n *\n * Required API Key ACLs:\n * - settings\n * @param getRecommendRule - The getRecommendRule object.\n * @param getRecommendRule.indexName - Name of the index on which to perform the operation.\n * @param getRecommendRule.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).\n * @param getRecommendRule.objectID - Unique record identifier.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n getRecommendRule(\n { indexName, model, objectID }: GetRecommendRuleProps,\n requestOptions?: RequestOptions,\n ): Promise<RecommendRule> {\n if (!indexName) {\n throw new Error('Parameter `indexName` is required when calling `getRecommendRule`.');\n }\n\n if (!model) {\n throw new Error('Parameter `model` is required when calling `getRecommendRule`.');\n }\n\n if (!objectID) {\n throw new Error('Parameter `objectID` is required when calling `getRecommendRule`.');\n }\n\n const requestPath = '/1/indexes/{indexName}/{model}/recommend/rules/{objectID}'\n .replace('{indexName}', encodeURIComponent(indexName))\n .replace('{model}', encodeURIComponent(model))\n .replace('{objectID}', encodeURIComponent(objectID));\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'GET',\n path: requestPath,\n queryParameters,\n headers,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * Checks the status of a given task. Deleting a Recommend rule is asynchronous. When you delete a rule, a task is created on a queue and completed depending on the load on the server. The API response includes a task ID that you can use to check the status.\n *\n * Required API Key ACLs:\n * - editSettings\n * @param getRecommendStatus - The getRecommendStatus object.\n * @param getRecommendStatus.indexName - Name of the index on which to perform the operation.\n * @param getRecommendStatus.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).\n * @param getRecommendStatus.taskID - Unique task identifier.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n getRecommendStatus(\n { indexName, model, taskID }: GetRecommendStatusProps,\n requestOptions?: RequestOptions,\n ): Promise<GetRecommendTaskResponse> {\n if (!indexName) {\n throw new Error('Parameter `indexName` is required when calling `getRecommendStatus`.');\n }\n\n if (!model) {\n throw new Error('Parameter `model` is required when calling `getRecommendStatus`.');\n }\n\n if (!taskID) {\n throw new Error('Parameter `taskID` is required when calling `getRecommendStatus`.');\n }\n\n const requestPath = '/1/indexes/{indexName}/{model}/task/{taskID}'\n .replace('{indexName}', encodeURIComponent(indexName))\n .replace('{model}', encodeURIComponent(model))\n .replace('{taskID}', encodeURIComponent(taskID));\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'GET',\n path: requestPath,\n queryParameters,\n headers,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * Retrieves recommendations from selected AI models.\n *\n * Required API Key ACLs:\n * - search\n * @param getRecommendationsParams - The getRecommendationsParams object.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n getRecommendations(\n getRecommendationsParams: GetRecommendationsParams | LegacyGetRecommendationsParams,\n requestOptions?: RequestOptions,\n ): Promise<GetRecommendationsResponse> {\n if (getRecommendationsParams && Array.isArray(getRecommendationsParams)) {\n const newSignatureRequest: GetRecommendationsParams = {\n requests: getRecommendationsParams,\n };\n\n getRecommendationsParams = newSignatureRequest;\n }\n\n if (!getRecommendationsParams) {\n throw new Error('Parameter `getRecommendationsParams` is required when calling `getRecommendations`.');\n }\n\n if (!getRecommendationsParams.requests) {\n throw new Error('Parameter `getRecommendationsParams.requests` is required when calling `getRecommendations`.');\n }\n\n const requestPath = '/1/indexes/*/recommendations';\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'POST',\n path: requestPath,\n queryParameters,\n headers,\n data: getRecommendationsParams,\n useReadTransporter: true,\n cacheable: true,\n };\n\n return transporter.request(request, requestOptions);\n },\n\n /**\n * Searches for Recommend rules. Use an empty query to list all rules for this recommendation scenario.\n *\n * Required API Key ACLs:\n * - settings\n * @param searchRecommendRules - The searchRecommendRules object.\n * @param searchRecommendRules.indexName - Name of the index on which to perform the operation.\n * @param searchRecommendRules.model - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).\n * @param searchRecommendRules.searchRecommendRulesParams - The searchRecommendRulesParams object.\n * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.\n */\n searchRecommendRules(\n { indexName, model, searchRecommendRulesParams }: SearchRecommendRulesProps,\n requestOptions?: RequestOptions,\n ): Promise<SearchRecommendRulesResponse> {\n if (!indexName) {\n throw new Error('Parameter `indexName` is required when calling `searchRecommendRules`.');\n }\n\n if (!model) {\n throw new Error('Parameter `model` is required when calling `searchRecommendRules`.');\n }\n\n const requestPath = '/1/indexes/{indexName}/{model}/recommend/rules/search'\n .replace('{indexName}', encodeURIComponent(indexName))\n .replace('{model}', encodeURIComponent(model));\n const headers: Headers = {};\n const queryParameters: QueryParameters = {};\n\n const request: Request = {\n method: 'POST',\n path: requestPath,\n queryParameters,\n headers,\n data: searchRecommendRulesParams ? searchRecommendRulesParams : {},\n useReadTransporter: true,\n cacheable: true,\n };\n\n return transporter.request(request, requestOptions);\n },\n };\n}\n","// Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT.\n\nimport { createXhrRequester } from '@algolia/requester-browser-xhr';\n\nimport {\n createBrowserLocalStorageCache,\n createFallbackableCache,\n createMemoryCache,\n createNullLogger,\n} from '@algolia/client-common';\n\nimport type { ClientOptions } from '@algolia/client-common';\n\nimport { apiClientVersion, createRecommendClient } from '../src/recommendClient';\n\nexport { apiClientVersion } from '../src/recommendClient';\n\nexport * from '../model';\n\nexport function recommendClient(appId: string, apiKey: string, options?: ClientOptions | undefined): RecommendClient {\n if (!appId || typeof appId !== 'string') {\n throw new Error('`appId` is missing.');\n }\n\n if (!apiKey || typeof apiKey !== 'string') {\n throw new Error('`apiKey` is missing.');\n }\n\n return createRecommendClient({\n appId,\n apiKey,\n timeouts: {\n connect: 1000,\n read: 2000,\n write: 30000,\n },\n logger: createNullLogger(),\n requester: createXhrRequester(),\n algoliaAgents: [{ segment: 'Browser' }],\n authMode: 'WithinQueryParameters',\n responsesCache: createMemoryCache(),\n requestsCache: createMemoryCache({ serializable: false }),\n hostsCache: createFallbackableCache({\n caches: [createBrowserLocalStorageCache({ key: `${apiClientVersion}-${appId}` }), createMemoryCache()],\n }),\n ...options,\n });\n}\n\nexport type RecommendClient = ReturnType<typeof createRecommendClient>;\n"],"mappings":"AAIO,SAASA,GAAgC,CAC9C,SAASC,EAAKC,EAAwC,CACpD,OAAO,IAAI,QAASC,GAAY,CAC9B,IAAMC,EAAgB,IAAI,eAC1BA,EAAc,KAAKF,EAAQ,OAAQA,EAAQ,IAAK,EAAI,EAEpD,OAAO,KAAKA,EAAQ,OAAO,EAAE,QAASG,GAAQD,EAAc,iBAAiBC,EAAKH,EAAQ,QAAQG,CAAG,CAAC,CAAC,EAEvG,IAAMC,EAAgB,CAACC,EAAiBC,IAC/B,WAAW,IAAM,CACtBJ,EAAc,MAAM,EAEpBD,EAAQ,CACN,OAAQ,EACR,QAAAK,EACA,WAAY,EACd,CAAC,CACH,EAAGD,CAAO,EAGNE,EAAiBH,EAAcJ,EAAQ,eAAgB,oBAAoB,EAE7EQ,EAEJN,EAAc,mBAAqB,IAAY,CACzCA,EAAc,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ACtC,SAAU,wBACV,eAAgBC,EAAkB,EAClC,cAAeA,EAAkB,CAAE,aAAc,EAAM,CAAC,EACxD,WAAYC,EAAwB,CAClC,OAAQ,CAACC,EAA+B,CAAE,IAAK,GAAGC,CAAgB,IAAIT,CAAK,EAAG,CAAC,EAAGM,EAAkB,CAAC,CACvG,CAAC,EACD,GAAGJ,CACL,CAAC,CACH","names":["createXhrRequester","send","request","resolve","baseRequester","key","createTimeout","timeout","content","connectTimeout","responseTimeout","createBrowserLocalStorageCache","options","storage","namespaceKey","getStorage","getNamespace","setNamespace","namespace","removeOutdatedCacheItems","timeToLive","filteredNamespaceWithoutOldFormattedCacheItems","cacheItem","filteredNamespaceWithoutExpiredItems","currentTimestamp","key","defaultValue","events","value","exists","createNullCache","_key","result","createFallbackableCache","caches","current","createMemoryCache","cache","keyAsString","promise","createAlgoliaAgent","version","algoliaAgent","options","addedAlgoliaAgent","createAuth","appId","apiKey","authMode","credentials","getAlgoliaAgent","algoliaAgents","client","version","defaultAlgoliaAgent","createAlgoliaAgent","algoliaAgent","createNullLogger","_message","_args","EXPIRATION_DELAY","createStatefulHost","host","status","lastUpdate","isUp","isTimedOut","AlgoliaError","message","name","ErrorWithStackTrace","AlgoliaError","message","stackTrace","name","RetryError","ApiError","status","DeserializationError","response","DetailedApiError","error","shuffle","array","shuffledArray","c","b","serializeUrl","host","path","queryParameters","queryParametersAsString","serializeQueryParameters","url","parameters","key","serializeData","request","requestOptions","data","serializeHeaders","baseHeaders","requestHeaders","requestOptionsHeaders","headers","serializedHeaders","header","value","deserializeSuccess","deserializeFailure","content","stackFrame","parsed","isNetworkError","isTimedOut","isRetryable","isSuccess","stackTraceWithoutCredentials","stackFrameWithoutCredentials","modifiedHeaders","createTransporter","hosts","hostsCache","logger","baseQueryParameters","algoliaAgent","timeouts","requester","requestsCache","responsesCache","createRetryableOptions","compatibleHosts","statefulHosts","compatibleHost","createStatefulHost","hostsUp","hostsTimedOut","hostsAvailable","timeoutsCount","baseTimeout","retryableRequest","isRead","dataQueryParameters","retry","retryableHosts","getTimeout","timeout","payload","pushToStackTrace","options","createRequest","createRetryableRequest","err","_","apiClientVersion","getDefaultHosts","appId","shuffle","createRecommendClient","appIdOption","apiKeyOption","authMode","algoliaAgents","options","auth","createAuth","transporter","createTransporter","getAlgoliaAgent","segment","version","apiKey","indexName","model","recommendRule","requestOptions","request","path","parameters","body","objectID","taskID","getRecommendationsParams","searchRecommendRulesParams","recommendClient","appId","apiKey","options","createRecommendClient","createNullLogger","m","createMemoryCache","createFallbackableCache","createBrowserLocalStorageCache","apiClientVersion"]}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@algolia/recommend"] = {}));
|
|
5
5
|
})(this, (function (exports) { 'use strict';
|
|
6
6
|
|
|
7
|
-
function H(){function r(e){return new Promise(o=>{let t=new XMLHttpRequest;t.open(e.method,e.url,true),Object.keys(e.headers).forEach(s=>t.setRequestHeader(s,e.headers[s]));let a=(s,n)=>setTimeout(()=>{t.abort(),o({status:0,content:n,isTimedOut:true});},s),d=a(e.connectTimeout,"Connection timeout"),c;t.onreadystatechange=()=>{t.readyState>t.OPENED&&c===void 0&&(clearTimeout(d),c=a(e.responseTimeout,"Socket timeout"));},t.onerror=()=>{t.status===0&&(clearTimeout(d),clearTimeout(c),o({content:t.responseText||"Network request failed",status:t.status,isTimedOut:false}));},t.onload=()=>{clearTimeout(d),clearTimeout(c),o({content:t.responseText,status:t.status,isTimedOut:false});},t.send(e.data);})}return {send:r}}function L(r){let e,o=`algolia-client-js-${r.key}`;function t(){return e===void 0&&(e=r.localStorage||window.localStorage),e}function a(){return JSON.parse(t().getItem(o)||"{}")}function d(s){t().setItem(o,JSON.stringify(s));}function c(){let s=r.timeToLive?r.timeToLive*1e3:null,n=a(),i=Object.fromEntries(Object.entries(n).filter(([,p])=>p.timestamp!==void 0));if(d(i),!s)return;let l=Object.fromEntries(Object.entries(i).filter(([,p])=>{let h=new Date().getTime();return !(p.timestamp+s<h)}));d(l);}return {get(s,n,i={miss:()=>Promise.resolve()}){return Promise.resolve().then(()=>(c(),a()[JSON.stringify(s)])).then(l=>Promise.all([l?l.value:n(),l!==void 0])).then(([l,p])=>Promise.all([l,p||i.miss(l)])).then(([l])=>l)},set(s,n){return Promise.resolve().then(()=>{let i=a();return i[JSON.stringify(s)]={timestamp:new Date().getTime(),value:n},t().setItem(o,JSON.stringify(i)),n})},delete(s){return Promise.resolve().then(()=>{let n=a();delete n[JSON.stringify(s)],t().setItem(o,JSON.stringify(n));})},clear(){return Promise.resolve().then(()=>{t().removeItem(o);})}}}function V(){return {get(r,e,o={miss:()=>Promise.resolve()}){return e().then(a=>Promise.all([a,o.miss(a)])).then(([a])=>a)},set(r,e){return Promise.resolve(e)},delete(r){return Promise.resolve()},clear(){return Promise.resolve()}}}function q(r){let e=[...r.caches],o=e.shift();return o===void 0?V():{get(t,a,d={miss:()=>Promise.resolve()}){return o.get(t,a,d).catch(()=>q({caches:e}).get(t,a,d))},set(t,a){return o.set(t,a).catch(()=>q({caches:e}).set(t,a))},delete(t){return o.delete(t).catch(()=>q({caches:e}).delete(t))},clear(){return o.clear().catch(()=>q({caches:e}).clear())}}}function A(r={serializable:true}){let e={};return {get(o,t,a={miss:()=>Promise.resolve()}){let d=JSON.stringify(o);if(d in e)return Promise.resolve(r.serializable?JSON.parse(e[d]):e[d]);let c=t();return c.then(s=>a.miss(s)).then(()=>c)},set(o,t){return e[JSON.stringify(o)]=r.serializable?JSON.stringify(t):t,Promise.resolve(t)},delete(o){return delete e[JSON.stringify(o)],Promise.resolve()},clear(){return e={},Promise.resolve()}}}function Y(r){let e={value:`Algolia for JavaScript (${r})`,add(o){let t=`; ${o.segment}${o.version!==void 0?` (${o.version})`:""}`;return e.value.indexOf(t)===-1&&(e.value=`${e.value}${t}`),e}};return e}function j(r,e,o="WithinHeaders"){let t={"x-algolia-api-key":e,"x-algolia-application-id":r};return {headers(){return o==="WithinHeaders"?t:{}},queryParameters(){return o==="WithinQueryParameters"?t:{}}}}function W({algoliaAgents:r,client:e,version:o}){let t=Y(o).add({segment:e,version:o});return r.forEach(a=>t.add(a)),t}function J(){return {debug(r,e){return Promise.resolve()},info(r,e){return Promise.resolve()},error(r,e){return Promise.resolve()}}}var $=120*1e3;function G(r,e="up"){let o=Date.now();function t(){return e==="up"||Date.now()-o>$}function a(){return e==="timed out"&&Date.now()-o<=$}return {...r,status:e,lastUpdate:o,isUp:t,isTimedOut:a}}var Q=class extends Error{name="AlgoliaError";constructor(r,e){super(r),e&&(this.name=e);}};var z=class extends Q{stackTrace;constructor(r,e,o){super(r,o),this.stackTrace=e;}},Z=class extends z{constructor(r){super("Unreachable hosts - your application id may be incorrect. If the error persists, please visit our help center https://alg.li/support-unreachable-hosts or reach out to the Algolia Support team: https://alg.li/support",r,"RetryError");}},I=class extends z{status;constructor(r,e,o,t="ApiError"){super(r,o,t),this.status=e;}},ee=class extends Q{response;constructor(r,e){super(r,"DeserializationError"),this.response=e;}},re=class extends I{error;constructor(r,e,o,t){super(r,e,t,"DetailedApiError"),this.error=o;}};function M(r){let e=r;for(let o=r.length-1;o>0;o--){let t=Math.floor(Math.random()*(o+1)),a=r[o];e[o]=r[t],e[t]=a;}return e}function te(r,e,o){let t=oe(o),a=`${r.protocol}://${r.url}${r.port?`:${r.port}`:""}/${e.charAt(0)==="/"?e.substring(1):e}`;return t.length&&(a+=`?${t}`),a}function oe(r){return Object.keys(r).filter(e=>r[e]!==void 0).sort().map(e=>`${e}=${encodeURIComponent(Object.prototype.toString.call(r[e])==="[object Array]"?r[e].join(","):r[e]).replace(/\+/g,"%20")}`).join("&")}function se(r,e){if(r.method==="GET"||r.data===void 0&&e.data===void 0)return;let o=Array.isArray(r.data)?r.data:{...r.data,...e.data};return JSON.stringify(o)}function ne(r,e,o){let t={Accept:"application/json",...r,...e,...o},a={};return Object.keys(t).forEach(d=>{let c=t[d];a[d.toLowerCase()]=c;}),a}function ae(r){try{return JSON.parse(r.content)}catch(e){throw new ee(e.message,r)}}function ie({content:r,status:e},o){try{let t=JSON.parse(r);return "error"in t?new re(t.message,e,t.error,o):new I(t.message,e,o)}catch{}return new I(r,e,o)}function me({isTimedOut:r,status:e}){return !r&&~~e===0}function ce({isTimedOut:r,status:e}){return r||me({isTimedOut:r,status:e})||~~(e/100)!==2&&~~(e/100)!==4}function ue({status:r}){return ~~(r/100)===2}function le(r){return r.map(e=>F(e))}function F(r){let e=r.request.headers["x-algolia-api-key"]?{"x-algolia-api-key":"*****"}:{};return {...r,request:{...r.request,headers:{...r.request.headers,...e}}}}function B({hosts:r,hostsCache:e,baseHeaders:o,logger:t,baseQueryParameters:a,algoliaAgent:d,timeouts:c,requester:s,requestsCache:n,responsesCache:i}){async function l(u){let m=await Promise.all(u.map(f=>e.get(f,()=>Promise.resolve(G(f))))),w=m.filter(f=>f.isUp()),R=m.filter(f=>f.isTimedOut()),E=[...w,...R];return {hosts:E.length>0?E:u,getTimeout(f,g){return (R.length===0&&f===0?1:R.length+3+f)*g}}}async function p(u,m,w=true){let R=[],E=se(u,m),x=ne(o,u.headers,m.headers),f=u.method==="GET"?{...u.data,...m.data}:{},g={...a,...u.queryParameters,...f};if(d.value&&(g["x-algolia-agent"]=d.value),m&&m.queryParameters)for(let P of Object.keys(m.queryParameters))!m.queryParameters[P]||Object.prototype.toString.call(m.queryParameters[P])==="[object Object]"?g[P]=m.queryParameters[P]:g[P]=m.queryParameters[P].toString();let v=0,N=async(P,S)=>{let T=P.pop();if(T===void 0)throw new Z(le(R));let C={...c,...m.timeouts},U={data:E,headers:x,method:u.method,url:te(T,u.path,g),connectTimeout:S(v,C.connect),responseTimeout:S(v,w?C.read:C.write)},k=b=>{let _={request:U,response:b,host:T,triesLeft:P.length};return R.push(_),_},y=await s.send(U);if(ce(y)){let b=k(y);return y.isTimedOut&&v++,t.info("Retryable failure",F(b)),await e.set(T,G(T,y.isTimedOut?"timed out":"down")),N(P,S)}if(ue(y))return ae(y);throw k(y),ie(y,R)},K=r.filter(P=>P.accept==="readWrite"||(w?P.accept==="read":P.accept==="write")),D=await l(K);return N([...D.hosts].reverse(),D.getTimeout)}function h(u,m={}){let w=u.useReadTransporter||u.method==="GET";if(!w)return p(u,m,w);let R=()=>p(u,m);if((m.cacheable||u.cacheable)!==true)return R();let x={request:u,requestOptions:m,transporter:{queryParameters:a,headers:o}};return i.get(x,()=>n.get(x,()=>n.set(x,R()).then(f=>Promise.all([n.delete(x),f]),f=>Promise.all([n.delete(x),Promise.reject(f)])).then(([f,g])=>g)),{miss:f=>i.set(x,f)})}return {hostsCache:e,requester:s,timeouts:c,logger:t,algoliaAgent:d,baseHeaders:o,baseQueryParameters:a,hosts:r,request:h,requestsCache:n,responsesCache:i}}var O="5.41.0";function de(r){return [{url:`${r}-dsn.algolia.net`,accept:"read",protocol:"https"},{url:`${r}.algolia.net`,accept:"write",protocol:"https"}].concat(M([{url:`${r}-1.algolianet.com`,accept:"readWrite",protocol:"https"},{url:`${r}-2.algolianet.com`,accept:"readWrite",protocol:"https"},{url:`${r}-3.algolianet.com`,accept:"readWrite",protocol:"https"}]))}function X({appId:r,apiKey:e,authMode:o,algoliaAgents:t,...a}){let d=j(r,e,o),c=B({hosts:de(r),...a,algoliaAgent:W({algoliaAgents:t,client:"Recommend",version:O}),baseHeaders:{"content-type":"text/plain",...d.headers(),...a.baseHeaders},baseQueryParameters:{...d.queryParameters(),...a.baseQueryParameters}});return {transporter:c,appId:r,apiKey:e,clearCache(){return Promise.all([c.requestsCache.clear(),c.responsesCache.clear()]).then(()=>{})},get _ua(){return c.algoliaAgent.value},addAlgoliaAgent(s,n){c.algoliaAgent.add({segment:s,version:n});},setClientApiKey({apiKey:s}){!o||o==="WithinHeaders"?c.baseHeaders["x-algolia-api-key"]=s:c.baseQueryParameters["x-algolia-api-key"]=s;},batchRecommendRules({indexName:s,model:n,recommendRule:i},l){if(!s)throw new Error("Parameter `indexName` is required when calling `batchRecommendRules`.");if(!n)throw new Error("Parameter `model` is required when calling `batchRecommendRules`.");let m={method:"POST",path:"/1/indexes/{indexName}/{model}/recommend/rules/batch".replace("{indexName}",encodeURIComponent(s)).replace("{model}",encodeURIComponent(n)),queryParameters:{},headers:{},data:i||{}};return c.request(m,l)},customDelete({path:s,parameters:n},i){if(!s)throw new Error("Parameter `path` is required when calling `customDelete`.");let u={method:"DELETE",path:"/{path}".replace("{path}",s),queryParameters:n||{},headers:{}};return c.request(u,i)},customGet({path:s,parameters:n},i){if(!s)throw new Error("Parameter `path` is required when calling `customGet`.");let u={method:"GET",path:"/{path}".replace("{path}",s),queryParameters:n||{},headers:{}};return c.request(u,i)},customPost({path:s,parameters:n,body:i},l){if(!s)throw new Error("Parameter `path` is required when calling `customPost`.");let m={method:"POST",path:"/{path}".replace("{path}",s),queryParameters:n||{},headers:{},data:i||{}};return c.request(m,l)},customPut({path:s,parameters:n,body:i},l){if(!s)throw new Error("Parameter `path` is required when calling `customPut`.");let m={method:"PUT",path:"/{path}".replace("{path}",s),queryParameters:n||{},headers:{},data:i||{}};return c.request(m,l)},deleteRecommendRule({indexName:s,model:n,objectID:i},l){if(!s)throw new Error("Parameter `indexName` is required when calling `deleteRecommendRule`.");if(!n)throw new Error("Parameter `model` is required when calling `deleteRecommendRule`.");if(!i)throw new Error("Parameter `objectID` is required when calling `deleteRecommendRule`.");let m={method:"DELETE",path:"/1/indexes/{indexName}/{model}/recommend/rules/{objectID}".replace("{indexName}",encodeURIComponent(s)).replace("{model}",encodeURIComponent(n)).replace("{objectID}",encodeURIComponent(i)),queryParameters:{},headers:{}};return c.request(m,l)},getRecommendRule({indexName:s,model:n,objectID:i},l){if(!s)throw new Error("Parameter `indexName` is required when calling `getRecommendRule`.");if(!n)throw new Error("Parameter `model` is required when calling `getRecommendRule`.");if(!i)throw new Error("Parameter `objectID` is required when calling `getRecommendRule`.");let m={method:"GET",path:"/1/indexes/{indexName}/{model}/recommend/rules/{objectID}".replace("{indexName}",encodeURIComponent(s)).replace("{model}",encodeURIComponent(n)).replace("{objectID}",encodeURIComponent(i)),queryParameters:{},headers:{}};return c.request(m,l)},getRecommendStatus({indexName:s,model:n,taskID:i},l){if(!s)throw new Error("Parameter `indexName` is required when calling `getRecommendStatus`.");if(!n)throw new Error("Parameter `model` is required when calling `getRecommendStatus`.");if(!i)throw new Error("Parameter `taskID` is required when calling `getRecommendStatus`.");let m={method:"GET",path:"/1/indexes/{indexName}/{model}/task/{taskID}".replace("{indexName}",encodeURIComponent(s)).replace("{model}",encodeURIComponent(n)).replace("{taskID}",encodeURIComponent(i)),queryParameters:{},headers:{}};return c.request(m,l)},getRecommendations(s,n){if(s&&Array.isArray(s)&&(s={requests:s}),!s)throw new Error("Parameter `getRecommendationsParams` is required when calling `getRecommendations`.");if(!s.requests)throw new Error("Parameter `getRecommendationsParams.requests` is required when calling `getRecommendations`.");let h={method:"POST",path:"/1/indexes/*/recommendations",queryParameters:{},headers:{},data:s,useReadTransporter:true,cacheable:true};return c.request(h,n)},searchRecommendRules({indexName:s,model:n,searchRecommendRulesParams:i},l){if(!s)throw new Error("Parameter `indexName` is required when calling `searchRecommendRules`.");if(!n)throw new Error("Parameter `model` is required when calling `searchRecommendRules`.");let m={method:"POST",path:"/1/indexes/{indexName}/{model}/recommend/rules/search".replace("{indexName}",encodeURIComponent(s)).replace("{model}",encodeURIComponent(n)),queryParameters:{},headers:{},data:i||{},useReadTransporter:true,cacheable:true};return c.request(m,l)}}}function Pt(r,e,o){if(!r||typeof r!="string")throw new Error("`appId` is missing.");if(!e||typeof e!="string")throw new Error("`apiKey` is missing.");return X({appId:r,apiKey:e,timeouts:{connect:1e3,read:2e3,write:3e4},logger:J(),requester:H(),algoliaAgents:[{segment:"Browser"}],authMode:"WithinQueryParameters",responsesCache:A(),requestsCache:A({serializable:false}),hostsCache:q({caches:[L({key:`${O}-${r}`}),A()]}),...o})}
|
|
7
|
+
function H(){function r(e){return new Promise(o=>{let t=new XMLHttpRequest;t.open(e.method,e.url,true),Object.keys(e.headers).forEach(s=>t.setRequestHeader(s,e.headers[s]));let a=(s,n)=>setTimeout(()=>{t.abort(),o({status:0,content:n,isTimedOut:true});},s),d=a(e.connectTimeout,"Connection timeout"),c;t.onreadystatechange=()=>{t.readyState>t.OPENED&&c===void 0&&(clearTimeout(d),c=a(e.responseTimeout,"Socket timeout"));},t.onerror=()=>{t.status===0&&(clearTimeout(d),clearTimeout(c),o({content:t.responseText||"Network request failed",status:t.status,isTimedOut:false}));},t.onload=()=>{clearTimeout(d),clearTimeout(c),o({content:t.responseText,status:t.status,isTimedOut:false});},t.send(e.data);})}return {send:r}}function L(r){let e,o=`algolia-client-js-${r.key}`;function t(){return e===void 0&&(e=r.localStorage||window.localStorage),e}function a(){return JSON.parse(t().getItem(o)||"{}")}function d(s){t().setItem(o,JSON.stringify(s));}function c(){let s=r.timeToLive?r.timeToLive*1e3:null,n=a(),i=Object.fromEntries(Object.entries(n).filter(([,p])=>p.timestamp!==void 0));if(d(i),!s)return;let l=Object.fromEntries(Object.entries(i).filter(([,p])=>{let h=new Date().getTime();return !(p.timestamp+s<h)}));d(l);}return {get(s,n,i={miss:()=>Promise.resolve()}){return Promise.resolve().then(()=>(c(),a()[JSON.stringify(s)])).then(l=>Promise.all([l?l.value:n(),l!==void 0])).then(([l,p])=>Promise.all([l,p||i.miss(l)])).then(([l])=>l)},set(s,n){return Promise.resolve().then(()=>{let i=a();return i[JSON.stringify(s)]={timestamp:new Date().getTime(),value:n},t().setItem(o,JSON.stringify(i)),n})},delete(s){return Promise.resolve().then(()=>{let n=a();delete n[JSON.stringify(s)],t().setItem(o,JSON.stringify(n));})},clear(){return Promise.resolve().then(()=>{t().removeItem(o);})}}}function V(){return {get(r,e,o={miss:()=>Promise.resolve()}){return e().then(a=>Promise.all([a,o.miss(a)])).then(([a])=>a)},set(r,e){return Promise.resolve(e)},delete(r){return Promise.resolve()},clear(){return Promise.resolve()}}}function q(r){let e=[...r.caches],o=e.shift();return o===void 0?V():{get(t,a,d={miss:()=>Promise.resolve()}){return o.get(t,a,d).catch(()=>q({caches:e}).get(t,a,d))},set(t,a){return o.set(t,a).catch(()=>q({caches:e}).set(t,a))},delete(t){return o.delete(t).catch(()=>q({caches:e}).delete(t))},clear(){return o.clear().catch(()=>q({caches:e}).clear())}}}function A(r={serializable:true}){let e={};return {get(o,t,a={miss:()=>Promise.resolve()}){let d=JSON.stringify(o);if(d in e)return Promise.resolve(r.serializable?JSON.parse(e[d]):e[d]);let c=t();return c.then(s=>a.miss(s)).then(()=>c)},set(o,t){return e[JSON.stringify(o)]=r.serializable?JSON.stringify(t):t,Promise.resolve(t)},delete(o){return delete e[JSON.stringify(o)],Promise.resolve()},clear(){return e={},Promise.resolve()}}}function Y(r){let e={value:`Algolia for JavaScript (${r})`,add(o){let t=`; ${o.segment}${o.version!==void 0?` (${o.version})`:""}`;return e.value.indexOf(t)===-1&&(e.value=`${e.value}${t}`),e}};return e}function j(r,e,o="WithinHeaders"){let t={"x-algolia-api-key":e,"x-algolia-application-id":r};return {headers(){return o==="WithinHeaders"?t:{}},queryParameters(){return o==="WithinQueryParameters"?t:{}}}}function W({algoliaAgents:r,client:e,version:o}){let t=Y(o).add({segment:e,version:o});return r.forEach(a=>t.add(a)),t}function J(){return {debug(r,e){return Promise.resolve()},info(r,e){return Promise.resolve()},error(r,e){return Promise.resolve()}}}var $=120*1e3;function G(r,e="up"){let o=Date.now();function t(){return e==="up"||Date.now()-o>$}function a(){return e==="timed out"&&Date.now()-o<=$}return {...r,status:e,lastUpdate:o,isUp:t,isTimedOut:a}}var Q=class extends Error{name="AlgoliaError";constructor(r,e){super(r),e&&(this.name=e);}};var z=class extends Q{stackTrace;constructor(r,e,o){super(r,o),this.stackTrace=e;}},Z=class extends z{constructor(r){super("Unreachable hosts - your application id may be incorrect. If the error persists, please visit our help center https://alg.li/support-unreachable-hosts or reach out to the Algolia Support team: https://alg.li/support",r,"RetryError");}},I=class extends z{status;constructor(r,e,o,t="ApiError"){super(r,o,t),this.status=e;}},ee=class extends Q{response;constructor(r,e){super(r,"DeserializationError"),this.response=e;}},re=class extends I{error;constructor(r,e,o,t){super(r,e,t,"DetailedApiError"),this.error=o;}};function M(r){let e=r;for(let o=r.length-1;o>0;o--){let t=Math.floor(Math.random()*(o+1)),a=r[o];e[o]=r[t],e[t]=a;}return e}function te(r,e,o){let t=oe(o),a=`${r.protocol}://${r.url}${r.port?`:${r.port}`:""}/${e.charAt(0)==="/"?e.substring(1):e}`;return t.length&&(a+=`?${t}`),a}function oe(r){return Object.keys(r).filter(e=>r[e]!==void 0).sort().map(e=>`${e}=${encodeURIComponent(Object.prototype.toString.call(r[e])==="[object Array]"?r[e].join(","):r[e]).replace(/\+/g,"%20")}`).join("&")}function se(r,e){if(r.method==="GET"||r.data===void 0&&e.data===void 0)return;let o=Array.isArray(r.data)?r.data:{...r.data,...e.data};return JSON.stringify(o)}function ne(r,e,o){let t={Accept:"application/json",...r,...e,...o},a={};return Object.keys(t).forEach(d=>{let c=t[d];a[d.toLowerCase()]=c;}),a}function ae(r){try{return JSON.parse(r.content)}catch(e){throw new ee(e.message,r)}}function ie({content:r,status:e},o){try{let t=JSON.parse(r);return "error"in t?new re(t.message,e,t.error,o):new I(t.message,e,o)}catch{}return new I(r,e,o)}function me({isTimedOut:r,status:e}){return !r&&~~e===0}function ce({isTimedOut:r,status:e}){return r||me({isTimedOut:r,status:e})||~~(e/100)!==2&&~~(e/100)!==4}function ue({status:r}){return ~~(r/100)===2}function le(r){return r.map(e=>F(e))}function F(r){let e=r.request.headers["x-algolia-api-key"]?{"x-algolia-api-key":"*****"}:{};return {...r,request:{...r.request,headers:{...r.request.headers,...e}}}}function B({hosts:r,hostsCache:e,baseHeaders:o,logger:t,baseQueryParameters:a,algoliaAgent:d,timeouts:c,requester:s,requestsCache:n,responsesCache:i}){async function l(u){let m=await Promise.all(u.map(f=>e.get(f,()=>Promise.resolve(G(f))))),w=m.filter(f=>f.isUp()),R=m.filter(f=>f.isTimedOut()),E=[...w,...R];return {hosts:E.length>0?E:u,getTimeout(f,g){return (R.length===0&&f===0?1:R.length+3+f)*g}}}async function p(u,m,w=true){let R=[],E=se(u,m),x=ne(o,u.headers,m.headers),f=u.method==="GET"?{...u.data,...m.data}:{},g={...a,...u.queryParameters,...f};if(d.value&&(g["x-algolia-agent"]=d.value),m&&m.queryParameters)for(let P of Object.keys(m.queryParameters))!m.queryParameters[P]||Object.prototype.toString.call(m.queryParameters[P])==="[object Object]"?g[P]=m.queryParameters[P]:g[P]=m.queryParameters[P].toString();let v=0,N=async(P,S)=>{let T=P.pop();if(T===void 0)throw new Z(le(R));let C={...c,...m.timeouts},U={data:E,headers:x,method:u.method,url:te(T,u.path,g),connectTimeout:S(v,C.connect),responseTimeout:S(v,w?C.read:C.write)},k=b=>{let _={request:U,response:b,host:T,triesLeft:P.length};return R.push(_),_},y=await s.send(U);if(ce(y)){let b=k(y);return y.isTimedOut&&v++,t.info("Retryable failure",F(b)),await e.set(T,G(T,y.isTimedOut?"timed out":"down")),N(P,S)}if(ue(y))return ae(y);throw k(y),ie(y,R)},K=r.filter(P=>P.accept==="readWrite"||(w?P.accept==="read":P.accept==="write")),D=await l(K);return N([...D.hosts].reverse(),D.getTimeout)}function h(u,m={}){let w=u.useReadTransporter||u.method==="GET";if(!w)return p(u,m,w);let R=()=>p(u,m);if((m.cacheable||u.cacheable)!==true)return R();let x={request:u,requestOptions:m,transporter:{queryParameters:a,headers:o}};return i.get(x,()=>n.get(x,()=>n.set(x,R()).then(f=>Promise.all([n.delete(x),f]),f=>Promise.all([n.delete(x),Promise.reject(f)])).then(([f,g])=>g)),{miss:f=>i.set(x,f)})}return {hostsCache:e,requester:s,timeouts:c,logger:t,algoliaAgent:d,baseHeaders:o,baseQueryParameters:a,hosts:r,request:h,requestsCache:n,responsesCache:i}}var O="5.42.0";function de(r){return [{url:`${r}-dsn.algolia.net`,accept:"read",protocol:"https"},{url:`${r}.algolia.net`,accept:"write",protocol:"https"}].concat(M([{url:`${r}-1.algolianet.com`,accept:"readWrite",protocol:"https"},{url:`${r}-2.algolianet.com`,accept:"readWrite",protocol:"https"},{url:`${r}-3.algolianet.com`,accept:"readWrite",protocol:"https"}]))}function X({appId:r,apiKey:e,authMode:o,algoliaAgents:t,...a}){let d=j(r,e,o),c=B({hosts:de(r),...a,algoliaAgent:W({algoliaAgents:t,client:"Recommend",version:O}),baseHeaders:{"content-type":"text/plain",...d.headers(),...a.baseHeaders},baseQueryParameters:{...d.queryParameters(),...a.baseQueryParameters}});return {transporter:c,appId:r,apiKey:e,clearCache(){return Promise.all([c.requestsCache.clear(),c.responsesCache.clear()]).then(()=>{})},get _ua(){return c.algoliaAgent.value},addAlgoliaAgent(s,n){c.algoliaAgent.add({segment:s,version:n});},setClientApiKey({apiKey:s}){!o||o==="WithinHeaders"?c.baseHeaders["x-algolia-api-key"]=s:c.baseQueryParameters["x-algolia-api-key"]=s;},batchRecommendRules({indexName:s,model:n,recommendRule:i},l){if(!s)throw new Error("Parameter `indexName` is required when calling `batchRecommendRules`.");if(!n)throw new Error("Parameter `model` is required when calling `batchRecommendRules`.");let m={method:"POST",path:"/1/indexes/{indexName}/{model}/recommend/rules/batch".replace("{indexName}",encodeURIComponent(s)).replace("{model}",encodeURIComponent(n)),queryParameters:{},headers:{},data:i||{}};return c.request(m,l)},customDelete({path:s,parameters:n},i){if(!s)throw new Error("Parameter `path` is required when calling `customDelete`.");let u={method:"DELETE",path:"/{path}".replace("{path}",s),queryParameters:n||{},headers:{}};return c.request(u,i)},customGet({path:s,parameters:n},i){if(!s)throw new Error("Parameter `path` is required when calling `customGet`.");let u={method:"GET",path:"/{path}".replace("{path}",s),queryParameters:n||{},headers:{}};return c.request(u,i)},customPost({path:s,parameters:n,body:i},l){if(!s)throw new Error("Parameter `path` is required when calling `customPost`.");let m={method:"POST",path:"/{path}".replace("{path}",s),queryParameters:n||{},headers:{},data:i||{}};return c.request(m,l)},customPut({path:s,parameters:n,body:i},l){if(!s)throw new Error("Parameter `path` is required when calling `customPut`.");let m={method:"PUT",path:"/{path}".replace("{path}",s),queryParameters:n||{},headers:{},data:i||{}};return c.request(m,l)},deleteRecommendRule({indexName:s,model:n,objectID:i},l){if(!s)throw new Error("Parameter `indexName` is required when calling `deleteRecommendRule`.");if(!n)throw new Error("Parameter `model` is required when calling `deleteRecommendRule`.");if(!i)throw new Error("Parameter `objectID` is required when calling `deleteRecommendRule`.");let m={method:"DELETE",path:"/1/indexes/{indexName}/{model}/recommend/rules/{objectID}".replace("{indexName}",encodeURIComponent(s)).replace("{model}",encodeURIComponent(n)).replace("{objectID}",encodeURIComponent(i)),queryParameters:{},headers:{}};return c.request(m,l)},getRecommendRule({indexName:s,model:n,objectID:i},l){if(!s)throw new Error("Parameter `indexName` is required when calling `getRecommendRule`.");if(!n)throw new Error("Parameter `model` is required when calling `getRecommendRule`.");if(!i)throw new Error("Parameter `objectID` is required when calling `getRecommendRule`.");let m={method:"GET",path:"/1/indexes/{indexName}/{model}/recommend/rules/{objectID}".replace("{indexName}",encodeURIComponent(s)).replace("{model}",encodeURIComponent(n)).replace("{objectID}",encodeURIComponent(i)),queryParameters:{},headers:{}};return c.request(m,l)},getRecommendStatus({indexName:s,model:n,taskID:i},l){if(!s)throw new Error("Parameter `indexName` is required when calling `getRecommendStatus`.");if(!n)throw new Error("Parameter `model` is required when calling `getRecommendStatus`.");if(!i)throw new Error("Parameter `taskID` is required when calling `getRecommendStatus`.");let m={method:"GET",path:"/1/indexes/{indexName}/{model}/task/{taskID}".replace("{indexName}",encodeURIComponent(s)).replace("{model}",encodeURIComponent(n)).replace("{taskID}",encodeURIComponent(i)),queryParameters:{},headers:{}};return c.request(m,l)},getRecommendations(s,n){if(s&&Array.isArray(s)&&(s={requests:s}),!s)throw new Error("Parameter `getRecommendationsParams` is required when calling `getRecommendations`.");if(!s.requests)throw new Error("Parameter `getRecommendationsParams.requests` is required when calling `getRecommendations`.");let h={method:"POST",path:"/1/indexes/*/recommendations",queryParameters:{},headers:{},data:s,useReadTransporter:true,cacheable:true};return c.request(h,n)},searchRecommendRules({indexName:s,model:n,searchRecommendRulesParams:i},l){if(!s)throw new Error("Parameter `indexName` is required when calling `searchRecommendRules`.");if(!n)throw new Error("Parameter `model` is required when calling `searchRecommendRules`.");let m={method:"POST",path:"/1/indexes/{indexName}/{model}/recommend/rules/search".replace("{indexName}",encodeURIComponent(s)).replace("{model}",encodeURIComponent(n)),queryParameters:{},headers:{},data:i||{},useReadTransporter:true,cacheable:true};return c.request(m,l)}}}function Pt(r,e,o){if(!r||typeof r!="string")throw new Error("`appId` is missing.");if(!e||typeof e!="string")throw new Error("`apiKey` is missing.");return X({appId:r,apiKey:e,timeouts:{connect:1e3,read:2e3,write:3e4},logger:J(),requester:H(),algoliaAgents:[{segment:"Browser"}],authMode:"WithinQueryParameters",responsesCache:A(),requestsCache:A({serializable:false}),hostsCache:q({caches:[L({key:`${O}-${r}`}),A()]}),...o})}
|
|
8
8
|
|
|
9
9
|
exports.apiClientVersion = O;
|
|
10
10
|
exports.recommendClient = Pt;
|
package/dist/builds/fetch.js
CHANGED
|
@@ -4,7 +4,7 @@ import { createFetchRequester } from "@algolia/requester-fetch";
|
|
|
4
4
|
|
|
5
5
|
// src/recommendClient.ts
|
|
6
6
|
import { createAuth, createTransporter, getAlgoliaAgent, shuffle } from "@algolia/client-common";
|
|
7
|
-
var apiClientVersion = "5.
|
|
7
|
+
var apiClientVersion = "5.42.0";
|
|
8
8
|
function getDefaultHosts(appId) {
|
|
9
9
|
return [
|
|
10
10
|
{
|