@avenga/linkinator
Version:
Find broken links, missing images, etc in your HTML. Scurry around your site and find all those broken links.
80 lines (79 loc) • 2.85 kB
JavaScript
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
if (typeof path === "string" && /^\.\.?\//.test(path)) {
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
});
}
return path;
};
import { promises as fs } from 'node:fs';
import path from 'node:path';
import process from 'node:process';
const validConfigExtensions = ['.js', '.mjs', '.cjs', '.json'];
export async function getConfig(flags) {
// Check to see if a config file path was passed
let config;
if (flags.config) {
config = await parseConfigFile(flags.config);
}
else {
config = (await tryGetDefaultConfig()) || {};
}
// Combine the flags passed on the CLI with the flags in the config file,
// with CLI flags getting precedence
return { ...config, ...flags };
}
/**
* Attempt to load `linkinator.config.json`, assuming the user hasn't
* passed a specific path to a config.
* @returns The contents of the default config if present, or an empty config.
*/
async function tryGetDefaultConfig() {
const defaultConfigPath = path.join(process.cwd(), 'linkinator.config.json');
try {
const config = await parseConfigFile(defaultConfigPath);
return config;
}
catch (e) {
return {};
}
}
async function parseConfigFile(configPath) {
const typeOfConfig = getTypeOfConfig(configPath);
switch (typeOfConfig) {
case '.json': {
return readJsonConfigFile(configPath);
}
case '.js':
case '.mjs':
case '.cjs': {
return importConfigFile(configPath);
}
default: {
throw new Error(`Config file ${configPath} is invalid`);
}
}
}
function getTypeOfConfig(configPath) {
// Returning json in case file doesn't have an extension for backward compatibility
const configExtension = path.extname(configPath) || '.json';
if (validConfigExtensions.includes(configExtension)) {
return configExtension;
}
throw new Error(`Config file should be either of extensions ${validConfigExtensions.join(',')}`);
}
async function importConfigFile(configPath) {
const config = (await import(__rewriteRelativeImportExtension(`file://${path.resolve(process.cwd(), configPath)}`)));
return config.default;
}
async function readJsonConfigFile(configPath) {
const configFileContents = await fs.readFile(configPath, {
encoding: 'utf8',
});
try {
return JSON.parse(configFileContents);
}
catch (error) {
throw new Error(`Error parsing ${configPath}: ${error}`);
}
}