@algolia/client-common 5.2.3 → 5.2.4-beta.2

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 (61) hide show
  1. package/dist/common.cjs +714 -0
  2. package/dist/common.cjs.map +1 -0
  3. package/dist/common.d.cts +438 -0
  4. package/dist/common.d.ts +438 -0
  5. package/dist/common.esm.js +653 -0
  6. package/dist/common.esm.js.map +1 -0
  7. package/package.json +17 -6
  8. package/dist/client-common.cjs +0 -783
  9. package/dist/client-common.esm.node.js +0 -747
  10. package/dist/index.d.ts +0 -10
  11. package/dist/index.d.ts.map +0 -1
  12. package/dist/src/cache/createBrowserLocalStorageCache.d.ts +0 -3
  13. package/dist/src/cache/createBrowserLocalStorageCache.d.ts.map +0 -1
  14. package/dist/src/cache/createFallbackableCache.d.ts +0 -3
  15. package/dist/src/cache/createFallbackableCache.d.ts.map +0 -1
  16. package/dist/src/cache/createMemoryCache.d.ts +0 -3
  17. package/dist/src/cache/createMemoryCache.d.ts.map +0 -1
  18. package/dist/src/cache/createNullCache.d.ts +0 -3
  19. package/dist/src/cache/createNullCache.d.ts.map +0 -1
  20. package/dist/src/cache/index.d.ts +0 -5
  21. package/dist/src/cache/index.d.ts.map +0 -1
  22. package/dist/src/constants.d.ts +0 -7
  23. package/dist/src/constants.d.ts.map +0 -1
  24. package/dist/src/createAlgoliaAgent.d.ts +0 -3
  25. package/dist/src/createAlgoliaAgent.d.ts.map +0 -1
  26. package/dist/src/createAuth.d.ts +0 -6
  27. package/dist/src/createAuth.d.ts.map +0 -1
  28. package/dist/src/createEchoRequester.d.ts +0 -7
  29. package/dist/src/createEchoRequester.d.ts.map +0 -1
  30. package/dist/src/createIterablePromise.d.ts +0 -13
  31. package/dist/src/createIterablePromise.d.ts.map +0 -1
  32. package/dist/src/getAlgoliaAgent.d.ts +0 -8
  33. package/dist/src/getAlgoliaAgent.d.ts.map +0 -1
  34. package/dist/src/transporter/createStatefulHost.d.ts +0 -3
  35. package/dist/src/transporter/createStatefulHost.d.ts.map +0 -1
  36. package/dist/src/transporter/createTransporter.d.ts +0 -3
  37. package/dist/src/transporter/createTransporter.d.ts.map +0 -1
  38. package/dist/src/transporter/errors.d.ts +0 -38
  39. package/dist/src/transporter/errors.d.ts.map +0 -1
  40. package/dist/src/transporter/helpers.d.ts +0 -9
  41. package/dist/src/transporter/helpers.d.ts.map +0 -1
  42. package/dist/src/transporter/index.d.ts +0 -7
  43. package/dist/src/transporter/index.d.ts.map +0 -1
  44. package/dist/src/transporter/responses.d.ts +0 -5
  45. package/dist/src/transporter/responses.d.ts.map +0 -1
  46. package/dist/src/transporter/stackTrace.d.ts +0 -4
  47. package/dist/src/transporter/stackTrace.d.ts.map +0 -1
  48. package/dist/src/types/cache.d.ts +0 -61
  49. package/dist/src/types/cache.d.ts.map +0 -1
  50. package/dist/src/types/createClient.d.ts +0 -12
  51. package/dist/src/types/createClient.d.ts.map +0 -1
  52. package/dist/src/types/createIterablePromise.d.ts +0 -36
  53. package/dist/src/types/createIterablePromise.d.ts.map +0 -1
  54. package/dist/src/types/host.d.ts +0 -37
  55. package/dist/src/types/host.d.ts.map +0 -1
  56. package/dist/src/types/index.d.ts +0 -7
  57. package/dist/src/types/index.d.ts.map +0 -1
  58. package/dist/src/types/requester.d.ts +0 -66
  59. package/dist/src/types/requester.d.ts.map +0 -1
  60. package/dist/src/types/transporter.d.ts +0 -128
  61. package/dist/src/types/transporter.d.ts.map +0 -1
