@commercetools/sdk-client-v2 0.1.0 → 1.0.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.
Files changed (33) hide show
  1. package/CHANGELOG.md +24 -1
  2. package/README.md +196 -1
  3. package/dist/commercetools-sdk-client-v2.browser.cjs.js +901 -1234
  4. package/dist/commercetools-sdk-client-v2.browser.esm.js +901 -1233
  5. package/dist/commercetools-sdk-client-v2.cjs.dev.js +901 -1234
  6. package/dist/commercetools-sdk-client-v2.cjs.prod.js +901 -1234
  7. package/dist/commercetools-sdk-client-v2.esm.js +901 -1233
  8. package/dist/commercetools-sdk-client-v2.umd.js +2 -0
  9. package/dist/commercetools-sdk-client-v2.umd.js.LICENSE.txt +15 -0
  10. package/dist/declarations/src/client-builder/ClientBuilder.d.ts +26 -26
  11. package/dist/declarations/src/http-user-agent/create-user-agent.d.ts +2 -2
  12. package/dist/declarations/src/index.d.ts +14 -15
  13. package/dist/declarations/src/sdk-client/allowed-methods.d.ts +2 -2
  14. package/dist/declarations/src/sdk-client/client.d.ts +2 -2
  15. package/dist/declarations/src/sdk-client/errors.d.ts +10 -10
  16. package/dist/declarations/src/sdk-client/validate.d.ts +7 -7
  17. package/dist/declarations/src/sdk-middleware-auth/anonymous-session-flow.d.ts +2 -2
  18. package/dist/declarations/src/sdk-middleware-auth/base-auth-flow.d.ts +2 -2
  19. package/dist/declarations/src/sdk-middleware-auth/build-requests.d.ts +11 -11
  20. package/dist/declarations/src/sdk-middleware-auth/build-token-cache-key.d.ts +2 -2
  21. package/dist/declarations/src/sdk-middleware-auth/client-credentials-flow.d.ts +2 -2
  22. package/dist/declarations/src/sdk-middleware-auth/existing-token.d.ts +2 -2
  23. package/dist/declarations/src/sdk-middleware-auth/index.d.ts +5 -5
  24. package/dist/declarations/src/sdk-middleware-auth/password-flow.d.ts +2 -2
  25. package/dist/declarations/src/sdk-middleware-auth/refresh-token-flow.d.ts +2 -2
  26. package/dist/declarations/src/sdk-middleware-auth/utils.d.ts +4 -4
  27. package/dist/declarations/src/sdk-middleware-correlation-id/correlation-id.d.ts +2 -2
  28. package/dist/declarations/src/sdk-middleware-http/http.d.ts +2 -2
  29. package/dist/declarations/src/sdk-middleware-http/parse-headers.d.ts +2 -2
  30. package/dist/declarations/src/sdk-middleware-logger/logger.d.ts +2 -2
  31. package/dist/declarations/src/sdk-middleware-queue/queue.d.ts +2 -2
  32. package/dist/declarations/src/sdk-middleware-user-agent/user-agent.d.ts +2 -2
  33. package/package.json +8 -8
@@ -1,100 +1,5 @@
1
- import qs from 'querystring';
2
1
  import fetch$1 from 'node-fetch';
3
-
4
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
5
- try {
6
- var info = gen[key](arg);
7
- var value = info.value;
8
- } catch (error) {
9
- reject(error);
10
- return;
11
- }
12
-
13
- if (info.done) {
14
- resolve(value);
15
- } else {
16
- Promise.resolve(value).then(_next, _throw);
17
- }
18
- }
19
-
20
- function _asyncToGenerator(fn) {
21
- return function () {
22
- var self = this,
23
- args = arguments;
24
- return new Promise(function (resolve, reject) {
25
- var gen = fn.apply(self, args);
26
-
27
- function _next(value) {
28
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
29
- }
30
-
31
- function _throw(err) {
32
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
33
- }
34
-
35
- _next(undefined);
36
- });
37
- };
38
- }
39
-
40
- function _arrayWithHoles(arr) {
41
- if (Array.isArray(arr)) return arr;
42
- }
43
-
44
- function _iterableToArrayLimit(arr, i) {
45
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
46
-
47
- if (_i == null) return;
48
- var _arr = [];
49
- var _n = true;
50
- var _d = false;
51
-
52
- var _s, _e;
53
-
54
- try {
55
- for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
56
- _arr.push(_s.value);
57
-
58
- if (i && _arr.length === i) break;
59
- }
60
- } catch (err) {
61
- _d = true;
62
- _e = err;
63
- } finally {
64
- try {
65
- if (!_n && _i["return"] != null) _i["return"]();
66
- } finally {
67
- if (_d) throw _e;
68
- }
69
- }
70
-
71
- return _arr;
72
- }
73
-
74
- function _arrayLikeToArray(arr, len) {
75
- if (len == null || len > arr.length) len = arr.length;
76
-
77
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
78
-
79
- return arr2;
80
- }
81
-
82
- function _unsupportedIterableToArray(o, minLen) {
83
- if (!o) return;
84
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
85
- var n = Object.prototype.toString.call(o).slice(8, -1);
86
- if (n === "Object" && o.constructor) n = o.constructor.name;
87
- if (n === "Map" || n === "Set") return Array.from(o);
88
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
89
- }
90
-
91
- function _nonIterableRest() {
92
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
93
- }
94
-
95
- function _slicedToArray(arr, i) {
96
- return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
97
- }
2
+ import qs from 'querystring';
98
3
 
