@algolia/client-common 4.14.2 → 5.0.0-alpha.11

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.
Files changed (89) hide show
  1. package/dist/client-common.cjs.js +804 -92
  2. package/dist/client-common.esm.node.js +776 -0
  3. package/dist/index.d.ts +10 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/src/cache/createBrowserLocalStorageCache.d.ts +3 -0
  6. package/dist/src/cache/createBrowserLocalStorageCache.d.ts.map +1 -0
  7. package/dist/src/cache/createFallbackableCache.d.ts +3 -0
  8. package/dist/src/cache/createFallbackableCache.d.ts.map +1 -0
  9. package/dist/src/cache/createMemoryCache.d.ts +3 -0
  10. package/dist/src/cache/createMemoryCache.d.ts.map +1 -0
  11. package/dist/src/cache/createNullCache.d.ts +3 -0
  12. package/dist/src/cache/createNullCache.d.ts.map +1 -0
  13. package/dist/src/cache/index.d.ts +5 -0
  14. package/dist/src/cache/index.d.ts.map +1 -0
  15. package/dist/src/constants.d.ts +7 -0
  16. package/dist/src/constants.d.ts.map +1 -0
  17. package/dist/src/createAlgoliaAgent.d.ts +3 -0
  18. package/dist/src/createAlgoliaAgent.d.ts.map +1 -0
  19. package/dist/src/createAuth.d.ts +6 -0
  20. package/dist/src/createAuth.d.ts.map +1 -0
  21. package/dist/src/createEchoRequester.d.ts +7 -0
  22. package/dist/src/createEchoRequester.d.ts.map +1 -0
  23. package/dist/src/createIterablePromise.d.ts +13 -0
  24. package/dist/src/createIterablePromise.d.ts.map +1 -0
  25. package/dist/src/getAlgoliaAgent.d.ts +8 -0
  26. package/dist/src/getAlgoliaAgent.d.ts.map +1 -0
  27. package/dist/src/transporter/createStatefulHost.d.ts +3 -0
  28. package/dist/src/transporter/createStatefulHost.d.ts.map +1 -0
  29. package/dist/src/transporter/createTransporter.d.ts +3 -0
  30. package/dist/src/transporter/createTransporter.d.ts.map +1 -0
  31. package/dist/src/transporter/errors.d.ts +21 -0
  32. package/dist/src/transporter/errors.d.ts.map +1 -0
  33. package/dist/src/transporter/helpers.d.ts +9 -0
  34. package/dist/src/transporter/helpers.d.ts.map +1 -0
  35. package/dist/src/transporter/index.d.ts +7 -0
  36. package/dist/src/transporter/index.d.ts.map +1 -0
  37. package/dist/src/transporter/responses.d.ts +5 -0
  38. package/dist/src/transporter/responses.d.ts.map +1 -0
  39. package/dist/src/transporter/stackTrace.d.ts +4 -0
  40. package/dist/src/transporter/stackTrace.d.ts.map +1 -0
  41. package/dist/src/types/cache.d.ts +47 -0
  42. package/dist/src/types/cache.d.ts.map +1 -0
  43. package/dist/src/types/createClient.d.ts +12 -0
  44. package/dist/src/types/createClient.d.ts.map +1 -0
  45. package/dist/src/types/createIterablePromise.d.ts +36 -0
  46. package/dist/src/types/createIterablePromise.d.ts.map +1 -0
  47. package/dist/src/types/host.d.ts +33 -0
  48. package/dist/src/types/host.d.ts.map +1 -0
  49. package/dist/src/types/index.d.ts +7 -0
  50. package/dist/src/types/index.d.ts.map +1 -0
  51. package/dist/src/types/requester.d.ts +66 -0
  52. package/dist/src/types/requester.d.ts.map +1 -0
  53. package/dist/src/types/transporter.d.ts +128 -0
  54. package/dist/src/types/transporter.d.ts.map +1 -0
  55. package/index.ts +9 -0
  56. package/package.json +25 -15
  57. package/src/__tests__/cache/browser-local-storage-cache.test.ts +134 -0
  58. package/src/__tests__/cache/fallbackable-cache.test.ts +126 -0
  59. package/src/__tests__/cache/memory-cache.test.ts +90 -0
  60. package/src/__tests__/cache/null-cache.test.ts +49 -0
  61. package/src/__tests__/create-iterable-promise.test.ts +238 -0
  62. package/src/cache/createBrowserLocalStorageCache.ts +74 -0
  63. package/src/cache/createFallbackableCache.ts +53 -0
  64. package/src/cache/createMemoryCache.ts +56 -0
  65. package/src/cache/createNullCache.ts +34 -0
  66. package/src/cache/index.ts +4 -0
  67. package/src/constants.ts +7 -0
  68. package/src/createAlgoliaAgent.ts +20 -0
  69. package/src/createAuth.ts +25 -0
  70. package/src/createEchoRequester.ts +59 -0
  71. package/src/createIterablePromise.ts +47 -0
  72. package/src/getAlgoliaAgent.ts +25 -0
  73. package/src/transporter/createStatefulHost.ts +24 -0
  74. package/src/transporter/createTransporter.ts +350 -0
  75. package/src/transporter/errors.ts +51 -0
  76. package/src/transporter/helpers.ts +119 -0
  77. package/src/transporter/index.ts +6 -0
  78. package/src/transporter/responses.ts +23 -0
  79. package/src/transporter/stackTrace.ts +30 -0
  80. package/src/types/cache.ts +61 -0
  81. package/src/types/createClient.ts +23 -0
  82. package/src/types/createIterablePromise.ts +40 -0
  83. package/src/types/host.ts +38 -0
  84. package/src/types/index.ts +6 -0
  85. package/src/types/requester.ts +72 -0
  86. package/src/types/transporter.ts +153 -0
  87. package/dist/client-common.d.ts +0 -102
  88. package/dist/client-common.esm.js +0 -89
  89. package/index.js +0 -2
