import { S3 } from 'aws-sdk' ; import { manifestVersion } from './constants' ; import { FileResult , Manifest , ManifestFile } from './types' ; import { generateRandomBuildId } from './utils' ; async function getAllObjectsFromBucket ( s3 , bucketId ) { let keys = [ ] ; let hasMore = true ; let ContinuationToken ; while ( hasMore ) { const response = await s3 . listObjectsV2 ( { Bucket : bucketId , ContinuationToken } ) . promise ( ) ; if ( response . Contents ) { const _keys = response . Contents . map ( ( entry ) => ( { key : entry . Key ! , eTag : entry . ETag ! , } ) ) ; keys = keys . concat ( _keys ) ; } hasMore = Boolean ( response . IsTruncated ) ; ContinuationToken = response . NextContinuationToken ; } return keys ; } export async function getOrCreateManifest ( s3 , bucketId , deploymentConfigurationKey ) { let manifest ; try { const manifestObj = await s3 . getObject ( { Key : deploymentConfigurationKey , Bucket : bucketId , } ) . promise ( ) ; if ( manifestObj . Body ) { const manifestBody = manifestObj . Body . toString ( 'utf-8' ) ; manifest = JSON . parse ( manifestBody ) as Manifest ; } } catch ( err ) { } if ( manifest ) { return manifest ; } const fileKeys = await getAllObjectsFromBucket ( s3 , bucketId ) ; const newBuildId = generateRandomBuildId ( ) ; const files = { } ; for ( const fileKey of fileKeys ) { files [ fileKey . key ] = { buildId : [ newBuildId ] , eTag : fileKey . eTag , } ; } return { currentBuild : newBuildId , version : manifestVersion , files , } ; }