@commercetools/ts-client 0.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +3 -0
  3. package/dist/commercetools-ts-client.browser.cjs.js +1534 -0
  4. package/dist/commercetools-ts-client.browser.esm.js +1512 -0
  5. package/dist/commercetools-ts-client.cjs.d.ts +1 -0
  6. package/dist/commercetools-ts-client.cjs.dev.js +1534 -0
  7. package/dist/commercetools-ts-client.cjs.js +7 -0
  8. package/dist/commercetools-ts-client.cjs.prod.js +1534 -0
  9. package/dist/commercetools-ts-client.esm.js +1512 -0
  10. package/dist/declarations/src/client/builder.d.ts +33 -0
  11. package/dist/declarations/src/client/client.d.ts +6 -0
  12. package/dist/declarations/src/client/index.d.ts +3 -0
  13. package/dist/declarations/src/index.d.ts +12 -0
  14. package/dist/declarations/src/middleware/auth-middleware/anonymous-session-flow.d.ts +2 -0
  15. package/dist/declarations/src/middleware/auth-middleware/auth-request-builder.d.ts +24 -0
  16. package/dist/declarations/src/middleware/auth-middleware/auth-request-executor.d.ts +2 -0
  17. package/dist/declarations/src/middleware/auth-middleware/client-credentials-flow.d.ts +2 -0
  18. package/dist/declarations/src/middleware/auth-middleware/existing-token-flow.d.ts +2 -0
  19. package/dist/declarations/src/middleware/auth-middleware/index.d.ts +6 -0
  20. package/dist/declarations/src/middleware/auth-middleware/password-flow.d.ts +2 -0
  21. package/dist/declarations/src/middleware/auth-middleware/refresh-token-flow.d.ts +2 -0
  22. package/dist/declarations/src/middleware/create-concurrent-modification-middleware.d.ts +2 -0
  23. package/dist/declarations/src/middleware/create-correlation-id-middleware.d.ts +2 -0
  24. package/dist/declarations/src/middleware/create-error-middleware.d.ts +2 -0
  25. package/dist/declarations/src/middleware/create-http-middleware.d.ts +2 -0
  26. package/dist/declarations/src/middleware/create-logger-middleware.d.ts +2 -0
  27. package/dist/declarations/src/middleware/create-queue-middleware.d.ts +2 -0
  28. package/dist/declarations/src/middleware/create-retry-middleware.d.ts +2 -0
  29. package/dist/declarations/src/middleware/create-user-agent-middleware.d.ts +2 -0
  30. package/dist/declarations/src/middleware/index.d.ts +9 -0
  31. package/dist/declarations/src/types/types.d.ts +336 -0
  32. package/dist/declarations/src/utils/constants.d.ts +5 -0
  33. package/dist/declarations/src/utils/executor.d.ts +2 -0
  34. package/dist/declarations/src/utils/generateID.d.ts +1 -0
  35. package/dist/declarations/src/utils/headers.d.ts +2 -0
  36. package/dist/declarations/src/utils/index.d.ts +16 -0
  37. package/dist/declarations/src/utils/isBuffer.d.ts +1 -0
  38. package/dist/declarations/src/utils/logger.d.ts +2 -0
  39. package/dist/declarations/src/utils/maskAuthData.d.ts +2 -0
  40. package/dist/declarations/src/utils/mergeAuthHeader.d.ts +2 -0
  41. package/dist/declarations/src/utils/methods.d.ts +2 -0
  42. package/dist/declarations/src/utils/retryDelay.d.ts +8 -0
  43. package/dist/declarations/src/utils/sleep.d.ts +1 -0
  44. package/dist/declarations/src/utils/tokenCacheKey.d.ts +2 -0
  45. package/dist/declarations/src/utils/tokenExpirationTime.d.ts +1 -0
  46. package/dist/declarations/src/utils/tokenStore.d.ts +2 -0
  47. package/dist/declarations/src/utils/userAgent.d.ts +2 -0
  48. package/dist/declarations/src/utils/validate.d.ts +30 -0
  49. package/package.json +62 -0
