{"version":3,"sources":["/home/runner/work/kora/kora/packages/store/dist/chunk-UTAHRVJB.cjs","../src/blob/server-blob-callbacks.ts","../src/blob/blob-chunking.ts","../src/blob/blob-transfer-error.ts","../src/blob/blob-manifest-transfer.ts","../src/blob/blob-gc.ts"],"names":["KoraError"],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACLA,oCAAyB;AA2BlB,SAAS,qBAAA,CAAsB,KAAA,EAAuD;AAC5F,EAAA,OAAO;AAAA,IACN,gBAAA,EAAkB,CAAC,IAAA,EAAA,GAAS,KAAA,CAAM,GAAA,CAAI,IAAI,CAAA;AAAA,IAC1C,MAAM,gBAAA,CAAiB,IAAA,EAAM,KAAA,EAAO;AAInC,MAAA,MAAM,OAAA,EAAS,MAAM,4BAAA,KAAc,CAAA;AACnC,MAAA,GAAA,CAAI,OAAA,IAAW,IAAA,EAAM;AACpB,QAAA,MAAA;AAAA,MACD;AACA,MAAA,MAAM,KAAA,CAAM,GAAA,CAAI,KAAK,CAAA;AAAA,IACtB;AAAA,EACD,CAAA;AACD;AAOO,SAAS,2BAAA,CAAA,EAGd;AACD,EAAA,MAAM,MAAA,EAAQ,IAAI,sCAAA,CAAgB,CAAA;AAClC,EAAA,OAAO,EAAE,KAAA,EAAO,SAAA,EAAW,qBAAA,CAAsB,KAAK,EAAE,CAAA;AACzD;AD/BA;AACA;AExBA;AAIO,IAAM,mBAAA,EAAqB,IAAA,EAAM,IAAA;AAqCxC,MAAA,SAAsB,SAAA,CACrB,KAAA,EACA,UAAA,EAAoB,kBAAA,EACpB,SAAA,EAAiC,CAAC,CAAA,EACqC;AACvE,EAAA,GAAA,CAAI,UAAA,GAAa,CAAA,EAAG;AACnB,IAAA,MAAM,IAAI,oBAAA;AAAA,MACT,CAAA,6CAAA,EAAgD,SAAS,CAAA,CAAA;AACzD,MAAA;AACA,MAAA;AACC,QAAA;AACD,MAAA;AACD,IAAA;AACD,EAAA;AAE+B,EAAA;AACY,EAAA;AAEe,EA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ACgB,IAAA;AAC3B,IAAA;AACD,EAAA;AACD;ALkHgE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/kora/kora/packages/store/dist/chunk-UTAHRVJB.cjs","sourcesContent":[null,"import { hashBlob } from '@korajs/core'\nimport { type ContentAddressedBlobStore, MemoryBlobStore } from './content-addressed-blob-store'\n\n/**\n * The server-side blob callbacks a `KoraSyncServer` accepts: read a chunk by\n * hash (to serve it) and persist an uploaded chunk by hash (to store it).\n */\nexport interface ServerBlobCallbacks {\n\tresolveBlobChunk: (hash: string) => Promise<Uint8Array | null>\n\tpersistBlobChunk: (hash: string, bytes: Uint8Array) => Promise<void>\n}\n\n/**\n * Adapt a {@link ContentAddressedBlobStore} into the read/persist callbacks a\n * `KoraSyncServer` needs for central blob storage. The server package depends\n * only on these plain function signatures, so a self-hosted server can back its\n * blob storage with any store (for example a `FilesystemBlobStore`) without the\n * server package taking a dependency on `@korajs/store`.\n *\n * @example\n * ```typescript\n * const server = new KoraSyncServer({\n *   store,\n *   ...toServerBlobCallbacks(new FilesystemBlobStore('/var/kora/blobs')),\n * })\n * ```\n */\nexport function toServerBlobCallbacks(store: ContentAddressedBlobStore): ServerBlobCallbacks {\n\treturn {\n\t\tresolveBlobChunk: (hash) => store.get(hash),\n\t\tasync persistBlobChunk(hash, bytes) {\n\t\t\t// The store keys by the hash it computes from the bytes; verify it matches\n\t\t\t// the declared hash so a mismatched upload is rejected, not silently stored\n\t\t\t// under the wrong key.\n\t\t\tconst actual = await hashBlob(bytes)\n\t\t\tif (actual !== hash) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tawait store.put(bytes)\n\t\t},\n\t}\n}\n\n/**\n * Convenience: an in-memory central blob store plus its server callbacks. For\n * tests and single-process deployments. Persistent deployments should back\n * {@link toServerBlobCallbacks} with a durable store instead.\n */\nexport function createMemoryServerBlobStore(): {\n\tstore: MemoryBlobStore\n\tcallbacks: ServerBlobCallbacks\n} {\n\tconst store = new MemoryBlobStore()\n\treturn { store, callbacks: toServerBlobCallbacks(store) }\n}\n","import { KoraError, hashBlob } from '@korajs/core'\nimport { BlobIntegrityError, type ContentAddressedBlobStore } from './content-addressed-blob-store'\n\n/** Default chunk size for out-of-band blob transfer (256 KiB). */\nexport const DEFAULT_CHUNK_SIZE = 256 * 1024\n\n/**\n * A manifest describing how a blob is split into content-addressed chunks.\n *\n * The manifest is small and travels with the operation stream (or alongside it);\n * the chunk bytes travel out of band. Because every chunk is content-addressed,\n * identical chunks across blobs are stored and transferred once, and a peer only\n * ever requests chunk hashes it does not already hold.\n */\nexport interface BlobManifest {\n\t/** Hex SHA-256 hash of the full reassembled blob (its content address). */\n\tblobHash: string\n\t/** Total size of the full blob in bytes. */\n\tsize: number\n\t/** The chunk size used to split the blob. */\n\tchunkSize: number\n\t/** Ordered hashes of each chunk. Repeats when identical chunks recur. */\n\tchunkHashes: string[]\n\tmimeType?: string\n\tfilename?: string\n}\n\n/** Optional metadata carried on a manifest. */\nexport interface BlobManifestMetadata {\n\tmimeType?: string\n\tfilename?: string\n}\n\n/**\n * Split a blob into content-addressed chunks and produce its manifest.\n *\n * @param bytes - The full blob content\n * @param chunkSize - Bytes per chunk (defaults to {@link DEFAULT_CHUNK_SIZE})\n * @param metadata - Optional mime type / filename to record on the manifest\n * @returns The manifest and a map of chunk hash to chunk bytes (deduplicated)\n */\nexport async function chunkBlob(\n\tbytes: Uint8Array,\n\tchunkSize: number = DEFAULT_CHUNK_SIZE,\n\tmetadata: BlobManifestMetadata = {},\n): Promise<{ manifest: BlobManifest; chunks: Map<string, Uint8Array> }> {\n\tif (chunkSize <= 0) {\n\t\tthrow new KoraError(\n\t\t\t`chunkBlob requires a positive chunkSize, got ${chunkSize}`,\n\t\t\t'INVALID_CHUNK_SIZE',\n\t\t\t{\n\t\t\t\tchunkSize,\n\t\t\t},\n\t\t)\n\t}\n\n\tconst chunkHashes: string[] = []\n\tconst chunks = new Map<string, Uint8Array>()\n\n\tfor (let offset = 0; offset < bytes.byteLength; offset += chunkSize) {\n\t\tconst end = Math.min(offset + chunkSize, bytes.byteLength)\n\t\tconst chunk = new Uint8Array(end - offset)\n\t\tchunk.set(bytes.subarray(offset, end))\n\t\tconst hash = await hashBlob(chunk)\n\t\tchunkHashes.push(hash)\n\t\t// Identical chunks collapse to one stored entry; the ordered hash list\n\t\t// still records every position so reassembly reproduces the exact bytes.\n\t\tif (!chunks.has(hash)) {\n\t\t\tchunks.set(hash, chunk)\n\t\t}\n\t}\n\n\tconst blobHash = await hashBlob(bytes)\n\tconst manifest: BlobManifest = {\n\t\tblobHash,\n\t\tsize: bytes.byteLength,\n\t\tchunkSize,\n\t\tchunkHashes,\n\t}\n\tif (metadata.mimeType !== undefined) {\n\t\tmanifest.mimeType = metadata.mimeType\n\t}\n\tif (metadata.filename !== undefined) {\n\t\tmanifest.filename = metadata.filename\n\t}\n\n\treturn { manifest, chunks }\n}\n\n/**\n * Reassemble a blob from chunks held in a content-addressed store, verifying\n * integrity at both levels: each chunk is verified by the store on read, and the\n * reassembled whole is verified against the manifest's blob hash.\n *\n * @param manifest - The blob manifest\n * @param chunkStore - A store holding the chunk bytes keyed by chunk hash\n * @returns The full reassembled blob bytes\n * @throws {BlobIntegrityError} If the reassembled bytes do not match blobHash\n * @throws {KoraError} `BLOB_CHUNK_MISSING` if a chunk named in the manifest is missing from the store\n */\nexport async function reassembleBlob(\n\tmanifest: BlobManifest,\n\tchunkStore: ContentAddressedBlobStore,\n): Promise<Uint8Array> {\n\tconst parts: Uint8Array[] = []\n\tlet total = 0\n\n\tfor (const hash of manifest.chunkHashes) {\n\t\tconst chunk = await chunkStore.get(hash)\n\t\tif (chunk === null) {\n\t\t\tthrow new KoraError(\n\t\t\t\t`Cannot reassemble blob ${manifest.blobHash}: missing chunk ${hash}`,\n\t\t\t\t'BLOB_CHUNK_MISSING',\n\t\t\t\t{ blobHash: manifest.blobHash, chunkHash: hash },\n\t\t\t)\n\t\t}\n\t\tparts.push(chunk)\n\t\ttotal += chunk.byteLength\n\t}\n\n\tconst out = new Uint8Array(total)\n\tlet offset = 0\n\tfor (const part of parts) {\n\t\tout.set(part, offset)\n\t\toffset += part.byteLength\n\t}\n\n\tconst actual = await hashBlob(out)\n\tif (actual !== manifest.blobHash) {\n\t\tthrow new BlobIntegrityError(manifest.blobHash, actual)\n\t}\n\treturn out\n}\n","import { KoraError } from '@korajs/core'\n\n/** Why a blob chunk request ended without bytes. */\nexport const BLOB_TRANSFER_ERROR_CODES = [\n\t// No answer (or only \"throttled\" answers) within the request's deadline.\n\t'BLOB_CHUNK_TIMEOUT',\n\t// Answered: nobody reachable holds the chunk (or may give it to this device).\n\t'BLOB_CHUNK_UNAVAILABLE',\n\t// The provider was closed (the app closed or disconnected) while the request waited.\n\t'BLOB_CHUNK_CANCELLED',\n] as const\nexport type BlobTransferErrorCode = (typeof BLOB_TRANSFER_ERROR_CODES)[number]\n\n/**\n * Why the last attempt of a blob chunk request did not produce bytes:\n * `not-connected` (the last try could not be sent; with `attempts` 0 the request never\n * left the device), `timeout` (sent, no answer),\n * `throttled` (the server asked to retry later), `not-held` (answered: nobody holds\n * it), `closed` (the provider was closed).\n */\nexport type BlobChunkFailureReason =\n\t| 'not-connected'\n\t| 'timeout'\n\t| 'throttled'\n\t| 'not-held'\n\t| 'closed'\n\n/**\n * A blob chunk could not be obtained. The transfer is resumable: chunks already\n * received are kept, so pulling the blob again later fetches only what is missing.\n *\n * `code` tells \"lost\" from \"refused\": `BLOB_CHUNK_TIMEOUT` (nothing answered in time,\n * after retries), `BLOB_CHUNK_UNAVAILABLE` (answered: no reachable peer or server\n * holds it), `BLOB_CHUNK_CANCELLED` (the app closed while it waited).\n */\nexport class BlobTransferError extends KoraError {\n\tconstructor(\n\t\tmessage: string,\n\t\tcode: BlobTransferErrorCode,\n\t\tpublic readonly hash: string,\n\t\t/** Requests actually sent (0 when none could be); tries made offline are not counted. */\n\t\tpublic readonly attempts: number,\n\t\tpublic readonly lastReason: BlobChunkFailureReason,\n\t) {\n\t\tsuper(message, code, { hash, attempts, lastReason })\n\t\tthis.name = 'BlobTransferError'\n\t}\n}\n","import { type BlobRef, type BlobRefMetadata, KoraError, hashBlob } from '@korajs/core'\nimport { type BlobManifest, chunkBlob } from './blob-chunking'\nimport type { ChunkProvider } from './blob-transfer'\nimport { BlobTransferError } from './blob-transfer-error'\nimport { BlobIntegrityError, type ContentAddressedBlobStore } from './content-addressed-blob-store'\n\n/**\n * Serialize a {@link BlobManifest} to canonical bytes for content addressing.\n *\n * Fields are emitted in a fixed order so the same manifest always produces the\n * same bytes, which is what lets the manifest be stored and fetched under its own\n * SHA-256 hash. Optional fields are omitted when absent.\n */\nexport function serializeBlobManifest(manifest: BlobManifest): Uint8Array {\n\tconst canonical: Record<string, unknown> = {\n\t\tblobHash: manifest.blobHash,\n\t\tsize: manifest.size,\n\t\tchunkSize: manifest.chunkSize,\n\t\tchunkHashes: manifest.chunkHashes,\n\t}\n\tif (manifest.mimeType !== undefined) {\n\t\tcanonical.mimeType = manifest.mimeType\n\t}\n\tif (manifest.filename !== undefined) {\n\t\tcanonical.filename = manifest.filename\n\t}\n\treturn new TextEncoder().encode(JSON.stringify(canonical))\n}\n\n/**\n * Parse canonical manifest bytes back into a {@link BlobManifest}, validating the\n * shape. Throws on malformed input rather than returning a partial manifest.\n */\nexport function parseBlobManifest(bytes: Uint8Array): BlobManifest {\n\tconst parsed: unknown = JSON.parse(new TextDecoder().decode(bytes))\n\tif (typeof parsed !== 'object' || parsed === null) {\n\t\tthrow new KoraError('Invalid blob manifest: not an object', 'INVALID_BLOB_MANIFEST')\n\t}\n\tconst obj = parsed as Record<string, unknown>\n\tif (typeof obj.blobHash !== 'string') {\n\t\tthrow new KoraError('Invalid blob manifest: missing blobHash', 'INVALID_BLOB_MANIFEST')\n\t}\n\tif (typeof obj.size !== 'number' || typeof obj.chunkSize !== 'number') {\n\t\tthrow new KoraError('Invalid blob manifest: missing size or chunkSize', 'INVALID_BLOB_MANIFEST')\n\t}\n\tif (!Array.isArray(obj.chunkHashes) || obj.chunkHashes.some((h) => typeof h !== 'string')) {\n\t\tthrow new KoraError(\n\t\t\t'Invalid blob manifest: chunkHashes must be an array of strings',\n\t\t\t'INVALID_BLOB_MANIFEST',\n\t\t)\n\t}\n\tconst manifest: BlobManifest = {\n\t\tblobHash: obj.blobHash,\n\t\tsize: obj.size,\n\t\tchunkSize: obj.chunkSize,\n\t\tchunkHashes: obj.chunkHashes as string[],\n\t}\n\tif (typeof obj.mimeType === 'string') {\n\t\tmanifest.mimeType = obj.mimeType\n\t}\n\tif (typeof obj.filename === 'string') {\n\t\tmanifest.filename = obj.filename\n\t}\n\treturn manifest\n}\n\n/**\n * Store a blob for out-of-band transfer, addressed entirely by content.\n *\n * Stages the blob's chunks (so this device can serve them), stores the full blob\n * (so local reads by hash are O(1)), and stores the blob's manifest as its own\n * content-addressed object. The returned {@link BlobRef} carries `manifestHash`,\n * so a peer that receives the reference in a synced record can pull the bytes\n * knowing only the reference — no separate manifest hand-off.\n *\n * @param store - The content-addressed store to stage chunks, blob, and manifest in\n * @param bytes - The full blob content\n * @param options - Optional chunk size and metadata\n * @returns The reference (including `manifestHash`) and the manifest\n */\nexport async function putBlobForTransfer(\n\tstore: ContentAddressedBlobStore,\n\tbytes: Uint8Array,\n\toptions: { chunkSize?: number } & BlobRefMetadata = {},\n): Promise<{ ref: BlobRef; manifest: BlobManifest }> {\n\tconst { manifest, chunks } = await chunkBlob(bytes, options.chunkSize, {\n\t\t...(options.mimeType !== undefined ? { mimeType: options.mimeType } : {}),\n\t\t...(options.filename !== undefined ? { filename: options.filename } : {}),\n\t})\n\tfor (const chunk of chunks.values()) {\n\t\tawait store.put(chunk)\n\t}\n\t// Full blob for local O(1) reads by content hash.\n\tconst baseRef = await store.put(bytes, {\n\t\t...(options.mimeType !== undefined ? { mimeType: options.mimeType } : {}),\n\t\t...(options.filename !== undefined ? { filename: options.filename } : {}),\n\t})\n\t// Manifest as its own content-addressed object, served over the same channel.\n\tconst manifestRef = await store.put(serializeBlobManifest(manifest))\n\treturn { ref: { ...baseRef, manifestHash: manifestRef.hash }, manifest }\n}\n\n/**\n * Fetch and integrity-verify a blob's manifest from a {@link ChunkProvider}.\n *\n * The manifest is a content-addressed object like a chunk, so it is requested by\n * its hash, verified to hash to that value, and parsed. Used to resolve a\n * {@link BlobRef}'s manifest before pulling the blob's chunks.\n *\n * @param provider - The source to fetch the manifest bytes from\n * @param manifestHash - The manifest's content hash (from `BlobRef.manifestHash`)\n * @throws {BlobIntegrityError} If the fetched bytes do not hash to `manifestHash`\n * @throws {BlobTransferError} If the provider cannot supply the manifest (`BLOB_CHUNK_UNAVAILABLE`,\n *   or the provider's own code)\n */\nexport async function fetchBlobManifest(\n\tprovider: ChunkProvider,\n\tmanifestHash: string,\n): Promise<BlobManifest> {\n\tconst bytes = await provider.getChunk(manifestHash)\n\tif (bytes === null) {\n\t\t// One provider call answered \"not held\" (a retrying provider rejects with its count).\n\t\tthrow new BlobTransferError(\n\t\t\t`Blob manifest ${manifestHash} could not be fetched from the provider (no reachable peer or server holds it, or may share it with this device)`,\n\t\t\t'BLOB_CHUNK_UNAVAILABLE',\n\t\t\tmanifestHash,\n\t\t\t1,\n\t\t\t'not-held',\n\t\t)\n\t}\n\tconst actual = await hashBlob(bytes)\n\tif (actual !== manifestHash) {\n\t\tthrow new BlobIntegrityError(manifestHash, actual)\n\t}\n\treturn parseBlobManifest(bytes)\n}\n\n/**\n * Resolve the manifest for a {@link BlobRef} that was stored via\n * {@link putBlobForTransfer}. Fetches and verifies the manifest by the ref's\n * `manifestHash`.\n *\n * @throws {KoraError} `BLOB_MANIFEST_MISSING` if the ref has no `manifestHash` (it was not stored for transfer)\n */\nexport async function resolveBlobManifest(\n\tprovider: ChunkProvider,\n\tref: BlobRef,\n): Promise<BlobManifest> {\n\tif (ref.manifestHash === undefined) {\n\t\tthrow new KoraError(\n\t\t\t`Blob ${ref.hash} has no manifest to resolve. Store it with putBlobForTransfer (or app.blobs.put) so its reference carries a manifestHash, or pull with an explicit manifest.`,\n\t\t\t'BLOB_MANIFEST_MISSING',\n\t\t\t{ blobHash: ref.hash },\n\t\t)\n\t}\n\treturn fetchBlobManifest(provider, ref.manifestHash)\n}\n","import { type BlobRef, isBlobRef } from '@korajs/core'\nimport { parseBlobManifest } from './blob-manifest-transfer'\nimport type { ContentAddressedBlobStore } from './content-addressed-blob-store'\n\n/** Outcome of a blob garbage-collection sweep. */\nexport interface BlobGcResult {\n\t/** Total distinct blobs held before the sweep. */\n\tscanned: number\n\t/** Distinct hashes kept because a live reference points to them (blob, manifest, or chunk). */\n\tlive: number\n\t/** Number of blobs deleted (or, with `dryRun`, that would be deleted). */\n\tcollected: number\n\t/** The hashes deleted (or, with `dryRun`, that would be deleted). */\n\tcollectedHashes: string[]\n}\n\n/** Options for {@link collectBlobGarbage}. */\nexport interface BlobGcOptions {\n\t/** Compute what would be collected without deleting anything. */\n\tdryRun?: boolean\n\t/**\n\t * Unreferenced blobs written within this long are kept (default 24 hours). A device\n\t * uploads a blob's bytes before the record that points at it, and the record can\n\t * arrive much later (the device went offline in between), so a blob is only garbage\n\t * once it has had time to be claimed. Applies to stores that report write times\n\t * (`FilesystemBlobStore`, `ObjectBlobStore`); others are swept as before.\n\t *\n\t * It applies to `dryRun` too: a dry run lists what a real sweep would delete. To list\n\t * every unreferenced blob however recent (to apply a grace of your own, per uploader\n\t * say), pass `graceMs: 0`.\n\t */\n\tgraceMs?: number\n\t/** The current time, for tests. */\n\tnow?: number\n}\n\n/** The default {@link BlobGcOptions.graceMs}: a day. */\nexport const DEFAULT_BLOB_GC_GRACE_MS = 24 * 60 * 60 * 1000\n\n/** A store that knows when each blob was last written, and can delete only older ones atomically. */\ninterface WriteTimedBlobStore {\n\tlastWrittenAt(hash: string): Promise<number | null>\n\tdeleteIfWrittenBefore(hash: string, cutoffMs: number): Promise<boolean>\n}\n\nfunction hasWriteTimes(\n\tstore: ContentAddressedBlobStore,\n): store is ContentAddressedBlobStore & WriteTimedBlobStore {\n\tconst candidate = store as Partial<WriteTimedBlobStore>\n\treturn (\n\t\ttypeof candidate.lastWrittenAt === 'function' &&\n\t\ttypeof candidate.deleteIfWrittenBefore === 'function'\n\t)\n}\n\n/**\n * Extract the {@link BlobRef}s referenced by a materialized record. Scans the\n * record's top-level field values, so it works without the schema; a `blob`\n * field simply holds a `BlobRef`.\n */\nexport function extractBlobRefs(record: Record<string, unknown>): BlobRef[] {\n\tconst refs: BlobRef[] = []\n\tfor (const value of Object.values(record)) {\n\t\tif (isBlobRef(value)) {\n\t\t\trefs.push(value)\n\t\t}\n\t}\n\treturn refs\n}\n\n/**\n * Garbage-collect a content-addressed blob store by mark-and-sweep: keep every\n * blob reachable from a live reference, delete the rest.\n *\n * The live set is closed over the reference graph — for each live {@link BlobRef}\n * it retains the blob hash, the manifest hash, and every chunk hash named in that\n * manifest. Because chunks (and blobs) are shared by content address, a chunk\n * referenced by any surviving blob is retained even if another blob that used it\n * was collected. This makes GC safe under deduplication.\n *\n * Mark-and-sweep (rather than reference counting) is deliberate: counts are\n * fragile under concurrent edits and CRDT merges, whereas a sweep against the\n * current live set is always correct for the state it observes. Run it\n * periodically or on demand.\n *\n * A manifest that cannot be read or parsed (corruption) contributes no chunk\n * hashes; its own hash still counts as live. The blob it describes is already\n * unusable, so its chunks becoming collectable is acceptable, and GC never\n * throws on a single bad manifest.\n *\n * @param store - The blob store to sweep\n * @param liveRefs - Every reference still reachable from live records\n * @param options - `dryRun` to report without deleting\n */\nexport async function collectBlobGarbage(\n\tstore: ContentAddressedBlobStore,\n\tliveRefs: Iterable<BlobRef>,\n\toptions: BlobGcOptions = {},\n): Promise<BlobGcResult> {\n\tconst live = new Set<string>()\n\tfor (const ref of liveRefs) {\n\t\tlive.add(ref.hash)\n\t\tif (ref.manifestHash === undefined) {\n\t\t\tcontinue\n\t\t}\n\t\tlive.add(ref.manifestHash)\n\t\ttry {\n\t\t\tconst manifestBytes = await store.get(ref.manifestHash)\n\t\t\tif (manifestBytes !== null) {\n\t\t\t\tconst manifest = parseBlobManifest(manifestBytes)\n\t\t\t\tfor (const chunkHash of manifest.chunkHashes) {\n\t\t\t\t\tlive.add(chunkHash)\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// A corrupt/unreadable manifest contributes no chunk hashes; the blob is\n\t\t\t// already broken. Never abort the whole sweep for one bad manifest.\n\t\t}\n\t}\n\n\tconst all = await store.list()\n\tconst collectedHashes: string[] = []\n\tconst graceMs = options.graceMs ?? DEFAULT_BLOB_GC_GRACE_MS\n\tconst cutoff = (options.now ?? Date.now()) - graceMs\n\tconst timed = graceMs > 0 && hasWriteTimes(store) ? store : null\n\tfor (const hash of all) {\n\t\tif (live.has(hash)) {\n\t\t\tcontinue\n\t\t}\n\t\tif (timed) {\n\t\t\tif (options.dryRun) {\n\t\t\t\tconst writtenAt = await timed.lastWrittenAt(hash)\n\t\t\t\tif (writtenAt === null || writtenAt >= cutoff) continue\n\t\t\t} else if (!(await timed.deleteIfWrittenBefore(hash, cutoff))) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcollectedHashes.push(hash)\n\t\t\tcontinue\n\t\t}\n\t\tcollectedHashes.push(hash)\n\t\tif (!options.dryRun) {\n\t\t\tawait store.delete(hash)\n\t\t}\n\t}\n\n\treturn {\n\t\tscanned: all.length,\n\t\tlive: live.size,\n\t\tcollected: collectedHashes.length,\n\t\tcollectedHashes,\n\t}\n}\n"]}