function sort( pkgs ) {
	var deps;
	var idx;
	var out;
	var M;
	var N;
	var i;
	var j;

	N = pkgs.length;
	if ( N === 0 ) {
		return pkgs;
	}
	M = new CompactAdjacencyMatrix( N );
	for ( i = 0; i < N; i++ ) {
		debug( 'Resolving dependencies for package: %s (%d of %d)', pkgs[ i ], i+1, N );
		deps = depList( pkgs[ i ], OPTS );

		debug( 'Processing %d dependencies...', deps.length );
		for ( j = 0; j < deps.length; j++ ) {
			idx = indexOf( pkgs, deps[ j ] );

			if (
				idx >= 0 && // ignore external dependencies
				!contains( deps[ j ], '_tools' ) && // ignore internal tools packages
				!isAncestorPackage( deps[ j ], pkgs[ i ] ) // ignore dependencies which are parent packages
			) {
				M.addEdge( idx, i );
			}
		}
	}
	debug( 'Sorting packages...' );
	out = M.toposort( pkgs );

	if ( out[ 0 ] ) {
		debug( 'Successfully sorted packages.' );
		out = out[ 0 ];
		for ( i = 0; i < out.length; i++ ) {
			out[ i ] = pkgs[ out[ i ] ];
		}
		return out;
	}
	out = out[ 1 ];
	for ( i = 0; i < out.length; i++ ) {
		out[ i ] = pkgs[ out[ i ] ];
	}
	debug( 'Failed to sort packages. Detected the following dependency chain containing a cycle: %s', out.join( ' -> ' ) );
	return new Error( format( 'unexpected error. Failed to sort packages. Detected the following dependency chain containing a cycle: `%s`.', out.join( ' -> ' ) ) );
}
Returns a topological sort.

@private
@param {(StringArray|EmptyArray)} pkgs - list of package names
@returns {(StringArray|EmptyArray|Error)} sorted package names