|
5 | 5 | using Docfx.Common; |
6 | 6 | using Json.Schema; |
7 | 7 |
|
| 8 | +#nullable enable |
| 9 | + |
8 | 10 | namespace Docfx.Build.SchemaDriven; |
9 | 11 |
|
10 | 12 | public class SchemaValidator |
11 | 13 | { |
12 | 14 | private readonly JsonSchema _schema; |
13 | 15 |
|
14 | | - private static readonly EvaluationOptions DefaultOptions = new() |
| 16 | + private static readonly EvaluationOptions DefaultEvaluationOptions = new() |
15 | 17 | { |
16 | | - ValidateAgainstMetaSchema = false, |
17 | 18 | OutputFormat = OutputFormat.List, |
18 | 19 | }; |
19 | 20 |
|
| 21 | + private static readonly JsonDocumentOptions DefaultJsonDocumentOptions = new() |
| 22 | + { |
| 23 | + AllowTrailingCommas = true, |
| 24 | + }; |
| 25 | + |
| 26 | + private static BuildOptions CreateBuildOptions => new() |
| 27 | + { |
| 28 | + Dialect = Dialect.Draft07, |
| 29 | + // Create SchemaRegistry instance to avoid exception (Overwriting registered schemas is not permitted) |
| 30 | + // https://github.com/json-everything/json-everything/issues/957 |
| 31 | + SchemaRegistry = new SchemaRegistry(), |
| 32 | + }; |
| 33 | + |
20 | 34 | static SchemaValidator() |
21 | 35 | { |
22 | | - SchemaRegistry.Global.Register(new("http://dotnet.github.io/docfx/schemas/v1.0/schema.json#"), MetaSchemas.Draft7); |
23 | | - SchemaRegistry.Global.Register(new("https://dotnet.github.io/docfx/schemas/v1.0/schema.json#"), MetaSchemas.Draft7); |
| 36 | + Uri[] uris = |
| 37 | + [ |
| 38 | + new Uri("http://dotnet.github.io/docfx/schemas/v1.0/schema.json#"), |
| 39 | + new Uri("https://dotnet.github.io/docfx/schemas/v1.0/schema.json#"), |
| 40 | + ]; |
| 41 | + |
| 42 | + foreach (var uri in uris) |
| 43 | + { |
| 44 | + SchemaRegistry.Global.Register(uri, MetaSchemas.Draft7); |
| 45 | + DialectRegistry.Global.Register(Dialect.Draft07.With([], id: uri)); |
| 46 | + } |
24 | 47 | } |
25 | 48 |
|
26 | 49 | public SchemaValidator(string json) |
27 | 50 | { |
28 | | - _schema = JsonSchema.FromText(json, new() { AllowTrailingCommas = true }); |
| 51 | + _schema = JsonSchema.FromText(json, CreateBuildOptions, jsonOptions: DefaultJsonDocumentOptions); |
29 | 52 | } |
30 | 53 |
|
31 | 54 | public void Validate(object obj) |
32 | 55 | { |
33 | 56 | var json = JsonSerializer.Serialize(obj); |
34 | | - var result = _schema.Evaluate(JsonDocument.Parse(json), DefaultOptions); |
| 57 | + var result = _schema.Evaluate(JsonDocument.Parse(json, DefaultJsonDocumentOptions).RootElement, DefaultEvaluationOptions); |
35 | 58 |
|
36 | 59 | if (result.IsValid) |
37 | 60 | return; |
38 | 61 |
|
39 | | - foreach (var detail in result.Details) |
| 62 | + foreach (var detail in result.Details ?? []) |
40 | 63 | { |
41 | | - if (detail.HasErrors) |
| 64 | + if (detail.Errors != null) |
42 | 65 | { |
43 | 66 | foreach (var (type, message) in detail.Errors) |
44 | 67 | { |
|
0 commit comments