@autofleet/network 1.8.1 → 1.8.3

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/lib/index.cjs CHANGED
@@ -1,3 +1,2 @@
1
- 'use strict';var node_module=require('node:module'),d=require('axios'),p=require('axios-retry'),y=require('@autofleet/logger'),A=require('deepmerge'),x=require('@autofleet/axios-cache-adapter'),agentkeepalive=require('agentkeepalive');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var d__default=/*#__PURE__*/_interopDefault(d);var p__default=/*#__PURE__*/_interopDefault(p);var y__default=/*#__PURE__*/_interopDefault(y);var A__default=/*#__PURE__*/_interopDefault(A);var x__default=/*#__PURE__*/_interopDefault(x);var {setup:v}=x__default.default,E=node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))),u,I=(...i)=>(u??=E("qs").stringify,u(...i)),T=["get","post","delete","head","put","patch","options"],S={arrayFormat:"brackets"},w={timeout:1e4,headers:{"X-AF-AUTH":"ANYONE","X-IAF-ORIGIN-SERVICE":process.env.AF_SERVICE_NAME||null},paramsSerializer:i=>I(i,S),"axios-retry":{shouldResetTimeout:true},keepAlive:true},c=i=>`[${(i.method||"").toUpperCase()}] ${i.baseURL??"unknown-base-url"}${i.url??"/unknown-url"}`,g=Number.parseInt(process.env.FREE_SOCKET_TIMEOUT,10)||5e3,l=class{#e;constructor(e={}){this.#e=e.logger??y__default.default(),this.settings=A__default.default(w,e),this.settings.keepAlive&&(this.settings.httpAgent=new agentkeepalive.HttpAgent({freeSocketTimeout:g}),this.settings.httpsAgent=new agentkeepalive.HttpsAgent({freeSocketTimeout:g}),delete this.settings.keepAlive),this.#i(),e.cache&&(this.settings.cache={maxAge:15*60*1e3,exclude:{query:false},...e.cache}),this.axios=e.cache?v(this.settings):d__default.default.create(this.settings),this.#t(e),this.#r(),this.#s();}#t(e){p__default.default(this.axios,{retries:0,retryDelay:p__default.default.exponentialDelay,...e});}#s(){this.axios.interceptors.request.use(e=>(this.#e.info(`Start Request: ${c(e)}`),e)),this.axios.interceptors.response.use(e=>(this.#e.info(`Finish Request: ${c(e.config)}`),e),e=>{if(e.request?._currentRequest?.reusedSocket&&["ECONNRESET","EPIPE"].includes(e.code))return this.#e.warn(`${e.code} issue, will retry`,{req:e.request._currentRequest._currentUrl}),this.axios.request(e.config);let t=e.config?.baseURL?e.config:e.request;throw this.#e.error(`Finish Request with error ${t?c(t):""}`,{status:e.status,data:e.response?.data}),e});}#i(){if(!this.settings.serviceUrl&&!this.settings.serviceName)throw new Error("At least one of the settings Missing serviceUrl or serviceName");let{settings:e}=this;if(e.serviceUrl)e.baseURL=e.serviceUrl;else if(e.serviceName){let t=`${e.serviceName}_SERVICE_HOST`;if(e.baseURL=`http://${process.env[t]}`,!e.baseURL)throw new Error(`Missing environment variable: ${t}`)}}#r(){T.forEach(e=>{this[e]=async(...t)=>this.axios[e](...t);});}async getAllPages(e,t={}){let o=[],r=null,n=null,s={params:{page:1},...t};for(s.params.page||=1;(s.params.page===1||n===r)&&n!==0;){let{data:a}=await this.get(e,s);n=a.length,s.params.page===1&&(r=a.length),s.params.page+=1,Array.prototype.push.apply(o,a);}return o}async getAllPagesFromQueryEndpoint(e,t={},o=100){let r=[],n=true,s=1;for(;n&&(o===-1||s<o);){let{data:a}=await this.post(e,{...t,page:s}),{rows:h,count:f}=a;s+=1,Array.prototype.push.apply(r,h),n=r.length<f;}return r}};
2
- module.exports=l;//# sourceMappingURL=index.cjs.map
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=s(require(`node:process`)),l=s(require(`node:module`)),u=s(require(`axios`)),d=s(require(`axios-retry`)),f=s(require(`@autofleet/logger`)),p=s(require(`deepmerge`)),m=s(require(`@autofleet/axios-cache-adapter`)),h=s(require(`agentkeepalive`)),{setup:g}=m.default,_=d.default,v=(0,l.createRequire)(require(`url`).pathToFileURL(__filename).href);let y;const b=(...e)=>(y??=v(`qs`).stringify,y(...e)),x=[`get`,`post`,`delete`,`head`,`put`,`patch`,`options`],S={arrayFormat:`brackets`},C={timeout:1e4,headers:{"X-AF-AUTH":`ANYONE`,"X-IAF-ORIGIN-SERVICE":c.env.AF_SERVICE_NAME||null},paramsSerializer:e=>b(e,S),"axios-retry":{shouldResetTimeout:!0},keepAlive:!0},w=e=>`[${(e.method||``).toUpperCase()}] ${e.baseURL??`unknown-base-url`}${e.url??`/unknown-url`}`,T=Number.parseInt(c.env.FREE_SOCKET_TIMEOUT||``,10)||5e3;var E=class{#logger;settings;axios;get;post;delete;head;put;patch;options;constructor(e={}){this.#logger=e.logger??(0,f.default)(),this.settings=(0,p.default)(C,e),this.settings.keepAlive&&(this.settings.httpAgent=new h.HttpAgent({freeSocketTimeout:T}),this.settings.httpsAgent=new h.HttpsAgent({freeSocketTimeout:T}),delete this.settings.keepAlive),this.#createBaseUrl(),e.cache&&(this.settings.cache={maxAge:900*1e3,exclude:{query:!1},...e.cache}),this.axios=e.cache?g(this.settings):u.default.create(this.settings),this.#addRetry(e),this.#buildClassHttpMethods(),this.#addLogs()}#addRetry(e){_(this.axios,{retries:0,retryDelay:d.default.exponentialDelay,...e})}#addLogs(){this.axios.interceptors.request.use(e=>(this.#logger.info(`Start Request: ${w(e)}`),e)),this.axios.interceptors.response.use(e=>(this.#logger.info(`Finish Request: ${w(e.config)}`),e),e=>{if(e.request?._currentRequest?.reusedSocket&&[`ECONNRESET`,`EPIPE`].includes(e.code))return this.#logger.warn(`${e.code} issue, will retry`,{req:e.request._currentRequest._currentUrl}),this.axios.request(e.config);let t=e.config?.baseURL?e.config:e.request;throw this.#logger.error(`Finish Request with error ${t?w(t):``}`,{status:e.status,data:e.response?.data}),e})}#createBaseUrl(){if(!this.settings.serviceUrl&&!this.settings.serviceName)throw Error(`At least one of the settings Missing serviceUrl or serviceName`);let{settings:e}=this;if(e.serviceUrl)e.baseURL=e.serviceUrl;else if(e.serviceName){let t=`${e.serviceName}_SERVICE_HOST`;e.baseURL=`http://${c.env[t]}`}}#buildClassHttpMethods(){x.forEach(e=>{this[e]=(...t)=>this.axios[e](...t)})}async getAllPages(e,t={}){let n=[],r=null,i=null,a={params:{page:1},...t};for(a.params.page||=1;(a.params.page===1||i===r)&&i!==0;){let{data:t}=await this.get(e,a);i=t.length,a.params.page===1&&(r=t.length),a.params.page+=1,Array.prototype.push.apply(n,t)}return n}async getAllPagesFromQueryEndpoint(e,t={},n=100){let r=[],i=!0,a=1;for(;i&&(n===-1||a<n);){let{data:n}=await this.post(e,{...t,page:a}),{rows:o,count:s}=n;a+=1,Array.prototype.push.apply(r,o),i=r.length<s}return r}};module.exports=E;
3
2
  //# sourceMappingURL=index.cjs.map
package/lib/index.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"names":["setup","axiosCacheAdapter","safeRequire","createRequire","qsStringify","lazilyLoadQsStringify","args","HTTPMethods","qsStringifyOptions","defaultSettings","params","createRequestString","request","FREE_SOCKET_TIMEOUT","Network","#logger","settings","Logger","merge","HttpAgent","HttpsAgent","#createBaseUrl","axios","#addRetry","#buildClassHttpMethods","#addLogs","axiosRetry","response","error","envServiceHostName","method","url","options","currentResult","resultsInFirstPage","lastResultsSize","localOptions","data","pageLimit","moreResultsToLoad","page","rows","count"],"mappings":"4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MAG5BD,CAAAA,CAAAA,CAAAA,CAAa,MAAO,CAAA,IAAA,EAAQ,CAC5B,CAAA,KAAA,CAAM,SAAU,CAAA,IAAA,CAAK,MAAMH,CAAeI,CAAAA,CAAI,EAChD,CAEA,OAAOJ,CACT,CAWA,MAAa,4BAAgCF,CAAAA,CAAAA,CAAaC,CAAkB,CAAA,EAAIM,CAAAA,CAAAA,CAAoB,GAAmB,CAAA,CACrH,IAAIL,CAAqB,CAAA,EAErBM,CAAAA,CAAAA,CAAoB,IACpBC,CAAAA,CAAAA,CAAO,CACX,CAAA,KAAOD,IAAsBD,CAAc,GAAA,EAAA,EAAME,CAAOF,CAAAA,CAAAA,CAAAA,EAAY,CAClE,GAAM,CAAE,IAAA,CAAAD,CAAK,CAAI,CAAA,MAAM,IAAK,CAAA,IAAA,CAAoCN,CAAK,CAAA,CACnE,GAAGC,CAAAA,CACH,IAAAQ,CAAAA,CACF,CAAC,CAAA,CACK,CAAE,IAAA,CAAAC,CAAM,CAAA,KAAA,CAAAC,CAAM,CAAIL,CAAAA,CAAAA,CACxBG,CAAQ,EAAA,CAAA,CACR,KAAM,CAAA,SAAA,CAAU,IAAK,CAAA,KAAA,CAAMP,EAAeQ,CAAI,CAAA,CAC9CF,CAAoBN,CAAAA,CAAAA,CAAc,MAASS,CAAAA,EAC7C,CAEA,OAAOT,CACT,CACF","file":"index.cjs","sourcesContent":["import { createRequire } from 'node:module';\nimport axios, { type CreateAxiosDefaults, type AxiosRequestConfig, type AxiosInstance, type AxiosResponse } from 'axios';\nimport axiosRetry, { type IAxiosRetryConfig } from 'axios-retry';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\nimport merge from 'deepmerge';\nimport axiosCacheAdapter from '@autofleet/axios-cache-adapter';\nimport { HttpAgent, HttpsAgent } from 'agentkeepalive';\nimport type { stringify } from 'qs';\nimport type * as sideEffect from '@autofleet/axios-cache-adapter';\n\ndeclare module 'axios' {\n /**In order for the `Axios` interface augmenting to work, we must have imported `axios-cache-adapter`. This side effect forces TS to not drop the import as it is in use. */\n const p: sideEffect.IAxiosCacheAdapterOptions;\n}\n\nconst { setup } = axiosCacheAdapter;\nconst safeRequire = createRequire(import.meta.url);\n\nlet qsStringify: typeof stringify | undefined;\nconst lazilyLoadQsStringify = (...args: Parameters<typeof stringify>) => {\n qsStringify ??= safeRequire('qs').stringify;\n return qsStringify(...args);\n}\n\nconst HTTPMethods = [\n 'get',\n 'post',\n 'delete',\n 'head',\n 'put',\n 'patch',\n 'options',\n] as const;\n\nconst qsStringifyOptions: NonNullable<Parameters<typeof stringify>[1]> = { arrayFormat: 'brackets' };\n\ninterface NetworkSettings extends CreateAxiosDefaults, IAxiosRetryConfig {\n serviceName?: string;\n serviceUrl?: string;\n keepAlive?: boolean;\n logger?: LoggerInstanceManager;\n timeout?: number;\n}\n\nconst defaultSettings: NetworkSettings = {\n timeout: 10_000,\n headers: {\n 'X-AF-AUTH': 'ANYONE',\n 'X-IAF-ORIGIN-SERVICE': process.env.AF_SERVICE_NAME || null,\n },\n paramsSerializer: params => lazilyLoadQsStringify(params, qsStringifyOptions),\n 'axios-retry': {\n shouldResetTimeout: true,\n },\n keepAlive: true,\n};\n\nconst createRequestString = (request: AxiosRequestConfig): string => `[${(request.method || '').toUpperCase()}] ${request.baseURL ?? 'unknown-base-url'}${request.url ?? '/unknown-url'}`;\n\n/*\n The default free socket keepalive timeout, in milliseconds.\n Setting to 5000 (5 seconds) as default because out grace period is 10 seconds\n and we want to make sure we don't have any socket issues.\n See https://www.npmjs.com/package/agentkeepalive\n\n There is also autoscaling reason for that, if we don't timeout at some point,\n new pods that were auto scaled will not be used.\n*/\nconst FREE_SOCKET_TIMEOUT = Number.parseInt(process.env.FREE_SOCKET_TIMEOUT, 10) || 5_000;\n\nexport default class Network {\n readonly #logger: LoggerInstanceManager;\n private readonly settings: NetworkSettings;\n private readonly axios: AxiosInstance;\n\n public get: AxiosInstance['get'];\n public post: AxiosInstance['post'];\n public delete: AxiosInstance['delete'];\n public head: AxiosInstance['head'];\n public put: AxiosInstance['put'];\n public patch: AxiosInstance['patch'];\n public options: AxiosInstance['options'];\n\n constructor(settings: NetworkSettings = {}) {\n this.#logger = settings.logger ?? Logger();\n this.settings = merge(defaultSettings, settings);\n if (this.settings.keepAlive) {\n this.settings.httpAgent = new HttpAgent({ freeSocketTimeout: FREE_SOCKET_TIMEOUT });\n this.settings.httpsAgent = new HttpsAgent({ freeSocketTimeout: FREE_SOCKET_TIMEOUT });\n delete this.settings.keepAlive;\n }\n this.#createBaseUrl();\n\n if(settings.cache) {\n this.settings.cache = {\n maxAge: 15 * 60 * 1000,\n // Store responses from requests with query parameters in cache\n exclude: { query: false },\n ...settings.cache,\n }\n }\n\n this.axios = settings.cache ? setup(this.settings) : axios.create(this.settings);\n this.#addRetry(settings);\n this.#buildClassHttpMethods();\n this.#addLogs();\n }\n\n #addRetry(settings: NetworkSettings): void {\n axiosRetry(this.axios, {\n retries: 0,\n retryDelay: axiosRetry.exponentialDelay,\n ...settings,\n });\n }\n\n #addLogs(): void {\n this.axios.interceptors.request.use((request) => {\n this.#logger.info(`Start Request: ${createRequestString(request)}`);\n return request;\n });\n\n this.axios.interceptors.response.use((response) => {\n this.#logger.info(`Finish Request: ${createRequestString(response.config)}`);\n return response;\n }, (error) => {\n if(error.request?._currentRequest?.reusedSocket && ['ECONNRESET', 'EPIPE'].includes(error.code)) {\n // See https://www.npmjs.com/package/agentkeepalive\n // Support req.reusedSocket\n // https://code-examples.net/en/q/28a8069\n this.#logger.warn(`${error.code} issue, will retry`, {\n req: error.request._currentRequest._currentUrl,\n // method: error.request._currentRequest._options.method,\n })\n return this.axios.request(error.config);\n }\n const request = error.config?.baseURL ? error.config : error.request;\n this.#logger.error(`Finish Request with error ${request ? createRequestString(request) : ''}`, {\n status: error.status,\n data: error.response?.data,\n });\n throw error;\n });\n }\n\n #createBaseUrl(): void {\n if (!this.settings.serviceUrl && !this.settings.serviceName) {\n throw new Error('At least one of the settings Missing serviceUrl or serviceName');\n }\n\n const { settings } = this;\n if (settings.serviceUrl) {\n settings.baseURL = settings.serviceUrl;\n } else if (settings.serviceName) {\n const envServiceHostName = `${settings.serviceName}_SERVICE_HOST`;\n settings.baseURL = `http://${process.env[envServiceHostName]}`;\n if (!settings.baseURL) {\n throw new Error(`Missing environment variable: ${envServiceHostName}`);\n }\n }\n }\n\n /**\n * Build class methods that wrap axios methods\n */\n #buildClassHttpMethods(): void {\n HTTPMethods.forEach((method) => {\n this[method] = async <T = any, R = AxiosResponse<T>>(...args: Parameters<AxiosInstance[typeof method]>): Promise<R> => this.axios[method](...args as [url: string, leaveUsAlone?: unknown]);\n });\n }\n\n /**\n * @param url The endpoint URL to send the request to.\n * @param options Additional options to include in the request payload.\n * @returns A promise that resolves to an array of all results.\n */\n public async getAllPages<T>(url: string, options: object = {}): Promise<T[]> {\n let currentResult: T[] = [];\n let resultsInFirstPage: number | null = null;\n let lastResultsSize: number | null = null;\n\n const localOptions = { params: { page: 1 }, ...options };\n // Make sure even if `options` had `params` we initialize `page` to 1.\n localOptions.params.page ||= 1;\n while ((localOptions.params.page === 1 || lastResultsSize === resultsInFirstPage) && lastResultsSize !== 0) {\n const { data } = await this.get<T[]>(url, localOptions);\n lastResultsSize = data.length;\n if (localOptions.params.page === 1) {\n resultsInFirstPage = data.length;\n }\n\n localOptions.params.page += 1;\n Array.prototype.push.apply(currentResult, data);\n }\n\n return currentResult;\n }\n\n /**\n * Fetches all pages from a paginated API endpoint until all results are retrieved \n * or an optional page limit is reached.\n *\n * @param url The endpoint URL to send the request to.\n * @param options Additional options to include in the request payload.\n * @param pageLimit The maximum number of pages to fetch. Set to -1 for no limit.\n * @returns A promise that resolves to an array of all results.\n */\n public async getAllPagesFromQueryEndpoint<T>(url: string, options: object = {}, pageLimit: number = 100): Promise<T[]> {\n let currentResult: T[] = [];\n\n let moreResultsToLoad = true;\n let page = 1;\n while (moreResultsToLoad && (pageLimit === -1 || page < pageLimit)) {\n const { data } = await this.post<{ rows: T[]; count: number; }>(url, {\n ...options,\n page,\n });\n const { rows, count } = data;\n page += 1;\n Array.prototype.push.apply(currentResult, rows);\n moreResultsToLoad = currentResult.length < count;\n }\n\n return currentResult;\n }\n};\n"]}
1
+ {"version":3,"file":"index.cjs","names":["axiosCacheAdapter","axiosRetry","qsStringify: typeof stringify | undefined","qsStringifyOptions: NonNullable<Parameters<typeof stringify>[1]>","defaultSettings: NetworkSettings","env","request: AxiosRequestConfig","#logger","settings: NetworkSettings","HttpAgent","HttpsAgent","#createBaseUrl","#addRetry","#buildClassHttpMethods","#addLogs","url: string","options: object","currentResult: T[]","resultsInFirstPage: number | null","lastResultsSize: number | null"],"sources":["../src/index.ts"],"sourcesContent":["import { env } from 'node:process';\nimport { createRequire } from 'node:module';\nimport axios, { type CreateAxiosDefaults, type AxiosRequestConfig, type AxiosInstance, type AxiosResponse, type AxiosRequestHeaders } from 'axios';\nimport axiosRetry, { type IAxiosRetryConfigExtended, type IAxiosRetryConfig, type IAxiosRetryReturn } from 'axios-retry';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\nimport merge from 'deepmerge';\nimport axiosCacheAdapter from '@autofleet/axios-cache-adapter';\nimport { HttpAgent, HttpsAgent } from 'agentkeepalive';\nimport type { stringify } from 'qs';\nimport type { IAxiosCacheAdapterOptions } from '@autofleet/axios-cache-adapter';\n\ndeclare module 'axios' {\n interface AxiosRequestConfig {\n /** configure how the cached requests will be handled, where they will be stored, etc. */\n cache?: IAxiosCacheAdapterOptions;\n /** force cache invalidation */\n clearCacheEntry?: boolean;\n 'axios-retry'?: IAxiosRetryConfigExtended;\n }\n}\n\n// Due to issue with multiple `axios` versions in monorepo, we need to explicitly override the types to use v0\nconst { setup } = axiosCacheAdapter as { setup: (options: AxiosRequestConfig) => AxiosInstance; };\nconst correctlyTypedAxiosRetry = axiosRetry as unknown as (axiosInstance: AxiosInstance, axiosRetryConfig?: IAxiosRetryConfig) => IAxiosRetryReturn;\n\nconst safeRequire = createRequire(import.meta.url);\n\nlet qsStringify: typeof stringify | undefined;\nconst lazilyLoadQsStringify = (...args: Parameters<typeof stringify>) => {\n qsStringify ??= safeRequire('qs').stringify;\n return qsStringify!(...args);\n};\n\nconst HTTPMethods = [\n 'get',\n 'post',\n 'delete',\n 'head',\n 'put',\n 'patch',\n 'options',\n] as const;\n\nconst qsStringifyOptions: NonNullable<Parameters<typeof stringify>[1]> = { arrayFormat: 'brackets' };\n\ninterface NetworkSettings extends CreateAxiosDefaults, IAxiosRetryConfig {\n serviceName?: string;\n serviceUrl?: string;\n keepAlive?: boolean;\n logger?: LoggerInstanceManager;\n timeout?: number;\n}\n\nconst defaultSettings: NetworkSettings = {\n timeout: 10_000,\n headers: {\n 'X-AF-AUTH': 'ANYONE',\n 'X-IAF-ORIGIN-SERVICE': env.AF_SERVICE_NAME || null as unknown as string,\n },\n paramsSerializer: params => lazilyLoadQsStringify(params, qsStringifyOptions),\n 'axios-retry': {\n shouldResetTimeout: true,\n },\n keepAlive: true,\n};\n\nconst createRequestString = (request: AxiosRequestConfig): string => `[${(request.method || '').toUpperCase()}] ${request.baseURL ?? 'unknown-base-url'}${request.url ?? '/unknown-url'}`;\n\n/*\n The default free socket keepalive timeout, in milliseconds.\n Setting to 5000 (5 seconds) as default because out grace period is 10 seconds\n and we want to make sure we don't have any socket issues.\n See https://www.npmjs.com/package/agentkeepalive\n\n There is also autoscaling reason for that, if we don't timeout at some point,\n new pods that were auto scaled will not be used.\n*/\nconst FREE_SOCKET_TIMEOUT = Number.parseInt(env.FREE_SOCKET_TIMEOUT || '', 10) || 5_000;\n\nexport default class Network {\n readonly #logger: LoggerInstanceManager;\n private readonly settings: NetworkSettings;\n private readonly axios: AxiosInstance;\n\n public get!: AxiosInstance['get'];\n public post!: AxiosInstance['post'];\n public delete!: AxiosInstance['delete'];\n public head!: AxiosInstance['head'];\n public put!: AxiosInstance['put'];\n public patch!: AxiosInstance['patch'];\n public options!: AxiosInstance['options'];\n\n constructor(settings: NetworkSettings = {}) {\n this.#logger = settings.logger ?? Logger();\n this.settings = merge(defaultSettings, settings);\n if (this.settings.keepAlive) {\n this.settings.httpAgent = new HttpAgent({ freeSocketTimeout: FREE_SOCKET_TIMEOUT });\n this.settings.httpsAgent = new HttpsAgent({ freeSocketTimeout: FREE_SOCKET_TIMEOUT });\n delete this.settings.keepAlive;\n }\n this.#createBaseUrl();\n\n if (settings.cache) {\n this.settings.cache = {\n maxAge: 15 * 60 * 1000,\n // Store responses from requests with query parameters in cache\n exclude: { query: false },\n ...settings.cache,\n };\n }\n\n this.axios = settings.cache ? setup(this.settings as NetworkSettings & { headers: AxiosRequestHeaders; }) : axios.create(this.settings);\n this.#addRetry(settings);\n this.#buildClassHttpMethods();\n this.#addLogs();\n }\n\n #addRetry(settings: NetworkSettings): void {\n correctlyTypedAxiosRetry(this.axios, {\n retries: 0,\n retryDelay: axiosRetry.exponentialDelay,\n ...settings,\n });\n }\n\n #addLogs(): void {\n this.axios.interceptors.request.use((request) => {\n this.#logger.info(`Start Request: ${createRequestString(request)}`);\n return request;\n });\n\n this.axios.interceptors.response.use((response) => {\n this.#logger.info(`Finish Request: ${createRequestString(response.config)}`);\n return response;\n }, (error) => {\n if (error.request?._currentRequest?.reusedSocket && ['ECONNRESET', 'EPIPE'].includes(error.code)) {\n // See https://www.npmjs.com/package/agentkeepalive\n // Support req.reusedSocket\n // https://code-examples.net/en/q/28a8069\n this.#logger.warn(`${error.code} issue, will retry`, {\n req: error.request._currentRequest._currentUrl,\n // method: error.request._currentRequest._options.method,\n });\n return this.axios.request(error.config);\n }\n const request = error.config?.baseURL ? error.config : error.request;\n this.#logger.error(`Finish Request with error ${request ? createRequestString(request) : ''}`, {\n status: error.status,\n data: error.response?.data,\n });\n throw error;\n });\n }\n\n #createBaseUrl(): void {\n if (!this.settings.serviceUrl && !this.settings.serviceName) {\n throw new Error('At least one of the settings Missing serviceUrl or serviceName');\n }\n\n const { settings } = this;\n if (settings.serviceUrl) {\n settings.baseURL = settings.serviceUrl;\n } else if (settings.serviceName) {\n const envServiceHostName = `${settings.serviceName}_SERVICE_HOST`;\n settings.baseURL = `http://${env[envServiceHostName]}`;\n }\n }\n\n /**\n * Build class methods that wrap axios methods\n */\n #buildClassHttpMethods(): void {\n HTTPMethods.forEach((method) => {\n this[method] = <T = any, R = AxiosResponse<T>>(\n ...args: Parameters<AxiosInstance[typeof method]>\n ): Promise<R> => this.axios[method](...args as [url: string, leaveUsAlone?: AxiosRequestConfig<unknown>]);\n });\n }\n\n /**\n * @param url The endpoint URL to send the request to.\n * @param options Additional options to include in the request payload.\n * @returns A promise that resolves to an array of all results.\n */\n public async getAllPages<T>(url: string, options: object = {}): Promise<T[]> {\n const currentResult: T[] = [];\n let resultsInFirstPage: number | null = null;\n let lastResultsSize: number | null = null;\n\n const localOptions = { params: { page: 1 }, ...options };\n // Make sure even if `options` had `params` we initialize `page` to 1.\n localOptions.params.page ||= 1;\n while ((localOptions.params.page === 1 || lastResultsSize === resultsInFirstPage) && lastResultsSize !== 0) {\n const { data } = await this.get<T[]>(url, localOptions);\n lastResultsSize = data.length;\n if (localOptions.params.page === 1) {\n resultsInFirstPage = data.length;\n }\n\n localOptions.params.page += 1;\n Array.prototype.push.apply(currentResult, data);\n }\n\n return currentResult;\n }\n\n /**\n * Fetches all pages from a paginated API endpoint until all results are retrieved\n * or an optional page limit is reached.\n *\n * @param url The endpoint URL to send the request to.\n * @param options Additional options to include in the request payload.\n * @param pageLimit The maximum number of pages to fetch. Set to -1 for no limit.\n * @returns A promise that resolves to an array of all results.\n */\n public async getAllPagesFromQueryEndpoint<T>(url: string, options: object = {}, pageLimit = 100): Promise<T[]> {\n const currentResult: T[] = [];\n\n let moreResultsToLoad = true;\n let page = 1;\n while (moreResultsToLoad && (pageLimit === -1 || page < pageLimit)) {\n const { data } = await this.post<{ rows: T[]; count: number; }>(url, {\n ...options,\n page,\n });\n const { rows, count } = data;\n page += 1;\n Array.prototype.push.apply(currentResult, rows);\n moreResultsToLoad = currentResult.length < count;\n }\n\n return currentRes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,GAAG,EAAS,YAAY,aAAa,CAAC,CACjE,EAAS,QAAU,CAAC,OAAO,EAAEF,EAAAA,IAAI,IAAqB,AACvD,CACF,CAKD,wBAA+B,CAC7B,EAAY,QAAQ,AAAC,GAAW,CAC9B,KAAK,GAAU,CACb,GAAG,IACY,KAAK,MAAM,GAAQ,GAAG,EAAkE,AAC1G,EAAC,AACH,CAOD,MAAa,YAAeU,EAAaC,EAAkB,CAAE,EAAgB,CAC3E,IAAMC,EAAqB,CAAE,EACzBC,EAAoC,KACpCC,EAAiC,KAE/B,EAAe,CAAE,OAAQ,CAAE,KAAM,CAAG,EAAE,GAAG,CAAS,EAGxD,IADA,EAAa,OAAO,OAAS,GACrB,EAAa,OAAO,OAAS,GAAK,IAAoB,IAAuB,IAAoB,GAAG,CAC1G,GAAM,CAAE,OAAM,CAAG,MAAM,KAAK,IAAS,EAAK,EAAa,CACvD,EAAkB,EAAK,OACnB,EAAa,OAAO,OAAS,IAC/B,EAAqB,EAAK,QAG5B,EAAa,OAAO,MAAQ,EAC5B,MAAM,UAAU,KAAK,MAAM,EAAe,EAAK,AAChD,CAED,OAAO,CACR,CAWD,MAAa,6BAAgCJ,EAAaC,EAAkB,CAAE,EAAE,EAAY,IAAmB,CAC7G,IAAMC,EAAqB,CAAE,EAEzB,EAAoB,GACpB,EAAO,EACX,KAAO,IAAsB,IAAc,IAAM,EAAO,IAAY,CAClE,GAAM,CAAE,OAAM,CAAG,MAAM,KAAK,KAAoC,EAAK,CACnE,GAAG,EACH,MACD,EAAC,CACI,CAAE,OAAM,QAAO,CAAG,EACxB,GAAQ,EACR,MAAM,UAAU,KAAK,MAAM,EAAe,EAAK,CAC/C,EAAoB,EAAc,OAAS,CAC5C,CAED,OAAO,CACR,CACF"}
package/lib/index.d.cts CHANGED
@@ -1,32 +1,53 @@
1
- import { AxiosInstance, CreateAxiosDefaults } from 'axios';
2
- import { IAxiosRetryConfig } from 'axios-retry';
3
- import { LoggerInstanceManager } from '@autofleet/logger';
4
- import * as sideEffect from '@autofleet/axios-cache-adapter';
1
+ import { AxiosInstance, CreateAxiosDefaults } from "axios";
2
+ import { IAxiosRetryConfig, IAxiosRetryConfigExtended } from "axios-retry";
3
+ import { LoggerInstanceManager } from "@autofleet/logger";
4
+ import { IAxiosCacheAdapterOptions } from "@autofleet/axios-cache-adapter";
5
5
 
6
- declare module 'axios' {
7
- const p: sideEffect.IAxiosCacheAdapterOptions;
6
+ //#region src/index.d.ts
7
+ declare module "axios" {
8
+ interface AxiosRequestConfig {
9
+ /** configure how the cached requests will be handled, where they will be stored, etc. */
10
+ cache?: IAxiosCacheAdapterOptions;
11
+ /** force cache invalidation */
12
+ clearCacheEntry?: boolean;
13
+ "axios-retry"?: IAxiosRetryConfigExtended;
14
+ }
8
15
  }
9
16
  interface NetworkSettings extends CreateAxiosDefaults, IAxiosRetryConfig {
10
- serviceName?: string;
11
- serviceUrl?: string;
12
- keepAlive?: boolean;
13
- logger?: LoggerInstanceManager;
14
- timeout?: number;
17
+ serviceName?: string;
18
+ serviceUrl?: string;
19
+ keepAlive?: boolean;
20
+ logger?: LoggerInstanceManager;
21
+ timeout?: number;
15
22
  }
16
23
  declare class Network {
17
- #private;
18
- private readonly settings;
19
- private readonly axios;
20
- get: AxiosInstance['get'];
21
- post: AxiosInstance['post'];
22
- delete: AxiosInstance['delete'];
23
- head: AxiosInstance['head'];
24
- put: AxiosInstance['put'];
25
- patch: AxiosInstance['patch'];
26
- options: AxiosInstance['options'];
27
- constructor(settings?: NetworkSettings);
28
- getAllPages<T>(url: string, options?: object): Promise<T[]>;
29
- getAllPagesFromQueryEndpoint<T>(url: string, options?: object, pageLimit?: number): Promise<T[]>;
24
+ #private;
25
+ private readonly settings;
26
+ private readonly axios;
27
+ get: AxiosInstance["get"];
28
+ post: AxiosInstance["post"];
29
+ delete: AxiosInstance["delete"];
30
+ head: AxiosInstance["head"];
31
+ put: AxiosInstance["put"];
32
+ patch: AxiosInstance["patch"];
33
+ options: AxiosInstance["options"];
34
+ constructor(settings?: NetworkSettings);
35
+ /**
36
+ * @param url The endpoint URL to send the request to.
37
+ * @param options Additional options to include in the request payload.
38
+ * @returns A promise that resolves to an array of all results.
39
+ */
40
+ getAllPages<T>(url: string, options?: object): Promise<T[]>;
41
+ /**
42
+ * Fetches all pages from a paginated API endpoint until all results are retrieved
43
+ * or an optional page limit is reached.
44
+ *
45
+ * @param url The endpoint URL to send the request to.
46
+ * @param options Additional options to include in the request payload.
47
+ * @param pageLimit The maximum number of pages to fetch. Set to -1 for no limit.
48
+ * @returns A promise that resolves to an array of all results.
49
+ */
50
+ getAllPagesFromQueryEndpoint<T>(url: string, options?: object, pageLimit?: number): Promise<T[]>;
30
51
  }
31
-
32
- export { Network as default };
52
+ export = Network;
53
+ //# sourceMappingURL=index.d.cts.map
package/lib/index.d.ts CHANGED
@@ -1,32 +1,54 @@
1
- import { AxiosInstance, CreateAxiosDefaults } from 'axios';
2
- import { IAxiosRetryConfig } from 'axios-retry';
3
- import { LoggerInstanceManager } from '@autofleet/logger';
4
- import * as sideEffect from '@autofleet/axios-cache-adapter';
1
+ import { AxiosInstance, CreateAxiosDefaults } from "axios";
2
+ import { IAxiosRetryConfig, IAxiosRetryConfigExtended } from "axios-retry";
3
+ import { LoggerInstanceManager } from "@autofleet/logger";
4
+ import { IAxiosCacheAdapterOptions } from "@autofleet/axios-cache-adapter";
5
5
 
6
- declare module 'axios' {
7
- const p: sideEffect.IAxiosCacheAdapterOptions;
6
+ //#region src/index.d.ts
7
+ declare module "axios" {
8
+ interface AxiosRequestConfig {
9
+ /** configure how the cached requests will be handled, where they will be stored, etc. */
10
+ cache?: IAxiosCacheAdapterOptions;
11
+ /** force cache invalidation */
12
+ clearCacheEntry?: boolean;
13
+ "axios-retry"?: IAxiosRetryConfigExtended;
14
+ }
8
15
  }
9
16
  interface NetworkSettings extends CreateAxiosDefaults, IAxiosRetryConfig {
10
- serviceName?: string;
11
- serviceUrl?: string;
12
- keepAlive?: boolean;
13
- logger?: LoggerInstanceManager;
14
- timeout?: number;
17
+ serviceName?: string;
18
+ serviceUrl?: string;
19
+ keepAlive?: boolean;
20
+ logger?: LoggerInstanceManager;
21
+ timeout?: number;
15
22
  }
16
23
  declare class Network {
17
- #private;
18
- private readonly settings;
19
- private readonly axios;
20
- get: AxiosInstance['get'];
21
- post: AxiosInstance['post'];
22
- delete: AxiosInstance['delete'];
23
- head: AxiosInstance['head'];
24
- put: AxiosInstance['put'];
25
- patch: AxiosInstance['patch'];
26
- options: AxiosInstance['options'];
27
- constructor(settings?: NetworkSettings);
28
- getAllPages<T>(url: string, options?: object): Promise<T[]>;
29
- getAllPagesFromQueryEndpoint<T>(url: string, options?: object, pageLimit?: number): Promise<T[]>;
24
+ #private;
25
+ private readonly settings;
26
+ private readonly axios;
27
+ get: AxiosInstance["get"];
28
+ post: AxiosInstance["post"];
29
+ delete: AxiosInstance["delete"];
30
+ head: AxiosInstance["head"];
31
+ put: AxiosInstance["put"];
32
+ patch: AxiosInstance["patch"];
33
+ options: AxiosInstance["options"];
34
+ constructor(settings?: NetworkSettings);
35
+ /**
36
+ * @param url The endpoint URL to send the request to.
37
+ * @param options Additional options to include in the request payload.
38
+ * @returns A promise that resolves to an array of all results.
39
+ */
40
+ getAllPages<T>(url: string, options?: object): Promise<T[]>;
41
+ /**
42
+ * Fetches all pages from a paginated API endpoint until all results are retrieved
43
+ * or an optional page limit is reached.
44
+ *
45
+ * @param url The endpoint URL to send the request to.
46
+ * @param options Additional options to include in the request payload.
47
+ * @param pageLimit The maximum number of pages to fetch. Set to -1 for no limit.
48
+ * @returns A promise that resolves to an array of all results.
49
+ */
50
+ getAllPagesFromQueryEndpoint<T>(url: string, options?: object, pageLimit?: number): Promise<T[]>;
30
51
  }
31
-
52
+ //#endregion
32
53
  export { Network as default };
54
+ //# sourceMappingURL=index.d.ts.map
package/lib/index.js CHANGED
@@ -1,3 +1,2 @@
1
- import {createRequire}from'node:module';import d from'axios';import p from'axios-retry';import y from'@autofleet/logger';import A from'deepmerge';import x from'@autofleet/axios-cache-adapter';import {HttpAgent,HttpsAgent}from'agentkeepalive';var {setup:v}=x,E=createRequire(import.meta.url),u,I=(...i)=>(u??=E("qs").stringify,u(...i)),T=["get","post","delete","head","put","patch","options"],S={arrayFormat:"brackets"},w={timeout:1e4,headers:{"X-AF-AUTH":"ANYONE","X-IAF-ORIGIN-SERVICE":process.env.AF_SERVICE_NAME||null},paramsSerializer:i=>I(i,S),"axios-retry":{shouldResetTimeout:true},keepAlive:true},c=i=>`[${(i.method||"").toUpperCase()}] ${i.baseURL??"unknown-base-url"}${i.url??"/unknown-url"}`,g=Number.parseInt(process.env.FREE_SOCKET_TIMEOUT,10)||5e3,l=class{#e;constructor(e={}){this.#e=e.logger??y(),this.settings=A(w,e),this.settings.keepAlive&&(this.settings.httpAgent=new HttpAgent({freeSocketTimeout:g}),this.settings.httpsAgent=new HttpsAgent({freeSocketTimeout:g}),delete this.settings.keepAlive),this.#i(),e.cache&&(this.settings.cache={maxAge:15*60*1e3,exclude:{query:false},...e.cache}),this.axios=e.cache?v(this.settings):d.create(this.settings),this.#t(e),this.#r(),this.#s();}#t(e){p(this.axios,{retries:0,retryDelay:p.exponentialDelay,...e});}#s(){this.axios.interceptors.request.use(e=>(this.#e.info(`Start Request: ${c(e)}`),e)),this.axios.interceptors.response.use(e=>(this.#e.info(`Finish Request: ${c(e.config)}`),e),e=>{if(e.request?._currentRequest?.reusedSocket&&["ECONNRESET","EPIPE"].includes(e.code))return this.#e.warn(`${e.code} issue, will retry`,{req:e.request._currentRequest._currentUrl}),this.axios.request(e.config);let t=e.config?.baseURL?e.config:e.request;throw this.#e.error(`Finish Request with error ${t?c(t):""}`,{status:e.status,data:e.response?.data}),e});}#i(){if(!this.settings.serviceUrl&&!this.settings.serviceName)throw new Error("At least one of the settings Missing serviceUrl or serviceName");let{settings:e}=this;if(e.serviceUrl)e.baseURL=e.serviceUrl;else if(e.serviceName){let t=`${e.serviceName}_SERVICE_HOST`;if(e.baseURL=`http://${process.env[t]}`,!e.baseURL)throw new Error(`Missing environment variable: ${t}`)}}#r(){T.forEach(e=>{this[e]=async(...t)=>this.axios[e](...t);});}async getAllPages(e,t={}){let o=[],r=null,n=null,s={params:{page:1},...t};for(s.params.page||=1;(s.params.page===1||n===r)&&n!==0;){let{data:a}=await this.get(e,s);n=a.length,s.params.page===1&&(r=a.length),s.params.page+=1,Array.prototype.push.apply(o,a);}return o}async getAllPagesFromQueryEndpoint(e,t={},o=100){let r=[],n=true,s=1;for(;n&&(o===-1||s<o);){let{data:a}=await this.post(e,{...t,page:s}),{rows:h,count:f}=a;s+=1,Array.prototype.push.apply(r,h),n=r.length<f;}return r}};
2
- export{l as default};//# sourceMappingURL=index.js.map
1
+ import{createRequire as e}from"node:module";import{env as t}from"node:process";import n from"axios";import r from"axios-retry";import i from"@autofleet/logger";import a from"deepmerge";import o from"@autofleet/axios-cache-adapter";import{HttpAgent as s,HttpsAgent as c}from"agentkeepalive";const{setup:l}=o,u=r,d=e(import.meta.url);let f;const p=(...e)=>(f??=d(`qs`).stringify,f(...e)),m=[`get`,`post`,`delete`,`head`,`put`,`patch`,`options`],h={arrayFormat:`brackets`},g={timeout:1e4,headers:{"X-AF-AUTH":`ANYONE`,"X-IAF-ORIGIN-SERVICE":t.AF_SERVICE_NAME||null},paramsSerializer:e=>p(e,h),"axios-retry":{shouldResetTimeout:!0},keepAlive:!0},_=e=>`[${(e.method||``).toUpperCase()}] ${e.baseURL??`unknown-base-url`}${e.url??`/unknown-url`}`,v=Number.parseInt(t.FREE_SOCKET_TIMEOUT||``,10)||5e3;var y=class{#logger;settings;axios;get;post;delete;head;put;patch;options;constructor(e={}){this.#logger=e.logger??i(),this.settings=a(g,e),this.settings.keepAlive&&(this.settings.httpAgent=new s({freeSocketTimeout:v}),this.settings.httpsAgent=new c({freeSocketTimeout:v}),delete this.settings.keepAlive),this.#createBaseUrl(),e.cache&&(this.settings.cache={maxAge:900*1e3,exclude:{query:!1},...e.cache}),this.axios=e.cache?l(this.settings):n.create(this.settings),this.#addRetry(e),this.#buildClassHttpMethods(),this.#addLogs()}#addRetry(e){u(this.axios,{retries:0,retryDelay:r.exponentialDelay,...e})}#addLogs(){this.axios.interceptors.request.use(e=>(this.#logger.info(`Start Request: ${_(e)}`),e)),this.axios.interceptors.response.use(e=>(this.#logger.info(`Finish Request: ${_(e.config)}`),e),e=>{if(e.request?._currentRequest?.reusedSocket&&[`ECONNRESET`,`EPIPE`].includes(e.code))return this.#logger.warn(`${e.code} issue, will retry`,{req:e.request._currentRequest._currentUrl}),this.axios.request(e.config);let t=e.config?.baseURL?e.config:e.request;throw this.#logger.error(`Finish Request with error ${t?_(t):``}`,{status:e.status,data:e.response?.data}),e})}#createBaseUrl(){if(!this.settings.serviceUrl&&!this.settings.serviceName)throw Error(`At least one of the settings Missing serviceUrl or serviceName`);let{settings:e}=this;if(e.serviceUrl)e.baseURL=e.serviceUrl;else if(e.serviceName){let n=`${e.serviceName}_SERVICE_HOST`;e.baseURL=`http://${t[n]}`}}#buildClassHttpMethods(){m.forEach(e=>{this[e]=(...t)=>this.axios[e](...t)})}async getAllPages(e,t={}){let n=[],r=null,i=null,a={params:{page:1},...t};for(a.params.page||=1;(a.params.page===1||i===r)&&i!==0;){let{data:t}=await this.get(e,a);i=t.length,a.params.page===1&&(r=t.length),a.params.page+=1,Array.prototype.push.apply(n,t)}return n}async getAllPagesFromQueryEndpoint(e,t={},n=100){let r=[],i=!0,a=1;for(;i&&(n===-1||a<n);){let{data:n}=await this.post(e,{...t,page:a}),{rows:o,count:s}=n;a+=1,Array.prototype.push.apply(r,o),i=r.length<s}return r}};export{y as default};
3
2
  //# sourceMappingURL=index.js.map
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"names":["setup","axiosCacheAdapter","safeRequire","createRequire","qsStringify","lazilyLoadQsStringify","args","HTTPMethods","qsStringifyOptions","defaultSettings","params","createRequestString","request","FREE_SOCKET_TIMEOUT","Network","#logger","settings","Logger","merge","HttpAgent","HttpsAgent","#createBaseUrl","axios","#addRetry","#buildClassHttpMethods","#addLogs","axiosRetry","response","error","envServiceHostName","method","url","options","currentResult","resultsInFirstPage","lastResultsSize","localOptions","data","pageLimit","moreResultsToLoad","page","rows","count"],"mappings":"kPAeA,IAAM,CAAE,KAAA,CAAAA,CAAM,CAAA,CAAIC,EACZC,CAAcC,CAAAA,aAAAA,CAAc,MAAY,CAAA,IAAA,CAAA,GAAG,CAE7CC,CAAAA,CAAAA,CACEC,CAAwB,CAAA,CAAA,GAAIC,CAChCF,IAAAA,CAAAA,GAAgBF,CAAY,CAAA,IAAI,CAAE,CAAA,SAAA,CAC3BE,CAAY,CAAA,GAAGE,CAAI,CAGtBC,CAAAA,CAAAA,CAAAA,CAAc,CAClB,KAAA,CACA,MACA,CAAA,QAAA,CACA,MACA,CAAA,KAAA,CACA,QACA,SACF,CAAA,CAEMC,CAAmE,CAAA,CAAE,WAAa,CAAA,UAAW,CAU7FC,CAAAA,CAAAA,CAAmC,CACvC,OAAS,CAAA,GAAA,CACT,OAAS,CAAA,CACP,WAAa,CAAA,QAAA,CACb,sBAAwB,CAAA,OAAA,CAAQ,GAAI,CAAA,eAAA,EAAmB,IACzD,CAAA,CACA,gBAAkBC,CAAAA,CAAAA,EAAUL,CAAsBK,CAAAA,CAAAA,CAAQF,CAAkB,CAC5E,CAAA,aAAA,CAAe,CACb,kBAAA,CAAoB,IACtB,CAAA,CACA,SAAW,CAAA,IACb,CAEMG,CAAAA,CAAAA,CAAuBC,CAAwC,EAAA,CAAA,CAAA,EAAA,CAAKA,CAAQ,CAAA,MAAA,EAAU,EAAI,EAAA,WAAA,EAAa,CAAKA,EAAAA,EAAAA,CAAAA,CAAQ,OAAW,EAAA,kBAAkB,CAAGA,EAAAA,CAAAA,CAAQ,GAAO,EAAA,cAAc,CAWjLC,CAAAA,CAAAA,CAAAA,CAAsB,MAAO,CAAA,QAAA,CAAS,OAAQ,CAAA,GAAA,CAAI,mBAAqB,CAAA,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AA,MAAM,IAAK,CAAA,GAAA,CAASN,CAAKK,CAAAA,CAAY,EACtDD,CAAkBE,CAAAA,CAAAA,CAAK,MACnBD,CAAAA,CAAAA,CAAa,MAAO,CAAA,IAAA,GAAS,CAC/BF,GAAAA,CAAAA,CAAqBG,EAAK,MAG5BD,CAAAA,CAAAA,CAAAA,CAAa,MAAO,CAAA,IAAA,EAAQ,CAC5B,CAAA,KAAA,CAAM,SAAU,CAAA,IAAA,CAAK,MAAMH,CAAeI,CAAAA,CAAI,EAChD,CAEA,OAAOJ,CACT,CAWA,MAAa,4BAAgCF,CAAAA,CAAAA,CAAaC,CAAkB,CAAA,EAAIM,CAAAA,CAAAA,CAAoB,GAAmB,CAAA,CACrH,IAAIL,CAAqB,CAAA,EAErBM,CAAAA,CAAAA,CAAoB,IACpBC,CAAAA,CAAAA,CAAO,CACX,CAAA,KAAOD,IAAsBD,CAAc,GAAA,EAAA,EAAME,CAAOF,CAAAA,CAAAA,CAAAA,EAAY,CAClE,GAAM,CAAE,IAAA,CAAAD,CAAK,CAAI,CAAA,MAAM,IAAK,CAAA,IAAA,CAAoCN,CAAK,CAAA,CACnE,GAAGC,CAAAA,CACH,IAAAQ,CAAAA,CACF,CAAC,CAAA,CACK,CAAE,IAAA,CAAAC,CAAM,CAAA,KAAA,CAAAC,CAAM,CAAIL,CAAAA,CAAAA,CACxBG,CAAQ,EAAA,CAAA,CACR,KAAM,CAAA,SAAA,CAAU,IAAK,CAAA,KAAA,CAAMP,EAAeQ,CAAI,CAAA,CAC9CF,CAAoBN,CAAAA,CAAAA,CAAc,MAASS,CAAAA,EAC7C,CAEA,OAAOT,CACT,CACF","file":"index.js","sourcesContent":["import { createRequire } from 'node:module';\nimport axios, { type CreateAxiosDefaults, type AxiosRequestConfig, type AxiosInstance, type AxiosResponse } from 'axios';\nimport axiosRetry, { type IAxiosRetryConfig } from 'axios-retry';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\nimport merge from 'deepmerge';\nimport axiosCacheAdapter from '@autofleet/axios-cache-adapter';\nimport { HttpAgent, HttpsAgent } from 'agentkeepalive';\nimport type { stringify } from 'qs';\nimport type * as sideEffect from '@autofleet/axios-cache-adapter';\n\ndeclare module 'axios' {\n /**In order for the `Axios` interface augmenting to work, we must have imported `axios-cache-adapter`. This side effect forces TS to not drop the import as it is in use. */\n const p: sideEffect.IAxiosCacheAdapterOptions;\n}\n\nconst { setup } = axiosCacheAdapter;\nconst safeRequire = createRequire(import.meta.url);\n\nlet qsStringify: typeof stringify | undefined;\nconst lazilyLoadQsStringify = (...args: Parameters<typeof stringify>) => {\n qsStringify ??= safeRequire('qs').stringify;\n return qsStringify(...args);\n}\n\nconst HTTPMethods = [\n 'get',\n 'post',\n 'delete',\n 'head',\n 'put',\n 'patch',\n 'options',\n] as const;\n\nconst qsStringifyOptions: NonNullable<Parameters<typeof stringify>[1]> = { arrayFormat: 'brackets' };\n\ninterface NetworkSettings extends CreateAxiosDefaults, IAxiosRetryConfig {\n serviceName?: string;\n serviceUrl?: string;\n keepAlive?: boolean;\n logger?: LoggerInstanceManager;\n timeout?: number;\n}\n\nconst defaultSettings: NetworkSettings = {\n timeout: 10_000,\n headers: {\n 'X-AF-AUTH': 'ANYONE',\n 'X-IAF-ORIGIN-SERVICE': process.env.AF_SERVICE_NAME || null,\n },\n paramsSerializer: params => lazilyLoadQsStringify(params, qsStringifyOptions),\n 'axios-retry': {\n shouldResetTimeout: true,\n },\n keepAlive: true,\n};\n\nconst createRequestString = (request: AxiosRequestConfig): string => `[${(request.method || '').toUpperCase()}] ${request.baseURL ?? 'unknown-base-url'}${request.url ?? '/unknown-url'}`;\n\n/*\n The default free socket keepalive timeout, in milliseconds.\n Setting to 5000 (5 seconds) as default because out grace period is 10 seconds\n and we want to make sure we don't have any socket issues.\n See https://www.npmjs.com/package/agentkeepalive\n\n There is also autoscaling reason for that, if we don't timeout at some point,\n new pods that were auto scaled will not be used.\n*/\nconst FREE_SOCKET_TIMEOUT = Number.parseInt(process.env.FREE_SOCKET_TIMEOUT, 10) || 5_000;\n\nexport default class Network {\n readonly #logger: LoggerInstanceManager;\n private readonly settings: NetworkSettings;\n private readonly axios: AxiosInstance;\n\n public get: AxiosInstance['get'];\n public post: AxiosInstance['post'];\n public delete: AxiosInstance['delete'];\n public head: AxiosInstance['head'];\n public put: AxiosInstance['put'];\n public patch: AxiosInstance['patch'];\n public options: AxiosInstance['options'];\n\n constructor(settings: NetworkSettings = {}) {\n this.#logger = settings.logger ?? Logger();\n this.settings = merge(defaultSettings, settings);\n if (this.settings.keepAlive) {\n this.settings.httpAgent = new HttpAgent({ freeSocketTimeout: FREE_SOCKET_TIMEOUT });\n this.settings.httpsAgent = new HttpsAgent({ freeSocketTimeout: FREE_SOCKET_TIMEOUT });\n delete this.settings.keepAlive;\n }\n this.#createBaseUrl();\n\n if(settings.cache) {\n this.settings.cache = {\n maxAge: 15 * 60 * 1000,\n // Store responses from requests with query parameters in cache\n exclude: { query: false },\n ...settings.cache,\n }\n }\n\n this.axios = settings.cache ? setup(this.settings) : axios.create(this.settings);\n this.#addRetry(settings);\n this.#buildClassHttpMethods();\n this.#addLogs();\n }\n\n #addRetry(settings: NetworkSettings): void {\n axiosRetry(this.axios, {\n retries: 0,\n retryDelay: axiosRetry.exponentialDelay,\n ...settings,\n });\n }\n\n #addLogs(): void {\n this.axios.interceptors.request.use((request) => {\n this.#logger.info(`Start Request: ${createRequestString(request)}`);\n return request;\n });\n\n this.axios.interceptors.response.use((response) => {\n this.#logger.info(`Finish Request: ${createRequestString(response.config)}`);\n return response;\n }, (error) => {\n if(error.request?._currentRequest?.reusedSocket && ['ECONNRESET', 'EPIPE'].includes(error.code)) {\n // See https://www.npmjs.com/package/agentkeepalive\n // Support req.reusedSocket\n // https://code-examples.net/en/q/28a8069\n this.#logger.warn(`${error.code} issue, will retry`, {\n req: error.request._currentRequest._currentUrl,\n // method: error.request._currentRequest._options.method,\n })\n return this.axios.request(error.config);\n }\n const request = error.config?.baseURL ? error.config : error.request;\n this.#logger.error(`Finish Request with error ${request ? createRequestString(request) : ''}`, {\n status: error.status,\n data: error.response?.data,\n });\n throw error;\n });\n }\n\n #createBaseUrl(): void {\n if (!this.settings.serviceUrl && !this.settings.serviceName) {\n throw new Error('At least one of the settings Missing serviceUrl or serviceName');\n }\n\n const { settings } = this;\n if (settings.serviceUrl) {\n settings.baseURL = settings.serviceUrl;\n } else if (settings.serviceName) {\n const envServiceHostName = `${settings.serviceName}_SERVICE_HOST`;\n settings.baseURL = `http://${process.env[envServiceHostName]}`;\n if (!settings.baseURL) {\n throw new Error(`Missing environment variable: ${envServiceHostName}`);\n }\n }\n }\n\n /**\n * Build class methods that wrap axios methods\n */\n #buildClassHttpMethods(): void {\n HTTPMethods.forEach((method) => {\n this[method] = async <T = any, R = AxiosResponse<T>>(...args: Parameters<AxiosInstance[typeof method]>): Promise<R> => this.axios[method](...args as [url: string, leaveUsAlone?: unknown]);\n });\n }\n\n /**\n * @param url The endpoint URL to send the request to.\n * @param options Additional options to include in the request payload.\n * @returns A promise that resolves to an array of all results.\n */\n public async getAllPages<T>(url: string, options: object = {}): Promise<T[]> {\n let currentResult: T[] = [];\n let resultsInFirstPage: number | null = null;\n let lastResultsSize: number | null = null;\n\n const localOptions = { params: { page: 1 }, ...options };\n // Make sure even if `options` had `params` we initialize `page` to 1.\n localOptions.params.page ||= 1;\n while ((localOptions.params.page === 1 || lastResultsSize === resultsInFirstPage) && lastResultsSize !== 0) {\n const { data } = await this.get<T[]>(url, localOptions);\n lastResultsSize = data.length;\n if (localOptions.params.page === 1) {\n resultsInFirstPage = data.length;\n }\n\n localOptions.params.page += 1;\n Array.prototype.push.apply(currentResult, data);\n }\n\n return currentResult;\n }\n\n /**\n * Fetches all pages from a paginated API endpoint until all results are retrieved \n * or an optional page limit is reached.\n *\n * @param url The endpoint URL to send the request to.\n * @param options Additional options to include in the request payload.\n * @param pageLimit The maximum number of pages to fetch. Set to -1 for no limit.\n * @returns A promise that resolves to an array of all results.\n */\n public async getAllPagesFromQueryEndpoint<T>(url: string, options: object = {}, pageLimit: number = 100): Promise<T[]> {\n let currentResult: T[] = [];\n\n let moreResultsToLoad = true;\n let page = 1;\n while (moreResultsToLoad && (pageLimit === -1 || page < pageLimit)) {\n const { data } = await this.post<{ rows: T[]; count: number; }>(url, {\n ...options,\n page,\n });\n const { rows, count } = data;\n page += 1;\n Array.prototype.push.apply(currentResult, rows);\n moreResultsToLoad = currentResult.length < count;\n }\n\n return currentResult;\n }\n};\n"]}
1
+ {"version":3,"file":"index.js","names":["qsStringify: typeof stringify | undefined","qsStringifyOptions: NonNullable<Parameters<typeof stringify>[1]>","defaultSettings: NetworkSettings","request: AxiosRequestConfig","#logger","settings: NetworkSettings","#createBaseUrl","#addRetry","#buildClassHttpMethods","#addLogs","url: string","options: object","currentResult: T[]","resultsInFirstPage: number | null","lastResultsSize: number | null"],"sources":["../src/index.ts"],"sourcesContent":["import { env } from 'node:process';\nimport { createRequire } from 'node:module';\nimport axios, { type CreateAxiosDefaults, type AxiosRequestConfig, type AxiosInstance, type AxiosResponse, type AxiosRequestHeaders } from 'axios';\nimport axiosRetry, { type IAxiosRetryConfigExtended, type IAxiosRetryConfig, type IAxiosRetryReturn } from 'axios-retry';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\nimport merge from 'deepmerge';\nimport axiosCacheAdapter from '@autofleet/axios-cache-adapter';\nimport { HttpAgent, HttpsAgent } from 'agentkeepalive';\nimport type { stringify } from 'qs';\nimport type { IAxiosCacheAdapterOptions } from '@autofleet/axios-cache-adapter';\n\ndeclare module 'axios' {\n interface AxiosRequestConfig {\n /** configure how the cached requests will be handled, where they will be stored, etc. */\n cache?: IAxiosCacheAdapterOptions;\n /** force cache invalidation */\n clearCacheEntry?: boolean;\n 'axios-retry'?: IAxiosRetryConfigExtended;\n }\n}\n\n// Due to issue with multiple `axios` versions in monorepo, we need to explicitly override the types to use v0\nconst { setup } = axiosCacheAdapter as { setup: (options: AxiosRequestConfig) => AxiosInstance; };\nconst correctlyTypedAxiosRetry = axiosRetry as unknown as (axiosInstance: AxiosInstance, axiosRetryConfig?: IAxiosRetryConfig) => IAxiosRetryReturn;\n\nconst safeRequire = createRequire(import.meta.url);\n\nlet qsStringify: typeof stringify | undefined;\nconst lazilyLoadQsStringify = (...args: Parameters<typeof stringify>) => {\n qsStringify ??= safeRequire('qs').stringify;\n return qsStringify!(...args);\n};\n\nconst HTTPMethods = [\n 'get',\n 'post',\n 'delete',\n 'head',\n 'put',\n 'patch',\n 'options',\n] as const;\n\nconst qsStringifyOptions: NonNullable<Parameters<typeof stringify>[1]> = { arrayFormat: 'brackets' };\n\ninterface NetworkSettings extends CreateAxiosDefaults, IAxiosRetryConfig {\n serviceName?: string;\n serviceUrl?: string;\n keepAlive?: boolean;\n logger?: LoggerInstanceManager;\n timeout?: number;\n}\n\nconst defaultSettings: NetworkSettings = {\n timeout: 10_000,\n headers: {\n 'X-AF-AUTH': 'ANYONE',\n 'X-IAF-ORIGIN-SERVICE': env.AF_SERVICE_NAME || null as unknown as string,\n },\n paramsSerializer: params => lazilyLoadQsStringify(params, qsStringifyOptions),\n 'axios-retry': {\n shouldResetTimeout: true,\n },\n keepAlive: true,\n};\n\nconst createRequestString = (request: AxiosRequestConfig): string => `[${(request.method || '').toUpperCase()}] ${request.baseURL ?? 'unknown-base-url'}${request.url ?? '/unknown-url'}`;\n\n/*\n The default free socket keepalive timeout, in milliseconds.\n Setting to 5000 (5 seconds) as default because out grace period is 10 seconds\n and we want to make sure we don't have any socket issues.\n See https://www.npmjs.com/package/agentkeepalive\n\n There is also autoscaling reason for that, if we don't timeout at some point,\n new pods that were auto scaled will not be used.\n*/\nconst FREE_SOCKET_TIMEOUT = Number.parseInt(env.FREE_SOCKET_TIMEOUT || '', 10) || 5_000;\n\nexport default class Network {\n readonly #logger: LoggerInstanceManager;\n private readonly settings: NetworkSettings;\n private readonly axios: AxiosInstance;\n\n public get!: AxiosInstance['get'];\n public post!: AxiosInstance['post'];\n public delete!: AxiosInstance['delete'];\n public head!: AxiosInstance['head'];\n public put!: AxiosInstance['put'];\n public patch!: AxiosInstance['patch'];\n public options!: AxiosInstance['options'];\n\n constructor(settings: NetworkSettings = {}) {\n this.#logger = settings.logger ?? Logger();\n this.settings = merge(defaultSettings, settings);\n if (this.settings.keepAlive) {\n this.settings.httpAgent = new HttpAgent({ freeSocketTimeout: FREE_SOCKET_TIMEOUT });\n this.settings.httpsAgent = new HttpsAgent({ freeSocketTimeout: FREE_SOCKET_TIMEOUT });\n delete this.settings.keepAlive;\n }\n this.#createBaseUrl();\n\n if (settings.cache) {\n this.settings.cache = {\n maxAge: 15 * 60 * 1000,\n // Store responses from requests with query parameters in cache\n exclude: { query: false },\n ...settings.cache,\n };\n }\n\n this.axios = settings.cache ? setup(this.settings as NetworkSettings & { headers: AxiosRequestHeaders; }) : axios.create(this.settings);\n this.#addRetry(settings);\n this.#buildClassHttpMethods();\n this.#addLogs();\n }\n\n #addRetry(settings: NetworkSettings): void {\n correctlyTypedAxiosRetry(this.axios, {\n retries: 0,\n retryDelay: axiosRetry.exponentialDelay,\n ...settings,\n });\n }\n\n #addLogs(): void {\n this.axios.interceptors.request.use((request) => {\n this.#logger.info(`Start Request: ${createRequestString(request)}`);\n return request;\n });\n\n this.axios.interceptors.response.use((response) => {\n this.#logger.info(`Finish Request: ${createRequestString(response.config)}`);\n return response;\n }, (error) => {\n if (error.request?._currentRequest?.reusedSocket && ['ECONNRESET', 'EPIPE'].includes(error.code)) {\n // See https://www.npmjs.com/package/agentkeepalive\n // Support req.reusedSocket\n // https://code-examples.net/en/q/28a8069\n this.#logger.warn(`${error.code} issue, will retry`, {\n req: error.request._currentRequest._currentUrl,\n // method: error.request._currentRequest._options.method,\n });\n return this.axios.request(error.config);\n }\n const request = error.config?.baseURL ? error.config : error.request;\n this.#logger.error(`Finish Request with error ${request ? createRequestString(request) : ''}`, {\n status: error.status,\n data: error.response?.data,\n });\n throw error;\n });\n }\n\n #createBaseUrl(): void {\n if (!this.settings.serviceUrl && !this.settings.serviceName) {\n throw new Error('At least one of the settings Missing serviceUrl or serviceName');\n }\n\n const { settings } = this;\n if (settings.serviceUrl) {\n settings.baseURL = settings.serviceUrl;\n } else if (settings.serviceName) {\n const envServiceHostName = `${settings.serviceName}_SERVICE_HOST`;\n settings.baseURL = `http://${env[envServiceHostName]}`;\n }\n }\n\n /**\n * Build class methods that wrap axios methods\n */\n #buildClassHttpMethods(): void {\n HTTPMethods.forEach((method) => {\n this[method] = <T = any, R = AxiosResponse<T>>(\n ...args: Parameters<AxiosInstance[typeof method]>\n ): Promise<R> => this.axios[method](...args as [url: string, leaveUsAlone?: AxiosRequestConfig<unknown>]);\n });\n }\n\n /**\n * @param url The endpoint URL to send the request to.\n * @param options Additional options to include in the request payload.\n * @returns A promise that resolves to an array of all results.\n */\n public async getAllPages<T>(url: string, options: object = {}): Promise<T[]> {\n const currentResult: T[] = [];\n let resultsInFirstPage: number | null = null;\n let lastResultsSize: number | null = null;\n\n const localOptions = { params: { page: 1 }, ...options };\n // Make sure even if `options` had `params` we initialize `page` to 1.\n localOptions.params.page ||= 1;\n while ((localOptions.params.page === 1 || lastResultsSize === resultsInFirstPage) && lastResultsSize !== 0) {\n const { data } = await this.get<T[]>(url, localOptions);\n lastResultsSize = data.length;\n if (localOptions.params.page === 1) {\n resultsInFirstPage = data.length;\n }\n\n localOptions.params.page += 1;\n Array.prototype.push.apply(currentResult, data);\n }\n\n return currentResult;\n }\n\n /**\n * Fetches all pages from a paginated API endpoint until all results are retrieved\n * or an optional page limit is reached.\n *\n * @param url The endpoint URL to send the request to.\n * @param options Additional options to include in the request payload.\n * @param pageLimit The maximum number of pages to fetch. Set to -1 for no limit.\n * @returns A promise that resolves to an array of all results.\n */\n public async getAllPagesFromQueryEndpoint<T>(url: string, options: object = {}, pageLimit = 100): Promise<T[]> {\n const currentResult: T[] = [];\n\n let moreResultsToLoad = true;\n let page = 1;\n while (moreResultsToLoad && (pageLimit === -1 || page < pageLimit)) {\n const { data } = await this.post<{ rows: T[]; count: number; }>(url, {\n ...options,\n page,\n });\n const { rows, count } = data;\n page += 1;\n Array.prototype.push.apply(currentResult, rows);\n moreResultsToLoad = currentResult.length < count;\n }\n\n return currentResult;\n }\n};\n"],"mappings":"kSAsBA,KAAM,CAAE,QAAO,CAAG,EACZ,EAA2B,EAE3B,EAAc,EAAc,OAAO,KAAK,IAAI,CAElD,IAAIA,EACJ,MAAM,EAAwB,CAAC,GAAG,KAChC,IAAgB,EAAY,KAAK,CAAC,UAC3B,EAAa,GAAG,EAAK,EAGxB,EAAc,CAClB,MACA,OACA,SACA,OACA,MACA,QACA,SACD,EAEKC,EAAmE,CAAE,YAAa,UAAY,EAU9FC,EAAmC,CACvC,QAAS,IACT,QAAS,CACP,YAAa,SACb,uBAAwB,EAAI,iBAAmB,IAChD,EACD,iBAAkB,GAAU,EAAsB,EAAQ,EAAmB,CAC7E,cAAe,CACb,mBAAoB,EACrB,EACD,UAAW,EACZ,EAEK,EAAsB,AAACC,GAAwC,CAAC,CAAC,GAAG,EAAQ,QAAU,IAAI,aAAa,CAAC,EAAE,EAAE,EAAQ,SAAW,qBAAqB,EAAQ,KAAO,gBAAgB,CAWnL,EAAsB,OAAO,SAAS,EAAI,qBAAuB,GAAI,GAAG,EAAI,IAElF,IAAqB,EAArB,KAA6B,CAC3B,QACA,SACA,MAEA,IACA,KACA,OACA,KACA,IACA,MACA,QAEA,YAAYE,EAA4B,CAAE,EAAE,CAC1C,KAAKD,QAAU,EAAS,QAAU,GAAQ,CAC1C,KAAK,SAAW,EAAM,EAAiB,EAAS,CAC5C,KAAK,SAAS,YAChB,KAAK,SAAS,UAAY,IAAI,EAAU,CAAE,kBAAmB,CAAqB,GAClF,KAAK,SAAS,WAAa,IAAI,EAAW,CAAE,kBAAmB,CAAqB,GACpF,OAAO,KAAK,SAAS,WAEvB,KAAKE,gBAAgB,CAEjB,EAAS,QACX,KAAK,SAAS,MAAQ,CACpB,OAAQ,IAAU,IAElB,QAAS,CAAE,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IAAM,EAAqB,GAAG,EAAS,YAAY,aAAa,CAAC,CACjE,EAAS,QAAU,CAAC,OAAO,EAAE,EAAI,IAAqB,AACvD,CACF,CAKD,wBAA+B,CAC7B,EAAY,QAAQ,AAAC,GAAW,CAC9B,KAAK,GAAU,CACb,GAAG,IACY,KAAK,MAAM,GAAQ,GAAG,EAAkE,AAC1G,EAAC,AACH,CAOD,MAAa,YAAeM,EAAaC,EAAkB,CAAE,EAAgB,CAC3E,IAAMC,EAAqB,CAAE,EACzBC,EAAoC,KACpCC,EAAiC,KAE/B,EAAe,CAAE,OAAQ,CAAE,KAAM,CAAG,EAAE,GAAG,CAAS,EAGxD,IADA,EAAa,OAAO,OAAS,GACrB,EAAa,OAAO,OAAS,GAAK,IAAoB,IAAuB,IAAoB,GAAG,CAC1G,GAAM,CAAE,OAAM,CAAG,MAAM,KAAK,IAAS,EAAK,EAAa,CACvD,EAAkB,EAAK,OACnB,EAAa,OAAO,OAAS,IAC/B,EAAqB,EAAK,QAG5B,EAAa,OAAO,MAAQ,EAC5B,MAAM,UAAU,KAAK,MAAM,EAAe,EAAK,AAChD,CAED,OAAO,CACR,CAWD,MAAa,6BAAgCJ,EAAaC,EAAkB,CAAE,EAAE,EAAY,IAAmB,CAC7G,IAAMC,EAAqB,CAAE,EAEzB,EAAoB,GACpB,EAAO,EACX,KAAO,IAAsB,IAAc,IAAM,EAAO,IAAY,CAClE,GAAM,CAAE,OAAM,CAAG,MAAM,KAAK,KAAoC,EAAK,CACnE,GAAG,EACH,MACD,EAAC,CACI,CAAE,OAAM,QAAO,CAAG,EACxB,GAAQ,EACR,MAAM,UAAU,KAAK,MAAM,EAAe,EAAK,CAC/C,EAAoB,EAAc,OAAS,CAC5C,CAED,OAAO,CACR,CACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autofleet/network",
3
- "version": "1.8.1",
3
+ "version": "1.8.3",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "./lib/index.cjs",
@@ -22,18 +22,19 @@
22
22
  "lib"
23
23
  ],
24
24
  "scripts": {
25
- "test": "tsx index.test.js",
26
- "build": "tsup"
25
+ "test": "tsx --test",
26
+ "coverage": "tsx --test --experimental-test-coverage",
27
+ "build": "tsdown"
27
28
  },
28
29
  "engines": {
29
30
  "node": ">=18"
30
31
  },
31
32
  "author": "Dor Shay",
32
- "license": "ISC",
33
+ "license": "Proprietary",
33
34
  "dependencies": {
34
35
  "@autofleet/axios-cache-adapter": "^2.7.3-hotfix-1",
35
36
  "agentkeepalive": "^4.6.0",
36
- "axios": "^0.29.0",
37
+ "axios": "^0.30.1",
37
38
  "axios-retry": "^4.5.0",
38
39
  "deepmerge": "^4.3.1",
39
40
  "qs": "^6.14.0"
@@ -47,8 +48,6 @@
47
48
  "@types/qs": "^6.9.18",
48
49
  "dotenv": "^16.4.7",
49
50
  "nock": "^14.0.1",
50
- "tsup": "^8.3.6",
51
- "tsx": "^4.19.2",
52
- "typescript": "^5.7.3"
51
+ "tsx": "^4.20.4"
53
52
  }
54
53
  }