@@ -0,0 +1,1534 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var qs = require('querystring');
6
+ var crytpo = require('crypto');
7
+ var fetch$1 = require('node-fetch');
8
+ var _ = require('buffer/');
9
+
10
+ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
11
+
12
+ var qs__default = /*#__PURE__*/_interopDefault(qs);
13
+ var crytpo__default = /*#__PURE__*/_interopDefault(crytpo);
14
+ var fetch__default = /*#__PURE__*/_interopDefault(fetch$1);
15
+
16
+ const HEADERS_CONTENT_TYPES = ['application/json', 'application/graphql'];
17
+ const CONCURRENCT_REQUEST = 20;
18
+ const CTP_API_URL = 'https://api.europe-west1.gcp.commercetools.com';
19
+ const CTP_AUTH_URL = 'https://auth.europe-west1.gcp.commercetools.com';
20
+ const DEFAULT_HEADERS = ['content-type', 'access-control-allow-origin', 'access-control-allow-headers', 'access-control-allow-methods', 'access-control-expose-headers', 'access-control-max-ag', 'x-correlation-id', 'server-timing', 'date', 'server', 'transfer-encoding', 'access-control-max-age', 'content-encoding', 'x-envoy-upstream-service-time', 'via', 'alt-svc', 'connection'];
21
+
22
+ function parse(headers) {
23
+ return DEFAULT_HEADERS.reduce((result, key) => {
24
+ let val = headers[key] ? headers[key] : typeof headers.get == 'function' ? headers.get(key) : null;
25
+ if (val) result[key] = val;
26
+ return result;
27
+ }, {});
28
+ }
29
+
30
+ function getHeaders(headers) {
31
+ if (!headers) return null; // node-fetch
32
+
33
+ if (headers.raw && typeof headers.raw == 'function') return headers.raw(); // Tmp fix for Firefox until it supports iterables
34
+
35
+ if (!headers.forEach) return parse(headers); // whatwg-fetch
36
+ return headers.forEach((value, name) => value);
37
+ }
38
+
39
+ function isBuffer(obj) {
40
+ return obj != null && obj.constructor != null && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj);
41
+ }
42
+
43
+ function calculateRetryDelay({
44
+ retryCount,
45
+ retryDelay,
46
+ // maxRetries,
47
+ backoff,
48
+ maxDelay
49
+ }) {
50
+ if (backoff) {
51
+ return retryCount !== 0 // do not increase if it's the first retry
52
+ ? Math.min(Math.round((Math.random() + 1) * retryDelay * 2 ** retryCount), maxDelay) : retryDelay;
53
+ }
54
+
55
+ return retryDelay;
56
+ }
57
+
58
+ function generateID() {
59
+ return crytpo__default["default"].randomBytes(32).toString('base64').replace(/[\/\-=+]/gi, '');
60
+ }
61
+
62
+ /*
63
+ This is the easiest way, for this use case, to detect if we're running in
64
+ Node.js or in a browser environment. In other cases, this won't be even a
65
+ problem as Rollup will provide the correct polyfill in the bundle.
66
+ The main advantage by doing it this way is that it allows to easily test
67
+ the code running in both environments, by overriding `global.window` in
68
+ the specific test.
69
+ */
70
+ const isBrowser = () => typeof window !== 'undefined' && window.document && window.document.nodeType === 9;
71
+
72
+ function getSystemInfo() {
73
+ if (isBrowser()) return window.navigator.userAgent;
74
+ const nodeVersion = process?.version.slice(1) || 'unknow'; // unknow environment like React Native etc
75
+
76
+ const platformInfo = `(${process.platform}; ${process.arch})`; // return `node.js/${nodeVersion}`
77
+
78
+ return `node.js/${nodeVersion} ${platformInfo}`;
79
+ }
80
+
81
+ function createUserAgent(options) {
82
+ let libraryInfo = null;
83
+ let contactInfo = null;
84
+
85
+ if (!options) {
86
+ throw new Error('Missing required option `name`');
87
+ } // Main info
88
+
89
+
90
+ const baseInfo = options.version ? `${options.name}/${options.version}` : options.name; // Library info
91
+
92
+ if (options.libraryName && !options.libraryVersion) {
93
+ libraryInfo = options.libraryName;
94
+ } else if (options.libraryName && options.libraryVersion) {
95
+ libraryInfo = `${options.libraryName}/${options.libraryVersion}`;
96
+ } // Contact info
97
+
98
+
99
+ if (options.contactUrl && !options.contactEmail) {
100
+ contactInfo = `(+${options.contactUrl})`;
101
+ } else if (!options.contactUrl && options.contactEmail) {
102
+ contactInfo = `(+${options.contactEmail})`;
103
+ } else if (options.contactUrl && options.contactEmail) {
104
+ contactInfo = `(+${options.contactUrl}; +${options.contactEmail})`;
105
+ } // System info
106
+
107
+
108
+ const systemInfo = getSystemInfo(); // customName
109
+
110
+ const customAgent = options.customAgent || '';
111
+ return [baseInfo, systemInfo, libraryInfo, contactInfo, customAgent].filter(Boolean).join(' ');
112
+ }
113
+
114
+ function maskAuthData(request) {
115
+ if (request?.headers) {
116
+ if (request.headers.Authorization) {
117
+ request.headers['Authorization'] = 'Bearer ********';
118
+ }
119
+
120
+ if (request.headers.authorization) {
121
+ request.headers['authorization'] = 'Bearer ********';
122
+ }
123
+ }
124
+ }
125
+
126
+ function calculateExpirationTime(expiresIn) {
127
+ return Date.now() + // Add a gap of 5 minutes before expiration time.
128
+ expiresIn * 1000 - 5 * 60 * 1000;
129
+ }
130
+
131
+ function buildTokenCacheKey(options) {
132
+ if (!options?.credentials?.clientId || !options.projectKey || !options.host) throw new Error('Missing required options.');
133
+ return {
134
+ clientId: options.credentials.clientId,
135
+ host: options.host,
136
+ projectKey: options.projectKey
137
+ };
138
+ }
139
+
140
+ function store(initVal) {
141
+ let value = initVal;
142
+ return {
143
+ get: TokenCacheOption => value,
144
+ set: (val, TokenCacheOption) => {
145
+ value = val;
146
+ }
147
+ };
148
+ }
149
+
150
+ function mergeAuthHeader(token, req) {
151
+ return { ...req,
152
+ headers: { ...req.headers,
153
+ Authorization: `Bearer ${token}`
154
+ }
155
+ };
156
+ }
157
+
158
+ async function executeHttpClientRequest(fetcher, config) {
159
+ async function sendRequest() {
160
+ const response = await fetcher({ ...config,
161
+ headers: { ...config.headers
162
+ }
163
+ }); // validations and error handlings can also be done here
164
+
165
+ return response;
166
+ } // Attempt to send the request.
167
+
168
+
169
+ return sendRequest().catch(error => {
170
+ throw error;
171
+ });
172
+ }
173
+
174
+ async function executor(request) {
175
+ const {
176
+ url,
177
+ httpClient,
178
+ ...rest
179
+ } = request;
180
+ const data = await executeHttpClientRequest(async options => {
181
+ const response = await httpClient(url, { ...rest,
182
+ ...options,
183
+ headers: { ...rest.headers,
184
+ ...options.headers,
185
+ // axios header encoding
186
+ 'Accept-Encoding': 'application/json'
187
+ },
188
+ // for axios
189
+ ...(rest.body ? {
190
+ data: rest.body
191
+ } : {}),
192
+ withCredentials: options.credentialsMode === 'include'
193
+ });
194
+ const data = response.json && typeof response.json == 'function' ? await response.json() : response.data || response;
195
+ return {
196
+ data,
197
+ statusCode: response.status || response.statusCode,
198
+ headers: response.headers
199
+ };
200
+ },
201
+ /**
202
+ * get this object from the
203
+ * middleware options or from
204
+ * http client config
205
+ */
206
+ {});
207
+ return data;
208
+ }
209
+
210
+ function sleep(ms) {
211
+ return new Promise(resolve => {
212
+ setTimeout(resolve, ms);
213
+ });
214
+ }
215
+
216
+ 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'];
217
+
218
+ /**
219
+ * validate some essential http options
220
+ * @param options
221
+ */
222
+ function validateHttpOptions(options) {
223
+ if (!options.host) throw new Error('Request `host` or `url` is missing or invalid, please pass in a valid host e.g `host: http://a-valid-host-url`');
224
+ if (!options.httpClient && typeof options.httpClient !== 'function') throw new Error('An `httpClient` is not available, please pass in a `fetch` or `axios` instance as an option or have them globally available.');
225
+ if (options.timeout && !options.getAbortController) throw new Error('`AbortController` is not available. Please pass in `getAbortController` as an option or have AbortController globally available when using timeout.');
226
+ }
227
+ /**
228
+ *
229
+ * @param retryCodes
230
+ * @example
231
+ * const retryCodes = [500, 504, "ETIMEDOUT"]
232
+ */
233
+
234
+ function validateRetryCodes(retryCodes) {
235
+ if (!Array.isArray(retryCodes)) {
236
+ throw new Error('`retryCodes` option must be an array of retry status (error) codes and/or messages.');
237
+ }
238
+ }
239
+ /**
240
+ * @param options
241
+ */
242
+
243
+ function validateClient(options) {
244
+ if (!options) throw new Error('Missing required options');
245
+ if (options.middlewares && !Array.isArray(options.middlewares)) throw new Error('Middlewares should be an array');
246
+
247
+ if (!options.middlewares || !Array.isArray(options.middlewares) || !options.middlewares.length) {
248
+ throw new Error('You need to provide at least one middleware');
249
+ }
250
+ }
251
+ /**
252
+ * @param options
253
+ */
254
+
255
+ function validate(funcName, request, options = {
256
+ allowedMethods: METHODS
257
+ }) {
258
+ 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`);
259
+ 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`);
260
+ 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`);
261
+ }
262
+
263
+ function compose({
264
+ middlewares
265
+ }) {
266
+ if (middlewares.length === 1) return middlewares[0];
267
+
268
+ const _middlewares = middlewares.slice();
269
+
270
+ return _middlewares.reduce((ac, cv) => (...args) => ac(cv.apply(null, args)));
271
+ } // process batch requests
272
+
273
+
274
+ let _options;
275
+
276
+ function process$1(request, fn, processOpt) {
277
+ validate('process', request, {
278
+ allowedMethods: ['GET']
279
+ });
280
+ 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
281
+
282
+ const opt = {
283
+ total: Number.POSITIVE_INFINITY,
284
+ accumulate: true,
285
+ ...processOpt
286
+ };
287
+ return new Promise((resolve, reject) => {
288
+ let _path,
289
+ _queryString = '';
290
+
291
+ if (request && request.uri) {
292
+ const [path, queryString] = request.uri.split('?');
293
+ _path = path;
294
+ _queryString = queryString;
295
+ }
296
+
297
+ const requestQuery = { ...qs__default["default"].parse(_queryString)
298
+ };
299
+ const query = {
300
+ // defaults
301
+ limit: 20,
302
+ // merge given query params
303
+ ...requestQuery
304
+ };
305
+ let itemsToGet = opt.total;
306
+ let hasFirstPageBeenProcessed = false;
307
+
308
+ const processPage = async (lastId, acc = []) => {
309
+ // Use the lesser value between limit and itemsToGet in query
310
+ const limit = query.limit < itemsToGet ? query.limit : itemsToGet;
311
+ const originalQueryString = qs__default["default"].stringify({ ...query,
312
+ limit
313
+ });
314
+ const enhancedQuery = {
315
+ sort: 'id asc',
316
+ withTotal: false,
317
+ ...(lastId ? {
318
+ where: `id > "${lastId}"`
319
+ } : {})
320
+ };
321
+ const enhancedQueryString = qs__default["default"].stringify(enhancedQuery);
322
+ const enhancedRequest = { ...request,
323
+ uri: `${_path}?${enhancedQueryString}&${originalQueryString}`
324
+ };
325
+
326
+ try {
327
+ const payload = await createClient(_options).execute(enhancedRequest);
328
+ const {
329
+ results,
330
+ count: resultsLength
331
+ } = payload?.body || {};
332
+
333
+ if (!resultsLength && hasFirstPageBeenProcessed) {
334
+ return resolve(acc || []);
335
+ }
336
+
337
+ const result = await Promise.resolve(fn(payload)); // const result = await fn(payload)
338
+
339
+ let accumulated;
340
+ hasFirstPageBeenProcessed = true;
341
+ if (opt.accumulate) accumulated = acc.concat(result || []);
342
+ itemsToGet -= resultsLength; // If there are no more items to get, it means the total number
343
+ // of items in the original request have been fetched so we
344
+ // resolve the promise.
345
+ // Also, if we get less results in a page then the limit set it
346
+ // means that there are no more pages and that we can finally
347
+ // resolve the promise.
348
+
349
+ if (resultsLength < query.limit || !itemsToGet) {
350
+ return resolve(accumulated || []);
351
+ }
352
+
353
+ const last = results[resultsLength - 1];
354
+ const newLastId = last && last.id;
355
+ processPage(newLastId, accumulated);
356
+ } catch (error) {
357
+ reject(error); // return {
358
+ // error
359
+ // }
360
+ }
361
+ }; // Start iterating through pages
362
+
363
+
364
+ processPage();
365
+ });
366
+ }
367
+ function createClient(middlewares) {
368
+ _options = middlewares;
369
+ validateClient(middlewares);
370
+ const resolver = {
371
+ async resolve(rs) {
372
+ const {
373
+ reject,
374
+ resolve,
375
+ response,
376
+ retryCount,
377
+ ...rest
378
+ } = rs;
379
+ const res = {
380
+ body: null,
381
+ error: null,
382
+ reject,
383
+ resolve,
384
+ ...(retryCount ? {
385
+ retryCount
386
+ } : {}),
387
+ request: rest,
388
+ ...response
389
+ };
390
+
391
+ if (res.error) {
392
+ res.reject(res);
393
+ return res;
394
+ }
395
+
396
+ res.resolve(res);
397
+ return res;
398
+ }
399
+
400
+ };
401
+ const dispatch = compose(middlewares)(resolver.resolve);
402
+ return {
403
+ process: process$1,
404
+
405
+ execute(request) {
406
+ validate('exec', request);
407
+ return new Promise((resolve, reject) => {
408
+ return dispatch({
409
+ reject,
410
+ resolve,
411
+ ...request
412
+ });
413
+ });
414
+ }
415
+
416
+ };
417
+ }
418
+
419
+ function _defineProperty(obj, key, value) {
420
+ if (key in obj) {
421
+ Object.defineProperty(obj, key, {
422
+ value: value,
423
+ enumerable: true,
424
+ configurable: true,
425
+ writable: true
426
+ });
427
+ } else {
428
+ obj[key] = value;
429
+ }
430
+
431
+ return obj;
432
+ }
433
+
434
+ function createCorrelationIdMiddleware$1(options) {
435
+ return next => request => {
436
+ const nextRequest = { ...request,
437
+ headers: { ...request.headers,
438
+ 'X-Correlation-ID': options.generate && typeof options.generate == 'function' ? options.generate() : generateID()
439
+ }
440
+ };
441
+ return next(nextRequest);
442
+ };
443
+ }
444
+
445
+ async function executeRequest$1({
446
+ url,
447
+ clientOptions,
448
+ httpClient
449
+ }) {
450
+ let timer;
451
+ const {
452
+ timeout,
453
+ abortController
454
+ } = clientOptions;
455
+
456
+ try {
457
+ if (timeout) timer = setTimeout(() => {
458
+ abortController.abort();
459
+ }, timeout);
460
+ const response = await executor({
461
+ url,
462
+ ...clientOptions,
463
+ httpClient,
464
+ method: clientOptions.method,
465
+ ...(clientOptions.body ? {
466
+ body: clientOptions.body
467
+ } : {})
468
+ });
469
+
470
+ if (response.statusCode >= 200 && response.statusCode < 300) {
471
+ if (clientOptions.method == 'HEAD') {
472
+ return {
473
+ statusCode: response.statusCode,
474
+ headers: getHeaders(response.headers)
475
+ };
476
+ }
477
+
478
+ return {
479
+ body: response.data || response,
480
+ statusCode: response.statusCode,
481
+ headers: getHeaders(response.headers)
482
+ };
483
+ }
484
+ /**
485
+ * handle non-ok (error) response
486
+ * build error body
487
+ */
488
+
489
+
490
+ return {
491
+ error: {
492
+ message: response.message || response.data.message,
493
+ method: clientOptions.method,
494
+ ...response
495
+ }
496
+ };
497
+ } catch (error) {
498
+ return {
499
+ // We know that this is a network error
500
+ error
501
+ };
502
+ } finally {
503
+ clearTimeout(timer);
504
+ }
505
+ }
506
+
507
+ function createHttpMiddleware$1(options) {
508
+ // validate response
509
+ validateHttpOptions(options);
510
+ const {
511
+ host,
512
+ credentialsMode,
513
+ httpClient,
514
+ timeout,
515
+ getAbortController,
516
+ httpClientOptions
517
+ } = options;
518
+ return next => {
519
+ return async request => {
520
+ let abortController;
521
+ if (timeout || getAbortController) abortController = (getAbortController ? getAbortController() : null) || new AbortController();
522
+ const url = host.replace(/\/$/, '') + request.uri;
523
+ const requestHeader = { ...request.headers
524
+ }; // validate header
525
+
526
+ if (!(requestHeader['Content-Type'] || requestHeader['content-type'])) {
527
+ requestHeader['Content-Type'] = 'application/json';
528
+ } // Ensure body is a string if content type is application/{json|graphql}
529
+
530
+
531
+ const body = HEADERS_CONTENT_TYPES.indexOf(requestHeader['Content-Type']) > -1 && typeof request.body === 'string' || isBuffer(request.body) ? request.body : JSON.stringify(request.body || undefined);
532
+
533
+ if (body && (typeof body === 'string' || isBuffer(body))) {
534
+ requestHeader['Content-Length'] = _.Buffer.byteLength(body).toString();
535
+ }
536
+
537
+ const clientOptions = {
538
+ method: request.method,
539
+ headers: requestHeader,
540
+ ...httpClientOptions
541
+ };
542
+
543
+ if (credentialsMode) {
544
+ clientOptions.credentialsMode = clientOptions.credentialsMode;
545
+ }
546
+
547
+ if (abortController) {
548
+ clientOptions.signal = abortController.signal;
549
+ }
550
+
551
+ if (timeout) {
552
+ clientOptions.timeout = timeout;
553
+ clientOptions.abortController = abortController;
554
+ }
555
+
556
+ if (body) {
557
+ clientOptions.body = body;
558
+ } // get result from executed request
559
+
560
+
561
+ const response = await executeRequest$1({
562
+ url,
563
+ clientOptions,
564
+ httpClient
565
+ });
566
+ const responseWithRequest = { ...request,
567
+ response
568
+ };
569
+ return next(responseWithRequest);
570
+ };
571
+ };
572
+ }
573
+
574
+ function createQueueMiddleware$1({
575
+ concurrency = 20
576
+ }) {
577
+ let runningCount = 0;
578
+ const queue = [];
579
+
580
+ const dequeue = next => {
581
+ runningCount--;
582
+
583
+ if (queue.length && runningCount <= concurrency) {
584
+ const nextTask = queue.shift();
585
+ runningCount++;
586
+ return next(nextTask.request);
587
+ }
588
+ };
589
+
590
+ const enqueue = ({
591
+ request
592
+ }) => queue.push({
593
+ request
594
+ });
595
+
596
+ return next => request => {
597
+ // wrap and override resolve and reject functions
598
+ const patchedRequest = { ...request,
599
+
600
+ resolve(data) {
601
+ request.resolve(data);
602
+ dequeue(next);
603
+ },
604
+
605
+ reject(error) {
606
+ request.reject(error);
607
+ dequeue(next);
608
+ }
609
+
610
+ }; // enqueue requests
611
+
612
+ enqueue({
613
+ request: patchedRequest
614
+ });
615
+
616
+ if (runningCount < concurrency) {
617
+ runningCount++;
618
+ const nextTask = queue.shift();
619
+ return next(nextTask.request);
620
+ }
621
+ };
622
+ }
623
+
624
+ function predicate(retryCodes, response) {
625
+ return !(retryCodes.includes(response?.error?.message) || [503, ...retryCodes].includes(response?.statusCode));
626
+ } // error, info, warn
627
+
628
+
629
+ function createRetryMiddleware$1(options) {
630
+ return next => async request => {
631
+ const {
632
+ retryCodes = [],
633
+ maxDelay = Infinity,
634
+ maxRetries = 3,
635
+ backoff = true,
636
+ retryDelay = 200
637
+ } = options || {};
638
+ let response,
639
+ retryCount = 0; // validate the `retryCodes` option
640
+
641
+ validateRetryCodes(retryCodes);
642
+
643
+ async function executeRequest() {
644
+ // first attenpt
645
+ response = await next(request);
646
+ retryCount++;
647
+
648
+ if (predicate(retryCodes, response)) {
649
+ return { ...response
650
+ };
651
+ }
652
+
653
+ while (retryCount < maxRetries) {
654
+ // check if the response if worth retrying for subsequest calls
655
+ response = await next(request);
656
+ retryCount++;
657
+
658
+ if (predicate(retryCodes, response)) {
659
+ return { ...response
660
+ };
661
+ } // delay next execution
662
+
663
+
664
+ const timer = calculateRetryDelay({
665
+ retryCount,
666
+ retryDelay,
667
+ maxRetries,
668
+ backoff,
669
+ maxDelay
670
+ });
671
+ await sleep(timer);
672
+ }
673
+
674
+ return { ...response,
675
+ retryCount
676
+ };
677
+ } // invoke executeRequest
678
+
679
+
680
+ return executeRequest();
681
+ };
682
+ }
683
+
684
+ function createLoggerMiddleware$1(options) {
685
+ return next => {
686
+ return async request => {
687
+ let response = await next(request);
688
+ const originalResponse = Object.assign({}, response);
689
+ const {
690
+ loggerFn = console.log,
691
+ // logLevel = 'ERROR',
692
+ maskSensitiveHeaderData = true,
693
+ includeOriginalRequest = true,
694
+ includeResponseHeaders = true // includeRequestInErrorResponse
695
+
696
+ } = options || {};
697
+
698
+ if (includeOriginalRequest && maskSensitiveHeaderData) {
699
+ maskAuthData(response.request);
700
+ }
701
+
702
+ if (!includeOriginalRequest) {
703
+ const {
704
+ request,
705
+ ...rest
706
+ } = response;
707
+ response = rest;
708
+ }
709
+
710
+ if (!includeResponseHeaders) {
711
+ const {
712
+ headers,
713
+ ...rest
714
+ } = response;
715
+ response = rest;
716
+ }
717
+
718
+ if (loggerFn && typeof loggerFn == 'function') {
719
+ loggerFn(response);
720
+ return originalResponse;
721
+ } // console.log({ Response: response })
722
+
723
+
724
+ return originalResponse;
725
+ };
726
+ };
727
+ }
728
+
729
+ var packageJson = {
730
+ name: "@commercetools/ts-client",
731
+ version: "0.0.1-beta.0",
732
+ engines: {
733
+ node: ">=14"
734
+ },
735
+ description: "commercetools Composable Commerce TypeScript SDK client.",
736
+ keywords: [
737
+ "commercetools",
738
+ "composable commerce",
739
+ "sdk",
740
+ "typescript",
741
+ "client",
742
+ "middleware",
743
+ "http",
744
+ "oauth",
745
+ "auth"
746
+ ],
747
+ homepage: "https://github.com/commercetools/commercetools-sdk-typescript",
748
+ license: "MIT",
749
+ directories: {
750
+ lib: "lib",
751
+ test: "test"
752
+ },
753
+ publishConfig: {
754
+ access: "public"
755
+ },
756
+ repository: {
757
+ type: "git",
758
+ url: "git+https://github.com/commercetools/commercetools-sdk-typescript.git"
759
+ },
760
+ bugs: {
761
+ url: "https://github.com/commercetools/commercetools-sdk-typescript/issues"
762
+ },
763
+ dependencies: {
764
+ axios: "^1.2.0",
765
+ buffer: "^6.0.3",
766
+ "node-fetch": "^2.6.1",
767
+ querystring: "^0.2.1"
768
+ },
769
+ files: [
770
+ "dist",
771
+ "CHANGELOG.md"
772
+ ],
773
+ author: "Chukwuemeka Ajima <meeky.ae@gmail.com>",
774
+ main: "dist/commercetools-ts-client.cjs.js",
775
+ module: "dist/commercetools-ts-client.esm.js",
776
+ browser: {
777
+ "./dist/commercetools-ts-client.cjs.js": "./dist/commercetools-ts-client.browser.cjs.js",
778
+ "./dist/commercetools-ts-client.esm.js": "./dist/commercetools-ts-client.browser.esm.js"
779
+ },
780
+ devDependencies: {
781
+ "abort-controller": "3.0.0",
782
+ "common-tags": "1.8.2",
783
+ dotenv: "16.0.2",
784
+ jest: "29.0.3",
785
+ nock: "12.0.3",
786
+ "organize-imports-cli": "0.10.0"
787
+ },
788
+ scripts: {
789
+ organize_imports: "find src -type f -name '*.ts' | xargs organize-imports-cli",
790
+ postbuild: "yarn organize_imports",
791
+ post_process_generate: "yarn organize_imports"
792
+ }
793
+ };
794
+
795
+ function createUserAgentMiddleware$1(options) {
796
+ return next => async request => {
797
+ const userAgent = createUserAgent({ ...options,
798
+ name: `commercetools-sdk-javascript-v2/${packageJson.version}`
799
+ });
800
+ const requestWithUserAgent = { ...request,
801
+ headers: { ...request.headers,
802
+ 'User-Agent': userAgent
803
+ }
804
+ };
805
+ return next(requestWithUserAgent);
806
+ };
807
+ }
808
+
809
+ function createConcurrentModificationMiddleware$1() {
810
+ return next => {
811
+ return async request => {
812
+ const response = await next(request);
813
+
814
+ if (response.statusCode == 409) {
815
+ /**
816
+ * extract the currentVersion
817
+ * from the error body and update
818
+ * request with the currentVersion
819
+ */
820
+ const version = response.error.body.errors[0].currentVersion; // update the resource version here
821
+
822
+ request.body = typeof request.body == 'string' ? { ...JSON.parse(request.body),
823
+ version
824
+ } : { ...request.body,
825
+ version
826
+ };
827
+ return next(request);
828
+ }
829
+
830
+ return response;
831
+ };
832
+ };
833
+ }
834
+
835
+ function createErrorMiddleware$1(options) {
836
+ return next => async request => {
837
+ const response = await next(request);
838
+
839
+ if (response.error) {
840
+ const {
841
+ error
842
+ } = response;
843
+ return { ...response,
844
+ statusCode: error.statusCode || 0,
845
+ headers: error.headers || getHeaders({}),
846
+ error: { ...error,
847
+ body: error.data || error
848
+ }
849
+ };
850
+ }
851
+
852
+ return response;
853
+ };
854
+ }
855
+
856
+ /**
857
+ *
858
+ * @param {AuthMiddlewareOptions} options
859
+ * @returns { IBuiltRequestParams } *
860
+ */
861
+
862
+ function buildRequestForClientCredentialsFlow(options) {
863
+ // Validate options
864
+ if (!options) throw new Error('Missing required options');
865
+ if (!options.host) throw new Error('Missing required option (host)');
866
+ if (!options.projectKey) throw new Error('Missing required option (projectKey)');
867
+ if (!options.credentials) throw new Error('Missing required option (credentials)');
868
+ const {
869
+ clientId,
870
+ clientSecret
871
+ } = options.credentials || {};
872
+ if (!(clientId && clientSecret)) throw new Error('Missing required credentials (clientId, clientSecret)');
873
+ const scope = options.scopes ? options.scopes.join(' ') : undefined;
874
+ const basicAuth = _.Buffer.from(`${clientId}:${clientSecret}`).toString('base64'); // This is mostly useful for internal testing purposes to be able to check
875
+ // other oauth endpoints.
876
+
877
+ const oauthUri = options.oauthUri || '/oauth/token';
878
+ const url = options.host.replace(/\/$/, '') + oauthUri;
879
+ const body = `grant_type=client_credentials${scope ? `&scope=${scope}` : ''}`;
880
+ return {
881
+ url,
882
+ body,
883
+ basicAuth
884
+ };
885
+ }
886
+ /**
887
+ *
888
+ * @param {AuthMiddlewareOptions} options
889
+ * @returns {IBuiltRequestParams} *
890
+ */
891
+
892
+ function buildRequestForAnonymousSessionFlow(options) {
893
+ if (!options) throw new Error('Missing required options');
894
+ if (!options.projectKey) throw new Error('Missing required option (projectKey)');
895
+ const projectKey = options.projectKey;
896
+ options.oauthUri = options.oauthUri || `/oauth/${projectKey}/anonymous/token`;
897
+ const result = buildRequestForClientCredentialsFlow(options);
898
+ if (options.credentials.anonymousId) result.body += `&anonymous_id=${options.credentials.anonymousId}`;
899
+ return { ...result
900
+ };
901
+ }
902
+ /**
903
+ *
904
+ * @param {RefreshAuthMiddlewareOptions} options
905
+ * @returns {IBuiltRequestParams}
906
+ */
907
+
908
+ function buildRequestForRefreshTokenFlow(options) {
909
+ if (!options) throw new Error('Missing required options');
910
+ if (!options.host) throw new Error('Missing required option (host)');
911
+ if (!options.projectKey) throw new Error('Missing required option (projectKey)');
912
+ if (!options.credentials) throw new Error('Missing required option (credentials)');
913
+ if (!options.refreshToken) throw new Error('Missing required option (refreshToken)');
914
+ const {
915
+ clientId,
916
+ clientSecret
917
+ } = options.credentials;
918
+ if (!(clientId && clientSecret)) throw new Error('Missing required credentials (clientId, clientSecret)');
919
+ const basicAuth = _.Buffer.from(`${clientId}:${clientSecret}`).toString('base64'); // This is mostly useful for internal testing purposes to be able to check
920
+ // other oauth endpoints.
921
+
922
+ const oauthUri = options.oauthUri || '/oauth/token';
923
+ const url = options.host.replace(/\/$/, '') + oauthUri;
924
+ const body = `grant_type=refresh_token&refresh_token=${encodeURIComponent(options.refreshToken)}`;
925
+ return {
926
+ basicAuth,
927
+ url,
928
+ body
929
+ };
930
+ }
931
+ /**
932
+ * @param {PasswordAuthMiddlewareOptions} options
933
+ * @returns {IBuiltRequestParams}
934
+ */
935
+
936
+ function buildRequestForPasswordFlow(options) {
937
+ if (!options) throw new Error('Missing required options');
938
+ if (!options.host) throw new Error('Missing required option (host)');
939
+ if (!options.projectKey) throw new Error('Missing required option (projectKey)');
940
+ if (!options.credentials) throw new Error('Missing required option (credentials)');
941
+ const {
942
+ clientId,
943
+ clientSecret,
944
+ user
945
+ } = options.credentials;
946
+ const projectKey = options.projectKey;
947
+ if (!(clientId && clientSecret && user)) throw new Error('Missing required credentials (clientId, clientSecret, user)');
948
+ const {
949
+ username,
950
+ password
951
+ } = user;
952
+ if (!(username && password)) throw new Error('Missing required user credentials (username, password)');
953
+ const scope = (options.scopes || []).join(' ');
954
+ const scopeStr = scope ? `&scope=${scope}` : '';
955
+ const basicAuth = _.Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
956
+ /**
957
+ * This is mostly useful for internal testing purposes to be able to check
958
+ * other oauth endpoints.
959
+ */
960
+
961
+ const oauthUri = options.oauthUri || `/oauth/${projectKey}/customers/token`;
962
+ const url = options.host.replace(/\/$/, '') + oauthUri; // encode username and password as requested by the system
963
+
964
+ const body = `grant_type=password&username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}${scopeStr}`;
965
+ return {
966
+ basicAuth,
967
+ url,
968
+ body
969
+ };
970
+ }
971
+
972
+ async function executeRequest(options) {
973
+ const {
974
+ request,
975
+ httpClient,
976
+ tokenCache,
977
+ tokenCacheKey,
978
+ requestState,
979
+ userOption,
980
+ next
981
+ } = options;
982
+ let url = options.url;
983
+ let body = options.body;
984
+ let basicAuth = options.basicAuth; // get the pending object from option
985
+
986
+ let pendingTasks = options.pendingTasks;
987
+ if (!httpClient || typeof httpClient !== 'function') throw new Error('an `httpClient` is not available, please pass in a `fetch` or `axios` instance as an option or have them globally available.');
988
+ /**
989
+ * If there is a token in the tokenCache, and it's not
990
+ * expired, append the token in the `Authorization` header.
991
+ */
992
+
993
+ const tokenCacheObject = tokenCache.get(tokenCacheKey);
994
+
995
+ if (tokenCacheObject && tokenCacheObject.token && Date.now() < tokenCacheObject.expirationTime) {
996
+ const requestWithAuth = mergeAuthHeader(tokenCacheObject.token, request);
997
+ return { ...requestWithAuth
998
+ };
999
+ }
1000
+ /**
1001
+ * Keep pending tasks until a token is fetched
1002
+ * Save next function as well, to call it once the token has been fetched, which prevents
1003
+ * unexpected behaviour in a context in which the next function uses global vars
1004
+ * or Promises to capture the token to hand it to other libraries, e.g. Apollo
1005
+ */
1006
+
1007
+
1008
+ pendingTasks.push({
1009
+ request,
1010
+ next
1011
+ }); // if a token is currently being fetched, then wait
1012
+
1013
+ if (requestState.get()) return; // signal that a token is being fetched
1014
+
1015
+ requestState.set(true);
1016
+ /**
1017
+ * use refreshToken flow if there is refresh-token
1018
+ * and there's either no token or the token is expired
1019
+ */
1020
+
1021
+ if (tokenCacheObject && tokenCacheObject.refreshToken && (!tokenCacheObject.token || tokenCacheObject.token && Date.now() > tokenCacheObject.expirationTime)) {
1022
+ if (!userOption) throw new Error('Missing required options.');
1023
+ const opt = { ...buildRequestForRefreshTokenFlow({ ...userOption,
1024
+ refreshToken: tokenCacheObject.refreshToken
1025
+ })
1026
+ }; // reassign values
1027
+
1028
+ url = opt.url;
1029
+ body = opt.body;
1030
+ basicAuth = opt.basicAuth;
1031
+ } // request a new token
1032
+
1033
+
1034
+ let response;
1035
+
1036
+ try {
1037
+ response = await executor({
1038
+ url,
1039
+ method: 'POST',
1040
+ headers: {
1041
+ Authorization: `Basic ${basicAuth}`,
1042
+ 'Content-Type': 'application/x-www-form-urlencoded',
1043
+ 'Conent-Length': _.Buffer.byteLength(body).toString()
1044
+ },
1045
+ httpClient,
1046
+ body
1047
+ }); // if (response.statusCode < 400) {
1048
+
1049
+ if (response.statusCode >= 200 && response.statusCode < 300) {
1050
+ const {
1051
+ access_token: token,
1052
+ expires_in: expiresIn,
1053
+ // expires_at: expiresAt,
1054
+ refresh_token: refreshToken
1055
+ } = response?.data; // calculate token expiration time
1056
+
1057
+ const expirationTime = calculateExpirationTime(expiresIn); // cache new generated token, refreshToken and expiration time
1058
+
1059
+ tokenCache.set({
1060
+ token,
1061
+ expirationTime,
1062
+ refreshToken
1063
+ }); // signal that a token fetch is complete
1064
+
1065
+ requestState.set(false);
1066
+ /**
1067
+ * Freeze and copy pending queue, reset
1068
+ * original one for accepting new pending tasks
1069
+ */
1070
+
1071
+ const requestQueue = pendingTasks.slice(); // const lastTask = requestQueue.pop()
1072
+ // reset pendingTask queue
1073
+
1074
+ pendingTasks = [];
1075
+
1076
+ if (requestQueue.length === 1) {
1077
+ return mergeAuthHeader(token, requestQueue.pop().request);
1078
+ } // execute all pending tasks if any
1079
+
1080
+
1081
+ for (let i = 0; i < requestQueue.length; i++) {
1082
+ const task = requestQueue[i];
1083
+ const requestWithAuth = mergeAuthHeader(token, task.request); // execute task
1084
+
1085
+ task.next(requestWithAuth);
1086
+ }
1087
+
1088
+ return;
1089
+ }
1090
+
1091
+ const error = new Error(response.data.message ? response.data.message : JSON.stringify(response.data));
1092
+ /**
1093
+ * reject the error immediately
1094
+ * and free up the middleware chain
1095
+ */
1096
+
1097
+ request.reject({ ...request,
1098
+ headers: { ...request.headers
1099
+ },
1100
+ response: {
1101
+ statusCode: response.statusCode || response.data.statusCode,
1102
+ error: {
1103
+ error,
1104
+ body: response
1105
+ }
1106
+ }
1107
+ });
1108
+ } catch (error) {
1109
+ return { ...request,
1110
+ headers: { ...request.headers
1111
+ },
1112
+ response: {
1113
+ statusCode: error.statusCode || 0,
1114
+ error: { ...response,
1115
+ error,
1116
+ body: response
1117
+ }
1118
+ }
1119
+ };
1120
+ }
1121
+ }
1122
+
1123
+ function createAuthMiddlewareForPasswordFlow$1(options) {
1124
+ const tokenCache = options.tokenCache || store({
1125
+ token: '',
1126
+ expirationTime: -1
1127
+ });
1128
+ const pendingTasks = [];
1129
+ const requestState = store(false);
1130
+ const tokenCacheKey = buildTokenCacheKey(options);
1131
+ return next => {
1132
+ return async request => {
1133
+ if (request.headers && (request.headers.Authorization || request.headers.authorization)) {
1134
+ return next(request);
1135
+ }
1136
+
1137
+ const requestOptions = {
1138
+ request,
1139
+ requestState,
1140
+ tokenCache,
1141
+ pendingTasks,
1142
+ tokenCacheKey,
1143
+ httpClient: options.httpClient || fetch__default["default"],
1144
+ ...buildRequestForPasswordFlow(options),
1145
+ userOption: options,
1146
+ next
1147
+ }; // make request to coco
1148
+
1149
+ const requestWithAuth = await executeRequest(requestOptions);
1150
+
1151
+ if (requestWithAuth) {
1152
+ return next(requestWithAuth);
1153
+ }
1154
+ };
1155
+ };
1156
+ }
1157
+
1158
+ function createAuthMiddlewareForAnonymousSessionFlow$1(options) {
1159
+ const pendingTasks = [];
1160
+ const requestState = store(false);
1161
+ const tokenCache = options.tokenCache || store({
1162
+ token: '',
1163
+ expirationTime: -1
1164
+ });
1165
+ const tokenCacheKey = buildTokenCacheKey(options);
1166
+ return next => {
1167
+ return async request => {
1168
+ // if here is a token in the header, then move on to the next middleware
1169
+ if (request.headers && (request.headers.Authorization || request.headers.authorization)) {
1170
+ // move on
1171
+ return next(request);
1172
+ } // prepare request options
1173
+
1174
+
1175
+ const requestOptions = {
1176
+ request,
1177
+ requestState,
1178
+ tokenCache,
1179
+ pendingTasks,
1180
+ tokenCacheKey,
1181
+ httpClient: options.httpClient || fetch__default["default"],
1182
+ ...buildRequestForAnonymousSessionFlow(options),
1183
+ userOption: options,
1184
+ next
1185
+ }; // make request to coco
1186
+
1187
+ const requestWithAuth = await executeRequest(requestOptions);
1188
+
1189
+ if (requestWithAuth) {
1190
+ return next(requestWithAuth);
1191
+ }
1192
+ };
1193
+ };
1194
+ }
1195
+
1196
+ function createAuthMiddlewareForClientCredentialsFlow$1(options) {
1197
+ const requestState = store(false);
1198
+ const pendingTasks = [];
1199
+ const tokenCache = options.tokenCache || store({
1200
+ token: '',
1201
+ expirationTime: -1
1202
+ });
1203
+ const tokenCacheKey = buildTokenCacheKey(options);
1204
+ return next => {
1205
+ return async request => {
1206
+ // if here is a token in the header, then move on to the next middleware
1207
+ if (request.headers && (request.headers.Authorization || request.headers.authorization)) {
1208
+ // move on
1209
+ return next(request);
1210
+ } // prepare request options
1211
+
1212
+
1213
+ const requestOptions = {
1214
+ request,
1215
+ requestState,
1216
+ tokenCache,
1217
+ pendingTasks,
1218
+ tokenCacheKey,
1219
+ httpClient: options.httpClient || fetch__default["default"],
1220
+ ...buildRequestForClientCredentialsFlow(options),
1221
+ next
1222
+ }; // make request to coco
1223
+
1224
+ const requestWithAuth = await executeRequest(requestOptions);
1225
+
1226
+ if (requestWithAuth) {
1227
+ // make the request and inject the token into the header
1228
+ return next(requestWithAuth);
1229
+ }
1230
+ };
1231
+ };
1232
+ }
1233
+
1234
+ function createAuthMiddlewareForRefreshTokenFlow$1(options) {
1235
+ const tokenCache = options.tokenCache || store({
1236
+ token: '',
1237
+ tokenCacheKey: null
1238
+ });
1239
+ const pendingTasks = [];
1240
+ const requestState = store(false);
1241
+ return next => {
1242
+ return async request => {
1243
+ if (request.headers && (request.headers.Authorization || request.headers.authorization)) {
1244
+ return next(request);
1245
+ } // prepare request options
1246
+
1247
+
1248
+ const requestOptions = {
1249
+ request,
1250
+ requestState,
1251
+ tokenCache,
1252
+ pendingTasks,
1253
+ httpClient: options.httpClient || fetch,
1254
+ ...buildRequestForRefreshTokenFlow(options),
1255
+ next
1256
+ }; // make request to coco
1257
+
1258
+ const requestWithAuth = await executeRequest(requestOptions);
1259
+
1260
+ if (requestWithAuth) {
1261
+ return next(requestWithAuth);
1262
+ }
1263
+ };
1264
+ };
1265
+ }
1266
+
1267
+ function createAuthMiddlewareForExistingTokenFlow$1(authorization, options) {
1268
+ return next => {
1269
+ return async request => {
1270
+ if (typeof authorization !== 'string') throw new Error('authorization must be a string');
1271
+ const force = options?.force === undefined ? true : options.force;
1272
+ /**
1273
+ * The request will not be modified if:
1274
+ * 1. no argument is passed
1275
+ * 2. force is false and authorization header exists
1276
+ */
1277
+
1278
+ if (!authorization || request.headers && (request.headers.Authorization || request.headers.authorization) && force === false) {
1279
+ return next(request);
1280
+ }
1281
+
1282
+ const requestWithAuth = { ...request,
1283
+ headers: { ...request.headers,
1284
+ Authorization: authorization
1285
+ }
1286
+ };
1287
+ return next(requestWithAuth);
1288
+ };
1289
+ };
1290
+ }
1291
+
1292
+ var middleware = /*#__PURE__*/Object.freeze({
1293
+ __proto__: null,
1294
+ createCorrelationIdMiddleware: createCorrelationIdMiddleware$1,
1295
+ createHttpMiddleware: createHttpMiddleware$1,
1296
+ createQueueMiddleware: createQueueMiddleware$1,
1297
+ createRetryMiddleware: createRetryMiddleware$1,
1298
+ createLoggerMiddleware: createLoggerMiddleware$1,
1299
+ createUserAgentMiddleware: createUserAgentMiddleware$1,
1300
+ createConcurrentModificationMiddleware: createConcurrentModificationMiddleware$1,
1301
+ createErrorMiddleware: createErrorMiddleware$1,
1302
+ createAuthMiddlewareForPasswordFlow: createAuthMiddlewareForPasswordFlow$1,
1303
+ createAuthMiddlewareForClientCredentialsFlow: createAuthMiddlewareForClientCredentialsFlow$1,
1304
+ createAuthMiddlewareForAnonymousSessionFlow: createAuthMiddlewareForAnonymousSessionFlow$1,
1305
+ createAuthMiddlewareForExistingTokenFlow: createAuthMiddlewareForExistingTokenFlow$1,
1306
+ createAuthMiddlewareForRefreshTokenFlow: createAuthMiddlewareForRefreshTokenFlow$1
1307
+ });
1308
+
1309
+ const {
1310
+ createAuthMiddlewareForPasswordFlow,
1311
+ createAuthMiddlewareForAnonymousSessionFlow,
1312
+ createAuthMiddlewareForClientCredentialsFlow,
1313
+ createAuthMiddlewareForRefreshTokenFlow,
1314
+ createAuthMiddlewareForExistingTokenFlow,
1315
+ createCorrelationIdMiddleware,
1316
+ createRetryMiddleware,
1317
+ createHttpMiddleware,
1318
+ createLoggerMiddleware,
1319
+ createQueueMiddleware,
1320
+ createUserAgentMiddleware,
1321
+ createConcurrentModificationMiddleware,
1322
+ createErrorMiddleware
1323
+ } = middleware;
1324
+ class ClientBuilder {
1325
+ constructor() {
1326
+ _defineProperty(this, "projectKey", void 0);
1327
+
1328
+ _defineProperty(this, "authMiddleware", void 0);
1329
+
1330
+ _defineProperty(this, "httpMiddleware", void 0);
1331
+
1332
+ _defineProperty(this, "userAgentMiddleware", void 0);
1333
+
1334
+ _defineProperty(this, "correlationIdMiddleware", void 0);
1335
+
1336
+ _defineProperty(this, "loggerMiddleware", void 0);
1337
+
1338
+ _defineProperty(this, "queueMiddleware", void 0);
1339
+
1340
+ _defineProperty(this, "retryMiddleware", void 0);
1341
+
1342
+ _defineProperty(this, "concurrentMiddleware", void 0);
1343
+
1344
+ _defineProperty(this, "errorMiddleware", void 0);
1345
+
1346
+ _defineProperty(this, "middlewares", []);
1347
+
1348
+ this.userAgentMiddleware = createUserAgentMiddleware({});
1349
+ }
1350
+
1351
+ withProjectKey(key) {
1352
+ this.projectKey = key;
1353
+ return this;
1354
+ }
1355
+
1356
+ defaultClient(baseUri, credentials, oauthUri, projectKey, scopes, httpClient) {
1357
+ return this.withClientCredentialsFlow({
1358
+ host: oauthUri,
1359
+ projectKey: projectKey || this.projectKey,
1360
+ credentials,
1361
+ scopes
1362
+ }).withHttpMiddleware({
1363
+ host: baseUri,
1364
+ httpClient: httpClient || fetch__default["default"]
1365
+ });
1366
+ }
1367
+
1368
+ withAuthMiddleware(authMiddleware) {
1369
+ this.authMiddleware = authMiddleware;
1370
+ return this;
1371
+ }
1372
+
1373
+ withMiddleware(middleware) {
1374
+ this.middlewares.push(middleware);
1375
+ return this;
1376
+ }
1377
+
1378
+ withClientCredentialsFlow(options) {
1379
+ return this.withAuthMiddleware(createAuthMiddlewareForClientCredentialsFlow({
1380
+ host: options.host || CTP_AUTH_URL,
1381
+ projectKey: options.projectKey || this.projectKey,
1382
+ credentials: {
1383
+ clientId: options.credentials.clientId || null,
1384
+ clientSecret: options.credentials.clientSecret || null
1385
+ },
1386
+ oauthUri: options.oauthUri || null,
1387
+ scopes: options.scopes,
1388
+ httpClient: options.httpClient || fetch__default["default"],
1389
+ ...options
1390
+ }));
1391
+ }
1392
+
1393
+ withPasswordFlow(options) {
1394
+ return this.withAuthMiddleware(createAuthMiddlewareForPasswordFlow({
1395
+ host: options.host || CTP_AUTH_URL,
1396
+ projectKey: options.projectKey || this.projectKey,
1397
+ credentials: {
1398
+ clientId: options.credentials.clientId || null,
1399
+ clientSecret: options.credentials.clientSecret || null,
1400
+ user: {
1401
+ username: options.credentials.user.username || null,
1402
+ password: options.credentials.user.password || null
1403
+ }
1404
+ },
1405
+ httpClient: options.httpClient || fetch__default["default"],
1406
+ ...options
1407
+ }));
1408
+ }
1409
+
1410
+ withAnonymousSessionFlow(options) {
1411
+ return this.withAuthMiddleware(createAuthMiddlewareForAnonymousSessionFlow({
1412
+ host: options.host || CTP_AUTH_URL,
1413
+ projectKey: this.projectKey || options.projectKey,
1414
+ credentials: {
1415
+ clientId: options.credentials.clientId || null,
1416
+ clientSecret: options.credentials.clientSecret || null,
1417
+ anonymousId: options.credentials.anonymousId || null
1418
+ },
1419
+ httpClient: options.httpClient || fetch__default["default"],
1420
+ ...options
1421
+ }));
1422
+ }
1423
+
1424
+ withRefreshTokenFlow(options) {
1425
+ return this.withAuthMiddleware(createAuthMiddlewareForRefreshTokenFlow({
1426
+ host: options.host || CTP_AUTH_URL,
1427
+ projectKey: this.projectKey || options.projectKey,
1428
+ credentials: {
1429
+ clientId: options.credentials.clientId || null,
1430
+ clientSecret: options.credentials.clientSecret || null
1431
+ },
1432
+ httpClient: options.httpClient || fetch__default["default"],
1433
+ refreshToken: options.refreshToken || null,
1434
+ ...options
1435
+ }));
1436
+ }
1437
+
1438
+ withRetryMiddleware(options) {
1439
+ this.retryMiddleware = createRetryMiddleware({ ...options
1440
+ });
1441
+ return this;
1442
+ }
1443
+
1444
+ withExistingTokenFlow(authorization, options) {
1445
+ return this.withAuthMiddleware(createAuthMiddlewareForExistingTokenFlow(authorization, {
1446
+ force: options.force || true,
1447
+ ...options
1448
+ }));
1449
+ }
1450
+
1451
+ withHttpMiddleware(options) {
1452
+ this.httpMiddleware = createHttpMiddleware({
1453
+ host: options.host || CTP_API_URL,
1454
+ httpClient: options.httpClient || fetch__default["default"],
1455
+ ...options
1456
+ });
1457
+ return this;
1458
+ }
1459
+
1460
+ withUserAgentMiddleware(options) {
1461
+ this.userAgentMiddleware = createUserAgentMiddleware(options);
1462
+ return this;
1463
+ }
1464
+
1465
+ withQueueMiddleware(options) {
1466
+ this.queueMiddleware = createQueueMiddleware({
1467
+ concurrency: options.concurrency || CONCURRENCT_REQUEST,
1468
+ ...options
1469
+ });
1470
+ return this;
1471
+ }
1472
+
1473
+ withLoggerMiddleware(options) {
1474
+ this.loggerMiddleware = createLoggerMiddleware(options);
1475
+ return this;
1476
+ }
1477
+
1478
+ withCorrelationIdMiddleware(options) {
1479
+ this.correlationIdMiddleware = createCorrelationIdMiddleware({
1480
+ generate: options?.generate,
1481
+ ...options
1482
+ });
1483
+ return this;
1484
+ }
1485
+
1486
+ withConcurrentModificationMiddleware() {
1487
+ this.concurrentMiddleware = createConcurrentModificationMiddleware();
1488
+ return this;
1489
+ }
1490
+
1491
+ withErrorMiddleware(options) {
1492
+ this.errorMiddleware = createErrorMiddleware(options);
1493
+ return this;
1494
+ } // builder
1495
+
1496
+
1497
+ build() {
1498
+ const middlewares = this.middlewares.slice();
1499
+ /**
1500
+ * - use default retry policy if not explicity added
1501
+ * - add retry middleware to be used by concurrent modification
1502
+ * middleware if not explicitly added as part of the middleware
1503
+ */
1504
+
1505
+ if (!this.retryMiddleware && this.concurrentMiddleware) this.withRetryMiddleware({});
1506
+ if (this.correlationIdMiddleware) middlewares.push(this.correlationIdMiddleware);
1507
+ if (this.userAgentMiddleware) middlewares.push(this.userAgentMiddleware);
1508
+ if (this.authMiddleware) middlewares.push(this.authMiddleware);
1509
+ if (this.queueMiddleware) middlewares.push(this.queueMiddleware);
1510
+ if (this.loggerMiddleware) middlewares.push(this.loggerMiddleware);
1511
+ if (this.errorMiddleware) middlewares.push(this.errorMiddleware);
1512
+ if (this.retryMiddleware) middlewares.push(this.retryMiddleware);
1513
+ if (this.concurrentMiddleware) middlewares.push(this.concurrentMiddleware);
1514
+ if (this.httpMiddleware) middlewares.push(this.httpMiddleware);
1515
+ return createClient({
1516
+ middlewares
1517
+ });
1518
+ }
1519
+
1520
+ }
1521
+
1522
+ exports.ClientBuilder = ClientBuilder;
1523
+ exports.Process = process$1;
1524
+ exports.createAuthMiddlewareForAnonymousSessionFlow = createAuthMiddlewareForAnonymousSessionFlow$1;
1525
+ exports.createAuthMiddlewareForClientCredentialsFlow = createAuthMiddlewareForClientCredentialsFlow$1;
1526
+ exports.createAuthMiddlewareForExistingTokenFlow = createAuthMiddlewareForExistingTokenFlow$1;
1527
+ exports.createAuthMiddlewareForPasswordFlow = createAuthMiddlewareForPasswordFlow$1;
1528
+ exports.createAuthMiddlewareForRefreshTokenFlow = createAuthMiddlewareForRefreshTokenFlow$1;
1529
+ exports.createClient = createClient;
1530
+ exports.createCorrelationIdMiddleware = createCorrelationIdMiddleware$1;
1531
+ exports.createHttpMiddleware = createHttpMiddleware$1;
1532
+ exports.createLoggerMiddleware = createLoggerMiddleware$1;
1533
+ exports.createQueueMiddleware = createQueueMiddleware$1;
1534
+ exports.createUserAgentMiddleware = createUserAgentMiddleware$1;