@chriscdn/file-cache 0.0.13 → 2.0.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/lib/index.d.ts CHANGED
@@ -2,7 +2,7 @@ type DirectoryPath = string;
2
2
  type FileName = string;
3
3
  type FilePath = string;
4
4
  type Milliseconds = number;
5
- export type FileCacheOptions<T extends Record<string, any>> = {
5
+ type FileCacheOptions<T extends Record<string, any>> = {
6
6
  cachePath: DirectoryPath;
7
7
  autoCreateCachePath?: boolean;
8
8
  cb: (filePath: FilePath, args: T, cache: FileCache<T>) => Promise<void>;
@@ -58,4 +58,5 @@ declare class FileCache<T extends Record<string, any>> {
58
58
  */
59
59
  cleanup(): Promise<void>;
60
60
  }
61
- export { type DirectoryPath, FileCache, type FileName, type FilePath };
61
+
62
+ export { type DirectoryPath, FileCache, type FileCacheOptions, type FileName, type FilePath };
package/lib/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ // src/index.ts
1
2
  import path from "path";
2
3
  import fs from "fs";
3
4
  import { pathExists, pathExistsSync } from "path-exists";
@@ -6,129 +7,137 @@ import { GroupSemaphore, Semaphore } from "@chriscdn/promise-semaphore";
6
7
  import touch from "touch";
7
8
  import { findNuke } from "@chriscdn/find-nuke";
8
9
  import { Duration } from "@chriscdn/duration";
9
- class FileCache {
10
- _cachePath;
11
- _cb;
12
- _ttl;
13
- _cleanupInterval;
14
- _resolveCacheKey;
15
- _ext;
16
- _intervalId = null;
17
- _semaphore = new Semaphore();
18
- _cleanupGroupSemaphore = new GroupSemaphore();
19
- constructor({ cachePath, autoCreateCachePath, cb, ext, ttl, cleanupInterval, resolveCacheKey, }) {
20
- this._cachePath = cachePath;
21
- this._cb = cb;
22
- this._ext = ext;
23
- this._ttl = ttl;
24
- this._cleanupInterval = cleanupInterval ??
25
- Duration.toMilliseconds({ days: 1 });
26
- this._resolveCacheKey = resolveCacheKey ??
27
- ((args) => (JSON.stringify(args)));
28
- // Startup code
29
- if ((pathExistsSync(cachePath))) {
30
- // we're good
31
- }
32
- else if (autoCreateCachePath) {
33
- fs.mkdirSync(cachePath, { recursive: true });
34
- }
35
- else {
36
- throw new Error("💥 FileCache error: cachePath does not exist.");
37
- }
38
- // fire and forget
39
- this.cleanup();
40
- this._intervalId = setInterval(this.cleanup.bind(this), this._cleanupInterval);
10
+ var FileCache = class {
11
+ _cachePath;
12
+ _cb;
13
+ _ttl;
14
+ _cleanupInterval;
15
+ _resolveCacheKey;
16
+ _ext;
17
+ _intervalId = null;
18
+ _semaphore = new Semaphore();
19
+ _cleanupGroupSemaphore = new GroupSemaphore();
20
+ constructor({
21
+ cachePath,
22
+ autoCreateCachePath,
23
+ cb,
24
+ ext,
25
+ ttl,
26
+ cleanupInterval,
27
+ resolveCacheKey
28
+ }) {
29
+ this._cachePath = cachePath;
30
+ this._cb = cb;
31
+ this._ext = ext;
32
+ this._ttl = ttl;
33
+ this._cleanupInterval = cleanupInterval ?? Duration.toMilliseconds({ days: 1 });
34
+ this._resolveCacheKey = resolveCacheKey ?? ((args) => JSON.stringify(args));
35
+ if (pathExistsSync(cachePath)) {
36
+ } else if (autoCreateCachePath) {
37
+ fs.mkdirSync(cachePath, { recursive: true });
38
+ } else {
39
+ throw new Error("\u{1F4A5} FileCache error: cachePath does not exist.");
41
40
  }
42
- /**
43
- * Resolves the filename for the cache based on the provided arguments.
44
- *
45
- * Uses the provided `resolveFileName` function if available, or falls back to
46
- * generating a hash from the arguments to create a unique file name.
47
- */
48
- async resolveFileName(args) {
49
- const [name, ext] = await Promise.all([
50
- this._resolveCacheKey(args),
51
- this._ext(args),
52
- ]);
53
- const resolvedFileName = sha1(JSON.stringify([name, ext]));
54
- return path.format({
55
- name: resolvedFileName,
56
- ext,
57
- });
41
+ this.cleanup();
42
+ this._intervalId = setInterval(
43
+ this.cleanup.bind(this),
44
+ this._cleanupInterval
45
+ );
46
+ }
47
+ /**
48
+ * Resolves the filename for the cache based on the provided arguments.
49
+ *
50
+ * Uses the provided `resolveFileName` function if available, or falls back to
51
+ * generating a hash from the arguments to create a unique file name.
52
+ */
53
+ async resolveFileName(args) {
54
+ const [name, ext] = await Promise.all([
55
+ this._resolveCacheKey(args),
56
+ this._ext(args)
57
+ ]);
58
+ const resolvedFileName = sha1(JSON.stringify([name, ext]));
59
+ return path.format({
60
+ name: resolvedFileName,
61
+ ext
62
+ });
63
+ }
64
+ /**
65
+ * Retrieves a cached file for the given arguments.
66
+ * If the file doesn't exist, it is generated by the callback and stored.
67
+ *
68
+ * Concurrency-safe, ensuring no conflicts when multiple requests are made
69
+ * for the same file.
70
+ *
71
+ * @param args The arguments used to determine the file's identity and generation
72
+ * @returns The path to the cached or newly created file
73
+ */
74
+ async getFile(args) {
75
+ const filePath = await this.resolveFilePath(args);
76
+ try {
77
+ await Promise.all([
78
+ this._cleanupGroupSemaphore.acquire("getFile"),
79
+ this._semaphore.acquire(filePath)
80
+ ]);
81
+ if (await pathExists(filePath)) {
82
+ touch(filePath);
83
+ } else {
84
+ await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
85
+ await this._cb(filePath, args, this);
86
+ }
87
+ } finally {
88
+ this._semaphore.release(filePath);
89
+ this._cleanupGroupSemaphore.release("getFile");
58
90
  }
59
- /**
60
- * Retrieves a cached file for the given arguments.
61
- * If the file doesn't exist, it is generated by the callback and stored.
62
- *
63
- * Concurrency-safe, ensuring no conflicts when multiple requests are made
64
- * for the same file.
65
- *
66
- * @param args The arguments used to determine the file's identity and generation
67
- * @returns The path to the cached or newly created file
68
- */
69
- async getFile(args) {
70
- const filePath = await this.resolveFilePath(args);
71
- try {
72
- await Promise.all([
73
- this._cleanupGroupSemaphore.acquire("getFile"),
74
- this._semaphore.acquire(filePath),
75
- ]);
76
- if (await pathExists(filePath)) {
77
- // fire and forget
78
- touch(filePath);
79
- }
80
- else {
81
- await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
82
- await this._cb(filePath, args, this);
83
- }
84
- }
85
- finally {
86
- this._semaphore.release(filePath);
87
- this._cleanupGroupSemaphore.release("getFile");
88
- }
89
- return filePath;
91
+ return filePath;
92
+ }
93
+ /**
94
+ * Resolves the full file path for the cached file based on the provided arguments.
95
+ *
96
+ * @param args The arguments used to resolve the file path
97
+ * @returns The full path to the cached file
98
+ */
99
+ async resolveFilePath(args) {
100
+ const fileName = await this.resolveFileName(args);
101
+ const filePath = path.resolve(
102
+ this._cachePath,
103
+ fileName[0],
104
+ fileName[1],
105
+ fileName[2],
106
+ fileName
107
+ );
108
+ return filePath;
109
+ }
110
+ /**
111
+ * Stops the background cleanup process, but does not delete any cached files.
112
+ */
113
+ destroy() {
114
+ if (this._intervalId) {
115
+ clearInterval(this._intervalId);
116
+ this._intervalId = null;
90
117
  }
91
- /**
92
- * Resolves the full file path for the cached file based on the provided arguments.
93
- *
94
- * @param args The arguments used to resolve the file path
95
- * @returns The full path to the cached file
96
- */
97
- async resolveFilePath(args) {
98
- const fileName = await this.resolveFileName(args);
99
- const filePath = path.resolve(this._cachePath, fileName[0], fileName[1], fileName[2], fileName);
100
- return filePath;
118
+ }
119
+ async has(args) {
120
+ const filePath = await this.resolveFilePath(args);
121
+ return await pathExists(filePath);
122
+ }
123
+ /**
124
+ * Runs a cleanup pass to remove files older than 1 day from the cache.
125
+ * This is called periodically, but can be triggered manually.
126
+ */
127
+ async cleanup() {
128
+ try {
129
+ await this._cleanupGroupSemaphore.acquire("cleanup");
130
+ await findNuke(this._cachePath, {
131
+ olderThan: this._ttl,
132
+ verbose: true,
133
+ deleteEmptyDirectories: true
134
+ });
135
+ } finally {
136
+ this._cleanupGroupSemaphore.release("cleanup");
101
137
  }
102
- /**
103
- * Stops the background cleanup process, but does not delete any cached files.
104
- */
105
- destroy() {
106
- if (this._intervalId) {
107
- clearInterval(this._intervalId);
108
- this._intervalId = null;
109
- }
110
- }
111
- async has(args) {
112
- const filePath = await this.resolveFilePath(args);
113
- return await pathExists(filePath);
114
- }
115
- /**
116
- * Runs a cleanup pass to remove files older than 1 day from the cache.
117
- * This is called periodically, but can be triggered manually.
118
- */
119
- async cleanup() {
120
- try {
121
- await this._cleanupGroupSemaphore.acquire("cleanup");
122
- await findNuke(this._cachePath, {
123
- olderThan: this._ttl,
124
- verbose: true,
125
- deleteEmptyDirectories: true,
126
- });
127
- }
128
- finally {
129
- this._cleanupGroupSemaphore.release("cleanup");
130
- }
131
- }
132
- }
133
- export { FileCache };
138
+ }
139
+ };
140
+ export {
141
+ FileCache
142
+ };
134
143
  //# sourceMappingURL=index.js.map
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAC;AACxE,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAiB9C,MAAM,SAAS;IACL,UAAU,CAAmC;IAC7C,GAAG,CAA4B;IAC/B,IAAI,CAA6B;IACjC,gBAAgB,CAAyC;IACzD,gBAAgB,CAEH;IACb,IAAI,CAA6B;IACjC,WAAW,GAA0C,IAAI,CAAC;IAC1D,UAAU,GAAc,IAAI,SAAS,EAAE,CAAC;IACxC,sBAAsB,GAAmB,IAAI,cAAc,EAAE,CAAC;IAEtE,YACE,EACE,SAAS,EACT,mBAAmB,EACnB,EAAE,EACF,GAAG,EACH,GAAG,EACH,eAAe,EACf,eAAe,GACK;QAEtB,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC;QACd,IAAI,CAA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AC;IAClB,CAAC;IAED;;OAEG;IACH,OAAO;QACL,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;YACrB,aAAa,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YAChC,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;QAC1B,CAAC;IACH,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,IAAO;QACf,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC;QAClD,OAAO,MAAM,UAAU,CAAC,QAAQ,CAAC,CAAC;IACpC,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,OAAO;QACX,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,sBAAsB,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;YACrD,MAAM,QAAQ,CAAC,IAAI,CAAC,UAAU,EAAE;gBAC9B,SAAS,EAAE,IAAI,CAAC,IAAI;gBACpB,OAAO,EAAE,IAAI;gBACb,sBAAsB,EAAE,IAAI;aAC7B,CAAC,CAAC;QACL,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC,sBAAsB,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QACjD,CAAC;IACH,CAAC;CACF;AAED,OAAO,EAAsB,SAAS,EAAgC,CAAC"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport { pathExists, pathExistsSync } from \"path-exists\";\nimport sha1 from \"sha1\";\nimport { GroupSemaphore, Semaphore } from \"@chriscdn/promise-semaphore\";\nimport touch from \"touch\";\nimport { findNuke } from \"@chriscdn/find-nuke\";\nimport { Duration } from \"@chriscdn/duration\";\n\ntype DirectoryPath = string;\ntype FileName = string;\ntype FilePath = string;\ntype Milliseconds = number;\n\nexport type FileCacheOptions<T extends Record<string, any>> = {\n cachePath: DirectoryPath;\n autoCreateCachePath?: boolean;\n cb: (filePath: FilePath, args: T, cache: FileCache<T>) => Promise<void>;\n ext: (args: T) => string | Promise<string>;\n resolveCacheKey?: (args: T) => string | Promise<string>;\n ttl: Milliseconds;\n cleanupInterval?: Milliseconds;\n};\n\nclass FileCache<T extends Record<string, any>> {\n private _cachePath: FileCacheOptions<T>[\"cachePath\"];\n private _cb: FileCacheOptions<T>[\"cb\"];\n private _ttl: FileCacheOptions<T>[\"ttl\"];\n private _cleanupInterval: FileCacheOptions<T>[\"cleanupInterval\"];\n private _resolveCacheKey: Required<\n FileCacheOptions<T>\n >[\"resolveCacheKey\"];\n private _ext: FileCacheOptions<T>[\"ext\"];\n private _intervalId: ReturnType<typeof setInterval> | null = null;\n private _semaphore: Semaphore = new Semaphore();\n private _cleanupGroupSemaphore: GroupSemaphore = new GroupSemaphore();\n\n constructor(\n {\n cachePath,\n autoCreateCachePath,\n cb,\n ext,\n ttl,\n cleanupInterval,\n resolveCacheKey,\n }: FileCacheOptions<T>,\n ) {\n this._cachePath = cachePath;\n this._cb = cb;\n this._ext = ext;\n this._ttl = ttl;\n this._cleanupInterval = cleanupInterval ??\n Duration.toMilliseconds({ days: 1 });\n\n this._resolveCacheKey = resolveCacheKey ??\n ((args: T) => (JSON.stringify(args)));\n\n // Startup code\n if ((pathExistsSync(cachePath))) {\n // we're good\n } else if (autoCreateCachePath) {\n fs.mkdirSync(cachePath, { recursive: true });\n } else {\n throw new Error(\"💥 FileCache error: cachePath does not exist.\");\n }\n\n // fire and forget\n this.cleanup();\n\n this._intervalId = setInterval(\n this.cleanup.bind(this),\n this._cleanupInterval,\n );\n }\n\n /**\n * Resolves the filename for the cache based on the provided arguments.\n *\n * Uses the provided `resolveFileName` function if available, or falls back to\n * generating a hash from the arguments to create a unique file name.\n */\n private async resolveFileName(args: T): Promise<FileName> {\n const [name, ext] = await Promise.all([\n this._resolveCacheKey(args),\n this._ext(args),\n ]);\n\n const resolvedFileName = sha1(JSON.stringify([name, ext]));\n\n return path.format({\n name: resolvedFileName,\n ext,\n }) as FileName;\n }\n\n /**\n * Retrieves a cached file for the given arguments.\n * If the file doesn't exist, it is generated by the callback and stored.\n *\n * Concurrency-safe, ensuring no conflicts when multiple requests are made\n * for the same file.\n *\n * @param args The arguments used to determine the file's identity and generation\n * @returns The path to the cached or newly created file\n */\n async getFile(args: T): Promise<FilePath> {\n const filePath = await this.resolveFilePath(args);\n\n try {\n await Promise.all([\n this._cleanupGroupSemaphore.acquire(\"getFile\"),\n this._semaphore.acquire(filePath),\n ]);\n\n if (await pathExists(filePath)) {\n // fire and forget\n touch(filePath);\n } else {\n await fs.promises.mkdir(path.dirname(filePath), { recursive: true });\n await this._cb(filePath, args, this);\n }\n } finally {\n this._semaphore.release(filePath);\n this._cleanupGroupSemaphore.release(\"getFile\");\n }\n\n return filePath;\n }\n\n /**\n * Resolves the full file path for the cached file based on the provided arguments.\n *\n * @param args The arguments used to resolve the file path\n * @returns The full path to the cached file\n */\n async resolveFilePath(args: T): Promise<FilePath> {\n const fileName = await this.resolveFileName(args);\n\n const filePath = path.resolve(\n this._cachePath,\n fileName[0]!,\n fileName[1]!,\n fileName[2]!,\n fileName,\n );\n\n return filePath;\n }\n\n /**\n * Stops the background cleanup process, but does not delete any cached files.\n */\n destroy() {\n if (this._intervalId) {\n clearInterval(this._intervalId);\n this._intervalId = null;\n }\n }\n\n async has(args: T): Promise<boolean> {\n const filePath = await this.resolveFilePath(args);\n return await pathExists(filePath);\n }\n\n /**\n * Runs a cleanup pass to remove files older than 1 day from the cache.\n * This is called periodically, but can be triggered manually.\n */\n async cleanup() {\n try {\n await this._cleanupGroupSemaphore.acquire(\"cleanup\");\n await findNuke(this._cachePath, {\n olderThan: this._ttl,\n verbose: true,\n deleteEmptyDirectories: true,\n });\n } finally {\n this._cleanupGroupSemaphore.release(\"cleanup\");\n }\n }\n}\n\nexport { type DirectoryPath, FileCache, type FileName, type FilePath };\n"],"mappings":";AAAA,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,SAAS,YAAY,sBAAsB;AAC3C,OAAO,UAAU;AACjB,SAAS,gBAAgB,iBAAiB;AAC1C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QACT,wBAAwB;AAAA,MAC1B,CAAC;AAAA,IACH,UAAE;AACA,WAAK,uBAAuB,QAAQ,SAAS;AAAA,IAC/C;AAAA,EACF;AACF;","names":[]}
package/package.json CHANGED
@@ -1,35 +1,37 @@
1
1
  {
2
2
  "name": "@chriscdn/file-cache",
3
- "version": "0.0.13",
4
- "description": "File cache ",
3
+ "version": "2.0.0",
4
+ "description": "File cache",
5
5
  "repository": "https://github.com/chriscdn/file-cache",
6
6
  "author": "Christopher Meyer <chris@schwiiz.org>",
7
7
  "license": "MIT",
8
8
  "type": "module",
9
- "source": "./src/index.ts",
10
- "module": "./lib/index.js",
9
+ "main": "./lib/index.js",
11
10
  "types": "./lib/index.d.ts",
12
- "exports": {
13
- "default": "./lib/index.js"
14
- },
11
+ "exports": "./lib/index.js",
15
12
  "scripts": {
16
- "build": "rimraf ./lib/ && tsc",
13
+ "build": "tsup",
17
14
  "test": "vitest"
18
15
  },
19
16
  "dependencies": {
20
- "@chriscdn/duration": "^1.0.3",
21
- "@chriscdn/find-nuke": "^0.0.5",
22
- "@chriscdn/promise-semaphore": "^3.1.1",
17
+ "@chriscdn/duration": "^2.0.0",
18
+ "@chriscdn/find-nuke": "^2.0.0",
19
+ "@chriscdn/promise-semaphore": "^4.0.0",
23
20
  "path-exists": "^5.0.0",
24
21
  "sha1": "^1.1.1",
25
- "temp": "^0.9.4",
26
22
  "touch": "^3.1.1"
27
23
  },
28
24
  "devDependencies": {
29
- "@tsconfig/node22": "^22.0.2",
25
+ "@tsconfig/strictest": "^2.0.7",
30
26
  "@types/sha1": "^1.1.5",
27
+ "@types/temp": "^0.9.4",
31
28
  "@types/touch": "^3.1.5",
32
- "typescript": "^5.9.2",
33
- "vitest": "^3.2.4"
34
- }
29
+ "temp": "^0.9.4",
30
+ "tsup": "^8.5.1",
31
+ "typescript": "^5.9.3",
32
+ "vitest": "^4.0.6"
33
+ },
34
+ "files": [
35
+ "lib"
36
+ ]
35
37
  }
package/.gitattributes DELETED
@@ -1 +0,0 @@
1
- *.pdf filter=lfs diff=lfs merge=lfs -text
@@ -1,45 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { FileCache } from "../src";
3
- import { Duration } from "@chriscdn/duration";
4
- import { promises as fs } from "fs";
5
- import temp from "temp";
6
- import { pathExists } from "path-exists";
7
-
8
- const pause = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
9
-
10
- const testPDFFile = "./__tests__/pdfs/lorem.pdf";
11
-
12
- describe("Cache Expiration", async () => {
13
- const cache = new FileCache<{ a: number }>({
14
- cachePath: await temp.mkdir("file-cache-test"),
15
- cb: async (filePath, { a }) => {
16
- await fs.copyFile(
17
- testPDFFile,
18
- filePath,
19
- );
20
- },
21
- ext: () => ".pdf",
22
- ttl: Duration.toMilliseconds({ seconds: 1 }),
23
- cleanupInterval: Duration.toMilliseconds({ seconds: 2 }),
24
- });
25
-
26
- it("sync", async () => {
27
- //
28
- const filePath3 = await cache.getFile({ a: 1 });
29
-
30
- // test if filePath exists
31
- expect(await pathExists(filePath3)).toBe(true);
32
-
33
- // wait a second
34
- await pause(Duration.toMilliseconds({ seconds: 1 }));
35
-
36
- // should still exist
37
- expect(await pathExists(filePath3)).toBe(true);
38
-
39
- // wait 2 seconds
40
- await pause(Duration.toMilliseconds({ seconds: 2 }));
41
-
42
- // should not longer exist due to cleanup
43
- expect(await pathExists(filePath3)).toBe(false);
44
- });
45
- });
Binary file
package/src/index.ts DELETED
@@ -1,184 +0,0 @@
1
- import path from "path";
2
- import fs from "fs";
3
- import { pathExists, pathExistsSync } from "path-exists";
4
- import sha1 from "sha1";
5
- import { GroupSemaphore, Semaphore } from "@chriscdn/promise-semaphore";
6
- import touch from "touch";
7
- import { findNuke } from "@chriscdn/find-nuke";
8
- import { Duration } from "@chriscdn/duration";
9
-
10
- type DirectoryPath = string;
11
- type FileName = string;
12
- type FilePath = string;
13
- type Milliseconds = number;
14
-
15
- export type FileCacheOptions<T extends Record<string, any>> = {
16
- cachePath: DirectoryPath;
17
- autoCreateCachePath?: boolean;
18
- cb: (filePath: FilePath, args: T, cache: FileCache<T>) => Promise<void>;
19
- ext: (args: T) => string | Promise<string>;
20
- resolveCacheKey?: (args: T) => string | Promise<string>;
21
- ttl: Milliseconds;
22
- cleanupInterval?: Milliseconds;
23
- };
24
-
25
- class FileCache<T extends Record<string, any>> {
26
- private _cachePath: FileCacheOptions<T>["cachePath"];
27
- private _cb: FileCacheOptions<T>["cb"];
28
- private _ttl: FileCacheOptions<T>["ttl"];
29
- private _cleanupInterval: FileCacheOptions<T>["cleanupInterval"];
30
- private _resolveCacheKey: Required<
31
- FileCacheOptions<T>
32
- >["resolveCacheKey"];
33
- private _ext: FileCacheOptions<T>["ext"];
34
- private _intervalId: ReturnType<typeof setInterval> | null = null;
35
- private _semaphore: Semaphore = new Semaphore();
36
- private _cleanupGroupSemaphore: GroupSemaphore = new GroupSemaphore();
37
-
38
- constructor(
39
- {
40
- cachePath,
41
- autoCreateCachePath,
42
- cb,
43
- ext,
44
- ttl,
45
- cleanupInterval,
46
- resolveCacheKey,
47
- }: FileCacheOptions<T>,
48
- ) {
49
- this._cachePath = cachePath;
50
- this._cb = cb;
51
- this._ext = ext;
52
- this._ttl = ttl;
53
- this._cleanupInterval = cleanupInterval ??
54
- Duration.toMilliseconds({ days: 1 });
55
-
56
- this._resolveCacheKey = resolveCacheKey ??
57
- ((args: T) => (JSON.stringify(args)));
58
-
59
- // Startup code
60
- if ((pathExistsSync(cachePath))) {
61
- // we're good
62
- } else if (autoCreateCachePath) {
63
- fs.mkdirSync(cachePath, { recursive: true });
64
- } else {
65
- throw new Error("💥 FileCache error: cachePath does not exist.");
66
- }
67
-
68
- // fire and forget
69
- this.cleanup();
70
-
71
- this._intervalId = setInterval(
72
- this.cleanup.bind(this),
73
- this._cleanupInterval,
74
- );
75
- }
76
-
77
- /**
78
- * Resolves the filename for the cache based on the provided arguments.
79
- *
80
- * Uses the provided `resolveFileName` function if available, or falls back to
81
- * generating a hash from the arguments to create a unique file name.
82
- */
83
- private async resolveFileName(args: T): Promise<FileName> {
84
- const [name, ext] = await Promise.all([
85
- this._resolveCacheKey(args),
86
- this._ext(args),
87
- ]);
88
-
89
- const resolvedFileName = sha1(JSON.stringify([name, ext]));
90
-
91
- return path.format({
92
- name: resolvedFileName,
93
- ext,
94
- }) as FileName;
95
- }
96
-
97
- /**
98
- * Retrieves a cached file for the given arguments.
99
- * If the file doesn't exist, it is generated by the callback and stored.
100
- *
101
- * Concurrency-safe, ensuring no conflicts when multiple requests are made
102
- * for the same file.
103
- *
104
- * @param args The arguments used to determine the file's identity and generation
105
- * @returns The path to the cached or newly created file
106
- */
107
- async getFile(args: T): Promise<FilePath> {
108
- const filePath = await this.resolveFilePath(args);
109
-
110
- try {
111
- await Promise.all([
112
- this._cleanupGroupSemaphore.acquire("getFile"),
113
- this._semaphore.acquire(filePath),
114
- ]);
115
-
116
- if (await pathExists(filePath)) {
117
- // fire and forget
118
- touch(filePath);
119
- } else {
120
- await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
121
- await this._cb(filePath, args, this);
122
- }
123
- } finally {
124
- this._semaphore.release(filePath);
125
- this._cleanupGroupSemaphore.release("getFile");
126
- }
127
-
128
- return filePath;
129
- }
130
-
131
- /**
132
- * Resolves the full file path for the cached file based on the provided arguments.
133
- *
134
- * @param args The arguments used to resolve the file path
135
- * @returns The full path to the cached file
136
- */
137
- async resolveFilePath(args: T): Promise<FilePath> {
138
- const fileName = await this.resolveFileName(args);
139
-
140
- const filePath = path.resolve(
141
- this._cachePath,
142
- fileName[0],
143
- fileName[1],
144
- fileName[2],
145
- fileName,
146
- );
147
-
148
- return filePath;
149
- }
150
-
151
- /**
152
- * Stops the background cleanup process, but does not delete any cached files.
153
- */
154
- destroy() {
155
- if (this._intervalId) {
156
- clearInterval(this._intervalId);
157
- this._intervalId = null;
158
- }
159
- }
160
-
161
- async has(args: T): Promise<boolean> {
162
- const filePath = await this.resolveFilePath(args);
163
- return await pathExists(filePath);
164
- }
165
-
166
- /**
167
- * Runs a cleanup pass to remove files older than 1 day from the cache.
168
- * This is called periodically, but can be triggered manually.
169
- */
170
- async cleanup() {
171
- try {
172
- await this._cleanupGroupSemaphore.acquire("cleanup");
173
- await findNuke(this._cachePath, {
174
- olderThan: this._ttl,
175
- verbose: true,
176
- deleteEmptyDirectories: true,
177
- });
178
- } finally {
179
- this._cleanupGroupSemaphore.release("cleanup");
180
- }
181
- }
182
- }
183
-
184
- export { type DirectoryPath, FileCache, type FileName, type FilePath };
package/tsconfig.json DELETED
@@ -1,11 +0,0 @@
1
- {
2
- "extends": "@tsconfig/node22/tsconfig.json",
3
- "compilerOptions": {
4
- "allowSyntheticDefaultImports": true,
5
- "outDir": "./lib",
6
- "declaration": true,
7
- "declarationDir": "./lib",
8
- "sourceMap": true
9
- },
10
- "include": ["./src/**/*"]
11
- }