@loveduk/cache-manager 1.0.1 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +73 -50
- package/dist/@types/CacheManager/index.d.ts +16 -5
- package/dist/@types/index.d.ts +2 -1
- package/dist/bundle.esm.js +1 -1
- package/dist/bundle.umd.js +1 -1
- package/package.json +27 -14
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2024 LoveKui
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 LoveKui
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,50 +1,73 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
1
|
+
# @loveduk/cache-manager
|
|
2
|
+
|
|
3
|
+
前端静态资源、3D Tiles 及三维模型(GLB/GLTF)的高性能透明本地持久化缓存管理器。基于 `IndexedDB`(LocalForage)与 `Fetch + XHR` 双引擎劫持技术,实现对特定资源请求的零侵入式秒开加速。
|
|
4
|
+
|
|
5
|
+
## ✨ 特性
|
|
6
|
+
|
|
7
|
+
- 🚀 **双引擎透明代理**:同时支持现代 `window.fetch` 与传统 `XMLHttpRequest`,无缝支持 Three.js / Cesium / Axios / 原生网络请求。
|
|
8
|
+
- 📦 **大文件高效存储**:针对 `.glb`、`.gltf`、`.bin` 等三维模型与二进制纹理,以原生 `ArrayBuffer` 格式存入 IndexedDB,杜绝内存序列化卡顿。
|
|
9
|
+
- ⏳ **灵活的生命周期**:支持按天配置 `expireTime` 过期时间与定时清理 `clearExpiredCache()`。
|
|
10
|
+
- 📊 **空间容量洞察**:提供 `calculateCacheSize()` 自动统计当前离线存储占用大小(Bytes / KB / MB / GB)。
|
|
11
|
+
- 🛡️ **SSR 安全友好**:内置 Node / Next.js 服务端渲染环境防护,非浏览器环境下自动静默。
|
|
12
|
+
|
|
13
|
+
## 📦 安装
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install @loveduk/cache-manager
|
|
17
|
+
# or
|
|
18
|
+
pnpm add @loveduk/cache-manager
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## 🛠️ 快速上手
|
|
22
|
+
|
|
23
|
+
### 1. 缓存 Three.js / R3F 三维模型(GLB)
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import CacheManager from "@loveduk/cache-manager";
|
|
27
|
+
|
|
28
|
+
// 初始化三维模型缓存管理器
|
|
29
|
+
const modelCache = new CacheManager({
|
|
30
|
+
storeUrls: [".glb", "/models/", "/assets/scenes/"],
|
|
31
|
+
storeName: "3DModelCacheDB", // 自定义 IndexedDB 数据库名称
|
|
32
|
+
expireTime: 30, // 30天后自动过期
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
// 后续所有的 fetch 或 useGLTF(".glb") 都会被自动透明拦截:
|
|
36
|
+
// 首次下载:自动存入本地 IndexedDB
|
|
37
|
+
// 二次访问:直接从本地返回,0 网络开销、瞬间秒开!
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
### 2. 统计当前缓存大小 & 清理
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
// 查询已占用的本地存储体积
|
|
44
|
+
const size = await modelCache.calculateCacheSize();
|
|
45
|
+
console.log("当前模型离线缓存占用:", size); // 如 "45.20 MB"
|
|
46
|
+
|
|
47
|
+
// 清理所有已过期的旧缓存
|
|
48
|
+
await modelCache.clearExpiredCache();
|
|
49
|
+
|
|
50
|
+
// 彻底清空所有离线缓存
|
|
51
|
+
modelCache.clear();
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## 📖 API 配置项
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
interface CacheManagerOptions {
|
|
58
|
+
/** 匹配需要缓存的 URL 规则关键字列表(如 [".glb", "/tiles/"]) */
|
|
59
|
+
storeUrls: string[];
|
|
60
|
+
/** 过期时间(单位:天),默认不过期 */
|
|
61
|
+
expireTime?: number;
|
|
62
|
+
/** IndexedDB 数据库名称,默认为 "CacheDB" */
|
|
63
|
+
storeName?: string;
|
|
64
|
+
/** 是否拦截 window.fetch,默认为 true */
|
|
65
|
+
enableFetch?: boolean;
|
|
66
|
+
/** 是否拦截 XMLHttpRequest,默认为 true */
|
|
67
|
+
enableXHR?: boolean;
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## License
|
|
72
|
+
|
|
73
|
+
ISC License.
|
|
@@ -1,13 +1,24 @@
|
|
|
1
|
+
export interface CacheManagerOptions {
|
|
2
|
+
storeUrls: string[];
|
|
3
|
+
expireTime?: number;
|
|
4
|
+
storeName?: string;
|
|
5
|
+
enableFetch?: boolean;
|
|
6
|
+
enableXHR?: boolean;
|
|
7
|
+
}
|
|
1
8
|
export default class CacheManager {
|
|
2
9
|
private storeUrls;
|
|
3
10
|
private store;
|
|
4
11
|
private expireTime;
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
12
|
+
private enableFetch;
|
|
13
|
+
private enableXHR;
|
|
14
|
+
private originalFetch;
|
|
15
|
+
constructor(options: CacheManagerOptions);
|
|
16
|
+
private checkNeedCache;
|
|
17
|
+
private saveToStore;
|
|
10
18
|
private init;
|
|
19
|
+
private initXHR;
|
|
20
|
+
private initFetch;
|
|
21
|
+
destroy(): void;
|
|
11
22
|
clear(): void;
|
|
12
23
|
calculateCacheSize(): Promise<string>;
|
|
13
24
|
private formatSize;
|
package/dist/@types/index.d.ts
CHANGED
package/dist/bundle.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import localStorage from"localforage";var events=["load","loadend","timeout","error","readystatechange","abort"],OriginXhr="__origin_xhr";function configEvent(e,t){var r,n={};for(r in e)n[r]=e[r];return n.target=n.currentTarget=t,n}function hook(o,e){function t(){for(var e,t=new s,r=0;r<events.length;++r){var n="on"+events[r];void 0===t[n]&&(t[n]=null)}for(e in t){var a="";try{a=typeof t[e]}catch(e){}"function"===a?this[e]=(r=>function(){var e=[].slice.call(arguments);if(o[r]&&c){var t=o[r].call(this,e,this[OriginXhr]);if(t)return t}return this[OriginXhr][r].apply(this[OriginXhr],e)})(e):e!==OriginXhr&&Object.defineProperty(this,e,{get:(n=>function(){var e,t,r=this[OriginXhr][n];return c?(e=this.hasOwnProperty(n+"_")?this[n+"_"]:r,(t=(o[n]||{}).getter)&&t(e,this)||e):r})(e),set:(a=>function(t){var r=this[OriginXhr];if(c){var n=this,e=o[a];if("on"===a.substring(0,2))n[a+"_"]=t,r[a]=function(e){e=configEvent(e,n),o[a]&&o[a].call(n,r,e)||t.call(n,e)};else{e=(e||{}).setter;t=e&&e(t,n)||t,this[a+"_"]=t;try{r[a]=t}catch(e){}}}else r[a]=t})(e),enumerable:!0})}var i=this;t.getProxy=function(){return i},this[OriginXhr]=t}var s=(e=e||window).XMLHttpRequest,c=!0;return t.prototype=s.prototype,e.XMLHttpRequest=t.prototype.constructor=t,Object.assign(e.XMLHttpRequest,{UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4}),{originXhr:s,unHook:function(){c=!1,e.XMLHttpRequest===t&&(e.XMLHttpRequest=s,t.prototype.constructor=s,s=void 0)}}}var eventLoad=events[0],eventLoadEnd=events[1],eventTimeout=events[2],eventError=events[3],eventReadyStateChange=events[4],eventAbort=events[5],prototype="prototype";function proxy(e,t){return proxyAjax(e,t=t||window)}function trim(e){return e.replace(/^\s+|\s+$/g,"")}function getEventTarget(e){return e.watcher||(e.watcher=document.createElement("a"))}function triggerListener(e,t){var r,n=e.getProxy(),a="on"+t+"_",i=configEvent({type:t},n);n[a]&&n[a](i),"function"==typeof Event?r=new Event(t,{bubbles:!1}):(r=document.createEvent("Event")).initEvent(t,!1,!0),getEventTarget(e).dispatchEvent(r)}function Handler(e){this.xhr=e,this.xhrProxy=e.getProxy()}function makeHandler(e){function t(e){Handler.call(this,e)}return(t[prototype]=Object.create(Handler[prototype])).next=e,t}Handler[prototype]=Object.create({resolve:function(e){var t=this.xhrProxy,r=this.xhr;t.readyState=4,r.resHeader=e.headers,t.response=t.responseText=e.response,t.statusText=e.statusText,t.status=e.status,triggerListener(r,eventReadyStateChange),triggerListener(r,eventLoad),triggerListener(r,eventLoadEnd)},reject:function(e){this.xhrProxy.status=0,triggerListener(this.xhr,e.type),triggerListener(this.xhr,eventLoadEnd)}});var RequestHandler=makeHandler(function(e){var t,r=this.xhr;for(t in e=e||r.config,r.withCredentials=e.withCredentials,r.open(e.method,e.url,!1!==e.async,e.user,e.password),e.headers)r.setRequestHeader(t,e.headers[t]);r.send(e.body)}),ResponseHandler=makeHandler(function(e){this.resolve(e)}),ErrorHandler=makeHandler(function(e){this.reject(e)});function proxyAjax(e,t){var a=e.onRequest,n=e.onResponse,i=e.onError;function r(e,t){var r=new ResponseHandler(e),t={response:(e=>{var t=e.responseType;if(!t||"text"===t)return e.responseText;var r=e.response;if("json"===t&&!r)try{return JSON.parse(e.responseText)}catch(e){console.warn(e)}return r})(t),status:t.status,statusText:t.statusText,config:e.config,headers:e.resHeader||e.getAllResponseHeaders().split("\r\n").reduce(function(e,t){return""!==t&&(e[(t=t.split(":")).shift()]=trim(t.join(":"))),e},{})};if(!n)return r.resolve(t);n(t,r)}function o(){return!0}function s(a){return function(e,t){var r,n;return t=t,r=a,n=new ErrorHandler(e=e),t={config:e.config,error:t,type:r},i?i(t,n):n.next(t),!0}}function c(e,t){return 4===e.readyState&&0!==e.status?r(e,t):4!==e.readyState&&triggerListener(e,eventReadyStateChange),!0}var{originXhr:e,unHook:t}=hook({onload:o,onloadend:o,onerror:s(eventError),ontimeout:s(eventTimeout),onabort:s(eventAbort),onreadystatechange:function(e){return c(e,this)},open:function(e,t){var r=this,n=t.config={headers:{}},e=(n.method=e[0],n.url=e[1],n.async=e[2],n.user=e[3],n.password=e[4],"on"+eventReadyStateChange);if((n.xhr=t)[e]||(t[e]=function(){return c(t,r)}),a)return!0},send:function(e,t){var r=t.config;if(r.withCredentials=t.withCredentials,r.body=e[0],a)return!(e=function(){a(r,new RequestHandler(t))})===r.async?e():setTimeout(e),!0},setRequestHeader:function(e,t){if(t.config.headers[e[0].toLowerCase()]=e[1],a)return!0},addEventListener:function(t,e){var r,n=this;if(-1!==events.indexOf(t[0]))return r=t[1],getEventTarget(e).addEventListener(t[0],function(e){e=configEvent(e,n);e.type=t[0],e.isTrusted=!0,r.call(n,e)}),!0},getAllResponseHeaders:function(e,t){var r=t.resHeader;if(r){var n,a="";for(n in r)a+=n+": "+r[n]+"\r\n";return a}},getResponseHeader:function(e,t){t=t.resHeader;if(t)return t[(e[0]||"").toLowerCase()]}},t);return{originXhr:e,unProxy:t}}class CacheManager{storeUrls;store;expireTime;enableFetch;enableXHR;originalFetch;constructor(e){this.storeUrls=e?.storeUrls||[],this.expireTime=e?.expireTime||void 0,this.enableFetch=e?.enableFetch??!0,this.enableXHR=e?.enableXHR??!0,"undefined"!=typeof window&&0!==this.storeUrls.length&&(this.store=localStorage.createInstance({name:e?.storeName||"CacheDB"}),this.init())}checkNeedCache(t){return!(!t||"string"!=typeof t||t.includes(".terrain"))&&this.storeUrls.some(e=>t.includes(e))}async saveToStore(t,r,n){if(this.store){var a=Date.now();let e;n&&("function"==typeof n.get?e=n.get("content-type")||void 0:"object"==typeof n&&(e=n["content-type"]||void 0));n={dataTimestamp:a,expireTime:this.expireTime?a+24*this.expireTime*60*60*1e3:void 0,url:t,contentType:e};try{await this.store.setItem(t,{metaData:n,data:r})}catch(e){console.warn("[CacheManager] saveToStore error:",e)}}}init(){this.enableXHR&&this.initXHR(),this.enableFetch&&this.initFetch()}initXHR(){proxy({onRequest:async(e,t)=>{var{url:r,headers:n}=e;if(this.checkNeedCache(r)){r=await this.store?.getItem(r);if(r?.data){var a=Date.now();if(!r.metaData?.expireTime||r.metaData.expireTime>a)return void t.resolve({config:e,status:200,headers:n,response:r.data})}}t.next(e)},onResponse:(e,t)=>{var{url:r}=e.config;this.checkNeedCache(r)&&this.saveToStore(r,e.response,e.headers),t.next(e)}})}initFetch(){"undefined"!=typeof window&&window.fetch&&(this.originalFetch=window.fetch.bind(window),window.fetch=async(e,t)=>{var r="string"==typeof e?e:e instanceof Request?e.url:e.toString();if("GET"!==(t?.method||(e instanceof Request?e.method:"GET")).toUpperCase()||!this.checkNeedCache(r))return this.originalFetch(e,t);try{var n=await this.store?.getItem(r);if(n?.data){var a,i,o=Date.now();if(!n.metaData?.expireTime||n.metaData.expireTime>o)return a=n.data,i=new Headers,n.metaData?.contentType&&i.set("Content-Type",n.metaData.contentType),i.set("X-Cache-Lookup","Hit From LocalCache"),new Response(a,{status:200,statusText:"OK",headers:i})}}catch(e){console.warn("[CacheManager] Read fetch cache failed:",e)}o=await this.originalFetch(e,t);if(o.ok)try{var s,c,h=o.clone(),u=o.headers.get("content-type")||"";r.includes(".glb")||r.includes(".gltf")||r.includes(".bin")||u.includes("octet-stream")||u.includes("gltf")||u.includes("image")?(s=await h.arrayBuffer(),this.saveToStore(r,s,o.headers)):(c=await h.text(),this.saveToStore(r,c,o.headers))}catch(e){console.warn("[CacheManager] Save fetch cache failed:",e)}return o})}destroy(){this.originalFetch&&"undefined"!=typeof window&&(window.fetch=this.originalFetch,this.originalFetch=void 0)}clear(){this.store?.clear()}async calculateCacheSize(){let a=0;var e=await this.store?.keys()||[];return await Promise.all(e.map(async t=>{try{var e,r,n=await this.store?.getItem(t);n?.data instanceof ArrayBuffer?a+=n.data.byteLength:"string"==typeof n?.data&&(e=JSON.stringify(n.data),r=new Blob([e]).size,a+=r)}catch(e){console.error(`Error getting size of key ${t}: `+e)}})),this.formatSize(a)}formatSize(e){var t;return 0===e?"0 Byte":(t=parseInt(Math.floor(Math.log(e)/Math.log(1024)).toString()),Math.round(e/Math.pow(1024,t)).toFixed(2)+" "+["Bytes","KB","MB","GB","TB"][t])}async clearExpiredCache(){let r=Date.now();var e=await this.store?.keys()||[];await Promise.all(e.map(async t=>{try{var e=await this.store?.getItem(t);e?.metaData&&e?.metaData?.expireTime&&e?.metaData?.expireTime<r&&await this.store?.removeItem(t)}catch(e){console.error(`Error clearing cache for key ${t}: `+e)}}))}}export{CacheManager as default};
|
package/dist/bundle.umd.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
((e,t)=>{"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("localforage")):"function"==typeof define&&define.amd?define(["localforage"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).CacheManager=t(e.localforage)})(this,function(t){var h=["load","loadend","timeout","error","readystatechange","abort"],u="__origin_xhr";function f(e,t){var r,n={};for(r in e)n[r]=e[r];return n.target=n.currentTarget=t,n}function d(o,e){function t(){for(var e,t=new s,r=0;r<h.length;++r){var n="on"+h[r];void 0===t[n]&&(t[n]=null)}for(e in t){var a="";try{a=typeof t[e]}catch(e){}"function"===a?this[e]=(r=>function(){var e=[].slice.call(arguments);if(o[r]&&c){var t=o[r].call(this,e,this[u]);if(t)return t}return this[u][r].apply(this[u],e)})(e):e!==u&&Object.defineProperty(this,e,{get:(n=>function(){var e,t,r=this[u][n];return c?(e=this.hasOwnProperty(n+"_")?this[n+"_"]:r,(t=(o[n]||{}).getter)&&t(e,this)||e):r})(e),set:(a=>function(t){var r=this[u];if(c){var n=this,e=o[a];if("on"===a.substring(0,2))n[a+"_"]=t,r[a]=function(e){e=f(e,n),o[a]&&o[a].call(n,r,e)||t.call(n,e)};else{e=(e||{}).setter;t=e&&e(t,n)||t,this[a+"_"]=t;try{r[a]=t}catch(e){}}}else r[a]=t})(e),enumerable:!0})}var i=this;t.getProxy=function(){return i},this[u]=t}var s=(e=e||window).XMLHttpRequest,c=!0;return t.prototype=s.prototype,e.XMLHttpRequest=t.prototype.constructor=t,Object.assign(e.XMLHttpRequest,{UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4}),{originXhr:s,unHook:function(){c=!1,e.XMLHttpRequest===t&&(e.XMLHttpRequest=s,t.prototype.constructor=s,s=void 0)}}}var n=h[0],a=h[1],l=h[2],p=h[3],y=h[4],g=h[5],r="prototype";function e(e,t){t=t||window;var a=e.onRequest,n=e.onResponse,i=e.onError;function r(e,t){var r=new x(e),t={response:(e=>{var t=e.responseType;if(!t||"text"===t)return e.responseText;var r=e.response;if("json"===t&&!r)try{return JSON.parse(e.responseText)}catch(e){console.warn(e)}return r})(t),status:t.status,statusText:t.statusText,config:e.config,headers:e.resHeader||e.getAllResponseHeaders().split("\r\n").reduce(function(e,t){return""!==t&&(e[(t=t.split(":")).shift()]=t.join(":").replace(/^\s+|\s+$/g,"")),e},{})};if(!n)return r.resolve(t);n(t,r)}function o(){return!0}function s(a){return function(e,t){var r,n;return t=t,r=a,n=new T(e=e),t={config:e.config,error:t,type:r},i?i(t,n):n.next(t),!0}}function c(e,t){return 4===e.readyState&&0!==e.status?r(e,t):4!==e.readyState&&w(e,y),!0}var{}=d({onload:o,onloadend:o,onerror:s(p),ontimeout:s(l),onabort:s(g),onreadystatechange:function(e){return c(e,this)},open:function(e,t){var r=this,n=t.config={headers:{}},e=(n.method=e[0],n.url=e[1],n.async=e[2],n.user=e[3],n.password=e[4],"on"+y);if((n.xhr=t)[e]||(t[e]=function(){return c(t,r)}),a)return!0},send:function(e,t){var r=t.config;if(r.withCredentials=t.withCredentials,r.body=e[0],a)return!(e=function(){a(r,new m(t))})===r.async?e():setTimeout(e),!0},setRequestHeader:function(e,t){if(t.config.headers[e[0].toLowerCase()]=e[1],a)return!0},addEventListener:function(t,e){var r,n=this;if(-1!==h.indexOf(t[0]))return r=t[1],v(e).addEventListener(t[0],function(e){e=f(e,n);e.type=t[0],e.isTrusted=!0,r.call(n,e)}),!0},getAllResponseHeaders:function(e,t){var r=t.resHeader;if(r){var n,a="";for(n in r)a+=n+": "+r[n]+"\r\n";return a}},getResponseHeader:function(e,t){t=t.resHeader;if(t)return t[(e[0]||"").toLowerCase()]}},t)}function v(e){return e.watcher||(e.watcher=document.createElement("a"))}function w(e,t){var r,n=e.getProxy(),a="on"+t+"_",i=f({type:t},n);n[a]&&n[a](i),"function"==typeof Event?r=new Event(t,{bubbles:!1}):(r=document.createEvent("Event")).initEvent(t,!1,!0),v(e).dispatchEvent(r)}function i(e){this.xhr=e,this.xhrProxy=e.getProxy()}function o(e){function t(e){i.call(this,e)}return(t[r]=Object.create(i[r])).next=e,t}i[r]=Object.create({resolve:function(e){var t=this.xhrProxy,r=this.xhr;t.readyState=4,r.resHeader=e.headers,t.response=t.responseText=e.response,t.statusText=e.statusText,t.status=e.status,w(r,y),w(r,n),w(r,a)},reject:function(e){this.xhrProxy.status=0,w(this.xhr,e.type),w(this.xhr,a)}});var m=o(function(e){var t,r=this.xhr;for(t in e=e||r.config,r.withCredentials=e.withCredentials,r.open(e.method,e.url,!1!==e.async,e.user,e.password),e.headers)r.setRequestHeader(t,e.headers[t]);r.send(e.body)}),x=o(function(e){this.resolve(e)}),T=o(function(e){this.reject(e)});return class{storeUrls;store;expireTime;enableFetch;enableXHR;originalFetch;constructor(e){this.storeUrls=e?.storeUrls||[],this.expireTime=e?.expireTime||void 0,this.enableFetch=e?.enableFetch??!0,this.enableXHR=e?.enableXHR??!0,"undefined"!=typeof window&&0!==this.storeUrls.length&&(this.store=t.createInstance({name:e?.storeName||"CacheDB"}),this.init())}checkNeedCache(t){return!(!t||"string"!=typeof t||t.includes(".terrain"))&&this.storeUrls.some(e=>t.includes(e))}async saveToStore(t,r,n){if(this.store){var a=Date.now();let e;n&&("function"==typeof n.get?e=n.get("content-type")||void 0:"object"==typeof n&&(e=n["content-type"]||void 0));n={dataTimestamp:a,expireTime:this.expireTime?a+24*this.expireTime*60*60*1e3:void 0,url:t,contentType:e};try{await this.store.setItem(t,{metaData:n,data:r})}catch(e){console.warn("[CacheManager] saveToStore error:",e)}}}init(){this.enableXHR&&this.initXHR(),this.enableFetch&&this.initFetch()}initXHR(){e({onRequest:async(e,t)=>{var{url:r,headers:n}=e;if(this.checkNeedCache(r)){r=await this.store?.getItem(r);if(r?.data){var a=Date.now();if(!r.metaData?.expireTime||r.metaData.expireTime>a)return void t.resolve({config:e,status:200,headers:n,response:r.data})}}t.next(e)},onResponse:(e,t)=>{var{url:r}=e.config;this.checkNeedCache(r)&&this.saveToStore(r,e.response,e.headers),t.next(e)}})}initFetch(){"undefined"!=typeof window&&window.fetch&&(this.originalFetch=window.fetch.bind(window),window.fetch=async(e,t)=>{var r="string"==typeof e?e:e instanceof Request?e.url:e.toString();if("GET"!==(t?.method||(e instanceof Request?e.method:"GET")).toUpperCase()||!this.checkNeedCache(r))return this.originalFetch(e,t);try{var n=await this.store?.getItem(r);if(n?.data){var a,i,o=Date.now();if(!n.metaData?.expireTime||n.metaData.expireTime>o)return a=n.data,i=new Headers,n.metaData?.contentType&&i.set("Content-Type",n.metaData.contentType),i.set("X-Cache-Lookup","Hit From LocalCache"),new Response(a,{status:200,statusText:"OK",headers:i})}}catch(e){console.warn("[CacheManager] Read fetch cache failed:",e)}o=await this.originalFetch(e,t);if(o.ok)try{var s,c,h=o.clone(),u=o.headers.get("content-type")||"";r.includes(".glb")||r.includes(".gltf")||r.includes(".bin")||u.includes("octet-stream")||u.includes("gltf")||u.includes("image")?(s=await h.arrayBuffer(),this.saveToStore(r,s,o.headers)):(c=await h.text(),this.saveToStore(r,c,o.headers))}catch(e){console.warn("[CacheManager] Save fetch cache failed:",e)}return o})}destroy(){this.originalFetch&&"undefined"!=typeof window&&(window.fetch=this.originalFetch,this.originalFetch=void 0)}clear(){this.store?.clear()}async calculateCacheSize(){let a=0;var e=await this.store?.keys()||[];return await Promise.all(e.map(async t=>{try{var e,r,n=await this.store?.getItem(t);n?.data instanceof ArrayBuffer?a+=n.data.byteLength:"string"==typeof n?.data&&(e=JSON.stringify(n.data),r=new Blob([e]).size,a+=r)}catch(e){console.error(`Error getting size of key ${t}: `+e)}})),this.formatSize(a)}formatSize(e){var t;return 0===e?"0 Byte":(t=parseInt(Math.floor(Math.log(e)/Math.log(1024)).toString()),Math.round(e/Math.pow(1024,t)).toFixed(2)+" "+["Bytes","KB","MB","GB","TB"][t])}async clearExpiredCache(){let r=Date.now();var e=await this.store?.keys()||[];await Promise.all(e.map(async t=>{try{var e=await this.store?.getItem(t);e?.metaData&&e?.metaData?.expireTime&&e?.metaData?.expireTime<r&&await this.store?.removeItem(t)}catch(e){console.error(`Error clearing cache for key ${t}: `+e)}}))}}});
|
package/package.json
CHANGED
|
@@ -1,44 +1,57 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@loveduk/cache-manager",
|
|
3
|
-
"version": "1.0
|
|
4
|
-
"description": "",
|
|
5
|
-
"module": "dist/bundle.esm.js",
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "Universal transparent cache manager for 3D tiles, GLB models, and web resources via Fetch & XHR",
|
|
6
5
|
"types": "dist/@types/index.d.ts",
|
|
6
|
+
"module": "dist/bundle.esm.js",
|
|
7
7
|
"main": "dist/bundle.esm.js",
|
|
8
8
|
"scripts": {
|
|
9
9
|
"test": "echo \"Error: no test specified\" && exit 1",
|
|
10
10
|
"dev": "rollup -w -c --environment MODE:dev",
|
|
11
|
-
"build": "rollup -c --environment MODE:prod"
|
|
11
|
+
"build": "rollup -c --environment MODE:prod",
|
|
12
|
+
"publish": "npm publish",
|
|
13
|
+
"link": "pnpm link --global"
|
|
12
14
|
},
|
|
13
|
-
"keywords": [
|
|
15
|
+
"keywords": [
|
|
16
|
+
"cache",
|
|
17
|
+
"fetch",
|
|
18
|
+
"xhr",
|
|
19
|
+
"ajax-hook",
|
|
20
|
+
"indexeddb",
|
|
21
|
+
"localforage",
|
|
22
|
+
"glb",
|
|
23
|
+
"threejs",
|
|
24
|
+
"3dtiles"
|
|
25
|
+
],
|
|
14
26
|
"publishConfig": {
|
|
15
|
-
"access": "public"
|
|
27
|
+
"access": "public",
|
|
28
|
+
"registry": "https://registry.npmjs.org/"
|
|
16
29
|
},
|
|
17
|
-
"author": "",
|
|
30
|
+
"author": "duk",
|
|
18
31
|
"license": "ISC",
|
|
19
32
|
"dependencies": {
|
|
20
|
-
"@babel/core": "^7.24.4",
|
|
21
|
-
"@babel/plugin-external-helpers": "^7.24.1",
|
|
22
|
-
"@babel/preset-env": "^7.24.4",
|
|
23
33
|
"ajax-hook": "^3.0.3",
|
|
24
|
-
"
|
|
25
|
-
"localforage": "^1.10.0",
|
|
26
|
-
"rollup-plugin-babel": "^4.4.0",
|
|
27
|
-
"rollup-plugin-uglify": "^6.0.4"
|
|
34
|
+
"localforage": "^1.10.0"
|
|
28
35
|
},
|
|
29
36
|
"devDependencies": {
|
|
37
|
+
"@babel/core": "^7.24.4",
|
|
38
|
+
"@babel/plugin-external-helpers": "^7.24.1",
|
|
39
|
+
"@babel/preset-env": "^7.24.4",
|
|
30
40
|
"@rollup/plugin-alias": "^5.1.0",
|
|
31
41
|
"@rollup/plugin-commonjs": "^25.0.7",
|
|
32
42
|
"@rollup/plugin-json": "^6.0.0",
|
|
33
43
|
"@rollup/plugin-node-resolve": "^15.2.1",
|
|
34
44
|
"@rollup/plugin-terser": "^0.4.4",
|
|
35
45
|
"@rollup/plugin-typescript": "^11.1.5",
|
|
46
|
+
"crypto-js": "^4.2.0",
|
|
36
47
|
"rollup": "^4.9.1",
|
|
48
|
+
"rollup-plugin-babel": "^4.4.0",
|
|
37
49
|
"rollup-plugin-copy": "^3.5.0",
|
|
38
50
|
"rollup-plugin-dts": "^6.1.0",
|
|
39
51
|
"rollup-plugin-font": "^1.1.2",
|
|
40
52
|
"rollup-plugin-serve": "^1.1.1",
|
|
41
53
|
"rollup-plugin-typescript2": "^0.36.0",
|
|
54
|
+
"rollup-plugin-uglify": "^6.0.4",
|
|
42
55
|
"tslib": "^2.6.2",
|
|
43
56
|
"typescript": "^5.4.3"
|
|
44
57
|
},
|