All files fetch-pkg.ts

2.52% Statements 5/198
100% Branches 0/0
0% Functions 0/1
2.52% Lines 5/198

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 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 2201x 1x 1x     1x   1x                                                                                                                                                                                                                                                                                                                                                                                                                                        
import fs from 'node:fs';
import path from 'node:path';
import genSysCacheDir from 'cachedir';
 
import type { FetchPkgOptions, FetchResult } from './types';
import { downloadFile, getHashText } from './utils';
 
const sysCacheDir = path.join(genSysCacheDir('npm-esmx'), 'packages');
 
/**
 * 获取文件,并缓存到本地。如果有缓存则使用缓存
 */
export async function fetchPkg<Level extends number>({
    cacheDir = sysCacheDir,
    outputDir,
    noCache,
    returnLevel = 2 as Level,
    logger = console.log,
    axiosReqCfg = {},
    name,
    url = '',
    onFinally = () => {}
}: FetchPkgOptions & { returnLevel?: Level }): Promise<FetchResult<Level>> {
    const returnWrapper = (ans: FetchResult<2>) => {
        onFinally(ans);
        return (returnLevel === 0 ? ans.hasError : ans) as FetchResult<Level>;
    };
 
    const paramsChecker = () => {
        url = axiosReqCfg.url || url;
        if (axiosReqCfg.baseURL) {
            url = new URL(url, axiosReqCfg.baseURL).href;
        }
        if (!name) {
            return returnWrapper({
                hasError: true,
                name,
                url,
                error: new Error('name is empty')
            });
        }
        if (!url) {
            return returnWrapper({
                hasError: true,
                name,
                url,
                error: new Error('url is empty')
            });
        }
        const urlInfo = new URL(url);
        urlInfo.searchParams.append(Date.now() + '_', Date.now() + '');
        axiosReqCfg.headers = axiosReqCfg.headers || {};
        axiosReqCfg.headers['Cache-Control'] =
            axiosReqCfg.headers['Cache-Control'] || 'no-cache';
        axiosReqCfg.headers.Pragma = axiosReqCfg.headers.Pragma || 'no-cache';
        axiosReqCfg.headers.Expires = axiosReqCfg.headers.Expires || '0';
        url = urlInfo.href;
        if (noCache && !outputDir) {
            return returnWrapper({
                hasError: true,
                name,
                url,
                error: new Error('outputFilePath is empty')
            });
        }
        if (!noCache && cacheDir === '') {
            return returnWrapper({
                hasError: true,
                name,
                url,
                error: new Error('cacheDir is empty')
            });
        }
    };
 
    const initDirs = async () => {
        if (outputDir && !fs.existsSync(outputDir)) {
            await fs.promises.mkdir(outputDir, { recursive: true });
        }
        if (!noCache) {
            if (!fs.existsSync(cacheDir)) {
                await fs.promises.mkdir(cacheDir, { recursive: true });
            }
        }
    };
 
    const t = paramsChecker();
    logger?.(`[fetch] [${name}] From ${url}`);
    if (t) {
        return t;
    }
    await initDirs();
 
    const urlInfo = new URL(url);
    const fileExt = path.parse(urlInfo.pathname).ext;
    urlInfo.pathname = urlInfo.pathname.replace(
        new RegExp(fileExt + '$'),
        '.txt'
    );
    const hashUrl = urlInfo.href;
 
    /*
        获取 hash。使用缓存时,一定要有 hash 值。
        现在的逻辑是不使用缓存时,不校验 hash 值。
        TODO: 理论上应该将《是否使用缓存》和《是否校验》分开,以后再说吧。
    */
    let hash = '';
    let hashAlg = '';
    if (!noCache) {
        const hashInfo = await getHashText(hashUrl, {
            ...axiosReqCfg,
            onDownloadProgress: undefined
        });
        if (hashInfo.error) {
            logger?.(`[fetch] [${name}] Error: ${hashInfo.error}`);
            return returnWrapper({
                hasError: true,
                name,
                url,
                error: hashInfo.error
            });
        }
        ({ hash, hashAlg } = hashInfo);
    }
    // 不使用缓存时 || 无hash文件时,直接下载到 outputPath,且不进行校验
    const download2output = noCache || !hash;
    if (download2output && !outputDir) {
        logger?.(`[fetch] [${name}] Error: outputDir is empty`);
        return returnWrapper({
            hasError: true,
            name,
            url,
            error: new Error('outputDir is empty')
        });
    }
    const outputFilePath = outputDir
        ? path.join(outputDir, name + fileExt)
        : '';
 
    const cacheFilePath = path.join(cacheDir, hash + fileExt);
    const tmpFilePath =
        (download2output
            ? outputFilePath
            : path.join(cacheDir, hash + fileExt)) + '.tmp';
 
    if (hash && fs.existsSync(cacheFilePath)) {
        logger?.(`[fetch] [${name}] Hit cache`);
        if (outputFilePath) {
            await fs.promises.cp(cacheFilePath, outputFilePath, {
                force: true
            });
        }
        return returnWrapper({
            hasError: false,
            name,
            url,
            filePath: outputFilePath || cacheFilePath,
            cacheFilePath,
            hash,
            hitCache: true
        });
    }
 
    const error = await downloadFile(
        url,
        tmpFilePath,
        hash,
        hashAlg,
        axiosReqCfg
    );
    if (error) {
        const err = error.error as Error;
        switch (error.errType) {
            case 'axios':
                logger?.(`[fetch] [${name}] Error: ${err.message}`);
                break;
            case 'file':
                logger?.(`[fetch] [${name}] Write file error: ${err.message}`);
                break;
            case 'hash':
                logger?.(`[fetch] [${name}] Hash not match`);
                break;
        }
        return returnWrapper({ hasError: true, name, url, error: err });
    }
    if (download2output) {
        await fs.promises.rename(tmpFilePath, outputFilePath);
        logger?.(
            `[fetch] [${name}] Downloaded without cache: ${outputFilePath}`
        );
        return returnWrapper({
            hasError: false,
            name,
            url,
            filePath: outputFilePath,
            cacheFilePath: outputFilePath,
            hash,
            hitCache: true
        });
    } else {
        await fs.promises.rename(tmpFilePath, cacheFilePath);
        if (outputFilePath) {
            await fs.promises.cp(cacheFilePath, outputFilePath, {
                force: true
            });
        }
        const filePath = outputFilePath || cacheFilePath;
        logger?.(`[fetch] [${name}] Downloaded: ${filePath}`);
        return returnWrapper({
            hasError: false,
            name,
            url,
            filePath,
            cacheFilePath,
            hash,
            hitCache: false
        });
    }
}