@eggjs/koa-static-cache 6.2.0 → 7.0.0-beta.13

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/README.md CHANGED
@@ -1,8 +1,6 @@
1
- # Koa Static Cache
1
+ # eggjs/koa-static-cache
2
2
 
3
3
  [![NPM version][npm-image]][npm-url]
4
- [![Node.js CI](https://github.com/eggjs/koa-static-cache/actions/workflows/nodejs.yml/badge.svg)](https://github.com/eggjs/koa-static-cache/actions/workflows/nodejs.yml)
5
- [![Test coverage][codecov-image]][codecov-url]
6
4
  [![Known Vulnerabilities][snyk-image]][snyk-url]
7
5
  [![npm download][download-image]][download-url]
8
6
  [![Node.js Version](https://img.shields.io/node/v/@eggjs/koa-static-cache.svg?style=flat)](https://nodejs.org/en/download/)
@@ -10,8 +8,6 @@
10
8
 
11
9
  [npm-image]: https://img.shields.io/npm/v/@eggjs/koa-static-cache.svg?style=flat-square
12
10
  [npm-url]: https://npmjs.org/package/@eggjs/koa-static-cache
13
- [codecov-image]: https://img.shields.io/codecov/c/github/eggjs/koa-static-cache.svg?style=flat-square
14
- [codecov-url]: https://codecov.io/github/eggjs/koa-static-cache?branch=master
15
11
  [snyk-image]: https://snyk.io/test/npm/@eggjs/koa-static-cache/badge.svg?style=flat-square
16
12
  [snyk-url]: https://snyk.io/test/npm/@eggjs/koa-static-cache
17
13
  [download-image]: https://img.shields.io/npm/dm/@eggjs/koa-static-cache.svg?style=flat-square
@@ -43,9 +39,11 @@ npm install @eggjs/koa-static-cache
43
39
  const path = require('path');
44
40
  const { staticCache } = require('@eggjs/koa-static-cache');
45
41
 
46
- app.use(staticCache(path.join(__dirname, 'public'), {
47
- maxAge: 365 * 24 * 60 * 60
48
- }));
42
+ app.use(
43
+ staticCache(path.join(__dirname, 'public'), {
44
+ maxAge: 365 * 24 * 60 * 60,
45
+ })
46
+ );
49
47
  ```
50
48
 
51
49
  - `options.dir` (str) - the directory you wish to serve, default to `process.cwd`.
@@ -68,9 +66,9 @@ For example, if you have this `alias` object:
68
66
  ```js
69
67
  const options = {
70
68
  alias: {
71
- '/favicon.png': '/favicon-32.png'
72
- }
73
- }
69
+ '/favicon.png': '/favicon-32.png',
70
+ },
71
+ };
74
72
  ```
75
73
 
76
74
  Then requests to `/favicon.png` will actually return `/favicon-32.png` without redirects or anything.
@@ -86,8 +84,8 @@ This allows you to do two things:
86
84
  Instead of doing:
87
85
 
88
86
  ```js
89
- app.use(staticCache('/public/js'))
90
- app.use(staticCache('/public/css'))
87
+ app.use(staticCache('/public/js'));
88
+ app.use(staticCache('/public/css'));
91
89
  ```
92
90
 
93
91
  You can do this:
@@ -111,9 +109,15 @@ For example, if you want to change the max age of `/package.json`, you can do th
111
109
  ```js
112
110
  const files = {};
113
111
 
114
- app.use(staticCache('/public', {
115
- maxAge: 60 * 60 * 24 * 365
116
- }, files));
112
+ app.use(
113
+ staticCache(
114
+ '/public',
115
+ {
116
+ maxAge: 60 * 60 * 24 * 365,
117
+ },
118
+ files
119
+ )
120
+ );
117
121
 
118
122
  files['/package.json'].maxAge = 60 * 60 * 24 * 30;
119
123
  ```
@@ -126,11 +130,13 @@ You can pass in a lru cache instance which has tow methods: `get(key)` and `set(
126
130
  const LRU = require('lru-cache');
127
131
  const files = new LRU({ max: 1000 });
128
132
 
129
- app.use(staticCache({
130
- dir: '/public',
131
- dynamic: true,
132
- files,
133
- }));
133
+ app.use(
134
+ staticCache({
135
+ dir: '/public',
136
+ dynamic: true,
137
+ files,
138
+ })
139
+ );
134
140
  ```
135
141
 
136
142
  ## License
@@ -139,6 +145,6 @@ app.use(staticCache({
139
145
 
140
146
  ## Contributors
141
147
 
142
- [![Contributors](https://contrib.rocks/image?repo=eggjs/koa-static-cache)](https://github.com/eggjs/koa-static-cache/graphs/contributors)
148
+ [![Contributors](https://contrib.rocks/image?repo=eggjs/egg)](https://github.com/eggjs/egg/graphs/contributors)
143
149
 
144
150
  Made with [contributors-img](https://contrib.rocks).
@@ -0,0 +1,101 @@
1
+ //#region src/index.d.ts
2
+ type FileFilter = (path: string) => boolean;
3
+ interface FileMeta {
4
+ maxAge?: number;
5
+ cacheControl?: string | ((path: string) => string);
6
+ buffer?: Buffer;
7
+ zipBuffer?: Buffer;
8
+ type?: string;
9
+ mime?: string;
10
+ mtime?: Date;
11
+ path?: string;
12
+ md5?: string;
13
+ length?: number;
14
+ }
15
+ interface FileMap {
16
+ [path: string]: FileMeta;
17
+ }
18
+ interface FileStore {
19
+ get(key: string): unknown;
20
+ set(key: string, value: unknown): void;
21
+ }
22
+ interface Options {
23
+ /**
24
+ * The root directory from which to serve static assets
25
+ * Default to `process.cwd`
26
+ */
27
+ dir?: string;
28
+ /**
29
+ * The max age for cache control
30
+ * Default to `0`
31
+ */
32
+ maxAge?: number;
33
+ /**
34
+ * The cache control header for static files
35
+ * Default to `undefined`
36
+ * Overrides `options.maxAge`
37
+ */
38
+ cacheControl?: string | ((path: string) => string);
39
+ /**
40
+ * store the files in memory instead of streaming from the filesystem on each request
41
+ */
42
+ buffer?: boolean;
43
+ /**
44
+ * when request's accept-encoding include gzip, files will compressed by gzip
45
+ * Default to `false`
46
+ */
47
+ gzip?: boolean;
48
+ /**
49
+ * try use gzip files, loaded from disk, like nginx gzip_static
50
+ * Default to `false`
51
+ */
52
+ usePrecompiledGzip?: boolean;
53
+ /**
54
+ * object map of aliases
55
+ * Default to `{}`
56
+ */
57
+ alias?: Record<string, string>;
58
+ /**
59
+ * the url prefix you wish to add
60
+ * Default to `''`
61
+ */
62
+ prefix?: string;
63
+ /**
64
+ * filter files at init dir, for example - skip non build (source) files.
65
+ * If array set - allow only listed files
66
+ * Default to `undefined`
67
+ */
68
+ filter?: FileFilter | string[];
69
+ /**
70
+ * dynamic load file which not cached on initialization
71
+ * Default to `false
72
+ */
73
+ dynamic?: boolean;
74
+ /**
75
+ * caches the assets on initialization or not,
76
+ * always work together with `options.dynamic`
77
+ * Default to `true`
78
+ */
79
+ preload?: boolean;
80
+ /**
81
+ * file store for caching
82
+ * Default to `undefined`
83
+ */
84
+ files?: FileMap | FileStore;
85
+ }
86
+ type Next = () => Promise<void>;
87
+ declare class FileManager {
88
+ store?: FileStore;
89
+ map?: FileMap;
90
+ constructor(store?: FileStore | FileMap);
91
+ get(key: string): unknown;
92
+ set(key: string, value: FileMeta): void;
93
+ }
94
+ type MiddlewareFunc = (ctx: any, next: Next) => Promise<void> | void;
95
+ declare function staticCache(): MiddlewareFunc;
96
+ declare function staticCache(dir: string): MiddlewareFunc;
97
+ declare function staticCache(options: Options): MiddlewareFunc;
98
+ declare function staticCache(dir: string, options: Options): MiddlewareFunc;
99
+ declare function staticCache(dir: string, options: Options, files: FileMap | FileStore): MiddlewareFunc;
100
+ //#endregion
101
+ export { FileFilter, FileManager, FileMap, FileMeta, FileStore, Options, staticCache };
package/dist/index.js ADDED
@@ -0,0 +1,158 @@
1
+ import crypto from "node:crypto";
2
+ import { debuglog, promisify } from "node:util";
3
+ import fs from "node:fs/promises";
4
+ import { createReadStream, readFileSync, statSync } from "node:fs";
5
+ import zlib from "node:zlib";
6
+ import path from "node:path";
7
+ import mime from "mime-types";
8
+ import { compressible } from "@eggjs/compressible";
9
+ import readDir from "fs-readdir-recursive";
10
+ import { decodeURIComponent, exists } from "utility";
11
+
12
+ //#region src/index.ts
13
+ const debug = debuglog("egg/koa-static-cache");
14
+ const gzip = promisify(zlib.gzip);
15
+ var FileManager = class {
16
+ store;
17
+ map;
18
+ constructor(store) {
19
+ if (store && typeof store.set === "function" && typeof store.get === "function") this.store = store;
20
+ else this.map = store || Object.create(null);
21
+ }
22
+ get(key) {
23
+ return this.store ? this.store.get(key) : this.map[key];
24
+ }
25
+ set(key, value) {
26
+ if (this.store) return this.store.set(key, value);
27
+ this.map[key] = value;
28
+ }
29
+ };
30
+ function staticCache(dirOrOptions, options = {}, filesStoreOrMap) {
31
+ let dir = "";
32
+ if (typeof dirOrOptions === "string") dir = dirOrOptions;
33
+ else if (dirOrOptions) options = dirOrOptions;
34
+ if (!dir && options.dir) dir = options.dir;
35
+ if (!dir) dir = process.cwd();
36
+ dir = path.normalize(dir);
37
+ debug("staticCache dir: %s", dir);
38
+ options.prefix = (options.prefix ?? "").replace(/\/*$/, "/");
39
+ const files = new FileManager(filesStoreOrMap ?? options.files);
40
+ const enableGzip = !!options.gzip;
41
+ const filePrefix = path.normalize(options.prefix.replace(/^\//, ""));
42
+ let fileFilter = () => {
43
+ return true;
44
+ };
45
+ if (Array.isArray(options.filter)) fileFilter = (file) => {
46
+ return options.filter.includes(file);
47
+ };
48
+ if (typeof options.filter === "function") fileFilter = options.filter;
49
+ if (options.preload !== false) {
50
+ debug("preload: %s", dir);
51
+ readDir(dir, (filename) => {
52
+ return !filename.startsWith(".") && filename !== "node_modules";
53
+ }).filter(fileFilter).forEach((name) => {
54
+ loadFile(name, dir, options, files);
55
+ });
56
+ debug("preload end");
57
+ }
58
+ debug("prepare middleware");
59
+ return async (ctx, next) => {
60
+ if (ctx.method !== "HEAD" && ctx.method !== "GET") return await next();
61
+ if (!ctx.path.startsWith(options.prefix)) return await next();
62
+ let filename = path.normalize(decodeURIComponent(ctx.path));
63
+ if (options.alias && options.alias[filename]) filename = options.alias[filename];
64
+ let file = files.get(filename);
65
+ if (!file) {
66
+ if (!options.dynamic) return await next();
67
+ if (path.basename(filename)[0] === ".") return await next();
68
+ if (filename.charAt(0) === path.sep) filename = filename.slice(1);
69
+ if (options.prefix !== "/") {
70
+ if (filename.indexOf(filePrefix) !== 0) return await next();
71
+ filename = filename.slice(filePrefix.length);
72
+ }
73
+ const fullpath = path.join(dir, filename);
74
+ if (!fullpath.startsWith(dir)) return await next();
75
+ const stats = await exists(fullpath);
76
+ if (!stats) return await next();
77
+ if (!stats.isFile()) return await next();
78
+ file = loadFile(filename, dir, options, files);
79
+ }
80
+ ctx.status = 200;
81
+ if (enableGzip) ctx.vary("Accept-Encoding");
82
+ if (!file.buffer) {
83
+ const stats = await fs.stat(file.path);
84
+ if (stats.mtime.getTime() !== file.mtime.getTime()) {
85
+ file.mtime = stats.mtime;
86
+ file.md5 = void 0;
87
+ file.length = stats.size;
88
+ }
89
+ }
90
+ ctx.response.lastModified = file.mtime;
91
+ if (file.md5) ctx.response.etag = file.md5;
92
+ if (ctx.fresh) {
93
+ ctx.status = 304;
94
+ return;
95
+ }
96
+ ctx.type = file.type;
97
+ ctx.length = file.zipBuffer ? file.zipBuffer.length : file.length;
98
+ ctx.set("cache-control", file.cacheControl ?? "public, max-age=" + file.maxAge);
99
+ if (file.md5) ctx.set("content-md5", file.md5);
100
+ if (ctx.method === "HEAD") return;
101
+ const acceptGzip = ctx.acceptsEncodings("gzip") === "gzip";
102
+ if (file.zipBuffer) {
103
+ if (acceptGzip) {
104
+ ctx.set("content-encoding", "gzip");
105
+ ctx.body = file.zipBuffer;
106
+ } else ctx.body = file.buffer;
107
+ return;
108
+ }
109
+ const shouldGzip = enableGzip && file.length > 1024 && acceptGzip && file.type && compressible(file.type);
110
+ if (file.buffer) {
111
+ if (shouldGzip) {
112
+ const gzFile = files.get(filename + ".gz");
113
+ if (options.usePrecompiledGzip && gzFile && gzFile.buffer) file.zipBuffer = gzFile.buffer;
114
+ else file.zipBuffer = await gzip(file.buffer);
115
+ ctx.set("content-encoding", "gzip");
116
+ ctx.body = file.zipBuffer;
117
+ } else ctx.body = file.buffer;
118
+ return;
119
+ }
120
+ const stream = createReadStream(file.path);
121
+ if (!file.md5) {
122
+ const hash = crypto.createHash("md5");
123
+ stream.on("data", hash.update.bind(hash));
124
+ stream.on("end", () => {
125
+ file.md5 = hash.digest("base64");
126
+ });
127
+ }
128
+ ctx.body = stream;
129
+ if (shouldGzip) {
130
+ ctx.remove("content-length");
131
+ ctx.set("content-encoding", "gzip");
132
+ ctx.body = stream.pipe(zlib.createGzip());
133
+ }
134
+ };
135
+ }
136
+ /**
137
+ * load file and add file content to cache
138
+ */
139
+ function loadFile(name, dir, options, fileManager) {
140
+ const pathname = path.normalize(path.join(options.prefix, name));
141
+ if (!fileManager.get(pathname)) fileManager.set(pathname, {});
142
+ const obj = fileManager.get(pathname);
143
+ const filename = obj.path = path.join(dir, name);
144
+ const stats = statSync(filename);
145
+ const buffer = readFileSync(filename);
146
+ obj.cacheControl = typeof options.cacheControl === "function" ? options.cacheControl(filename) : options.cacheControl;
147
+ obj.maxAge = (typeof obj.maxAge === "number" ? obj.maxAge : options.maxAge) || 0;
148
+ obj.type = obj.mime = mime.lookup(pathname) || "application/octet-stream";
149
+ obj.mtime = stats.mtime;
150
+ obj.length = stats.size;
151
+ obj.md5 = crypto.createHash("md5").update(buffer).digest("base64");
152
+ debug("file: %s", JSON.stringify(obj, null, 2));
153
+ if (options.buffer) obj.buffer = buffer;
154
+ return obj;
155
+ }
156
+
157
+ //#endregion
158
+ export { FileManager, staticCache };
package/package.json CHANGED
@@ -1,10 +1,7 @@
1
1
  {
2
2
  "name": "@eggjs/koa-static-cache",
3
3
  "description": "Static cache middleware for koa",
4
- "version": "6.2.0",
5
- "publishConfig": {
6
- "access": "public"
7
- },
4
+ "version": "7.0.0-beta.13",
8
5
  "keywords": [
9
6
  "koa",
10
7
  "middleware",
@@ -17,73 +14,58 @@
17
14
  "license": "MIT",
18
15
  "repository": {
19
16
  "type": "git",
20
- "url": "git+https://github.com/eggjs/koa-static-cache.git"
17
+ "url": "git://github.com/eggjs/egg.git",
18
+ "directory": "packages/koa-static-cache"
21
19
  },
22
20
  "bugs": {
23
- "url": "https://github.com/eggjs/koa-static-cache/issues"
21
+ "url": "https://github.com/eggjs/egg/issues"
24
22
  },
23
+ "homepage": "https://github.com/eggjs/egg/tree/next/packages/koa-static-cache",
25
24
  "engines": {
26
- "node": ">= 18.19.0"
25
+ "node": ">=22.18.0"
27
26
  },
28
27
  "dependencies": {
29
28
  "@eggjs/compressible": "^3.0.0",
30
29
  "fs-readdir-recursive": "^1.1.0",
31
- "mime-types": "^2.1.35",
32
- "utility": "^2.4.0"
30
+ "mime-types": "^3.0.0",
31
+ "utility": "^2.5.0"
33
32
  },
34
33
  "devDependencies": {
35
- "@arethetypeswrong/cli": "^0.17.4",
36
- "@eggjs/bin": "7",
37
- "@eggjs/koa": "2",
38
- "@eggjs/supertest": "8",
39
- "@eggjs/tsconfig": "1",
40
34
  "@types/fs-readdir-recursive": "^1.1.3",
41
- "@types/mime-types": "^2.1.4",
42
- "@types/mocha": "10",
43
- "@types/node": "22",
44
- "eslint": "8",
45
- "eslint-config-egg": "14",
46
- "rimraf": "6",
47
- "tshy": "3",
48
- "tshy-after": "1",
49
- "typescript": "5",
50
- "ylru": "2"
51
- },
52
- "scripts": {
53
- "lint": "eslint --cache src test --ext .ts",
54
- "pretest": "npm run clean && npm run lint -- --fix",
55
- "test": "egg-bin test",
56
- "preci": "npm run clean && npm run lint",
57
- "ci": "egg-bin cov",
58
- "postci": "npm run prepublishOnly && npm run clean",
59
- "clean": "rimraf dist",
60
- "prepublishOnly": "tshy && tshy-after && attw --pack"
35
+ "@types/mime-types": "^3.0.0",
36
+ "@types/node": "24.5.2",
37
+ "oxlint": "^1.18.0",
38
+ "oxlint-tsgolint": "^0.2.0",
39
+ "rimraf": "^6.0.1",
40
+ "tsdown": "^0.15.4",
41
+ "typescript": "5.9.2",
42
+ "vitest": "4.0.0-beta.13",
43
+ "ylru": "^2.0.0",
44
+ "@eggjs/bin": "8.0.0-beta.13",
45
+ "@eggjs/koa": "3.1.0-beta.13",
46
+ "@eggjs/supertest": "9.0.0-beta.13",
47
+ "@eggjs/tsconfig": "3.1.0-beta.13"
61
48
  },
62
49
  "type": "module",
63
- "tshy": {
64
- "exports": {
65
- ".": "./src/index.ts",
66
- "./package.json": "./package.json"
67
- }
68
- },
69
50
  "exports": {
70
- ".": {
71
- "import": {
72
- "types": "./dist/esm/index.d.ts",
73
- "default": "./dist/esm/index.js"
74
- },
75
- "require": {
76
- "types": "./dist/commonjs/index.d.ts",
77
- "default": "./dist/commonjs/index.js"
78
- }
79
- },
51
+ ".": "./dist/index.js",
80
52
  "./package.json": "./package.json"
81
53
  },
54
+ "publishConfig": {
55
+ "access": "public"
56
+ },
82
57
  "files": [
83
- "dist",
84
- "src"
58
+ "dist"
85
59
  ],
86
- "types": "./dist/commonjs/index.d.ts",
87
- "main": "./dist/commonjs/index.js",
88
- "module": "./dist/esm/index.js"
89
- }
60
+ "types": "./dist/index.d.ts",
61
+ "main": "./dist/index.js",
62
+ "module": "./dist/index.js",
63
+ "scripts": {
64
+ "build": "tsdown",
65
+ "typecheck": "tsc --noEmit",
66
+ "lint": "oxlint --type-aware",
67
+ "lint:fix": "npm run lint -- --fix",
68
+ "test": "npm run lint:fix && vitest run",
69
+ "ci": "vitest run --coverage"
70
+ }
71
+ }
@@ -1,99 +0,0 @@
1
- export type FileFilter = (path: string) => boolean;
2
- export interface FileMeta {
3
- maxAge?: number;
4
- cacheControl?: string | ((path: string) => string);
5
- buffer?: Buffer;
6
- zipBuffer?: Buffer;
7
- type?: string;
8
- mime?: string;
9
- mtime?: Date;
10
- path?: string;
11
- md5?: string;
12
- length?: number;
13
- }
14
- export interface FileMap {
15
- [path: string]: FileMeta;
16
- }
17
- export interface FileStore {
18
- get(key: string): unknown;
19
- set(key: string, value: unknown): void;
20
- }
21
- export interface Options {
22
- /**
23
- * The root directory from which to serve static assets
24
- * Default to `process.cwd`
25
- */
26
- dir?: string;
27
- /**
28
- * The max age for cache control
29
- * Default to `0`
30
- */
31
- maxAge?: number;
32
- /**
33
- * The cache control header for static files
34
- * Default to `undefined`
35
- * Overrides `options.maxAge`
36
- */
37
- cacheControl?: string | ((path: string) => string);
38
- /**
39
- * store the files in memory instead of streaming from the filesystem on each request
40
- */
41
- buffer?: boolean;
42
- /**
43
- * when request's accept-encoding include gzip, files will compressed by gzip
44
- * Default to `false`
45
- */
46
- gzip?: boolean;
47
- /**
48
- * try use gzip files, loaded from disk, like nginx gzip_static
49
- * Default to `false`
50
- */
51
- usePrecompiledGzip?: boolean;
52
- /**
53
- * object map of aliases
54
- * Default to `{}`
55
- */
56
- alias?: Record<string, string>;
57
- /**
58
- * the url prefix you wish to add
59
- * Default to `''`
60
- */
61
- prefix?: string;
62
- /**
63
- * filter files at init dir, for example - skip non build (source) files.
64
- * If array set - allow only listed files
65
- * Default to `undefined`
66
- */
67
- filter?: FileFilter | string[];
68
- /**
69
- * dynamic load file which not cached on initialization
70
- * Default to `false
71
- */
72
- dynamic?: boolean;
73
- /**
74
- * caches the assets on initialization or not,
75
- * always work together with `options.dynamic`
76
- * Default to `true`
77
- */
78
- preload?: boolean;
79
- /**
80
- * file store for caching
81
- * Default to `undefined`
82
- */
83
- files?: FileMap | FileStore;
84
- }
85
- type Next = () => Promise<void>;
86
- export declare class FileManager {
87
- store?: FileStore;
88
- map?: FileMap;
89
- constructor(store?: FileStore | FileMap);
90
- get(key: string): unknown;
91
- set(key: string, value: FileMeta): void;
92
- }
93
- type MiddlewareFunc = (ctx: any, next: Next) => Promise<void> | void;
94
- export declare function staticCache(): MiddlewareFunc;
95
- export declare function staticCache(dir: string): MiddlewareFunc;
96
- export declare function staticCache(options: Options): MiddlewareFunc;
97
- export declare function staticCache(dir: string, options: Options): MiddlewareFunc;
98
- export declare function staticCache(dir: string, options: Options, files: FileMap | FileStore): MiddlewareFunc;
99
- export {};