import { signS3Get, signS3Put, signS3Delete, signS3Copy, encodeCanonicalPath } from '~/utils/sigv4' import { parseBucketsXml, parseObjectsXml, type S3Bucket, type S3Object } from '~/utils/s3xml' export function useS3Client() { const config = useRuntimeConfig() async function get(path: string): Promise { const headers = await signS3Get(path, config.public.s3AccessKey, config.public.s3SecretKey) return $fetch(`/api${encodeCanonicalPath(path)}`, { headers, responseType: 'text' }) } async function listBuckets(): Promise { return parseBucketsXml(await get('/')) } async function listObjects(bucket: string): Promise { return parseObjectsXml(await get(`/${bucket}`)) } async function downloadObject(bucket: string, key: string): Promise { const path = `/${bucket}/${key}` const headers = await signS3Get(path, config.public.s3AccessKey, config.public.s3SecretKey) return $fetch(`/api${encodeCanonicalPath(path)}`, { headers, responseType: 'blob' }) } async function getObjectText(bucket: string, key: string): Promise { return get(`/${bucket}/${key}`) } async function uploadObject(bucket: string, key: string, file: File): Promise { const path = `/${bucket}/${key}` const headers = await signS3Put(path, config.public.s3AccessKey, config.public.s3SecretKey) await $fetch(`/api${encodeCanonicalPath(path)}`, { method: 'PUT', headers: { ...headers, 'Content-Type': file.type || 'application/octet-stream' }, body: file, }) } async function deleteObject(bucket: string, key: string): Promise { const path = `/${bucket}/${key}` const headers = await signS3Delete(path, config.public.s3AccessKey, config.public.s3SecretKey) await $fetch(`/api${encodeCanonicalPath(path)}`, { method: 'DELETE', headers }) } async function copyObject(sourceBucket: string, sourceKey: string, destBucket: string, destKey: string): Promise { const destPath = `/${destBucket}/${destKey}` const copySource = `/${sourceBucket}/${sourceKey}` const headers = await signS3Copy(destPath, copySource, config.public.s3AccessKey, config.public.s3SecretKey) await $fetch(`/api${encodeCanonicalPath(destPath)}`, { method: 'PUT', headers }) } async function moveObject(sourceBucket: string, sourceKey: string, destBucket: string, destKey: string): Promise { await copyObject(sourceBucket, sourceKey, destBucket, destKey) await deleteObject(sourceBucket, sourceKey) } return { listBuckets, listObjects, downloadObject, getObjectText, uploadObject, deleteObject, copyObject, moveObject } }