All files / packages/sds-metadata/scripts generate-exports.js

0% Statements 0/21
0% Branches 0/2
0% Functions 0/8
0% Lines 0/21

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                                                                                                                                                                               
import path from 'path';
import { fileURLToPath } from 'url';
import { globbySync } from 'globby';
import fs from 'fs';
import camelCase from 'lodash.camelcase';
 
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const rootDir = path.join(__dirname, '../');
 
 
// Get all JSON files from the generated directory
function getMetadaFilesMap() {
    const jsonFiles = globbySync(path.join(rootDir, 'dist/*.json'));
 
    // Create a map of camelCase keys to file paths
    return jsonFiles.reduce((acc, file) => {
        const key = camelCase(path.basename(file, '.json'));
        const relativePath = './' + path.relative(rootDir, file);
        acc[key] = relativePath;
        return acc;
    }, {});
}
 
 
// Create a lightweight ESM index file with static JSON imports
async function generateMJSFile(fileMap) {
    const esmContent = `
// This file is auto-generated. Do not edit directly.
 
${Object.entries(fileMap)
            .map(([key, filePath]) => `import ${key}Data from '${filePath}' with { type: 'json' };`)
            .join('\n')}
 
const metadata = {
    ${Object.entries(fileMap)
            .map(([key, filePath]) => `
    get ${key}() {
        return ${key}Data;
    },
`).join('')}
};
 
export default metadata;
`;
 
    // Write ESM index file directly
    await fs.promises.writeFile(
        path.join(rootDir, `./metadata.mjs`),
        esmContent,
        'utf8'
    );
}
 
async function generateCJSFile(fileMap) {
    // Create a lightweight CJS index file
    const cjsContent = `
// This file is auto-generated. Do not edit directly.
 
const metadata = {
    ${Object.entries(fileMap)
            .map(([key, filePath]) => `
    get ${key}() {
        return require('${filePath}');
    },
`).join('')}
};
 
module.exports = metadata;
`;
 
    // Write CJS index file directly
    await fs.promises.writeFile(
        path.join(rootDir, `./metadata.cjs`),
        cjsContent,
        'utf8'
    );
}
 
export async function generateExports(){
    const fileMap = getMetadaFilesMap();
    await generateMJSFile(fileMap);
    await generateCJSFile(fileMap);
}
 
if (import.meta.url === `file://${process.argv[1]}`) {
    generateExports();
}