git-fs-s3 0.3.5

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/cache.ts","../src/edge-utils.ts","../src/errors.ts","../src/git-errors.ts","../src/git-fs.ts","../src/path.ts","../src/refs.ts","../src/retry.ts","../src/stores/memory.ts"],"sourcesContent":["export {\n\ttype CachedObjectStore,\n\ttype CacheOptions,\n\tcreateCachedStore,\n} from \"./cache.js\";\nexport {\n\tconcat,\n\tdecodeAscii,\n\tdecodeUtf8,\n\tdeflate,\n\tencodeUtf8,\n\tfromHex,\n\thasNullByte,\n\treadBlobContent,\n\tsha1,\n\ttoBase64,\n\ttoHex,\n} from \"./edge-utils.js\";\nexport { FsError } from \"./errors.js\";\nexport {\n\tformatErrorResponse,\n\tGitAuthenticationError,\n\tGitAuthorizationError,\n\tGitConflictError,\n\tGitError,\n\tGitInvalidRequestError,\n\tGitObjectNotFoundError,\n\tGitPathNotFoundError,\n\tGitProtocolError,\n\tGitRateLimitError,\n\tGitRefNotFoundError,\n\tGitRepositoryNotFoundError,\n\ttype MergeConflictDetail,\n} from \"./git-errors.js\";\nexport { createGitFs, type GitFs } from \"./git-fs.js\";\nexport {\n\tisFullSha,\n\tisSafeBranchName,\n\tisSafeFullRefName,\n\tisSafeRefName,\n\tisSafeRepoPath,\n\tqualifyBranchRef,\n} from \"./refs.js\";\nexport {\n\tCircuitOpenError,\n\tcreateRetryStore,\n\ttype RetryOptions,\n} from \"./retry.js\";\nexport { MemoryObjectStore } from \"./stores/memory.js\";\nexport type {\n\tGitFsClient,\n\tGitFsOptions,\n\tListOptions,\n\tListResult,\n\tObjectStat,\n\tObjectStore,\n\tStat,\n} from \"./types.js\";\n","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/** 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 coalesce = options.coalesce ?? true;\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\tconst admit = (key: string, data: Uint8Array) => {\n\t\tif (data.byteLength <= maxEntryBytes) {\n\t\t\tcache.set(key, data.slice(), { 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}\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(() => pending.delete(key));\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 : cached.slice();\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 fetched = await store.get(key);\n\t\t\t\tif (fetched !== null) {\n\t\t\t\t\tadmit(key, fetched);\n\t\t\t\t} else if (cacheMisses) {\n\t\t\t\t\tcache.set(key, MISS, { ttl: ttlForKey?.(key) });\n\t\t\t\t}\n\t\t\t\treturn fetched;\n\t\t\t});\n\t\t\treturn data === null ? null : data.slice();\n\t\t},\n\n\t\tasync put(key: string, data: Uint8Array): Promise<void> {\n\t\t\tawait store.put(key, data);\n\t\t\tadmit(key, data);\n\t\t\tif (data.byteLength > maxEntryBytes) cache.delete(key);\n\t\t\tclearStaleListEntries(key);\n\t\t},\n\n\t\tasync delete(key: string): Promise<void> {\n\t\t\tawait store.delete(key);\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\tclearStaleListEntries(key);\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 stat = await store.head(key);\n\t\t\t\tif (stat === null && cacheMisses) {\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 fetched = await store.list(prefix, listOptions);\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\tinvalidate(prefix: string): void {\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 * Edge-compatible utilities replacing node:crypto, node:zlib, and Buffer.\n *\n * Every function here uses only Web APIs (SubtleCrypto, CompressionStream,\n * TextEncoder/TextDecoder) — no Node built-ins. They work on Cloudflare\n * Workers, Vercel Edge, Deno Deploy, and Node >= 18.\n */\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n// ---------------------------------------------------------------------------\n// Text\n// ---------------------------------------------------------------------------\n\n/**\n * Encode a UTF-8 string to bytes.\n *\n * Return type pinned to `Uint8Array<ArrayBuffer>` (not the bare `Uint8Array`,\n * whose default type argument differs across TypeScript versions) so it's\n * always assignable to Fetch API `BodyInit` regardless of a consumer's own\n * TypeScript/lib version.\n */\nexport function encodeUtf8(data: string): Uint8Array<ArrayBuffer> {\n\treturn textEncoder.encode(data);\n}\n\n/** Decode bytes as UTF-8. */\nexport function decodeUtf8(data: Uint8Array): string {\n\treturn textDecoder.decode(data);\n}\n\n/** Decode bytes as ASCII. */\nexport function decodeAscii(data: Uint8Array): string {\n\tlet s = \"\";\n\tfor (let i = 0; i < data.length; i++)\n\t\ts += String.fromCharCode(data[i] as number);\n\treturn s;\n}\n\n// ---------------------------------------------------------------------------\n// Array manipulation\n// ---------------------------------------------------------------------------\n\n/** Concatenate any number of Uint8Arrays into one. */\nexport function concat(...parts: Uint8Array[]): Uint8Array<ArrayBuffer> {\n\tlet total = 0;\n\tfor (const p of parts) total += p.length;\n\tconst out = new Uint8Array(total);\n\tlet offset = 0;\n\tfor (const p of parts) {\n\t\tout.set(p, offset);\n\t\toffset += p.length;\n\t}\n\treturn out;\n}\n\n/** Extract a subarray (alias for Uint8Array.subarray for readability). */\nexport function slice(\n\tdata: Uint8Array,\n\tstart: number,\n\tend?: number,\n): Uint8Array {\n\treturn data.subarray(start, end);\n}\n\n// ---------------------------------------------------------------------------\n// Encoding\n// ---------------------------------------------------------------------------\n\n/** Uint8Array → lowercase hex string. */\nexport function toHex(data: Uint8Array): string {\n\tlet hex = \"\";\n\tfor (let i = 0; i < data.length; i++)\n\t\thex += (data[i] as number).toString(16).padStart(2, \"0\");\n\treturn hex;\n}\n\n/** Uint8Array → base64 string. */\nexport function toBase64(data: Uint8Array): string {\n\tlet binary = \"\";\n\tfor (let i = 0; i < data.length; i++)\n\t\tbinary += String.fromCharCode(data[i] as number);\n\treturn btoa(binary);\n}\n\n/** Hex string → Uint8Array. */\nexport function fromHex(hex: string): Uint8Array<ArrayBuffer> {\n\tconst bytes = new Uint8Array(hex.length / 2);\n\tfor (let i = 0; i < bytes.length; i++) {\n\t\tbytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n\t}\n\treturn bytes;\n}\n\n// ---------------------------------------------------------------------------\n// Crypto\n// ---------------------------------------------------------------------------\n\n/** SHA-1 hash via Web Crypto API. Returns a hex string. */\nexport async function sha1(data: Uint8Array | string): Promise<string> {\n\tconst bytes = typeof data === \"string\" ? encodeUtf8(data) : data;\n\tconst hash = await globalThis.crypto.subtle.digest(\"SHA-1\", bytes);\n\treturn toHex(new Uint8Array(hash));\n}\n\n// ---------------------------------------------------------------------------\n// Compression\n// ---------------------------------------------------------------------------\n\n/**\n * Deflate compress via the CompressionStream Web API.\n * Falls back to throwing if CompressionStream is unavailable (very old runtimes).\n */\nexport async function deflate(\n\tdata: Uint8Array,\n): Promise<Uint8Array<ArrayBuffer>> {\n\tconst stream = new Blob([data])\n\t\t.stream()\n\t\t.pipeThrough(new CompressionStream(\"deflate\"));\n\treturn new Uint8Array(await new Response(stream).arrayBuffer());\n}\n\n// ---------------------------------------------------------------------------\n// Binary detection (replaces Buffer.includes(0) pattern)\n// ---------------------------------------------------------------------------\n\n/** Check if a Uint8Array contains a null byte. */\nexport function hasNullByte(data: Uint8Array): boolean {\n\treturn data.includes(0);\n}\n\n/**\n * Read a blob as text or binary metadata — the edge-compatible replacement\n * for the `Buffer.from(blob)` pattern used throughout diff.ts and history.ts.\n */\nexport function readBlobContent(blob: Uint8Array): {\n\tisBinary: boolean;\n\ttext: string;\n\tbytes: Uint8Array;\n} {\n\tconst isBinary = hasNullByte(blob);\n\treturn {\n\t\tisBinary,\n\t\ttext: isBinary ? \"\" : decodeUtf8(blob),\n\t\tbytes: blob,\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 eisdir = (syscall: string, path: string) =>\n\tnew FsError(\"EISDIR\", 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","/**\n * Git-server error types carrying an HTTP status and a retryability flag, so\n * transport layers can map internal failures to responses without inspecting\n * messages. Extend {@link GitError} for app-specific cases (storage backends,\n * quota, …) and {@link formatErrorResponse} keeps working for them.\n */\nexport class GitError extends Error {\n\tstatusCode: number;\n\tretryable: boolean;\n\n\tconstructor(message: string, statusCode = 500, retryable = false) {\n\t\tsuper(message);\n\t\tthis.name = this.constructor.name;\n\t\tthis.statusCode = statusCode;\n\t\tthis.retryable = retryable;\n\t\tError.captureStackTrace?.(this, this.constructor);\n\t}\n\n\ttoJSON(): Record<string, unknown> {\n\t\treturn {\n\t\t\terror: this.name,\n\t\t\tmessage: this.message,\n\t\t\tstatusCode: this.statusCode,\n\t\t\tretryable: this.retryable,\n\t\t};\n\t}\n}\n\n/** A file/directory path not found within a tree (404). */\nexport class GitPathNotFoundError extends GitError {\n\tconstructor(message: string) {\n\t\tsuper(message, 404, false);\n\t}\n}\n\n/** A git object not found (404). */\nexport class GitObjectNotFoundError extends GitError {\n\tconstructor(message: string) {\n\t\tsuper(message, 404, false);\n\t}\n}\n\n/** A ref (branch/tag) not found (404). */\nexport class GitRefNotFoundError extends GitError {\n\tconstructor(message: string) {\n\t\tsuper(message, 404, false);\n\t}\n}\n\n/** The repository itself not found (404). */\nexport class GitRepositoryNotFoundError extends GitError {\n\tconstructor(message: string) {\n\t\tsuper(message, 404, false);\n\t}\n}\n\nexport interface MergeConflictDetail {\n\tfile: string;\n\tbaseLines?: string[];\n\tsourceLines?: string[];\n\ttargetLines?: string[];\n}\n\n/** A merge conflict (409), carrying per-file conflict detail. */\nexport class GitConflictError extends GitError {\n\tconflicts: MergeConflictDetail[];\n\n\tconstructor(message: string, conflicts: MergeConflictDetail[] = []) {\n\t\tsuper(message, 409, false);\n\t\tthis.conflicts = conflicts;\n\t}\n\n\toverride toJSON(): Record<string, unknown> {\n\t\treturn { ...super.toJSON(), conflicts: this.conflicts };\n\t}\n}\n\n/** Authentication failed (401). */\nexport class GitAuthenticationError extends GitError {\n\tconstructor(message: string) {\n\t\tsuper(message, 401, false);\n\t}\n}\n\n/** Authorization failed (403). */\nexport class GitAuthorizationError extends GitError {\n\tconstructor(message: string) {\n\t\tsuper(message, 403, false);\n\t}\n}\n\n/** Too many failed attempts (429). */\nexport class GitRateLimitError extends GitError {\n\tconstructor(message: string) {\n\t\tsuper(message, 429, false);\n\t}\n}\n\n/** Malformed request (400). */\nexport class GitInvalidRequestError extends GitError {\n\tconstructor(message: string) {\n\t\tsuper(message, 400, false);\n\t}\n}\n\n/** Git wire-protocol violation (400). */\nexport class GitProtocolError extends GitError {\n\tconstructor(message: string) {\n\t\tsuper(message, 400, false);\n\t}\n}\n\n/**\n * Map any error to an HTTP response shape. 401s carry the WWW-Authenticate\n * header git clients need before they will prompt for credentials. Non-GitError\n * failures are masked as opaque 500s — internal messages don't leak.\n */\nexport function formatErrorResponse(error: unknown): {\n\tstatus: number;\n\tbody: Record<string, unknown>;\n\theaders?: Record<string, string>;\n} {\n\tif (error instanceof GitError) {\n\t\treturn {\n\t\t\tstatus: error.statusCode,\n\t\t\tbody: error.toJSON(),\n\t\t\theaders:\n\t\t\t\terror.statusCode === 401\n\t\t\t\t\t? { \"WWW-Authenticate\": 'Basic realm=\"Git Repository\"' }\n\t\t\t\t\t: undefined,\n\t\t};\n\t}\n\n\tif (error instanceof Error) {\n\t\treturn {\n\t\t\tstatus: 500,\n\t\t\tbody: {\n\t\t\t\terror: \"InternalServerError\",\n\t\t\t\tmessage: \"An internal error occurred\",\n\t\t\t\tretryable: true,\n\t\t\t},\n\t\t};\n\t}\n\n\treturn {\n\t\tstatus: 500,\n\t\tbody: {\n\t\t\terror: \"UnknownError\",\n\t\t\tmessage: \"An unknown error occurred\",\n\t\t\tretryable: true,\n\t\t},\n\t};\n}\n","import { LRUCache } from \"lru-cache\";\nimport { enoent, enotdir, enotempty, eperm } from \"./errors.js\";\nimport { normalizePath } from \"./path.js\";\nimport type {\n\tEncoding,\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\n/**\n * A loose git object path: `objects/xx/<38 hex>` under any gitdir. The two\n * capture groups let the gitdir scope be recovered from a full path.\n */\nconst LOOSE_OBJECT_RE = /(^|\\/)objects\\/[0-9a-f]{2}\\/[0-9a-f]{38}$/;\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 * 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}\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 structurallyAbsent = options.isStructurallyAbsent;\n\tconst useLooseHints = options.looseObjectHints ?? false;\n\tconst onNote = options.onNote;\n\n\tconst toKey = (path: string): string => {\n\t\tif (prefix === \"\") return path;\n\t\treturn path === \"\" ? prefix : `${prefix}/${path}`;\n\t};\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/** The gitdir scope of a loose-object path, or null when it isn't one. */\n\tfunction looseScope(path: string): string | null {\n\t\tconst match = LOOSE_OBJECT_RE.exec(path);\n\t\tif (match === null) return null;\n\t\treturn path.slice(0, match.index);\n\t}\n\n\tfunction knownAbsent(path: string): boolean {\n\t\tif (structurallyAbsent?.(path)) return true;\n\t\tif (!useLooseHints) return false;\n\t\tconst scope = looseScope(path);\n\t\treturn scope !== null && 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 (knownAbsent(path)) throw enoent(syscall, filepath);\n\t\tconst k = toKey(path);\n\t\tif (k === prefix || k === \"\") return makeStat(\"dir\", 0);\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 promises: GitFsClient[\"promises\"] = {\n\t\tasync readFile(filepath, opts) {\n\t\t\tconst path = normalizePath(filepath);\n\t\t\tif (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 && LOOSE_OBJECT_RE.test(first) ? \"present\" : \"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\tconst entries = await promises.readdir(packDir).catch(() => []);\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\tfunction invalidate(pathPrefix: string): void {\n\t\tconst normalized = normalizePath(pathPrefix);\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 { promises, detectLooseObjects, prefetchPacks, invalidate };\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","/**\n * Git ref-name validation, mirroring isomorphic-git's own internal `isValidRef`\n * character-class rules (the check `git.branch` and top-level `git.writeRef`\n * run before touching disk).\n *\n * Several of isomorphic-git's OTHER ref-touching primitives — `git.commit`,\n * `git.merge`, `git.deleteBranch`, and top-level `git.resolveRef`/\n * `git.deleteRef` — do NOT run this check internally: they resolve straight\n * through `fs.write`/`fs.rm(join(gitdir, ref))` with no jail to the gitdir.\n * On a shared-storage server (many repos under one prefix or base directory),\n * every branch/ref name that originates from request input must be validated\n * against these predicates before it reaches any of those primitives —\n * otherwise a `\"../\"`-laden name lets a caller with write access to any single\n * repo read, corrupt, or delete another repo's ref/object files.\n */\n\nconst BAD_REF_COMPONENT =\n\t// biome-ignore lint/suspicious/noControlCharactersInRegex: control chars are exactly what git's own ref-name rules reject — this needs to match the same range.\n\t/(^|[/.])([/.]|$)|^@$|@\\{|[\\x00-\\x20\\x7f~^:?*[\\\\]|\\.lock(\\/|$)/;\n\nconst FULL_SHA_RE = /^[0-9a-f]{40}$/i;\n\n/** Validates a fully-qualified ref (must start with refs/heads/ or refs/tags/). */\nexport function isSafeFullRefName(ref: string): boolean {\n\tif (!ref.startsWith(\"refs/heads/\") && !ref.startsWith(\"refs/tags/\")) {\n\t\treturn false;\n\t}\n\treturn !BAD_REF_COMPONENT.test(ref);\n}\n\n/**\n * Validates a bare branch name (no refs/ prefix). Rejects anything that looks\n * like a full ref path — a name of `\"refs/heads/x\"` would otherwise sail\n * through unprefixed at call sites that build `refs/heads/${name}` themselves\n * (doubling the prefix into something that still resolves), or be used as-is\n * at call sites that pass a name already containing `\"refs/\"` straight\n * through. Also rejects 40-hex SHA-shaped values so a stored branch name can\n * never be ambiguous with a commit SHA at write time; use\n * {@link isSafeRefName} on read paths that accept both shapes.\n */\nexport function isSafeBranchName(name: string): boolean {\n\tif (!name || name.startsWith(\"refs/\") || name === \"HEAD\") return false;\n\tif (FULL_SHA_RE.test(name)) return false;\n\treturn !BAD_REF_COMPONENT.test(name);\n}\n\n/** True for a full 40-hex-char commit SHA — the shape {@link isSafeBranchName} deliberately rejects. */\nexport function isFullSha(value: string): boolean {\n\treturn FULL_SHA_RE.test(value);\n}\n\n/**\n * Validates a \"ref\" field that may name either a branch or a commit SHA it's\n * pinned to — the shape read-path route params take (permalinks, raw links).\n * Both shapes still go through the traversal check.\n */\nexport function isSafeRefName(value: string): boolean {\n\treturn isSafeBranchName(value) || isFullSha(value);\n}\n\n/**\n * Validates a repo-relative file path from request input: relative, no `..`\n * segments, no `.git/` prefix, no null bytes. Use this anywhere a path\n * segment comes straight off a URL or form field rather than re-deriving the\n * checks ad hoc.\n */\nexport function isSafeRepoPath(p: string): boolean {\n\tif (p.startsWith(\"/\")) return false;\n\tif (p.split(\"/\").some((segment) => segment === \"..\")) return false;\n\tif (/^\\.git(\\/|$)/i.test(p)) return false;\n\tif (p.includes(\"\\0\")) return false;\n\treturn true;\n}\n\n/**\n * Qualify a bare branch name to `refs/heads/<name>` before handing it to\n * isomorphic-git. `resolveRef`/`expand` try several candidate paths in\n * sequence for a bare name — `ref`, `refs/ref`, `refs/tags/ref`,\n * `refs/heads/ref`, … — missing (and, against object storage, paying a real\n * round trip for) the first three every time. For a branch-only ref model,\n * skip straight to the winner. Left untouched: already-qualified refs,\n * `\"HEAD\"` (its own first candidate, already optimal), and 40-hex oids\n * (resolved locally by isomorphic-git with no I/O at all).\n */\nexport function qualifyBranchRef(ref: string): string {\n\tif (ref.startsWith(\"refs/\") || ref === \"HEAD\" || FULL_SHA_RE.test(ref)) {\n\t\treturn ref;\n\t}\n\treturn `refs/heads/${ref}`;\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\nfunction defaultIsRetryable(error: unknown): boolean {\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 ?? defaultIsRetryable;\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\n\tasync function guarded<T>(fn: () => Promise<T>): Promise<T> {\n\t\tif (breaker === null) return fn();\n\t\tif (state === \"open\") {\n\t\t\tif (Date.now() - lastFailureAt < breaker.resetMs) {\n\t\t\t\tthrow new CircuitOpenError();\n\t\t\t}\n\t\t\tstate = \"half-open\";\n\t\t}\n\t\ttry {\n\t\t\tconst result = await fn();\n\t\t\tif (state === \"half-open\") {\n\t\t\t\tstate = \"closed\";\n\t\t\t\tfailures = 0;\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tfailures++;\n\t\t\tlastFailureAt = Date.now();\n\t\t\tif (failures >= breaker.threshold) state = \"open\";\n\t\t\tthrow error;\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\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};\n}\n","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 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":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,uBAAyB;AAsEzB,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,WAAW,QAAQ,YAAY;AACrC,QAAM,QAAQ,QAAQ;AACtB,QAAM,SAAS,QAAQ;AAEvB,QAAM,QAAQ,IAAI,0BAA6B;AAAA,IAC9C,SAAS;AAAA,IACT,iBAAiB,CAAC,UAA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ient, a as GitFsOptions, b as ObjectStat, L as ListOptions, c as ListResult } from './types-QgIkUR_q.cjs';
2
+ export { S as Stat } from './types-QgIkUR_q.cjs';
3
+
4
+ interface CacheOptions {
5
+ /** Maximum bytes of object data held in memory. Default 50 MiB. */
6
+ maxBytes?: number;
7
+ /**
8
+ * Largest single entry admitted to the cache. Defaults to a tenth of
9
+ * `maxBytes` so one huge packfile cannot evict the whole working set.
10
+ */
11
+ maxEntryBytes?: number;
12
+ /** Entry time-to-live in milliseconds. Default 60 000. */
13
+ ttlMs?: number;
14
+ /**
15
+ * Override the TTL for a specific key (get/head) or list prefix (list),
16
+ * in milliseconds. Return `undefined` to fall back to `ttlMs`. Git refs
17
+ * (`refs/heads/<branch>`, `HEAD`) are mutable — the same key's value
18
+ * changes on every push — unlike content-addressed object keys, which
19
+ * never change for a given key and are safe to cache for the full
20
+ * `ttlMs`. Without this, a long `ttlMs` tuned for objects also caches
21
+ * ref reads that long, so a warm process can keep serving a
22
+ * pre-push ref value for the rest of that TTL even though nothing
23
+ * changed *this* process's own cache (see `invalidate`) — it just never
24
+ * knew to. Give ref-like keys a short override (a few seconds) instead:
25
+ * a ref read is one small object, so re-reading it far more often than
26
+ * `ttlMs` is cheap, and every read downstream of a fresh ref (tree,
27
+ * commit, blob — all keyed by the sha it resolves to) still gets the
28
+ * full-length cache/coalescing benefit.
29
+ */
30
+ ttlForKey?: (key: string) => number | undefined;
31
+ /**
32
+ * Also cache "key does not exist" results. Loose-object probes on packed
33
+ * repositories are almost always misses, so this saves many round trips —
34
+ * but only enable it when a single process is the only writer, otherwise
35
+ * another instance's push can be masked for up to `ttlMs`.
36
+ */
37
+ cacheMisses?: boolean;
38
+ /**
39
+ * Also cache `list()` results (directory listings and `limit: 1`
40
+ * existence probes). Writes through this store keep cached listings
41
+ * consistent; after writing to the backend by any other means, call
42
+ * `invalidate()` with the affected prefix. Default false.
43
+ */
44
+ cacheLists?: boolean;
45
+ /**
46
+ * Collapse concurrent `get`/`head`/`list` calls for the same key into a
47
+ * single backend request. Default true.
48
+ */
49
+ coalesce?: boolean;
50
+ /** Called when a read is answered from cache. */
51
+ onHit?: (key: string) => void;
52
+ /** Called when a read has to go to the backing store. */
53
+ onMiss?: (key: string) => void;
54
+ }
55
+ /** An {@link ObjectStore} wrapper that also supports explicit invalidation. */
56
+ interface CachedObjectStore extends ObjectStore {
57
+ /**
58
+ * Drop every cached entry — contents, misses, and listings — whose key
59
+ * falls under `prefix` (exact keys included). Call this after the backing
60
+ * store was modified by something other than this wrapper.
61
+ */
62
+ invalidate(prefix: string): void;
63
+ }
64
+ /**
65
+ * Wrap an {@link ObjectStore} with an in-process LRU read cache.
66
+ *
67
+ * Git object keys are content-addressed and therefore immutable, which makes
68
+ * them ideal cache entries; mutable keys (refs, packed-refs) are bounded by
69
+ * `ttlMs`. Writes and deletes through this wrapper invalidate their key and
70
+ * any cached listings they affect — with one asymmetry: a non-empty `limit: 1`
71
+ * probe (a "directory exists" answer) survives writes underneath it, because
72
+ * adding a key below a prefix cannot make that prefix stop existing, while
73
+ * empty probes and full listings are always dropped.
74
+ */
75
+ declare function createCachedStore(store: ObjectStore, options?: CacheOptions): CachedObjectStore;
76
+
77
+ /**
78
+ * Edge-compatible utilities replacing node:crypto, node:zlib, and Buffer.
79
+ *
80
+ * Every function here uses only Web APIs (SubtleCrypto, CompressionStream,
81
+ * TextEncoder/TextDecoder) — no Node built-ins. They work on Cloudflare
82
+ * Workers, Vercel Edge, Deno Deploy, and Node >= 18.
83
+ */
84
+ /**
85
+ * Encode a UTF-8 string to bytes.
86
+ *
87
+ * Return type pinned to `Uint8Array<ArrayBuffer>` (not the bare `Uint8Array`,
88
+ * whose default type argument differs across TypeScript versions) so it's
89
+ * always assignable to Fetch API `BodyInit` regardless of a consumer's own
90
+ * TypeScript/lib version.
91
+ */
92
+ declare function encodeUtf8(data: string): Uint8Array<ArrayBuffer>;
93
+ /** Decode bytes as UTF-8. */
94
+ declare function decodeUtf8(data: Uint8Array): string;
95
+ /** Decode bytes as ASCII. */
96
+ declare function decodeAscii(data: Uint8Array): string;
97
+ /** Concatenate any number of Uint8Arrays into one. */
98
+ declare function concat(...parts: Uint8Array[]): Uint8Array<ArrayBuffer>;
99
+ /** Uint8Array → lowercase hex string. */
100
+ declare function toHex(data: Uint8Array): string;
101
+ /** Uint8Array → base64 string. */
102
+ declare function toBase64(data: Uint8Array): string;
103
+ /** Hex string → Uint8Array. */
104
+ declare function fromHex(hex: string): Uint8Array<ArrayBuffer>;
105
+ /** SHA-1 hash via Web Crypto API. Returns a hex string. */
106
+ declare function sha1(data: Uint8Array | string): Promise<string>;
107
+ /**
108
+ * Deflate compress via the CompressionStream Web API.
109
+ * Falls back to throwing if CompressionStream is unavailable (very old runtimes).
110
+ */
111
+ declare function deflate(data: Uint8Array): Promise<Uint8Array<ArrayBuffer>>;
112
+ /** Check if a Uint8Array contains a null byte. */
113
+ declare function hasNullByte(data: Uint8Array): boolean;
114
+ /**
115
+ * Read a blob as text or binary metadata — the edge-compatible replacement
116
+ * for the `Buffer.from(blob)` pattern used throughout diff.ts and history.ts.
117
+ */
118
+ declare function readBlobContent(blob: Uint8Array): {
119
+ isBinary: boolean;
120
+ text: string;
121
+ bytes: Uint8Array;
122
+ };
123
+
124
+ /**
125
+ * Node-style filesystem error carrying a `code` property, which is what
126
+ * isomorphic-git inspects to distinguish "file not found" from real failures.
127
+ */
128
+ declare class FsError extends Error {
129
+ readonly code: string;
130
+ readonly syscall: string;
131
+ readonly path: string;
132
+ constructor(code: string, syscall: string, path: string);
133
+ }
134
+
135
+ /**
136
+ * Git-server error types carrying an HTTP status and a retryability flag, so
137
+ * transport layers can map internal failures to responses without inspecting
138
+ * messages. Extend {@link GitError} for app-specific cases (storage backends,
139
+ * quota, …) and {@link formatErrorResponse} keeps working for them.
140
+ */
141
+ declare class GitError extends Error {
142
+ statusCode: number;
143
+ retryable: boolean;
144
+ constructor(message: string, statusCode?: number, retryable?: boolean);
145
+ toJSON(): Record<string, unknown>;
146
+ }
147
+ /** A file/directory path not found within a tree (404). */
148
+ declare class GitPathNotFoundError extends GitError {
149
+ constructor(message: string);
150
+ }
151
+ /** A git object not found (404). */
152
+ declare class GitObjectNotFoundError extends GitError {
153
+ constructor(message: string);
154
+ }
155
+ /** A ref (branch/tag) not found (404). */
156
+ declare class GitRefNotFoundError extends GitError {
157
+ constructor(message: string);
158
+ }
159
+ /** The repository itself not found (404). */
160
+ declare class GitRepositoryNotFoundError extends GitError {
161
+ constructor(message: string);
162
+ }
163
+ interface MergeConflictDetail {
164
+ file: string;
165
+ baseLines?: string[];
166
+ sourceLines?: string[];
167
+ targetLines?: string[];
168
+ }
169
+ /** A merge conflict (409), carrying per-file conflict detail. */
170
+ declare class GitConflictError extends GitError {
171
+ conflicts: MergeConflictDetail[];
172
+ constructor(message: string, conflicts?: MergeConflictDetail[]);
173
+ toJSON(): Record<string, unknown>;
174
+ }
175
+ /** Authentication failed (401). */
176
+ declare class GitAuthenticationError extends GitError {
177
+ constructor(message: string);
178
+ }
179
+ /** Authorization failed (403). */
180
+ declare class GitAuthorizationError extends GitError {
181
+ constructor(message: string);
182
+ }
183
+ /** Too many failed attempts (429). */
184
+ declare class GitRateLimitError extends GitError {
185
+ constructor(message: string);
186
+ }
187
+ /** Malformed request (400). */
188
+ declare class GitInvalidRequestError extends GitError {
189
+ constructor(message: string);
190
+ }
191
+ /** Git wire-protocol violation (400). */
192
+ declare class GitProtocolError extends GitError {
193
+ constructor(message: string);
194
+ }
195
+ /**
196
+ * Map any error to an HTTP response shape. 401s carry the WWW-Authenticate
197
+ * header git clients need before they will prompt for credentials. Non-GitError
198
+ * failures are masked as opaque 500s — internal messages don't leak.
199
+ */
200
+ declare function formatErrorResponse(error: unknown): {
201
+ status: number;
202
+ body: Record<string, unknown>;
203
+ headers?: Record<string, string>;
204
+ };
205
+
206
+ /**
207
+ * The filesystem returned by {@link createGitFs}: the isomorphic-git client
208
+ * plus git-aware maintenance hooks.
209
+ */
210
+ interface GitFs extends GitFsClient {
211
+ /**
212
+ * Probe, with one bounded list, whether `gitdir` contains any loose
213
+ * objects, and remember the answer. This is the only way a loose-object
214
+ * hint is ever created; call it before full-history walks (commit logs,
215
+ * reachability traversals) so fully packed repositories skip every
216
+ * guaranteed-miss loose-object read. A later loose write flips the hint
217
+ * back, so it cannot go stale mid-push.
218
+ */
219
+ detectLooseObjects(gitdir: string): Promise<void>;
220
+ /**
221
+ * Warm the cache with every pack file under `gitdir` in parallel (plus
222
+ * the loose-object hint) before a sequential history walk. Skipped when
223
+ * the pack directory holds more than `maxPacks * 2` entries — warming
224
+ * only helps when the cache budget actually fits the packs.
225
+ */
226
+ prefetchPacks(gitdir: string, options?: {
227
+ maxPacks?: number;
228
+ }): Promise<void>;
229
+ /**
230
+ * Clear fs-level state (loose-object hints) under `pathPrefix`, and
231
+ * forward to the store's `invalidate` when it has one. Call after the
232
+ * backing store was modified by something other than this fs.
233
+ */
234
+ invalidate(pathPrefix: string): void;
235
+ }
236
+ /**
237
+ * Create a promise-based filesystem client for isomorphic-git backed by an
238
+ * {@link ObjectStore}.
239
+ *
240
+ * Semantics:
241
+ * - Directories are implicit, as in object storage: `mkdir` is a no-op and a
242
+ * directory "exists" whenever at least one key lives under its prefix.
243
+ * - Symbolic links are not supported (`readlink`/`symlink` throw). Bare
244
+ * repositories never contain them.
245
+ * - Designed for bare, server-side repositories (`git.init({bare: true})`,
246
+ * plumbing commands, ref updates). Worktree checkouts belong on a real disk.
247
+ */
248
+ declare function createGitFs(store: ObjectStore, options?: GitFsOptions): GitFs;
249
+
250
+ /**
251
+ * Git ref-name validation, mirroring isomorphic-git's own internal `isValidRef`
252
+ * character-class rules (the check `git.branch` and top-level `git.writeRef`
253
+ * run before touching disk).
254
+ *
255
+ * Several of isomorphic-git's OTHER ref-touching primitives — `git.commit`,
256
+ * `git.merge`, `git.deleteBranch`, and top-level `git.resolveRef`/
257
+ * `git.deleteRef` — do NOT run this check internally: they resolve straight
258
+ * through `fs.write`/`fs.rm(join(gitdir, ref))` with no jail to the gitdir.
259
+ * On a shared-storage server (many repos under one prefix or base directory),
260
+ * every branch/ref name that originates from request input must be validated
261
+ * against these predicates before it reaches any of those primitives —
262
+ * otherwise a `"../"`-laden name lets a caller with write access to any single
263
+ * repo read, corrupt, or delete another repo's ref/object files.
264
+ */
265
+ /** Validates a fully-qualified ref (must start with refs/heads/ or refs/tags/). */
266
+ declare function isSafeFullRefName(ref: string): boolean;
267
+ /**
268
+ * Validates a bare branch name (no refs/ prefix). Rejects anything that looks
269
+ * like a full ref path — a name of `"refs/heads/x"` would otherwise sail
270
+ * through unprefixed at call sites that build `refs/heads/${name}` themselves
271
+ * (doubling the prefix into something that still resolves), or be used as-is
272
+ * at call sites that pass a name already containing `"refs/"` straight
273
+ * through. Also rejects 40-hex SHA-shaped values so a stored branch name can
274
+ * never be ambiguous with a commit SHA at write time; use
275
+ * {@link isSafeRefName} on read paths that accept both shapes.
276
+ */
277
+ declare function isSafeBranchName(name: string): boolean;
278
+ /** True for a full 40-hex-char commit SHA — the shape {@link isSafeBranchName} deliberately rejects. */
279
+ declare function isFullSha(value: string): boolean;
280
+ /**
281
+ * Validates a "ref" field that may name either a branch or a commit SHA it's
282
+ * pinned to — the shape read-path route params take (permalinks, raw links).
283
+ * Both shapes still go through the traversal check.
284
+ */
285
+ declare function isSafeRefName(value: string): boolean;
286
+ /**
287
+ * Validates a repo-relative file path from request input: relative, no `..`
288
+ * segments, no `.git/` prefix, no null bytes. Use this anywhere a path
289
+ * segment comes straight off a URL or form field rather than re-deriving the
290
+ * checks ad hoc.
291
+ */
292
+ declare function isSafeRepoPath(p: string): boolean;
293
+ /**
294
+ * Qualify a bare branch name to `refs/heads/<name>` before handing it to
295
+ * isomorphic-git. `resolveRef`/`expand` try several candidate paths in
296
+ * sequence for a bare name — `ref`, `refs/ref`, `refs/tags/ref`,
297
+ * `refs/heads/ref`, … — missing (and, against object storage, paying a real
298
+ * round trip for) the first three every time. For a branch-only ref model,
299
+ * skip straight to the winner. Left untouched: already-qualified refs,
300
+ * `"HEAD"` (its own first candidate, already optimal), and 40-hex oids
301
+ * (resolved locally by isomorphic-git with no I/O at all).
302
+ */
303
+ declare function qualifyBranchRef(ref: string): string;
304
+
305
+ /** Options accepted by {@link createRetryStore}. */
306
+ interface RetryOptions {
307
+ /** Retries after the first attempt (total attempts = retries + 1). Default 3. */
308
+ retries?: number;
309
+ /** Backoff base delay in milliseconds, doubled each attempt. Default 100. */
310
+ initialDelayMs?: number;
311
+ /** Upper bound for the backoff base delay. Default 5000. */
312
+ maxDelayMs?: number;
313
+ /** Random jitter added to each delay, as a fraction of it. Default 0.3. */
314
+ jitter?: number;
315
+ /**
316
+ * Decide whether an error is worth retrying. The store contract maps
317
+ * "not found" to `null` rather than throwing, so any thrown error is a
318
+ * genuine failure; the default retries network faults, throttling, and
319
+ * HTTP 5xx responses.
320
+ */
321
+ isRetryable?: (error: unknown) => boolean;
322
+ /**
323
+ * Circuit breaker configuration, or `false` to disable. After `threshold`
324
+ * consecutive failures the store fails fast for `resetMs`, then lets one
325
+ * request probe the backend again. Defaults: 5 failures, 30 000 ms.
326
+ */
327
+ breaker?: false | {
328
+ threshold?: number;
329
+ resetMs?: number;
330
+ };
331
+ /** Called before each retry sleep; useful for logging/metrics. */
332
+ onRetry?: (info: {
333
+ key: string;
334
+ op: string;
335
+ attempt: number;
336
+ delayMs: number;
337
+ }) => void;
338
+ }
339
+ /**
340
+ * Thrown instead of calling the backend while the circuit breaker is open.
341
+ * Carries `code: "EUNAVAILABLE"` so callers can map it to a 503.
342
+ */
343
+ declare class CircuitOpenError extends Error {
344
+ readonly code = "EUNAVAILABLE";
345
+ constructor();
346
+ }
347
+ /**
348
+ * Wrap an {@link ObjectStore} with retries (exponential backoff + jitter) and
349
+ * an optional per-instance circuit breaker.
350
+ *
351
+ * Place this decorator closest to the network store, underneath any cache:
352
+ * the cache then never stores transient failures, and callers coalesced onto
353
+ * one request share a single retried attempt.
354
+ */
355
+ declare function createRetryStore(store: ObjectStore, options?: RetryOptions): ObjectStore;
356
+
357
+ /**
358
+ * In-memory {@link ObjectStore}. Useful for tests, examples, and ephemeral
359
+ * repositories; also the reference implementation for the list/delimiter
360
+ * semantics other stores must match.
361
+ */
362
+ declare class MemoryObjectStore implements ObjectStore {
363
+ private readonly objects;
364
+ get(key: string): Promise<Uint8Array | null>;
365
+ put(key: string, data: Uint8Array): Promise<void>;
366
+ delete(key: string): Promise<void>;
367
+ head(key: string): Promise<ObjectStat | null>;
368
+ list(prefix: string, options?: ListOptions): Promise<ListResult>;
369
+ /** Number of stored objects (test convenience, not part of ObjectStore). */
370
+ get size(): number;
371
+ }
372
+
373
+ export { type CacheOptions, type CachedObjectStore, CircuitOpenError, FsError, GitAuthenticationError, GitAuthorizationError, GitConflictError, GitError, type GitFs, GitFsClient, GitFsOptions, GitInvalidRequestError, GitObjectNotFoundError, GitPathNotFoundError, GitProtocolError, GitRateLimitError, GitRefNotFoundError, GitRepositoryNotFoundError, ListOptions, ListResult, MemoryObjectStore, type MergeConflictDetail, ObjectStat, ObjectStore, type RetryOptions, concat, createCachedStore, createGitFs, createRetryStore, decodeAscii, decodeUtf8, deflate, encodeUtf8, formatErrorResponse, fromHex, hasNullByte, isFullSha, isSafeBranchName, isSafeFullRefName, isSafeRefName, isSafeRepoPath, qualifyBranchRef, readBlobContent, sha1, toBase64, toHex };