git-fs-s3 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -17
- package/dist/{chunk-Z4656PGE.js → chunk-2JP4MS6H.js} +2 -2
- package/dist/{chunk-YQFNY6PG.js → chunk-FIFWOMPM.js} +1 -1
- package/dist/chunk-FIFWOMPM.js.map +1 -0
- package/dist/http.js +3 -3
- package/dist/http.js.map +1 -1
- package/dist/index.js +2 -3
- package/dist/index.js.map +1 -1
- package/dist/ops.js +2 -2
- package/dist/types/cache.d.ts +81 -0
- package/dist/types/edge-utils.d.ts +43 -0
- package/dist/types/errors.d.ts +16 -0
- package/dist/types/git-errors.d.ts +70 -0
- package/dist/types/git-fs.d.ts +60 -0
- package/dist/types/git-layout.d.ts +52 -0
- package/dist/types/http/index.d.ts +7 -0
- package/dist/types/http/info-refs.d.ts +27 -0
- package/dist/types/http/pack-reuse.d.ts +26 -0
- package/dist/types/http/pkt-line.d.ts +14 -0
- package/dist/types/http/reachability.d.ts +36 -0
- package/dist/types/http/receive-pack.d.ts +54 -0
- package/dist/types/http/repack.d.ts +24 -0
- package/dist/types/http/types.d.ts +40 -0
- package/dist/types/http/upload-pack.d.ts +21 -0
- package/dist/types/index.d.ts +11 -0
- package/dist/types/ops/branch.d.ts +38 -0
- package/dist/types/ops/commit.d.ts +45 -0
- package/dist/types/ops/diff.d.ts +24 -0
- package/dist/types/ops/file-history.d.ts +41 -0
- package/dist/types/ops/history.d.ts +85 -0
- package/dist/types/ops/index.d.ts +9 -0
- package/dist/types/ops/last-commit.d.ts +23 -0
- package/dist/types/ops/merge.d.ts +28 -0
- package/dist/types/ops/tree.d.ts +19 -0
- package/dist/{types-BHoHOaQt.d.cts → types/ops/types.d.ts} +7 -9
- package/dist/types/pack-files.d.ts +28 -0
- package/dist/types/path.d.ts +9 -0
- package/dist/types/refs.d.ts +54 -0
- package/dist/types/retry.d.ts +52 -0
- package/dist/types/stores/memory.d.ts +16 -0
- package/dist/{s3.d.ts → types/stores/s3.d.ts} +4 -7
- package/dist/{types-dbHzZ4ed.d.ts → types/types.d.ts} +11 -22
- package/package.json +18 -22
- package/dist/chunk-YQFNY6PG.js.map +0 -1
- package/dist/http.cjs +0 -1063
- package/dist/http.cjs.map +0 -1
- package/dist/http.d.cts +0 -215
- package/dist/http.d.ts +0 -215
- package/dist/index.cjs +0 -944
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -479
- package/dist/index.d.ts +0 -479
- package/dist/ops.cjs +0 -1060
- package/dist/ops.cjs.map +0 -1
- package/dist/ops.d.cts +0 -302
- package/dist/ops.d.ts +0 -302
- package/dist/s3.cjs +0 -123
- package/dist/s3.cjs.map +0 -1
- package/dist/s3.d.cts +0 -36
- package/dist/types-BHoHOaQt.d.ts +0 -53
- package/dist/types-dbHzZ4ed.d.cts +0 -131
- /package/dist/{chunk-Z4656PGE.js.map → chunk-2JP4MS6H.js.map} +0 -0
package/dist/http.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/http/index.ts","../src/http/info-refs.ts","../src/edge-utils.ts","../src/ops/branch.ts","../src/refs.ts","../src/http/pkt-line.ts","../src/http/types.ts","../src/http/reachability.ts","../src/http/receive-pack.ts","../src/http/repack.ts","../src/pack-files.ts","../src/http/pack-reuse.ts","../src/http/upload-pack.ts"],"sourcesContent":["export {\n\ttype GitService,\n\thandleInfoRefs,\n\ttype InfoRefsOptions,\n\tlistAllRefs,\n} from \"./info-refs.js\";\nexport {\n\tFLUSH,\n\tparsePktLines,\n\tpktLine,\n\tpktLineBuffer,\n\tsideBandPackfile,\n} from \"./pkt-line.js\";\nexport {\n\tcollectReachableOids,\n\ttype ReachabilityResult,\n} from \"./reachability.js\";\nexport {\n\ttype ApplyReceivePackOptions,\n\tapplyReceivePack,\n\tapplyRefUpdates,\n\tensureRepoInitialized,\n\tindexIncomingPack,\n\tparseReceivePackBody,\n\ttype RefUpdateCommand,\n\ttype RefUpdateResult,\n\treceivePackResponse,\n} from \"./receive-pack.js\";\nexport {\n\tREPACK_PACK_COUNT_THRESHOLD,\n\ttype RepackOptions,\n\trepackRepository,\n} from \"./repack.js\";\nexport {\n\ttype GitHttpResult,\n\ttype HttpHooks,\n\ttype RawFsPromises,\n\trawFs,\n} from \"./types.js\";\nexport { handleUploadPack, type UploadPackOptions } from \"./upload-pack.js\";\n","import git from \"isomorphic-git\";\nimport { concat } from \"../edge-utils.js\";\nimport {\n\tlistBranches,\n\tlistLooseRefNames,\n\tresolveLooseRefFast,\n} from \"../ops/branch.js\";\nimport type { Repo } from \"../ops/types.js\";\nimport { FLUSH, pktLine } from \"./pkt-line.js\";\nimport { type GitHttpResult, type HttpHooks, runStep } from \"./types.js\";\n\nexport type GitService = \"git-upload-pack\" | \"git-receive-pack\";\n\n/** All refs with resolved oids, plus the symref HEAD should advertise. */\nexport async function listAllRefs(repo: Repo, defaultBranch = \"main\") {\n\tconst [branches, tagNames] = await Promise.all([\n\t\tlistBranches(repo),\n\t\tlistLooseRefNames(repo, \"refs/tags\").then(\n\t\t\t(names) => names ?? git.listTags(repo),\n\t\t),\n\t]);\n\tconst tagRefs = await Promise.all(\n\t\ttagNames.map(async (tag) => {\n\t\t\tconst name = `refs/tags/${tag}`;\n\t\t\treturn resolveLooseRefFast(repo, name)\n\t\t\t\t.then((oid) => ({ name, oid }))\n\t\t\t\t.catch(() => null);\n\t\t}),\n\t);\n\tconst branchRefs = branches.map((b) => ({\n\t\tname: `refs/heads/${b.name}`,\n\t\toid: b.commit,\n\t}));\n\tconst defaultRef = branches.find((b) => b.isDefault);\n\tconst headSymref = defaultRef\n\t\t? `refs/heads/${defaultRef.name}`\n\t\t: await Promise.resolve(git.currentBranch({ ...repo, fullname: true }))\n\t\t\t\t.then((cb) => cb ?? `refs/heads/${defaultBranch}`)\n\t\t\t\t.catch(() => `refs/heads/${defaultBranch}`);\n\n\t// HEAD in a bare repo is almost always a symref to a branch whose oid\n\t// branchRefs already resolved above with one direct GET each — reuse it\n\t// instead of a second, separate resolveRef(\"HEAD\") call. isomorphic-git's\n\t// ref resolution runs its full multi-candidate expansion (refs/%s,\n\t// refs/tags/%s, refs/heads/%s, refs/remotes/%s, refs/remotes/%s/HEAD)\n\t// even when the symref target is already fully qualified, which used to\n\t// cost several guaranteed-404 R2 reads on every clone/fetch. Falls back\n\t// to the slow-but-correct path only when that lookup misses: detached\n\t// HEAD (points at a raw sha, not a symref) or a symref to a branch that\n\t// doesn't exist yet (freshly initialized, still-empty repo).\n\tconst headOid =\n\t\tbranchRefs.find((r) => r?.name === headSymref)?.oid ??\n\t\t(await git.resolveRef({ ...repo, ref: \"HEAD\" }).catch(() => null));\n\n\tconst refs: Array<{ name: string; oid: string }> = [];\n\tif (headOid) refs.push({ name: \"HEAD\", oid: headOid });\n\tfor (const r of branchRefs) if (r) refs.push(r);\n\tfor (const r of tagRefs) if (r) refs.push(r);\n\n\treturn { refs, headSymref };\n}\n\nexport interface InfoRefsOptions {\n\tservice: GitService;\n\tdefaultBranch?: string;\n\t/** Advertised in the agent capability. Default \"git-fs-s3\". */\n\tagent?: string;\n}\n\n/**\n * `GET …/info/refs?service=…` — the ref advertisement. Authentication and\n * authorization are the caller's job before invoking this.\n *\n * Capabilities advertised match what the sibling handlers implement:\n * side-band-64k (honored by handleUploadPack's response framing — clients\n * like isomorphic-git unconditionally expect it), tip/reachable sha1 wants,\n * delete-refs and report-status for pushes.\n */\nexport async function handleInfoRefs(\n\trepo: Repo,\n\toptions: InfoRefsOptions,\n\thooks?: HttpHooks,\n): Promise<GitHttpResult> {\n\tconst { service } = options;\n\tconst agent = options.agent ?? \"git-fs-s3\";\n\tconst { refs, headSymref } = await runStep(hooks, \"listAllRefs\", () =>\n\t\tlistAllRefs(repo, options.defaultBranch ?? \"main\"),\n\t);\n\n\tconst isUpload = service === \"git-upload-pack\";\n\tconst caps = isUpload\n\t\t? `no-progress side-band-64k symref=HEAD:${headSymref} allow-tip-sha1-in-want allow-reachable-sha1-in-want agent=${agent}`\n\t\t: `delete-refs report-status no-done agent=${agent}`;\n\n\tconst parts: Uint8Array[] = [pktLine(`# service=${service}\\n`), FLUSH];\n\n\tif (refs.length === 0) {\n\t\t// Empty repo: git needs this exact sentinel\n\t\tparts.push(\n\t\t\tpktLine(\n\t\t\t\t`0000000000000000000000000000000000000000 capabilities^{}\\0${caps}\\n`,\n\t\t\t),\n\t\t);\n\t} else {\n\t\tlet first = true;\n\t\tfor (const { name, oid } of refs) {\n\t\t\tparts.push(\n\t\t\t\tpktLine(first ? `${oid} ${name}\\0${caps}\\n` : `${oid} ${name}\\n`),\n\t\t\t);\n\t\t\tfirst = false;\n\t\t}\n\t}\n\tparts.push(FLUSH);\n\n\treturn {\n\t\tstatus: 200,\n\t\theaders: {\n\t\t\t\"Content-Type\": `application/x-${service}-advertisement`,\n\t\t\t\"Cache-Control\": \"no-cache\",\n\t\t},\n\t\tbody: concat(...parts),\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// ---------------------------------------------------------------------------\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","import git from \"isomorphic-git\";\nimport { GitInvalidRequestError } from \"../git-errors.js\";\nimport { isSafeBranchName } from \"../refs.js\";\nimport type { Repo } from \"./types.js\";\n\nexport interface Branch {\n\tname: string;\n\tcommit: string;\n\tisDefault: boolean;\n}\n\n/**\n * Defense in depth for every branch-name argument below: `git.deleteBranch`\n * and raw resolveRef/writeRef reads don't validate ref names internally the\n * way `git.branch` does (see refs.ts) — guard at the point the primitives are\n * actually called, not just at an API boundary far above.\n */\nexport function assertSafeBranchName(name: string): void {\n\tif (!isSafeBranchName(name)) {\n\t\tthrow new GitInvalidRequestError(`Invalid branch name: ${name}`);\n\t}\n}\n\nconst FULL_SHA_RE = /^[0-9a-f]{40}$/i;\n\ntype RecursiveFileLister = {\n\tlistFilesRecursively(dirpath: string): Promise<string[]>;\n};\n\nfunction hasRecursiveFileLister(\n\tfs: Repo[\"fs\"],\n): fs is Repo[\"fs\"] & RecursiveFileLister {\n\treturn (\n\t\ttypeof fs === \"object\" &&\n\t\tfs !== null &&\n\t\t\"listFilesRecursively\" in fs &&\n\t\ttypeof (fs as Partial<RecursiveFileLister>).listFilesRecursively ===\n\t\t\t\"function\"\n\t);\n}\n\ntype PromisesFs = {\n\treadFile(path: string, encoding: \"utf8\"): Promise<string | Uint8Array>;\n};\n\n// Repo.fs is typed as isomorphic-git's own fs union (promise- or\n// callback-based) since that's what git.readTree's signature allows, but\n// every fs this package actually constructs (git-fs.ts) is promise-based —\n// this just keeps the callback-style branch honest instead of crashing on\n// it. Shared by every loose-ref fast path below instead of each repeating\n// the same cast + presence check.\nfunction getPromisesFs(fs: Repo[\"fs\"]): PromisesFs | null {\n\tconst promises = (fs as { promises?: PromisesFs }).promises;\n\treturn promises ?? null;\n}\n\nfunction decodeFileContent(content: string | Uint8Array): string {\n\treturn typeof content === \"string\"\n\t\t? content\n\t\t: new TextDecoder().decode(content);\n}\n\n/**\n * Lists loose branch names without isomorphic-git's recursive readdir/stat\n * traversal. Object stores already return only leaf keys in a recursive LIST,\n * so this is one request regardless of branch-name nesting. Ordinary\n * filesystems retain isomorphic-git's implementation and packed refs remain\n * supported there.\n */\nasync function listLooseBranches(repo: Repo): Promise<string[] | null> {\n\treturn listLooseRefNames(repo, \"refs/heads\");\n}\n\n/**\n * Loose ref names under `dir` (e.g. `refs/tags`) in one recursive listing,\n * or `null` when the fs can't list recursively (use isomorphic-git's walk).\n */\nexport async function listLooseRefNames(\n\trepo: Repo,\n\tdir: \"refs/heads\" | \"refs/tags\",\n): Promise<string[] | null> {\n\tif (!hasRecursiveFileLister(repo.fs)) return null;\n\tconst names = await repo.fs.listFilesRecursively(`${repo.gitdir}/${dir}`);\n\treturn names.filter(isSafeBranchName);\n}\n\n/** Read packed branch refs so the object-store fast path preserves Git semantics. */\nasync function readPackedBranches(repo: Repo): Promise<Map<string, string>> {\n\tif (!hasRecursiveFileLister(repo.fs)) return new Map();\n\tconst promisesFs = getPromisesFs(repo.fs);\n\tif (!promisesFs) return new Map();\n\ttry {\n\t\tconst content = await promisesFs.readFile(\n\t\t\t`${repo.gitdir}/packed-refs`,\n\t\t\t\"utf8\",\n\t\t);\n\t\tconst refs = new Map<string, string>();\n\t\tfor (const line of decodeFileContent(content).split(\"\\n\")) {\n\t\t\tconst match = /^([0-9a-f]{40}) refs\\/heads\\/(.+)$/i.exec(line);\n\t\t\tif (match?.[1] && match[2] && isSafeBranchName(match[2])) {\n\t\t\t\trefs.set(match[2], match[1]);\n\t\t\t}\n\t\t}\n\t\treturn refs;\n\t} catch {\n\t\treturn new Map();\n\t}\n}\n\n/** Read the symbolic HEAD directly when the object-store fs is available. */\nasync function getCurrentLooseBranch(repo: Repo): Promise<string | null> {\n\tif (!hasRecursiveFileLister(repo.fs)) return null;\n\tconst promisesFs = getPromisesFs(repo.fs);\n\tif (!promisesFs) return null;\n\ttry {\n\t\tconst content = await promisesFs.readFile(`${repo.gitdir}/HEAD`, \"utf8\");\n\t\tconst head = decodeFileContent(content).trim();\n\t\tconst match = /^ref: refs\\/heads\\/(.+)$/.exec(head);\n\t\treturn match?.[1] && isSafeBranchName(match[1]) ? match[1] : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Resolve a fully-qualified ref's oid with one read instead of isomorphic-\n * git's own `resolveRef`, which does a stat *then* a read for a loose ref\n * (two round trips against object storage) — wasteful specifically here,\n * where the caller already knows the ref exists (it came from a directory\n * listing moments earlier). Reads the loose file directly and falls back to\n * `git.resolveRef` only when that doesn't pan out (packed-refs, or anything\n * else the plain-loose-file assumption doesn't cover), so correctness for\n * those cases is unchanged — this only removes the redundant round trip on\n * the common path.\n */\nexport async function resolveLooseRefFast(\n\trepo: Repo,\n\tref: string,\n): Promise<string> {\n\tconst promisesFs = getPromisesFs(repo.fs);\n\tif (promisesFs) {\n\t\ttry {\n\t\t\tconst content = await promisesFs.readFile(\n\t\t\t\t`${repo.gitdir}/${ref}`,\n\t\t\t\t\"utf8\",\n\t\t\t);\n\t\t\tconst oid = decodeFileContent(content).trim();\n\t\t\tif (FULL_SHA_RE.test(oid)) return oid;\n\t\t} catch {\n\t\t\t// Not a loose file (packed-refs, or genuinely absent) — fall through.\n\t\t}\n\t}\n\treturn git.resolveRef({ ...repo, ref });\n}\n\n/** All branches with their tip commits; [] for an empty repository. */\nexport async function listBranches(repo: Repo): Promise<Branch[]> {\n\ttry {\n\t\tconst [looseBranches, looseCurrentBranch, packedBranches] =\n\t\t\tawait Promise.all([\n\t\t\t\tlistLooseBranches(repo),\n\t\t\t\tgetCurrentLooseBranch(repo),\n\t\t\t\treadPackedBranches(repo),\n\t\t\t]);\n\t\tconst branches =\n\t\t\tlooseBranches === null\n\t\t\t\t? await git.listBranches(repo)\n\t\t\t\t: [...new Set([...looseBranches, ...packedBranches.keys()])].sort();\n\t\tconst currentBranch =\n\t\t\tlooseBranches === null\n\t\t\t\t? await git\n\t\t\t\t\t\t.currentBranch({ ...repo, fullname: false })\n\t\t\t\t\t\t.catch(() => null)\n\t\t\t\t: looseCurrentBranch;\n\n\t\treturn Promise.all(\n\t\t\tbranches.map(async (branch) => {\n\t\t\t\tconst packedCommit = packedBranches.get(branch);\n\t\t\t\treturn {\n\t\t\t\t\tname: branch,\n\t\t\t\t\tcommit:\n\t\t\t\t\t\tpackedCommit && !looseBranches?.includes(branch)\n\t\t\t\t\t\t\t? packedCommit\n\t\t\t\t\t\t\t: await resolveLooseRefFast(repo, `refs/heads/${branch}`),\n\t\t\t\t\tisDefault: branch === currentBranch,\n\t\t\t\t};\n\t\t\t}),\n\t\t);\n\t} catch (err: unknown) {\n\t\tif ((err as { code?: string }).code === \"NotFoundError\") return [];\n\t\tthrow err;\n\t}\n}\n\n/** Create `name` pointing at the tip of `startPoint` (no checkout). */\nexport async function createBranchFrom(\n\trepo: Repo,\n\tname: string,\n\tstartPoint = \"main\",\n): Promise<void> {\n\tassertSafeBranchName(name);\n\tassertSafeBranchName(startPoint);\n\tconst object = await resolveLooseRefFast(repo, `refs/heads/${startPoint}`);\n\tawait git.branch({ ...repo, ref: name, checkout: false, object });\n}\n\n/** Delete a branch ref (validated — deleteBranch has no internal ref check). */\nexport async function deleteBranchByName(\n\trepo: Repo,\n\tname: string,\n): Promise<void> {\n\tassertSafeBranchName(name);\n\tawait git.deleteBranch({ ...repo, ref: name });\n}\n\n/** Throws (NotFoundError) unless the branch resolves. */\nexport async function assertBranchExists(\n\trepo: Repo,\n\tname: string,\n): Promise<void> {\n\tassertSafeBranchName(name);\n\tawait resolveLooseRefFast(repo, `refs/heads/${name}`);\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","/**\n * Git pkt-line framing (smart HTTP protocol wire format).\n *\n * Edge-compatible: uses Uint8Array instead of Buffer.\n */\n\nimport { concat, decodeAscii, decodeUtf8, encodeUtf8 } from \"../edge-utils.js\";\n\n/** Flush packet: exactly four zero bytes. */\nexport const FLUSH: Uint8Array<ArrayBuffer> = new Uint8Array([\n\t0x30, 0x30, 0x30, 0x30,\n]); // \"0000\"\n\n/** Frame a UTF-8 string as one pkt-line. */\nexport function pktLine(data: string): Uint8Array<ArrayBuffer> {\n\tconst body = encodeUtf8(data);\n\tconst len = (body.length + 4).toString(16).padStart(4, \"0\");\n\treturn concat(encodeUtf8(len), body);\n}\n\n/** Frame raw bytes as one pkt-line. */\nexport function pktLineBuffer(body: Uint8Array): Uint8Array<ArrayBuffer> {\n\tconst len = (body.length + 4).toString(16).padStart(4, \"0\");\n\treturn concat(encodeUtf8(len), body);\n}\n\n/** Decode pkt-lines to strings; `null` marks a flush-pkt. Stops on garbage. */\nexport function parsePktLines(buf: Uint8Array): Array<string | null> {\n\tconst lines: Array<string | null> = [];\n\tlet pos = 0;\n\twhile (pos + 4 <= buf.length) {\n\t\tconst len = Number.parseInt(decodeAscii(buf.subarray(pos, pos + 4)), 16);\n\t\tif (len === 0) {\n\t\t\tlines.push(null);\n\t\t\tpos += 4;\n\t\t} else if (len >= 4) {\n\t\t\tlines.push(decodeUtf8(buf.subarray(pos + 4, pos + len)));\n\t\t\tpos += len;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn lines;\n}\n\n/**\n * Per the git protocol, once side-band-64k has been negotiated, packfile\n * bytes in the upload-pack response must be chunked into pkt-lines each\n * prefixed with a control byte (0x01 = packfile data), terminated by a\n * flush-pkt. Without this, clients that don't special-case \"no side-band\" —\n * e.g. isomorphic-git's GitSideBand.demux, which always treats the response\n * as side-band-framed — misparse the raw packfile bytes as bogus pkt-line\n * length headers and spin forever. (Native `git` tolerates a raw unframed\n * stream when side-band isn't negotiated, so this only surfaces with\n * isomorphic-git as the HTTP client.)\n */\nconst SIDE_BAND_MAX_CHUNK = 65515;\n\nexport function sideBandPackfile(\n\tpackData: Uint8Array,\n): Uint8Array<ArrayBuffer> {\n\tconst parts: Uint8Array[] = [];\n\tfor (\n\t\tlet offset = 0;\n\t\toffset < packData.length;\n\t\toffset += SIDE_BAND_MAX_CHUNK\n\t) {\n\t\tconst chunk = packData.subarray(offset, offset + SIDE_BAND_MAX_CHUNK);\n\t\tparts.push(pktLineBuffer(concat(new Uint8Array([1]), chunk)));\n\t}\n\tparts.push(FLUSH);\n\treturn concat(...parts);\n}\n","import type { Repo } from \"../ops/types.js\";\n\n/**\n * Transport-agnostic HTTP response the handlers produce.\n *\n * `body` is pinned to `Uint8Array<ArrayBuffer>` (not the bare `Uint8Array`,\n * whose default type argument isn't consistent across TypeScript versions)\n * so it's always assignable to Fetch API `BodyInit` regardless of which\n * TypeScript/lib version a consumer compiles against — every producer here\n * (`concat`, `pktLine`, `TextEncoder.encode`) is ArrayBuffer-backed already.\n */\nexport interface GitHttpResult {\n\tstatus: number;\n\theaders: Record<string, string>;\n\tbody: Uint8Array<ArrayBuffer>;\n}\n\n/** Optional instrumentation hooks shared by the /http handlers. */\nexport interface HttpHooks {\n\t/** Wrap a timed sub-step. Default: run directly. */\n\tstep?: <T>(label: string, fn: () => Promise<T>) => Promise<T>;\n\t/** Non-fatal problem sink (missing objects, failed repacks). */\n\tonWarn?: (message: string, error?: unknown) => void;\n}\n\nexport const runStep = <T>(\n\thooks: HttpHooks | undefined,\n\tlabel: string,\n\tfn: () => Promise<T>,\n): Promise<T> => (hooks?.step ? hooks.step(label, fn) : fn());\n\n/**\n * The raw promise-fs surface some /http paths need beyond isomorphic-git's\n * plumbing (writing an incoming pack file, listing/deleting pack files).\n * Both `node:fs` and this package's `GitFs` satisfy it via `.promises`.\n */\nexport interface RawFsPromises {\n\treadFile(path: string): Promise<Uint8Array | string>;\n\twriteFile(path: string, data: Uint8Array | string): Promise<void>;\n\tunlink(path: string): Promise<void>;\n\treaddir(path: string): Promise<string[]>;\n\tmkdir(path: string, options?: { recursive?: boolean }): Promise<unknown>;\n\tstat(path: string): Promise<unknown>;\n}\n\n/** Duck-type the `.promises` surface off a repo's fs. */\nexport function rawFs(repo: Repo): RawFsPromises {\n\tconst fs = repo.fs as { promises?: RawFsPromises };\n\tif (!fs?.promises) {\n\t\tthrow new TypeError(\n\t\t\t\"This operation needs a promise fs (`fs.promises`) — node:fs and createGitFs both provide one\",\n\t\t);\n\t}\n\treturn fs.promises;\n}\n","import git from \"isomorphic-git\";\nimport type { Repo } from \"../ops/types.js\";\nimport type { HttpHooks } from \"./types.js\";\n\nexport interface ReachabilityResult {\n\toids: string[];\n\t/**\n\t * False if any object in the graph couldn't be read — repack uses this\n\t * (not a raw object-count comparison) to decide whether it's safe to\n\t * delete old packs: counts alone can't distinguish \"everything read fine\"\n\t * from \"some objects silently failed\".\n\t */\n\tcomplete: boolean;\n}\n\nconst delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * A read landing in the gap between a repack's new consolidated pack being\n * uploaded and the stale-pack cleanup finishing can transiently miss an\n * object that is not actually lost — it exists in the new pack the whole\n * time; the reader's cached pack listing was just taken mid-transition. One\n * retry after a short delay is enough to observe the consistent listing.\n */\nconst MISSING_OBJECT_RETRY_DELAY_MS = 200;\n\n/**\n * Walk the object graph from `startOids`, returning every reachable oid.\n * Concurrent traversal paths are deduplicated promise-per-oid; a missing\n * object is retried once, then reported through `hooks.onWarn` and\n * reflected in `complete: false`.\n *\n * `haveOids` bounds the walk: any oid in this set is assumed already\n * verified (it was reachable from a ref that existed before this call) and\n * is recorded in `seen` without being read or descended into. Without a\n * boundary, every call re-walks the *entire* history from scratch — for\n * receive-pack validation (see receive-pack.ts) that means every push pays\n * for reading every object in the repo, not just the ones it introduced,\n * and one transient read failure anywhere in that whole history rejects an\n * otherwise-valid push.\n *\n * Commits, trees and tags are read once each (parsed). Blobs have no\n * children, so `verifyBlobs: false` records a blob from its tree entry\n * without reading (and inflating) it — for callers that read every blob\n * themselves afterwards anyway, like upload-pack's `packObjects`. Leave it\n * true wherever the walk *is* the existence check (receive-pack, repack).\n */\nexport async function collectReachableOids(\n\trepo: Repo,\n\tstartOids: string[],\n\thooks?: HttpHooks,\n\thaveOids?: ReadonlySet<string> | readonly string[],\n\toptions?: { verifyBlobs?: boolean },\n): Promise<ReachabilityResult> {\n\tconst verifyBlobs = options?.verifyBlobs ?? true;\n\tconst have = haveOids instanceof Set ? haveOids : new Set(haveOids ?? []);\n\tconst seen = new Set<string>();\n\tlet complete = true;\n\tconst promises = new Map<string, Promise<void>>();\n\n\tasync function readAndVisitChildren(oid: string): Promise<void> {\n\t\tconst obj = await git.readObject({ ...repo, oid });\n\t\tseen.add(oid);\n\t\tconst children: [string, string | undefined][] = [];\n\t\tif (obj.type === \"commit\") {\n\t\t\tconst commit = obj.object as { tree: string; parent: string[] };\n\t\t\tchildren.push([commit.tree, \"tree\"]);\n\t\t\tfor (const parent of commit.parent) children.push([parent, \"commit\"]);\n\t\t} else if (obj.type === \"tree\") {\n\t\t\tconst tree = obj.object as { oid: string; type: string }[];\n\t\t\tfor (const entry of tree) {\n\t\t\t\t// Gitlinks (submodules, mode 160000) point at commits in another\n\t\t\t\t// repository; git never stores them here, so following one would\n\t\t\t\t// report a \"missing\" object and fail every walk over that history.\n\t\t\t\tif (entry.type === \"commit\") continue;\n\t\t\t\tchildren.push([entry.oid, entry.type]);\n\t\t\t}\n\t\t} else if (obj.type === \"tag\") {\n\t\t\tchildren.push([(obj.object as { object: string }).object, undefined]);\n\t\t}\n\t\tawait Promise.all(children.map(([child, type]) => visit(child, type)));\n\t}\n\n\tfunction visit(oid: string, type?: string): Promise<void> {\n\t\tconst existing = promises.get(oid);\n\t\tif (existing) return existing;\n\n\t\tif (have.has(oid) || (type === \"blob\" && !verifyBlobs)) {\n\t\t\tseen.add(oid);\n\t\t\tconst p = Promise.resolve();\n\t\t\tpromises.set(oid, p);\n\t\t\treturn p;\n\t\t}\n\n\t\tconst p = (async () => {\n\t\t\ttry {\n\t\t\t\tawait readAndVisitChildren(oid);\n\t\t\t} catch {\n\t\t\t\ttry {\n\t\t\t\t\tawait delay(MISSING_OBJECT_RETRY_DELAY_MS);\n\t\t\t\t\tawait readAndVisitChildren(oid);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tcomplete = false;\n\t\t\t\t\thooks?.onWarn?.(`missing object ${oid}`, err);\n\t\t\t\t}\n\t\t\t}\n\t\t})();\n\n\t\tpromises.set(oid, p);\n\t\treturn p;\n\t}\n\n\tawait Promise.all(startOids.map((oid) => visit(oid)));\n\treturn { oids: Array.from(seen), complete };\n}\n","import git from \"isomorphic-git\";\nimport { concat, decodeAscii, decodeUtf8 } from \"../edge-utils.js\";\nimport type { Repo } from \"../ops/types.js\";\nimport { isSafeFullRefName } from \"../refs.js\";\nimport { FLUSH, pktLine } from \"./pkt-line.js\";\nimport { collectReachableOids } from \"./reachability.js\";\nimport { type RepackOptions, repackRepository } from \"./repack.js\";\nimport { type GitHttpResult, type HttpHooks, rawFs, runStep } from \"./types.js\";\n\nconst ZERO_OID = \"0\".repeat(40);\n\nexport interface RefUpdateCommand {\n\toldOid: string;\n\tnewOid: string;\n\trefName: string;\n}\n\nexport interface RefUpdateResult {\n\trefName: string;\n\tok: boolean;\n\treason?: string;\n}\n\n/** Split a receive-pack body: pkt-line ref commands, flush, then raw PACK. */\nexport function parseReceivePackBody(body: Uint8Array): {\n\trefUpdates: RefUpdateCommand[];\n\tpackData: Uint8Array;\n} {\n\tconst refUpdates: RefUpdateCommand[] = [];\n\tlet pos = 0;\n\twhile (pos + 4 <= body.length) {\n\t\tconst len = Number.parseInt(decodeAscii(body.subarray(pos, pos + 4)), 16);\n\t\tif (len === 0) {\n\t\t\tpos += 4;\n\t\t\tbreak; // flush = end of ref update commands\n\t\t}\n\t\tif (len < 4) break;\n\t\t// Strip NUL-separated capabilities from the first command line\n\t\tconst line = decodeUtf8(body.subarray(pos + 4, pos + len))\n\t\t\t.replace(/\\n$/, \"\")\n\t\t\t.split(\"\\0\")[0];\n\t\tpos += len;\n\t\tconst parts = (line ?? \"\").split(\" \");\n\t\tconst [oldOid, newOid, refName] = parts;\n\t\tif (oldOid && newOid && refName) {\n\t\t\trefUpdates.push({ oldOid, newOid, refName });\n\t\t}\n\t}\n\treturn { refUpdates, packData: body.subarray(pos) };\n}\n\n/** Initialize the repo when its HEAD doesn't exist yet (first push). */\nexport async function ensureRepoInitialized(\n\trepo: Repo,\n\tdefaultBranch = \"main\",\n): Promise<void> {\n\tconst fsp = rawFs(repo);\n\ttry {\n\t\tawait fsp.stat(`${repo.gitdir}/HEAD`);\n\t} catch {\n\t\tawait fsp.mkdir(repo.gitdir, { recursive: true }).catch(() => {});\n\t\tawait git.init({ ...repo, dir: repo.gitdir, defaultBranch, bare: true });\n\t}\n}\n\n/** Write the incoming PACK into objects/pack/ and index it. */\nexport async function indexIncomingPack(\n\trepo: Repo,\n\tpackData: Uint8Array,\n\thooks?: HttpHooks,\n): Promise<string[]> {\n\tif (packData.length < 4) return [];\n\tconst packName = await runStep(\n\t\thooks,\n\t\t\"write + indexPack incoming pack\",\n\t\tasync () => {\n\t\t\tconst fsp = rawFs(repo);\n\t\t\tconst packDir = `${repo.gitdir}/objects/pack`;\n\t\t\tawait fsp.mkdir(packDir, { recursive: true });\n\n\t\t\tconst packName = `recv-${Date.now()}`;\n\t\t\tawait fsp.writeFile(`${packDir}/${packName}.pack`, packData);\n\n\t\t\tawait git.indexPack({\n\t\t\t\t...repo,\n\t\t\t\tdir: packDir,\n\t\t\t\tfilepath: `${packName}.pack`,\n\t\t\t});\n\t\t\treturn packName;\n\t\t},\n\t);\n\treturn [\n\t\t`${repo.gitdir}/objects/pack/${packName}.pack`,\n\t\t`${repo.gitdir}/objects/pack/${packName}.idx`,\n\t];\n}\n\n/**\n * Validate a ref name and compare-and-swap it against its claimed current\n * oid. Returns the failure result to report if either check fails, or\n * `null` when both pass — shared by the preflight check (`validateRefUpdates`,\n * run before the possibly-slow pack indexing/graph-walk work, purely to\n * avoid doing that work for an update already doomed to fail) and the real\n * atomicity guarantee (`applyRefUpdates`, run again right before writing,\n * since a concurrent push could have moved the ref in the time that work\n * took).\n */\nasync function checkRefCas(\n\trepo: Repo,\n\trefName: string,\n\toldOid: string,\n): Promise<RefUpdateResult | null> {\n\tif (!isSafeFullRefName(refName)) {\n\t\treturn { refName, ok: false, reason: \"invalid ref name\" };\n\t}\n\tconst currentOid = await git\n\t\t.resolveRef({ ...repo, ref: refName })\n\t\t.catch(() => ZERO_OID);\n\treturn currentOid === oldOid\n\t\t? null\n\t\t: {\n\t\t\t\trefName,\n\t\t\t\tok: false,\n\t\t\t\treason: \"non-fast-forward, ref updated by another push\",\n\t\t\t};\n}\n\n/** Every branch/tag tip currently in the repo, as a validation boundary — see\n * its call site in {@link applyReceivePack}. */\nasync function collectExistingRefTips(repo: Repo): Promise<Set<string>> {\n\tconst [branches, tags] = await Promise.all([\n\t\tgit.listBranches(repo),\n\t\tgit.listTags(repo),\n\t]);\n\tconst refs = [\n\t\t...branches.map((b) => `refs/heads/${b}`),\n\t\t...tags.map((t) => `refs/tags/${t}`),\n\t];\n\tconst oids = await Promise.all(\n\t\trefs.map((ref) => git.resolveRef({ ...repo, ref }).catch(() => null)),\n\t);\n\treturn new Set(oids.filter((oid): oid is string => oid !== null));\n}\n\nasync function validateRefUpdates(\n\trepo: Repo,\n\trefUpdates: RefUpdateCommand[],\n): Promise<RefUpdateResult[]> {\n\treturn Promise.all(\n\t\trefUpdates.map(\n\t\t\tasync ({ oldOid, refName }) =>\n\t\t\t\t(await checkRefCas(repo, refName, oldOid)) ?? { refName, ok: true },\n\t\t),\n\t);\n}\n\n/**\n * Apply ref updates, enforcing compare-and-swap against each command's\n * claimed oldOid. Every client-supplied refName is validated before any\n * filesystem call reads or writes through it.\n */\nexport async function applyRefUpdates(\n\trepo: Repo,\n\trefUpdates: RefUpdateCommand[],\n\thooks?: HttpHooks,\n): Promise<RefUpdateResult[]> {\n\treturn runStep(hooks, \"apply ref updates\", () =>\n\t\tPromise.all(\n\t\t\trefUpdates.map(async ({ oldOid, newOid, refName }) => {\n\t\t\t\tconst failure = await checkRefCas(repo, refName, oldOid);\n\t\t\t\tif (failure) return failure;\n\n\t\t\t\tif (newOid === ZERO_OID) {\n\t\t\t\t\tawait git.deleteRef({ ...repo, ref: refName }).catch(() => {});\n\t\t\t\t} else {\n\t\t\t\t\tawait git.writeRef({\n\t\t\t\t\t\t...repo,\n\t\t\t\t\t\tref: refName,\n\t\t\t\t\t\tvalue: newOid,\n\t\t\t\t\t\tforce: true,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn { refName, ok: true };\n\t\t\t}),\n\t\t),\n\t);\n}\n\n/** The report-status response body for a set of ref-update results. */\nexport function receivePackResponse(results: RefUpdateResult[]): GitHttpResult {\n\tconst responseBody = concat(\n\t\tpktLine(\"unpack ok\\n\"),\n\t\t...results.map(({ refName, ok, reason }) =>\n\t\t\tpktLine(ok ? `ok ${refName}\\n` : `ng ${refName} ${reason}\\n`),\n\t\t),\n\t\tFLUSH,\n\t);\n\n\treturn {\n\t\tstatus: 200,\n\t\theaders: {\n\t\t\t\"Content-Type\": \"application/x-git-receive-pack-result\",\n\t\t\t\"Cache-Control\": \"no-cache\",\n\t\t},\n\t\tbody: responseBody,\n\t};\n}\n\nexport interface ApplyReceivePackOptions {\n\tdefaultBranch?: string;\n\t/**\n\t * Repack tuning, or `false` to skip repacking entirely. The returned\n\t * `stalePackPaths` are gitdir-relative pack files the repack deleted from\n\t * this repo — after syncing to any secondary storage, delete them there\n\t * too.\n\t */\n\trepack?: RepackOptions | false;\n}\n\n/**\n * The storage half of a push against `repo`: initialize if needed, index the\n * incoming pack, CAS-apply ref updates, then repack when enough packs have\n * accumulated. Serialize concurrent pushes to the same repo externally (a\n * per-repo lock); build the HTTP response afterwards with\n * {@link receivePackResponse}.\n */\nexport async function applyReceivePack(\n\trepo: Repo,\n\tparsed: { refUpdates: RefUpdateCommand[]; packData: Uint8Array },\n\toptions?: ApplyReceivePackOptions,\n\thooks?: HttpHooks,\n): Promise<{ results: RefUpdateResult[]; stalePackPaths: string[] }> {\n\tawait ensureRepoInitialized(repo, options?.defaultBranch ?? \"main\");\n\tconst preflight = await validateRefUpdates(repo, parsed.refUpdates);\n\tconst acceptedUpdates = parsed.refUpdates.filter(\n\t\t(_, index) => preflight[index]?.ok,\n\t);\n\tconst incomingPackPaths = await indexIncomingPack(\n\t\trepo,\n\t\tacceptedUpdates.some((update) => update.newOid !== ZERO_OID)\n\t\t\t? parsed.packData\n\t\t\t: new Uint8Array(),\n\t\thooks,\n\t);\n\n\tconst newTips = acceptedUpdates\n\t\t.filter((update) => update.newOid !== ZERO_OID)\n\t\t.map((update) => update.newOid);\n\tif (newTips.length > 0) {\n\t\t// Every oid reachable from an existing ref was already accepted by an\n\t\t// earlier push — not just the ref(s) this push happens to touch. A\n\t\t// brand-new branch (oldOid === ZERO_OID, so it has no pre-image of its\n\t\t// own) is the common case this matters for: creating a branch off an\n\t\t// existing one is still just one new commit's worth of new objects,\n\t\t// and shouldn't cost a walk of the entire repo history to validate.\n\t\tconst haveOids = await collectExistingRefTips(repo);\n\t\tfor (const update of acceptedUpdates) {\n\t\t\tif (update.oldOid !== ZERO_OID) haveOids.add(update.oldOid);\n\t\t}\n\t\tconst { complete } = await collectReachableOids(\n\t\t\trepo,\n\t\t\tnewTips,\n\t\t\thooks,\n\t\t\thaveOids,\n\t\t);\n\t\tif (!complete) {\n\t\t\tawait Promise.all(\n\t\t\t\tincomingPackPaths.map((filepath) =>\n\t\t\t\t\trawFs(repo)\n\t\t\t\t\t\t.unlink(filepath)\n\t\t\t\t\t\t.catch(() => {}),\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn {\n\t\t\t\tresults: preflight.map((result) =>\n\t\t\t\t\tresult.ok\n\t\t\t\t\t\t? { ...result, ok: false, reason: \"incomplete object graph\" }\n\t\t\t\t\t\t: result,\n\t\t\t\t),\n\t\t\t\tstalePackPaths: [],\n\t\t\t};\n\t\t}\n\t}\n\n\tconst applied = await applyRefUpdates(repo, acceptedUpdates, hooks);\n\tconst results = preflight.map((result, index) =>\n\t\tresult.ok\n\t\t\t? (applied.find(\n\t\t\t\t\t(entry) => entry.refName === parsed.refUpdates[index]?.refName,\n\t\t\t\t) ?? result)\n\t\t\t: result,\n\t);\n\tconst repackOptions = options?.repack;\n\tconst stalePackPaths =\n\t\trepackOptions === false || !results.some((result) => result.ok)\n\t\t\t? []\n\t\t\t: await runStep(hooks, \"repack\", () =>\n\t\t\t\t\trepackRepository(repo, repackOptions, hooks),\n\t\t\t\t);\n\treturn { results, stalePackPaths };\n}\n","/**\n * Pack consolidation: merge all packs into one, reusing stored (possibly\n * deltified) entries when every object is packed.\n *\n * Edge-compatible: uses Web Crypto (SHA-1), CompressionStream (deflate),\n * and Uint8Array throughout — no node:crypto, node:zlib, or Buffer.\n */\n\nimport git from \"isomorphic-git\";\nimport { concat, deflate, encodeUtf8, fromHex, sha1 } from \"../edge-utils.js\";\nimport type { Repo } from \"../ops/types.js\";\nimport {\n\ttype PackFileName,\n\tpackFileName,\n\tparsePackDirectory,\n} from \"../pack-files.js\";\nimport { buildPackFromExistingPacks } from \"./pack-reuse.js\";\nimport { collectReachableOids } from \"./reachability.js\";\nimport { type HttpHooks, rawFs } from \"./types.js\";\n\ntype PackObjectType = \"commit\" | \"tree\" | \"blob\" | \"tag\";\n\n// Git pack object type bits (bits 6-4 of the header's first byte) — same\n// constants real git and isomorphic-git's own (de)serializers use.\nconst PACK_OBJECT_TYPE_BITS: Record<PackObjectType, number> = {\n\tcommit: 0b0010000,\n\ttree: 0b0100000,\n\tblob: 0b0110000,\n\ttag: 0b1000000,\n};\n\n// Git's pack object header: first byte packs (continuation bit | 3-bit type |\n// low 4 bits of length); any remaining length is emitted 7 bits at a time,\n// each with its own continuation bit, little-endian.\nfunction encodePackObjectHeader(\n\ttype: PackObjectType,\n\tlength: number,\n): Uint8Array {\n\tconst bytes: number[] = [];\n\tlet more = length > 0b1111;\n\tbytes.push(\n\t\t(more ? 0b10000000 : 0) | PACK_OBJECT_TYPE_BITS[type] | (length & 0b1111),\n\t);\n\tlength >>>= 4;\n\twhile (more) {\n\t\tmore = length > 0b01111111;\n\t\tbytes.push((more ? 0b10000000 : 0) | (length & 0b01111111));\n\t\tlength >>>= 7;\n\t}\n\treturn new Uint8Array(bytes);\n}\n\n// Git's object hash: sha1(\"<type> <byte length>\\0<content>\") — matches\n// isomorphic-git's internal GitObject.wrap + shasum, computed independently\n// here rather than trusted from isomorphic-git's own read path.\nasync function hashGitObject(\n\ttype: string,\n\tcontent: Uint8Array,\n): Promise<string> {\n\tconst prefix = encodeUtf8(`${type} ${content.length}\\0`);\n\treturn sha1(concat(prefix, content));\n}\n\ntype VerifiedObject = { type: PackObjectType; content: Uint8Array };\n\n/**\n * Read every reachable object and independently re-derive its oid from the\n * bytes isomorphic-git handed back, instead of trusting the oid it was asked\n * for. isomorphic-git's *packed*-object read path never verifies the\n * resolved content's SHA-1 against the requested oid — only the\n * loose-object branch does.\n */\nasync function readAndVerifyObjects(\n\trepo: Repo,\n\toids: string[],\n): Promise<Map<string, VerifiedObject>> {\n\tconst objects = new Map<string, VerifiedObject>();\n\tconst BATCH_SIZE = 100;\n\tfor (let i = 0; i < oids.length; i += BATCH_SIZE) {\n\t\tconst batch = oids.slice(i, i + BATCH_SIZE);\n\t\tconst entries = await Promise.all(\n\t\t\tbatch.map(async (oid) => {\n\t\t\t\tconst { type, object } = await git.readObject({\n\t\t\t\t\t...repo,\n\t\t\t\t\toid,\n\t\t\t\t\tformat: \"content\",\n\t\t\t\t});\n\t\t\t\tconst content = object as unknown as Uint8Array;\n\t\t\t\tconst actualOid = await hashGitObject(type, content);\n\t\t\t\tif (actualOid !== oid) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`repack: object ${oid} failed independent SHA-1 verification ` +\n\t\t\t\t\t\t\t`(recomputed ${actualOid}) — refusing to trust this read, aborting repack`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn { oid, type: type as PackObjectType, content };\n\t\t\t}),\n\t\t);\n\t\tfor (const { oid, type, content } of entries) {\n\t\t\tobjects.set(oid, { type, content });\n\t\t}\n\t}\n\treturn objects;\n}\n\n/**\n * Serialize verified objects into a pack containing only full (never\n * deltified) entries, in the given oid order.\n */\nasync function buildVerifiedPack(\n\toids: string[],\n\tobjects: Map<string, VerifiedObject>,\n): Promise<Uint8Array> {\n\t// PACK header: \"PACK\" + version(2) + count, all big-endian uint32\n\tconst header = new Uint8Array(12);\n\tconst view = new DataView(header.buffer);\n\theader.set(encodeUtf8(\"PACK\"), 0);\n\tview.setUint32(4, 2, false); // version 2\n\tview.setUint32(8, oids.length, false); // object count\n\n\tconst chunks: Uint8Array[] = [header];\n\n\tconst BATCH_SIZE = 100;\n\tfor (let i = 0; i < oids.length; i += BATCH_SIZE) {\n\t\tconst batch = oids.slice(i, i + BATCH_SIZE);\n\t\tconst encoded = await Promise.all(\n\t\t\tbatch.map(async (oid) => {\n\t\t\t\tconst entry = objects.get(oid);\n\t\t\t\tif (!entry) {\n\t\t\t\t\tthrow new Error(`repack: missing verified object for ${oid}`);\n\t\t\t\t}\n\t\t\t\tconst objHeader = encodePackObjectHeader(\n\t\t\t\t\tentry.type,\n\t\t\t\t\tentry.content.length,\n\t\t\t\t);\n\t\t\t\tconst compressed = await deflate(entry.content);\n\t\t\t\treturn concat(objHeader, compressed);\n\t\t\t}),\n\t\t);\n\t\tchunks.push(...encoded);\n\t}\n\n\t// Git's pack trailer is the SHA-1 of every preceding byte (header +\n\t// every object entry) as a single digest — NOT an incremental/chained\n\t// hash. Web Crypto's subtle.digest has no streaming mode, so unlike\n\t// Node's crypto.createHash this can't be folded into the loop above;\n\t// everything is already buffered in `chunks`, so hash it in one pass.\n\tconst packBody = concat(...chunks);\n\tconst trailer = fromHex(await sha1(packBody));\n\treturn concat(packBody, trailer);\n}\n\n/**\n * Default repack threshold. Consolidating is O(total repo object count) —\n * so paying it on every push makes push latency grow with repo size forever.\n */\nexport const REPACK_PACK_COUNT_THRESHOLD = 4;\n\nasync function readPackDirectory(repo: Repo): Promise<PackFileName[]> {\n\tconst entries = await rawFs(repo)\n\t\t.readdir(`${repo.gitdir}/objects/pack`)\n\t\t.catch(() => [] as string[]);\n\treturn parsePackDirectory(entries);\n}\n\nasync function countPacks(repo: Repo): Promise<number> {\n\tconst files = await readPackDirectory(repo);\n\treturn files.filter((file) => file.kind === \"pack\").length;\n}\n\nexport interface RepackOptions {\n\t/** Skip repacking below this many accumulated packs. Default 4. */\n\tthreshold?: number;\n}\n\n/**\n * Consolidate all pack files into one, returning the gitdir-relative paths\n * of the old .pack/.idx files it removed — after syncing the new pack to any\n * secondary storage, delete those same paths there too.\n */\nexport async function repackRepository(\n\trepo: Repo,\n\toptions?: RepackOptions,\n\thooks?: HttpHooks,\n): Promise<string[]> {\n\tconst threshold = options?.threshold ?? REPACK_PACK_COUNT_THRESHOLD;\n\tconst fsp = rawFs(repo);\n\ttry {\n\t\tif ((await countPacks(repo)) < threshold) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst [branches, tags] = await Promise.all([\n\t\t\tgit.listBranches(repo),\n\t\t\tgit.listTags(repo),\n\t\t]);\n\t\tconst refNames = [\n\t\t\t...branches.map((b) => `refs/heads/${b}`),\n\t\t\t...tags.map((t) => `refs/tags/${t}`),\n\t\t];\n\t\tconst tipOids = (\n\t\t\tawait Promise.all(\n\t\t\t\trefNames.map((ref) =>\n\t\t\t\t\tgit.resolveRef({ ...repo, ref }).catch(() => null),\n\t\t\t\t),\n\t\t\t)\n\t\t).filter((oid): oid is string => oid !== null);\n\t\tif (tipOids.length === 0) return [];\n\n\t\tconst { oids: reachable, complete } = await collectReachableOids(\n\t\t\trepo,\n\t\t\ttipOids,\n\t\t\thooks,\n\t\t);\n\t\tif (!complete || reachable.length === 0) return [];\n\n\t\tconst packDir = `${repo.gitdir}/objects/pack`;\n\t\t// Copy stored entries when everything is packed: keeps deltas, so\n\t\t// the consolidated pack is as compact as its sources. Loose objects\n\t\t// fall back to a verified, non-deltified rebuild.\n\t\tconst packBuffer =\n\t\t\t(await buildPackFromExistingPacks(repo, reachable)) ??\n\t\t\t(await buildVerifiedPack(\n\t\t\t\treachable,\n\t\t\t\tawait readAndVerifyObjects(repo, reachable),\n\t\t\t));\n\n\t\tawait fsp.mkdir(packDir, { recursive: true });\n\t\tconst newBase = `pack-${Date.now()}`;\n\t\tconst newPackFile = packFileName(newBase, \"pack\");\n\t\tawait fsp.writeFile(`${packDir}/${newPackFile}`, packBuffer);\n\n\t\tconst { oids: indexedOids } = await git.indexPack({\n\t\t\t...repo,\n\t\t\tdir: packDir,\n\t\t\tfilepath: newPackFile,\n\t\t});\n\n\t\t// indexPack re-hashes every object it indexes, so this also verifies\n\t\t// the content. Reused packs may carry extra delta bases: superset is fine.\n\t\tconst indexed = new Set(indexedOids);\n\t\tif (reachable.some((oid) => !indexed.has(oid))) {\n\t\t\tawait Promise.all(\n\t\t\t\t([\"pack\", \"idx\"] as const).map((kind) =>\n\t\t\t\t\tfsp\n\t\t\t\t\t\t.unlink(`${packDir}/${packFileName(newBase, kind)}`)\n\t\t\t\t\t\t.catch(() => {}),\n\t\t\t\t),\n\t\t\t);\n\t\t\tthrow new Error(\n\t\t\t\t\"repack: indexed pack is missing reachable objects — aborting\",\n\t\t\t);\n\t\t}\n\n\t\tconst stale = (await readPackDirectory(repo)).filter(\n\t\t\t(file) => file.base !== newBase,\n\t\t);\n\t\tawait Promise.all(\n\t\t\tstale.map((file) =>\n\t\t\t\tfsp.unlink(`${packDir}/${file.name}`).catch(() => {}),\n\t\t\t),\n\t\t);\n\t\treturn stale.map((file) => `objects/pack/${file.name}`);\n\t} catch (err) {\n\t\thooks?.onWarn?.(\"repack failed (non-fatal)\", err);\n\t\treturn [];\n\t}\n}\n","/**\n * Typed view of a git `objects/pack` directory listing.\n *\n * Every pack is a set of sibling files sharing one base name\n * (`pack-<hash>.pack`, `.idx`, and optionally `.keep`/`.bitmap`/`.rev`).\n * Parsing names once into {@link PackFileName} lets callers group, filter and\n * rename by kind instead of re-matching filename strings at each call site.\n *\n * Edge-compatible: no node: imports.\n */\n\n/** Every file kind git writes into `objects/pack`. */\nexport const PACK_FILE_KINDS = [\n\t\"pack\",\n\t\"idx\",\n\t\"keep\",\n\t\"bitmap\",\n\t\"rev\",\n] as const;\nexport type PackFileKind = (typeof PACK_FILE_KINDS)[number];\n\n/** Kinds isomorphic-git actually reads; the rest are git-CLI accelerators. */\nexport const READABLE_PACK_FILE_KINDS: ReadonlySet<PackFileKind> = new Set([\n\t\"pack\",\n\t\"idx\",\n]);\n\nexport interface PackFileName {\n\t/** Shared base of a pack's sibling files, e.g. `pack-1a2b…`. */\n\treadonly base: string;\n\treadonly kind: PackFileKind;\n\t/** The file name as listed, e.g. `pack-1a2b….idx`. */\n\treadonly name: string;\n}\n\nconst KNOWN_KINDS: ReadonlySet<string> = new Set(PACK_FILE_KINDS);\n\nfunction isPackFileKind(value: string): value is PackFileKind {\n\treturn KNOWN_KINDS.has(value);\n}\n\n/** Parse a pack-directory entry; `null` for anything git didn't put there. */\nexport function parsePackFileName(name: string): PackFileName | null {\n\tconst dot = name.lastIndexOf(\".\");\n\tif (dot <= 0) return null;\n\tconst kind = name.slice(dot + 1);\n\tif (!isPackFileKind(kind)) return null;\n\treturn { base: name.slice(0, dot), kind, name };\n}\n\n/** File name of the `kind` sibling of the pack with this base name. */\nexport function packFileName(base: string, kind: PackFileKind): string {\n\treturn `${base}.${kind}`;\n}\n\n/** Parse a directory listing, dropping entries that aren't pack files. */\nexport function parsePackDirectory(entries: readonly string[]): PackFileName[] {\n\treturn entries\n\t\t.map(parsePackFileName)\n\t\t.filter((file): file is PackFileName => file !== null);\n}\n","/**\n * Build a packfile by copying already-compressed entries out of existing\n * packs (\"pack reuse\"), instead of inflating and re-deflating every object.\n *\n * Entries keep their stored form, deltas included, so the output is as\n * compact as the packs it came from. `OFS_DELTA` entries are rewritten as\n * `REF_DELTA` (base named by oid), since offsets don't survive the move into\n * a new pack; delta bases are always included and written before the deltas\n * that use them. Formats: gitformat-pack(5).\n *\n * Edge-compatible: Web Crypto SHA-1 and Uint8Array only.\n */\n\nimport { concat, encodeUtf8, fromHex, sha1, toHex } from \"../edge-utils.js\";\nimport type { Repo } from \"../ops/types.js\";\nimport { packFileName, parsePackDirectory } from \"../pack-files.js\";\nimport { rawFs } from \"./types.js\";\n\nconst OBJ_OFS_DELTA = 6;\nconst OBJ_REF_DELTA = 7;\nconst OID_BYTES = 20;\nconst PACK_TRAILER_BYTES = 20;\n\nconst IDX_V2 = {\n\tmagic: 0xff744f63,\n\tversion: 2,\n\theaderBytes: 8,\n\tfanoutEntries: 256,\n\t/** Offsets with this bit set index the 64-bit large-offset table. */\n\tlargeOffsetFlag: 0x80000000,\n} as const;\n\n/** One object's stored entry inside a pack. */\ninterface PackEntry {\n\treadonly pack: Uint8Array;\n\treadonly start: number;\n\treadonly end: number;\n}\n\n/** Every object stored in a pack, by oid, plus its offset → oid inverse. */\ninterface IndexedPack {\n\treadonly entries: Map<string, PackEntry>;\n\treadonly oidAtOffset: Map<number, string>;\n}\n\n/** An object's position in a pack, as listed by its `.idx`. */\nexport interface PackIndexEntry {\n\treadonly oid: string;\n\treadonly offset: number;\n}\n\n/** Entries of a version-2 `.idx`; `null` for any other format. */\nexport function readPackIndex(idx: Uint8Array): PackIndexEntry[] | null {\n\tconst view = new DataView(idx.buffer, idx.byteOffset, idx.byteLength);\n\tconst namesStart = IDX_V2.headerBytes + IDX_V2.fanoutEntries * 4;\n\tif (\n\t\tidx.byteLength < namesStart ||\n\t\tview.getUint32(0) !== IDX_V2.magic ||\n\t\tview.getUint32(4) !== IDX_V2.version\n\t) {\n\t\treturn null;\n\t}\n\t// The last fanout slot counts every object in the pack.\n\tconst count = view.getUint32(namesStart - 4);\n\tconst crcStart = namesStart + count * OID_BYTES;\n\tconst offsetsStart = crcStart + count * 4;\n\tif (idx.byteLength < offsetsStart + count * 4) return null;\n\n\tconst entries: PackIndexEntry[] = [];\n\tfor (let i = 0; i < count; i++) {\n\t\tconst offset = view.getUint32(offsetsStart + i * 4);\n\t\t// Packs over 2 GiB never reach this in-memory path; let the caller\n\t\t// fall back instead of half-supporting the large-offset table.\n\t\tif (offset & IDX_V2.largeOffsetFlag) return null;\n\t\tconst at = namesStart + i * OID_BYTES;\n\t\tentries.push({ oid: toHex(idx.subarray(at, at + OID_BYTES)), offset });\n\t}\n\treturn entries;\n}\n\n/** Locate every entry of `pack` using its `.idx`. */\nfunction indexPack(idx: Uint8Array, pack: Uint8Array): IndexedPack | null {\n\tconst located = readPackIndex(idx);\n\tif (!located) return null;\n\n\t// An entry runs until the next entry's offset (or the pack trailer).\n\tlocated.sort((a, b) => a.offset - b.offset);\n\tconst entries = new Map<string, PackEntry>();\n\tconst oidAtOffset = new Map<number, string>();\n\tconst packEnd = pack.byteLength - PACK_TRAILER_BYTES;\n\tfor (let i = 0; i < located.length; i++) {\n\t\tconst { oid, offset } = located[i] as PackIndexEntry;\n\t\tconst end = located[i + 1]?.offset ?? packEnd;\n\t\tentries.set(oid, { pack, start: offset, end });\n\t\toidAtOffset.set(offset, oid);\n\t}\n\treturn { entries, oidAtOffset };\n}\n\n/** The variable-length type/size header that starts every pack entry. */\ninterface EntryHeader {\n\treadonly type: number;\n\treadonly size: number;\n\t/** Bytes the header occupies. */\n\treadonly length: number;\n}\n\nfunction readEntryHeader(bytes: Uint8Array, start: number): EntryHeader {\n\tlet byte = bytes[start] as number;\n\tconst type = (byte >> 4) & 0b111;\n\tlet size = byte & 0b1111;\n\tlet shift = 4;\n\tlet at = start + 1;\n\twhile (byte & 0x80) {\n\t\tbyte = bytes[at++] as number;\n\t\tsize += (byte & 0x7f) * 2 ** shift;\n\t\tshift += 7;\n\t}\n\treturn { type, size, length: at - start };\n}\n\nfunction encodeEntryHeader(type: number, size: number): Uint8Array {\n\tconst bytes: number[] = [];\n\tlet rest = Math.floor(size / 16);\n\tbytes.push((rest > 0 ? 0x80 : 0) | (type << 4) | (size % 16));\n\twhile (rest > 0) {\n\t\tconst low = rest % 128;\n\t\trest = Math.floor(rest / 128);\n\t\tbytes.push((rest > 0 ? 0x80 : 0) | low);\n\t}\n\treturn new Uint8Array(bytes);\n}\n\n/** `OFS_DELTA`'s negative base offset: big-endian base-128 with +1 carries. */\nfunction readOfsDeltaOffset(\n\tbytes: Uint8Array,\n\tstart: number,\n): { distance: number; length: number } {\n\tlet at = start;\n\tlet byte = bytes[at++] as number;\n\tlet distance = byte & 0x7f;\n\twhile (byte & 0x80) {\n\t\tbyte = bytes[at++] as number;\n\t\tdistance = (distance + 1) * 128 + (byte & 0x7f);\n\t}\n\treturn { distance, length: at - start };\n}\n\n/** A pack entry ready to copy, with the oid of its delta base if any. */\ninterface ReusableEntry {\n\treadonly bytes: Uint8Array;\n\treadonly baseOid: string | null;\n}\n\n/** Copy one entry, rewriting `OFS_DELTA` to `REF_DELTA`. */\nfunction reusableEntry(\n\tentry: PackEntry,\n\tindexed: IndexedPack,\n): ReusableEntry | null {\n\tconst { pack, start, end } = entry;\n\tconst header = readEntryHeader(pack, start);\n\tconst bodyStart = start + header.length;\n\tif (header.type === OBJ_REF_DELTA) {\n\t\treturn {\n\t\t\tbytes: pack.subarray(start, end),\n\t\t\tbaseOid: toHex(pack.subarray(bodyStart, bodyStart + OID_BYTES)),\n\t\t};\n\t}\n\tif (header.type !== OBJ_OFS_DELTA) {\n\t\treturn { bytes: pack.subarray(start, end), baseOid: null };\n\t}\n\tconst { distance, length } = readOfsDeltaOffset(pack, bodyStart);\n\tconst baseOid = indexed.oidAtOffset.get(start - distance);\n\tif (baseOid === undefined) return null;\n\treturn {\n\t\tbytes: concat(\n\t\t\tencodeEntryHeader(OBJ_REF_DELTA, header.size),\n\t\t\tfromHex(baseOid),\n\t\t\tpack.subarray(bodyStart + length, end),\n\t\t),\n\t\tbaseOid,\n\t};\n}\n\n/**\n * A pack holding at least `oids`, built from stored entries, or `null` when\n * any of them (or a delta base they need) isn't in a readable pack — e.g. a\n * loose object — so the caller should build the pack another way.\n */\nexport async function buildPackFromExistingPacks(\n\trepo: Repo,\n\toids: readonly string[],\n): Promise<Uint8Array | null> {\n\tconst fsp = rawFs(repo);\n\tconst packDir = `${repo.gitdir}/objects/pack`;\n\tconst packs = parsePackDirectory(\n\t\tawait fsp.readdir(packDir).catch(() => [] as string[]),\n\t).filter((file) => file.kind === \"pack\");\n\n\tconst indexes: IndexedPack[] = [];\n\tfor (const { base } of packs) {\n\t\t// A pack without a readable index can't be reused.\n\t\tconst [pack, idx] = await Promise.all([\n\t\t\tfsp.readFile(`${packDir}/${packFileName(base, \"pack\")}`),\n\t\t\tfsp.readFile(`${packDir}/${packFileName(base, \"idx\")}`),\n\t\t]).catch(() => [null, null]);\n\t\tif (!(pack instanceof Uint8Array) || !(idx instanceof Uint8Array)) {\n\t\t\treturn null;\n\t\t}\n\t\tconst indexed = indexPack(idx, pack);\n\t\tif (!indexed) return null;\n\t\tindexes.push(indexed);\n\t}\n\n\tconst locate = (oid: string): ReusableEntry | null => {\n\t\tfor (const indexed of indexes) {\n\t\t\tconst entry = indexed.entries.get(oid);\n\t\t\tif (entry) return reusableEntry(entry, indexed);\n\t\t}\n\t\treturn null;\n\t};\n\n\t// Depth-first so every base is written before the deltas that use it.\n\tconst ordered: Uint8Array[] = [];\n\tconst done = new Set<string>();\n\tconst pending = new Set<string>();\n\tconst visit = (oid: string): boolean => {\n\t\tif (done.has(oid)) return true;\n\t\tif (pending.has(oid)) return false; // a delta cycle means corruption\n\t\tconst entry = locate(oid);\n\t\tif (!entry) return false;\n\t\tpending.add(oid);\n\t\tif (entry.baseOid !== null && !visit(entry.baseOid)) return false;\n\t\tpending.delete(oid);\n\t\tdone.add(oid);\n\t\tordered.push(entry.bytes);\n\t\treturn true;\n\t};\n\tfor (const oid of oids) {\n\t\tif (!visit(oid)) return null;\n\t}\n\n\tconst header = new Uint8Array(12);\n\theader.set(encodeUtf8(\"PACK\"), 0);\n\tconst view = new DataView(header.buffer);\n\tview.setUint32(4, 2);\n\tview.setUint32(8, ordered.length);\n\tconst body = concat(header, ...ordered);\n\treturn concat(body, fromHex(await sha1(body)));\n}\n","import git from \"isomorphic-git\";\nimport { concat } from \"../edge-utils.js\";\nimport type { Repo } from \"../ops/types.js\";\nimport { parsePackDirectory } from \"../pack-files.js\";\nimport { buildPackFromExistingPacks } from \"./pack-reuse.js\";\nimport { parsePktLines, pktLine, sideBandPackfile } from \"./pkt-line.js\";\nimport { collectReachableOids } from \"./reachability.js\";\nimport { type GitHttpResult, type HttpHooks, rawFs, runStep } from \"./types.js\";\n\nconst ZERO_OID = \"0\".repeat(40);\n\nexport interface UploadPackOptions {\n\t/**\n\t * Called once before the reachability walk — wire loose-object detection\n\t * (`GitFs.detectLooseObjects`) here so a fully packed repo's walk doesn't\n\t * pay a doomed loose-object probe per object.\n\t */\n\tbeforeWalk?: () => Promise<void>;\n}\n\n/**\n * `POST …/git-upload-pack` — serve a clone/fetch. Authorization is the\n * caller's job. Negotiation is client-driven (no multi_ack advertised):\n * \"have\" batches without \"done\" get a bare NAK; the final batch gets the\n * packfile, side-band-64k framed.\n *\n * Fast path: a fresh clone (no haves) of a repo consolidated down to a\n * single pack serves that pack's bytes directly — skipping the O(objects)\n * traversal + repack entirely.\n */\nexport async function handleUploadPack(\n\trepo: Repo,\n\tbody: Uint8Array,\n\toptions?: UploadPackOptions,\n\thooks?: HttpHooks,\n): Promise<GitHttpResult> {\n\tconst lines = parsePktLines(body);\n\n\tconst wants: string[] = [];\n\tconst haves: string[] = [];\n\tlet done = false;\n\tfor (const line of lines) {\n\t\tif (!line) continue;\n\t\tif (line.startsWith(\"want \")) {\n\t\t\twants.push(line.slice(5, 45));\n\t\t}\n\t\tif (line.startsWith(\"have \")) {\n\t\t\tconst sha = line.slice(5, 45);\n\t\t\tif (sha !== ZERO_OID) {\n\t\t\t\thaves.push(sha);\n\t\t\t}\n\t\t}\n\t\tif (line.startsWith(\"done\")) {\n\t\t\tdone = true;\n\t\t}\n\t}\n\n\tif (wants.length === 0) {\n\t\treturn {\n\t\t\tstatus: 200,\n\t\t\theaders: { \"Content-Type\": \"application/x-git-upload-pack-result\" },\n\t\t\tbody: concat(pktLine(\"NAK\\n\")),\n\t\t};\n\t}\n\n\tif (haves.length > 0 && !done) {\n\t\treturn {\n\t\t\tstatus: 200,\n\t\t\theaders: { \"Content-Type\": \"application/x-git-upload-pack-result\" },\n\t\t\tbody: concat(pktLine(\"NAK\\n\")),\n\t\t};\n\t}\n\n\t// Fresh clone = no haves, so all objects are needed. When the repo is down\n\t// to a single pack, serve it directly and skip the traversal + pack build.\n\tif (haves.length === 0) {\n\t\tconst packDirPath = `${repo.gitdir}/objects/pack`;\n\t\tconst entries = await runStep(hooks, \"readdir objects/pack\", () =>\n\t\t\trawFs(repo)\n\t\t\t\t.readdir(packDirPath)\n\t\t\t\t.catch(() => [] as string[]),\n\t\t);\n\t\tconst packNames = parsePackDirectory(entries)\n\t\t\t.filter((file) => file.kind === \"pack\")\n\t\t\t.map((file) => file.name);\n\t\tconst packName = packNames[0];\n\t\tif (packNames.length === 1 && packName !== undefined) {\n\t\t\tconst packData = await runStep(\n\t\t\t\thooks,\n\t\t\t\t\"read consolidated pack (fast path)\",\n\t\t\t\t() => rawFs(repo).readFile(`${packDirPath}/${packName}`),\n\t\t\t);\n\t\t\tconst bytes =\n\t\t\t\tpackData instanceof Uint8Array\n\t\t\t\t\t? packData\n\t\t\t\t\t: new TextEncoder().encode(packData as string);\n\t\t\treturn {\n\t\t\t\tstatus: 200,\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/x-git-upload-pack-result\",\n\t\t\t\t\t\"Cache-Control\": \"no-cache\",\n\t\t\t\t},\n\t\t\t\tbody: concat(pktLine(\"NAK\\n\"), sideBandPackfile(bytes)),\n\t\t\t};\n\t\t}\n\t}\n\n\tif (options?.beforeWalk) {\n\t\tawait runStep(hooks, \"beforeWalk\", options.beforeWalk);\n\t}\n\n\t// Walk haves first so the wants walk can stop at anything the client\n\t// already has, instead of re-walking all shared history a second time.\n\tlet haveSet: ReadonlySet<string> | undefined;\n\tif (haves.length > 0) {\n\t\tconst { oids: haveOids } = await runStep(\n\t\t\thooks,\n\t\t\t\"collectReachableOids(haves)\",\n\t\t\t() =>\n\t\t\t\tcollectReachableOids(repo, haves, hooks, undefined, {\n\t\t\t\t\tverifyBlobs: false,\n\t\t\t\t}),\n\t\t);\n\t\thaveSet = new Set(haveOids);\n\t}\n\n\tconst { oids: wantOids } = await runStep(\n\t\thooks,\n\t\t\"collectReachableOids(wants)\",\n\t\t() =>\n\t\t\tcollectReachableOids(repo, wants, hooks, haveSet, {\n\t\t\t\tverifyBlobs: false,\n\t\t\t}),\n\t);\n\t// Boundary oids are recorded as seen by the walk; drop them from the pack.\n\tconst oids = haveSet ? wantOids.filter((oid) => !haveSet.has(oid)) : wantOids;\n\n\t// Copy stored (already compressed, possibly deltified) entries when every\n\t// object is packed; build from scratch only when some aren't.\n\tconst reused = await runStep(\n\t\thooks,\n\t\t`reuse pack entries (${oids.length} oids)`,\n\t\t() => buildPackFromExistingPacks(repo, oids),\n\t);\n\tconst packBytes =\n\t\treused ??\n\t\t(await runStep(hooks, `packObjects (${oids.length} oids)`, async () => {\n\t\t\tconst { packfile } = await git.packObjects({ ...repo, oids });\n\t\t\treturn packfile instanceof Uint8Array\n\t\t\t\t? packfile\n\t\t\t\t: new Uint8Array(packfile ?? []);\n\t\t}));\n\n\treturn {\n\t\tstatus: 200,\n\t\theaders: {\n\t\t\t\"Content-Type\": \"application/x-git-upload-pack-result\",\n\t\t\t\"Cache-Control\": \"no-cache\",\n\t\t},\n\t\tbody: concat(pktLine(\"NAK\\n\"), sideBandPackfile(packBytes)),\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;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ACtE,UAAM,EAAE,SAAS,IAAI,MAAM,uBAAAC,QAAI,YAAY,EAAE,GAAG,MAAM,KAAK,CAAC;AAC5D,WAAO,oBAAoB,aACxB,WACA,IAAI,WAAW,YAAY,CAAC,CAAC;AAAA,EACjC,CAAC;AAEF,SAAO;AAAA,IACN,QAAQ;AAAA,IACR,SAAS;AAAA,MACR,gBAAgB;AAAA,MAChB,iBAAiB;AAAA,IAClB;AAAA,IACA,MAAM,OAAO,QAAQ,OAAO,GAAG,iBAAiB,SAAS,CAAC;AAAA,EAC3D;AACD;","names":["import_isomorphic_git","FULL_SHA_RE","git","git","import_isomorphic_git","git","p","import_isomorphic_git","import_isomorphic_git","git","git","packName","import_isomorphic_git","ZERO_OID","git"]}
|
package/dist/http.d.cts
DELETED
|
@@ -1,215 +0,0 @@
|
|
|
1
|
-
import { R as Repo } from './types-BHoHOaQt.cjs';
|
|
2
|
-
import 'isomorphic-git';
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Transport-agnostic HTTP response the handlers produce.
|
|
6
|
-
*
|
|
7
|
-
* `body` is pinned to `Uint8Array<ArrayBuffer>` (not the bare `Uint8Array`,
|
|
8
|
-
* whose default type argument isn't consistent across TypeScript versions)
|
|
9
|
-
* so it's always assignable to Fetch API `BodyInit` regardless of which
|
|
10
|
-
* TypeScript/lib version a consumer compiles against — every producer here
|
|
11
|
-
* (`concat`, `pktLine`, `TextEncoder.encode`) is ArrayBuffer-backed already.
|
|
12
|
-
*/
|
|
13
|
-
interface GitHttpResult {
|
|
14
|
-
status: number;
|
|
15
|
-
headers: Record<string, string>;
|
|
16
|
-
body: Uint8Array<ArrayBuffer>;
|
|
17
|
-
}
|
|
18
|
-
/** Optional instrumentation hooks shared by the /http handlers. */
|
|
19
|
-
interface HttpHooks {
|
|
20
|
-
/** Wrap a timed sub-step. Default: run directly. */
|
|
21
|
-
step?: <T>(label: string, fn: () => Promise<T>) => Promise<T>;
|
|
22
|
-
/** Non-fatal problem sink (missing objects, failed repacks). */
|
|
23
|
-
onWarn?: (message: string, error?: unknown) => void;
|
|
24
|
-
}
|
|
25
|
-
/**
|
|
26
|
-
* The raw promise-fs surface some /http paths need beyond isomorphic-git's
|
|
27
|
-
* plumbing (writing an incoming pack file, listing/deleting pack files).
|
|
28
|
-
* Both `node:fs` and this package's `GitFs` satisfy it via `.promises`.
|
|
29
|
-
*/
|
|
30
|
-
interface RawFsPromises {
|
|
31
|
-
readFile(path: string): Promise<Uint8Array | string>;
|
|
32
|
-
writeFile(path: string, data: Uint8Array | string): Promise<void>;
|
|
33
|
-
unlink(path: string): Promise<void>;
|
|
34
|
-
readdir(path: string): Promise<string[]>;
|
|
35
|
-
mkdir(path: string, options?: {
|
|
36
|
-
recursive?: boolean;
|
|
37
|
-
}): Promise<unknown>;
|
|
38
|
-
stat(path: string): Promise<unknown>;
|
|
39
|
-
}
|
|
40
|
-
/** Duck-type the `.promises` surface off a repo's fs. */
|
|
41
|
-
declare function rawFs(repo: Repo): RawFsPromises;
|
|
42
|
-
|
|
43
|
-
type GitService = "git-upload-pack" | "git-receive-pack";
|
|
44
|
-
/** All refs with resolved oids, plus the symref HEAD should advertise. */
|
|
45
|
-
declare function listAllRefs(repo: Repo, defaultBranch?: string): Promise<{
|
|
46
|
-
refs: {
|
|
47
|
-
name: string;
|
|
48
|
-
oid: string;
|
|
49
|
-
}[];
|
|
50
|
-
headSymref: string;
|
|
51
|
-
}>;
|
|
52
|
-
interface InfoRefsOptions {
|
|
53
|
-
service: GitService;
|
|
54
|
-
defaultBranch?: string;
|
|
55
|
-
/** Advertised in the agent capability. Default "git-fs-s3". */
|
|
56
|
-
agent?: string;
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* `GET …/info/refs?service=…` — the ref advertisement. Authentication and
|
|
60
|
-
* authorization are the caller's job before invoking this.
|
|
61
|
-
*
|
|
62
|
-
* Capabilities advertised match what the sibling handlers implement:
|
|
63
|
-
* side-band-64k (honored by handleUploadPack's response framing — clients
|
|
64
|
-
* like isomorphic-git unconditionally expect it), tip/reachable sha1 wants,
|
|
65
|
-
* delete-refs and report-status for pushes.
|
|
66
|
-
*/
|
|
67
|
-
declare function handleInfoRefs(repo: Repo, options: InfoRefsOptions, hooks?: HttpHooks): Promise<GitHttpResult>;
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* Git pkt-line framing (smart HTTP protocol wire format).
|
|
71
|
-
*
|
|
72
|
-
* Edge-compatible: uses Uint8Array instead of Buffer.
|
|
73
|
-
*/
|
|
74
|
-
/** Flush packet: exactly four zero bytes. */
|
|
75
|
-
declare const FLUSH: Uint8Array<ArrayBuffer>;
|
|
76
|
-
/** Frame a UTF-8 string as one pkt-line. */
|
|
77
|
-
declare function pktLine(data: string): Uint8Array<ArrayBuffer>;
|
|
78
|
-
/** Frame raw bytes as one pkt-line. */
|
|
79
|
-
declare function pktLineBuffer(body: Uint8Array): Uint8Array<ArrayBuffer>;
|
|
80
|
-
/** Decode pkt-lines to strings; `null` marks a flush-pkt. Stops on garbage. */
|
|
81
|
-
declare function parsePktLines(buf: Uint8Array): Array<string | null>;
|
|
82
|
-
declare function sideBandPackfile(packData: Uint8Array): Uint8Array<ArrayBuffer>;
|
|
83
|
-
|
|
84
|
-
interface ReachabilityResult {
|
|
85
|
-
oids: string[];
|
|
86
|
-
/**
|
|
87
|
-
* False if any object in the graph couldn't be read — repack uses this
|
|
88
|
-
* (not a raw object-count comparison) to decide whether it's safe to
|
|
89
|
-
* delete old packs: counts alone can't distinguish "everything read fine"
|
|
90
|
-
* from "some objects silently failed".
|
|
91
|
-
*/
|
|
92
|
-
complete: boolean;
|
|
93
|
-
}
|
|
94
|
-
/**
|
|
95
|
-
* Walk the object graph from `startOids`, returning every reachable oid.
|
|
96
|
-
* Concurrent traversal paths are deduplicated promise-per-oid; a missing
|
|
97
|
-
* object is retried once, then reported through `hooks.onWarn` and
|
|
98
|
-
* reflected in `complete: false`.
|
|
99
|
-
*
|
|
100
|
-
* `haveOids` bounds the walk: any oid in this set is assumed already
|
|
101
|
-
* verified (it was reachable from a ref that existed before this call) and
|
|
102
|
-
* is recorded in `seen` without being read or descended into. Without a
|
|
103
|
-
* boundary, every call re-walks the *entire* history from scratch — for
|
|
104
|
-
* receive-pack validation (see receive-pack.ts) that means every push pays
|
|
105
|
-
* for reading every object in the repo, not just the ones it introduced,
|
|
106
|
-
* and one transient read failure anywhere in that whole history rejects an
|
|
107
|
-
* otherwise-valid push.
|
|
108
|
-
*
|
|
109
|
-
* Commits, trees and tags are read once each (parsed). Blobs have no
|
|
110
|
-
* children, so `verifyBlobs: false` records a blob from its tree entry
|
|
111
|
-
* without reading (and inflating) it — for callers that read every blob
|
|
112
|
-
* themselves afterwards anyway, like upload-pack's `packObjects`. Leave it
|
|
113
|
-
* true wherever the walk *is* the existence check (receive-pack, repack).
|
|
114
|
-
*/
|
|
115
|
-
declare function collectReachableOids(repo: Repo, startOids: string[], hooks?: HttpHooks, haveOids?: ReadonlySet<string> | readonly string[], options?: {
|
|
116
|
-
verifyBlobs?: boolean;
|
|
117
|
-
}): Promise<ReachabilityResult>;
|
|
118
|
-
|
|
119
|
-
/**
|
|
120
|
-
* Pack consolidation: merge all packs into one, reusing stored (possibly
|
|
121
|
-
* deltified) entries when every object is packed.
|
|
122
|
-
*
|
|
123
|
-
* Edge-compatible: uses Web Crypto (SHA-1), CompressionStream (deflate),
|
|
124
|
-
* and Uint8Array throughout — no node:crypto, node:zlib, or Buffer.
|
|
125
|
-
*/
|
|
126
|
-
|
|
127
|
-
/**
|
|
128
|
-
* Default repack threshold. Consolidating is O(total repo object count) —
|
|
129
|
-
* so paying it on every push makes push latency grow with repo size forever.
|
|
130
|
-
*/
|
|
131
|
-
declare const REPACK_PACK_COUNT_THRESHOLD = 4;
|
|
132
|
-
interface RepackOptions {
|
|
133
|
-
/** Skip repacking below this many accumulated packs. Default 4. */
|
|
134
|
-
threshold?: number;
|
|
135
|
-
}
|
|
136
|
-
/**
|
|
137
|
-
* Consolidate all pack files into one, returning the gitdir-relative paths
|
|
138
|
-
* of the old .pack/.idx files it removed — after syncing the new pack to any
|
|
139
|
-
* secondary storage, delete those same paths there too.
|
|
140
|
-
*/
|
|
141
|
-
declare function repackRepository(repo: Repo, options?: RepackOptions, hooks?: HttpHooks): Promise<string[]>;
|
|
142
|
-
|
|
143
|
-
interface RefUpdateCommand {
|
|
144
|
-
oldOid: string;
|
|
145
|
-
newOid: string;
|
|
146
|
-
refName: string;
|
|
147
|
-
}
|
|
148
|
-
interface RefUpdateResult {
|
|
149
|
-
refName: string;
|
|
150
|
-
ok: boolean;
|
|
151
|
-
reason?: string;
|
|
152
|
-
}
|
|
153
|
-
/** Split a receive-pack body: pkt-line ref commands, flush, then raw PACK. */
|
|
154
|
-
declare function parseReceivePackBody(body: Uint8Array): {
|
|
155
|
-
refUpdates: RefUpdateCommand[];
|
|
156
|
-
packData: Uint8Array;
|
|
157
|
-
};
|
|
158
|
-
/** Initialize the repo when its HEAD doesn't exist yet (first push). */
|
|
159
|
-
declare function ensureRepoInitialized(repo: Repo, defaultBranch?: string): Promise<void>;
|
|
160
|
-
/** Write the incoming PACK into objects/pack/ and index it. */
|
|
161
|
-
declare function indexIncomingPack(repo: Repo, packData: Uint8Array, hooks?: HttpHooks): Promise<string[]>;
|
|
162
|
-
/**
|
|
163
|
-
* Apply ref updates, enforcing compare-and-swap against each command's
|
|
164
|
-
* claimed oldOid. Every client-supplied refName is validated before any
|
|
165
|
-
* filesystem call reads or writes through it.
|
|
166
|
-
*/
|
|
167
|
-
declare function applyRefUpdates(repo: Repo, refUpdates: RefUpdateCommand[], hooks?: HttpHooks): Promise<RefUpdateResult[]>;
|
|
168
|
-
/** The report-status response body for a set of ref-update results. */
|
|
169
|
-
declare function receivePackResponse(results: RefUpdateResult[]): GitHttpResult;
|
|
170
|
-
interface ApplyReceivePackOptions {
|
|
171
|
-
defaultBranch?: string;
|
|
172
|
-
/**
|
|
173
|
-
* Repack tuning, or `false` to skip repacking entirely. The returned
|
|
174
|
-
* `stalePackPaths` are gitdir-relative pack files the repack deleted from
|
|
175
|
-
* this repo — after syncing to any secondary storage, delete them there
|
|
176
|
-
* too.
|
|
177
|
-
*/
|
|
178
|
-
repack?: RepackOptions | false;
|
|
179
|
-
}
|
|
180
|
-
/**
|
|
181
|
-
* The storage half of a push against `repo`: initialize if needed, index the
|
|
182
|
-
* incoming pack, CAS-apply ref updates, then repack when enough packs have
|
|
183
|
-
* accumulated. Serialize concurrent pushes to the same repo externally (a
|
|
184
|
-
* per-repo lock); build the HTTP response afterwards with
|
|
185
|
-
* {@link receivePackResponse}.
|
|
186
|
-
*/
|
|
187
|
-
declare function applyReceivePack(repo: Repo, parsed: {
|
|
188
|
-
refUpdates: RefUpdateCommand[];
|
|
189
|
-
packData: Uint8Array;
|
|
190
|
-
}, options?: ApplyReceivePackOptions, hooks?: HttpHooks): Promise<{
|
|
191
|
-
results: RefUpdateResult[];
|
|
192
|
-
stalePackPaths: string[];
|
|
193
|
-
}>;
|
|
194
|
-
|
|
195
|
-
interface UploadPackOptions {
|
|
196
|
-
/**
|
|
197
|
-
* Called once before the reachability walk — wire loose-object detection
|
|
198
|
-
* (`GitFs.detectLooseObjects`) here so a fully packed repo's walk doesn't
|
|
199
|
-
* pay a doomed loose-object probe per object.
|
|
200
|
-
*/
|
|
201
|
-
beforeWalk?: () => Promise<void>;
|
|
202
|
-
}
|
|
203
|
-
/**
|
|
204
|
-
* `POST …/git-upload-pack` — serve a clone/fetch. Authorization is the
|
|
205
|
-
* caller's job. Negotiation is client-driven (no multi_ack advertised):
|
|
206
|
-
* "have" batches without "done" get a bare NAK; the final batch gets the
|
|
207
|
-
* packfile, side-band-64k framed.
|
|
208
|
-
*
|
|
209
|
-
* Fast path: a fresh clone (no haves) of a repo consolidated down to a
|
|
210
|
-
* single pack serves that pack's bytes directly — skipping the O(objects)
|
|
211
|
-
* traversal + repack entirely.
|
|
212
|
-
*/
|
|
213
|
-
declare function handleUploadPack(repo: Repo, body: Uint8Array, options?: UploadPackOptions, hooks?: HttpHooks): Promise<GitHttpResult>;
|
|
214
|
-
|
|
215
|
-
export { type ApplyReceivePackOptions, FLUSH, type GitHttpResult, type GitService, type HttpHooks, type InfoRefsOptions, REPACK_PACK_COUNT_THRESHOLD, type RawFsPromises, type ReachabilityResult, type RefUpdateCommand, type RefUpdateResult, type RepackOptions, type UploadPackOptions, applyReceivePack, applyRefUpdates, collectReachableOids, ensureRepoInitialized, handleInfoRefs, handleUploadPack, indexIncomingPack, listAllRefs, parsePktLines, parseReceivePackBody, pktLine, pktLineBuffer, rawFs, receivePackResponse, repackRepository, sideBandPackfile };
|