-
-
Notifications
You must be signed in to change notification settings - Fork 98
/
validate.ts
70 lines (61 loc) · 2.53 KB
/
validate.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
import { Document } from '@stoplight/spectral-core';
import { Yaml } from '@stoplight/spectral-parsers';
import { createSpectral } from './spectral';
import { normalizeInput, mergePatch, hasErrorDiagnostic, hasWarningDiagnostic, hasInfoDiagnostic, hasHintDiagnostic, createUncaghtDiagnostic } from './utils';
import type { Spectral, IRunOpts } from '@stoplight/spectral-core';
import type { Parser } from './parser';
import type { ResolverOptions } from './resolver';
import type { AsyncAPIDocumentInterface } from './models';
import type { Input, Diagnostic } from './types';
export interface ValidateOptions extends IRunOpts {
source?: string;
allowedSeverity?: {
error?: boolean;
warning?: boolean;
info?: boolean;
hint?: boolean;
};
__unstable?: {
resolver?: Omit<ResolverOptions, 'cache'>;
};
}
export interface ValidateOutput {
validated: unknown;
diagnostics: Diagnostic[];
extras: {
document: Document;
}
}
const defaultOptions: ValidateOptions = {
allowedSeverity: {
error: false,
warning: true,
info: true,
hint: true,
},
__unstable: {},
};
export async function validate(parser: Parser, parserSpectral: Spectral, asyncapi: Input, options: ValidateOptions = {}): Promise<ValidateOutput> {
let document: Document | undefined;
try {
const { allowedSeverity } = mergePatch<ValidateOptions>(defaultOptions, options);
const stringifiedDocument = normalizeInput(asyncapi as Exclude<Input, AsyncAPIDocumentInterface>);
document = new Document(stringifiedDocument, Yaml, options.source) as Document;
// add input data (asyncapi argument) to the document to reuse it in rules
(document as any).__parserInput = asyncapi;
const spectral = options.__unstable?.resolver ? createSpectral(parser, options) : parserSpectral;
// eslint-disable-next-line prefer-const
let { resolved: validated, results } = await spectral.runWithResolved(document, { });
if (
(!allowedSeverity?.error && hasErrorDiagnostic(results)) ||
(!allowedSeverity?.warning && hasWarningDiagnostic(results)) ||
(!allowedSeverity?.info && hasInfoDiagnostic(results)) ||
(!allowedSeverity?.hint && hasHintDiagnostic(results))
) {
validated = undefined;
}
return { validated, diagnostics: results, extras: { document: document as Document } };
} catch (err: unknown) {
return { validated: undefined, diagnostics: createUncaghtDiagnostic(err, 'Error thrown during AsyncAPI document validation', document), extras: { document: document as Document } };
}
}