require() just before use

This commit is contained in:
dragonwocky 2021-11-07 22:57:21 +11:00
parent bf3948f9c5
commit 5cab38d07c
4 changed files with 39 additions and 33 deletions

View File

@ -12,8 +12,6 @@ module.exports = {};
* @module notion-enhancer/api/fmt * @module notion-enhancer/api/fmt
*/ */
const fs = require('notion-enhancer/api/fs.cjs');
/** /**
* transform a heading into a slug (a lowercase alphanumeric string separated by dashes), * transform a heading into a slug (a lowercase alphanumeric string separated by dashes),
* e.g. for use as an anchor id * e.g. for use as an anchor id
@ -132,8 +130,10 @@ module.exports.is = async (value, type, { extension = '' } = {}) => {
case 'url': case 'url':
case 'color': case 'color':
return typeof value === 'string' && test(value, patterns[type]) && extension; return typeof value === 'string' && test(value, patterns[type]) && extension;
case 'file': case 'file': {
return typeof value === 'string' && value && (await fs.isFile(value)) && extension; const { isFile } = require('notion-enhancer/api/fs.cjs');
return typeof value === 'string' && value && (await isFile(value)) && extension;
}
} }
return false; return false;
}; };

View File

@ -6,8 +6,6 @@
'use strict'; 'use strict';
const { fmt, registry } = require('notion-enhancer/api/_.cjs');
const check = async ( const check = async (
mod, mod,
key, key,
@ -21,18 +19,19 @@ const check = async (
optional = false, optional = false,
} = {} } = {}
) => { ) => {
const { is } = require('notion-enhancer/api/fmt.cjs');
let test; let test;
for (const type of Array.isArray(types) ? [types] : types.split('|')) { for (const type of Array.isArray(types) ? [types] : types.split('|')) {
if (type === 'file') { if (type === 'file') {
test = test =
value && !value.startsWith('http') value && !value.startsWith('http')
? await fmt.is(`repo/${mod._dir}/${value}`, type, { extension }) ? await is(`repo/${mod._dir}/${value}`, type, { extension })
: false; : false;
} else test = await fmt.is(value, type, { extension }); } else test = await is(value, type, { extension });
if (test) break; if (test) break;
} }
if (!test) { if (!test) {
if (optional && (await fmt.is(value, 'undefined'))) return true; if (optional && (await is(value, 'undefined'))) return true;
if (error) mod._err(error); if (error) mod._err(error);
return false; return false;
} }
@ -40,12 +39,11 @@ const check = async (
}; };
const validateEnvironments = async (mod) => { const validateEnvironments = async (mod) => {
mod.environments = mod.environments ?? registry.supportedEnvs; const { supportedEnvs } = require('notion-enhancer/api/registry.cjs');
mod.environments = mod.environments ?? supportedEnvs;
const isArray = await check(mod, 'environments', mod.environments, 'array'); const isArray = await check(mod, 'environments', mod.environments, 'array');
if (!isArray) return false; if (!isArray) return false;
return mod.environments.map((tag) => return mod.environments.map((tag) => check(mod, 'environments.env', tag, supportedEnvs));
check(mod, 'environments.env', tag, registry.supportedEnvs)
);
}, },
validateTags = async (mod) => { validateTags = async (mod) => {
const isArray = await check(mod, 'tags', mod.tags, 'array'); const isArray = await check(mod, 'tags', mod.tags, 'array');
@ -122,7 +120,7 @@ const validateEnvironments = async (mod) => {
} }
tests.push([ tests.push([
check(mod, 'js.electron.file.source', file.source, 'file', { check(mod, 'js.electron.file.source', file.source, 'file', {
extension: '.mjs', extension: '.cjs',
}), }),
// referencing the file within the electron app // referencing the file within the electron app
// existence can't be validated, so only format is // existence can't be validated, so only format is
@ -136,17 +134,18 @@ const validateEnvironments = async (mod) => {
return tests; return tests;
}, },
validateOptions = async (mod) => { validateOptions = async (mod) => {
const isArray = await check(mod, 'options', mod.options, 'array'); const { supportedEnvs, optionTypes } = require('notion-enhancer/api/registry.cjs'),
isArray = await check(mod, 'options', mod.options, 'array');
if (!isArray) return false; if (!isArray) return false;
const tests = []; const tests = [];
for (const option of mod.options) { for (const option of mod.options) {
const key = 'options.option', const key = 'options.option',
optTypeValid = await check(mod, `${key}.type`, option.type, registry.optionTypes); optTypeValid = await check(mod, `${key}.type`, option.type, optionTypes);
if (!optTypeValid) { if (!optTypeValid) {
tests.push(false); tests.push(false);
continue; continue;
} }
option.environments = option.environments ?? registry.supportedEnvs; option.environments = option.environments ?? supportedEnvs;
tests.push([ tests.push([
check(mod, `${key}.key`, option.key, 'alphanumeric'), check(mod, `${key}.key`, option.key, 'alphanumeric'),
check(mod, `${key}.label`, option.label, 'string'), check(mod, `${key}.label`, option.label, 'string'),
@ -156,7 +155,7 @@ const validateEnvironments = async (mod) => {
check(mod, `${key}.environments`, option.environments, 'array').then((isArray) => { check(mod, `${key}.environments`, option.environments, 'array').then((isArray) => {
if (!isArray) return false; if (!isArray) return false;
return option.environments.map((environment) => return option.environments.map((environment) =>
check(mod, `${key}.environments.env`, environment, registry.supportedEnvs) check(mod, `${key}.environments.env`, environment, supportedEnvs)
); );
}), }),
]); ]);

View File

@ -122,7 +122,7 @@ const validateEnvironments = async (mod) => {
} }
tests.push([ tests.push([
check(mod, 'js.electron.file.source', file.source, 'file', { check(mod, 'js.electron.file.source', file.source, 'file', {
extension: '.mjs', extension: '.cjs',
}), }),
// referencing the file within the electron app // referencing the file within the electron app
// existence can't be validated, so only format is // existence can't be validated, so only format is

View File

@ -11,9 +11,6 @@
* @module notion-enhancer/api/registry * @module notion-enhancer/api/registry
*/ */
const { env, fs, storage } = require('notion-enhancer/api/_.cjs'),
{ validate } = require('notion-enhancer/api/registry-validation.cjs');
/** /**
* mod ids whitelisted as part of the enhancer's core, permanently enabled * mod ids whitelisted as part of the enhancer's core, permanently enabled
* @constant * @constant
@ -43,13 +40,19 @@ module.exports.optionTypes = ['toggle', 'select', 'text', 'number', 'color', 'fi
* the name of the active configuration profile * the name of the active configuration profile
* @returns {string} * @returns {string}
*/ */
module.exports.profileName = async () => storage.get(['currentprofile'], 'default'); module.exports.profileName = async () => {
const storage = require('notion-enhancer/api/storage.cjs');
return storage.get(['currentprofile'], 'default');
};
/** /**
* the root database for the current profile * the root database for the current profile
* @returns {object} the get/set functions for the profile's storage * @returns {object} the get/set functions for the profile's storage
*/ */
module.exports.profileDB = async () => storage.db(['profiles', await profileName()]); module.exports.profileDB = async () => {
const storage = require('notion-enhancer/api/storage.cjs');
return storage.db(['profiles', await module.exports.profileName()]);
};
let _list, let _list,
_errors = []; _errors = [];
@ -60,12 +63,14 @@ let _list,
*/ */
module.exports.list = async (filter = (mod) => true) => { module.exports.list = async (filter = (mod) => true) => {
if (!_list) { if (!_list) {
const { validate } = require('notion-enhancer/api/registry-validation.cjs'),
{ getJSON } = require('notion-enhancer/api/fs.cjs');
_list = new Promise(async (res, rej) => { _list = new Promise(async (res, rej) => {
const passed = []; const passed = [];
for (const dir of await fs.getJSON('repo/registry.json')) { for (const dir of await getJSON('repo/registry.json')) {
try { try {
const mod = { const mod = {
...(await fs.getJSON(`repo/${dir}/mod.json`)), ...(await getJSON(`repo/${dir}/mod.json`)),
_dir: dir, _dir: dir,
_err: (message) => _errors.push({ source: dir, message }), _err: (message) => _errors.push({ source: dir, message }),
}; };
@ -87,7 +92,7 @@ module.exports.list = async (filter = (mod) => true) => {
* @returns {array<object>} error objects with an error message and a source directory * @returns {array<object>} error objects with an error message and a source directory
*/ */
module.exports.errors = async () => { module.exports.errors = async () => {
await list(); await module.exports.list();
return _errors; return _errors;
}; };
@ -97,7 +102,7 @@ module.exports.errors = async () => {
* @returns {object} the mod's mod.json * @returns {object} the mod's mod.json
*/ */
module.exports.get = async (id) => { module.exports.get = async (id) => {
return (await list((mod) => mod.id === id))[0]; return (await module.exports.list((mod) => mod.id === id))[0];
}; };
/** /**
@ -107,10 +112,11 @@ module.exports.get = async (id) => {
* @returns {boolean} whether or not the mod is enabled * @returns {boolean} whether or not the mod is enabled
*/ */
module.exports.enabled = async (id) => { module.exports.enabled = async (id) => {
const mod = await get(id); const env = require('notion-enhancer/api/env.cjs'),
mod = await module.exports.get(id);
if (!mod.environments.includes(env.name)) return false; if (!mod.environments.includes(env.name)) return false;
if (core.includes(id)) return true; if (module.exports.core.includes(id)) return true;
return (await profileDB()).get(['_mods', id], false); return (await module.exports.profileDB()).get(['_mods', id], false);
}; };
/** /**
@ -143,14 +149,15 @@ module.exports.optionDefault = async (id, key) => {
* @returns {object} an object with the wrapped get/set functions * @returns {object} an object with the wrapped get/set functions
*/ */
module.exports.db = async (id) => { module.exports.db = async (id) => {
const db = await profileDB(); const storage = require('notion-enhancer/api/storage.cjs'),
db = await module.exports.profileDB();
return storage.db( return storage.db(
[id], [id],
async (path, fallback = undefined) => { async (path, fallback = undefined) => {
if (typeof path === 'string') path = [path]; if (typeof path === 'string') path = [path];
if (path.length === 2) { if (path.length === 2) {
// profiles -> profile -> mod -> option // profiles -> profile -> mod -> option
fallback = (await optionDefault(id, path[1])) ?? fallback; fallback = (await module.exports.optionDefault(id, path[1])) ?? fallback;
} }
return db.get(path, fallback); return db.get(path, fallback);
}, },