-
-
Notifications
You must be signed in to change notification settings - Fork 246
/
Copy pathspectral.ts
201 lines (168 loc) · 6.43 KB
/
spectral.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import { safeStringify } from '@stoplight/json';
import { Resolver } from '@stoplight/json-ref-resolver';
import { DiagnosticSeverity, Dictionary } from '@stoplight/types';
import { YamlParserResult } from '@stoplight/yaml';
import { memoize, merge } from 'lodash';
import { STATIC_ASSETS } from './assets';
import { Document, IDocument, IParsedResult, isParsedResult, ParsedDocument } from './document';
import { DocumentInventory } from './documentInventory';
import { CoreFunctions, functions as coreFunctions } from './functions';
import * as Parsers from './parsers';
import { readRuleset } from './rulesets';
import { compileExportedFunction, setFunctionContext } from './rulesets/evaluators';
import { mergeExceptions } from './rulesets/mergers/exceptions';
import { IRulesetReadOptions } from './rulesets/reader';
import { DEFAULT_SEVERITY_LEVEL, getDiagnosticSeverity } from './rulesets/severity';
import { runRules } from './runner';
import {
FormatLookup,
FunctionCollection,
IConstructorOpts,
IFunctionContext,
IResolver,
IRuleResult,
IRunOpts,
ISpectralFullResult,
PartialRuleCollection,
RegisteredFormats,
RuleCollection,
RunRuleCollection,
} from './types';
import { IRuleset, RulesetExceptionCollection } from './types/ruleset';
import { ComputeFingerprintFunc, defaultComputeResultFingerprint, empty, prepareResults } from './utils';
import { generateDocumentWideResult } from './utils/generateDocumentWideResult';
memoize.Cache = WeakMap;
export * from './types';
export class Spectral {
private readonly _resolver: IResolver;
public functions: FunctionCollection & CoreFunctions = { ...coreFunctions };
public rules: RunRuleCollection = {};
public exceptions: RulesetExceptionCollection = {};
public formats: RegisteredFormats;
private readonly _computeFingerprint: ComputeFingerprintFunc;
constructor(opts?: IConstructorOpts) {
this._computeFingerprint = memoize(opts?.computeFingerprint || defaultComputeResultFingerprint);
this._resolver = opts?.resolver || new Resolver();
this.formats = {};
}
public static registerStaticAssets(assets: Dictionary<string, string>) {
empty(STATIC_ASSETS);
Object.assign(STATIC_ASSETS, assets);
}
public async runWithResolved(
target: IParsedResult | IDocument | object | string,
opts: IRunOpts = {},
): Promise<ISpectralFullResult> {
const document: IDocument =
target instanceof Document
? target
: isParsedResult(target)
? new ParsedDocument(target)
: new Document<unknown, YamlParserResult<unknown>>(
typeof target === 'string' ? target : safeStringify(target, undefined, 2),
Parsers.Yaml,
opts.resolve?.documentUri,
);
if (document.source === null && opts.resolve?.documentUri !== void 0) {
(document as Omit<Document, 'source'> & { source: string }).source = opts.resolve?.documentUri;
}
const inventory = new DocumentInventory(document, this._resolver);
await inventory.resolve();
const validationResults: IRuleResult[] = [...inventory.diagnostics, ...document.diagnostics, ...inventory.errors];
if (document.formats === void 0) {
const registeredFormats = Object.keys(this.formats);
const foundFormats = registeredFormats.filter(format => this.formats[format](inventory.resolved));
if (foundFormats.length === 0 && opts.ignoreUnknownFormat !== true) {
document.formats = null;
if (registeredFormats.length > 0) {
validationResults.push(this._generateUnrecognizedFormatError(document));
}
} else {
document.formats = foundFormats;
}
}
return {
resolved: inventory.resolved,
results: prepareResults(
[...validationResults, ...runRules(inventory, this.rules, this.functions, this.exceptions)],
this._computeFingerprint,
),
};
}
public async run(target: IParsedResult | Document | object | string, opts: IRunOpts = {}): Promise<IRuleResult[]> {
return (await this.runWithResolved(target, opts)).results;
}
public setFunctions(functions: FunctionCollection) {
empty(this.functions);
Object.assign(this.functions, { ...coreFunctions, ...functions });
}
public setRules(rules: RuleCollection) {
empty(this.rules);
for (const name in rules) {
if (!rules.hasOwnProperty(name)) continue;
const rule = rules[name];
this.rules[name] = {
name,
...rule,
severity: rule.severity === void 0 ? DEFAULT_SEVERITY_LEVEL : getDiagnosticSeverity(rule.severity),
};
}
}
public mergeRules(rules: PartialRuleCollection) {
for (const name in rules) {
if (!rules.hasOwnProperty(name)) continue;
const rule = rules[name];
if (rule) {
this.rules[name] = merge(this.rules[name], rule);
}
}
}
private setExceptions(exceptions: RulesetExceptionCollection) {
const target: RulesetExceptionCollection = {};
mergeExceptions(target, exceptions);
empty(this.exceptions);
Object.assign(this.exceptions, target);
}
public async loadRuleset(uris: string[] | string, options?: IRulesetReadOptions) {
this.setRuleset(await readRuleset(Array.isArray(uris) ? uris : [uris], options));
}
public setRuleset(ruleset: IRuleset) {
this.setRules(ruleset.rules);
this.setFunctions(
Object.entries(ruleset.functions).reduce<FunctionCollection>(
(fns, [key, { code, ref, name, source, schema }]) => {
if (code === void 0) {
if (ref !== void 0) {
({ code } = ruleset.functions[ref]);
}
}
if (code === void 0) {
// shall we log or sth?
return fns;
}
const context: IFunctionContext = {
functions: this.functions,
cache: new Map(),
};
fns[key] = setFunctionContext(context, compileExportedFunction(code, name, source, schema));
return fns;
},
{
...coreFunctions,
},
),
);
this.setExceptions(ruleset.exceptions);
}
public registerFormat(format: string, fn: FormatLookup) {
this.formats[format] = fn;
}
private _generateUnrecognizedFormatError(document: IDocument): IRuleResult {
return generateDocumentWideResult(
document,
`The provided document does not match any of the registered formats [${Object.keys(this.formats).join(', ')}]`,
DiagnosticSeverity.Warning,
'unrecognized-format',
);
}
}