axios-cache-interceptor
Advanced tools
Comparing version 0.10.7 to 1.0.0
@@ -1,2 +0,2 @@ | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.AxiosCacheInterceptor=t():e.AxiosCacheInterceptor=t()}("undefined"!=typeof self?self:this,(()=>(()=>{"use strict";var e={d:(t,a)=>{for(var r in a)e.o(a,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:a[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{Header:()=>i,buildKeyGenerator:()=>A,buildMemoryStorage:()=>x,buildStorage:()=>w,buildWebStorage:()=>E,canStale:()=>b,createCacheResponse:()=>f,createValidateStatus:()=>d,defaultHeaderInterpreter:()=>s,defaultKeyGenerator:()=>j,defaultRequestInterceptor:()=>g,defaultResponseInterceptor:()=>m,isExpired:()=>y,isMethodIn:()=>u,isStorage:()=>v,setupCache:()=>O,testCachePredicate:()=>h,updateCache:()=>p,updateStaleRequest:()=>l});var a=Symbol("cache-parser");function r(e){return("string"==typeof e||"number"==typeof e)&&(e=Number(e))>=0&&e<1/0}function n(e){return!0===e||"number"==typeof e||"string"==typeof e&&"false"!==e}var o=Number;const i=Object.freeze({IfModifiedSince:"if-modified-since",LastModified:"last-modified",IfNoneMatch:"if-none-match",CacheControl:"cache-control",ETag:"etag",Expires:"expires",Age:"age",XAxiosCacheEtag:"x-axios-cache-etag",XAxiosCacheLastModified:"x-axios-cache-last-modified",XAxiosCacheStaleIfError:"x-axios-cache-stale-if-error"}),s=e=>{if(!e)return"not enough headers";const t=e[i.CacheControl];if(t){const{noCache:s,noStore:c,mustRevalidate:d,maxAge:u,immutable:l}=function(e){var t=Object.defineProperty({},a,{enumerable:!1,value:1});if(!e||"string"!=typeof e)return t;var i=function(e){var t={},a=e.toLowerCase().replace(/\s+/g,"").split(",");for(var r in a){var n,o=a[r].split("=",2);t[o[0]]=null==(n=o[1])||n}return t}(e),s=i["max-age"],c=i["max-stale"],d=i["min-fresh"],u=i["s-maxage"],l=i["stale-if-error"],f=i["stale-while-revalidate"];return n(i.immutable)&&(t.immutable=!0),r(s)&&(t.maxAge=o(s)),r(c)&&(t.maxStale=o(c)),r(d)&&(t.minFresh=o(d)),n(i["must-revalidate"])&&(t.mustRevalidate=!0),n(i["must-understand"])&&(t.mustUnderstand=!0),n(i["no-cache"])&&(t.noCache=!0),n(i["no-store"])&&(t.noStore=!0),n(i["no-transform"])&&(t.noTransform=!0),n(i["only-if-cached"])&&(t.onlyIfCached=!0),n(i.private)&&(t.private=!0),n(i["proxy-revalidate"])&&(t.proxyRevalidate=!0),n(i.public)&&(t.public=!0),r(u)&&(t.sMaxAge=o(u)),r(l)&&(t.staleIfError=o(l)),r(f)&&(t.staleWhileRevalidate=o(f)),t}(String(t));if(s||c)return"dont cache";if(l)return 31536e6;if(d)return 0;if(void 0!==u){const t=e[i.Age];return t?1e3*(u-Number(t)):1e3*u}}const s=e[i.Expires];if(s){const e=Date.parse(String(s))-Date.now();return e>=0?e:"dont cache"}return"not enough headers"};var c=Symbol();function d(e){return e?t=>e(t)||304===t:e=>e>=200&&e<300||304===e}function u(e="get",t=[]){return e=e.toLowerCase(),t.some((t=>t===e))}function l(e,t){var a;t.headers||(t.headers={});const{etag:r,modifiedSince:n}=t.cache;if(r){const n=!0===r?null===(a=e.data)||void 0===a?void 0:a.headers[i.ETag]:r;n&&(t.headers[i.IfNoneMatch]=n)}n&&(t.headers[i.IfModifiedSince]=!0===n?e.data.headers[i.LastModified]||new Date(e.createdAt).toUTCString():n.toUTCString())}function f(e,t){return 304===e.status&&t?(e.cached=!0,e.data=t.data,e.status=t.status,e.statusText=t.statusText,e.headers=Object.assign(Object.assign({},t.headers),e.headers),t):{data:e.data,status:e.status,statusText:e.statusText,headers:e.headers}}function g(e){const t=async t=>{var a,r,n,o,i,s,f,g,h;const p=t.id=e.generateKey(t);if(!1===t.cache)return null===(a=e.debug)||void 0===a||a.call(e,{msg:"Ignoring cache because config.cache === false",data:t}),t;if(t.cache=Object.assign(Object.assign({},e.defaults.cache),t.cache),!u(t.method,t.cache.methods))return null===(r=e.debug)||void 0===r||r.call(e,{msg:`Ignored because method (${t.method}) is not in cache.methods (${t.cache.methods})`}),t;let m=await e.storage.get(p,t);const v=t.cache.override;e:if("empty"===m.state||"stale"===m.state||v){if(e.waiting[p]&&!v&&(m=await e.storage.get(p,t),"empty"!==m.state)){null===(n=e.debug)||void 0===n||n.call(e,{id:p,msg:"Waiting list had an deferred for this key, waiting for it to finish"});break e}return e.waiting[p]=function(){var e,t,a=new Promise((function(a,r){e=a,t=r}));return a.resolve=e,a.reject=t,a[c]=1,a}(),null===(o=e.waiting[p])||void 0===o||o.catch((()=>{})),await e.storage.set(p,{state:"loading",previous:v?m.data?"stale":"empty":m.state,data:m.data,createdAt:v&&!m.createdAt?Date.now():m.createdAt},t),"stale"===m.state&&(l(m,t),null===(i=e.debug)||void 0===i||i.call(e,{id:p,msg:"Updated stale request"})),t.validateStatus=d(t.validateStatus),null===(s=e.debug)||void 0===s||s.call(e,{id:p,msg:"Sending request, waiting for response",data:{overrideCache:v,state:m.state}}),t}let b;if("loading"===m.state){const a=e.waiting[p];if(!a)return await e.storage.remove(p,t),t;null===(f=e.debug)||void 0===f||f.call(e,{id:p,msg:"Detected concurrent request, waiting for it to finish"});try{b=await a}catch(a){return null===(g=e.debug)||void 0===g||g.call(e,{id:p,msg:"Deferred rejected, requesting again",data:a}),t}}else b=m.data;return t.adapter=()=>Promise.resolve({config:t,data:b.data,headers:b.headers,status:b.status,statusText:b.statusText,cached:!0,id:p}),null===(h=e.debug)||void 0===h||h.call(e,{id:p,msg:"Returning cached response"}),t};return{onFulfilled:t,apply:()=>e.interceptors.request.use(t)}}async function h(e,t){var a;if("function"==typeof t)return t(e);const{statusCheck:r,responseMatch:n,containsHeaders:o}=t;if(r&&!await r(e.status)||n&&!await n(e))return!1;if(o)for(const[t,r]of Object.entries(o))if(!await r(null!==(a=e.headers[t.toLowerCase()])&&void 0!==a?a:e.headers[t]))return!1;return!0}async function p(e,t,a){if("function"==typeof a)return a(t);for(const[r,n]of Object.entries(a)){if("delete"===n){await e.remove(r,t.config);continue}const a=await e.get(r,t.config);if("loading"===a.state)continue;const o=await n(a,t);"delete"!==o?"ignore"!==o&&await e.set(r,o,t.config):await e.remove(r,t.config)}}function m(e){const t=async(t,a)=>{var r;await e.storage.remove(t,a),null===(r=e.waiting[t])||void 0===r||r.reject(),delete e.waiting[t]},a=async a=>{var r,n,o,s,c,d,u,l,g,m,v;const b=a.id=null!==(r=(v=a.config).id)&&void 0!==r?r:v.id=e.generateKey(a.config);if(null!==(n=a.cached)&&void 0!==n||(a.cached=!1),a.cached)return null===(o=e.debug)||void 0===o||o.call(e,{id:b,msg:"Returned cached response"}),a;const y=a.config.cache;if(!y)return null===(s=e.debug)||void 0===s||s.call(e,{id:b,msg:"Response with config.cache falsy",data:a}),Object.assign(Object.assign({},a),{cached:!1});const w=a.config,x=await e.storage.get(b,w);if((null==y?void 0:y.update)&&await p(e.storage,a,y.update),"loading"!==x.state)return null===(c=e.debug)||void 0===c||c.call(e,{id:b,msg:"Response not cached and storage isn't loading",data:{cache:x,response:a}}),a;if(!x.data&&!await h(a,y.cachePredicate))return await t(b,w),null===(d=e.debug)||void 0===d||d.call(e,{id:b,msg:"Cache predicate rejected this response"}),a;for(const e of Object.keys(a.headers))e.startsWith("x-axios-cache")&&delete a.headers[e];y.etag&&!0!==y.etag&&(a.headers[i.XAxiosCacheEtag]=y.etag),y.modifiedSince&&(a.headers[i.XAxiosCacheLastModified]=!0===y.modifiedSince?"use-cache-timestamp":y.modifiedSince.toUTCString());let S=y.ttl||-1;if(null==y?void 0:y.interpretHeader){const r=e.headerInterpreter(a.headers);if("dont cache"===r)return await t(b,w),null===(u=e.debug)||void 0===u||u.call(e,{id:b,msg:"Cache header interpreted as 'dont cache'",data:{cache:x,response:a,expirationTime:r}}),a;S="not enough headers"===r?S:r}const I=f(a,x.data);"function"==typeof S&&(S=await S(a)),y.staleIfError&&(a.headers[i.XAxiosCacheStaleIfError]=String(S)),null===(l=e.debug)||void 0===l||l.call(e,{id:b,msg:"Useful response configuration found",data:{cacheConfig:y,cacheResponse:I}});const C={state:"cached",ttl:S,createdAt:Date.now(),data:I},A=e.waiting[b];return A&&(A.resolve(C.data),delete e.waiting[b],null===(g=e.debug)||void 0===g||g.call(e,{id:b,msg:"Found waiting deferred(s) and resolved them"})),await e.storage.set(b,C,w),null===(m=e.debug)||void 0===m||m.call(e,{id:b,msg:"Response cached",data:{cache:C,response:a}}),a},r=async a=>{var r,n,o,i,s,c;const d=a.config;if(!(null==d?void 0:d.cache)||!d.id)throw null===(r=e.debug)||void 0===r||r.call(e,{msg:"Web request returned an error but cache handling is not enabled",data:{error:a}}),a;const u=await e.storage.get(d.id,d),l=d.cache;if("loading"!==u.state||"stale"!==u.previous)throw await t(d.id,d),null===(n=e.debug)||void 0===n||n.call(e,{msg:"Caught an error in the request interceptor",data:{error:a,config:d}}),a;if(null==l?void 0:l.staleIfError){const t="function"==typeof l.staleIfError?await l.staleIfError(a.response,u,a):l.staleIfError;if(null===(o=e.debug)||void 0===o||o.call(e,{msg:"Found cache if stale config for rejected response",data:{error:a,config:d,staleIfError:t}}),!0===t||"number"==typeof t&&u.createdAt+t>Date.now())return null===(i=e.waiting[d.id])||void 0===i||i.resolve(u.data),delete e.waiting[d.id],await e.storage.set(d.id,{state:"stale",createdAt:Date.now(),data:u.data},d),null===(s=e.debug)||void 0===s||s.call(e,{msg:"staleIfError resolved this response with cached data",data:{error:a,config:d,cache:u}}),{cached:!0,config:d,id:d.id,data:u.data.data,headers:u.data.headers,status:u.data.status,statusText:u.data.statusText}}throw null===(c=e.debug)||void 0===c||c.call(e,{msg:"Received an unknown error that could not be handled",data:{error:a,config:d}}),a};return{onFulfilled:a,onRejected:r,apply:()=>e.interceptors.response.use(a,r)}}const v=e=>!!e&&!!e["is-storage"];function b(e){const t=e.data.headers;return i.ETag in t||i.LastModified in t||i.XAxiosCacheEtag in t||i.XAxiosCacheStaleIfError in t||i.XAxiosCacheLastModified in t}function y(e){return e.createdAt+e.ttl<=Date.now()}function w({set:e,find:t,remove:a}){return{"is-storage":1,set:e,remove:a,get:async(r,n)=>{const o=await t(r,n);if(!o)return{state:"empty"};if("cached"!==o.state||!y(o))return o;if(b(o)){const t={state:"stale",createdAt:o.createdAt,data:o.data};return await e(r,t,n),t}return await a(r,n),{state:"empty"}}}}function x(e=!1){const t=w({set:(e,a)=>{t.data[e]=a},remove:e=>{delete t.data[e]},find:a=>{const r=t.data[a];return e&&void 0!==r?"function"==typeof structuredClone?structuredClone(r):JSON.parse(JSON.stringify(r)):r}});return t.data=Object.create(null),t}function S(e){var t=typeof e;if(e&&"object"===t&&!(e instanceof Date||e instanceof RegExp)){for(var a=Array.isArray(e)?[]:{},r=Object.keys(e).sort((function(e,t){return e>t?1:-1})),n=r.length;n--;){var o=r[n];a[o]=S(e[o])}return String(e.constructor)+JSON.stringify(a,r)}return t+String(e)}function I(e){e=S(e);for(var t=5381,a=0;a<e.length;)t=33*t^e.charCodeAt(a++);return t}const C=/^\/|\/$/g;function A(e){return t=>{if(t.id)return t.id;const a=e(t);return"string"==typeof a||"number"==typeof a?`${a}`:`${I(a)}`}}const j=A((({baseURL:e="",url:t="",method:a="get",params:r,data:n})=>(e&&(e=e.replace(C,"")),t&&(t=t.replace(C,"")),a&&(a=a.toLowerCase()),{url:e+(e&&t?"/":"")+t,params:r,method:a,data:n})));function O(e,t={}){var a,r,n,o,i;const c=e;if(c.storage=t.storage||x(),!v(c.storage))throw new Error("Use buildStorage() function");return c.waiting=t.waiting||{},c.generateKey=t.generateKey||j,c.headerInterpreter=t.headerInterpreter||s,c.requestInterceptor=t.requestInterceptor||g(c),c.responseInterceptor=t.responseInterceptor||m(c),c.debug=t.debug,c.defaults.cache={update:t.update||{},ttl:null!==(a=t.ttl)&&void 0!==a?a:3e5,methods:t.methods||["get"],cachePredicate:t.cachePredicate||{statusCheck:e=>e>=200&&e<400},etag:null===(r=t.etag)||void 0===r||r,modifiedSince:null!==(n=t.modifiedSince)&&void 0!==n?n:!1===t.etag,interpretHeader:null===(o=t.interpretHeader)||void 0===o||o,staleIfError:null===(i=t.staleIfError)||void 0===i||i,override:!1},c.requestInterceptor.apply(),c.responseInterceptor.apply(),c}function E(e,t=""){return w({find:a=>{const r=e.getItem(t+a);return r?JSON.parse(r):void 0},remove:a=>{e.removeItem(t+a)},set:(a,r)=>{const n=()=>e.setItem(t+a,JSON.stringify(r));try{return n()}catch(r){const o=Object.entries(e).filter((e=>e[0].startsWith(t))).map((e=>[e[0],JSON.parse(e[1])]));for(const t of o)"cached"===t[1].state&&y(t[1])&&!b(t[1])&&e.removeItem(t[0]);try{return n()}catch(t){const a=o.sort(((e,t)=>(e[1].createdAt||0)-(t[1].createdAt||0)));for(const t of a){e.removeItem(t[0]);try{return n()}catch(e){}}}e.removeItem(t+a)}}})}return console.error("You are using a development build. Make sure to use the correct build in production\nhttps://axios-cache-interceptor.js.org/#/pages/installing\n\n"),t})())); | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.AxiosCacheInterceptor=t():e.AxiosCacheInterceptor=t()}("undefined"!=typeof self?self:this,(()=>(()=>{"use strict";var e={d:(t,a)=>{for(var r in a)e.o(a,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:a[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{Header:()=>i,buildKeyGenerator:()=>A,buildMemoryStorage:()=>x,buildStorage:()=>w,buildWebStorage:()=>O,canStale:()=>b,createCacheResponse:()=>f,createValidateStatus:()=>d,defaultHeaderInterpreter:()=>s,defaultKeyGenerator:()=>j,defaultRequestInterceptor:()=>g,defaultResponseInterceptor:()=>m,isExpired:()=>y,isMethodIn:()=>u,isStorage:()=>v,setupCache:()=>E,testCachePredicate:()=>h,updateCache:()=>p,updateStaleRequest:()=>l});var a=Symbol("cache-parser");function r(e){return("string"==typeof e||"number"==typeof e)&&(e=Number(e))>=0&&e<1/0}function n(e){return!0===e||"number"==typeof e||"string"==typeof e&&"false"!==e}var o=Number;const i=Object.freeze({IfModifiedSince:"if-modified-since",LastModified:"last-modified",IfNoneMatch:"if-none-match",CacheControl:"cache-control",Pragma:"pragma",ETag:"etag",Expires:"expires",Age:"age",XAxiosCacheEtag:"x-axios-cache-etag",XAxiosCacheLastModified:"x-axios-cache-last-modified",XAxiosCacheStaleIfError:"x-axios-cache-stale-if-error"}),s=e=>{if(!e)return"not enough headers";const t=e[i.CacheControl];if(t){const{noCache:s,noStore:c,mustRevalidate:d,maxAge:u,immutable:l}=function(e){var t=Object.defineProperty({},a,{enumerable:!1,value:1});if(!e||"string"!=typeof e)return t;var i=function(e){var t={},a=e.toLowerCase().replace(/\s+/g,"").split(",");for(var r in a){var n,o=a[r].split("=",2);t[o[0]]=null==(n=o[1])||n}return t}(e),s=i["max-age"],c=i["max-stale"],d=i["min-fresh"],u=i["s-maxage"],l=i["stale-if-error"],f=i["stale-while-revalidate"];return n(i.immutable)&&(t.immutable=!0),r(s)&&(t.maxAge=o(s)),r(c)&&(t.maxStale=o(c)),r(d)&&(t.minFresh=o(d)),n(i["must-revalidate"])&&(t.mustRevalidate=!0),n(i["must-understand"])&&(t.mustUnderstand=!0),n(i["no-cache"])&&(t.noCache=!0),n(i["no-store"])&&(t.noStore=!0),n(i["no-transform"])&&(t.noTransform=!0),n(i["only-if-cached"])&&(t.onlyIfCached=!0),n(i.private)&&(t.private=!0),n(i["proxy-revalidate"])&&(t.proxyRevalidate=!0),n(i.public)&&(t.public=!0),r(u)&&(t.sMaxAge=o(u)),r(l)&&(t.staleIfError=o(l)),r(f)&&(t.staleWhileRevalidate=o(f)),t}(String(t));if(s||c)return"dont cache";if(l)return 31536e6;if(d)return 0;if(void 0!==u){const t=e[i.Age];return t?1e3*(u-Number(t)):1e3*u}}const s=e[i.Expires];if(s){const e=Date.parse(String(s))-Date.now();return e>=0?e:"dont cache"}return"not enough headers"};var c=Symbol();function d(e){return e?t=>e(t)||304===t:e=>e>=200&&e<300||304===e}function u(e="get",t=[]){return e=e.toLowerCase(),t.some((t=>t===e))}function l(e,t){var a;t.headers||(t.headers={});const{etag:r,modifiedSince:n}=t.cache;if(r){const n=!0===r?null===(a=e.data)||void 0===a?void 0:a.headers[i.ETag]:r;n&&(t.headers[i.IfNoneMatch]=n)}n&&(t.headers[i.IfModifiedSince]=!0===n?e.data.headers[i.LastModified]||new Date(e.createdAt).toUTCString():n.toUTCString())}function f(e,t){return 304===e.status&&t?(e.cached=!0,e.data=t.data,e.status=t.status,e.statusText=t.statusText,e.headers=Object.assign(Object.assign({},t.headers),e.headers),t):{data:e.data,status:e.status,statusText:e.statusText,headers:e.headers}}function g(e){const t=async t=>{var a,r,n,o,s,f,g,h,p,m,v,b,y,w,x,S,C,I;const A=t.id=e.generateKey(t);if(!1===t.cache)return null===(a=e.debug)||void 0===a||a.call(e,{msg:"Ignoring cache because config.cache === false",data:t}),t;if(t.cache=Object.assign(Object.assign({},e.defaults.cache),t.cache),t.cache.cacheTakeover&&(null!==(r=t.headers)&&void 0!==r||(t.headers={}),null!==(n=(y=t.headers)[w=i.CacheControl])&&void 0!==n||(y[w]="no-cache"),null!==(o=(x=t.headers)[S=i.Pragma])&&void 0!==o||(x[S]="no-cache"),null!==(s=(C=t.headers)[I=i.Expires])&&void 0!==s||(C[I]="0")),!u(t.method,t.cache.methods))return null===(f=e.debug)||void 0===f||f.call(e,{msg:`Ignored because method (${t.method}) is not in cache.methods (${t.cache.methods})`}),t;let j=await e.storage.get(A,t);const E=t.cache.override;e:if("empty"===j.state||"stale"===j.state||E){if(e.waiting[A]&&!E&&(j=await e.storage.get(A,t),"empty"!==j.state)){null===(g=e.debug)||void 0===g||g.call(e,{id:A,msg:"Waiting list had an deferred for this key, waiting for it to finish"});break e}return e.waiting[A]=function(){var e,t,a=new Promise((function(a,r){e=a,t=r}));return a.resolve=e,a.reject=t,a[c]=1,a}(),e.waiting[A].catch((()=>{})),await e.storage.set(A,{state:"loading",previous:E?j.data?"stale":"empty":j.state,data:j.data,createdAt:E&&!j.createdAt?Date.now():j.createdAt},t),"stale"===j.state&&(l(j,t),null===(h=e.debug)||void 0===h||h.call(e,{id:A,msg:"Updated stale request"})),t.validateStatus=d(t.validateStatus),null===(p=e.debug)||void 0===p||p.call(e,{id:A,msg:"Sending request, waiting for response",data:{overrideCache:E,state:j.state}}),t}let O;if("loading"===j.state){const a=e.waiting[A];if(!a)return await e.storage.remove(A,t),t;null===(m=e.debug)||void 0===m||m.call(e,{id:A,msg:"Detected concurrent request, waiting for it to finish"});try{O=await a}catch(a){return null===(v=e.debug)||void 0===v||v.call(e,{id:A,msg:"Deferred rejected, requesting again",data:a}),t}}else O=j.data;return t.adapter=()=>Promise.resolve({config:t,data:O.data,headers:O.headers,status:O.status,statusText:O.statusText,cached:!0,id:A}),null===(b=e.debug)||void 0===b||b.call(e,{id:A,msg:"Returning cached response"}),t};return{onFulfilled:t,apply:()=>e.interceptors.request.use(t)}}async function h(e,t){var a;if("function"==typeof t)return t(e);const{statusCheck:r,responseMatch:n,containsHeaders:o}=t;if(r&&!await r(e.status)||n&&!await n(e))return!1;if(o)for(const[t,r]of Object.entries(o))if(!await r(null!==(a=e.headers[t.toLowerCase()])&&void 0!==a?a:e.headers[t]))return!1;return!0}async function p(e,t,a){if("function"==typeof a)return a(t);for(const[r,n]of Object.entries(a)){if("delete"===n){await e.remove(r,t.config);continue}const a=await e.get(r,t.config);if("loading"===a.state)continue;const o=await n(a,t);"delete"!==o?"ignore"!==o&&await e.set(r,o,t.config):await e.remove(r,t.config)}}function m(e){const t=async(t,a)=>{var r;await e.storage.remove(t,a),null===(r=e.waiting[t])||void 0===r||r.reject(),delete e.waiting[t]},a=async a=>{var r,n,o,s,c,d,u,l,g,m,v;const b=a.id=null!==(r=(v=a.config).id)&&void 0!==r?r:v.id=e.generateKey(a.config);if(null!==(n=a.cached)&&void 0!==n||(a.cached=!1),a.cached)return null===(o=e.debug)||void 0===o||o.call(e,{id:b,msg:"Returned cached response"}),a;const y=a.config.cache;if(!y)return null===(s=e.debug)||void 0===s||s.call(e,{id:b,msg:"Response with config.cache falsy",data:a}),Object.assign(Object.assign({},a),{cached:!1});const w=a.config,x=await e.storage.get(b,w);if((null==y?void 0:y.update)&&await p(e.storage,a,y.update),"loading"!==x.state)return null===(c=e.debug)||void 0===c||c.call(e,{id:b,msg:"Response not cached and storage isn't loading",data:{cache:x,response:a}}),a;if(!x.data&&!await h(a,y.cachePredicate))return await t(b,w),null===(d=e.debug)||void 0===d||d.call(e,{id:b,msg:"Cache predicate rejected this response"}),a;for(const e of Object.keys(a.headers))e.startsWith("x-axios-cache")&&delete a.headers[e];y.etag&&!0!==y.etag&&(a.headers[i.XAxiosCacheEtag]=y.etag),y.modifiedSince&&(a.headers[i.XAxiosCacheLastModified]=!0===y.modifiedSince?"use-cache-timestamp":y.modifiedSince.toUTCString());let S=y.ttl||-1;if(null==y?void 0:y.interpretHeader){const r=e.headerInterpreter(a.headers);if("dont cache"===r)return await t(b,w),null===(u=e.debug)||void 0===u||u.call(e,{id:b,msg:"Cache header interpreted as 'dont cache'",data:{cache:x,response:a,expirationTime:r}}),a;S="not enough headers"===r?S:r}const C=f(a,x.data);"function"==typeof S&&(S=await S(a)),y.staleIfError&&(a.headers[i.XAxiosCacheStaleIfError]=String(S)),null===(l=e.debug)||void 0===l||l.call(e,{id:b,msg:"Useful response configuration found",data:{cacheConfig:y,cacheResponse:C}});const I={state:"cached",ttl:S,createdAt:Date.now(),data:C},A=e.waiting[b];return A&&(A.resolve(I.data),delete e.waiting[b],null===(g=e.debug)||void 0===g||g.call(e,{id:b,msg:"Found waiting deferred(s) and resolved them"})),await e.storage.set(b,I,w),null===(m=e.debug)||void 0===m||m.call(e,{id:b,msg:"Response cached",data:{cache:I,response:a}}),a},r=async a=>{var r,n,o,i,s,c;const d=a.config;if(!(null==d?void 0:d.cache)||!d.id)throw null===(r=e.debug)||void 0===r||r.call(e,{msg:"Web request returned an error but cache handling is not enabled",data:{error:a}}),a;const u=await e.storage.get(d.id,d),l=d.cache;if("loading"!==u.state||"stale"!==u.previous)throw await t(d.id,d),null===(n=e.debug)||void 0===n||n.call(e,{msg:"Caught an error in the request interceptor",data:{error:a,config:d}}),a;if(null==l?void 0:l.staleIfError){const t="function"==typeof l.staleIfError?await l.staleIfError(a.response,u,a):l.staleIfError;if(null===(o=e.debug)||void 0===o||o.call(e,{msg:"Found cache if stale config for rejected response",data:{error:a,config:d,staleIfError:t}}),!0===t||"number"==typeof t&&u.createdAt+t>Date.now())return null===(i=e.waiting[d.id])||void 0===i||i.resolve(u.data),delete e.waiting[d.id],await e.storage.set(d.id,{state:"stale",createdAt:Date.now(),data:u.data},d),null===(s=e.debug)||void 0===s||s.call(e,{msg:"staleIfError resolved this response with cached data",data:{error:a,config:d,cache:u}}),{cached:!0,config:d,id:d.id,data:u.data.data,headers:u.data.headers,status:u.data.status,statusText:u.data.statusText}}throw null===(c=e.debug)||void 0===c||c.call(e,{msg:"Received an unknown error that could not be handled",data:{error:a,config:d}}),a};return{onFulfilled:a,onRejected:r,apply:()=>e.interceptors.response.use(a,r)}}const v=e=>!!e&&!!e["is-storage"];function b(e){const t=e.data.headers;return i.ETag in t||i.LastModified in t||i.XAxiosCacheEtag in t||i.XAxiosCacheStaleIfError in t||i.XAxiosCacheLastModified in t}function y(e){return e.createdAt+e.ttl<=Date.now()}function w({set:e,find:t,remove:a}){return{"is-storage":1,set:e,remove:a,get:async(r,n)=>{const o=await t(r,n);if(!o)return{state:"empty"};if("cached"!==o.state||!y(o))return o;if(b(o)){const t={state:"stale",createdAt:o.createdAt,data:o.data};return await e(r,t,n),t}return await a(r,n),{state:"empty"}}}}function x(e=!1){const t=w({set:(e,a)=>{t.data[e]=a},remove:e=>{delete t.data[e]},find:a=>{const r=t.data[a];return e&&void 0!==r?"function"==typeof structuredClone?structuredClone(r):JSON.parse(JSON.stringify(r)):r}});return t.data=Object.create(null),t}function S(e){var t=typeof e;if(e&&"object"===t&&!(e instanceof Date||e instanceof RegExp)){for(var a=Array.isArray(e)?[]:{},r=Object.keys(e).sort((function(e,t){return e>t?1:-1})),n=r.length;n--;){var o=r[n];a[o]=S(e[o])}return String(e.constructor)+JSON.stringify(a,r)}return t+String(e)}function C(e){e=S(e);for(var t=5381,a=0;a<e.length;)t=33*t^e.charCodeAt(a++);return t}const I=/^\/|\/$/g;function A(e){return t=>{if(t.id)return t.id;const a=e(t);return"string"==typeof a||"number"==typeof a?`${a}`:`${C(a)}`}}const j=A((({baseURL:e="",url:t="",method:a="get",params:r,data:n})=>(e&&(e=e.replace(I,"")),t&&(t=t.replace(I,"")),a&&(a=a.toLowerCase()),{url:e+(e&&t?"/":"")+t,params:r,method:a,data:n})));function E(e,t={}){var a,r,n,o,i,c;const d=e;if(d.storage=t.storage||x(),!v(d.storage))throw new Error("Use buildStorage() function");return d.waiting=t.waiting||{},d.generateKey=t.generateKey||j,d.headerInterpreter=t.headerInterpreter||s,d.requestInterceptor=t.requestInterceptor||g(d),d.responseInterceptor=t.responseInterceptor||m(d),d.debug=t.debug,d.defaults.cache={update:t.update||{},ttl:null!==(a=t.ttl)&&void 0!==a?a:3e5,methods:t.methods||["get"],cachePredicate:t.cachePredicate||{statusCheck:e=>e>=200&&e<400},etag:null===(r=t.etag)||void 0===r||r,modifiedSince:null!==(n=t.modifiedSince)&&void 0!==n?n:!1===t.etag,interpretHeader:null===(o=t.interpretHeader)||void 0===o||o,cacheTakeover:null===(i=t.cacheTakeover)||void 0===i||i,staleIfError:null===(c=t.staleIfError)||void 0===c||c,override:!1},d.requestInterceptor.apply(),d.responseInterceptor.apply(),d}function O(e,t="axios-cache-"){return w({find:a=>{const r=e.getItem(t+a);return r?JSON.parse(r):void 0},remove:a=>{e.removeItem(t+a)},set:(a,r)=>{const n=()=>e.setItem(t+a,JSON.stringify(r));try{return n()}catch(r){const o=Object.entries(e).filter((e=>e[0].startsWith(t))).map((e=>[e[0],JSON.parse(e[1])]));for(const t of o)"cached"===t[1].state&&y(t[1])&&!b(t[1])&&e.removeItem(t[0]);try{return n()}catch(t){const a=o.sort(((e,t)=>(e[1].createdAt||0)-(t[1].createdAt||0)));for(const t of a){e.removeItem(t[0]);try{return n()}catch(e){}}}e.removeItem(t+a)}}})}return console.error("You are using a development build. Make sure to use the correct build in production\nhttps://axios-cache-interceptor.js.org/#/pages/installing\n\n"),t})())); | ||
//# sourceMappingURL=index.bundle.js.map |
@@ -1,2 +0,2 @@ | ||
import type { AxiosDefaults, AxiosInstance, AxiosInterceptorManager, AxiosRequestConfig, AxiosResponse } from 'axios'; | ||
import type { AxiosInstance, AxiosInterceptorManager, AxiosRequestConfig, AxiosResponse } from 'axios'; | ||
import type { CacheInstance, CacheProperties } from './cache'; | ||
@@ -7,3 +7,3 @@ /** | ||
*/ | ||
export declare type CacheAxiosResponse<R = any, D = any> = AxiosResponse<R, D> & { | ||
export type CacheAxiosResponse<R = any, D = any> = AxiosResponse<R, D> & { | ||
config: CacheRequestConfig<R, D>; | ||
@@ -21,3 +21,3 @@ /** The id used for this request. if config specified an id, the id will be returned */ | ||
*/ | ||
export declare type CacheRequestConfig<R = any, D = any> = AxiosRequestConfig<D> & { | ||
export type CacheRequestConfig<R = any, D = any> = AxiosRequestConfig<D> & { | ||
/** | ||
@@ -59,3 +59,3 @@ * An id for this request, if this request is used in cache, only the last request made | ||
<T = any, D = any, R = CacheAxiosResponse<T, D>>(url: string, config?: CacheRequestConfig<T, D>): Promise<R>; | ||
defaults: AxiosDefaults<any> & { | ||
defaults: AxiosInstance['defaults'] & { | ||
cache: CacheProperties; | ||
@@ -62,0 +62,0 @@ }; |
@@ -12,7 +12,8 @@ import type { Method } from 'axios'; | ||
*/ | ||
export declare type CacheProperties<R = unknown, D = unknown> = { | ||
export type CacheProperties<R = unknown, D = unknown> = { | ||
/** | ||
* The time until the cached value is expired in milliseconds. | ||
* | ||
* If a function is used, it will receive the complete response and waits to return a TTL value | ||
* If a function is used, it will receive the complete response and waits to return a | ||
* TTL value | ||
* | ||
@@ -33,2 +34,9 @@ * When using `interpretHeader: true`, this value will only be used if the interpreter | ||
/** | ||
* If this interceptor should include some headers in the request to tell any possible | ||
* adapter / client that only we should use cache mechanisms to this request. | ||
* | ||
* @default true | ||
*/ | ||
cacheTakeover: boolean; | ||
/** | ||
* All methods that should be cached. | ||
@@ -53,3 +61,4 @@ * | ||
* | ||
* The id used is the same as the id on `CacheRequestConfig['id']`, auto-generated or not. | ||
* The id used is the same as the id on `CacheRequestConfig['id']`, auto-generated or | ||
* not. | ||
* | ||
@@ -73,3 +82,4 @@ * **Using a function instead of an object is supported but not recommended, as it's | ||
* Use `If-Modified-Since` header in this request. Use a date to force a custom value or | ||
* true to use the last cached timestamp. If never cached before, the header is not set. | ||
* true to use the last cached timestamp. If never cached before, the header is not | ||
* set. | ||
* | ||
@@ -109,3 +119,4 @@ * @default false // The opposite of the resulting `etag` option. | ||
* This option bypasses the current cache and always make a new http request. This will | ||
* not delete the current cache, it will just replace the cache when the response arrives. | ||
* not delete the current cache, it will just replace the cache when the response | ||
* arrives. | ||
* | ||
@@ -151,3 +162,3 @@ * Unlike as `cache: false`, this will not disable the cache, it will just ignore the | ||
*/ | ||
requestInterceptor: AxiosInterceptor<CacheRequestConfig>; | ||
requestInterceptor: AxiosInterceptor<CacheRequestConfig<unknown, unknown>>; | ||
/** | ||
@@ -158,3 +169,3 @@ * The response interceptor that will be used to handle the cache. | ||
*/ | ||
responseInterceptor: AxiosInterceptor<CacheAxiosResponse>; | ||
responseInterceptor: AxiosInterceptor<CacheAxiosResponse<unknown, unknown>>; | ||
/** | ||
@@ -174,3 +185,3 @@ * Logs useful information in the console | ||
*/ | ||
export declare type DebugObject = Partial<{ | ||
export type DebugObject = Partial<{ | ||
id: string; | ||
@@ -177,0 +188,0 @@ msg: string; |
import type { AxiosInstance } from 'axios'; | ||
import type { AxiosCacheInstance } from './axios'; | ||
import type { CacheInstance, CacheProperties } from './cache'; | ||
export declare type CacheOptions = Partial<CacheInstance> & Partial<CacheProperties>; | ||
export type CacheOptions = Partial<CacheInstance> & Partial<CacheProperties>; | ||
/** | ||
@@ -6,0 +6,0 @@ * Apply the caching interceptors for a already created axios instance. |
@@ -38,2 +38,10 @@ export declare const Header: Readonly<{ | ||
* ```txt | ||
* Pragma: no - cache; | ||
* ``` | ||
* | ||
* @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Pragma | ||
*/ | ||
Pragma: "pragma"; | ||
/** | ||
* ```txt | ||
* ETag: W / '<etag_value>'; | ||
@@ -40,0 +48,0 @@ * ETag: '<etag_value>'; |
import type { AxiosRequestHeaders } from 'axios'; | ||
export declare type InterpreterResult = 'dont cache' | 'not enough headers' | number; | ||
export type InterpreterResult = 'dont cache' | 'not enough headers' | number; | ||
/** | ||
@@ -11,3 +11,3 @@ * Interpret all http headers to determina a time to live. | ||
*/ | ||
export declare type HeadersInterpreter = (headers?: AxiosRequestHeaders) => InterpreterResult; | ||
export type HeadersInterpreter = (headers?: Record<string, string | undefined>) => InterpreterResult; | ||
/** | ||
@@ -21,3 +21,3 @@ * Interpret a single string header | ||
*/ | ||
export declare type HeaderInterpreter = (header: string, headers: AxiosRequestHeaders) => InterpreterResult; | ||
export type HeaderInterpreter = (header: string, headers: AxiosRequestHeaders) => InterpreterResult; | ||
//# sourceMappingURL=types.d.ts.map |
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.AxiosCacheInterceptor=t():e.AxiosCacheInterceptor=t()}("undefined"!=typeof self?self:this,(function(){return function(){"use strict";var e={d:function(t,r){for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r:function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{Header:function(){return i},buildKeyGenerator:function(){return E},buildMemoryStorage:function(){return C},buildStorage:function(){return I},buildWebStorage:function(){return P},canStale:function(){return w},createCacheResponse:function(){return p},createValidateStatus:function(){return l},defaultHeaderInterpreter:function(){return s},defaultKeyGenerator:function(){return T},defaultRequestInterceptor:function(){return g},defaultResponseInterceptor:function(){return y},isExpired:function(){return S},isMethodIn:function(){return h},isStorage:function(){return x},setupCache:function(){return M},testCachePredicate:function(){return m},updateCache:function(){return b},updateStaleRequest:function(){return v}});var r=Symbol("cache-parser");function n(e){return("string"==typeof e||"number"==typeof e)&&(e=Number(e))>=0&&e<1/0}function a(e){return!0===e||"number"==typeof e||"string"==typeof e&&"false"!==e}var o=Number;var i=Object.freeze({IfModifiedSince:"if-modified-since",LastModified:"last-modified",IfNoneMatch:"if-none-match",CacheControl:"cache-control",ETag:"etag",Expires:"expires",Age:"age",XAxiosCacheEtag:"x-axios-cache-etag",XAxiosCacheLastModified:"x-axios-cache-last-modified",XAxiosCacheStaleIfError:"x-axios-cache-stale-if-error"}),s=function(e){if(!e)return"not enough headers";var t=e[i.CacheControl];if(t){var s=function(e){var t=Object.defineProperty({},r,{enumerable:!1,value:1});if(!e||"string"!=typeof e)return t;var i=function(e){var t={},r=e.toLowerCase().replace(/\s+/g,"").split(",");for(var n in r){var a,o=r[n].split("=",2);t[o[0]]=null==(a=o[1])||a}return t}(e),s=i["max-age"],c=i["max-stale"],u=i["min-fresh"],d=i["s-maxage"],f=i["stale-if-error"],l=i["stale-while-revalidate"];return a(i.immutable)&&(t.immutable=!0),n(s)&&(t.maxAge=o(s)),n(c)&&(t.maxStale=o(c)),n(u)&&(t.minFresh=o(u)),a(i["must-revalidate"])&&(t.mustRevalidate=!0),a(i["must-understand"])&&(t.mustUnderstand=!0),a(i["no-cache"])&&(t.noCache=!0),a(i["no-store"])&&(t.noStore=!0),a(i["no-transform"])&&(t.noTransform=!0),a(i["only-if-cached"])&&(t.onlyIfCached=!0),a(i.private)&&(t.private=!0),a(i["proxy-revalidate"])&&(t.proxyRevalidate=!0),a(i.public)&&(t.public=!0),n(d)&&(t.sMaxAge=o(d)),n(f)&&(t.staleIfError=o(f)),n(l)&&(t.staleWhileRevalidate=o(l)),t}(String(t)),c=s.noCache,u=s.noStore,d=s.mustRevalidate,f=s.maxAge,l=s.immutable;if(c||u)return"dont cache";if(l)return 31536e6;if(d)return 0;if(void 0!==f){var h=e[i.Age];return h?1e3*(f-Number(h)):1e3*f}}var v=e[i.Expires];if(v){var p=Date.parse(String(v))-Date.now();return p>=0?p:"dont cache"}return"not enough headers"};var c=function(){return c=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var a in t=arguments[r])Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},c.apply(this,arguments)};function u(e,t,r,n){return new(r||(r=Promise))((function(a,o){function i(e){try{c(n.next(e))}catch(e){o(e)}}function s(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?a(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,s)}c((n=n.apply(e,t||[])).next())}))}function d(e,t){var r,n,a,o,i={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;i;)try{if(r=1,n&&(a=2&o[0]?n.return:o[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,o[1])).done)return a;switch(n=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return i.label++,{value:o[1],done:!1};case 5:i.label++,n=o[1],o=[0];continue;case 7:o=i.ops.pop(),i.trys.pop();continue;default:if(!(a=i.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){i=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){i.label=o[1];break}if(6===o[0]&&i.label<a[1]){i.label=a[1],a=o;break}if(a&&i.label<a[2]){i.label=a[2],i.ops.push(o);break}a[2]&&i.ops.pop(),i.trys.pop();continue}o=t.call(e,i)}catch(e){o=[6,e],n=0}finally{r=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}Object.create;Object.create;var f=Symbol();function l(e){return e?function(t){return e(t)||304===t}:function(e){return e>=200&&e<300||304===e}}function h(e,t){return void 0===e&&(e="get"),void 0===t&&(t=[]),e=e.toLowerCase(),t.some((function(t){return t===e}))}function v(e,t){var r;t.headers||(t.headers={});var n=t.cache,a=n.etag,o=n.modifiedSince;if(a){var s=!0===a?null===(r=e.data)||void 0===r?void 0:r.headers[i.ETag]:a;s&&(t.headers[i.IfNoneMatch]=s)}o&&(t.headers[i.IfModifiedSince]=!0===o?e.data.headers[i.LastModified]||new Date(e.createdAt).toUTCString():o.toUTCString())}function p(e,t){return 304===e.status&&t?(e.cached=!0,e.data=t.data,e.status=t.status,e.statusText=t.statusText,e.headers=c(c({},t.headers),e.headers),t):{data:e.data,status:e.status,statusText:e.statusText,headers:e.headers}}function g(e){var t=this,r=function(r){return u(t,void 0,void 0,(function(){var t,n,a,o,i,s;return d(this,(function(u){switch(u.label){case 0:return t=r.id=e.generateKey(r),!1===r.cache?[2,r]:(r.cache=c(c({},e.defaults.cache),r.cache),h(r.method,r.cache.methods)?[4,e.storage.get(t,r)]:[2,r]);case 1:return n=u.sent(),a=r.cache.override,"empty"===n.state||"stale"===n.state||a?!e.waiting[t]||a?[3,3]:[4,e.storage.get(t,r)]:[3,5];case 2:if("empty"!==(n=u.sent()).state)return[3,5];u.label=3;case 3:return e.waiting[t]=function(){var e,t,r=new Promise((function(r,n){e=r,t=n}));return r.resolve=e,r.reject=t,r[f]=1,r}(),null===(s=e.waiting[t])||void 0===s||s.catch((function(){})),[4,e.storage.set(t,{state:"loading",previous:a?n.data?"stale":"empty":n.state,data:n.data,createdAt:a&&!n.createdAt?Date.now():n.createdAt},r)];case 4:return u.sent(),"stale"===n.state&&v(n,r),r.validateStatus=l(r.validateStatus),[2,r];case 5:return"loading"!==n.state?[3,12]:(i=e.waiting[t])?[3,7]:[4,e.storage.remove(t,r)];case 6:return u.sent(),[2,r];case 7:0,u.label=8;case 8:return u.trys.push([8,10,,11]),[4,i];case 9:return o=u.sent(),[3,11];case 10:return u.sent(),[2,r];case 11:return[3,13];case 12:o=n.data,u.label=13;case 13:return r.adapter=function(){return Promise.resolve({config:r,data:o.data,headers:o.headers,status:o.status,statusText:o.statusText,cached:!0,id:t})},[2,r]}}))}))};return{onFulfilled:r,apply:function(){return e.interceptors.request.use(r)}}}function m(e,t){var r;return u(this,void 0,void 0,(function(){var n,a,o,i,s,c,u,f,l,h;return d(this,(function(d){switch(d.label){case 0:return"function"==typeof t?[2,t(e)]:(n=t.statusCheck,a=t.responseMatch,o=t.containsHeaders,(s=n)?[4,n(e.status)]:[3,2]);case 1:s=!d.sent(),d.label=2;case 2:return(i=s)?[3,5]:(c=a)?[4,a(e)]:[3,4];case 3:c=!d.sent(),d.label=4;case 4:i=c,d.label=5;case 5:if(i)return[2,!1];if(!o)return[3,9];u=0,f=Object.entries(o),d.label=6;case 6:return u<f.length?(l=f[u],h=l[0],[4,(0,l[1])(null!==(r=e.headers[h.toLowerCase()])&&void 0!==r?r:e.headers[h])]):[3,9];case 7:if(!d.sent())return[2,!1];d.label=8;case 8:return u++,[3,6];case 9:return[2,!0]}}))}))}function b(e,t,r){return u(this,void 0,void 0,(function(){var n,a,o,i,s,c,u;return d(this,(function(d){switch(d.label){case 0:if("function"==typeof r)return[2,r(t)];n=0,a=Object.entries(r),d.label=1;case 1:return n<a.length?(o=a[n],i=o[0],"delete"!==(s=o[1])?[3,3]:[4,e.remove(i,t.config)]):[3,10];case 2:return d.sent(),[3,9];case 3:return[4,e.get(i,t.config)];case 4:return"loading"===(c=d.sent()).state?[3,9]:[4,s(c,t)];case 5:return"delete"!==(u=d.sent())?[3,7]:[4,e.remove(i,t.config)];case 6:return d.sent(),[3,9];case 7:return"ignore"===u?[3,9]:[4,e.set(i,u,t.config)];case 8:d.sent(),d.label=9;case 9:return n++,[3,1];case 10:return[2]}}))}))}function y(e){var t=this,r=function(r,n){return u(t,void 0,void 0,(function(){var t;return d(this,(function(a){switch(a.label){case 0:return[4,e.storage.remove(r,n)];case 1:return a.sent(),null===(t=e.waiting[r])||void 0===t||t.reject(),delete e.waiting[r],[2]}}))}))},n=function(n){return u(t,void 0,void 0,(function(){var t,a,o,s,u,f,l,h,v,g,y,x,w,S,I,C;return d(this,(function(d){switch(d.label){case 0:return t=n.id=null!==(S=(C=n.config).id)&&void 0!==S?S:C.id=e.generateKey(n.config),null!==(I=n.cached)&&void 0!==I||(n.cached=!1),n.cached?[2,n]:(a=n.config.cache)?(o=n.config,[4,e.storage.get(t,o)]):[2,c(c({},n),{cached:!1})];case 1:return s=d.sent(),(null==a?void 0:a.update)?[4,b(e.storage,n,a.update)]:[3,3];case 2:d.sent(),d.label=3;case 3:return"loading"!==s.state?[2,n]:(u=!s.data)?[4,m(n,a.cachePredicate)]:[3,5];case 4:u=!d.sent(),d.label=5;case 5:return u?[4,r(t,o)]:[3,7];case 6:return d.sent(),[2,n];case 7:for(f=0,l=Object.keys(n.headers);f<l.length;f++)(h=l[f]).startsWith("x-axios-cache")&&delete n.headers[h];return a.etag&&!0!==a.etag&&(n.headers[i.XAxiosCacheEtag]=a.etag),a.modifiedSince&&(n.headers[i.XAxiosCacheLastModified]=!0===a.modifiedSince?"use-cache-timestamp":a.modifiedSince.toUTCString()),v=a.ttl||-1,(null==a?void 0:a.interpretHeader)?"dont cache"!==(g=e.headerInterpreter(n.headers))?[3,9]:[4,r(t,o)]:[3,10];case 8:return d.sent(),[2,n];case 9:v="not enough headers"===g?v:g,d.label=10;case 10:return y=p(n,s.data),"function"!=typeof v?[3,12]:[4,v(n)];case 11:v=d.sent(),d.label=12;case 12:return a.staleIfError&&(n.headers[i.XAxiosCacheStaleIfError]=String(v)),x={state:"cached",ttl:v,createdAt:Date.now(),data:y},(w=e.waiting[t])&&(w.resolve(x.data),delete e.waiting[t]),[4,e.storage.set(t,x,o)];case 13:return d.sent(),[2,n]}}))}))},a=function(n){return u(t,void 0,void 0,(function(){var t,a,o,i,s,c;return d(this,(function(u){switch(u.label){case 0:if(!(null==(t=n.config)?void 0:t.cache)||!t.id)throw n;return[4,e.storage.get(t.id,t)];case 1:return a=u.sent(),o=t.cache,"loading"===a.state&&"stale"===a.previous?[3,3]:[4,r(t.id,t)];case 2:throw u.sent(),n;case 3:return(null==o?void 0:o.staleIfError)?"function"!=typeof o.staleIfError?[3,5]:[4,o.staleIfError(n.response,a,n)]:[3,8];case 4:return s=u.sent(),[3,6];case 5:s=o.staleIfError,u.label=6;case 6:return!0===(i=s)||"number"==typeof i&&a.createdAt+i>Date.now()?(null===(c=e.waiting[t.id])||void 0===c||c.resolve(a.data),delete e.waiting[t.id],[4,e.storage.set(t.id,{state:"stale",createdAt:Date.now(),data:a.data},t)]):[3,8];case 7:return u.sent(),[2,{cached:!0,config:t,id:t.id,data:a.data.data,headers:a.data.headers,status:a.data.status,statusText:a.data.statusText}];case 8:throw n}}))}))};return{onFulfilled:n,onRejected:a,apply:function(){return e.interceptors.response.use(n,a)}}}var x=function(e){return!!e&&!!e["is-storage"]};function w(e){var t=e.data.headers;return i.ETag in t||i.LastModified in t||i.XAxiosCacheEtag in t||i.XAxiosCacheStaleIfError in t||i.XAxiosCacheLastModified in t}function S(e){return e.createdAt+e.ttl<=Date.now()}function I(e){var t,r=this,n=e.set,a=e.find,o=e.remove;return(t={})["is-storage"]=1,t.set=n,t.remove=o,t.get=function(e,t){return u(r,void 0,void 0,(function(){var r,i;return d(this,(function(s){switch(s.label){case 0:return[4,a(e,t)];case 1:return(r=s.sent())?"cached"===r.state&&S(r)?w(r)?(i={state:"stale",createdAt:r.createdAt,data:r.data},[4,n(e,i,t)]):[3,3]:[2,r]:[2,{state:"empty"}];case 2:return s.sent(),[2,i];case 3:return[4,o(e,t)];case 4:return s.sent(),[2,{state:"empty"}]}}))}))},t}function C(e){void 0===e&&(e=!1);var t=I({set:function(e,r){t.data[e]=r},remove:function(e){delete t.data[e]},find:function(r){var n=t.data[r];return e&&void 0!==n?"function"==typeof structuredClone?structuredClone(n):JSON.parse(JSON.stringify(n)):n}});return t.data=Object.create(null),t}function A(e){var t=typeof e;if(e&&"object"===t&&!(e instanceof Date||e instanceof RegExp)){for(var r=Array.isArray(e)?[]:{},n=Object.keys(e).sort((function(e,t){return e>t?1:-1})),a=n.length;a--;){var o=n[a];r[o]=A(e[o])}return String(e.constructor)+JSON.stringify(r,n)}return t+String(e)}function O(e){e=A(e);for(var t=5381,r=0;r<e.length;)t=33*t^e.charCodeAt(r++);return t}var j=/^\/|\/$/g;function E(e){return function(t){if(t.id)return t.id;var r=e(t);return"".concat("string"==typeof r||"number"==typeof r?r:O(r))}}var T=E((function(e){var t=e.baseURL,r=void 0===t?"":t,n=e.url,a=void 0===n?"":n,o=e.method,i=void 0===o?"get":o,s=e.params,c=e.data;return r&&(r=r.replace(j,"")),a&&(a=a.replace(j,"")),i&&(i=i.toLowerCase()),{url:r+(r&&a?"/":"")+a,params:s,method:i,data:c}}));function M(e,t){var r,n,a,o,i;void 0===t&&(t={});var c=e;if(c.storage=t.storage||C(),!x(c.storage))throw new Error("Use buildStorage() function");return c.waiting=t.waiting||{},c.generateKey=t.generateKey||T,c.headerInterpreter=t.headerInterpreter||s,c.requestInterceptor=t.requestInterceptor||g(c),c.responseInterceptor=t.responseInterceptor||y(c),c.debug=t.debug,c.defaults.cache={update:t.update||{},ttl:null!==(r=t.ttl)&&void 0!==r?r:3e5,methods:t.methods||["get"],cachePredicate:t.cachePredicate||{statusCheck:function(e){return e>=200&&e<400}},etag:null===(n=t.etag)||void 0===n||n,modifiedSince:null!==(a=t.modifiedSince)&&void 0!==a?a:!1===t.etag,interpretHeader:null===(o=t.interpretHeader)||void 0===o||o,staleIfError:null===(i=t.staleIfError)||void 0===i||i,override:!1},c.requestInterceptor.apply(),c.responseInterceptor.apply(),c}function P(e,t){return void 0===t&&(t=""),I({find:function(r){var n=e.getItem(t+r);return n?JSON.parse(n):void 0},remove:function(r){e.removeItem(t+r)},set:function(r,n){var a=function(){return e.setItem(t+r,JSON.stringify(n))};try{return a()}catch(n){for(var o=Object.entries(e).filter((function(e){return e[0].startsWith(t)})).map((function(e){return[e[0],JSON.parse(e[1])]})),i=0,s=o;i<s.length;i++){var c=s[i];"cached"===c[1].state&&S(c[1])&&!w(c[1])&&e.removeItem(c[0])}try{return a()}catch(t){for(var u=o.sort((function(e,t){return(e[1].createdAt||0)-(t[1].createdAt||0)})),d=0,f=u;d<f.length;d++){var l=f[d];e.removeItem(l[0]);try{return a()}catch(e){}}}e.removeItem(t+r)}}})}return t}()})); | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.AxiosCacheInterceptor=t():e.AxiosCacheInterceptor=t()}("undefined"!=typeof self?self:this,(function(){return function(){"use strict";var e={d:function(t,r){for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r:function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{Header:function(){return i},buildKeyGenerator:function(){return j},buildMemoryStorage:function(){return C},buildStorage:function(){return I},buildWebStorage:function(){return P},canStale:function(){return w},createCacheResponse:function(){return p},createValidateStatus:function(){return f},defaultHeaderInterpreter:function(){return c},defaultKeyGenerator:function(){return T},defaultRequestInterceptor:function(){return g},defaultResponseInterceptor:function(){return y},isExpired:function(){return S},isMethodIn:function(){return h},isStorage:function(){return x},setupCache:function(){return M},testCachePredicate:function(){return m},updateCache:function(){return b},updateStaleRequest:function(){return v}});var r=Symbol("cache-parser");function n(e){return("string"==typeof e||"number"==typeof e)&&(e=Number(e))>=0&&e<1/0}function a(e){return!0===e||"number"==typeof e||"string"==typeof e&&"false"!==e}var o=Number;var i=Object.freeze({IfModifiedSince:"if-modified-since",LastModified:"last-modified",IfNoneMatch:"if-none-match",CacheControl:"cache-control",Pragma:"pragma",ETag:"etag",Expires:"expires",Age:"age",XAxiosCacheEtag:"x-axios-cache-etag",XAxiosCacheLastModified:"x-axios-cache-last-modified",XAxiosCacheStaleIfError:"x-axios-cache-stale-if-error"}),c=function(e){if(!e)return"not enough headers";var t=e[i.CacheControl];if(t){var c=function(e){var t=Object.defineProperty({},r,{enumerable:!1,value:1});if(!e||"string"!=typeof e)return t;var i=function(e){var t={},r=e.toLowerCase().replace(/\s+/g,"").split(",");for(var n in r){var a,o=r[n].split("=",2);t[o[0]]=null==(a=o[1])||a}return t}(e),c=i["max-age"],s=i["max-stale"],u=i["min-fresh"],d=i["s-maxage"],l=i["stale-if-error"],f=i["stale-while-revalidate"];return a(i.immutable)&&(t.immutable=!0),n(c)&&(t.maxAge=o(c)),n(s)&&(t.maxStale=o(s)),n(u)&&(t.minFresh=o(u)),a(i["must-revalidate"])&&(t.mustRevalidate=!0),a(i["must-understand"])&&(t.mustUnderstand=!0),a(i["no-cache"])&&(t.noCache=!0),a(i["no-store"])&&(t.noStore=!0),a(i["no-transform"])&&(t.noTransform=!0),a(i["only-if-cached"])&&(t.onlyIfCached=!0),a(i.private)&&(t.private=!0),a(i["proxy-revalidate"])&&(t.proxyRevalidate=!0),a(i.public)&&(t.public=!0),n(d)&&(t.sMaxAge=o(d)),n(l)&&(t.staleIfError=o(l)),n(f)&&(t.staleWhileRevalidate=o(f)),t}(String(t)),s=c.noCache,u=c.noStore,d=c.mustRevalidate,l=c.maxAge,f=c.immutable;if(s||u)return"dont cache";if(f)return 31536e6;if(d)return 0;if(void 0!==l){var h=e[i.Age];return h?1e3*(l-Number(h)):1e3*l}}var v=e[i.Expires];if(v){var p=Date.parse(String(v))-Date.now();return p>=0?p:"dont cache"}return"not enough headers"};var s=function(){return s=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var a in t=arguments[r])Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},s.apply(this,arguments)};function u(e,t,r,n){return new(r||(r=Promise))((function(a,o){function i(e){try{s(n.next(e))}catch(e){o(e)}}function c(e){try{s(n.throw(e))}catch(e){o(e)}}function s(e){var t;e.done?a(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,c)}s((n=n.apply(e,t||[])).next())}))}function d(e,t){var r,n,a,o,i={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function c(c){return function(s){return function(c){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(i=0)),i;)try{if(r=1,n&&(a=2&c[0]?n.return:c[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,c[1])).done)return a;switch(n=0,a&&(c=[2&c[0],a.value]),c[0]){case 0:case 1:a=c;break;case 4:return i.label++,{value:c[1],done:!1};case 5:i.label++,n=c[1],c=[0];continue;case 7:c=i.ops.pop(),i.trys.pop();continue;default:if(!(a=i.trys,(a=a.length>0&&a[a.length-1])||6!==c[0]&&2!==c[0])){i=0;continue}if(3===c[0]&&(!a||c[1]>a[0]&&c[1]<a[3])){i.label=c[1];break}if(6===c[0]&&i.label<a[1]){i.label=a[1],a=c;break}if(a&&i.label<a[2]){i.label=a[2],i.ops.push(c);break}a[2]&&i.ops.pop(),i.trys.pop();continue}c=t.call(e,i)}catch(e){c=[6,e],n=0}finally{r=a=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}([c,s])}}}Object.create;Object.create;var l=Symbol();function f(e){return e?function(t){return e(t)||304===t}:function(e){return e>=200&&e<300||304===e}}function h(e,t){return void 0===e&&(e="get"),void 0===t&&(t=[]),e=e.toLowerCase(),t.some((function(t){return t===e}))}function v(e,t){var r;t.headers||(t.headers={});var n=t.cache,a=n.etag,o=n.modifiedSince;if(a){var c=!0===a?null===(r=e.data)||void 0===r?void 0:r.headers[i.ETag]:a;c&&(t.headers[i.IfNoneMatch]=c)}o&&(t.headers[i.IfModifiedSince]=!0===o?e.data.headers[i.LastModified]||new Date(e.createdAt).toUTCString():o.toUTCString())}function p(e,t){return 304===e.status&&t?(e.cached=!0,e.data=t.data,e.status=t.status,e.statusText=t.statusText,e.headers=s(s({},t.headers),e.headers),t):{data:e.data,status:e.status,statusText:e.statusText,headers:e.headers}}function g(e){var t=this,r=function(r){return u(t,void 0,void 0,(function(){var t,n,a,o,c,u,p,g,m,b,y,x,w,S,I;return d(this,(function(d){switch(d.label){case 0:return t=r.id=e.generateKey(r),!1===r.cache?[2,r]:(r.cache=s(s({},e.defaults.cache),r.cache),r.cache.cacheTakeover&&(null!==(u=r.headers)&&void 0!==u||(r.headers={}),null!==(p=(b=r.headers)[y=i.CacheControl])&&void 0!==p||(b[y]="no-cache"),null!==(g=(x=r.headers)[w=i.Pragma])&&void 0!==g||(x[w]="no-cache"),null!==(m=(S=r.headers)[I=i.Expires])&&void 0!==m||(S[I]="0")),h(r.method,r.cache.methods)?[4,e.storage.get(t,r)]:[2,r]);case 1:return n=d.sent(),a=r.cache.override,"empty"===n.state||"stale"===n.state||a?!e.waiting[t]||a?[3,3]:[4,e.storage.get(t,r)]:[3,5];case 2:if("empty"!==(n=d.sent()).state)return[3,5];d.label=3;case 3:return e.waiting[t]=function(){var e,t,r=new Promise((function(r,n){e=r,t=n}));return r.resolve=e,r.reject=t,r[l]=1,r}(),e.waiting[t].catch((function(){})),[4,e.storage.set(t,{state:"loading",previous:a?n.data?"stale":"empty":n.state,data:n.data,createdAt:a&&!n.createdAt?Date.now():n.createdAt},r)];case 4:return d.sent(),"stale"===n.state&&v(n,r),r.validateStatus=f(r.validateStatus),[2,r];case 5:return"loading"!==n.state?[3,12]:(c=e.waiting[t])?[3,7]:[4,e.storage.remove(t,r)];case 6:return d.sent(),[2,r];case 7:0,d.label=8;case 8:return d.trys.push([8,10,,11]),[4,c];case 9:return o=d.sent(),[3,11];case 10:return d.sent(),[2,r];case 11:return[3,13];case 12:o=n.data,d.label=13;case 13:return r.adapter=function(){return Promise.resolve({config:r,data:o.data,headers:o.headers,status:o.status,statusText:o.statusText,cached:!0,id:t})},[2,r]}}))}))};return{onFulfilled:r,apply:function(){return e.interceptors.request.use(r)}}}function m(e,t){var r;return u(this,void 0,void 0,(function(){var n,a,o,i,c,s,u,l,f,h;return d(this,(function(d){switch(d.label){case 0:return"function"==typeof t?[2,t(e)]:(n=t.statusCheck,a=t.responseMatch,o=t.containsHeaders,(c=n)?[4,n(e.status)]:[3,2]);case 1:c=!d.sent(),d.label=2;case 2:return(i=c)?[3,5]:(s=a)?[4,a(e)]:[3,4];case 3:s=!d.sent(),d.label=4;case 4:i=s,d.label=5;case 5:if(i)return[2,!1];if(!o)return[3,9];u=0,l=Object.entries(o),d.label=6;case 6:return u<l.length?(f=l[u],h=f[0],[4,(0,f[1])(null!==(r=e.headers[h.toLowerCase()])&&void 0!==r?r:e.headers[h])]):[3,9];case 7:if(!d.sent())return[2,!1];d.label=8;case 8:return u++,[3,6];case 9:return[2,!0]}}))}))}function b(e,t,r){return u(this,void 0,void 0,(function(){var n,a,o,i,c,s,u;return d(this,(function(d){switch(d.label){case 0:if("function"==typeof r)return[2,r(t)];n=0,a=Object.entries(r),d.label=1;case 1:return n<a.length?(o=a[n],i=o[0],"delete"!==(c=o[1])?[3,3]:[4,e.remove(i,t.config)]):[3,10];case 2:return d.sent(),[3,9];case 3:return[4,e.get(i,t.config)];case 4:return"loading"===(s=d.sent()).state?[3,9]:[4,c(s,t)];case 5:return"delete"!==(u=d.sent())?[3,7]:[4,e.remove(i,t.config)];case 6:return d.sent(),[3,9];case 7:return"ignore"===u?[3,9]:[4,e.set(i,u,t.config)];case 8:d.sent(),d.label=9;case 9:return n++,[3,1];case 10:return[2]}}))}))}function y(e){var t=this,r=function(r,n){return u(t,void 0,void 0,(function(){var t;return d(this,(function(a){switch(a.label){case 0:return[4,e.storage.remove(r,n)];case 1:return a.sent(),null===(t=e.waiting[r])||void 0===t||t.reject(),delete e.waiting[r],[2]}}))}))},n=function(n){return u(t,void 0,void 0,(function(){var t,a,o,c,u,l,f,h,v,g,y,x,w,S,I,C;return d(this,(function(d){switch(d.label){case 0:return t=n.id=null!==(S=(C=n.config).id)&&void 0!==S?S:C.id=e.generateKey(n.config),null!==(I=n.cached)&&void 0!==I||(n.cached=!1),n.cached?[2,n]:(a=n.config.cache)?(o=n.config,[4,e.storage.get(t,o)]):[2,s(s({},n),{cached:!1})];case 1:return c=d.sent(),(null==a?void 0:a.update)?[4,b(e.storage,n,a.update)]:[3,3];case 2:d.sent(),d.label=3;case 3:return"loading"!==c.state?[2,n]:(u=!c.data)?[4,m(n,a.cachePredicate)]:[3,5];case 4:u=!d.sent(),d.label=5;case 5:return u?[4,r(t,o)]:[3,7];case 6:return d.sent(),[2,n];case 7:for(l=0,f=Object.keys(n.headers);l<f.length;l++)(h=f[l]).startsWith("x-axios-cache")&&delete n.headers[h];return a.etag&&!0!==a.etag&&(n.headers[i.XAxiosCacheEtag]=a.etag),a.modifiedSince&&(n.headers[i.XAxiosCacheLastModified]=!0===a.modifiedSince?"use-cache-timestamp":a.modifiedSince.toUTCString()),v=a.ttl||-1,(null==a?void 0:a.interpretHeader)?"dont cache"!==(g=e.headerInterpreter(n.headers))?[3,9]:[4,r(t,o)]:[3,10];case 8:return d.sent(),[2,n];case 9:v="not enough headers"===g?v:g,d.label=10;case 10:return y=p(n,c.data),"function"!=typeof v?[3,12]:[4,v(n)];case 11:v=d.sent(),d.label=12;case 12:return a.staleIfError&&(n.headers[i.XAxiosCacheStaleIfError]=String(v)),x={state:"cached",ttl:v,createdAt:Date.now(),data:y},(w=e.waiting[t])&&(w.resolve(x.data),delete e.waiting[t]),[4,e.storage.set(t,x,o)];case 13:return d.sent(),[2,n]}}))}))},a=function(n){return u(t,void 0,void 0,(function(){var t,a,o,i,c,s;return d(this,(function(u){switch(u.label){case 0:if(!(null==(t=n.config)?void 0:t.cache)||!t.id)throw n;return[4,e.storage.get(t.id,t)];case 1:return a=u.sent(),o=t.cache,"loading"===a.state&&"stale"===a.previous?[3,3]:[4,r(t.id,t)];case 2:throw u.sent(),n;case 3:return(null==o?void 0:o.staleIfError)?"function"!=typeof o.staleIfError?[3,5]:[4,o.staleIfError(n.response,a,n)]:[3,8];case 4:return c=u.sent(),[3,6];case 5:c=o.staleIfError,u.label=6;case 6:return!0===(i=c)||"number"==typeof i&&a.createdAt+i>Date.now()?(null===(s=e.waiting[t.id])||void 0===s||s.resolve(a.data),delete e.waiting[t.id],[4,e.storage.set(t.id,{state:"stale",createdAt:Date.now(),data:a.data},t)]):[3,8];case 7:return u.sent(),[2,{cached:!0,config:t,id:t.id,data:a.data.data,headers:a.data.headers,status:a.data.status,statusText:a.data.statusText}];case 8:throw n}}))}))};return{onFulfilled:n,onRejected:a,apply:function(){return e.interceptors.response.use(n,a)}}}var x=function(e){return!!e&&!!e["is-storage"]};function w(e){var t=e.data.headers;return i.ETag in t||i.LastModified in t||i.XAxiosCacheEtag in t||i.XAxiosCacheStaleIfError in t||i.XAxiosCacheLastModified in t}function S(e){return e.createdAt+e.ttl<=Date.now()}function I(e){var t,r=this,n=e.set,a=e.find,o=e.remove;return(t={})["is-storage"]=1,t.set=n,t.remove=o,t.get=function(e,t){return u(r,void 0,void 0,(function(){var r,i;return d(this,(function(c){switch(c.label){case 0:return[4,a(e,t)];case 1:return(r=c.sent())?"cached"===r.state&&S(r)?w(r)?(i={state:"stale",createdAt:r.createdAt,data:r.data},[4,n(e,i,t)]):[3,3]:[2,r]:[2,{state:"empty"}];case 2:return c.sent(),[2,i];case 3:return[4,o(e,t)];case 4:return c.sent(),[2,{state:"empty"}]}}))}))},t}function C(e){void 0===e&&(e=!1);var t=I({set:function(e,r){t.data[e]=r},remove:function(e){delete t.data[e]},find:function(r){var n=t.data[r];return e&&void 0!==n?"function"==typeof structuredClone?structuredClone(n):JSON.parse(JSON.stringify(n)):n}});return t.data=Object.create(null),t}function A(e){var t=typeof e;if(e&&"object"===t&&!(e instanceof Date||e instanceof RegExp)){for(var r=Array.isArray(e)?[]:{},n=Object.keys(e).sort((function(e,t){return e>t?1:-1})),a=n.length;a--;){var o=n[a];r[o]=A(e[o])}return String(e.constructor)+JSON.stringify(r,n)}return t+String(e)}function E(e){e=A(e);for(var t=5381,r=0;r<e.length;)t=33*t^e.charCodeAt(r++);return t}var O=/^\/|\/$/g;function j(e){return function(t){if(t.id)return t.id;var r=e(t);return"".concat("string"==typeof r||"number"==typeof r?r:E(r))}}var T=j((function(e){var t=e.baseURL,r=void 0===t?"":t,n=e.url,a=void 0===n?"":n,o=e.method,i=void 0===o?"get":o,c=e.params,s=e.data;return r&&(r=r.replace(O,"")),a&&(a=a.replace(O,"")),i&&(i=i.toLowerCase()),{url:r+(r&&a?"/":"")+a,params:c,method:i,data:s}}));function M(e,t){var r,n,a,o,i,s;void 0===t&&(t={});var u=e;if(u.storage=t.storage||C(),!x(u.storage))throw new Error("Use buildStorage() function");return u.waiting=t.waiting||{},u.generateKey=t.generateKey||T,u.headerInterpreter=t.headerInterpreter||c,u.requestInterceptor=t.requestInterceptor||g(u),u.responseInterceptor=t.responseInterceptor||y(u),u.debug=t.debug,u.defaults.cache={update:t.update||{},ttl:null!==(r=t.ttl)&&void 0!==r?r:3e5,methods:t.methods||["get"],cachePredicate:t.cachePredicate||{statusCheck:function(e){return e>=200&&e<400}},etag:null===(n=t.etag)||void 0===n||n,modifiedSince:null!==(a=t.modifiedSince)&&void 0!==a?a:!1===t.etag,interpretHeader:null===(o=t.interpretHeader)||void 0===o||o,cacheTakeover:null===(i=t.cacheTakeover)||void 0===i||i,staleIfError:null===(s=t.staleIfError)||void 0===s||s,override:!1},u.requestInterceptor.apply(),u.responseInterceptor.apply(),u}function P(e,t){return void 0===t&&(t="axios-cache-"),I({find:function(r){var n=e.getItem(t+r);return n?JSON.parse(n):void 0},remove:function(r){e.removeItem(t+r)},set:function(r,n){var a=function(){return e.setItem(t+r,JSON.stringify(n))};try{return a()}catch(n){for(var o=Object.entries(e).filter((function(e){return e[0].startsWith(t)})).map((function(e){return[e[0],JSON.parse(e[1])]})),i=0,c=o;i<c.length;i++){var s=c[i];"cached"===s[1].state&&S(s[1])&&!w(s[1])&&e.removeItem(s[0])}try{return a()}catch(t){for(var u=o.sort((function(e,t){return(e[1].createdAt||0)-(t[1].createdAt||0)})),d=0,l=u;d<l.length;d++){var f=l[d];e.removeItem(f[0]);try{return a()}catch(e){}}}e.removeItem(t+r)}}})}return t}()})); |
@@ -9,4 +9,4 @@ import type { CacheAxiosResponse, CacheRequestConfig } from '../cache/axios'; | ||
} | ||
export declare type RequestInterceptor = AxiosInterceptor<CacheRequestConfig<unknown, unknown>>; | ||
export declare type ResponseInterceptor = AxiosInterceptor<CacheAxiosResponse<unknown, unknown>>; | ||
export type RequestInterceptor = AxiosInterceptor<CacheRequestConfig<unknown, unknown>>; | ||
export type ResponseInterceptor = AxiosInterceptor<CacheAxiosResponse<unknown, unknown>>; | ||
//# sourceMappingURL=build.d.ts.map |
@@ -12,3 +12,3 @@ import type { Method } from 'axios'; | ||
export declare function isMethodIn(requestMethod?: Method | string, methodList?: Method[]): boolean; | ||
export declare type ConfigWithCache<D> = CacheRequestConfig<unknown, D> & { | ||
export type ConfigWithCache<D> = CacheRequestConfig<unknown, D> & { | ||
cache: Partial<CacheProperties>; | ||
@@ -15,0 +15,0 @@ }; |
@@ -6,7 +6,10 @@ import type { CacheRequestConfig } from '../cache/axios'; | ||
export declare const isStorage: (obj: unknown) => obj is AxiosStorage; | ||
/** Returns true if this storage is expired, but it has sufficient properties to stale. */ | ||
/** Returns true if this has sufficient properties to stale instead of expire. */ | ||
export declare function canStale(value: CachedStorageValue): boolean; | ||
/** Checks if the provided cache is expired. You should also check if the cache {@link canStale} */ | ||
/** | ||
* Checks if the provided cache is expired. You should also check if the cache | ||
* {@link canStale} | ||
*/ | ||
export declare function isExpired(value: CachedStorageValue): boolean; | ||
export declare type BuildStorage = Omit<AxiosStorage, 'get'> & { | ||
export type BuildStorage = Omit<AxiosStorage, 'get'> & { | ||
/** | ||
@@ -13,0 +16,0 @@ * Returns the value for the given key. This method does not have to make checks for |
@@ -28,5 +28,5 @@ import type { AxiosStorage, StorageValue } from './types'; | ||
export declare function buildMemoryStorage(cloneData?: boolean): MemoryStorage; | ||
export declare type MemoryStorage = AxiosStorage & { | ||
export type MemoryStorage = AxiosStorage & { | ||
data: Record<string, StorageValue>; | ||
}; | ||
//# sourceMappingURL=memory.d.ts.map |
@@ -1,7 +0,6 @@ | ||
import type { AxiosResponseHeaders } from 'axios'; | ||
import type { CacheRequestConfig } from '../cache/axios'; | ||
import type { MaybePromise } from '../util/types'; | ||
export declare type CachedResponse = { | ||
export type CachedResponse = { | ||
data?: unknown; | ||
headers: AxiosResponseHeaders; | ||
headers: Record<string, string | undefined>; | ||
status: number; | ||
@@ -11,5 +10,5 @@ statusText: string; | ||
/** The value returned for a given key. */ | ||
export declare type StorageValue = StaleStorageValue | CachedStorageValue | LoadingStorageValue | EmptyStorageValue; | ||
export declare type NotEmptyStorageValue = Exclude<StorageValue, EmptyStorageValue>; | ||
export declare type StaleStorageValue = { | ||
export type StorageValue = StaleStorageValue | CachedStorageValue | LoadingStorageValue | EmptyStorageValue; | ||
export type NotEmptyStorageValue = Exclude<StorageValue, EmptyStorageValue>; | ||
export type StaleStorageValue = { | ||
data: CachedResponse; | ||
@@ -20,5 +19,8 @@ ttl?: undefined; | ||
}; | ||
export declare type CachedStorageValue = { | ||
export type CachedStorageValue = { | ||
data: CachedResponse; | ||
/** The number in milliseconds to wait after createdAt before the value is considered stale. */ | ||
/** | ||
* The number in milliseconds to wait after createdAt before the value is considered | ||
* stale. | ||
*/ | ||
ttl: number; | ||
@@ -28,3 +30,3 @@ createdAt: number; | ||
}; | ||
export declare type LoadingStorageValue = { | ||
export type LoadingStorageValue = { | ||
data?: undefined; | ||
@@ -42,3 +44,3 @@ ttl?: undefined; | ||
}; | ||
export declare type EmptyStorageValue = { | ||
export type EmptyStorageValue = { | ||
data?: undefined; | ||
@@ -67,3 +69,3 @@ ttl?: undefined; | ||
*/ | ||
export declare type AxiosStorage = { | ||
export type AxiosStorage = { | ||
/** | ||
@@ -87,5 +89,7 @@ * Sets a new value for the given key | ||
/** | ||
* Returns the value for the given key. This method make checks for cache invalidation or etc. | ||
* Returns the value for the given key. This method make checks for cache invalidation | ||
* or etc. | ||
* | ||
* If the provided `find()` method returned null, this will map it to a `'empty'` storage value. | ||
* If the provided `find()` method returned null, this will map it to a `'empty'` | ||
* storage value. | ||
* | ||
@@ -92,0 +96,0 @@ * @param key The key to look for |
import type { CacheAxiosResponse, CacheRequestConfig } from '../cache/axios'; | ||
import type { CachedStorageValue, LoadingStorageValue, StorageValue } from '../storage/types'; | ||
export declare type CachePredicate<R = unknown, D = unknown> = Exclude<CachePredicateObject<R, D> | CachePredicateObject<R, D>['responseMatch'], undefined>; | ||
export declare type CachePredicateObject<R = unknown, D = unknown> = { | ||
export type CachePredicate<R = unknown, D = unknown> = Exclude<CachePredicateObject<R, D> | CachePredicateObject<R, D>['responseMatch'], undefined>; | ||
export type CachePredicateObject<R = unknown, D = unknown> = { | ||
/** Matches if this function returned true. */ | ||
@@ -19,6 +19,9 @@ statusCheck?: (status: number) => MaybePromise<boolean>; | ||
}; | ||
/** A simple function that receives a cache request config and should return a string id for it. */ | ||
export declare type KeyGenerator<R = unknown, D = unknown> = (options: CacheRequestConfig<R, D>) => string; | ||
export declare type MaybePromise<T> = T | Promise<T> | PromiseLike<T>; | ||
/** | ||
* A simple function that receives a cache request config and should return a string id | ||
* for it. | ||
*/ | ||
export type KeyGenerator<R = unknown, D = unknown> = (options: CacheRequestConfig<R, D>) => string; | ||
export type MaybePromise<T> = T | Promise<T> | PromiseLike<T>; | ||
/** | ||
* You can use a `number` to ensure an max time (in seconds) that the cache can be reused. | ||
@@ -31,6 +34,6 @@ * | ||
*/ | ||
export declare type StaleIfErrorPredicate<R, D> = number | boolean | ((networkResponse: CacheAxiosResponse<R, D> | undefined, cache: LoadingStorageValue & { | ||
export type StaleIfErrorPredicate<R, D> = number | boolean | ((networkResponse: CacheAxiosResponse<R, D> | undefined, cache: LoadingStorageValue & { | ||
previous: 'stale'; | ||
}, error: Record<string, unknown>) => MaybePromise<number | boolean>); | ||
export declare type CacheUpdaterFn<R, D> = (response: CacheAxiosResponse<R, D>) => MaybePromise<void>; | ||
export type CacheUpdaterFn<R, D> = (response: CacheAxiosResponse<R, D>) => MaybePromise<void>; | ||
/** | ||
@@ -42,3 +45,3 @@ * A record for a custom cache updater for each specified request id. | ||
*/ | ||
export declare type CacheUpdaterRecord<R, D> = { | ||
export type CacheUpdaterRecord<R, D> = { | ||
[requestId: string]: 'delete' | ((cached: Exclude<StorageValue, LoadingStorageValue>, response: CacheAxiosResponse<R, D>) => MaybePromise<CachedStorageValue | 'delete' | 'ignore'>); | ||
@@ -51,3 +54,3 @@ }; | ||
*/ | ||
export declare type CacheUpdater<R, D> = CacheUpdaterFn<R, D> | CacheUpdaterRecord<R, D>; | ||
export type CacheUpdater<R, D> = CacheUpdaterFn<R, D> | CacheUpdaterRecord<R, D>; | ||
//# sourceMappingURL=types.d.ts.map |
{ | ||
"name": "axios-cache-interceptor", | ||
"version": "0.10.7", | ||
"version": "1.0.0", | ||
"description": "Cache interceptor for axios", | ||
@@ -10,12 +10,14 @@ "license": "MIT", | ||
"exports": { | ||
"./*": "./*", | ||
"./package.json": "./package.json", | ||
".": { | ||
"import": "./dist/index.mjs", | ||
"require": "./dist/index.cjs" | ||
"require": "./dist/index.cjs", | ||
"types": "./dist/index.d.ts" | ||
}, | ||
"./dev": { | ||
"import": "./dev/index.mjs", | ||
"require": "./dev/index.cjs" | ||
} | ||
"require": "./dev/index.cjs", | ||
"types": "./dist/index.d.ts" | ||
}, | ||
"./package.json": "./package.json", | ||
"./*": "./*" | ||
}, | ||
@@ -32,3 +34,7 @@ "jsdelivr": "./dist/index.bundle.js", | ||
"lint": "eslint . --ext .ts", | ||
"version": "auto-changelog -p && git add CHANGELOG.md" | ||
"version": "auto-changelog -p && git add CHANGELOG.md", | ||
"benchmark": "cd benchmark && yarn start", | ||
"docs:dev": "vitepress dev docs --port 1227", | ||
"docs:build": "vitepress build docs", | ||
"docs:serve": "vitepress serve docs" | ||
}, | ||
@@ -56,8 +62,8 @@ "funding": "https://github.com/ArthurFiorette/axios-cache-interceptor?sponsor=1", | ||
"@arthurfiorette/prettier-config": "*", | ||
"@types/jest": "^28.1.0", | ||
"@types/jest": "^29.2.4", | ||
"@types/webpack": "^5.28.0", | ||
"@typescript-eslint/eslint-plugin": "^5.14.0", | ||
"@typescript-eslint/eslint-plugin": "^5.34.0", | ||
"@typescript-eslint/parser": "^5.14.0", | ||
"auto-changelog": "^2.4.0", | ||
"axios": "^0.27.2", | ||
"axios": "^1.0.0", | ||
"es-check": "^7.0.0", | ||
@@ -67,18 +73,25 @@ "eslint": "^8.15.0", | ||
"eslint-plugin-prettier": "^4.0.0", | ||
"jest": "^28.1.2", | ||
"jest-environment-jsdom": "^28.1.2", | ||
"jest": "^29.3.1", | ||
"jest-environment-jsdom": "^29.0.0", | ||
"prettier": "^2.5.1", | ||
"prettier-plugin-jsdoc": "^0.3.30", | ||
"prettier-plugin-organize-imports": "^3.0.0", | ||
"ts-jest": "^28.0.1", | ||
"prettier-plugin-jsdoc": "^0.4.2", | ||
"prettier-plugin-organize-imports": "^3.2.1", | ||
"ts-jest": "^29.0.3", | ||
"ts-loader": "^9.2.6", | ||
"tslib": "^2.3.1", | ||
"typescript": "^4.5.4", | ||
"vitepress": "^1.0.0-alpha.29", | ||
"webpack": "^5.66.0", | ||
"webpack-cli": "^4.9.1" | ||
"webpack-cli": "^5.0.1" | ||
}, | ||
"packageManager": "yarn@1.22.17", | ||
"peerDependencies": { | ||
"axios": "^1" | ||
}, | ||
"packageManager": "yarn@1.22.19", | ||
"resolutions": { | ||
"colors": "1.4.0" | ||
}, | ||
"engines": { | ||
"node": ">=12" | ||
} | ||
} |
<p align="center"> | ||
Help axios-cache-interceptor grow! Star and share this amazing repo with your friends and co-workers! | ||
<i> | ||
Help axios-cache-interceptor grow! Star and share this amazing repo with your friends and co-workers! | ||
</i> | ||
</p> | ||
@@ -20,12 +22,4 @@ | ||
<div align="center"> | ||
<pre> | ||
<h1>⚡ | ||
Axios Cache Interceptor</h1> | ||
</pre> | ||
<br /> | ||
</div> | ||
<h3 align="center"> | ||
<code>Axios Cache Interceptor</code> is a small and efficient cache interceptor for axios. | ||
<b>⚡Axios Cache Interceptor</b> is a small and efficient cache interceptor for axios. | ||
<br /> | ||
@@ -32,0 +26,0 @@ <br /> |
/* eslint-disable @typescript-eslint/no-explicit-any */ | ||
import type { | ||
AxiosDefaults, | ||
AxiosInstance, | ||
@@ -78,3 +77,3 @@ AxiosInterceptorManager, | ||
defaults: AxiosDefaults<any> & { | ||
defaults: AxiosInstance['defaults'] & { | ||
cache: CacheProperties; | ||
@@ -81,0 +80,0 @@ }; |
@@ -22,3 +22,4 @@ import type { Method } from 'axios'; | ||
* | ||
* If a function is used, it will receive the complete response and waits to return a TTL value | ||
* If a function is used, it will receive the complete response and waits to return a | ||
* TTL value | ||
* | ||
@@ -41,2 +42,10 @@ * When using `interpretHeader: true`, this value will only be used if the interpreter | ||
/** | ||
* If this interceptor should include some headers in the request to tell any possible | ||
* adapter / client that only we should use cache mechanisms to this request. | ||
* | ||
* @default true | ||
*/ | ||
cacheTakeover: boolean; | ||
/** | ||
* All methods that should be cached. | ||
@@ -63,3 +72,4 @@ * | ||
* | ||
* The id used is the same as the id on `CacheRequestConfig['id']`, auto-generated or not. | ||
* The id used is the same as the id on `CacheRequestConfig['id']`, auto-generated or | ||
* not. | ||
* | ||
@@ -85,3 +95,4 @@ * **Using a function instead of an object is supported but not recommended, as it's | ||
* Use `If-Modified-Since` header in this request. Use a date to force a custom value or | ||
* true to use the last cached timestamp. If never cached before, the header is not set. | ||
* true to use the last cached timestamp. If never cached before, the header is not | ||
* set. | ||
* | ||
@@ -123,3 +134,4 @@ * @default false // The opposite of the resulting `etag` option. | ||
* This option bypasses the current cache and always make a new http request. This will | ||
* not delete the current cache, it will just replace the cache when the response arrives. | ||
* not delete the current cache, it will just replace the cache when the response | ||
* arrives. | ||
* | ||
@@ -170,3 +182,3 @@ * Unlike as `cache: false`, this will not disable the cache, it will just ignore the | ||
*/ | ||
requestInterceptor: AxiosInterceptor<CacheRequestConfig>; | ||
requestInterceptor: AxiosInterceptor<CacheRequestConfig<unknown, unknown>>; | ||
@@ -178,3 +190,3 @@ /** | ||
*/ | ||
responseInterceptor: AxiosInterceptor<CacheAxiosResponse>; | ||
responseInterceptor: AxiosInterceptor<CacheAxiosResponse<unknown, unknown>>; | ||
@@ -181,0 +193,0 @@ /** |
@@ -95,2 +95,4 @@ import type { AxiosInstance } from 'axios'; | ||
cacheTakeover: options.cacheTakeover ?? true, | ||
staleIfError: options.staleIfError ?? true, | ||
@@ -97,0 +99,0 @@ |
@@ -42,2 +42,11 @@ export const Header = Object.freeze({ | ||
* ```txt | ||
* Pragma: no - cache; | ||
* ``` | ||
* | ||
* @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Pragma | ||
*/ | ||
Pragma: 'pragma', | ||
/** | ||
* ```txt | ||
* ETag: W / '<etag_value>'; | ||
@@ -44,0 +53,0 @@ * ETag: '<etag_value>'; |
@@ -13,3 +13,5 @@ import type { AxiosRequestHeaders } from 'axios'; | ||
*/ | ||
export type HeadersInterpreter = (headers?: AxiosRequestHeaders) => InterpreterResult; | ||
export type HeadersInterpreter = ( | ||
headers?: Record<string, string | undefined> | ||
) => InterpreterResult; | ||
@@ -16,0 +18,0 @@ /** |
import { deferred } from 'fast-defer'; | ||
import type { AxiosCacheInstance, CacheAxiosResponse } from '../cache/axios'; | ||
import { Header } from '../header/headers'; | ||
import type { | ||
@@ -18,3 +19,3 @@ CachedResponse, | ||
const onFulfilled: RequestInterceptor['onFulfilled'] = async (config) => { | ||
const key = (config.id = axios.generateKey(config)); | ||
const id = (config.id = axios.generateKey(config)); | ||
@@ -35,2 +36,13 @@ if (config.cache === false) { | ||
// Applies sufficient headers to prevent other cache systems to work along with this one | ||
// | ||
// Its currently used before isMethodIn because if the isMethodIn returns false, the request | ||
// shouldn't be cached an therefore neither in the browser. | ||
if (config.cache.cacheTakeover) { | ||
config.headers ??= {}; | ||
config.headers[Header.CacheControl] ??= 'no-cache'; | ||
config.headers[Header.Pragma] ??= 'no-cache'; | ||
config.headers[Header.Expires] ??= '0'; | ||
} | ||
if (!isMethodIn(config.method, config.cache.methods)) { | ||
@@ -47,3 +59,3 @@ if (__ACI_DEV__) { | ||
// Assumes that the storage handled staled responses | ||
let cache = await axios.storage.get(key, config); | ||
let cache = await axios.storage.get(id, config); | ||
const overrideCache = config.cache.override; | ||
@@ -62,4 +74,4 @@ | ||
*/ | ||
if (axios.waiting[key] && !overrideCache) { | ||
cache = (await axios.storage.get(key, config)) as | ||
if (axios.waiting[id] && !overrideCache) { | ||
cache = (await axios.storage.get(id, config)) as | ||
| CachedStorageValue | ||
@@ -78,3 +90,3 @@ | LoadingStorageValue; | ||
axios.debug?.({ | ||
id: key, | ||
id, | ||
msg: 'Waiting list had an deferred for this key, waiting for it to finish' | ||
@@ -89,12 +101,13 @@ }); | ||
// Create a deferred to resolve other requests for the same key when it's completed | ||
axios.waiting[key] = deferred(); | ||
axios.waiting[id] = deferred(); | ||
/** | ||
* Add a default reject handler to catch when the request is aborted without others | ||
* waiting for it. | ||
* Adds a default reject handler to catch when the request gets aborted without | ||
* others waiting for it. | ||
*/ | ||
axios.waiting[key]?.catch(() => undefined); | ||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion | ||
axios.waiting[id]!.catch(() => undefined); | ||
await axios.storage.set( | ||
key, | ||
id, | ||
{ | ||
@@ -129,3 +142,3 @@ state: 'loading', | ||
axios.debug?.({ | ||
id: key, | ||
id, | ||
msg: 'Updated stale request' | ||
@@ -140,3 +153,3 @@ }); | ||
axios.debug?.({ | ||
id: key, | ||
id, | ||
msg: 'Sending request, waiting for response', | ||
@@ -156,3 +169,3 @@ data: { | ||
if (cache.state === 'loading') { | ||
const deferred = axios.waiting[key]; | ||
const deferred = axios.waiting[id]; | ||
@@ -162,3 +175,3 @@ // Just in case, the deferred doesn't exists. | ||
if (!deferred) { | ||
await axios.storage.remove(key, config); | ||
await axios.storage.remove(id, config); | ||
return config; | ||
@@ -169,3 +182,3 @@ } | ||
axios.debug?.({ | ||
id: key, | ||
id, | ||
msg: 'Detected concurrent request, waiting for it to finish' | ||
@@ -180,3 +193,3 @@ }); | ||
axios.debug?.({ | ||
id: key, | ||
id, | ||
msg: 'Deferred rejected, requesting again', | ||
@@ -204,3 +217,3 @@ data: err | ||
cached: true, | ||
id: key | ||
id | ||
}); | ||
@@ -210,3 +223,3 @@ | ||
axios.debug?.({ | ||
id: key, | ||
id, | ||
msg: 'Returning cached response' | ||
@@ -213,0 +226,0 @@ }); |
@@ -1,2 +0,1 @@ | ||
import type { CacheProperties } from '..'; | ||
import type { | ||
@@ -7,2 +6,3 @@ AxiosCacheInstance, | ||
} from '../cache/axios'; | ||
import type { CacheProperties } from '../cache/cache'; | ||
import { Header } from '../header/headers'; | ||
@@ -24,6 +24,6 @@ import type { CachedStorageValue } from '../storage/types'; | ||
const rejectResponse = async (responseId: string, config: CacheRequestConfig) => { | ||
// Update the cache to empty to prevent infinite loading state | ||
// Updates the cache to empty to prevent infinite loading state | ||
await axios.storage.remove(responseId, config); | ||
// Reject the deferred if present | ||
// Rejects the deferred, if present | ||
axios.waiting[responseId]?.reject(); | ||
@@ -30,0 +30,0 @@ |
@@ -15,3 +15,3 @@ import type { CacheRequestConfig } from '../cache/axios'; | ||
/** Returns true if this storage is expired, but it has sufficient properties to stale. */ | ||
/** Returns true if this has sufficient properties to stale instead of expire. */ | ||
export function canStale(value: CachedStorageValue): boolean { | ||
@@ -29,3 +29,6 @@ const headers = value.data.headers; | ||
/** Checks if the provided cache is expired. You should also check if the cache {@link canStale} */ | ||
/** | ||
* Checks if the provided cache is expired. You should also check if the cache | ||
* {@link canStale} | ||
*/ | ||
export function isExpired(value: CachedStorageValue): boolean { | ||
@@ -32,0 +35,0 @@ return value.createdAt + value.ttl <= Date.now(); |
@@ -5,3 +5,3 @@ import { buildStorage } from './build'; | ||
/** | ||
* Modern function to natively deep clone | ||
* Modern function to natively deep clone. | ||
* | ||
@@ -8,0 +8,0 @@ * @link https://caniuse.com/mdn-api_structuredclone (07/03/2022 -> 59.4%) |
@@ -1,2 +0,1 @@ | ||
import type { AxiosResponseHeaders } from 'axios'; | ||
import type { CacheRequestConfig } from '../cache/axios'; | ||
@@ -7,3 +6,3 @@ import type { MaybePromise } from '../util/types'; | ||
data?: unknown; | ||
headers: AxiosResponseHeaders; | ||
headers: Record<string, string | undefined>; | ||
status: number; | ||
@@ -31,3 +30,6 @@ statusText: string; | ||
data: CachedResponse; | ||
/** The number in milliseconds to wait after createdAt before the value is considered stale. */ | ||
/** | ||
* The number in milliseconds to wait after createdAt before the value is considered | ||
* stale. | ||
*/ | ||
ttl: number; | ||
@@ -105,5 +107,7 @@ createdAt: number; | ||
/** | ||
* Returns the value for the given key. This method make checks for cache invalidation or etc. | ||
* Returns the value for the given key. This method make checks for cache invalidation | ||
* or etc. | ||
* | ||
* If the provided `find()` method returned null, this will map it to a `'empty'` storage value. | ||
* If the provided `find()` method returned null, this will map it to a `'empty'` | ||
* storage value. | ||
* | ||
@@ -110,0 +114,0 @@ * @param key The key to look for |
@@ -24,3 +24,3 @@ import { buildStorage, canStale, isExpired } from './build'; | ||
*/ | ||
export function buildWebStorage(storage: Storage, prefix = '') { | ||
export function buildWebStorage(storage: Storage, prefix = 'axios-cache-') { | ||
return buildStorage({ | ||
@@ -27,0 +27,0 @@ find: (key) => { |
@@ -31,3 +31,6 @@ import type { CacheAxiosResponse, CacheRequestConfig } from '../cache/axios'; | ||
/** A simple function that receives a cache request config and should return a string id for it. */ | ||
/** | ||
* A simple function that receives a cache request config and should return a string id | ||
* for it. | ||
*/ | ||
export type KeyGenerator<R = unknown, D = unknown> = ( | ||
@@ -34,0 +37,0 @@ options: CacheRequestConfig<R, D> |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
362612
73
2708
2
4
23
68