@@ -1,747 +0,0 @@
1
- function createAuth(appId, apiKey, authMode = 'WithinHeaders') {
2
- const credentials = {
3
- 'x-algolia-api-key': apiKey,
4
- 'x-algolia-application-id': appId
5
- };
6
- return {
7
- headers() {
8
- return authMode === 'WithinHeaders' ? credentials : {};
9
- },
10
- queryParameters() {
11
- return authMode === 'WithinQueryParameters' ? credentials : {};
12
- }
13
- };
14
- }
15
-
16
- function getUrlParams({
17
- host,
18
- search,
19
- pathname
20
- }) {
21
- const urlSearchParams = search.split('?');
22
- if (urlSearchParams.length === 1) {
23
- return {
24
- host,
25
- algoliaAgent: '',
26
- searchParams: undefined,
27
- path: pathname
28
- };
29
- }
30
- const splitSearchParams = urlSearchParams[1].split('&');
31
- let algoliaAgent = '';
32
- const searchParams = {};
33
- if (splitSearchParams.length > 0) {
34
- splitSearchParams.forEach(param => {
35
- const [key, value] = param.split('=');
36
- if (key === 'x-algolia-agent') {
37
- algoliaAgent = value;
38
- return;
39
- }
40
- searchParams[key] = value;
41
- });
42
- }
43
- return {
44
- host,
45
- algoliaAgent,
46
- searchParams: Object.keys(searchParams).length === 0 ? undefined : searchParams,
47
- path: pathname
48
- };
49
- }
50
- function createEchoRequester({
51
- getURL,
52
- status = 200
53
- }) {
54
- function send(request) {
55
- const {
56
- host,
57
- searchParams,
58
- algoliaAgent,
59
- path
60
- } = getUrlParams(getURL(request.url));
61
- const content = {
62
- ...request,
63
- data: request.data ? JSON.parse(request.data) : undefined,
64
- path,
65
- host,
66
- algoliaAgent,
67
- searchParams
68
- };
69
- return Promise.resolve({
70
- content: JSON.stringify(content),
71
- isTimedOut: false,
72
- status
73
- });
74
- }
75
- return {
76
- send
77
- };
78
- }
79
-
80
- /**
81
- * Helper: Returns the promise of a given `func` to iterate on, based on a given `validate` condition.
82
- *
83
- * @param createIterator - The createIterator options.
84
- * @param createIterator.func - The function to run, which returns a promise.
85
- * @param createIterator.validate - The validator function. It receives the resolved return of `func`.
86
- * @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`.
87
- * @param createIterator.error - The `validate` condition to throw an error, and its message.
88
- * @param createIterator.timeout - The function to decide how long to wait between iterations.
89
- */
90
- function createIterablePromise({
91
- func,
92
- validate,
93
- aggregator,
94
- error,
95
- timeout = () => 0
96
- }) {
97
- const retry = previousResponse => {
98
- return new Promise((resolve, reject) => {
99
- func(previousResponse).then(response => {
100
- if (aggregator) {
101
- aggregator(response);
102
- }
103
- if (validate(response)) {
104
- return resolve(response);
105
- }
106
- if (error && error.validate(response)) {
107
- return reject(new Error(error.message(response)));
108
- }
109
- return setTimeout(() => {
110
- retry(response).then(resolve).catch(reject);
111
- }, timeout());
112
- }).catch(err => {
113
- reject(err);
114
- });
115
- });
116
- };
117
- return retry();
118
- }
119
-
120
- function createBrowserLocalStorageCache(options) {
121
- let storage;
122
- // We've changed the namespace to avoid conflicts with v4, as this version is a huge breaking change
123
- const namespaceKey = `algolia-client-js-${options.key}`;
124
- function getStorage() {
125
- if (storage === undefined) {
126
- storage = options.localStorage || window.localStorage;
127
- }
128
- return storage;
129
- }
130
- function getNamespace() {
131
- return JSON.parse(getStorage().getItem(namespaceKey) || '{}');
132
- }
133
- function setNamespace(namespace) {
134
- getStorage().setItem(namespaceKey, JSON.stringify(namespace));
135
- }
136
- function removeOutdatedCacheItems() {
137
- const timeToLive = options.timeToLive ? options.timeToLive * 1000 : null;
138
- const namespace = getNamespace();
139
- const filteredNamespaceWithoutOldFormattedCacheItems = Object.fromEntries(Object.entries(namespace).filter(([, cacheItem]) => {
140
- return cacheItem.timestamp !== undefined;
141
- }));
142
- setNamespace(filteredNamespaceWithoutOldFormattedCacheItems);
143
- if (!timeToLive) {
144
- return;
145
- }
146
- const filteredNamespaceWithoutExpiredItems = Object.fromEntries(Object.entries(filteredNamespaceWithoutOldFormattedCacheItems).filter(([, cacheItem]) => {
147
- const currentTimestamp = new Date().getTime();
148
- const isExpired = cacheItem.timestamp + timeToLive < currentTimestamp;
149
- return !isExpired;
150
- }));
151
- setNamespace(filteredNamespaceWithoutExpiredItems);
152
- }
153
- return {
154
- get(key, defaultValue, events = {
155
- miss: () => Promise.resolve()
156
- }) {
157
- return Promise.resolve().then(() => {
158
- removeOutdatedCacheItems();
159
- return getNamespace()[JSON.stringify(key)];
160
- }).then(value => {
161
- return Promise.all([value ? value.value : defaultValue(), value !== undefined]);
162
- }).then(([value, exists]) => {
163
- return Promise.all([value, exists || events.miss(value)]);
164
- }).then(([value]) => value);
165
- },
166
- set(key, value) {
167
- return Promise.resolve().then(() => {
168
- const namespace = getNamespace();
169
- namespace[JSON.stringify(key)] = {
170
- timestamp: new Date().getTime(),
171
- value
172
- };
173
- getStorage().setItem(namespaceKey, JSON.stringify(namespace));
174
- return value;
175
- });
176
- },
177
- delete(key) {
178
- return Promise.resolve().then(() => {
179
- const namespace = getNamespace();
180
- delete namespace[JSON.stringify(key)];
181
- getStorage().setItem(namespaceKey, JSON.stringify(namespace));
182
- });
183
- },
184
- clear() {
185
- return Promise.resolve().then(() => {
186
- getStorage().removeItem(namespaceKey);
187
- });
188
- }
189
- };
190
- }
191
-
192
- function createNullCache() {
193
- return {
194
- get(_key, defaultValue, events = {
195
- miss: () => Promise.resolve()
196
- }) {
197
- const value = defaultValue();
198
- return value.then(result => Promise.all([result, events.miss(result)])).then(([result]) => result);
199
- },
200
- set(_key, value) {
201
- return Promise.resolve(value);
202
- },
203
- delete(_key) {
204
- return Promise.resolve();
205
- },
206
- clear() {
207
- return Promise.resolve();
208
- }
209
- };
210
- }
211
-
212
- function createFallbackableCache(options) {
213
- const caches = [...options.caches];
214
- const current = caches.shift();
215
- if (current === undefined) {
216
- return createNullCache();
217
- }
218
- return {
219
- get(key, defaultValue, events = {
220
- miss: () => Promise.resolve()
221
- }) {
222
- return current.get(key, defaultValue, events).catch(() => {
223
- return createFallbackableCache({
224
- caches
225
- }).get(key, defaultValue, events);
226
- });
227
- },
228
- set(key, value) {
229
- return current.set(key, value).catch(() => {
230
- return createFallbackableCache({
231
- caches
232
- }).set(key, value);
233
- });
234
- },
235
- delete(key) {
236
- return current.delete(key).catch(() => {
237
- return createFallbackableCache({
238
- caches
239
- }).delete(key);
240
- });
241
- },
242
- clear() {
243
- return current.clear().catch(() => {
244
- return createFallbackableCache({
245
- caches
246
- }).clear();
247
- });
248
- }
249
- };
250
- }
251
-
252
- function createMemoryCache(options = {
253
- serializable: true
254
- }) {
255
- let cache = {};
256
- return {
257
- get(key, defaultValue, events = {
258
- miss: () => Promise.resolve()
259
- }) {
260
- const keyAsString = JSON.stringify(key);
261
- if (keyAsString in cache) {
262
- return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]);
263
- }
264
- const promise = defaultValue();
265
- return promise.then(value => events.miss(value)).then(() => promise);
266
- },
267
- set(key, value) {
268
- cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value;
269
- return Promise.resolve(value);
270
- },
271
- delete(key) {
272
- delete cache[JSON.stringify(key)];
273
- return Promise.resolve();
274
- },
275
- clear() {
276
- cache = {};
277
- return Promise.resolve();
278
- }
279
- };
280
- }
281
-
282
- // By default, API Clients at Algolia have expiration delay of 5 mins.
283
- // In the JavaScript client, we have 2 mins.
284
- const EXPIRATION_DELAY = 2 * 60 * 1000;
285
- function createStatefulHost(host, status = 'up') {
286
- const lastUpdate = Date.now();
287
- function isUp() {
288
- return status === 'up' || Date.now() - lastUpdate > EXPIRATION_DELAY;
289
- }
290
- function isTimedOut() {
291
- return status === 'timed out' && Date.now() - lastUpdate <= EXPIRATION_DELAY;
292
- }
293
- return {
294
- ...host,
295
- status,
296
- lastUpdate,
297
- isUp,
298
- isTimedOut
299
- };
300
- }
301
-
302
- function _defineProperty(e, r, t) {
303
- return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
304
- value: t,
305
- enumerable: !0,
306
- configurable: !0,
307
- writable: !0
308
- }) : e[r] = t, e;
309
- }
310
- function _toPrimitive(t, r) {
311
- if ("object" != typeof t || !t) return t;
312
- var e = t[Symbol.toPrimitive];
313
- if (void 0 !== e) {
314
- var i = e.call(t, r || "default");
315
- if ("object" != typeof i) return i;
316
- throw new TypeError("@@toPrimitive must return a primitive value.");
317
- }
318
- return ("string" === r ? String : Number)(t);
319
- }
320
- function _toPropertyKey(t) {
321
- var i = _toPrimitive(t, "string");
322
- return "symbol" == typeof i ? i : i + "";
323
- }
324
-
325
- class AlgoliaError extends Error {
326
- constructor(message, name) {
327
- super(message);
328
- _defineProperty(this, "name", 'AlgoliaError');
329
- if (name) {
330
- this.name = name;
331
- }
332
- }
333
- }
334
- class ErrorWithStackTrace extends AlgoliaError {
335
- constructor(message, stackTrace, name) {
336
- super(message, name);
337
- // the array and object should be frozen to reflect the stackTrace at the time of the error
338
- _defineProperty(this, "stackTrace", void 0);
339
- this.stackTrace = stackTrace;
340
- }
341
- }
342
- class RetryError extends ErrorWithStackTrace {
343
- constructor(stackTrace) {
344
- super('Unreachable hosts - your application id may be incorrect. If the error persists, please reach out to the Algolia Support team: https://alg.li/support.', stackTrace, 'RetryError');
345
- }
346
- }
347
- class ApiError extends ErrorWithStackTrace {
348
- constructor(message, status, stackTrace, name = 'ApiError') {
349
- super(message, stackTrace, name);
350
- _defineProperty(this, "status", void 0);
351
- this.status = status;
352
- }
353
- }
354
- class DeserializationError extends AlgoliaError {
355
- constructor(message, response) {
356
- super(message, 'DeserializationError');
357
- _defineProperty(this, "response", void 0);
358
- this.response = response;
359
- }
360
- }
361
- // DetailedApiError is only used by the ingestion client to return more informative error, other clients will use ApiClient.
362
- class DetailedApiError extends ApiError {
363
- constructor(message, status, error, stackTrace) {
364
- super(message, status, stackTrace, 'DetailedApiError');
365
- _defineProperty(this, "error", void 0);
366
- this.error = error;
367
- }
368
- }
369
-
370
- function shuffle(array) {
371
- const shuffledArray = array;
372
- for (let c = array.length - 1; c > 0; c--) {
373
- const b = Math.floor(Math.random() * (c + 1));
374
- const a = array[c];
375
- shuffledArray[c] = array[b];
376
- shuffledArray[b] = a;
377
- }
378
- return shuffledArray;
379
- }
380
- function serializeUrl(host, path, queryParameters) {
381
- const queryParametersAsString = serializeQueryParameters(queryParameters);
382
- let url = `${host.protocol}://${host.url}${host.port ? `:${host.port}` : ''}/${path.charAt(0) === '/' ? path.substring(1) : path}`;
383
- if (queryParametersAsString.length) {
384
- url += `?${queryParametersAsString}`;
385
- }
386
- return url;
387
- }
388
- function serializeQueryParameters(parameters) {
389
- return Object.keys(parameters).filter(key => parameters[key] !== undefined).sort().map(key => `${key}=${encodeURIComponent(Object.prototype.toString.call(parameters[key]) === '[object Array]' ? parameters[key].join(',') : parameters[key]).replaceAll('+', '%20')}`).join('&');
390
- }
391
- function serializeData(request, requestOptions) {
392
- if (request.method === 'GET' || request.data === undefined && requestOptions.data === undefined) {
393
- return undefined;
394
- }
395
- const data = Array.isArray(request.data) ? request.data : {
396
- ...request.data,
397
- ...requestOptions.data
398
- };
399
- return JSON.stringify(data);
400
- }
401
- function serializeHeaders(baseHeaders, requestHeaders, requestOptionsHeaders) {
402
- const headers = {
403
- Accept: 'application/json',
404
- ...baseHeaders,
405
- ...requestHeaders,
406
- ...requestOptionsHeaders
407
- };
408
- const serializedHeaders = {};
409
- Object.keys(headers).forEach(header => {
410
- const value = headers[header];
411
- serializedHeaders[header.toLowerCase()] = value;
412
- });
413
- return serializedHeaders;
414
- }
415
- function deserializeSuccess(response) {
416
- try {
417
- return JSON.parse(response.content);
418
- } catch (e) {
419
- throw new DeserializationError(e.message, response);
420
- }
421
- }
422
- function deserializeFailure({
423
- content,
424
- status
425
- }, stackFrame) {
426
- try {
427
- const parsed = JSON.parse(content);
428
- if ('error' in parsed) {
429
- return new DetailedApiError(parsed.message, status, parsed.error, stackFrame);
430
- }
431
- return new ApiError(parsed.message, status, stackFrame);
432
- } catch {
433
- // ..
434
- }
435
- return new ApiError(content, status, stackFrame);
436
- }
437
-
438
- function isNetworkError({
439
- isTimedOut,
440
- status
441
- }) {
442
- return !isTimedOut && ~~status === 0;
443
- }
444
- function isRetryable({
445
- isTimedOut,
446
- status
447
- }) {
448
- return isTimedOut || isNetworkError({
449
- isTimedOut,
450
- status
451
- }) || ~~(status / 100) !== 2 && ~~(status / 100) !== 4;
452
- }
453
- function isSuccess({
454
- status
455
- }) {
456
- return ~~(status / 100) === 2;
457
- }
458
-
459
- function stackTraceWithoutCredentials(stackTrace) {
460
- return stackTrace.map(stackFrame => stackFrameWithoutCredentials(stackFrame));
461
- }
462
- function stackFrameWithoutCredentials(stackFrame) {
463
- const modifiedHeaders = stackFrame.request.headers['x-algolia-api-key'] ? {
464
- 'x-algolia-api-key': '*****'
465
- } : {};
466
- return {
467
- ...stackFrame,
468
- request: {
469
- ...stackFrame.request,
470
- headers: {
471
- ...stackFrame.request.headers,
472
- ...modifiedHeaders
473
- }
474
- }
475
- };
476
- }
477
-
478
- function createTransporter({
479
- hosts,
480
- hostsCache,
481
- baseHeaders,
482
- baseQueryParameters,
483
- algoliaAgent,
484
- timeouts,
485
- requester,
486
- requestsCache,
487
- responsesCache
488
- }) {
489
- async function createRetryableOptions(compatibleHosts) {
490
- const statefulHosts = await Promise.all(compatibleHosts.map(compatibleHost => {
491
- return hostsCache.get(compatibleHost, () => {
492
- return Promise.resolve(createStatefulHost(compatibleHost));
493
- });
494
- }));
495
- const hostsUp = statefulHosts.filter(host => host.isUp());
496
- const hostsTimedOut = statefulHosts.filter(host => host.isTimedOut());
497
- // Note, we put the hosts that previously timed out on the end of the list.
498
- const hostsAvailable = [...hostsUp, ...hostsTimedOut];
499
- const compatibleHostsAvailable = hostsAvailable.length > 0 ? hostsAvailable : compatibleHosts;
500
- return {
501
- hosts: compatibleHostsAvailable,
502
- getTimeout(timeoutsCount, baseTimeout) {
503
- /**
504
- * Imagine that you have 4 hosts, if timeouts will increase
505
- * on the following way: 1 (timed out) > 4 (timed out) > 5 (200).
506
- *
507
- * Note that, the very next request, we start from the previous timeout.
508
- *
509
- * 5 (timed out) > 6 (timed out) > 7 ...
510
- *
511
- * This strategy may need to be reviewed, but is the strategy on the our
512
- * current v3 version.
513
- */
514
- const timeoutMultiplier = hostsTimedOut.length === 0 && timeoutsCount === 0 ? 1 : hostsTimedOut.length + 3 + timeoutsCount;
515
- return timeoutMultiplier * baseTimeout;
516
- }
517
- };
518
- }
519
- async function retryableRequest(request, requestOptions, isRead = true) {
520
- const stackTrace = [];
521
- /**
522
- * First we prepare the payload that do not depend from hosts.
523
- */
524
- const data = serializeData(request, requestOptions);
525
- const headers = serializeHeaders(baseHeaders, request.headers, requestOptions.headers);
526
- // On `GET`, the data is proxied to query parameters.
527
- const dataQueryParameters = request.method === 'GET' ? {
528
- ...request.data,
529
- ...requestOptions.data
530
- } : {};
531
- const queryParameters = {
532
- ...baseQueryParameters,
533
- ...request.queryParameters,
534
- ...dataQueryParameters
535
- };
536
- if (algoliaAgent.value) {
537
- queryParameters['x-algolia-agent'] = algoliaAgent.value;
538
- }
539
- if (requestOptions && requestOptions.queryParameters) {
540
- for (const key of Object.keys(requestOptions.queryParameters)) {
541
- // We want to keep `undefined` and `null` values,
542
- // but also avoid stringifying `object`s, as they are
543
- // handled in the `serializeUrl` step right after.
544
- if (!requestOptions.queryParameters[key] || Object.prototype.toString.call(requestOptions.queryParameters[key]) === '[object Object]') {
545
- queryParameters[key] = requestOptions.queryParameters[key];
546
- } else {
547
- queryParameters[key] = requestOptions.queryParameters[key].toString();
548
- }
549
- }
550
- }
551
- let timeoutsCount = 0;
552
- const retry = async (retryableHosts, getTimeout) => {
553
- /**
554
- * We iterate on each host, until there is no host left.
555
- */
556
- const host = retryableHosts.pop();
557
- if (host === undefined) {
558
- throw new RetryError(stackTraceWithoutCredentials(stackTrace));
559
- }
560
- const timeout = {
561
- ...timeouts,
562
- ...requestOptions.timeouts
563
- };
564
- const payload = {
565
- data,
566
- headers,
567
- method: request.method,
568
- url: serializeUrl(host, request.path, queryParameters),
569
- connectTimeout: getTimeout(timeoutsCount, timeout.connect),
570
- responseTimeout: getTimeout(timeoutsCount, isRead ? timeout.read : timeout.write)
571
- };
572
- /**
573
- * The stackFrame is pushed to the stackTrace so we
574
- * can have information about onRetry and onFailure
575
- * decisions.
576
- */
577
- const pushToStackTrace = response => {
578
- const stackFrame = {
579
- request: payload,
580
- response,
581
- host,
582
- triesLeft: retryableHosts.length
583
- };
584
- stackTrace.push(stackFrame);
585
- return stackFrame;
586
- };
587
- const response = await requester.send(payload);
588
- if (isRetryable(response)) {
589
- const stackFrame = pushToStackTrace(response);
590
- // If response is a timeout, we increase the number of timeouts so we can increase the timeout later.
591
- if (response.isTimedOut) {
592
- timeoutsCount++;
593
- }
594
- /**
595
- * Failures are individually sent to the logger, allowing
596
- * the end user to debug / store stack frames even
597
- * when a retry error does not happen.
598
- */
599
- // eslint-disable-next-line no-console -- this will be fixed by exposing a `logger` to the transporter
600
- console.log('Retryable failure', stackFrameWithoutCredentials(stackFrame));
601
- /**
602
- * We also store the state of the host in failure cases. If the host, is
603
- * down it will remain down for the next 2 minutes. In a timeout situation,
604
- * this host will be added end of the list of hosts on the next request.
605
- */
606
- await hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? 'timed out' : 'down'));
607
- return retry(retryableHosts, getTimeout);
608
- }
609
- if (isSuccess(response)) {
610
- return deserializeSuccess(response);
611
- }
612
- pushToStackTrace(response);
613
- throw deserializeFailure(response, stackTrace);
614
- };
615
- /**
616
- * Finally, for each retryable host perform request until we got a non
617
- * retryable response. Some notes here:
618
- *
619
- * 1. The reverse here is applied so we can apply a `pop` later on => more performant.
620
- * 2. We also get from the retryable options a timeout multiplier that is tailored
621
- * for the current context.
622
- */
623
- const compatibleHosts = hosts.filter(host => host.accept === 'readWrite' || (isRead ? host.accept === 'read' : host.accept === 'write'));
624
- const options = await createRetryableOptions(compatibleHosts);
625
- return retry([...options.hosts].reverse(), options.getTimeout);
626
- }
627
- function createRequest(request, requestOptions = {}) {
628
- /**
629
- * A read request is either a `GET` request, or a request that we make
630
- * via the `read` transporter (e.g. `search`).
631
- */
632
- const isRead = request.useReadTransporter || request.method === 'GET';
633
- if (!isRead) {
634
- /**
635
- * On write requests, no cache mechanisms are applied, and we
636
- * proxy the request immediately to the requester.
637
- */
638
- return retryableRequest(request, requestOptions, isRead);
639
- }
640
- const createRetryableRequest = () => {
641
- /**
642
- * Then, we prepare a function factory that contains the construction of
643
- * the retryable request. At this point, we may *not* perform the actual
644
- * request. But we want to have the function factory ready.
645
- */
646
- return retryableRequest(request, requestOptions);
647
- };
648
- /**
649
- * Once we have the function factory ready, we need to determine of the
650
- * request is "cacheable" - should be cached. Note that, once again,
651
- * the user can force this option.
652
- */
653
- const cacheable = requestOptions.cacheable || request.cacheable;
654
- /**
655
- * If is not "cacheable", we immediately trigger the retryable request, no
656
- * need to check cache implementations.
657
- */
658
- if (cacheable !== true) {
659
- return createRetryableRequest();
660
- }
661
- /**
662
- * If the request is "cacheable", we need to first compute the key to ask
663
- * the cache implementations if this request is on progress or if the
664
- * response already exists on the cache.
665
- */
666
- const key = {
667
- request,
668
- requestOptions,
669
- transporter: {
670
- queryParameters: baseQueryParameters,
671
- headers: baseHeaders
672
- }
673
- };
674
- /**
675
- * With the computed key, we first ask the responses cache
676
- * implementation if this request was been resolved before.
677
- */
678
- return responsesCache.get(key, () => {
679
- /**
680
- * If the request has never resolved before, we actually ask if there
681
- * is a current request with the same key on progress.
682
- */
683
- return requestsCache.get(key, () =>
684
- /**
685
- * Finally, if there is no request in progress with the same key,
686
- * this `createRetryableRequest()` will actually trigger the
687
- * retryable request.
688
- */
689
- requestsCache.set(key, createRetryableRequest()).then(response => Promise.all([requestsCache.delete(key), response]), err => Promise.all([requestsCache.delete(key), Promise.reject(err)])).then(([_, response]) => response));
690
- }, {
691
- /**
692
- * Of course, once we get this response back from the server, we
693
- * tell response cache to actually store the received response
694
- * to be used later.
695
- */
696
- miss: response => responsesCache.set(key, response)
697
- });
698
- }
699
- return {
700
- hostsCache,
701
- requester,
702
- timeouts,
703
- algoliaAgent,
704
- baseHeaders,
705
- baseQueryParameters,
706
- hosts,
707
- request: createRequest,
708
- requestsCache,
709
- responsesCache
710
- };
711
- }
712
-
713
- function createAlgoliaAgent(version) {
714
- const algoliaAgent = {
715
- value: `Algolia for JavaScript (${version})`,
716
- add(options) {
717
- const addedAlgoliaAgent = `; ${options.segment}${options.version !== undefined ? ` (${options.version})` : ''}`;
718
- if (algoliaAgent.value.indexOf(addedAlgoliaAgent) === -1) {
719
- algoliaAgent.value = `${algoliaAgent.value}${addedAlgoliaAgent}`;
720
- }
721
- return algoliaAgent;
722
- }
723
- };
724
- return algoliaAgent;
725
- }
726
-
727
- function getAlgoliaAgent({
728
- algoliaAgents,
729
- client,
730
- version
731
- }) {
732
- const defaultAlgoliaAgent = createAlgoliaAgent(version).add({
733
- segment: client,
734
- version
735
- });
736
- algoliaAgents.forEach(algoliaAgent => defaultAlgoliaAgent.add(algoliaAgent));
737
- return defaultAlgoliaAgent;
738
- }
739
-
740
- const DEFAULT_CONNECT_TIMEOUT_BROWSER = 1000;
741
- const DEFAULT_READ_TIMEOUT_BROWSER = 2000;
742
- const DEFAULT_WRITE_TIMEOUT_BROWSER = 30000;
743
- const DEFAULT_CONNECT_TIMEOUT_NODE = 2000;
744
- const DEFAULT_READ_TIMEOUT_NODE = 5000;
745
- const DEFAULT_WRITE_TIMEOUT_NODE = 30000;
746
-
747
- export { AlgoliaError, ApiError, DEFAULT_CONNECT_TIMEOUT_BROWSER, DEFAULT_CONNECT_TIMEOUT_NODE, DEFAULT_READ_TIMEOUT_BROWSER, DEFAULT_READ_TIMEOUT_NODE, DEFAULT_WRITE_TIMEOUT_BROWSER, DEFAULT_WRITE_TIMEOUT_NODE, DeserializationError, DetailedApiError, ErrorWithStackTrace, RetryError, createAlgoliaAgent, createAuth, createBrowserLocalStorageCache, createEchoRequester, createFallbackableCache, createIterablePromise, createMemoryCache, createNullCache, createStatefulHost, createTransporter, deserializeFailure, deserializeSuccess, getAlgoliaAgent, isNetworkError, isRetryable, isSuccess, serializeData, serializeHeaders, serializeQueryParameters, serializeUrl, shuffle, stackFrameWithoutCredentials, stackTraceWithoutCredentials };