99
4
  function _defineProperty(obj, key, value) {
100
5
  if (key in obj) {
@@ -111,88 +16,24 @@ function _defineProperty(obj, key, value) {
111
16
  return obj;
112
17
  }
113
18
 
114
- function ownKeys(object, enumerableOnly) {
115
- var keys = Object.keys(object);
116
-
117
- if (Object.getOwnPropertySymbols) {
118
- var symbols = Object.getOwnPropertySymbols(object);
119
-
120
- if (enumerableOnly) {
121
- symbols = symbols.filter(function (sym) {
122
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
123
- });
124
- }
125
-
126
- keys.push.apply(keys, symbols);
127
- }
128
-
129
- return keys;
130
- }
131
-
132
- function _objectSpread2(target) {
133
- for (var i = 1; i < arguments.length; i++) {
134
- var source = arguments[i] != null ? arguments[i] : {};
135
-
136
- if (i % 2) {
137
- ownKeys(Object(source), true).forEach(function (key) {
138
- _defineProperty(target, key, source[key]);
139
- });
140
- } else if (Object.getOwnPropertyDescriptors) {
141
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
142
- } else {
143
- ownKeys(Object(source)).forEach(function (key) {
144
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
145
- });
146
- }
147
- }
148
-
149
- return target;
150
- }
151
-
152
- function _arrayWithoutHoles(arr) {
153
- if (Array.isArray(arr)) return _arrayLikeToArray(arr);
154
- }
155
-
156
- function _iterableToArray(iter) {
157
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
158
- }
159
-
160
- function _nonIterableSpread() {
161
- throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
162
- }
163
-
164
- function _toConsumableArray(arr) {
165
- return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
166
- }
167
-
168
19
  var METHODS = ['ACL', 'BIND', 'CHECKOUT', 'CONNECT', 'COPY', 'DELETE', 'GET', 'HEAD', 'LINK', 'LOCK', 'M-SEARCH', 'MERGE', 'MKACTIVITY', 'MKCALENDAR', 'MKCOL', 'MOVE', 'NOTIFY', 'OPTIONS', 'PATCH', 'POST', 'PROPFIND', 'PROPPATCH', 'PURGE', 'PUT', 'REBIND', 'REPORT', 'SEARCH', 'SOURCE', 'SUBSCRIBE', 'TRACE', 'UNBIND', 'UNLINK', 'UNLOCK', 'UNSUBSCRIBE'];
169
20
 
170
21
  /**
171
22
  * @throws {Error}
172
23
  */
173
- function validate(funcName, request) {
174
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
175
- allowedMethods: METHODS
176
- };
177
- if (!request) throw new Error("The \"".concat(funcName, "\" function requires a \"Request\" object as an argument. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest"));
178
- if (typeof request.uri !== 'string') throw new Error("The \"".concat(funcName, "\" Request object requires a valid uri. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest"));
179
- if (!options.allowedMethods.includes(request.method)) throw new Error("The \"".concat(funcName, "\" Request object requires a valid method. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest"));
180
- }
181
24
 
182
- function compose() {
183
- for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {
184
- funcs[_key] = arguments[_key];
185
- }
25
+ function validate(funcName, request, options = {
26
+ allowedMethods: METHODS
27
+ }) {
28
+ if (!request) throw new Error(`The "${funcName}" function requires a "Request" object as an argument. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest`);
29
+ if (typeof request.uri !== 'string') throw new Error(`The "${funcName}" Request object requires a valid uri. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest`);
30
+ if (!options.allowedMethods.includes(request.method)) throw new Error(`The "${funcName}" Request object requires a valid method. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest`);
31
+ }
186
32
 
187
- funcs = funcs.filter(function (func) {
188
- return typeof func === 'function';
189
- });
33
+ function compose(...funcs) {
34
+ funcs = funcs.filter(func => typeof func === 'function');
190
35
  if (funcs.length === 1) return funcs[0];
191
- return funcs.reduce(function (a, b) {
192
- return function () {
193
- return a(b.apply(void 0, arguments));
194
- };
195
- });
36
+ return funcs.reduce((a, b) => (...args) => a(b(...args)));
196
37
  }
197
38
 
198
39
  function createClient(options) {
@@ -203,16 +44,16 @@ function createClient(options) {
203
44
  /**
204
45
  * Given a request object,
205
46
  */
206
- execute: function execute(request) {
47
+ execute(request) {
207
48
  validate('exec', request);
208
- return new Promise(function (resolve, reject) {
209
- var resolver = function resolver(rq, rs) {
49
+ return new Promise((resolve, reject) => {
50
+ const resolver = (rq, rs) => {
210
51
  // Note: pick the promise `resolve` and `reject` function from
211
52
  // the response object. This is not necessary the same function
212
53
  // given from the `new Promise` constructor, as middlewares could
213
54
  // override those functions for custom behaviours.
214
55
  if (rs.error) rs.reject(rs.error);else {
215
- var resObj = {
56
+ const resObj = {
216
57
  body: rs.body || {},
217
58
  statusCode: rs.statusCode
218
59
  };
@@ -222,280 +63,109 @@ function createClient(options) {
222
63
  }
223
64
  };
224
65
 
225
- var dispatch = compose.apply(void 0, _toConsumableArray(options.middlewares))(resolver);
66
+ const dispatch = compose(...options.middlewares)(resolver);
226
67
  dispatch(request, // Initial response shape
227
68
  {
228
- resolve: resolve,
229
- reject: reject,
69
+ resolve,
70
+ reject,
230
71
  body: undefined,
231
72
  error: undefined
232
73
  });
233
74
  });
234
75
  },
235
- process: function process(request, fn, processOpt) {
236
- var _this = this;
237
76
 
77
+ process(request, fn, processOpt) {
238
78
  validate('process', request, {
239
79
  allowedMethods: ['GET']
240
80
  });
241
81
  if (typeof fn !== 'function') throw new Error('The "process" function accepts a "Function" as a second argument that returns a Promise. See https://commercetools.github.io/nodejs/sdk/api/sdkClient.html#processrequest-processfn-options'); // Set default process options
242
82
 
243
- var opt = _objectSpread2({
83
+ const opt = {
244
84
  total: Number.POSITIVE_INFINITY,
245
- accumulate: true
246
- }, processOpt);
247
-
248
- return new Promise(function (resolve, reject) {
249
- var _path,
85
+ accumulate: true,
86
+ ...processOpt
87
+ };
88
+ return new Promise((resolve, reject) => {
89
+ let _path,
250
90
  _queryString = '';
251
91
 
252
92
  if (request && request.uri) {
253
- var _request$uri$split = request.uri.split('?'),
254
- _request$uri$split2 = _slicedToArray(_request$uri$split, 2),
255
- path = _request$uri$split2[0],
256
- queryString = _request$uri$split2[1];
257
-
93
+ const [path, queryString] = request.uri.split('?');
258
94
  _path = path;
259
95
  _queryString = queryString;
260
96
  }
261
97
 
262
- var requestQuery = _objectSpread2({}, qs.parse(_queryString));
263
-
264
- var query = _objectSpread2({
98
+ const requestQuery = { ...qs.parse(_queryString)
99
+ };
100
+ const query = {
265
101
  // defaults
266
- limit: 20
267
- }, requestQuery);
268
-
269
- var hasFirstPageBeenProcessed = false;
270
- var itemsToGet = opt.total;
271
-
272
- var processPage = /*#__PURE__*/function () {
273
- var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(lastId) {
274
- var acc,
275
- limit,
276
- originalQueryString,
277
- enhancedQuery,
278
- enhancedQueryString,
279
- enhancedRequest,
280
- payload,
281
- _payload$body,
282
- results,
283
- resultsLength,
284
- result,
285
- accumulated,
286
- last,
287
- newLastId,
288
- _args = arguments;
289
-
290
- return regeneratorRuntime.wrap(function _callee$(_context) {
291
- while (1) {
292
- switch (_context.prev = _context.next) {
293
- case 0:
294
- acc = _args.length > 1 && _args[1] !== undefined ? _args[1] : [];
295
- // Use the lesser value between limit and itemsToGet in query
296
- limit = query.limit < itemsToGet ? query.limit : itemsToGet;
297
- originalQueryString = qs.stringify(_objectSpread2(_objectSpread2({}, query), {}, {
298
- limit: limit
299
- }));
300
- enhancedQuery = _objectSpread2({
301
- sort: 'id asc',
302
- withTotal: false
303
- }, lastId ? {
304
- where: "id > \"".concat(lastId, "\"")
305
- } : {});
306
- enhancedQueryString = qs.stringify(enhancedQuery);
307
- enhancedRequest = _objectSpread2(_objectSpread2({}, request), {}, {
308
- uri: "".concat(_path, "?").concat(enhancedQueryString, "&").concat(originalQueryString)
309
- });
310
- _context.prev = 6;
311
- _context.next = 9;
312
- return _this.execute(enhancedRequest);
313
-
314
- case 9:
315
- payload = _context.sent;
316
- _payload$body = payload.body, results = _payload$body.results, resultsLength = _payload$body.count;
317
-
318
- if (!(!resultsLength && hasFirstPageBeenProcessed)) {
319
- _context.next = 13;
320
- break;
321
- }
322
-
323
- return _context.abrupt("return", resolve(acc || []));
324
-
325
- case 13:
326
- _context.next = 15;
327
- return Promise.resolve(fn(payload));
328
-
329
- case 15:
330
- result = _context.sent;
331
- hasFirstPageBeenProcessed = true;
332
- if (opt.accumulate) accumulated = acc.concat(result || []);
333
- itemsToGet -= resultsLength; // If there are no more items to get, it means the total number
334
- // of items in the original request have been fetched so we
335
- // resolve the promise.
336
- // Also, if we get less results in a page then the limit set it
337
- // means that there are no more pages and that we can finally
338
- // resolve the promise.
339
-
340
- if (!(resultsLength < query.limit || !itemsToGet)) {
341
- _context.next = 21;
342
- break;
343
- }
344
-
345
- return _context.abrupt("return", resolve(accumulated || []));
346
-
347
- case 21:
348
- last = results[resultsLength - 1];
349
- newLastId = last && last.id;
350
- processPage(newLastId, accumulated);
351
- _context.next = 29;
352
- break;
353
-
354
- case 26:
355
- _context.prev = 26;
356
- _context.t0 = _context["catch"](6);
357
- reject(_context.t0);
358
-
359
- case 29:
360
- case "end":
361
- return _context.stop();
362
- }
363
- }
364
- }, _callee, null, [[6, 26]]);
365
- }));
366
-
367
- return function processPage(_x) {
368
- return _ref.apply(this, arguments);
102
+ limit: 20,
103
+ // merge given query params
104
+ ...requestQuery
105
+ };
106
+ let hasFirstPageBeenProcessed = false;
107
+ let itemsToGet = opt.total;
108
+
109
+ const processPage = async (lastId, acc = []) => {
110
+ // Use the lesser value between limit and itemsToGet in query
111
+ const limit = query.limit < itemsToGet ? query.limit : itemsToGet;
112
+ const originalQueryString = qs.stringify({ ...query,
113
+ limit
114
+ });
115
+ const enhancedQuery = {
116
+ sort: 'id asc',
117
+ withTotal: false,
118
+ ...(lastId ? {
119
+ where: `id > "${lastId}"`
120
+ } : {})
121
+ };
122
+ const enhancedQueryString = qs.stringify(enhancedQuery);
123
+ const enhancedRequest = { ...request,
124
+ uri: `${_path}?${enhancedQueryString}&${originalQueryString}`
369
125
  };
370
- }(); // Start iterating through pages
371
-
372
-
373
- processPage();
374
- });
375
- }
376
- };
377
- }
378
-
379
- function defineError(statusCode, message) {
380
- var meta = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
381
- this.status = this.statusCode = this.code = statusCode;
382
- this.message = message;
383
- Object.assign(this, meta);
384
- this.name = this.constructor.name;
385
- this.constructor.prototype.__proto__ = Error.prototype;
386
- if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
387
- }
388
-
389
- function NetworkError() {
390
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
391
- args[_key] = arguments[_key];
392
- }
393
-
394
- defineError.call.apply(defineError, [this, 0
395
- /* special code to indicate network errors */
396
- ].concat(args));
397
- }
398
- function HttpError() {
399
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
400
- args[_key2] = arguments[_key2];
401
- }
402
-
403
- defineError.call.apply(defineError, [this].concat(args));
404
- }
405
- function BadRequest() {
406
- for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
407
- args[_key3] = arguments[_key3];
408
- }
409
-
410
- defineError.call.apply(defineError, [this, 400].concat(args));
411
- }
412
- function Unauthorized() {
413
- for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
414
- args[_key4] = arguments[_key4];
415
- }
416
-
417
- defineError.call.apply(defineError, [this, 401].concat(args));
418
- }
419
- function Forbidden() {
420
- for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
421
- args[_key5] = arguments[_key5];
422
- }
423
-
424
- defineError.call.apply(defineError, [this, 403].concat(args));
425
- }
426
- function NotFound() {
427
- for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
428
- args[_key6] = arguments[_key6];
429
- }
430
-
431
- defineError.call.apply(defineError, [this, 404].concat(args));
432
- }
433
- function ConcurrentModification() {
434
- for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
435
- args[_key7] = arguments[_key7];
436
- }
437
-
438
- defineError.call.apply(defineError, [this, 409].concat(args));
439
- }
440
- function InternalServerError() {
441
- for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
442
- args[_key8] = arguments[_key8];
443
- }
444
-
445
- defineError.call.apply(defineError, [this, 500].concat(args));
446
- }
447
- function ServiceUnavailable() {
448
- for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) {
449
- args[_key9] = arguments[_key9];
450
- }
451
-
452
- defineError.call.apply(defineError, [this, 503].concat(args));
453
- }
454
- function getErrorByCode(code) {
455
- switch (code) {
456
- case 0:
457
- return NetworkError;
458
-
459
- case 400:
460
- return BadRequest;
461
126
 
462
- case 401:
463
- return Unauthorized;
127
+ try {
128
+ const payload = await this.execute(enhancedRequest);
129
+ const {
130
+ results,
131
+ count: resultsLength
132
+ } = payload.body;
464
133
 
465
- case 403:
466
- return Forbidden;
134
+ if (!resultsLength && hasFirstPageBeenProcessed) {
135
+ return resolve(acc || []);
136
+ }
467
137
 
468
- case 404:
469
- return NotFound;
138
+ const result = await Promise.resolve(fn(payload));
139
+ let accumulated;
140
+ hasFirstPageBeenProcessed = true;
141
+ if (opt.accumulate) accumulated = acc.concat(result || []);
142
+ itemsToGet -= resultsLength; // If there are no more items to get, it means the total number
143
+ // of items in the original request have been fetched so we
144
+ // resolve the promise.
145
+ // Also, if we get less results in a page then the limit set it
146
+ // means that there are no more pages and that we can finally
147
+ // resolve the promise.
148
+
149
+ if (resultsLength < query.limit || !itemsToGet) {
150
+ return resolve(accumulated || []);
151
+ }
470
152
 
471
- case 409:
472
- return ConcurrentModification;
153
+ const last = results[resultsLength - 1];
154
+ const newLastId = last && last.id;
155
+ processPage(newLastId, accumulated);
156
+ } catch (error) {
157
+ reject(error);
158
+ }
159
+ }; // Start iterating through pages
473
160
 
474
- case 500:
475
- return InternalServerError;
476
161
 
477
- case 503:
478
- return ServiceUnavailable;
162
+ processPage();
163
+ });
164
+ }
479
165
 
480
- default:
481
- return undefined;
482
- }
166
+ };
483
167
  }
484
168
 
485
- var errors = /*#__PURE__*/Object.freeze({
486
- __proto__: null,
487
- NetworkError: NetworkError,
488
- HttpError: HttpError,
489
- BadRequest: BadRequest,
490
- Unauthorized: Unauthorized,
491
- Forbidden: Forbidden,
492
- NotFound: NotFound,
493
- ConcurrentModification: ConcurrentModification,
494
- InternalServerError: InternalServerError,
495
- ServiceUnavailable: ServiceUnavailable,
496
- 'default': getErrorByCode
497
- });
498
-
499
169
  // POST https://{host}/oauth/token?grant_type=client_credentials&scope={scope}
500
170
  // Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
