@commercetools/sdk-client-v2 0.1.2 → 1.0.2

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