@commercetools/ts-client 4.1.0 → 4.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/dist/commercetools-ts-client.browser.cjs.js +4 -2
- package/dist/commercetools-ts-client.browser.esm.js +4 -2
- package/dist/commercetools-ts-client.cjs.dev.js +4 -2
- package/dist/commercetools-ts-client.cjs.prod.js +4 -2
- package/dist/commercetools-ts-client.esm.js +4 -2
- package/dist/commercetools-ts-client.umd.js +1 -1
- package/dist/declarations/src/types/types.d.ts +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# @commercetools/ts-client
|
|
2
2
|
|
|
3
|
+
## 4.2.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#1154](https://github.com/commercetools/commercetools-sdk-typescript/pull/1154) [`0a6ea36`](https://github.com/commercetools/commercetools-sdk-typescript/commit/0a6ea364b2acd57d5e517ca21511de5f77bca6f0) Thanks [@ajimae](https://github.com/ajimae)! - Add meta-headers to auth http requests
|
|
8
|
+
|
|
9
|
+
## 4.2.0
|
|
10
|
+
|
|
11
|
+
### Minor Changes
|
|
12
|
+
|
|
13
|
+
- [#1149](https://github.com/commercetools/commercetools-sdk-typescript/pull/1149) [`af65db6`](https://github.com/commercetools/commercetools-sdk-typescript/commit/af65db6a26fb8d96c0edcccdf720a850c30f9888) Thanks [@ajimae](https://github.com/ajimae)! - add generic type to `execute` method
|
|
14
|
+
|
|
15
|
+
```diff
|
|
16
|
+
- execute(request: ClientRequest): Promise<ClientResult>
|
|
17
|
+
+ execute<T extends object = any>(request: ClientRequest): Promise<ClientResult<T>>
|
|
18
|
+
```
|
|
19
|
+
|
|
3
20
|
## 4.1.0
|
|
4
21
|
|
|
5
22
|
### Minor Changes
|
|
@@ -655,7 +655,8 @@ async function executeRequest$1(options) {
|
|
|
655
655
|
tokenCache,
|
|
656
656
|
userOption,
|
|
657
657
|
tokenCacheObject,
|
|
658
|
-
tokenCacheKey
|
|
658
|
+
tokenCacheKey,
|
|
659
|
+
request
|
|
659
660
|
} = options;
|
|
660
661
|
let url = options.url;
|
|
661
662
|
let body = options.body;
|
|
@@ -690,6 +691,7 @@ async function executeRequest$1(options) {
|
|
|
690
691
|
url,
|
|
691
692
|
method: 'POST',
|
|
692
693
|
headers: {
|
|
694
|
+
...request.headers,
|
|
693
695
|
Authorization: `Basic ${basicAuth}`,
|
|
694
696
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
695
697
|
'Content-Length': byteLength(body)
|
|
@@ -1191,7 +1193,7 @@ function createQueueMiddleware$1({
|
|
|
1191
1193
|
|
|
1192
1194
|
var packageJson = {
|
|
1193
1195
|
name: "@commercetools/ts-client",
|
|
1194
|
-
version: "4.1
|
|
1196
|
+
version: "4.2.1",
|
|
1195
1197
|
engines: {
|
|
1196
1198
|
node: ">=18"
|
|
1197
1199
|
},
|
|
@@ -651,7 +651,8 @@ async function executeRequest$1(options) {
|
|
|
651
651
|
tokenCache,
|
|
652
652
|
userOption,
|
|
653
653
|
tokenCacheObject,
|
|
654
|
-
tokenCacheKey
|
|
654
|
+
tokenCacheKey,
|
|
655
|
+
request
|
|
655
656
|
} = options;
|
|
656
657
|
let url = options.url;
|
|
657
658
|
let body = options.body;
|
|
@@ -686,6 +687,7 @@ async function executeRequest$1(options) {
|
|
|
686
687
|
url,
|
|
687
688
|
method: 'POST',
|
|
688
689
|
headers: {
|
|
690
|
+
...request.headers,
|
|
689
691
|
Authorization: `Basic ${basicAuth}`,
|
|
690
692
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
691
693
|
'Content-Length': byteLength(body)
|
|
@@ -1187,7 +1189,7 @@ function createQueueMiddleware$1({
|
|
|
1187
1189
|
|
|
1188
1190
|
var packageJson = {
|
|
1189
1191
|
name: "@commercetools/ts-client",
|
|
1190
|
-
version: "4.1
|
|
1192
|
+
version: "4.2.1",
|
|
1191
1193
|
engines: {
|
|
1192
1194
|
node: ">=18"
|
|
1193
1195
|
},
|
|
@@ -655,7 +655,8 @@ async function executeRequest$1(options) {
|
|
|
655
655
|
tokenCache,
|
|
656
656
|
userOption,
|
|
657
657
|
tokenCacheObject,
|
|
658
|
-
tokenCacheKey
|
|
658
|
+
tokenCacheKey,
|
|
659
|
+
request
|
|
659
660
|
} = options;
|
|
660
661
|
let url = options.url;
|
|
661
662
|
let body = options.body;
|
|
@@ -690,6 +691,7 @@ async function executeRequest$1(options) {
|
|
|
690
691
|
url,
|
|
691
692
|
method: 'POST',
|
|
692
693
|
headers: {
|
|
694
|
+
...request.headers,
|
|
693
695
|
Authorization: `Basic ${basicAuth}`,
|
|
694
696
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
695
697
|
'Content-Length': byteLength(body)
|
|
@@ -1191,7 +1193,7 @@ function createQueueMiddleware$1({
|
|
|
1191
1193
|
|
|
1192
1194
|
var packageJson = {
|
|
1193
1195
|
name: "@commercetools/ts-client",
|
|
1194
|
-
version: "4.1
|
|
1196
|
+
version: "4.2.1",
|
|
1195
1197
|
engines: {
|
|
1196
1198
|
node: ">=18"
|
|
1197
1199
|
},
|
|
@@ -655,7 +655,8 @@ async function executeRequest$1(options) {
|
|
|
655
655
|
tokenCache,
|
|
656
656
|
userOption,
|
|
657
657
|
tokenCacheObject,
|
|
658
|
-
tokenCacheKey
|
|
658
|
+
tokenCacheKey,
|
|
659
|
+
request
|
|
659
660
|
} = options;
|
|
660
661
|
let url = options.url;
|
|
661
662
|
let body = options.body;
|
|
@@ -690,6 +691,7 @@ async function executeRequest$1(options) {
|
|
|
690
691
|
url,
|
|
691
692
|
method: 'POST',
|
|
692
693
|
headers: {
|
|
694
|
+
...request.headers,
|
|
693
695
|
Authorization: `Basic ${basicAuth}`,
|
|
694
696
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
695
697
|
'Content-Length': byteLength(body)
|
|
@@ -1191,7 +1193,7 @@ function createQueueMiddleware$1({
|
|
|
1191
1193
|
|
|
1192
1194
|
var packageJson = {
|
|
1193
1195
|
name: "@commercetools/ts-client",
|
|
1194
|
-
version: "4.1
|
|
1196
|
+
version: "4.2.1",
|
|
1195
1197
|
engines: {
|
|
1196
1198
|
node: ">=18"
|
|
1197
1199
|
},
|
|
@@ -651,7 +651,8 @@ async function executeRequest$1(options) {
|
|
|
651
651
|
tokenCache,
|
|
652
652
|
userOption,
|
|
653
653
|
tokenCacheObject,
|
|
654
|
-
tokenCacheKey
|
|
654
|
+
tokenCacheKey,
|
|
655
|
+
request
|
|
655
656
|
} = options;
|
|
656
657
|
let url = options.url;
|
|
657
658
|
let body = options.body;
|
|
@@ -686,6 +687,7 @@ async function executeRequest$1(options) {
|
|
|
686
687
|
url,
|
|
687
688
|
method: 'POST',
|
|
688
689
|
headers: {
|
|
690
|
+
...request.headers,
|
|
689
691
|
Authorization: `Basic ${basicAuth}`,
|
|
690
692
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
691
693
|
'Content-Length': byteLength(body)
|
|
@@ -1187,7 +1189,7 @@ function createQueueMiddleware$1({
|
|
|
1187
1189
|
|
|
1188
1190
|
var packageJson = {
|
|
1189
1191
|
name: "@commercetools/ts-client",
|
|
1190
|
-
version: "4.1
|
|
1192
|
+
version: "4.2.1",
|
|
1191
1193
|
engines: {
|
|
1192
1194
|
node: ">=18"
|
|
1193
1195
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var window;(window||={})["@commercetools/ts-client"]=(()=>{var ce=Object.defineProperty;var Ie=Object.getOwnPropertyDescriptor;var Ne=Object.getOwnPropertyNames;var Ue=Object.prototype.hasOwnProperty;var pe=(e,r)=>{for(var t in r)ce(e,t,{get:r[t],enumerable:!0})},ve=(e,r,t,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Ne(r))!Ue.call(e,i)&&i!==t&&ce(e,i,{get:()=>r[i],enumerable:!(o=Ie(r,i))||o.enumerable});return e};var je=e=>ve(ce({},"__esModule",{value:!0}),e);var Mr={};pe(Mr,{ClientBuilder:()=>$,Process:()=>ue,createAuthMiddlewareForAnonymousSessionFlow:()=>H,createAuthMiddlewareForClientCredentialsFlow:()=>B,createAuthMiddlewareForExistingTokenFlow:()=>_,createAuthMiddlewareForPasswordFlow:()=>K,createAuthMiddlewareForRefreshTokenFlow:()=>L,createClient:()=>P,createConcurrentModificationMiddleware:()=>J,createCorrelationIdMiddleware:()=>V,createErrorMiddleware:()=>G,createHttpMiddleware:()=>Y,createLoggerMiddleware:()=>W,createQueueMiddleware:()=>X,createUserAgentMiddleware:()=>Z});var be={};pe(be,{createAuthMiddlewareForAnonymousSessionFlow:()=>H,createAuthMiddlewareForClientCredentialsFlow:()=>B,createAuthMiddlewareForExistingTokenFlow:()=>_,createAuthMiddlewareForPasswordFlow:()=>K,createAuthMiddlewareForRefreshTokenFlow:()=>L,createConcurrentModificationMiddleware:()=>J,createCorrelationIdMiddleware:()=>V,createErrorMiddleware:()=>G,createHttpMiddleware:()=>Y,createLoggerMiddleware:()=>W,createQueueMiddleware:()=>X,createUserAgentMiddleware:()=>Z});function N(e){return e&&typeof e=="string"?new TextEncoder().encode(e).length.toString():e&&e instanceof Uint8Array?e.byteLength.toString():e&&typeof e=="object"?new TextEncoder().encode(JSON.stringify(e)).length.toString():"0"}var g={};pe(g,{CONCURRENCT_REQUEST:()=>Be,CTP_API_URL:()=>_e,CTP_AUTH_URL:()=>Ke,DEFAULT_HEADERS:()=>he,HEADERS_CONTENT_TYPES:()=>He});var He=["application/json","application/graphql"],Be=20,_e="https://api.europe-west1.gcp.commercetools.com",Ke="https://auth.europe-west1.gcp.commercetools.com",he=["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"];function T(e,r,t={}){this.code=t.code??=this.constructor.name,this.statusCode=e,this.status=e,this.message=r,Object.assign(this,t),this.name=this.constructor.name,this.constructor.prototype.__proto__=Error.prototype,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}function Te(...e){T.call(this,0,...e)}function xe(...e){T.call(this,...e)}function Le(...e){T.call(this,400,...e)}function $e(...e){T.call(this,401,...e)}function De(...e){T.call(this,403,...e)}function Qe(...e){T.call(this,404,...e)}function ze(...e){T.call(this,409,...e)}function Je(...e){T.call(this,500,...e)}function Ve(...e){T.call(this,503,...e)}function we(e){switch(e){case 0:return Te;case 400:return Le;case 401:return $e;case 403:return De;case 404:return Qe;case 409:return ze;case 500:return Je;case 503:return Ve;default:return}}function Ge({statusCode:e,message:r,...t}){let o=r||"Unexpected non-JSON error response";e===404&&(o=`URI not found: ${t.originalRequest?.uri||t.uri}`);let i=we(e);return i?new i(o,t):new xe(e,o,t)}var U=Ge;function Ye(e,r){return[503,...e].includes(r?.status||r?.statusCode)}async function We(e,r){async function t(){return await e({...r,headers:{...r.headers}})}return t().catch(o=>Promise.reject(o))}async function v(e){let{url:r,httpClient:t,...o}=e;return await We(async s=>{let{enableRetry:a,retryConfig:n,timeout:d,getAbortController:c}=o,{retryCodes:l=[],maxDelay:u=1/0,maxRetries:y=3,backoff:M=!0,retryDelay:C=200,retryOnAbort:p=!0}=n||{},q,h,w=0,R;fe(l);async function E(){return t(r,{...s,...o,headers:{...o.headers},...o.body?{data:o.body}:{},withCredentials:s.credentialsMode==="include"})}function F(){let m=(c?c():null)||new AbortController;return o.abortController=m,o.signal=m.signal,m}async function I(){let m=async(re,Fe)=>{let Q={};if(d){let k=F();R=setTimeout(()=>{k.abort(),k=F()},d)}try{if(Q=await E(),Q.status>399&&Ye(re,Q))return{_response:Q,shouldRetry:!0}}catch(k){if((k.name.includes("AbortError")||k.name.includes("TimeoutError"))&&Fe)return{_response:k,shouldRetry:!0};throw k}finally{clearTimeout(R)}return{_response:Q,shouldRetry:!1}},{_response:D,shouldRetry:ee}=await m(l,p);for(;a&&ee&&w<y;){w++,await oe(te({retryCount:w,retryDelay:C,maxRetries:y,backoff:M,maxDelay:u}));let re=await m(l,p);D=re._response,ee=re.shouldRetry}return D}let f=await I();try{f.text&&typeof f.text=="function"?(q=await f.text()||JSON.stringify(f[Object.getOwnPropertySymbols(f)[1]]),h=JSON.parse(q)):h=f.data||f}catch(m){throw m}return{data:h,retryCount:w,statusCode:f.status||f.statusCode||h.statusCode,headers:f.headers}},{validateStatus:s=>!0})}function ie(){return("1000000-1000-4000-8000"+-1e11).replace(/[018]/g,e=>(parseInt(e)^Math.floor(Math.random()*256)&15>>parseInt(e)/4).toString(16))}function Xe(e){return he.reduce((r,t)=>{let o=e[t]?e[t]:typeof e.get=="function"?e.get(t):null;return o&&(r[t]=o),r},{})}function x(e){if(!e)return null;if(e.raw&&typeof e.raw=="function")return e.raw();if(!e.forEach)return Xe(e);let r={};return e.forEach((t,o)=>r[o]=t),r}function z(e){return e!=null&&e.constructor!=null&&typeof e.constructor.isBuffer=="function"&&e.constructor.isBuffer(e)}function S(e){let r=JSON.parse(JSON.stringify(e));return r?.headers&&(r.headers.Authorization&&(r.headers.Authorization="Bearer ********"),r.headers.authorization&&(r.headers.authorization="Bearer ********")),r}function j(e,r){return{...r,headers:{...r.headers,Authorization:`Bearer ${e}`}}}var me=["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"];function te({retryCount:e,retryDelay:r,backoff:t,maxDelay:o}){return t&&e!==0?Math.min(Math.round((Math.random()+1)*r*2**e),o):r}Math.min(Math.round((Math.random()+1)*200*2**10),1/0);function oe(e){return new Promise(r=>{setTimeout(r,e)})}function A(e){if(!e?.credentials?.clientId||!e.projectKey||!e.host)throw new Error("Missing required options.");return{clientId:e.credentials.clientId,host:e.host,projectKey:e.projectKey}}function ne(e){return Date.now()+e*1e3-5*60*1e3}function b(e){let r=e;return{get:t=>r,set:(t,o)=>{r=t}}}function Ee(e){return typeof e<"u"&&e!==null}function Ze(e){return Ee(e)?typeof e=="string"?e:Object.fromEntries(Object.entries(e).filter(([r,t])=>![null,void 0,""].includes(t))):""}function er(e){let r={},t=new URLSearchParams(e);for(let o of t.keys())t.getAll(o).length>1?r[o]=t.getAll(o):r[o]=t.get(o);return r}function rr(e){if(e=Ze(e),!e)return"";let r=new URLSearchParams(e);for(let[t,o]of Object.entries(e))Array.isArray(o)&&(r.delete(t),o.filter(Ee).forEach(i=>r.append(t,i)));return r.toString()}function ye(e,r=er){return r(e)}function se(e,r=rr){return r(e)}var tr=()=>typeof window<"u"&&window.document&&window.document.nodeType===9;function or(){if(tr())return window.navigator.userAgent;let e=process?.version?.slice(1)||"unknown",r=`(${process?.platform||""}; ${process?.arch||""})`;return`node.js/${e} ${r.trim()}`}function ae(e){let r=null,t=null;if(!e)throw new Error("Missing required option `name`");let o=e.version?`${e.name}/${e.version}`:e.name;e.libraryName&&!e.libraryVersion?r=e.libraryName:e.libraryName&&e.libraryVersion&&(r=`${e.libraryName}/${e.libraryVersion}`),e.contactUrl&&!e.contactEmail?t=`(+${e.contactUrl})`:!e.contactUrl&&e.contactEmail?t=`(+${e.contactEmail})`:e.contactUrl&&e.contactEmail&&(t=`(+${e.contactUrl}; +${e.contactEmail})`);let i=or(),s=e.customAgent||"";return[o,i,r,t,s].filter(Boolean).join(" ")}function Me(e){if(!e.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`");if(!e.httpClient&&typeof e.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.");if(e.httpClientOptions&&Object.prototype.toString.call(e.httpClientOptions)!=="[object Object]")throw new Error("`httpClientOptions` must be an object type")}function fe(e){if(!Array.isArray(e))throw new Error("`retryCodes` option must be an array of retry status (error) codes and/or messages.")}function ge(e){if(!e)throw new Error("Missing required options");if(e.middlewares&&!Array.isArray(e.middlewares))throw new Error("Middlewares should be an array");if(!e.middlewares||!Array.isArray(e.middlewares)||!e.middlewares.length)throw new Error("You need to provide at least one middleware")}function le(e,r,t={allowedMethods:me}){if(!r)throw new Error(`The "${e}" function requires a "Request" object as an argument. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest`);if(typeof r.uri!="string")throw new Error(`The "${e}" Request object requires a valid uri. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest`);if(!t.allowedMethods.includes(r.method))throw new Error(`The "${e}" Request object requires a valid method. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest`)}function Ce(e){if(!Array.isArray(e))throw new Error("`stringBodyContentTypes` option must be an array of strings")}function Re(e){if(!e)throw new Error("Missing required options");if(!e.host)throw new Error("Missing required option (host)");if(!e.projectKey)throw new Error("Missing required option (projectKey)");if(!e.credentials)throw new Error("Missing required option (credentials)");let{clientId:r,clientSecret:t}=e.credentials||{};if(!(r&&t))throw new Error("Missing required credentials (clientId, clientSecret)");let o=e.scopes?e.scopes.join(" "):void 0,i=btoa(`${r}:${t}`),s=e.oauthUri||"/oauth/token",a=e.host.replace(/\/$/,"")+s,n=`grant_type=client_credentials${o?`&scope=${o}`:""}`;return{url:a,body:n,basicAuth:i}}function Oe(e){if(!e)throw new Error("Missing required options");if(!e.projectKey)throw new Error("Missing required option (projectKey)");let r=e.projectKey;e.oauthUri=e.oauthUri||`/oauth/${r}/anonymous/token`;let t=Re(e);return e.credentials.anonymousId&&(t.body+=`&anonymous_id=${e.credentials.anonymousId}`),{...t}}function de(e){if(!e)throw new Error("Missing required options");if(!e.host)throw new Error("Missing required option (host)");if(!e.projectKey)throw new Error("Missing required option (projectKey)");if(!e.credentials)throw new Error("Missing required option (credentials)");if(!e.refreshToken)throw new Error("Missing required option (refreshToken)");let{clientId:r,clientSecret:t}=e.credentials;if(!(r&&t))throw new Error("Missing required credentials (clientId, clientSecret)");let o=btoa(`${r}:${t}`),i=e.oauthUri||"/oauth/token",s=e.host.replace(/\/$/,"")+i,a=`grant_type=refresh_token&refresh_token=${encodeURIComponent(e.refreshToken)}`;return{basicAuth:o,url:s,body:a}}function ke(e){if(!e)throw new Error("Missing required options");if(!e.host)throw new Error("Missing required option (host)");if(!e.projectKey)throw new Error("Missing required option (projectKey)");if(!e.credentials)throw new Error("Missing required option (credentials)");let{clientId:r,clientSecret:t,user:o}=e.credentials,i=e.projectKey;if(!(r&&t&&o))throw new Error("Missing required credentials (clientId, clientSecret, user)");let{username:s,password:a}=o;if(!(s&&a))throw new Error("Missing required user credentials (username, password)");let n=(e.scopes||[]).join(" "),d=n?`&scope=${n}`:"",c=btoa(`${r}:${t}`),l=e.oauthUri||`/oauth/${i}/customers/token`,u=e.host.replace(/\/$/,"")+l,y=`grant_type=password&username=${encodeURIComponent(s)}&password=${encodeURIComponent(a)}${d}`;return{basicAuth:c,url:u,body:y}}async function Ae(e){let{httpClient:r,httpClientOptions:t,tokenCache:o,userOption:i,tokenCacheObject:s,tokenCacheKey:a}=e,n=e.url,d=e.body,c=e.basicAuth;if(!r||typeof r!="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.");if(s&&s.refreshToken&&(!s.token||s.token&&Date.now()>s.expirationTime)){if(!i)throw new Error("Missing required options.");let u={...de({...i,refreshToken:s.refreshToken})};n=u.url,d=u.body,c=u.basicAuth}let l;try{if(l=await v({url:n,method:"POST",headers:{Authorization:`Basic ${c}`,"Content-Type":"application/x-www-form-urlencoded","Content-Length":N(d)},httpClient:r,httpClientOptions:t,body:d}),l.statusCode>=200&&l.statusCode<300){let{access_token:u,expires_in:y,refresh_token:M}=l?.data,C=ne(y),p={token:u,expirationTime:C,refreshToken:M};return await o.set(p,a),Promise.resolve(!0)}throw U({code:l.data.error,statusCode:l.data.statusCode,message:l.data.message,error:l.data.errors})}catch(u){throw u}}async function O(e,r=null,t,o,i,s,a,n){let d={request:e,tokenCache:i,tokenCacheKey:o,httpClient:a.httpClient||fetch,httpClientOptions:a.httpClientOptions,...s(a),userOption:a,next:n},c=async l=>{let u=Object.assign({},l);return u.statusCode==401&&(r=Ae(d),await r,r=null,t=await i.get(o),u=await n(j(t.token,e))),u};return e.headers&&(e.headers.Authorization||e.headers.authorization)?c(await n(e)):(t=await i.get(o),t&&t.token&&Date.now()<t.expirationTime?c(await n(j(t.token,e))):(r?await r:(r=Ae(d),await r,r=null),t=await i.get(o),n(j(t.token,e))))}function H(e){let r=e.tokenCache||b({token:"",expirationTime:-1}),t,o=null,i=A(e);return s=>async a=>O(a,o,t,i,r,Oe,e,s)}function B(e){let r=e.tokenCache||b({token:"",expirationTime:-1}),t,o=null,i=A(e);return s=>async a=>O(a,o,t,i,r,Re,e,s)}function _(e,r){return t=>async o=>{if(typeof e!="string")throw new Error("authorization must be a string");let i=r?.force===void 0?!0:r.force;if(!e||o.headers&&(o.headers.Authorization||o.headers.authorization)&&i===!1)return t(o);let s={...o,headers:{...o.headers,Authorization:e}};return t(s)}}function K(e){let r=e.tokenCache||b({token:"",expirationTime:-1}),t,o=null,i=A(e);return s=>async a=>O(a,o,t,i,r,ke,e,s)}function L(e){let r=e.tokenCache||b({token:"",tokenCacheKey:null}),t,o=null,i=A(e);return s=>async a=>O(a,o,t,i,r,de,e,s)}function J(e){return r=>async t=>{let o=await r(t);if(o.statusCode==409){let i=o.error.body?.errors?.[0]?.currentVersion;if(i)return e&&typeof e=="function"?t.body=await e(i,t,o):t.body=typeof t.body=="string"?{...JSON.parse(t.body),version:i}:{...t.body,version:i},r(t)}return o}}function V(e){return r=>t=>{let o={...t,headers:{...t.headers,"X-Correlation-ID":e?.generate&&typeof e.generate=="function"?e.generate():ie()}};return r(o)}}function G(e={}){return r=>async t=>{let o=await r(t);if(o.error){let{error:i}=o;return e.handler&&typeof e.handler=="function"?e.handler({error:i,request:t,response:o,next:r}):{...o,statusCode:i.statusCode||0,headers:i.headers||x({}),body:i,error:i}}return o}}async function ir({url:e,httpClient:r,clientOptions:t}){let{request:o,maskSensitiveHeaderData:i,includeRequestInErrorResponse:s,includeResponseHeaders:a}=t;try{let n=await v({url:e,...t,httpClient:r,method:t.method,...t.body?{body:t.body}:{}});if(a||(n.headers=null),n.statusCode>=200&&n.statusCode<300)return t.method=="HEAD"?{body:null,statusCode:n.statusCode,retryCount:n.retryCount,headers:x(n.headers)}:{body:n.data,statusCode:n.statusCode,retryCount:n.retryCount,headers:x(n.headers)};let d=U({code:n.data?.errors?.[0].code,message:n?.data?.message||n?.message,statusCode:n.statusCode||n?.data?.statusCode,method:t.method,headers:x(n.headers),body:n.data,error:n.data,retryCount:n.retryCount,...s?{originalRequest:i?S(o):o}:{uri:o.uri}});return{...d,error:d}}catch(n){let d=a?x(n.response?.headers):null,c=n.response?.status||n.response?.statusCode||n.response?.data.statusCode||0,l=n.response?.data?.message;throw{body:null,error:U({statusCode:c,code:"NetworkError",status:c,message:l||n.message,headers:d,body:n.response?.data||n,error:n.response?.data||n,...s?{originalRequest:i?S(o):o}:{uri:o.uri}})}}}function Y(e){Me(e);let{host:r,credentialsMode:t,httpClient:o,timeout:i,enableRetry:s,retryConfig:a,getAbortController:n,includeOriginalRequest:d,includeRequestInErrorResponse:c=!0,includeResponseHeaders:l=!0,maskSensitiveHeaderData:u,httpClientOptions:y,stringBodyContentTypes:M=[]}=e;return C=>async p=>{let q=r.replace(/\/$/,"")+p.uri,h={...p.headers};Ce(M),Object.prototype.hasOwnProperty.call(h,"Content-Type")||Object.prototype.hasOwnProperty.call(h,"content-type")||(h["Content-Type"]="application/json"),h["Content-Type"]===null&&delete h["Content-Type"];let w=[...g.HEADERS_CONTENT_TYPES,...M].indexOf(h["Content-Type"])>-1&&typeof p.body=="string"||z(p.body)?p.body:JSON.stringify(p.body||void 0);w&&(typeof w=="string"||z(w))&&(h["Content-Length"]=N(w));let R={enableRetry:s,retryConfig:a,request:p,method:p.method,headers:h,includeRequestInErrorResponse:c,maskSensitiveHeaderData:u,includeResponseHeaders:l,...y};t&&(R.credentialsMode=t),i&&(R.timeout=i,R.getAbortController=n),w&&(R.body=w);let E=await ir({url:q,clientOptions:R,httpClient:o}),F={...p,includeOriginalRequest:d,maskSensitiveHeaderData:u,response:E};return C(F)}}function W(e){return r=>async t=>{let o=await r(t),i=Object.assign({},o),{loggerFn:s=console.log}=e||{};return s&&typeof s=="function"&&s(o),i}}function X({concurrency:e=20}){let r=0,t=[],o=()=>0>=e?Promise.resolve():new Promise(s=>{let a=()=>{r<e?(r++,s()):t.push(a)};a()}),i=()=>{if(r--,t.length>0){let s=t.shift();s&&s()}};return s=>a=>o().then(()=>{let n={...a,resolve(d){a.resolve(d),i()},reject(d){a.reject(d),i()}};return s(n).finally(()=>{i()})})}var Se={name:"@commercetools/ts-client",version:"4.1.0",engines:{node:">=18"},description:"commercetools Composable Commerce TypeScript SDK client.",keywords:["commercetools","composable commerce","sdk","typescript","client","middleware","http","oauth","auth"],homepage:"https://github.com/commercetools/commercetools-sdk-typescript",license:"MIT",directories:{lib:"lib",test:"test"},publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/commercetools/commercetools-sdk-typescript.git"},bugs:{url:"https://github.com/commercetools/commercetools-sdk-typescript/issues"},dependencies:{buffer:"^6.0.3"},files:["dist","CHANGELOG.md"],author:"Chukwuemeka Ajima <meeky.ae@gmail.com>",main:"dist/commercetools-ts-client.cjs.js",module:"dist/commercetools-ts-client.esm.js",browser:{"./dist/commercetools-ts-client.cjs.js":"./dist/commercetools-ts-client.browser.cjs.js","./dist/commercetools-ts-client.esm.js":"./dist/commercetools-ts-client.browser.esm.js"},devDependencies:{"common-tags":"1.8.2",dotenv:"16.5.0",jest:"29.7.0",nock:"14.0.4","organize-imports-cli":"0.10.0"},scripts:{organize_imports:"find src -type f -name '*.ts' | xargs organize-imports-cli",postbuild:"yarn organize_imports",post_process_generate:"yarn organize_imports",docs:"typedoc --out docs"}};function Z(e){return r=>async t=>{let o=ae({...e,name:`${e.name?e.name+"/":""}commercetools-sdk-javascript-v3/${Se.version}`}),i={...t,headers:{...t.headers,"User-Agent":o}};return r(i)}}function sr({middlewares:e}){return e.length===1?e[0]:e.slice().reduce((t,o)=>(...i)=>t(o.apply(null,i)))}var Pe;function ue(e,r,t){if(le("process",e,{allowedMethods:["GET"]}),typeof r!="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');let o={total:Number.POSITIVE_INFINITY,accumulate:!0,...t};return new Promise((i,s)=>{let a,n="";if(e&&e.uri){let[M,C]=e.uri.split("?");a=M,n=C}let c={limit:20,...{...ye(n)}},l=o.total,u=!1,y=async(M,C=[])=>{let p=c.limit<l?c.limit:l,q=se({...c,limit:p}),h={sort:"id asc",withTotal:!1,...M?{where:`id > "${M}"`}:{}},w=se(h),R={...e,uri:`${a}?${w}&${q}`};try{let E=await P(Pe).execute(R),{results:F,count:I}=E?.body||{};if(!I&&u)return i(C||[]);let f=await Promise.resolve(r(E)),m;if(u=!0,o.accumulate&&(m=C.concat(f||[])),l-=I,I<c.limit||!l)return i(m||[]);let D=F[I-1],ee=D&&D.id;y(ee,m)}catch(E){s(E)}};y()})}function P(e){Pe=e,ge(e);let r=!1,t={async resolve(i){let{response:s,includeOriginalRequest:a,maskSensitiveHeaderData:n,...d}=i,{retryCount:c,...l}=s;return r=n,{body:null,error:null,reject:i.reject,resolve:i.resolve,...l,...a?{originalRequest:d}:{},...s?.retryCount?{retryCount:s.retryCount}:{}}}},o=sr(e)(t.resolve);return{process:ue,execute(i){return le("exec",i),new Promise(async(s,a)=>{try{let n=await o({reject:a,resolve:s,...i});if(n.error)return a(n.error);n.originalRequest&&r&&(n.originalRequest=S(n.originalRequest)),s(n)}catch(n){a(n)}})}}}var{createAuthMiddlewareForPasswordFlow:ar,createAuthMiddlewareForAnonymousSessionFlow:lr,createAuthMiddlewareForClientCredentialsFlow:dr,createAuthMiddlewareForRefreshTokenFlow:ur,createAuthMiddlewareForExistingTokenFlow:cr,createCorrelationIdMiddleware:pr,createHttpMiddleware:hr,createLoggerMiddleware:wr,createQueueMiddleware:fr,createUserAgentMiddleware:qe,createConcurrentModificationMiddleware:mr,createErrorMiddleware:yr}=be,$=class{projectKey;authMiddleware;httpMiddleware;userAgentMiddleware;correlationIdMiddleware;loggerMiddleware;queueMiddleware;concurrentMiddleware;telemetryMiddleware;beforeMiddleware;afterMiddleware;errorMiddleware;middlewares=[];constructor(){this.userAgentMiddleware=qe({})}withProjectKey(r){return this.projectKey=r,this}defaultClient(r,t,o,i,s,a){return this.withClientCredentialsFlow({host:o,projectKey:i||this.projectKey,credentials:t,httpClient:a||fetch,scopes:s}).withHttpMiddleware({host:r,httpClient:a||fetch})}withAuthMiddleware(r){return this.authMiddleware=r,this}withMiddleware(r){return this.middlewares.push(r),this}withErrorMiddleware(r){return this.errorMiddleware=yr(r),this}withClientCredentialsFlow(r){return this.withAuthMiddleware(dr({host:r.host||g.CTP_AUTH_URL,projectKey:r.projectKey||this.projectKey,credentials:{clientId:r.credentials.clientId||null,clientSecret:r.credentials.clientSecret||null},oauthUri:r.oauthUri||null,scopes:r.scopes,httpClient:r.httpClient||fetch,...r}))}withPasswordFlow(r){return this.withAuthMiddleware(ar({host:r.host||g.CTP_AUTH_URL,projectKey:r.projectKey||this.projectKey,credentials:{clientId:r.credentials.clientId||null,clientSecret:r.credentials.clientSecret||null,user:{username:r.credentials.user.username||null,password:r.credentials.user.password||null}},httpClient:r.httpClient||fetch,...r}))}withAnonymousSessionFlow(r){return this.withAuthMiddleware(lr({host:r.host||g.CTP_AUTH_URL,projectKey:this.projectKey||r.projectKey,credentials:{clientId:r.credentials.clientId||null,clientSecret:r.credentials.clientSecret||null,anonymousId:r.credentials.anonymousId||null},httpClient:r.httpClient||fetch,...r}))}withRefreshTokenFlow(r){return this.withAuthMiddleware(ur({host:r.host||g.CTP_AUTH_URL,projectKey:this.projectKey||r.projectKey,credentials:{clientId:r.credentials.clientId||null,clientSecret:r.credentials.clientSecret||null},httpClient:r.httpClient||fetch,refreshToken:r.refreshToken||null,...r}))}withExistingTokenFlow(r,t){return this.withAuthMiddleware(cr(r,{force:t.force||!0,...t}))}withHttpMiddleware(r){return this.httpMiddleware=hr({host:r.host||g.CTP_API_URL,httpClient:r.httpClient||fetch,...r}),this}withUserAgentMiddleware(r){return this.userAgentMiddleware=qe(r),this}withQueueMiddleware(r){return this.queueMiddleware=fr({concurrency:r.concurrency||g.CONCURRENCT_REQUEST,...r}),this}withLoggerMiddleware(r){return this.loggerMiddleware=wr(r),this}withCorrelationIdMiddleware(r){return this.correlationIdMiddleware=pr({generate:r?.generate,...r}),this}withConcurrentModificationMiddleware(r){return this.concurrentMiddleware=mr(r?.concurrentModificationHandlerFn),this}withTelemetryMiddleware(r){let{createTelemetryMiddleware:t,...o}=r;return this.withUserAgentMiddleware({customAgent:o?.userAgent||"typescript-sdk-apm-middleware"}),this.telemetryMiddleware=t(o),this}withBeforeExecutionMiddleware(r){let{middleware:t,...o}=r||{};return this.beforeMiddleware=r.middleware(o),this}withAfterExecutionMiddleware(r){let{middleware:t,...o}=r||{};return this.afterMiddleware=r.middleware(o),this}build(){let r=this.middlewares.slice();return this.telemetryMiddleware&&r.push(this.telemetryMiddleware),this.correlationIdMiddleware&&r.push(this.correlationIdMiddleware),this.userAgentMiddleware&&r.push(this.userAgentMiddleware),this.errorMiddleware&&r.push(this.errorMiddleware),this.authMiddleware&&r.push(this.authMiddleware),this.beforeMiddleware&&r.push(this.beforeMiddleware),this.queueMiddleware&&r.push(this.queueMiddleware),this.loggerMiddleware&&r.push(this.loggerMiddleware),this.concurrentMiddleware&&r.push(this.concurrentMiddleware),this.httpMiddleware&&r.push(this.httpMiddleware),this.afterMiddleware&&r.push(this.afterMiddleware),P({middlewares:r})}};return je(Mr);})();
|
|
1
|
+
var window;(window||={})["@commercetools/ts-client"]=(()=>{var ce=Object.defineProperty;var Ie=Object.getOwnPropertyDescriptor;var Ne=Object.getOwnPropertyNames;var Ue=Object.prototype.hasOwnProperty;var pe=(e,r)=>{for(var t in r)ce(e,t,{get:r[t],enumerable:!0})},ve=(e,r,t,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Ne(r))!Ue.call(e,i)&&i!==t&&ce(e,i,{get:()=>r[i],enumerable:!(o=Ie(r,i))||o.enumerable});return e};var je=e=>ve(ce({},"__esModule",{value:!0}),e);var Mr={};pe(Mr,{ClientBuilder:()=>$,Process:()=>ue,createAuthMiddlewareForAnonymousSessionFlow:()=>H,createAuthMiddlewareForClientCredentialsFlow:()=>B,createAuthMiddlewareForExistingTokenFlow:()=>_,createAuthMiddlewareForPasswordFlow:()=>K,createAuthMiddlewareForRefreshTokenFlow:()=>L,createClient:()=>q,createConcurrentModificationMiddleware:()=>J,createCorrelationIdMiddleware:()=>V,createErrorMiddleware:()=>G,createHttpMiddleware:()=>Y,createLoggerMiddleware:()=>W,createQueueMiddleware:()=>X,createUserAgentMiddleware:()=>Z});var be={};pe(be,{createAuthMiddlewareForAnonymousSessionFlow:()=>H,createAuthMiddlewareForClientCredentialsFlow:()=>B,createAuthMiddlewareForExistingTokenFlow:()=>_,createAuthMiddlewareForPasswordFlow:()=>K,createAuthMiddlewareForRefreshTokenFlow:()=>L,createConcurrentModificationMiddleware:()=>J,createCorrelationIdMiddleware:()=>V,createErrorMiddleware:()=>G,createHttpMiddleware:()=>Y,createLoggerMiddleware:()=>W,createQueueMiddleware:()=>X,createUserAgentMiddleware:()=>Z});function N(e){return e&&typeof e=="string"?new TextEncoder().encode(e).length.toString():e&&e instanceof Uint8Array?e.byteLength.toString():e&&typeof e=="object"?new TextEncoder().encode(JSON.stringify(e)).length.toString():"0"}var g={};pe(g,{CONCURRENCT_REQUEST:()=>Be,CTP_API_URL:()=>_e,CTP_AUTH_URL:()=>Ke,DEFAULT_HEADERS:()=>he,HEADERS_CONTENT_TYPES:()=>He});var He=["application/json","application/graphql"],Be=20,_e="https://api.europe-west1.gcp.commercetools.com",Ke="https://auth.europe-west1.gcp.commercetools.com",he=["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"];function T(e,r,t={}){this.code=t.code??=this.constructor.name,this.statusCode=e,this.status=e,this.message=r,Object.assign(this,t),this.name=this.constructor.name,this.constructor.prototype.__proto__=Error.prototype,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}function Te(...e){T.call(this,0,...e)}function xe(...e){T.call(this,...e)}function Le(...e){T.call(this,400,...e)}function $e(...e){T.call(this,401,...e)}function De(...e){T.call(this,403,...e)}function Qe(...e){T.call(this,404,...e)}function ze(...e){T.call(this,409,...e)}function Je(...e){T.call(this,500,...e)}function Ve(...e){T.call(this,503,...e)}function we(e){switch(e){case 0:return Te;case 400:return Le;case 401:return $e;case 403:return De;case 404:return Qe;case 409:return ze;case 500:return Je;case 503:return Ve;default:return}}function Ge({statusCode:e,message:r,...t}){let o=r||"Unexpected non-JSON error response";e===404&&(o=`URI not found: ${t.originalRequest?.uri||t.uri}`);let i=we(e);return i?new i(o,t):new xe(e,o,t)}var U=Ge;function Ye(e,r){return[503,...e].includes(r?.status||r?.statusCode)}async function We(e,r){async function t(){return await e({...r,headers:{...r.headers}})}return t().catch(o=>Promise.reject(o))}async function v(e){let{url:r,httpClient:t,...o}=e;return await We(async s=>{let{enableRetry:a,retryConfig:n,timeout:l,getAbortController:u}=o,{retryCodes:c=[],maxDelay:d=1/0,maxRetries:p=3,backoff:M=!0,retryDelay:C=200,retryOnAbort:h=!0}=n||{},E,w,f=0,R;fe(c);async function O(){return t(r,{...s,...o,headers:{...o.headers},...o.body?{data:o.body}:{},withCredentials:s.credentialsMode==="include"})}function F(){let y=(u?u():null)||new AbortController;return o.abortController=y,o.signal=y.signal,y}async function I(){let y=async(re,Fe)=>{let Q={};if(l){let S=F();R=setTimeout(()=>{S.abort(),S=F()},l)}try{if(Q=await O(),Q.status>399&&Ye(re,Q))return{_response:Q,shouldRetry:!0}}catch(S){if((S.name.includes("AbortError")||S.name.includes("TimeoutError"))&&Fe)return{_response:S,shouldRetry:!0};throw S}finally{clearTimeout(R)}return{_response:Q,shouldRetry:!1}},{_response:D,shouldRetry:ee}=await y(c,h);for(;a&&ee&&f<p;){f++,await oe(te({retryCount:f,retryDelay:C,maxRetries:p,backoff:M,maxDelay:d}));let re=await y(c,h);D=re._response,ee=re.shouldRetry}return D}let m=await I();try{m.text&&typeof m.text=="function"?(E=await m.text()||JSON.stringify(m[Object.getOwnPropertySymbols(m)[1]]),w=JSON.parse(E)):w=m.data||m}catch(y){throw y}return{data:w,retryCount:f,statusCode:m.status||m.statusCode||w.statusCode,headers:m.headers}},{validateStatus:s=>!0})}function ie(){return("1000000-1000-4000-8000"+-1e11).replace(/[018]/g,e=>(parseInt(e)^Math.floor(Math.random()*256)&15>>parseInt(e)/4).toString(16))}function Xe(e){return he.reduce((r,t)=>{let o=e[t]?e[t]:typeof e.get=="function"?e.get(t):null;return o&&(r[t]=o),r},{})}function x(e){if(!e)return null;if(e.raw&&typeof e.raw=="function")return e.raw();if(!e.forEach)return Xe(e);let r={};return e.forEach((t,o)=>r[o]=t),r}function z(e){return e!=null&&e.constructor!=null&&typeof e.constructor.isBuffer=="function"&&e.constructor.isBuffer(e)}function P(e){let r=JSON.parse(JSON.stringify(e));return r?.headers&&(r.headers.Authorization&&(r.headers.Authorization="Bearer ********"),r.headers.authorization&&(r.headers.authorization="Bearer ********")),r}function j(e,r){return{...r,headers:{...r.headers,Authorization:`Bearer ${e}`}}}var me=["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"];function te({retryCount:e,retryDelay:r,backoff:t,maxDelay:o}){return t&&e!==0?Math.min(Math.round((Math.random()+1)*r*2**e),o):r}Math.min(Math.round((Math.random()+1)*200*2**10),1/0);function oe(e){return new Promise(r=>{setTimeout(r,e)})}function A(e){if(!e?.credentials?.clientId||!e.projectKey||!e.host)throw new Error("Missing required options.");return{clientId:e.credentials.clientId,host:e.host,projectKey:e.projectKey}}function ne(e){return Date.now()+e*1e3-5*60*1e3}function b(e){let r=e;return{get:t=>r,set:(t,o)=>{r=t}}}function Ee(e){return typeof e<"u"&&e!==null}function Ze(e){return Ee(e)?typeof e=="string"?e:Object.fromEntries(Object.entries(e).filter(([r,t])=>![null,void 0,""].includes(t))):""}function er(e){let r={},t=new URLSearchParams(e);for(let o of t.keys())t.getAll(o).length>1?r[o]=t.getAll(o):r[o]=t.get(o);return r}function rr(e){if(e=Ze(e),!e)return"";let r=new URLSearchParams(e);for(let[t,o]of Object.entries(e))Array.isArray(o)&&(r.delete(t),o.filter(Ee).forEach(i=>r.append(t,i)));return r.toString()}function ye(e,r=er){return r(e)}function se(e,r=rr){return r(e)}var tr=()=>typeof window<"u"&&window.document&&window.document.nodeType===9;function or(){if(tr())return window.navigator.userAgent;let e=process?.version?.slice(1)||"unknown",r=`(${process?.platform||""}; ${process?.arch||""})`;return`node.js/${e} ${r.trim()}`}function ae(e){let r=null,t=null;if(!e)throw new Error("Missing required option `name`");let o=e.version?`${e.name}/${e.version}`:e.name;e.libraryName&&!e.libraryVersion?r=e.libraryName:e.libraryName&&e.libraryVersion&&(r=`${e.libraryName}/${e.libraryVersion}`),e.contactUrl&&!e.contactEmail?t=`(+${e.contactUrl})`:!e.contactUrl&&e.contactEmail?t=`(+${e.contactEmail})`:e.contactUrl&&e.contactEmail&&(t=`(+${e.contactUrl}; +${e.contactEmail})`);let i=or(),s=e.customAgent||"";return[o,i,r,t,s].filter(Boolean).join(" ")}function Me(e){if(!e.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`");if(!e.httpClient&&typeof e.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.");if(e.httpClientOptions&&Object.prototype.toString.call(e.httpClientOptions)!=="[object Object]")throw new Error("`httpClientOptions` must be an object type")}function fe(e){if(!Array.isArray(e))throw new Error("`retryCodes` option must be an array of retry status (error) codes and/or messages.")}function ge(e){if(!e)throw new Error("Missing required options");if(e.middlewares&&!Array.isArray(e.middlewares))throw new Error("Middlewares should be an array");if(!e.middlewares||!Array.isArray(e.middlewares)||!e.middlewares.length)throw new Error("You need to provide at least one middleware")}function le(e,r,t={allowedMethods:me}){if(!r)throw new Error(`The "${e}" function requires a "Request" object as an argument. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest`);if(typeof r.uri!="string")throw new Error(`The "${e}" Request object requires a valid uri. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest`);if(!t.allowedMethods.includes(r.method))throw new Error(`The "${e}" Request object requires a valid method. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest`)}function Ce(e){if(!Array.isArray(e))throw new Error("`stringBodyContentTypes` option must be an array of strings")}function Re(e){if(!e)throw new Error("Missing required options");if(!e.host)throw new Error("Missing required option (host)");if(!e.projectKey)throw new Error("Missing required option (projectKey)");if(!e.credentials)throw new Error("Missing required option (credentials)");let{clientId:r,clientSecret:t}=e.credentials||{};if(!(r&&t))throw new Error("Missing required credentials (clientId, clientSecret)");let o=e.scopes?e.scopes.join(" "):void 0,i=btoa(`${r}:${t}`),s=e.oauthUri||"/oauth/token",a=e.host.replace(/\/$/,"")+s,n=`grant_type=client_credentials${o?`&scope=${o}`:""}`;return{url:a,body:n,basicAuth:i}}function Oe(e){if(!e)throw new Error("Missing required options");if(!e.projectKey)throw new Error("Missing required option (projectKey)");let r=e.projectKey;e.oauthUri=e.oauthUri||`/oauth/${r}/anonymous/token`;let t=Re(e);return e.credentials.anonymousId&&(t.body+=`&anonymous_id=${e.credentials.anonymousId}`),{...t}}function de(e){if(!e)throw new Error("Missing required options");if(!e.host)throw new Error("Missing required option (host)");if(!e.projectKey)throw new Error("Missing required option (projectKey)");if(!e.credentials)throw new Error("Missing required option (credentials)");if(!e.refreshToken)throw new Error("Missing required option (refreshToken)");let{clientId:r,clientSecret:t}=e.credentials;if(!(r&&t))throw new Error("Missing required credentials (clientId, clientSecret)");let o=btoa(`${r}:${t}`),i=e.oauthUri||"/oauth/token",s=e.host.replace(/\/$/,"")+i,a=`grant_type=refresh_token&refresh_token=${encodeURIComponent(e.refreshToken)}`;return{basicAuth:o,url:s,body:a}}function ke(e){if(!e)throw new Error("Missing required options");if(!e.host)throw new Error("Missing required option (host)");if(!e.projectKey)throw new Error("Missing required option (projectKey)");if(!e.credentials)throw new Error("Missing required option (credentials)");let{clientId:r,clientSecret:t,user:o}=e.credentials,i=e.projectKey;if(!(r&&t&&o))throw new Error("Missing required credentials (clientId, clientSecret, user)");let{username:s,password:a}=o;if(!(s&&a))throw new Error("Missing required user credentials (username, password)");let n=(e.scopes||[]).join(" "),l=n?`&scope=${n}`:"",u=btoa(`${r}:${t}`),c=e.oauthUri||`/oauth/${i}/customers/token`,d=e.host.replace(/\/$/,"")+c,p=`grant_type=password&username=${encodeURIComponent(s)}&password=${encodeURIComponent(a)}${l}`;return{basicAuth:u,url:d,body:p}}async function Ae(e){let{httpClient:r,httpClientOptions:t,tokenCache:o,userOption:i,tokenCacheObject:s,tokenCacheKey:a,request:n}=e,l=e.url,u=e.body,c=e.basicAuth;if(!r||typeof r!="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.");if(s&&s.refreshToken&&(!s.token||s.token&&Date.now()>s.expirationTime)){if(!i)throw new Error("Missing required options.");let p={...de({...i,refreshToken:s.refreshToken})};l=p.url,u=p.body,c=p.basicAuth}let d;try{if(d=await v({url:l,method:"POST",headers:{...n.headers,Authorization:`Basic ${c}`,"Content-Type":"application/x-www-form-urlencoded","Content-Length":N(u)},httpClient:r,httpClientOptions:t,body:u}),d.statusCode>=200&&d.statusCode<300){let{access_token:p,expires_in:M,refresh_token:C}=d?.data,h=ne(M),E={token:p,expirationTime:h,refreshToken:C};return await o.set(E,a),Promise.resolve(!0)}throw U({code:d.data.error,statusCode:d.data.statusCode,message:d.data.message,error:d.data.errors})}catch(p){throw p}}async function k(e,r=null,t,o,i,s,a,n){let l={request:e,tokenCache:i,tokenCacheKey:o,httpClient:a.httpClient||fetch,httpClientOptions:a.httpClientOptions,...s(a),userOption:a,next:n},u=async c=>{let d=Object.assign({},c);return d.statusCode==401&&(r=Ae(l),await r,r=null,t=await i.get(o),d=await n(j(t.token,e))),d};return e.headers&&(e.headers.Authorization||e.headers.authorization)?u(await n(e)):(t=await i.get(o),t&&t.token&&Date.now()<t.expirationTime?u(await n(j(t.token,e))):(r?await r:(r=Ae(l),await r,r=null),t=await i.get(o),n(j(t.token,e))))}function H(e){let r=e.tokenCache||b({token:"",expirationTime:-1}),t,o=null,i=A(e);return s=>async a=>k(a,o,t,i,r,Oe,e,s)}function B(e){let r=e.tokenCache||b({token:"",expirationTime:-1}),t,o=null,i=A(e);return s=>async a=>k(a,o,t,i,r,Re,e,s)}function _(e,r){return t=>async o=>{if(typeof e!="string")throw new Error("authorization must be a string");let i=r?.force===void 0?!0:r.force;if(!e||o.headers&&(o.headers.Authorization||o.headers.authorization)&&i===!1)return t(o);let s={...o,headers:{...o.headers,Authorization:e}};return t(s)}}function K(e){let r=e.tokenCache||b({token:"",expirationTime:-1}),t,o=null,i=A(e);return s=>async a=>k(a,o,t,i,r,ke,e,s)}function L(e){let r=e.tokenCache||b({token:"",tokenCacheKey:null}),t,o=null,i=A(e);return s=>async a=>k(a,o,t,i,r,de,e,s)}function J(e){return r=>async t=>{let o=await r(t);if(o.statusCode==409){let i=o.error.body?.errors?.[0]?.currentVersion;if(i)return e&&typeof e=="function"?t.body=await e(i,t,o):t.body=typeof t.body=="string"?{...JSON.parse(t.body),version:i}:{...t.body,version:i},r(t)}return o}}function V(e){return r=>t=>{let o={...t,headers:{...t.headers,"X-Correlation-ID":e?.generate&&typeof e.generate=="function"?e.generate():ie()}};return r(o)}}function G(e={}){return r=>async t=>{let o=await r(t);if(o.error){let{error:i}=o;return e.handler&&typeof e.handler=="function"?e.handler({error:i,request:t,response:o,next:r}):{...o,statusCode:i.statusCode||0,headers:i.headers||x({}),body:i,error:i}}return o}}async function ir({url:e,httpClient:r,clientOptions:t}){let{request:o,maskSensitiveHeaderData:i,includeRequestInErrorResponse:s,includeResponseHeaders:a}=t;try{let n=await v({url:e,...t,httpClient:r,method:t.method,...t.body?{body:t.body}:{}});if(a||(n.headers=null),n.statusCode>=200&&n.statusCode<300)return t.method=="HEAD"?{body:null,statusCode:n.statusCode,retryCount:n.retryCount,headers:x(n.headers)}:{body:n.data,statusCode:n.statusCode,retryCount:n.retryCount,headers:x(n.headers)};let l=U({code:n.data?.errors?.[0].code,message:n?.data?.message||n?.message,statusCode:n.statusCode||n?.data?.statusCode,method:t.method,headers:x(n.headers),body:n.data,error:n.data,retryCount:n.retryCount,...s?{originalRequest:i?P(o):o}:{uri:o.uri}});return{...l,error:l}}catch(n){let l=a?x(n.response?.headers):null,u=n.response?.status||n.response?.statusCode||n.response?.data.statusCode||0,c=n.response?.data?.message;throw{body:null,error:U({statusCode:u,code:"NetworkError",status:u,message:c||n.message,headers:l,body:n.response?.data||n,error:n.response?.data||n,...s?{originalRequest:i?P(o):o}:{uri:o.uri}})}}}function Y(e){Me(e);let{host:r,credentialsMode:t,httpClient:o,timeout:i,enableRetry:s,retryConfig:a,getAbortController:n,includeOriginalRequest:l,includeRequestInErrorResponse:u=!0,includeResponseHeaders:c=!0,maskSensitiveHeaderData:d,httpClientOptions:p,stringBodyContentTypes:M=[]}=e;return C=>async h=>{let E=r.replace(/\/$/,"")+h.uri,w={...h.headers};Ce(M),Object.prototype.hasOwnProperty.call(w,"Content-Type")||Object.prototype.hasOwnProperty.call(w,"content-type")||(w["Content-Type"]="application/json"),w["Content-Type"]===null&&delete w["Content-Type"];let f=[...g.HEADERS_CONTENT_TYPES,...M].indexOf(w["Content-Type"])>-1&&typeof h.body=="string"||z(h.body)?h.body:JSON.stringify(h.body||void 0);f&&(typeof f=="string"||z(f))&&(w["Content-Length"]=N(f));let R={enableRetry:s,retryConfig:a,request:h,method:h.method,headers:w,includeRequestInErrorResponse:u,maskSensitiveHeaderData:d,includeResponseHeaders:c,...p};t&&(R.credentialsMode=t),i&&(R.timeout=i,R.getAbortController=n),f&&(R.body=f);let O=await ir({url:E,clientOptions:R,httpClient:o}),F={...h,includeOriginalRequest:l,maskSensitiveHeaderData:d,response:O};return C(F)}}function W(e){return r=>async t=>{let o=await r(t),i=Object.assign({},o),{loggerFn:s=console.log}=e||{};return s&&typeof s=="function"&&s(o),i}}function X({concurrency:e=20}){let r=0,t=[],o=()=>0>=e?Promise.resolve():new Promise(s=>{let a=()=>{r<e?(r++,s()):t.push(a)};a()}),i=()=>{if(r--,t.length>0){let s=t.shift();s&&s()}};return s=>a=>o().then(()=>{let n={...a,resolve(l){a.resolve(l),i()},reject(l){a.reject(l),i()}};return s(n).finally(()=>{i()})})}var Se={name:"@commercetools/ts-client",version:"4.2.1",engines:{node:">=18"},description:"commercetools Composable Commerce TypeScript SDK client.",keywords:["commercetools","composable commerce","sdk","typescript","client","middleware","http","oauth","auth"],homepage:"https://github.com/commercetools/commercetools-sdk-typescript",license:"MIT",directories:{lib:"lib",test:"test"},publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/commercetools/commercetools-sdk-typescript.git"},bugs:{url:"https://github.com/commercetools/commercetools-sdk-typescript/issues"},dependencies:{buffer:"^6.0.3"},files:["dist","CHANGELOG.md"],author:"Chukwuemeka Ajima <meeky.ae@gmail.com>",main:"dist/commercetools-ts-client.cjs.js",module:"dist/commercetools-ts-client.esm.js",browser:{"./dist/commercetools-ts-client.cjs.js":"./dist/commercetools-ts-client.browser.cjs.js","./dist/commercetools-ts-client.esm.js":"./dist/commercetools-ts-client.browser.esm.js"},devDependencies:{"common-tags":"1.8.2",dotenv:"16.5.0",jest:"29.7.0",nock:"14.0.4","organize-imports-cli":"0.10.0"},scripts:{organize_imports:"find src -type f -name '*.ts' | xargs organize-imports-cli",postbuild:"yarn organize_imports",post_process_generate:"yarn organize_imports",docs:"typedoc --out docs"}};function Z(e){return r=>async t=>{let o=ae({...e,name:`${e.name?e.name+"/":""}commercetools-sdk-javascript-v3/${Se.version}`}),i={...t,headers:{...t.headers,"User-Agent":o}};return r(i)}}function sr({middlewares:e}){return e.length===1?e[0]:e.slice().reduce((t,o)=>(...i)=>t(o.apply(null,i)))}var Pe;function ue(e,r,t){if(le("process",e,{allowedMethods:["GET"]}),typeof r!="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');let o={total:Number.POSITIVE_INFINITY,accumulate:!0,...t};return new Promise((i,s)=>{let a,n="";if(e&&e.uri){let[M,C]=e.uri.split("?");a=M,n=C}let u={limit:20,...{...ye(n)}},c=o.total,d=!1,p=async(M,C=[])=>{let h=u.limit<c?u.limit:c,E=se({...u,limit:h}),w={sort:"id asc",withTotal:!1,...M?{where:`id > "${M}"`}:{}},f=se(w),R={...e,uri:`${a}?${f}&${E}`};try{let O=await q(Pe).execute(R),{results:F,count:I}=O?.body||{};if(!I&&d)return i(C||[]);let m=await Promise.resolve(r(O)),y;if(d=!0,o.accumulate&&(y=C.concat(m||[])),c-=I,I<u.limit||!c)return i(y||[]);let D=F[I-1],ee=D&&D.id;p(ee,y)}catch(O){s(O)}};p()})}function q(e){Pe=e,ge(e);let r=!1,t={async resolve(i){let{response:s,includeOriginalRequest:a,maskSensitiveHeaderData:n,...l}=i,{retryCount:u,...c}=s;return r=n,{body:null,error:null,reject:i.reject,resolve:i.resolve,...c,...a?{originalRequest:l}:{},...s?.retryCount?{retryCount:s.retryCount}:{}}}},o=sr(e)(t.resolve);return{process:ue,execute(i){return le("exec",i),new Promise(async(s,a)=>{try{let n=await o({reject:a,resolve:s,...i});if(n.error)return a(n.error);n.originalRequest&&r&&(n.originalRequest=P(n.originalRequest)),s(n)}catch(n){a(n)}})}}}var{createAuthMiddlewareForPasswordFlow:ar,createAuthMiddlewareForAnonymousSessionFlow:lr,createAuthMiddlewareForClientCredentialsFlow:dr,createAuthMiddlewareForRefreshTokenFlow:ur,createAuthMiddlewareForExistingTokenFlow:cr,createCorrelationIdMiddleware:pr,createHttpMiddleware:hr,createLoggerMiddleware:wr,createQueueMiddleware:fr,createUserAgentMiddleware:qe,createConcurrentModificationMiddleware:mr,createErrorMiddleware:yr}=be,$=class{projectKey;authMiddleware;httpMiddleware;userAgentMiddleware;correlationIdMiddleware;loggerMiddleware;queueMiddleware;concurrentMiddleware;telemetryMiddleware;beforeMiddleware;afterMiddleware;errorMiddleware;middlewares=[];constructor(){this.userAgentMiddleware=qe({})}withProjectKey(r){return this.projectKey=r,this}defaultClient(r,t,o,i,s,a){return this.withClientCredentialsFlow({host:o,projectKey:i||this.projectKey,credentials:t,httpClient:a||fetch,scopes:s}).withHttpMiddleware({host:r,httpClient:a||fetch})}withAuthMiddleware(r){return this.authMiddleware=r,this}withMiddleware(r){return this.middlewares.push(r),this}withErrorMiddleware(r){return this.errorMiddleware=yr(r),this}withClientCredentialsFlow(r){return this.withAuthMiddleware(dr({host:r.host||g.CTP_AUTH_URL,projectKey:r.projectKey||this.projectKey,credentials:{clientId:r.credentials.clientId||null,clientSecret:r.credentials.clientSecret||null},oauthUri:r.oauthUri||null,scopes:r.scopes,httpClient:r.httpClient||fetch,...r}))}withPasswordFlow(r){return this.withAuthMiddleware(ar({host:r.host||g.CTP_AUTH_URL,projectKey:r.projectKey||this.projectKey,credentials:{clientId:r.credentials.clientId||null,clientSecret:r.credentials.clientSecret||null,user:{username:r.credentials.user.username||null,password:r.credentials.user.password||null}},httpClient:r.httpClient||fetch,...r}))}withAnonymousSessionFlow(r){return this.withAuthMiddleware(lr({host:r.host||g.CTP_AUTH_URL,projectKey:this.projectKey||r.projectKey,credentials:{clientId:r.credentials.clientId||null,clientSecret:r.credentials.clientSecret||null,anonymousId:r.credentials.anonymousId||null},httpClient:r.httpClient||fetch,...r}))}withRefreshTokenFlow(r){return this.withAuthMiddleware(ur({host:r.host||g.CTP_AUTH_URL,projectKey:this.projectKey||r.projectKey,credentials:{clientId:r.credentials.clientId||null,clientSecret:r.credentials.clientSecret||null},httpClient:r.httpClient||fetch,refreshToken:r.refreshToken||null,...r}))}withExistingTokenFlow(r,t){return this.withAuthMiddleware(cr(r,{force:t.force||!0,...t}))}withHttpMiddleware(r){return this.httpMiddleware=hr({host:r.host||g.CTP_API_URL,httpClient:r.httpClient||fetch,...r}),this}withUserAgentMiddleware(r){return this.userAgentMiddleware=qe(r),this}withQueueMiddleware(r){return this.queueMiddleware=fr({concurrency:r.concurrency||g.CONCURRENCT_REQUEST,...r}),this}withLoggerMiddleware(r){return this.loggerMiddleware=wr(r),this}withCorrelationIdMiddleware(r){return this.correlationIdMiddleware=pr({generate:r?.generate,...r}),this}withConcurrentModificationMiddleware(r){return this.concurrentMiddleware=mr(r?.concurrentModificationHandlerFn),this}withTelemetryMiddleware(r){let{createTelemetryMiddleware:t,...o}=r;return this.withUserAgentMiddleware({customAgent:o?.userAgent||"typescript-sdk-apm-middleware"}),this.telemetryMiddleware=t(o),this}withBeforeExecutionMiddleware(r){let{middleware:t,...o}=r||{};return this.beforeMiddleware=r.middleware(o),this}withAfterExecutionMiddleware(r){let{middleware:t,...o}=r||{};return this.afterMiddleware=r.middleware(o),this}build(){let r=this.middlewares.slice();return this.telemetryMiddleware&&r.push(this.telemetryMiddleware),this.correlationIdMiddleware&&r.push(this.correlationIdMiddleware),this.userAgentMiddleware&&r.push(this.userAgentMiddleware),this.errorMiddleware&&r.push(this.errorMiddleware),this.authMiddleware&&r.push(this.authMiddleware),this.beforeMiddleware&&r.push(this.beforeMiddleware),this.queueMiddleware&&r.push(this.queueMiddleware),this.loggerMiddleware&&r.push(this.loggerMiddleware),this.concurrentMiddleware&&r.push(this.concurrentMiddleware),this.httpMiddleware&&r.push(this.httpMiddleware),this.afterMiddleware&&r.push(this.afterMiddleware),q({middlewares:r})}};return je(Mr);})();
|
|
@@ -323,7 +323,7 @@ type TResponse = {
|
|
|
323
323
|
}
|
|
324
324
|
|
|
325
325
|
export type Client = {
|
|
326
|
-
execute(request: ClientRequest): Promise<ClientResult
|
|
326
|
+
execute<T extends object = any>(request: ClientRequest): Promise<ClientResult<T>>
|
|
327
327
|
process<T extends object = any>(
|
|
328
328
|
request: ClientRequest,
|
|
329
329
|
fn: ProcessFn<T>,
|