All files / rusted-chromium/download download.ts

73.49% Statements 61/83
50% Branches 15/30
56.25% Functions 9/16
73.17% Lines 60/82

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 1864x 4x 4x   4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x     4x 4x       11x                                   1x           1x               1x 1x 1x     1x 1x                             15x       15x 15x   15x   15x                       15x   15x   15x 11x 11x       11x         11x   11x   11x 19x 11x                 11x   8x       11x 11x 11x 11x   11x 11x 11x 1x   11x     11x           4x       4x     4x 4x           4x                           1x      
import { createWriteStream } from 'node:fs'
import { mkdir, stat, rmdir, unlink } from 'node:fs/promises'
import { join as pathJoin } from 'node:path'
 
import { fetchChromeZipFile } from '../api'
import { DEFAULT_FULL_CONFIG, DEFAULT_SINGLE_CONFIG } from '../commons/constants'
import { DOWNLOAD_ZIP, EXTRACT_ZIP } from '../commons/loggerTexts'
import { NoChromiumDownloadError } from '../errors'
import type { DownloadReportEntry, IChromeConfig } from '../interfaces/interfaces'
import { DebugMode, logger } from '../log/logger'
import { progress } from '../log/progress'
import { spinner } from '../log/spinner'
import { loadStore } from '../store/loadStore'
import { existsAndIsFolder } from '../utils/file.utils'
import { isChromeSingleConfig } from '../utils/typeguards'
import { getChromeDownloadUrl, loadVersions, mapVersions } from '../versions'
import { FluentDownload } from './download-fluent'
import { FluentDownloadSingleIncomplete } from './download-fluent-single'
 
/* eslint-disable @typescript-eslint/no-var-requires */
const extract = require('extract-zip')
const Progress = require('node-fetch-progress')
/* eslint-enable @typescript-eslint/no-var-requires */
 
function registerSigIntHandler(path: string): void {
    process.on('SIGINT', () => {
        return stat(path)
            .then(stats => {
                if (stats.isDirectory()) {
                    return rmdir(path, { recursive: true })
                } else if (stats.isFile()) {
                    return unlink(path)
                } else {
                    return
                }
            })
            .finally(() => {
                process.exit(130)
            })
    })
}
 
function enrichAdditionalConfig(additionalConfig: Partial<IChromeConfig> = {}): IChromeConfig {
    Iif (isChromeSingleConfig(additionalConfig)) {
        return {
            ...DEFAULT_SINGLE_CONFIG,
            ...additionalConfig,
        }
    } else {
        return {
            ...DEFAULT_FULL_CONFIG,
            ...additionalConfig,
        }
    }
}
 
async function extractZip(downloadPath: string) {
    try {
        spinner.start(EXTRACT_ZIP)
        await extract(`${downloadPath}.zip`, { dir: pathJoin(__dirname, downloadPath), onEntry: function(file: {fileName: string}) {
            spinner.update(`Extracting: ${file.fileName}`)
        } })
        spinner.success(downloadPath)
        unlink(`${downloadPath}.zip`).catch(err => {
            logger.error(`Error removing zip file after extracting: ${err.toString()}`)
        })
    } catch (err) {
        spinner.error((err as Error).toString())
    }
}
 
/**
 * Downloads a chromium zip file based on the given config
 * @see DEFAULT_FULL_CONFIG
 * @see DEFAULT_SINGLE_CONFIG
 * @param additionalConfig Manually set config, which will override the settings in the default config
 */
async function downloadForConfig(config: IChromeConfig): Promise<DownloadReportEntry[]> {
    Iif(config.debug) {
        logger.setDebugMode(DebugMode.DEBUG)
    }
 
    const versions = await loadVersions()
    const store = await loadStore()
 
    const mappedVersions = mapVersions(versions, config, store)
 
    Iif (!isChromeSingleConfig(config) && config.list) {
        logger.info('versions:')
        mappedVersions.forEach(v => {
            if (v.disabled) {
                logger.warn(v.value)
            } else {
                logger.info(v.value)
            }
        })
        return []
    }
 
    logger.debug(`total number of versions: ${versions.length}, filtered versions: ${mappedVersions.length}`)
 
    const { chromeUrl, filenameOS, report, selectedVersion } = await getChromeDownloadUrl(config, mappedVersions)
 
    if (chromeUrl && selectedVersion && config.download) {
        const filename = `chrome-${filenameOS}-${config.arch}-${selectedVersion.value}`
        const downloadPath = config.downloadFolder
            ? pathJoin(config.downloadFolder, filename)
            : filename
 
        Iif (!!config.downloadFolder && !(await existsAndIsFolder(config.downloadFolder))) {
            await mkdir(config.downloadFolder, { recursive: true })
            logger.info(`${config.downloadFolder} created'`)
        }
 
        const zipFileResponse = await fetchChromeZipFile(chromeUrl)
 
        let isFirstProgress = true
 
        new Progress(zipFileResponse, { throttle: 100 }).on('progress', (p: { progress: number, total: number }) => {
            if (isFirstProgress) {
                progress.start({
                    barLength: 40,
                    steps: Math.round(p.total / 1024 / 1024),
                    unit: 'MB',
                    showNumeric: true,
                    start: DOWNLOAD_ZIP.start,
                    success: DOWNLOAD_ZIP.success(downloadPath),
                    fail: DOWNLOAD_ZIP.fail,
                })
                isFirstProgress = false
            } else {
                progress.fraction(p.progress)
            }
        })
 
        const filenameWithExtension = downloadPath + '.zip'
        const file = createWriteStream(filenameWithExtension)
        registerSigIntHandler(filenameWithExtension)
        zipFileResponse.body.pipe(file)
 
        return new Promise((resolve, reject) => {
            zipFileResponse.body.on('end', async () => {
                if (config.autoUnzip) {
                    await extractZip(downloadPath)
                }
                resolve(report)
            })
 
            zipFileResponse.body.on('error', () => {
                reject()
            })
        })
    }
 
    Iif (!chromeUrl && config.download && config.single) {
        throw new NoChromiumDownloadError()
    }
 
    return report
}
 
const fluent = new FluentDownload()
const fluentSingle = new FluentDownloadSingleIncomplete()
 
/**
 * Downloads a chromium zip file based on the given config
 */
 
export const downloadChromium = Object.assign(
    downloadForConfig,
    { 
        /**
         * Allows to setup the configuration for downloading rusted-chromium via a fluent interface.
         * If a value is not set, it defaults to "false".
         * Complete the configuration and start executing with ".start()"
         */
        with: fluent,
        withSingle: fluentSingle,
        /**
         * Downloads a chromium zip file with default config, which can be partially overridden 
         * @param config IChromeConfig to override the default config. May omit fields and can be ommited entirely
         */
        withDefaults: (config: Partial<IChromeConfig> = {}) => downloadForConfig(enrichAdditionalConfig(config)),
    }
)