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