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