json-structure 0.1.6__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- json_structure/__init__.py +302 -0
- json_structure/_version.py +34 -0
- json_structure/error_codes.py +615 -0
- json_structure/instance_validator.py +1191 -0
- json_structure/json_source_locator.py +373 -0
- json_structure/schema_exporter.py +561 -0
- json_structure/schema_validator.py +1055 -0
- json_structure-0.1.6.dist-info/METADATA +260 -0
- json_structure-0.1.6.dist-info/RECORD +11 -0
- json_structure-0.1.6.dist-info/WHEEL +4 -0
- json_structure-0.1.6.dist-info/entry_points.txt +3 -0
|
@@ -0,0 +1,1055 @@
|
|
|
1
|
+
# encoding: utf-8
|
|
2
|
+
"""
|
|
3
|
+
json_structure_schema_validator.py
|
|
4
|
+
|
|
5
|
+
A validation tool for the experimental JSON Structure Core specification
|
|
6
|
+
published by C. Vasters (Microsoft) in February 2025.
|
|
7
|
+
This version optionally supports the JSON Structure JSONStructureImport extension via the
|
|
8
|
+
--allowimport flag and allows passing a mapping of URI to filenames via the
|
|
9
|
+
--importmap option.
|
|
10
|
+
It also supports extended validation features via the --extended flag.
|
|
11
|
+
|
|
12
|
+
Usage:
|
|
13
|
+
python json_structure_schema_validator.py [--metaschema] [--allowimport] [--extended] [--importmap URI=filename ...] <path_to_json_file>
|
|
14
|
+
|
|
15
|
+
The --metaschema parameter allows '$' in property names.
|
|
16
|
+
The --allowimport parameter enables processing of the $import and $importdefs keywords.
|
|
17
|
+
The --extended parameter enables validation of conditional composition and validation extensions.
|
|
18
|
+
If a URI mapping is provided via --importmap, the external schema file is loaded from the given path.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import sys
|
|
22
|
+
import json
|
|
23
|
+
import re
|
|
24
|
+
from urllib.parse import urlparse
|
|
25
|
+
from typing import List, Optional, Union
|
|
26
|
+
from .error_codes import ValidationError, ValidationSeverity, JsonLocation
|
|
27
|
+
from .json_source_locator import JsonSourceLocator
|
|
28
|
+
from . import error_codes as ErrorCodes
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class JSONStructureSchemaCoreValidator:
|
|
32
|
+
"""
|
|
33
|
+
Validates JSON Structure Core documents for conformance with the specification.
|
|
34
|
+
Provides error messages annotated with estimated line and column numbers.
|
|
35
|
+
Optionally supports the JSON Structure JSONStructureImport extension if allow_import is True.
|
|
36
|
+
Optionally supports extended validation features if extended is True.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
ABSOLUTE_URI_REGEX = re.compile(r'^[a-zA-Z][a-zA-Z0-9+\-.]*://')
|
|
40
|
+
MAP_KEY_REGEX = re.compile(r'^[A-Za-z0-9._-]+$')
|
|
41
|
+
RESERVED_KEYWORDS = {
|
|
42
|
+
"definitions", "$extends", "$id", "$ref", "$root", "$schema", "$uses",
|
|
43
|
+
"$offers", "abstract", "additionalProperties", "const", "default",
|
|
44
|
+
"description", "enum", "examples", "format", "items", "maxLength",
|
|
45
|
+
"name", "precision", "properties", "required", "scale", "type",
|
|
46
|
+
"values", "choices", "selector", "tuple"
|
|
47
|
+
}
|
|
48
|
+
PRIMITIVE_TYPES = {
|
|
49
|
+
"string", "number", "integer", "boolean", "null", "int8", "uint8", "int16", "uint16",
|
|
50
|
+
"int32", "uint32", "int64", "uint64", "int128", "uint128", "float8",
|
|
51
|
+
"float", "double", "decimal", "date", "datetime", "time", "duration",
|
|
52
|
+
"uuid", "uri", "binary", "jsonpointer"
|
|
53
|
+
}
|
|
54
|
+
COMPOUND_TYPES = {"object", "array", "set", "map", "tuple", "choice", "any"}
|
|
55
|
+
|
|
56
|
+
# Extended keywords for conditional composition
|
|
57
|
+
COMPOSITION_KEYWORDS = {"allOf", "anyOf", "oneOf", "not", "if", "then", "else"}
|
|
58
|
+
|
|
59
|
+
# Extended keywords for validation
|
|
60
|
+
NUMERIC_VALIDATION_KEYWORDS = {"minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf"}
|
|
61
|
+
STRING_VALIDATION_KEYWORDS = {"minLength", "maxLength", "pattern", "format"}
|
|
62
|
+
ARRAY_VALIDATION_KEYWORDS = {"minItems", "maxItems", "uniqueItems", "contains", "minContains", "maxContains"}
|
|
63
|
+
OBJECT_VALIDATION_KEYWORDS = {"minProperties", "maxProperties", "minEntries", "maxEntries",
|
|
64
|
+
"dependentRequired", "patternProperties", "patternKeys",
|
|
65
|
+
"propertyNames", "keyNames", "has"}
|
|
66
|
+
|
|
67
|
+
# Valid format values
|
|
68
|
+
VALID_FORMATS = {
|
|
69
|
+
"ipv4", "ipv6", "email", "idn-email", "hostname", "idn-hostname",
|
|
70
|
+
"iri", "iri-reference", "uri-template", "relative-json-pointer", "regex"
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
# Extension names
|
|
74
|
+
KNOWN_EXTENSIONS = {
|
|
75
|
+
"JSONStructureImport", "JSONStructureAlternateNames", "JSONStructureUnits",
|
|
76
|
+
"JSONStructureConditionalComposition", "JSONStructureValidation"
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
def __init__(self, allow_dollar=False, allow_import=False, import_map=None, extended=False, external_schemas=None):
|
|
80
|
+
"""
|
|
81
|
+
Initializes a validator instance.
|
|
82
|
+
:param allow_dollar: Boolean flag to allow '$' in property names.
|
|
83
|
+
:param allow_import: Boolean flag to enable processing of $import/$importdefs.
|
|
84
|
+
:param import_map: Dictionary mapping URI to local filenames.
|
|
85
|
+
:param extended: Boolean flag to enable extended validation features.
|
|
86
|
+
:param external_schemas: List of schema dicts to use for resolving imports by $id.
|
|
87
|
+
Each schema should have a '$id' field matching the import URI.
|
|
88
|
+
"""
|
|
89
|
+
self.errors: List[ValidationError] = []
|
|
90
|
+
self.doc = None
|
|
91
|
+
self.source_text = None
|
|
92
|
+
self.source_locator: Optional[JsonSourceLocator] = None
|
|
93
|
+
self.allow_import = allow_import
|
|
94
|
+
self.import_map = import_map if import_map is not None else {}
|
|
95
|
+
self.extended = extended
|
|
96
|
+
self.enabled_extensions = set()
|
|
97
|
+
# Build lookup for external schemas by $id
|
|
98
|
+
self.external_schemas = {}
|
|
99
|
+
if external_schemas:
|
|
100
|
+
for schema in external_schemas:
|
|
101
|
+
if isinstance(schema, dict) and "$id" in schema:
|
|
102
|
+
self.external_schemas[schema["$id"]] = schema
|
|
103
|
+
if allow_dollar:
|
|
104
|
+
self.identifier_regex = re.compile(r'^[A-Za-z_$][A-Za-z0-9_$]*$')
|
|
105
|
+
else:
|
|
106
|
+
self.identifier_regex = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$')
|
|
107
|
+
|
|
108
|
+
def validate(self, doc, source_text=None):
|
|
109
|
+
"""
|
|
110
|
+
Main entry point for validating a JSON Structure Core document.
|
|
111
|
+
:param doc: A dict parsed from JSON.
|
|
112
|
+
:param source_text: The original JSON text for computing line and column.
|
|
113
|
+
:return: List of ValidationError objects, empty if valid.
|
|
114
|
+
"""
|
|
115
|
+
self.errors = []
|
|
116
|
+
self.doc = doc
|
|
117
|
+
self.source_text = source_text
|
|
118
|
+
|
|
119
|
+
# Initialize source locator for location tracking
|
|
120
|
+
if source_text:
|
|
121
|
+
self.source_locator = JsonSourceLocator(source_text)
|
|
122
|
+
else:
|
|
123
|
+
self.source_locator = None
|
|
124
|
+
|
|
125
|
+
if not isinstance(doc, dict):
|
|
126
|
+
self._err("Root of the document must be a JSON object.", "#", ErrorCodes.SCHEMA_INVALID_TYPE)
|
|
127
|
+
return self.errors
|
|
128
|
+
|
|
129
|
+
# Process $import and $importdefs keywords recursively.
|
|
130
|
+
self._process_imports(doc, "#")
|
|
131
|
+
|
|
132
|
+
# Check which extensions are enabled
|
|
133
|
+
if self.extended:
|
|
134
|
+
self._check_enabled_extensions(doc)
|
|
135
|
+
|
|
136
|
+
self._check_required_top_level_keywords(doc, "#")
|
|
137
|
+
if "$schema" in doc:
|
|
138
|
+
self._check_is_absolute_uri(doc["$schema"], "$schema", "#/$schema")
|
|
139
|
+
if "$id" in doc:
|
|
140
|
+
self._check_is_absolute_uri(doc["$id"], "$id", "#/$id")
|
|
141
|
+
if "$uses" in doc:
|
|
142
|
+
self._check_uses(doc["$uses"], "#/$uses")
|
|
143
|
+
if "type" in doc and "$root" in doc:
|
|
144
|
+
self._err("Document cannot have both 'type' at root and '$root' at the same time.", "#", ErrorCodes.SCHEMA_ROOT_CONFLICT)
|
|
145
|
+
if "type" in doc:
|
|
146
|
+
self._validate_schema(doc, is_root=True, path="#", name_in_namespace=None)
|
|
147
|
+
if "$root" in doc:
|
|
148
|
+
self._check_json_pointer(doc["$root"], self.doc, "#/$root")
|
|
149
|
+
if "definitions" in doc:
|
|
150
|
+
if not isinstance(doc["definitions"], dict):
|
|
151
|
+
self._err("definitions must be an object.", "#/definitions", ErrorCodes.SCHEMA_KEYWORD_INVALID_TYPE)
|
|
152
|
+
else:
|
|
153
|
+
self._validate_namespace(doc["definitions"], "#/definitions")
|
|
154
|
+
if "$offers" in doc:
|
|
155
|
+
self._check_offers(doc["$offers"], "#/$offers")
|
|
156
|
+
|
|
157
|
+
# Check for composition keywords at root if no type is present
|
|
158
|
+
if self.extended and "type" not in doc:
|
|
159
|
+
self._check_composition_keywords(doc, "#")
|
|
160
|
+
|
|
161
|
+
return self.errors
|
|
162
|
+
|
|
163
|
+
def _check_enabled_extensions(self, doc):
|
|
164
|
+
"""
|
|
165
|
+
Check which extensions are enabled based on $schema and $uses.
|
|
166
|
+
"""
|
|
167
|
+
schema_uri = doc.get("$schema", "")
|
|
168
|
+
uses = doc.get("$uses", [])
|
|
169
|
+
|
|
170
|
+
# Check if using extended or validation meta-schema
|
|
171
|
+
if "extended" in schema_uri or "validation" in schema_uri:
|
|
172
|
+
# These meta-schemas enable certain extensions by default
|
|
173
|
+
if "validation" in schema_uri:
|
|
174
|
+
self.enabled_extensions.add("JSONStructureConditionalComposition")
|
|
175
|
+
self.enabled_extensions.add("JSONStructureValidation")
|
|
176
|
+
|
|
177
|
+
# Check $uses array
|
|
178
|
+
if isinstance(uses, list):
|
|
179
|
+
for ext in uses:
|
|
180
|
+
if ext in self.KNOWN_EXTENSIONS:
|
|
181
|
+
self.enabled_extensions.add(ext)
|
|
182
|
+
|
|
183
|
+
def _check_uses(self, uses, path):
|
|
184
|
+
"""
|
|
185
|
+
Validate the $uses keyword.
|
|
186
|
+
"""
|
|
187
|
+
if not isinstance(uses, list):
|
|
188
|
+
self._err("$uses must be an array.", path, ErrorCodes.SCHEMA_KEYWORD_INVALID_TYPE)
|
|
189
|
+
return
|
|
190
|
+
|
|
191
|
+
for idx, ext in enumerate(uses):
|
|
192
|
+
if not isinstance(ext, str):
|
|
193
|
+
self._err(f"$uses[{idx}] must be a string.", f"{path}[{idx}]", ErrorCodes.SCHEMA_KEYWORD_INVALID_TYPE)
|
|
194
|
+
elif self.extended and ext not in self.KNOWN_EXTENSIONS:
|
|
195
|
+
self._err(f"Unknown extension '{ext}' in $uses.", f"{path}[{idx}]", ErrorCodes.SCHEMA_USES_UNKNOWN_EXTENSION)
|
|
196
|
+
|
|
197
|
+
def _check_required_top_level_keywords(self, obj, location):
|
|
198
|
+
"""
|
|
199
|
+
Ensures $schema and $id are present at the root level.
|
|
200
|
+
"""
|
|
201
|
+
if "$schema" not in obj:
|
|
202
|
+
self._err("Missing required '$schema' keyword at root.", location)
|
|
203
|
+
if "$id" not in obj:
|
|
204
|
+
self._err("Missing required '$id' keyword at root.", location)
|
|
205
|
+
|
|
206
|
+
def _check_is_absolute_uri(self, value, keyword_name, location):
|
|
207
|
+
"""
|
|
208
|
+
Checks if a given string is an absolute URI.
|
|
209
|
+
"""
|
|
210
|
+
if not isinstance(value, str):
|
|
211
|
+
self._err(f"'{keyword_name}' must be a string.", location)
|
|
212
|
+
return
|
|
213
|
+
if not self.ABSOLUTE_URI_REGEX.search(value):
|
|
214
|
+
self._err(f"'{keyword_name}' must be an absolute URI.", location)
|
|
215
|
+
|
|
216
|
+
def _rewrite_refs(self, obj, target_path):
|
|
217
|
+
"""
|
|
218
|
+
Recursively rewrites $ref pointers in an imported schema to be relative to the target path.
|
|
219
|
+
When a schema is imported at path (e.g., #/definitions/People), all internal $ref pointers
|
|
220
|
+
like #/definitions/X or #/X need to be rewritten to point to target_path/X.
|
|
221
|
+
[Metaschema: JSONStructureImport extension - reference rewriting]
|
|
222
|
+
:param obj: The imported schema object to rewrite.
|
|
223
|
+
:param target_path: The JSON pointer path where the schema is being imported (e.g., "#/definitions/People").
|
|
224
|
+
"""
|
|
225
|
+
if isinstance(obj, dict):
|
|
226
|
+
for key, value in obj.items():
|
|
227
|
+
if key == "$ref" and isinstance(value, str) and value.startswith("#"):
|
|
228
|
+
# Rewrite the $ref to be relative to target_path
|
|
229
|
+
# Original ref like "#/definitions/Address" or "#/Address"
|
|
230
|
+
# needs to become "target_path/Address"
|
|
231
|
+
ref_parts = value.lstrip("#").split("/")
|
|
232
|
+
# Get the final referenced name (last part of the path)
|
|
233
|
+
if ref_parts and ref_parts[-1]:
|
|
234
|
+
ref_name = ref_parts[-1]
|
|
235
|
+
# Rewrite to point to the same name under target_path
|
|
236
|
+
obj[key] = f"{target_path}/{ref_name}"
|
|
237
|
+
elif key == "$extends" and isinstance(value, str) and value.startswith("#"):
|
|
238
|
+
# Also rewrite $extends references
|
|
239
|
+
ref_parts = value.lstrip("#").split("/")
|
|
240
|
+
if ref_parts and ref_parts[-1]:
|
|
241
|
+
ref_name = ref_parts[-1]
|
|
242
|
+
obj[key] = f"{target_path}/{ref_name}"
|
|
243
|
+
else:
|
|
244
|
+
self._rewrite_refs(value, target_path)
|
|
245
|
+
elif isinstance(obj, list):
|
|
246
|
+
for item in obj:
|
|
247
|
+
self._rewrite_refs(item, target_path)
|
|
248
|
+
|
|
249
|
+
def _process_imports(self, obj, path):
|
|
250
|
+
"""
|
|
251
|
+
Recursively processes $import and $importdefs keywords.
|
|
252
|
+
If allow_import is False, an error is reported.
|
|
253
|
+
Otherwise, external schemas are fetched and their definitions merged appropriately.
|
|
254
|
+
- If the import is at the root level, definitions go into obj["definitions"]
|
|
255
|
+
- If the import is inside a namespace (e.g., definitions/People), definitions merge directly into obj
|
|
256
|
+
This merging is done in-place so that imported definitions appear as if they were defined locally.
|
|
257
|
+
After merging, $ref pointers in the imported content are rewritten to point to their new locations.
|
|
258
|
+
"""
|
|
259
|
+
if isinstance(obj, dict):
|
|
260
|
+
# Process import keywords at current level.
|
|
261
|
+
for key in list(obj.keys()):
|
|
262
|
+
if key in ("$import", "$importdefs"):
|
|
263
|
+
if not self.allow_import:
|
|
264
|
+
self._err(f"JSONStructureImport keyword '{key}' encountered but allow_import not enabled.", f"{path}/{key}")
|
|
265
|
+
continue
|
|
266
|
+
uri = obj[key]
|
|
267
|
+
if not isinstance(uri, str):
|
|
268
|
+
self._err(f"JSONStructureImport keyword '{key}' value must be a string URI.", f"{path}/{key}")
|
|
269
|
+
continue
|
|
270
|
+
# Allow relative URIs if they're in import_map or external_schemas
|
|
271
|
+
if not self.ABSOLUTE_URI_REGEX.search(uri):
|
|
272
|
+
if uri not in self.import_map and uri not in self.external_schemas:
|
|
273
|
+
self._err(f"JSONStructureImport keyword '{key}' value must be an absolute URI.", f"{path}/{key}")
|
|
274
|
+
continue
|
|
275
|
+
external = self._fetch_external_schema(uri)
|
|
276
|
+
if external is None:
|
|
277
|
+
self._err(f"Unable to fetch external schema from {uri}.", f"{path}/{key}")
|
|
278
|
+
continue
|
|
279
|
+
if key == "$import":
|
|
280
|
+
imported_defs = {}
|
|
281
|
+
# Import root type if available.
|
|
282
|
+
if "type" in external and "name" in external:
|
|
283
|
+
imported_defs[external["name"]] = external
|
|
284
|
+
# Also import definitions from definitions if available.
|
|
285
|
+
if "definitions" in external and isinstance(external["definitions"], dict):
|
|
286
|
+
imported_defs.update(external["definitions"])
|
|
287
|
+
else: # $importdefs
|
|
288
|
+
if "definitions" in external and isinstance(external["definitions"], dict):
|
|
289
|
+
imported_defs = external["definitions"]
|
|
290
|
+
else:
|
|
291
|
+
imported_defs = {}
|
|
292
|
+
# Determine where to merge and the actual target path for ref rewriting
|
|
293
|
+
if path == "#":
|
|
294
|
+
# Root level import - put in definitions
|
|
295
|
+
target_path = "#/definitions"
|
|
296
|
+
if "definitions" not in obj:
|
|
297
|
+
obj["definitions"] = {}
|
|
298
|
+
merge_target = obj["definitions"]
|
|
299
|
+
else:
|
|
300
|
+
# Nested import (e.g., inside a namespace) - merge directly into current object
|
|
301
|
+
target_path = path
|
|
302
|
+
merge_target = obj
|
|
303
|
+
# Rewrite $ref pointers in imported content to point to their new location
|
|
304
|
+
for k, v in imported_defs.items():
|
|
305
|
+
if isinstance(v, dict):
|
|
306
|
+
# Deep copy to avoid modifying cached schemas
|
|
307
|
+
import copy
|
|
308
|
+
v = copy.deepcopy(v)
|
|
309
|
+
self._rewrite_refs(v, target_path)
|
|
310
|
+
imported_defs[k] = v
|
|
311
|
+
# Merge imported definitions
|
|
312
|
+
for k, v in imported_defs.items():
|
|
313
|
+
if k not in merge_target:
|
|
314
|
+
merge_target[k] = v
|
|
315
|
+
del obj[key]
|
|
316
|
+
# Recurse into all values.
|
|
317
|
+
for key, value in obj.items():
|
|
318
|
+
self._process_imports(value, f"{path}/{key}")
|
|
319
|
+
elif isinstance(obj, list):
|
|
320
|
+
for idx, item in enumerate(obj):
|
|
321
|
+
self._process_imports(item, f"{path}[{idx}]")
|
|
322
|
+
|
|
323
|
+
def _fetch_external_schema(self, uri):
|
|
324
|
+
"""
|
|
325
|
+
Fetches an external schema from a URI.
|
|
326
|
+
Resolution order:
|
|
327
|
+
1. Check external_schemas (pre-loaded schemas matched by $id)
|
|
328
|
+
2. Check import_map (URI to file path mapping)
|
|
329
|
+
"""
|
|
330
|
+
# First check sideloaded schemas by $id
|
|
331
|
+
if uri in self.external_schemas:
|
|
332
|
+
return self.external_schemas[uri]
|
|
333
|
+
# Then check import_map for file paths
|
|
334
|
+
if uri in self.import_map:
|
|
335
|
+
try:
|
|
336
|
+
with open(self.import_map[uri], "r", encoding="utf-8") as f:
|
|
337
|
+
return json.load(f)
|
|
338
|
+
except Exception as e:
|
|
339
|
+
self._err(f"Failed to load imported schema from {self.import_map[uri]}: {e}", "#/import")
|
|
340
|
+
return None
|
|
341
|
+
# URI not found in external_schemas or import_map
|
|
342
|
+
return None
|
|
343
|
+
|
|
344
|
+
def _validate_namespace(self, obj, path):
|
|
345
|
+
"""
|
|
346
|
+
Recursively validates objects in definitions as either a namespace or a schema.
|
|
347
|
+
"""
|
|
348
|
+
if not isinstance(obj, dict):
|
|
349
|
+
self._err(f"{path} must be an object.", path)
|
|
350
|
+
return
|
|
351
|
+
for k, v in obj.items():
|
|
352
|
+
subpath = f"{path}/{k}"
|
|
353
|
+
if isinstance(v, dict) and ("type" in v or "$ref" in v or
|
|
354
|
+
(self.extended and self._has_composition_keywords(v))):
|
|
355
|
+
self._validate_schema(v, is_root=False, path=subpath, name_in_namespace=k)
|
|
356
|
+
else:
|
|
357
|
+
if not isinstance(v, dict):
|
|
358
|
+
self._err(f"{subpath} is not a valid namespace or schema object.", subpath)
|
|
359
|
+
else:
|
|
360
|
+
self._validate_namespace(v, subpath)
|
|
361
|
+
|
|
362
|
+
def _has_composition_keywords(self, obj):
|
|
363
|
+
"""
|
|
364
|
+
Check if object has any composition keywords.
|
|
365
|
+
"""
|
|
366
|
+
return any(key in obj for key in self.COMPOSITION_KEYWORDS)
|
|
367
|
+
|
|
368
|
+
def _validate_schema(self, schema_obj, is_root=False, path="", name_in_namespace=None):
|
|
369
|
+
"""
|
|
370
|
+
Validates an individual schema object.
|
|
371
|
+
"""
|
|
372
|
+
if not isinstance(schema_obj, dict):
|
|
373
|
+
self._err(f"{path} must be an object to be a schema.", path)
|
|
374
|
+
return
|
|
375
|
+
|
|
376
|
+
# Check composition keywords if extended validation is enabled
|
|
377
|
+
if self.extended:
|
|
378
|
+
self._check_composition_keywords(schema_obj, path)
|
|
379
|
+
|
|
380
|
+
if is_root and "type" in schema_obj and "name" not in schema_obj:
|
|
381
|
+
if not isinstance(schema_obj["type"], list):
|
|
382
|
+
self._err("Root schema with 'type' must have a 'name' property.", path)
|
|
383
|
+
if "name" in schema_obj:
|
|
384
|
+
if not isinstance(schema_obj["name"], str):
|
|
385
|
+
self._err(f"'name' must be a string.", path + "/name")
|
|
386
|
+
else:
|
|
387
|
+
if not self.identifier_regex.match(schema_obj["name"]):
|
|
388
|
+
self._err(f"'name' must match the identifier pattern.", path + "/name")
|
|
389
|
+
if "abstract" in schema_obj:
|
|
390
|
+
if not isinstance(schema_obj["abstract"], bool):
|
|
391
|
+
self._err(f"'abstract' keyword must be boolean.", path + "/abstract")
|
|
392
|
+
if "$extends" in schema_obj:
|
|
393
|
+
if not isinstance(schema_obj["$extends"], str):
|
|
394
|
+
self._err(f"'$extends' must be a JSON pointer string.", path + "/$extends")
|
|
395
|
+
else:
|
|
396
|
+
self._check_json_pointer(schema_obj["$extends"], self.doc, path + "/$extends")
|
|
397
|
+
|
|
398
|
+
# Check if this is a non-schema with composition keywords
|
|
399
|
+
has_type_or_ref = "type" in schema_obj or "$ref" in schema_obj
|
|
400
|
+
has_composition = self.extended and self._has_composition_keywords(schema_obj)
|
|
401
|
+
|
|
402
|
+
if not has_type_or_ref and not has_composition:
|
|
403
|
+
self._err("Missing required 'type' or '$ref' in schema object.", path)
|
|
404
|
+
return
|
|
405
|
+
|
|
406
|
+
if "type" in schema_obj and "$ref" in schema_obj:
|
|
407
|
+
self._err("Cannot have both 'type' and '$ref'.", path)
|
|
408
|
+
return
|
|
409
|
+
|
|
410
|
+
if "$ref" in schema_obj:
|
|
411
|
+
if not isinstance(schema_obj["$ref"], str):
|
|
412
|
+
self._err("'$ref' must be a string.", path + "/$ref")
|
|
413
|
+
else:
|
|
414
|
+
self._check_json_pointer(schema_obj["$ref"], self.doc, path + "/$ref")
|
|
415
|
+
return
|
|
416
|
+
|
|
417
|
+
if "type" in schema_obj:
|
|
418
|
+
tval = schema_obj["type"]
|
|
419
|
+
if isinstance(tval, list):
|
|
420
|
+
if not tval:
|
|
421
|
+
self._err("Type union cannot be empty.", path + "/type")
|
|
422
|
+
else:
|
|
423
|
+
for idx, union_item in enumerate(tval):
|
|
424
|
+
self._check_union_type_item(union_item, f"{path}/type[{idx}]")
|
|
425
|
+
elif isinstance(tval, dict):
|
|
426
|
+
if "$ref" not in tval:
|
|
427
|
+
if "type" in tval or "properties" in tval:
|
|
428
|
+
self._validate_schema(tval, is_root=False, path=f"{path}/type(inline)")
|
|
429
|
+
else:
|
|
430
|
+
self._err("Type dict must have '$ref' or be a valid schema object.", path + "/type")
|
|
431
|
+
else:
|
|
432
|
+
self._check_json_pointer(tval["$ref"], self.doc, path + "/type/$ref")
|
|
433
|
+
else:
|
|
434
|
+
if not isinstance(tval, str):
|
|
435
|
+
self._err("Type must be a string, list, or object with $ref.", path + "/type")
|
|
436
|
+
else:
|
|
437
|
+
if (tval not in self.PRIMITIVE_TYPES and
|
|
438
|
+
tval not in self.COMPOUND_TYPES):
|
|
439
|
+
self._err(f"Type '{tval}' is not a recognized primitive or compound type.", path + "/type")
|
|
440
|
+
else:
|
|
441
|
+
if tval == "any":
|
|
442
|
+
pass
|
|
443
|
+
elif tval == "object":
|
|
444
|
+
self._check_object_schema(schema_obj, path)
|
|
445
|
+
elif tval == "array":
|
|
446
|
+
self._check_array_schema(schema_obj, path)
|
|
447
|
+
elif tval == "set":
|
|
448
|
+
self._check_set_schema(schema_obj, path)
|
|
449
|
+
elif tval == "map":
|
|
450
|
+
self._check_map_schema(schema_obj, path)
|
|
451
|
+
elif tval == "tuple":
|
|
452
|
+
self._check_tuple_schema(schema_obj, path)
|
|
453
|
+
elif tval == "choice":
|
|
454
|
+
self._check_choice_schema(schema_obj, path)
|
|
455
|
+
else:
|
|
456
|
+
self._check_primitive_schema(schema_obj, path)
|
|
457
|
+
|
|
458
|
+
# Extended validation checks
|
|
459
|
+
if self.extended and "type" in schema_obj:
|
|
460
|
+
self._check_extended_validation_keywords(schema_obj, path)
|
|
461
|
+
|
|
462
|
+
if "required" in schema_obj:
|
|
463
|
+
if "type" in schema_obj and isinstance(schema_obj["type"], str):
|
|
464
|
+
if schema_obj["type"] != "object":
|
|
465
|
+
self._err("'required' can only appear in an object schema.", path + "/required")
|
|
466
|
+
if "additionalProperties" in schema_obj:
|
|
467
|
+
if "type" in schema_obj and isinstance(schema_obj["type"], str):
|
|
468
|
+
if schema_obj["type"] != "object":
|
|
469
|
+
self._err("'additionalProperties' can only appear in an object schema.", path + "/additionalProperties")
|
|
470
|
+
if "enum" in schema_obj:
|
|
471
|
+
if not isinstance(schema_obj["enum"], list):
|
|
472
|
+
self._err("Enum must be an array.", path + "/enum")
|
|
473
|
+
if "type" in schema_obj and isinstance(schema_obj["type"], str):
|
|
474
|
+
if schema_obj["type"] in self.COMPOUND_TYPES:
|
|
475
|
+
self._err("'enum' cannot be used with compound types.", path + "/enum")
|
|
476
|
+
if "const" in schema_obj:
|
|
477
|
+
if "type" in schema_obj and isinstance(schema_obj["type"], str):
|
|
478
|
+
if schema_obj["type"] in self.COMPOUND_TYPES:
|
|
479
|
+
self._err("'const' cannot be used with compound types.", path + "/const")
|
|
480
|
+
|
|
481
|
+
def _check_composition_keywords(self, obj, path):
|
|
482
|
+
"""
|
|
483
|
+
Check conditional composition keywords if the extension is enabled.
|
|
484
|
+
"""
|
|
485
|
+
if not self.extended:
|
|
486
|
+
return
|
|
487
|
+
|
|
488
|
+
# Check if conditional composition is enabled
|
|
489
|
+
if "JSONStructureConditionalComposition" not in self.enabled_extensions:
|
|
490
|
+
for key in self.COMPOSITION_KEYWORDS:
|
|
491
|
+
if key in obj:
|
|
492
|
+
self._err(f"Conditional composition keyword '{key}' requires JSONStructureConditionalComposition extension.", f"{path}/{key}")
|
|
493
|
+
return
|
|
494
|
+
|
|
495
|
+
# Validate allOf, anyOf, oneOf
|
|
496
|
+
for key in ["allOf", "anyOf", "oneOf"]:
|
|
497
|
+
if key in obj:
|
|
498
|
+
val = obj[key]
|
|
499
|
+
if not isinstance(val, list):
|
|
500
|
+
self._err(f"'{key}' must be an array.", f"{path}/{key}")
|
|
501
|
+
elif len(val) == 0:
|
|
502
|
+
self._err(f"'{key}' array cannot be empty.", f"{path}/{key}")
|
|
503
|
+
else:
|
|
504
|
+
for idx, item in enumerate(val):
|
|
505
|
+
if isinstance(item, dict):
|
|
506
|
+
self._validate_schema(item, is_root=False, path=f"{path}/{key}[{idx}]")
|
|
507
|
+
else:
|
|
508
|
+
self._err(f"'{key}' array items must be schema objects.", f"{path}/{key}[{idx}]")
|
|
509
|
+
|
|
510
|
+
# Validate not
|
|
511
|
+
if "not" in obj:
|
|
512
|
+
val = obj["not"]
|
|
513
|
+
if isinstance(val, dict):
|
|
514
|
+
self._validate_schema(val, is_root=False, path=f"{path}/not")
|
|
515
|
+
else:
|
|
516
|
+
self._err("'not' must be a schema object.", f"{path}/not")
|
|
517
|
+
|
|
518
|
+
# Validate if/then/else
|
|
519
|
+
for key in ["if", "then", "else"]:
|
|
520
|
+
if key in obj:
|
|
521
|
+
val = obj[key]
|
|
522
|
+
if isinstance(val, dict):
|
|
523
|
+
self._validate_schema(val, is_root=False, path=f"{path}/{key}")
|
|
524
|
+
else:
|
|
525
|
+
self._err(f"'{key}' must be a schema object.", f"{path}/{key}")
|
|
526
|
+
|
|
527
|
+
def _check_extended_validation_keywords(self, obj, path):
|
|
528
|
+
"""
|
|
529
|
+
Check extended validation keywords based on type.
|
|
530
|
+
"""
|
|
531
|
+
if "JSONStructureValidation" not in self.enabled_extensions:
|
|
532
|
+
# Check if any validation keywords are present without the extension
|
|
533
|
+
all_validation_keywords = (self.NUMERIC_VALIDATION_KEYWORDS |
|
|
534
|
+
self.STRING_VALIDATION_KEYWORDS |
|
|
535
|
+
self.ARRAY_VALIDATION_KEYWORDS |
|
|
536
|
+
self.OBJECT_VALIDATION_KEYWORDS |
|
|
537
|
+
{"default"})
|
|
538
|
+
for key in all_validation_keywords:
|
|
539
|
+
if key in obj:
|
|
540
|
+
self._err(f"Validation keyword '{key}' requires JSONStructureValidation extension.", f"{path}/{key}")
|
|
541
|
+
return
|
|
542
|
+
|
|
543
|
+
tval = obj.get("type")
|
|
544
|
+
if isinstance(tval, str):
|
|
545
|
+
# Check numeric validation keywords
|
|
546
|
+
if tval in ["number", "integer", "float", "double", "decimal",
|
|
547
|
+
"int8", "uint8", "int16", "uint16", "int32", "uint32",
|
|
548
|
+
"int64", "uint64", "int128", "uint128", "float8"]:
|
|
549
|
+
self._check_numeric_validation(obj, path, tval)
|
|
550
|
+
|
|
551
|
+
# Check string validation keywords
|
|
552
|
+
elif tval == "string":
|
|
553
|
+
self._check_string_validation(obj, path)
|
|
554
|
+
|
|
555
|
+
# Check array/set validation keywords
|
|
556
|
+
elif tval in ["array", "set"]:
|
|
557
|
+
self._check_array_validation(obj, path, tval)
|
|
558
|
+
|
|
559
|
+
# Check object/map validation keywords
|
|
560
|
+
elif tval in ["object", "map"]:
|
|
561
|
+
self._check_object_validation(obj, path, tval)
|
|
562
|
+
|
|
563
|
+
# Check default keyword
|
|
564
|
+
if "default" in obj:
|
|
565
|
+
# Default can be any value, just ensure it's present
|
|
566
|
+
pass
|
|
567
|
+
|
|
568
|
+
def _check_numeric_validation(self, obj, path, type_name):
|
|
569
|
+
"""
|
|
570
|
+
Check numeric validation keywords.
|
|
571
|
+
"""
|
|
572
|
+
# For extended types whose base is string, values should be strings
|
|
573
|
+
string_based_types = {"int64", "uint64", "int128", "uint128", "decimal"}
|
|
574
|
+
expects_string = type_name in string_based_types
|
|
575
|
+
|
|
576
|
+
for key in ["minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf"]:
|
|
577
|
+
if key in obj:
|
|
578
|
+
val = obj[key]
|
|
579
|
+
if expects_string:
|
|
580
|
+
if not isinstance(val, str):
|
|
581
|
+
self._err(f"'{key}' for type '{type_name}' must be a string.", f"{path}/{key}")
|
|
582
|
+
else:
|
|
583
|
+
if not isinstance(val, (int, float)):
|
|
584
|
+
self._err(f"'{key}' must be a number.", f"{path}/{key}")
|
|
585
|
+
elif key == "multipleOf" and val <= 0:
|
|
586
|
+
self._err(f"'multipleOf' must be a positive number.", f"{path}/{key}")
|
|
587
|
+
|
|
588
|
+
def _check_string_validation(self, obj, path):
|
|
589
|
+
"""
|
|
590
|
+
Check string validation keywords.
|
|
591
|
+
"""
|
|
592
|
+
if "minLength" in obj:
|
|
593
|
+
val = obj["minLength"]
|
|
594
|
+
if not isinstance(val, int) or val < 0:
|
|
595
|
+
self._err("'minLength' must be a non-negative integer.", f"{path}/minLength")
|
|
596
|
+
|
|
597
|
+
if "maxLength" in obj:
|
|
598
|
+
val = obj["maxLength"]
|
|
599
|
+
if not isinstance(val, int) or val < 0:
|
|
600
|
+
self._err("'maxLength' must be a non-negative integer.", f"{path}/maxLength")
|
|
601
|
+
|
|
602
|
+
if "pattern" in obj:
|
|
603
|
+
val = obj["pattern"]
|
|
604
|
+
if not isinstance(val, str):
|
|
605
|
+
self._err("'pattern' must be a string.", f"{path}/pattern")
|
|
606
|
+
else:
|
|
607
|
+
# Try to compile the regex
|
|
608
|
+
try:
|
|
609
|
+
re.compile(val)
|
|
610
|
+
except re.error as e:
|
|
611
|
+
self._err(f"'pattern' is not a valid regular expression: {e}", f"{path}/pattern")
|
|
612
|
+
|
|
613
|
+
if "format" in obj:
|
|
614
|
+
val = obj["format"]
|
|
615
|
+
if not isinstance(val, str):
|
|
616
|
+
self._err("'format' must be a string.", f"{path}/format")
|
|
617
|
+
elif val not in self.VALID_FORMATS:
|
|
618
|
+
self._err(f"Unknown format '{val}'.", f"{path}/format")
|
|
619
|
+
|
|
620
|
+
def _check_array_validation(self, obj, path, type_name):
|
|
621
|
+
"""
|
|
622
|
+
Check array/set validation keywords.
|
|
623
|
+
"""
|
|
624
|
+
for key in ["minItems", "maxItems"]:
|
|
625
|
+
if key in obj:
|
|
626
|
+
val = obj[key]
|
|
627
|
+
if not isinstance(val, int) or val < 0:
|
|
628
|
+
self._err(f"'{key}' must be a non-negative integer.", f"{path}/{key}")
|
|
629
|
+
|
|
630
|
+
if "uniqueItems" in obj:
|
|
631
|
+
val = obj["uniqueItems"]
|
|
632
|
+
if not isinstance(val, bool):
|
|
633
|
+
self._err("'uniqueItems' must be a boolean.", f"{path}/uniqueItems")
|
|
634
|
+
elif type_name == "set" and val is False:
|
|
635
|
+
self._err("'uniqueItems' cannot be false for 'set' type.", f"{path}/uniqueItems")
|
|
636
|
+
|
|
637
|
+
if "contains" in obj:
|
|
638
|
+
val = obj["contains"]
|
|
639
|
+
if isinstance(val, dict):
|
|
640
|
+
self._validate_schema(val, is_root=False, path=f"{path}/contains")
|
|
641
|
+
else:
|
|
642
|
+
self._err("'contains' must be a schema object.", f"{path}/contains")
|
|
643
|
+
|
|
644
|
+
for key in ["minContains", "maxContains"]:
|
|
645
|
+
if key in obj:
|
|
646
|
+
val = obj[key]
|
|
647
|
+
if not isinstance(val, int) or val < 0:
|
|
648
|
+
self._err(f"'{key}' must be a non-negative integer.", f"{path}/{key}")
|
|
649
|
+
# These require 'contains' to be present
|
|
650
|
+
if "contains" not in obj:
|
|
651
|
+
self._err(f"'{key}' requires 'contains' to be present.", f"{path}/{key}")
|
|
652
|
+
|
|
653
|
+
def _check_object_validation(self, obj, path, type_name):
|
|
654
|
+
"""
|
|
655
|
+
Check object/map validation keywords.
|
|
656
|
+
"""
|
|
657
|
+
# Handle minProperties/minEntries and maxProperties/maxEntries
|
|
658
|
+
min_key = "minEntries" if type_name == "map" else "minProperties"
|
|
659
|
+
max_key = "maxEntries" if type_name == "map" else "maxProperties"
|
|
660
|
+
|
|
661
|
+
for key in [min_key, max_key, "minProperties", "maxProperties", "minEntries", "maxEntries"]:
|
|
662
|
+
if key in obj:
|
|
663
|
+
# Check if using the right keyword for the type
|
|
664
|
+
if type_name == "map" and key in ["minProperties", "maxProperties"]:
|
|
665
|
+
self._err(f"Use '{key.replace('Properties', 'Entries')}' for map type instead of '{key}'.", f"{path}/{key}")
|
|
666
|
+
elif type_name == "object" and key in ["minEntries", "maxEntries"]:
|
|
667
|
+
self._err(f"Use '{key.replace('Entries', 'Properties')}' for object type instead of '{key}'.", f"{path}/{key}")
|
|
668
|
+
|
|
669
|
+
val = obj[key]
|
|
670
|
+
if not isinstance(val, int) or val < 0:
|
|
671
|
+
self._err(f"'{key}' must be a non-negative integer.", f"{path}/{key}")
|
|
672
|
+
|
|
673
|
+
if "dependentRequired" in obj:
|
|
674
|
+
if type_name != "object":
|
|
675
|
+
self._err("'dependentRequired' only applies to object type.", f"{path}/dependentRequired")
|
|
676
|
+
else:
|
|
677
|
+
val = obj["dependentRequired"]
|
|
678
|
+
if not isinstance(val, dict):
|
|
679
|
+
self._err("'dependentRequired' must be an object.", f"{path}/dependentRequired")
|
|
680
|
+
else:
|
|
681
|
+
for prop, deps in val.items():
|
|
682
|
+
if not isinstance(deps, list):
|
|
683
|
+
self._err(f"'dependentRequired/{prop}' must be an array.", f"{path}/dependentRequired/{prop}")
|
|
684
|
+
else:
|
|
685
|
+
for idx, dep in enumerate(deps):
|
|
686
|
+
if not isinstance(dep, str):
|
|
687
|
+
self._err(f"'dependentRequired/{prop}[{idx}]' must be a string.", f"{path}/dependentRequired/{prop}[{idx}]")
|
|
688
|
+
|
|
689
|
+
# Handle patternProperties/patternKeys
|
|
690
|
+
pattern_key = "patternKeys" if type_name == "map" else "patternProperties"
|
|
691
|
+
for key in ["patternProperties", "patternKeys"]:
|
|
692
|
+
if key in obj:
|
|
693
|
+
if type_name == "map" and key == "patternProperties":
|
|
694
|
+
self._err(f"Use 'patternKeys' for map type instead of 'patternProperties'.", f"{path}/{key}")
|
|
695
|
+
elif type_name == "object" and key == "patternKeys":
|
|
696
|
+
self._err(f"Use 'patternProperties' for object type instead of 'patternKeys'.", f"{path}/{key}")
|
|
697
|
+
|
|
698
|
+
val = obj[key]
|
|
699
|
+
if not isinstance(val, dict):
|
|
700
|
+
self._err(f"'{key}' must be an object.", f"{path}/{key}")
|
|
701
|
+
else:
|
|
702
|
+
for pattern, schema in val.items():
|
|
703
|
+
# Try to compile the pattern
|
|
704
|
+
try:
|
|
705
|
+
re.compile(pattern)
|
|
706
|
+
except re.error as e:
|
|
707
|
+
self._err(f"'{key}/{pattern}' is not a valid regular expression: {e}", f"{path}/{key}/{pattern}")
|
|
708
|
+
if isinstance(schema, dict):
|
|
709
|
+
self._validate_schema(schema, is_root=False, path=f"{path}/{key}/{pattern}")
|
|
710
|
+
else:
|
|
711
|
+
self._err(f"'{key}/{pattern}' must be a schema object.", f"{path}/{key}/{pattern}")
|
|
712
|
+
|
|
713
|
+
|
|
714
|
+
# Handle propertyNames/keyNames
|
|
715
|
+
name_key = "keyNames" if type_name == "map" else "propertyNames"
|
|
716
|
+
for key in ["propertyNames", "keyNames"]:
|
|
717
|
+
if key in obj:
|
|
718
|
+
if type_name == "map" and key == "propertyNames":
|
|
719
|
+
self._err(f"Use 'keyNames' for map type instead of 'propertyNames'.", f"{path}/{key}")
|
|
720
|
+
elif type_name == "object" and key == "keyNames":
|
|
721
|
+
self._err(f"Use 'propertyNames' for object type instead of 'keyNames'.", f"{path}/{key}")
|
|
722
|
+
|
|
723
|
+
val = obj[key]
|
|
724
|
+
if isinstance(val, dict):
|
|
725
|
+
# Must be a string type schema
|
|
726
|
+
if "type" in val and val["type"] != "string":
|
|
727
|
+
self._err(f"'{key}' schema must have type 'string'.", f"{path}/{key}")
|
|
728
|
+
self._validate_schema(val, is_root=False, path=f"{path}/{key}")
|
|
729
|
+
else:
|
|
730
|
+
self._err(f"'{key}' must be a schema object.", f"{path}/{key}")
|
|
731
|
+
|
|
732
|
+
if "has" in obj:
|
|
733
|
+
val = obj["has"]
|
|
734
|
+
if isinstance(val, dict):
|
|
735
|
+
self._validate_schema(val, is_root=False, path=f"{path}/has")
|
|
736
|
+
else:
|
|
737
|
+
self._err("'has' must be a schema object.", f"{path}/has")
|
|
738
|
+
|
|
739
|
+
def _check_union_type_item(self, union_item, path):
|
|
740
|
+
"""
|
|
741
|
+
Checks one item in a union's type array.
|
|
742
|
+
"""
|
|
743
|
+
if isinstance(union_item, str):
|
|
744
|
+
if (union_item not in self.PRIMITIVE_TYPES and
|
|
745
|
+
union_item not in self.COMPOUND_TYPES):
|
|
746
|
+
self._err(f"'{union_item}' not recognized as a valid type name.", path)
|
|
747
|
+
if union_item in self.COMPOUND_TYPES:
|
|
748
|
+
self._err(f"Inline compound type '{union_item}' is not permitted in a union. Must use a $ref.", path)
|
|
749
|
+
elif isinstance(union_item, dict):
|
|
750
|
+
if "$ref" not in union_item:
|
|
751
|
+
self._err("Inline compound definitions not allowed in union. Must be a $ref.", path)
|
|
752
|
+
else:
|
|
753
|
+
self._check_json_pointer(union_item["$ref"], self.doc, path + "/$ref")
|
|
754
|
+
else:
|
|
755
|
+
self._err("Union item must be a string or an object with $ref.", path)
|
|
756
|
+
|
|
757
|
+
def _check_object_schema(self, obj, path):
|
|
758
|
+
"""
|
|
759
|
+
Checks constraints specific to an 'object' type.
|
|
760
|
+
If the object extends another type via '$extends', 'properties' is optional.
|
|
761
|
+
"""
|
|
762
|
+
if "properties" not in obj and "$extends" not in obj:
|
|
763
|
+
self._err("Object type must have 'properties' if not extending another type.", path + "/properties")
|
|
764
|
+
elif "properties" in obj:
|
|
765
|
+
props = obj["properties"]
|
|
766
|
+
if not isinstance(props, dict):
|
|
767
|
+
self._err("Properties must be an object.", path + "/properties")
|
|
768
|
+
else:
|
|
769
|
+
for prop_name, prop_schema in props.items():
|
|
770
|
+
if not self.identifier_regex.match(prop_name):
|
|
771
|
+
self._err(f"Property key '{prop_name}' does not match the identifier pattern.", path + f"/properties/{prop_name}")
|
|
772
|
+
if isinstance(prop_schema, dict):
|
|
773
|
+
self._validate_schema(prop_schema, is_root=False, path=f"{path}/properties/{prop_name}")
|
|
774
|
+
else:
|
|
775
|
+
self._err(f"Property '{prop_name}' must be an object (a schema).", path + f"/properties/{prop_name}")
|
|
776
|
+
|
|
777
|
+
def _check_array_schema(self, obj, path):
|
|
778
|
+
"""
|
|
779
|
+
Checks constraints for an 'array' type.
|
|
780
|
+
"""
|
|
781
|
+
if "items" not in obj:
|
|
782
|
+
self._err("Array type must have 'items'.", path + "/items")
|
|
783
|
+
else:
|
|
784
|
+
items_schema = obj["items"]
|
|
785
|
+
if not isinstance(items_schema, dict):
|
|
786
|
+
self._err("'items' must be an object (a schema).", path + "/items")
|
|
787
|
+
else:
|
|
788
|
+
self._validate_schema(items_schema, is_root=False, path=path + "/items")
|
|
789
|
+
|
|
790
|
+
def _check_set_schema(self, obj, path):
|
|
791
|
+
"""
|
|
792
|
+
Checks constraints for a 'set' type.
|
|
793
|
+
"""
|
|
794
|
+
if "items" not in obj:
|
|
795
|
+
self._err("Set type must have 'items'.", path + "/items")
|
|
796
|
+
else:
|
|
797
|
+
items_schema = obj["items"]
|
|
798
|
+
if not isinstance(items_schema, dict):
|
|
799
|
+
self._err("'items' must be an object (a schema).", path + "/items")
|
|
800
|
+
else:
|
|
801
|
+
self._validate_schema(items_schema, is_root=False, path=path + "/items")
|
|
802
|
+
|
|
803
|
+
def _check_map_schema(self, obj, path):
|
|
804
|
+
"""
|
|
805
|
+
Checks constraints for a 'map' type.
|
|
806
|
+
"""
|
|
807
|
+
if "values" not in obj:
|
|
808
|
+
self._err("Map type must have 'values'.", path + "/values")
|
|
809
|
+
else:
|
|
810
|
+
values_schema = obj["values"]
|
|
811
|
+
if not isinstance(values_schema, dict):
|
|
812
|
+
self._err("'values' must be an object (a schema).", path + "/values")
|
|
813
|
+
else:
|
|
814
|
+
self._validate_schema(values_schema, is_root=False, path=path + "/values")
|
|
815
|
+
|
|
816
|
+
def _check_tuple_schema(self, obj, path):
|
|
817
|
+
"""
|
|
818
|
+
Checks constraints for a 'tuple' type.
|
|
819
|
+
A valid tuple schema must:
|
|
820
|
+
- Include a 'name' attribute.
|
|
821
|
+
- Have a 'properties' object where each key is a valid identifier.
|
|
822
|
+
- Include a 'tuple' keyword that is an array of strings defining the order.
|
|
823
|
+
- Ensure that every element in the 'tuple' array corresponds to a property in 'properties'.
|
|
824
|
+
"""
|
|
825
|
+
# Check that 'name' is present.
|
|
826
|
+
if "name" not in obj:
|
|
827
|
+
self._err("Tuple type must include a 'name' attribute.", path + "/name")
|
|
828
|
+
|
|
829
|
+
# Validate properties.
|
|
830
|
+
if "properties" not in obj:
|
|
831
|
+
self._err("Tuple type must have 'properties'.", path + "/properties")
|
|
832
|
+
else:
|
|
833
|
+
props = obj["properties"]
|
|
834
|
+
if not isinstance(props, dict):
|
|
835
|
+
self._err("'properties' must be an object.", path + "/properties")
|
|
836
|
+
else:
|
|
837
|
+
for prop_name, prop_schema in props.items():
|
|
838
|
+
if not self.identifier_regex.match(prop_name):
|
|
839
|
+
self._err(f"Tuple property key '{prop_name}' does not match the identifier pattern.", path + f"/properties/{prop_name}")
|
|
840
|
+
if isinstance(prop_schema, dict):
|
|
841
|
+
self._validate_schema(prop_schema, is_root=False, path=f"{path}/properties/{prop_name}")
|
|
842
|
+
else:
|
|
843
|
+
self._err(f"Tuple property '{prop_name}' must be an object (a schema).", path + f"/properties/{prop_name}")
|
|
844
|
+
|
|
845
|
+
# Check that the 'tuple' keyword is present.
|
|
846
|
+
if "tuple" not in obj:
|
|
847
|
+
self._err("Tuple type must include the 'tuple' keyword defining the order of elements.", path + "/tuple")
|
|
848
|
+
else:
|
|
849
|
+
tuple_order = obj["tuple"]
|
|
850
|
+
if not isinstance(tuple_order, list):
|
|
851
|
+
self._err("'tuple' keyword must be an array of strings.", path + "/tuple")
|
|
852
|
+
else:
|
|
853
|
+
for idx, element in enumerate(tuple_order):
|
|
854
|
+
if not isinstance(element, str):
|
|
855
|
+
self._err(f"Element at index {idx} in 'tuple' array must be a string.", path + f"/tuple[{idx}]")
|
|
856
|
+
elif "properties" in obj and isinstance(obj["properties"], dict) and element not in obj["properties"]:
|
|
857
|
+
self._err(f"Element '{element}' in 'tuple' does not correspond to any property in 'properties'.", path + f"/tuple[{idx}]")
|
|
858
|
+
|
|
859
|
+
def _check_choice_schema(self, obj, path):
|
|
860
|
+
"""
|
|
861
|
+
Checks constraints for a 'choice' type (tagged or inline union).
|
|
862
|
+
"""
|
|
863
|
+
if "choices" not in obj:
|
|
864
|
+
self._err("Choice type must have 'choices'.", path + "/choices")
|
|
865
|
+
else:
|
|
866
|
+
choices = obj["choices"]
|
|
867
|
+
if not isinstance(choices, dict):
|
|
868
|
+
self._err("'choices' must be an object (map).", path + "/choices")
|
|
869
|
+
else:
|
|
870
|
+
for name, choice_schema in choices.items():
|
|
871
|
+
if not isinstance(name, str):
|
|
872
|
+
self._err(f"Choice key '{name}' must be a string.", path + f"/choices/{name}")
|
|
873
|
+
if isinstance(choice_schema, dict):
|
|
874
|
+
self._validate_schema(choice_schema, is_root=False, path=f"{path}/choices/{name}")
|
|
875
|
+
else:
|
|
876
|
+
self._err(f"Choice value for '{name}' must be an object (schema).", path + f"/choices/{name}")
|
|
877
|
+
if "selector" in obj and not isinstance(obj.get("selector"), str):
|
|
878
|
+
self._err("'selector' must be a string.", path + "/selector")
|
|
879
|
+
|
|
880
|
+
def _check_primitive_schema(self, obj, path):
|
|
881
|
+
"""
|
|
882
|
+
Checks constraints for a recognized primitive type.
|
|
883
|
+
Additional annotation checks can be added here.
|
|
884
|
+
"""
|
|
885
|
+
pass
|
|
886
|
+
|
|
887
|
+
def _check_json_pointer(self, pointer, doc, path):
|
|
888
|
+
"""
|
|
889
|
+
Validates that the pointer is a valid JSON Pointer within the same document.
|
|
890
|
+
"""
|
|
891
|
+
if not isinstance(pointer, str):
|
|
892
|
+
self._err("JSON Pointer must be a string.", path)
|
|
893
|
+
return
|
|
894
|
+
if not pointer.startswith("#"):
|
|
895
|
+
self._err("JSON Pointer must start with '#' when referencing the same document.", path)
|
|
896
|
+
return
|
|
897
|
+
parts = pointer.split("/")
|
|
898
|
+
cur = doc
|
|
899
|
+
if pointer == "#":
|
|
900
|
+
return
|
|
901
|
+
for i, p in enumerate(parts):
|
|
902
|
+
if i == 0:
|
|
903
|
+
continue
|
|
904
|
+
p = p.replace("~1", "/").replace("~0", "~")
|
|
905
|
+
if isinstance(cur, dict):
|
|
906
|
+
if p in cur:
|
|
907
|
+
cur = cur[p]
|
|
908
|
+
else:
|
|
909
|
+
self._err(f"JSON Pointer segment '/{p}' not found.", path)
|
|
910
|
+
return
|
|
911
|
+
else:
|
|
912
|
+
self._err(f"JSON Pointer segment '/{p}' not applicable to non-object.", path)
|
|
913
|
+
return
|
|
914
|
+
|
|
915
|
+
def _check_offers(self, offers, path):
|
|
916
|
+
"""
|
|
917
|
+
Validates the structure of the $offers map.
|
|
918
|
+
"""
|
|
919
|
+
if not isinstance(offers, dict):
|
|
920
|
+
self._err("$offers must be an object.", path)
|
|
921
|
+
return
|
|
922
|
+
for addin_name, addin_val in offers.items():
|
|
923
|
+
if not isinstance(addin_name, str):
|
|
924
|
+
self._err("$offers keys must be strings.", path)
|
|
925
|
+
if isinstance(addin_val, str):
|
|
926
|
+
self._check_json_pointer(addin_val, self.doc, f"{path}/{addin_name}")
|
|
927
|
+
elif isinstance(addin_val, list):
|
|
928
|
+
for idx, pointer in enumerate(addin_val):
|
|
929
|
+
if not isinstance(pointer, str):
|
|
930
|
+
self._err(f"$offers/{addin_name}[{idx}] must be a string (JSON Pointer).", f"{path}/{addin_name}[{idx}]")
|
|
931
|
+
else:
|
|
932
|
+
self._check_json_pointer(pointer, self.doc, f"{path}/{addin_name}[{idx}]")
|
|
933
|
+
else:
|
|
934
|
+
self._err(f"$offers/{addin_name} must be a string or array of strings.", f"{path}/{addin_name}")
|
|
935
|
+
|
|
936
|
+
def _locate(self, pointer):
|
|
937
|
+
"""
|
|
938
|
+
Heuristically locates the first occurrence of the JSON pointer path in the source text.
|
|
939
|
+
Returns a tuple (line, column) if found, or None.
|
|
940
|
+
"""
|
|
941
|
+
if not self.source_text or not pointer.startswith("#"):
|
|
942
|
+
return None
|
|
943
|
+
parts = pointer[1:].split("/")
|
|
944
|
+
pos = 0
|
|
945
|
+
for part in parts:
|
|
946
|
+
part = part.replace("~1", "/").replace("~0", "~")
|
|
947
|
+
pattern = f'"{part}"'
|
|
948
|
+
found = self.source_text.find(pattern, pos)
|
|
949
|
+
if found == -1:
|
|
950
|
+
return None
|
|
951
|
+
pos = found + len(pattern)
|
|
952
|
+
line = self.source_text.count("\n", 0, pos) + 1
|
|
953
|
+
last_newline = self.source_text.rfind("\n", 0, pos)
|
|
954
|
+
col = pos - last_newline if last_newline != -1 else pos + 1
|
|
955
|
+
return (line, col)
|
|
956
|
+
|
|
957
|
+
def _err(self, message: str, location: str = "#", code: str = ErrorCodes.SCHEMA_ERROR):
|
|
958
|
+
"""
|
|
959
|
+
Appends a ValidationError with line and column information (if available)
|
|
960
|
+
to the validation errors.
|
|
961
|
+
"""
|
|
962
|
+
if self.source_locator:
|
|
963
|
+
loc = self.source_locator.get_location(location)
|
|
964
|
+
else:
|
|
965
|
+
loc = JsonLocation.unknown()
|
|
966
|
+
|
|
967
|
+
error = ValidationError(
|
|
968
|
+
code=code,
|
|
969
|
+
message=message,
|
|
970
|
+
path=location,
|
|
971
|
+
severity=ValidationSeverity.ERROR,
|
|
972
|
+
location=loc
|
|
973
|
+
)
|
|
974
|
+
self.errors.append(error)
|
|
975
|
+
|
|
976
|
+
|
|
977
|
+
def validate_json_structure_schema_core(schema_document, source_text=None, allow_dollar=False, allow_import=False, import_map=None, extended=False):
|
|
978
|
+
"""
|
|
979
|
+
Validates the provided schema_document dict against the JSON Structure Core specification.
|
|
980
|
+
:param schema_document: Parsed JSON Structure document.
|
|
981
|
+
:param source_text: Original JSON text.
|
|
982
|
+
:param allow_dollar: Allow '$' in property names.
|
|
983
|
+
:param allow_import: Enable processing of $import/$importdefs keywords.
|
|
984
|
+
:param import_map: Dictionary mapping URI to local filenames.
|
|
985
|
+
:param extended: Enable extended validation features.
|
|
986
|
+
:return: List of error strings; empty if valid.
|
|
987
|
+
"""
|
|
988
|
+
validator = JSONStructureSchemaCoreValidator(allow_dollar=allow_dollar, allow_import=allow_import, import_map=import_map, extended=extended)
|
|
989
|
+
return validator.validate(schema_document, source_text)
|
|
990
|
+
|
|
991
|
+
|
|
992
|
+
def main():
|
|
993
|
+
"""
|
|
994
|
+
Command line entry point.
|
|
995
|
+
Expects [--metaschema] [--allowimport] [--extended] [--importmap URI=filename ...] and <path_to_json_file> as arguments.
|
|
996
|
+
Prints errors with line and column information if found, otherwise prints "Schema is valid."
|
|
997
|
+
"""
|
|
998
|
+
args = sys.argv[1:]
|
|
999
|
+
allow_dollar = False
|
|
1000
|
+
allow_import = False
|
|
1001
|
+
extended = False
|
|
1002
|
+
import_map = {}
|
|
1003
|
+
|
|
1004
|
+
# Process flags.
|
|
1005
|
+
while args and args[0].startswith("--"):
|
|
1006
|
+
arg = args.pop(0)
|
|
1007
|
+
if arg == "--metaschema":
|
|
1008
|
+
allow_dollar = True
|
|
1009
|
+
elif arg == "--allowimport":
|
|
1010
|
+
allow_import = True
|
|
1011
|
+
elif arg == "--extended":
|
|
1012
|
+
extended = True
|
|
1013
|
+
elif arg.startswith("--importmap"):
|
|
1014
|
+
if "=" in arg:
|
|
1015
|
+
_, mapping_str = arg.split("--importmap=", 1)
|
|
1016
|
+
else:
|
|
1017
|
+
if not args:
|
|
1018
|
+
print("Missing value for --importmap")
|
|
1019
|
+
sys.exit(1)
|
|
1020
|
+
mapping_str = args.pop(0)
|
|
1021
|
+
parts = mapping_str.split("=", 1)
|
|
1022
|
+
if len(parts) != 2:
|
|
1023
|
+
print("Invalid --importmap format. Expected format: URI=filename")
|
|
1024
|
+
sys.exit(1)
|
|
1025
|
+
uri, filename = parts
|
|
1026
|
+
import_map[uri] = filename
|
|
1027
|
+
else:
|
|
1028
|
+
print(f"Unknown flag {arg}")
|
|
1029
|
+
sys.exit(1)
|
|
1030
|
+
|
|
1031
|
+
if len(args) < 1:
|
|
1032
|
+
print("Usage: python json_structure_schema_validator.py [--metaschema] [--allowimport] [--extended] [--importmap URI=filename ...] <path_to_json_file>")
|
|
1033
|
+
sys.exit(1)
|
|
1034
|
+
file_path = args[0]
|
|
1035
|
+
try:
|
|
1036
|
+
with open(file_path, "r", encoding="utf-8") as file_in:
|
|
1037
|
+
source_text = file_in.read()
|
|
1038
|
+
data = json.loads(source_text)
|
|
1039
|
+
except (FileNotFoundError, json.JSONDecodeError) as ex:
|
|
1040
|
+
if hasattr(ex, 'lineno') and hasattr(ex, 'colno'):
|
|
1041
|
+
print(f"Error reading JSON file: {ex.msg} (Line: {ex.lineno}, Column: {ex.colno})")
|
|
1042
|
+
else:
|
|
1043
|
+
print(f"Error reading JSON file: {ex}")
|
|
1044
|
+
sys.exit(1)
|
|
1045
|
+
errors = validate_json_structure_schema_core(data, source_text, allow_dollar=allow_dollar, allow_import=allow_import, import_map=import_map, extended=extended)
|
|
1046
|
+
if errors:
|
|
1047
|
+
print("Schema is invalid:")
|
|
1048
|
+
for err in errors:
|
|
1049
|
+
print(" -", err)
|
|
1050
|
+
sys.exit(1)
|
|
1051
|
+
print("Schema is valid.")
|
|
1052
|
+
|
|
1053
|
+
|
|
1054
|
+
if __name__ == "__main__":
|
|
1055
|
+
main()
|