501
171
  function buildRequestForClientCredentialsFlow(options) {
@@ -503,21 +173,22 @@ function buildRequestForClientCredentialsFlow(options) {
503
173
  if (!options.host) throw new Error('Missing required option (host)');
504
174
  if (!options.projectKey) throw new Error('Missing required option (projectKey)');
505
175
  if (!options.credentials) throw new Error('Missing required option (credentials)');
506
- var _options$credentials = options.credentials,
507
- clientId = _options$credentials.clientId,
508
- clientSecret = _options$credentials.clientSecret;
176
+ const {
177
+ clientId,
178
+ clientSecret
179
+ } = options.credentials;
509
180
  if (!(clientId && clientSecret)) throw new Error('Missing required credentials (clientId, clientSecret)');
510
- var scope = options.scopes ? options.scopes.join(' ') : undefined;
511
- var basicAuth = Buffer.from("".concat(clientId, ":").concat(clientSecret)).toString('base64'); // This is mostly useful for internal testing purposes to be able to check
181
+ const scope = options.scopes ? options.scopes.join(' ') : undefined;
182
+ const basicAuth = Buffer.from(`${clientId}:${clientSecret}`).toString('base64'); // This is mostly useful for internal testing purposes to be able to check
512
183
  // other oauth endpoints.
513
184
 
514
- var oauthUri = options.oauthUri || '/oauth/token';
515
- var url = options.host.replace(/\/$/, '') + oauthUri;
516
- var body = "grant_type=client_credentials".concat(scope ? "&scope=".concat(scope) : '');
185
+ const oauthUri = options.oauthUri || '/oauth/token';
186
+ const url = options.host.replace(/\/$/, '') + oauthUri;
187
+ const body = `grant_type=client_credentials${scope ? `&scope=${scope}` : ''}`;
517
188
  return {
518
- basicAuth: basicAuth,
519
- url: url,
520
- body: body
189
+ basicAuth,
190
+ url,
191
+ body
521
192
  };
522
193
  }
523
194
  function buildRequestForPasswordFlow(options) {
@@ -525,31 +196,34 @@ function buildRequestForPasswordFlow(options) {
525
196
  if (!options.host) throw new Error('Missing required option (host)');
526
197
  if (!options.projectKey) throw new Error('Missing required option (projectKey)');
527
198
  if (!options.credentials) throw new Error('Missing required option (credentials)');
528
- var _options$credentials2 = options.credentials,
529
- clientId = _options$credentials2.clientId,
530
- clientSecret = _options$credentials2.clientSecret,
531
- user = _options$credentials2.user;
532
- var pKey = options.projectKey;
199
+ const {
200
+ clientId,
201
+ clientSecret,
202
+ user
203
+ } = options.credentials;
204
+ const pKey = options.projectKey;
533
205
  if (!(clientId && clientSecret && user)) throw new Error('Missing required credentials (clientId, clientSecret, user)');
534
- var username = user.username,
535
- password = user.password;
206
+ const {
207
+ username,
208
+ password
209
+ } = user;
536
210
  if (!(username && password)) throw new Error('Missing required user credentials (username, password)');
537
- var scope = (options.scopes || []).join(' ');
538
- var scopeStr = scope ? "&scope=".concat(scope) : '';
539
- var basicAuth = Buffer.from("".concat(clientId, ":").concat(clientSecret)).toString('base64');
211
+ const scope = (options.scopes || []).join(' ');
212
+ const scopeStr = scope ? `&scope=${scope}` : '';
213
+ const basicAuth = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
540
214
  /**
541
215
  * This is mostly useful for internal testing purposes to be able to check
542
216
  * other oauth endpoints.
543
217
  */
544
218
 
545
- var oauthUri = options.oauthUri || "/oauth/".concat(pKey, "/customers/token");
546
- var url = options.host.replace(/\/$/, '') + oauthUri; // encode username and password as requested by platform
219
+ const oauthUri = options.oauthUri || `/oauth/${pKey}/customers/token`;
220
+ const url = options.host.replace(/\/$/, '') + oauthUri; // encode username and password as requested by platform
547
221
 
548
- var body = "grant_type=password&username=".concat(encodeURIComponent(username), "&password=").concat(encodeURIComponent(password)).concat(scopeStr);
222
+ const body = `grant_type=password&username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}${scopeStr}`;
549
223
  return {
550
- basicAuth: basicAuth,
551
- url: url,
552
- body: body
224
+ basicAuth,
225
+ url,
226
+ body
553
227
  };
554
228
  }
555
229
  function buildRequestForRefreshTokenFlow(options) {
@@ -558,46 +232,40 @@ function buildRequestForRefreshTokenFlow(options) {
558
232
  if (!options.projectKey) throw new Error('Missing required option (projectKey)');
559
233
  if (!options.credentials) throw new Error('Missing required option (credentials)');
560
234
  if (!options.refreshToken) throw new Error('Missing required option (refreshToken)');
561
- var _options$credentials3 = options.credentials,
562
- clientId = _options$credentials3.clientId,
563
- clientSecret = _options$credentials3.clientSecret;
235
+ const {
236
+ clientId,
237
+ clientSecret
238
+ } = options.credentials;
564
239
  if (!(clientId && clientSecret)) throw new Error('Missing required credentials (clientId, clientSecret)');
565
- var basicAuth = Buffer.from("".concat(clientId, ":").concat(clientSecret)).toString('base64'); // This is mostly useful for internal testing purposes to be able to check
240
+ const basicAuth = Buffer.from(`${clientId}:${clientSecret}`).toString('base64'); // This is mostly useful for internal testing purposes to be able to check
566
241
  // other oauth endpoints.
567
242
 
568
- var oauthUri = options.oauthUri || '/oauth/token';
569
- var url = options.host.replace(/\/$/, '') + oauthUri;
570
- var body = "grant_type=refresh_token&refresh_token=".concat(encodeURIComponent(options.refreshToken));
243
+ const oauthUri = options.oauthUri || '/oauth/token';
244
+ const url = options.host.replace(/\/$/, '') + oauthUri;
245
+ const body = `grant_type=refresh_token&refresh_token=${encodeURIComponent(options.refreshToken)}`;
571
246
  return {
572
- basicAuth: basicAuth,
573
- url: url,
574
- body: body
247
+ basicAuth,
248
+ url,
249
+ body
575
250
  };
576
251
  }
577
252
  function buildRequestForAnonymousSessionFlow(options) {
578
253
  if (!options) throw new Error('Missing required options');
579
254
  if (!options.projectKey) throw new Error('Missing required option (projectKey)');
580
- var pKey = options.projectKey;
581
- options.oauthUri = options.oauthUri || "/oauth/".concat(pKey, "/anonymous/token");
582
- var result = buildRequestForClientCredentialsFlow(options);
583
- if (options.credentials.anonymousId) result.body += "&anonymous_id=".concat(options.credentials.anonymousId);
584
- return _objectSpread2({}, result);
585
- }
586
-
587
- function buildTokenCacheKey(options) {
588
- return {
589
- clientId: options.credentials.clientId,
590
- host: options.host,
591
- projectKey: options.projectKey
255
+ const pKey = options.projectKey;
256
+ options.oauthUri = options.oauthUri || `/oauth/${pKey}/anonymous/token`;
257
+ const result = buildRequestForClientCredentialsFlow(options);
258
+ if (options.credentials.anonymousId) result.body += `&anonymous_id=${options.credentials.anonymousId}`;
259
+ return { ...result
592
260
  };
593
261
  }
594
262
 
595
263
  function mergeAuthHeader(token, req) {
596
- return _objectSpread2(_objectSpread2({}, req), {}, {
597
- headers: _objectSpread2(_objectSpread2({}, req.headers), {}, {
598
- Authorization: "Bearer ".concat(token)
599
- })
600
- });
264
+ return { ...req,
265
+ headers: { ...req.headers,
266
+ Authorization: `Bearer ${token}`
267
+ }
268
+ };
601
269
  }
602
270
 
603
271
  function calculateExpirationTime(expiresIn) {
@@ -605,136 +273,108 @@ function calculateExpirationTime(expiresIn) {
605
273
  expiresIn * 1000 - 2 * 60 * 60 * 1000;
606
274
  }
607
275
 
608
- function executeRequest(_x) {
609
- return _executeRequest.apply(this, arguments);
610
- }
611
-
612
- function _executeRequest() {
613
- _executeRequest = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) {
614
- var fetcher, url, basicAuth, body, tokenCache, requestState, pendingTasks, response, tokenCacheKey, _res, _yield$_res$json, token, expiresIn, refreshToken, expirationTime, executionQueue, parsed, text, error;
615
-
616
- return regeneratorRuntime.wrap(function _callee$(_context) {
617
- while (1) {
618
- switch (_context.prev = _context.next) {
619
- case 0:
620
- fetcher = _ref.fetcher, url = _ref.url, basicAuth = _ref.basicAuth, body = _ref.body, tokenCache = _ref.tokenCache, requestState = _ref.requestState, pendingTasks = _ref.pendingTasks, response = _ref.response, tokenCacheKey = _ref.tokenCacheKey;
621
- _context.prev = 1;
622
- _context.next = 4;
623
- return fetcher(url, {
624
- method: 'POST',
625
- headers: {
626
- Authorization: "Basic ".concat(basicAuth),
627
- 'Content-Length': Buffer.byteLength(body).toString(),
628
- 'Content-Type': 'application/x-www-form-urlencoded'
629
- },
630
- body: body
631
- });
276
+ async function executeRequest({
277
+ fetcher,
278
+ url,
279
+ basicAuth,
280
+ body,
281
+ tokenCache,
282
+ requestState,
283
+ pendingTasks,
284
+ response,
285
+ tokenCacheKey
286
+ }) {
287
+ try {
288
+ const _res = await fetcher(url, {
289
+ method: 'POST',
290
+ headers: {
291
+ Authorization: `Basic ${basicAuth}`,
292
+ 'Content-Length': Buffer.byteLength(body).toString(),
293
+ 'Content-Type': 'application/x-www-form-urlencoded'
294
+ },
295
+ body
296
+ });
632
297
 
633
- case 4:
634
- _res = _context.sent;
298
+ if (_res.ok) {
299
+ const {
300
+ access_token: token,
301
+ expires_in: expiresIn,
302
+ refresh_token: refreshToken
303
+ } = await _res.json();
304
+ const expirationTime = calculateExpirationTime(expiresIn); // cache new generated token
305
+
306
+ tokenCache.set({
307
+ token,
308
+ expirationTime,
309
+ refreshToken
310
+ }, tokenCacheKey); // Dispatch all pending requests
311
+
312
+ requestState.set(false);
313
+ /**
314
+ * Freeze and copy pending queue, reset original one for accepting
315
+ * new pending tasks
316
+ */
635
317
 
636
- if (!_res.ok) {
637
- _context.next = 19;
638
- break;
639
- }
318
+ const executionQueue = pendingTasks.slice();
319
+ pendingTasks = [];
320
+ executionQueue.forEach(task => {
321
+ // Assign the new token in the request header
322
+ const requestWithAuth = mergeAuthHeader(token, task.request);
323
+ /**
324
+ * console.log('test', cache, pendingTasks)
325
+ * Continue by calling the task's own next function
326
+ */
327
+
328
+ task.next(requestWithAuth, task.response);
329
+ });
330
+ return;
331
+ } // Handle error response
640
332
 
641
- _context.next = 8;
642
- return _res.json();
643
-
644
- case 8:
645
- _yield$_res$json = _context.sent;
646
- token = _yield$_res$json.access_token;
647
- expiresIn = _yield$_res$json.expires_in;
648
- refreshToken = _yield$_res$json.refresh_token;
649
- expirationTime = calculateExpirationTime(expiresIn); // cache new generated token
650
-
651
- tokenCache.set({
652
- token: token,
653
- expirationTime: expirationTime,
654
- refreshToken: refreshToken
655
- }, tokenCacheKey); // Dispatch all pending requests
656
-
657
- requestState.set(false);
658
- /**
659
- * Freeze and copy pending queue, reset original one for accepting
660
- * new pending tasks
661
- */
662
-
663
- executionQueue = pendingTasks.slice();
664
- pendingTasks = [];
665
- executionQueue.forEach(function (task) {
666
- // Assign the new token in the request header
667
- var requestWithAuth = mergeAuthHeader(token, task.request);
668
- /**
669
- * console.log('test', cache, pendingTasks)
670
- * Continue by calling the task's own next function
671
- */
672
-
673
- task.next(requestWithAuth, task.response);
674
- });
675
- return _context.abrupt("return");
676
333
 
677
- case 19:
678
- _context.next = 21;
679
- return _res.text();
334
+ let parsed;
335
+ const text = await _res.text();
680
336
 
681
- case 21:
682
- text = _context.sent;
337
+ try {
338
+ parsed = JSON.parse(text);
339
+ } catch (error) {
340
+ /* noop */
341
+ }
683
342
 
684
- try {
685
- parsed = JSON.parse(text);
686
- } catch (error) {
687
- /* noop */
688
- }
343
+ const error = new Error(parsed ? parsed.message : text);
344
+ if (parsed) error.body = parsed;
345
+ /**
346
+ * to notify that token is either fetched or failed
347
+ * in the below case token failed to be fetched
348
+ * and reset requestState to false
349
+ * so requestState could be shared between multi authMiddlewareBase functions
350
+ */
689
351
 
690
- error = new Error(parsed ? parsed.message : text);
691
- if (parsed) error.body = parsed;
692
- /**
693
- * to notify that token is either fetched or failed
694
- * in the below case token failed to be fetched
695
- * and reset requestState to false
696
- * so requestState could be shared between multi authMiddlewareBase functions
697
- */
698
-
699
- requestState.set(false);
700
- response.reject(error);
701
- _context.next = 33;
702
- break;
703
-
704
- case 29:
705
- _context.prev = 29;
706
- _context.t0 = _context["catch"](1);
707
-
708
- /**
709
- * to notify that token is either fetched or failed
710
- * in the below case token failed to be fetched
711
- * and reset requestState to false
712
- * so requestState could be shared between multi authMiddlewareBase functions
713
- */
714
- requestState.set(false);
715
- if (response && typeof response.reject === 'function') response.reject(_context.t0);
716
-
717
- case 33:
718
- case "end":
719
- return _context.stop();
720
- }
721
- }
722
- }, _callee, null, [[1, 29]]);
723
- }));
724
- return _executeRequest.apply(this, arguments);
352
+ requestState.set(false);
353
+ response.reject(error);
354
+ } catch (error) {
355
+ /**
356
+ * to notify that token is either fetched or failed
357
+ * in the below case token failed to be fetched
358
+ * and reset requestState to false
359
+ * so requestState could be shared between multi authMiddlewareBase functions
360
+ */
361
+ requestState.set(false);
362
+ if (response && typeof response.reject === 'function') response.reject(error);
363
+ }
725
364
  }
726
365
 
727
- function authMiddlewareBase(_ref2, next, userOptions) {
728
- var request = _ref2.request,
729
- response = _ref2.response,
730
- url = _ref2.url,
731
- basicAuth = _ref2.basicAuth,
732
- body = _ref2.body,
733
- pendingTasks = _ref2.pendingTasks,
734
- requestState = _ref2.requestState,
735
- tokenCache = _ref2.tokenCache,
736
- tokenCacheKey = _ref2.tokenCacheKey,
737
- fetcher = _ref2.fetch;
366
+ function authMiddlewareBase({
367
+ request,
368
+ response,
369
+ url,
370
+ basicAuth,
371
+ body,
372
+ pendingTasks,
373
+ requestState,
374
+ tokenCache,
375
+ tokenCacheKey,
376
+ fetch: fetcher
377
+ }, next, userOptions) {
738
378
  if (!fetcher && typeof fetch === 'undefined') throw new Error('`fetch` is not available. Please pass in `fetch` as an option or have it globally available.');
739
379
  if (!fetcher) fetcher = fetch; // Check if there is already a `Authorization` header in the request.
740
380
  // If so, then go directly to the next middleware.
@@ -746,10 +386,10 @@ function authMiddlewareBase(_ref2, next, userOptions) {
746
386
  // the token in the `Authorization` header.
747
387
 
748
388
 
749
- var tokenObj = tokenCache.get(tokenCacheKey);
389
+ const tokenObj = tokenCache.get(tokenCacheKey);
750
390
 
751
391
  if (tokenObj && tokenObj.token && Date.now() < tokenObj.expirationTime) {
752
- var requestWithAuth = mergeAuthHeader(tokenObj.token, request);
392
+ const requestWithAuth = mergeAuthHeader(tokenObj.token, request);
753
393
  next(requestWithAuth, response);
754
394
  return;
755
395
  }
@@ -762,9 +402,9 @@ function authMiddlewareBase(_ref2, next, userOptions) {
762
402
 
763
403
 
764
404
  pendingTasks.push({
765
- request: request,
766
- response: response,
767
- next: next
405
+ request,
406
+ response,
407
+ next
768
408
  }); // If a token is currently being fetched, just wait ;)
769
409
 
770
410
  if (requestState.get()) return; // Mark that a token is being fetched
@@ -777,373 +417,268 @@ function authMiddlewareBase(_ref2, next, userOptions) {
777
417
 
778
418
  if (tokenObj && tokenObj.refreshToken && (!tokenObj.token || tokenObj.token && Date.now() > tokenObj.expirationTime)) {
779
419
  if (!userOptions) throw new Error('Missing required options');
780
- executeRequest(_objectSpread2(_objectSpread2({
781
- fetcher: fetcher
782
- }, buildRequestForRefreshTokenFlow(_objectSpread2(_objectSpread2({}, userOptions), {}, {
783
- refreshToken: tokenObj.refreshToken
784
- }))), {}, {
785
- tokenCacheKey: tokenCacheKey,
786
- tokenCache: tokenCache,
787
- requestState: requestState,
788
- pendingTasks: pendingTasks,
789
- response: response
790
- }));
420
+ executeRequest({
421
+ fetcher,
422
+ ...buildRequestForRefreshTokenFlow({ ...userOptions,
423
+ refreshToken: tokenObj.refreshToken
424
+ }),
425
+ tokenCacheKey,
426
+ tokenCache,
427
+ requestState,
428
+ pendingTasks,
429
+ response
430
+ });
791
431
  return;
792
432
  } // Token and refreshToken are not present or invalid. Request a new token...
793
433
 
794
434
 
795
435
  executeRequest({
796
- fetcher: fetcher,
797
- url: url,
798
- basicAuth: basicAuth,
799
- body: body,
800
- tokenCacheKey: tokenCacheKey,
801
- tokenCache: tokenCache,
802
- requestState: requestState,
803
- pendingTasks: pendingTasks,
804
- response: response
436
+ fetcher,
437
+ url,
438
+ basicAuth,
439
+ body,
440
+ tokenCacheKey,
441
+ tokenCache,
442
+ requestState,
443
+ pendingTasks,
444
+ response
805
445
  });
806
446
  }
807
447
 
808
448
  function store(initVal) {
809
- var value = initVal;
449
+ let value = initVal;
810
450
  return {
811
- get: function get() {
812
- return value;
813
- },
814
- set: function set(val) {
451
+ get: () => value,
452
+ set: val => {
815
453
  value = val;
816
454
  return value;
817
455
  }
818
456
  };
819
457
  }
820
458
 
821
- function createAuthMiddlewareForClientCredentialsFlow$1(options) {
822
- var tokenCache = options.tokenCache || store({
823
- token: '',
824
- expirationTime: -1
825
- });
826
- var requestState = store(false);
827
- var pendingTasks = [];
828
- return function (next) {
829
- return function (request, response) {
830
- // Check if there is already a `Authorization` header in the request.
831
- // If so, then go directly to the next middleware.
832
- if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
833
- next(request, response);
834
- return;
835
- }
836
-
837
- var params = _objectSpread2(_objectSpread2({
838
- request: request,
839
- response: response
840
- }, buildRequestForClientCredentialsFlow(options)), {}, {
841
- pendingTasks: pendingTasks,
842
- requestState: requestState,
843
- tokenCache: tokenCache,
844
- tokenCacheKey: buildTokenCacheKey(options),
845
- fetch: options.fetch
846
- });
459
+ function createAuthMiddlewareForAnonymousSessionFlow$1(options) {
460
+ const tokenCache = store({});
461
+ const pendingTasks = [];
462
+ const requestState = store(false);
463
+ return next => (request, response) => {
464
+ // Check if there is already a `Authorization` header in the request.
465
+ // If so, then go directly to the next middleware.
466
+ if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
467
+ next(request, response);
468
+ return;
469
+ }
847
470
 
848
- authMiddlewareBase(params, next);
471
+ const params = {
472
+ request,
473
+ response,
474
+ ...buildRequestForAnonymousSessionFlow(options),
475
+ pendingTasks,
476
+ requestState,
477
+ tokenCache,
478
+ fetch: options.fetch
849
479
  };
480
+ authMiddlewareBase(params, next, options);
850
481
  };
851
482
  }
852
483
 
853
- function createAuthMiddlewareForPasswordFlow$1(options) {
854
- var tokenCache = store({});
855
- var pendingTasks = [];
856
- var requestState = store(false);
857
- return function (next) {
858
- return function (request, response) {
859
- // Check if there is already a `Authorization` header in the request.
860
- // If so, then go directly to the next middleware.
861
- if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
862
- next(request, response);
863
- return;
864
- }
865
-
866
- var params = _objectSpread2(_objectSpread2({
867
- request: request,
868
- response: response
869
- }, buildRequestForPasswordFlow(options)), {}, {
870
- pendingTasks: pendingTasks,
871
- requestState: requestState,
872
- tokenCache: tokenCache,
873
- fetch: options.fetch
874
- });
875
-
876
- authMiddlewareBase(params, next, options);
877
- };
484
+ function buildTokenCacheKey(options) {
485
+ return {
486
+ clientId: options.credentials.clientId,
487
+ host: options.host,
488
+ projectKey: options.projectKey
878
489
  };
879
490
  }
880
491
 
881
- function createAuthMiddlewareForRefreshTokenFlow$1(options) {
882
- var tokenCache = store({});
883
- var pendingTasks = [];
884
- var requestState = store(false);
885
- return function (next) {
886
- return function (request, response) {
887
- // Check if there is already a `Authorization` header in the request.
888
- // If so, then go directly to the next middleware.
889
- if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
890
- next(request, response);
891
- return;
892
- }
893
-
894
- var params = _objectSpread2(_objectSpread2({
895
- request: request,
896
- response: response
897
- }, buildRequestForRefreshTokenFlow(options)), {}, {
898
- pendingTasks: pendingTasks,
899
- requestState: requestState,
900
- tokenCache: tokenCache,
901
- fetch: options.fetch
902
- });
492
+ function createAuthMiddlewareForClientCredentialsFlow$1(options) {
493
+ const tokenCache = options.tokenCache || store({
494
+ token: '',
495
+ expirationTime: -1
496
+ });
497
+ const requestState = store(false);
498
+ const pendingTasks = [];
499
+ return next => (request, response) => {
500
+ // Check if there is already a `Authorization` header in the request.
501
+ // If so, then go directly to the next middleware.
502
+ if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
503
+ next(request, response);
504
+ return;
505
+ }
903
506
 
904
- authMiddlewareBase(params, next);
507
+ const params = {
508
+ request,
509
+ response,
510
+ ...buildRequestForClientCredentialsFlow(options),
511
+ pendingTasks,
512
+ requestState,
513
+ tokenCache,
514
+ tokenCacheKey: buildTokenCacheKey(options),
515
+ fetch: options.fetch
905
516
  };
517
+ authMiddlewareBase(params, next);
906
518
  };
907
519
  }
908
520
 
909
- function createAuthMiddlewareForAnonymousSessionFlow$1(options) {
910
- var tokenCache = store({});
911
- var pendingTasks = [];
912
- var requestState = store(false);
913
- return function (next) {
914
- return function (request, response) {
915
- // Check if there is already a `Authorization` header in the request.
916
- // If so, then go directly to the next middleware.
917
- if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
918
- next(request, response);
919
- return;
920
- }
521
+ function createAuthMiddlewareWithExistingToken$1(authorization = '', options = {}) {
522
+ return next => (request, response) => {
523
+ if (typeof authorization !== 'string') throw new Error('authorization must be a string');
524
+ const force = options.force === undefined ? true : options.force;
525
+ /** The request will not be modified if:
526
+ * 1. no argument is passed
527
+ * 2. force is false and authorization header exists
528
+ */
921
529
 
922
- var params = _objectSpread2(_objectSpread2({
923
- request: request,
924
- response: response
925
- }, buildRequestForAnonymousSessionFlow(options)), {}, {
926
- pendingTasks: pendingTasks,
927
- requestState: requestState,
928
- tokenCache: tokenCache,
929
- fetch: options.fetch
930
- });
530
+ if (!authorization || (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) && force === false) {
531
+ return next(request, response);
532
+ }
931
533
 
932
- authMiddlewareBase(params, next, options);
534
+ const requestWithAuth = { ...request,
535
+ headers: { ...request.headers,
536
+ Authorization: authorization
537
+ }
933
538
  };
539
+ return next(requestWithAuth, response);
934
540
  };
935
541
  }
936
542
 
937
- function createAuthMiddlewareWithExistingToken$1() {
938
- var authorization = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
939
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
940
- return function (next) {
941
- return function (request, response) {
942
- if (typeof authorization !== 'string') throw new Error('authorization must be a string');
943
- var force = options.force === undefined ? true : options.force;
944
- /** The request will not be modified if:
945
- * 1. no argument is passed
946
- * 2. force is false and authorization header exists
947
- */
948
-
949
- if (!authorization || (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) && force === false) {
950
- return next(request, response);
951
- }
952
-
953
- var requestWithAuth = _objectSpread2(_objectSpread2({}, request), {}, {
954
- headers: _objectSpread2(_objectSpread2({}, request.headers), {}, {
955
- Authorization: authorization
956
- })
957
- });
543
+ function createAuthMiddlewareForPasswordFlow$1(options) {
544
+ const tokenCache = store({});
545
+ const pendingTasks = [];
546
+ const requestState = store(false);
547
+ return next => (request, response) => {
548
+ // Check if there is already a `Authorization` header in the request.
549
+ // If so, then go directly to the next middleware.
550
+ if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
551
+ next(request, response);
552
+ return;
553
+ }
958
554
 
959
- return next(requestWithAuth, response);
555
+ const params = {
556
+ request,
557
+ response,
558
+ ...buildRequestForPasswordFlow(options),
559
+ pendingTasks,
560
+ requestState,
561
+ tokenCache,
562
+ fetch: options.fetch
960
563
  };
564
+ authMiddlewareBase(params, next, options);
961
565
  };
962
566
  }
963
567
 
964
- function createCorrelationIdMiddleware(options) {
965
- return function (next) {
966
- return function (request, response) {
967
- var nextRequest = _objectSpread2(_objectSpread2({}, request), {}, {
968
- headers: _objectSpread2(_objectSpread2({}, request.headers), {}, {
969
- 'X-Correlation-ID': options.generate()
970
- })
971
- });
568
+ function createAuthMiddlewareForRefreshTokenFlow$1(options) {
569
+ const tokenCache = store({});
570
+ const pendingTasks = [];
571
+ const requestState = store(false);
572
+ return next => (request, response) => {
573
+ // Check if there is already a `Authorization` header in the request.
574
+ // If so, then go directly to the next middleware.
575
+ if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
576
+ next(request, response);
577
+ return;
578
+ }
972
579
 
973
- next(nextRequest, response);
580
+ const params = {
581
+ request,
582
+ response,
583
+ ...buildRequestForRefreshTokenFlow(options),
584
+ pendingTasks,
585
+ requestState,
586
+ tokenCache,
587
+ fetch: options.fetch
974
588
  };
589
+ authMiddlewareBase(params, next);
975
590
  };
976
591
  }
977
592
 
978
- function createLoggerMiddleware() {
979
- return function (next) {
980
- return function (request, response) {
981
- var error = response.error,
982
- body = response.body,
983
- statusCode = response.statusCode;
984
- console.log('Request: ', request);
985
- console.log('Response: ', {
986
- error: error,
987
- body: body,
988
- statusCode: statusCode
989
- });
990
- next(request, response);
593
+ var authMiddlewares = /*#__PURE__*/Object.freeze({
594
+ __proto__: null,
595
+ createAuthMiddlewareForAnonymousSessionFlow: createAuthMiddlewareForAnonymousSessionFlow$1,
596
+ createAuthMiddlewareForClientCredentialsFlow: createAuthMiddlewareForClientCredentialsFlow$1,
597
+ createAuthMiddlewareWithExistingToken: createAuthMiddlewareWithExistingToken$1,
598
+ createAuthMiddlewareForPasswordFlow: createAuthMiddlewareForPasswordFlow$1,
599
+ createAuthMiddlewareForRefreshTokenFlow: createAuthMiddlewareForRefreshTokenFlow$1
600
+ });
601
+
602
+ function createCorrelationIdMiddleware(options) {
603
+ return next => (request, response) => {
604
+ const nextRequest = { ...request,
605
+ headers: { ...request.headers,
606
+ 'X-Correlation-ID': options.generate()
607
+ }
991
608
  };
609
+ next(nextRequest, response);
992
610
  };
993
611
  }
994
612
 
995
- /*
996
- This is the easiest way, for this use case, to detect if we're running in
997
- Node.js or in a browser environment. In other cases, this won't be even a
998
- problem as Rollup will provide the correct polyfill in the bundle.
999
- The main advantage by doing it this way is that it allows to easily test
1000
- the code running in both environments, by overriding `global.window` in
1001
- the specific test.
1002
- */
1003
- var isBrowser = function isBrowser() {
1004
- return window.document && window.document.nodeType === 9;
1005
- };
1006
-
1007
- function getSystemInfo() {
1008
- if (isBrowser()) return window.navigator.userAgent;
1009
- var nodeVersion = process.version.slice(1); // const platformInfo = `(${process.platform}; ${process.arch})`
1010
- // return `Node.js/${nodeVersion} ${platformInfo}`
1011
-
1012
- return "node.js/".concat(nodeVersion);
613
+ function defineError(statusCode, message, meta = {}) {
614
+ this.status = this.statusCode = this.code = statusCode;
615
+ this.message = message;
616
+ Object.assign(this, meta);
617
+ this.name = this.constructor.name;
618
+ this.constructor.prototype.__proto__ = Error.prototype;
619
+ if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
1013
620
  }
1014
621
 
1015
- function createUserAgent(options) {
1016
- if (!options || Object.keys(options).length === 0 || !{}.hasOwnProperty.call(options, 'name')) throw new Error('Missing required option `name`'); // Main info
1017
-
1018
- var baseInfo = options.version ? "".concat(options.name, "/").concat(options.version) : options.name; // Library info
1019
-
1020
- var libraryInfo = null;
1021
- if (options.libraryName && !options.libraryVersion) libraryInfo = options.libraryName;else if (options.libraryName && options.libraryVersion) libraryInfo = "".concat(options.libraryName, "/").concat(options.libraryVersion); // Contact info
1022
-
1023
- var contactInfo = null;
1024
- if (options.contactUrl && !options.contactEmail) contactInfo = "(+".concat(options.contactUrl, ")");else if (!options.contactUrl && options.contactEmail) contactInfo = "(+".concat(options.contactEmail, ")");else if (options.contactUrl && options.contactEmail) contactInfo = "(+".concat(options.contactUrl, "; +").concat(options.contactEmail, ")"); // System info
1025
-
1026
- var systemInfo = getSystemInfo();
1027
- return [baseInfo, systemInfo, libraryInfo, contactInfo].filter(Boolean).join(' ');
622
+ function NetworkError(...args) {
623
+ defineError.call(this, 0
624
+ /* special code to indicate network errors */
625
+ , ...args);
1028
626
  }
1029
-
1030
- var _require = require('root-require')('package.json'),
1031
- version = _require.version;
1032
-
1033
- function createUserAgentMiddleware() {
1034
- var userAgent = createUserAgent({
1035
- name: "commercetools-sdk-javascript-v2/".concat(version)
1036
- });
1037
- return function (next) {
1038
- return function (request, response) {
1039
- var requestWithUserAgent = _objectSpread2(_objectSpread2({}, request), {}, {
1040
- headers: _objectSpread2(_objectSpread2({}, request.headers), {}, {
1041
- 'User-Agent': userAgent
1042
- })
1043
- });
1044
-
1045
- next(requestWithUserAgent, response);
1046
- };
1047
- };
627
+ function HttpError(...args) {
628
+ defineError.call(this,
629
+ /* code will be passed as arg */
630
+ ...args);
1048
631
  }
1049
-
1050
- function createQueueMiddleware(_ref) {
1051
- var _ref$concurrency = _ref.concurrency,
1052
- concurrency = _ref$concurrency === void 0 ? 20 : _ref$concurrency;
1053
- var queue = [];
1054
- var runningCount = 0;
1055
-
1056
- var dequeue = function dequeue(next) {
1057
- // We assume here that this task has been completed
1058
- runningCount -= 1; // Check if there are any other pending tasks and execute them
1059
-
1060
- if (queue.length && runningCount <= concurrency) {
1061
- var nextTask = queue.shift();
1062
- runningCount += 1;
1063
- next(nextTask.request, nextTask.response);
1064
- }
1065
- };
1066
-
1067
- return function (next) {
1068
- return function (request, response) {
1069
- // Override response `resolve` and `reject` to know when the request has
1070
- // been completed and therefore trigger a pending task in the queue.
1071
- var patchedResponse = _objectSpread2(_objectSpread2({}, response), {}, {
1072
- resolve: function resolve(data) {
1073
- // Resolve original promise
1074
- response.resolve(data);
1075
- dequeue(next);
1076
- },
1077
- reject: function reject(error) {
1078
- // Reject original promise
1079
- response.reject(error);
1080
- dequeue(next);
1081
- }
1082
- }); // Add task to the queue
1083
-
1084
-
1085
- queue.push({
1086
- request: request,
1087
- response: patchedResponse
1088
- }); // If possible, run the task straight away
1089
-
1090
- if (runningCount < concurrency) {
1091
- var nextTask = queue.shift();
1092
- runningCount += 1;
1093
- next(nextTask.request, nextTask.response);
1094
- }
1095
- };
1096
- };
632
+ function BadRequest(...args) {
633
+ defineError.call(this, 400, ...args);
1097
634
  }
635
+ function Unauthorized(...args) {
636
+ defineError.call(this, 401, ...args);
637
+ }
638
+ function Forbidden(...args) {
639
+ defineError.call(this, 403, ...args);
640
+ }
641
+ function NotFound(...args) {
642
+ defineError.call(this, 404, ...args);
643
+ }
644
+ function ConcurrentModification(...args) {
645
+ defineError.call(this, 409, ...args);
646
+ }
647
+ function InternalServerError(...args) {
648
+ defineError.call(this, 500, ...args);
649
+ }
650
+ function ServiceUnavailable(...args) {
651
+ defineError.call(this, 503, ...args);
652
+ }
653
+ function getErrorByCode(code) {
654
+ switch (code) {
655
+ case 0:
656
+ return NetworkError;
1098
657
 
1099
- function _typeof(obj) {
1100
- "@babel/helpers - typeof";
1101
-
1102
- if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
1103
- _typeof = function (obj) {
1104
- return typeof obj;
1105
- };
1106
- } else {
1107
- _typeof = function (obj) {
1108
- return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
1109
- };
1110
- }
658
+ case 400:
659
+ return BadRequest;
1111
660
 
1112
- return _typeof(obj);
1113
- }
661
+ case 401:
662
+ return Unauthorized;
1114
663
 
1115
- function _objectWithoutPropertiesLoose(source, excluded) {
1116
- if (source == null) return {};
1117
- var target = {};
1118
- var sourceKeys = Object.keys(source);
1119
- var key, i;
664
+ case 403:
665
+ return Forbidden;
1120
666
 
1121
- for (i = 0; i < sourceKeys.length; i++) {
1122
- key = sourceKeys[i];
1123
- if (excluded.indexOf(key) >= 0) continue;
1124
- target[key] = source[key];
1125
- }
667
+ case 404:
668
+ return NotFound;
1126
669
 
1127
- return target;
1128
- }
670
+ case 409:
671
+ return ConcurrentModification;
1129
672
 
1130
- function _objectWithoutProperties(source, excluded) {
1131
- if (source == null) return {};
1132
- var target = _objectWithoutPropertiesLoose(source, excluded);
1133
- var key, i;
673
+ case 500:
674
+ return InternalServerError;
1134
675
 
1135
- if (Object.getOwnPropertySymbols) {
1136
- var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
676
+ case 503:
677
+ return ServiceUnavailable;
1137
678
 
1138
- for (i = 0; i < sourceSymbolKeys.length; i++) {
1139
- key = sourceSymbolKeys[i];
1140
- if (excluded.indexOf(key) >= 0) continue;
1141
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
1142
- target[key] = source[key];
1143
- }
679
+ default:
680
+ return undefined;
1144
681
  }
1145
-
1146
- return target;
1147
682
  }
1148
683
 
1149
684
  function parseHeaders(headers) {
@@ -1152,23 +687,21 @@ function parseHeaders(headers) {
1152
687
 
1153
688
  if (!headers.forEach) return {}; // whatwg-fetch
1154
689
 
1155
- var map = {};
1156
- headers.forEach(function (value, name) {
690
+ const map = {};
691
+ headers.forEach((value, name) => {
1157
692
  map[name] = value;
1158
693
  });
1159
694
  return map;
1160
695
  }
1161
696
 
1162
- var _excluded = ["statusCode", "message"];
1163
-
1164
- function createError(_ref) {
1165
- var statusCode = _ref.statusCode,
1166
- message = _ref.message,
1167
- rest = _objectWithoutProperties(_ref, _excluded);
1168
-
1169
- var errorMessage = message || 'Unexpected non-JSON error response';
1170
- if (statusCode === 404) errorMessage = "URI not found: ".concat(rest.originalRequest.uri);
1171
- var ResponseError = getErrorByCode(statusCode);
697
+ function createError({
698
+ statusCode,
699
+ message,
700
+ ...rest
701
+ }) {
702
+ let errorMessage = message || 'Unexpected non-JSON error response';
703
+ if (statusCode === 404) errorMessage = `URI not found: ${rest.originalRequest.uri}`;
704
+ const ResponseError = getErrorByCode(statusCode);
1172
705
  if (ResponseError) return new ResponseError(errorMessage, rest);
1173
706
  return new HttpError(statusCode, errorMessage, rest);
1174
707
  } // calculates the delay duration exponentially
@@ -1177,7 +710,7 @@ function createError(_ref) {
1177
710
 
1178
711
  function calcDelayDuration(retryCount, retryDelay, maxRetries, backoff, maxDelay) {
1179
712
  if (backoff) return retryCount !== 0 // do not increase if it's the first retry
1180
- ? Math.min(Math.round((Math.random() + 1) * retryDelay * Math.pow(2, retryCount)), maxDelay) : retryDelay;
713
+ ? Math.min(Math.round((Math.random() + 1) * retryDelay * 2 ** retryCount), maxDelay) : retryDelay;
1181
714
  return retryDelay;
1182
715
  }
1183
716
 
@@ -1188,30 +721,27 @@ function maskAuthData(request, maskSensitiveHeaderData) {
1188
721
  }
1189
722
  }
1190
723
 
1191
- function createHttpMiddleware(_ref2) {
1192
- var host = _ref2.host,
1193
- credentialsMode = _ref2.credentialsMode,
1194
- includeResponseHeaders = _ref2.includeResponseHeaders,
1195
- includeOriginalRequest = _ref2.includeOriginalRequest,
1196
- _ref2$maskSensitiveHe = _ref2.maskSensitiveHeaderData,
1197
- maskSensitiveHeaderData = _ref2$maskSensitiveHe === void 0 ? true : _ref2$maskSensitiveHe,
1198
- enableRetry = _ref2.enableRetry,
1199
- timeout = _ref2.timeout,
1200
- _ref2$retryConfig = _ref2.retryConfig;
1201
- _ref2$retryConfig = _ref2$retryConfig === void 0 ? {} : _ref2$retryConfig;
1202
- var _ref2$retryConfig$max = _ref2$retryConfig.maxRetries,
1203
- maxRetries = _ref2$retryConfig$max === void 0 ? 10 : _ref2$retryConfig$max,
1204
- _ref2$retryConfig$bac = _ref2$retryConfig.backoff,
1205
- backoff = _ref2$retryConfig$bac === void 0 ? true : _ref2$retryConfig$bac,
1206
- _ref2$retryConfig$ret = _ref2$retryConfig.retryDelay,
1207
- retryDelay = _ref2$retryConfig$ret === void 0 ? 200 : _ref2$retryConfig$ret,
1208
- _ref2$retryConfig$max2 = _ref2$retryConfig.maxDelay,
1209
- maxDelay = _ref2$retryConfig$max2 === void 0 ? Infinity : _ref2$retryConfig$max2,
1210
- fetcher = _ref2.fetch,
1211
- getAbortController = _ref2.getAbortController;
724
+ function createHttpMiddleware({
725
+ host,
726
+ credentialsMode,
727
+ includeResponseHeaders,
728
+ includeOriginalRequest,
729
+ maskSensitiveHeaderData = true,
730
+ enableRetry,
731
+ timeout,
732
+ retryConfig: {
733
+ // encourage exponential backoff to prevent spamming the server if down
734
+ maxRetries = 10,
735
+ backoff = true,
736
+ retryDelay = 200,
737
+ maxDelay = Infinity
738
+ } = {},
739
+ fetch: fetcher,
740
+ getAbortController
741
+ }) {
1212
742
  if (!fetcher && typeof fetch === 'undefined') throw new Error('`fetch` is not available. Please pass in `fetch` as an option or have it globally available.');
1213
743
  if (timeout && !getAbortController && typeof AbortController === 'undefined') throw new Error('`AbortController` is not available. Please pass in `getAbortController` as an option or have AbortController globally available when using timeout.');
1214
- var fetchFunction;
744
+ let fetchFunction;
1215
745
 
1216
746
  if (fetcher) {
1217
747
  fetchFunction = fetcher;
@@ -1222,187 +752,335 @@ function createHttpMiddleware(_ref2) {
1222
752
  fetchFunction = fetch;
1223
753
  }
1224
754
 
1225
- return function (next) {
1226
- return function (request, response) {
1227
- var abortController;
1228
- if (timeout || getAbortController) abortController = (getAbortController ? getAbortController() : null) || new AbortController();
1229
- var url = host.replace(/\/$/, '') + request.uri;
1230
- var body = typeof request.body === 'string' || Buffer.isBuffer(request.body) ? request.body : // NOTE: `stringify` of `null` gives the String('null')
1231
- JSON.stringify(request.body || undefined);
1232
-
1233
- var requestHeader = _objectSpread2({}, request.headers);
1234
-
1235
- if (!Object.prototype.hasOwnProperty.call(requestHeader, 'Content-Type')) {
1236
- requestHeader['Content-Type'] = 'application/json';
1237
- }
1238
-
1239
- if (body) {
1240
- requestHeader['Content-Length'] = Buffer.byteLength(body).toString();
1241
- }
1242
-
1243
- var fetchOptions = {
1244
- method: request.method,
1245
- headers: requestHeader
1246
- };
1247
-
1248
- if (credentialsMode) {
1249
- fetchOptions.credentialsMode = credentialsMode;
1250
- }
1251
-
1252
- if (abortController) {
1253
- fetchOptions.signal = abortController.signal;
1254
- }
1255
-
1256
- if (body) {
1257
- fetchOptions.body = body;
1258
- }
1259
-
1260
- var retryCount = 0; // wrap in a fn so we can retry if error occur
1261
-
1262
- function executeFetch() {
1263
- // Kick off timer for abortController directly before fetch.
1264
- var timer;
1265
- if (timeout) timer = setTimeout(function () {
1266
- abortController.abort();
1267
- }, timeout);
1268
- fetchFunction(url, fetchOptions).then(function (res) {
1269
- if (res.ok) {
1270
- if (fetchOptions.method === 'HEAD') {
1271
- next(request, _objectSpread2(_objectSpread2({}, response), {}, {
1272
- statusCode: res.status
1273
- }));
1274
- return;
1275
- }
755
+ return next => (request, response) => {
756
+ let abortController;
757
+ if (timeout || getAbortController) abortController = (getAbortController ? getAbortController() : null) || new AbortController();
758
+ const url = host.replace(/\/$/, '') + request.uri;
759
+ const body = typeof request.body === 'string' || Buffer.isBuffer(request.body) ? request.body : // NOTE: `stringify` of `null` gives the String('null')
760
+ JSON.stringify(request.body || undefined);
761
+ const requestHeader = { ...request.headers
762
+ };
1276
763
 
1277
- res.text().then(function (result) {
1278
- // Try to parse the response as JSON
1279
- var parsed;
764
+ if (!Object.prototype.hasOwnProperty.call(requestHeader, 'Content-Type')) {
765
+ requestHeader['Content-Type'] = 'application/json';
766
+ }
1280
767
 
1281
- try {
1282
- parsed = result.length > 0 ? JSON.parse(result) : {};
1283
- } catch (err) {
1284
- if (enableRetry && retryCount < maxRetries) {
1285
- setTimeout(executeFetch, calcDelayDuration(retryCount, retryDelay, maxRetries, backoff, maxDelay));
1286
- retryCount += 1;
1287
- return;
1288
- }
768
+ if (body) {
769
+ requestHeader['Content-Length'] = Buffer.byteLength(body).toString();
770
+ }
1289
771
 
1290
- parsed = result;
1291
- }
772
+ const fetchOptions = {
773
+ method: request.method,
774
+ headers: requestHeader
775
+ };
1292
776
 
1293
- var parsedResponse = _objectSpread2(_objectSpread2({}, response), {}, {
1294
- body: parsed,
1295
- statusCode: res.status
1296
- });
777
+ if (credentialsMode) {
778
+ fetchOptions.credentialsMode = credentialsMode;
779
+ }
1297
780
 
1298
- if (includeResponseHeaders) parsedResponse.headers = parseHeaders(res.headers);
781
+ if (abortController) {
782
+ fetchOptions.signal = abortController.signal;
783
+ }
1299
784
 
1300
- if (includeOriginalRequest) {
1301
- parsedResponse.request = _objectSpread2({}, fetchOptions);
1302
- maskAuthData(parsedResponse.request, maskSensitiveHeaderData);
1303
- }
785
+ if (body) {
786
+ fetchOptions.body = body;
787
+ }
1304
788
 
1305
- next(request, parsedResponse);
789
+ let retryCount = 0; // wrap in a fn so we can retry if error occur
790
+
791
+ function executeFetch() {
792
+ // Kick off timer for abortController directly before fetch.
793
+ let timer;
794
+ if (timeout) timer = setTimeout(() => {
795
+ abortController.abort();
796
+ }, timeout);
797
+ fetchFunction(url, fetchOptions).then(res => {
798
+ if (res.ok) {
799
+ if (fetchOptions.method === 'HEAD') {
800
+ next(request, { ...response,
801
+ statusCode: res.status
1306
802
  });
1307
803
  return;
1308
804
  }
1309
805
 
1310
- if (res.status === 503 && enableRetry) if (retryCount < maxRetries) {
1311
- setTimeout(executeFetch, calcDelayDuration(retryCount, retryDelay, maxRetries, backoff, maxDelay));
1312
- retryCount += 1;
1313
- return;
1314
- } // Server responded with an error. Try to parse it as JSON, then
1315
- // return a proper error type with all necessary meta information.
1316
-
1317
- res.text().then(function (text) {
1318
- // Try to parse the error response as JSON
1319
- var parsed;
806
+ res.text().then(result => {
807
+ // Try to parse the response as JSON
808
+ let parsed;
1320
809
 
1321
810
  try {
1322
- parsed = JSON.parse(text);
1323
- } catch (error) {
1324
- parsed = text;
1325
- }
811
+ parsed = result.length > 0 ? JSON.parse(result) : {};
812
+ } catch (err) {
813
+ if (enableRetry && retryCount < maxRetries) {
814
+ setTimeout(executeFetch, calcDelayDuration(retryCount, retryDelay, maxRetries, backoff, maxDelay));
815
+ retryCount += 1;
816
+ return;
817
+ }
1326
818
 
1327
- var error = createError(_objectSpread2({
1328
- statusCode: res.status,
1329
- originalRequest: request,
1330
- retryCount: retryCount,
1331
- headers: parseHeaders(res.headers)
1332
- }, _typeof(parsed) === 'object' ? {
1333
- message: parsed.message,
1334
- body: parsed
1335
- } : {
1336
- message: parsed,
1337
- body: parsed
1338
- }));
1339
- maskAuthData(error.originalRequest, maskSensitiveHeaderData); // Let the final resolver to reject the promise
819
+ parsed = result;
820
+ }
1340
821
 
1341
- var parsedResponse = _objectSpread2(_objectSpread2({}, response), {}, {
1342
- error: error,
822
+ const parsedResponse = { ...response,
823
+ body: parsed,
1343
824
  statusCode: res.status
1344
- });
825
+ };
826
+ if (includeResponseHeaders) parsedResponse.headers = parseHeaders(res.headers);
827
+
828
+ if (includeOriginalRequest) {
829
+ parsedResponse.request = { ...fetchOptions
830
+ };
831
+ maskAuthData(parsedResponse.request, maskSensitiveHeaderData);
832
+ }
1345
833
 
1346
834
  next(request, parsedResponse);
1347
835
  });
1348
- }, // We know that this is a "network" error thrown by the `fetch` library
1349
- function (e) {
1350
- if (enableRetry) if (retryCount < maxRetries) {
1351
- setTimeout(executeFetch, calcDelayDuration(retryCount, retryDelay, maxRetries, backoff, maxDelay));
1352
- retryCount += 1;
1353
- return;
836
+ return;
837
+ }
838
+
839
+ if (res.status === 503 && enableRetry) if (retryCount < maxRetries) {
840
+ setTimeout(executeFetch, calcDelayDuration(retryCount, retryDelay, maxRetries, backoff, maxDelay));
841
+ retryCount += 1;
842
+ return;
843
+ } // Server responded with an error. Try to parse it as JSON, then
844
+ // return a proper error type with all necessary meta information.
845
+
846
+ res.text().then(text => {
847
+ // Try to parse the error response as JSON
848
+ let parsed;
849
+
850
+ try {
851
+ parsed = JSON.parse(text);
852
+ } catch (error) {
853
+ parsed = text;
1354
854
  }
1355
- var error = new NetworkError(e.message, {
855
+
856
+ const error = createError({
857
+ statusCode: res.status,
1356
858
  originalRequest: request,
1357
- retryCount: retryCount
859
+ retryCount,
860
+ headers: parseHeaders(res.headers),
861
+ ...(typeof parsed === 'object' ? {
862
+ message: parsed.message,
863
+ body: parsed
864
+ } : {
865
+ message: parsed,
866
+ body: parsed
867
+ })
1358
868
  });
1359
- maskAuthData(error.originalRequest, maskSensitiveHeaderData);
1360
- next(request, _objectSpread2(_objectSpread2({}, response), {}, {
1361
- error: error,
1362
- statusCode: 0
1363
- }));
1364
- })["finally"](function () {
1365
- clearTimeout(timer);
869
+ maskAuthData(error.originalRequest, maskSensitiveHeaderData); // Let the final resolver to reject the promise
870
+
871
+ const parsedResponse = { ...response,
872
+ error,
873
+ statusCode: res.status
874
+ };
875
+ next(request, parsedResponse);
1366
876
  });
1367
- }
877
+ }, // We know that this is a "network" error thrown by the `fetch` library
878
+ e => {
879
+ if (enableRetry) if (retryCount < maxRetries) {
880
+ setTimeout(executeFetch, calcDelayDuration(retryCount, retryDelay, maxRetries, backoff, maxDelay));
881
+ retryCount += 1;
882
+ return;
883
+ }
884
+ const error = new NetworkError(e.message, {
885
+ originalRequest: request,
886
+ retryCount
887
+ });
888
+ maskAuthData(error.originalRequest, maskSensitiveHeaderData);
889
+ next(request, { ...response,
890
+ error,
891
+ statusCode: 0
892
+ });
893
+ }).finally(() => {
894
+ clearTimeout(timer);
895
+ });
896
+ }
1368
897
 
1369
- executeFetch();
1370
- };
898
+ executeFetch();
1371
899
  };
1372
900
  }
1373
901
 
1374
- function _classCallCheck(instance, Constructor) {
1375
- if (!(instance instanceof Constructor)) {
1376
- throw new TypeError("Cannot call a class as a function");
1377
- }
902
+ function createLoggerMiddleware() {
903
+ return next => (request, response) => {
904
+ const {
905
+ error,
906
+ body,
907
+ statusCode
908
+ } = response;
909
+ console.log('Request: ', request);
910
+ console.log('Response: ', {
911
+ error,
912
+ body,
913
+ statusCode
914
+ });
915
+ next(request, response);
916
+ };
1378
917
  }
1379
918
 
1380
- function _defineProperties(target, props) {
1381
- for (var i = 0; i < props.length; i++) {
1382
- var descriptor = props[i];
1383
- descriptor.enumerable = descriptor.enumerable || false;
1384
- descriptor.configurable = true;
1385
- if ("value" in descriptor) descriptor.writable = true;
1386
- Object.defineProperty(target, descriptor.key, descriptor);
1387
- }
919
+ function createQueueMiddleware({
920
+ concurrency = 20
921
+ }) {
922
+ const queue = [];
923
+ let runningCount = 0;
924
+
925
+ const dequeue = next => {
926
+ // We assume here that this task has been completed
927
+ runningCount -= 1; // Check if there are any other pending tasks and execute them
928
+
929
+ if (queue.length && runningCount <= concurrency) {
930
+ const nextTask = queue.shift();
931
+ runningCount += 1;
932
+ next(nextTask.request, nextTask.response);
933
+ }
934
+ };
935
+
936
+ return next => (request, response) => {
937
+ // Override response `resolve` and `reject` to know when the request has
938
+ // been completed and therefore trigger a pending task in the queue.
939
+ const patchedResponse = { ...response,
940
+
941
+ resolve(data) {
942
+ // Resolve original promise
943
+ response.resolve(data);
944
+ dequeue(next);
945
+ },
946
+
947
+ reject(error) {
948
+ // Reject original promise
949
+ response.reject(error);
950
+ dequeue(next);
951
+ }
952
+
953
+ }; // Add task to the queue
954
+
955
+ queue.push({
956
+ request,
957
+ response: patchedResponse
958
+ }); // If possible, run the task straight away
959
+
960
+ if (runningCount < concurrency) {
961
+ const nextTask = queue.shift();
962
+ runningCount += 1;
963
+ next(nextTask.request, nextTask.response);
964
+ }
965
+ };
1388
966
  }
1389
967
 
1390
- function _createClass(Constructor, protoProps, staticProps) {
1391
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
1392
- if (staticProps) _defineProperties(Constructor, staticProps);
1393
- return Constructor;
968
+ var packageJson = {
969
+ name: "@commercetools/sdk-client-v2",
970
+ version: "1.0.0",
971
+ description: "commercetools TypeScript SDK client.",
972
+ keywords: [
973
+ "commercetools",
974
+ "sdk",
975
+ "typescript",
976
+ "client",
977
+ "middleware",
978
+ "http",
979
+ "oauth",
980
+ "auth"
981
+ ],
982
+ homepage: "https://github.com/commercetools/commercetools-sdk-typescript",
983
+ license: "MIT",
984
+ directories: {
985
+ lib: "lib",
986
+ test: "test"
987
+ },
988
+ publishConfig: {
989
+ access: "public"
990
+ },
991
+ repository: {
992
+ type: "git",
993
+ url: "git+https://github.com/commercetools/commercetools-sdk-typescript.git"
994
+ },
995
+ bugs: {
996
+ url: "https://github.com/commercetools/commercetools-sdk-typescript/issues"
997
+ },
998
+ dependencies: {
999
+ "node-fetch": "^2.6.1",
1000
+ querystring: "^0.2.1"
1001
+ },
1002
+ files: [
1003
+ "dist",
1004
+ "CHANGELOG.md"
1005
+ ],
1006
+ author: "Chukwuemeka Ajima <meeky.ae@gmail.com>",
1007
+ main: "dist/commercetools-sdk-client-v2.cjs.js",
1008
+ module: "dist/commercetools-sdk-client-v2.esm.js",
1009
+ browser: {
1010
+ "./dist/commercetools-sdk-client-v2.cjs.js": "./dist/commercetools-sdk-client-v2.browser.cjs.js",
1011
+ "./dist/commercetools-sdk-client-v2.esm.js": "./dist/commercetools-sdk-client-v2.browser.esm.js"
1012
+ },
1013
+ devDependencies: {
1014
+ "abort-controller": "3.0.0",
1015
+ "common-tags": "1.8.2",
1016
+ dotenv: "10.0.0",
1017
+ jest: "27.3.1",
1018
+ nock: "12.0.3",
1019
+ "organize-imports-cli": "0.8.0"
1020
+ },
1021
+ scripts: {
1022
+ organize_imports: "find src -type f -name '*.ts' | xargs organize-imports-cli",
1023
+ postbuild: "yarn organize_imports",
1024
+ post_process_generate: "yarn organize_imports"
1025
+ }
1026
+ };
1027
+
1028
+ /*
1029
+ This is the easiest way, for this use case, to detect if we're running in
1030
+ Node.js or in a browser environment. In other cases, this won't be even a
1031
+ problem as Rollup will provide the correct polyfill in the bundle.
1032
+ The main advantage by doing it this way is that it allows to easily test
1033
+ the code running in both environments, by overriding `global.window` in
1034
+ the specific test.
1035
+ */
1036
+ const isBrowser = () => window.document && window.document.nodeType === 9;
1037
+
1038
+ function getSystemInfo() {
1039
+ if (isBrowser()) return window.navigator.userAgent;
1040
+ const nodeVersion = process.version.slice(1); // const platformInfo = `(${process.platform}; ${process.arch})`
1041
+ // return `Node.js/${nodeVersion} ${platformInfo}`
1042
+
1043
+ return `node.js/${nodeVersion}`;
1394
1044
  }
1395
1045
 
1396
- var createAuthMiddlewareForPasswordFlow = createAuthMiddlewareForPasswordFlow$1,
1397
- createAuthMiddlewareForAnonymousSessionFlow = createAuthMiddlewareForAnonymousSessionFlow$1,
1398
- createAuthMiddlewareForClientCredentialsFlow = createAuthMiddlewareForClientCredentialsFlow$1,
1399
- createAuthMiddlewareForRefreshTokenFlow = createAuthMiddlewareForRefreshTokenFlow$1,
1400
- createAuthMiddlewareWithExistingToken = createAuthMiddlewareWithExistingToken$1;
1046
+ function createUserAgent(options) {
1047
+ if (!options || Object.keys(options).length === 0 || !{}.hasOwnProperty.call(options, 'name')) throw new Error('Missing required option `name`'); // Main info
1048
+
1049
+ const baseInfo = options.version ? `${options.name}/${options.version}` : options.name; // Library info
1401
1050
 
1402
- var ClientBuilder = /*#__PURE__*/function () {
1403
- function ClientBuilder() {
1404
- _classCallCheck(this, ClientBuilder);
1051
+ let libraryInfo = null;
1052
+ if (options.libraryName && !options.libraryVersion) libraryInfo = options.libraryName;else if (options.libraryName && options.libraryVersion) libraryInfo = `${options.libraryName}/${options.libraryVersion}`; // Contact info
1053
+
1054
+ let contactInfo = null;
1055
+ if (options.contactUrl && !options.contactEmail) contactInfo = `(+${options.contactUrl})`;else if (!options.contactUrl && options.contactEmail) contactInfo = `(+${options.contactEmail})`;else if (options.contactUrl && options.contactEmail) contactInfo = `(+${options.contactUrl}; +${options.contactEmail})`; // System info
1056
+
1057
+ const systemInfo = getSystemInfo();
1058
+ return [baseInfo, systemInfo, libraryInfo, contactInfo].filter(Boolean).join(' ');
1059
+ }
1405
1060
 
1061
+ function createUserAgentMiddleware() {
1062
+ const userAgent = createUserAgent({
1063
+ name: `commercetools-sdk-javascript-v2/${packageJson.version}`
1064
+ });
1065
+ return next => (request, response) => {
1066
+ const requestWithUserAgent = { ...request,
1067
+ headers: { ...request.headers,
1068
+ 'User-Agent': userAgent
1069
+ }
1070
+ };
1071
+ next(requestWithUserAgent, response);
1072
+ };
1073
+ }
1074
+
1075
+ const {
1076
+ createAuthMiddlewareForPasswordFlow,
1077
+ createAuthMiddlewareForAnonymousSessionFlow,
1078
+ createAuthMiddlewareForClientCredentialsFlow,
1079
+ createAuthMiddlewareForRefreshTokenFlow,
1080
+ createAuthMiddlewareWithExistingToken
1081
+ } = authMiddlewares;
1082
+ class ClientBuilder {
1083
+ constructor() {
1406
1084
  _defineProperty(this, "projectKey", void 0);
1407
1085
 
1408
1086
  _defineProperty(this, "authMiddleware", void 0);
@@ -1420,157 +1098,147 @@ var ClientBuilder = /*#__PURE__*/function () {
1420
1098
  _defineProperty(this, "middlewares", []);
1421
1099
  }
1422
1100
 
1423
- _createClass(ClientBuilder, [{
1424
- key: "withProjectKey",
1425
- value: function withProjectKey(key) {
1426
- this.projectKey = key;
1427
- return this;
1428
- }
1429
- }, {
1430
- key: "defaultClient",
1431
- value: function defaultClient(baseUri, credentials, oauthUri, projectKey) {
1432
- return this.withClientCredentialsFlow({
1433
- host: oauthUri,
1434
- projectKey: projectKey || this.projectKey,
1435
- credentials: credentials
1436
- }).withHttpMiddleware({
1437
- host: baseUri,
1438
- fetch: fetch$1
1439
- }).withLoggerMiddleware();
1440
- }
1441
- }, {
1442
- key: "withAuthMiddleware",
1443
- value: function withAuthMiddleware(authMiddleware) {
1444
- this.authMiddleware = authMiddleware;
1445
- return this;
1446
- }
1447
- }, {
1448
- key: "withMiddleware",
1449
- value: function withMiddleware(middleware) {
1450
- this.middlewares.push(middleware);
1451
- return this;
1452
- }
1453
- }, {
1454
- key: "withClientCredentialsFlow",
1455
- value: function withClientCredentialsFlow(options) {
1456
- return this.withAuthMiddleware(createAuthMiddlewareForClientCredentialsFlow(_objectSpread2({
1457
- host: options.host || 'https://auth.europe-west1.gcp.commercetools.com',
1458
- projectKey: options.projectKey || this.projectKey,
1459
- credentials: {
1460
- clientId: options.credentials.clientId || '',
1461
- clientSecret: options.credentials.clientSecret || ''
1462
- },
1463
- oauthUri: options.oauthUri || '',
1464
- scopes: options.scopes,
1465
- fetch: options.fetch || fetch$1
1466
- }, options)));
1467
- }
1468
- }, {
1469
- key: "withPasswordFlow",
1470
- value: function withPasswordFlow(options) {
1471
- return this.withAuthMiddleware(createAuthMiddlewareForPasswordFlow(_objectSpread2({
1472
- host: options.host || 'https://auth.europe-west1.gcp.commercetools.com',
1473
- projectKey: options.projectKey || this.projectKey,
1474
- credentials: {
1475
- clientId: process.env.myClientId,
1476
- clientSecret: process.env.myClientSecret,
1477
- user: {
1478
- username: options.credentials.user.username || '',
1479
- password: options.credentials.user.password || ''
1480
- }
1481
- },
1482
- fetch: options.fetch || fetch$1
1483
- }, options)));
1484
- }
1485
- }, {
1486
- key: "withAnonymousSessionFlow",
1487
- value: function withAnonymousSessionFlow(options) {
1488
- return this.withAuthMiddleware(createAuthMiddlewareForAnonymousSessionFlow(_objectSpread2({
1489
- host: options.host || 'https://auth.europe-west1.gcp.commercetools.com',
1490
- projectKey: this.projectKey || options.projectKey,
1491
- credentials: {
1492
- clientId: options.credentials.clientId || '',
1493
- clientSecret: options.credentials.clientSecret || '',
1494
- anonymousId: options.credentials.anonymousId || ''
1495
- },
1496
- fetch: options.fetch || fetch$1
1497
- }, options)));
1498
- }
1499
- }, {
1500
- key: "withRefreshTokenFlow",
1501
- value: function withRefreshTokenFlow(options) {
1502
- return this.withAuthMiddleware(createAuthMiddlewareForRefreshTokenFlow(_objectSpread2({
1503
- host: options.host || 'https://auth.europe-west1.gcp.commercetools.com',
1504
- projectKey: this.projectKey || options.projectKey,
1505
- credentials: {
1506
- clientId: options.credentials.clientId || '',
1507
- clientSecret: options.credentials.clientSecret || ''
1508
- },
1509
- fetch: options.fetch || fetch$1,
1510
- refreshToken: options.refreshToken || ''
1511
- }, options)));
1512
- }
1513
- }, {
1514
- key: "withExistingTokenFlow",
1515
- value: function withExistingTokenFlow(authorization, options) {
1516
- return this.withAuthMiddleware(createAuthMiddlewareWithExistingToken(authorization, _objectSpread2({
1517
- force: options.force || true
1518
- }, options)));
1519
- }
1520
- }, {
1521
- key: "withHttpMiddleware",
1522
- value: function withHttpMiddleware(options) {
1523
- this.httpMiddleware = createHttpMiddleware(_objectSpread2({
1524
- host: options.host || 'https://api.europe-west1.gcp.commercetools.com',
1525
- fetch: options.fetch || fetch$1
1526
- }, options));
1527
- return this;
1528
- }
1529
- }, {
1530
- key: "withUserAgentMiddleware",
1531
- value: function withUserAgentMiddleware() {
1532
- this.userAgentMiddleware = createUserAgentMiddleware();
1533
- return this;
1534
- }
1535
- }, {
1536
- key: "withQueueMiddleware",
1537
- value: function withQueueMiddleware(options) {
1538
- this.queueMiddleware = createQueueMiddleware(_objectSpread2({
1539
- concurrency: options.concurrency || 20
1540
- }, options));
1541
- return this;
1542
- }
1543
- }, {
1544
- key: "withLoggerMiddleware",
1545
- value: function withLoggerMiddleware() {
1546
- this.loggerMiddleware = createLoggerMiddleware();
1547
- return this;
1548
- }
1549
- }, {
1550
- key: "withCorrelationIdMiddleware",
1551
- value: function withCorrelationIdMiddleware(options) {
1552
- this.correlationIdMiddleware = createCorrelationIdMiddleware(_objectSpread2({
1553
- generate: options.generate || null
1554
- }, options));
1555
- return this;
1556
- }
1557
- }, {
1558
- key: "build",
1559
- value: function build() {
1560
- var middlewares = this.middlewares.slice();
1561
- if (this.correlationIdMiddleware) middlewares.push(this.correlationIdMiddleware);
1562
- if (this.userAgentMiddleware) middlewares.push(this.userAgentMiddleware);
1563
- if (this.authMiddleware) middlewares.push(this.authMiddleware);
1564
- if (this.loggerMiddleware) middlewares.push(this.loggerMiddleware);
1565
- if (this.queueMiddleware) middlewares.push(this.queueMiddleware);
1566
- if (this.httpMiddleware) middlewares.push(this.httpMiddleware);
1567
- return createClient({
1568
- middlewares: middlewares
1569
- });
1570
- }
1571
- }]);
1101
+ withProjectKey(key) {
1102
+ this.projectKey = key;
1103
+ return this;
1104
+ }
1105
+
1106
+ defaultClient(baseUri, credentials, oauthUri, projectKey) {
1107
+ return this.withClientCredentialsFlow({
1108
+ host: oauthUri,
1109
+ projectKey: projectKey || this.projectKey,
1110
+ credentials
1111
+ }).withHttpMiddleware({
1112
+ host: baseUri,
1113
+ fetch: fetch$1
1114
+ }).withLoggerMiddleware();
1115
+ }
1116
+
1117
+ withAuthMiddleware(authMiddleware) {
1118
+ this.authMiddleware = authMiddleware;
1119
+ return this;
1120
+ }
1121
+
1122
+ withMiddleware(middleware) {
1123
+ this.middlewares.push(middleware);
1124
+ return this;
1125
+ }
1126
+
1127
+ withClientCredentialsFlow(options) {
1128
+ return this.withAuthMiddleware(createAuthMiddlewareForClientCredentialsFlow({
1129
+ host: options.host || 'https://auth.europe-west1.gcp.commercetools.com',
1130
+ projectKey: options.projectKey || this.projectKey,
1131
+ credentials: {
1132
+ clientId: options.credentials.clientId || '',
1133
+ clientSecret: options.credentials.clientSecret || ''
1134
+ },
1135
+ oauthUri: options.oauthUri || '',
1136
+ scopes: options.scopes,
1137
+ fetch: options.fetch || fetch$1,
1138
+ ...options
1139
+ }));
1140
+ }
1141
+
1142
+ withPasswordFlow(options) {
1143
+ return this.withAuthMiddleware(createAuthMiddlewareForPasswordFlow({
1144
+ host: options.host || 'https://auth.europe-west1.gcp.commercetools.com',
1145
+ projectKey: options.projectKey || this.projectKey,
1146
+ credentials: {
1147
+ clientId: process.env.myClientId,
1148
+ clientSecret: process.env.myClientSecret,
1149
+ user: {
1150
+ username: options.credentials.user.username || '',
1151
+ password: options.credentials.user.password || ''
1152
+ }
1153
+ },
1154
+ fetch: options.fetch || fetch$1,
1155
+ ...options
1156
+ }));
1157
+ }
1158
+
1159
+ withAnonymousSessionFlow(options) {
1160
+ return this.withAuthMiddleware(createAuthMiddlewareForAnonymousSessionFlow({
1161
+ host: options.host || 'https://auth.europe-west1.gcp.commercetools.com',
1162
+ projectKey: this.projectKey || options.projectKey,
1163
+ credentials: {
1164
+ clientId: options.credentials.clientId || '',
1165
+ clientSecret: options.credentials.clientSecret || '',
1166
+ anonymousId: options.credentials.anonymousId || ''
1167
+ },
1168
+ fetch: options.fetch || fetch$1,
1169
+ ...options
1170
+ }));
1171
+ }
1172
+
1173
+ withRefreshTokenFlow(options) {
1174
+ return this.withAuthMiddleware(createAuthMiddlewareForRefreshTokenFlow({
1175
+ host: options.host || 'https://auth.europe-west1.gcp.commercetools.com',
1176
+ projectKey: this.projectKey || options.projectKey,
1177
+ credentials: {
1178
+ clientId: options.credentials.clientId || '',
1179
+ clientSecret: options.credentials.clientSecret || ''
1180
+ },
1181
+ fetch: options.fetch || fetch$1,
1182
+ refreshToken: options.refreshToken || '',
1183
+ ...options
1184
+ }));
1185
+ }
1186
+
1187
+ withExistingTokenFlow(authorization, options) {
1188
+ return this.withAuthMiddleware(createAuthMiddlewareWithExistingToken(authorization, {
1189
+ force: options.force || true,
1190
+ ...options
1191
+ }));
1192
+ }
1193
+
1194
+ withHttpMiddleware(options) {
1195
+ this.httpMiddleware = createHttpMiddleware({
1196
+ host: options.host || 'https://api.europe-west1.gcp.commercetools.com',
1197
+ fetch: options.fetch || fetch$1,
1198
+ ...options
1199
+ });
1200
+ return this;
1201
+ }
1202
+
1203
+ withUserAgentMiddleware() {
1204
+ this.userAgentMiddleware = createUserAgentMiddleware();
1205
+ return this;
1206
+ }
1207
+
1208
+ withQueueMiddleware(options) {
1209
+ this.queueMiddleware = createQueueMiddleware({
1210
+ concurrency: options.concurrency || 20,
1211
+ ...options
1212
+ });
1213
+ return this;
1214
+ }
1215
+
1216
+ withLoggerMiddleware() {
1217
+ this.loggerMiddleware = createLoggerMiddleware();
1218
+ return this;
1219
+ }
1220
+
1221
+ withCorrelationIdMiddleware(options) {
1222
+ this.correlationIdMiddleware = createCorrelationIdMiddleware({
1223
+ generate: options.generate || null,
1224
+ ...options
1225
+ });
1226
+ return this;
1227
+ }
1572
1228
 
1573
- return ClientBuilder;
1574
- }();
1229
+ build() {
1230
+ const middlewares = this.middlewares.slice();
1231
+ if (this.correlationIdMiddleware) middlewares.push(this.correlationIdMiddleware);
1232
+ if (this.userAgentMiddleware) middlewares.push(this.userAgentMiddleware);
1233
+ if (this.authMiddleware) middlewares.push(this.authMiddleware);
1234
+ if (this.loggerMiddleware) middlewares.push(this.loggerMiddleware);
1235
+ if (this.queueMiddleware) middlewares.push(this.queueMiddleware);
1236
+ if (this.httpMiddleware) middlewares.push(this.httpMiddleware);
1237
+ return createClient({
1238
+ middlewares
1239
+ });
1240
+ }
1241
+
1242
+ }
1575
1243
 
1576
- export { ClientBuilder, createAuthMiddlewareForAnonymousSessionFlow$1 as createAuthForAnonymousSessionFlow, createAuthMiddlewareForClientCredentialsFlow$1 as createAuthForClientCredentialsFlow, createAuthMiddlewareForPasswordFlow$1 as createAuthForPasswordFlow, createAuthMiddlewareForRefreshTokenFlow$1 as createAuthForRefreshTokenFlow, createAuthMiddlewareWithExistingToken$1 as createAuthWithExistingToken, createClient, createCorrelationIdMiddleware, createHttpMiddleware as createHttpClient, createLoggerMiddleware, createQueueMiddleware, createUserAgentMiddleware, errors, getErrorByCode };
1244
+ export { ClientBuilder, createAuthMiddlewareForAnonymousSessionFlow$1 as createAuthForAnonymousSessionFlow, createAuthMiddlewareForClientCredentialsFlow$1 as createAuthForClientCredentialsFlow, createAuthMiddlewareForPasswordFlow$1 as createAuthForPasswordFlow, createAuthMiddlewareForRefreshTokenFlow$1 as createAuthForRefreshTokenFlow, createAuthMiddlewareWithExistingToken$1 as createAuthWithExistingToken, createClient, createCorrelationIdMiddleware, createHttpMiddleware as createHttpClient, createLoggerMiddleware, createQueueMiddleware, createUserAgentMiddleware, getErrorByCode };