@@ -0,0 +1,350 @@
1
+ import type {
2
+ EndRequest,
3
+ Host,
4
+ Request,
5
+ RequestOptions,
6
+ Response,
7
+ StackFrame,
8
+ TransporterOptions,
9
+ Transporter,
10
+ QueryParameters,
11
+ } from '../types';
12
+
13
+ import { createStatefulHost } from './createStatefulHost';
14
+ import { RetryError } from './errors';
15
+ import {
16
+ deserializeFailure,
17
+ deserializeSuccess,
18
+ serializeData,
19
+ serializeHeaders,
20
+ serializeUrl,
21
+ } from './helpers';
22
+ import { isRetryable, isSuccess } from './responses';
23
+ import {
24
+ stackTraceWithoutCredentials,
25
+ stackFrameWithoutCredentials,
26
+ } from './stackTrace';
27
+
28
+ type RetryableOptions = {
29
+ hosts: Host[];
30
+ getTimeout: (retryCount: number, timeout: number) => number;
31
+ };
32
+
33
+ export function createTransporter({
34
+ hosts,
35
+ hostsCache,
36
+ baseHeaders,
37
+ baseQueryParameters,
38
+ algoliaAgent,
39
+ timeouts,
40
+ requester,
41
+ requestsCache,
42
+ responsesCache,
43
+ }: TransporterOptions): Transporter {
44
+ async function createRetryableOptions(
45
+ compatibleHosts: Host[]
46
+ ): Promise<RetryableOptions> {
47
+ const statefulHosts = await Promise.all(
48
+ compatibleHosts.map((compatibleHost) => {
49
+ return hostsCache.get(compatibleHost, () => {
50
+ return Promise.resolve(createStatefulHost(compatibleHost));
51
+ });
52
+ })
53
+ );
54
+ const hostsUp = statefulHosts.filter((host) => host.isUp());
55
+ const hostsTimedOut = statefulHosts.filter((host) => host.isTimedOut());
56
+
57
+ // Note, we put the hosts that previously timed out on the end of the list.
58
+ const hostsAvailable = [...hostsUp, ...hostsTimedOut];
59
+ const compatibleHostsAvailable =
60
+ hostsAvailable.length > 0 ? hostsAvailable : compatibleHosts;
61
+
62
+ return {
63
+ hosts: compatibleHostsAvailable,
64
+ getTimeout(timeoutsCount: number, baseTimeout: number): number {
65
+ /**
66
+ * Imagine that you have 4 hosts, if timeouts will increase
67
+ * on the following way: 1 (timed out) > 4 (timed out) > 5 (200).
68
+ *
69
+ * Note that, the very next request, we start from the previous timeout.
70
+ *
71
+ * 5 (timed out) > 6 (timed out) > 7 ...
72
+ *
73
+ * This strategy may need to be reviewed, but is the strategy on the our
74
+ * current v3 version.
75
+ */
76
+ const timeoutMultiplier =
77
+ hostsTimedOut.length === 0 && timeoutsCount === 0
78
+ ? 1
79
+ : hostsTimedOut.length + 3 + timeoutsCount;
80
+
81
+ return timeoutMultiplier * baseTimeout;
82
+ },
83
+ };
84
+ }
85
+
86
+ async function retryableRequest<TResponse>(
87
+ request: Request,
88
+ requestOptions: RequestOptions,
89
+ isRead = true
90
+ ): Promise<TResponse> {
91
+ const stackTrace: StackFrame[] = [];
92
+
93
+ /**
94
+ * First we prepare the payload that do not depend from hosts.
95
+ */
96
+ const data = serializeData(request, requestOptions);
97
+ const headers = serializeHeaders(
98
+ baseHeaders,
99
+ request.headers,
100
+ requestOptions.headers
101
+ );
102
+
103
+ // On `GET`, the data is proxied to query parameters.
104
+ const dataQueryParameters: QueryParameters =
105
+ request.method === 'GET'
106
+ ? {
107
+ ...request.data,
108
+ ...requestOptions.data,
109
+ }
110
+ : {};
111
+
112
+ const queryParameters: QueryParameters = {
113
+ ...baseQueryParameters,
114
+ ...request.queryParameters,
115
+ ...dataQueryParameters,
116
+ };
117
+
118
+ if (algoliaAgent.value) {
119
+ queryParameters['x-algolia-agent'] = algoliaAgent.value;
120
+ }
121
+
122
+ if (requestOptions && requestOptions.queryParameters) {
123
+ for (const key of Object.keys(requestOptions.queryParameters)) {
124
+ // We want to keep `undefined` and `null` values,
125
+ // but also avoid stringifying `object`s, as they are
126
+ // handled in the `serializeUrl` step right after.
127
+ if (
128
+ !requestOptions.queryParameters[key] ||
129
+ Object.prototype.toString.call(
130
+ requestOptions.queryParameters[key]
131
+ ) === '[object Object]'
132
+ ) {
133
+ queryParameters[key] = requestOptions.queryParameters[key];
134
+ } else {
135
+ queryParameters[key] = requestOptions.queryParameters[key].toString();
136
+ }
137
+ }
138
+ }
139
+
140
+ let timeoutsCount = 0;
141
+
142
+ const retry = async (
143
+ retryableHosts: Host[],
144
+ getTimeout: (timeoutsCount: number, timeout: number) => number
145
+ ): Promise<TResponse> => {
146
+ /**
147
+ * We iterate on each host, until there is no host left.
148
+ */
149
+ const host = retryableHosts.pop();
150
+ if (host === undefined) {
151
+ throw new RetryError(stackTraceWithoutCredentials(stackTrace));
152
+ }
153
+
154
+ let responseTimeout = requestOptions.timeout;
155
+ if (responseTimeout === undefined) {
156
+ responseTimeout = isRead ? timeouts.read : timeouts.write;
157
+ }
158
+
159
+ const payload: EndRequest = {
160
+ data,
161
+ headers,
162
+ method: request.method,
163
+ url: serializeUrl(host, request.path, queryParameters),
164
+ connectTimeout: getTimeout(timeoutsCount, timeouts.connect),
165
+ responseTimeout: getTimeout(timeoutsCount, responseTimeout),
166
+ };
167
+
168
+ /**
169
+ * The stackFrame is pushed to the stackTrace so we
170
+ * can have information about onRetry and onFailure
171
+ * decisions.
172
+ */
173
+ const pushToStackTrace = (response: Response): StackFrame => {
174
+ const stackFrame: StackFrame = {
175
+ request: payload,
176
+ response,
177
+ host,
178
+ triesLeft: retryableHosts.length,
179
+ };
180
+
181
+ stackTrace.push(stackFrame);
182
+
183
+ return stackFrame;
184
+ };
185
+
186
+ const response = await requester.send(payload);
187
+
188
+ if (isRetryable(response)) {
189
+ const stackFrame = pushToStackTrace(response);
190
+
191
+ // If response is a timeout, we increase the number of timeouts so we can increase the timeout later.
192
+ if (response.isTimedOut) {
193
+ timeoutsCount++;
194
+ }
195
+ /**
196
+ * Failures are individually sent to the logger, allowing
197
+ * the end user to debug / store stack frames even
198
+ * when a retry error does not happen.
199
+ */
200
+ // eslint-disable-next-line no-console -- this will be fixed by exposing a `logger` to the transporter
201
+ console.log(
202
+ 'Retryable failure',
203
+ stackFrameWithoutCredentials(stackFrame)
204
+ );
205
+
206
+ /**
207
+ * We also store the state of the host in failure cases. If the host, is
208
+ * down it will remain down for the next 2 minutes. In a timeout situation,
209
+ * this host will be added end of the list of hosts on the next request.
210
+ */
211
+ await hostsCache.set(
212
+ host,
213
+ createStatefulHost(host, response.isTimedOut ? 'timed out' : 'down')
214
+ );
215
+
216
+ return retry(retryableHosts, getTimeout);
217
+ }
218
+
219
+ if (isSuccess(response)) {
220
+ return deserializeSuccess(response);
221
+ }
222
+
223
+ pushToStackTrace(response);
224
+ throw deserializeFailure(response, stackTrace);
225
+ };
226
+
227
+ /**
228
+ * Finally, for each retryable host perform request until we got a non
229
+ * retryable response. Some notes here:
230
+ *
231
+ * 1. The reverse here is applied so we can apply a `pop` later on => more performant.
232
+ * 2. We also get from the retryable options a timeout multiplier that is tailored
233
+ * for the current context.
234
+ */
235
+ const compatibleHosts = hosts.filter(
236
+ (host) =>
237
+ host.accept === 'readWrite' ||
238
+ (isRead ? host.accept === 'read' : host.accept === 'write')
239
+ );
240
+ const options = await createRetryableOptions(compatibleHosts);
241
+
242
+ return retry([...options.hosts].reverse(), options.getTimeout);
243
+ }
244
+
245
+ function createRequest<TResponse>(
246
+ request: Request,
247
+ requestOptions: RequestOptions = {}
248
+ ): Promise<TResponse> {
249
+ /**
250
+ * A read request is either a `GET` request, or a request that we make
251
+ * via the `read` transporter (e.g. `search`).
252
+ */
253
+ const isRead = request.useReadTransporter || request.method === 'GET';
254
+ if (!isRead) {
255
+ /**
256
+ * On write requests, no cache mechanisms are applied, and we
257
+ * proxy the request immediately to the requester.
258
+ */
259
+ return retryableRequest<TResponse>(request, requestOptions, isRead);
260
+ }
261
+
262
+ const createRetryableRequest = (): Promise<TResponse> => {
263
+ /**
264
+ * Then, we prepare a function factory that contains the construction of
265
+ * the retryable request. At this point, we may *not* perform the actual
266
+ * request. But we want to have the function factory ready.
267
+ */
268
+ return retryableRequest<TResponse>(request, requestOptions);
269
+ };
270
+
271
+ /**
272
+ * Once we have the function factory ready, we need to determine of the
273
+ * request is "cacheable" - should be cached. Note that, once again,
274
+ * the user can force this option.
275
+ */
276
+ const cacheable = requestOptions.cacheable || request.cacheable;
277
+
278
+ /**
279
+ * If is not "cacheable", we immediately trigger the retryable request, no
280
+ * need to check cache implementations.
281
+ */
282
+ if (cacheable !== true) {
283
+ return createRetryableRequest();
284
+ }
285
+
286
+ /**
287
+ * If the request is "cacheable", we need to first compute the key to ask
288
+ * the cache implementations if this request is on progress or if the
289
+ * response already exists on the cache.
290
+ */
291
+ const key = {
292
+ request,
293
+ requestOptions,
294
+ transporter: {
295
+ queryParameters: baseQueryParameters,
296
+ headers: baseHeaders,
297
+ },
298
+ };
299
+
300
+ /**
301
+ * With the computed key, we first ask the responses cache
302
+ * implementation if this request was been resolved before.
303
+ */
304
+ return responsesCache.get(
305
+ key,
306
+ () => {
307
+ /**
308
+ * If the request has never resolved before, we actually ask if there
309
+ * is a current request with the same key on progress.
310
+ */
311
+ return requestsCache.get(key, () =>
312
+ /**
313
+ * Finally, if there is no request in progress with the same key,
314
+ * this `createRetryableRequest()` will actually trigger the
315
+ * retryable request.
316
+ */
317
+ requestsCache
318
+ .set(key, createRetryableRequest())
319
+ .then(
320
+ (response) => Promise.all([requestsCache.delete(key), response]),
321
+ (err) =>
322
+ Promise.all([requestsCache.delete(key), Promise.reject(err)])
323
+ )
324
+ .then(([_, response]) => response)
325
+ );
326
+ },
327
+ {
328
+ /**
329
+ * Of course, once we get this response back from the server, we
330
+ * tell response cache to actually store the received response
331
+ * to be used later.
332
+ */
333
+ miss: (response) => responsesCache.set(key, response),
334
+ }
335
+ );
336
+ }
337
+
338
+ return {
339
+ hostsCache,
340
+ requester,
341
+ timeouts,
342
+ algoliaAgent,
343
+ baseHeaders,
344
+ baseQueryParameters,
345
+ hosts,
346
+ request: createRequest,
347
+ requestsCache,
348
+ responsesCache,
349
+ };
350
+ }
@@ -0,0 +1,51 @@
1
+ import type { Response, StackFrame } from '../types';
2
+
3
+ export class AlgoliaError extends Error {
4
+ name: string = 'AlgoliaError';
5
+
6
+ constructor(message: string, name: string) {
7
+ super(message);
8
+
9
+ if (name) {
10
+ this.name = name;
11
+ }
12
+ }
13
+ }
14
+
15
+ export class ErrorWithStackTrace extends AlgoliaError {
16
+ stackTrace: StackFrame[];
17
+
18
+ constructor(message: string, stackTrace: StackFrame[], name: string) {
19
+ super(message, name);
20
+ // the array and object should be frozen to reflect the stackTrace at the time of the error
21
+ this.stackTrace = stackTrace;
22
+ }
23
+ }
24
+
25
+ export class RetryError extends ErrorWithStackTrace {
26
+ constructor(stackTrace: StackFrame[]) {
27
+ super(
28
+ 'Unreachable hosts - your application id may be incorrect. If the error persists, contact support@algolia.com.',
29
+ stackTrace,
30
+ 'RetryError'
31
+ );
32
+ }
33
+ }
34
+
35
+ export class ApiError extends ErrorWithStackTrace {
36
+ status: number;
37
+
38
+ constructor(message: string, status: number, stackTrace: StackFrame[]) {
39
+ super(message, stackTrace, 'ApiError');
40
+ this.status = status;
41
+ }
42
+ }
43
+
44
+ export class DeserializationError extends AlgoliaError {
45
+ response: Response;
46
+
47
+ constructor(message: string, response: Response) {
48
+ super(message, 'DeserializationError');
49
+ this.response = response;
50
+ }
51
+ }
@@ -0,0 +1,119 @@
1
+ import type {
2
+ Headers,
3
+ Host,
4
+ QueryParameters,
5
+ Request,
6
+ RequestOptions,
7
+ Response,
8
+ StackFrame,
9
+ } from '../types';
10
+
11
+ import { ApiError, DeserializationError } from './errors';
12
+
13
+ export function shuffle<TData>(array: TData[]): TData[] {
14
+ const shuffledArray = array;
15
+
16
+ for (let c = array.length - 1; c > 0; c--) {
17
+ const b = Math.floor(Math.random() * (c + 1));
18
+ const a = array[c];
19
+
20
+ shuffledArray[c] = array[b];
21
+ shuffledArray[b] = a;
22
+ }
23
+
24
+ return shuffledArray;
25
+ }
26
+
27
+ export function serializeUrl(
28
+ host: Host,
29
+ path: string,
30
+ queryParameters: QueryParameters
31
+ ): string {
32
+ const queryParametersAsString = serializeQueryParameters(queryParameters);
33
+ let url = `${host.protocol}://${host.url}/${
34
+ path.charAt(0) === '/' ? path.substr(1) : path
35
+ }`;
36
+
37
+ if (queryParametersAsString.length) {
38
+ url += `?${queryParametersAsString}`;
39
+ }
40
+
41
+ return url;
42
+ }
43
+
44
+ export function serializeQueryParameters(parameters: QueryParameters): string {
45
+ const isObjectOrArray = (value: any): boolean =>
46
+ Object.prototype.toString.call(value) === '[object Object]' ||
47
+ Object.prototype.toString.call(value) === '[object Array]';
48
+
49
+ return Object.keys(parameters)
50
+ .map(
51
+ (key) =>
52
+ `${key}=${
53
+ isObjectOrArray(parameters[key])
54
+ ? JSON.stringify(parameters[key])
55
+ : parameters[key]
56
+ }`
57
+ )
58
+ .join('&');
59
+ }
60
+
61
+ export function serializeData(
62
+ request: Request,
63
+ requestOptions: RequestOptions
64
+ ): string | undefined {
65
+ if (
66
+ request.method === 'GET' ||
67
+ (request.data === undefined && requestOptions.data === undefined)
68
+ ) {
69
+ return undefined;
70
+ }
71
+
72
+ const data = Array.isArray(request.data)
73
+ ? request.data
74
+ : { ...request.data, ...requestOptions.data };
75
+
76
+ return JSON.stringify(data);
77
+ }
78
+
79
+ export function serializeHeaders(
80
+ baseHeaders: Headers,
81
+ requestHeaders: Headers,
82
+ requestOptionsHeaders?: Headers
83
+ ): Headers {
84
+ const headers: Headers = {
85
+ Accept: 'application/json',
86
+ ...baseHeaders,
87
+ ...requestHeaders,
88
+ ...requestOptionsHeaders,
89
+ };
90
+ const serializedHeaders: Headers = {};
91
+
92
+ Object.keys(headers).forEach((header) => {
93
+ const value = headers[header];
94
+ serializedHeaders[header.toLowerCase()] = value;
95
+ });
96
+
97
+ return serializedHeaders;
98
+ }
99
+
100
+ export function deserializeSuccess<TObject>(response: Response): TObject {
101
+ try {
102
+ return JSON.parse(response.content);
103
+ } catch (e) {
104
+ throw new DeserializationError((e as Error).message, response);
105
+ }
106
+ }
107
+
108
+ export function deserializeFailure(
109
+ { content, status }: Response,
110
+ stackFrame: StackFrame[]
111
+ ): Error {
112
+ let message = content;
113
+ try {
114
+ message = JSON.parse(content).message;
115
+ } catch (e) {
116
+ // ..
117
+ }
118
+ return new ApiError(message, status, stackFrame);
119
+ }
@@ -0,0 +1,6 @@
1
+ export * from './createTransporter';
2
+ export * from './createStatefulHost';
3
+ export * from './errors';
4
+ export * from './helpers';
5
+ export * from './responses';
6
+ export * from './stackTrace';
@@ -0,0 +1,23 @@
1
+ import type { Response } from '../types';
2
+
3
+ export function isNetworkError({
4
+ isTimedOut,
5
+ status,
6
+ }: Omit<Response, 'content'>): boolean {
7
+ return !isTimedOut && ~~status === 0;
8
+ }
9
+
10
+ export function isRetryable({
11
+ isTimedOut,
12
+ status,
13
+ }: Omit<Response, 'content'>): boolean {
14
+ return (
15
+ isTimedOut ||
16
+ isNetworkError({ isTimedOut, status }) ||
17
+ (~~(status / 100) !== 2 && ~~(status / 100) !== 4)
18
+ );
19
+ }
20
+
21
+ export function isSuccess({ status }: Pick<Response, 'status'>): boolean {
22
+ return ~~(status / 100) === 2;
23
+ }
@@ -0,0 +1,30 @@
1
+ import type { Headers, StackFrame } from '../types';
2
+
3
+ export function stackTraceWithoutCredentials(
4
+ stackTrace: StackFrame[]
5
+ ): StackFrame[] {
6
+ return stackTrace.map((stackFrame) =>
7
+ stackFrameWithoutCredentials(stackFrame)
8
+ );
9
+ }
10
+
11
+ export function stackFrameWithoutCredentials(
12
+ stackFrame: StackFrame
13
+ ): StackFrame {
14
+ const modifiedHeaders: Headers = stackFrame.request.headers[
15
+ 'x-algolia-api-key'
16
+ ]
17
+ ? { 'x-algolia-api-key': '*****' }
18
+ : {};
19
+
20
+ return {
21
+ ...stackFrame,
22
+ request: {
23
+ ...stackFrame.request,
24
+ headers: {
25
+ ...stackFrame.request.headers,
26
+ ...modifiedHeaders,
27
+ },
28
+ },
29
+ };
30
+ }
@@ -0,0 +1,61 @@
1
+ export type Cache = {
2
+ /**
3
+ * Gets the value of the given `key`.
4
+ */
5
+ get: <TValue>(
6
+ key: Record<string, any> | string,
7
+ defaultValue: () => Promise<TValue>,
8
+ events?: CacheEvents<TValue>
9
+ ) => Promise<TValue>;
10
+
11
+ /**
12
+ * Sets the given value with the given `key`.
13
+ */
14
+ set: <TValue>(
15
+ key: Record<string, any> | string,
16
+ value: TValue
17
+ ) => Promise<TValue>;
18
+
19
+ /**
20
+ * Deletes the given `key`.
21
+ */
22
+ delete: (key: Record<string, any> | string) => Promise<void>;
23
+
24
+ /**
25
+ * Clears the cache.
26
+ */
27
+ clear: () => Promise<void>;
28
+ };
29
+
30
+ export type CacheEvents<TValue> = {
31
+ /**
32
+ * The callback when the given `key` is missing from the cache.
33
+ */
34
+ miss: (value: TValue) => Promise<any>;
35
+ };
36
+
37
+ export type MemoryCacheOptions = {
38
+ /**
39
+ * If keys and values should be serialized using `JSON.stringify`.
40
+ */
41
+ serializable?: boolean;
42
+ };
43
+
44
+ export type BrowserLocalStorageOptions = {
45
+ /**
46
+ * The cache key.
47
+ */
48
+ key: string;
49
+
50
+ /**
51
+ * The native local storage implementation.
52
+ */
53
+ localStorage?: Storage;
54
+ };
55
+
56
+ export type FallbackableCacheOptions = {
57
+ /**
58
+ * List of caches order by priority.
59
+ */
60
+ caches: Cache[];
61
+ };
@@ -0,0 +1,23 @@
1
+ import type { AlgoliaAgentOptions, TransporterOptions } from './transporter';
2
+
3
+ export type AuthMode = 'WithinHeaders' | 'WithinQueryParameters';
4
+
5
+ type OverriddenTransporterOptions =
6
+ | 'baseHeaders'
7
+ | 'baseQueryParameters'
8
+ | 'hosts';
9
+
10
+ export type CreateClientOptions = Omit<
11
+ TransporterOptions,
12
+ OverriddenTransporterOptions | 'algoliaAgent'
13
+ > &
14
+ Partial<Pick<TransporterOptions, OverriddenTransporterOptions>> & {
15
+ appId: string;
16
+ apiKey: string;
17
+ authMode?: AuthMode;
18
+ algoliaAgents: AlgoliaAgentOptions[];
19
+ };
20
+
21
+ export type ClientOptions = Partial<
22
+ Omit<CreateClientOptions, 'apiKey' | 'appId'>
23
+ >;
@@ -0,0 +1,40 @@
1
+ export type IterableOptions<TResponse> = Partial<{
2
+ /**
3
+ * The function that runs right after the API call has been resolved, allows you to do anything with the response before `validate`.
4
+ */
5
+ aggregator: (response: TResponse) => void;
6
+
7
+ /**
8
+ * The `validate` condition to throw an error and its message.
9
+ */
10
+ error: {
11
+ /**
12
+ * The function to validate the error condition.
13
+ */
14
+ validate: (response: TResponse) => boolean;
15
+
16
+ /**
17
+ * The error message to throw.
18
+ */
19
+ message: (response: TResponse) => string;
20
+ };
21
+
22
+ /**
23
+ * The function to decide how long to wait between iterations.
24
+ */
25
+ timeout: () => number;
26
+ }>;
27
+
28
+ export type CreateIterablePromise<TResponse> = IterableOptions<TResponse> & {
29
+ /**
30
+ * The function to run, which returns a promise.
31
+ *
32
+ * The `previousResponse` parameter (`undefined` on the first call) allows you to build your request with incremental logic, to iterate on `page` or `cursor` for example.
33
+ */
34
+ func: (previousResponse?: TResponse) => Promise<TResponse>;
35
+
36
+ /**
37
+ * The validator function. It receive the resolved return of the API call.
38
+ */
39
+ validate: (response: TResponse) => boolean;
40
+ };