@nordhavnhq/beacon 0.7.0 → 0.8.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/README.md +4 -2
- package/dist/{cache-1gURpP7O.d.cts → cache-DIs1jN1m.d.cts} +6 -1
- package/dist/{cache-1gURpP7O.d.ts → cache-DIs1jN1m.d.ts} +6 -1
- package/dist/chunk-FLRBCD6H.js +361 -0
- package/dist/chunk-FLRBCD6H.js.map +1 -0
- package/dist/file-store.cjs +293 -34
- package/dist/file-store.cjs.map +1 -1
- package/dist/file-store.d.cts +10 -24
- package/dist/file-store.d.ts +10 -24
- package/dist/file-store.js +34 -128
- package/dist/file-store.js.map +1 -1
- package/dist/index.cjs +832 -136
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +188 -30
- package/dist/index.d.ts +188 -30
- package/dist/index.js +475 -138
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/file-store.d.ts
CHANGED
|
@@ -7,40 +7,26 @@ interface FileCacheStoreOptions {
|
|
|
7
7
|
maxEntries?: number;
|
|
8
8
|
/**
|
|
9
9
|
* Called when the disk cannot be read or written. The store then keeps
|
|
10
|
-
* working from memory, like the default store. Default: one
|
|
11
|
-
*
|
|
10
|
+
* working from memory, like the default store. Default: one warning per
|
|
11
|
+
* store, so a read-only volume is noticed without flooding the log: on the
|
|
12
|
+
* console, or through the `logger` of the client the store is given to.
|
|
12
13
|
*/
|
|
13
14
|
onError?: (err: unknown) => void;
|
|
14
15
|
}
|
|
15
16
|
declare class FileCacheStore implements CacheStore {
|
|
16
|
-
|
|
17
|
-
private readonly
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
17
|
+
/** The entries in `dir` itself, for a store no client was given to. */
|
|
18
|
+
private readonly own;
|
|
19
|
+
/** The cache of the first client's folder, once there is one. */
|
|
20
|
+
private first;
|
|
21
|
+
/** The folder caches of every client it was given to, for `clear`. */
|
|
22
|
+
private readonly attached;
|
|
21
23
|
constructor(options: FileCacheStoreOptions);
|
|
24
|
+
private get cache();
|
|
22
25
|
get(key: string): CacheEntry | undefined;
|
|
23
26
|
set(key: string, entry: CacheEntry): void;
|
|
24
27
|
delete(key: string): void;
|
|
25
28
|
keys(): Iterable<string>;
|
|
26
29
|
clear(): void;
|
|
27
|
-
/** File name per key: a hash, as keys hold `/` and `:` and may be long. */
|
|
28
|
-
private fileOf;
|
|
29
|
-
/** Fills memory from disk, oldest file first so eviction order survives a restart. */
|
|
30
|
-
private load;
|
|
31
|
-
/** Temp file plus rename, so a reader (or a crash) never sees half a file. */
|
|
32
|
-
private write;
|
|
33
|
-
/**
|
|
34
|
-
* Hands a disk problem to `onError`. Never throws and never leaves a rejection
|
|
35
|
-
* behind: this runs inside a cache write, which runs inside a read, and a
|
|
36
|
-
* hook that fails (or an `async` one whose own work fails) must not fail the
|
|
37
|
-
* read or stop the process over a cache that merely fell back to memory.
|
|
38
|
-
*/
|
|
39
|
-
private fail;
|
|
40
|
-
/** Whether a temp file is old enough to have been abandoned. Unknown counts as "no". */
|
|
41
|
-
private orphaned;
|
|
42
|
-
private remove;
|
|
43
|
-
private list;
|
|
44
30
|
}
|
|
45
31
|
|
|
46
32
|
export { FileCacheStore };
|
package/dist/file-store.js
CHANGED
|
@@ -1,143 +1,49 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { fileDeps, FileCache, ATTACH, attachShared } from './chunk-FLRBCD6H.js';
|
|
2
|
+
import { randomBytes, createHash } from 'crypto';
|
|
3
|
+
import { writeFileSync, utimesSync, statSync, rmSync, rmdirSync, renameSync, readFileSync, readdirSync, mkdirSync } from 'fs';
|
|
4
|
+
import { resolve, join } from 'path';
|
|
4
5
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
var FileCacheStore = class {
|
|
6
|
+
var NODE_DEPS = fileDeps(
|
|
7
|
+
{ mkdirSync, readdirSync, readFileSync, renameSync, rmdirSync, rmSync, statSync, utimesSync, writeFileSync },
|
|
8
|
+
{ createHash, randomBytes },
|
|
9
|
+
{ join, resolve }
|
|
10
|
+
);
|
|
11
|
+
var FileCacheStore = class _FileCacheStore {
|
|
11
12
|
constructor(options) {
|
|
12
|
-
/**
|
|
13
|
-
this.
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
13
|
+
/** The folder caches of every client it was given to, for `clear`. */
|
|
14
|
+
this.attached = /* @__PURE__ */ new Set();
|
|
15
|
+
this.own = new FileCache(options, NODE_DEPS);
|
|
16
|
+
let firstIdentity;
|
|
17
|
+
const attach = (scope) => {
|
|
18
|
+
const plain = Object.getPrototypeOf(this) === _FileCacheStore.prototype;
|
|
19
|
+
if (!plain && firstIdentity !== void 0 && firstIdentity !== scope.identity) return void 0;
|
|
20
|
+
const attached = attachShared(options, NODE_DEPS, scope);
|
|
21
|
+
if (!attached) return void 0;
|
|
22
|
+
firstIdentity ??= scope.identity;
|
|
23
|
+
this.first ??= attached.store;
|
|
24
|
+
this.attached.add(attached.store);
|
|
25
|
+
return plain ? attached : { ...attached, store: this };
|
|
26
|
+
};
|
|
27
|
+
Object.defineProperty(this, ATTACH, { value: attach });
|
|
28
|
+
}
|
|
29
|
+
get cache() {
|
|
30
|
+
return this.first ?? this.own;
|
|
24
31
|
}
|
|
25
32
|
get(key) {
|
|
26
|
-
return this.
|
|
33
|
+
return this.cache.get(key);
|
|
27
34
|
}
|
|
28
35
|
set(key, entry) {
|
|
29
|
-
this.
|
|
30
|
-
this.map.set(key, entry);
|
|
31
|
-
this.write(key, entry);
|
|
32
|
-
while (this.map.size > this.maxEntries) {
|
|
33
|
-
const oldest = this.map.keys().next().value;
|
|
34
|
-
if (oldest === void 0) break;
|
|
35
|
-
this.delete(oldest);
|
|
36
|
-
}
|
|
36
|
+
this.cache.set(key, entry);
|
|
37
37
|
}
|
|
38
38
|
delete(key) {
|
|
39
|
-
this.
|
|
40
|
-
this.remove(this.fileOf(key));
|
|
39
|
+
this.cache.delete(key);
|
|
41
40
|
}
|
|
42
41
|
keys() {
|
|
43
|
-
return this.
|
|
42
|
+
return this.cache.keys();
|
|
44
43
|
}
|
|
45
44
|
clear() {
|
|
46
|
-
this.
|
|
47
|
-
for (const
|
|
48
|
-
if (CACHE_FILE.test(name)) this.remove(join(this.dir, name));
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
// ── Disk ────────────────────────────────────────────────────────────────────
|
|
52
|
-
/** File name per key: a hash, as keys hold `/` and `:` and may be long. */
|
|
53
|
-
fileOf(key) {
|
|
54
|
-
return join(this.dir, createHash("sha256").update(key).digest("hex") + SUFFIX);
|
|
55
|
-
}
|
|
56
|
-
/** Fills memory from disk, oldest file first so eviction order survives a restart. */
|
|
57
|
-
load() {
|
|
58
|
-
try {
|
|
59
|
-
mkdirSync(this.dir, { recursive: true });
|
|
60
|
-
} catch (err) {
|
|
61
|
-
this.fail(err);
|
|
62
|
-
return;
|
|
63
|
-
}
|
|
64
|
-
const found = [];
|
|
65
|
-
for (const name of this.list()) {
|
|
66
|
-
const file = join(this.dir, name);
|
|
67
|
-
if (TEMP_FILE.test(name)) {
|
|
68
|
-
if (this.orphaned(file)) this.remove(file);
|
|
69
|
-
continue;
|
|
70
|
-
}
|
|
71
|
-
if (!CACHE_FILE.test(name)) continue;
|
|
72
|
-
try {
|
|
73
|
-
const stored = JSON.parse(readFileSync(file, "utf8"));
|
|
74
|
-
if (stored?.v !== 1 || typeof stored.key !== "string" || !stored.entry || file !== this.fileOf(stored.key)) {
|
|
75
|
-
throw new Error("not a cache file");
|
|
76
|
-
}
|
|
77
|
-
found.push({ key: stored.key, entry: stored.entry, mtime: statSync(file).mtimeMs });
|
|
78
|
-
} catch {
|
|
79
|
-
this.remove(file);
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
found.sort((a, b) => a.mtime - b.mtime);
|
|
83
|
-
for (const { key, entry } of found) this.map.set(key, entry);
|
|
84
|
-
while (this.map.size > this.maxEntries) {
|
|
85
|
-
const oldest = this.map.keys().next().value;
|
|
86
|
-
if (oldest === void 0) break;
|
|
87
|
-
this.delete(oldest);
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
/** Temp file plus rename, so a reader (or a crash) never sees half a file. */
|
|
91
|
-
write(key, entry) {
|
|
92
|
-
const file = this.fileOf(key);
|
|
93
|
-
const tmp = `${file}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
|
94
|
-
try {
|
|
95
|
-
const stored = { v: 1, key, entry };
|
|
96
|
-
writeFileSync(tmp, JSON.stringify(stored));
|
|
97
|
-
renameSync(tmp, file);
|
|
98
|
-
} catch (err) {
|
|
99
|
-
this.remove(tmp);
|
|
100
|
-
this.fail(err);
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
/**
|
|
104
|
-
* Hands a disk problem to `onError`. Never throws and never leaves a rejection
|
|
105
|
-
* behind: this runs inside a cache write, which runs inside a read, and a
|
|
106
|
-
* hook that fails (or an `async` one whose own work fails) must not fail the
|
|
107
|
-
* read or stop the process over a cache that merely fell back to memory.
|
|
108
|
-
*/
|
|
109
|
-
fail(err) {
|
|
110
|
-
try {
|
|
111
|
-
const outcome = this.onError(err);
|
|
112
|
-
if (typeof outcome?.then === "function") {
|
|
113
|
-
outcome.then(void 0, () => {
|
|
114
|
-
});
|
|
115
|
-
}
|
|
116
|
-
} catch {
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
/** Whether a temp file is old enough to have been abandoned. Unknown counts as "no". */
|
|
120
|
-
orphaned(file) {
|
|
121
|
-
try {
|
|
122
|
-
return Date.now() - statSync(file).mtimeMs > TEMP_ORPHAN_MS;
|
|
123
|
-
} catch {
|
|
124
|
-
return false;
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
remove(file) {
|
|
128
|
-
try {
|
|
129
|
-
rmSync(file, { force: true });
|
|
130
|
-
} catch (err) {
|
|
131
|
-
this.fail(err);
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
list() {
|
|
135
|
-
try {
|
|
136
|
-
return readdirSync(this.dir);
|
|
137
|
-
} catch (err) {
|
|
138
|
-
this.fail(err);
|
|
139
|
-
return [];
|
|
140
|
-
}
|
|
45
|
+
if (this.attached.size === 0) this.own.clear();
|
|
46
|
+
for (const cache of this.attached) cache.clear();
|
|
141
47
|
}
|
|
142
48
|
};
|
|
143
49
|
|
package/dist/file-store.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/file-store.ts"],"names":[],"mappings":";;;;;AAgDA,IAAM,MAAA,GAAS,OAAA;AAQf,IAAM,UAAA,GAAa,sBAAA;AACnB,IAAM,SAAA,GAAY,8CAAA;AAQlB,IAAM,cAAA,GAAiB,GAAA;AAEhB,IAAM,iBAAN,MAA2C;AAAA,EAOhD,YAAY,OAAA,EAAgC;AAF5C;AAAA,IAAA,IAAA,CAAiB,GAAA,uBAAU,GAAA,EAAwB;AAGjD,IAAA,IAAI,CAAC,OAAA,EAAS,GAAA,EAAK,MAAM,IAAI,MAAM,mCAAmC,CAAA;AACtE,IAAA,IAAA,CAAK,MAAM,OAAA,CAAQ,GAAA;AACnB,IAAA,IAAA,CAAK,UAAA,GAAa,QAAQ,UAAA,IAAc,GAAA;AAExC,IAAA,IAAI,MAAA,GAAS,KAAA;AACb,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA,CAAQ,OAAA,KAAY,CAAC,GAAA,KAAQ;AAC1C,MAAA,IAAI,MAAA,EAAQ;AACZ,MAAA,MAAA,GAAS,IAAA;AACT,MAAA,OAAA,CAAQ,IAAA,CAAK,sCAAsC,IAAA,CAAK,GAAG,oCAAoC,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,GAAG,CAAA;AAAA,IACzI,CAAA,CAAA;AAEA,IAAA,IAAA,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CAAA;AACf,MAAA,IAAA,CAAK,KAAK,GAAG,CAAA;AAAA,IACf;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQQ,KAAK,GAAA,EAAoB;AAC/B,IAAA,IAAI;AACF,MAAA,MAAM,OAAA,GAAmB,IAAA,CAAK,OAAA,CAAQ,GAAG,CAAA;AACzC,MAAA,IAAI,OAAQ,OAAA,EAAmD,IAAA,KAAS,UAAA,EAAY;AAClF,QAAC,OAAA,CAAiC,IAAA,CAAK,KAAA,CAAA,EAAW,MAAM;AAAA,QAAC,CAAC,CAAA;AAAA,MAC5D;AAAA,IACF,CAAA,CAAA,MACM;AAAA,IAEN;AAAA,EACF;AAAA;AAAA,EAGQ,SAAS,IAAA,EAAuB;AACtC,IAAA,IAAI;AACF,MAAA,OAAO,KAAK,GAAA,EAAI,GAAI,QAAA,CAAS,IAAI,EAAE,OAAA,GAAU,cAAA;AAAA,IAC/C,CAAA,CAAA,MACM;AACJ,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,EACF;AAAA,EAEQ,OAAO,IAAA,EAAoB;AACjC,IAAA,IAAI;AACF,MAAA,MAAA,CAAO,IAAA,EAAM,EAAE,KAAA,EAAO,IAAA,EAAM,CAAA;AAAA,IAC9B,SACO,GAAA,EAAK;AACV,MAAA,IAAA,CAAK,KAAK,GAAG,CAAA;AAAA,IACf;AAAA,EACF;AAAA,EAEQ,IAAA,GAAiB;AACvB,IAAA,IAAI;AACF,MAAA,OAAO,WAAA,CAAY,KAAK,GAAG,CAAA;AAAA,IAC7B,SACO,GAAA,EAAK;AACV,MAAA,IAAA,CAAK,KAAK,GAAG,CAAA;AACb,MAAA,OAAO,EAAC;AAAA,IACV;AAAA,EACF;AACF","file":"file-store.js","sourcesContent":["/**\n * A `CacheStore` that keeps its entries on disk as well as in memory, so a\n * restarted process still has the last good content - also when the studio is\n * down at that very moment.\n *\n * Node only (it uses `node:fs`), which is why it lives at its own entry point,\n * `@nordhavnhq/beacon/file-store`, and the main entry stays browser-safe.\n *\n * ```ts\n * import { createClient } from '@nordhavnhq/beacon'\n * import { FileCacheStore } from '@nordhavnhq/beacon/file-store'\n *\n * const studio = createClient({\n * apiKey,\n * cache: { store: new FileCacheStore({ dir: '/data/studio-cache' }) },\n * })\n * ```\n *\n * Reads come from memory; the disk is read once, when the store is created, and\n * written through on every change. One directory per site: cache keys do not\n * include the project or the API key, so two sites sharing a directory would\n * serve each other's content while the studio is unreachable.\n */\nimport { createHash, randomBytes } from 'node:crypto'\nimport { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { CacheEntry, CacheStore } from './cache'\n\nexport interface FileCacheStoreOptions {\n /** Directory for the cache files. Created when missing. Put it on a volume that survives a redeploy. */\n dir: string\n /** Soft cap on entries; oldest are evicted first, from memory and disk. Default `500`. */\n maxEntries?: number\n /**\n * Called when the disk cannot be read or written. The store then keeps\n * working from memory, like the default store. Default: one `console.warn`\n * per store, so a read-only volume is noticed without flooding the log.\n */\n onError?: (err: unknown) => void\n}\n\n/** On-disk shape. `v` leaves room to change it without misreading old files. */\ninterface StoredFile {\n v: 1\n key: string\n entry: CacheEntry\n}\n\nconst SUFFIX = '.json'\n\n/**\n * The only names this store reads, replaces or removes: the sha256 of a cache\n * key (see `fileOf`), and the temp file of a write to one. `dir` may hold other\n * files - a mistyped path can point at a project root - and those are never\n * touched, whatever their extension.\n */\nconst CACHE_FILE = /^[0-9a-f]{64}\\.json$/\nconst TEMP_FILE = /^[0-9a-f]{64}\\.json\\.\\d+(\\.[0-9a-f]+)?\\.tmp$/\n\n/**\n * How old a temp file must be before a starting store takes it for an orphan.\n * A write takes milliseconds, so anything younger may be a write under way in\n * another process on the same directory: the old and the new container during\n * a redeploy, or the workers of a cluster.\n */\nconst TEMP_ORPHAN_MS = 60_000\n\nexport class FileCacheStore implements CacheStore {\n private readonly dir: string\n private readonly maxEntries: number\n private readonly onError: (err: unknown) => void\n /** Same order contract as `MemoryCacheStore`: oldest written first. */\n private readonly map = new Map<string, CacheEntry>()\n\n constructor(options: FileCacheStoreOptions) {\n if (!options?.dir) throw new Error('FileCacheStore: `dir` is required')\n this.dir = options.dir\n this.maxEntries = options.maxEntries ?? 500\n\n let warned = false\n this.onError = options.onError ?? ((err) => {\n if (warned) return\n warned = true\n console.warn(`[@nordhavnhq/beacon] file cache at ${this.dir} unusable, continuing in memory:`, err instanceof Error ? err.message : err)\n })\n\n this.load()\n }\n\n get(key: string): CacheEntry | undefined {\n return this.map.get(key)\n }\n\n set(key: string, entry: CacheEntry): void {\n this.map.delete(key)\n this.map.set(key, entry)\n this.write(key, entry)\n while (this.map.size > this.maxEntries) {\n const oldest = this.map.keys().next().value\n if (oldest === undefined) break\n this.delete(oldest)\n }\n }\n\n delete(key: string): void {\n this.map.delete(key)\n this.remove(this.fileOf(key))\n }\n\n keys(): Iterable<string> {\n return this.map.keys()\n }\n\n clear(): void {\n this.map.clear()\n for (const name of this.list()) {\n if (CACHE_FILE.test(name)) this.remove(join(this.dir, name))\n }\n }\n\n // ── Disk ────────────────────────────────────────────────────────────────────\n\n /** File name per key: a hash, as keys hold `/` and `:` and may be long. */\n private fileOf(key: string): string {\n return join(this.dir, createHash('sha256').update(key).digest('hex') + SUFFIX)\n }\n\n /** Fills memory from disk, oldest file first so eviction order survives a restart. */\n private load(): void {\n try {\n mkdirSync(this.dir, { recursive: true })\n }\n catch (err) {\n this.fail(err)\n return\n }\n\n const found: { key: string, entry: CacheEntry, mtime: number }[] = []\n for (const name of this.list()) {\n const file = join(this.dir, name)\n // Left behind by a process killed between write and rename - unless it\n // is fresh, and then it belongs to a write that is still happening.\n if (TEMP_FILE.test(name)) {\n if (this.orphaned(file)) this.remove(file)\n continue\n }\n // Not one of ours: leave it exactly as it is.\n if (!CACHE_FILE.test(name)) continue\n try {\n const stored = JSON.parse(readFileSync(file, 'utf8')) as StoredFile\n if (stored?.v !== 1 || typeof stored.key !== 'string' || !stored.entry || file !== this.fileOf(stored.key)) {\n throw new Error('not a cache file')\n }\n found.push({ key: stored.key, entry: stored.entry, mtime: statSync(file).mtimeMs })\n }\n catch {\n // Ours by name but unreadable, or filed under another key: it can only\n // ever be a miss, so drop it.\n this.remove(file)\n }\n }\n\n found.sort((a, b) => a.mtime - b.mtime)\n for (const { key, entry } of found) this.map.set(key, entry)\n while (this.map.size > this.maxEntries) {\n const oldest = this.map.keys().next().value\n if (oldest === undefined) break\n this.delete(oldest)\n }\n }\n\n /** Temp file plus rename, so a reader (or a crash) never sees half a file. */\n private write(key: string, entry: CacheEntry): void {\n const file = this.fileOf(key)\n // The random part keeps two processes apart that write the same key at the\n // same moment. The pid alone does not: in a container it is 1 for both.\n const tmp = `${file}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`\n try {\n const stored: StoredFile = { v: 1, key, entry }\n writeFileSync(tmp, JSON.stringify(stored))\n renameSync(tmp, file)\n }\n catch (err) {\n this.remove(tmp)\n this.fail(err)\n }\n }\n\n /**\n * Hands a disk problem to `onError`. Never throws and never leaves a rejection\n * behind: this runs inside a cache write, which runs inside a read, and a\n * hook that fails (or an `async` one whose own work fails) must not fail the\n * read or stop the process over a cache that merely fell back to memory.\n */\n private fail(err: unknown): void {\n try {\n const outcome: unknown = this.onError(err)\n if (typeof (outcome as { then?: unknown } | null | undefined)?.then === 'function') {\n (outcome as PromiseLike<unknown>).then(undefined, () => {})\n }\n }\n catch {\n /* the hook's own problem */\n }\n }\n\n /** Whether a temp file is old enough to have been abandoned. Unknown counts as \"no\". */\n private orphaned(file: string): boolean {\n try {\n return Date.now() - statSync(file).mtimeMs > TEMP_ORPHAN_MS\n }\n catch {\n return false\n }\n }\n\n private remove(file: string): void {\n try {\n rmSync(file, { force: true })\n }\n catch (err) {\n this.fail(err)\n }\n }\n\n private list(): string[] {\n try {\n return readdirSync(this.dir)\n }\n catch (err) {\n this.fail(err)\n return []\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/file-store.ts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;AAC9B,IAAA,OAAO,IAAA,CAAK,SAAS,IAAA,CAAK,GAAA;AAAA,EAC5B;AAAA,EAEA,IAAI,GAAA,EAAqC;AACvC,IAAA,OAAO,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,GAAG,CAAA;AAAA,EAC3B;AAAA,EAEA,GAAA,CAAI,KAAa,KAAA,EAAyB;AACxC,IAAA,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,GAAA,EAAK,KAAK,CAAA;AAAA,EAC3B;AAAA,EAEA,OAAO,GAAA,EAAmB;AACxB,IAAA,IAAA,CAAK,KAAA,CAAM,OAAO,GAAG,CAAA;AAAA,EACvB;AAAA,EAEA,IAAA,GAAyB;AACvB,IAAA,OAAO,IAAA,CAAK,MAAM,IAAA,EAAK;AAAA,EACzB;AAAA,EAEA,KAAA,GAAc;AACZ,IAAA,IAAI,KAAK,QAAA,CAAS,IAAA,KAAS,CAAA,EAAG,IAAA,CAAK,IAAI,KAAA,EAAM;AAC7C,IAAA,KAAA,MAAW,KAAA,IAAS,IAAA,CAAK,QAAA,EAAU,KAAA,CAAM,KAAA,EAAM;AAAA,EACjD;AACF","file":"file-store.js","sourcesContent":["/**\n * A `CacheStore` that keeps its entries on disk as well as in memory, so a\n * restarted process still has the last good content - also when the studio is\n * down at that very moment.\n *\n * Node only (it uses `node:fs`), which is why it lives at its own entry point,\n * `@nordhavnhq/beacon/file-store`, and the main entry stays browser-safe. The\n * client's `cache.dir` option builds the same store without this import:\n *\n * ```ts\n * import { createClient } from '@nordhavnhq/beacon'\n *\n * const studio = createClient({ cache: { dir: '/data/studio-cache' } })\n * ```\n *\n * Reads come from memory; the disk is read once, when the store is first\n * used, and written through on every change. Given to a client as\n * `cache.store`, the store keeps its entries in a folder of `dir` named after\n * a hash of that client's server and key, so sites and keys sharing a\n * directory never see each other's content; on the first start after 0.7 it\n * copies the cache files 0.7 left in `dir` into that folder. Given to clients\n * of several keys (a reader and a writer, say), it keeps a folder per key, and\n * each client caches in its own. A store used on its own, without a client,\n * keeps its entries in `dir` itself, as up to 0.7.\n *\n * Its own methods `get`, `set`, `delete` and `keys` (as a site counts what\n * came from disk) act on the folder of the first client it was given to, or\n * on `dir` itself before that; `clear` clears the folder of every client it\n * was given to (a purge reaches the reader and the writer alike).\n *\n * A subclass is used as given, so its overrides keep applying: the clients\n * call its own methods, which act on the folder of the first key it was\n * given to. Given to a client of another key, it is not shared: that client\n * caches in memory, with a warning.\n */\nimport { createHash, randomBytes } from 'node:crypto'\nimport { mkdirSync, readdirSync, readFileSync, renameSync, rmdirSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport type { CacheEntry, CacheStore } from './cache'\nimport { ATTACH, FileCache, attachShared, fileDeps, type AttachedStore, type FileSystem, type StoreScope } from './file-cache'\n\nexport interface FileCacheStoreOptions {\n /** Directory for the cache files. Created when missing. Put it on a volume that survives a redeploy. */\n dir: string\n /** Soft cap on entries; oldest are evicted first, from memory and disk. Default `500`. */\n maxEntries?: number\n /**\n * Called when the disk cannot be read or written. The store then keeps\n * working from memory, like the default store. Default: one warning per\n * store, so a read-only volume is noticed without flooding the log: on the\n * console, or through the `logger` of the client the store is given to.\n */\n onError?: (err: unknown) => void\n}\n\nconst NODE_DEPS = fileDeps(\n { mkdirSync, readdirSync, readFileSync, renameSync, rmdirSync, rmSync, statSync, utimesSync, writeFileSync } as unknown as FileSystem,\n { createHash, randomBytes },\n { join, resolve },\n)\n\nexport class FileCacheStore implements CacheStore {\n /** The entries in `dir` itself, for a store no client was given to. */\n private readonly own: FileCache\n /** The cache of the first client's folder, once there is one. */\n private first: CacheStore | undefined\n /** The folder caches of every client it was given to, for `clear`. */\n private readonly attached = new Set<CacheStore>()\n\n constructor(options: FileCacheStoreOptions) {\n this.own = new FileCache(options, NODE_DEPS)\n let firstIdentity: string | undefined\n // How a client hands over its identity, and gets the cache of its folder\n // back (`attachShared`); kept out of the public type.\n const attach = (scope: StoreScope): AttachedStore | undefined => {\n // A subclass keeps its overrides: the client gets the store itself,\n // which can stand for one folder only.\n const plain = Object.getPrototypeOf(this) === FileCacheStore.prototype\n if (!plain && firstIdentity !== undefined && firstIdentity !== scope.identity) return undefined\n const attached = attachShared(options, NODE_DEPS, scope)\n if (!attached) return undefined\n firstIdentity ??= scope.identity\n this.first ??= attached.store\n this.attached.add(attached.store)\n return plain ? attached : { ...attached, store: this }\n }\n Object.defineProperty(this, ATTACH, { value: attach })\n }\n\n private get cache(): CacheStore {\n return this.first ?? this.own\n }\n\n get(key: string): CacheEntry | undefined {\n return this.cache.get(key)\n }\n\n set(key: string, entry: CacheEntry): void {\n this.cache.set(key, entry)\n }\n\n delete(key: string): void {\n this.cache.delete(key)\n }\n\n keys(): Iterable<string> {\n return this.cache.keys()\n }\n\n clear(): void {\n if (this.attached.size === 0) this.own.clear()\n for (const cache of this.attached) cache.clear()\n }\n}\n"]}
|