import downloader from '@bracketed/downloader';
export default async function download(repo, dest) {
    const normalizedRepository = normalize(repo);
    const url = normalizedRepository.url || getUrl(normalizedRepository);
    if (!url)
        return false;
    return await downloader(url, dest, {
        extract: true,
        strip: 1,
    })
        .then(() => true)
        .catch(() => false);
}
function normalize(repo) {
    const regex = /^(?:(direct):([^#]+)(?:#(.+))?)$/;
    const match = regex.exec(repo);
    if (!match) {
        const regex = /^(?:(github|gitlab|bitbucket):)?(?:(.+):)?([^/]+)\/([^#]+)(?:#(.+))?$/;
        const match = regex.exec(repo);
        const type = match[1] || 'github';
        let origin = match[2] || null;
        const owner = match[3];
        const name = match[4];
        const checkout = match[5] || 'main';
        if (!origin) {
            switch (type) {
                case 'github':
                    origin = 'github.com';
                    break;
                case 'gitlab':
                    origin = 'gitlab.com';
                    break;
                case 'bitbucket':
                    origin = 'bitbucket.org';
                    break;
            }
        }
        return {
            type,
            origin,
            owner,
            name,
            checkout,
        };
    }
    return {
        type: 'direct',
        url: match[2],
        checkout: match[3] || 'master',
    };
}
function getUrl(repo) {
    let url;
    switch (repo.type) {
        case 'github':
            url = `https://codeload.github.com/${repo.owner}/${repo.name}/zip/refs/heads/${repo.checkout}`;
            break;
        case 'gitlab':
            url = `https://gitlab.com/${repo.owner}/${repo.name}/-/archive/${repo.checkout}/${repo.name}-${repo.checkout}.zip`;
            break;
        case 'bitbucket':
            url = `https://bitbucket.org/${repo.owner}/${repo.name}/get/${repo.checkout}.zip`;
            break;
    }
    return url;
}
//# sourceMappingURL=index.js.map