@commercetools/sdk-client-v2 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/commercetools-sdk-client-v2.browser.cjs.js +780 -1156
- package/dist/commercetools-sdk-client-v2.browser.esm.js +780 -1156
- package/dist/commercetools-sdk-client-v2.cjs.dev.js +780 -1156
- package/dist/commercetools-sdk-client-v2.cjs.prod.js +780 -1156
- package/dist/commercetools-sdk-client-v2.esm.js +780 -1156
- package/dist/commercetools-sdk-client-v2.umd.js +1 -1
- package/dist/declarations/src/client-builder/ClientBuilder.d.ts +26 -26
- package/dist/declarations/src/http-user-agent/create-user-agent.d.ts +2 -2
- package/dist/declarations/src/index.d.ts +14 -14
- package/dist/declarations/src/sdk-client/allowed-methods.d.ts +2 -2
- package/dist/declarations/src/sdk-client/client.d.ts +2 -2
- package/dist/declarations/src/sdk-client/errors.d.ts +10 -10
- package/dist/declarations/src/sdk-client/validate.d.ts +7 -7
- package/dist/declarations/src/sdk-middleware-auth/anonymous-session-flow.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-auth/base-auth-flow.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-auth/build-requests.d.ts +11 -11
- package/dist/declarations/src/sdk-middleware-auth/build-token-cache-key.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-auth/client-credentials-flow.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-auth/existing-token.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-auth/index.d.ts +5 -5
- package/dist/declarations/src/sdk-middleware-auth/password-flow.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-auth/refresh-token-flow.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-auth/utils.d.ts +4 -4
- package/dist/declarations/src/sdk-middleware-correlation-id/correlation-id.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-http/http.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-http/parse-headers.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-logger/logger.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-queue/queue.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-user-agent/user-agent.d.ts +2 -2
- package/package.json +4 -4
- 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
|
-
|
|
207
|
-
|
|
208
|
-
};
|
|
209
|
-
if (
|
|
210
|
-
if (
|
|
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
|
-
|
|
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(
|
|
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
|
|
56
|
+
execute(request) {
|
|
239
57
|
validate('exec', request);
|
|
240
|
-
return new Promise(
|
|
241
|
-
|
|
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
|
-
|
|
65
|
+
const resObj = {
|
|
248
66
|
body: rs.body || {},
|
|
249
67
|
statusCode: rs.statusCode
|
|
250
68
|
};
|
|
@@ -254,157 +72,106 @@ function createClient(options) {
|
|
|
254
72
|
}
|
|
255
73
|
};
|
|
256
74
|
|
|
257
|
-
|
|
75
|
+
const dispatch = compose(...options.middlewares)(resolver);
|
|
258
76
|
dispatch(request, // Initial response shape
|
|
259
77
|
{
|
|
260
|
-
resolve
|
|
261
|
-
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
|
-
|
|
92
|
+
const opt = {
|
|
276
93
|
total: Number.POSITIVE_INFINITY,
|
|
277
|
-
accumulate: true
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
return new Promise(
|
|
281
|
-
|
|
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
|
-
|
|
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
|
-
|
|
295
|
-
|
|
296
|
-
|
|
107
|
+
const requestQuery = { ...qs__default["default"].parse(_queryString)
|
|
108
|
+
};
|
|
109
|
+
const query = {
|
|
297
110
|
// defaults
|
|
298
|
-
limit: 20
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
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
|
-
|
|
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
|
|
|
@@ -415,21 +182,22 @@ function buildRequestForClientCredentialsFlow(options) {
|
|
|
415
182
|
if (!options.host) throw new Error('Missing required option (host)');
|
|
416
183
|
if (!options.projectKey) throw new Error('Missing required option (projectKey)');
|
|
417
184
|
if (!options.credentials) throw new Error('Missing required option (credentials)');
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
185
|
+
const {
|
|
186
|
+
clientId,
|
|
187
|
+
clientSecret
|
|
188
|
+
} = options.credentials;
|
|
421
189
|
if (!(clientId && clientSecret)) throw new Error('Missing required credentials (clientId, clientSecret)');
|
|
422
|
-
|
|
423
|
-
|
|
190
|
+
const scope = options.scopes ? options.scopes.join(' ') : undefined;
|
|
191
|
+
const basicAuth = Buffer.from(`${clientId}:${clientSecret}`).toString('base64'); // This is mostly useful for internal testing purposes to be able to check
|
|
424
192
|
// other oauth endpoints.
|
|
425
193
|
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
194
|
+
const oauthUri = options.oauthUri || '/oauth/token';
|
|
195
|
+
const url = options.host.replace(/\/$/, '') + oauthUri;
|
|
196
|
+
const body = `grant_type=client_credentials${scope ? `&scope=${scope}` : ''}`;
|
|
429
197
|
return {
|
|
430
|
-
basicAuth
|
|
431
|
-
url
|
|
432
|
-
body
|
|
198
|
+
basicAuth,
|
|
199
|
+
url,
|
|
200
|
+
body
|
|
433
201
|
};
|
|
434
202
|
}
|
|
435
203
|
function buildRequestForPasswordFlow(options) {
|
|
@@ -437,31 +205,34 @@ function buildRequestForPasswordFlow(options) {
|
|
|
437
205
|
if (!options.host) throw new Error('Missing required option (host)');
|
|
438
206
|
if (!options.projectKey) throw new Error('Missing required option (projectKey)');
|
|
439
207
|
if (!options.credentials) throw new Error('Missing required option (credentials)');
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
208
|
+
const {
|
|
209
|
+
clientId,
|
|
210
|
+
clientSecret,
|
|
211
|
+
user
|
|
212
|
+
} = options.credentials;
|
|
213
|
+
const pKey = options.projectKey;
|
|
445
214
|
if (!(clientId && clientSecret && user)) throw new Error('Missing required credentials (clientId, clientSecret, user)');
|
|
446
|
-
|
|
447
|
-
|
|
215
|
+
const {
|
|
216
|
+
username,
|
|
217
|
+
password
|
|
218
|
+
} = user;
|
|
448
219
|
if (!(username && password)) throw new Error('Missing required user credentials (username, password)');
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
220
|
+
const scope = (options.scopes || []).join(' ');
|
|
221
|
+
const scopeStr = scope ? `&scope=${scope}` : '';
|
|
222
|
+
const basicAuth = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
|
|
452
223
|
/**
|
|
453
224
|
* This is mostly useful for internal testing purposes to be able to check
|
|
454
225
|
* other oauth endpoints.
|
|
455
226
|
*/
|
|
456
227
|
|
|
457
|
-
|
|
458
|
-
|
|
228
|
+
const oauthUri = options.oauthUri || `/oauth/${pKey}/customers/token`;
|
|
229
|
+
const url = options.host.replace(/\/$/, '') + oauthUri; // encode username and password as requested by platform
|
|
459
230
|
|
|
460
|
-
|
|
231
|
+
const body = `grant_type=password&username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}${scopeStr}`;
|
|
461
232
|
return {
|
|
462
|
-
basicAuth
|
|
463
|
-
url
|
|
464
|
-
body
|
|
233
|
+
basicAuth,
|
|
234
|
+
url,
|
|
235
|
+
body
|
|
465
236
|
};
|
|
466
237
|
}
|
|
467
238
|
function buildRequestForRefreshTokenFlow(options) {
|
|
@@ -470,38 +241,40 @@ function buildRequestForRefreshTokenFlow(options) {
|
|
|
470
241
|
if (!options.projectKey) throw new Error('Missing required option (projectKey)');
|
|
471
242
|
if (!options.credentials) throw new Error('Missing required option (credentials)');
|
|
472
243
|
if (!options.refreshToken) throw new Error('Missing required option (refreshToken)');
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
244
|
+
const {
|
|
245
|
+
clientId,
|
|
246
|
+
clientSecret
|
|
247
|
+
} = options.credentials;
|
|
476
248
|
if (!(clientId && clientSecret)) throw new Error('Missing required credentials (clientId, clientSecret)');
|
|
477
|
-
|
|
249
|
+
const basicAuth = Buffer.from(`${clientId}:${clientSecret}`).toString('base64'); // This is mostly useful for internal testing purposes to be able to check
|
|
478
250
|
// other oauth endpoints.
|
|
479
251
|
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
252
|
+
const oauthUri = options.oauthUri || '/oauth/token';
|
|
253
|
+
const url = options.host.replace(/\/$/, '') + oauthUri;
|
|
254
|
+
const body = `grant_type=refresh_token&refresh_token=${encodeURIComponent(options.refreshToken)}`;
|
|
483
255
|
return {
|
|
484
|
-
basicAuth
|
|
485
|
-
url
|
|
486
|
-
body
|
|
256
|
+
basicAuth,
|
|
257
|
+
url,
|
|
258
|
+
body
|
|
487
259
|
};
|
|
488
260
|
}
|
|
489
261
|
function buildRequestForAnonymousSessionFlow(options) {
|
|
490
262
|
if (!options) throw new Error('Missing required options');
|
|
491
263
|
if (!options.projectKey) throw new Error('Missing required option (projectKey)');
|
|
492
|
-
|
|
493
|
-
options.oauthUri = options.oauthUri ||
|
|
494
|
-
|
|
495
|
-
if (options.credentials.anonymousId) result.body +=
|
|
496
|
-
return
|
|
264
|
+
const pKey = options.projectKey;
|
|
265
|
+
options.oauthUri = options.oauthUri || `/oauth/${pKey}/anonymous/token`;
|
|
266
|
+
const result = buildRequestForClientCredentialsFlow(options);
|
|
267
|
+
if (options.credentials.anonymousId) result.body += `&anonymous_id=${options.credentials.anonymousId}`;
|
|
268
|
+
return { ...result
|
|
269
|
+
};
|
|
497
270
|
}
|
|
498
271
|
|
|
499
272
|
function mergeAuthHeader(token, req) {
|
|
500
|
-
return
|
|
501
|
-
headers:
|
|
502
|
-
Authorization:
|
|
503
|
-
}
|
|
504
|
-
}
|
|
273
|
+
return { ...req,
|
|
274
|
+
headers: { ...req.headers,
|
|
275
|
+
Authorization: `Bearer ${token}`
|
|
276
|
+
}
|
|
277
|
+
};
|
|
505
278
|
}
|
|
506
279
|
|
|
507
280
|
function calculateExpirationTime(expiresIn) {
|
|
@@ -509,136 +282,108 @@ function calculateExpirationTime(expiresIn) {
|
|
|
509
282
|
expiresIn * 1000 - 2 * 60 * 60 * 1000;
|
|
510
283
|
}
|
|
511
284
|
|
|
512
|
-
function executeRequest(
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
},
|
|
534
|
-
body: body
|
|
535
|
-
});
|
|
285
|
+
async function executeRequest({
|
|
286
|
+
fetcher,
|
|
287
|
+
url,
|
|
288
|
+
basicAuth,
|
|
289
|
+
body,
|
|
290
|
+
tokenCache,
|
|
291
|
+
requestState,
|
|
292
|
+
pendingTasks,
|
|
293
|
+
response,
|
|
294
|
+
tokenCacheKey
|
|
295
|
+
}) {
|
|
296
|
+
try {
|
|
297
|
+
const _res = await fetcher(url, {
|
|
298
|
+
method: 'POST',
|
|
299
|
+
headers: {
|
|
300
|
+
Authorization: `Basic ${basicAuth}`,
|
|
301
|
+
'Content-Length': Buffer.byteLength(body).toString(),
|
|
302
|
+
'Content-Type': 'application/x-www-form-urlencoded'
|
|
303
|
+
},
|
|
304
|
+
body
|
|
305
|
+
});
|
|
536
306
|
|
|
537
|
-
|
|
538
|
-
|
|
307
|
+
if (_res.ok) {
|
|
308
|
+
const {
|
|
309
|
+
access_token: token,
|
|
310
|
+
expires_in: expiresIn,
|
|
311
|
+
refresh_token: refreshToken
|
|
312
|
+
} = await _res.json();
|
|
313
|
+
const expirationTime = calculateExpirationTime(expiresIn); // cache new generated token
|
|
314
|
+
|
|
315
|
+
tokenCache.set({
|
|
316
|
+
token,
|
|
317
|
+
expirationTime,
|
|
318
|
+
refreshToken
|
|
319
|
+
}, tokenCacheKey); // Dispatch all pending requests
|
|
320
|
+
|
|
321
|
+
requestState.set(false);
|
|
322
|
+
/**
|
|
323
|
+
* Freeze and copy pending queue, reset original one for accepting
|
|
324
|
+
* new pending tasks
|
|
325
|
+
*/
|
|
539
326
|
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
327
|
+
const executionQueue = pendingTasks.slice();
|
|
328
|
+
pendingTasks = [];
|
|
329
|
+
executionQueue.forEach(task => {
|
|
330
|
+
// Assign the new token in the request header
|
|
331
|
+
const requestWithAuth = mergeAuthHeader(token, task.request);
|
|
332
|
+
/**
|
|
333
|
+
* console.log('test', cache, pendingTasks)
|
|
334
|
+
* Continue by calling the task's own next function
|
|
335
|
+
*/
|
|
336
|
+
|
|
337
|
+
task.next(requestWithAuth, task.response);
|
|
338
|
+
});
|
|
339
|
+
return;
|
|
340
|
+
} // Handle error response
|
|
544
341
|
|
|
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
342
|
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
return _res.text();
|
|
343
|
+
let parsed;
|
|
344
|
+
const text = await _res.text();
|
|
584
345
|
|
|
585
|
-
|
|
586
|
-
|
|
346
|
+
try {
|
|
347
|
+
parsed = JSON.parse(text);
|
|
348
|
+
} catch (error) {
|
|
349
|
+
/* noop */
|
|
350
|
+
}
|
|
587
351
|
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
352
|
+
const error = new Error(parsed ? parsed.message : text);
|
|
353
|
+
if (parsed) error.body = parsed;
|
|
354
|
+
/**
|
|
355
|
+
* to notify that token is either fetched or failed
|
|
356
|
+
* in the below case token failed to be fetched
|
|
357
|
+
* and reset requestState to false
|
|
358
|
+
* so requestState could be shared between multi authMiddlewareBase functions
|
|
359
|
+
*/
|
|
593
360
|
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
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);
|
|
361
|
+
requestState.set(false);
|
|
362
|
+
response.reject(error);
|
|
363
|
+
} catch (error) {
|
|
364
|
+
/**
|
|
365
|
+
* to notify that token is either fetched or failed
|
|
366
|
+
* in the below case token failed to be fetched
|
|
367
|
+
* and reset requestState to false
|
|
368
|
+
* so requestState could be shared between multi authMiddlewareBase functions
|
|
369
|
+
*/
|
|
370
|
+
requestState.set(false);
|
|
371
|
+
if (response && typeof response.reject === 'function') response.reject(error);
|
|
372
|
+
}
|
|
629
373
|
}
|
|
630
374
|
|
|
631
|
-
function authMiddlewareBase(
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
375
|
+
function authMiddlewareBase({
|
|
376
|
+
request,
|
|
377
|
+
response,
|
|
378
|
+
url,
|
|
379
|
+
basicAuth,
|
|
380
|
+
body,
|
|
381
|
+
pendingTasks,
|
|
382
|
+
requestState,
|
|
383
|
+
tokenCache,
|
|
384
|
+
tokenCacheKey,
|
|
385
|
+
fetch: fetcher
|
|
386
|
+
}, next, userOptions) {
|
|
642
387
|
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
388
|
if (!fetcher) fetcher = fetch; // Check if there is already a `Authorization` header in the request.
|
|
644
389
|
// If so, then go directly to the next middleware.
|
|
@@ -650,10 +395,10 @@ function authMiddlewareBase(_ref2, next, userOptions) {
|
|
|
650
395
|
// the token in the `Authorization` header.
|
|
651
396
|
|
|
652
397
|
|
|
653
|
-
|
|
398
|
+
const tokenObj = tokenCache.get(tokenCacheKey);
|
|
654
399
|
|
|
655
400
|
if (tokenObj && tokenObj.token && Date.now() < tokenObj.expirationTime) {
|
|
656
|
-
|
|
401
|
+
const requestWithAuth = mergeAuthHeader(tokenObj.token, request);
|
|
657
402
|
next(requestWithAuth, response);
|
|
658
403
|
return;
|
|
659
404
|
}
|
|
@@ -666,9 +411,9 @@ function authMiddlewareBase(_ref2, next, userOptions) {
|
|
|
666
411
|
|
|
667
412
|
|
|
668
413
|
pendingTasks.push({
|
|
669
|
-
request
|
|
670
|
-
response
|
|
671
|
-
next
|
|
414
|
+
request,
|
|
415
|
+
response,
|
|
416
|
+
next
|
|
672
417
|
}); // If a token is currently being fetched, just wait ;)
|
|
673
418
|
|
|
674
419
|
if (requestState.get()) return; // Mark that a token is being fetched
|
|
@@ -681,41 +426,39 @@ function authMiddlewareBase(_ref2, next, userOptions) {
|
|
|
681
426
|
|
|
682
427
|
if (tokenObj && tokenObj.refreshToken && (!tokenObj.token || tokenObj.token && Date.now() > tokenObj.expirationTime)) {
|
|
683
428
|
if (!userOptions) throw new Error('Missing required options');
|
|
684
|
-
executeRequest(
|
|
685
|
-
fetcher
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
tokenCacheKey
|
|
690
|
-
tokenCache
|
|
691
|
-
requestState
|
|
692
|
-
pendingTasks
|
|
693
|
-
response
|
|
694
|
-
})
|
|
429
|
+
executeRequest({
|
|
430
|
+
fetcher,
|
|
431
|
+
...buildRequestForRefreshTokenFlow({ ...userOptions,
|
|
432
|
+
refreshToken: tokenObj.refreshToken
|
|
433
|
+
}),
|
|
434
|
+
tokenCacheKey,
|
|
435
|
+
tokenCache,
|
|
436
|
+
requestState,
|
|
437
|
+
pendingTasks,
|
|
438
|
+
response
|
|
439
|
+
});
|
|
695
440
|
return;
|
|
696
441
|
} // Token and refreshToken are not present or invalid. Request a new token...
|
|
697
442
|
|
|
698
443
|
|
|
699
444
|
executeRequest({
|
|
700
|
-
fetcher
|
|
701
|
-
url
|
|
702
|
-
basicAuth
|
|
703
|
-
body
|
|
704
|
-
tokenCacheKey
|
|
705
|
-
tokenCache
|
|
706
|
-
requestState
|
|
707
|
-
pendingTasks
|
|
708
|
-
response
|
|
445
|
+
fetcher,
|
|
446
|
+
url,
|
|
447
|
+
basicAuth,
|
|
448
|
+
body,
|
|
449
|
+
tokenCacheKey,
|
|
450
|
+
tokenCache,
|
|
451
|
+
requestState,
|
|
452
|
+
pendingTasks,
|
|
453
|
+
response
|
|
709
454
|
});
|
|
710
455
|
}
|
|
711
456
|
|
|
712
457
|
function store(initVal) {
|
|
713
|
-
|
|
458
|
+
let value = initVal;
|
|
714
459
|
return {
|
|
715
|
-
get:
|
|
716
|
-
|
|
717
|
-
},
|
|
718
|
-
set: function set(val) {
|
|
460
|
+
get: () => value,
|
|
461
|
+
set: val => {
|
|
719
462
|
value = val;
|
|
720
463
|
return value;
|
|
721
464
|
}
|
|
@@ -723,30 +466,27 @@ function store(initVal) {
|
|
|
723
466
|
}
|
|
724
467
|
|
|
725
468
|
function createAuthMiddlewareForAnonymousSessionFlow$1(options) {
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
return
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
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
|
-
});
|
|
469
|
+
const tokenCache = store({});
|
|
470
|
+
const pendingTasks = [];
|
|
471
|
+
const requestState = store(false);
|
|
472
|
+
return next => (request, response) => {
|
|
473
|
+
// Check if there is already a `Authorization` header in the request.
|
|
474
|
+
// If so, then go directly to the next middleware.
|
|
475
|
+
if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
|
|
476
|
+
next(request, response);
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
747
479
|
|
|
748
|
-
|
|
480
|
+
const params = {
|
|
481
|
+
request,
|
|
482
|
+
response,
|
|
483
|
+
...buildRequestForAnonymousSessionFlow(options),
|
|
484
|
+
pendingTasks,
|
|
485
|
+
requestState,
|
|
486
|
+
tokenCache,
|
|
487
|
+
fetch: options.fetch
|
|
749
488
|
};
|
|
489
|
+
authMiddlewareBase(params, next, options);
|
|
750
490
|
};
|
|
751
491
|
}
|
|
752
492
|
|
|
@@ -759,186 +499,127 @@ function buildTokenCacheKey(options) {
|
|
|
759
499
|
}
|
|
760
500
|
|
|
761
501
|
function createAuthMiddlewareForClientCredentialsFlow$1(options) {
|
|
762
|
-
|
|
502
|
+
const tokenCache = options.tokenCache || store({
|
|
763
503
|
token: '',
|
|
764
504
|
expirationTime: -1
|
|
765
505
|
});
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
return
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
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
|
-
});
|
|
506
|
+
const requestState = store(false);
|
|
507
|
+
const pendingTasks = [];
|
|
508
|
+
return next => (request, response) => {
|
|
509
|
+
// Check if there is already a `Authorization` header in the request.
|
|
510
|
+
// If so, then go directly to the next middleware.
|
|
511
|
+
if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
|
|
512
|
+
next(request, response);
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
787
515
|
|
|
788
|
-
|
|
516
|
+
const params = {
|
|
517
|
+
request,
|
|
518
|
+
response,
|
|
519
|
+
...buildRequestForClientCredentialsFlow(options),
|
|
520
|
+
pendingTasks,
|
|
521
|
+
requestState,
|
|
522
|
+
tokenCache,
|
|
523
|
+
tokenCacheKey: buildTokenCacheKey(options),
|
|
524
|
+
fetch: options.fetch
|
|
789
525
|
};
|
|
526
|
+
authMiddlewareBase(params, next);
|
|
790
527
|
};
|
|
791
528
|
}
|
|
792
529
|
|
|
793
|
-
function createAuthMiddlewareWithExistingToken$1() {
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
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
|
-
}
|
|
530
|
+
function createAuthMiddlewareWithExistingToken$1(authorization = '', options = {}) {
|
|
531
|
+
return next => (request, response) => {
|
|
532
|
+
if (typeof authorization !== 'string') throw new Error('authorization must be a string');
|
|
533
|
+
const force = options.force === undefined ? true : options.force;
|
|
534
|
+
/** The request will not be modified if:
|
|
535
|
+
* 1. no argument is passed
|
|
536
|
+
* 2. force is false and authorization header exists
|
|
537
|
+
*/
|
|
808
538
|
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
})
|
|
813
|
-
});
|
|
539
|
+
if (!authorization || (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) && force === false) {
|
|
540
|
+
return next(request, response);
|
|
541
|
+
}
|
|
814
542
|
|
|
815
|
-
|
|
543
|
+
const requestWithAuth = { ...request,
|
|
544
|
+
headers: { ...request.headers,
|
|
545
|
+
Authorization: authorization
|
|
546
|
+
}
|
|
816
547
|
};
|
|
548
|
+
return next(requestWithAuth, response);
|
|
817
549
|
};
|
|
818
550
|
}
|
|
819
551
|
|
|
820
552
|
function createAuthMiddlewareForPasswordFlow$1(options) {
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
return
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
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
|
-
});
|
|
553
|
+
const tokenCache = store({});
|
|
554
|
+
const pendingTasks = [];
|
|
555
|
+
const requestState = store(false);
|
|
556
|
+
return next => (request, response) => {
|
|
557
|
+
// Check if there is already a `Authorization` header in the request.
|
|
558
|
+
// If so, then go directly to the next middleware.
|
|
559
|
+
if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
|
|
560
|
+
next(request, response);
|
|
561
|
+
return;
|
|
562
|
+
}
|
|
842
563
|
|
|
843
|
-
|
|
564
|
+
const params = {
|
|
565
|
+
request,
|
|
566
|
+
response,
|
|
567
|
+
...buildRequestForPasswordFlow(options),
|
|
568
|
+
pendingTasks,
|
|
569
|
+
requestState,
|
|
570
|
+
tokenCache,
|
|
571
|
+
fetch: options.fetch
|
|
844
572
|
};
|
|
573
|
+
authMiddlewareBase(params, next, options);
|
|
845
574
|
};
|
|
846
575
|
}
|
|
847
576
|
|
|
848
577
|
function createAuthMiddlewareForRefreshTokenFlow$1(options) {
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
return
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
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
|
-
});
|
|
578
|
+
const tokenCache = store({});
|
|
579
|
+
const pendingTasks = [];
|
|
580
|
+
const requestState = store(false);
|
|
581
|
+
return next => (request, response) => {
|
|
582
|
+
// Check if there is already a `Authorization` header in the request.
|
|
583
|
+
// If so, then go directly to the next middleware.
|
|
584
|
+
if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
|
|
585
|
+
next(request, response);
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
870
588
|
|
|
871
|
-
|
|
589
|
+
const params = {
|
|
590
|
+
request,
|
|
591
|
+
response,
|
|
592
|
+
...buildRequestForRefreshTokenFlow(options),
|
|
593
|
+
pendingTasks,
|
|
594
|
+
requestState,
|
|
595
|
+
tokenCache,
|
|
596
|
+
fetch: options.fetch
|
|
872
597
|
};
|
|
598
|
+
authMiddlewareBase(params, next);
|
|
873
599
|
};
|
|
874
600
|
}
|
|
875
601
|
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
602
|
+
var authMiddlewares = /*#__PURE__*/Object.freeze({
|
|
603
|
+
__proto__: null,
|
|
604
|
+
createAuthMiddlewareForAnonymousSessionFlow: createAuthMiddlewareForAnonymousSessionFlow$1,
|
|
605
|
+
createAuthMiddlewareForClientCredentialsFlow: createAuthMiddlewareForClientCredentialsFlow$1,
|
|
606
|
+
createAuthMiddlewareWithExistingToken: createAuthMiddlewareWithExistingToken$1,
|
|
607
|
+
createAuthMiddlewareForPasswordFlow: createAuthMiddlewareForPasswordFlow$1,
|
|
608
|
+
createAuthMiddlewareForRefreshTokenFlow: createAuthMiddlewareForRefreshTokenFlow$1
|
|
609
|
+
});
|
|
884
610
|
|
|
885
|
-
|
|
611
|
+
function createCorrelationIdMiddleware(options) {
|
|
612
|
+
return next => (request, response) => {
|
|
613
|
+
const nextRequest = { ...request,
|
|
614
|
+
headers: { ...request.headers,
|
|
615
|
+
'X-Correlation-ID': options.generate()
|
|
616
|
+
}
|
|
886
617
|
};
|
|
618
|
+
next(nextRequest, response);
|
|
887
619
|
};
|
|
888
620
|
}
|
|
889
621
|
|
|
890
|
-
function
|
|
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] : {};
|
|
622
|
+
function defineError(statusCode, message, meta = {}) {
|
|
942
623
|
this.status = this.statusCode = this.code = statusCode;
|
|
943
624
|
this.message = message;
|
|
944
625
|
Object.assign(this, meta);
|
|
@@ -947,70 +628,36 @@ function defineError(statusCode, message) {
|
|
|
947
628
|
if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
|
|
948
629
|
}
|
|
949
630
|
|
|
950
|
-
function NetworkError() {
|
|
951
|
-
|
|
952
|
-
args[_key] = arguments[_key];
|
|
953
|
-
}
|
|
954
|
-
|
|
955
|
-
defineError.call.apply(defineError, [this, 0
|
|
631
|
+
function NetworkError(...args) {
|
|
632
|
+
defineError.call(this, 0
|
|
956
633
|
/* special code to indicate network errors */
|
|
957
|
-
|
|
634
|
+
, ...args);
|
|
958
635
|
}
|
|
959
|
-
function HttpError() {
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
defineError.call.apply(defineError, [this].concat(args));
|
|
636
|
+
function HttpError(...args) {
|
|
637
|
+
defineError.call(this,
|
|
638
|
+
/* code will be passed as arg */
|
|
639
|
+
...args);
|
|
965
640
|
}
|
|
966
|
-
function BadRequest() {
|
|
967
|
-
|
|
968
|
-
args[_key3] = arguments[_key3];
|
|
969
|
-
}
|
|
970
|
-
|
|
971
|
-
defineError.call.apply(defineError, [this, 400].concat(args));
|
|
641
|
+
function BadRequest(...args) {
|
|
642
|
+
defineError.call(this, 400, ...args);
|
|
972
643
|
}
|
|
973
|
-
function Unauthorized() {
|
|
974
|
-
|
|
975
|
-
args[_key4] = arguments[_key4];
|
|
976
|
-
}
|
|
977
|
-
|
|
978
|
-
defineError.call.apply(defineError, [this, 401].concat(args));
|
|
644
|
+
function Unauthorized(...args) {
|
|
645
|
+
defineError.call(this, 401, ...args);
|
|
979
646
|
}
|
|
980
|
-
function Forbidden() {
|
|
981
|
-
|
|
982
|
-
args[_key5] = arguments[_key5];
|
|
983
|
-
}
|
|
984
|
-
|
|
985
|
-
defineError.call.apply(defineError, [this, 403].concat(args));
|
|
647
|
+
function Forbidden(...args) {
|
|
648
|
+
defineError.call(this, 403, ...args);
|
|
986
649
|
}
|
|
987
|
-
function NotFound() {
|
|
988
|
-
|
|
989
|
-
args[_key6] = arguments[_key6];
|
|
990
|
-
}
|
|
991
|
-
|
|
992
|
-
defineError.call.apply(defineError, [this, 404].concat(args));
|
|
650
|
+
function NotFound(...args) {
|
|
651
|
+
defineError.call(this, 404, ...args);
|
|
993
652
|
}
|
|
994
|
-
function ConcurrentModification() {
|
|
995
|
-
|
|
996
|
-
args[_key7] = arguments[_key7];
|
|
997
|
-
}
|
|
998
|
-
|
|
999
|
-
defineError.call.apply(defineError, [this, 409].concat(args));
|
|
653
|
+
function ConcurrentModification(...args) {
|
|
654
|
+
defineError.call(this, 409, ...args);
|
|
1000
655
|
}
|
|
1001
|
-
function InternalServerError() {
|
|
1002
|
-
|
|
1003
|
-
args[_key8] = arguments[_key8];
|
|
1004
|
-
}
|
|
1005
|
-
|
|
1006
|
-
defineError.call.apply(defineError, [this, 500].concat(args));
|
|
656
|
+
function InternalServerError(...args) {
|
|
657
|
+
defineError.call(this, 500, ...args);
|
|
1007
658
|
}
|
|
1008
|
-
function ServiceUnavailable() {
|
|
1009
|
-
|
|
1010
|
-
args[_key9] = arguments[_key9];
|
|
1011
|
-
}
|
|
1012
|
-
|
|
1013
|
-
defineError.call.apply(defineError, [this, 503].concat(args));
|
|
659
|
+
function ServiceUnavailable(...args) {
|
|
660
|
+
defineError.call(this, 503, ...args);
|
|
1014
661
|
}
|
|
1015
662
|
function getErrorByCode(code) {
|
|
1016
663
|
switch (code) {
|
|
@@ -1049,23 +696,21 @@ function parseHeaders(headers) {
|
|
|
1049
696
|
|
|
1050
697
|
if (!headers.forEach) return {}; // whatwg-fetch
|
|
1051
698
|
|
|
1052
|
-
|
|
1053
|
-
headers.forEach(
|
|
699
|
+
const map = {};
|
|
700
|
+
headers.forEach((value, name) => {
|
|
1054
701
|
map[name] = value;
|
|
1055
702
|
});
|
|
1056
703
|
return map;
|
|
1057
704
|
}
|
|
1058
705
|
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
if (statusCode === 404) errorMessage = "URI not found: ".concat(rest.originalRequest.uri);
|
|
1068
|
-
var ResponseError = getErrorByCode(statusCode);
|
|
706
|
+
function createError({
|
|
707
|
+
statusCode,
|
|
708
|
+
message,
|
|
709
|
+
...rest
|
|
710
|
+
}) {
|
|
711
|
+
let errorMessage = message || 'Unexpected non-JSON error response';
|
|
712
|
+
if (statusCode === 404) errorMessage = `URI not found: ${rest.originalRequest.uri}`;
|
|
713
|
+
const ResponseError = getErrorByCode(statusCode);
|
|
1069
714
|
if (ResponseError) return new ResponseError(errorMessage, rest);
|
|
1070
715
|
return new HttpError(statusCode, errorMessage, rest);
|
|
1071
716
|
} // calculates the delay duration exponentially
|
|
@@ -1074,7 +719,7 @@ function createError(_ref) {
|
|
|
1074
719
|
|
|
1075
720
|
function calcDelayDuration(retryCount, retryDelay, maxRetries, backoff, maxDelay) {
|
|
1076
721
|
if (backoff) return retryCount !== 0 // do not increase if it's the first retry
|
|
1077
|
-
? Math.min(Math.round((Math.random() + 1) * retryDelay *
|
|
722
|
+
? Math.min(Math.round((Math.random() + 1) * retryDelay * 2 ** retryCount), maxDelay) : retryDelay;
|
|
1078
723
|
return retryDelay;
|
|
1079
724
|
}
|
|
1080
725
|
|
|
@@ -1085,30 +730,27 @@ function maskAuthData(request, maskSensitiveHeaderData) {
|
|
|
1085
730
|
}
|
|
1086
731
|
}
|
|
1087
732
|
|
|
1088
|
-
function createHttpMiddleware(
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
maxDelay = _ref2$retryConfig$max2 === void 0 ? Infinity : _ref2$retryConfig$max2,
|
|
1107
|
-
fetcher = _ref2.fetch,
|
|
1108
|
-
getAbortController = _ref2.getAbortController;
|
|
733
|
+
function createHttpMiddleware({
|
|
734
|
+
host,
|
|
735
|
+
credentialsMode,
|
|
736
|
+
includeResponseHeaders,
|
|
737
|
+
includeOriginalRequest,
|
|
738
|
+
maskSensitiveHeaderData = true,
|
|
739
|
+
enableRetry,
|
|
740
|
+
timeout,
|
|
741
|
+
retryConfig: {
|
|
742
|
+
// encourage exponential backoff to prevent spamming the server if down
|
|
743
|
+
maxRetries = 10,
|
|
744
|
+
backoff = true,
|
|
745
|
+
retryDelay = 200,
|
|
746
|
+
maxDelay = Infinity
|
|
747
|
+
} = {},
|
|
748
|
+
fetch: fetcher,
|
|
749
|
+
getAbortController
|
|
750
|
+
}) {
|
|
1109
751
|
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
752
|
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
|
-
|
|
753
|
+
let fetchFunction;
|
|
1112
754
|
|
|
1113
755
|
if (fetcher) {
|
|
1114
756
|
fetchFunction = fetcher;
|
|
@@ -1119,259 +761,222 @@ function createHttpMiddleware(_ref2) {
|
|
|
1119
761
|
fetchFunction = fetch;
|
|
1120
762
|
}
|
|
1121
763
|
|
|
1122
|
-
return
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
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
|
-
}
|
|
764
|
+
return next => (request, response) => {
|
|
765
|
+
let abortController;
|
|
766
|
+
if (timeout || getAbortController) abortController = (getAbortController ? getAbortController() : null) || new AbortController();
|
|
767
|
+
const url = host.replace(/\/$/, '') + request.uri;
|
|
768
|
+
const body = typeof request.body === 'string' || Buffer.isBuffer(request.body) ? request.body : // NOTE: `stringify` of `null` gives the String('null')
|
|
769
|
+
JSON.stringify(request.body || undefined);
|
|
770
|
+
const requestHeader = { ...request.headers
|
|
771
|
+
};
|
|
1173
772
|
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
773
|
+
if (!Object.prototype.hasOwnProperty.call(requestHeader, 'Content-Type')) {
|
|
774
|
+
requestHeader['Content-Type'] = 'application/json';
|
|
775
|
+
}
|
|
1177
776
|
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
if (enableRetry && retryCount < maxRetries) {
|
|
1182
|
-
setTimeout(executeFetch, calcDelayDuration(retryCount, retryDelay, maxRetries, backoff, maxDelay));
|
|
1183
|
-
retryCount += 1;
|
|
1184
|
-
return;
|
|
1185
|
-
}
|
|
777
|
+
if (body) {
|
|
778
|
+
requestHeader['Content-Length'] = Buffer.byteLength(body).toString();
|
|
779
|
+
}
|
|
1186
780
|
|
|
1187
|
-
|
|
1188
|
-
|
|
781
|
+
const fetchOptions = {
|
|
782
|
+
method: request.method,
|
|
783
|
+
headers: requestHeader
|
|
784
|
+
};
|
|
1189
785
|
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
});
|
|
786
|
+
if (credentialsMode) {
|
|
787
|
+
fetchOptions.credentialsMode = credentialsMode;
|
|
788
|
+
}
|
|
1194
789
|
|
|
1195
|
-
|
|
790
|
+
if (abortController) {
|
|
791
|
+
fetchOptions.signal = abortController.signal;
|
|
792
|
+
}
|
|
1196
793
|
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
}
|
|
794
|
+
if (body) {
|
|
795
|
+
fetchOptions.body = body;
|
|
796
|
+
}
|
|
1201
797
|
|
|
1202
|
-
|
|
798
|
+
let retryCount = 0; // wrap in a fn so we can retry if error occur
|
|
799
|
+
|
|
800
|
+
function executeFetch() {
|
|
801
|
+
// Kick off timer for abortController directly before fetch.
|
|
802
|
+
let timer;
|
|
803
|
+
if (timeout) timer = setTimeout(() => {
|
|
804
|
+
abortController.abort();
|
|
805
|
+
}, timeout);
|
|
806
|
+
fetchFunction(url, fetchOptions).then(res => {
|
|
807
|
+
if (res.ok) {
|
|
808
|
+
if (fetchOptions.method === 'HEAD') {
|
|
809
|
+
next(request, { ...response,
|
|
810
|
+
statusCode: res.status
|
|
1203
811
|
});
|
|
1204
812
|
return;
|
|
1205
813
|
}
|
|
1206
814
|
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
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;
|
|
815
|
+
res.text().then(result => {
|
|
816
|
+
// Try to parse the response as JSON
|
|
817
|
+
let parsed;
|
|
1217
818
|
|
|
1218
819
|
try {
|
|
1219
|
-
parsed = JSON.parse(
|
|
1220
|
-
} catch (
|
|
1221
|
-
|
|
1222
|
-
|
|
820
|
+
parsed = result.length > 0 ? JSON.parse(result) : {};
|
|
821
|
+
} catch (err) {
|
|
822
|
+
if (enableRetry && retryCount < maxRetries) {
|
|
823
|
+
setTimeout(executeFetch, calcDelayDuration(retryCount, retryDelay, maxRetries, backoff, maxDelay));
|
|
824
|
+
retryCount += 1;
|
|
825
|
+
return;
|
|
826
|
+
}
|
|
1223
827
|
|
|
1224
|
-
|
|
1225
|
-
|
|
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
|
|
828
|
+
parsed = result;
|
|
829
|
+
}
|
|
1237
830
|
|
|
1238
|
-
|
|
1239
|
-
|
|
831
|
+
const parsedResponse = { ...response,
|
|
832
|
+
body: parsed,
|
|
1240
833
|
statusCode: res.status
|
|
1241
|
-
}
|
|
834
|
+
};
|
|
835
|
+
if (includeResponseHeaders) parsedResponse.headers = parseHeaders(res.headers);
|
|
836
|
+
|
|
837
|
+
if (includeOriginalRequest) {
|
|
838
|
+
parsedResponse.request = { ...fetchOptions
|
|
839
|
+
};
|
|
840
|
+
maskAuthData(parsedResponse.request, maskSensitiveHeaderData);
|
|
841
|
+
}
|
|
1242
842
|
|
|
1243
843
|
next(request, parsedResponse);
|
|
1244
844
|
});
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
845
|
+
return;
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
if (res.status === 503 && enableRetry) if (retryCount < maxRetries) {
|
|
849
|
+
setTimeout(executeFetch, calcDelayDuration(retryCount, retryDelay, maxRetries, backoff, maxDelay));
|
|
850
|
+
retryCount += 1;
|
|
851
|
+
return;
|
|
852
|
+
} // Server responded with an error. Try to parse it as JSON, then
|
|
853
|
+
// return a proper error type with all necessary meta information.
|
|
854
|
+
|
|
855
|
+
res.text().then(text => {
|
|
856
|
+
// Try to parse the error response as JSON
|
|
857
|
+
let parsed;
|
|
858
|
+
|
|
859
|
+
try {
|
|
860
|
+
parsed = JSON.parse(text);
|
|
861
|
+
} catch (error) {
|
|
862
|
+
parsed = text;
|
|
1251
863
|
}
|
|
1252
|
-
|
|
864
|
+
|
|
865
|
+
const error = createError({
|
|
866
|
+
statusCode: res.status,
|
|
1253
867
|
originalRequest: request,
|
|
1254
|
-
retryCount
|
|
868
|
+
retryCount,
|
|
869
|
+
headers: parseHeaders(res.headers),
|
|
870
|
+
...(typeof parsed === 'object' ? {
|
|
871
|
+
message: parsed.message,
|
|
872
|
+
body: parsed
|
|
873
|
+
} : {
|
|
874
|
+
message: parsed,
|
|
875
|
+
body: parsed
|
|
876
|
+
})
|
|
1255
877
|
});
|
|
1256
|
-
maskAuthData(error.originalRequest, maskSensitiveHeaderData);
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
878
|
+
maskAuthData(error.originalRequest, maskSensitiveHeaderData); // Let the final resolver to reject the promise
|
|
879
|
+
|
|
880
|
+
const parsedResponse = { ...response,
|
|
881
|
+
error,
|
|
882
|
+
statusCode: res.status
|
|
883
|
+
};
|
|
884
|
+
next(request, parsedResponse);
|
|
1263
885
|
});
|
|
1264
|
-
}
|
|
886
|
+
}, // We know that this is a "network" error thrown by the `fetch` library
|
|
887
|
+
e => {
|
|
888
|
+
if (enableRetry) if (retryCount < maxRetries) {
|
|
889
|
+
setTimeout(executeFetch, calcDelayDuration(retryCount, retryDelay, maxRetries, backoff, maxDelay));
|
|
890
|
+
retryCount += 1;
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
893
|
+
const error = new NetworkError(e.message, {
|
|
894
|
+
originalRequest: request,
|
|
895
|
+
retryCount
|
|
896
|
+
});
|
|
897
|
+
maskAuthData(error.originalRequest, maskSensitiveHeaderData);
|
|
898
|
+
next(request, { ...response,
|
|
899
|
+
error,
|
|
900
|
+
statusCode: 0
|
|
901
|
+
});
|
|
902
|
+
}).finally(() => {
|
|
903
|
+
clearTimeout(timer);
|
|
904
|
+
});
|
|
905
|
+
}
|
|
1265
906
|
|
|
1266
|
-
|
|
1267
|
-
};
|
|
907
|
+
executeFetch();
|
|
1268
908
|
};
|
|
1269
909
|
}
|
|
1270
910
|
|
|
1271
911
|
function createLoggerMiddleware() {
|
|
1272
|
-
return
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
912
|
+
return next => (request, response) => {
|
|
913
|
+
const {
|
|
914
|
+
error,
|
|
915
|
+
body,
|
|
916
|
+
statusCode
|
|
917
|
+
} = response;
|
|
918
|
+
console.log('Request: ', request);
|
|
919
|
+
console.log('Response: ', {
|
|
920
|
+
error,
|
|
921
|
+
body,
|
|
922
|
+
statusCode
|
|
923
|
+
});
|
|
924
|
+
next(request, response);
|
|
1285
925
|
};
|
|
1286
926
|
}
|
|
1287
927
|
|
|
1288
|
-
function createQueueMiddleware(
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
928
|
+
function createQueueMiddleware({
|
|
929
|
+
concurrency = 20
|
|
930
|
+
}) {
|
|
931
|
+
const queue = [];
|
|
932
|
+
let runningCount = 0;
|
|
1293
933
|
|
|
1294
|
-
|
|
934
|
+
const dequeue = next => {
|
|
1295
935
|
// We assume here that this task has been completed
|
|
1296
936
|
runningCount -= 1; // Check if there are any other pending tasks and execute them
|
|
1297
937
|
|
|
1298
938
|
if (queue.length && runningCount <= concurrency) {
|
|
1299
|
-
|
|
939
|
+
const nextTask = queue.shift();
|
|
1300
940
|
runningCount += 1;
|
|
1301
941
|
next(nextTask.request, nextTask.response);
|
|
1302
942
|
}
|
|
1303
943
|
};
|
|
1304
944
|
|
|
1305
|
-
return
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
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);
|
|
945
|
+
return next => (request, response) => {
|
|
946
|
+
// Override response `resolve` and `reject` to know when the request has
|
|
947
|
+
// been completed and therefore trigger a pending task in the queue.
|
|
948
|
+
const patchedResponse = { ...response,
|
|
949
|
+
|
|
950
|
+
resolve(data) {
|
|
951
|
+
// Resolve original promise
|
|
952
|
+
response.resolve(data);
|
|
953
|
+
dequeue(next);
|
|
954
|
+
},
|
|
955
|
+
|
|
956
|
+
reject(error) {
|
|
957
|
+
// Reject original promise
|
|
958
|
+
response.reject(error);
|
|
959
|
+
dequeue(next);
|
|
1332
960
|
}
|
|
1333
|
-
};
|
|
1334
|
-
};
|
|
1335
|
-
}
|
|
1336
961
|
|
|
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 typeof window !== 'undefined' && window.document && window.document.nodeType === 9;
|
|
1347
|
-
};
|
|
962
|
+
}; // Add task to the queue
|
|
1348
963
|
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
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
|
|
964
|
+
queue.push({
|
|
965
|
+
request,
|
|
966
|
+
response: patchedResponse
|
|
967
|
+
}); // If possible, run the task straight away
|
|
1359
968
|
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
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
|
|
1367
|
-
|
|
1368
|
-
var systemInfo = getSystemInfo();
|
|
1369
|
-
return [baseInfo, systemInfo, libraryInfo, contactInfo].filter(Boolean).join(' ');
|
|
969
|
+
if (runningCount < concurrency) {
|
|
970
|
+
const nextTask = queue.shift();
|
|
971
|
+
runningCount += 1;
|
|
972
|
+
next(nextTask.request, nextTask.response);
|
|
973
|
+
}
|
|
974
|
+
};
|
|
1370
975
|
}
|
|
1371
976
|
|
|
1372
977
|
var packageJson = {
|
|
1373
978
|
name: "@commercetools/sdk-client-v2",
|
|
1374
|
-
version: "0.
|
|
979
|
+
version: "0.2.0",
|
|
1375
980
|
description: "commercetools TypeScript SDK client.",
|
|
1376
981
|
keywords: [
|
|
1377
982
|
"commercetools",
|
|
@@ -1416,9 +1021,9 @@ var packageJson = {
|
|
|
1416
1021
|
},
|
|
1417
1022
|
devDependencies: {
|
|
1418
1023
|
"abort-controller": "3.0.0",
|
|
1419
|
-
"common-tags": "
|
|
1420
|
-
dotenv: "
|
|
1421
|
-
jest: "27.
|
|
1024
|
+
"common-tags": "1.8.2",
|
|
1025
|
+
dotenv: "10.0.0",
|
|
1026
|
+
jest: "27.3.1",
|
|
1422
1027
|
nock: "12.0.3",
|
|
1423
1028
|
"organize-imports-cli": "0.8.0"
|
|
1424
1029
|
},
|
|
@@ -1429,33 +1034,62 @@ var packageJson = {
|
|
|
1429
1034
|
}
|
|
1430
1035
|
};
|
|
1431
1036
|
|
|
1037
|
+
/*
|
|
1038
|
+
This is the easiest way, for this use case, to detect if we're running in
|
|
1039
|
+
Node.js or in a browser environment. In other cases, this won't be even a
|
|
1040
|
+
problem as Rollup will provide the correct polyfill in the bundle.
|
|
1041
|
+
The main advantage by doing it this way is that it allows to easily test
|
|
1042
|
+
the code running in both environments, by overriding `global.window` in
|
|
1043
|
+
the specific test.
|
|
1044
|
+
*/
|
|
1045
|
+
const isBrowser = () => typeof window !== 'undefined' && window.document && window.document.nodeType === 9;
|
|
1046
|
+
|
|
1047
|
+
function getSystemInfo() {
|
|
1048
|
+
if (isBrowser()) return window.navigator.userAgent;
|
|
1049
|
+
const nodeVersion = process.version.slice(1); // const platformInfo = `(${process.platform}; ${process.arch})`
|
|
1050
|
+
// return `Node.js/${nodeVersion} ${platformInfo}`
|
|
1051
|
+
|
|
1052
|
+
return `node.js/${nodeVersion}`;
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
function createUserAgent(options) {
|
|
1056
|
+
if (!options || Object.keys(options).length === 0 || !{}.hasOwnProperty.call(options, 'name')) throw new Error('Missing required option `name`'); // Main info
|
|
1057
|
+
|
|
1058
|
+
const baseInfo = options.version ? `${options.name}/${options.version}` : options.name; // Library info
|
|
1059
|
+
|
|
1060
|
+
let libraryInfo = null;
|
|
1061
|
+
if (options.libraryName && !options.libraryVersion) libraryInfo = options.libraryName;else if (options.libraryName && options.libraryVersion) libraryInfo = `${options.libraryName}/${options.libraryVersion}`; // Contact info
|
|
1062
|
+
|
|
1063
|
+
let contactInfo = null;
|
|
1064
|
+
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
|
|
1065
|
+
|
|
1066
|
+
const systemInfo = getSystemInfo();
|
|
1067
|
+
return [baseInfo, systemInfo, libraryInfo, contactInfo].filter(Boolean).join(' ');
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1432
1070
|
function createUserAgentMiddleware() {
|
|
1433
|
-
|
|
1434
|
-
name:
|
|
1071
|
+
const userAgent = createUserAgent({
|
|
1072
|
+
name: `commercetools-sdk-javascript-v2/${packageJson.version}`
|
|
1435
1073
|
});
|
|
1436
|
-
return
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
})
|
|
1442
|
-
});
|
|
1443
|
-
|
|
1444
|
-
next(requestWithUserAgent, response);
|
|
1074
|
+
return next => (request, response) => {
|
|
1075
|
+
const requestWithUserAgent = { ...request,
|
|
1076
|
+
headers: { ...request.headers,
|
|
1077
|
+
'User-Agent': userAgent
|
|
1078
|
+
}
|
|
1445
1079
|
};
|
|
1080
|
+
next(requestWithUserAgent, response);
|
|
1446
1081
|
};
|
|
1447
1082
|
}
|
|
1448
1083
|
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1084
|
+
const {
|
|
1085
|
+
createAuthMiddlewareForPasswordFlow,
|
|
1086
|
+
createAuthMiddlewareForAnonymousSessionFlow,
|
|
1087
|
+
createAuthMiddlewareForClientCredentialsFlow,
|
|
1088
|
+
createAuthMiddlewareForRefreshTokenFlow,
|
|
1089
|
+
createAuthMiddlewareWithExistingToken
|
|
1090
|
+
} = authMiddlewares;
|
|
1091
|
+
class ClientBuilder {
|
|
1092
|
+
constructor() {
|
|
1459
1093
|
_defineProperty(this, "projectKey", void 0);
|
|
1460
1094
|
|
|
1461
1095
|
_defineProperty(this, "authMiddleware", void 0);
|
|
@@ -1473,158 +1107,148 @@ var ClientBuilder = /*#__PURE__*/function () {
|
|
|
1473
1107
|
_defineProperty(this, "middlewares", []);
|
|
1474
1108
|
}
|
|
1475
1109
|
|
|
1476
|
-
|
|
1477
|
-
key
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
}
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
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
|
-
}]);
|
|
1110
|
+
withProjectKey(key) {
|
|
1111
|
+
this.projectKey = key;
|
|
1112
|
+
return this;
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
defaultClient(baseUri, credentials, oauthUri, projectKey) {
|
|
1116
|
+
return this.withClientCredentialsFlow({
|
|
1117
|
+
host: oauthUri,
|
|
1118
|
+
projectKey: projectKey || this.projectKey,
|
|
1119
|
+
credentials
|
|
1120
|
+
}).withHttpMiddleware({
|
|
1121
|
+
host: baseUri,
|
|
1122
|
+
fetch: fetch__default["default"]
|
|
1123
|
+
}).withLoggerMiddleware();
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
withAuthMiddleware(authMiddleware) {
|
|
1127
|
+
this.authMiddleware = authMiddleware;
|
|
1128
|
+
return this;
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
withMiddleware(middleware) {
|
|
1132
|
+
this.middlewares.push(middleware);
|
|
1133
|
+
return this;
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
withClientCredentialsFlow(options) {
|
|
1137
|
+
return this.withAuthMiddleware(createAuthMiddlewareForClientCredentialsFlow({
|
|
1138
|
+
host: options.host || 'https://auth.europe-west1.gcp.commercetools.com',
|
|
1139
|
+
projectKey: options.projectKey || this.projectKey,
|
|
1140
|
+
credentials: {
|
|
1141
|
+
clientId: options.credentials.clientId || '',
|
|
1142
|
+
clientSecret: options.credentials.clientSecret || ''
|
|
1143
|
+
},
|
|
1144
|
+
oauthUri: options.oauthUri || '',
|
|
1145
|
+
scopes: options.scopes,
|
|
1146
|
+
fetch: options.fetch || fetch__default["default"],
|
|
1147
|
+
...options
|
|
1148
|
+
}));
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
withPasswordFlow(options) {
|
|
1152
|
+
return this.withAuthMiddleware(createAuthMiddlewareForPasswordFlow({
|
|
1153
|
+
host: options.host || 'https://auth.europe-west1.gcp.commercetools.com',
|
|
1154
|
+
projectKey: options.projectKey || this.projectKey,
|
|
1155
|
+
credentials: {
|
|
1156
|
+
clientId: process.env.myClientId,
|
|
1157
|
+
clientSecret: process.env.myClientSecret,
|
|
1158
|
+
user: {
|
|
1159
|
+
username: options.credentials.user.username || '',
|
|
1160
|
+
password: options.credentials.user.password || ''
|
|
1161
|
+
}
|
|
1162
|
+
},
|
|
1163
|
+
fetch: options.fetch || fetch__default["default"],
|
|
1164
|
+
...options
|
|
1165
|
+
}));
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
withAnonymousSessionFlow(options) {
|
|
1169
|
+
return this.withAuthMiddleware(createAuthMiddlewareForAnonymousSessionFlow({
|
|
1170
|
+
host: options.host || 'https://auth.europe-west1.gcp.commercetools.com',
|
|
1171
|
+
projectKey: this.projectKey || options.projectKey,
|
|
1172
|
+
credentials: {
|
|
1173
|
+
clientId: options.credentials.clientId || '',
|
|
1174
|
+
clientSecret: options.credentials.clientSecret || '',
|
|
1175
|
+
anonymousId: options.credentials.anonymousId || ''
|
|
1176
|
+
},
|
|
1177
|
+
fetch: options.fetch || fetch__default["default"],
|
|
1178
|
+
...options
|
|
1179
|
+
}));
|
|
1180
|
+
}
|
|
1625
1181
|
|
|
1626
|
-
|
|
1627
|
-
|
|
1182
|
+
withRefreshTokenFlow(options) {
|
|
1183
|
+
return this.withAuthMiddleware(createAuthMiddlewareForRefreshTokenFlow({
|
|
1184
|
+
host: options.host || 'https://auth.europe-west1.gcp.commercetools.com',
|
|
1185
|
+
projectKey: this.projectKey || options.projectKey,
|
|
1186
|
+
credentials: {
|
|
1187
|
+
clientId: options.credentials.clientId || '',
|
|
1188
|
+
clientSecret: options.credentials.clientSecret || ''
|
|
1189
|
+
},
|
|
1190
|
+
fetch: options.fetch || fetch__default["default"],
|
|
1191
|
+
refreshToken: options.refreshToken || '',
|
|
1192
|
+
...options
|
|
1193
|
+
}));
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
withExistingTokenFlow(authorization, options) {
|
|
1197
|
+
return this.withAuthMiddleware(createAuthMiddlewareWithExistingToken(authorization, {
|
|
1198
|
+
force: options.force || true,
|
|
1199
|
+
...options
|
|
1200
|
+
}));
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
withHttpMiddleware(options) {
|
|
1204
|
+
this.httpMiddleware = createHttpMiddleware({
|
|
1205
|
+
host: options.host || 'https://api.europe-west1.gcp.commercetools.com',
|
|
1206
|
+
fetch: options.fetch || fetch__default["default"],
|
|
1207
|
+
...options
|
|
1208
|
+
});
|
|
1209
|
+
return this;
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
withUserAgentMiddleware() {
|
|
1213
|
+
this.userAgentMiddleware = createUserAgentMiddleware();
|
|
1214
|
+
return this;
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
withQueueMiddleware(options) {
|
|
1218
|
+
this.queueMiddleware = createQueueMiddleware({
|
|
1219
|
+
concurrency: options.concurrency || 20,
|
|
1220
|
+
...options
|
|
1221
|
+
});
|
|
1222
|
+
return this;
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
withLoggerMiddleware() {
|
|
1226
|
+
this.loggerMiddleware = createLoggerMiddleware();
|
|
1227
|
+
return this;
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
withCorrelationIdMiddleware(options) {
|
|
1231
|
+
this.correlationIdMiddleware = createCorrelationIdMiddleware({
|
|
1232
|
+
generate: options.generate || null,
|
|
1233
|
+
...options
|
|
1234
|
+
});
|
|
1235
|
+
return this;
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
build() {
|
|
1239
|
+
const middlewares = this.middlewares.slice();
|
|
1240
|
+
if (this.correlationIdMiddleware) middlewares.push(this.correlationIdMiddleware);
|
|
1241
|
+
if (this.userAgentMiddleware) middlewares.push(this.userAgentMiddleware);
|
|
1242
|
+
if (this.authMiddleware) middlewares.push(this.authMiddleware);
|
|
1243
|
+
if (this.loggerMiddleware) middlewares.push(this.loggerMiddleware);
|
|
1244
|
+
if (this.queueMiddleware) middlewares.push(this.queueMiddleware);
|
|
1245
|
+
if (this.httpMiddleware) middlewares.push(this.httpMiddleware);
|
|
1246
|
+
return createClient({
|
|
1247
|
+
middlewares
|
|
1248
|
+
});
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
}
|
|
1628
1252
|
|
|
1629
1253
|
exports.ClientBuilder = ClientBuilder;
|
|
1630
1254
|
exports.createAuthForAnonymousSessionFlow = createAuthMiddlewareForAnonymousSessionFlow$1;
|