{"version":3,"sources":["/home/runner/work/kora/kora/packages/store/dist/blob-object.cjs","../src/blob/open-blob-store.ts","../src/blob/azure-blob-backend.ts","../src/blob/object-blob-store.ts","../src/blob/s3-blob-backend.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACZA,oCAA0B;ADc1B;AACA;AEfA,gCAA2B;AFiB3B;AACA;AGlBA;AAGC;AACA;AACA;AAAA;AAKD,IAAM,aAAA,EAAe,gBAAA;AACrB,IAAM,qBAAA,EAAuB,CAAA;AAC7B,IAAM,cAAA,EAAgB,GAAA;AACtB,IAAM,mBAAA,EAAqB,GAAA;AAEpB,IAAM,iBAAA,EAAN,MAAA,QAA+B,gBAAU;AAAA,EAC/C,WAAA,CACC,OAAA,EACgB,MAAA,EACf;AACD,IAAA,KAAA,CAAM,OAAA,EAAS,oBAAA,EAAsB,EAAE,OAAO,CAAC,CAAA;AAF/B,IAAA,IAAA,CAAA,OAAA,EAAA,MAAA;AAAA,EAGjB;AAAA,EAHiB;AAIlB,CAAA;AAkCO,IAAM,gBAAA,YAAN,MAA2D;AAAA,EAMjE,WAAA,CAA6B,OAAA,EAA+B;AAA/B,IAAA,IAAA,CAAA,QAAA,EAAA,OAAA;AAC5B,IAAA,IAAA,CAAK,SAAA,EAAW,OAAA,CAAQ,QAAA;AAAA,EACzB;AAAA,EAF6B;AAAA,iBALpB,QAAA,EAAU,KAAA;AAAA,EACV;AAAA,kBACD,WAAA,EAA4B,KAAA;AAAA,kBAC5B,cAAA,EAAkC,OAAA,CAAQ,OAAA,CAAQ,EAAA;AAAA,EAM1D,MAAM,GAAA,CAAI,KAAA,EAAmB,SAAA,EAA4B,CAAC,CAAA,EAAqB;AAC9E,IAAA,MAAM,IAAA,EAAM,MAAM,iCAAA,KAAc,EAAO,QAAQ,CAAA;AAC/C,IAAA,MAAM,IAAA,CAAK,KAAA,CAAM,GAAA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,UAAA;AACA,UAAA;AACA,UAAA;AACA,QAAA;AACD,QAAA;AACD,MAAA;AACA,MAAA;AACD,IAAA;AACD,EAAA;AACM,EAAA;AAEJ,IAAA;AACA,IAAA;AACD,EAAA;AAEM,EAAA;AACN,IAAA;AACM,IAAA;AACL,MAAA;AACC,QAAA;AACA,QAAA;AACA,QAAA;AACC,UAAA;AACA,UAAA;AACA,UAAA;AACD,QAAA;AACA,QAAA;AACD,MAAA;AACA,MAAA;AACI,MAAA;AACA,MAAA;AACJ,MAAA;AACD,IAAA;AACM,IAAA;AACL,MAAA;AACC,QAAA;AACA,QAAA;AACA,QAAA;AACA,MAAA;AAED,MAAA;AACI,MAAA;AACL,IAAA;AACM,IAAA;AACL,MAAA;AACI,MAAA;AACA,MAAA;AACJ,MAAA;AACC,QAAA;AACA,QAAA;AACA,QAAA;AACD,MAAA;AACD,IAAA;AACM,IAAA;AACL,MAAA;AACI,MAAA;AACA,MAAA;AACJ,MAAA;AACD,IAAA;AACM,IAAA;AACL,MAAA;AACI,MAAA;AACA,MAAA;AACJ,MAAA;AACD,IAAA;AACM,IAAA;AACL,MAAA;AACI,MAAA;AACD,MAAA;AACF,QAAA;AACC,UAAA;AACA,UAAA;AACD,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACC,UAAA;AACA,UAAA;AACD,QAAA;AACA,QAAA;AACD,MAAA;AACA,MAAA;AACD,IAAA;AACD,EAAA;AACD;AJwOU;AACA;AC7ZD;AACD,EAAA;AACR;AAqBgB;AAGT,EAAA;AACF,EAAA;AACC,IAAA;AACA,IAAA;AACH,MAAA;AACD,IAAA;AACC,MAAA;AACC,QAAA;AACA,QAAA;AACD,MAAA;AACD,IAAA;AACI,IAAA;AACH,MAAA;AACA,MAAA;AACI,MAAA;AACH,QAAA;AACC,UAAA;AACA,UAAA;AACD,QAAA;AACD,MAAA;AACC,QAAA;AACC,UAAA;AACA,UAAA;AACA,UAAA;AACA,UAAA;AACA,UAAA;AACA,QAAA;AACF,MAAA;AACD,IAAA;AACI,IAAA;AACH,MAAA;AACC,QAAA;AACC,UAAA;AACA,UAAA;AACA,QAAA;AACF,MAAA;AACD,IAAA;AACM,IAAA;AACL,MAAA;AACA,MAAA;AACD,IAAA;AACD,EAAA;AACM,EAAA;AACC,EAAA;AACR;ADyYU;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/kora/kora/packages/store/dist/blob-object.cjs","sourcesContent":[null,"import { KoraError } from '@korajs/core'\nimport { createAzureBlobBackend, managedIdentityTokenProvider } from './azure-blob-backend'\nimport type { ContentAddressedBlobStore } from './content-addressed-blob-store'\nimport { FilesystemBlobStore } from './filesystem-blob-store'\nimport { ObjectBlobStore } from './object-blob-store'\nimport { createS3BlobBackend } from './s3-blob-backend'\n\nexport type BlobStoreEnvironment = Readonly<Record<string, string | undefined>>\n\nfunction invalid(message: string, code: string): KoraError {\n\treturn new KoraError(message, code)\n}\n\n/**\n * Opens the blob store the host configured, so application code never names a provider.\n *\n * - `KORA_BLOB_STORE_URL=s3://<bucket>`, with `KORA_BLOB_STORE_ACCESS_KEY_ID`,\n *   `KORA_BLOB_STORE_SECRET_ACCESS_KEY`, and optionally `KORA_BLOB_STORE_REGION` and\n *   `KORA_BLOB_STORE_ENDPOINT` for S3-compatible services such as R2 and MinIO.\n * - `KORA_BLOB_STORE_URL=https://<account>.blob.core.windows.net/<container>`, using the workload's\n *   managed identity (`AZURE_CLIENT_ID` picks one).\n * - `KORA_BLOB_DIR=/path` for a directory.\n *\n * Returns null when none is configured. A store it can't use is refused here, at startup, rather\n * than at the first upload.\n *\n * @example\n * ```typescript\n * const blobs = openBlobStoreFromEnv(process.env)\n * createProductionServer({ store, syncOptions: blobs ? toServerBlobCallbacks(blobs) : {} })\n * ```\n */\nexport function openBlobStoreFromEnv(\n\tenv: BlobStoreEnvironment,\n): (ContentAddressedBlobStore & { readonly location?: string }) | null {\n\tconst raw = env.KORA_BLOB_STORE_URL?.trim()\n\tif (raw) {\n\t\tlet url: URL\n\t\ttry {\n\t\t\turl = new URL(raw)\n\t\t} catch {\n\t\t\tthrow invalid(\n\t\t\t\t'KORA_BLOB_STORE_URL is not a valid URL. Use s3://<bucket> or https://<account>.blob.core.windows.net/<container>.',\n\t\t\t\t'INVALID_BLOB_STORE_URL',\n\t\t\t)\n\t\t}\n\t\tif (url.protocol === 's3:') {\n\t\t\tconst accessKeyId = env.KORA_BLOB_STORE_ACCESS_KEY_ID\n\t\t\tconst secretAccessKey = env.KORA_BLOB_STORE_SECRET_ACCESS_KEY\n\t\t\tif (!accessKeyId || !secretAccessKey)\n\t\t\t\tthrow invalid(\n\t\t\t\t\t'An s3:// blob store needs KORA_BLOB_STORE_ACCESS_KEY_ID and KORA_BLOB_STORE_SECRET_ACCESS_KEY.',\n\t\t\t\t\t'BLOB_STORE_CREDENTIALS_MISSING',\n\t\t\t\t)\n\t\t\treturn new ObjectBlobStore(\n\t\t\t\tcreateS3BlobBackend({\n\t\t\t\t\tbucket: url.hostname,\n\t\t\t\t\taccessKeyId,\n\t\t\t\t\tsecretAccessKey,\n\t\t\t\t\t...(env.KORA_BLOB_STORE_REGION ? { region: env.KORA_BLOB_STORE_REGION } : {}),\n\t\t\t\t\t...(env.KORA_BLOB_STORE_ENDPOINT ? { endpoint: env.KORA_BLOB_STORE_ENDPOINT } : {}),\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t\tif (url.protocol === 'https:' && url.hostname.endsWith('.blob.core.windows.net')) {\n\t\t\treturn new ObjectBlobStore(\n\t\t\t\tcreateAzureBlobBackend({\n\t\t\t\t\tcontainerUrl: raw,\n\t\t\t\t\tgetToken: managedIdentityTokenProvider(env, env.AZURE_CLIENT_ID),\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t\tthrow invalid(\n\t\t\t`KORA_BLOB_STORE_URL points at ${url.host}, which isn't a supported store. Use s3://<bucket> or an Azure Blob container URL.`,\n\t\t\t'UNSUPPORTED_BLOB_STORE',\n\t\t)\n\t}\n\tconst dir = env.KORA_BLOB_DIR?.trim()\n\treturn dir ? new FilesystemBlobStore(dir) : null\n}\n","import { createHash } from 'node:crypto'\nimport {\n\ttype ObjectProperties,\n\ttype ObjectStorageBackend,\n\tObjectStoreError,\n\ttype RetryOptions,\n\tsendWithRetry,\n} from './object-blob-store'\n\nconst API_VERSION = '2023-11-03'\nconst STORAGE_RESOURCE = 'https://storage.azure.com/'\n/** Refresh this long before expiry, so a token never lapses in the middle of a request. */\nconst TOKEN_EARLY_REFRESH_MS = 5 * 60_000\n\nexport interface AzureBlobBackendOptions extends RetryOptions {\n\t/** `https://<account>.blob.core.windows.net/<container>` */\n\treadonly containerUrl: string\n\treadonly getToken: () => Promise<string>\n}\n\ninterface ManagedIdentityEnvironment {\n\treadonly IDENTITY_ENDPOINT?: string | undefined\n\treadonly IDENTITY_HEADER?: string | undefined\n}\n\n/**\n * Tokens from the managed identity of the Azure workload this process runs in, so the application\n * holds no storage key. `clientId` picks one identity when several are attached.\n */\nexport function managedIdentityTokenProvider(\n\tenv: ManagedIdentityEnvironment,\n\tclientId: string | undefined,\n\tfetchImpl: typeof globalThis.fetch = globalThis.fetch,\n): () => Promise<string> {\n\tlet cached: { readonly token: string; readonly expiresAt: number } | null = null\n\tlet pending: Promise<string> | null = null\n\n\tasync function acquire(): Promise<string> {\n\t\tif (!env.IDENTITY_ENDPOINT || !env.IDENTITY_HEADER) {\n\t\t\tthrow new ObjectStoreError(\n\t\t\t\t'No managed identity is available: IDENTITY_ENDPOINT and IDENTITY_HEADER are not set. This store authenticates as an Azure workload, so give the app a managed identity or configure a different blob store.',\n\t\t\t\tnull,\n\t\t\t)\n\t\t}\n\t\tconst url = new URL(env.IDENTITY_ENDPOINT)\n\t\turl.searchParams.set('resource', STORAGE_RESOURCE)\n\t\turl.searchParams.set('api-version', '2019-08-01')\n\t\tif (clientId) url.searchParams.set('client_id', clientId)\n\t\tconst response = await fetchImpl(url, { headers: { 'X-IDENTITY-HEADER': env.IDENTITY_HEADER } })\n\t\tif (!response.ok) {\n\t\t\tthrow new ObjectStoreError(\n\t\t\t\t`The managed identity endpoint refused a storage token (${response.status}). Check that the identity is attached to this app.`,\n\t\t\t\tresponse.status,\n\t\t\t)\n\t\t}\n\t\tconst body = (await response.json()) as { access_token: string; expires_on: string | number }\n\t\tcached = { token: body.access_token, expiresAt: Number(body.expires_on) * 1000 }\n\t\treturn body.access_token\n\t}\n\n\treturn async () => {\n\t\tif (cached && cached.expiresAt - TOKEN_EARLY_REFRESH_MS > Date.now()) return cached.token\n\t\tpending ??= acquire().finally(() => {\n\t\t\tpending = null\n\t\t})\n\t\treturn pending\n\t}\n}\n\nexport function createAzureBlobBackend(options: AzureBlobBackendOptions): ObjectStorageBackend {\n\tconst container = options.containerUrl.replace(/\\/+$/, '')\n\tconst request = async (\n\t\tmethod: string,\n\t\tpath: string,\n\t\theaders: Readonly<Record<string, string>> = {},\n\t\tbody?: Uint8Array,\n\t): Promise<Response> =>\n\t\tsendWithRetry(\n\t\t\t`${container}${path}`,\n\t\t\tasync () => ({\n\t\t\t\tmethod,\n\t\t\t\theaders: {\n\t\t\t\t\tauthorization: `Bearer ${await options.getToken()}`,\n\t\t\t\t\t'x-ms-version': API_VERSION,\n\t\t\t\t\t...headers,\n\t\t\t\t},\n\t\t\t\t...(body ? { body: body as unknown as BodyInit } : {}),\n\t\t\t}),\n\t\t\toptions,\n\t\t)\n\tconst failed = (response: Response, action: string): ObjectStoreError =>\n\t\tnew ObjectStoreError(\n\t\t\t`Could not ${action} a blob in ${container}: ${response.status} (${response.headers.get('x-ms-error-code') ?? 'unknown'}). A 403 means the app's identity has no access to this container yet.`,\n\t\t\tresponse.status,\n\t\t)\n\n\treturn {\n\t\tlocation: container,\n\t\tasync putIfAbsent(key, bytes) {\n\t\t\tconst response = await request(\n\t\t\t\t'PUT',\n\t\t\t\t`/${key}`,\n\t\t\t\t{\n\t\t\t\t\t'x-ms-blob-type': 'BlockBlob',\n\t\t\t\t\t'If-None-Match': '*',\n\t\t\t\t\t// The service rejects the upload if these bytes were damaged on the way.\n\t\t\t\t\t'Content-MD5': createHash('md5').update(bytes).digest('base64'),\n\t\t\t\t\t'Content-Type': 'application/octet-stream',\n\t\t\t\t},\n\t\t\t\tbytes,\n\t\t\t)\n\t\t\tawait response.body?.cancel()\n\t\t\tif (response.status === 201) return 'created'\n\t\t\tif (response.status === 409 || response.status === 412) return 'exists'\n\t\t\tthrow failed(response, 'write')\n\t\t},\n\t\tasync touch(key) {\n\t\t\tconst response = await request('PUT', `/${key}?comp=metadata`, {\n\t\t\t\t'x-ms-meta-refreshedat': String(Date.now()),\n\t\t\t})\n\t\t\tif (response.status !== 200) throw failed(response, 'refresh')\n\t\t},\n\t\tasync head(key): Promise<ObjectProperties | null> {\n\t\t\tconst response = await request('HEAD', `/${key}`)\n\t\t\tif (response.status === 404) return null\n\t\t\tif (response.status !== 200) throw failed(response, 'inspect')\n\t\t\treturn {\n\t\t\t\tetag: response.headers.get('etag') ?? '',\n\t\t\t\tbytes: Number(response.headers.get('content-length') ?? 0),\n\t\t\t\twrittenAt: Date.parse(response.headers.get('last-modified') ?? ''),\n\t\t\t}\n\t\t},\n\t\tasync get(key) {\n\t\t\tconst response = await request('GET', `/${key}`)\n\t\t\tif (response.status === 404) return null\n\t\t\tif (response.status !== 200) throw failed(response, 'read')\n\t\t\treturn new Uint8Array(await response.arrayBuffer())\n\t\t},\n\t\tasync delete(key, ifEtag) {\n\t\t\tconst response = await request('DELETE', `/${key}`, ifEtag ? { 'If-Match': ifEtag } : {})\n\t\t\tif (response.status === 404 || response.status === 412) return false\n\t\t\tif (response.status !== 202) throw failed(response, 'delete')\n\t\t\treturn true\n\t\t},\n\t\tasync list() {\n\t\t\tconst entries: { key: string; bytes: number }[] = []\n\t\t\tlet marker = ''\n\t\t\tdo {\n\t\t\t\tconst response = await request(\n\t\t\t\t\t'GET',\n\t\t\t\t\t`?restype=container&comp=list${marker ? `&marker=${encodeURIComponent(marker)}` : ''}`,\n\t\t\t\t)\n\t\t\t\tif (response.status !== 200) throw failed(response, 'list')\n\t\t\t\tconst xml = await response.text()\n\t\t\t\tfor (const [, blob = ''] of xml.matchAll(/<Blob>([\\s\\S]*?)<\\/Blob>/g)) {\n\t\t\t\t\tconst key = blob.match(/<Name>([^<]*)<\\/Name>/)?.[1]\n\t\t\t\t\tif (key)\n\t\t\t\t\t\tentries.push({\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tbytes: Number(blob.match(/<Content-Length>(\\d+)<\\/Content-Length>/)?.[1] ?? 0),\n\t\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tmarker = xml.match(/<NextMarker>([^<]+)<\\/NextMarker>/)?.[1] ?? ''\n\t\t\t} while (marker)\n\t\t\treturn entries\n\t\t},\n\t}\n}\n","import {\n\ttype BlobRef,\n\ttype BlobRefMetadata,\n\tKoraError,\n\tcreateBlobRef,\n\thashBlob,\n} from '@korajs/core'\nimport { BlobIntegrityError, type ContentAddressedBlobStore } from './content-addressed-blob-store'\n\n/** Hashes can arrive from clients. Only this shape is ever turned into a key, so none can escape the store. */\nconst CONTENT_HASH = /^[a-f0-9]{64}$/\nconst DEFAULT_MAX_ATTEMPTS = 5\nconst RETRY_BASE_MS = 250\nconst REQUEST_TIMEOUT_MS = 60_000\n\nexport class ObjectStoreError extends KoraError {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly status: number | null,\n\t) {\n\t\tsuper(message, 'OBJECT_STORE_ERROR', { status })\n\t}\n}\n\nexport interface ObjectProperties {\n\treadonly etag: string\n\treadonly bytes: number\n\treadonly writtenAt: number\n}\n\n/**\n * The few operations a cloud object store must offer. Everything that decides whether data is safe\n * lives in {@link ObjectBlobStore}, so a new provider is only this translation.\n */\nexport interface ObjectStorageBackend {\n\t/** Where the bytes live, for logs. Must not contain a credential. */\n\treadonly location: string\n\t/** Writes atomically unless the key exists, and must never replace existing bytes. */\n\tputIfAbsent(key: string, bytes: Uint8Array): Promise<'created' | 'exists'>\n\t/** Makes an existing object count as just written. */\n\ttouch(key: string): Promise<void>\n\thead(key: string): Promise<ObjectProperties | null>\n\tget(key: string): Promise<Uint8Array | null>\n\t/** With `ifEtag`, deletes only that exact version. False when the condition failed. */\n\tdelete(key: string, ifEtag?: string): Promise<boolean>\n\tlist(): Promise<readonly { readonly key: string; readonly bytes: number }[]>\n}\n\n/**\n * A durable {@link ContentAddressedBlobStore} on any object store.\n *\n * Objects use the `<hash[0:2]>/<hash>` layout of the filesystem store, so a store moves between\n * providers by copying paths. Reads verify the bytes hash to the requested key. Beyond the base\n * contract it reports write times and total bytes, which a server needs to bound the store and\n * collect unreferenced content safely.\n */\nexport class ObjectBlobStore implements ContentAddressedBlobStore {\n\treadonly durable = true\n\treadonly location: string\n\tprivate totalCache: number | null = null\n\tprivate capacityQueue: Promise<unknown> = Promise.resolve()\n\n\tconstructor(private readonly backend: ObjectStorageBackend) {\n\t\tthis.location = backend.location\n\t}\n\n\tasync put(bytes: Uint8Array, metadata: BlobRefMetadata = {}): Promise<BlobRef> {\n\t\tconst ref = await createBlobRef(bytes, metadata)\n\t\tawait this.write(ref.hash, bytes)\n\t\treturn ref\n\t}\n\n\t/**\n\t * {@link put}, unless the content is new and would take the store past `maxTotalBytes`. Serialized\n\t * within this process. Separate processes can overshoot by what they upload at the same moment.\n\t */\n\tputWithinCapacity(\n\t\tbytes: Uint8Array,\n\t\tmaxTotalBytes: number,\n\t): Promise<'stored' | 'refreshed' | 'full'> {\n\t\tconst run = this.capacityQueue.then(async () => {\n\t\t\tconst hash = await hashBlob(bytes)\n\t\t\tif (!(await this.has(hash)) && (await this.totalBytes()) + bytes.byteLength > maxTotalBytes) {\n\t\t\t\treturn 'full' as const\n\t\t\t}\n\t\t\treturn this.write(hash, bytes)\n\t\t})\n\t\tthis.capacityQueue = run.catch(() => undefined)\n\t\treturn run\n\t}\n\n\tasync get(hash: string): Promise<Uint8Array | null> {\n\t\tif (!CONTENT_HASH.test(hash)) return null\n\t\tconst bytes = await this.backend.get(keyFor(hash))\n\t\tif (!bytes) return null\n\t\tconst actual = await hashBlob(bytes)\n\t\tif (actual !== hash) throw new BlobIntegrityError(hash, actual)\n\t\treturn bytes\n\t}\n\n\tasync has(hash: string): Promise<boolean> {\n\t\treturn (await this.properties(hash)) !== null\n\t}\n\n\tasync delete(hash: string): Promise<boolean> {\n\t\tconst known = await this.properties(hash)\n\t\tif (!known || !(await this.backend.delete(keyFor(hash)))) return false\n\t\tthis.adjustTotal(-known.bytes)\n\t\treturn true\n\t}\n\n\t/** When the bytes behind `hash` were last written or uploaded again, in ms, or null when absent. */\n\tasync lastWrittenAt(hash: string): Promise<number | null> {\n\t\treturn (await this.properties(hash))?.writtenAt ?? null\n\t}\n\n\t/** Deletes only if not written since `cutoffMs`. A re-upload racing the delete wins. */\n\tasync deleteIfWrittenBefore(hash: string, cutoffMs: number): Promise<boolean> {\n\t\tconst known = await this.properties(hash)\n\t\tif (!known || known.writtenAt >= cutoffMs) return false\n\t\tif (!(await this.backend.delete(keyFor(hash), known.etag))) return false\n\t\tthis.adjustTotal(-known.bytes)\n\t\treturn true\n\t}\n\n\tasync size(): Promise<number> {\n\t\treturn (await this.backend.list()).length\n\t}\n\n\tasync list(): Promise<string[]> {\n\t\treturn (await this.backend.list()).map(({ key }) => key.slice(key.lastIndexOf('/') + 1))\n\t}\n\n\tasync totalBytes(): Promise<number> {\n\t\tif (this.totalCache === null) {\n\t\t\tthis.totalCache = (await this.backend.list()).reduce((sum, entry) => sum + entry.bytes, 0)\n\t\t}\n\t\treturn this.totalCache\n\t}\n\n\tprivate async write(hash: string, bytes: Uint8Array): Promise<'stored' | 'refreshed'> {\n\t\tif ((await this.backend.putIfAbsent(keyFor(hash), bytes)) === 'created') {\n\t\t\tthis.adjustTotal(bytes.byteLength)\n\t\t\treturn 'stored'\n\t\t}\n\t\t// Garbage collection spares recent uploads, so an upload of existing content must count as one.\n\t\tawait this.backend.touch(keyFor(hash))\n\t\treturn 'refreshed'\n\t}\n\n\tprivate async properties(hash: string): Promise<ObjectProperties | null> {\n\t\treturn CONTENT_HASH.test(hash) ? this.backend.head(keyFor(hash)) : null\n\t}\n\n\tprivate adjustTotal(delta: number): void {\n\t\tif (this.totalCache !== null) this.totalCache += delta\n\t}\n}\n\nfunction keyFor(hash: string): string {\n\treturn `${hash.slice(0, 2)}/${hash}`\n}\n\nexport interface RetryOptions {\n\treadonly fetch?: typeof globalThis.fetch\n\treadonly maxAttempts?: number\n\treadonly sleep?: (ms: number) => Promise<void>\n}\n\n/** Sends a request, retrying what is safe to retry. `prepare` runs per attempt so signatures stay fresh. */\nexport async function sendWithRetry(\n\turl: string,\n\tprepare: () => Promise<RequestInit>,\n\toptions: RetryOptions = {},\n): Promise<Response> {\n\tconst send = options.fetch ?? globalThis.fetch\n\tconst attempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS\n\tconst sleep =\n\t\toptions.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))\n\tlet failure: unknown\n\tfor (let attempt = 1; attempt <= attempts; attempt += 1) {\n\t\ttry {\n\t\t\tconst init = await prepare()\n\t\t\tconst response = await send(url, { ...init, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) })\n\t\t\tif (response.status !== 408 && response.status !== 429 && response.status < 500)\n\t\t\t\treturn response\n\t\t\tfailure = new ObjectStoreError(\n\t\t\t\t`The object store returned ${response.status}`,\n\t\t\t\tresponse.status,\n\t\t\t)\n\t\t\tawait response.body?.cancel()\n\t\t} catch (error) {\n\t\t\t// A status of null means configuration is wrong, which no retry will fix.\n\t\t\tif (error instanceof ObjectStoreError && error.status === null) throw error\n\t\t\tfailure = error\n\t\t}\n\t\tif (attempt < attempts) await sleep(RETRY_BASE_MS * 2 ** (attempt - 1))\n\t}\n\tthrow failure\n}\n","import { createHash, createHmac } from 'node:crypto'\nimport {\n\ttype ObjectProperties,\n\ttype ObjectStorageBackend,\n\tObjectStoreError,\n\ttype RetryOptions,\n\tsendWithRetry,\n} from './object-blob-store'\n\nexport interface S3BlobBackendOptions extends RetryOptions {\n\treadonly bucket: string\n\treadonly accessKeyId: string\n\treadonly secretAccessKey: string\n\treadonly region?: string\n\t/** For S3-compatible services such as R2 and MinIO. Defaults to AWS for the region. */\n\treadonly endpoint?: string\n\treadonly now?: () => Date\n}\n\nconst sha256 = (data: string | Uint8Array): string =>\n\tcreateHash('sha256').update(data).digest('hex')\nconst hmac = (key: string | Buffer, data: string): Buffer =>\n\tcreateHmac('sha256', key).update(data).digest()\nconst encodeSegment = (value: string): string =>\n\tencodeURIComponent(value).replace(\n\t\t/[!'()*]/g,\n\t\t(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,\n\t)\n\n/** Signs a request with AWS Signature Version 4. Exported so it can be checked against AWS's published vectors. */\nexport function signS3Request(input: {\n\treadonly method: string\n\treadonly url: URL\n\treadonly headers: Readonly<Record<string, string>>\n\treadonly payloadHash: string\n\treadonly accessKeyId: string\n\treadonly secretAccessKey: string\n\treadonly region: string\n\treadonly now: Date\n}): Record<string, string> {\n\tconst amzDate = input.now.toISOString().replace(/[:-]|\\.\\d{3}/g, '')\n\tconst day = amzDate.slice(0, 8)\n\tconst headers: Record<string, string> = {\n\t\t...input.headers,\n\t\thost: input.url.host,\n\t\t'x-amz-content-sha256': input.payloadHash,\n\t\t'x-amz-date': amzDate,\n\t}\n\tconst names = Object.keys(headers)\n\t\t.map((name) => name.toLowerCase())\n\t\t.sort()\n\tconst lower = Object.fromEntries(\n\t\tObject.entries(headers).map(([name, value]) => [name.toLowerCase(), value.trim()]),\n\t)\n\tconst signedHeaders = names.join(';')\n\tconst query = [...input.url.searchParams.entries()]\n\t\t.map(([name, value]) => [encodeSegment(name), encodeSegment(value)] as const)\n\t\t.sort(([a, av], [b, bv]) => (a === b ? (av < bv ? -1 : 1) : a < b ? -1 : 1))\n\t\t.map(([name, value]) => `${name}=${value}`)\n\t\t.join('&')\n\tconst canonical = [\n\t\tinput.method,\n\t\tinput.url.pathname,\n\t\tquery,\n\t\t...names.map((name) => `${name}:${lower[name]}`),\n\t\t'',\n\t\tsignedHeaders,\n\t\tinput.payloadHash,\n\t].join('\\n')\n\tconst scope = `${day}/${input.region}/s3/aws4_request`\n\tconst toSign = ['AWS4-HMAC-SHA256', amzDate, scope, sha256(canonical)].join('\\n')\n\tconst key = hmac(\n\t\thmac(hmac(hmac(`AWS4${input.secretAccessKey}`, day), input.region), 's3'),\n\t\t'aws4_request',\n\t)\n\tconst signature = createHmac('sha256', key).update(toSign).digest('hex')\n\treturn {\n\t\t...headers,\n\t\tauthorization: `AWS4-HMAC-SHA256 Credential=${input.accessKeyId}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`,\n\t}\n}\n\n/** S3 and the services that speak its API. Needs conditional writes and deletes, which AWS has offered since 2024. */\nexport function createS3BlobBackend(options: S3BlobBackendOptions): ObjectStorageBackend {\n\tconst region = options.region ?? 'us-east-1'\n\tconst endpoint = (options.endpoint ?? `https://s3.${region}.amazonaws.com`).replace(/\\/+$/, '')\n\tconst location = `${endpoint}/${options.bucket}`\n\tconst request = async (\n\t\tmethod: string,\n\t\tpath: string,\n\t\theaders: Readonly<Record<string, string>> = {},\n\t\tbody?: Uint8Array,\n\t): Promise<Response> => {\n\t\tconst target = `${location}${path}`\n\t\tconst payloadHash = sha256(body ?? '')\n\t\treturn sendWithRetry(\n\t\t\ttarget,\n\t\t\tasync () => ({\n\t\t\t\tmethod,\n\t\t\t\theaders: signS3Request({\n\t\t\t\t\tmethod,\n\t\t\t\t\turl: new URL(target),\n\t\t\t\t\theaders,\n\t\t\t\t\tpayloadHash,\n\t\t\t\t\taccessKeyId: options.accessKeyId,\n\t\t\t\t\tsecretAccessKey: options.secretAccessKey,\n\t\t\t\t\tregion,\n\t\t\t\t\tnow: options.now?.() ?? new Date(),\n\t\t\t\t}),\n\t\t\t\t...(body ? { body: body as unknown as BodyInit } : {}),\n\t\t\t}),\n\t\t\toptions,\n\t\t)\n\t}\n\tconst failed = (response: Response, action: string): ObjectStoreError =>\n\t\tnew ObjectStoreError(\n\t\t\t`Could not ${action} an object in ${location}: ${response.status}. A 403 means these credentials have no access to this bucket.`,\n\t\t\tresponse.status,\n\t\t)\n\n\treturn {\n\t\tlocation,\n\t\tasync putIfAbsent(key, bytes) {\n\t\t\tconst response = await request(\n\t\t\t\t'PUT',\n\t\t\t\t`/${key}`,\n\t\t\t\t{\n\t\t\t\t\t'if-none-match': '*',\n\t\t\t\t\t'content-md5': createHash('md5').update(bytes).digest('base64'),\n\t\t\t\t\t'content-type': 'application/octet-stream',\n\t\t\t\t},\n\t\t\t\tbytes,\n\t\t\t)\n\t\t\tawait response.body?.cancel()\n\t\t\tif (response.status === 200) return 'created'\n\t\t\tif (response.status === 409 || response.status === 412) return 'exists'\n\t\t\tthrow failed(response, 'write')\n\t\t},\n\t\tasync touch(key) {\n\t\t\tconst response = await request('PUT', `/${key}`, {\n\t\t\t\t'x-amz-copy-source': `/${options.bucket}/${key}`,\n\t\t\t\t'x-amz-metadata-directive': 'REPLACE',\n\t\t\t\t'x-amz-meta-refreshedat': String(Date.now()),\n\t\t\t})\n\t\t\t// A copy can report 200 and still carry an error in its body.\n\t\t\tconst text = await response.text()\n\t\t\tif (response.status !== 200 || text.includes('<Error>')) throw failed(response, 'refresh')\n\t\t},\n\t\tasync head(key): Promise<ObjectProperties | null> {\n\t\t\tconst response = await request('HEAD', `/${key}`)\n\t\t\tif (response.status === 404) return null\n\t\t\tif (response.status !== 200) throw failed(response, 'inspect')\n\t\t\treturn {\n\t\t\t\tetag: response.headers.get('etag') ?? '',\n\t\t\t\tbytes: Number(response.headers.get('content-length') ?? 0),\n\t\t\t\twrittenAt: Date.parse(response.headers.get('last-modified') ?? ''),\n\t\t\t}\n\t\t},\n\t\tasync get(key) {\n\t\t\tconst response = await request('GET', `/${key}`)\n\t\t\tif (response.status === 404) return null\n\t\t\tif (response.status !== 200) throw failed(response, 'read')\n\t\t\treturn new Uint8Array(await response.arrayBuffer())\n\t\t},\n\t\tasync delete(key, ifEtag) {\n\t\t\tconst response = await request('DELETE', `/${key}`, ifEtag ? { 'if-match': ifEtag } : {})\n\t\t\tif (response.status === 412 || response.status === 404) return false\n\t\t\tif (response.status !== 204) throw failed(response, 'delete')\n\t\t\treturn true\n\t\t},\n\t\tasync list() {\n\t\t\tconst entries: { key: string; bytes: number }[] = []\n\t\t\tlet token = ''\n\t\t\tdo {\n\t\t\t\tconst response = await request(\n\t\t\t\t\t'GET',\n\t\t\t\t\t`?list-type=2${token ? `&continuation-token=${encodeURIComponent(token)}` : ''}`,\n\t\t\t\t)\n\t\t\t\tif (response.status !== 200) throw failed(response, 'list')\n\t\t\t\tconst xml = await response.text()\n\t\t\t\tfor (const [, item = ''] of xml.matchAll(/<Contents>([\\s\\S]*?)<\\/Contents>/g)) {\n\t\t\t\t\tconst key = item.match(/<Key>([^<]*)<\\/Key>/)?.[1]\n\t\t\t\t\tif (key) entries.push({ key, bytes: Number(item.match(/<Size>(\\d+)<\\/Size>/)?.[1] ?? 0) })\n\t\t\t\t}\n\t\t\t\ttoken = xml.match(/<NextContinuationToken>([^<]+)<\\/NextContinuationToken>/)?.[1] ?? ''\n\t\t\t} while (token)\n\t\t\treturn entries\n\t\t},\n\t}\n}\n"]}