git-fs-s3 0.15.2 → 0.16.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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cache.ts","../src/errors.ts","../src/git-fs.ts","../src/path.ts","../src/prefix.ts","../src/retry.ts"],"sourcesContent":["import { LRUCache } from \"lru-cache\";\nimport type {\n\tListOptions,\n\tListResult,\n\tObjectStat,\n\tObjectStore,\n} from \"./types.js\";\n\nexport interface CacheOptions {\n\t/** Maximum bytes of object data held in memory. Default 50 MiB. */\n\tmaxBytes?: number;\n\t/**\n\t * Largest single entry admitted to the cache. Defaults to a tenth of\n\t * `maxBytes` so one huge packfile cannot evict the whole working set.\n\t */\n\tmaxEntryBytes?: number;\n\t/** Entry time-to-live in milliseconds. Default 60 000. */\n\tttlMs?: number;\n\t/**\n\t * Override the TTL for a specific key (get/head) or list prefix (list),\n\t * in milliseconds. Return `undefined` to fall back to `ttlMs`. Git refs\n\t * (`refs/heads/<branch>`, `HEAD`) are mutable — the same key's value\n\t * changes on every push — unlike content-addressed object keys, which\n\t * never change for a given key and are safe to cache for the full\n\t * `ttlMs`. Without this, a long `ttlMs` tuned for objects also caches\n\t * ref reads that long, so a warm process can keep serving a\n\t * pre-push ref value for the rest of that TTL even though nothing\n\t * changed *this* process's own cache (see `invalidate`) — it just never\n\t * knew to. Give ref-like keys a short override (a few seconds) instead:\n\t * a ref read is one small object, so re-reading it far more often than\n\t * `ttlMs` is cheap, and every read downstream of a fresh ref (tree,\n\t * commit, blob — all keyed by the sha it resolves to) still gets the\n\t * full-length cache/coalescing benefit.\n\t */\n\tttlForKey?: (key: string) => number | undefined;\n\t/**\n\t * Also cache \"key does not exist\" results. Loose-object probes on packed\n\t * repositories are almost always misses, so this saves many round trips —\n\t * but only enable it when a single process is the only writer, otherwise\n\t * another instance's push can be masked for up to `ttlMs`.\n\t */\n\tcacheMisses?: boolean;\n\t/**\n\t * Also cache `list()` results (directory listings and `limit: 1`\n\t * existence probes). Writes through this store keep cached listings\n\t * consistent; after writing to the backend by any other means, call\n\t * `invalidate()` with the affected prefix. Default false.\n\t */\n\tcacheLists?: boolean;\n\t/**\n\t * Collapse concurrent `get`/`head`/`list` calls for the same key into a\n\t * single backend request. Default true.\n\t */\n\tcoalesce?: boolean;\n\t/**\n\t * Return defensive copies from `get` (and copy on admit), so a caller\n\t * mutating returned bytes can't corrupt the cache. Default true. Set\n\t * false when no reader mutates results (isomorphic-git doesn't): every\n\t * hit otherwise copies the whole entry, which for packfiles is megabytes\n\t * per read.\n\t */\n\tcopy?: boolean;\n\t/** Called when a read is answered from cache. */\n\tonHit?: (key: string) => void;\n\t/** Called when a read has to go to the backing store. */\n\tonMiss?: (key: string) => void;\n}\n\n/** An {@link ObjectStore} wrapper that also supports explicit invalidation. */\nexport interface CachedObjectStore extends ObjectStore {\n\t/**\n\t * Drop every cached entry — contents, misses, and listings — whose key\n\t * falls under `prefix` (exact keys included). Call this after the backing\n\t * store was modified by something other than this wrapper.\n\t */\n\tinvalidate(prefix: string): void;\n}\n\nconst MISS = Symbol(\"miss\");\ntype CacheEntry = Uint8Array | typeof MISS;\n\ninterface ListEntry {\n\tresult: ListResult;\n\t/** The raw list prefix this entry describes. */\n\tprefix: string;\n\t/** True for `limit: 1` existence probes. */\n\tprobe: boolean;\n\t/** True when the listing came back with no objects or prefixes. */\n\tempty: boolean;\n}\n\nfunction listEntrySize(entry: ListEntry): number {\n\tlet size = entry.prefix.length + 16;\n\tfor (const o of entry.result.objects) size += o.key.length + 8;\n\tfor (const p of entry.result.prefixes) size += p.length;\n\treturn size;\n}\n\nfunction copyListResult(result: ListResult): ListResult {\n\treturn {\n\t\tobjects: result.objects.map((o) => ({ ...o })),\n\t\tprefixes: [...result.prefixes],\n\t};\n}\n\n/**\n * Wrap an {@link ObjectStore} with an in-process LRU read cache.\n *\n * Git object keys are content-addressed and therefore immutable, which makes\n * them ideal cache entries; mutable keys (refs, packed-refs) are bounded by\n * `ttlMs`. Writes and deletes through this wrapper invalidate their key and\n * any cached listings they affect — with one asymmetry: a non-empty `limit: 1`\n * probe (a \"directory exists\" answer) survives writes underneath it, because\n * adding a key below a prefix cannot make that prefix stop existing, while\n * empty probes and full listings are always dropped.\n */\nexport function createCachedStore(\n\tstore: ObjectStore,\n\toptions: CacheOptions = {},\n): CachedObjectStore {\n\tconst maxBytes = options.maxBytes ?? 50 * 1024 * 1024;\n\tconst maxEntryBytes = options.maxEntryBytes ?? Math.ceil(maxBytes / 10);\n\tconst ttl = options.ttlMs ?? 60_000;\n\tconst ttlForKey = options.ttlForKey;\n\tconst cacheMisses = options.cacheMisses ?? false;\n\tconst cacheLists = options.cacheLists ?? false;\n\tconst range = store.getRange?.bind(store);\n\tconst coalesce = options.coalesce ?? true;\n\tconst copy = options.copy ?? true;\n\tconst clone = (data: Uint8Array) => (copy ? data.slice() : data);\n\tconst onHit = options.onHit;\n\tconst onMiss = options.onMiss;\n\n\tconst cache = new LRUCache<string, CacheEntry>({\n\t\tmaxSize: maxBytes,\n\t\tsizeCalculation: (value) => (value === MISS ? 1 : value.byteLength || 1),\n\t\tttl,\n\t});\n\tconst listCache = new LRUCache<string, ListEntry>({\n\t\tmaxSize: Math.max(1, Math.ceil(maxBytes / 10)),\n\t\tsizeCalculation: listEntrySize,\n\t\tttl,\n\t});\n\n\tconst pendingGets = new Map<string, Promise<Uint8Array | null>>();\n\tconst pendingHeads = new Map<string, Promise<ObjectStat | null>>();\n\tconst pendingLists = new Map<string, Promise<ListResult>>();\n\n\t/**\n\t * Bumped by every write, delete and invalidation. A backend read that\n\t * started before one of those may finish after it carrying the old answer\n\t * (the old bytes, or \"missing\" for a key that now exists); it still\n\t * answers its own callers, but only a read that saw no write in between\n\t * may populate the cache — otherwise a stale miss could hide a freshly\n\t * written object for the whole TTL.\n\t */\n\tlet generation = 0;\n\tconst unchangedSince = (start: number) => generation === start;\n\n\tconst admit = (key: string, data: Uint8Array) => {\n\t\tif (data.byteLength <= maxEntryBytes) {\n\t\t\tcache.set(key, clone(data), { ttl: ttlForKey?.(key) });\n\t\t}\n\t};\n\n\t/** Drop list entries a write/delete at `key` may have made stale. */\n\tfunction clearStaleListEntries(key: string): void {\n\t\tfor (const [listKey, entry] of listCache.entries()) {\n\t\t\tif (!key.startsWith(entry.prefix)) continue;\n\t\t\tif (entry.probe && !entry.empty) continue;\n\t\t\tlistCache.delete(listKey);\n\t\t}\n\t\t// Readers arriving after this write must not join a listing that\n\t\t// started before it.\n\t\tfor (const listKey of pendingLists.keys()) {\n\t\t\tconst prefix = listKey.split(\"|\").slice(2).join(\"|\");\n\t\t\tif (key.startsWith(prefix)) pendingLists.delete(listKey);\n\t\t}\n\t}\n\n\t/** A write to `key` happened: no in-flight read of it may be joined or cached. */\n\tfunction noteWrite(key: string): void {\n\t\tgeneration++;\n\t\tpendingGets.delete(key);\n\t\tpendingHeads.delete(key);\n\t}\n\n\tfunction coalesced<T>(\n\t\tpending: Map<string, Promise<T>>,\n\t\tkey: string,\n\t\tfn: () => Promise<T>,\n\t): Promise<T> {\n\t\tif (!coalesce) return fn();\n\t\tconst inflight = pending.get(key);\n\t\tif (inflight !== undefined) return inflight;\n\t\tconst p = fn().finally(() => {\n\t\t\tif (pending.get(key) === p) pending.delete(key);\n\t\t});\n\t\tpending.set(key, p);\n\t\treturn p;\n\t}\n\n\treturn {\n\t\tasync get(key: string): Promise<Uint8Array | null> {\n\t\t\tconst cached = cache.get(key);\n\t\t\tif (cached !== undefined) {\n\t\t\t\tonHit?.(key);\n\t\t\t\treturn cached === MISS ? null : clone(cached);\n\t\t\t}\n\t\t\tconst data = await coalesced(pendingGets, key, async () => {\n\t\t\t\tonMiss?.(key);\n\t\t\t\tconst start = generation;\n\t\t\t\tconst fetched = await store.get(key);\n\t\t\t\tif (unchangedSince(start)) {\n\t\t\t\t\tif (fetched !== null) {\n\t\t\t\t\t\tadmit(key, fetched);\n\t\t\t\t\t} else if (cacheMisses) {\n\t\t\t\t\t\tcache.set(key, MISS, { ttl: ttlForKey?.(key) });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn fetched;\n\t\t\t});\n\t\t\treturn data === null ? null : clone(data);\n\t\t},\n\n\t\tasync put(key: string, data: Uint8Array): Promise<void> {\n\t\t\tnoteWrite(key);\n\t\t\ttry {\n\t\t\t\tawait store.put(key, data);\n\t\t\t} finally {\n\t\t\t\t// Even a failed put may have landed; never keep serving the\n\t\t\t\t// pre-write answer for this key.\n\t\t\t\tnoteWrite(key);\n\t\t\t\tcache.delete(key);\n\t\t\t\tclearStaleListEntries(key);\n\t\t\t}\n\t\t\tadmit(key, data);\n\t\t},\n\n\t\tasync delete(key: string): Promise<void> {\n\t\t\tnoteWrite(key);\n\t\t\ttry {\n\t\t\t\tawait store.delete(key);\n\t\t\t} finally {\n\t\t\t\tnoteWrite(key);\n\t\t\t\tcache.delete(key);\n\t\t\t\tclearStaleListEntries(key);\n\t\t\t}\n\t\t\tif (cacheMisses) {\n\t\t\t\tcache.set(key, MISS, { ttl: ttlForKey?.(key) });\n\t\t\t} else {\n\t\t\t\tcache.delete(key);\n\t\t\t}\n\t\t},\n\n\t\tasync head(key: string): Promise<ObjectStat | null> {\n\t\t\tconst cached = cache.get(key);\n\t\t\tif (cached !== undefined) {\n\t\t\t\tonHit?.(key);\n\t\t\t\treturn cached === MISS ? null : { size: cached.byteLength };\n\t\t\t}\n\t\t\treturn coalesced(pendingHeads, key, async () => {\n\t\t\t\tonMiss?.(key);\n\t\t\t\tconst start = generation;\n\t\t\t\tconst stat = await store.head(key);\n\t\t\t\tif (stat === null && cacheMisses && unchangedSince(start)) {\n\t\t\t\t\tcache.set(key, MISS, { ttl: ttlForKey?.(key) });\n\t\t\t\t}\n\t\t\t\treturn stat;\n\t\t\t});\n\t\t},\n\n\t\tasync list(prefix: string, listOptions?: ListOptions): Promise<ListResult> {\n\t\t\tif (!cacheLists) return store.list(prefix, listOptions);\n\t\t\tconst listKey = `${listOptions?.delimiter ?? \"\"}|${listOptions?.limit ?? \"\"}|${prefix}`;\n\t\t\tconst cached = listCache.get(listKey);\n\t\t\tif (cached !== undefined) {\n\t\t\t\tonHit?.(prefix);\n\t\t\t\treturn copyListResult(cached.result);\n\t\t\t}\n\t\t\tconst result = await coalesced(pendingLists, listKey, async () => {\n\t\t\t\tonMiss?.(prefix);\n\t\t\t\tconst start = generation;\n\t\t\t\tconst fetched = await store.list(prefix, listOptions);\n\t\t\t\tif (!unchangedSince(start)) return fetched;\n\t\t\t\tlistCache.set(\n\t\t\t\t\tlistKey,\n\t\t\t\t\t{\n\t\t\t\t\t\tresult: copyListResult(fetched),\n\t\t\t\t\t\tprefix,\n\t\t\t\t\t\tprobe: listOptions?.limit === 1,\n\t\t\t\t\t\tempty:\n\t\t\t\t\t\t\tfetched.objects.length === 0 && fetched.prefixes.length === 0,\n\t\t\t\t\t},\n\t\t\t\t\t{ ttl: ttlForKey?.(prefix) },\n\t\t\t\t);\n\t\t\t\treturn fetched;\n\t\t\t});\n\t\t\treturn copyListResult(result);\n\t\t},\n\n\t\t// Forwarded straight to the backing store: a range read is a handful of\n\t\t// bytes at a known offset, so caching one buys nothing, and bypassing the\n\t\t// cache here keeps this wrapper's read paths unchanged.\n\t\t...(range\n\t\t\t? {\n\t\t\t\t\tgetRange: (key: string, start: number, end: number) =>\n\t\t\t\t\t\trange(key, start, end),\n\t\t\t\t}\n\t\t\t: {}),\n\n\t\tinvalidate(prefix: string): void {\n\t\t\tgeneration++;\n\t\t\tfor (const key of [...pendingGets.keys()]) {\n\t\t\t\tif (key.startsWith(prefix)) pendingGets.delete(key);\n\t\t\t}\n\t\t\tfor (const key of [...pendingHeads.keys()]) {\n\t\t\t\tif (key.startsWith(prefix)) pendingHeads.delete(key);\n\t\t\t}\n\t\t\tpendingLists.clear();\n\t\t\tfor (const key of cache.keys()) {\n\t\t\t\tif (key.startsWith(prefix)) cache.delete(key);\n\t\t\t}\n\t\t\tfor (const [listKey, entry] of listCache.entries()) {\n\t\t\t\tif (\n\t\t\t\t\tentry.prefix.startsWith(prefix) ||\n\t\t\t\t\tprefix.startsWith(entry.prefix)\n\t\t\t\t) {\n\t\t\t\t\tlistCache.delete(listKey);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t};\n}\n","/**\n * Node-style filesystem error carrying a `code` property, which is what\n * isomorphic-git inspects to distinguish \"file not found\" from real failures.\n */\nexport class FsError extends Error {\n\treadonly code: string;\n\treadonly syscall: string;\n\treadonly path: string;\n\n\tconstructor(code: string, syscall: string, path: string) {\n\t\tsuper(`${code}: ${syscall} '${path}'`);\n\t\tthis.name = \"FsError\";\n\t\tthis.code = code;\n\t\tthis.syscall = syscall;\n\t\tthis.path = path;\n\t}\n}\n\nexport const enoent = (syscall: string, path: string) =>\n\tnew FsError(\"ENOENT\", syscall, path);\n\nexport const enotdir = (syscall: string, path: string) =>\n\tnew FsError(\"ENOTDIR\", syscall, path);\n\nexport const enotempty = (syscall: string, path: string) =>\n\tnew FsError(\"ENOTEMPTY\", syscall, path);\n\nexport const einval = (syscall: string, path: string) =>\n\tnew FsError(\"EINVAL\", syscall, path);\n\nexport const eperm = (syscall: string, path: string) =>\n\tnew FsError(\"EPERM\", syscall, path);\n","import { LRUCache } from \"lru-cache\";\nimport { enoent, enotdir, enotempty, eperm } from \"./errors.js\";\nimport { parseLooseObjectPath } from \"./git-layout.js\";\nimport { parsePackDirectory, READABLE_PACK_FILE_KINDS } from \"./pack-files.js\";\nimport { normalizePath, toKey as toKeyWithPrefix } from \"./path.js\";\nimport type {\n\tEncoding,\n\tGitdirFacts,\n\tGitFsClient,\n\tGitFsOptions,\n\tObjectStore,\n\tReadFileOptions,\n\tStat,\n\tWriteFileOptions,\n} from \"./types.js\";\n\nconst FILE_MODE = 0o100644;\nconst DIR_MODE = 0o40000;\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\nfunction makeStat(type: \"file\" | \"dir\", size: number): Stat {\n\tconst epoch = new Date(0);\n\treturn {\n\t\ttype,\n\t\tmode: type === \"file\" ? FILE_MODE : DIR_MODE,\n\t\tsize,\n\t\tino: 0,\n\t\tmtimeMs: 0,\n\t\tctimeMs: 0,\n\t\tuid: 0,\n\t\tgid: 0,\n\t\tdev: 0,\n\t\tmtime: epoch,\n\t\tctime: epoch,\n\t\tisFile: () => type === \"file\",\n\t\tisDirectory: () => type === \"dir\",\n\t\tisSymbolicLink: () => false,\n\t};\n}\n\nfunction resolveEncoding(\n\toptions?: ReadFileOptions | WriteFileOptions | Encoding,\n): Encoding | undefined {\n\tif (typeof options === \"string\") return options;\n\treturn options?.encoding;\n}\n\n/**\n * The filesystem returned by {@link createGitFs}: the isomorphic-git client\n * plus git-aware maintenance hooks.\n */\nexport interface GitFs extends GitFsClient {\n\t/**\n\t * Return every file below a directory in one object-store listing. Unlike\n\t * `readdir`, this deliberately does not use a delimiter: object storage can\n\t * enumerate a ref namespace recursively without the stat-per-entry walk a\n\t * POSIX filesystem needs to distinguish files from implicit directories.\n\t * Paths are relative to `dirpath` and never include directory entries.\n\t */\n\tlistFilesRecursively(dirpath: string): Promise<string[]>;\n\t/**\n\t * Probe, with one bounded list, whether `gitdir` contains any loose\n\t * objects, and remember the answer. This is the only way a loose-object\n\t * hint is ever created; call it before full-history walks (commit logs,\n\t * reachability traversals) so fully packed repositories skip every\n\t * guaranteed-miss loose-object read. A later loose write flips the hint\n\t * back, so it cannot go stale mid-push.\n\t */\n\tdetectLooseObjects(gitdir: string): Promise<void>;\n\t/**\n\t * Warm the cache with every pack file under `gitdir` in parallel (plus\n\t * the loose-object hint) before a sequential history walk. Skipped when\n\t * the pack directory holds more than `maxPacks * 2` entries — warming\n\t * only helps when the cache budget actually fits the packs.\n\t */\n\tprefetchPacks(gitdir: string, options?: { maxPacks?: number }): Promise<void>;\n\t/**\n\t * Clear fs-level state (loose-object hints) under `pathPrefix`, and\n\t * forward to the store's `invalidate` when it has one. Call after the\n\t * backing store was modified by something other than this fs.\n\t */\n\tinvalidate(pathPrefix: string): void;\n\t/**\n\t * Declare that `gitdir` exists, so `stat` answers \"directory\" for it with\n\t * zero store calls. isomorphic-git stats the gitdir on every command\n\t * (`discoverGitdir`); in object storage that is a HEAD that always misses\n\t * plus a listing. Register once the caller has confirmed the repository\n\t * exists by other means (e.g. its database row); `invalidate` forgets it.\n\t */\n\tregisterGitdir(gitdir: string, facts?: GitdirFacts): void;\n}\n\n/**\n * Create a promise-based filesystem client for isomorphic-git backed by an\n * {@link ObjectStore}.\n *\n * Semantics:\n * - Directories are implicit, as in object storage: `mkdir` is a no-op and a\n * directory \"exists\" whenever at least one key lives under its prefix.\n * - Symbolic links are not supported (`readlink`/`symlink` throw). Bare\n * repositories never contain them.\n * - Designed for bare, server-side repositories (`git.init({bare: true})`,\n * plumbing commands, ref updates). Worktree checkouts belong on a real disk.\n */\nexport function createGitFs(\n\tstore: ObjectStore,\n\toptions: GitFsOptions = {},\n): GitFs {\n\tconst prefix = options.prefix ?? \"\";\n\tconst useLooseHints = options.looseObjectHints ?? false;\n\tconst onNote = options.onNote;\n\n\tconst toKey = (path: string): string => toKeyWithPrefix(prefix, path);\n\n\t/**\n\t * Per-gitdir \"does any loose object exist\" hint. Entries are only created\n\t * by {@link GitFs.detectLooseObjects}, so a pathological ref that merely\n\t * looks like a loose object (`refs/heads/objects/aa/…`) derives a scope\n\t * that was never registered and can never be wrongly short-circuited.\n\t */\n\tconst looseHints = new LRUCache<string, \"none\" | \"present\">({\n\t\tmax: 1024,\n\t\tttl: options.hintTtlMs ?? 3_600_000,\n\t});\n\n\t/** Gitdirs the caller vouched for via {@link GitFs.registerGitdir}. */\n\tconst registeredGitdirs = new LRUCache<string, ReadonlySet<string>>({\n\t\tmax: 4096,\n\t});\n\n\t/** Whether `path` is a top-level file its registered gitdir lacks. */\n\tfunction registeredAbsent(path: string): boolean {\n\t\tconst slash = path.lastIndexOf(\"/\");\n\t\tif (slash < 0) return false;\n\t\tconst absent = registeredGitdirs.get(path.slice(0, slash));\n\t\treturn absent?.has(path.slice(slash + 1)) ?? false;\n\t}\n\n\t/** The gitdir scope of a loose-object path, or null when it isn't one. */\n\tfunction looseScope(path: string): string | null {\n\t\treturn parseLooseObjectPath(path)?.gitdir ?? null;\n\t}\n\n\tconst pendingDetections = new Map<string, Promise<void>>();\n\n\t/**\n\t * Resolve the loose-object hint for `path`'s gitdir before answering, so a\n\t * read that runs before any explicit `detectLooseObjects` call (e.g. the\n\t * first commit read of a request) doesn't pay a doomed GET. One coalesced\n\t * listing per gitdir, cached for `hintTtlMs`.\n\t */\n\tasync function knownAbsent(path: string): Promise<boolean> {\n\t\tif (registeredAbsent(path)) return true;\n\t\tif (!useLooseHints) return false;\n\t\tconst scope = looseScope(path);\n\t\tif (scope === null) return false;\n\t\tif (!looseHints.has(scope)) {\n\t\t\tlet pending = pendingDetections.get(scope);\n\t\t\tif (!pending) {\n\t\t\t\tpending = detectLooseObjects(scope).finally(() =>\n\t\t\t\t\tpendingDetections.delete(scope),\n\t\t\t\t);\n\t\t\t\tpendingDetections.set(scope, pending);\n\t\t\t}\n\t\t\tawait pending;\n\t\t}\n\t\treturn looseHints.get(scope) === \"none\";\n\t}\n\n\tasync function isDirectory(dirKey: string): Promise<boolean> {\n\t\tconst { objects, prefixes } = await store.list(`${dirKey}/`, {\n\t\t\tlimit: 1,\n\t\t});\n\t\treturn objects.length > 0 || prefixes.length > 0;\n\t}\n\n\tasync function stat(filepath: string, syscall: string): Promise<Stat> {\n\t\tconst path = normalizePath(filepath);\n\t\tif (await knownAbsent(path)) throw enoent(syscall, filepath);\n\t\tconst k = toKey(path);\n\t\tif (k === prefix || k === \"\" || registeredGitdirs.has(path)) {\n\t\t\treturn makeStat(\"dir\", 0);\n\t\t}\n\t\tconst fileStat = await store.head(k);\n\t\tif (fileStat) return makeStat(\"file\", fileStat.size);\n\t\t// A loose-object path is always a leaf; when the object itself is\n\t\t// absent there is no point probing for a directory of the same name.\n\t\tif (useLooseHints && looseScope(path) !== null) {\n\t\t\tthrow enoent(syscall, filepath);\n\t\t}\n\t\tif (await isDirectory(k)) return makeStat(\"dir\", 0);\n\t\tthrow enoent(syscall, filepath);\n\t}\n\n\tconst range = store.getRange?.bind(store);\n\n\tconst promises: GitFsClient[\"promises\"] = {\n\t\t// Only defined when the backing store supports ranges, so a caller can\n\t\t// test for it rather than have to interpret a failure.\n\t\t...(range\n\t\t\t? {\n\t\t\t\t\tgetRange: (filepath: string, start: number, end: number) =>\n\t\t\t\t\t\trange(toKey(normalizePath(filepath)), start, end),\n\t\t\t\t}\n\t\t\t: {}),\n\n\t\tasync readFile(filepath, opts) {\n\t\t\tconst path = normalizePath(filepath);\n\t\t\tif (await knownAbsent(path)) throw enoent(\"open\", filepath);\n\t\t\tconst data = await store.get(toKey(path));\n\t\t\tif (data === null) throw enoent(\"open\", filepath);\n\t\t\treturn resolveEncoding(opts) === \"utf8\" ? textDecoder.decode(data) : data;\n\t\t},\n\n\t\tasync writeFile(filepath, data, _opts) {\n\t\t\tconst path = normalizePath(filepath);\n\t\t\tif (useLooseHints) {\n\t\t\t\tconst scope = looseScope(path);\n\t\t\t\t// Flip before the write lands so a racing read can never\n\t\t\t\t// short-circuit an object that is in the middle of arriving.\n\t\t\t\tif (scope !== null) looseHints.set(scope, \"present\");\n\t\t\t}\n\t\t\tconst bytes = typeof data === \"string\" ? textEncoder.encode(data) : data;\n\t\t\tawait store.put(toKey(path), bytes);\n\t\t},\n\n\t\tasync unlink(filepath) {\n\t\t\tconst k = toKey(normalizePath(filepath));\n\t\t\tif ((await store.head(k)) === null) throw enoent(\"unlink\", filepath);\n\t\t\tawait store.delete(k);\n\t\t},\n\n\t\tasync readdir(dirpath) {\n\t\t\tconst k = toKey(normalizePath(dirpath));\n\t\t\tconst isRoot = k === prefix || k === \"\";\n\t\t\tconst listPrefix = isRoot && k === \"\" ? \"\" : `${k}/`;\n\t\t\tconst { objects, prefixes } = await store.list(listPrefix, {\n\t\t\t\tdelimiter: \"/\",\n\t\t\t});\n\t\t\tif (objects.length === 0 && prefixes.length === 0) {\n\t\t\t\tif (!isRoot && (await store.head(k)) !== null) {\n\t\t\t\t\tthrow enotdir(\"scandir\", dirpath);\n\t\t\t\t}\n\t\t\t\tif (!isRoot) throw enoent(\"scandir\", dirpath);\n\t\t\t}\n\t\t\tconst names = objects.map((o) => o.key.slice(listPrefix.length));\n\t\t\tconst dirNames = prefixes.map((p) =>\n\t\t\t\tp.slice(listPrefix.length).replace(/\\/$/, \"\"),\n\t\t\t);\n\t\t\treturn [...names, ...dirNames].sort();\n\t\t},\n\n\t\tasync mkdir(_dirpath, _opts) {\n\t\t\t// Directories are implicit in object storage.\n\t\t},\n\n\t\tasync rmdir(dirpath) {\n\t\t\tconst k = toKey(normalizePath(dirpath));\n\t\t\tconst { objects, prefixes } = await store.list(`${k}/`, { limit: 1 });\n\t\t\tif (objects.length > 0 || prefixes.length > 0) {\n\t\t\t\tthrow enotempty(\"rmdir\", dirpath);\n\t\t\t}\n\t\t\t// Empty implicit directories don't exist; nothing to remove.\n\t\t},\n\n\t\tstat: (filepath) => stat(filepath, \"stat\"),\n\t\tlstat: (filepath) => stat(filepath, \"lstat\"),\n\n\t\tasync readlink(filepath): Promise<never> {\n\t\t\tthrow enoent(\"readlink\", filepath);\n\t\t},\n\n\t\tasync symlink(_target, filepath): Promise<never> {\n\t\t\tthrow eperm(\"symlink\", filepath);\n\t\t},\n\n\t\tasync chmod(_filepath, _mode) {\n\t\t\t// POSIX modes don't exist in object storage.\n\t\t},\n\t};\n\n\tasync function detectLooseObjects(gitdir: string): Promise<void> {\n\t\tif (!useLooseHints) return;\n\t\tconst scope = normalizePath(gitdir);\n\t\t// A live hint must win over re-detection: after a loose write flips it\n\t\t// to \"present\", re-deriving from a (possibly cached, pre-write) listing\n\t\t// could wrongly reinstate \"none\" and mask real objects.\n\t\tif (looseHints.has(scope)) return;\n\t\ttry {\n\t\t\tconst { objects } = await store.list(`${toKey(scope)}/objects/`, {\n\t\t\t\tlimit: 1,\n\t\t\t});\n\t\t\t// Loose fan-out directories (two hex digits) sort before \"info/\"\n\t\t\t// and \"pack/\", so when any loose object exists it is the first key.\n\t\t\tconst first = objects[0]?.key;\n\t\t\tconst hint =\n\t\t\t\tfirst !== undefined && parseLooseObjectPath(first) !== null\n\t\t\t\t\t? \"present\"\n\t\t\t\t\t: \"none\";\n\t\t\tlooseHints.set(scope, hint);\n\t\t\tonNote?.(`loose objects ${hint} under ${scope}`);\n\t\t} catch {\n\t\t\t// Leave unknown — reads fall back to their normal round trip.\n\t\t}\n\t}\n\n\tasync function prefetchPacks(\n\t\tgitdir: string,\n\t\tprefetchOptions?: { maxPacks?: number },\n\t): Promise<void> {\n\t\tconst maxPacks = prefetchOptions?.maxPacks ?? 30;\n\t\tconst packDir = `${normalizePath(gitdir)}/objects/pack`;\n\t\t// isomorphic-git never reads .bitmap/.rev/.keep, so fetching them is a\n\t\t// wasted GET and wasted cache space.\n\t\tconst entries = parsePackDirectory(\n\t\t\tawait promises.readdir(packDir).catch(() => []),\n\t\t)\n\t\t\t.filter((file) => READABLE_PACK_FILE_KINDS.has(file.kind))\n\t\t\t.map((file) => file.name);\n\t\tif (entries.length > maxPacks * 2) {\n\t\t\tawait detectLooseObjects(gitdir);\n\t\t\treturn;\n\t\t}\n\t\tawait Promise.all([\n\t\t\tdetectLooseObjects(gitdir),\n\t\t\t...entries.map((name) =>\n\t\t\t\tpromises.readFile(`${packDir}/${name}`).catch(() => undefined),\n\t\t\t),\n\t\t]);\n\t}\n\n\tasync function listFilesRecursively(dirpath: string): Promise<string[]> {\n\t\tconst directory = toKey(normalizePath(dirpath));\n\t\tconst listPrefix = directory === \"\" ? \"\" : `${directory}/`;\n\t\tconst { objects } = await store.list(listPrefix);\n\t\treturn objects\n\t\t\t.map((object) => object.key.slice(listPrefix.length))\n\t\t\t.filter((path) => path.length > 0)\n\t\t\t.sort();\n\t}\n\n\tfunction registerGitdir(gitdir: string, facts?: GitdirFacts): void {\n\t\tregisteredGitdirs.set(\n\t\t\tnormalizePath(gitdir),\n\t\t\tnew Set(facts?.absentFiles ?? []),\n\t\t);\n\t}\n\n\tfunction invalidate(pathPrefix: string): void {\n\t\tconst normalized = normalizePath(pathPrefix);\n\t\tfor (const dir of registeredGitdirs.keys()) {\n\t\t\tif (dir.startsWith(normalized)) registeredGitdirs.delete(dir);\n\t\t}\n\t\tfor (const scope of looseHints.keys()) {\n\t\t\tif (scope.startsWith(normalized)) looseHints.delete(scope);\n\t\t}\n\t\tconst maybe = store as ObjectStore & {\n\t\t\tinvalidate?: (prefix: string) => void;\n\t\t};\n\t\tmaybe.invalidate?.(toKey(normalized));\n\t}\n\n\treturn {\n\t\tpromises,\n\t\tlistFilesRecursively,\n\t\tdetectLooseObjects,\n\t\tprefetchPacks,\n\t\tinvalidate,\n\t\tregisterGitdir,\n\t};\n}\n","import { einval } from \"./errors.js\";\n\n/**\n * Normalize an absolute-or-relative filesystem path into a storage key\n * segment: no leading/trailing slashes, `.` segments dropped, `..` resolved.\n * A `..` that would escape the root throws EINVAL — paths handed to the fs\n * must never address keys outside the configured prefix.\n */\nexport function normalizePath(filepath: string): string {\n\tconst segments = filepath.split(\"/\");\n\tconst out: string[] = [];\n\tfor (const segment of segments) {\n\t\tif (segment === \"\" || segment === \".\") continue;\n\t\tif (segment === \"..\") {\n\t\t\tif (out.length === 0) throw einval(\"resolve\", filepath);\n\t\t\tout.pop();\n\t\t\tcontinue;\n\t\t}\n\t\tout.push(segment);\n\t}\n\treturn out.join(\"/\");\n}\n\n/** Join a configured key prefix with a normalized path. */\nexport function toKey(prefix: string, filepath: string): string {\n\tconst normalized = normalizePath(filepath);\n\tif (prefix === \"\") return normalized;\n\treturn normalized === \"\" ? prefix : `${prefix}/${normalized}`;\n}\n","import type { ObjectStore } from \"./types.js\";\n\nconst BATCH = 20;\n\nasync function inBatches<T>(\n\titems: T[],\n\tfn: (item: T) => Promise<void>,\n): Promise<void> {\n\tfor (let i = 0; i < items.length; i += BATCH) {\n\t\tawait Promise.all(items.slice(i, i + BATCH).map(fn));\n\t}\n}\n\n/**\n * Delete every object under `prefix` (one paginated LIST, then batched\n * deletes). Returns the number of objects deleted. Callers serialise against\n * concurrent writers (e.g. a repository lock) and invalidate any cache\n * layered above `store`.\n */\nexport async function deletePrefix(\n\tstore: ObjectStore,\n\tprefix: string,\n): Promise<number> {\n\tconst { objects } = await store.list(prefix);\n\tawait inBatches(objects, (object) => store.delete(object.key));\n\treturn objects.length;\n}\n\nexport interface MovePrefixOptions {\n\t/**\n\t * Copy one object, e.g. a store's server-side `copy` (no bytes pass through\n\t * this process). Defaults to `get` + `put` on `store`.\n\t */\n\tcopy?: (fromKey: string, toKey: string) => Promise<void>;\n}\n\n/**\n * Move every object under `from` to the same relative key under `to`: copy\n * everything first, then delete the old keys only once every copy succeeded,\n * so a failed copy leaves the source untouched (a partial destination may\n * remain; call {@link deletePrefix} on it to clean up). Returns the number of\n * objects moved. `from` and `to` must not overlap.\n */\nexport async function movePrefix(\n\tstore: ObjectStore,\n\tfrom: string,\n\tto: string,\n\toptions: MovePrefixOptions = {},\n): Promise<number> {\n\tif (from.startsWith(to) || to.startsWith(from)) {\n\t\tthrow new Error(`movePrefix: prefixes overlap (${from} -> ${to})`);\n\t}\n\tconst copy =\n\t\toptions.copy ??\n\t\t(async (fromKey: string, toKey: string) => {\n\t\t\tconst data = await store.get(fromKey);\n\t\t\tif (data) await store.put(toKey, data);\n\t\t});\n\tconst { objects } = await store.list(from);\n\tawait inBatches(objects, (object) =>\n\t\tcopy(object.key, to + object.key.slice(from.length)),\n\t);\n\tawait inBatches(objects, (object) => store.delete(object.key));\n\treturn objects.length;\n}\n","import type { ObjectStore } from \"./types.js\";\n\n/** Options accepted by {@link createRetryStore}. */\nexport interface RetryOptions {\n\t/** Retries after the first attempt (total attempts = retries + 1). Default 3. */\n\tretries?: number;\n\t/** Backoff base delay in milliseconds, doubled each attempt. Default 100. */\n\tinitialDelayMs?: number;\n\t/** Upper bound for the backoff base delay. Default 5000. */\n\tmaxDelayMs?: number;\n\t/** Random jitter added to each delay, as a fraction of it. Default 0.3. */\n\tjitter?: number;\n\t/**\n\t * Decide whether an error is worth retrying. The store contract maps\n\t * \"not found\" to `null` rather than throwing, so any thrown error is a\n\t * genuine failure; the default retries network faults, throttling, and\n\t * HTTP 5xx responses.\n\t */\n\tisRetryable?: (error: unknown) => boolean;\n\t/**\n\t * Circuit breaker configuration, or `false` to disable. After `threshold`\n\t * consecutive failures the store fails fast for `resetMs`, then lets one\n\t * request probe the backend again. Defaults: 5 failures, 30 000 ms.\n\t */\n\tbreaker?: false | { threshold?: number; resetMs?: number };\n\t/** Called before each retry sleep; useful for logging/metrics. */\n\tonRetry?: (info: {\n\t\tkey: string;\n\t\top: string;\n\t\tattempt: number;\n\t\tdelayMs: number;\n\t}) => void;\n}\n\n/**\n * Thrown instead of calling the backend while the circuit breaker is open.\n * Carries `code: \"EUNAVAILABLE\"` so callers can map it to a 503.\n */\nexport class CircuitOpenError extends Error {\n\treadonly code = \"EUNAVAILABLE\";\n\n\tconstructor() {\n\t\tsuper(\"Circuit breaker is open, object store unavailable\");\n\t\tthis.name = \"CircuitOpenError\";\n\t}\n}\n\nconst RETRYABLE_NAMES = new Set([\n\t\"TimeoutError\",\n\t\"RequestTimeout\",\n\t\"RequestTimeoutException\",\n\t\"SlowDown\",\n\t\"ThrottlingException\",\n\t\"TooManyRequestsException\",\n]);\n\nconst RETRYABLE_CODES = new Set([\n\t\"ECONNRESET\",\n\t\"ECONNREFUSED\",\n\t\"EPIPE\",\n\t\"ETIMEDOUT\",\n\t\"ENOTFOUND\",\n\t\"EAI_AGAIN\",\n\t\"EPROTO\",\n]);\n\n/**\n * The default retry classifier: network faults, timeouts, throttling and HTTP\n * 5xx/429 (including `$metadata.httpStatusCode`-shaped errors). `fetch`\n * reports a dropped connection as a bare `TypeError`, which counts too.\n * Compose it in a custom `isRetryable`.\n */\nexport function isRetryableError(error: unknown): boolean {\n\tif (error instanceof TypeError) return true;\n\tif (typeof error !== \"object\" || error === null) return false;\n\tconst err = error as {\n\t\tname?: string;\n\t\tcode?: string;\n\t\t$metadata?: { httpStatusCode?: number };\n\t};\n\tif (err.name !== undefined && RETRYABLE_NAMES.has(err.name)) return true;\n\tif (err.code !== undefined && RETRYABLE_CODES.has(err.code)) return true;\n\tconst status = err.$metadata?.httpStatusCode;\n\treturn status !== undefined && (status >= 500 || status === 429);\n}\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Wrap an {@link ObjectStore} with retries (exponential backoff + jitter) and\n * an optional per-instance circuit breaker.\n *\n * Place this decorator closest to the network store, underneath any cache:\n * the cache then never stores transient failures, and callers coalesced onto\n * one request share a single retried attempt.\n */\nexport function createRetryStore(\n\tstore: ObjectStore,\n\toptions: RetryOptions = {},\n): ObjectStore {\n\tconst retries = options.retries ?? 3;\n\tconst initialDelayMs = options.initialDelayMs ?? 100;\n\tconst maxDelayMs = options.maxDelayMs ?? 5000;\n\tconst jitter = options.jitter ?? 0.3;\n\tconst isRetryable = options.isRetryable ?? isRetryableError;\n\tconst breaker =\n\t\toptions.breaker === false\n\t\t\t? null\n\t\t\t: {\n\t\t\t\t\tthreshold: options.breaker?.threshold ?? 5,\n\t\t\t\t\tresetMs: options.breaker?.resetMs ?? 30_000,\n\t\t\t\t};\n\n\tlet failures = 0;\n\tlet lastFailureAt = 0;\n\tlet state: \"closed\" | \"open\" | \"half-open\" = \"closed\";\n\tlet probing = false;\n\n\t/**\n\t * Consecutive transient failures open the circuit; any success closes it\n\t * and resets the count. Non-retryable errors (a 403, a malformed request)\n\t * say nothing about the backend's health and never count. Once the reset\n\t * window passes, exactly one request probes the backend (half-open);\n\t * everything else keeps failing fast until that probe settles.\n\t */\n\tasync function guarded<T>(fn: () => Promise<T>): Promise<T> {\n\t\tif (breaker === null) return fn();\n\t\tlet isProbe = false;\n\t\tif (state !== \"closed\") {\n\t\t\tif (\n\t\t\t\tprobing ||\n\t\t\t\t(state === \"open\" && Date.now() - lastFailureAt < breaker.resetMs)\n\t\t\t) {\n\t\t\t\tthrow new CircuitOpenError();\n\t\t\t}\n\t\t\tstate = \"half-open\";\n\t\t\tprobing = true;\n\t\t\tisProbe = true;\n\t\t}\n\t\ttry {\n\t\t\tconst result = await fn();\n\t\t\tfailures = 0;\n\t\t\tstate = \"closed\";\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tif (isRetryable(error)) {\n\t\t\t\tfailures++;\n\t\t\t\tlastFailureAt = Date.now();\n\t\t\t\tif (failures >= breaker.threshold || isProbe) state = \"open\";\n\t\t\t} else if (isProbe) {\n\t\t\t\t// The backend answered; it's up.\n\t\t\t\tfailures = 0;\n\t\t\t\tstate = \"closed\";\n\t\t\t}\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tif (isProbe) probing = false;\n\t\t}\n\t}\n\n\tasync function run<T>(op: string, key: string, fn: () => Promise<T>) {\n\t\tlet lastError: unknown;\n\t\tfor (let attempt = 0; attempt <= retries; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn await guarded(fn);\n\t\t\t} catch (error) {\n\t\t\t\tlastError = error;\n\t\t\t\tif (error instanceof CircuitOpenError) throw error;\n\t\t\t\tif (!isRetryable(error) || attempt === retries) throw error;\n\t\t\t\tconst base = Math.min(initialDelayMs * 2 ** attempt, maxDelayMs);\n\t\t\t\tconst delayMs = Math.round(base + Math.random() * base * jitter);\n\t\t\t\toptions.onRetry?.({ key, op, attempt: attempt + 1, delayMs });\n\t\t\t\tawait sleep(delayMs);\n\t\t\t}\n\t\t}\n\t\tthrow lastError;\n\t}\n\n\t// Optional methods must be forwarded explicitly: this returns a new object,\n\t// so anything not listed here is dropped — and a dropped `getRange` is\n\t// invisible, because callers that want it report \"unknown\" rather than\n\t// failing. `object-size.test.ts` asserts it survives the whole stack.\n\tconst range = store.getRange?.bind(store);\n\n\treturn {\n\t\tget: (key) => run(\"get\", key, () => store.get(key)),\n\t\tput: (key, data) => run(\"put\", key, () => store.put(key, data)),\n\t\tdelete: (key) => run(\"delete\", key, () => store.delete(key)),\n\t\thead: (key) => run(\"head\", key, () => store.head(key)),\n\t\tlist: (prefix, listOptions) =>\n\t\t\trun(\"list\", prefix, () => store.list(prefix, listOptions)),\n\t\t...(range\n\t\t\t? {\n\t\t\t\t\tgetRange: (key: string, start: number, end: number) =>\n\t\t\t\t\t\trun(\"getRange\", key, () => range(key, start, end)),\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AA8EzB,IAAM,OAAO,uBAAO,MAAM;AAa1B,SAAS,cAAc,OAA0B;AAChD,MAAI,OAAO,MAAM,OAAO,SAAS;AACjC,aAAW,KAAK,MAAM,OAAO,QAAS,SAAQ,EAAE,IAAI,SAAS;AAC7D,aAAW,KAAK,MAAM,OAAO,SAAU,SAAQ,EAAE;AACjD,SAAO;AACR;AAEA,SAAS,eAAe,QAAgC;AACvD,SAAO;AAAA,IACN,SAAS,OAAO,QAAQ,IAAI,CAAC,OAAO,EAAE,GAAG,EAAE,EAAE;AAAA,IAC7C,UAAU,CAAC,GAAG,OAAO,QAAQ;AAAA,EAC9B;AACD;AAaO,SAAS,kBACf,OACA,UAAwB,CAAC,GACL;AACpB,QAAM,WAAW,QAAQ,YAAY,KAAK,OAAO;AACjD,QAAM,gBAAgB,QAAQ,iBAAiB,KAAK,KAAK,WAAW,EAAE;AACtE,QAAM,MAAM,QAAQ,SAAS;AAC7B,QAAM,YAAY,QAAQ;AAC1B,QAAM,cAAc,QAAQ,eAAe;AAC3C,QAAM,aAAa,QAAQ,cAAc;AACzC,QAAM,QAAQ,MAAM,UAAU,KAAK,KAAK;AACxC,QAAM,WAAW,QAAQ,YAAY;AACrC,QAAM,OAAO,QAAQ,QAAQ;AAC7B,QAAM,QAAQ,CAAC,SAAsB,OAAO,KAAK,MAAM,IAAI;AAC3D,QAAM,QAAQ,QAAQ;AACtB,QAAM,SAAS,QAAQ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AQ,IAAI,UAAU,KAAK,MAAM,MAAM,OAAO,GAAG,CAAC;AAAA,IAC3D,MAAM,CAAC,QAAQ,IAAI,QAAQ,KAAK,MAAM,MAAM,KAAK,GAAG,CAAC;AAAA,IACrD,MAAM,CAAC,QAAQ,gBACd,IAAI,QAAQ,QAAQ,MAAM,MAAM,KAAK,QAAQ,WAAW,CAAC;AAAA,IAC1D,GAAI,QACD;AAAA,MACA,UAAU,CAAC,KAAa,OAAe,QACtC,IAAI,YAAY,KAAK,MAAM,MAAM,KAAK,OAAO,GAAG,CAAC;AAAA,IACnD,IACC,CAAC;AAAA,EACL;AACD;","names":["LRUCache","toKey","LRUCache","toKey"]}
1
+ {"version":3,"file":"index.js","names":["toKey","toKeyWithPrefix"],"sources":["../src/cache.ts","../src/errors.ts","../src/path.ts","../src/git-fs.ts","../src/prefix.ts","../src/retry.ts"],"sourcesContent":["import { LRUCache } from \"lru-cache\";\nimport type {\n\tListOptions,\n\tListResult,\n\tObjectStat,\n\tObjectStore,\n} from \"./types.js\";\n\nexport interface CacheOptions {\n\t/** Maximum bytes of object data held in memory. Default 50 MiB. */\n\tmaxBytes?: number;\n\t/**\n\t * Largest single entry admitted to the cache. Defaults to a tenth of\n\t * `maxBytes` so one huge packfile cannot evict the whole working set.\n\t */\n\tmaxEntryBytes?: number;\n\t/**\n\t * Largest range read (`getRange`) admitted to the cache, in bytes. A range\n\t * read is a slice of a pack at a known offset: a header probe, or a small\n\t * object's bytes. Slices up to this size are cached; larger slices always\n\t * go to the backing store so a big blob cannot churn the cache. Range\n\t * entries have their own LRU, capped at a quarter of `maxBytes`. Default\n\t * 64 KiB; 0 disables range caching.\n\t */\n\tmaxRangeBytes?: number;\n\t/** Entry time-to-live in milliseconds. Default 60 000. */\n\tttlMs?: number;\n\t/**\n\t * Override the TTL for a specific key (get/head) or list prefix (list),\n\t * in milliseconds. Return `undefined` to fall back to `ttlMs`. Git refs\n\t * (`refs/heads/<branch>`, `HEAD`) are mutable — the same key's value\n\t * changes on every push — unlike content-addressed object keys, which\n\t * never change for a given key and are safe to cache for the full\n\t * `ttlMs`. Without this, a long `ttlMs` tuned for objects also caches\n\t * ref reads that long, so a warm process can keep serving a\n\t * pre-push ref value for the rest of that TTL even though nothing\n\t * changed *this* process's own cache (see `invalidate`) — it just never\n\t * knew to. Give ref-like keys a short override (a few seconds) instead:\n\t * a ref read is one small object, so re-reading it far more often than\n\t * `ttlMs` is cheap, and every read downstream of a fresh ref (tree,\n\t * commit, blob — all keyed by the sha it resolves to) still gets the\n\t * full-length cache/coalescing benefit.\n\t */\n\tttlForKey?: (key: string) => number | undefined;\n\t/**\n\t * Also cache \"key does not exist\" results. Loose-object probes on packed\n\t * repositories are almost always misses, so this saves many round trips —\n\t * but only enable it when a single process is the only writer, otherwise\n\t * another instance's push can be masked for up to `ttlMs`.\n\t */\n\tcacheMisses?: boolean;\n\t/**\n\t * Also cache `list()` results (directory listings and `limit: 1`\n\t * existence probes). Writes through this store keep cached listings\n\t * consistent; after writing to the backend by any other means, call\n\t * `invalidate()` with the affected prefix. Default false.\n\t */\n\tcacheLists?: boolean;\n\t/**\n\t * Collapse concurrent `get`/`head`/`list` calls for the same key into a\n\t * single backend request. Default true.\n\t */\n\tcoalesce?: boolean;\n\t/**\n\t * Return defensive copies from `get` (and copy on admit), so a caller\n\t * mutating returned bytes can't corrupt the cache. Default true. Set\n\t * false when no reader mutates results (isomorphic-git doesn't): every\n\t * hit otherwise copies the whole entry, which for packfiles is megabytes\n\t * per read.\n\t */\n\tcopy?: boolean;\n\t/** Called when a read is answered from cache. */\n\tonHit?: (key: string) => void;\n\t/** Called when a read has to go to the backing store. */\n\tonMiss?: (key: string) => void;\n}\n\n/** An {@link ObjectStore} wrapper that also supports explicit invalidation. */\nexport interface CachedObjectStore extends ObjectStore {\n\t/**\n\t * Drop every cached entry — contents, misses, and listings — whose key\n\t * falls under `prefix` (exact keys included). Call this after the backing\n\t * store was modified by something other than this wrapper.\n\t */\n\tinvalidate(prefix: string): void;\n}\n\nconst MISS = Symbol(\"miss\");\ntype CacheEntry = Uint8Array | typeof MISS;\n\ninterface ListEntry {\n\tresult: ListResult;\n\t/** The raw list prefix this entry describes. */\n\tprefix: string;\n\t/** True for `limit: 1` existence probes. */\n\tprobe: boolean;\n\t/** True when the listing came back with no objects or prefixes. */\n\tempty: boolean;\n}\n\nfunction listEntrySize(entry: ListEntry): number {\n\tlet size = entry.prefix.length + 16;\n\tfor (const o of entry.result.objects) size += o.key.length + 8;\n\tfor (const p of entry.result.prefixes) size += p.length;\n\treturn size;\n}\n\nfunction copyListResult(result: ListResult): ListResult {\n\treturn {\n\t\tobjects: result.objects.map((o) => ({ ...o })),\n\t\tprefixes: [...result.prefixes],\n\t};\n}\n\n/**\n * Wrap an {@link ObjectStore} with an in-process LRU read cache.\n *\n * Git object keys are content-addressed and therefore immutable, which makes\n * them ideal cache entries; mutable keys (refs, packed-refs) are bounded by\n * `ttlMs`. Writes and deletes through this wrapper invalidate their key and\n * any cached listings they affect — with one asymmetry: a non-empty `limit: 1`\n * probe (a \"directory exists\" answer) survives writes underneath it, because\n * adding a key below a prefix cannot make that prefix stop existing, while\n * empty probes and full listings are always dropped.\n */\nexport function createCachedStore(\n\tstore: ObjectStore,\n\toptions: CacheOptions = {},\n): CachedObjectStore {\n\tconst maxBytes = options.maxBytes ?? 50 * 1024 * 1024;\n\tconst maxEntryBytes = options.maxEntryBytes ?? Math.ceil(maxBytes / 10);\n\tconst ttl = options.ttlMs ?? 60_000;\n\tconst ttlForKey = options.ttlForKey;\n\tconst cacheMisses = options.cacheMisses ?? false;\n\tconst cacheLists = options.cacheLists ?? false;\n\tconst range = store.getRange?.bind(store);\n\tconst maxRangeBytes = options.maxRangeBytes ?? 64 * 1024;\n\tconst coalesce = options.coalesce ?? true;\n\tconst copy = options.copy ?? true;\n\tconst clone = (data: Uint8Array) => (copy ? data.slice() : data);\n\tconst onHit = options.onHit;\n\tconst onMiss = options.onMiss;\n\n\tconst cache = new LRUCache<string, CacheEntry>({\n\t\tmaxSize: maxBytes,\n\t\tsizeCalculation: (value) => (value === MISS ? 1 : value.byteLength || 1),\n\t\tttl,\n\t});\n\tconst listCache = new LRUCache<string, ListEntry>({\n\t\tmaxSize: Math.max(1, Math.ceil(maxBytes / 10)),\n\t\tsizeCalculation: listEntrySize,\n\t\tttl,\n\t});\n\n\t// Range slices, keyed `${key}\\0${start}\\0${end}`. Separate from `cache`\n\t// because a slice is not the whole object: `get`/`head` must never see it.\n\t// `rangeKeysByObject` indexes them by object key so a write to one object\n\t// drops only that object's slices; `dispose` keeps it in step with LRU\n\t// eviction and TTL expiry.\n\tconst rangeKeysByObject = new Map<string, Set<string>>();\n\tconst rangeCache = new LRUCache<string, Uint8Array>({\n\t\tmaxSize: Math.max(1, Math.ceil(maxBytes / 4)),\n\t\tsizeCalculation: (value) => value.byteLength || 1,\n\t\tttl,\n\t\tdispose: (_value, rangeKey) => {\n\t\t\tconst key = rangeKey.slice(0, rangeKey.indexOf(\"\\0\"));\n\t\t\tconst keys = rangeKeysByObject.get(key);\n\t\t\tif (keys?.delete(rangeKey) && keys.size === 0) {\n\t\t\t\trangeKeysByObject.delete(key);\n\t\t\t}\n\t\t},\n\t});\n\tconst pendingRanges = new Map<string, Promise<Uint8Array | null>>();\n\tconst rangePrefix = (key: string) => `${key}\\0`;\n\tconst admitRange = (key: string, rangeKey: string, data: Uint8Array) => {\n\t\trangeCache.set(rangeKey, clone(data), { ttl: ttlForKey?.(key) });\n\t\t// lru-cache silently rejects an entry larger than maxSize, without\n\t\t// calling `dispose`; indexing it would leak.\n\t\tif (!rangeCache.has(rangeKey)) return;\n\t\tconst keys = rangeKeysByObject.get(key) ?? new Set<string>();\n\t\tkeys.add(rangeKey);\n\t\trangeKeysByObject.set(key, keys);\n\t};\n\tconst pendingRangeObjects = () =>\n\t\t[...pendingRanges.keys()].map((k) => k.slice(0, k.indexOf(\"\\0\")));\n\t/** Drop every slice (cached or in flight) of the object at `key`. */\n\tconst dropRanges = (key: string) => {\n\t\tfor (const rangeKey of [...(rangeKeysByObject.get(key) ?? [])]) {\n\t\t\trangeCache.delete(rangeKey);\n\t\t}\n\t\tconst prefix = rangePrefix(key);\n\t\tfor (const rangeKey of [...pendingRanges.keys()]) {\n\t\t\tif (rangeKey.startsWith(prefix)) pendingRanges.delete(rangeKey);\n\t\t}\n\t};\n\n\tconst pendingGets = new Map<string, Promise<Uint8Array | null>>();\n\tconst pendingHeads = new Map<string, Promise<ObjectStat | null>>();\n\tconst pendingLists = new Map<string, Promise<ListResult>>();\n\n\t/**\n\t * Bumped by every write, delete and invalidation. A backend read that\n\t * started before one of those may finish after it carrying the old answer\n\t * (the old bytes, or \"missing\" for a key that now exists); it still\n\t * answers its own callers, but only a read that saw no write in between\n\t * may populate the cache — otherwise a stale miss could hide a freshly\n\t * written object for the whole TTL.\n\t */\n\tlet generation = 0;\n\tconst unchangedSince = (start: number) => generation === start;\n\n\tconst admit = (key: string, data: Uint8Array) => {\n\t\tif (data.byteLength <= maxEntryBytes) {\n\t\t\tcache.set(key, clone(data), { ttl: ttlForKey?.(key) });\n\t\t}\n\t};\n\n\t/** Drop list entries a write/delete at `key` may have made stale. */\n\tfunction clearStaleListEntries(key: string): void {\n\t\tfor (const [listKey, entry] of listCache.entries()) {\n\t\t\tif (!key.startsWith(entry.prefix)) continue;\n\t\t\tif (entry.probe && !entry.empty) continue;\n\t\t\tlistCache.delete(listKey);\n\t\t}\n\t\t// Readers arriving after this write must not join a listing that\n\t\t// started before it.\n\t\tfor (const listKey of pendingLists.keys()) {\n\t\t\tconst prefix = listKey.split(\"|\").slice(2).join(\"|\");\n\t\t\tif (key.startsWith(prefix)) pendingLists.delete(listKey);\n\t\t}\n\t}\n\n\t/** A write to `key` happened: no in-flight read of it may be joined or cached. */\n\tfunction noteWrite(key: string): void {\n\t\tgeneration++;\n\t\tpendingGets.delete(key);\n\t\tpendingHeads.delete(key);\n\t\tdropRanges(key);\n\t}\n\n\tfunction coalesced<T>(\n\t\tpending: Map<string, Promise<T>>,\n\t\tkey: string,\n\t\tfn: () => Promise<T>,\n\t): Promise<T> {\n\t\tif (!coalesce) return fn();\n\t\tconst inflight = pending.get(key);\n\t\tif (inflight !== undefined) return inflight;\n\t\tconst p = fn().finally(() => {\n\t\t\tif (pending.get(key) === p) pending.delete(key);\n\t\t});\n\t\tpending.set(key, p);\n\t\treturn p;\n\t}\n\n\treturn {\n\t\tasync get(key: string): Promise<Uint8Array | null> {\n\t\t\tconst cached = cache.get(key);\n\t\t\tif (cached !== undefined) {\n\t\t\t\tonHit?.(key);\n\t\t\t\treturn cached === MISS ? null : clone(cached);\n\t\t\t}\n\t\t\tconst data = await coalesced(pendingGets, key, async () => {\n\t\t\t\tonMiss?.(key);\n\t\t\t\tconst start = generation;\n\t\t\t\tconst fetched = await store.get(key);\n\t\t\t\tif (unchangedSince(start)) {\n\t\t\t\t\tif (fetched !== null) {\n\t\t\t\t\t\tadmit(key, fetched);\n\t\t\t\t\t} else if (cacheMisses) {\n\t\t\t\t\t\tcache.set(key, MISS, { ttl: ttlForKey?.(key) });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn fetched;\n\t\t\t});\n\t\t\treturn data === null ? null : clone(data);\n\t\t},\n\n\t\tasync put(key: string, data: Uint8Array): Promise<void> {\n\t\t\tnoteWrite(key);\n\t\t\ttry {\n\t\t\t\tawait store.put(key, data);\n\t\t\t} finally {\n\t\t\t\t// Even a failed put may have landed; never keep serving the\n\t\t\t\t// pre-write answer for this key.\n\t\t\t\tnoteWrite(key);\n\t\t\t\tcache.delete(key);\n\t\t\t\tclearStaleListEntries(key);\n\t\t\t}\n\t\t\tadmit(key, data);\n\t\t},\n\n\t\tasync delete(key: string): Promise<void> {\n\t\t\tnoteWrite(key);\n\t\t\ttry {\n\t\t\t\tawait store.delete(key);\n\t\t\t} finally {\n\t\t\t\tnoteWrite(key);\n\t\t\t\tcache.delete(key);\n\t\t\t\tclearStaleListEntries(key);\n\t\t\t}\n\t\t\tif (cacheMisses) {\n\t\t\t\tcache.set(key, MISS, { ttl: ttlForKey?.(key) });\n\t\t\t} else {\n\t\t\t\tcache.delete(key);\n\t\t\t}\n\t\t},\n\n\t\tasync head(key: string): Promise<ObjectStat | null> {\n\t\t\tconst cached = cache.get(key);\n\t\t\tif (cached !== undefined) {\n\t\t\t\tonHit?.(key);\n\t\t\t\treturn cached === MISS ? null : { size: cached.byteLength };\n\t\t\t}\n\t\t\treturn coalesced(pendingHeads, key, async () => {\n\t\t\t\tonMiss?.(key);\n\t\t\t\tconst start = generation;\n\t\t\t\tconst stat = await store.head(key);\n\t\t\t\tif (stat === null && cacheMisses && unchangedSince(start)) {\n\t\t\t\t\tcache.set(key, MISS, { ttl: ttlForKey?.(key) });\n\t\t\t\t}\n\t\t\t\treturn stat;\n\t\t\t});\n\t\t},\n\n\t\tasync list(prefix: string, listOptions?: ListOptions): Promise<ListResult> {\n\t\t\tif (!cacheLists) return store.list(prefix, listOptions);\n\t\t\tconst listKey = `${listOptions?.delimiter ?? \"\"}|${listOptions?.limit ?? \"\"}|${prefix}`;\n\t\t\tconst cached = listCache.get(listKey);\n\t\t\tif (cached !== undefined) {\n\t\t\t\tonHit?.(prefix);\n\t\t\t\treturn copyListResult(cached.result);\n\t\t\t}\n\t\t\tconst result = await coalesced(pendingLists, listKey, async () => {\n\t\t\t\tonMiss?.(prefix);\n\t\t\t\tconst start = generation;\n\t\t\t\tconst fetched = await store.list(prefix, listOptions);\n\t\t\t\tif (!unchangedSince(start)) return fetched;\n\t\t\t\tlistCache.set(\n\t\t\t\t\tlistKey,\n\t\t\t\t\t{\n\t\t\t\t\t\tresult: copyListResult(fetched),\n\t\t\t\t\t\tprefix,\n\t\t\t\t\t\tprobe: listOptions?.limit === 1,\n\t\t\t\t\t\tempty:\n\t\t\t\t\t\t\tfetched.objects.length === 0 && fetched.prefixes.length === 0,\n\t\t\t\t\t},\n\t\t\t\t\t{ ttl: ttlForKey?.(prefix) },\n\t\t\t\t);\n\t\t\t\treturn fetched;\n\t\t\t});\n\t\t\treturn copyListResult(result);\n\t\t},\n\n\t\t// Small slices are cached (see `maxRangeBytes`); larger ones go straight\n\t\t// to the backing store.\n\t\t...(range\n\t\t\t? {\n\t\t\t\t\tasync getRange(\n\t\t\t\t\t\tkey: string,\n\t\t\t\t\t\tstart: number,\n\t\t\t\t\t\tend: number,\n\t\t\t\t\t): Promise<Uint8Array | null> {\n\t\t\t\t\t\tif (end - start + 1 > maxRangeBytes) return range(key, start, end);\n\t\t\t\t\t\tconst rangeKey = `${rangePrefix(key)}${start}\\0${end}`;\n\t\t\t\t\t\tconst cached = rangeCache.get(rangeKey);\n\t\t\t\t\t\tif (cached !== undefined) {\n\t\t\t\t\t\t\tonHit?.(key);\n\t\t\t\t\t\t\treturn clone(cached);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst data = await coalesced(pendingRanges, rangeKey, async () => {\n\t\t\t\t\t\t\tonMiss?.(key);\n\t\t\t\t\t\t\tconst gen = generation;\n\t\t\t\t\t\t\tconst fetched = await range(key, start, end);\n\t\t\t\t\t\t\tif (fetched !== null && unchangedSince(gen)) {\n\t\t\t\t\t\t\t\tadmitRange(key, rangeKey, fetched);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn fetched;\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn data === null ? null : clone(data);\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\n\t\tinvalidate(prefix: string): void {\n\t\t\tgeneration++;\n\t\t\tfor (const key of [\n\t\t\t\t...rangeKeysByObject.keys(),\n\t\t\t\t...pendingRangeObjects(),\n\t\t\t]) {\n\t\t\t\tif (key.startsWith(prefix)) dropRanges(key);\n\t\t\t}\n\t\t\tfor (const key of [...pendingGets.keys()]) {\n\t\t\t\tif (key.startsWith(prefix)) pendingGets.delete(key);\n\t\t\t}\n\t\t\tfor (const key of [...pendingHeads.keys()]) {\n\t\t\t\tif (key.startsWith(prefix)) pendingHeads.delete(key);\n\t\t\t}\n\t\t\tpendingLists.clear();\n\t\t\tfor (const key of cache.keys()) {\n\t\t\t\tif (key.startsWith(prefix)) cache.delete(key);\n\t\t\t}\n\t\t\tfor (const [listKey, entry] of listCache.entries()) {\n\t\t\t\tif (\n\t\t\t\t\tentry.prefix.startsWith(prefix) ||\n\t\t\t\t\tprefix.startsWith(entry.prefix)\n\t\t\t\t) {\n\t\t\t\t\tlistCache.delete(listKey);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t};\n}\n","/**\n * Node-style filesystem error carrying a `code` property, which is what\n * isomorphic-git inspects to distinguish \"file not found\" from real failures.\n */\nexport class FsError extends Error {\n\treadonly code: string;\n\treadonly syscall: string;\n\treadonly path: string;\n\n\tconstructor(code: string, syscall: string, path: string) {\n\t\tsuper(`${code}: ${syscall} '${path}'`);\n\t\tthis.name = \"FsError\";\n\t\tthis.code = code;\n\t\tthis.syscall = syscall;\n\t\tthis.path = path;\n\t}\n}\n\nexport const enoent = (syscall: string, path: string) =>\n\tnew FsError(\"ENOENT\", syscall, path);\n\nexport const enotdir = (syscall: string, path: string) =>\n\tnew FsError(\"ENOTDIR\", syscall, path);\n\nexport const enotempty = (syscall: string, path: string) =>\n\tnew FsError(\"ENOTEMPTY\", syscall, path);\n\nexport const einval = (syscall: string, path: string) =>\n\tnew FsError(\"EINVAL\", syscall, path);\n\nexport const eperm = (syscall: string, path: string) =>\n\tnew FsError(\"EPERM\", syscall, path);\n","import { einval } from \"./errors.js\";\n\n/**\n * Normalize an absolute-or-relative filesystem path into a storage key\n * segment: no leading/trailing slashes, `.` segments dropped, `..` resolved.\n * A `..` that would escape the root throws EINVAL — paths handed to the fs\n * must never address keys outside the configured prefix.\n */\nexport function normalizePath(filepath: string): string {\n\tconst segments = filepath.split(\"/\");\n\tconst out: string[] = [];\n\tfor (const segment of segments) {\n\t\tif (segment === \"\" || segment === \".\") continue;\n\t\tif (segment === \"..\") {\n\t\t\tif (out.length === 0) throw einval(\"resolve\", filepath);\n\t\t\tout.pop();\n\t\t\tcontinue;\n\t\t}\n\t\tout.push(segment);\n\t}\n\treturn out.join(\"/\");\n}\n\n/** Join a configured key prefix with a normalized path. */\nexport function toKey(prefix: string, filepath: string): string {\n\tconst normalized = normalizePath(filepath);\n\tif (prefix === \"\") return normalized;\n\treturn normalized === \"\" ? prefix : `${prefix}/${normalized}`;\n}\n","import { LRUCache } from \"lru-cache\";\nimport { enoent, enotdir, enotempty, eperm } from \"./errors.js\";\nimport { parseLooseObjectPath } from \"./git-layout.js\";\nimport { parsePackDirectory, READABLE_PACK_FILE_KINDS } from \"./pack-files.js\";\nimport { normalizePath, toKey as toKeyWithPrefix } from \"./path.js\";\nimport type {\n\tEncoding,\n\tGitdirFacts,\n\tGitFsClient,\n\tGitFsOptions,\n\tObjectStore,\n\tReadFileOptions,\n\tStat,\n\tWriteFileOptions,\n} from \"./types.js\";\n\nconst FILE_MODE = 0o100644;\nconst DIR_MODE = 0o40000;\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\nfunction makeStat(type: \"file\" | \"dir\", size: number): Stat {\n\tconst epoch = new Date(0);\n\treturn {\n\t\ttype,\n\t\tmode: type === \"file\" ? FILE_MODE : DIR_MODE,\n\t\tsize,\n\t\tino: 0,\n\t\tmtimeMs: 0,\n\t\tctimeMs: 0,\n\t\tuid: 0,\n\t\tgid: 0,\n\t\tdev: 0,\n\t\tmtime: epoch,\n\t\tctime: epoch,\n\t\tisFile: () => type === \"file\",\n\t\tisDirectory: () => type === \"dir\",\n\t\tisSymbolicLink: () => false,\n\t};\n}\n\nfunction resolveEncoding(\n\toptions?: ReadFileOptions | WriteFileOptions | Encoding,\n): Encoding | undefined {\n\tif (typeof options === \"string\") return options;\n\treturn options?.encoding;\n}\n\n/**\n * The filesystem returned by {@link createGitFs}: the isomorphic-git client\n * plus git-aware maintenance hooks.\n */\nexport interface GitFs extends GitFsClient {\n\t/**\n\t * Return every file below a directory in one object-store listing. Unlike\n\t * `readdir`, this deliberately does not use a delimiter: object storage can\n\t * enumerate a ref namespace recursively without the stat-per-entry walk a\n\t * POSIX filesystem needs to distinguish files from implicit directories.\n\t * Paths are relative to `dirpath` and never include directory entries.\n\t */\n\tlistFilesRecursively(dirpath: string): Promise<string[]>;\n\t/**\n\t * Probe, with one bounded list, whether `gitdir` contains any loose\n\t * objects, and remember the answer. This is the only way a loose-object\n\t * hint is ever created; call it before full-history walks (commit logs,\n\t * reachability traversals) so fully packed repositories skip every\n\t * guaranteed-miss loose-object read. A later loose write flips the hint\n\t * back, so it cannot go stale mid-push.\n\t */\n\tdetectLooseObjects(gitdir: string): Promise<void>;\n\t/**\n\t * Warm the cache with every pack file under `gitdir` in parallel (plus\n\t * the loose-object hint) before a sequential history walk. Skipped when\n\t * the pack directory holds more than `maxPacks * 2` entries — warming\n\t * only helps when the cache budget actually fits the packs.\n\t */\n\tprefetchPacks(gitdir: string, options?: { maxPacks?: number }): Promise<void>;\n\t/**\n\t * Clear fs-level state (loose-object hints) under `pathPrefix`, and\n\t * forward to the store's `invalidate` when it has one. Call after the\n\t * backing store was modified by something other than this fs.\n\t */\n\tinvalidate(pathPrefix: string): void;\n\t/**\n\t * Declare that `gitdir` exists, so `stat` answers \"directory\" for it with\n\t * zero store calls. isomorphic-git stats the gitdir on every command\n\t * (`discoverGitdir`); in object storage that is a HEAD that always misses\n\t * plus a listing. Register once the caller has confirmed the repository\n\t * exists by other means (e.g. its database row); `invalidate` forgets it.\n\t */\n\tregisterGitdir(gitdir: string, facts?: GitdirFacts): void;\n}\n\n/**\n * Create a promise-based filesystem client for isomorphic-git backed by an\n * {@link ObjectStore}.\n *\n * Semantics:\n * - Directories are implicit, as in object storage: `mkdir` is a no-op and a\n * directory \"exists\" whenever at least one key lives under its prefix.\n * - Symbolic links are not supported (`readlink`/`symlink` throw). Bare\n * repositories never contain them.\n * - Designed for bare, server-side repositories (`git.init({bare: true})`,\n * plumbing commands, ref updates). Worktree checkouts belong on a real disk.\n */\nexport function createGitFs(\n\tstore: ObjectStore,\n\toptions: GitFsOptions = {},\n): GitFs {\n\tconst prefix = options.prefix ?? \"\";\n\tconst useLooseHints = options.looseObjectHints ?? false;\n\tconst onNote = options.onNote;\n\n\tconst toKey = (path: string): string => toKeyWithPrefix(prefix, path);\n\n\t/**\n\t * Per-gitdir \"does any loose object exist\" hint. Entries are only created\n\t * by {@link GitFs.detectLooseObjects}, so a pathological ref that merely\n\t * looks like a loose object (`refs/heads/objects/aa/…`) derives a scope\n\t * that was never registered and can never be wrongly short-circuited.\n\t */\n\tconst looseHints = new LRUCache<string, \"none\" | \"present\">({\n\t\tmax: 1024,\n\t\tttl: options.hintTtlMs ?? 3_600_000,\n\t});\n\n\t/** Gitdirs the caller vouched for via {@link GitFs.registerGitdir}. */\n\tconst registeredGitdirs = new LRUCache<string, ReadonlySet<string>>({\n\t\tmax: 4096,\n\t});\n\n\t/** Whether `path` is a top-level file its registered gitdir lacks. */\n\tfunction registeredAbsent(path: string): boolean {\n\t\tconst slash = path.lastIndexOf(\"/\");\n\t\tif (slash < 0) return false;\n\t\tconst absent = registeredGitdirs.get(path.slice(0, slash));\n\t\treturn absent?.has(path.slice(slash + 1)) ?? false;\n\t}\n\n\t/** The gitdir scope of a loose-object path, or null when it isn't one. */\n\tfunction looseScope(path: string): string | null {\n\t\treturn parseLooseObjectPath(path)?.gitdir ?? null;\n\t}\n\n\tconst pendingDetections = new Map<string, Promise<void>>();\n\n\t/**\n\t * Resolve the loose-object hint for `path`'s gitdir before answering, so a\n\t * read that runs before any explicit `detectLooseObjects` call (e.g. the\n\t * first commit read of a request) doesn't pay a doomed GET. One coalesced\n\t * listing per gitdir, cached for `hintTtlMs`.\n\t */\n\tasync function knownAbsent(path: string): Promise<boolean> {\n\t\tif (registeredAbsent(path)) return true;\n\t\tif (!useLooseHints) return false;\n\t\tconst scope = looseScope(path);\n\t\tif (scope === null) return false;\n\t\tif (!looseHints.has(scope)) {\n\t\t\tlet pending = pendingDetections.get(scope);\n\t\t\tif (!pending) {\n\t\t\t\tpending = detectLooseObjects(scope).finally(() =>\n\t\t\t\t\tpendingDetections.delete(scope),\n\t\t\t\t);\n\t\t\t\tpendingDetections.set(scope, pending);\n\t\t\t}\n\t\t\tawait pending;\n\t\t}\n\t\treturn looseHints.get(scope) === \"none\";\n\t}\n\n\tasync function isDirectory(dirKey: string): Promise<boolean> {\n\t\tconst { objects, prefixes } = await store.list(`${dirKey}/`, {\n\t\t\tlimit: 1,\n\t\t});\n\t\treturn objects.length > 0 || prefixes.length > 0;\n\t}\n\n\tasync function stat(filepath: string, syscall: string): Promise<Stat> {\n\t\tconst path = normalizePath(filepath);\n\t\tif (await knownAbsent(path)) throw enoent(syscall, filepath);\n\t\tconst k = toKey(path);\n\t\tif (k === prefix || k === \"\" || registeredGitdirs.has(path)) {\n\t\t\treturn makeStat(\"dir\", 0);\n\t\t}\n\t\tconst fileStat = await store.head(k);\n\t\tif (fileStat) return makeStat(\"file\", fileStat.size);\n\t\t// A loose-object path is always a leaf; when the object itself is\n\t\t// absent there is no point probing for a directory of the same name.\n\t\tif (useLooseHints && looseScope(path) !== null) {\n\t\t\tthrow enoent(syscall, filepath);\n\t\t}\n\t\tif (await isDirectory(k)) return makeStat(\"dir\", 0);\n\t\tthrow enoent(syscall, filepath);\n\t}\n\n\tconst range = store.getRange?.bind(store);\n\n\tconst promises: GitFsClient[\"promises\"] = {\n\t\t// Only defined when the backing store supports ranges, so a caller can\n\t\t// test for it rather than have to interpret a failure.\n\t\t...(range\n\t\t\t? {\n\t\t\t\t\tgetRange: (filepath: string, start: number, end: number) =>\n\t\t\t\t\t\trange(toKey(normalizePath(filepath)), start, end),\n\t\t\t\t}\n\t\t\t: {}),\n\n\t\tasync readFile(filepath, opts) {\n\t\t\tconst path = normalizePath(filepath);\n\t\t\tif (await knownAbsent(path)) throw enoent(\"open\", filepath);\n\t\t\tconst data = await store.get(toKey(path));\n\t\t\tif (data === null) throw enoent(\"open\", filepath);\n\t\t\treturn resolveEncoding(opts) === \"utf8\" ? textDecoder.decode(data) : data;\n\t\t},\n\n\t\tasync writeFile(filepath, data, _opts) {\n\t\t\tconst path = normalizePath(filepath);\n\t\t\tif (useLooseHints) {\n\t\t\t\tconst scope = looseScope(path);\n\t\t\t\t// Flip before the write lands so a racing read can never\n\t\t\t\t// short-circuit an object that is in the middle of arriving.\n\t\t\t\tif (scope !== null) looseHints.set(scope, \"present\");\n\t\t\t}\n\t\t\tconst bytes = typeof data === \"string\" ? textEncoder.encode(data) : data;\n\t\t\tawait store.put(toKey(path), bytes);\n\t\t},\n\n\t\tasync unlink(filepath) {\n\t\t\tconst k = toKey(normalizePath(filepath));\n\t\t\tif ((await store.head(k)) === null) throw enoent(\"unlink\", filepath);\n\t\t\tawait store.delete(k);\n\t\t},\n\n\t\tasync readdir(dirpath) {\n\t\t\tconst k = toKey(normalizePath(dirpath));\n\t\t\tconst isRoot = k === prefix || k === \"\";\n\t\t\tconst listPrefix = isRoot && k === \"\" ? \"\" : `${k}/`;\n\t\t\tconst { objects, prefixes } = await store.list(listPrefix, {\n\t\t\t\tdelimiter: \"/\",\n\t\t\t});\n\t\t\tif (objects.length === 0 && prefixes.length === 0) {\n\t\t\t\tif (!isRoot && (await store.head(k)) !== null) {\n\t\t\t\t\tthrow enotdir(\"scandir\", dirpath);\n\t\t\t\t}\n\t\t\t\tif (!isRoot) throw enoent(\"scandir\", dirpath);\n\t\t\t}\n\t\t\tconst names = objects.map((o) => o.key.slice(listPrefix.length));\n\t\t\tconst dirNames = prefixes.map((p) =>\n\t\t\t\tp.slice(listPrefix.length).replace(/\\/$/, \"\"),\n\t\t\t);\n\t\t\treturn [...names, ...dirNames].sort();\n\t\t},\n\n\t\tasync mkdir(_dirpath, _opts) {\n\t\t\t// Directories are implicit in object storage.\n\t\t},\n\n\t\tasync rmdir(dirpath) {\n\t\t\tconst k = toKey(normalizePath(dirpath));\n\t\t\tconst { objects, prefixes } = await store.list(`${k}/`, { limit: 1 });\n\t\t\tif (objects.length > 0 || prefixes.length > 0) {\n\t\t\t\tthrow enotempty(\"rmdir\", dirpath);\n\t\t\t}\n\t\t\t// Empty implicit directories don't exist; nothing to remove.\n\t\t},\n\n\t\tstat: (filepath) => stat(filepath, \"stat\"),\n\t\tlstat: (filepath) => stat(filepath, \"lstat\"),\n\n\t\tasync readlink(filepath): Promise<never> {\n\t\t\tthrow enoent(\"readlink\", filepath);\n\t\t},\n\n\t\tasync symlink(_target, filepath): Promise<never> {\n\t\t\tthrow eperm(\"symlink\", filepath);\n\t\t},\n\n\t\tasync chmod(_filepath, _mode) {\n\t\t\t// POSIX modes don't exist in object storage.\n\t\t},\n\t};\n\n\tasync function detectLooseObjects(gitdir: string): Promise<void> {\n\t\tif (!useLooseHints) return;\n\t\tconst scope = normalizePath(gitdir);\n\t\t// A live hint must win over re-detection: after a loose write flips it\n\t\t// to \"present\", re-deriving from a (possibly cached, pre-write) listing\n\t\t// could wrongly reinstate \"none\" and mask real objects.\n\t\tif (looseHints.has(scope)) return;\n\t\ttry {\n\t\t\tconst { objects } = await store.list(`${toKey(scope)}/objects/`, {\n\t\t\t\tlimit: 1,\n\t\t\t});\n\t\t\t// Loose fan-out directories (two hex digits) sort before \"info/\"\n\t\t\t// and \"pack/\", so when any loose object exists it is the first key.\n\t\t\tconst first = objects[0]?.key;\n\t\t\tconst hint =\n\t\t\t\tfirst !== undefined && parseLooseObjectPath(first) !== null\n\t\t\t\t\t? \"present\"\n\t\t\t\t\t: \"none\";\n\t\t\tlooseHints.set(scope, hint);\n\t\t\tonNote?.(`loose objects ${hint} under ${scope}`);\n\t\t} catch {\n\t\t\t// Leave unknown — reads fall back to their normal round trip.\n\t\t}\n\t}\n\n\tasync function prefetchPacks(\n\t\tgitdir: string,\n\t\tprefetchOptions?: { maxPacks?: number },\n\t): Promise<void> {\n\t\tconst maxPacks = prefetchOptions?.maxPacks ?? 30;\n\t\tconst packDir = `${normalizePath(gitdir)}/objects/pack`;\n\t\t// isomorphic-git never reads .bitmap/.rev/.keep, so fetching them is a\n\t\t// wasted GET and wasted cache space.\n\t\tconst entries = parsePackDirectory(\n\t\t\tawait promises.readdir(packDir).catch(() => []),\n\t\t)\n\t\t\t.filter((file) => READABLE_PACK_FILE_KINDS.has(file.kind))\n\t\t\t.map((file) => file.name);\n\t\tif (entries.length > maxPacks * 2) {\n\t\t\tawait detectLooseObjects(gitdir);\n\t\t\treturn;\n\t\t}\n\t\tawait Promise.all([\n\t\t\tdetectLooseObjects(gitdir),\n\t\t\t...entries.map((name) =>\n\t\t\t\tpromises.readFile(`${packDir}/${name}`).catch(() => undefined),\n\t\t\t),\n\t\t]);\n\t}\n\n\tasync function listFilesRecursively(dirpath: string): Promise<string[]> {\n\t\tconst directory = toKey(normalizePath(dirpath));\n\t\tconst listPrefix = directory === \"\" ? \"\" : `${directory}/`;\n\t\tconst { objects } = await store.list(listPrefix);\n\t\treturn objects\n\t\t\t.map((object) => object.key.slice(listPrefix.length))\n\t\t\t.filter((path) => path.length > 0)\n\t\t\t.sort();\n\t}\n\n\tfunction registerGitdir(gitdir: string, facts?: GitdirFacts): void {\n\t\tregisteredGitdirs.set(\n\t\t\tnormalizePath(gitdir),\n\t\t\tnew Set(facts?.absentFiles ?? []),\n\t\t);\n\t}\n\n\tfunction invalidate(pathPrefix: string): void {\n\t\tconst normalized = normalizePath(pathPrefix);\n\t\tfor (const dir of registeredGitdirs.keys()) {\n\t\t\tif (dir.startsWith(normalized)) registeredGitdirs.delete(dir);\n\t\t}\n\t\tfor (const scope of looseHints.keys()) {\n\t\t\tif (scope.startsWith(normalized)) looseHints.delete(scope);\n\t\t}\n\t\tconst maybe = store as ObjectStore & {\n\t\t\tinvalidate?: (prefix: string) => void;\n\t\t};\n\t\tmaybe.invalidate?.(toKey(normalized));\n\t}\n\n\treturn {\n\t\tpromises,\n\t\tlistFilesRecursively,\n\t\tdetectLooseObjects,\n\t\tprefetchPacks,\n\t\tinvalidate,\n\t\tregisterGitdir,\n\t};\n}\n","import type { ObjectStore } from \"./types.js\";\n\nconst BATCH = 20;\n\nasync function inBatches<T>(\n\titems: T[],\n\tfn: (item: T) => Promise<void>,\n): Promise<void> {\n\tfor (let i = 0; i < items.length; i += BATCH) {\n\t\tawait Promise.all(items.slice(i, i + BATCH).map(fn));\n\t}\n}\n\n/**\n * Delete every object under `prefix` (one paginated LIST, then batched\n * deletes). Returns the number of objects deleted. Callers serialise against\n * concurrent writers (e.g. a repository lock) and invalidate any cache\n * layered above `store`.\n */\nexport async function deletePrefix(\n\tstore: ObjectStore,\n\tprefix: string,\n): Promise<number> {\n\tconst { objects } = await store.list(prefix);\n\tawait inBatches(objects, (object) => store.delete(object.key));\n\treturn objects.length;\n}\n\nexport interface MovePrefixOptions {\n\t/**\n\t * Copy one object, e.g. a store's server-side `copy` (no bytes pass through\n\t * this process). Defaults to `get` + `put` on `store`.\n\t */\n\tcopy?: (fromKey: string, toKey: string) => Promise<void>;\n}\n\n/**\n * Move every object under `from` to the same relative key under `to`: copy\n * everything first, then delete the old keys only once every copy succeeded,\n * so a failed copy leaves the source untouched (a partial destination may\n * remain; call {@link deletePrefix} on it to clean up). Returns the number of\n * objects moved. `from` and `to` must not overlap.\n */\nexport async function movePrefix(\n\tstore: ObjectStore,\n\tfrom: string,\n\tto: string,\n\toptions: MovePrefixOptions = {},\n): Promise<number> {\n\tif (from.startsWith(to) || to.startsWith(from)) {\n\t\tthrow new Error(`movePrefix: prefixes overlap (${from} -> ${to})`);\n\t}\n\tconst copy =\n\t\toptions.copy ??\n\t\t(async (fromKey: string, toKey: string) => {\n\t\t\tconst data = await store.get(fromKey);\n\t\t\tif (data) await store.put(toKey, data);\n\t\t});\n\tconst { objects } = await store.list(from);\n\tawait inBatches(objects, (object) =>\n\t\tcopy(object.key, to + object.key.slice(from.length)),\n\t);\n\tawait inBatches(objects, (object) => store.delete(object.key));\n\treturn objects.length;\n}\n","import type { ObjectStore } from \"./types.js\";\n\n/** Options accepted by {@link createRetryStore}. */\nexport interface RetryOptions {\n\t/** Retries after the first attempt (total attempts = retries + 1). Default 3. */\n\tretries?: number;\n\t/** Backoff base delay in milliseconds, doubled each attempt. Default 100. */\n\tinitialDelayMs?: number;\n\t/** Upper bound for the backoff base delay. Default 5000. */\n\tmaxDelayMs?: number;\n\t/** Random jitter added to each delay, as a fraction of it. Default 0.3. */\n\tjitter?: number;\n\t/**\n\t * Decide whether an error is worth retrying. The store contract maps\n\t * \"not found\" to `null` rather than throwing, so any thrown error is a\n\t * genuine failure; the default retries network faults, throttling, and\n\t * HTTP 5xx responses.\n\t */\n\tisRetryable?: (error: unknown) => boolean;\n\t/**\n\t * Circuit breaker configuration, or `false` to disable. After `threshold`\n\t * consecutive failures the store fails fast for `resetMs`, then lets one\n\t * request probe the backend again. Defaults: 5 failures, 30 000 ms.\n\t */\n\tbreaker?: false | { threshold?: number; resetMs?: number };\n\t/** Called before each retry sleep; useful for logging/metrics. */\n\tonRetry?: (info: {\n\t\tkey: string;\n\t\top: string;\n\t\tattempt: number;\n\t\tdelayMs: number;\n\t}) => void;\n}\n\n/**\n * Thrown instead of calling the backend while the circuit breaker is open.\n * Carries `code: \"EUNAVAILABLE\"` so callers can map it to a 503.\n */\nexport class CircuitOpenError extends Error {\n\treadonly code = \"EUNAVAILABLE\";\n\n\tconstructor() {\n\t\tsuper(\"Circuit breaker is open, object store unavailable\");\n\t\tthis.name = \"CircuitOpenError\";\n\t}\n}\n\nconst RETRYABLE_NAMES = new Set([\n\t\"TimeoutError\",\n\t\"RequestTimeout\",\n\t\"RequestTimeoutException\",\n\t\"SlowDown\",\n\t\"ThrottlingException\",\n\t\"TooManyRequestsException\",\n]);\n\nconst RETRYABLE_CODES = new Set([\n\t\"ECONNRESET\",\n\t\"ECONNREFUSED\",\n\t\"EPIPE\",\n\t\"ETIMEDOUT\",\n\t\"ENOTFOUND\",\n\t\"EAI_AGAIN\",\n\t\"EPROTO\",\n]);\n\n/**\n * The default retry classifier: network faults, timeouts, throttling and HTTP\n * 5xx/429 (including `$metadata.httpStatusCode`-shaped errors). `fetch`\n * reports a dropped connection as a bare `TypeError`, which counts too.\n * Compose it in a custom `isRetryable`.\n */\nexport function isRetryableError(error: unknown): boolean {\n\tif (error instanceof TypeError) return true;\n\tif (typeof error !== \"object\" || error === null) return false;\n\tconst err = error as {\n\t\tname?: string;\n\t\tcode?: string;\n\t\t$metadata?: { httpStatusCode?: number };\n\t};\n\tif (err.name !== undefined && RETRYABLE_NAMES.has(err.name)) return true;\n\tif (err.code !== undefined && RETRYABLE_CODES.has(err.code)) return true;\n\tconst status = err.$metadata?.httpStatusCode;\n\treturn status !== undefined && (status >= 500 || status === 429);\n}\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Wrap an {@link ObjectStore} with retries (exponential backoff + jitter) and\n * an optional per-instance circuit breaker.\n *\n * Place this decorator closest to the network store, underneath any cache:\n * the cache then never stores transient failures, and callers coalesced onto\n * one request share a single retried attempt.\n */\nexport function createRetryStore(\n\tstore: ObjectStore,\n\toptions: RetryOptions = {},\n): ObjectStore {\n\tconst retries = options.retries ?? 3;\n\tconst initialDelayMs = options.initialDelayMs ?? 100;\n\tconst maxDelayMs = options.maxDelayMs ?? 5000;\n\tconst jitter = options.jitter ?? 0.3;\n\tconst isRetryable = options.isRetryable ?? isRetryableError;\n\tconst breaker =\n\t\toptions.breaker === false\n\t\t\t? null\n\t\t\t: {\n\t\t\t\t\tthreshold: options.breaker?.threshold ?? 5,\n\t\t\t\t\tresetMs: options.breaker?.resetMs ?? 30_000,\n\t\t\t\t};\n\n\tlet failures = 0;\n\tlet lastFailureAt = 0;\n\tlet state: \"closed\" | \"open\" | \"half-open\" = \"closed\";\n\tlet probing = false;\n\n\t/**\n\t * Consecutive transient failures open the circuit; any success closes it\n\t * and resets the count. Non-retryable errors (a 403, a malformed request)\n\t * say nothing about the backend's health and never count. Once the reset\n\t * window passes, exactly one request probes the backend (half-open);\n\t * everything else keeps failing fast until that probe settles.\n\t */\n\tasync function guarded<T>(fn: () => Promise<T>): Promise<T> {\n\t\tif (breaker === null) return fn();\n\t\tlet isProbe = false;\n\t\tif (state !== \"closed\") {\n\t\t\tif (\n\t\t\t\tprobing ||\n\t\t\t\t(state === \"open\" && Date.now() - lastFailureAt < breaker.resetMs)\n\t\t\t) {\n\t\t\t\tthrow new CircuitOpenError();\n\t\t\t}\n\t\t\tstate = \"half-open\";\n\t\t\tprobing = true;\n\t\t\tisProbe = true;\n\t\t}\n\t\ttry {\n\t\t\tconst result = await fn();\n\t\t\tfailures = 0;\n\t\t\tstate = \"closed\";\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tif (isRetryable(error)) {\n\t\t\t\tfailures++;\n\t\t\t\tlastFailureAt = Date.now();\n\t\t\t\tif (failures >= breaker.threshold || isProbe) state = \"open\";\n\t\t\t} else if (isProbe) {\n\t\t\t\t// The backend answered; it's up.\n\t\t\t\tfailures = 0;\n\t\t\t\tstate = \"closed\";\n\t\t\t}\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tif (isProbe) probing = false;\n\t\t}\n\t}\n\n\tasync function run<T>(op: string, key: string, fn: () => Promise<T>) {\n\t\tlet lastError: unknown;\n\t\tfor (let attempt = 0; attempt <= retries; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn await guarded(fn);\n\t\t\t} catch (error) {\n\t\t\t\tlastError = error;\n\t\t\t\tif (error instanceof CircuitOpenError) throw error;\n\t\t\t\tif (!isRetryable(error) || attempt === retries) throw error;\n\t\t\t\tconst base = Math.min(initialDelayMs * 2 ** attempt, maxDelayMs);\n\t\t\t\tconst delayMs = Math.round(base + Math.random() * base * jitter);\n\t\t\t\toptions.onRetry?.({ key, op, attempt: attempt + 1, delayMs });\n\t\t\t\tawait sleep(delayMs);\n\t\t\t}\n\t\t}\n\t\tthrow lastError;\n\t}\n\n\t// Optional methods must be forwarded explicitly: this returns a new object,\n\t// so anything not listed here is dropped — and a dropped `getRange` is\n\t// invisible, because callers that want it report \"unknown\" rather than\n\t// failing. `object-size.test.ts` asserts it survives the whole stack.\n\tconst range = store.getRange?.bind(store);\n\n\treturn {\n\t\tget: (key) => run(\"get\", key, () => store.get(key)),\n\t\tput: (key, data) => run(\"put\", key, () => store.put(key, data)),\n\t\tdelete: (key) => run(\"delete\", key, () => store.delete(key)),\n\t\thead: (key) => run(\"head\", key, () => store.head(key)),\n\t\tlist: (prefix, listOptions) =>\n\t\t\trun(\"list\", prefix, () => store.list(prefix, listOptions)),\n\t\t...(range\n\t\t\t? {\n\t\t\t\t\tgetRange: (key: string, start: number, end: number) =>\n\t\t\t\t\t\trun(\"getRange\", key, () => range(key, start, end)),\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n"],"mappings":";;;;;AAuFA,MAAM,OAAO,OAAO,MAAM;AAa1B,SAAS,cAAc,OAA0B;CAChD,IAAI,OAAO,MAAM,OAAO,SAAS;CACjC,KAAK,MAAM,KAAK,MAAM,OAAO,SAAS,QAAQ,EAAE,IAAI,SAAS;CAC7D,KAAK,MAAM,KAAK,MAAM,OAAO,UAAU,QAAQ,EAAE;CACjD,OAAO;AACR;AAEA,SAAS,eAAe,QAAgC;CACvD,OAAO;EACN,SAAS,OAAO,QAAQ,KAAK,OAAO,EAAE,GAAG,EAAE,EAAE;EAC7C,UAAU,CAAC,GAAG,OAAO,QAAQ;CAC9B;AACD;;;;;;;;;;;;AAaA,SAAgB,kBACf,OACA,UAAwB,CAAC,GACL;CACpB,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,gBAAgB,QAAQ,iBAAiB,KAAK,KAAK,WAAW,EAAE;CACtE,MAAM,MAAM,QAAQ,SAAS;CAC7B,MAAM,YAAY,QAAQ;CAC1B,MAAM,cAAc,QAAQ,eAAe;CAC3C,MAAM,aAAa,QAAQ,cAAc;CACzC,MAAM,QAAQ,MAAM,UAAU,KAAK,KAAK;CACxC,MAAM,gBAAgB,QAAQ,iBAAiB;CAC/C,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,OAAO,QAAQ,QAAQ;CAC7B,MAAM,SAAS,SAAsB,OAAO,KAA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D,MAAM,MAAM,OAAO;EACpB;EAED,MAAM;CACP;CAMA,MAAM,QAAQ,MAAM,UAAU,KAAK,KAAK;CAExC,OAAO;EACN,MAAM,QAAQ,IAAI,OAAO,WAAW,MAAM,IAAI,GAAG,CAAC;EAClD,MAAM,KAAK,SAAS,IAAI,OAAO,WAAW,MAAM,IAAI,KAAK,IAAI,CAAC;EAC9D,SAAS,QAAQ,IAAI,UAAU,WAAW,MAAM,OAAO,GAAG,CAAC;EAC3D,OAAO,QAAQ,IAAI,QAAQ,WAAW,MAAM,KAAK,GAAG,CAAC;EACrD,OAAO,QAAQ,gBACd,IAAI,QAAQ,cAAc,MAAM,KAAK,QAAQ,WAAW,CAAC;EAC1D,GAAI,QACD,EACA,WAAW,KAAa,OAAe,QACtC,IAAI,YAAY,WAAW,MAAM,KAAK,OAAO,GAAG,CAAC,EACnD,IACC,CAAC;CACL;AACD"}
@@ -0,0 +1,61 @@
1
+ //#region src/stores/memory.ts
2
+ /**
3
+ * In-memory {@link ObjectStore}. Useful for tests, examples, and ephemeral
4
+ * repositories; also the reference implementation for the list/delimiter
5
+ * semantics other stores must match.
6
+ */
7
+ var MemoryObjectStore = class {
8
+ objects = /* @__PURE__ */ new Map();
9
+ async get(key) {
10
+ const data = this.objects.get(key);
11
+ return data ? data.slice() : null;
12
+ }
13
+ async getRange(key, start, end) {
14
+ const data = this.objects.get(key);
15
+ return data ? data.slice(start, end + 1) : null;
16
+ }
17
+ async put(key, data) {
18
+ this.objects.set(key, data.slice());
19
+ }
20
+ async delete(key) {
21
+ this.objects.delete(key);
22
+ }
23
+ async head(key) {
24
+ const data = this.objects.get(key);
25
+ return data ? { size: data.byteLength } : null;
26
+ }
27
+ async list(prefix, options) {
28
+ const delimiter = options?.delimiter;
29
+ const limit = options?.limit ?? Number.POSITIVE_INFINITY;
30
+ const objects = [];
31
+ const prefixes = /* @__PURE__ */ new Set();
32
+ for (const [key, data] of this.objects) {
33
+ if (!key.startsWith(prefix)) continue;
34
+ const rest = key.slice(prefix.length);
35
+ if (delimiter !== void 0) {
36
+ const idx = rest.indexOf(delimiter);
37
+ if (idx !== -1) prefixes.add(prefix + rest.slice(0, idx + delimiter.length));
38
+ else objects.push({
39
+ key,
40
+ size: data.byteLength
41
+ });
42
+ } else objects.push({
43
+ key,
44
+ size: data.byteLength
45
+ });
46
+ if (objects.length + prefixes.size >= limit) break;
47
+ }
48
+ return {
49
+ objects,
50
+ prefixes: [...prefixes]
51
+ };
52
+ }
53
+ /** Number of stored objects (test convenience, not part of ObjectStore). */
54
+ get size() {
55
+ return this.objects.size;
56
+ }
57
+ };
58
+ //#endregion
59
+ export { MemoryObjectStore as t };
60
+
61
+ //# sourceMappingURL=memory-M2cCuVF-.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory-M2cCuVF-.js","names":[],"sources":["../src/stores/memory.ts"],"sourcesContent":["import type {\n\tListOptions,\n\tListResult,\n\tObjectStat,\n\tObjectStore,\n} from \"../types.js\";\n\n/**\n * In-memory {@link ObjectStore}. Useful for tests, examples, and ephemeral\n * repositories; also the reference implementation for the list/delimiter\n * semantics other stores must match.\n */\nexport class MemoryObjectStore implements ObjectStore {\n\tprivate readonly objects = new Map<string, Uint8Array>();\n\n\tasync get(key: string): Promise<Uint8Array | null> {\n\t\tconst data = this.objects.get(key);\n\t\treturn data ? data.slice() : null;\n\t}\n\n\tasync getRange(\n\t\tkey: string,\n\t\tstart: number,\n\t\tend: number,\n\t): Promise<Uint8Array | null> {\n\t\tconst data = this.objects.get(key);\n\t\treturn data ? data.slice(start, end + 1) : null;\n\t}\n\n\tasync put(key: string, data: Uint8Array): Promise<void> {\n\t\tthis.objects.set(key, data.slice());\n\t}\n\n\tasync delete(key: string): Promise<void> {\n\t\tthis.objects.delete(key);\n\t}\n\n\tasync head(key: string): Promise<ObjectStat | null> {\n\t\tconst data = this.objects.get(key);\n\t\treturn data ? { size: data.byteLength } : null;\n\t}\n\n\tasync list(prefix: string, options?: ListOptions): Promise<ListResult> {\n\t\tconst delimiter = options?.delimiter;\n\t\tconst limit = options?.limit ?? Number.POSITIVE_INFINITY;\n\t\tconst objects: ListResult[\"objects\"] = [];\n\t\tconst prefixes = new Set<string>();\n\n\t\tfor (const [key, data] of this.objects) {\n\t\t\tif (!key.startsWith(prefix)) continue;\n\t\t\tconst rest = key.slice(prefix.length);\n\t\t\tif (delimiter !== undefined) {\n\t\t\t\tconst idx = rest.indexOf(delimiter);\n\t\t\t\tif (idx !== -1) {\n\t\t\t\t\tprefixes.add(prefix + rest.slice(0, idx + delimiter.length));\n\t\t\t\t} else {\n\t\t\t\t\tobjects.push({ key, size: data.byteLength });\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tobjects.push({ key, size: data.byteLength });\n\t\t\t}\n\t\t\tif (objects.length + prefixes.size >= limit) break;\n\t\t}\n\n\t\treturn { objects, prefixes: [...prefixes] };\n\t}\n\n\t/** Number of stored objects (test convenience, not part of ObjectStore). */\n\tget size(): number {\n\t\treturn this.objects.size;\n\t}\n}\n"],"mappings":";;;;;;AAYA,IAAa,oBAAb,MAAsD;CACrD,0BAA2B,IAAI,IAAwB;CAEvD,MAAM,IAAI,KAAyC;EAClD,MAAM,OAAO,KAAK,QAAQ,IAAI,GAAG;EACjC,OAAO,OAAO,KAAK,MAAM,IAAI;CAC9B;CAEA,MAAM,SACL,KACA,OACA,KAC6B;EAC7B,MAAM,OAAO,KAAK,QAAQ,IAAI,GAAG;EACjC,OAAO,OAAO,KAAK,MAAM,OAAO,MAAM,CAAC,IAAI;CAC5C;CAEA,MAAM,IAAI,KAAa,MAAiC;EACvD,KAAK,QAAQ,IAAI,KAAK,KAAK,MAAM,CAAC;CACnC;CAEA,MAAM,OAAO,KAA4B;EACxC,KAAK,QAAQ,OAAO,GAAG;CACxB;CAEA,MAAM,KAAK,KAAyC;EACnD,MAAM,OAAO,KAAK,QAAQ,IAAI,GAAG;EACjC,OAAO,OAAO,EAAE,MAAM,KAAK,WAAW,IAAI;CAC3C;CAEA,MAAM,KAAK,QAAgB,SAA4C;EACtE,MAAM,YAAY,SAAS;EAC3B,MAAM,QAAQ,SAAS,SAAS,OAAO;EACvC,MAAM,UAAiC,CAAC;EACxC,MAAM,2BAAW,IAAI,IAAY;EAEjC,KAAK,MAAM,CAAC,KAAK,SAAS,KAAK,SAAS;GACvC,IAAI,CAAC,IAAI,WAAW,MAAM,GAAG;GAC7B,MAAM,OAAO,IAAI,MAAM,OAAO,MAAM;GACpC,IAAI,cAAc,KAAA,GAAW;IAC5B,MAAM,MAAM,KAAK,QAAQ,SAAS;IAClC,IAAI,QAAQ,IACX,SAAS,IAAI,SAAS,KAAK,MAAM,GAAG,MAAM,UAAU,MAAM,CAAC;SAE3D,QAAQ,KAAK;KAAE;KAAK,MAAM,KAAK;IAAW,CAAC;GAE7C,OACC,QAAQ,KAAK;IAAE;IAAK,MAAM,KAAK;GAAW,CAAC;GAE5C,IAAI,QAAQ,SAAS,SAAS,QAAQ,OAAO;EAC9C;EAEA,OAAO;GAAE;GAAS,UAAU,CAAC,GAAG,QAAQ;EAAE;CAC3C;;CAGA,IAAI,OAAe;EAClB,OAAO,KAAK,QAAQ;CACrB;AACD"}
package/dist/node.js CHANGED
@@ -1,75 +1,78 @@
1
- import {
2
- MemoryObjectStore
3
- } from "./chunk-HLYCSNJ2.js";
4
-
5
- // src/stores/file.ts
6
- import { mkdir, readdir, readFile, rm, writeFile } from "fs/promises";
7
- import path from "path";
1
+ import { t as MemoryObjectStore } from "./memory-M2cCuVF-.js";
2
+ import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ //#region src/stores/file.ts
5
+ /**
6
+ * A disk-backed {@link ObjectStore} for local development and tests that
7
+ * should survive restarts: the same semantics as `MemoryObjectStore`, which
8
+ * serves every read, with each write mirrored to a file under `root` and the
9
+ * whole tree loaded back on first use. Node-only (`git-fs-s3/node`); keep it
10
+ * out of edge builds. Not for production: it holds everything in memory and
11
+ * is single-process.
12
+ *
13
+ * Keys map to paths under `root`. A key that would escape it (`../x`) is
14
+ * rejected, failing closed.
15
+ */
8
16
  var FileObjectStore = class {
9
- constructor(root) {
10
- this.root = root;
11
- }
12
- root;
13
- memory = new MemoryObjectStore();
14
- loaded = null;
15
- fileFor(key) {
16
- const file = path.resolve(this.root, key);
17
- if (!file.startsWith(path.resolve(this.root) + path.sep)) {
18
- throw new Error(`Storage key escapes the store root: ${key}`);
19
- }
20
- return file;
21
- }
22
- ready() {
23
- this.loaded ??= this.load(this.root);
24
- return this.loaded;
25
- }
26
- async load(dir) {
27
- const entries = await readdir(dir, { withFileTypes: true }).catch(
28
- (error) => {
29
- if (error.code === "ENOENT") return [];
30
- throw error;
31
- }
32
- );
33
- for (const entry of entries) {
34
- const full = path.join(dir, entry.name);
35
- if (entry.isDirectory()) {
36
- await this.load(full);
37
- } else if (entry.isFile()) {
38
- const key = path.relative(this.root, full).split(path.sep).join("/");
39
- await this.memory.put(key, new Uint8Array(await readFile(full)));
40
- }
41
- }
42
- }
43
- async get(key) {
44
- await this.ready();
45
- return this.memory.get(key);
46
- }
47
- async getRange(key, start, end) {
48
- await this.ready();
49
- return this.memory.getRange(key, start, end);
50
- }
51
- async head(key) {
52
- await this.ready();
53
- return this.memory.head(key);
54
- }
55
- async list(prefix, options) {
56
- await this.ready();
57
- return this.memory.list(prefix, options);
58
- }
59
- async put(key, data) {
60
- await this.ready();
61
- const file = this.fileFor(key);
62
- await mkdir(path.dirname(file), { recursive: true });
63
- await writeFile(file, data);
64
- await this.memory.put(key, data);
65
- }
66
- async delete(key) {
67
- await this.ready();
68
- await rm(this.fileFor(key), { force: true });
69
- await this.memory.delete(key);
70
- }
71
- };
72
- export {
73
- FileObjectStore
17
+ root;
18
+ memory = new MemoryObjectStore();
19
+ loaded = null;
20
+ constructor(root) {
21
+ this.root = root;
22
+ }
23
+ fileFor(key) {
24
+ const file = path.resolve(this.root, key);
25
+ if (!file.startsWith(path.resolve(this.root) + path.sep)) throw new Error(`Storage key escapes the store root: ${key}`);
26
+ return file;
27
+ }
28
+ ready() {
29
+ this.loaded ??= this.load(this.root);
30
+ return this.loaded;
31
+ }
32
+ async load(dir) {
33
+ const entries = await readdir(dir, { withFileTypes: true }).catch((error) => {
34
+ if (error.code === "ENOENT") return [];
35
+ throw error;
36
+ });
37
+ for (const entry of entries) {
38
+ const full = path.join(dir, entry.name);
39
+ if (entry.isDirectory()) await this.load(full);
40
+ else if (entry.isFile()) {
41
+ const key = path.relative(this.root, full).split(path.sep).join("/");
42
+ await this.memory.put(key, new Uint8Array(await readFile(full)));
43
+ }
44
+ }
45
+ }
46
+ async get(key) {
47
+ await this.ready();
48
+ return this.memory.get(key);
49
+ }
50
+ async getRange(key, start, end) {
51
+ await this.ready();
52
+ return this.memory.getRange(key, start, end);
53
+ }
54
+ async head(key) {
55
+ await this.ready();
56
+ return this.memory.head(key);
57
+ }
58
+ async list(prefix, options) {
59
+ await this.ready();
60
+ return this.memory.list(prefix, options);
61
+ }
62
+ async put(key, data) {
63
+ await this.ready();
64
+ const file = this.fileFor(key);
65
+ await mkdir(path.dirname(file), { recursive: true });
66
+ await writeFile(file, data);
67
+ await this.memory.put(key, data);
68
+ }
69
+ async delete(key) {
70
+ await this.ready();
71
+ await rm(this.fileFor(key), { force: true });
72
+ await this.memory.delete(key);
73
+ }
74
74
  };
