@commercetools/ts-client 2.1.0-alpha.0 → 2.1.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.
@@ -3,8 +3,6 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var fetch$1 = require('node-fetch');
6
- var uuid = require('uuid');
7
- var _ = require('buffer/');
8
6
  var AbortController = require('abort-controller');
9
7
 
10
8
  function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
@@ -12,7 +10,7 @@ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e };
12
10
  var fetch__default = /*#__PURE__*/_interopDefault(fetch$1);
13
11
  var AbortController__default = /*#__PURE__*/_interopDefault(AbortController);
14
12
 
15
- function toPrimitive(t, r) {
13
+ function _toPrimitive(t, r) {
16
14
  if ("object" != typeof t || !t) return t;
17
15
  var e = t[Symbol.toPrimitive];
18
16
  if (void 0 !== e) {
@@ -23,24 +21,18 @@ function toPrimitive(t, r) {
23
21
  return ("string" === r ? String : Number)(t);
24
22
  }
25
23
 
26
- function toPropertyKey(t) {
27
- var i = toPrimitive(t, "string");
24
+ function _toPropertyKey(t) {
25
+ var i = _toPrimitive(t, "string");
28
26
  return "symbol" == typeof i ? i : i + "";
29
27
  }
30
28
 
31
- function _defineProperty(obj, key, value) {
32
- key = toPropertyKey(key);
33
- if (key in obj) {
34
- Object.defineProperty(obj, key, {
35
- value: value,
36
- enumerable: true,
37
- configurable: true,
38
- writable: true
39
- });
40
- } else {
41
- obj[key] = value;
42
- }
43
- return obj;
29
+ function _defineProperty(e, r, t) {
30
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
31
+ value: t,
32
+ enumerable: !0,
33
+ configurable: !0,
34
+ writable: !0
35
+ }) : e[r] = t, e;
44
36
  }
45
37
 
46
38
  const HEADERS_CONTENT_TYPES = ['application/json', 'application/graphql'];
@@ -192,10 +184,12 @@ async function executor(request) {
192
184
  let _response = {};
193
185
  try {
194
186
  _response = await execute();
195
- if (_response.status > 399 && hasResponseRetryCode(retryCodes, _response)) return {
196
- _response,
197
- shouldRetry: true
198
- };
187
+ if (_response.status > 399 && hasResponseRetryCode(retryCodes, _response)) {
188
+ return {
189
+ _response,
190
+ shouldRetry: true
191
+ };
192
+ }
199
193
  } catch (e) {
200
194
  if (e.name.includes('AbortError') && retryWhenAborted) {
201
195
  return {
@@ -240,7 +234,7 @@ async function executor(request) {
240
234
  try {
241
235
  // try to parse the `fetch` response as text
242
236
  if (response.text && typeof response.text == 'function') {
243
- result = await response.text();
237
+ result = (await response.text()) || response[Object.getOwnPropertySymbols(response)[1]];
244
238
  data = JSON.parse(result);
245
239
  } else {
246
240
  // axios response
@@ -266,7 +260,8 @@ async function executor(request) {
266
260
  }
267
261
 
268
262
  function generateID() {
269
- return uuid.v4();
263
+ // @ts-ignore
264
+ return ([1e6] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (parseInt(c) ^ Math.floor(Math.random() * 256) & 15 >> parseInt(c) / 4).toString(16));
270
265
  }
271
266
 
272
267
  function parse(headers) {
@@ -455,16 +450,11 @@ function createUserAgent(options) {
455
450
  return [baseInfo, systemInfo, libraryInfo, contactInfo, customAgent].filter(Boolean).join(' ');
456
451
  }
457
452
 
458
- function responseCache() {
459
- let val;
460
- return {
461
- set(response) {
462
- val = response;
463
- },
464
- get() {
465
- return val;
466
- }
467
- };
453
+ function byteLength(body) {
454
+ if (typeof body === 'string') return body.length.toString();
455
+ if (body && typeof body === 'object') return new TextEncoder().encode(JSON.stringify(body)).length.toString();
456
+ if (body instanceof Uint8Array) return body.length.toString();
457
+ return '0';
468
458
  }
469
459
 
470
460
  /**
@@ -527,7 +517,8 @@ function buildRequestForClientCredentialsFlow(options) {
527
517
  } = options.credentials || {};
528
518
  if (!(clientId && clientSecret)) throw new Error('Missing required credentials (clientId, clientSecret)');
529
519
  const scope = options.scopes ? options.scopes.join(' ') : undefined;
530
- const basicAuth = _.Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
520
+ const basicAuth = btoa(`${clientId}:${clientSecret}`);
521
+
531
522
  // This is mostly useful for internal testing purposes to be able to check
532
523
  // other oauth endpoints.
533
524
  const oauthUri = options.oauthUri || '/oauth/token';
@@ -573,9 +564,10 @@ function buildRequestForRefreshTokenFlow(options) {
573
564
  clientSecret
574
565
  } = options.credentials;
575
566
  if (!(clientId && clientSecret)) throw new Error('Missing required credentials (clientId, clientSecret)');
576
- const basicAuth = _.Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
577
- // This is mostly useful for internal testing purposes to be able to check
578
- // other oauth endpoints.
567
+ const basicAuth = btoa(`${clientId}:${clientSecret}`);
568
+
569
+ // This is mostly useful for internal testing
570
+ // purposes to be able to check other oauth endpoints.
579
571
  const oauthUri = options.oauthUri || '/oauth/token';
580
572
  const url = options.host.replace(/\/$/, '') + oauthUri;
581
573
  const body = `grant_type=refresh_token&refresh_token=${encodeURIComponent(options.refreshToken)}`;
@@ -609,7 +601,7 @@ function buildRequestForPasswordFlow(options) {
609
601
  if (!(username && password)) throw new Error('Missing required user credentials (username, password)');
610
602
  const scope = (options.scopes || []).join(' ');
611
603
  const scopeStr = scope ? `&scope=${scope}` : '';
612
- const basicAuth = _.Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
604
+ const basicAuth = btoa(`${clientId}:${clientSecret}`);
613
605
 
614
606
  /**
615
607
  * This is mostly useful for internal testing purposes to be able to check
@@ -629,48 +621,16 @@ function buildRequestForPasswordFlow(options) {
629
621
 
630
622
  async function executeRequest$1(options) {
631
623
  const {
632
- request,
633
624
  httpClient,
634
625
  tokenCache,
635
- tokenCacheKey,
636
626
  userOption,
637
- tokenCacheObject,
638
- next
627
+ tokenCacheObject
639
628
  } = options;
640
629
  let url = options.url;
641
630
  let body = options.body;
642
631
  let basicAuth = options.basicAuth;
643
-
644
- // get the pending object from option
645
- // let pendingTasks: Array<Task> = options.pendingTasks
646
-
647
632
  if (!httpClient || typeof httpClient !== 'function') throw new Error('an `httpClient` is not available, please pass in a `fetch` or `axios` instance as an option or have them globally available.');
648
633
 
649
- /**
650
- * If there is a token in the tokenCache, and it's not
651
- * expired, append the token in the `Authorization` header.
652
- */
653
- // const tokenCacheObject = tokenCache.get(tokenCacheKey)
654
-
655
- // if (
656
- // tokenCacheObject && tokenCacheObject.token
657
- // && Date.now() < tokenCacheObject.expirationTime
658
- // ) {
659
- // return next(
660
- // mergeAuthHeader(
661
- // tokenCacheObject.token, request
662
- // )
663
- // );
664
- // }
665
-
666
- /**
667
- * Keep pending tasks until a token is fetched
668
- * Save next function as well, to call it once the token has been fetched, which prevents
669
- * unexpected behaviour in a context in which the next function uses global vars
670
- * or Promises to capture the token to hand it to other libraries, e.g. Apollo
671
- */
672
- // pendingTasks.push({ request, next })
673
-
674
634
  /**
675
635
  * use refreshToken flow if there is refresh-token
676
636
  * and there's either no token or the token is expired
@@ -701,7 +661,7 @@ async function executeRequest$1(options) {
701
661
  headers: {
702
662
  Authorization: `Basic ${basicAuth}`,
703
663
  'Content-Type': 'application/x-www-form-urlencoded',
704
- 'Content-Length': _.Buffer.byteLength(body).toString()
664
+ 'Content-Length': byteLength(body)
705
665
  },
706
666
  httpClient,
707
667
  body
@@ -722,74 +682,23 @@ async function executeRequest$1(options) {
722
682
  expirationTime,
723
683
  refreshToken
724
684
  });
725
-
726
- /**
727
- * Freeze and copy pending queue, reset
728
- * original one for accepting new pending tasks
729
- */
730
- // const requestQueue = pendingTasks.slice()
731
-
732
- // // reset pendingTask queue
733
- // pendingTasks = []
734
-
735
- // if (requestQueue.length === 1) {
736
- // return mergeAuthHeader(token, requestQueue.pop().request)
737
- // }
738
-
739
- // // execute all pending tasks if any
740
- // for (let i = 0; i < pendingTasks.length; i++) {
741
- // const task: Task = pendingTasks[i];
742
- // const requestWithAuth = mergeAuthHeader(token, task.request)
743
-
744
- // // execute task
745
- // // task.next(requestWithAuth)
746
-
747
- // pendingTasks[i].request = requestWithAuth;
748
- // }
749
-
750
- // return pendingTasks;
751
685
  return Promise.resolve(true);
752
686
  }
753
- const error = new Error(response.data.message ? response.data.message : JSON.stringify(response.data));
754
- /**
755
- * reject the error immediately
756
- * and free up the middleware chain
757
- */
758
- return request.reject({
759
- ...request,
760
- headers: {
761
- ...request.headers
762
- },
763
- response: {
764
- statusCode: response.statusCode || response.data.statusCode,
765
- error: {
766
- error,
767
- body: response
768
- }
769
- }
687
+
688
+ // bubble up the error for the catch block
689
+ throw createError({
690
+ code: response.data.error,
691
+ statusCode: response.data.statusCode,
692
+ message: response.data.message,
693
+ error: response.data.errors
770
694
  });
771
695
  } catch (error) {
772
- request.reject({
773
- ...request,
774
- headers: {
775
- ...request.headers
776
- },
777
- response: {
778
- body: null,
779
- statusCode: error.statusCode || 0,
780
- error: {
781
- ...response,
782
- error,
783
- body: response
784
- }
785
- }
786
- });
696
+ // throw error and free up the middleware chain
697
+ throw error;
787
698
  }
788
699
  }
789
700
 
790
701
  function createAuthMiddlewareForAnonymousSessionFlow$1(options) {
791
- // const pendingTasks: Array<Task> = []
792
- // const requestState = new Mutex()
793
702
  const tokenCache = options.tokenCache || store({
794
703
  token: '',
795
704
  expirationTime: -1
@@ -804,6 +713,11 @@ function createAuthMiddlewareForAnonymousSessionFlow$1(options) {
804
713
  // move on
805
714
  return next(request);
806
715
  }
716
+
717
+ /**
718
+ * If there is a token in the tokenCache, and it's not
719
+ * expired, append the token in the `Authorization` header.
720
+ */
807
721
  tokenCacheObject = tokenCache.get(tokenCacheKey);
808
722
  if (tokenCacheObject && tokenCacheObject.token && Date.now() < tokenCacheObject.expirationTime) {
809
723
  return next(mergeAuthHeader(tokenCacheObject.token, request));
@@ -811,8 +725,6 @@ function createAuthMiddlewareForAnonymousSessionFlow$1(options) {
811
725
 
812
726
  // prepare request options
813
727
  const requestOptions = {
814
- // requestState,
815
- // pendingTasks,
816
728
  request,
817
729
  tokenCache,
818
730
  tokenCacheKey,
@@ -832,18 +744,14 @@ function createAuthMiddlewareForAnonymousSessionFlow$1(options) {
832
744
  tokenFetchPromise = null;
833
745
  }
834
746
 
835
- // Now the token is present in the tokenCache
747
+ // Now the token is present in the tokenCache and can be accessed
836
748
  tokenCacheObject = tokenCache.get(tokenCacheKey);
837
- if (tokenCacheObject && tokenCacheObject.token && Date.now() < tokenCacheObject.expirationTime) {
838
- return next(mergeAuthHeader(tokenCacheObject.token, request));
839
- }
749
+ return next(mergeAuthHeader(tokenCacheObject.token, request));
840
750
  };
841
751
  };
842
752
  }
843
753
 
844
754
  function createAuthMiddlewareForClientCredentialsFlow$1(options) {
845
- // const requestState = new Mutex()
846
- // const pendingTasks: Array<Task> = []
847
755
  const tokenCache = options.tokenCache || store({
848
756
  token: '',
849
757
  expirationTime: -1
@@ -858,6 +766,11 @@ function createAuthMiddlewareForClientCredentialsFlow$1(options) {
858
766
  // move on
859
767
  return next(request);
860
768
  }
769
+
770
+ /**
771
+ * If there is a token in the tokenCache, and it's not
772
+ * expired, append the token in the `Authorization` header.
773
+ */
861
774
  tokenCacheObject = tokenCache.get(tokenCacheKey);
862
775
  if (tokenCacheObject && tokenCacheObject.token && Date.now() < tokenCacheObject.expirationTime) {
863
776
  return next(mergeAuthHeader(tokenCacheObject.token, request));
@@ -865,8 +778,6 @@ function createAuthMiddlewareForClientCredentialsFlow$1(options) {
865
778
 
866
779
  // prepare request options
867
780
  const requestOptions = {
868
- // requestState,
869
- // pendingTasks,
870
781
  request,
871
782
  tokenCache,
872
783
  tokenCacheKey,
@@ -888,9 +799,7 @@ function createAuthMiddlewareForClientCredentialsFlow$1(options) {
888
799
 
889
800
  // Now the token is present in the tokenCache
890
801
  tokenCacheObject = tokenCache.get(tokenCacheKey);
891
- if (tokenCacheObject && tokenCacheObject.token && Date.now() < tokenCacheObject.expirationTime) {
892
- return next(mergeAuthHeader(tokenCacheObject.token, request));
893
- }
802
+ return next(mergeAuthHeader(tokenCacheObject.token, request));
894
803
  };
895
804
  };
896
805
  }
@@ -931,12 +840,20 @@ function createAuthMiddlewareForPasswordFlow$1(options) {
931
840
  const tokenCacheKey = buildTokenCacheKey(options);
932
841
  return next => {
933
842
  return async request => {
843
+ // if here is a token in the header, then move on to the next middleware
934
844
  if (request.headers && (request.headers.Authorization || request.headers.authorization)) {
935
845
  return next(request);
936
846
  }
847
+
848
+ /**
849
+ * If there is a token in the tokenCache, and it's not
850
+ * expired, append the token in the `Authorization` header.
851
+ */
852
+ tokenCacheObject = tokenCache.get(tokenCacheKey);
853
+ if (tokenCacheObject && tokenCacheObject.token && Date.now() < tokenCacheObject.expirationTime) {
854
+ return next(mergeAuthHeader(tokenCacheObject.token, request));
855
+ }
937
856
  const requestOptions = {
938
- // requestState,
939
- // pendingTasks,
940
857
  request,
941
858
  tokenCache,
942
859
  tokenCacheKey,
@@ -958,9 +875,7 @@ function createAuthMiddlewareForPasswordFlow$1(options) {
958
875
 
959
876
  // Now the token is present in the tokenCache
960
877
  tokenCacheObject = tokenCache.get(tokenCacheKey);
961
- if (tokenCacheObject && tokenCacheObject.token && Date.now() < tokenCacheObject.expirationTime) {
962
- return next(mergeAuthHeader(tokenCacheObject.token, request));
963
- }
878
+ return next(mergeAuthHeader(tokenCacheObject.token, request));
964
879
  };
965
880
  };
966
881
  }
@@ -970,10 +885,6 @@ function createAuthMiddlewareForRefreshTokenFlow$1(options) {
970
885
  token: '',
971
886
  tokenCacheKey: null
972
887
  });
973
-
974
- // const pendingTasks: Array<Task> = []
975
- // const requestState = new Mutex()
976
-
977
888
  let tokenCacheObject;
978
889
  let tokenFetchPromise = null;
979
890
  const tokenCacheKey = buildTokenCacheKey(options);
@@ -983,10 +894,17 @@ function createAuthMiddlewareForRefreshTokenFlow$1(options) {
983
894
  return next(request);
984
895
  }
985
896
 
897
+ /**
898
+ * If there is a token in the tokenCache, and it's not
899
+ * expired, append the token in the `Authorization` header.
900
+ */
901
+ tokenCacheObject = tokenCache.get(tokenCacheKey);
902
+ if (tokenCacheObject && tokenCacheObject.token && Date.now() < tokenCacheObject.expirationTime) {
903
+ return next(mergeAuthHeader(tokenCacheObject.token, request));
904
+ }
905
+
986
906
  // prepare request options
987
907
  const requestOptions = {
988
- // pendingTasks,
989
- // requestState,
990
908
  request,
991
909
  tokenCache,
992
910
  httpClient: options.httpClient || fetch,
@@ -1006,9 +924,7 @@ function createAuthMiddlewareForRefreshTokenFlow$1(options) {
1006
924
 
1007
925
  // Now the token is present in the tokenCache
1008
926
  tokenCacheObject = tokenCache.get(tokenCacheKey);
1009
- if (tokenCacheObject && tokenCacheObject.token && Date.now() < tokenCacheObject.expirationTime) {
1010
- return next(mergeAuthHeader(tokenCacheObject.token, request));
1011
- }
927
+ return next(mergeAuthHeader(tokenCacheObject.token, request));
1012
928
  };
1013
929
  };
1014
930
  }
@@ -1016,7 +932,6 @@ function createAuthMiddlewareForRefreshTokenFlow$1(options) {
1016
932
  function createConcurrentModificationMiddleware$1(modifierFunction) {
1017
933
  return next => {
1018
934
  return async request => {
1019
- request['concurrent'] = true;
1020
935
  const response = await next(request);
1021
936
  if (response.statusCode == 409) {
1022
937
  /**
@@ -1024,11 +939,11 @@ function createConcurrentModificationMiddleware$1(modifierFunction) {
1024
939
  * from the error body and update
1025
940
  * request with the currentVersion
1026
941
  */
1027
- const version = response.error?.body?.errors?.[0]?.currentVersion;
942
+ const version = response.error.body?.errors?.[0]?.currentVersion;
1028
943
 
1029
944
  // update the resource version here
1030
945
  if (version) {
1031
- if (modifierFunction) {
946
+ if (modifierFunction && typeof modifierFunction == 'function') {
1032
947
  request.body = await modifierFunction(version, request, response);
1033
948
  } else {
1034
949
  request.body = typeof request.body == 'string' ? {
@@ -1039,18 +954,10 @@ function createConcurrentModificationMiddleware$1(modifierFunction) {
1039
954
  version
1040
955
  };
1041
956
  }
1042
- return next({
1043
- ...request,
1044
- response
1045
- });
957
+ return next(request);
1046
958
  }
1047
959
  }
1048
- request.continue = true;
1049
- delete request['concurrent'];
1050
- return next({
1051
- ...request,
1052
- response
1053
- });
960
+ return response;
1054
961
  };
1055
962
  };
1056
963
  }
@@ -1089,20 +996,12 @@ function createErrorMiddleware(options) {
1089
996
  };
1090
997
  }
1091
998
 
1092
- let result;
1093
- const cache = responseCache();
1094
999
  async function executeRequest({
1095
1000
  url,
1096
1001
  httpClient,
1097
1002
  clientOptions
1098
1003
  }) {
1099
1004
  let timer;
1100
-
1101
- // don't make further api calls
1102
- if (clientOptions.request['continue']) {
1103
- delete clientOptions.request['continue'];
1104
- return cache.get();
1105
- }
1106
1005
  const {
1107
1006
  timeout,
1108
1007
  request,
@@ -1129,22 +1028,19 @@ async function executeRequest({
1129
1028
  }
1130
1029
  if (response.statusCode >= 200 && response.statusCode < 300) {
1131
1030
  if (clientOptions.method == 'HEAD') {
1132
- const _result = {
1031
+ return {
1133
1032
  body: null,
1134
1033
  statusCode: response.statusCode,
1135
1034
  retryCount: response.retryCount,
1136
1035
  headers: getHeaders(response.headers)
1137
1036
  };
1138
- cache.set(_result);
1139
- return _result;
1140
1037
  }
1141
- result = {
1038
+ return {
1142
1039
  body: response.data,
1143
1040
  statusCode: response.statusCode,
1144
1041
  retryCount: response.retryCount,
1145
1042
  headers: getHeaders(response.headers)
1146
1043
  };
1147
- return result;
1148
1044
  }
1149
1045
  const error = createError({
1150
1046
  message: response?.data?.message || response?.message,
@@ -1164,18 +1060,17 @@ async function executeRequest({
1164
1060
  * handle non-ok (error) response
1165
1061
  * build error body
1166
1062
  */
1167
- result = {
1063
+ return {
1168
1064
  body: response.data,
1169
1065
  code: response.statusCode,
1170
1066
  statusCode: response.statusCode,
1171
1067
  headers: getHeaders(response.headers),
1172
1068
  error
1173
1069
  };
1174
- return result;
1175
1070
  } catch (e) {
1176
1071
  // We know that this is a network error
1177
1072
  const headers = includeResponseHeaders ? getHeaders(e.response?.headers) : null;
1178
- const statusCode = e.response?.status || e.response?.data || 0;
1073
+ const statusCode = e.response?.status || e.response?.data0 || 0;
1179
1074
  const message = e.response?.data?.message;
1180
1075
  const error = createError({
1181
1076
  statusCode,
@@ -1191,16 +1086,11 @@ async function executeRequest({
1191
1086
  uri: request.uri
1192
1087
  })
1193
1088
  });
1194
- result = {
1089
+ throw {
1195
1090
  body: error,
1196
1091
  error
1197
1092
  };
1198
- return result;
1199
1093
  } finally {
1200
- /**
1201
- * finally cache the response
1202
- */
1203
- cache.set(result);
1204
1094
  clearTimeout(timer);
1205
1095
  }
1206
1096
  }
@@ -1243,7 +1133,7 @@ function createHttpMiddleware$1(options) {
1243
1133
  // Ensure body is a string if content type is application/{json|graphql}
1244
1134
  const body = HEADERS_CONTENT_TYPES.indexOf(requestHeader['Content-Type']) > -1 && typeof request.body === 'string' || isBuffer(request.body) ? request.body : JSON.stringify(request.body || undefined);
1245
1135
  if (body && (typeof body === 'string' || isBuffer(body))) {
1246
- requestHeader['Content-Length'] = _.Buffer.byteLength(body).toString();
1136
+ requestHeader['Content-Length'] = byteLength(body);
1247
1137
  }
1248
1138
  const clientOptions = {
1249
1139
  enableRetry,
@@ -1276,9 +1166,6 @@ function createHttpMiddleware$1(options) {
1276
1166
  clientOptions,
1277
1167
  httpClient
1278
1168
  });
1279
- if (request['concurrent']) {
1280
- return response;
1281
- }
1282
1169
  const responseWithRequest = {
1283
1170
  ...request,
1284
1171
  includeOriginalRequest,
@@ -1311,48 +1198,56 @@ function createQueueMiddleware$1({
1311
1198
  }) {
1312
1199
  let runningCount = 0;
1313
1200
  const queue = [];
1314
- const dequeue = next => {
1201
+ const waitForSlot = () => {
1202
+ if (0 >= concurrency) return Promise.resolve();
1203
+ return new Promise(resolve => {
1204
+ const tryNext = () => {
1205
+ if (runningCount < concurrency) {
1206
+ runningCount++;
1207
+ resolve();
1208
+ } else {
1209
+ queue.push(tryNext);
1210
+ }
1211
+ };
1212
+ tryNext();
1213
+ });
1214
+ };
1215
+
1216
+ // Function to free up a slot after a request is completed
1217
+ const freeSlot = () => {
1315
1218
  runningCount--;
1316
- if (queue.length && runningCount <= concurrency) {
1317
- const nextTask = queue.shift();
1318
- runningCount++;
1319
- return next(nextTask.request);
1219
+ if (queue.length > 0) {
1220
+ const nextInQueue = queue.shift();
1221
+ if (nextInQueue) {
1222
+ nextInQueue();
1223
+ }
1320
1224
  }
1321
1225
  };
1322
- const enqueue = ({
1323
- request
1324
- }) => queue.push({
1325
- request
1326
- });
1327
1226
  return next => request => {
1328
- // wrap and override resolve and reject functions
1329
- const patchedRequest = {
1330
- ...request,
1331
- resolve(data) {
1332
- request.resolve(data);
1333
- dequeue(next);
1334
- },
1335
- reject(error) {
1336
- request.reject(error);
1337
- dequeue(next);
1338
- }
1339
- };
1227
+ return waitForSlot().then(() => {
1228
+ const patchedRequest = {
1229
+ ...request,
1230
+ resolve(data) {
1231
+ request.resolve(data);
1232
+ freeSlot();
1233
+ },
1234
+ reject(error) {
1235
+ request.reject(error);
1236
+ freeSlot();
1237
+ }
1238
+ };
1340
1239
 
1341
- // enqueue requests
1342
- enqueue({
1343
- request: patchedRequest
1240
+ // Process the next middleware
1241
+ return next(patchedRequest).finally(() => {
1242
+ freeSlot();
1243
+ });
1344
1244
  });
1345
- if (runningCount < concurrency) {
1346
- runningCount++;
1347
- const nextTask = queue.shift();
1348
- return next(nextTask.request);
1349
- }
1350
1245
  };
1351
1246
  }
1352
1247
 
1353
1248
  var packageJson = {
1354
1249
  name: "@commercetools/ts-client",
1355
- version: "2.1.0-alpha.0",
1250
+ version: "2.1.0",
1356
1251
  engines: {
1357
1252
  node: ">=14"
1358
1253
  },
@@ -1386,16 +1281,11 @@ var packageJson = {
1386
1281
  },
1387
1282
  dependencies: {
1388
1283
  "abort-controller": "3.0.0",
1389
- buffer: "^6.0.3",
1390
- "node-fetch": "^2.6.1",
1391
- uuid: "10.0.0"
1284
+ "node-fetch": "^2.6.1"
1392
1285
  },
1393
1286
  files: [
1394
1287
  "dist",
1395
- "CHANGELOG.md",
1396
- "LICENSE",
1397
- "README.md",
1398
- "package.json"
1288
+ "CHANGELOG.md"
1399
1289
  ],
1400
1290
  author: "Chukwuemeka Ajima <meeky.ae@gmail.com>",
1401
1291
  main: "dist/commercetools-ts-client.cjs.js",
@@ -1550,6 +1440,7 @@ function process$1(request, fn, processOpt) {
1550
1440
  function createClient(middlewares) {
1551
1441
  _options = middlewares;
1552
1442
  validateClient(middlewares);
1443
+ let _maskSensitiveHeaderData = false;
1553
1444
  const resolver = {
1554
1445
  async resolve(rs) {
1555
1446
  const {
@@ -1562,25 +1453,20 @@ function createClient(middlewares) {
1562
1453
  retryCount,
1563
1454
  ...rest
1564
1455
  } = response;
1565
- // _maskSensitiveHeaderData = maskSensitiveHeaderData
1566
-
1456
+ _maskSensitiveHeaderData = maskSensitiveHeaderData;
1567
1457
  const res = {
1568
1458
  body: null,
1569
1459
  error: null,
1570
1460
  reject: rs.reject,
1571
1461
  resolve: rs.resolve,
1572
1462
  ...rest,
1463
+ ...(includeOriginalRequest ? {
1464
+ originalRequest: request
1465
+ } : {}),
1573
1466
  ...(response?.retryCount ? {
1574
1467
  retryCount: response.retryCount
1575
- } : {}),
1576
- ...(includeOriginalRequest ? {
1577
- originalRequest: maskSensitiveHeaderData ? maskAuthData(request) : request
1578
1468
  } : {})
1579
1469
  };
1580
- if (res.error) {
1581
- rs.reject(res.error);
1582
- }
1583
- rs.resolve(res);
1584
1470
  return res;
1585
1471
  }
1586
1472
  };
@@ -1590,11 +1476,20 @@ function createClient(middlewares) {
1590
1476
  execute(request) {
1591
1477
  validate('exec', request);
1592
1478
  return new Promise(async (resolve, reject) => {
1593
- return dispatch({
1594
- reject,
1595
- resolve,
1596
- ...request
1597
- });
1479
+ try {
1480
+ const response = await dispatch({
1481
+ reject,
1482
+ resolve,
1483
+ ...request
1484
+ });
1485
+ if (response.error) return reject(response.error);
1486
+ if (response.originalRequest && _maskSensitiveHeaderData) {
1487
+ response.originalRequest = maskAuthData(response.originalRequest);
1488
+ }
1489
+ resolve(response);
1490
+ } catch (err) {
1491
+ reject(err);
1492
+ }
1598
1493
  });
1599
1494
  }
1600
1495
  };