All files indexHelpers.js

93.51% Statements 72/77
80% Branches 44/55
94.12% Functions 16/17
93.42% Lines 71/76

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 18714x 14x                     14x       1x 1x 1x 1x   1x       1x     1x     1x 407x 378x         14x 13131x 1x     13130x 13006x               124x     14x 104070x 208219x 71047x       33023x     14x 11343x 11343x 11343x   11343x     14x 1992x       16112x             1764x       14x 138x       138x 5x     133x     14x 5x   5x 1499x   1499x 499x       1499x 998x   998x 2994x       501x     1499x     5x     14x 5x 5x   5x 1x     5x 2x   2x 6x     3x     5x     14x 1x   1x       14x 13131x           13096x     35x   35x         14x                        
const fs = require('node:fs');
const path = require('node:path');
 
/**
 * ! This function has a wanted sideeffect, as it modifies the json object that is passed by reference.
 *
 *  The depth attribute set in the options parameter here - which is defined by setting the `--direct` flag - is of
 *  no use with npm < 3, as the older npm versions flattened all dependencies into one single directory. So in
 *  order to making `--direct` work with older versions of npm, we need to filter out all non-dependencies from
 *  the json result.
 */
// TODO: Add tests for this function
const deleteNonDirectDependenciesFromAllDependencies = function deleteNonDirectDependenciesFromAllDependencies(
    { _dependencies: directDependencies = {}, dependencies: allDependencies = {}, devDependencies = {} } = {},
    options,
) {
    const allDependenciesArray = Object.keys(allDependencies);
    const directDependenciesArray = Object.keys(directDependencies);
    const devDependenciesArray = Object.keys(devDependencies);
    let wantedDependenciesArray = [];
 
    Iif (options.production && !options.development) {
        wantedDependenciesArray = directDependenciesArray.filter(
            (directDependency) => !devDependenciesArray.includes(directDependency),
        );
    } else Iif (!options.production && options.development) {
        wantedDependenciesArray = devDependenciesArray;
    } else {
        wantedDependenciesArray = directDependenciesArray;
    }
 
    allDependenciesArray.forEach((currentDependency) => {
        if (!wantedDependenciesArray.includes(currentDependency)) {
            delete allDependencies[currentDependency];
        }
    });
};
 
const getRepositoryUrl = function getRepositoryUrl({ clarificationRepository, jsonRepository }) {
    if (clarificationRepository) {
        return clarificationRepository;
    }
 
    if (typeof jsonRepository?.url === 'string') {
        return jsonRepository.url
            .replace('git+ssh://git@', 'git://')
            .replace('git+https://github.com', 'https://github.com')
            .replace('git://github.com', 'https://github.com')
            .replace('git@github.com:', 'https://github.com/')
            .replace(/\.git$/, '');
    }
 
    return undefined;
};
 
const getFirstNotUndefinedOrUndefined = function getFirstNotUndefinedOrUndefined() {
    for (let i = 0; i < arguments.length; i++) {
        if (typeof arguments[i] !== 'undefined') {
            return arguments[i];
        }
    }
 
    return undefined;
};
 
const getAuthorDetails = function getAuthorDetails({ clarification, author }) {
    let publisher = getFirstNotUndefinedOrUndefined(clarification?.publisher, author?.name);
    let email = getFirstNotUndefinedOrUndefined(clarification?.email, author?.email);
    let url = getFirstNotUndefinedOrUndefined(clarification?.url, author?.url);
 
    return { publisher, email, url };
};
 
const getLinesWithCopyright = function getLinesWithCopyright(fileContents = '') {
    return fileContents
        .replace(/\r\n/g, '\n')
        .split('\n\n')
        .filter(function selectCopyRightStatements(value) {
            return (
                value.startsWith('opyright', 1) && // include copyright statements
                !value.startsWith('opyright notice', 1) && // exclude lines from from license text
                !value.startsWith('opyright and related rights', 1)
            );
        })
        .filter(function removeDuplicates(value, index, list) {
            return index === 0 || value !== list[0];
        });
};
 
const getOptionArray = (option) => {
    Iif (Array.isArray(option)) {
        return option;
    }
 
    if (typeof option === 'string') {
        return option.split(';');
    }
 
    return false;
};
 
const getCsvData = (sorted, customFormat, csvComponentPrefix) => {
    const csvDataArr = [];
 
    Object.entries(sorted).forEach(([key, module]) => {
        const dataElements = [];
 
        if (csvComponentPrefix) {
            dataElements.push(`"${csvComponentPrefix}"`);
        }
 
        // Grab the custom keys from the custom format
        if (typeof customFormat === 'object' && Object.keys(customFormat).length > 0) {
            dataElements.push(`"${key}"`);
 
            Object.keys(customFormat).forEach((item) => {
                dataElements.push(`"${module[item]}"`);
            });
        } else {
            // Be sure to push empty strings for empty values, as this is what CSV expects:
            dataElements.push([`"${key}"`, `"${module.licenses || ''}"`, `"${module.repository || ''}"`]);
        }
 
        csvDataArr.push(dataElements.join(','));
    });
 
    return csvDataArr;
};
 
const getCsvHeaders = (customFormat, csvComponentPrefix) => {
    const prefixName = '"component"';
    const entriesArr = [];
 
    if (csvComponentPrefix) {
        entriesArr.push(prefixName);
    }
 
    if (typeof customFormat === 'object' && Object.keys(customFormat).length > 0) {
        entriesArr.push('"module name"');
 
        Object.keys(customFormat).forEach((item) => {
            entriesArr.push(`"${item}"`);
        });
    } else {
        entriesArr.push('"module name"', '"license"', '"repository"');
    }
 
    return entriesArr.join(',');
};
 
const getModuleNameForLicenseTextHeader = (moduleName = '') => {
    const lastIndexOfAtCharacter = moduleName.lastIndexOf('@');
 
    return `${moduleName.substring(0, lastIndexOfAtCharacter)} ${moduleName.substring(lastIndexOfAtCharacter + 1)}\n`;
};
 
// Eventually store the contents of the module's README.md in currentExtendedPackageJson.readme:
const storeReadmeInJsonIfExists = (modulePath, currentExtendedPackageJson) => {
    if (
        typeof modulePath !== 'string' ||
        typeof currentExtendedPackageJson !== 'object' ||
        modulePath === '' ||
        currentExtendedPackageJson?.readme?.toLowerCase()?.indexOf('no readme data found') === -1
    ) {
        return;
    }
 
    const readmeFile = path.join(modulePath, 'README.md');
 
    Iif (fs.existsSync(readmeFile)) {
        currentExtendedPackageJson.readme = fs.readFileSync(readmeFile, 'utf8').toString();
    }
};
 
module.exports = {
    deleteNonDirectDependenciesFromAllDependencies,
    getAuthorDetails,
    getCsvData,
    getCsvHeaders,
    getFirstNotUndefinedOrUndefined,
    getLinesWithCopyright,
    getModuleNameForLicenseTextHeader,
    getOptionArray,
    getRepositoryUrl,
    storeReadmeInJsonIfExists,
};