75
+ //#endregion
76
+ export { FileObjectStore };
77
+
75
78
  //# sourceMappingURL=node.js.map
package/dist/node.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/stores/file.ts"],"sourcesContent":["/**\n * A disk-backed {@link ObjectStore} for local development and tests that\n * should survive restarts: the same semantics as `MemoryObjectStore`, which\n * serves every read, with each write mirrored to a file under `root` and the\n * whole tree loaded back on first use. Node-only (`git-fs-s3/node`); keep it\n * out of edge builds. Not for production: it holds everything in memory and\n * is single-process.\n *\n * Keys map to paths under `root`. A key that would escape it (`../x`) is\n * rejected, failing closed.\n */\nimport { mkdir, readdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type {\n\tListOptions,\n\tListResult,\n\tObjectStat,\n\tObjectStore,\n} from \"../types.js\";\nimport { MemoryObjectStore } from \"./memory.js\";\n\nexport class FileObjectStore implements ObjectStore {\n\tprivate readonly memory = new MemoryObjectStore();\n\tprivate loaded: Promise<void> | null = null;\n\n\tconstructor(private readonly root: string) {}\n\n\tprivate fileFor(key: string): string {\n\t\tconst file = path.resolve(this.root, key);\n\t\tif (!file.startsWith(path.resolve(this.root) + path.sep)) {\n\t\t\tthrow new Error(`Storage key escapes the store root: ${key}`);\n\t\t}\n\t\treturn file;\n\t}\n\n\tprivate ready(): Promise<void> {\n\t\tthis.loaded ??= this.load(this.root);\n\t\treturn this.loaded;\n\t}\n\n\tprivate async load(dir: string): Promise<void> {\n\t\tconst entries = await readdir(dir, { withFileTypes: true }).catch(\n\t\t\t(error: NodeJS.ErrnoException) => {\n\t\t\t\tif (error.code === \"ENOENT\") return [];\n\t\t\t\tthrow error;\n\t\t\t},\n\t\t);\n\t\tfor (const entry of entries) {\n\t\t\tconst full = path.join(dir, entry.name);\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tawait this.load(full);\n\t\t\t} else if (entry.isFile()) {\n\t\t\t\tconst key = path.relative(this.root, full).split(path.sep).join(\"/\");\n\t\t\t\tawait this.memory.put(key, new Uint8Array(await readFile(full)));\n\t\t\t}\n\t\t}\n\t}\n\n\tasync get(key: string): Promise<Uint8Array | null> {\n\t\tawait this.ready();\n\t\treturn this.memory.get(key);\n\t}\n\n\tasync getRange(\n\t\tkey: string,\n\t\tstart: number,\n\t\tend: number,\n\t): Promise<Uint8Array | null> {\n\t\tawait this.ready();\n\t\treturn this.memory.getRange(key, start, end);\n\t}\n\n\tasync head(key: string): Promise<ObjectStat | null> {\n\t\tawait this.ready();\n\t\treturn this.memory.head(key);\n\t}\n\n\tasync list(prefix: string, options?: ListOptions): Promise<ListResult> {\n\t\tawait this.ready();\n\t\treturn this.memory.list(prefix, options);\n\t}\n\n\tasync put(key: string, data: Uint8Array): Promise<void> {\n\t\tawait this.ready();\n\t\tconst file = this.fileFor(key);\n\t\tawait mkdir(path.dirname(file), { recursive: true });\n\t\tawait writeFile(file, data);\n\t\tawait this.memory.put(key, data);\n\t}\n\n\tasync delete(key: string): Promise<void> {\n\t\tawait this.ready();\n\t\tawait rm(this.fileFor(key), { force: true });\n\t\tawait this.memory.delete(key);\n\t}\n}\n"],"mappings":";;;;;AAWA,SAAS,OAAO,SAAS,UAAU,IAAI,iBAAiB;AACxD,OAAO,UAAU;AASV,IAAM,kBAAN,MAA6C;AAAA,EAInD,YAA6B,MAAc;AAAd;AAAA,EAAe;AAAA,EAAf;AAAA,EAHZ,SAAS,IAAI,kBAAkB;AAAA,EACxC,SAA+B;AAAA,EAI/B,QAAQ,KAAqB;AACpC,UAAM,OAAO,KAAK,QAAQ,KAAK,MAAM,GAAG;AACxC,QAAI,CAAC,KAAK,WAAW,KAAK,QAAQ,KAAK,IAAI,IAAI,KAAK,GAAG,GAAG;AACzD,YAAM,IAAI,MAAM,uCAAuC,GAAG,EAAE;AAAA,IAC7D;AACA,WAAO;AAAA,EACR;AAAA,EAEQ,QAAuB;AAC9B,SAAK,WAAW,KAAK,KAAK,KAAK,IAAI;AACnC,WAAO,KAAK;AAAA,EACb;AAAA,EAEA,MAAc,KAAK,KAA4B;AAC9C,UAAM,UAAU,MAAM,QAAQ,KAAK,EAAE,eAAe,KAAK,CAAC,EAAE;AAAA,MAC3D,CAAC,UAAiC;AACjC,YAAI,MAAM,SAAS,SAAU,QAAO,CAAC;AACrC,cAAM;AAAA,MACP;AAAA,IACD;AACA,eAAW,SAAS,SAAS;AAC5B,YAAM,OAAO,KAAK,KAAK,KAAK,MAAM,IAAI;AACtC,UAAI,MAAM,YAAY,GAAG;AACxB,cAAM,KAAK,KAAK,IAAI;AAAA,MACrB,WAAW,MAAM,OAAO,GAAG;AAC1B,cAAM,MAAM,KAAK,SAAS,KAAK,MAAM,IAAI,EAAE,MAAM,KAAK,GAAG,EAAE,KAAK,GAAG;AACnE,cAAM,KAAK,OAAO,IAAI,KAAK,IAAI,WAAW,MAAM,SAAS,IAAI,CAAC,CAAC;AAAA,MAChE;AAAA,IACD;AAAA,EACD;AAAA,EAEA,MAAM,IAAI,KAAyC;AAClD,UAAM,KAAK,MAAM;AACjB,WAAO,KAAK,OAAO,IAAI,GAAG;AAAA,EAC3B;AAAA,EAEA,MAAM,SACL,KACA,OACA,KAC6B;AAC7B,UAAM,KAAK,MAAM;AACjB,WAAO,KAAK,OAAO,SAAS,KAAK,OAAO,GAAG;AAAA,EAC5C;AAAA,EAEA,MAAM,KAAK,KAAyC;AACnD,UAAM,KAAK,MAAM;AACjB,WAAO,KAAK,OAAO,KAAK,GAAG;AAAA,EAC5B;AAAA,EAEA,MAAM,KAAK,QAAgB,SAA4C;AACtE,UAAM,KAAK,MAAM;AACjB,WAAO,KAAK,OAAO,KAAK,QAAQ,OAAO;AAAA,EACxC;AAAA,EAEA,MAAM,IAAI,KAAa,MAAiC;AACvD,UAAM,KAAK,MAAM;AACjB,UAAM,OAAO,KAAK,QAAQ,GAAG;AAC7B,UAAM,MAAM,KAAK,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AACnD,UAAM,UAAU,MAAM,IAAI;AAC1B,UAAM,KAAK,OAAO,IAAI,KAAK,IAAI;AAAA,EAChC;AAAA,EAEA,MAAM,OAAO,KAA4B;AACxC,UAAM,KAAK,MAAM;AACjB,UAAM,GAAG,KAAK,QAAQ,GAAG,GAAG,EAAE,OAAO,KAAK,CAAC;AAC3C,UAAM,KAAK,OAAO,OAAO,GAAG;AAAA,EAC7B;AACD;","names":[]}
1
+ {"version":3,"file":"node.js","names":[],"sources":["../src/stores/file.ts"],"sourcesContent":["/**\n * A disk-backed {@link ObjectStore} for local development and tests that\n * should survive restarts: the same semantics as `MemoryObjectStore`, which\n * serves every read, with each write mirrored to a file under `root` and the\n * whole tree loaded back on first use. Node-only (`git-fs-s3/node`); keep it\n * out of edge builds. Not for production: it holds everything in memory and\n * is single-process.\n *\n * Keys map to paths under `root`. A key that would escape it (`../x`) is\n * rejected, failing closed.\n */\nimport { mkdir, readdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type {\n\tListOptions,\n\tListResult,\n\tObjectStat,\n\tObjectStore,\n} from \"../types.js\";\nimport { MemoryObjectStore } from \"./memory.js\";\n\nexport class FileObjectStore implements ObjectStore {\n\tprivate readonly memory = new MemoryObjectStore();\n\tprivate loaded: Promise<void> | null = null;\n\n\tconstructor(private readonly root: string) {}\n\n\tprivate fileFor(key: string): string {\n\t\tconst file = path.resolve(this.root, key);\n\t\tif (!file.startsWith(path.resolve(this.root) + path.sep)) {\n\t\t\tthrow new Error(`Storage key escapes the store root: ${key}`);\n\t\t}\n\t\treturn file;\n\t}\n\n\tprivate ready(): Promise<void> {\n\t\tthis.loaded ??= this.load(this.root);\n\t\treturn this.loaded;\n\t}\n\n\tprivate async load(dir: string): Promise<void> {\n\t\tconst entries = await readdir(dir, { withFileTypes: true }).catch(\n\t\t\t(error: NodeJS.ErrnoException) => {\n\t\t\t\tif (error.code === \"ENOENT\") return [];\n\t\t\t\tthrow error;\n\t\t\t},\n\t\t);\n\t\tfor (const entry of entries) {\n\t\t\tconst full = path.join(dir, entry.name);\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tawait this.load(full);\n\t\t\t} else if (entry.isFile()) {\n\t\t\t\tconst key = path.relative(this.root, full).split(path.sep).join(\"/\");\n\t\t\t\tawait this.memory.put(key, new Uint8Array(await readFile(full)));\n\t\t\t}\n\t\t}\n\t}\n\n\tasync get(key: string): Promise<Uint8Array | null> {\n\t\tawait this.ready();\n\t\treturn this.memory.get(key);\n\t}\n\n\tasync getRange(\n\t\tkey: string,\n\t\tstart: number,\n\t\tend: number,\n\t): Promise<Uint8Array | null> {\n\t\tawait this.ready();\n\t\treturn this.memory.getRange(key, start, end);\n\t}\n\n\tasync head(key: string): Promise<ObjectStat | null> {\n\t\tawait this.ready();\n\t\treturn this.memory.head(key);\n\t}\n\n\tasync list(prefix: string, options?: ListOptions): Promise<ListResult> {\n\t\tawait this.ready();\n\t\treturn this.memory.list(prefix, options);\n\t}\n\n\tasync put(key: string, data: Uint8Array): Promise<void> {\n\t\tawait this.ready();\n\t\tconst file = this.fileFor(key);\n\t\tawait mkdir(path.dirname(file), { recursive: true });\n\t\tawait writeFile(file, data);\n\t\tawait this.memory.put(key, data);\n\t}\n\n\tasync delete(key: string): Promise<void> {\n\t\tawait this.ready();\n\t\tawait rm(this.fileFor(key), { force: true });\n\t\tawait this.memory.delete(key);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;AAqBA,IAAa,kBAAb,MAAoD;CAItB;CAH7B,SAA0B,IAAI,kBAAkB;CAChD,SAAuC;CAEvC,YAAY,MAA+B;EAAd,KAAA,OAAA;CAAe;CAE5C,QAAgB,KAAqB;EACpC,MAAM,OAAO,KAAK,QAAQ,KAAK,MAAM,GAAG;EACxC,IAAI,CAAC,KAAK,WAAW,KAAK,QAAQ,KAAK,IAAI,IAAI,KAAK,GAAG,GACtD,MAAM,IAAI,MAAM,uCAAuC,KAAK;EAE7D,OAAO;CACR;CAEA,QAA+B;EAC9B,KAAK,WAAW,KAAK,KAAK,KAAK,IAAI;EACnC,OAAO,KAAK;CACb;CAEA,MAAc,KAAK,KAA4B;EAC9C,MAAM,UAAU,MAAM,QAAQ,KAAK,EAAE,eAAe,KAAK,CAAC,CAAC,CAAC,OAC1D,UAAiC;GACjC,IAAI,MAAM,SAAS,UAAU,OAAO,CAAC;GACrC,MAAM;EACP,CACD;EACA,KAAK,MAAM,SAAS,SAAS;GAC5B,MAAM,OAAO,KAAK,KAAK,KAAK,MAAM,IAAI;GACtC,IAAI,MAAM,YAAY,GACrB,MAAM,KAAK,KAAK,IAAI;QACd,IAAI,MAAM,OAAO,GAAG;IAC1B,MAAM,MAAM,KAAK,SAAS,KAAK,MAAM,IAAI,CAAC,CAAC,MAAM,KAAK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