hyper/app/config/init.ts

62 lines
2.2 KiB
TypeScript
Raw Normal View History

2019-11-28 05:17:01 -09:00
import vm from 'vm';
import notify from '../notify';
import mapKeys from '../utils/map-keys';
2023-06-26 01:29:50 -08:00
import type {parsedConfig, rawConfig, configOptions} from '../../lib/config';
2022-12-25 20:01:04 -09:00
import _ from 'lodash';
const _extract = (script?: vm.Script): Record<string, any> => {
const module: Record<string, any> = {};
2023-05-29 22:21:20 -08:00
script?.runInNewContext({module}, {displayErrors: true});
if (!module.exports) {
throw new Error('Error reading configuration: `module.exports` not set');
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return module.exports;
};
const _syntaxValidation = (cfg: string) => {
try {
2023-05-29 22:21:20 -08:00
return new vm.Script(cfg, {filename: '.hyper.js'});
} catch (_err) {
const err = _err as {name: string};
2020-11-06 08:47:09 -09:00
notify(`Error loading config: ${err.name}`, `${err}`, {error: err});
}
};
const _extractDefault = (cfg: string) => {
return _extract(_syntaxValidation(cfg));
};
// init config
2022-12-25 20:01:04 -09:00
const _init = (userCfg: rawConfig, defaultCfg: rawConfig): parsedConfig => {
2020-04-27 05:32:08 -08:00
return {
config: (() => {
2022-12-25 20:01:04 -09:00
if (userCfg?.config) {
2023-06-28 22:21:51 -08:00
const conf = userCfg.config;
conf.defaultProfile = conf.defaultProfile || 'default';
conf.profiles = conf.profiles || [];
conf.profiles = conf.profiles.length > 0 ? conf.profiles : [{name: 'default', config: {}}];
conf.profiles = conf.profiles.map((p, i) => ({
...p,
name: p.name || `profile-${i + 1}`,
config: p.config || {}
}));
if (!conf.profiles.map((p) => p.name).includes(conf.defaultProfile)) {
conf.defaultProfile = conf.profiles[0].name;
}
return _.merge({}, defaultCfg.config, conf);
2020-04-27 05:32:08 -08:00
} else {
notify('Error reading configuration: `config` key is missing');
2022-12-25 20:01:04 -09:00
return defaultCfg.config || ({} as configOptions);
2020-04-27 05:32:08 -08:00
}
})(),
// Merging platform specific keymaps with user defined keymaps
2022-12-25 20:01:04 -09:00
keymaps: mapKeys({...defaultCfg.keymaps, ...userCfg?.keymaps}),
// Ignore undefined values in plugin and localPlugins array Issue #1862
2022-12-25 20:01:04 -09:00
plugins: (userCfg?.plugins && userCfg.plugins.filter(Boolean)) || [],
localPlugins: (userCfg?.localPlugins && userCfg.localPlugins.filter(Boolean)) || []
2020-04-27 05:32:08 -08:00
};
};
2019-11-28 05:17:01 -09:00
export {_init, _extractDefault};