@nkduy/mc-asset-loader 0.0.0-stage → 1.6.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/index.d.ts ADDED
@@ -0,0 +1,344 @@
1
+ export type VersionTypeName = "release" | "snapshot" | "old_beta" | "old_alpha"
2
+
3
+ /** A raw row of Mojang's version manifest. */
4
+ export interface ManifestRow {
5
+ id: string
6
+ type: VersionTypeName | string
7
+ url: string
8
+ time?: string
9
+ releaseTime: string
10
+ sha1?: string
11
+ complianceLevel?: number
12
+ [key: string]: unknown
13
+ }
14
+
15
+ export interface GitHubRelease {
16
+ tag_name: string
17
+ prerelease?: boolean
18
+ published_at?: string
19
+ assets?: { name: string, size: number, browser_download_url: string }[]
20
+ [key: string]: unknown
21
+ }
22
+
23
+ /** The listing a type is built from: Mojang's manifest for "java" and "assets", the releases array for "bedrock". */
24
+ export type SourceManifest = VersionManifest | GitHubRelease[]
25
+
26
+ export interface VersionManifest {
27
+ latest?: { release?: string, snapshot?: string }
28
+ versions: ManifestRow[]
29
+ }
30
+
31
+ export type VersionFilter = string | ((all: ManifestVersion[]) => ManifestVersion[])
32
+ export type VersionFilterArg = VersionFilter | VersionFilter[]
33
+
34
+ export interface VersionTypeKeywords {
35
+ RELEASE: "release"
36
+ SNAPSHOT: "snapshot"
37
+ BETA: "old_beta"
38
+ ALPHA: "old_alpha"
39
+ /** One entry per advertised update: the newest patch of each line, curated drops, and a newer snapshot. */
40
+ MAIN: (all: ManifestVersion[]) => ManifestVersion[]
41
+ /** Versions with the modern assets/ layout: 13w24a and later. */
42
+ MODERN: (all: ManifestVersion[]) => ManifestVersion[]
43
+ /** User keywords are plain assignments. */
44
+ [keyword: string]: VersionFilter
45
+ }
46
+
47
+ export const VersionType: VersionTypeKeywords
48
+
49
+ /** The 13w24a instant: before it jars have no assets/ folder. */
50
+ export const LEGACY_ASSETS_BEFORE: number
51
+
52
+ /** An entry read from a zip: plain data plus a memoised read(). */
53
+ export interface ZipEntry {
54
+ path: string
55
+ size: number
56
+ /** CRC-32 of the uncompressed bytes, from the zip's central directory. */
57
+ crc: number
58
+ read(): Promise<Uint8Array>
59
+ /** The bytes as stored, skipping decompression. */
60
+ raw(): Promise<RawBytes>
61
+ }
62
+
63
+ /** Parses zip bytes into entries. Nothing is decompressed until an entry is read. */
64
+ export function readZip(bytes: Uint8Array | ArrayBuffer): ZipEntry[]
65
+
66
+ /**
67
+ * Builds a zip from a Map or plain object of path to bytes, or an array of entries with read().
68
+ * An entry that also has raw(), crc and size is copied as stored, without decompressing or recompressing it.
69
+ */
70
+ export function writeZip(
71
+ files: Map<string, Uint8Array> | Record<string, Uint8Array> | Array<{
72
+ path: string
73
+ read(): Uint8Array | Promise<Uint8Array>
74
+ raw?(): Promise<RawBytes>
75
+ crc?: number
76
+ size?: number
77
+ }>,
78
+ options?: {
79
+ /** false stores everything uncompressed, faster for already-compressed files. Copied entries keep their stored form either way. Default true. */
80
+ compress?: boolean
81
+ /** How many files pack at once. Default 32. */
82
+ concurrency?: number
83
+ onProgress?: (done: number, total: number) => void
84
+ }
85
+ ): Promise<Uint8Array>
86
+
87
+ /** The latest release, the newest snapshot, or whichever of the two is newer. */
88
+ export type VersionKeyword = "release" | "snapshot" | "newest"
89
+
90
+ /** A version to operate on: an id, a keyword, or an entry from the manifest. */
91
+ export type VersionRef = string | VersionKeyword | ManifestVersion
92
+
93
+ export interface VersionOptions {
94
+ version?: VersionRef
95
+ }
96
+
97
+ export interface ObjectsOptions extends VersionOptions {
98
+ /** Include asset objects (the separate host) in listings and reads. */
99
+ objects?: boolean
100
+ }
101
+
102
+ export interface ReadOptions extends ObjectsOptions {
103
+ /** On paths present in both the jar and the objects, take the jar copy. */
104
+ prefer?: "jar" | "object"
105
+ }
106
+
107
+ /** The query and every option apart from `version` and `objects` are mc-path-search-sort's. */
108
+ export interface SearchOptions extends ObjectsOptions {
109
+ /** Only paths starting with this prefix. */
110
+ root?: string
111
+ /** Only paths passing through these folders, wherever they sit. */
112
+ path?: string
113
+ /** One or several extensions, leading dot optional. */
114
+ extension?: string | string[]
115
+ /** Your own predicate over the path, only called for what already matched. */
116
+ filter?: (path: string) => boolean
117
+ /** Cap on results, applied after sorting. */
118
+ limit?: number
119
+ /** Also match folder names, on by default; files inside a matching folder rank after name matches. */
120
+ folders?: boolean
121
+ caseSensitive?: boolean
122
+ /** What a typed space becomes. Default "_". */
123
+ spaces?: string
124
+ }
125
+
126
+ /** A file's bytes as stored: plain when compression is null, deflated when "deflate-raw". */
127
+ export interface RawBytes {
128
+ compression: "deflate-raw" | null
129
+ bytes: Uint8Array
130
+ }
131
+
132
+ export interface FileEntry {
133
+ path: string
134
+ /** Which copy a plain read takes. Java only: bedrock and assets have a single source, so it is absent there. */
135
+ source?: "jar" | "object"
136
+ size: number
137
+ /** Present when an asset object backs the entry. */
138
+ hash?: string
139
+ /** CRC-32 of the uncompressed bytes, present on jar-backed entries. */
140
+ crc?: number
141
+ /** The bytes, memoised: repeat reads return the identical buffer. */
142
+ read(options?: { prefer?: "jar" | "object" }): Promise<Uint8Array>
143
+ /** The bytes as stored, skipping decompression. */
144
+ raw(options?: { prefer?: "jar" | "object" }): Promise<RawBytes>
145
+ }
146
+
147
+ export interface FolderEntry {
148
+ /** Full path, ready to feed back into list(). */
149
+ path: string
150
+ /** Everything beneath: jar, object, or both. Java only, absent on bedrock and assets. */
151
+ source?: "jar" | "object" | "both"
152
+ /** The objects setting the folder was listed with, used by its methods unless overridden. */
153
+ objects: boolean
154
+ list(folder?: string | FolderEntry, options?: { objects?: boolean, folders?: false }): Promise<FileEntry[]>
155
+ list(folder: string | FolderEntry, options: { objects?: boolean, folders: true }): Promise<FolderListing>
156
+ list(options: { objects?: boolean, folders: true }): Promise<FolderListing>
157
+ list(options: { objects?: boolean, folders?: false }): Promise<FileEntry[]>
158
+ search(query: string | RegExp, options?: Omit<SearchOptions, "version" | "root">): Promise<FileEntry[]>
159
+ file(relativeOrFullPath: string): Promise<FileEntry | null>
160
+ read(relativeOrFullPathOrEntry: string | FileEntry, options?: { prefer?: "jar" | "object" }): Promise<Uint8Array | null>
161
+ }
162
+
163
+ export interface FolderListing {
164
+ files: FileEntry[]
165
+ folders: FolderEntry[]
166
+ }
167
+
168
+ export interface GetterOptions extends VersionOptions {
169
+ /** The default namespace when the id carries no prefix. Default "minecraft". Bedrock has no namespaces, so anything but "minecraft" is a miss there. */
170
+ namespace?: string
171
+ }
172
+
173
+ export interface TextureOptions extends GetterOptions {
174
+ /** Return `{ data, meta }` with the parsed .mcmeta (or null) alongside the png. */
175
+ meta?: boolean
176
+ prefer?: "jar" | "object"
177
+ }
178
+
179
+ export interface TextureWithMeta {
180
+ data: Uint8Array
181
+ meta: Record<string, unknown> | null
182
+ }
183
+
184
+ export type BulkFilter = ((path: string) => boolean) | Array<string | FileEntry>
185
+
186
+ export interface LoadObjectsOptions extends VersionOptions {
187
+ filter?: BulkFilter
188
+ /** Default 32. */
189
+ concurrency?: number
190
+ onProgress?: (done: number, total: number) => void
191
+ /** `false` skips the cache entirely: retrieval without warming. */
192
+ cache?: boolean
193
+ }
194
+
195
+ export interface ExportOptions extends ObjectsOptions {
196
+ filter?: BulkFilter
197
+ /** Node only: write a folder tree here instead of returning zip bytes. */
198
+ dir?: string
199
+ concurrency?: number
200
+ onProgress?: (done: number, total: number) => void
201
+ }
202
+
203
+ /** The raw per-version document (downloads, assetIndex, libraries, ...). */
204
+ export interface VersionDetails {
205
+ id: string
206
+ assets?: string
207
+ assetIndex?: { id: string, sha1: string, size: number, totalSize?: number, url: string }
208
+ downloads: { client: { sha1: string, size: number, url: string }, [key: string]: { sha1: string, size: number, url: string } }
209
+ [key: string]: unknown
210
+ }
211
+
212
+ /** A manifest row enriched with `legacyLayout` and every version-scoped call bound to it. */
213
+ export interface ManifestVersion extends ManifestRow {
214
+ /** True before 13w24a, when textures sit at the jar root and identifier getters cannot resolve. */
215
+ legacyLayout: boolean
216
+ details(): Promise<VersionDetails>
217
+ list(folder?: string | FolderEntry, options?: Omit<ObjectsOptions, "version"> & { folders?: false }): Promise<FileEntry[]>
218
+ list(folder: string | FolderEntry, options: Omit<ObjectsOptions, "version"> & { folders: true }): Promise<FolderListing>
219
+ list(options: Omit<ObjectsOptions, "version"> & { folders: true }): Promise<FolderListing>
220
+ list(options: Omit<ObjectsOptions, "version"> & { folders?: false }): Promise<FileEntry[]>
221
+ search(query: string | RegExp, options?: Omit<SearchOptions, "version">): Promise<FileEntry[]>
222
+ file(path: string, options?: Omit<ObjectsOptions, "version">): Promise<FileEntry | null>
223
+ read(pathOrEntry: string | FileEntry, options?: Omit<ReadOptions, "version">): Promise<Uint8Array | null>
224
+ getTexture(id: string, options?: Omit<TextureOptions, "version"> & { meta?: false }): Promise<Uint8Array | null>
225
+ getTexture(id: string, options: Omit<TextureOptions, "version"> & { meta: true }): Promise<TextureWithMeta | null>
226
+ getModel(id: string, options?: Omit<GetterOptions, "version">): Promise<any | null>
227
+ getBlockstate(id: string, options?: Omit<GetterOptions, "version">): Promise<any | null>
228
+ getItemDefinition(id: string, options?: Omit<GetterOptions, "version">): Promise<any | null>
229
+ getSound(id: string, options?: Omit<GetterOptions, "version">): Promise<Uint8Array | null>
230
+ getStructure(id: string, options?: Omit<GetterOptions, "version">): Promise<Uint8Array | null>
231
+ getLang(code: string, options?: Omit<GetterOptions, "version">): Promise<Record<string, string> | null>
232
+ loadJar(options?: { onProgress?: (done: number, total: number | null) => void }): Promise<void>
233
+ loadObjects(options?: Omit<LoadObjectsOptions, "version">): Promise<Map<string, Uint8Array>>
234
+ export(options?: Omit<ExportOptions, "version"> & { dir?: undefined }): Promise<Uint8Array>
235
+ export(options: Omit<ExportOptions, "version"> & { dir: string }): Promise<number>
236
+ }
237
+
238
+ export interface Latest {
239
+ release: ManifestVersion | null
240
+ /** The newest genuinely snapshot-typed entry, never the manifest's own `latest` field. */
241
+ snapshot: ManifestVersion | null
242
+ /** The head of the list. */
243
+ newest: ManifestVersion | null
244
+ }
245
+
246
+ export interface ManifestAPI {
247
+ versions(filter?: VersionFilterArg): Promise<ManifestVersion[]>
248
+ version(id: string | VersionKeyword): Promise<ManifestVersion | null>
249
+ latest(): Promise<Latest>
250
+ details(version: VersionRef): Promise<VersionDetails>
251
+ /** Supply a manifest to own, or call with nothing to refetch now and hand ownership back. */
252
+ update(manifest?: SourceManifest): Promise<void>
253
+ }
254
+
255
+ /** Caller-supplied storage. Keys are `meta/...` or `blobs/...`; values are always bytes. */
256
+ export interface CacheAPI {
257
+ read?(key: string): Uint8Array | ArrayBuffer | null | undefined | Promise<Uint8Array | ArrayBuffer | null | undefined>
258
+ write?(key: string, bytes: Uint8Array): void | Promise<void>
259
+ delete?(key: string): void | Promise<void>
260
+ /** Every stored file with its size, powering cacheStats() and listCache(). */
261
+ list?(): Array<{ key: string, size: number }> | Promise<Array<{ key: string, size: number }>>
262
+ clear?(): void | Promise<void>
263
+ }
264
+
265
+ export interface MinecraftAssetsOptions {
266
+ /** What to serve: "java" (default) from Mojang's version servers, "assets" for the Java asset indexes on their own (no jar), or "bedrock" from the bedrock-samples releases. */
267
+ type?: "java" | "assets" | "bedrock"
268
+ /** Where the built-in cache lives (Node). Default: an OS temp location. */
269
+ cacheDir?: string
270
+ /** Byte cap on the built-in cache, LRU. Default 1 GB; `Infinity` or `null` disables eviction. */
271
+ cacheSize?: number | null
272
+ /** Namespaces the built-in cache, so separate instances can keep separate caches. */
273
+ cacheKey?: string
274
+ /** Replaces the built-in cache entirely. */
275
+ cacheAPI?: CacheAPI
276
+ /** A url prefix, or a function returning the url to request (falsy means direct). */
277
+ proxy?: string | ((url: string) => string | false | null | undefined)
278
+ /** The default version. Default: "release". */
279
+ version?: VersionRef | null
280
+ /** A caller-supplied manifest. "bedrock" takes GitHub's releases array; "assets" derives its index list from it. */
281
+ manifest?: SourceManifest
282
+ /** Trust window in ms for a library-fetched manifest; `Infinity`/`null` keeps one copy per session. */
283
+ manifestExpiry?: number | null
284
+ /** Called with a 0 to 1 ratio while the manifest is built. Only "assets", which resolves every version's index. */
285
+ onManifestProgress?: (progress: number) => void
286
+ /** Serves an expired manifest from the cache and refetches it in the background, then calls this if the new one differs. Browser only; without it an expired manifest is awaited. */
287
+ onManifestUpdate?: (manifest: ManifestAPI) => void
288
+ /** Instance-wide default for the objects flag. Default false. */
289
+ objects?: boolean
290
+ /**
291
+ * Probe the local .minecraft installation for jars, asset indexes, and asset objects before
292
+ * downloading (Node only, "java" and "assets" types). On by default at the platform's standard
293
+ * location; a string sets the folder, `false` disables. Files are sha1-verified against the
294
+ * manifest before use, and anything missing or failing falls back to the normal download.
295
+ */
296
+ minecraftDir?: string | boolean
297
+ }
298
+
299
+ export default class MinecraftAssets {
300
+ constructor(options?: MinecraftAssetsOptions)
301
+
302
+ /** The id the default version resolves to, or null before the manifest has been loaded. */
303
+ readonly version: string | null
304
+ /** The default version's type, or null before the manifest has been loaded. */
305
+ readonly channel: VersionTypeName | null
306
+ /**
307
+ * Changes the default version: an id, a keyword, or an entry. Resolves it (fetching the manifest if
308
+ * needed) and returns the entry; an unknown version throws, changing nothing.
309
+ */
310
+ setVersion(value?: VersionRef | null): Promise<ManifestVersion>
311
+ readonly manifest: ManifestAPI
312
+
313
+ list(folder?: string | FolderEntry, options?: ObjectsOptions & { folders?: false }): Promise<FileEntry[]>
314
+ list(folder: string | FolderEntry, options: ObjectsOptions & { folders: true }): Promise<FolderListing>
315
+ list(options: ObjectsOptions & { folders: true }): Promise<FolderListing>
316
+ list(options: ObjectsOptions & { folders?: false }): Promise<FileEntry[]>
317
+ search(query: string | RegExp, options?: SearchOptions): Promise<FileEntry[]>
318
+ file(path: string, options?: ObjectsOptions): Promise<FileEntry | null>
319
+ read(pathOrEntry: string | FileEntry, options?: ReadOptions): Promise<Uint8Array | null>
320
+
321
+ getTexture(id: string, options?: TextureOptions & { meta?: false }): Promise<Uint8Array | null>
322
+ getTexture(id: string, options: TextureOptions & { meta: true }): Promise<TextureWithMeta | null>
323
+ getModel(id: string, options?: GetterOptions): Promise<any | null>
324
+ getBlockstate(id: string, options?: GetterOptions): Promise<any | null>
325
+ getItemDefinition(id: string, options?: GetterOptions): Promise<any | null>
326
+ getSound(id: string, options?: GetterOptions): Promise<Uint8Array | null>
327
+ getStructure(id: string, options?: GetterOptions): Promise<Uint8Array | null>
328
+ getLang(code: string, options?: GetterOptions): Promise<Record<string, string> | null>
329
+
330
+ /** Downloads the version's data now, with byte progress, instead of waiting for the first read. total is null when the server declares no length. */
331
+ loadJar(options?: VersionOptions & { onProgress?: (done: number, total: number | null) => void }): Promise<void>
332
+ loadObjects(options?: LoadObjectsOptions): Promise<Map<string, Uint8Array>>
333
+ export(options?: ExportOptions & { dir?: undefined }): Promise<Uint8Array>
334
+ export(options: ExportOptions & { dir: string }): Promise<number>
335
+
336
+ /** File count and total bytes of the cache. null when a cacheAPI has no list(). */
337
+ cacheStats(): Promise<{ files: number, size: number } | null>
338
+ /** Every cached file as { key, size }, biggest first. null when a cacheAPI has no list(). */
339
+ listCache(): Promise<Array<{ key: string, size: number }> | null>
340
+ /** Clears the whole cache, or just one file when passed its key. */
341
+ clearCache(key?: string): Promise<void>
342
+ /** Changes the byte cap on the built-in cache and evicts down to it. `Infinity` or `null` disables eviction. Does nothing with a cacheAPI. */
343
+ setCacheSize(size: number | null): Promise<void>
344
+ }
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@nkduy/mc-asset-loader",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.6.0",
4
+ "description": "Fetch anything from any Minecraft: Java Edition version, in Node and the browser, touching the network as little as possible",
5
+ "author": "NKDuy",
6
+ "license": "MPL-2.0",
7
+ "type": "module",
8
+ "main": "./src/index.js",
9
+ "types": "./index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./index.d.ts",
13
+ "browser": "./dist/mc-asset-loader.min.js",
14
+ "default": "./src/index.js"
15
+ }
16
+ },
17
+ "browser": {
18
+ "./src/cache.js": false,
19
+ "./src/zlib-node.js": false
20
+ },
21
+ "files": [
22
+ "src",
23
+ "dist",
24
+ "index.d.ts",
25
+ "LICENSE"
26
+ ],
27
+ "engines": {
28
+ "node": ">=18"
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/khanhduy1407/McTitleGen.git"
33
+ },
34
+ "bugs": {
35
+ "url": "https://github.com/khanhduy1407/McTitleGen/issues"
36
+ },
37
+ "scripts": {
38
+ "test": "node --test",
39
+ "build": "esbuild src/index.js --bundle --minify --format=esm --platform=browser --external:node:* --outfile=dist/mc-asset-loader.min.js"
40
+ },
41
+ "devDependencies": {
42
+ "esbuild": "^0.25.0"
43
+ },
44
+ "keywords": [
45
+ "minecraft",
46
+ "assets",
47
+ "textures",
48
+ "resource pack",
49
+ "mojang"
50
+ ],
51
+ "dependencies": {
52
+ "@nkduy/mc-path-search-sort": "^1.2.0"
53
+ }
54
+ }
package/src/bedrock.js ADDED
@@ -0,0 +1,54 @@
1
+ import { parseZip, rawFromBuffer } from "./zip.js"
2
+ import { ZipSource } from "./source.js"
3
+ import { readBody } from "./util.js"
4
+
5
+ const skip = path => path.startsWith(".github/") || path === ".gitignore" || (!path.includes("/") && path.toLowerCase().endsWith(".md"))
6
+
7
+ export class BedrockZip extends ZipSource {
8
+ constructor(options) {
9
+ super(options)
10
+ this.archive = options.archive
11
+ this.key = options.key
12
+ }
13
+
14
+ get blobKey() { return "bedrock_" + this.key }
15
+
16
+ async _loadBuffer() {
17
+ const cached = await this.store.get("blobs", this.blobKey)
18
+ if (cached) return cached
19
+ const res = await this.request(this.url)
20
+ const total = this.size ?? (Number(res.headers.get("content-length")) || null)
21
+ let done = 0
22
+ const bytes = await readBody(res, this._progress ? n => this._progress(done += n, total) : undefined)
23
+ this._persisted = this.store.set("blobs", this.blobKey, bytes).catch(() => {})
24
+ return bytes
25
+ }
26
+
27
+ async _loadListing() {
28
+ const buf = await this.buffer()
29
+ const map = new Map()
30
+ for (const e of parseZip(buf).entries) {
31
+ if (e.path.endsWith("/")) continue
32
+ let path = e.path
33
+ if (this.archive) {
34
+ const slash = path.indexOf("/")
35
+ if (slash < 0) continue
36
+ path = path.slice(slash + 1)
37
+ }
38
+ if (!path || skip(path)) continue
39
+ map.set(path, { ...e, path })
40
+ }
41
+ return { entries: map }
42
+ }
43
+
44
+ async raw(path) {
45
+ await this.listing()
46
+ return this.rawSync(path)
47
+ }
48
+
49
+ rawSync(path) {
50
+ const entry = this._list.entries.get(path)
51
+ if (!entry) return null
52
+ return { entry, data: rawFromBuffer(this._held, entry) }
53
+ }
54
+ }
package/src/cache.js ADDED
@@ -0,0 +1,127 @@
1
+ import fs from "node:fs/promises"
2
+ import path from "node:path"
3
+ import os from "node:os"
4
+
5
+ const STORES = ["meta", "blobs"]
6
+ const SAFE = /[^A-Za-z0-9_.%-]/g
7
+
8
+ const encodeKey = key => encodeURIComponent(key).replace(SAFE, c => "%" + c.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0"))
9
+ const decodeKey = name => decodeURIComponent(name)
10
+
11
+ export class FileCache {
12
+ constructor(dir, { maxSize = 1_000_000_000, key } = {}) {
13
+ this.dir = path.join(dir || path.join(os.tmpdir(), "mc-asset-loader"), key ?? "")
14
+ this.maxSize = maxSize == null ? Infinity : maxSize
15
+ this._index = null
16
+ this._scan = null
17
+ }
18
+
19
+ _file(store, key) {
20
+ if (!STORES.includes(store)) throw new Error("Unknown store " + store)
21
+ return path.join(this.dir, store, encodeKey(key))
22
+ }
23
+
24
+ async _ready() {
25
+ if (this._index) return this._index
26
+ if (!this._scan) this._scan = this._load().then(index => this._index = index)
27
+ return this._scan
28
+ }
29
+
30
+ async _load() {
31
+ const index = new Map()
32
+ for (const store of STORES) {
33
+ const dir = path.join(this.dir, store)
34
+ const names = await fs.readdir(dir).catch(() => [])
35
+ await Promise.all(names.map(async name => {
36
+ if (name.includes(".tmp-")) return
37
+ const st = await fs.stat(path.join(dir, name)).catch(() => null)
38
+ if (st?.isFile()) index.set(store + "/" + name, { size: st.size, mtime: st.mtimeMs })
39
+ }))
40
+ }
41
+ return index
42
+ }
43
+
44
+ async get(store, key) {
45
+ const file = this._file(store, key)
46
+ const index = await this._ready()
47
+ let data
48
+ try {
49
+ data = await fs.readFile(file)
50
+ } catch {
51
+ return undefined
52
+ }
53
+ const now = Date.now()
54
+ fs.utimes(file, now / 1000, now / 1000).catch(() => {})
55
+ const id = store + "/" + path.basename(file)
56
+ const rec = index.get(id)
57
+ if (rec) rec.mtime = now
58
+ else index.set(id, { size: data.length, mtime: now })
59
+ if (store === "meta") return JSON.parse(data.toString("utf8"))
60
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
61
+ }
62
+
63
+ async set(store, key, value) {
64
+ const file = this._file(store, key)
65
+ const index = await this._ready()
66
+ const bytes = store === "meta" ? Buffer.from(JSON.stringify(value), "utf8") : value
67
+ await fs.mkdir(path.dirname(file), { recursive: true })
68
+ const tmp = file + ".tmp-" + Math.random().toString(36).slice(2)
69
+ try {
70
+ await fs.writeFile(tmp, bytes)
71
+ await fs.rename(tmp, file)
72
+ } catch (e) {
73
+ await fs.rm(tmp, { force: true }).catch(() => {})
74
+ throw e
75
+ }
76
+ index.set(store + "/" + path.basename(file), { size: bytes.length, mtime: Date.now() })
77
+ await this._evict()
78
+ }
79
+
80
+ async delete(store, key) {
81
+ const file = this._file(store, key)
82
+ const index = await this._ready()
83
+ index.delete(store + "/" + path.basename(file))
84
+ await fs.rm(file, { force: true })
85
+ }
86
+
87
+ async list() {
88
+ const index = await this._ready()
89
+ return Array.from(index.entries()).map(([id, rec]) => {
90
+ const slash = id.indexOf("/")
91
+ return { key: id.slice(0, slash + 1) + decodeKey(id.slice(slash + 1)), size: rec.size }
92
+ })
93
+ }
94
+
95
+ async keys(store) {
96
+ const names = await fs.readdir(path.join(this.dir, store)).catch(() => [])
97
+ return names.filter(n => !n.includes(".tmp-")).map(decodeKey)
98
+ }
99
+
100
+ async clear() {
101
+ this._index = null
102
+ this._scan = null
103
+ for (const store of STORES) await fs.rm(path.join(this.dir, store), { recursive: true, force: true })
104
+ }
105
+
106
+ async setMaxSize(maxSize) {
107
+ this.maxSize = maxSize == null ? Infinity : maxSize
108
+ if (!isFinite(this.maxSize)) return
109
+ await this._ready()
110
+ await this._evict()
111
+ }
112
+
113
+ async _evict() {
114
+ if (!isFinite(this.maxSize)) return
115
+ const index = this._index
116
+ let total = 0
117
+ for (const rec of index.values()) total += rec.size
118
+ if (total <= this.maxSize) return
119
+ const order = Array.from(index.entries()).sort((a, b) => a[1].mtime - b[1].mtime)
120
+ for (const [id, rec] of order) {
121
+ if (total <= this.maxSize) break
122
+ index.delete(id)
123
+ total -= rec.size
124
+ await fs.rm(path.join(this.dir, id), { force: true }).catch(() => {})
125
+ }
126
+ }
127
+ }