1const Apify = require('apify');
2
3const { utils: { log, sleep }, client } = Apify;
4
5Apify.main(async () => {
6    log.info('Getting input.');
7    const {
8        regexString,
9        waitForFinish,
10        version,
11        buildTag
12    } = await Apify.getInput();
13
14    log.info('Constructing regex.')
15    const regex = new RegExp(regexString, 'i');
16
17    log.info('Getting all user\'s actors.');
18    const { items } = await client.acts.listActs();
19
20    log.info('Filtering items that match our regex.');
21    const actorsToRebuild = items.filter(({ name }) => regex.test(name));
22    const actorCount = actorsToRebuild.length;
23    if (actorCount > 50) {
24        throw new Error(`Too many actors to rebuild (${actorCount}).`
25         + 'Max is 50. Use a more specific regular expression.');
26    }
27
28    log.info(`Starting build of ${actorCount} actors.`);
29    let failedBuildsCount = 0;
30    const promises = actorsToRebuild.map(async ({ id }, idx) => {
31        await sleep(idx * 500);
32        return client.acts.buildAct({
33            actId: id,
34            version,
35            useCache: false,
36            tag: buildTag,
37            waitForFinish: waitForFinish ? 120 : 0
38        }).catch(err => {
39            log.exception(err);
40            failedBuildsCount++
41        });
42        
43    });
44    await Promise.all(promises);
45
46    log.info(`All builds ${waitForFinish ? 'finished' : 'dispatched'}.`);
47    if (failedBuildsCount) {
48        throw new Error('Some of the builds were not successful. See log.');
49    }
50});