@nordhavnhq/beacon 0.6.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 -3
- package/dist/{cache-q8uLEGYg.d.cts → cache-DIs1jN1m.d.cts} +8 -3
- package/dist/{cache-q8uLEGYg.d.ts → cache-DIs1jN1m.d.ts} +8 -3
- 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 +1443 -106
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +225 -81
- package/dist/index.d.ts +225 -81
- package/dist/index.js +1085 -103
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
# @nordhavnhq/beacon
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
JavaScript client for the content API: the websites built on the platform read
|
|
4
|
+
and write their content with it.
|
|
4
5
|
|
|
5
|
-
|
|
6
|
-
|
|
6
|
+
Public on npm, MIT licensed. This README is short on purpose: the
|
|
7
|
+
documentation is the platform guide's Beacon pages.
|
|
7
8
|
|
|
8
9
|
## License
|
|
9
10
|
|
|
@@ -60,8 +60,8 @@ interface CacheOptions {
|
|
|
60
60
|
/**
|
|
61
61
|
* Minimum ms between two project-stamp checks. Default `60000` (1 minute) -
|
|
62
62
|
* this is the freshness window for PUBLIC visitors (an edit is picked up on
|
|
63
|
-
* the next check after it lands)
|
|
64
|
-
*
|
|
63
|
+
* the next check after it lands). A read with `{ cache: false }` skips the
|
|
64
|
+
* wait.
|
|
65
65
|
*
|
|
66
66
|
* The check fires only on a read and is throttled, so a quiet site barely
|
|
67
67
|
* checks at all; the interval only caps the busy case. Each check costs the
|
|
@@ -87,7 +87,12 @@ interface CacheOptions {
|
|
|
87
87
|
waitForFresh?: number | false;
|
|
88
88
|
/** Soft cap on entries; oldest are evicted first. Default `500`. */
|
|
89
89
|
maxEntries?: number;
|
|
90
|
-
/**
|
|
90
|
+
/**
|
|
91
|
+
* Custom backing store. Defaults to an in-memory store. A `FileCacheStore`
|
|
92
|
+
* passed to a client is kept per key, as the client's `cache.dir` is; a
|
|
93
|
+
* store of your own gets the cache keys as they are, so one shared by
|
|
94
|
+
* several sites must keep them apart itself.
|
|
95
|
+
*/
|
|
91
96
|
store?: CacheStore;
|
|
92
97
|
}
|
|
93
98
|
/** In-memory store with insertion-order (FIFO) eviction once `maxEntries` is hit. */
|
|
@@ -60,8 +60,8 @@ interface CacheOptions {
|
|
|
60
60
|
/**
|
|
61
61
|
* Minimum ms between two project-stamp checks. Default `60000` (1 minute) -
|
|
62
62
|
* this is the freshness window for PUBLIC visitors (an edit is picked up on
|
|
63
|
-
* the next check after it lands)
|
|
64
|
-
*
|
|
63
|
+
* the next check after it lands). A read with `{ cache: false }` skips the
|
|
64
|
+
* wait.
|
|
65
65
|
*
|
|
66
66
|
* The check fires only on a read and is throttled, so a quiet site barely
|
|
67
67
|
* checks at all; the interval only caps the busy case. Each check costs the
|
|
@@ -87,7 +87,12 @@ interface CacheOptions {
|
|
|
87
87
|
waitForFresh?: number | false;
|
|
88
88
|
/** Soft cap on entries; oldest are evicted first. Default `500`. */
|
|
89
89
|
maxEntries?: number;
|
|
90
|
-
/**
|
|
90
|
+
/**
|
|
91
|
+
* Custom backing store. Defaults to an in-memory store. A `FileCacheStore`
|
|
92
|
+
* passed to a client is kept per key, as the client's `cache.dir` is; a
|
|
93
|
+
* store of your own gets the cache keys as they are, so one shared by
|
|
94
|
+
* several sites must keep them apart itself.
|
|
95
|
+
*/
|
|
91
96
|
store?: CacheStore;
|
|
92
97
|
}
|
|
93
98
|
/** In-memory store with insertion-order (FIFO) eviction once `maxEntries` is hit. */
|
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
// src/file-cache.ts
|
|
2
|
+
var ATTACH = /* @__PURE__ */ Symbol.for("@nordhavnhq/beacon/file-cache-attach/3");
|
|
3
|
+
var SUFFIX = ".json";
|
|
4
|
+
var CACHE_FILE = /^[0-9a-f]{64}\.json$/;
|
|
5
|
+
var TEMP_FILE = /^[0-9a-f]{64}\.json\.\d+(\.[0-9a-f]+)?\.tmp$/;
|
|
6
|
+
var FOLDER = /^[0-9a-f]{16}$/;
|
|
7
|
+
var MARKER = ".beacon-cache";
|
|
8
|
+
var MARKER_TEXT = "A cache of @nordhavnhq/beacon. Removed by beacon once unused for 30 days; safe to delete.\n";
|
|
9
|
+
var TEMP_ORPHAN_MS = 6e4;
|
|
10
|
+
var STALE_MS = 30 * 24 * 36e5;
|
|
11
|
+
var TOUCH_MS = 24 * 36e5;
|
|
12
|
+
var FileCache = class {
|
|
13
|
+
constructor(options, deps) {
|
|
14
|
+
/** Same order contract as `MemoryCacheStore`: oldest written first. */
|
|
15
|
+
this.map = /* @__PURE__ */ new Map();
|
|
16
|
+
/** Read from disk on first use, not at construction: a client attaching first decides where from. */
|
|
17
|
+
this.loaded = false;
|
|
18
|
+
this.touchedAt = 0;
|
|
19
|
+
/** Where the one warning goes without an `onError`: the console, or the attaching client's `logger`. */
|
|
20
|
+
this.warnTo = (...args) => console.warn(...args);
|
|
21
|
+
if (!options?.dir) throw new Error("FileCacheStore: `dir` is required");
|
|
22
|
+
this.dir = options.dir;
|
|
23
|
+
this.folder = options.dir;
|
|
24
|
+
this.maxEntries = options.maxEntries ?? 500;
|
|
25
|
+
this.deps = deps;
|
|
26
|
+
let warned = false;
|
|
27
|
+
this.onError = options.onError ?? ((err) => {
|
|
28
|
+
if (warned) return;
|
|
29
|
+
warned = true;
|
|
30
|
+
this.warnTo?.(`[@nordhavnhq/beacon] file cache at ${this.folder} unusable, continuing in memory:`, err instanceof Error ? err.message : err);
|
|
31
|
+
});
|
|
32
|
+
this.ownWarning = options.onError === void 0;
|
|
33
|
+
}
|
|
34
|
+
get(key) {
|
|
35
|
+
this.ensureLoaded();
|
|
36
|
+
this.touch();
|
|
37
|
+
return this.map.get(key);
|
|
38
|
+
}
|
|
39
|
+
set(key, entry) {
|
|
40
|
+
this.ensureLoaded();
|
|
41
|
+
this.map.delete(key);
|
|
42
|
+
this.map.set(key, entry);
|
|
43
|
+
this.write(key, entry);
|
|
44
|
+
this.evict();
|
|
45
|
+
}
|
|
46
|
+
delete(key) {
|
|
47
|
+
this.ensureLoaded();
|
|
48
|
+
this.map.delete(key);
|
|
49
|
+
this.remove(this.fileOf(key));
|
|
50
|
+
}
|
|
51
|
+
keys() {
|
|
52
|
+
this.ensureLoaded();
|
|
53
|
+
return this.map.keys();
|
|
54
|
+
}
|
|
55
|
+
clear() {
|
|
56
|
+
this.ensureLoaded();
|
|
57
|
+
this.map.clear();
|
|
58
|
+
for (const name of this.list(this.folder)) {
|
|
59
|
+
if (CACHE_FILE.test(name)) this.remove(this.deps.join(this.folder, name));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Moves the store into its folder (`<dir>/<hash>`) and reads that; copies
|
|
64
|
+
* the cache files of 0.7 in when asked and the folder is empty; then clears
|
|
65
|
+
* out folders of this store that went unused (`sweep`). Entries already
|
|
66
|
+
* read from `dir` itself are dropped from memory. A second client with the
|
|
67
|
+
* same identity finds it done; one with another identity is refused, as the
|
|
68
|
+
* store holds one site's entries.
|
|
69
|
+
*/
|
|
70
|
+
[ATTACH](scope) {
|
|
71
|
+
const hash = this.deps.sha256(scope.identity).slice(0, 16);
|
|
72
|
+
if (this.hash !== void 0) {
|
|
73
|
+
return this.hash === hash && this.attached ? { ...this.attached, first: false } : void 0;
|
|
74
|
+
}
|
|
75
|
+
if (this.ownWarning) this.warnTo = scope.warn;
|
|
76
|
+
this.hash = hash;
|
|
77
|
+
this.folder = this.deps.join(this.dir, hash);
|
|
78
|
+
this.map.clear();
|
|
79
|
+
this.loaded = false;
|
|
80
|
+
this.ensureLoaded();
|
|
81
|
+
this.mark();
|
|
82
|
+
const legacy = this.legacyFiles();
|
|
83
|
+
const copied = scope.adoptLegacy && this.map.size === 0 ? this.adopt(legacy) : 0;
|
|
84
|
+
this.sweep();
|
|
85
|
+
this.attached = { store: this, dir: this.dir, folder: this.folder, loaded: this.map.size, legacy: legacy.length, copied, first: true };
|
|
86
|
+
return this.attached;
|
|
87
|
+
}
|
|
88
|
+
// ── Disk ────────────────────────────────────────────────────────────────────
|
|
89
|
+
/** File name per key: a hash, as keys hold `/` and `:` and may be long. */
|
|
90
|
+
fileOf(key, folder = this.folder) {
|
|
91
|
+
return this.deps.join(folder, this.deps.sha256(key) + SUFFIX);
|
|
92
|
+
}
|
|
93
|
+
ensureLoaded() {
|
|
94
|
+
if (this.loaded) return;
|
|
95
|
+
this.loaded = true;
|
|
96
|
+
this.load();
|
|
97
|
+
}
|
|
98
|
+
/** Fills memory from disk, oldest file first so eviction order survives a restart. */
|
|
99
|
+
load() {
|
|
100
|
+
try {
|
|
101
|
+
this.deps.fs.mkdirSync(this.folder, { recursive: true });
|
|
102
|
+
} catch (err) {
|
|
103
|
+
this.fail(err);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
for (const name of this.list(this.folder)) {
|
|
107
|
+
if (TEMP_FILE.test(name)) {
|
|
108
|
+
const file = this.deps.join(this.folder, name);
|
|
109
|
+
if (this.olderThan(file, TEMP_ORPHAN_MS)) this.remove(file);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
const found = this.readEntries(this.folder, (file) => this.remove(file));
|
|
113
|
+
for (const { key, entry } of found) this.map.set(key, entry);
|
|
114
|
+
this.evict();
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* The readable cache files in `folder`, oldest first. Files that are this
|
|
118
|
+
* store's by name but not a cache entry (half written, filed under another
|
|
119
|
+
* key) go to `bad`; anything else in `folder` is not looked at.
|
|
120
|
+
*/
|
|
121
|
+
readEntries(folder, bad) {
|
|
122
|
+
const { fs } = this.deps;
|
|
123
|
+
const found = [];
|
|
124
|
+
for (const name of this.list(folder)) {
|
|
125
|
+
if (!CACHE_FILE.test(name)) continue;
|
|
126
|
+
const file = this.deps.join(folder, name);
|
|
127
|
+
try {
|
|
128
|
+
const stored = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
129
|
+
if (stored?.v !== 1 || typeof stored.key !== "string" || !stored.entry || file !== this.fileOf(stored.key, folder)) {
|
|
130
|
+
throw new Error("not a cache file");
|
|
131
|
+
}
|
|
132
|
+
found.push({ key: stored.key, entry: stored.entry, mtime: fs.statSync(file).mtimeMs });
|
|
133
|
+
} catch {
|
|
134
|
+
bad(file);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return found.sort((a, b) => a.mtime - b.mtime);
|
|
138
|
+
}
|
|
139
|
+
/** The cache files of 0.7 in `dir` itself: read only, never changed or removed. */
|
|
140
|
+
legacyFiles() {
|
|
141
|
+
return this.readEntries(this.dir, () => {
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Copies the cache files of 0.7 into the (empty) folder, the newest
|
|
146
|
+
* `maxEntries` of them, so a site that restarts during an outage right after
|
|
147
|
+
* upgrading still has its content. Copied, not moved: a 0.7 process on the
|
|
148
|
+
* same directory (the old container during a redeploy) keeps its own.
|
|
149
|
+
*/
|
|
150
|
+
adopt(legacy) {
|
|
151
|
+
const take = legacy.slice(-this.maxEntries);
|
|
152
|
+
for (const { key, entry } of take) {
|
|
153
|
+
this.map.set(key, entry);
|
|
154
|
+
this.write(key, entry);
|
|
155
|
+
}
|
|
156
|
+
return take.length;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* At attach, in `dir`: removes the folders of this store that went unused
|
|
160
|
+
* for `STALE_MS`. A folder counts only when its name is a hash, it carries
|
|
161
|
+
* `MARKER`, and it holds nothing but cache files, temp files and the
|
|
162
|
+
* marker: then those go, and the folder. Anything else (a folder of the
|
|
163
|
+
* site's, another site's 0.7 cache files, a folder with one foreign file in
|
|
164
|
+
* it) is never touched, and neither is anything in `dir` itself.
|
|
165
|
+
*
|
|
166
|
+
* Silent on failure: this is tidying, not caching, and a folder another
|
|
167
|
+
* user owns is no reason to say the cache is unusable.
|
|
168
|
+
*/
|
|
169
|
+
sweep() {
|
|
170
|
+
const { fs, join } = this.deps;
|
|
171
|
+
let entries;
|
|
172
|
+
try {
|
|
173
|
+
entries = fs.readdirSync(this.dir, { withFileTypes: true });
|
|
174
|
+
} catch {
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
for (const entry of entries) {
|
|
178
|
+
if (!entry.isDirectory() || !FOLDER.test(entry.name) || entry.name === this.hash) continue;
|
|
179
|
+
const folder = join(this.dir, entry.name);
|
|
180
|
+
const marker = join(folder, MARKER);
|
|
181
|
+
if (!this.olderThan(marker, STALE_MS) || !this.olderThan(folder, STALE_MS)) continue;
|
|
182
|
+
this.quietly(() => {
|
|
183
|
+
const names = fs.readdirSync(folder);
|
|
184
|
+
if (!names.every((name) => name === MARKER || CACHE_FILE.test(name) || TEMP_FILE.test(name))) return;
|
|
185
|
+
for (const name of names) fs.rmSync(join(folder, name), { force: true });
|
|
186
|
+
fs.rmdirSync(folder);
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/** Puts `MARKER` in the folder, or marks it as used if it is there: see `touch`. */
|
|
191
|
+
mark() {
|
|
192
|
+
const marker = this.deps.join(this.folder, MARKER);
|
|
193
|
+
const now = /* @__PURE__ */ new Date();
|
|
194
|
+
this.touchedAt = now.getTime();
|
|
195
|
+
this.quietly(() => {
|
|
196
|
+
try {
|
|
197
|
+
this.deps.fs.utimesSync(marker, now, now);
|
|
198
|
+
} catch {
|
|
199
|
+
this.deps.fs.writeFileSync(marker, MARKER_TEXT);
|
|
200
|
+
}
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Marks the folder as used, at most once per `TOUCH_MS`: a site whose
|
|
205
|
+
* content does not change writes nothing, and its folder must not look
|
|
206
|
+
* abandoned to the sweep of another site sharing `dir`.
|
|
207
|
+
*/
|
|
208
|
+
touch() {
|
|
209
|
+
if (this.hash === void 0 || Date.now() - this.touchedAt < TOUCH_MS) return;
|
|
210
|
+
this.mark();
|
|
211
|
+
}
|
|
212
|
+
evict() {
|
|
213
|
+
while (this.map.size > this.maxEntries) {
|
|
214
|
+
const oldest = this.map.keys().next().value;
|
|
215
|
+
if (oldest === void 0) break;
|
|
216
|
+
this.delete(oldest);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
/** Temp file plus rename, so a reader (or a crash) never sees half a file. */
|
|
220
|
+
write(key, entry) {
|
|
221
|
+
const file = this.fileOf(key);
|
|
222
|
+
const tmp = `${file}.${processId()}.${this.deps.randomHex(6)}.tmp`;
|
|
223
|
+
const stored = JSON.stringify({ v: 1, key, entry });
|
|
224
|
+
try {
|
|
225
|
+
this.writeAt(tmp, file, stored);
|
|
226
|
+
} catch (err) {
|
|
227
|
+
this.remove(tmp);
|
|
228
|
+
this.fail(err);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* One write. A folder that is gone, before the temp file is written or
|
|
233
|
+
* before it is renamed, is made again and the write done once more: the
|
|
234
|
+
* sweep of another site sharing `dir` removes a folder only after 30 days
|
|
235
|
+
* unused, but a process may well sit that long without a read, and a
|
|
236
|
+
* person may clear the directory by hand. Only a failure that outlasts
|
|
237
|
+
* that second try is reported.
|
|
238
|
+
*/
|
|
239
|
+
writeAt(tmp, file, stored) {
|
|
240
|
+
const { fs } = this.deps;
|
|
241
|
+
try {
|
|
242
|
+
fs.writeFileSync(tmp, stored);
|
|
243
|
+
fs.renameSync(tmp, file);
|
|
244
|
+
} catch (err) {
|
|
245
|
+
if (!isMissing(err)) throw err;
|
|
246
|
+
fs.mkdirSync(this.folder, { recursive: true });
|
|
247
|
+
if (this.hash !== void 0) this.mark();
|
|
248
|
+
fs.writeFileSync(tmp, stored);
|
|
249
|
+
fs.renameSync(tmp, file);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Hands a disk problem to `onError`. Never throws and never leaves a rejection
|
|
254
|
+
* behind: this runs inside a cache write, which runs inside a read, and a
|
|
255
|
+
* hook that fails (or an `async` one whose own work fails) must not fail the
|
|
256
|
+
* read or stop the process over a cache that merely fell back to memory.
|
|
257
|
+
*/
|
|
258
|
+
fail(err) {
|
|
259
|
+
try {
|
|
260
|
+
const outcome = this.onError(err);
|
|
261
|
+
if (typeof outcome?.then === "function") {
|
|
262
|
+
outcome.then(void 0, () => {
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
} catch {
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
/** Whether a file or folder was last changed more than `ms` ago. Unknown (missing) counts as "no". */
|
|
269
|
+
olderThan(path, ms) {
|
|
270
|
+
try {
|
|
271
|
+
return Date.now() - this.deps.fs.statSync(path).mtimeMs > ms;
|
|
272
|
+
} catch {
|
|
273
|
+
return false;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
quietly(run) {
|
|
277
|
+
try {
|
|
278
|
+
run();
|
|
279
|
+
} catch {
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
remove(file) {
|
|
283
|
+
try {
|
|
284
|
+
this.deps.fs.rmSync(file, { force: true });
|
|
285
|
+
} catch (err) {
|
|
286
|
+
this.fail(err);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
/** The names in `folder`; none for a folder that is not there (yet, or any more), which is no disk problem. */
|
|
290
|
+
list(folder) {
|
|
291
|
+
try {
|
|
292
|
+
return this.deps.fs.readdirSync(folder);
|
|
293
|
+
} catch (err) {
|
|
294
|
+
if (!isMissing(err)) this.fail(err);
|
|
295
|
+
return [];
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
var FILE_CACHES = /* @__PURE__ */ Symbol.for("@nordhavnhq/beacon/file-caches/2");
|
|
300
|
+
var FIRST_STARTS = /* @__PURE__ */ Symbol.for("@nordhavnhq/beacon/first-starts/1");
|
|
301
|
+
function hasFolders(deps, dir) {
|
|
302
|
+
const { fs, join } = deps;
|
|
303
|
+
try {
|
|
304
|
+
return fs.readdirSync(dir, { withFileTypes: true }).some((entry) => entry.isDirectory() && FOLDER.test(entry.name) && fs.readdirSync(join(dir, entry.name)).includes(MARKER));
|
|
305
|
+
} catch {
|
|
306
|
+
return false;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
function registry(symbol) {
|
|
310
|
+
const scope = globalThis;
|
|
311
|
+
const map = scope[symbol] ?? /* @__PURE__ */ new Map();
|
|
312
|
+
scope[symbol] = map;
|
|
313
|
+
return map;
|
|
314
|
+
}
|
|
315
|
+
function attachShared(options, deps, scope) {
|
|
316
|
+
const dir = deps.resolve(options.dir);
|
|
317
|
+
const firstStarts = registry(FIRST_STARTS);
|
|
318
|
+
if (!firstStarts.has(dir)) firstStarts.set(dir, !hasFolders(deps, dir));
|
|
319
|
+
const caches = registry(FILE_CACHES);
|
|
320
|
+
const id = `${dir}
|
|
321
|
+
${scope.identity}`;
|
|
322
|
+
const maxEntries = options.maxEntries ?? 500;
|
|
323
|
+
let shared = caches.get(id);
|
|
324
|
+
if (!shared) {
|
|
325
|
+
shared = { cache: new FileCache(options, deps), maxEntries, onError: options.onError, told: false };
|
|
326
|
+
caches.set(id, shared);
|
|
327
|
+
}
|
|
328
|
+
const attached = shared.cache[ATTACH]({ ...scope, adoptLegacy: scope.adoptLegacy && firstStarts.get(dir) === true });
|
|
329
|
+
const differs = maxEntries !== shared.maxEntries || options.onError !== void 0 && options.onError !== shared.onError;
|
|
330
|
+
if (attached && differs && !shared.told) {
|
|
331
|
+
shared.told = true;
|
|
332
|
+
scope.warn?.(`[@nordhavnhq/beacon] file cache ${attached.folder} is already open in this process: its first settings apply (maxEntries ${shared.maxEntries}, ${shared.onError ? "the first store's onError" : "no onError"}), not this one's`);
|
|
333
|
+
}
|
|
334
|
+
return attached;
|
|
335
|
+
}
|
|
336
|
+
function isMissing(err) {
|
|
337
|
+
return err?.code === "ENOENT";
|
|
338
|
+
}
|
|
339
|
+
function processId() {
|
|
340
|
+
return globalThis.process?.pid ?? 0;
|
|
341
|
+
}
|
|
342
|
+
function builtinFileDeps(builtin) {
|
|
343
|
+
const fs = builtin("node:fs");
|
|
344
|
+
const crypto = builtin("node:crypto");
|
|
345
|
+
const path = builtin("node:path");
|
|
346
|
+
if (!fs || !crypto || !path) return void 0;
|
|
347
|
+
return fileDeps(fs, crypto, path);
|
|
348
|
+
}
|
|
349
|
+
function fileDeps(fs, crypto, path) {
|
|
350
|
+
return {
|
|
351
|
+
fs,
|
|
352
|
+
join: path.join,
|
|
353
|
+
resolve: path.resolve,
|
|
354
|
+
sha256: (text) => crypto.createHash("sha256").update(text).digest("hex"),
|
|
355
|
+
randomHex: (bytes) => crypto.randomBytes(bytes).toString("hex")
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
export { ATTACH, FileCache, attachShared, builtinFileDeps, fileDeps };
|
|
360
|
+
//# sourceMappingURL=chunk-FLRBCD6H.js.map
|
|
361
|
+
//# sourceMappingURL=chunk-FLRBCD6H.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/file-cache.ts"],"names":[],"mappings":";AAgHO,IAAM,MAAA,mBAAS,MAAA,CAAO,GAAA,CAAI,wCAAwC;AAUzE,IAAM,MAAA,GAAS,OAAA;AAQf,IAAM,UAAA,GAAa,sBAAA;AACnB,IAAM,SAAA,GAAY,8CAAA;AAGlB,IAAM,MAAA,GAAS,gBAAA;AAOR,IAAM,MAAA,GAAS,eAAA;AACtB,IAAM,WAAA,GAAc,6FAAA;AAQpB,IAAM,cAAA,GAAiB,GAAA;AAQhB,IAAM,QAAA,GAAW,KAAK,EAAA,GAAK,IAAA;AAClC,IAAM,W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file":"chunk-FLRBCD6H.js","sourcesContent":["/**\n * The file cache behind `FileCacheStore` (`@nordhavnhq/beacon/file-store`) and\n * the `cache.dir` option: entries on disk as well as in memory, so a restarted\n * process still has the last good content, also when the studio is down at\n * that very moment.\n *\n * Node's `fs`, `crypto` and `path` come in as `FileDeps` and are not imported\n * here: the file-store entry hands over its static imports, the main entry\n * (for `cache.dir`) takes them from `process.getBuiltinModule`, so the main\n * entry stays loadable in a browser.\n *\n * Kept per site. A client hands its identity over (`ATTACH`, `attachShared`);\n * the entries then live in `<dir>/<hash>/`, the hash a short sha256 of the\n * server and the credentials the client sends, and two sites (or two keys of\n * a developer) sharing `dir` never see each other's content. One cache per\n * folder in a process (`attachShared`), whoever asks for it. A store no client\n * attached to keeps its entries in `dir` itself, as it did up to 0.7.\n *\n * What it removes on its own is narrow on purpose, as `dir` may be mistyped\n * (a project root, `/tmp`, a parent of other sites' folders): only its own\n * cache files, and only folders it made itself, which carry `MARKER`.\n */\nimport type { CacheEntry, CacheStore } from './cache'\n\nexport interface FileCacheOptions {\n /** Directory for the cache files. Created when missing. */\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. Without one, the store\n * warns once, through the client's `logger` once a client attached it.\n */\n onError?: (err: unknown) => void\n}\n\n/*\n * The parts of Node's `fs`, `crypto` and `path` the store uses, declared\n * locally: beacon's main entry builds one too (for `cache.dir`) and must\n * typecheck without Node's types.\n */\ninterface DirEntry {\n name: string\n isDirectory(): boolean\n}\nexport interface FileSystem {\n mkdirSync(path: string, options: { recursive: true }): unknown\n readdirSync(path: string): string[]\n readdirSync(path: string, options: { withFileTypes: true }): DirEntry[]\n readFileSync(path: string, encoding: 'utf8'): string\n writeFileSync(path: string, data: string): void\n renameSync(from: string, to: string): void\n rmSync(path: string, options: { force: true }): void\n rmdirSync(path: string): void\n statSync(path: string): { mtimeMs: number }\n utimesSync(path: string, atime: Date, mtime: Date): void\n}\nexport interface FileDeps {\n fs: FileSystem\n join(...parts: string[]): string\n resolve(path: string): string\n sha256(text: string): string\n randomHex(bytes: number): string\n}\n\n/** What a client tells the store it attaches to. */\nexport interface StoreScope {\n /** Server and credentials (`identityOf`), hashed into the folder's name. */\n identity: string\n /**\n * Whether the cache files of 0.7 in `dir` itself are copied into a folder\n * that has no entries yet: for a `FileCacheStore` a site passes in, which\n * up to 0.7 had one `dir` per site, on the first start after 0.7 (decided\n * in `attachShared`). Not for `cache.dir`, new in 0.8.\n */\n adoptLegacy: boolean\n /** Where disk problems go when the store has no `onError` of its own; `undefined` keeps them quiet. */\n warn: ((...args: unknown[]) => void) | undefined\n}\n\n/** What the store reports back to the client that attached it. */\nexport interface AttachedStore {\n /** What the client caches in: the cache of its folder. */\n store: CacheStore\n /** The store's `dir`. */\n dir: string\n /** Where its entries live: `<dir>/<hash>`. */\n folder: string\n /** Entries in the folder on attaching, copied ones included. */\n loaded: number\n /** Cache files of 0.7 in `dir` itself, left where they are. */\n legacy: number\n /** How many of those were copied into the folder (`adoptLegacy`). */\n copied: number\n /** `false` for a second client with the same identity: it was already loaded. */\n first: boolean\n}\n\n/**\n * The method a client calls to hand the store its identity. A symbol from\n * the global registry: the main entry and the file-store entry are separate\n * bundles (and a site may load two copies), and must still find each other.\n * Returns `undefined` when the store already serves another identity.\n *\n * Keep this symbol (and the `globalThis` ones below) stable across releases.\n * A site can load two copies of beacon (a dependency pinning another\n * version), and a client from one hands its identity to a store from the\n * other through this name. If it is ever bumped, clients must keep trying\n * the older symbols too: else a store from an older copy is no longer found,\n * and a client of the newer one uses it as a plain store, in its unsplit\n * `dir`, as 0.7 did.\n */\nexport const ATTACH = Symbol.for('@nordhavnhq/beacon/file-cache-attach/3')\nexport type Attach = (scope: StoreScope) => AttachedStore | undefined\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/** The name of a folder this store makes: 16 hex characters of a sha256. */\nconst FOLDER = /^[0-9a-f]{16}$/\n\n/**\n * Put in every folder this store makes, and kept fresh while it is used: the\n * sweep of another client looks only at folders that carry it, so a folder of\n * anything else that happens to have a fitting name is never touched.\n */\nexport const MARKER = '.beacon-cache'\nconst MARKER_TEXT = 'A cache of @nordhavnhq/beacon. Removed by beacon once unused for 30 days; safe to delete.\\n'\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\n/**\n * How long a folder of this store may go unused before a starting store\n * removes it: the cache of a key that was replaced. Its own folder is marked\n * as used at start and then at least daily (`TOUCH_MS`), whether or not\n * anything changes.\n */\nexport const STALE_MS = 30 * 24 * 3_600_000\nconst TOUCH_MS = 24 * 3_600_000\n\nexport class FileCache implements CacheStore {\n private readonly dir: string\n private readonly maxEntries: number\n private readonly onError: (err: unknown) => void\n private readonly deps: FileDeps\n /** Same order contract as `MemoryCacheStore`: oldest written first. */\n private readonly map = new Map<string, CacheEntry>()\n /** Where the entries live: `dir` until a client attaches, then `<dir>/<hash>`. */\n private folder: string\n /** The folder's name once a client attached. */\n private hash: string | undefined\n /** What the first attach reported, for the clients after it. */\n private attached: AttachedStore | undefined\n /** Read from disk on first use, not at construction: a client attaching first decides where from. */\n private loaded = false\n private touchedAt = 0\n /** Whether disk problems go to the default warning (and so follow an attaching client's `logger`). */\n private readonly ownWarning: boolean\n /** Where the one warning goes without an `onError`: the console, or the attaching client's `logger`. */\n private warnTo: ((...args: unknown[]) => void) | undefined = (...args) => console.warn(...args)\n\n constructor(options: FileCacheOptions, deps: FileDeps) {\n if (!options?.dir) throw new Error('FileCacheStore: `dir` is required')\n this.dir = options.dir\n this.folder = options.dir\n this.maxEntries = options.maxEntries ?? 500\n this.deps = deps\n\n let warned = false\n this.onError = options.onError ?? ((err) => {\n if (warned) return\n warned = true\n this.warnTo?.(`[@nordhavnhq/beacon] file cache at ${this.folder} unusable, continuing in memory:`, err instanceof Error ? err.message : err)\n })\n this.ownWarning = options.onError === undefined\n }\n\n get(key: string): CacheEntry | undefined {\n this.ensureLoaded()\n this.touch()\n return this.map.get(key)\n }\n\n set(key: string, entry: CacheEntry): void {\n this.ensureLoaded()\n this.map.delete(key)\n this.map.set(key, entry)\n this.write(key, entry)\n this.evict()\n }\n\n delete(key: string): void {\n this.ensureLoaded()\n this.map.delete(key)\n this.remove(this.fileOf(key))\n }\n\n keys(): Iterable<string> {\n this.ensureLoaded()\n return this.map.keys()\n }\n\n clear(): void {\n this.ensureLoaded()\n this.map.clear()\n for (const name of this.list(this.folder)) {\n if (CACHE_FILE.test(name)) this.remove(this.deps.join(this.folder, name))\n }\n }\n\n /**\n * Moves the store into its folder (`<dir>/<hash>`) and reads that; copies\n * the cache files of 0.7 in when asked and the folder is empty; then clears\n * out folders of this store that went unused (`sweep`). Entries already\n * read from `dir` itself are dropped from memory. A second client with the\n * same identity finds it done; one with another identity is refused, as the\n * store holds one site's entries.\n */\n [ATTACH](scope: StoreScope): AttachedStore | undefined {\n const hash = this.deps.sha256(scope.identity).slice(0, 16)\n if (this.hash !== undefined) {\n return this.hash === hash && this.attached ? { ...this.attached, first: false } : undefined\n }\n if (this.ownWarning) this.warnTo = scope.warn\n this.hash = hash\n this.folder = this.deps.join(this.dir, hash)\n this.map.clear()\n this.loaded = false\n this.ensureLoaded()\n this.mark()\n const legacy = this.legacyFiles()\n const copied = scope.adoptLegacy && this.map.size === 0 ? this.adopt(legacy) : 0\n this.sweep()\n this.attached = { store: this, dir: this.dir, folder: this.folder, loaded: this.map.size, legacy: legacy.length, copied, first: true }\n return this.attached\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, folder = this.folder): string {\n return this.deps.join(folder, this.deps.sha256(key) + SUFFIX)\n }\n\n private ensureLoaded(): void {\n if (this.loaded) return\n this.loaded = true\n this.load()\n }\n\n /** Fills memory from disk, oldest file first so eviction order survives a restart. */\n private load(): void {\n try {\n this.deps.fs.mkdirSync(this.folder, { recursive: true })\n }\n catch (err) {\n this.fail(err)\n return\n }\n for (const name of this.list(this.folder)) {\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 const file = this.deps.join(this.folder, name)\n if (this.olderThan(file, TEMP_ORPHAN_MS)) this.remove(file)\n }\n }\n // Ours by name but unreadable, or filed under another key: it can only\n // ever be a miss, so it goes.\n const found = this.readEntries(this.folder, file => this.remove(file))\n for (const { key, entry } of found) this.map.set(key, entry)\n this.evict()\n }\n\n /**\n * The readable cache files in `folder`, oldest first. Files that are this\n * store's by name but not a cache entry (half written, filed under another\n * key) go to `bad`; anything else in `folder` is not looked at.\n */\n private readEntries(folder: string, bad: (file: string) => void): { key: string, entry: CacheEntry, mtime: number }[] {\n const { fs } = this.deps\n const found: { key: string, entry: CacheEntry, mtime: number }[] = []\n for (const name of this.list(folder)) {\n if (!CACHE_FILE.test(name)) continue\n const file = this.deps.join(folder, name)\n try {\n const stored = JSON.parse(fs.readFileSync(file, 'utf8')) as StoredFile\n if (stored?.v !== 1 || typeof stored.key !== 'string' || !stored.entry || file !== this.fileOf(stored.key, folder)) {\n throw new Error('not a cache file')\n }\n found.push({ key: stored.key, entry: stored.entry, mtime: fs.statSync(file).mtimeMs })\n }\n catch {\n bad(file)\n }\n }\n return found.sort((a, b) => a.mtime - b.mtime)\n }\n\n /** The cache files of 0.7 in `dir` itself: read only, never changed or removed. */\n private legacyFiles(): { key: string, entry: CacheEntry, mtime: number }[] {\n return this.readEntries(this.dir, () => {})\n }\n\n /**\n * Copies the cache files of 0.7 into the (empty) folder, the newest\n * `maxEntries` of them, so a site that restarts during an outage right after\n * upgrading still has its content. Copied, not moved: a 0.7 process on the\n * same directory (the old container during a redeploy) keeps its own.\n */\n private adopt(legacy: { key: string, entry: CacheEntry }[]): number {\n const take = legacy.slice(-this.maxEntries)\n for (const { key, entry } of take) {\n this.map.set(key, entry)\n this.write(key, entry)\n }\n return take.length\n }\n\n /**\n * At attach, in `dir`: removes the folders of this store that went unused\n * for `STALE_MS`. A folder counts only when its name is a hash, it carries\n * `MARKER`, and it holds nothing but cache files, temp files and the\n * marker: then those go, and the folder. Anything else (a folder of the\n * site's, another site's 0.7 cache files, a folder with one foreign file in\n * it) is never touched, and neither is anything in `dir` itself.\n *\n * Silent on failure: this is tidying, not caching, and a folder another\n * user owns is no reason to say the cache is unusable.\n */\n private sweep(): void {\n const { fs, join } = this.deps\n let entries: DirEntry[]\n try {\n entries = fs.readdirSync(this.dir, { withFileTypes: true })\n }\n catch {\n return\n }\n for (const entry of entries) {\n // `isDirectory()` of a symbolic link is false: one is never followed.\n if (!entry.isDirectory() || !FOLDER.test(entry.name) || entry.name === this.hash) continue\n const folder = join(this.dir, entry.name)\n const marker = join(folder, MARKER)\n if (!this.olderThan(marker, STALE_MS) || !this.olderThan(folder, STALE_MS)) continue\n this.quietly(() => {\n const names = fs.readdirSync(folder)\n if (!names.every(name => name === MARKER || CACHE_FILE.test(name) || TEMP_FILE.test(name))) return\n for (const name of names) fs.rmSync(join(folder, name), { force: true })\n fs.rmdirSync(folder)\n })\n }\n }\n\n /** Puts `MARKER` in the folder, or marks it as used if it is there: see `touch`. */\n private mark(): void {\n const marker = this.deps.join(this.folder, MARKER)\n const now = new Date()\n this.touchedAt = now.getTime()\n this.quietly(() => {\n try {\n this.deps.fs.utimesSync(marker, now, now)\n }\n catch {\n this.deps.fs.writeFileSync(marker, MARKER_TEXT)\n }\n })\n }\n\n /**\n * Marks the folder as used, at most once per `TOUCH_MS`: a site whose\n * content does not change writes nothing, and its folder must not look\n * abandoned to the sweep of another site sharing `dir`.\n */\n private touch(): void {\n if (this.hash === undefined || Date.now() - this.touchedAt < TOUCH_MS) return\n this.mark()\n }\n\n private evict(): void {\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}.${processId()}.${this.deps.randomHex(6)}.tmp`\n const stored = JSON.stringify({ v: 1, key, entry } satisfies StoredFile)\n try {\n this.writeAt(tmp, file, stored)\n }\n catch (err) {\n this.remove(tmp)\n this.fail(err)\n }\n }\n\n /**\n * One write. A folder that is gone, before the temp file is written or\n * before it is renamed, is made again and the write done once more: the\n * sweep of another site sharing `dir` removes a folder only after 30 days\n * unused, but a process may well sit that long without a read, and a\n * person may clear the directory by hand. Only a failure that outlasts\n * that second try is reported.\n */\n private writeAt(tmp: string, file: string, stored: string): void {\n const { fs } = this.deps\n try {\n fs.writeFileSync(tmp, stored)\n fs.renameSync(tmp, file)\n }\n catch (err) {\n if (!isMissing(err)) throw err\n fs.mkdirSync(this.folder, { recursive: true })\n if (this.hash !== undefined) this.mark()\n fs.writeFileSync(tmp, stored)\n fs.renameSync(tmp, file)\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 file or folder was last changed more than `ms` ago. Unknown (missing) counts as \"no\". */\n private olderThan(path: string, ms: number): boolean {\n try {\n return Date.now() - this.deps.fs.statSync(path).mtimeMs > ms\n }\n catch {\n return false\n }\n }\n\n private quietly(run: () => void): void {\n try {\n run()\n }\n catch {\n /* see `sweep` */\n }\n }\n\n private remove(file: string): void {\n try {\n this.deps.fs.rmSync(file, { force: true })\n }\n catch (err) {\n this.fail(err)\n }\n }\n\n /** The names in `folder`; none for a folder that is not there (yet, or any more), which is no disk problem. */\n private list(folder: string): string[] {\n try {\n return this.deps.fs.readdirSync(folder)\n }\n catch (err) {\n if (!isMissing(err)) this.fail(err)\n return []\n }\n }\n}\n\n/**\n * The file caches attached by clients, one per folder (resolved `dir` and\n * identity) in a process, on `globalThis`: whoever asks for a folder gets\n * the same cache, `cache.dir` and a `FileCacheStore` alike, also from\n * another build of beacon (its ESM and CommonJS entries, a dev server's\n * reload). A site that makes a client (or a store) per request does not read\n * the directory again each time, and no two caches on one folder evict each\n * other's files. The first to ask decides `maxEntries` and `onError`; a later\n * one asking with others is told so, once.\n *\n * Keep the symbol stable (see `ATTACH`).\n */\nconst FILE_CACHES = Symbol.for('@nordhavnhq/beacon/file-caches/2')\n\ninterface SharedCache {\n cache: FileCache\n maxEntries: number\n onError: ((err: unknown) => void) | undefined\n /** Whether a later asker was already told that the first one's settings apply. */\n told: boolean\n}\n\n/**\n * Per resolved `dir` in a process, whether this is the first start after\n * 0.7: no folder of beacon's in it yet (a hash name with `MARKER`) when the\n * first client of the process attached. Decided once, before that client\n * makes its own folder, so a reader and a writer of one site, whichever\n * comes first, both copy the 0.7 entries into their folders; a new key in a\n * later process finds the folders and copies nothing (the 0.7 entries are\n * months old by then). Keep the symbol stable (see `ATTACH`).\n */\nconst FIRST_STARTS = Symbol.for('@nordhavnhq/beacon/first-starts/1')\n\n/** Whether `dir` holds a folder of beacon's: a hash name with `MARKER` in it. */\nfunction hasFolders(deps: FileDeps, dir: string): boolean {\n const { fs, join } = deps\n try {\n return fs.readdirSync(dir, { withFileTypes: true }).some(entry =>\n entry.isDirectory() && FOLDER.test(entry.name) && fs.readdirSync(join(dir, entry.name)).includes(MARKER))\n }\n catch {\n return false\n }\n}\n\nfunction registry<T>(symbol: symbol): Map<string, T> {\n const scope = globalThis as unknown as Record<symbol, Map<string, T> | undefined>\n const map = scope[symbol] ?? new Map<string, T>()\n scope[symbol] = map\n return map\n}\n\n/** Attaches `scope` to the cache of its folder in `options.dir`, made with `options` and `deps` if it is the first. */\nexport function attachShared(options: FileCacheOptions, deps: FileDeps, scope: StoreScope): AttachedStore | undefined {\n const dir = deps.resolve(options.dir)\n const firstStarts = registry<boolean>(FIRST_STARTS)\n if (!firstStarts.has(dir)) firstStarts.set(dir, !hasFolders(deps, dir))\n const caches = registry<SharedCache>(FILE_CACHES)\n const id = `${dir}\\n${scope.identity}`\n const maxEntries = options.maxEntries ?? 500\n let shared = caches.get(id)\n if (!shared) {\n shared = { cache: new FileCache(options, deps), maxEntries, onError: options.onError, told: false }\n caches.set(id, shared)\n }\n const attached = shared.cache[ATTACH]({ ...scope, adoptLegacy: scope.adoptLegacy && firstStarts.get(dir) === true })\n const differs = maxEntries !== shared.maxEntries || (options.onError !== undefined && options.onError !== shared.onError)\n if (attached && differs && !shared.told) {\n shared.told = true\n scope.warn?.(`[@nordhavnhq/beacon] file cache ${attached.folder} is already open in this process: its first settings apply (maxEntries ${shared.maxEntries}, ${shared.onError ? 'the first store\\'s onError' : 'no onError'}), not this one's`)\n }\n return attached\n}\n\nfunction isMissing(err: unknown): boolean {\n return (err as { code?: unknown } | null)?.code === 'ENOENT'\n}\n\n/** The pid, for temp file names; `0` where there is no `process`. */\nfunction processId(): number {\n return (globalThis as { process?: { pid?: number } }).process?.pid ?? 0\n}\n\n/**\n * `FileDeps` from the modules Node hands out synchronously\n * (`process.getBuiltinModule`, Node 22.3 and later), or `undefined` where\n * there are none: a browser, an edge runtime, an older Node.\n */\nexport function builtinFileDeps(builtin: (id: string) => unknown): FileDeps | undefined {\n const fs = builtin('node:fs') as FileSystem | undefined\n const crypto = builtin('node:crypto') as NodeCrypto | undefined\n const path = builtin('node:path') as NodePath | undefined\n if (!fs || !crypto || !path) return undefined\n return fileDeps(fs, crypto, path)\n}\n\ninterface NodeCrypto {\n createHash(algorithm: 'sha256'): { update(text: string): { digest(encoding: 'hex'): string } }\n randomBytes(size: number): { toString(encoding: 'hex'): string }\n}\ninterface NodePath {\n join(...parts: string[]): string\n resolve(path: string): string\n}\n\n/** `FileDeps` from Node's `fs`, `crypto` and `path`. */\nexport function fileDeps(fs: FileSystem, crypto: NodeCrypto, path: NodePath): FileDeps {\n return {\n fs,\n join: path.join,\n resolve: path.resolve,\n sha256: text => crypto.createHash('sha256').update(text).digest('hex'),\n randomHex: bytes => crypto.randomBytes(bytes).toString('hex'),\n }\n}\n"]}
|