getta 1.0.15 → 1.0.17
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 +1 -1
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/index.mjs.map +1 -1
- package/dist/production.analysis.txt +15 -15
- package/dist/types/cjs/constants.d.cts.map +1 -1
- package/dist/types/cjs/helpers/buildEndpoint/index.d.cts.map +1 -1
- package/dist/types/cjs/helpers/defaultPathTemplateCallback/index.d.cts.map +1 -1
- package/dist/types/cjs/helpers/delay/index.d.cts.map +1 -1
- package/dist/types/cjs/helpers/getResponseGroup/index.d.cts.map +1 -1
- package/dist/types/cjs/helpers/isCacheabilityValid/index.d.cts.map +1 -1
- package/dist/types/cjs/main.d.cts.map +1 -1
- package/dist/types/esm/constants.d.ts.map +1 -1
- package/dist/types/esm/helpers/buildEndpoint/index.d.ts.map +1 -1
- package/dist/types/esm/helpers/defaultPathTemplateCallback/index.d.ts.map +1 -1
- package/dist/types/esm/helpers/delay/index.d.ts.map +1 -1
- package/dist/types/esm/helpers/getResponseGroup/index.d.ts.map +1 -1
- package/dist/types/esm/helpers/isCacheabilityValid/index.d.ts.map +1 -1
- package/dist/types/esm/main.d.ts.map +1 -1
- package/dist/types/tsconfig.build.tsbuildinfo +1 -1
- package/package.json +38 -35
- package/src/helpers/buildEndpoint/index.ts +7 -3
- package/src/main.ts +12 -18
package/LICENSE
CHANGED
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";require("core-js/modules/es.array.push.js");var e=require("lodash-es"),t=require("ts-md5"),r=require("query-string");const s="arrayBuffer",a="blob",i="formData",h="json",o="text",c={ARRAY_BUFFER_FORMAT:s,BLOB_FORMAT:a,FORM_DATA_FORMAT:i,JSON_FORMAT:h,TEXT_FORMAT:o},n=e=>e,_=5e3,E={"content-type":"application/json"},p=5,u=3,R=/({type})|({id})|({id,\+})|({brief\|standard})/g,T=/({\w+\?})/g,d=50,m=100,l="Getta expected to receive 'basePath' in the constructor options,\n but recevied undefined.",x="The request exceeded the maximum number of redirects, which is",f="The request exceeded the maximum number of retries, which is",g="Getta expected to receive 'get', 'post', 'put' or 'delete', but received",y="The requested resource could not been found.",O="The request timed out. Getta did not get a response within",S="get",A="post",P="put",q="delete",C=[S,A,P,q],D="information",L="successful",F="redirection",M="clientError",b="serverError",w="ETag",H="Location",N="If-None-Match",v="Cache-Control",U="request_sent",I="response_received",k="response_from_cache",$="request_failed",Q=(e,t,r)=>{const s=Object.keys(t);return e.replace(r,(e=>{for(const r of s)if(e.includes(r)&&void 0!==t[r])return String(t[r]);return""}))},G=(e,t,{optionalPathTemplateRegExp:s,pathTemplateCallback:a,pathTemplateData:i,pathTemplateRegExp:h,queryParams:o})=>{const c=e.endsWith("/")||t.startsWith("/")?"":"/";let n=`${e}${c}${t}`;if(i&&(n=a(n,i,h)),n=n.replace(s,""),n.endsWith("/")&&(n=n.slice(0,Math.max(0,n.length-1))),o&&Object.keys(o).length>0){n=`${n}${r.extract(n)?"&":"?"}${r.stringify(o)}`}return n};class X{constructor(e){this._rateLimitCount=0,this._rateLimitedRequestQueue=[],this._rateLimitTimer=void 0,this._requestTracker={active:[],pending:new Map};const{basePath:t,bodyParser:r=n,cache:s,enableConditionalRequests:a=!0,fetchTimeout:i=_,headers:o,log:c,maxRedirects:x=p,maxRetries:f=u,optionalPathTemplateRegExp:g=T,pathTemplateCallback:y=Q,pathTemplateRegExp:O=R,performance:S,queryParams:A={},rateLimit:P=!1,rateLimitPerSecond:q=d,requestRetryWait:C=m,streamReader:D=h}=e;if(!t)throw new Error(l);this._basePath=t,this._bodyParser=r,this._cache=s,this._conditionalRequestsEnabled=a,this._fetchTimeout=i,this._headers={...E,...o},this._log=c,this._maxRedirects=x,this._maxRetries=f,this._optionalPathTemplateRegExp=g,this._pathTemplateCallback=y,this._pathTemplateRegExp=O,this._performance=S,this._queryParams=A,this._rateLimit=P,this._rateLimitPerSecond=q,this._requestRetryWait=C,this._streamReader=D}get cache(){return this._cache}createShortcut(t,r,{method:s,...a}){if(!C.includes(s))throw new Error(`${g} ${s}`);this[t]=async({method:t,...i}={},h)=>this[t??s](r,e.merge({},a,i),h)}async delete(e,t={},r){return this._delete(e,t,r)}async get(e,t={},r){return this._get(e,t,r)}async post(e,t,r){return this._request(e,{...t,method:A},r)}async put(e,t,r){return this._request(e,{...t,method:P},r)}_addRequestToRateLimitedQueue(e,t,r){return new Promise((s=>{this._rateLimitedRequestQueue.push([s,e,t,r])}))}async _cacheEntryDelete(e){return!!this._cache&&this._cache.delete(e)}async _cacheEntryGet(e){if(this._cache)return this._cache.get(e)}async _cacheEntryHas(e){if(!this._cache)return!1;try{return await this._cache.has(e)}catch{return!1}}async _cacheEntrySet(e,t,r){if(this._cache)return this._cache.set(e,t,{cacheHeaders:r})}async _delete(e,{headers:r={},pathTemplateData:s,queryParams:a={},...i},h){const o=G(this._basePath,e,{optionalPathTemplateRegExp:this._optionalPathTemplateRegExp,pathTemplateCallback:this._pathTemplateCallback,pathTemplateData:s,pathTemplateRegExp:this._pathTemplateRegExp,queryParams:{...this._queryParams,...a}}),c=t.Md5.hashStr(o);return await this._cacheEntryHas(c)&&this._cacheEntryDelete(c),this._fetch(o,{headers:{...this._headers,...r},method:q,...i},h)}async _fetch(t,r,s={}){s.startTime=this._performance.now();try{const{redirects:e,retries:a,...i}=r;return await new Promise(((h,o)=>{(async()=>{const c=setTimeout((()=>{o(new Error(`${O} ${String(this._fetchTimeout)}ms.`))}),this._fetchTimeout);if(this._rateLimit&&(this._startRateLimit(),!(this._rateLimitCount<this._rateLimitPerSecond)))return clearTimeout(c),void h(await this._addRequestToRateLimitedQueue(t,r,s));e||a||this._log?.(U,{context:{fetchMethod:i.method,fetchRedirets:e,fetchRequestHeaders:i.headers,fetchRetries:a,fetchUrl:t,logEntryName:"FETCH_REQUEST_SENT",...s},stats:{startTime:s.startTime}});const n=await fetch(t,i);clearTimeout(c);const{body:_,headers:E,status:p}=n,u=(e=>{switch(!0){case e<200:return D;case e<300:return L;case e<400:return F;case e<500:return M;default:return b}})(p);if(u===F&&E.has(H))h(await this._fetchRedirectHandler(n,E.get(H),{redirects:e,status:p,...i},s));else if(u!==b)try{Object.defineProperty(n,"data",{enumerable:!0,value:_?this._bodyParser(await n[this._streamReader]()):void 0,writable:!0}),this._logResponse(n,t,r,s),h(n)}catch(e){e instanceof Error?o(e):o(new Error(`Unable to ${i.method} ${t} due to previous error`))}else h(await this._fetchRetryHandler(n,t,{retries:a,...i},s))})()}))}catch(r){const{startTime:a,...i}=s,h=this._performance.now();return this._log?.($,{context:{error:r,fetchUrl:t,logEntryName:"FETCH_REQUEST_FAILED",...i},stats:{duration:a?h-a:0,endTime:h,startTime:a}}),{errors:e.castArray(r)}}}async _fetchRedirectHandler(e,t,r,s){const{method:a,redirects:i=1,status:h,...o}=r;if(i===this._maxRedirects)return e.errors=[new Error(`${x} ${String(this._maxRedirects)}.`)],this._logResponse(e,t,r,s),e;const c=303===h?S:a;return this._fetch(t,{method:c,redirects:i+1,...o})}async _fetchRetryHandler(e,t,r,s){const{retries:a=1,...i}=r;return a===this._maxRetries?(e.errors=[new Error(`${f} ${String(this._maxRetries)}.`)],this._logResponse(e,t,r,s),e):(await(h=this._requestRetryWait,new Promise((e=>setTimeout(e,h)))),this._fetch(t,{retries:a+1,...i}));var h}async _get(e,{headers:r={},pathTemplateData:s,queryParams:a={}},i){const h=G(this._basePath,e,{optionalPathTemplateRegExp:this._optionalPathTemplateRegExp,pathTemplateCallback:this._pathTemplateCallback,pathTemplateData:s,pathTemplateRegExp:this._pathTemplateRegExp,queryParams:{...this._queryParams,...a}}),o=t.Md5.hashStr(h),c=await this._cacheEntryHas(o);if(c){if((e=>!e.metadata.cacheControl.noCache&&e.checkTTL())(c)){const e={...r,"cache-control":c.printCacheControl()};return this._log?.(k,{context:{fetchMethod:S,fetchResponseHeaders:e,fetchUrl:h,logEntryName:"FETCH_RESPONSE_FROM_CACHE",...i}}),{data:await this._cacheEntryGet(o),headers:new Headers(e)}}this._conditionalRequestsEnabled&&c.metadata.etag&&(r[N]=c.metadata.etag)}const n=this._trackRequest(o);return n||this._getResolve(o,await this._fetch(h,{headers:{...this._headers,...r},method:S},i))}async _getResolve(e,t){const{data:r,headers:s,status:a}=t;if(404===a){this._cacheEntryDelete(e);let{errors:r}=t;r||(r=[]),r.push(new Error(y)),t.errors=r}else if(304===a){const r=await this._cacheEntryGet(e);r&&(this._cacheEntrySet(e,r,{cacheControl:s.get(v)??void 0,etag:s.get(w)??void 0}),t.data=r)}else r&&this._cacheEntrySet(e,r,{cacheControl:s.get(v)??void 0,etag:s.get(w)??void 0});return this._resolvePendingRequests(e,t),this._requestTracker.active=this._requestTracker.active.filter((t=>t!==e)),t}_logResponse(e,t,r,s){const{headers:a,status:i}=e,{method:h,redirects:o,retries:c}=r,{startTime:n,..._}=s,E=this._performance.now(),p=n?E-n:0;this._log?.(I,{context:{fetchMethod:h,fetchRedirects:o,fetchResponseHeaders:Object.fromEntries(a.entries()),fetchResponseStatus:i,fetchRetries:c,fetchUrl:t,logEntryName:"FETCH_RESPONSE_RECEIVED",..._},stats:{duration:p,endTime:E,startTime:n}})}async _releaseRateLimitedRequestQueue(){for(const[e,t,r,s]of this._rateLimitedRequestQueue)e(await this._fetch(t,r,s));this._rateLimitedRequestQueue=[]}async _request(e,{body:t,headers:r,method:s,pathTemplateData:a,queryParams:i,...h},o){const c=G(this._basePath,e,{optionalPathTemplateRegExp:this._optionalPathTemplateRegExp,pathTemplateCallback:this._pathTemplateCallback,pathTemplateData:a,pathTemplateRegExp:this._pathTemplateRegExp,queryParams:{...this._queryParams,...i}});return this._fetch(c,{body:t,headers:{...this._headers,...r},method:s,...h},o)}_resolvePendingRequests(e,t){const r=this._requestTracker.pending.get(e);if(r){for(const{resolve:e}of r)e(t);this._requestTracker.pending.delete(e)}}_setPendingRequest(e,t){let r=this._requestTracker.pending.get(e);r||(r=[]),r.push(t),this._requestTracker.pending.set(e,r)}_startRateLimit(){this._rateLimitTimer||(this._rateLimitTimer=setTimeout((()=>{this._rateLimitTimer=void 0,this._rateLimitCount=0,this._rateLimitedRequestQueue.length>0&&this._releaseRateLimitedRequestQueue()}),1e3)),this._rateLimitCount+=1}_trackRequest(e){if(this._requestTracker.active.includes(e))return new Promise((t=>{this._setPendingRequest(e,{resolve:t})}));this._requestTracker.active.push(e)}}exports.ARRAY_BUFFER_FORMAT=s,exports.BLOB_FORMAT=a,exports.CACHE_CONTROL_HEADER=v,exports.CLIENT_ERROR_REPSONSE=M,exports.COOKIE_HEADER="Cookie",exports.DEFAULT_BODY_PARSER=n,exports.DEFAULT_FETCH_TIMEOUT=_,exports.DEFAULT_HEADERS=E,exports.DEFAULT_MAX_REDIRECTS=p,exports.DEFAULT_MAX_RETRIES=u,exports.DEFAULT_PATH_TEMPLATE_REGEX=R,exports.DEFAULT_RATE_LIMIT=d,exports.DEFAULT_REQUEST_RETRY_WAIT=m,exports.DELETE_METHOD=q,exports.ETAG_HEADER=w,exports.FETCH_METHODS=C,exports.FETCH_TIMEOUT_ERROR=O,exports.FORM_DATA_FORMAT=i,exports.GET_METHOD=S,exports.Getta=X,exports.IF_NONE_MATCH_HEADER=N,exports.INFORMATION_REPSONSE=D,exports.INVALID_FETCH_METHOD_ERROR=g,exports.JSON_FORMAT=h,exports.LOCATION_HEADER=H,exports.MAX_REDIRECTS_EXCEEDED_ERROR=x,exports.MAX_RETRIES_EXCEEDED_ERROR=f,exports.MISSING_BASE_PATH_ERROR=l,exports.NOT_FOUND_STATUS_CODE=404,exports.NOT_MODIFIED_STATUS_CODE=304,exports.OPTIONAL_PATH_TEMPLATE_REGEX=T,exports.POST_METHOD=A,exports.PUT_METHOD=P,exports.REDIRECTION_REPSONSE=F,exports.REQUEST_FAILED=$,exports.REQUEST_SENT=U,exports.RESOURCE_NOT_FOUND_ERROR=y,exports.RESPONSE_FROM_CACHE=k,exports.RESPONSE_RECEIVED=I,exports.SERVER_ERROR_REPSONSE=b,exports.STREAM_READERS=c,exports.SUCCESSFUL_REPSONSE=L,exports.TEXT_FORMAT=o,exports.createRestClient=(e,t)=>{const r=new X(e);if(!t)return r;for(const e of Object.keys(t)){const s=t[e];s&&r.createShortcut(e,...s)}return r},exports.defaultPathTemplateCallback=Q;
|
|
1
|
+
"use strict";require("core-js/modules/es.array.push.js");var e=require("lodash-es"),t=require("ts-md5"),r=require("query-string");const s="arrayBuffer",a="blob",i="formData",h="json",o="text",c={ARRAY_BUFFER_FORMAT:s,BLOB_FORMAT:a,FORM_DATA_FORMAT:i,JSON_FORMAT:h,TEXT_FORMAT:o},n=e=>e,_=5e3,E={"content-type":"application/json"},p=5,u=3,R=/({type})|({id})|({id,\+})|({brief\|standard})/g,d=/({\w+\?})/g,T=50,m=100,l="Getta expected to receive 'basePath' in the constructor options,\n but recevied undefined.",x="The request exceeded the maximum number of redirects, which is",f="The request exceeded the maximum number of retries, which is",g="Getta expected to receive 'get', 'post', 'put' or 'delete', but received",y="The requested resource could not been found.",O="The request timed out. Getta did not get a response within",S="get",A="post",P="put",q="delete",C=[S,A,P,q],D="information",L="successful",F="redirection",M="clientError",b="serverError",w="ETag",H="Location",N="If-None-Match",v="Cache-Control",U="request_sent",I="response_received",k="response_from_cache",$="request_failed",Q=(e,t,r)=>{const s=Object.keys(t);return e.replace(r,(e=>{for(const r of s)if(e.includes(r)&&void 0!==t[r])return String(t[r]);return""}))},G=(t,s,{optionalPathTemplateRegExp:a,pathTemplateCallback:i,pathTemplateData:h,pathTemplateRegExp:o,queryParams:c={}})=>{const n=t.endsWith("/")||s.startsWith("/")?"":"/";let _=`${t}${n}${s}`;h&&(_=i(_,h,o)),_=_.replace(a,""),_.endsWith("/")&&(_=_.slice(0,Math.max(0,_.length-1)));const E=e.omitBy(c,(e=>!e));if(Object.keys(E).length>0){_=`${_}${r.extract(_)?"&":"?"}${r.stringify(E)}`}return _};class B{constructor(e){this._rateLimitCount=0,this._rateLimitedRequestQueue=[],this._rateLimitTimer=void 0,this._requestTracker={active:[],pending:new Map};const{basePath:t,bodyParser:r=n,cache:s,enableConditionalRequests:a=!0,fetchTimeout:i=_,headers:o,log:c,maxRedirects:x=p,maxRetries:f=u,optionalPathTemplateRegExp:g=d,pathTemplateCallback:y=Q,pathTemplateRegExp:O=R,performance:S,queryParams:A={},rateLimit:P=!1,rateLimitPerSecond:q=T,requestRetryWait:C=m,streamReader:D=h}=e;if(!t)throw new Error(l);this._basePath=t,this._bodyParser=r,this._cache=s,this._conditionalRequestsEnabled=a,this._fetchTimeout=i,this._headers={...E,...o},this._log=c,this._maxRedirects=x,this._maxRetries=f,this._optionalPathTemplateRegExp=g,this._pathTemplateCallback=y,this._pathTemplateRegExp=O,this._performance=S,this._queryParams=A,this._rateLimit=P,this._rateLimitPerSecond=q,this._requestRetryWait=C,this._streamReader=D}get cache(){return this._cache}createShortcut(t,r,{method:s,...a}){if(!C.includes(s))throw new Error(`${g} ${s}`);this[t]=async({method:t,...i}={},h)=>this[t??s](r,e.merge({},a,i),h)}async delete(e,t={},r){return this._delete(e,t,r)}async get(e,t={},r){return this._get(e,t,r)}async post(e,t,r){return this._request(e,{...t,method:A},r)}async put(e,t,r){return this._request(e,{...t,method:P},r)}_addRequestToRateLimitedQueue(e,t,r){return new Promise((s=>{this._rateLimitedRequestQueue.push([s,e,t,r])}))}async _cacheEntryDelete(e){return!!this._cache&&this._cache.delete(e)}async _cacheEntryGet(e){if(this._cache)return this._cache.get(e)}async _cacheEntryHas(e){if(!this._cache)return!1;try{return await this._cache.has(e)}catch{return!1}}async _cacheEntrySet(e,t,r){if(this._cache)return this._cache.set(e,t,{cacheHeaders:r})}async _delete(e,{headers:r={},pathTemplateData:s,queryParams:a={},...i},h){const o=G(this._basePath,e,{optionalPathTemplateRegExp:this._optionalPathTemplateRegExp,pathTemplateCallback:this._pathTemplateCallback,pathTemplateData:s,pathTemplateRegExp:this._pathTemplateRegExp,queryParams:{...this._queryParams,...a}}),c=t.Md5.hashStr(o);return await this._cacheEntryHas(c)&&this._cacheEntryDelete(c),this._fetch(o,{headers:{...this._headers,...r},method:q,...i},h)}async _fetch(t,r,s={}){s.startTime=this._performance.now();try{const{redirects:e,retries:a,...i}=r;return await new Promise(((h,o)=>{(async()=>{const c=setTimeout((()=>{o(new Error(`${O} ${String(this._fetchTimeout)}ms.`))}),this._fetchTimeout);if(this._rateLimit&&(this._startRateLimit(),!(this._rateLimitCount<this._rateLimitPerSecond)))return clearTimeout(c),void h(await this._addRequestToRateLimitedQueue(t,r,s));e||a||this._log?.(U,{context:{fetchMethod:i.method,fetchRedirets:e,fetchRequestHeaders:i.headers,fetchRetries:a,fetchUrl:t,logEntryName:"FETCH_REQUEST_SENT",...s},stats:{startTime:s.startTime}});const n=await fetch(t,i);clearTimeout(c);const{body:_,headers:E,status:p}=n,u=(e=>{switch(!0){case e<200:return D;case e<300:return L;case e<400:return F;case e<500:return M;default:return b}})(p);if(u===F&&E.has(H))h(await this._fetchRedirectHandler(n,E.get(H),{redirects:e,status:p,...i},s));else if(u!==b)try{Object.defineProperty(n,"data",{enumerable:!0,value:_?this._bodyParser(await n[this._streamReader]()):void 0,writable:!0}),this._logResponse(n,t,r,s),h(n)}catch(e){e instanceof Error?o(e):o(new Error(`Unable to ${i.method} ${t} due to previous error`))}else h(await this._fetchRetryHandler(n,t,{retries:a,...i},s))})()}))}catch(r){const{startTime:a,...i}=s,h=this._performance.now();return this._log?.($,{context:{error:r,fetchUrl:t,logEntryName:"FETCH_REQUEST_FAILED",...i},stats:{duration:a?h-a:0,endTime:h,startTime:a}}),{errors:e.castArray(r)}}}async _fetchRedirectHandler(e,t,r,s){const{method:a,redirects:i=1,status:h,...o}=r;if(i===this._maxRedirects)return e.errors=[new Error(`${x} ${String(this._maxRedirects)}.`)],this._logResponse(e,t,r,s),e;const c=303===h?S:a;return this._fetch(t,{method:c,redirects:i+1,...o})}async _fetchRetryHandler(e,t,r,s){const{retries:a=1,...i}=r;return a===this._maxRetries?(e.errors=[new Error(`${f} ${String(this._maxRetries)}.`)],this._logResponse(e,t,r,s),e):(await(h=this._requestRetryWait,new Promise((e=>setTimeout(e,h)))),this._fetch(t,{retries:a+1,...i}));var h}async _get(e,{headers:r={},pathTemplateData:s,queryParams:a={}},i){const h=G(this._basePath,e,{optionalPathTemplateRegExp:this._optionalPathTemplateRegExp,pathTemplateCallback:this._pathTemplateCallback,pathTemplateData:s,pathTemplateRegExp:this._pathTemplateRegExp,queryParams:{...this._queryParams,...a}}),o=t.Md5.hashStr(h),c=await this._cacheEntryHas(o);if(c){if((e=>!e.metadata.cacheControl.noCache&&e.checkTTL())(c)){const e={...r,"cache-control":c.printCacheControl()};return this._log?.(k,{context:{fetchMethod:S,fetchResponseHeaders:e,fetchUrl:h,logEntryName:"FETCH_RESPONSE_FROM_CACHE",...i}}),{data:await this._cacheEntryGet(o),headers:new Headers(e)}}this._conditionalRequestsEnabled&&c.metadata.etag&&(r[N]=c.metadata.etag)}const n=this._trackRequest(o);return n||this._getResolve(o,await this._fetch(h,{headers:{...this._headers,...r},method:S},i))}async _getResolve(e,t){const{data:r,headers:s,status:a}=t;if(404===a){this._cacheEntryDelete(e);let{errors:r}=t;r??=[],r.push(new Error(y)),t.errors=r}else if(304===a){const r=await this._cacheEntryGet(e);r&&(this._cacheEntrySet(e,r,{cacheControl:s.get(v)??void 0,etag:s.get(w)??void 0}),t.data=r)}else r&&this._cacheEntrySet(e,r,{cacheControl:s.get(v)??void 0,etag:s.get(w)??void 0});return this._resolvePendingRequests(e,t),this._requestTracker.active=this._requestTracker.active.filter((t=>t!==e)),t}_logResponse(e,t,r,s){const{headers:a,status:i}=e,{method:h,redirects:o,retries:c}=r,{startTime:n,..._}=s,E=this._performance.now(),p=n?E-n:0;this._log?.(I,{context:{fetchMethod:h,fetchRedirects:o,fetchResponseHeaders:Object.fromEntries(a.entries()),fetchResponseStatus:i,fetchRetries:c,fetchUrl:t,logEntryName:"FETCH_RESPONSE_RECEIVED",..._},stats:{duration:p,endTime:E,startTime:n}})}async _releaseRateLimitedRequestQueue(){for(const[e,t,r,s]of this._rateLimitedRequestQueue)e(await this._fetch(t,r,s));this._rateLimitedRequestQueue=[]}async _request(e,{body:t,headers:r,method:s,pathTemplateData:a,queryParams:i,...h},o){const c=G(this._basePath,e,{optionalPathTemplateRegExp:this._optionalPathTemplateRegExp,pathTemplateCallback:this._pathTemplateCallback,pathTemplateData:a,pathTemplateRegExp:this._pathTemplateRegExp,queryParams:{...this._queryParams,...i}});return this._fetch(c,{body:t,headers:{...this._headers,...r},method:s,...h},o)}_resolvePendingRequests(e,t){const r=this._requestTracker.pending.get(e);if(r){for(const{resolve:e}of r)e(t);this._requestTracker.pending.delete(e)}}_setPendingRequest(e,t){let r=this._requestTracker.pending.get(e);r??=[],r.push(t),this._requestTracker.pending.set(e,r)}_startRateLimit(){this._rateLimitTimer??=setTimeout((()=>{this._rateLimitTimer=void 0,this._rateLimitCount=0,this._rateLimitedRequestQueue.length>0&&this._releaseRateLimitedRequestQueue()}),1e3),this._rateLimitCount+=1}_trackRequest(e){if(this._requestTracker.active.includes(e))return new Promise((t=>{this._setPendingRequest(e,{resolve:t})}));this._requestTracker.active.push(e)}}exports.ARRAY_BUFFER_FORMAT=s,exports.BLOB_FORMAT=a,exports.CACHE_CONTROL_HEADER=v,exports.CLIENT_ERROR_REPSONSE=M,exports.COOKIE_HEADER="Cookie",exports.DEFAULT_BODY_PARSER=n,exports.DEFAULT_FETCH_TIMEOUT=_,exports.DEFAULT_HEADERS=E,exports.DEFAULT_MAX_REDIRECTS=p,exports.DEFAULT_MAX_RETRIES=u,exports.DEFAULT_PATH_TEMPLATE_REGEX=R,exports.DEFAULT_RATE_LIMIT=T,exports.DEFAULT_REQUEST_RETRY_WAIT=m,exports.DELETE_METHOD=q,exports.ETAG_HEADER=w,exports.FETCH_METHODS=C,exports.FETCH_TIMEOUT_ERROR=O,exports.FORM_DATA_FORMAT=i,exports.GET_METHOD=S,exports.Getta=B,exports.IF_NONE_MATCH_HEADER=N,exports.INFORMATION_REPSONSE=D,exports.INVALID_FETCH_METHOD_ERROR=g,exports.JSON_FORMAT=h,exports.LOCATION_HEADER=H,exports.MAX_REDIRECTS_EXCEEDED_ERROR=x,exports.MAX_RETRIES_EXCEEDED_ERROR=f,exports.MISSING_BASE_PATH_ERROR=l,exports.NOT_FOUND_STATUS_CODE=404,exports.NOT_MODIFIED_STATUS_CODE=304,exports.OPTIONAL_PATH_TEMPLATE_REGEX=d,exports.POST_METHOD=A,exports.PUT_METHOD=P,exports.REDIRECTION_REPSONSE=F,exports.REQUEST_FAILED=$,exports.REQUEST_SENT=U,exports.RESOURCE_NOT_FOUND_ERROR=y,exports.RESPONSE_FROM_CACHE=k,exports.RESPONSE_RECEIVED=I,exports.SERVER_ERROR_REPSONSE=b,exports.STREAM_READERS=c,exports.SUCCESSFUL_REPSONSE=L,exports.TEXT_FORMAT=o,exports.createRestClient=(e,t)=>{const r=new B(e);if(!t)return r;for(const e of Object.keys(t)){const s=t[e];s&&r.createShortcut(e,...s)}return r},exports.defaultPathTemplateCallback=Q;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/cjs/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../getta/src//constants.ts","../getta/src//helpers/defaultPathTemplateCallback/index.ts","../getta/src//helpers/buildEndpoint/index.ts","../getta/src//main.ts","../getta/src//helpers/getResponseGroup/index.ts","../getta/src//helpers/delay/index.ts","../getta/src//helpers/isCacheabilityValid/index.ts"],"sourcesContent":["import { type PlainObject } from './types.ts';\n\nexport const ARRAY_BUFFER_FORMAT = 'arrayBuffer';\nexport const BLOB_FORMAT = 'blob';\nexport const FORM_DATA_FORMAT = 'formData';\nexport const JSON_FORMAT = 'json';\nexport const TEXT_FORMAT = 'text';\n\nexport const STREAM_READERS = {\n ARRAY_BUFFER_FORMAT,\n BLOB_FORMAT,\n FORM_DATA_FORMAT,\n JSON_FORMAT,\n TEXT_FORMAT,\n};\n\nexport const DEFAULT_BODY_PARSER = (body: PlainObject) => body;\nexport const DEFAULT_FETCH_TIMEOUT = 5000;\nexport const DEFAULT_HEADERS = { 'content-type': 'application/json' };\nexport const DEFAULT_MAX_REDIRECTS = 5;\nexport const DEFAULT_MAX_RETRIES = 3;\nexport const DEFAULT_PATH_TEMPLATE_REGEX = /({type})|({id})|({id,\\+})|({brief\\|standard})/g;\nexport const OPTIONAL_PATH_TEMPLATE_REGEX = /({\\w+\\?})/g;\nexport const DEFAULT_RATE_LIMIT = 50;\nexport const DEFAULT_REQUEST_RETRY_WAIT = 100;\n\nexport const MISSING_BASE_PATH_ERROR = `Getta expected to receive 'basePath' in the constructor options,\n but recevied undefined.`;\n\nexport const MAX_REDIRECTS_EXCEEDED_ERROR = 'The request exceeded the maximum number of redirects, which is';\n\nexport const MAX_RETRIES_EXCEEDED_ERROR = 'The request exceeded the maximum number of retries, which is';\n\nexport const INVALID_FETCH_METHOD_ERROR = \"Getta expected to receive 'get', 'post', 'put' or 'delete', but received\";\n\nexport const RESOURCE_NOT_FOUND_ERROR = 'The requested resource could not been found.';\n\nexport const FETCH_TIMEOUT_ERROR = 'The request timed out. Getta did not get a response within';\n\nexport const GET_METHOD = 'get';\nexport const POST_METHOD = 'post';\nexport const PUT_METHOD = 'put';\nexport const DELETE_METHOD = 'delete';\n\nexport const FETCH_METHODS = [GET_METHOD, POST_METHOD, PUT_METHOD, DELETE_METHOD];\n\nexport const INFORMATION_REPSONSE = 'information';\nexport const SUCCESSFUL_REPSONSE = 'successful';\nexport const REDIRECTION_REPSONSE = 'redirection';\nexport const CLIENT_ERROR_REPSONSE = 'clientError';\nexport const SERVER_ERROR_REPSONSE = 'serverError';\n\nexport const NOT_MODIFIED_STATUS_CODE = 304;\nexport const NOT_FOUND_STATUS_CODE = 404;\n\nexport const COOKIE_HEADER = 'Cookie';\nexport const ETAG_HEADER = 'ETag';\nexport const LOCATION_HEADER = 'Location';\nexport const IF_NONE_MATCH_HEADER = 'If-None-Match';\nexport const CACHE_CONTROL_HEADER = 'Cache-Control';\n\nexport const REQUEST_SENT = 'request_sent';\nexport const RESPONSE_RECEIVED = 'response_received';\nexport const RESPONSE_FROM_CACHE = 'response_from_cache';\nexport const REQUEST_FAILED = 'request_failed';\n","export const defaultPathTemplateCallback = (\n pathTemplate: string,\n data: Record<string, string | number | boolean>,\n pathTemplateRegExp: RegExp,\n) => {\n const dataKeys = Object.keys(data);\n\n return pathTemplate.replace(pathTemplateRegExp, match => {\n for (const key of dataKeys) {\n if (match.includes(key) && data[key] !== undefined) {\n return String(data[key]);\n }\n }\n\n return '';\n });\n};\n","import queryString from 'query-string';\nimport { type BuildEndpointOptions } from './types.ts';\n\nexport const buildEndpoint = (\n basePath: string,\n path: string,\n {\n optionalPathTemplateRegExp,\n pathTemplateCallback,\n pathTemplateData,\n pathTemplateRegExp,\n queryParams,\n }: BuildEndpointOptions,\n) => {\n const pathJoiner = basePath.endsWith('/') || path.startsWith('/') ? '' : '/';\n let endpoint = `${basePath}${pathJoiner}${path}`;\n\n if (pathTemplateData) {\n endpoint = pathTemplateCallback(endpoint, pathTemplateData, pathTemplateRegExp);\n }\n\n endpoint = endpoint.replace(optionalPathTemplateRegExp, '');\n\n if (endpoint.endsWith('/')) {\n endpoint = endpoint.slice(0, Math.max(0, endpoint.length - 1));\n }\n\n if (queryParams && Object.keys(queryParams).length > 0) {\n const queryJoin = queryString.extract(endpoint) ? '&' : '?';\n endpoint = `${endpoint}${queryJoin}${queryString.stringify(queryParams)}`;\n }\n\n return endpoint;\n};\n","import { type CacheHeaders, type Core } from '@cachemap/core';\nimport { type Cacheability } from 'cacheability';\nimport { castArray, merge } from 'lodash-es';\nimport { Md5 } from 'ts-md5';\nimport { type SetRequired } from 'type-fest';\nimport * as consts from './constants.ts';\nimport { buildEndpoint } from './helpers/buildEndpoint/index.ts';\nimport { defaultPathTemplateCallback } from './helpers/defaultPathTemplateCallback/index.ts';\nimport { delay } from './helpers/delay/index.ts';\nimport { getResponseGroup } from './helpers/getResponseGroup/index.ts';\nimport { isCacheabilityValid } from './helpers/isCacheabilityValid/index.ts';\nimport {\n type ConstructorOptions,\n type Context,\n type FetchOptions,\n type FetchRedirectHandlerOptions,\n type FetchResponse,\n type Func,\n type Log,\n type PathTemplateCallback,\n type PendingRequestResolver,\n type PendingRequestResolvers,\n type Performance,\n type PlainObject,\n type RequestOptions,\n type RequestQueue,\n type RequestTracker,\n type ShortcutProperties,\n type Shortcuts,\n type StreamReader,\n} from './types.ts';\n\nexport class Getta {\n private _basePath: string;\n private _bodyParser: Func;\n private _cache?: Core;\n private _conditionalRequestsEnabled: boolean;\n private _fetchTimeout: number;\n private _headers: Record<string, string>;\n private _log: Log | undefined;\n private _maxRedirects: number;\n private _maxRetries: number;\n private _optionalPathTemplateRegExp: RegExp;\n private _pathTemplateCallback: PathTemplateCallback;\n private _pathTemplateRegExp: RegExp;\n private _performance: Performance;\n private _queryParams: PlainObject;\n private _rateLimit: boolean;\n private _rateLimitCount = 0;\n private _rateLimitedRequestQueue: RequestQueue = [];\n private _rateLimitPerSecond: number;\n private _rateLimitTimer: NodeJS.Timer | undefined = undefined;\n private _requestRetryWait: number;\n private _requestTracker: RequestTracker = { active: [], pending: new Map() };\n private _streamReader: StreamReader;\n\n constructor(options: ConstructorOptions) {\n const {\n basePath,\n bodyParser = consts.DEFAULT_BODY_PARSER,\n cache,\n enableConditionalRequests = true,\n fetchTimeout = consts.DEFAULT_FETCH_TIMEOUT,\n headers,\n log,\n maxRedirects = consts.DEFAULT_MAX_REDIRECTS,\n maxRetries = consts.DEFAULT_MAX_RETRIES,\n optionalPathTemplateRegExp = consts.OPTIONAL_PATH_TEMPLATE_REGEX,\n pathTemplateCallback = defaultPathTemplateCallback,\n pathTemplateRegExp = consts.DEFAULT_PATH_TEMPLATE_REGEX,\n performance,\n queryParams = {},\n rateLimit = false,\n rateLimitPerSecond = consts.DEFAULT_RATE_LIMIT,\n requestRetryWait = consts.DEFAULT_REQUEST_RETRY_WAIT,\n streamReader = consts.JSON_FORMAT,\n } = options;\n\n if (!basePath) {\n throw new Error(consts.MISSING_BASE_PATH_ERROR);\n }\n\n this._basePath = basePath;\n this._bodyParser = bodyParser;\n this._cache = cache;\n this._conditionalRequestsEnabled = enableConditionalRequests;\n this._fetchTimeout = fetchTimeout;\n this._headers = { ...consts.DEFAULT_HEADERS, ...headers };\n this._log = log;\n this._maxRedirects = maxRedirects;\n this._maxRetries = maxRetries;\n this._optionalPathTemplateRegExp = optionalPathTemplateRegExp;\n this._pathTemplateCallback = pathTemplateCallback;\n this._pathTemplateRegExp = pathTemplateRegExp;\n this._performance = performance;\n this._queryParams = queryParams;\n this._rateLimit = rateLimit;\n this._rateLimitPerSecond = rateLimitPerSecond;\n this._requestRetryWait = requestRetryWait;\n this._streamReader = streamReader;\n }\n\n get cache(): Core | undefined {\n return this._cache;\n }\n\n public createShortcut(\n name: string,\n path: string,\n { method, ...otherOptions }: SetRequired<RequestOptions, 'method'>,\n ) {\n if (!consts.FETCH_METHODS.includes(method)) {\n throw new Error(`${consts.INVALID_FETCH_METHOD_ERROR} ${method}`);\n }\n\n // @ts-expect-error No index signature with a parameter of type 'string'\n this[name] = async <Resource extends PlainObject>(\n { method: requestMethod, ...otherOptionOverrides }: RequestOptions = {},\n context?: Context,\n ) =>\n // @ts-expect-error Type 'undefined' is not assignable to type 'BodyInit'\n // To generic and complex to type without casting.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n this[requestMethod ?? method](path, merge({}, otherOptions, otherOptionOverrides), context) as Promise<\n FetchResponse<Resource>\n >;\n }\n\n public async delete(path: string, options: Omit<RequestOptions, 'method'> = {}, context?: Context) {\n return this._delete(path, options, context);\n }\n\n public async get(path: string, options: Omit<RequestOptions, 'method'> = {}, context?: Context) {\n return this._get(path, options, context);\n }\n\n public async post(path: string, options: Omit<SetRequired<RequestOptions, 'body'>, 'method'>, context?: Context) {\n return this._request(path, { ...options, method: consts.POST_METHOD }, context);\n }\n\n public async put(path: string, options: Omit<SetRequired<RequestOptions, 'body'>, 'methood'>, context?: Context) {\n return this._request(path, { ...options, method: consts.PUT_METHOD }, context);\n }\n\n private _addRequestToRateLimitedQueue(endpoint: string, options: FetchOptions, context: Context) {\n return new Promise((resolve: (value: FetchResponse) => void) => {\n this._rateLimitedRequestQueue.push([resolve, endpoint, options, context]);\n });\n }\n\n private async _cacheEntryDelete(requestHash: string): Promise<boolean> {\n if (!this._cache) {\n return false;\n }\n\n return this._cache.delete(requestHash);\n }\n\n private async _cacheEntryGet(requestHash: string): Promise<PlainObject | undefined> {\n if (!this._cache) {\n return undefined;\n }\n\n return this._cache.get(requestHash);\n }\n\n private async _cacheEntryHas(requestHash: string): Promise<Cacheability | false> {\n if (!this._cache) {\n return false;\n }\n\n try {\n return await this._cache.has(requestHash);\n } catch {\n return false;\n }\n }\n\n private async _cacheEntrySet(requestHash: string, data: PlainObject, cacheHeaders: CacheHeaders): Promise<void> {\n if (!this._cache) {\n return undefined;\n }\n\n return this._cache.set(requestHash, data, { cacheHeaders });\n }\n\n private async _delete(\n path: string,\n { headers = {}, pathTemplateData, queryParams = {}, ...rest }: Omit<RequestOptions, 'method'>,\n context?: Context,\n ) {\n const endpoint = buildEndpoint(this._basePath, path, {\n optionalPathTemplateRegExp: this._optionalPathTemplateRegExp,\n pathTemplateCallback: this._pathTemplateCallback,\n pathTemplateData,\n pathTemplateRegExp: this._pathTemplateRegExp,\n queryParams: { ...this._queryParams, ...queryParams },\n });\n\n const requestHash = Md5.hashStr(endpoint);\n const cacheability = await this._cacheEntryHas(requestHash);\n\n if (cacheability) {\n void this._cacheEntryDelete(requestHash);\n }\n\n return this._fetch(\n endpoint,\n {\n headers: { ...this._headers, ...headers },\n method: consts.DELETE_METHOD,\n ...rest,\n },\n context,\n );\n }\n\n private async _fetch(endpoint: string, options: FetchOptions, context: Context = {}): Promise<FetchResponse> {\n context.startTime = this._performance.now();\n\n try {\n const { redirects, retries, ...rest } = options;\n\n return await new Promise<FetchResponse>((resolve, reject) => {\n void (async () => {\n const fetchTimer = setTimeout(() => {\n reject(new Error(`${consts.FETCH_TIMEOUT_ERROR} ${String(this._fetchTimeout)}ms.`));\n }, this._fetchTimeout);\n\n if (this._rateLimit) {\n this._startRateLimit();\n\n if (!(this._rateLimitCount < this._rateLimitPerSecond)) {\n clearTimeout(fetchTimer);\n resolve(await this._addRequestToRateLimitedQueue(endpoint, options, context));\n return;\n }\n }\n\n if (!redirects && !retries) {\n this._log?.(consts.REQUEST_SENT, {\n context: {\n fetchMethod: rest.method,\n fetchRedirets: redirects,\n fetchRequestHeaders: rest.headers,\n fetchRetries: retries,\n fetchUrl: endpoint,\n logEntryName: 'FETCH_REQUEST_SENT',\n ...context,\n },\n stats: { startTime: context.startTime },\n });\n }\n\n // Casting as fetch response does not support generics.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const res = (await fetch(endpoint, rest)) as FetchResponse;\n\n clearTimeout(fetchTimer);\n\n const { body, headers, status } = res;\n const responseGroup = getResponseGroup(status);\n\n if (responseGroup === consts.REDIRECTION_REPSONSE && headers.has(consts.LOCATION_HEADER)) {\n resolve(\n await this._fetchRedirectHandler(\n res,\n // Has check above means this cannot be undefined.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n headers.get(consts.LOCATION_HEADER)!,\n {\n redirects,\n status,\n ...rest,\n },\n context,\n ),\n );\n\n return;\n }\n\n if (responseGroup === consts.SERVER_ERROR_REPSONSE) {\n resolve(\n await this._fetchRetryHandler(\n res,\n endpoint,\n {\n retries,\n ...rest,\n },\n context,\n ),\n );\n\n return;\n }\n\n try {\n Object.defineProperty(res, 'data', {\n enumerable: true,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n value: body ? this._bodyParser(await res[this._streamReader]()) : undefined,\n writable: true,\n });\n\n this._logResponse(res, endpoint, options, context);\n resolve(res);\n } catch (error) {\n if (error instanceof Error) {\n reject(error);\n } else {\n reject(new Error(`Unable to ${rest.method} ${endpoint} due to previous error`));\n }\n }\n })();\n });\n } catch (error) {\n const { startTime, ...rest } = context;\n const endTime = this._performance.now();\n\n this._log?.(consts.REQUEST_FAILED, {\n context: { error, fetchUrl: endpoint, logEntryName: 'FETCH_REQUEST_FAILED', ...rest },\n stats: { duration: startTime ? endTime - startTime : 0, endTime, startTime },\n });\n\n // Based on above code, error is going to be a type of Error.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return { errors: castArray(error) } as FetchResponse;\n }\n }\n\n private async _fetchRedirectHandler(\n res: FetchResponse,\n endpoint: string,\n options: FetchRedirectHandlerOptions,\n context: Context,\n ): Promise<FetchResponse> {\n const { method, redirects = 1, status, ...rest } = options;\n\n if (redirects === this._maxRedirects) {\n res.errors = [new Error(`${consts.MAX_REDIRECTS_EXCEEDED_ERROR} ${String(this._maxRedirects)}.`)];\n this._logResponse(res, endpoint, options, context);\n return res;\n }\n\n const redirectMethod = status === 303 ? consts.GET_METHOD : method;\n return this._fetch(endpoint, { method: redirectMethod, redirects: redirects + 1, ...rest });\n }\n\n private async _fetchRetryHandler(res: FetchResponse, endpoint: string, options: FetchOptions, context: Context) {\n const { retries = 1, ...rest } = options;\n\n if (retries === this._maxRetries) {\n res.errors = [new Error(`${consts.MAX_RETRIES_EXCEEDED_ERROR} ${String(this._maxRetries)}.`)];\n this._logResponse(res, endpoint, options, context);\n return res;\n }\n\n await delay(this._requestRetryWait);\n return this._fetch(endpoint, { retries: retries + 1, ...rest });\n }\n\n private async _get(\n path: string,\n { headers = {}, pathTemplateData, queryParams = {} }: Omit<RequestOptions, 'method'>,\n context?: Context,\n ) {\n const endpoint = buildEndpoint(this._basePath, path, {\n optionalPathTemplateRegExp: this._optionalPathTemplateRegExp,\n pathTemplateCallback: this._pathTemplateCallback,\n pathTemplateData,\n pathTemplateRegExp: this._pathTemplateRegExp,\n queryParams: { ...this._queryParams, ...queryParams },\n });\n\n const requestHash = Md5.hashStr(endpoint);\n const cacheability = await this._cacheEntryHas(requestHash);\n\n if (cacheability) {\n if (isCacheabilityValid(cacheability)) {\n const newHeaders = {\n ...headers,\n 'cache-control': cacheability.printCacheControl(),\n };\n\n this._log?.(consts.RESPONSE_FROM_CACHE, {\n context: {\n fetchMethod: consts.GET_METHOD,\n fetchResponseHeaders: newHeaders,\n fetchUrl: endpoint,\n logEntryName: 'FETCH_RESPONSE_FROM_CACHE',\n ...context,\n },\n });\n\n return {\n data: await this._cacheEntryGet(requestHash),\n headers: new Headers(newHeaders),\n };\n }\n\n if (this._conditionalRequestsEnabled && cacheability.metadata.etag) {\n headers[consts.IF_NONE_MATCH_HEADER] = cacheability.metadata.etag;\n }\n }\n\n const pendingRequest = this._trackRequest(requestHash);\n\n if (pendingRequest) {\n return pendingRequest;\n }\n\n return this._getResolve(\n requestHash,\n await this._fetch(endpoint, { headers: { ...this._headers, ...headers }, method: consts.GET_METHOD }, context),\n );\n }\n\n private async _getResolve(requestHash: string, res: FetchResponse) {\n const { data, headers, status } = res;\n\n if (status === consts.NOT_FOUND_STATUS_CODE) {\n void this._cacheEntryDelete(requestHash);\n let { errors } = res;\n\n if (!errors) {\n errors = [];\n }\n\n errors.push(new Error(consts.RESOURCE_NOT_FOUND_ERROR));\n res.errors = errors;\n } else if (status === consts.NOT_MODIFIED_STATUS_CODE) {\n const cachedData = await this._cacheEntryGet(requestHash);\n\n if (cachedData) {\n void this._cacheEntrySet(requestHash, cachedData, {\n cacheControl: headers.get(consts.CACHE_CONTROL_HEADER) ?? undefined,\n etag: headers.get(consts.ETAG_HEADER) ?? undefined,\n });\n\n res.data = cachedData;\n }\n } else if (data) {\n void this._cacheEntrySet(requestHash, data, {\n cacheControl: headers.get(consts.CACHE_CONTROL_HEADER) ?? undefined,\n etag: headers.get(consts.ETAG_HEADER) ?? undefined,\n });\n }\n\n this._resolvePendingRequests(requestHash, res);\n this._requestTracker.active = this._requestTracker.active.filter(value => value !== requestHash);\n return res;\n }\n\n private _logResponse(res: FetchResponse, endpoint: string, options: FetchOptions, context: Context) {\n const { headers, status } = res;\n const { method, redirects, retries } = options;\n const { startTime, ...otherContext } = context;\n const endTime = this._performance.now();\n const duration = startTime ? endTime - startTime : 0;\n\n this._log?.(consts.RESPONSE_RECEIVED, {\n context: {\n fetchMethod: method,\n fetchRedirects: redirects,\n fetchResponseHeaders: Object.fromEntries(headers.entries()),\n fetchResponseStatus: status,\n fetchRetries: retries,\n fetchUrl: endpoint,\n logEntryName: 'FETCH_RESPONSE_RECEIVED',\n ...otherContext,\n },\n stats: { duration, endTime, startTime },\n });\n }\n\n private async _releaseRateLimitedRequestQueue() {\n for (const [resolve, endpoint, options, context] of this._rateLimitedRequestQueue) {\n resolve(await this._fetch(endpoint, options, context));\n }\n\n this._rateLimitedRequestQueue = [];\n }\n\n private async _request(\n path: string,\n { body, headers, method, pathTemplateData, queryParams, ...rest }: SetRequired<RequestOptions, 'method'>,\n context?: Context,\n ) {\n const endpoint = buildEndpoint(this._basePath, path, {\n optionalPathTemplateRegExp: this._optionalPathTemplateRegExp,\n pathTemplateCallback: this._pathTemplateCallback,\n pathTemplateData,\n pathTemplateRegExp: this._pathTemplateRegExp,\n queryParams: { ...this._queryParams, ...queryParams },\n });\n\n return this._fetch(\n endpoint,\n {\n body,\n headers: { ...this._headers, ...headers },\n method,\n ...rest,\n },\n context,\n );\n }\n\n private _resolvePendingRequests(requestHash: string, responseData: FetchResponse) {\n const pendingRequests = this._requestTracker.pending.get(requestHash);\n\n if (!pendingRequests) {\n return;\n }\n\n for (const { resolve } of pendingRequests) {\n resolve(responseData);\n }\n\n this._requestTracker.pending.delete(requestHash);\n }\n\n private _setPendingRequest(requestHash: string, resolver: PendingRequestResolvers) {\n let pending = this._requestTracker.pending.get(requestHash);\n if (!pending) pending = [];\n pending.push(resolver);\n this._requestTracker.pending.set(requestHash, pending);\n }\n\n private _startRateLimit() {\n if (!this._rateLimitTimer) {\n this._rateLimitTimer = setTimeout(() => {\n this._rateLimitTimer = undefined;\n this._rateLimitCount = 0;\n\n if (this._rateLimitedRequestQueue.length > 0) {\n void this._releaseRateLimitedRequestQueue();\n }\n }, 1000);\n }\n\n this._rateLimitCount += 1;\n }\n\n private _trackRequest(requestHash: string): Promise<FetchResponse> | undefined {\n if (this._requestTracker.active.includes(requestHash)) {\n return new Promise((resolve: PendingRequestResolver) => {\n this._setPendingRequest(requestHash, { resolve });\n });\n }\n\n this._requestTracker.active.push(requestHash);\n return;\n }\n}\n\nexport const createRestClient = <N extends string>(options: ConstructorOptions, shortcuts?: Shortcuts) => {\n // Typing proving too complex without casting.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const getta = new Getta(options) as Getta & ShortcutProperties<N>;\n\n if (!shortcuts) {\n return getta;\n }\n\n for (const key of Object.keys(shortcuts)) {\n const shortcut = shortcuts[key];\n\n if (shortcut) {\n getta.createShortcut(key, ...shortcut);\n }\n }\n\n return getta;\n};\n","import * as consts from '../../constants.ts';\n\nexport const getResponseGroup = (status: number) => {\n switch (true) {\n case status < 200: {\n return consts.INFORMATION_REPSONSE;\n }\n\n case status < 300: {\n return consts.SUCCESSFUL_REPSONSE;\n }\n\n case status < 400: {\n return consts.REDIRECTION_REPSONSE;\n }\n\n case status < 500: {\n return consts.CLIENT_ERROR_REPSONSE;\n }\n\n default: {\n return consts.SERVER_ERROR_REPSONSE;\n }\n }\n};\n","export const delay = (ms: number) => {\n return new Promise(resolve => setTimeout(resolve, ms));\n};\n","import { type Cacheability } from 'cacheability';\n\nexport const isCacheabilityValid = (cacheability: Cacheability) => {\n const noCache = cacheability.metadata.cacheControl.noCache ?? false;\n return !noCache && cacheability.checkTTL();\n};\n"],"names":["ARRAY_BUFFER_FORMAT","BLOB_FORMAT","FORM_DATA_FORMAT","JSON_FORMAT","TEXT_FORMAT","STREAM_READERS","DEFAULT_BODY_PARSER","body","DEFAULT_FETCH_TIMEOUT","DEFAULT_HEADERS","DEFAULT_MAX_REDIRECTS","DEFAULT_MAX_RETRIES","DEFAULT_PATH_TEMPLATE_REGEX","OPTIONAL_PATH_TEMPLATE_REGEX","DEFAULT_RATE_LIMIT","DEFAULT_REQUEST_RETRY_WAIT","MISSING_BASE_PATH_ERROR","MAX_REDIRECTS_EXCEEDED_ERROR","MAX_RETRIES_EXCEEDED_ERROR","INVALID_FETCH_METHOD_ERROR","RESOURCE_NOT_FOUND_ERROR","FETCH_TIMEOUT_ERROR","GET_METHOD","POST_METHOD","PUT_METHOD","DELETE_METHOD","FETCH_METHODS","INFORMATION_REPSONSE","SUCCESSFUL_REPSONSE","REDIRECTION_REPSONSE","CLIENT_ERROR_REPSONSE","SERVER_ERROR_REPSONSE","ETAG_HEADER","LOCATION_HEADER","IF_NONE_MATCH_HEADER","CACHE_CONTROL_HEADER","REQUEST_SENT","RESPONSE_RECEIVED","RESPONSE_FROM_CACHE","REQUEST_FAILED","defaultPathTemplateCallback","pathTemplate","data","pathTemplateRegExp","dataKeys","Object","keys","replace","match","key","includes","undefined","String","buildEndpoint","basePath","path","optionalPathTemplateRegExp","pathTemplateCallback","pathTemplateData","queryParams","pathJoiner","endsWith","startsWith","endpoint","slice","Math","max","length","queryString","extract","stringify","Getta","constructor","options","_rateLimitCount","_rateLimitedRequestQueue","_rateLimitTimer","_requestTracker","active","pending","Map","bodyParser","consts","cache","enableConditionalRequests","fetchTimeout","headers","log","maxRedirects","maxRetries","performance","rateLimit","rateLimitPerSecond","requestRetryWait","streamReader","Error","this","_basePath","_bodyParser","_cache","_conditionalRequestsEnabled","_fetchTimeout","_headers","_log","_maxRedirects","_maxRetries","_optionalPathTemplateRegExp","_pathTemplateCallback","_pathTemplateRegExp","_performance","_queryParams","_rateLimit","_rateLimitPerSecond","_requestRetryWait","_streamReader","createShortcut","name","method","otherOptions","async","requestMethod","otherOptionOverrides","context","merge","delete","_delete","get","_get","post","_request","put","_addRequestToRateLimitedQueue","Promise","resolve","push","_cacheEntryDelete","requestHash","_cacheEntryGet","_cacheEntryHas","has","_cacheEntrySet","cacheHeaders","set","rest","Md5","hashStr","_fetch","startTime","now","redirects","retries","reject","fetchTimer","setTimeout","_startRateLimit","clearTimeout","fetchMethod","fetchRedirets","fetchRequestHeaders","fetchRetries","fetchUrl","logEntryName","stats","res","fetch","status","responseGroup","getResponseGroup","_fetchRedirectHandler","defineProperty","enumerable","value","writable","_logResponse","error","_fetchRetryHandler","endTime","duration","errors","castArray","redirectMethod","ms","cacheability","metadata","cacheControl","noCache","checkTTL","isCacheabilityValid","newHeaders","printCacheControl","fetchResponseHeaders","Headers","etag","pendingRequest","_trackRequest","_getResolve","cachedData","_resolvePendingRequests","filter","otherContext","fetchRedirects","fromEntries","entries","fetchResponseStatus","_releaseRateLimitedRequestQueue","responseData","pendingRequests","_setPendingRequest","resolver","shortcuts","getta","shortcut"],"mappings":"kIAEO,MAAMA,EAAsB,cACtBC,EAAc,OACdC,EAAmB,WACnBC,EAAc,OACdC,EAAc,OAEdC,EAAiB,CAC5BL,sBACAC,cACAC,mBACAC,cACAC,eAGWE,EAAuBC,GAAsBA,EAC7CC,EAAwB,IACxBC,EAAkB,CAAE,eAAgB,oBACpCC,EAAwB,EACxBC,EAAsB,EACtBC,EAA8B,iDAC9BC,EAA+B,aAC/BC,EAAqB,GACrBC,EAA6B,IAE7BC,EAA0B,8FAG1BC,EAA+B,iEAE/BC,EAA6B,+DAE7BC,EAA6B,2EAE7BC,EAA2B,+CAE3BC,EAAsB,6DAEtBC,EAAa,MACbC,EAAc,OACdC,EAAa,MACbC,EAAgB,SAEhBC,EAAgB,CAACJ,EAAYC,EAAaC,EAAYC,GAEtDE,EAAuB,cACvBC,EAAsB,aACtBC,EAAuB,cACvBC,EAAwB,cACxBC,EAAwB,cAMxBC,EAAc,OACdC,EAAkB,WAClBC,EAAuB,gBACvBC,EAAuB,gBAEvBC,EAAe,eACfC,EAAoB,oBACpBC,EAAsB,sBACtBC,EAAiB,iBChEjBC,EAA8B,CACzCC,EACAC,EACAC,KAEA,MAAMC,EAAWC,OAAOC,KAAKJ,GAE7B,OAAOD,EAAaM,QA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AAOwD,KAAKE,EAEnC,2IHpf2B,0sBAFQ,qCADG,wYG0fR,CAAmB/D,EAA6BwI,KAG9E,MAAMC,EAAQ,IAAI3I,EAAME,GAExB,IAAKwI,EACH,OAAOC,EAGT,IAAK,MAAMjK,KAAOJ,OAAOC,KAAKmK,GAAY,CACxC,MAAME,EAAWF,EAAUhK,GAEvBkK,GACFD,EAAM/F,eAAelE,KAAQkK,EAEjC,CAEA,OAAOD,CAAAA"}
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../getta/src//constants.ts","../getta/src//helpers/defaultPathTemplateCallback/index.ts","../getta/src//helpers/buildEndpoint/index.ts","../getta/src//main.ts","../getta/src//helpers/getResponseGroup/index.ts","../getta/src//helpers/delay/index.ts","../getta/src//helpers/isCacheabilityValid/index.ts"],"sourcesContent":["import { type PlainObject } from './types.ts';\n\nexport const ARRAY_BUFFER_FORMAT = 'arrayBuffer';\nexport const BLOB_FORMAT = 'blob';\nexport const FORM_DATA_FORMAT = 'formData';\nexport const JSON_FORMAT = 'json';\nexport const TEXT_FORMAT = 'text';\n\nexport const STREAM_READERS = {\n ARRAY_BUFFER_FORMAT,\n BLOB_FORMAT,\n FORM_DATA_FORMAT,\n JSON_FORMAT,\n TEXT_FORMAT,\n};\n\nexport const DEFAULT_BODY_PARSER = (body: PlainObject) => body;\nexport const DEFAULT_FETCH_TIMEOUT = 5000;\nexport const DEFAULT_HEADERS = { 'content-type': 'application/json' };\nexport const DEFAULT_MAX_REDIRECTS = 5;\nexport const DEFAULT_MAX_RETRIES = 3;\nexport const DEFAULT_PATH_TEMPLATE_REGEX = /({type})|({id})|({id,\\+})|({brief\\|standard})/g;\nexport const OPTIONAL_PATH_TEMPLATE_REGEX = /({\\w+\\?})/g;\nexport const DEFAULT_RATE_LIMIT = 50;\nexport const DEFAULT_REQUEST_RETRY_WAIT = 100;\n\nexport const MISSING_BASE_PATH_ERROR = `Getta expected to receive 'basePath' in the constructor options,\n but recevied undefined.`;\n\nexport const MAX_REDIRECTS_EXCEEDED_ERROR = 'The request exceeded the maximum number of redirects, which is';\n\nexport const MAX_RETRIES_EXCEEDED_ERROR = 'The request exceeded the maximum number of retries, which is';\n\nexport const INVALID_FETCH_METHOD_ERROR = \"Getta expected to receive 'get', 'post', 'put' or 'delete', but received\";\n\nexport const RESOURCE_NOT_FOUND_ERROR = 'The requested resource could not been found.';\n\nexport const FETCH_TIMEOUT_ERROR = 'The request timed out. Getta did not get a response within';\n\nexport const GET_METHOD = 'get';\nexport const POST_METHOD = 'post';\nexport const PUT_METHOD = 'put';\nexport const DELETE_METHOD = 'delete';\n\nexport const FETCH_METHODS = [GET_METHOD, POST_METHOD, PUT_METHOD, DELETE_METHOD];\n\nexport const INFORMATION_REPSONSE = 'information';\nexport const SUCCESSFUL_REPSONSE = 'successful';\nexport const REDIRECTION_REPSONSE = 'redirection';\nexport const CLIENT_ERROR_REPSONSE = 'clientError';\nexport const SERVER_ERROR_REPSONSE = 'serverError';\n\nexport const NOT_MODIFIED_STATUS_CODE = 304;\nexport const NOT_FOUND_STATUS_CODE = 404;\n\nexport const COOKIE_HEADER = 'Cookie';\nexport const ETAG_HEADER = 'ETag';\nexport const LOCATION_HEADER = 'Location';\nexport const IF_NONE_MATCH_HEADER = 'If-None-Match';\nexport const CACHE_CONTROL_HEADER = 'Cache-Control';\n\nexport const REQUEST_SENT = 'request_sent';\nexport const RESPONSE_RECEIVED = 'response_received';\nexport const RESPONSE_FROM_CACHE = 'response_from_cache';\nexport const REQUEST_FAILED = 'request_failed';\n","export const defaultPathTemplateCallback = (\n pathTemplate: string,\n data: Record<string, string | number | boolean>,\n pathTemplateRegExp: RegExp,\n) => {\n const dataKeys = Object.keys(data);\n\n return pathTemplate.replace(pathTemplateRegExp, match => {\n for (const key of dataKeys) {\n if (match.includes(key) && data[key] !== undefined) {\n return String(data[key]);\n }\n }\n\n return '';\n });\n};\n","import { omitBy } from 'lodash-es';\nimport queryString from 'query-string';\nimport { type PlainObject } from '#types.ts';\nimport { type BuildEndpointOptions } from './types.ts';\n\nexport const buildEndpoint = (\n basePath: string,\n path: string,\n {\n optionalPathTemplateRegExp,\n pathTemplateCallback,\n pathTemplateData,\n pathTemplateRegExp,\n queryParams = {},\n }: BuildEndpointOptions,\n) => {\n const pathJoiner = basePath.endsWith('/') || path.startsWith('/') ? '' : '/';\n let endpoint = `${basePath}${pathJoiner}${path}`;\n\n if (pathTemplateData) {\n endpoint = pathTemplateCallback(endpoint, pathTemplateData, pathTemplateRegExp);\n }\n\n endpoint = endpoint.replace(optionalPathTemplateRegExp, '');\n\n if (endpoint.endsWith('/')) {\n endpoint = endpoint.slice(0, Math.max(0, endpoint.length - 1));\n }\n\n const sanitisedSearchParams = omitBy<PlainObject>(queryParams, entry => !entry);\n\n if (Object.keys(sanitisedSearchParams).length > 0) {\n const queryJoin = queryString.extract(endpoint) ? '&' : '?';\n endpoint = `${endpoint}${queryJoin}${queryString.stringify(sanitisedSearchParams)}`;\n }\n\n return endpoint;\n};\n","import { type CacheHeaders, type Core } from '@cachemap/core';\nimport { type Cacheability } from 'cacheability';\nimport { castArray, merge } from 'lodash-es';\nimport { Md5 } from 'ts-md5';\nimport { type SetRequired } from 'type-fest';\nimport * as consts from './constants.ts';\nimport { buildEndpoint } from './helpers/buildEndpoint/index.ts';\nimport { defaultPathTemplateCallback } from './helpers/defaultPathTemplateCallback/index.ts';\nimport { delay } from './helpers/delay/index.ts';\nimport { getResponseGroup } from './helpers/getResponseGroup/index.ts';\nimport { isCacheabilityValid } from './helpers/isCacheabilityValid/index.ts';\nimport {\n type ConstructorOptions,\n type Context,\n type FetchOptions,\n type FetchRedirectHandlerOptions,\n type FetchResponse,\n type Func,\n type Log,\n type PathTemplateCallback,\n type PendingRequestResolver,\n type PendingRequestResolvers,\n type Performance,\n type PlainObject,\n type RequestOptions,\n type RequestQueue,\n type RequestTracker,\n type ShortcutProperties,\n type Shortcuts,\n type StreamReader,\n} from './types.ts';\n\nexport class Getta {\n private _basePath: string;\n private _bodyParser: Func;\n private _cache?: Core;\n private _conditionalRequestsEnabled: boolean;\n private _fetchTimeout: number;\n private _headers: Record<string, string>;\n private _log: Log | undefined;\n private _maxRedirects: number;\n private _maxRetries: number;\n private _optionalPathTemplateRegExp: RegExp;\n private _pathTemplateCallback: PathTemplateCallback;\n private _pathTemplateRegExp: RegExp;\n private _performance: Performance;\n private _queryParams: PlainObject;\n private _rateLimit: boolean;\n private _rateLimitCount = 0;\n private _rateLimitedRequestQueue: RequestQueue = [];\n private _rateLimitPerSecond: number;\n private _rateLimitTimer: NodeJS.Timeout | undefined = undefined;\n private _requestRetryWait: number;\n private _requestTracker: RequestTracker = { active: [], pending: new Map() };\n private _streamReader: StreamReader;\n\n constructor(options: ConstructorOptions) {\n const {\n basePath,\n bodyParser = consts.DEFAULT_BODY_PARSER,\n cache,\n enableConditionalRequests = true,\n fetchTimeout = consts.DEFAULT_FETCH_TIMEOUT,\n headers,\n log,\n maxRedirects = consts.DEFAULT_MAX_REDIRECTS,\n maxRetries = consts.DEFAULT_MAX_RETRIES,\n optionalPathTemplateRegExp = consts.OPTIONAL_PATH_TEMPLATE_REGEX,\n pathTemplateCallback = defaultPathTemplateCallback,\n pathTemplateRegExp = consts.DEFAULT_PATH_TEMPLATE_REGEX,\n performance,\n queryParams = {},\n rateLimit = false,\n rateLimitPerSecond = consts.DEFAULT_RATE_LIMIT,\n requestRetryWait = consts.DEFAULT_REQUEST_RETRY_WAIT,\n streamReader = consts.JSON_FORMAT,\n } = options;\n\n if (!basePath) {\n throw new Error(consts.MISSING_BASE_PATH_ERROR);\n }\n\n this._basePath = basePath;\n this._bodyParser = bodyParser;\n this._cache = cache;\n this._conditionalRequestsEnabled = enableConditionalRequests;\n this._fetchTimeout = fetchTimeout;\n this._headers = { ...consts.DEFAULT_HEADERS, ...headers };\n this._log = log;\n this._maxRedirects = maxRedirects;\n this._maxRetries = maxRetries;\n this._optionalPathTemplateRegExp = optionalPathTemplateRegExp;\n this._pathTemplateCallback = pathTemplateCallback;\n this._pathTemplateRegExp = pathTemplateRegExp;\n this._performance = performance;\n this._queryParams = queryParams;\n this._rateLimit = rateLimit;\n this._rateLimitPerSecond = rateLimitPerSecond;\n this._requestRetryWait = requestRetryWait;\n this._streamReader = streamReader;\n }\n\n get cache(): Core | undefined {\n return this._cache;\n }\n\n public createShortcut(\n name: string,\n path: string,\n { method, ...otherOptions }: SetRequired<RequestOptions, 'method'>,\n ) {\n if (!consts.FETCH_METHODS.includes(method)) {\n throw new Error(`${consts.INVALID_FETCH_METHOD_ERROR} ${method}`);\n }\n\n // @ts-expect-error No index signature with a parameter of type 'string'\n this[name] = async <Resource extends PlainObject>(\n { method: requestMethod, ...otherOptionOverrides }: RequestOptions = {},\n context?: Context,\n ) =>\n // @ts-expect-error Type 'undefined' is not assignable to type 'BodyInit'\n // To generic and complex to type without casting.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n this[requestMethod ?? method](path, merge({}, otherOptions, otherOptionOverrides), context) as Promise<\n FetchResponse<Resource>\n >;\n }\n\n public async delete(path: string, options: Omit<RequestOptions, 'method'> = {}, context?: Context) {\n return this._delete(path, options, context);\n }\n\n public async get(path: string, options: Omit<RequestOptions, 'method'> = {}, context?: Context) {\n return this._get(path, options, context);\n }\n\n public async post(path: string, options: Omit<SetRequired<RequestOptions, 'body'>, 'method'>, context?: Context) {\n return this._request(path, { ...options, method: consts.POST_METHOD }, context);\n }\n\n public async put(path: string, options: Omit<SetRequired<RequestOptions, 'body'>, 'methood'>, context?: Context) {\n return this._request(path, { ...options, method: consts.PUT_METHOD }, context);\n }\n\n private _addRequestToRateLimitedQueue(endpoint: string, options: FetchOptions, context: Context) {\n return new Promise((resolve: (value: FetchResponse) => void) => {\n this._rateLimitedRequestQueue.push([resolve, endpoint, options, context]);\n });\n }\n\n private async _cacheEntryDelete(requestHash: string): Promise<boolean> {\n if (!this._cache) {\n return false;\n }\n\n return this._cache.delete(requestHash);\n }\n\n private async _cacheEntryGet(requestHash: string): Promise<PlainObject | undefined> {\n if (!this._cache) {\n return undefined;\n }\n\n return this._cache.get(requestHash);\n }\n\n private async _cacheEntryHas(requestHash: string): Promise<Cacheability | false> {\n if (!this._cache) {\n return false;\n }\n\n try {\n return await this._cache.has(requestHash);\n } catch {\n return false;\n }\n }\n\n private async _cacheEntrySet(requestHash: string, data: PlainObject, cacheHeaders: CacheHeaders): Promise<void> {\n if (!this._cache) {\n return undefined;\n }\n\n return this._cache.set(requestHash, data, { cacheHeaders });\n }\n\n private async _delete(\n path: string,\n { headers = {}, pathTemplateData, queryParams = {}, ...rest }: Omit<RequestOptions, 'method'>,\n context?: Context,\n ) {\n const endpoint = buildEndpoint(this._basePath, path, {\n optionalPathTemplateRegExp: this._optionalPathTemplateRegExp,\n pathTemplateCallback: this._pathTemplateCallback,\n pathTemplateData,\n pathTemplateRegExp: this._pathTemplateRegExp,\n queryParams: { ...this._queryParams, ...queryParams },\n });\n\n const requestHash = Md5.hashStr(endpoint);\n const cacheability = await this._cacheEntryHas(requestHash);\n\n if (cacheability) {\n void this._cacheEntryDelete(requestHash);\n }\n\n return this._fetch(\n endpoint,\n {\n headers: { ...this._headers, ...headers },\n method: consts.DELETE_METHOD,\n ...rest,\n },\n context,\n );\n }\n\n private async _fetch(endpoint: string, options: FetchOptions, context: Context = {}): Promise<FetchResponse> {\n context.startTime = this._performance.now();\n\n try {\n const { redirects, retries, ...rest } = options;\n\n return await new Promise<FetchResponse>((resolve, reject) => {\n void (async () => {\n const fetchTimer = setTimeout(() => {\n reject(new Error(`${consts.FETCH_TIMEOUT_ERROR} ${String(this._fetchTimeout)}ms.`));\n }, this._fetchTimeout);\n\n if (this._rateLimit) {\n this._startRateLimit();\n\n if (!(this._rateLimitCount < this._rateLimitPerSecond)) {\n clearTimeout(fetchTimer);\n resolve(await this._addRequestToRateLimitedQueue(endpoint, options, context));\n return;\n }\n }\n\n if (!redirects && !retries) {\n this._log?.(consts.REQUEST_SENT, {\n context: {\n fetchMethod: rest.method,\n fetchRedirets: redirects,\n fetchRequestHeaders: rest.headers,\n fetchRetries: retries,\n fetchUrl: endpoint,\n logEntryName: 'FETCH_REQUEST_SENT',\n ...context,\n },\n stats: { startTime: context.startTime },\n });\n }\n\n // Casting as fetch response does not support generics.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const res = (await fetch(endpoint, rest)) as FetchResponse;\n\n clearTimeout(fetchTimer);\n\n const { body, headers, status } = res;\n const responseGroup = getResponseGroup(status);\n\n if (responseGroup === consts.REDIRECTION_REPSONSE && headers.has(consts.LOCATION_HEADER)) {\n resolve(\n await this._fetchRedirectHandler(\n res,\n // Has check above means this cannot be undefined.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n headers.get(consts.LOCATION_HEADER)!,\n {\n redirects,\n status,\n ...rest,\n },\n context,\n ),\n );\n\n return;\n }\n\n if (responseGroup === consts.SERVER_ERROR_REPSONSE) {\n resolve(\n await this._fetchRetryHandler(\n res,\n endpoint,\n {\n retries,\n ...rest,\n },\n context,\n ),\n );\n\n return;\n }\n\n try {\n Object.defineProperty(res, 'data', {\n enumerable: true,\n\n value: body ? this._bodyParser(await res[this._streamReader]()) : undefined,\n writable: true,\n });\n\n this._logResponse(res, endpoint, options, context);\n resolve(res);\n } catch (error) {\n if (error instanceof Error) {\n reject(error);\n } else {\n reject(new Error(`Unable to ${rest.method} ${endpoint} due to previous error`));\n }\n }\n })();\n });\n } catch (error) {\n const { startTime, ...rest } = context;\n const endTime = this._performance.now();\n\n this._log?.(consts.REQUEST_FAILED, {\n context: { error, fetchUrl: endpoint, logEntryName: 'FETCH_REQUEST_FAILED', ...rest },\n stats: { duration: startTime ? endTime - startTime : 0, endTime, startTime },\n });\n\n // Based on above code, error is going to be a type of Error.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return { errors: castArray(error) } as FetchResponse;\n }\n }\n\n private async _fetchRedirectHandler(\n res: FetchResponse,\n endpoint: string,\n options: FetchRedirectHandlerOptions,\n context: Context,\n ): Promise<FetchResponse> {\n const { method, redirects = 1, status, ...rest } = options;\n\n if (redirects === this._maxRedirects) {\n res.errors = [new Error(`${consts.MAX_REDIRECTS_EXCEEDED_ERROR} ${String(this._maxRedirects)}.`)];\n this._logResponse(res, endpoint, options, context);\n return res;\n }\n\n const redirectMethod = status === 303 ? consts.GET_METHOD : method;\n return this._fetch(endpoint, { method: redirectMethod, redirects: redirects + 1, ...rest });\n }\n\n private async _fetchRetryHandler(res: FetchResponse, endpoint: string, options: FetchOptions, context: Context) {\n const { retries = 1, ...rest } = options;\n\n if (retries === this._maxRetries) {\n res.errors = [new Error(`${consts.MAX_RETRIES_EXCEEDED_ERROR} ${String(this._maxRetries)}.`)];\n this._logResponse(res, endpoint, options, context);\n return res;\n }\n\n await delay(this._requestRetryWait);\n return this._fetch(endpoint, { retries: retries + 1, ...rest });\n }\n\n private async _get(\n path: string,\n { headers = {}, pathTemplateData, queryParams = {} }: Omit<RequestOptions, 'method'>,\n context?: Context,\n ) {\n const endpoint = buildEndpoint(this._basePath, path, {\n optionalPathTemplateRegExp: this._optionalPathTemplateRegExp,\n pathTemplateCallback: this._pathTemplateCallback,\n pathTemplateData,\n pathTemplateRegExp: this._pathTemplateRegExp,\n queryParams: { ...this._queryParams, ...queryParams },\n });\n\n const requestHash = Md5.hashStr(endpoint);\n const cacheability = await this._cacheEntryHas(requestHash);\n\n if (cacheability) {\n if (isCacheabilityValid(cacheability)) {\n const newHeaders = {\n ...headers,\n 'cache-control': cacheability.printCacheControl(),\n };\n\n this._log?.(consts.RESPONSE_FROM_CACHE, {\n context: {\n fetchMethod: consts.GET_METHOD,\n fetchResponseHeaders: newHeaders,\n fetchUrl: endpoint,\n logEntryName: 'FETCH_RESPONSE_FROM_CACHE',\n ...context,\n },\n });\n\n return {\n data: await this._cacheEntryGet(requestHash),\n headers: new Headers(newHeaders),\n };\n }\n\n if (this._conditionalRequestsEnabled && cacheability.metadata.etag) {\n headers[consts.IF_NONE_MATCH_HEADER] = cacheability.metadata.etag;\n }\n }\n\n const pendingRequest = this._trackRequest(requestHash);\n\n if (pendingRequest) {\n return pendingRequest;\n }\n\n return this._getResolve(\n requestHash,\n await this._fetch(endpoint, { headers: { ...this._headers, ...headers }, method: consts.GET_METHOD }, context),\n );\n }\n\n private async _getResolve(requestHash: string, res: FetchResponse) {\n const { data, headers, status } = res;\n\n if (status === consts.NOT_FOUND_STATUS_CODE) {\n void this._cacheEntryDelete(requestHash);\n let { errors } = res;\n errors ??= [];\n errors.push(new Error(consts.RESOURCE_NOT_FOUND_ERROR));\n res.errors = errors;\n } else if (status === consts.NOT_MODIFIED_STATUS_CODE) {\n const cachedData = await this._cacheEntryGet(requestHash);\n\n if (cachedData) {\n void this._cacheEntrySet(requestHash, cachedData, {\n cacheControl: headers.get(consts.CACHE_CONTROL_HEADER) ?? undefined,\n etag: headers.get(consts.ETAG_HEADER) ?? undefined,\n });\n\n res.data = cachedData;\n }\n } else if (data) {\n void this._cacheEntrySet(requestHash, data, {\n cacheControl: headers.get(consts.CACHE_CONTROL_HEADER) ?? undefined,\n etag: headers.get(consts.ETAG_HEADER) ?? undefined,\n });\n }\n\n this._resolvePendingRequests(requestHash, res);\n this._requestTracker.active = this._requestTracker.active.filter(value => value !== requestHash);\n return res;\n }\n\n private _logResponse(res: FetchResponse, endpoint: string, options: FetchOptions, context: Context) {\n const { headers, status } = res;\n const { method, redirects, retries } = options;\n const { startTime, ...otherContext } = context;\n const endTime = this._performance.now();\n const duration = startTime ? endTime - startTime : 0;\n\n this._log?.(consts.RESPONSE_RECEIVED, {\n context: {\n fetchMethod: method,\n fetchRedirects: redirects,\n fetchResponseHeaders: Object.fromEntries(headers.entries()),\n fetchResponseStatus: status,\n fetchRetries: retries,\n fetchUrl: endpoint,\n logEntryName: 'FETCH_RESPONSE_RECEIVED',\n ...otherContext,\n },\n stats: { duration, endTime, startTime },\n });\n }\n\n private async _releaseRateLimitedRequestQueue() {\n for (const [resolve, endpoint, options, context] of this._rateLimitedRequestQueue) {\n resolve(await this._fetch(endpoint, options, context));\n }\n\n this._rateLimitedRequestQueue = [];\n }\n\n private async _request(\n path: string,\n { body, headers, method, pathTemplateData, queryParams, ...rest }: SetRequired<RequestOptions, 'method'>,\n context?: Context,\n ) {\n const endpoint = buildEndpoint(this._basePath, path, {\n optionalPathTemplateRegExp: this._optionalPathTemplateRegExp,\n pathTemplateCallback: this._pathTemplateCallback,\n pathTemplateData,\n pathTemplateRegExp: this._pathTemplateRegExp,\n queryParams: { ...this._queryParams, ...queryParams },\n });\n\n return this._fetch(\n endpoint,\n {\n body,\n headers: { ...this._headers, ...headers },\n method,\n ...rest,\n },\n context,\n );\n }\n\n private _resolvePendingRequests(requestHash: string, responseData: FetchResponse) {\n const pendingRequests = this._requestTracker.pending.get(requestHash);\n\n if (!pendingRequests) {\n return;\n }\n\n for (const { resolve } of pendingRequests) {\n resolve(responseData);\n }\n\n this._requestTracker.pending.delete(requestHash);\n }\n\n private _setPendingRequest(requestHash: string, resolver: PendingRequestResolvers) {\n let pending = this._requestTracker.pending.get(requestHash);\n pending ??= [];\n pending.push(resolver);\n this._requestTracker.pending.set(requestHash, pending);\n }\n\n private _startRateLimit() {\n this._rateLimitTimer ??= setTimeout(() => {\n this._rateLimitTimer = undefined;\n this._rateLimitCount = 0;\n\n if (this._rateLimitedRequestQueue.length > 0) {\n void this._releaseRateLimitedRequestQueue();\n }\n }, 1000);\n\n this._rateLimitCount += 1;\n }\n\n private _trackRequest(requestHash: string): Promise<FetchResponse> | undefined {\n if (this._requestTracker.active.includes(requestHash)) {\n return new Promise((resolve: PendingRequestResolver) => {\n this._setPendingRequest(requestHash, { resolve });\n });\n }\n\n this._requestTracker.active.push(requestHash);\n return;\n }\n}\n\nexport const createRestClient = <N extends string>(options: ConstructorOptions, shortcuts?: Shortcuts) => {\n // Typing proving too complex without casting.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const getta = new Getta(options) as Getta & ShortcutProperties<N>;\n\n if (!shortcuts) {\n return getta;\n }\n\n for (const key of Object.keys(shortcuts)) {\n const shortcut = shortcuts[key];\n\n if (shortcut) {\n getta.createShortcut(key, ...shortcut);\n }\n }\n\n return getta;\n};\n","import * as consts from '../../constants.ts';\n\nexport const getResponseGroup = (status: number) => {\n switch (true) {\n case status < 200: {\n return consts.INFORMATION_REPSONSE;\n }\n\n case status < 300: {\n return consts.SUCCESSFUL_REPSONSE;\n }\n\n case status < 400: {\n return consts.REDIRECTION_REPSONSE;\n }\n\n case status < 500: {\n return consts.CLIENT_ERROR_REPSONSE;\n }\n\n default: {\n return consts.SERVER_ERROR_REPSONSE;\n }\n }\n};\n","export const delay = (ms: number) => {\n return new Promise(resolve => setTimeout(resolve, ms));\n};\n","import { type Cacheability } from 'cacheability';\n\nexport const isCacheabilityValid = (cacheability: Cacheability) => {\n const noCache = cacheability.metadata.cacheControl.noCache ?? false;\n return !noCache && cacheability.checkTTL();\n};\n"],"names":["ARRAY_BUFFER_FORMAT","BLOB_FORMAT","FORM_DATA_FORMAT","JSON_FORMAT","TEXT_FORMAT","STREAM_READERS","DEFAULT_BODY_PARSER","body","DEFAULT_FETCH_TIMEOUT","DEFAULT_HEADERS","DEFAULT_MAX_REDIRECTS","DEFAULT_MAX_RETRIES","DEFAULT_PATH_TEMPLATE_REGEX","OPTIONAL_PATH_TEMPLATE_REGEX","DEFAULT_RATE_LIMIT","DEFAULT_REQUEST_RETRY_WAIT","MISSING_BASE_PATH_ERROR","MAX_REDIRECTS_EXCEEDED_ERROR","MAX_RETRIES_EXCEEDED_ERROR","INVALID_FETCH_METHOD_ERROR","RESOURCE_NOT_FOUND_ERROR","FETCH_TIMEOUT_ERROR","GET_METHOD","POST_METHOD","PUT_METHOD","DELETE_METHOD","FETCH_METHODS","INFORMATION_REPSONSE","SUCCESSFUL_REPSONSE","REDIRECTION_REPSONSE","CLIENT_ERROR_REPSONSE","SERVER_ERROR_REPSONSE","ETAG_HEADER","LOCATION_HEADER","IF_NONE_MATCH_HEADER","CACHE_CONTROL_HEADER","REQUEST_SENT","RESPONSE_RECEIVED","RESPONSE_FROM_CACHE","REQUEST_FAILED","defaultPathTemplateCallback","pathTemplate","data","pathTemplateRegExp","dataKeys","Object","keys","replace","match","key","includes","undefined","String","buildEndpoint","basePath","path","optionalPathTemplateRegExp","pathTemplateCallback","pathTemplateData","queryParams","pathJoiner","endsWith","startsWith","endpoint","slice","Math","max","length","sanitisedSearchParams","omitBy","entry","queryString","extract","stringify","Getta","constructor","options","_rateLimitCount","_rateLimitedRequestQueue","_rateLimitTimer","_requestTracker","active","pending","Map","bodyParser","consts","cache","enableConditionalRequests","fetchTimeout","headers","log","maxRedirects","maxRetries","performance","rateLimit","rateLimitPerSecond","requestRetryWait","streamReader","Error","this","_basePath","_bodyParser","_cache","_conditionalRequestsEnabled","_fetchTimeout","_headers","_log","_maxRedirects","_maxRetries","_optionalPathTemplateRegExp","_pathTemplateCallback","_pathTemplateRegExp","_performance","_queryParams","_rateLimit","_rateLimitPerSecond","_requestRetryWait","_streamReader","createShortcut","name","method","otherOptions","async","requestMethod","otherOptionOverrides","context","merge","delete","_delete","get","_get","post","_request","put","_addRequestToRateLimitedQueue","Promise","resolve","push","_cacheEntryDelete","requestHash","_cacheEntryGet","_cacheEntryHas","has","_cacheEntrySet","cacheHeaders","set","rest","Md5","hashStr","_fetch","startTime","now","redirects","retries","reject","fetchTimer","setTimeout","_startRateLimit","clearTimeout","fetchMethod","fetchRedirets","fetchRequestHeaders","fetchRetries","fetchUrl","logEntryName","stats","res","fetch","status","responseGroup","getResponseGroup","_fetchRedirectHandler","defineProperty","enumerable","value","writable","_logResponse","error","_fetchRetryHandler","endTime","duration","errors","castArray","redirectMethod","ms","cacheability","metadata","cacheControl","noCache","checkTTL","isCacheabilityValid","newHeaders","printCacheControl","fetchResponseHeaders","Headers","etag","pendingRequest","_trackRequest","_getResolve","cachedData","_resolvePendingRequests","filter","otherContext","fetchRedirects","fromEntries","entries","fetchResponseStatus","_releaseRateLimitedRequestQueue","responseData","pendingRequests","_setPendingRequest","resolver","shortcuts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E,uBAAAA,CAAwB7D,EAAqBqE,GACnD,MAAMC,EAAkB9G,KAAKnB,gBAAgBE,QAAQ+C,IAAIU,GAEzD,GAAKsE,EAAL,CAIA,IAAK,MAAMzE,QAAEA,KAAayE,EACxBzE,EAAQwE,GAGV7G,KAAKnB,gBAAgBE,QAAQ6C,OAAOY,EANpC,CAOF,CAEQuE,kBAAAA,CAAmBvE,EAAqBwE,GAC9C,IAAIjI,EAAUiB,KAAKnB,gBAAgBE,QAAQ+C,IAAIU,GAC/CzD,IAAY,GACZA,EAAQuD,KAAK0E,GACbhH,KAAKnB,gBAAgBE,QAAQ+D,IAAIN,EAAazD,EAChD,CAEQ2E,eAAAA,GACN1D,KAAKpB,kBAAoB6E,YAAW,KAClCzD,KAAKpB,qBAAkB5B,EACvBgD,KAAKtB,gBAAkB,EAEnBsB,KAAKrB,yBAAyBX,OAAS,GACpCgC,KAAK4G,oCAEX,KAEH5G,KAAKtB,iBAAmB,CAC1B,CAEQwH,aAAAA,CAAc1D,GACpB,GAAIxC,KAAKnB,gBAAgBC,OAAO/B,SAASyF,GACvC,OAAO,IAAIJ,SAASC,IAClBrC,KAAK+G,mBAAmBvE,EAAa,CAAEH,eAI3CrC,KAAKnB,gBAAgBC,OAAOwD,KAAKE,EAEnC,2IH9e2B,0sBAFQ,qCADG,wYGofR,CAAmB/D,EAA6BwI,KAG9E,MAAMC,EAAQ,IAAI3I,EAAME,GAExB,IAAKwI,EACH,OAAOC,EAGT,IAAK,MAAMpK,KAAOJ,OAAOC,KAAKsK,GAAY,CACxC,MAAME,EAAWF,EAAUnK,GAEvBqK,GACFD,EAAM/F,eAAerE,KAAQqK,EAEjC,CAEA,OAAOD"}
|
package/dist/esm/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"core-js/modules/es.array.push.js";import{merge as e,castArray as t}from"lodash-es";import{Md5 as r}from"ts-md5";import a from"query-string";const s="arrayBuffer",i="blob",h="formData",c="json",o="text",n={ARRAY_BUFFER_FORMAT:s,BLOB_FORMAT:i,FORM_DATA_FORMAT:h,JSON_FORMAT:c,TEXT_FORMAT:o},u=e=>e,m=5e3,d={"content-type":"application/json"},_=5,l=3,p=/({type})|({id})|({id,\+})|({brief\|standard})/g,R=/({\w+\?})/g,T=50,f=100,g="Getta expected to receive 'basePath' in the constructor options,\n but recevied undefined.",y="The request exceeded the maximum number of redirects, which is",E="The request exceeded the maximum number of retries, which is",q="Getta expected to receive 'get', 'post', 'put' or 'delete', but received",P="The requested resource could not been found.",b="The request timed out. Getta did not get a response within",x="get",w="post",C="put",v="delete",L=[x,w,C,v],k="information",S="successful",H="redirection",O="clientError",$="serverError",D=304,F=404,M="Cookie",A="ETag",Q="Location",j="If-None-Match",N="Cache-Control",U="request_sent",G="response_received",W="response_from_cache",B="request_failed",I=(e,t,r)=>{const a=Object.keys(t);return e.replace(r,(e=>{for(const r of a)if(e.includes(r)&&void 0!==t[r])return String(t[r]);return""}))},J=(e,t,{optionalPathTemplateRegExp:r,pathTemplateCallback:s,pathTemplateData:i,pathTemplateRegExp:h,queryParams:c})=>{const o=e.endsWith("/")||t.startsWith("/")?"":"/";let n=`${e}${o}${t}`;if(i&&(n=s(n,i,h)),n=n.replace(r,""),n.endsWith("/")&&(n=n.slice(0,Math.max(0,n.length-1))),c&&Object.keys(c).length>0){n=`${n}${a.extract(n)?"&":"?"}${a.stringify(c)}`}return n};class V{constructor(e){this._rateLimitCount=0,this._rateLimitedRequestQueue=[],this._rateLimitTimer=void 0,this._requestTracker={active:[],pending:new Map};const{basePath:t,bodyParser:r=u,cache:a,enableConditionalRequests:s=!0,fetchTimeout:i=m,headers:h,log:o,maxRedirects:n=_,maxRetries:y=l,optionalPathTemplateRegExp:E=R,pathTemplateCallback:q=I,pathTemplateRegExp:P=p,performance:b,queryParams:x={},rateLimit:w=!1,rateLimitPerSecond:C=T,requestRetryWait:v=f,streamReader:L=c}=e;if(!t)throw new Error(g);this._basePath=t,this._bodyParser=r,this._cache=a,this._conditionalRequestsEnabled=s,this._fetchTimeout=i,this._headers={...d,...h},this._log=o,this._maxRedirects=n,this._maxRetries=y,this._optionalPathTemplateRegExp=E,this._pathTemplateCallback=q,this._pathTemplateRegExp=P,this._performance=b,this._queryParams=x,this._rateLimit=w,this._rateLimitPerSecond=C,this._requestRetryWait=v,this._streamReader=L}get cache(){return this._cache}createShortcut(t,r,{method:a,...s}){if(!L.includes(a))throw new Error(`${q} ${a}`);this[t]=async({method:t,...i}={},h)=>this[t??a](r,e({},s,i),h)}async delete(e,t={},r){return this._delete(e,t,r)}async get(e,t={},r){return this._get(e,t,r)}async post(e,t,r){return this._request(e,{...t,method:w},r)}async put(e,t,r){return this._request(e,{...t,method:C},r)}_addRequestToRateLimitedQueue(e,t,r){return new Promise((a=>{this._rateLimitedRequestQueue.push([a,e,t,r])}))}async _cacheEntryDelete(e){return!!this._cache&&this._cache.delete(e)}async _cacheEntryGet(e){if(this._cache)return this._cache.get(e)}async _cacheEntryHas(e){if(!this._cache)return!1;try{return await this._cache.has(e)}catch{return!1}}async _cacheEntrySet(e,t,r){if(this._cache)return this._cache.set(e,t,{cacheHeaders:r})}async _delete(e,{headers:t={},pathTemplateData:a,queryParams:s={},...i},h){const c=J(this._basePath,e,{optionalPathTemplateRegExp:this._optionalPathTemplateRegExp,pathTemplateCallback:this._pathTemplateCallback,pathTemplateData:a,pathTemplateRegExp:this._pathTemplateRegExp,queryParams:{...this._queryParams,...s}}),o=r.hashStr(c);return await this._cacheEntryHas(o)&&this._cacheEntryDelete(o),this._fetch(c,{headers:{...this._headers,...t},method:v,...i},h)}async _fetch(e,r,a={}){a.startTime=this._performance.now();try{const{redirects:t,retries:s,...i}=r;return await new Promise(((h,c)=>{(async()=>{const o=setTimeout((()=>{c(new Error(`${b} ${String(this._fetchTimeout)}ms.`))}),this._fetchTimeout);if(this._rateLimit&&(this._startRateLimit(),!(this._rateLimitCount<this._rateLimitPerSecond)))return clearTimeout(o),void h(await this._addRequestToRateLimitedQueue(e,r,a));t||s||this._log?.(U,{context:{fetchMethod:i.method,fetchRedirets:t,fetchRequestHeaders:i.headers,fetchRetries:s,fetchUrl:e,logEntryName:"FETCH_REQUEST_SENT",...a},stats:{startTime:a.startTime}});const n=await fetch(e,i);clearTimeout(o);const{body:u,headers:m,status:d}=n,_=(e=>{switch(!0){case e<200:return k;case e<300:return S;case e<400:return H;case e<500:return O;default:return $}})(d);if(_===H&&m.has(Q))h(await this._fetchRedirectHandler(n,m.get(Q),{redirects:t,status:d,...i},a));else if(_!==$)try{Object.defineProperty(n,"data",{enumerable:!0,value:u?this._bodyParser(await n[this._streamReader]()):void 0,writable:!0}),this._logResponse(n,e,r,a),h(n)}catch(t){t instanceof Error?c(t):c(new Error(`Unable to ${i.method} ${e} due to previous error`))}else h(await this._fetchRetryHandler(n,e,{retries:s,...i},a))})()}))}catch(r){const{startTime:s,...i}=a,h=this._performance.now();return this._log?.(B,{context:{error:r,fetchUrl:e,logEntryName:"FETCH_REQUEST_FAILED",...i},stats:{duration:s?h-s:0,endTime:h,startTime:s}}),{errors:t(r)}}}async _fetchRedirectHandler(e,t,r,a){const{method:s,redirects:i=1,status:h,...c}=r;if(i===this._maxRedirects)return e.errors=[new Error(`${y} ${String(this._maxRedirects)}.`)],this._logResponse(e,t,r,a),e;const o=303===h?x:s;return this._fetch(t,{method:o,redirects:i+1,...c})}async _fetchRetryHandler(e,t,r,a){const{retries:s=1,...i}=r;return s===this._maxRetries?(e.errors=[new Error(`${E} ${String(this._maxRetries)}.`)],this._logResponse(e,t,r,a),e):(await(h=this._requestRetryWait,new Promise((e=>setTimeout(e,h)))),this._fetch(t,{retries:s+1,...i}));var h}async _get(e,{headers:t={},pathTemplateData:a,queryParams:s={}},i){const h=J(this._basePath,e,{optionalPathTemplateRegExp:this._optionalPathTemplateRegExp,pathTemplateCallback:this._pathTemplateCallback,pathTemplateData:a,pathTemplateRegExp:this._pathTemplateRegExp,queryParams:{...this._queryParams,...s}}),c=r.hashStr(h),o=await this._cacheEntryHas(c);if(o){if((e=>!e.metadata.cacheControl.noCache&&e.checkTTL())(o)){const e={...t,"cache-control":o.printCacheControl()};return this._log?.(W,{context:{fetchMethod:x,fetchResponseHeaders:e,fetchUrl:h,logEntryName:"FETCH_RESPONSE_FROM_CACHE",...i}}),{data:await this._cacheEntryGet(c),headers:new Headers(e)}}this._conditionalRequestsEnabled&&o.metadata.etag&&(t[j]=o.metadata.etag)}const n=this._trackRequest(c);return n||this._getResolve(c,await this._fetch(h,{headers:{...this._headers,...t},method:x},i))}async _getResolve(e,t){const{data:r,headers:a,status:s}=t;if(404===s){this._cacheEntryDelete(e);let{errors:r}=t;r||(r=[]),r.push(new Error(P)),t.errors=r}else if(304===s){const r=await this._cacheEntryGet(e);r&&(this._cacheEntrySet(e,r,{cacheControl:a.get(N)??void 0,etag:a.get(A)??void 0}),t.data=r)}else r&&this._cacheEntrySet(e,r,{cacheControl:a.get(N)??void 0,etag:a.get(A)??void 0});return this._resolvePendingRequests(e,t),this._requestTracker.active=this._requestTracker.active.filter((t=>t!==e)),t}_logResponse(e,t,r,a){const{headers:s,status:i}=e,{method:h,redirects:c,retries:o}=r,{startTime:n,...u}=a,m=this._performance.now(),d=n?m-n:0;this._log?.(G,{context:{fetchMethod:h,fetchRedirects:c,fetchResponseHeaders:Object.fromEntries(s.entries()),fetchResponseStatus:i,fetchRetries:o,fetchUrl:t,logEntryName:"FETCH_RESPONSE_RECEIVED",...u},stats:{duration:d,endTime:m,startTime:n}})}async _releaseRateLimitedRequestQueue(){for(const[e,t,r,a]of this._rateLimitedRequestQueue)e(await this._fetch(t,r,a));this._rateLimitedRequestQueue=[]}async _request(e,{body:t,headers:r,method:a,pathTemplateData:s,queryParams:i,...h},c){const o=J(this._basePath,e,{optionalPathTemplateRegExp:this._optionalPathTemplateRegExp,pathTemplateCallback:this._pathTemplateCallback,pathTemplateData:s,pathTemplateRegExp:this._pathTemplateRegExp,queryParams:{...this._queryParams,...i}});return this._fetch(o,{body:t,headers:{...this._headers,...r},method:a,...h},c)}_resolvePendingRequests(e,t){const r=this._requestTracker.pending.get(e);if(r){for(const{resolve:e}of r)e(t);this._requestTracker.pending.delete(e)}}_setPendingRequest(e,t){let r=this._requestTracker.pending.get(e);r||(r=[]),r.push(t),this._requestTracker.pending.set(e,r)}_startRateLimit(){this._rateLimitTimer||(this._rateLimitTimer=setTimeout((()=>{this._rateLimitTimer=void 0,this._rateLimitCount=0,this._rateLimitedRequestQueue.length>0&&this._releaseRateLimitedRequestQueue()}),1e3)),this._rateLimitCount+=1}_trackRequest(e){if(this._requestTracker.active.includes(e))return new Promise((t=>{this._setPendingRequest(e,{resolve:t})}));this._requestTracker.active.push(e)}}const X=(e,t)=>{const r=new V(e);if(!t)return r;for(const e of Object.keys(t)){const a=t[e];a&&r.createShortcut(e,...a)}return r};export{s as ARRAY_BUFFER_FORMAT,i as BLOB_FORMAT,N as CACHE_CONTROL_HEADER,O as CLIENT_ERROR_REPSONSE,M as COOKIE_HEADER,u as DEFAULT_BODY_PARSER,m as DEFAULT_FETCH_TIMEOUT,d as DEFAULT_HEADERS,_ as DEFAULT_MAX_REDIRECTS,l as DEFAULT_MAX_RETRIES,p as DEFAULT_PATH_TEMPLATE_REGEX,T as DEFAULT_RATE_LIMIT,f as DEFAULT_REQUEST_RETRY_WAIT,v as DELETE_METHOD,A as ETAG_HEADER,L as FETCH_METHODS,b as FETCH_TIMEOUT_ERROR,h as FORM_DATA_FORMAT,x as GET_METHOD,V as Getta,j as IF_NONE_MATCH_HEADER,k as INFORMATION_REPSONSE,q as INVALID_FETCH_METHOD_ERROR,c as JSON_FORMAT,Q as LOCATION_HEADER,y as MAX_REDIRECTS_EXCEEDED_ERROR,E as MAX_RETRIES_EXCEEDED_ERROR,g as MISSING_BASE_PATH_ERROR,F as NOT_FOUND_STATUS_CODE,D as NOT_MODIFIED_STATUS_CODE,R as OPTIONAL_PATH_TEMPLATE_REGEX,w as POST_METHOD,C as PUT_METHOD,H as REDIRECTION_REPSONSE,B as REQUEST_FAILED,U as REQUEST_SENT,P as RESOURCE_NOT_FOUND_ERROR,W as RESPONSE_FROM_CACHE,G as RESPONSE_RECEIVED,$ as SERVER_ERROR_REPSONSE,n as STREAM_READERS,S as SUCCESSFUL_REPSONSE,o as TEXT_FORMAT,X as createRestClient,I as defaultPathTemplateCallback};
|
|
1
|
+
import"core-js/modules/es.array.push.js";import{omitBy as e,merge as t,castArray as r}from"lodash-es";import{Md5 as a}from"ts-md5";import s from"query-string";const i="arrayBuffer",h="blob",c="formData",o="json",n="text",u={ARRAY_BUFFER_FORMAT:i,BLOB_FORMAT:h,FORM_DATA_FORMAT:c,JSON_FORMAT:o,TEXT_FORMAT:n},m=e=>e,d=5e3,_={"content-type":"application/json"},l=5,p=3,R=/({type})|({id})|({id,\+})|({brief\|standard})/g,T=/({\w+\?})/g,f=50,g=100,y="Getta expected to receive 'basePath' in the constructor options,\n but recevied undefined.",E="The request exceeded the maximum number of redirects, which is",q="The request exceeded the maximum number of retries, which is",P="Getta expected to receive 'get', 'post', 'put' or 'delete', but received",b="The requested resource could not been found.",x="The request timed out. Getta did not get a response within",w="get",C="post",v="put",L="delete",k=[w,C,v,L],S="information",H="successful",O="redirection",$="clientError",D="serverError",F=304,M=404,A="Cookie",Q="ETag",j="Location",N="If-None-Match",U="Cache-Control",G="request_sent",W="response_received",B="response_from_cache",I="request_failed",J=(e,t,r)=>{const a=Object.keys(t);return e.replace(r,(e=>{for(const r of a)if(e.includes(r)&&void 0!==t[r])return String(t[r]);return""}))},V=(t,r,{optionalPathTemplateRegExp:a,pathTemplateCallback:i,pathTemplateData:h,pathTemplateRegExp:c,queryParams:o={}})=>{const n=t.endsWith("/")||r.startsWith("/")?"":"/";let u=`${t}${n}${r}`;h&&(u=i(u,h,c)),u=u.replace(a,""),u.endsWith("/")&&(u=u.slice(0,Math.max(0,u.length-1)));const m=e(o,(e=>!e));if(Object.keys(m).length>0){u=`${u}${s.extract(u)?"&":"?"}${s.stringify(m)}`}return u};class X{constructor(e){this._rateLimitCount=0,this._rateLimitedRequestQueue=[],this._rateLimitTimer=void 0,this._requestTracker={active:[],pending:new Map};const{basePath:t,bodyParser:r=m,cache:a,enableConditionalRequests:s=!0,fetchTimeout:i=d,headers:h,log:c,maxRedirects:n=l,maxRetries:u=p,optionalPathTemplateRegExp:E=T,pathTemplateCallback:q=J,pathTemplateRegExp:P=R,performance:b,queryParams:x={},rateLimit:w=!1,rateLimitPerSecond:C=f,requestRetryWait:v=g,streamReader:L=o}=e;if(!t)throw new Error(y);this._basePath=t,this._bodyParser=r,this._cache=a,this._conditionalRequestsEnabled=s,this._fetchTimeout=i,this._headers={..._,...h},this._log=c,this._maxRedirects=n,this._maxRetries=u,this._optionalPathTemplateRegExp=E,this._pathTemplateCallback=q,this._pathTemplateRegExp=P,this._performance=b,this._queryParams=x,this._rateLimit=w,this._rateLimitPerSecond=C,this._requestRetryWait=v,this._streamReader=L}get cache(){return this._cache}createShortcut(e,r,{method:a,...s}){if(!k.includes(a))throw new Error(`${P} ${a}`);this[e]=async({method:e,...i}={},h)=>this[e??a](r,t({},s,i),h)}async delete(e,t={},r){return this._delete(e,t,r)}async get(e,t={},r){return this._get(e,t,r)}async post(e,t,r){return this._request(e,{...t,method:C},r)}async put(e,t,r){return this._request(e,{...t,method:v},r)}_addRequestToRateLimitedQueue(e,t,r){return new Promise((a=>{this._rateLimitedRequestQueue.push([a,e,t,r])}))}async _cacheEntryDelete(e){return!!this._cache&&this._cache.delete(e)}async _cacheEntryGet(e){if(this._cache)return this._cache.get(e)}async _cacheEntryHas(e){if(!this._cache)return!1;try{return await this._cache.has(e)}catch{return!1}}async _cacheEntrySet(e,t,r){if(this._cache)return this._cache.set(e,t,{cacheHeaders:r})}async _delete(e,{headers:t={},pathTemplateData:r,queryParams:s={},...i},h){const c=V(this._basePath,e,{optionalPathTemplateRegExp:this._optionalPathTemplateRegExp,pathTemplateCallback:this._pathTemplateCallback,pathTemplateData:r,pathTemplateRegExp:this._pathTemplateRegExp,queryParams:{...this._queryParams,...s}}),o=a.hashStr(c);return await this._cacheEntryHas(o)&&this._cacheEntryDelete(o),this._fetch(c,{headers:{...this._headers,...t},method:L,...i},h)}async _fetch(e,t,a={}){a.startTime=this._performance.now();try{const{redirects:r,retries:s,...i}=t;return await new Promise(((h,c)=>{(async()=>{const o=setTimeout((()=>{c(new Error(`${x} ${String(this._fetchTimeout)}ms.`))}),this._fetchTimeout);if(this._rateLimit&&(this._startRateLimit(),!(this._rateLimitCount<this._rateLimitPerSecond)))return clearTimeout(o),void h(await this._addRequestToRateLimitedQueue(e,t,a));r||s||this._log?.(G,{context:{fetchMethod:i.method,fetchRedirets:r,fetchRequestHeaders:i.headers,fetchRetries:s,fetchUrl:e,logEntryName:"FETCH_REQUEST_SENT",...a},stats:{startTime:a.startTime}});const n=await fetch(e,i);clearTimeout(o);const{body:u,headers:m,status:d}=n,_=(e=>{switch(!0){case e<200:return S;case e<300:return H;case e<400:return O;case e<500:return $;default:return D}})(d);if(_===O&&m.has(j))h(await this._fetchRedirectHandler(n,m.get(j),{redirects:r,status:d,...i},a));else if(_!==D)try{Object.defineProperty(n,"data",{enumerable:!0,value:u?this._bodyParser(await n[this._streamReader]()):void 0,writable:!0}),this._logResponse(n,e,t,a),h(n)}catch(t){t instanceof Error?c(t):c(new Error(`Unable to ${i.method} ${e} due to previous error`))}else h(await this._fetchRetryHandler(n,e,{retries:s,...i},a))})()}))}catch(t){const{startTime:s,...i}=a,h=this._performance.now();return this._log?.(I,{context:{error:t,fetchUrl:e,logEntryName:"FETCH_REQUEST_FAILED",...i},stats:{duration:s?h-s:0,endTime:h,startTime:s}}),{errors:r(t)}}}async _fetchRedirectHandler(e,t,r,a){const{method:s,redirects:i=1,status:h,...c}=r;if(i===this._maxRedirects)return e.errors=[new Error(`${E} ${String(this._maxRedirects)}.`)],this._logResponse(e,t,r,a),e;const o=303===h?w:s;return this._fetch(t,{method:o,redirects:i+1,...c})}async _fetchRetryHandler(e,t,r,a){const{retries:s=1,...i}=r;return s===this._maxRetries?(e.errors=[new Error(`${q} ${String(this._maxRetries)}.`)],this._logResponse(e,t,r,a),e):(await(h=this._requestRetryWait,new Promise((e=>setTimeout(e,h)))),this._fetch(t,{retries:s+1,...i}));var h}async _get(e,{headers:t={},pathTemplateData:r,queryParams:s={}},i){const h=V(this._basePath,e,{optionalPathTemplateRegExp:this._optionalPathTemplateRegExp,pathTemplateCallback:this._pathTemplateCallback,pathTemplateData:r,pathTemplateRegExp:this._pathTemplateRegExp,queryParams:{...this._queryParams,...s}}),c=a.hashStr(h),o=await this._cacheEntryHas(c);if(o){if((e=>!e.metadata.cacheControl.noCache&&e.checkTTL())(o)){const e={...t,"cache-control":o.printCacheControl()};return this._log?.(B,{context:{fetchMethod:w,fetchResponseHeaders:e,fetchUrl:h,logEntryName:"FETCH_RESPONSE_FROM_CACHE",...i}}),{data:await this._cacheEntryGet(c),headers:new Headers(e)}}this._conditionalRequestsEnabled&&o.metadata.etag&&(t[N]=o.metadata.etag)}const n=this._trackRequest(c);return n||this._getResolve(c,await this._fetch(h,{headers:{...this._headers,...t},method:w},i))}async _getResolve(e,t){const{data:r,headers:a,status:s}=t;if(404===s){this._cacheEntryDelete(e);let{errors:r}=t;r??=[],r.push(new Error(b)),t.errors=r}else if(304===s){const r=await this._cacheEntryGet(e);r&&(this._cacheEntrySet(e,r,{cacheControl:a.get(U)??void 0,etag:a.get(Q)??void 0}),t.data=r)}else r&&this._cacheEntrySet(e,r,{cacheControl:a.get(U)??void 0,etag:a.get(Q)??void 0});return this._resolvePendingRequests(e,t),this._requestTracker.active=this._requestTracker.active.filter((t=>t!==e)),t}_logResponse(e,t,r,a){const{headers:s,status:i}=e,{method:h,redirects:c,retries:o}=r,{startTime:n,...u}=a,m=this._performance.now(),d=n?m-n:0;this._log?.(W,{context:{fetchMethod:h,fetchRedirects:c,fetchResponseHeaders:Object.fromEntries(s.entries()),fetchResponseStatus:i,fetchRetries:o,fetchUrl:t,logEntryName:"FETCH_RESPONSE_RECEIVED",...u},stats:{duration:d,endTime:m,startTime:n}})}async _releaseRateLimitedRequestQueue(){for(const[e,t,r,a]of this._rateLimitedRequestQueue)e(await this._fetch(t,r,a));this._rateLimitedRequestQueue=[]}async _request(e,{body:t,headers:r,method:a,pathTemplateData:s,queryParams:i,...h},c){const o=V(this._basePath,e,{optionalPathTemplateRegExp:this._optionalPathTemplateRegExp,pathTemplateCallback:this._pathTemplateCallback,pathTemplateData:s,pathTemplateRegExp:this._pathTemplateRegExp,queryParams:{...this._queryParams,...i}});return this._fetch(o,{body:t,headers:{...this._headers,...r},method:a,...h},c)}_resolvePendingRequests(e,t){const r=this._requestTracker.pending.get(e);if(r){for(const{resolve:e}of r)e(t);this._requestTracker.pending.delete(e)}}_setPendingRequest(e,t){let r=this._requestTracker.pending.get(e);r??=[],r.push(t),this._requestTracker.pending.set(e,r)}_startRateLimit(){this._rateLimitTimer??=setTimeout((()=>{this._rateLimitTimer=void 0,this._rateLimitCount=0,this._rateLimitedRequestQueue.length>0&&this._releaseRateLimitedRequestQueue()}),1e3),this._rateLimitCount+=1}_trackRequest(e){if(this._requestTracker.active.includes(e))return new Promise((t=>{this._setPendingRequest(e,{resolve:t})}));this._requestTracker.active.push(e)}}const Y=(e,t)=>{const r=new X(e);if(!t)return r;for(const e of Object.keys(t)){const a=t[e];a&&r.createShortcut(e,...a)}return r};export{i as ARRAY_BUFFER_FORMAT,h as BLOB_FORMAT,U as CACHE_CONTROL_HEADER,$ as CLIENT_ERROR_REPSONSE,A as COOKIE_HEADER,m as DEFAULT_BODY_PARSER,d as DEFAULT_FETCH_TIMEOUT,_ as DEFAULT_HEADERS,l as DEFAULT_MAX_REDIRECTS,p as DEFAULT_MAX_RETRIES,R as DEFAULT_PATH_TEMPLATE_REGEX,f as DEFAULT_RATE_LIMIT,g as DEFAULT_REQUEST_RETRY_WAIT,L as DELETE_METHOD,Q as ETAG_HEADER,k as FETCH_METHODS,x as FETCH_TIMEOUT_ERROR,c as FORM_DATA_FORMAT,w as GET_METHOD,X as Getta,N as IF_NONE_MATCH_HEADER,S as INFORMATION_REPSONSE,P as INVALID_FETCH_METHOD_ERROR,o as JSON_FORMAT,j as LOCATION_HEADER,E as MAX_REDIRECTS_EXCEEDED_ERROR,q as MAX_RETRIES_EXCEEDED_ERROR,y as MISSING_BASE_PATH_ERROR,M as NOT_FOUND_STATUS_CODE,F as NOT_MODIFIED_STATUS_CODE,T as OPTIONAL_PATH_TEMPLATE_REGEX,C as POST_METHOD,v as PUT_METHOD,O as REDIRECTION_REPSONSE,I as REQUEST_FAILED,G as REQUEST_SENT,b as RESOURCE_NOT_FOUND_ERROR,B as RESPONSE_FROM_CACHE,W as RESPONSE_RECEIVED,D as SERVER_ERROR_REPSONSE,u as STREAM_READERS,H as SUCCESSFUL_REPSONSE,n as TEXT_FORMAT,Y as createRestClient,J as defaultPathTemplateCallback};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/esm/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../getta/src//constants.ts","../getta/src//helpers/defaultPathTemplateCallback/index.ts","../getta/src//helpers/buildEndpoint/index.ts","../getta/src//main.ts","../getta/src//helpers/getResponseGroup/index.ts","../getta/src//helpers/delay/index.ts","../getta/src//helpers/isCacheabilityValid/index.ts"],"sourcesContent":["import { type PlainObject } from './types.ts';\n\nexport const ARRAY_BUFFER_FORMAT = 'arrayBuffer';\nexport const BLOB_FORMAT = 'blob';\nexport const FORM_DATA_FORMAT = 'formData';\nexport const JSON_FORMAT = 'json';\nexport const TEXT_FORMAT = 'text';\n\nexport const STREAM_READERS = {\n ARRAY_BUFFER_FORMAT,\n BLOB_FORMAT,\n FORM_DATA_FORMAT,\n JSON_FORMAT,\n TEXT_FORMAT,\n};\n\nexport const DEFAULT_BODY_PARSER = (body: PlainObject) => body;\nexport const DEFAULT_FETCH_TIMEOUT = 5000;\nexport const DEFAULT_HEADERS = { 'content-type': 'application/json' };\nexport const DEFAULT_MAX_REDIRECTS = 5;\nexport const DEFAULT_MAX_RETRIES = 3;\nexport const DEFAULT_PATH_TEMPLATE_REGEX = /({type})|({id})|({id,\\+})|({brief\\|standard})/g;\nexport const OPTIONAL_PATH_TEMPLATE_REGEX = /({\\w+\\?})/g;\nexport const DEFAULT_RATE_LIMIT = 50;\nexport const DEFAULT_REQUEST_RETRY_WAIT = 100;\n\nexport const MISSING_BASE_PATH_ERROR = `Getta expected to receive 'basePath' in the constructor options,\n but recevied undefined.`;\n\nexport const MAX_REDIRECTS_EXCEEDED_ERROR = 'The request exceeded the maximum number of redirects, which is';\n\nexport const MAX_RETRIES_EXCEEDED_ERROR = 'The request exceeded the maximum number of retries, which is';\n\nexport const INVALID_FETCH_METHOD_ERROR = \"Getta expected to receive 'get', 'post', 'put' or 'delete', but received\";\n\nexport const RESOURCE_NOT_FOUND_ERROR = 'The requested resource could not been found.';\n\nexport const FETCH_TIMEOUT_ERROR = 'The request timed out. Getta did not get a response within';\n\nexport const GET_METHOD = 'get';\nexport const POST_METHOD = 'post';\nexport const PUT_METHOD = 'put';\nexport const DELETE_METHOD = 'delete';\n\nexport const FETCH_METHODS = [GET_METHOD, POST_METHOD, PUT_METHOD, DELETE_METHOD];\n\nexport const INFORMATION_REPSONSE = 'information';\nexport const SUCCESSFUL_REPSONSE = 'successful';\nexport const REDIRECTION_REPSONSE = 'redirection';\nexport const CLIENT_ERROR_REPSONSE = 'clientError';\nexport const SERVER_ERROR_REPSONSE = 'serverError';\n\nexport const NOT_MODIFIED_STATUS_CODE = 304;\nexport const NOT_FOUND_STATUS_CODE = 404;\n\nexport const COOKIE_HEADER = 'Cookie';\nexport const ETAG_HEADER = 'ETag';\nexport const LOCATION_HEADER = 'Location';\nexport const IF_NONE_MATCH_HEADER = 'If-None-Match';\nexport const CACHE_CONTROL_HEADER = 'Cache-Control';\n\nexport const REQUEST_SENT = 'request_sent';\nexport const RESPONSE_RECEIVED = 'response_received';\nexport const RESPONSE_FROM_CACHE = 'response_from_cache';\nexport const REQUEST_FAILED = 'request_failed';\n","export const defaultPathTemplateCallback = (\n pathTemplate: string,\n data: Record<string, string | number | boolean>,\n pathTemplateRegExp: RegExp,\n) => {\n const dataKeys = Object.keys(data);\n\n return pathTemplate.replace(pathTemplateRegExp, match => {\n for (const key of dataKeys) {\n if (match.includes(key) && data[key] !== undefined) {\n return String(data[key]);\n }\n }\n\n return '';\n });\n};\n","import queryString from 'query-string';\nimport { type BuildEndpointOptions } from './types.ts';\n\nexport const buildEndpoint = (\n basePath: string,\n path: string,\n {\n optionalPathTemplateRegExp,\n pathTemplateCallback,\n pathTemplateData,\n pathTemplateRegExp,\n queryParams,\n }: BuildEndpointOptions,\n) => {\n const pathJoiner = basePath.endsWith('/') || path.startsWith('/') ? '' : '/';\n let endpoint = `${basePath}${pathJoiner}${path}`;\n\n if (pathTemplateData) {\n endpoint = pathTemplateCallback(endpoint, pathTemplateData, pathTemplateRegExp);\n }\n\n endpoint = endpoint.replace(optionalPathTemplateRegExp, '');\n\n if (endpoint.endsWith('/')) {\n endpoint = endpoint.slice(0, Math.max(0, endpoint.length - 1));\n }\n\n if (queryParams && Object.keys(queryParams).length > 0) {\n const queryJoin = queryString.extract(endpoint) ? '&' : '?';\n endpoint = `${endpoint}${queryJoin}${queryString.stringify(queryParams)}`;\n }\n\n return endpoint;\n};\n","import { type CacheHeaders, type Core } from '@cachemap/core';\nimport { type Cacheability } from 'cacheability';\nimport { castArray, merge } from 'lodash-es';\nimport { Md5 } from 'ts-md5';\nimport { type SetRequired } from 'type-fest';\nimport * as consts from './constants.ts';\nimport { buildEndpoint } from './helpers/buildEndpoint/index.ts';\nimport { defaultPathTemplateCallback } from './helpers/defaultPathTemplateCallback/index.ts';\nimport { delay } from './helpers/delay/index.ts';\nimport { getResponseGroup } from './helpers/getResponseGroup/index.ts';\nimport { isCacheabilityValid } from './helpers/isCacheabilityValid/index.ts';\nimport {\n type ConstructorOptions,\n type Context,\n type FetchOptions,\n type FetchRedirectHandlerOptions,\n type FetchResponse,\n type Func,\n type Log,\n type PathTemplateCallback,\n type PendingRequestResolver,\n type PendingRequestResolvers,\n type Performance,\n type PlainObject,\n type RequestOptions,\n type RequestQueue,\n type RequestTracker,\n type ShortcutProperties,\n type Shortcuts,\n type StreamReader,\n} from './types.ts';\n\nexport class Getta {\n private _basePath: string;\n private _bodyParser: Func;\n private _cache?: Core;\n private _conditionalRequestsEnabled: boolean;\n private _fetchTimeout: number;\n private _headers: Record<string, string>;\n private _log: Log | undefined;\n private _maxRedirects: number;\n private _maxRetries: number;\n private _optionalPathTemplateRegExp: RegExp;\n private _pathTemplateCallback: PathTemplateCallback;\n private _pathTemplateRegExp: RegExp;\n private _performance: Performance;\n private _queryParams: PlainObject;\n private _rateLimit: boolean;\n private _rateLimitCount = 0;\n private _rateLimitedRequestQueue: RequestQueue = [];\n private _rateLimitPerSecond: number;\n private _rateLimitTimer: NodeJS.Timer | undefined = undefined;\n private _requestRetryWait: number;\n private _requestTracker: RequestTracker = { active: [], pending: new Map() };\n private _streamReader: StreamReader;\n\n constructor(options: ConstructorOptions) {\n const {\n basePath,\n bodyParser = consts.DEFAULT_BODY_PARSER,\n cache,\n enableConditionalRequests = true,\n fetchTimeout = consts.DEFAULT_FETCH_TIMEOUT,\n headers,\n log,\n maxRedirects = consts.DEFAULT_MAX_REDIRECTS,\n maxRetries = consts.DEFAULT_MAX_RETRIES,\n optionalPathTemplateRegExp = consts.OPTIONAL_PATH_TEMPLATE_REGEX,\n pathTemplateCallback = defaultPathTemplateCallback,\n pathTemplateRegExp = consts.DEFAULT_PATH_TEMPLATE_REGEX,\n performance,\n queryParams = {},\n rateLimit = false,\n rateLimitPerSecond = consts.DEFAULT_RATE_LIMIT,\n requestRetryWait = consts.DEFAULT_REQUEST_RETRY_WAIT,\n streamReader = consts.JSON_FORMAT,\n } = options;\n\n if (!basePath) {\n throw new Error(consts.MISSING_BASE_PATH_ERROR);\n }\n\n this._basePath = basePath;\n this._bodyParser = bodyParser;\n this._cache = cache;\n this._conditionalRequestsEnabled = enableConditionalRequests;\n this._fetchTimeout = fetchTimeout;\n this._headers = { ...consts.DEFAULT_HEADERS, ...headers };\n this._log = log;\n this._maxRedirects = maxRedirects;\n this._maxRetries = maxRetries;\n this._optionalPathTemplateRegExp = optionalPathTemplateRegExp;\n this._pathTemplateCallback = pathTemplateCallback;\n this._pathTemplateRegExp = pathTemplateRegExp;\n this._performance = performance;\n this._queryParams = queryParams;\n this._rateLimit = rateLimit;\n this._rateLimitPerSecond = rateLimitPerSecond;\n this._requestRetryWait = requestRetryWait;\n this._streamReader = streamReader;\n }\n\n get cache(): Core | undefined {\n return this._cache;\n }\n\n public createShortcut(\n name: string,\n path: string,\n { method, ...otherOptions }: SetRequired<RequestOptions, 'method'>,\n ) {\n if (!consts.FETCH_METHODS.includes(method)) {\n throw new Error(`${consts.INVALID_FETCH_METHOD_ERROR} ${method}`);\n }\n\n // @ts-expect-error No index signature with a parameter of type 'string'\n this[name] = async <Resource extends PlainObject>(\n { method: requestMethod, ...otherOptionOverrides }: RequestOptions = {},\n context?: Context,\n ) =>\n // @ts-expect-error Type 'undefined' is not assignable to type 'BodyInit'\n // To generic and complex to type without casting.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n this[requestMethod ?? method](path, merge({}, otherOptions, otherOptionOverrides), context) as Promise<\n FetchResponse<Resource>\n >;\n }\n\n public async delete(path: string, options: Omit<RequestOptions, 'method'> = {}, context?: Context) {\n return this._delete(path, options, context);\n }\n\n public async get(path: string, options: Omit<RequestOptions, 'method'> = {}, context?: Context) {\n return this._get(path, options, context);\n }\n\n public async post(path: string, options: Omit<SetRequired<RequestOptions, 'body'>, 'method'>, context?: Context) {\n return this._request(path, { ...options, method: consts.POST_METHOD }, context);\n }\n\n public async put(path: string, options: Omit<SetRequired<RequestOptions, 'body'>, 'methood'>, context?: Context) {\n return this._request(path, { ...options, method: consts.PUT_METHOD }, context);\n }\n\n private _addRequestToRateLimitedQueue(endpoint: string, options: FetchOptions, context: Context) {\n return new Promise((resolve: (value: FetchResponse) => void) => {\n this._rateLimitedRequestQueue.push([resolve, endpoint, options, context]);\n });\n }\n\n private async _cacheEntryDelete(requestHash: string): Promise<boolean> {\n if (!this._cache) {\n return false;\n }\n\n return this._cache.delete(requestHash);\n }\n\n private async _cacheEntryGet(requestHash: string): Promise<PlainObject | undefined> {\n if (!this._cache) {\n return undefined;\n }\n\n return this._cache.get(requestHash);\n }\n\n private async _cacheEntryHas(requestHash: string): Promise<Cacheability | false> {\n if (!this._cache) {\n return false;\n }\n\n try {\n return await this._cache.has(requestHash);\n } catch {\n return false;\n }\n }\n\n private async _cacheEntrySet(requestHash: string, data: PlainObject, cacheHeaders: CacheHeaders): Promise<void> {\n if (!this._cache) {\n return undefined;\n }\n\n return this._cache.set(requestHash, data, { cacheHeaders });\n }\n\n private async _delete(\n path: string,\n { headers = {}, pathTemplateData, queryParams = {}, ...rest }: Omit<RequestOptions, 'method'>,\n context?: Context,\n ) {\n const endpoint = buildEndpoint(this._basePath, path, {\n optionalPathTemplateRegExp: this._optionalPathTemplateRegExp,\n pathTemplateCallback: this._pathTemplateCallback,\n pathTemplateData,\n pathTemplateRegExp: this._pathTemplateRegExp,\n queryParams: { ...this._queryParams, ...queryParams },\n });\n\n const requestHash = Md5.hashStr(endpoint);\n const cacheability = await this._cacheEntryHas(requestHash);\n\n if (cacheability) {\n void this._cacheEntryDelete(requestHash);\n }\n\n return this._fetch(\n endpoint,\n {\n headers: { ...this._headers, ...headers },\n method: consts.DELETE_METHOD,\n ...rest,\n },\n context,\n );\n }\n\n private async _fetch(endpoint: string, options: FetchOptions, context: Context = {}): Promise<FetchResponse> {\n context.startTime = this._performance.now();\n\n try {\n const { redirects, retries, ...rest } = options;\n\n return await new Promise<FetchResponse>((resolve, reject) => {\n void (async () => {\n const fetchTimer = setTimeout(() => {\n reject(new Error(`${consts.FETCH_TIMEOUT_ERROR} ${String(this._fetchTimeout)}ms.`));\n }, this._fetchTimeout);\n\n if (this._rateLimit) {\n this._startRateLimit();\n\n if (!(this._rateLimitCount < this._rateLimitPerSecond)) {\n clearTimeout(fetchTimer);\n resolve(await this._addRequestToRateLimitedQueue(endpoint, options, context));\n return;\n }\n }\n\n if (!redirects && !retries) {\n this._log?.(consts.REQUEST_SENT, {\n context: {\n fetchMethod: rest.method,\n fetchRedirets: redirects,\n fetchRequestHeaders: rest.headers,\n fetchRetries: retries,\n fetchUrl: endpoint,\n logEntryName: 'FETCH_REQUEST_SENT',\n ...context,\n },\n stats: { startTime: context.startTime },\n });\n }\n\n // Casting as fetch response does not support generics.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const res = (await fetch(endpoint, rest)) as FetchResponse;\n\n clearTimeout(fetchTimer);\n\n const { body, headers, status } = res;\n const responseGroup = getResponseGroup(status);\n\n if (responseGroup === consts.REDIRECTION_REPSONSE && headers.has(consts.LOCATION_HEADER)) {\n resolve(\n await this._fetchRedirectHandler(\n res,\n // Has check above means this cannot be undefined.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n headers.get(consts.LOCATION_HEADER)!,\n {\n redirects,\n status,\n ...rest,\n },\n context,\n ),\n );\n\n return;\n }\n\n if (responseGroup === consts.SERVER_ERROR_REPSONSE) {\n resolve(\n await this._fetchRetryHandler(\n res,\n endpoint,\n {\n retries,\n ...rest,\n },\n context,\n ),\n );\n\n return;\n }\n\n try {\n Object.defineProperty(res, 'data', {\n enumerable: true,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n value: body ? this._bodyParser(await res[this._streamReader]()) : undefined,\n writable: true,\n });\n\n this._logResponse(res, endpoint, options, context);\n resolve(res);\n } catch (error) {\n if (error instanceof Error) {\n reject(error);\n } else {\n reject(new Error(`Unable to ${rest.method} ${endpoint} due to previous error`));\n }\n }\n })();\n });\n } catch (error) {\n const { startTime, ...rest } = context;\n const endTime = this._performance.now();\n\n this._log?.(consts.REQUEST_FAILED, {\n context: { error, fetchUrl: endpoint, logEntryName: 'FETCH_REQUEST_FAILED', ...rest },\n stats: { duration: startTime ? endTime - startTime : 0, endTime, startTime },\n });\n\n // Based on above code, error is going to be a type of Error.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return { errors: castArray(error) } as FetchResponse;\n }\n }\n\n private async _fetchRedirectHandler(\n res: FetchResponse,\n endpoint: string,\n options: FetchRedirectHandlerOptions,\n context: Context,\n ): Promise<FetchResponse> {\n const { method, redirects = 1, status, ...rest } = options;\n\n if (redirects === this._maxRedirects) {\n res.errors = [new Error(`${consts.MAX_REDIRECTS_EXCEEDED_ERROR} ${String(this._maxRedirects)}.`)];\n this._logResponse(res, endpoint, options, context);\n return res;\n }\n\n const redirectMethod = status === 303 ? consts.GET_METHOD : method;\n return this._fetch(endpoint, { method: redirectMethod, redirects: redirects + 1, ...rest });\n }\n\n private async _fetchRetryHandler(res: FetchResponse, endpoint: string, options: FetchOptions, context: Context) {\n const { retries = 1, ...rest } = options;\n\n if (retries === this._maxRetries) {\n res.errors = [new Error(`${consts.MAX_RETRIES_EXCEEDED_ERROR} ${String(this._maxRetries)}.`)];\n this._logResponse(res, endpoint, options, context);\n return res;\n }\n\n await delay(this._requestRetryWait);\n return this._fetch(endpoint, { retries: retries + 1, ...rest });\n }\n\n private async _get(\n path: string,\n { headers = {}, pathTemplateData, queryParams = {} }: Omit<RequestOptions, 'method'>,\n context?: Context,\n ) {\n const endpoint = buildEndpoint(this._basePath, path, {\n optionalPathTemplateRegExp: this._optionalPathTemplateRegExp,\n pathTemplateCallback: this._pathTemplateCallback,\n pathTemplateData,\n pathTemplateRegExp: this._pathTemplateRegExp,\n queryParams: { ...this._queryParams, ...queryParams },\n });\n\n const requestHash = Md5.hashStr(endpoint);\n const cacheability = await this._cacheEntryHas(requestHash);\n\n if (cacheability) {\n if (isCacheabilityValid(cacheability)) {\n const newHeaders = {\n ...headers,\n 'cache-control': cacheability.printCacheControl(),\n };\n\n this._log?.(consts.RESPONSE_FROM_CACHE, {\n context: {\n fetchMethod: consts.GET_METHOD,\n fetchResponseHeaders: newHeaders,\n fetchUrl: endpoint,\n logEntryName: 'FETCH_RESPONSE_FROM_CACHE',\n ...context,\n },\n });\n\n return {\n data: await this._cacheEntryGet(requestHash),\n headers: new Headers(newHeaders),\n };\n }\n\n if (this._conditionalRequestsEnabled && cacheability.metadata.etag) {\n headers[consts.IF_NONE_MATCH_HEADER] = cacheability.metadata.etag;\n }\n }\n\n const pendingRequest = this._trackRequest(requestHash);\n\n if (pendingRequest) {\n return pendingRequest;\n }\n\n return this._getResolve(\n requestHash,\n await this._fetch(endpoint, { headers: { ...this._headers, ...headers }, method: consts.GET_METHOD }, context),\n );\n }\n\n private async _getResolve(requestHash: string, res: FetchResponse) {\n const { data, headers, status } = res;\n\n if (status === consts.NOT_FOUND_STATUS_CODE) {\n void this._cacheEntryDelete(requestHash);\n let { errors } = res;\n\n if (!errors) {\n errors = [];\n }\n\n errors.push(new Error(consts.RESOURCE_NOT_FOUND_ERROR));\n res.errors = errors;\n } else if (status === consts.NOT_MODIFIED_STATUS_CODE) {\n const cachedData = await this._cacheEntryGet(requestHash);\n\n if (cachedData) {\n void this._cacheEntrySet(requestHash, cachedData, {\n cacheControl: headers.get(consts.CACHE_CONTROL_HEADER) ?? undefined,\n etag: headers.get(consts.ETAG_HEADER) ?? undefined,\n });\n\n res.data = cachedData;\n }\n } else if (data) {\n void this._cacheEntrySet(requestHash, data, {\n cacheControl: headers.get(consts.CACHE_CONTROL_HEADER) ?? undefined,\n etag: headers.get(consts.ETAG_HEADER) ?? undefined,\n });\n }\n\n this._resolvePendingRequests(requestHash, res);\n this._requestTracker.active = this._requestTracker.active.filter(value => value !== requestHash);\n return res;\n }\n\n private _logResponse(res: FetchResponse, endpoint: string, options: FetchOptions, context: Context) {\n const { headers, status } = res;\n const { method, redirects, retries } = options;\n const { startTime, ...otherContext } = context;\n const endTime = this._performance.now();\n const duration = startTime ? endTime - startTime : 0;\n\n this._log?.(consts.RESPONSE_RECEIVED, {\n context: {\n fetchMethod: method,\n fetchRedirects: redirects,\n fetchResponseHeaders: Object.fromEntries(headers.entries()),\n fetchResponseStatus: status,\n fetchRetries: retries,\n fetchUrl: endpoint,\n logEntryName: 'FETCH_RESPONSE_RECEIVED',\n ...otherContext,\n },\n stats: { duration, endTime, startTime },\n });\n }\n\n private async _releaseRateLimitedRequestQueue() {\n for (const [resolve, endpoint, options, context] of this._rateLimitedRequestQueue) {\n resolve(await this._fetch(endpoint, options, context));\n }\n\n this._rateLimitedRequestQueue = [];\n }\n\n private async _request(\n path: string,\n { body, headers, method, pathTemplateData, queryParams, ...rest }: SetRequired<RequestOptions, 'method'>,\n context?: Context,\n ) {\n const endpoint = buildEndpoint(this._basePath, path, {\n optionalPathTemplateRegExp: this._optionalPathTemplateRegExp,\n pathTemplateCallback: this._pathTemplateCallback,\n pathTemplateData,\n pathTemplateRegExp: this._pathTemplateRegExp,\n queryParams: { ...this._queryParams, ...queryParams },\n });\n\n return this._fetch(\n endpoint,\n {\n body,\n headers: { ...this._headers, ...headers },\n method,\n ...rest,\n },\n context,\n );\n }\n\n private _resolvePendingRequests(requestHash: string, responseData: FetchResponse) {\n const pendingRequests = this._requestTracker.pending.get(requestHash);\n\n if (!pendingRequests) {\n return;\n }\n\n for (const { resolve } of pendingRequests) {\n resolve(responseData);\n }\n\n this._requestTracker.pending.delete(requestHash);\n }\n\n private _setPendingRequest(requestHash: string, resolver: PendingRequestResolvers) {\n let pending = this._requestTracker.pending.get(requestHash);\n if (!pending) pending = [];\n pending.push(resolver);\n this._requestTracker.pending.set(requestHash, pending);\n }\n\n private _startRateLimit() {\n if (!this._rateLimitTimer) {\n this._rateLimitTimer = setTimeout(() => {\n this._rateLimitTimer = undefined;\n this._rateLimitCount = 0;\n\n if (this._rateLimitedRequestQueue.length > 0) {\n void this._releaseRateLimitedRequestQueue();\n }\n }, 1000);\n }\n\n this._rateLimitCount += 1;\n }\n\n private _trackRequest(requestHash: string): Promise<FetchResponse> | undefined {\n if (this._requestTracker.active.includes(requestHash)) {\n return new Promise((resolve: PendingRequestResolver) => {\n this._setPendingRequest(requestHash, { resolve });\n });\n }\n\n this._requestTracker.active.push(requestHash);\n return;\n }\n}\n\nexport const createRestClient = <N extends string>(options: ConstructorOptions, shortcuts?: Shortcuts) => {\n // Typing proving too complex without casting.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const getta = new Getta(options) as Getta & ShortcutProperties<N>;\n\n if (!shortcuts) {\n return getta;\n }\n\n for (const key of Object.keys(shortcuts)) {\n const shortcut = shortcuts[key];\n\n if (shortcut) {\n getta.createShortcut(key, ...shortcut);\n }\n }\n\n return getta;\n};\n","import * as consts from '../../constants.ts';\n\nexport const getResponseGroup = (status: number) => {\n switch (true) {\n case status < 200: {\n return consts.INFORMATION_REPSONSE;\n }\n\n case status < 300: {\n return consts.SUCCESSFUL_REPSONSE;\n }\n\n case status < 400: {\n return consts.REDIRECTION_REPSONSE;\n }\n\n case status < 500: {\n return consts.CLIENT_ERROR_REPSONSE;\n }\n\n default: {\n return consts.SERVER_ERROR_REPSONSE;\n }\n }\n};\n","export const delay = (ms: number) => {\n return new Promise(resolve => setTimeout(resolve, ms));\n};\n","import { type Cacheability } from 'cacheability';\n\nexport const isCacheabilityValid = (cacheability: Cacheability) => {\n const noCache = cacheability.metadata.cacheControl.noCache ?? false;\n return !noCache && cacheability.checkTTL();\n};\n"],"names":["ARRAY_BUFFER_FORMAT","BLOB_FORMAT","FORM_DATA_FORMAT","JSON_FORMAT","TEXT_FORMAT","STREAM_READERS","DEFAULT_BODY_PARSER","body","DEFAULT_FETCH_TIMEOUT","DEFAULT_HEADERS","DEFAULT_MAX_REDIRECTS","DEFAULT_MAX_RETRIES","DEFAULT_PATH_TEMPLATE_REGEX","OPTIONAL_PATH_TEMPLATE_REGEX","DEFAULT_RATE_LIMIT","DEFAULT_REQUEST_RETRY_WAIT","MISSING_BASE_PATH_ERROR","MAX_REDIRECTS_EXCEEDED_ERROR","MAX_RETRIES_EXCEEDED_ERROR","INVALID_FETCH_METHOD_ERROR","RESOURCE_NOT_FOUND_ERROR","FETCH_TIMEOUT_ERROR","GET_METHOD","POST_METHOD","PUT_METHOD","DELETE_METHOD","FETCH_METHODS","INFORMATION_REPSONSE","SUCCESSFUL_REPSONSE","REDIRECTION_REPSONSE","CLIENT_ERROR_REPSONSE","SERVER_ERROR_REPSONSE","NOT_MODIFIED_STATUS_CODE","NOT_FOUND_STATUS_CODE","COOKIE_HEADER","ETAG_HEADER","LOCATION_HEADER","IF_NONE_MATCH_HEADER","CACHE_CONTROL_HEADER","REQUEST_SENT","RESPONSE_RECEIVED","RESPONSE_FROM_CACHE","REQUEST_FAILED","defaultPathTemplateCallback","pathTemplate","data","pathTemplateRegExp","dataKeys","Object","keys","replace","match","key","includes","undefined","String","buildEndpoint","basePath","path","optionalPathTemplateRegExp","pathTemplateCallback","pathTemplateData","queryParams","pathJoiner","endsWith","startsWith","endpoint","slice","Math","max","length","queryString","extract","stringify","Getta","constructor","options","_rateLimitCount","_rateLimitedRequestQueue","_rateLimitTimer","_requestTracker","active","pending","Map","bodyParser","consts","cache","enableConditionalRequests","fetchTimeout","headers","log","maxRedirects","maxRetries","performance","rateLimit","rateLimitPerSecond","requestRetryWait","streamReader","Error","this","_basePath","_bodyParser","_cache","_conditionalRequestsEnabled","_fetchTimeout","_headers","_log","_maxRedirects","_maxRetries","_optionalPathTemplateRegExp","_pathTemplateCallback","_pathTemplateRegExp","_performance","_queryParams","_rateLimit","_rateLimitPerSecond","_requestRetryWait","_streamReader","createShortcut","name","method","otherOptions","async","requestMethod","otherOptionOverrides","context","merge","delete","_delete","get","_get","post","_request","put","_addRequestToRateLimitedQueue","Promise","resolve","push","_cacheEntryDelete","requestHash","_cacheEntryGet","_cacheEntryHas","has","_cacheEntrySet","cacheHeaders","set","rest","Md5","hashStr","_fetch","startTime","now","redirects","retries","reject","fetchTimer","setTimeout","_startRateLimit","clearTimeout","fetchMethod","fetchRedirets","fetchRequestHeaders","fetchRetries","fetchUrl","logEntryName","stats","res","fetch","status","responseGroup","getResponseGroup","_fetchRedirectHandler","defineProperty","enumerable","value","writable","_logResponse","error","_fetchRetryHandler","endTime","duration","errors","castArray","redirectMethod","ms","cacheability","metadata","cacheControl","noCache","checkTTL","isCacheabilityValid","newHeaders","printCacheControl","fetchResponseHeaders","Headers","etag","pendingRequest","_trackRequest","_getResolve","cachedData","_resolvePendingRequests","filter","otherContext","fetchRedirects","fromEntries","entries","fetchResponseStatus","_releaseRateLimitedRequestQueue","responseData","pendingRequests","_setPendingRequest","resolver","createRestClient","shortcuts","getta","shortcut"],"mappings":"mJAEO,MAAMA,EAAsB,cACtBC,EAAc,OACdC,EAAmB,WACnBC,EAAc,OACdC,EAAc,OAEdC,EAAiB,CAC5BL,sBACAC,cACAC,mBACAC,cACAC,eAGWE,EAAuBC,GAAsBA,EAC7CC,EAAwB,IACxBC,EAAkB,CAAE,eAAgB,oBACpCC,EAAwB,EACxBC,EAAsB,EACtBC,EAA8B,iDAC9BC,EAA+B,aAC/BC,EAAqB,GACrBC,EAA6B,IAE7BC,EAA0B,8FAG1BC,EAA+B,iEAE/BC,EAA6B,+DAE7BC,EAA6B,2EAE7BC,EAA2B,+CAE3BC,EAAsB,6DAEtBC,EAAa,MACbC,EAAc,OACdC,EAAa,MACbC,EAAgB,SAEhBC,EAAgB,CAACJ,EAAYC,EAAaC,EAAYC,GAEtDE,EAAuB,cACvBC,EAAsB,aACtBC,EAAuB,cACvBC,EAAwB,cACxBC,EAAwB,cAExBC,EAA2B,IAC3BC,EAAwB,IAExBC,EAAgB,SAChBC,EAAc,OACdC,EAAkB,WAClBC,EAAuB,gBACvBC,EAAuB,gBAEvBC,EAAe,eACfC,EAAoB,oBACpBC,EAAsB,sBACtBC,EAAiB,iBChEjBC,EAA8B,CACzCC,EACAC,EACAC,KAEA,MAAMC,EAAWC,OAAOC,KAAKJ,GAE7B,OAAOD,EAAaM,QAAQJ,GAAoBK,IAC9C,IAAK,MAAMC,KAAOL,EAChB,GAAII,EAAME,SAASD,SAAs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,EAAME,GAExB,IAAKyI,EACH,OAAOC,EAGT,IAAK,MAAMlK,KAAOJ,OAAOC,KAAKoK,GAAY,CACxC,MAAME,EAAWF,EAAUjK,GAEvBmK,GACFD,EAAMhG,eAAelE,KAAQmK,EAEjC,CAEA,OAAOD,CAAAA"}
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../getta/src//constants.ts","../getta/src//helpers/defaultPathTemplateCallback/index.ts","../getta/src//helpers/buildEndpoint/index.ts","../getta/src//main.ts","../getta/src//helpers/getResponseGroup/index.ts","../getta/src//helpers/delay/index.ts","../getta/src//helpers/isCacheabilityValid/index.ts"],"sourcesContent":["import { type PlainObject } from './types.ts';\n\nexport const ARRAY_BUFFER_FORMAT = 'arrayBuffer';\nexport const BLOB_FORMAT = 'blob';\nexport const FORM_DATA_FORMAT = 'formData';\nexport const JSON_FORMAT = 'json';\nexport const TEXT_FORMAT = 'text';\n\nexport const STREAM_READERS = {\n ARRAY_BUFFER_FORMAT,\n BLOB_FORMAT,\n FORM_DATA_FORMAT,\n JSON_FORMAT,\n TEXT_FORMAT,\n};\n\nexport const DEFAULT_BODY_PARSER = (body: PlainObject) => body;\nexport const DEFAULT_FETCH_TIMEOUT = 5000;\nexport const DEFAULT_HEADERS = { 'content-type': 'application/json' };\nexport const DEFAULT_MAX_REDIRECTS = 5;\nexport const DEFAULT_MAX_RETRIES = 3;\nexport const DEFAULT_PATH_TEMPLATE_REGEX = /({type})|({id})|({id,\\+})|({brief\\|standard})/g;\nexport const OPTIONAL_PATH_TEMPLATE_REGEX = /({\\w+\\?})/g;\nexport const DEFAULT_RATE_LIMIT = 50;\nexport const DEFAULT_REQUEST_RETRY_WAIT = 100;\n\nexport const MISSING_BASE_PATH_ERROR = `Getta expected to receive 'basePath' in the constructor options,\n but recevied undefined.`;\n\nexport const MAX_REDIRECTS_EXCEEDED_ERROR = 'The request exceeded the maximum number of redirects, which is';\n\nexport const MAX_RETRIES_EXCEEDED_ERROR = 'The request exceeded the maximum number of retries, which is';\n\nexport const INVALID_FETCH_METHOD_ERROR = \"Getta expected to receive 'get', 'post', 'put' or 'delete', but received\";\n\nexport const RESOURCE_NOT_FOUND_ERROR = 'The requested resource could not been found.';\n\nexport const FETCH_TIMEOUT_ERROR = 'The request timed out. Getta did not get a response within';\n\nexport const GET_METHOD = 'get';\nexport const POST_METHOD = 'post';\nexport const PUT_METHOD = 'put';\nexport const DELETE_METHOD = 'delete';\n\nexport const FETCH_METHODS = [GET_METHOD, POST_METHOD, PUT_METHOD, DELETE_METHOD];\n\nexport const INFORMATION_REPSONSE = 'information';\nexport const SUCCESSFUL_REPSONSE = 'successful';\nexport const REDIRECTION_REPSONSE = 'redirection';\nexport const CLIENT_ERROR_REPSONSE = 'clientError';\nexport const SERVER_ERROR_REPSONSE = 'serverError';\n\nexport const NOT_MODIFIED_STATUS_CODE = 304;\nexport const NOT_FOUND_STATUS_CODE = 404;\n\nexport const COOKIE_HEADER = 'Cookie';\nexport const ETAG_HEADER = 'ETag';\nexport const LOCATION_HEADER = 'Location';\nexport const IF_NONE_MATCH_HEADER = 'If-None-Match';\nexport const CACHE_CONTROL_HEADER = 'Cache-Control';\n\nexport const REQUEST_SENT = 'request_sent';\nexport const RESPONSE_RECEIVED = 'response_received';\nexport const RESPONSE_FROM_CACHE = 'response_from_cache';\nexport const REQUEST_FAILED = 'request_failed';\n","export const defaultPathTemplateCallback = (\n pathTemplate: string,\n data: Record<string, string | number | boolean>,\n pathTemplateRegExp: RegExp,\n) => {\n const dataKeys = Object.keys(data);\n\n return pathTemplate.replace(pathTemplateRegExp, match => {\n for (const key of dataKeys) {\n if (match.includes(key) && data[key] !== undefined) {\n return String(data[key]);\n }\n }\n\n return '';\n });\n};\n","import { omitBy } from 'lodash-es';\nimport queryString from 'query-string';\nimport { type PlainObject } from '#types.ts';\nimport { type BuildEndpointOptions } from './types.ts';\n\nexport const buildEndpoint = (\n basePath: string,\n path: string,\n {\n optionalPathTemplateRegExp,\n pathTemplateCallback,\n pathTemplateData,\n pathTemplateRegExp,\n queryParams = {},\n }: BuildEndpointOptions,\n) => {\n const pathJoiner = basePath.endsWith('/') || path.startsWith('/') ? '' : '/';\n let endpoint = `${basePath}${pathJoiner}${path}`;\n\n if (pathTemplateData) {\n endpoint = pathTemplateCallback(endpoint, pathTemplateData, pathTemplateRegExp);\n }\n\n endpoint = endpoint.replace(optionalPathTemplateRegExp, '');\n\n if (endpoint.endsWith('/')) {\n endpoint = endpoint.slice(0, Math.max(0, endpoint.length - 1));\n }\n\n const sanitisedSearchParams = omitBy<PlainObject>(queryParams, entry => !entry);\n\n if (Object.keys(sanitisedSearchParams).length > 0) {\n const queryJoin = queryString.extract(endpoint) ? '&' : '?';\n endpoint = `${endpoint}${queryJoin}${queryString.stringify(sanitisedSearchParams)}`;\n }\n\n return endpoint;\n};\n","import { type CacheHeaders, type Core } from '@cachemap/core';\nimport { type Cacheability } from 'cacheability';\nimport { castArray, merge } from 'lodash-es';\nimport { Md5 } from 'ts-md5';\nimport { type SetRequired } from 'type-fest';\nimport * as consts from './constants.ts';\nimport { buildEndpoint } from './helpers/buildEndpoint/index.ts';\nimport { defaultPathTemplateCallback } from './helpers/defaultPathTemplateCallback/index.ts';\nimport { delay } from './helpers/delay/index.ts';\nimport { getResponseGroup } from './helpers/getResponseGroup/index.ts';\nimport { isCacheabilityValid } from './helpers/isCacheabilityValid/index.ts';\nimport {\n type ConstructorOptions,\n type Context,\n type FetchOptions,\n type FetchRedirectHandlerOptions,\n type FetchResponse,\n type Func,\n type Log,\n type PathTemplateCallback,\n type PendingRequestResolver,\n type PendingRequestResolvers,\n type Performance,\n type PlainObject,\n type RequestOptions,\n type RequestQueue,\n type RequestTracker,\n type ShortcutProperties,\n type Shortcuts,\n type StreamReader,\n} from './types.ts';\n\nexport class Getta {\n private _basePath: string;\n private _bodyParser: Func;\n private _cache?: Core;\n private _conditionalRequestsEnabled: boolean;\n private _fetchTimeout: number;\n private _headers: Record<string, string>;\n private _log: Log | undefined;\n private _maxRedirects: number;\n private _maxRetries: number;\n private _optionalPathTemplateRegExp: RegExp;\n private _pathTemplateCallback: PathTemplateCallback;\n private _pathTemplateRegExp: RegExp;\n private _performance: Performance;\n private _queryParams: PlainObject;\n private _rateLimit: boolean;\n private _rateLimitCount = 0;\n private _rateLimitedRequestQueue: RequestQueue = [];\n private _rateLimitPerSecond: number;\n private _rateLimitTimer: NodeJS.Timeout | undefined = undefined;\n private _requestRetryWait: number;\n private _requestTracker: RequestTracker = { active: [], pending: new Map() };\n private _streamReader: StreamReader;\n\n constructor(options: ConstructorOptions) {\n const {\n basePath,\n bodyParser = consts.DEFAULT_BODY_PARSER,\n cache,\n enableConditionalRequests = true,\n fetchTimeout = consts.DEFAULT_FETCH_TIMEOUT,\n headers,\n log,\n maxRedirects = consts.DEFAULT_MAX_REDIRECTS,\n maxRetries = consts.DEFAULT_MAX_RETRIES,\n optionalPathTemplateRegExp = consts.OPTIONAL_PATH_TEMPLATE_REGEX,\n pathTemplateCallback = defaultPathTemplateCallback,\n pathTemplateRegExp = consts.DEFAULT_PATH_TEMPLATE_REGEX,\n performance,\n queryParams = {},\n rateLimit = false,\n rateLimitPerSecond = consts.DEFAULT_RATE_LIMIT,\n requestRetryWait = consts.DEFAULT_REQUEST_RETRY_WAIT,\n streamReader = consts.JSON_FORMAT,\n } = options;\n\n if (!basePath) {\n throw new Error(consts.MISSING_BASE_PATH_ERROR);\n }\n\n this._basePath = basePath;\n this._bodyParser = bodyParser;\n this._cache = cache;\n this._conditionalRequestsEnabled = enableConditionalRequests;\n this._fetchTimeout = fetchTimeout;\n this._headers = { ...consts.DEFAULT_HEADERS, ...headers };\n this._log = log;\n this._maxRedirects = maxRedirects;\n this._maxRetries = maxRetries;\n this._optionalPathTemplateRegExp = optionalPathTemplateRegExp;\n this._pathTemplateCallback = pathTemplateCallback;\n this._pathTemplateRegExp = pathTemplateRegExp;\n this._performance = performance;\n this._queryParams = queryParams;\n this._rateLimit = rateLimit;\n this._rateLimitPerSecond = rateLimitPerSecond;\n this._requestRetryWait = requestRetryWait;\n this._streamReader = streamReader;\n }\n\n get cache(): Core | undefined {\n return this._cache;\n }\n\n public createShortcut(\n name: string,\n path: string,\n { method, ...otherOptions }: SetRequired<RequestOptions, 'method'>,\n ) {\n if (!consts.FETCH_METHODS.includes(method)) {\n throw new Error(`${consts.INVALID_FETCH_METHOD_ERROR} ${method}`);\n }\n\n // @ts-expect-error No index signature with a parameter of type 'string'\n this[name] = async <Resource extends PlainObject>(\n { method: requestMethod, ...otherOptionOverrides }: RequestOptions = {},\n context?: Context,\n ) =>\n // @ts-expect-error Type 'undefined' is not assignable to type 'BodyInit'\n // To generic and complex to type without casting.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n this[requestMethod ?? method](path, merge({}, otherOptions, otherOptionOverrides), context) as Promise<\n FetchResponse<Resource>\n >;\n }\n\n public async delete(path: string, options: Omit<RequestOptions, 'method'> = {}, context?: Context) {\n return this._delete(path, options, context);\n }\n\n public async get(path: string, options: Omit<RequestOptions, 'method'> = {}, context?: Context) {\n return this._get(path, options, context);\n }\n\n public async post(path: string, options: Omit<SetRequired<RequestOptions, 'body'>, 'method'>, context?: Context) {\n return this._request(path, { ...options, method: consts.POST_METHOD }, context);\n }\n\n public async put(path: string, options: Omit<SetRequired<RequestOptions, 'body'>, 'methood'>, context?: Context) {\n return this._request(path, { ...options, method: consts.PUT_METHOD }, context);\n }\n\n private _addRequestToRateLimitedQueue(endpoint: string, options: FetchOptions, context: Context) {\n return new Promise((resolve: (value: FetchResponse) => void) => {\n this._rateLimitedRequestQueue.push([resolve, endpoint, options, context]);\n });\n }\n\n private async _cacheEntryDelete(requestHash: string): Promise<boolean> {\n if (!this._cache) {\n return false;\n }\n\n return this._cache.delete(requestHash);\n }\n\n private async _cacheEntryGet(requestHash: string): Promise<PlainObject | undefined> {\n if (!this._cache) {\n return undefined;\n }\n\n return this._cache.get(requestHash);\n }\n\n private async _cacheEntryHas(requestHash: string): Promise<Cacheability | false> {\n if (!this._cache) {\n return false;\n }\n\n try {\n return await this._cache.has(requestHash);\n } catch {\n return false;\n }\n }\n\n private async _cacheEntrySet(requestHash: string, data: PlainObject, cacheHeaders: CacheHeaders): Promise<void> {\n if (!this._cache) {\n return undefined;\n }\n\n return this._cache.set(requestHash, data, { cacheHeaders });\n }\n\n private async _delete(\n path: string,\n { headers = {}, pathTemplateData, queryParams = {}, ...rest }: Omit<RequestOptions, 'method'>,\n context?: Context,\n ) {\n const endpoint = buildEndpoint(this._basePath, path, {\n optionalPathTemplateRegExp: this._optionalPathTemplateRegExp,\n pathTemplateCallback: this._pathTemplateCallback,\n pathTemplateData,\n pathTemplateRegExp: this._pathTemplateRegExp,\n queryParams: { ...this._queryParams, ...queryParams },\n });\n\n const requestHash = Md5.hashStr(endpoint);\n const cacheability = await this._cacheEntryHas(requestHash);\n\n if (cacheability) {\n void this._cacheEntryDelete(requestHash);\n }\n\n return this._fetch(\n endpoint,\n {\n headers: { ...this._headers, ...headers },\n method: consts.DELETE_METHOD,\n ...rest,\n },\n context,\n );\n }\n\n private async _fetch(endpoint: string, options: FetchOptions, context: Context = {}): Promise<FetchResponse> {\n context.startTime = this._performance.now();\n\n try {\n const { redirects, retries, ...rest } = options;\n\n return await new Promise<FetchResponse>((resolve, reject) => {\n void (async () => {\n const fetchTimer = setTimeout(() => {\n reject(new Error(`${consts.FETCH_TIMEOUT_ERROR} ${String(this._fetchTimeout)}ms.`));\n }, this._fetchTimeout);\n\n if (this._rateLimit) {\n this._startRateLimit();\n\n if (!(this._rateLimitCount < this._rateLimitPerSecond)) {\n clearTimeout(fetchTimer);\n resolve(await this._addRequestToRateLimitedQueue(endpoint, options, context));\n return;\n }\n }\n\n if (!redirects && !retries) {\n this._log?.(consts.REQUEST_SENT, {\n context: {\n fetchMethod: rest.method,\n fetchRedirets: redirects,\n fetchRequestHeaders: rest.headers,\n fetchRetries: retries,\n fetchUrl: endpoint,\n logEntryName: 'FETCH_REQUEST_SENT',\n ...context,\n },\n stats: { startTime: context.startTime },\n });\n }\n\n // Casting as fetch response does not support generics.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const res = (await fetch(endpoint, rest)) as FetchResponse;\n\n clearTimeout(fetchTimer);\n\n const { body, headers, status } = res;\n const responseGroup = getResponseGroup(status);\n\n if (responseGroup === consts.REDIRECTION_REPSONSE && headers.has(consts.LOCATION_HEADER)) {\n resolve(\n await this._fetchRedirectHandler(\n res,\n // Has check above means this cannot be undefined.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n headers.get(consts.LOCATION_HEADER)!,\n {\n redirects,\n status,\n ...rest,\n },\n context,\n ),\n );\n\n return;\n }\n\n if (responseGroup === consts.SERVER_ERROR_REPSONSE) {\n resolve(\n await this._fetchRetryHandler(\n res,\n endpoint,\n {\n retries,\n ...rest,\n },\n context,\n ),\n );\n\n return;\n }\n\n try {\n Object.defineProperty(res, 'data', {\n enumerable: true,\n\n value: body ? this._bodyParser(await res[this._streamReader]()) : undefined,\n writable: true,\n });\n\n this._logResponse(res, endpoint, options, context);\n resolve(res);\n } catch (error) {\n if (error instanceof Error) {\n reject(error);\n } else {\n reject(new Error(`Unable to ${rest.method} ${endpoint} due to previous error`));\n }\n }\n })();\n });\n } catch (error) {\n const { startTime, ...rest } = context;\n const endTime = this._performance.now();\n\n this._log?.(consts.REQUEST_FAILED, {\n context: { error, fetchUrl: endpoint, logEntryName: 'FETCH_REQUEST_FAILED', ...rest },\n stats: { duration: startTime ? endTime - startTime : 0, endTime, startTime },\n });\n\n // Based on above code, error is going to be a type of Error.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return { errors: castArray(error) } as FetchResponse;\n }\n }\n\n private async _fetchRedirectHandler(\n res: FetchResponse,\n endpoint: string,\n options: FetchRedirectHandlerOptions,\n context: Context,\n ): Promise<FetchResponse> {\n const { method, redirects = 1, status, ...rest } = options;\n\n if (redirects === this._maxRedirects) {\n res.errors = [new Error(`${consts.MAX_REDIRECTS_EXCEEDED_ERROR} ${String(this._maxRedirects)}.`)];\n this._logResponse(res, endpoint, options, context);\n return res;\n }\n\n const redirectMethod = status === 303 ? consts.GET_METHOD : method;\n return this._fetch(endpoint, { method: redirectMethod, redirects: redirects + 1, ...rest });\n }\n\n private async _fetchRetryHandler(res: FetchResponse, endpoint: string, options: FetchOptions, context: Context) {\n const { retries = 1, ...rest } = options;\n\n if (retries === this._maxRetries) {\n res.errors = [new Error(`${consts.MAX_RETRIES_EXCEEDED_ERROR} ${String(this._maxRetries)}.`)];\n this._logResponse(res, endpoint, options, context);\n return res;\n }\n\n await delay(this._requestRetryWait);\n return this._fetch(endpoint, { retries: retries + 1, ...rest });\n }\n\n private async _get(\n path: string,\n { headers = {}, pathTemplateData, queryParams = {} }: Omit<RequestOptions, 'method'>,\n context?: Context,\n ) {\n const endpoint = buildEndpoint(this._basePath, path, {\n optionalPathTemplateRegExp: this._optionalPathTemplateRegExp,\n pathTemplateCallback: this._pathTemplateCallback,\n pathTemplateData,\n pathTemplateRegExp: this._pathTemplateRegExp,\n queryParams: { ...this._queryParams, ...queryParams },\n });\n\n const requestHash = Md5.hashStr(endpoint);\n const cacheability = await this._cacheEntryHas(requestHash);\n\n if (cacheability) {\n if (isCacheabilityValid(cacheability)) {\n const newHeaders = {\n ...headers,\n 'cache-control': cacheability.printCacheControl(),\n };\n\n this._log?.(consts.RESPONSE_FROM_CACHE, {\n context: {\n fetchMethod: consts.GET_METHOD,\n fetchResponseHeaders: newHeaders,\n fetchUrl: endpoint,\n logEntryName: 'FETCH_RESPONSE_FROM_CACHE',\n ...context,\n },\n });\n\n return {\n data: await this._cacheEntryGet(requestHash),\n headers: new Headers(newHeaders),\n };\n }\n\n if (this._conditionalRequestsEnabled && cacheability.metadata.etag) {\n headers[consts.IF_NONE_MATCH_HEADER] = cacheability.metadata.etag;\n }\n }\n\n const pendingRequest = this._trackRequest(requestHash);\n\n if (pendingRequest) {\n return pendingRequest;\n }\n\n return this._getResolve(\n requestHash,\n await this._fetch(endpoint, { headers: { ...this._headers, ...headers }, method: consts.GET_METHOD }, context),\n );\n }\n\n private async _getResolve(requestHash: string, res: FetchResponse) {\n const { data, headers, status } = res;\n\n if (status === consts.NOT_FOUND_STATUS_CODE) {\n void this._cacheEntryDelete(requestHash);\n let { errors } = res;\n errors ??= [];\n errors.push(new Error(consts.RESOURCE_NOT_FOUND_ERROR));\n res.errors = errors;\n } else if (status === consts.NOT_MODIFIED_STATUS_CODE) {\n const cachedData = await this._cacheEntryGet(requestHash);\n\n if (cachedData) {\n void this._cacheEntrySet(requestHash, cachedData, {\n cacheControl: headers.get(consts.CACHE_CONTROL_HEADER) ?? undefined,\n etag: headers.get(consts.ETAG_HEADER) ?? undefined,\n });\n\n res.data = cachedData;\n }\n } else if (data) {\n void this._cacheEntrySet(requestHash, data, {\n cacheControl: headers.get(consts.CACHE_CONTROL_HEADER) ?? undefined,\n etag: headers.get(consts.ETAG_HEADER) ?? undefined,\n });\n }\n\n this._resolvePendingRequests(requestHash, res);\n this._requestTracker.active = this._requestTracker.active.filter(value => value !== requestHash);\n return res;\n }\n\n private _logResponse(res: FetchResponse, endpoint: string, options: FetchOptions, context: Context) {\n const { headers, status } = res;\n const { method, redirects, retries } = options;\n const { startTime, ...otherContext } = context;\n const endTime = this._performance.now();\n const duration = startTime ? endTime - startTime : 0;\n\n this._log?.(consts.RESPONSE_RECEIVED, {\n context: {\n fetchMethod: method,\n fetchRedirects: redirects,\n fetchResponseHeaders: Object.fromEntries(headers.entries()),\n fetchResponseStatus: status,\n fetchRetries: retries,\n fetchUrl: endpoint,\n logEntryName: 'FETCH_RESPONSE_RECEIVED',\n ...otherContext,\n },\n stats: { duration, endTime, startTime },\n });\n }\n\n private async _releaseRateLimitedRequestQueue() {\n for (const [resolve, endpoint, options, context] of this._rateLimitedRequestQueue) {\n resolve(await this._fetch(endpoint, options, context));\n }\n\n this._rateLimitedRequestQueue = [];\n }\n\n private async _request(\n path: string,\n { body, headers, method, pathTemplateData, queryParams, ...rest }: SetRequired<RequestOptions, 'method'>,\n context?: Context,\n ) {\n const endpoint = buildEndpoint(this._basePath, path, {\n optionalPathTemplateRegExp: this._optionalPathTemplateRegExp,\n pathTemplateCallback: this._pathTemplateCallback,\n pathTemplateData,\n pathTemplateRegExp: this._pathTemplateRegExp,\n queryParams: { ...this._queryParams, ...queryParams },\n });\n\n return this._fetch(\n endpoint,\n {\n body,\n headers: { ...this._headers, ...headers },\n method,\n ...rest,\n },\n context,\n );\n }\n\n private _resolvePendingRequests(requestHash: string, responseData: FetchResponse) {\n const pendingRequests = this._requestTracker.pending.get(requestHash);\n\n if (!pendingRequests) {\n return;\n }\n\n for (const { resolve } of pendingRequests) {\n resolve(responseData);\n }\n\n this._requestTracker.pending.delete(requestHash);\n }\n\n private _setPendingRequest(requestHash: string, resolver: PendingRequestResolvers) {\n let pending = this._requestTracker.pending.get(requestHash);\n pending ??= [];\n pending.push(resolver);\n this._requestTracker.pending.set(requestHash, pending);\n }\n\n private _startRateLimit() {\n this._rateLimitTimer ??= setTimeout(() => {\n this._rateLimitTimer = undefined;\n this._rateLimitCount = 0;\n\n if (this._rateLimitedRequestQueue.length > 0) {\n void this._releaseRateLimitedRequestQueue();\n }\n }, 1000);\n\n this._rateLimitCount += 1;\n }\n\n private _trackRequest(requestHash: string): Promise<FetchResponse> | undefined {\n if (this._requestTracker.active.includes(requestHash)) {\n return new Promise((resolve: PendingRequestResolver) => {\n this._setPendingRequest(requestHash, { resolve });\n });\n }\n\n this._requestTracker.active.push(requestHash);\n return;\n }\n}\n\nexport const createRestClient = <N extends string>(options: ConstructorOptions, shortcuts?: Shortcuts) => {\n // Typing proving too complex without casting.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const getta = new Getta(options) as Getta & ShortcutProperties<N>;\n\n if (!shortcuts) {\n return getta;\n }\n\n for (const key of Object.keys(shortcuts)) {\n const shortcut = shortcuts[key];\n\n if (shortcut) {\n getta.createShortcut(key, ...shortcut);\n }\n }\n\n return getta;\n};\n","import * as consts from '../../constants.ts';\n\nexport const getResponseGroup = (status: number) => {\n switch (true) {\n case status < 200: {\n return consts.INFORMATION_REPSONSE;\n }\n\n case status < 300: {\n return consts.SUCCESSFUL_REPSONSE;\n }\n\n case status < 400: {\n return consts.REDIRECTION_REPSONSE;\n }\n\n case status < 500: {\n return consts.CLIENT_ERROR_REPSONSE;\n }\n\n default: {\n return consts.SERVER_ERROR_REPSONSE;\n }\n }\n};\n","export const delay = (ms: number) => {\n return new Promise(resolve => setTimeout(resolve, ms));\n};\n","import { type Cacheability } from 'cacheability';\n\nexport const isCacheabilityValid = (cacheability: Cacheability) => {\n const noCache = cacheability.metadata.cacheControl.noCache ?? false;\n return !noCache && cacheability.checkTTL();\n};\n"],"names":["ARRAY_BUFFER_FORMAT","BLOB_FORMAT","FORM_DATA_FORMAT","JSON_FORMAT","TEXT_FORMAT","STREAM_READERS","DEFAULT_BODY_PARSER","body","DEFAULT_FETCH_TIMEOUT","DEFAULT_HEADERS","DEFAULT_MAX_REDIRECTS","DEFAULT_MAX_RETRIES","DEFAULT_PATH_TEMPLATE_REGEX","OPTIONAL_PATH_TEMPLATE_REGEX","DEFAULT_RATE_LIMIT","DEFAULT_REQUEST_RETRY_WAIT","MISSING_BASE_PATH_ERROR","MAX_REDIRECTS_EXCEEDED_ERROR","MAX_RETRIES_EXCEEDED_ERROR","INVALID_FETCH_METHOD_ERROR","RESOURCE_NOT_FOUND_ERROR","FETCH_TIMEOUT_ERROR","GET_METHOD","POST_METHOD","PUT_METHOD","DELETE_METHOD","FETCH_METHODS","INFORMATION_REPSONSE","SUCCESSFUL_REPSONSE","REDIRECTION_REPSONSE","CLIENT_ERROR_REPSONSE","SERVER_ERROR_REPSONSE","NOT_MODIFIED_STATUS_CODE","NOT_FOUND_STATUS_CODE","COOKIE_HEADER","ETAG_HEADER","LOCATION_HEADER","IF_NONE_MATCH_HEADER","CACHE_CONTROL_HEADER","REQUEST_SENT","RESPONSE_RECEIVED","RESPONSE_FROM_CACHE","REQUEST_FAILED","defaultPathTemplateCallback","pathTemplate","data","pathTemplateRegExp","dataKeys","Object","keys","replace","match","key","includes","undefined","String","buildEndpoint","basePath","path","optionalPathTemplateRegExp","pathTemplateCallback","pathTemplateData","queryParams","pathJoiner","endsWith","startsWith","endpoint","slice","Math","max","length","sanitisedSearchParams","omitBy","entry","queryString","extract","stringify","Getta","constructor","options","_rateLimitCount","_rateLimitedRequestQueue","_rateLimitTimer","_requestTracker","active","pending","Map","bodyParser","consts","cache","enableConditionalRequests","fetchTimeout","headers","log","maxRedirects","maxRetries","performance","rateLimit","rateLimitPerSecond","requestRetryWait","streamReader","Error","this","_basePath","_bodyParser","_cache","_conditionalRequestsEnabled","_fetchTimeout","_headers","_log","_maxRedirects","_maxRetries","_optionalPathTemplateRegExp","_pathTemplateCallback","_pathTemplateRegExp","_performance","_queryParams","_rateLimit","_rateLimitPerSecond","_requestRetryWait","_streamReader","createShortcut","name","method","otherOptions","async","requestMethod","otherOptionOverrides","context","merge","delete","_delete","get","_get","post","_request","put","_addRequestToRateLimitedQueue","Promise","resolve","push","_cacheEntryDelete","requestHash","_cacheEntryGet","_cacheEntryHas","has","_cacheEntrySet","cacheHeaders","set","rest","Md5","hashStr","_fetch","startTime","now","redirects","retries","reject","fetchTimer","setTimeout","_startRateLimit","clearTimeout","fetchMethod","fetchRedirets","fetchRequestHeaders","fetchRetries","fetchUrl","logEntryName","stats","res","fetch","status","responseGroup","getResponseGroup","_fetchRedirectHandler","defineProperty","enumerable","value","writable","_logResponse","error","_fetchRetryHandler","endTime","duration","errors","castArray","redirectMethod","ms","cacheability","metadata","cacheControl","noCache","checkTTL","isCacheabilityValid","newHeaders","printCacheControl","fetchResponseHeaders","Headers","etag","pendingRequest","_trackRequest","_getResolve","cachedData","_resolvePendingRequests","filter","otherContext","fetchRedirects","fromEntries","entries","fetchResponseStatus","_releaseRateLimitedRequestQueue","responseData","pendingRequests","_setPendingRequest","resolver","createRestClient","shortcuts","getta","shortcut"],"mappings":"+JAEO,MAAMA,EAA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AAqBqE,GACnD,MAAMC,EAAkB9G,KAAKnB,gBAAgBE,QAAQ+C,IAAIU,GAEzD,GAAKsE,EAAL,CAIA,IAAK,MAAMzE,QAAEA,KAAayE,EACxBzE,EAAQwE,GAGV7G,KAAKnB,gBAAgBE,QAAQ6C,OAAOY,EANpC,CAOF,CAEQuE,kBAAAA,CAAmBvE,EAAqBwE,GAC9C,IAAIjI,EAAUiB,KAAKnB,gBAAgBE,QAAQ+C,IAAIU,GAC/CzD,IAAY,GACZA,EAAQuD,KAAK0E,GACbhH,KAAKnB,gBAAgBE,QAAQ+D,IAAIN,EAAazD,EAChD,CAEQ2E,eAAAA,GACN1D,KAAKpB,kBAAoB6E,YAAW,KAClCzD,KAAKpB,qBAAkB5B,EACvBgD,KAAKtB,gBAAkB,EAEnBsB,KAAKrB,yBAAyBX,OAAS,GACpCgC,KAAK4G,oCAEX,KAEH5G,KAAKtB,iBAAmB,CAC1B,CAEQwH,aAAAA,CAAc1D,GACpB,GAAIxC,KAAKnB,gBAAgBC,OAAO/B,SAASyF,GACvC,OAAO,IAAIJ,SAASC,IAClBrC,KAAK+G,mBAAmBvE,EAAa,CAAEH,eAI3CrC,KAAKnB,gBAAgBC,OAAOwD,KAAKE,EAEnC,EAGK,MAAMyE,EAAmB,CAAmBxI,EAA6ByI,KAG9E,MAAMC,EAAQ,IAAI5I,EAAME,GAExB,IAAKyI,EACH,OAAOC,EAGT,IAAK,MAAMrK,KAAOJ,OAAOC,KAAKuK,GAAY,CACxC,MAAME,EAAWF,EAAUpK,GAEvBsK,GACFD,EAAMhG,eAAerE,KAAQsK,EAEjC,CAEA,OAAOD"}
|
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
-----------------------------
|
|
2
2
|
Rollup File Analysis
|
|
3
3
|
-----------------------------
|
|
4
|
-
bundle size:
|
|
5
|
-
original size: 23.
|
|
6
|
-
code reduction: 7.
|
|
4
|
+
bundle size: 21.94 KB
|
|
5
|
+
original size: 23.814 KB
|
|
6
|
+
code reduction: 7.87 %
|
|
7
7
|
module count: 8
|
|
8
8
|
|
|
9
9
|
████████████████████████████████████████░░░░░░░░░░
|
|
10
10
|
file: /src/main.ts
|
|
11
|
-
bundle space: 80.
|
|
12
|
-
rendered size: 17.
|
|
13
|
-
original size: 18.
|
|
14
|
-
code reduction: 5.
|
|
11
|
+
bundle space: 80.47 %
|
|
12
|
+
rendered size: 17.656 KB
|
|
13
|
+
original size: 18.689 KB
|
|
14
|
+
code reduction: 5.53 %
|
|
15
15
|
dependents: 1
|
|
16
16
|
- /src/index.ts
|
|
17
17
|
|
|
18
18
|
████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
|
|
19
19
|
file: /src/constants.ts
|
|
20
|
-
bundle space: 9.
|
|
20
|
+
bundle space: 9.93 %
|
|
21
21
|
rendered size: 2.179 KB
|
|
22
22
|
original size: 2.52 KB
|
|
23
23
|
code reduction: 13.53 %
|
|
@@ -26,18 +26,18 @@ dependents: 3
|
|
|
26
26
|
- /src/main.ts
|
|
27
27
|
- /src/index.ts
|
|
28
28
|
|
|
29
|
-
|
|
29
|
+
██░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
|
|
30
30
|
file: /src/helpers/buildEndpoint/index.ts
|
|
31
|
-
bundle space:
|
|
32
|
-
rendered size:
|
|
33
|
-
original size:
|
|
34
|
-
code reduction:
|
|
31
|
+
bundle space: 4.18 %
|
|
32
|
+
rendered size: 917 Bytes
|
|
33
|
+
original size: 1.148 KB
|
|
34
|
+
code reduction: 20.12 %
|
|
35
35
|
dependents: 1
|
|
36
36
|
- /src/main.ts
|
|
37
37
|
|
|
38
38
|
█░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
|
|
39
39
|
file: /src/helpers/getResponseGroup/index.ts
|
|
40
|
-
bundle space: 2.
|
|
40
|
+
bundle space: 2.53 %
|
|
41
41
|
rendered size: 554 Bytes
|
|
42
42
|
original size: 486 Bytes
|
|
43
43
|
code reduction: 0 %
|
|
@@ -46,7 +46,7 @@ dependents: 1
|
|
|
46
46
|
|
|
47
47
|
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
|
|
48
48
|
file: /src/helpers/defaultPathTemplateCallback/index.ts
|
|
49
|
-
bundle space: 1.
|
|
49
|
+
bundle space: 1.74 %
|
|
50
50
|
rendered size: 381 Bytes
|
|
51
51
|
original size: 424 Bytes
|
|
52
52
|
code reduction: 10.14 %
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.d.cts","sourceRoot":"","sources":["../../../src/constants.cts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C,eAAO,MAAM,mBAAmB,gBAAgB,CAAC;AACjD,eAAO,MAAM,WAAW,SAAS,CAAC;AAClC,eAAO,MAAM,gBAAgB,aAAa,CAAC;AAC3C,eAAO,MAAM,WAAW,SAAS,CAAC;AAClC,eAAO,MAAM,WAAW,SAAS,CAAC;AAElC,eAAO,MAAM,cAAc;;;;;;CAM1B,CAAC;AAEF,eAAO,MAAM,mBAAmB,
|
|
1
|
+
{"version":3,"file":"constants.d.cts","sourceRoot":"","sources":["../../../src/constants.cts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C,eAAO,MAAM,mBAAmB,gBAAgB,CAAC;AACjD,eAAO,MAAM,WAAW,SAAS,CAAC;AAClC,eAAO,MAAM,gBAAgB,aAAa,CAAC;AAC3C,eAAO,MAAM,WAAW,SAAS,CAAC;AAClC,eAAO,MAAM,WAAW,SAAS,CAAC;AAElC,eAAO,MAAM,cAAc;;;;;;CAM1B,CAAC;AAEF,eAAO,MAAM,mBAAmB,GAAI,MAAM,WAAW,gBAAS,CAAC;AAC/D,eAAO,MAAM,qBAAqB,OAAO,CAAC;AAC1C,eAAO,MAAM,eAAe;;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CAAC;AACrD,eAAO,MAAM,mBAAmB,wBAAwB,CAAC;AACzD,eAAO,MAAM,cAAc,mBAAmB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../../../../../src/helpers/buildEndpoint/index.cts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../../../../../src/helpers/buildEndpoint/index.cts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAEvD,eAAO,MAAM,aAAa,GACxB,UAAU,MAAM,EAChB,MAAM,MAAM,EACZ,0GAMG,oBAAoB,WAuBxB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../../../../../src/helpers/defaultPathTemplateCallback/index.cts"],"names":[],"mappings":"AAAA,eAAO,MAAM,2BAA2B,
|
|
1
|
+
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../../../../../src/helpers/defaultPathTemplateCallback/index.cts"],"names":[],"mappings":"AAAA,eAAO,MAAM,2BAA2B,GACtC,cAAc,MAAM,EACpB,MAAM,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,EAC/C,oBAAoB,MAAM,WAa3B,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../../../../../src/helpers/delay/index.cts"],"names":[],"mappings":"AAAA,eAAO,MAAM,KAAK,
|
|
1
|
+
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../../../../../src/helpers/delay/index.cts"],"names":[],"mappings":"AAAA,eAAO,MAAM,KAAK,GAAI,IAAI,MAAM,qBAE/B,CAAC"}
|