From 7fce9649ec3646c2d13a981d87c47b0666b09c5f Mon Sep 17 00:00:00 2001 From: ssube Date: Sun, 17 Nov 2019 18:43:25 -0600 Subject: [PATCH] lint: extract common rule source logic from file/module helpers --- src/rule/index.ts | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/src/rule/index.ts b/src/rule/index.ts index 51b5b13..cc59dde 100644 --- a/src/rule/index.ts +++ b/src/rule/index.ts @@ -74,7 +74,7 @@ export interface RuleSourceData { export interface RuleSourceModule { definitions?: Dictionary; name: string; - rules: Array; + rules: Array; } export function createRuleSelector(options: Partial): RuleSelector { @@ -96,6 +96,25 @@ export function createRuleSources(options: Partial): RuleSources { }; } +export function isPOJSO(val: any): val is RuleData { + const pojsoProto = Reflect.getPrototypeOf({}); + return Reflect.getPrototypeOf(val) === pojsoProto; +} + +export async function loadRuleSource(data: RuleSourceData | RuleSourceModule, ctx: VisitorContext): Promise> { + if (doesExist(data.definitions)) { + ctx.addSchema(data.name, data.definitions); + } + + return Array.from(data.rules).map((it: Rule | RuleData) => { + if (isPOJSO(it)) { + return new SchemaRule(it); + } else { + return it; + } + }); +} + export async function loadRuleFiles(paths: Array, ctx: VisitorContext): Promise> { const parser = new YamlParser(); const rules = []; @@ -116,11 +135,7 @@ export async function loadRuleFiles(paths: Array, ctx: VisitorContext): continue; } - if (doesExist(data.definitions)) { - ctx.addSchema(data.name, data.definitions); - } - - rules.push(...data.rules.map((it: RuleData) => new SchemaRule(it))); + rules.push(...await loadRuleSource(data, ctx)); } } @@ -155,19 +170,15 @@ export async function loadRuleModules(modules: Array, ctx: VisitorContex for (const name of modules) { try { /* eslint-disable-next-line @typescript-eslint/no-var-requires */ - const module: RuleSourceModule = r(name); - if (!validateRules(ctx, module)) { + const data: RuleSourceModule = r(name); + if (!validateRules(ctx, data)) { ctx.logger.error({ module: name, }, 'error loading rule module'); continue; } - if (doesExist(module.definitions)) { - ctx.addSchema(module.name, module.definitions); - } - - rules.push(...module.rules); + rules.push(...await loadRuleSource(data, ctx)); } catch (err) { ctx.logger.error(err, 'error requiring rule module'); }