@equinor/fusion-framework-cli
Version:
--- title: Fusion Framework CLI ---
67 lines • 2.31 kB
JavaScript
import { readFile } from 'node:fs/promises';
import { extname } from 'node:path';
import { findUpMultiple } from 'find-up';
import { assert } from 'node:console';
import { AssertionError } from 'node:assert';
import { pathToFileURL } from 'node:url';
import { transpile } from './ts-transpile.js';
import { fileExists } from './file-exists.js';
export const supportedExt = ['.ts', '.mjs', '.js', '.json'];
/**
* @param filename name if config file without extension
*/
export const findConfigs = async (filename, options) => {
const { extensions, ...findOptions } = options ?? {};
extensions && assertConfigFileType(extensions);
return findUpMultiple((extensions ?? supportedExt).map((ext) => [filename, ext].join('')), {
...findOptions,
type: 'file',
});
};
export const resolveConfig = async (filename, options) => {
const [file] = await findConfigs(filename, options?.find);
if (file) {
return {
path: file,
config: await loadConfig(file),
};
}
};
function assertConfigFileType(value, message) {
const values = typeof value === 'string' ? [value] : value;
for (const ext of values) {
assert(supportedExt.includes(ext), new AssertionError({
message: message ?? 'unsupported file type',
actual: value,
expected: supportedExt.join('|'),
}));
}
}
const configExtname = (file) => {
const ext = extname(file);
assertConfigFileType(ext);
return ext;
};
export const loadConfig = async (file) => {
assert(await fileExists(file, { assert: true }), `failed to access file ${file}`);
switch (configExtname(file)) {
case '.ts': {
return loadConfig(await transpile(file));
}
case '.mjs':
case '.js': {
const result = (await import(String(pathToFileURL(file)))).default;
return typeof result === 'function' ? result : () => result;
}
case '.json': {
return async () => JSON.parse(await readFile(file, 'utf-8'));
}
default:
throw Error('unsupported file type');
}
};
export function initiateConfig(config, ...args) {
return Promise.resolve(config(...args));
}
export default loadConfig;
//# sourceMappingURL=config.js.map