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.
@@ -0,0 +1,1191 @@
1
+ # encoding: utf-8
2
+ """
3
+ json_structure_instance_validator.py
4
+
5
+ Validates JSON document instances against JSON Structures conforming to the experimental
6
+ JSON Structure Core specification (C. Vasters, Microsoft, February 2025), including
7
+ all constructs from the core spec: primitive types, compound types, abstract types,
8
+ $extends, $offers, $uses, as well as the JSON Structure JSONStructureImport extensions ($import and $importdefs).
9
+
10
+ Additionally, if the instance provides a "$uses" clause containing "JSONStructureConditionalComposition" and/or "JSONStructureValidation",
11
+ the corresponding conditional composition and validation addin constraints are enforced.
12
+ Extensions such as "JSONStructureAlternateNames" or "JSONStructureUnits" are generally ignored for validation.
13
+
14
+ Furthermore, when the root schema’s "$schema" equals
15
+ "https://json-structure.org/meta/extended/v0/#"
16
+ all addins (i.e. all keys offered in "$offers") are automatically enabled.
17
+
18
+ This implementation also supports extended validation keywords as defined in the
19
+ "JSON Structure JSONStructureValidation" spec, including numeric, string, array, object constraints,
20
+ and the "has" keyword.
21
+
22
+ Usage:
23
+ python json_structure_instance_validator.py <schema_file> <instance_file>
24
+
25
+ The code sections are annotated with references to the metaschema constructs.
26
+ """
27
+
28
+ import sys
29
+ import json
30
+ import re
31
+ import datetime
32
+ import uuid
33
+ from urllib.parse import urlparse
34
+
35
+ # Regular expressions for date, datetime, time, duration and JSON pointer.
36
+ _DATE_REGEX = re.compile(r'^\d{4}-\d{2}-\d{2}$')
37
+ _DATETIME_REGEX = re.compile(
38
+ r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+\-]\d{2}:\d{2})$'
39
+ )
40
+ _TIME_REGEX = re.compile(r'^\d{2}:\d{2}:\d{2}(?:\.\d+)?$')
41
+ # ISO 8601 duration pattern: P[n]Y[n]M[n]DT[n]H[n]M[n]S or P[n]W
42
+ _DURATION_REGEX = re.compile(
43
+ r'^P(?:\d+Y)?(?:\d+M)?(?:\d+D)?(?:T(?:\d+H)?(?:\d+M)?(?:\d+(?:\.\d+)?S)?)?$|^P\d+W$'
44
+ )
45
+ _JSONPOINTER_REGEX = re.compile(r'^#(\/[^\/]+)*$')
46
+
47
+
48
+ class JSONStructureInstanceValidator:
49
+ """
50
+ Validator for JSON document instances against full JSON Structure Core schemas.
51
+ Implements all core constructs including abstract types, $extends, $offers, $uses,
52
+ the JSONStructureImport extension ($import and $importdefs), as well as conditional composition
53
+ (allOf, anyOf, oneOf, not, if/then/else) and validation addin constraints.
54
+ """
55
+ ABSOLUTE_URI_REGEX = re.compile(r'^[a-zA-Z][a-zA-Z0-9+\-.]*://')
56
+
57
+ def __init__(self, root_schema, allow_import=False, import_map=None, extended=False, external_schemas=None):
58
+ """
59
+ Initializes the validator.
60
+ :param root_schema: The JSON Structure (as dict).
61
+ :param allow_import: Enables processing of $import/$importdefs.
62
+ :param import_map: Dict mapping URIs to local filenames.
63
+ :param extended: Enable extended validation features.
64
+ :param external_schemas: List of schema dicts to use for resolving imports by $id.
65
+ Each schema should have a '$id' field matching the import URI.
66
+ """
67
+ self.root_schema = root_schema
68
+ self.errors = []
69
+ self.allow_import = allow_import
70
+ self.import_map = import_map if import_map is not None else {}
71
+ self.extended = extended
72
+ self.enabled_extensions = set()
73
+ # Build lookup for external schemas by $id
74
+ self.external_schemas = {}
75
+ if external_schemas:
76
+ for schema in external_schemas:
77
+ if isinstance(schema, dict) and "$id" in schema:
78
+ self.external_schemas[schema["$id"]] = schema
79
+ # Process $import and $importdefs if enabled. [Metaschema: JSONStructureImport extension constructs]
80
+ if self.allow_import:
81
+ self._process_imports(self.root_schema, "#")
82
+ self._detect_enabled_extensions()
83
+
84
+ def _detect_enabled_extensions(self):
85
+ schema_uri = self.root_schema.get("$schema", "")
86
+ uses = self.root_schema.get("$uses", [])
87
+ if "extended" in schema_uri or "validation" in schema_uri:
88
+ self.enabled_extensions.add("JSONStructureConditionalComposition")
89
+ self.enabled_extensions.add("JSONStructureValidation")
90
+ if isinstance(uses, list):
91
+ for ext in uses:
92
+ self.enabled_extensions.add(ext)
93
+ # If extended=True was passed to constructor, enable validation extensions
94
+ if self.extended:
95
+ self.enabled_extensions.add("JSONStructureConditionalComposition")
96
+ self.enabled_extensions.add("JSONStructureValidation")
97
+
98
+ def validate_instance(self, instance, schema=None, path="#", meta=None):
99
+ """
100
+ Validates an instance against a schema.
101
+ Resolves $ref, processes $extends, rejects abstract schemas, applies $uses,
102
+ then validates based on type. Finally, conditionally validates conditional composition
103
+ and validation addin constraints.
104
+ :param instance: The JSON instance.
105
+ :param schema: The schema to validate against (defaults to root schema).
106
+ :param path: JSON Pointer for error reporting.
107
+ :return: List of error messages.
108
+ """
109
+ if schema is None:
110
+ schema = self.root_schema
111
+
112
+ # Handle $root - redirect to the designated root type
113
+ # [Metaschema: $root keyword designates a reusable type as the root]
114
+ if "$root" in schema and "type" not in schema:
115
+ root_ref = schema.get("$root")
116
+ if root_ref:
117
+ resolved = self._resolve_ref(root_ref)
118
+ if resolved is None:
119
+ self.errors.append(f"Cannot resolve $root reference {root_ref}")
120
+ return self.errors
121
+ return self.validate_instance(instance, resolved, path)
122
+
123
+ # --- Automatically enable all addins if using extended metaschema ---
124
+ # Only do this if $uses is present; otherwise, do NOT auto-enable addins (per spec)
125
+ if self.root_schema.get("$schema") == "https://json-structure.org/meta/extended/v0/#":
126
+ if "$uses" in schema:
127
+ all_addins = [
128
+ "JSONStructureConditionalComposition",
129
+ "JSONStructureValidation",
130
+ "JSONStructureUnits",
131
+ "JSONStructureAlternateNames"
132
+ ]
133
+ schema.setdefault("$uses", [])
134
+ for addin in all_addins:
135
+ if addin not in schema["$uses"]:
136
+ schema["$uses"].append(addin)
137
+ # If $uses is not present, do not auto-enable addins; enforcement is handled later
138
+
139
+ if isinstance(instance, dict) and "$uses" in instance and self.root_schema.get("$schema") == "https://json-structure.org/meta/validation/v0/#":
140
+ # Automatically enable the JSONStructureValidation addin.
141
+ schema.setdefault("$uses", [])
142
+ if "JSONStructureValidation" in instance["$uses"] and not "JSONStructureValidation" in schema["$uses"]:
143
+ schema["$uses"].append("JSONStructureValidation")
144
+ if "JSONStructureConditionalComposition" in instance["$uses"] and not "JSONStructureConditionalComposition" in schema["$uses"]:
145
+ schema["$uses"].append("JSONStructureConditionalComposition")
146
+ # [Metaschema: JSONStructureValidation metaschema automatically enables JSONStructureValidation addin]
147
+
148
+ # the core schema https://json-structure.org/meta/validation/v0/# has no JSONStructureConditionalComposition or JSONStructureValidation addins
149
+ # an instance referencing these addins will be rejected
150
+ if isinstance(instance, dict) and "$uses" in instance and self.root_schema.get("$schema") == "https://json-structure.org/meta/core/v0/#":
151
+ if "JSONStructureValidation" in instance["$uses"] or "JSONStructureConditionalComposition" in instance["$uses"]:
152
+ self.errors.append(
153
+ f"Instance at {path} references JSONStructureConditionalComposition or JSONStructureValidation addins but the schema does not support them")
154
+
155
+ # Resolve $ref at schema level. [Metaschema: TypeReference]
156
+ if "$ref" in schema:
157
+ ref = schema["$ref"]
158
+ resolved = self._resolve_ref(ref)
159
+ if resolved is None:
160
+ self.errors.append(f"Cannot resolve $ref {ref} at {path}")
161
+ return self.errors
162
+ return self.validate_instance(instance, resolved, path)
163
+
164
+ hasConditionals = False
165
+ if "$uses" in self.root_schema:
166
+ if "JSONStructureConditionalComposition" in self.root_schema["$uses"]:
167
+ hasConditionals = self._validate_conditionals(schema, instance, path) # Handle schemas that are only conditional composition at the root (no 'type')
168
+ conditional_keywords = ("allOf", "anyOf", "oneOf", "not", "if", "then", "else")
169
+ has_conditionals_at_root = any(k in schema for k in conditional_keywords)
170
+ if not schema.get("type") and has_conditionals_at_root:
171
+ schema_uri = self.root_schema.get("$schema", "")
172
+ is_validation = schema_uri.endswith("/validation/v0/#")
173
+ is_extended = schema_uri.endswith("/extended/v0/#")
174
+
175
+ # Check extended metaschema enforcement first
176
+ if is_extended and not (isinstance(self.root_schema, dict) and "$uses" in self.root_schema and "JSONStructureConditionalComposition" in self.root_schema["$uses"]):
177
+ self.errors.append(
178
+ "Conditional composition is not enabled: $uses must include 'JSONStructureConditionalComposition' for the extended metaschema")
179
+ return self.errors
180
+
181
+ enable_conditional = (
182
+ self.extended or
183
+ is_validation or
184
+ (isinstance(self.root_schema, dict) and "$uses" in self.root_schema and (
185
+ "JSONStructureConditionalComposition" in self.root_schema["$uses"] or "JSONStructureValidation" in self.root_schema["$uses"]
186
+ ))
187
+ )
188
+
189
+ if enable_conditional:
190
+ self._validate_conditionals(schema, instance, path)
191
+ return self.errors
192
+ else:
193
+ self.errors.append(f"Conditional composition keywords present at {path} but not enabled")
194
+ return self.errors
195
+
196
+ # Handle case where "type" is a dict with a $ref. [Metaschema: PrimitiveOrReference]
197
+ schema_type = schema.get("type")
198
+ if not schema_type:
199
+ self.errors.append(f"Schema at {path} has no 'type'")
200
+ return self.errors
201
+
202
+ if isinstance(schema_type, dict):
203
+ if "$ref" in schema_type:
204
+ resolved = self._resolve_ref(schema_type["$ref"])
205
+ if resolved is None:
206
+ self.errors.append(f"Cannot resolve $ref {schema_type['$ref']} at {path}/type")
207
+ return self.errors
208
+ new_schema = dict(schema)
209
+ new_schema["type"] = resolved.get("type")
210
+ if "properties" in resolved:
211
+ merged_props = dict(resolved.get("properties"))
212
+ merged_props.update(new_schema.get("properties", {}))
213
+ new_schema["properties"] = merged_props
214
+ # Also copy tuple keyword for tuple types
215
+ if "tuple" in resolved:
216
+ new_schema["tuple"] = resolved.get("tuple")
217
+ # Copy required if present
218
+ if "required" in resolved and "required" not in new_schema:
219
+ new_schema["required"] = resolved.get("required")
220
+ # Copy choices for choice types
221
+ if "choices" in resolved:
222
+ new_schema["choices"] = resolved.get("choices")
223
+ # Copy selector for inline unions
224
+ if "selector" in resolved:
225
+ new_schema["selector"] = resolved.get("selector")
226
+ # Copy $extends for inherited types
227
+ if "$extends" in resolved and "$extends" not in new_schema:
228
+ new_schema["$extends"] = resolved.get("$extends")
229
+ schema = new_schema
230
+ schema_type = schema.get("type")
231
+ else:
232
+ self.errors.append(f"Schema at {path} has invalid 'type'")
233
+ return self.errors
234
+
235
+ # Handle union types. [Metaschema: TypeUnion]
236
+ if isinstance(schema_type, list):
237
+ union_valid = False
238
+ union_errors = []
239
+ for t in schema_type:
240
+ backup = list(self.errors)
241
+ self.errors = []
242
+ self.validate_instance(instance, {"type": t}, path)
243
+ if not self.errors:
244
+ union_valid = True
245
+ break
246
+ else:
247
+ union_errors.extend(self.errors)
248
+ self.errors = backup
249
+ if not union_valid:
250
+ self.errors.append(f"Instance at {path} does not match any type in union: {union_errors}")
251
+ return self.errors
252
+
253
+ if not isinstance(schema_type, str):
254
+ self.errors.append(f"Schema at {path} has invalid 'type'")
255
+ return self.errors # Process $extends. [Metaschema: $extends in ObjectType/TupleType]
256
+ if schema_type != "choice" and "$extends" in schema:
257
+ base = self._resolve_ref(schema["$extends"])
258
+ if base is None:
259
+ self.errors.append(f"Cannot resolve $extends {schema['$extends']} at {path}")
260
+ return self.errors
261
+ base_props = base.get("properties", {})
262
+ derived_props = schema.get("properties", {})
263
+ for key in base_props:
264
+ if key in derived_props:
265
+ self.errors.append(
266
+ f"Property '{key}' is inherited via $extends and must not be redefined at {path}")
267
+ merged = dict(base)
268
+ merged.update(schema)
269
+ # Properly merge properties: base properties + derived properties
270
+ if "properties" in base or "properties" in schema:
271
+ merged_props = dict(base_props)
272
+ merged_props.update(derived_props)
273
+ merged["properties"] = merged_props
274
+ merged.pop("$extends", None)
275
+ merged.pop("abstract", None)
276
+ schema = merged
277
+
278
+ # Reject abstract schemas. [Metaschema: abstract property]
279
+ if schema.get("abstract") is True:
280
+ self.errors.append(f"Abstract schema at {path} cannot be used for instance validation")
281
+ return self.errors
282
+
283
+ # Process $uses add-in. [Metaschema: $offers and $uses]
284
+ if isinstance(instance, dict) and "$uses" in instance:
285
+ schema = self._apply_uses(schema, instance)
286
+ instance.pop("$uses")
287
+
288
+ # --- Begin type-based validation ---
289
+ # Primitive types.
290
+ if schema_type == "any":
291
+ pass
292
+ elif schema_type == "string":
293
+ if not isinstance(instance, str):
294
+ self.errors.append(f"Expected string at {path}, got {type(instance).__name__}")
295
+ elif schema_type == "number":
296
+ if isinstance(instance, bool) or not isinstance(instance, (int, float)):
297
+ self.errors.append(f"Expected number at {path}, got {type(instance).__name__}")
298
+ elif schema_type == "boolean":
299
+ if not isinstance(instance, bool):
300
+ self.errors.append(f"Expected boolean at {path}, got {type(instance).__name__}")
301
+ elif schema_type == "null":
302
+ if instance is not None:
303
+ self.errors.append(f"Expected null at {path}, got {type(instance).__name__}")
304
+ elif schema_type == "int8":
305
+ if not isinstance(instance, int):
306
+ self.errors.append(f"Expected int8 at {path}, got {type(instance).__name__}")
307
+ elif not (-2**7 <= instance <= 2**7 - 1):
308
+ self.errors.append(f"int8 value at {path} out of range")
309
+ elif schema_type == "uint8":
310
+ if not isinstance(instance, int):
311
+ self.errors.append(f"Expected uint8 at {path}, got {type(instance).__name__}")
312
+ elif not (0 <= instance <= 2**8 - 1):
313
+ self.errors.append(f"uint8 value at {path} out of range")
314
+ elif schema_type == "int16":
315
+ if not isinstance(instance, int):
316
+ self.errors.append(f"Expected int16 at {path}, got {type(instance).__name__}")
317
+ elif not (-2**15 <= instance <= 2**15 - 1):
318
+ self.errors.append(f"int16 value at {path} out of range")
319
+ elif schema_type == "uint16":
320
+ if not isinstance(instance, int):
321
+ self.errors.append(f"Expected uint16 at {path}, got {type(instance).__name__}")
322
+ elif not (0 <= instance <= 2**16 - 1):
323
+ self.errors.append(f"uint16 value at {path} out of range")
324
+ elif schema_type == "int32" or schema_type == "integer":
325
+ if not isinstance(instance, int):
326
+ self.errors.append(f"Expected {schema_type} at {path}, got {type(instance).__name__}")
327
+ elif not (-2**31 <= instance <= 2**31 - 1):
328
+ self.errors.append(f"{schema_type} value at {path} out of range")
329
+ elif schema_type == "uint32":
330
+ if not isinstance(instance, int):
331
+ self.errors.append(f"Expected uint32 at {path}, got {type(instance).__name__}")
332
+ elif not (0 <= instance <= 2**32 - 1):
333
+ self.errors.append(f"uint32 value at {path} out of range")
334
+ elif schema_type == "int64":
335
+ if not isinstance(instance, str):
336
+ self.errors.append(f"Expected int64 as string at {path}, got {type(instance).__name__}")
337
+ else:
338
+ try:
339
+ value = int(instance)
340
+ if not (-2**63 <= value <= 2**63 - 1):
341
+ self.errors.append(f"int64 value at {path} out of range")
342
+ except ValueError:
343
+ self.errors.append(f"Invalid int64 format at {path}")
344
+ elif schema_type == "uint64":
345
+ if not isinstance(instance, str):
346
+ self.errors.append(f"Expected uint64 as string at {path}, got {type(instance).__name__}")
347
+ else:
348
+ try:
349
+ value = int(instance)
350
+ if not (0 <= value <= 2**64 - 1):
351
+ self.errors.append(f"uint64 value at {path} out of range")
352
+ except ValueError:
353
+ self.errors.append(f"Invalid uint64 format at {path}")
354
+ elif schema_type == "int128":
355
+ if not isinstance(instance, str):
356
+ self.errors.append(f"Expected int128 as string at {path}, got {type(instance).__name__}")
357
+ else:
358
+ try:
359
+ value = int(instance)
360
+ if not (-2**127 <= value <= 2**127 - 1):
361
+ self.errors.append(f"int128 value at {path} out of range")
362
+ except ValueError:
363
+ self.errors.append(f"Invalid int128 format at {path}")
364
+ elif schema_type == "uint128":
365
+ if not isinstance(instance, str):
366
+ self.errors.append(f"Expected uint128 as string at {path}, got {type(instance).__name__}")
367
+ else:
368
+ try:
369
+ value = int(instance)
370
+ if not (0 <= value <= 2**128 - 1):
371
+ self.errors.append(f"uint128 value at {path} out of range")
372
+ except ValueError:
373
+ self.errors.append(f"Invalid uint128 format at {path}")
374
+ elif schema_type == "float8":
375
+ if not isinstance(instance, (int, float)):
376
+ self.errors.append(f"Expected float8 at {path}, got {type(instance).__name__}")
377
+ elif schema_type in ("float", "double"):
378
+ if not isinstance(instance, (int, float)):
379
+ self.errors.append(f"Expected {schema_type} at {path}, got {type(instance).__name__}")
380
+ elif schema_type == "decimal":
381
+ if not isinstance(instance, str):
382
+ self.errors.append(f"Expected decimal as string at {path}, got {type(instance).__name__}")
383
+ else:
384
+ try:
385
+ float(instance)
386
+ except ValueError:
387
+ self.errors.append(f"Invalid decimal format at {path}")
388
+ elif schema_type == "date":
389
+ if not isinstance(instance, str) or not _DATE_REGEX.match(instance):
390
+ self.errors.append(f"Expected date (YYYY-MM-DD) at {path}")
391
+ elif schema_type == "datetime":
392
+ if not isinstance(instance, str) or not _DATETIME_REGEX.match(instance):
393
+ self.errors.append(f"Expected datetime (RFC3339) at {path}")
394
+ elif schema_type == "time":
395
+ if not isinstance(instance, str) or not _TIME_REGEX.match(instance):
396
+ self.errors.append(f"Expected time (HH:MM:SS) at {path}")
397
+ elif schema_type == "duration":
398
+ if not isinstance(instance, str):
399
+ self.errors.append(f"Expected duration as string at {path}")
400
+ elif not _DURATION_REGEX.match(instance):
401
+ self.errors.append(f"Expected duration (ISO 8601 format) at {path}")
402
+ elif schema_type == "uuid":
403
+ if not isinstance(instance, str):
404
+ self.errors.append(f"Expected uuid as string at {path}")
405
+ else:
406
+ try:
407
+ uuid.UUID(instance)
408
+ except ValueError:
409
+ self.errors.append(f"Invalid uuid format at {path}")
410
+ elif schema_type == "uri":
411
+ if not isinstance(instance, str):
412
+ self.errors.append(f"Expected uri as string at {path}")
413
+ else:
414
+ parsed = urlparse(instance)
415
+ if not parsed.scheme:
416
+ self.errors.append(f"Invalid uri format at {path}")
417
+ elif schema_type == "binary":
418
+ if not isinstance(instance, str):
419
+ self.errors.append(f"Expected binary (base64 string) at {path}")
420
+ elif schema_type == "jsonpointer":
421
+ if not isinstance(instance, str) or not _JSONPOINTER_REGEX.match(instance):
422
+ self.errors.append(f"Expected JSON pointer format at {path}")
423
+ # Compound types.
424
+ elif schema_type == "object":
425
+ # Validate schema: properties MUST have at least one entry if present,
426
+ # unless the schema uses $extends (properties may be inherited)
427
+ if "properties" in schema:
428
+ props_def = schema["properties"]
429
+ if not isinstance(props_def, dict) or (len(props_def) == 0 and "$extends" not in schema):
430
+ self.errors.append(f"Object schema at {path} has 'properties' but it is empty - properties MUST have at least one entry")
431
+ return self.errors
432
+
433
+ if not isinstance(instance, dict):
434
+ self.errors.append(f"Expected object at {path}, got {type(instance).__name__}")
435
+ else:
436
+ props = schema.get("properties", {})
437
+ req = schema.get("required", [])
438
+ for r in req:
439
+ if r not in instance:
440
+ self.errors.append(f"Missing required property '{r}' at {path}")
441
+ for prop, prop_schema in props.items():
442
+ if prop in instance:
443
+ self.validate_instance(instance[prop], prop_schema, f"{path}/{prop}")
444
+ if "additionalProperties" in schema:
445
+ addl = schema["additionalProperties"]
446
+ if addl is False:
447
+ for key in instance.keys():
448
+ if key not in props:
449
+ self.errors.append(f"Additional property '{key}' not allowed at {path}")
450
+ elif isinstance(addl, dict):
451
+ for key in instance.keys():
452
+ if key not in props:
453
+ self.validate_instance(instance[key], addl, f"{path}/{key}")
454
+ # Extended object constraint: "has" keyword. [Metaschema: ObjectValidationAddIn]
455
+ if "has" in schema:
456
+ has_schema = schema["has"]
457
+ valid = any(len(self.validate_instance(val, has_schema, f"{path}/{prop}")) == 0
458
+ for prop, val in instance.items())
459
+ if not valid:
460
+ self.errors.append(f"Object at {path} does not have any property satisfying 'has' schema")
461
+ # dependencies (dependentRequired) validation
462
+ if "dependentRequired" in schema and isinstance(schema["dependentRequired"], dict):
463
+ for prop_name, required_deps in schema["dependentRequired"].items():
464
+ if prop_name in instance and isinstance(required_deps, list):
465
+ for dep in required_deps:
466
+ if dep not in instance:
467
+ self.errors.append(
468
+ f"Property '{prop_name}' at {path} requires dependent property '{dep}'")
469
+ elif schema_type == "array":
470
+ if not isinstance(instance, list):
471
+ self.errors.append(f"Expected array at {path}, got {type(instance).__name__}")
472
+ else:
473
+ items_schema = schema.get("items")
474
+ if items_schema:
475
+ for idx, item in enumerate(instance):
476
+ self.validate_instance(item, items_schema, f"{path}[{idx}]")
477
+ elif schema_type == "set":
478
+ if not isinstance(instance, list):
479
+ self.errors.append(f"Expected set (unique array) at {path}, got {type(instance).__name__}")
480
+ else:
481
+ serialized = [json.dumps(x, sort_keys=True) for x in instance]
482
+ if len(serialized) != len(set(serialized)):
483
+ self.errors.append(f"Set at {path} contains duplicate items")
484
+ items_schema = schema.get("items")
485
+ if items_schema:
486
+ for idx, item in enumerate(instance):
487
+ self.validate_instance(item, items_schema, f"{path}[{idx}]")
488
+ elif schema_type == "map":
489
+ if not isinstance(instance, dict):
490
+ self.errors.append(f"Expected map (object) at {path}, got {type(instance).__name__}")
491
+ else:
492
+ # Map keys MAY be any valid JSON string (no restrictions on key format)
493
+ values_schema = schema.get("values")
494
+ if values_schema:
495
+ for key, val in instance.items():
496
+ self.validate_instance(val, values_schema, f"{path}/{key}")
497
+ elif schema_type == "tuple":
498
+ if not isinstance(instance, list):
499
+ self.errors.append(f"Expected tuple (array) at {path}, got {type(instance).__name__}")
500
+ else:
501
+ # Retrieve the tuple ordering
502
+ order = schema.get("tuple")
503
+ props = schema.get("properties", {})
504
+ if order is None:
505
+ self.errors.append(f"Tuple schema at {path} is missing the required 'tuple' keyword for ordering")
506
+ elif not isinstance(order, list):
507
+ self.errors.append(f"'tuple' keyword at {path} must be an array of property names")
508
+ else:
509
+ # Verify each name in order exists in properties
510
+ for prop_name in order:
511
+ if prop_name not in props:
512
+ self.errors.append(f"Tuple order key '{prop_name}' at {path} not defined in properties")
513
+ expected_len = len(order)
514
+ if len(instance) != expected_len:
515
+ self.errors.append(f"Tuple at {path} length {len(instance)} does not equal expected {expected_len}")
516
+ else:
517
+ for idx, prop_name in enumerate(order):
518
+ prop_schema = props[prop_name]
519
+ self.validate_instance(instance[idx], prop_schema, f"{path}/{prop_name}")
520
+ elif schema_type == "choice":
521
+ if not isinstance(instance, dict):
522
+ self.errors.append(f"Expected choice object at {path}, got {type(instance).__name__}")
523
+ else:
524
+ choices = schema.get("choices", {})
525
+ extends = schema.get("$extends")
526
+ selector = schema.get("selector")
527
+ if extends is None:
528
+ # Tagged union: exactly one property matching a choice key
529
+ if len(instance) != 1:
530
+ self.errors.append(f"Tagged union at {path} must have a single property")
531
+ else:
532
+ key, value = next(iter(instance.items()))
533
+ if key not in choices:
534
+ self.errors.append(f"Property '{key}' at {path} not one of choices {list(choices.keys())}")
535
+ else:
536
+ self.validate_instance(value, choices[key], f"{path}/{key}")
537
+ else:
538
+ # Inline union: must have selector property
539
+ if selector is None:
540
+ self.errors.append(f"Inline union at {path} missing 'selector' in schema")
541
+ else:
542
+ sel_val = instance.get(selector)
543
+ if not isinstance(sel_val, str):
544
+ self.errors.append(f"Selector '{selector}' at {path} must be a string")
545
+ elif sel_val not in choices:
546
+ self.errors.append(f"Selector '{sel_val}' at {path} not one of choices {list(choices.keys())}")
547
+ else:
548
+ # validate remaining properties against chosen variant
549
+ variant = choices[sel_val]
550
+ inst_copy = dict(instance)
551
+ inst_copy.pop(selector, None)
552
+ self.validate_instance(inst_copy, variant, path)
553
+ else:
554
+ self.errors.append(f"Unsupported type '{schema_type}' at {path}")
555
+
556
+ # --- Enforce extended features if enabled ---
557
+ # Only enable conditional composition if explicitly enabled via $uses or the validation metaschema
558
+ schema_uri = self.root_schema.get("$schema", "")
559
+ is_validation = schema_uri.endswith("/validation/v0/#")
560
+ is_extended = schema_uri.endswith("/extended/v0/#")
561
+ # Only enable if:
562
+ # - self.extended is set (CLI override)
563
+ # - validation metaschema (enables both addins by default)
564
+ # - $uses in schema explicitly enables the addin
565
+ enable_conditional = (
566
+ self.extended or
567
+ is_validation or
568
+ (isinstance(schema, dict) and "$uses" in schema and (
569
+ "JSONStructureConditionalComposition" in schema["$uses"] or "JSONStructureValidation" in schema["$uses"]
570
+ ))
571
+ )
572
+ # If the schema is the extended metaschema and has any conditional composition keyword but does NOT have $uses, this is an error (per spec)
573
+ conditional_keywords = ("allOf", "anyOf", "oneOf", "not", "if", "then", "else")
574
+ if is_extended and any(k in schema for k in conditional_keywords):
575
+ if not (isinstance(schema, dict) and "$uses" in schema and "JSONStructureConditionalComposition" in schema["$uses"]):
576
+ self.errors.append(
577
+ "Conditional composition is not enabled: $uses must include 'JSONStructureConditionalComposition' for the extended metaschema")
578
+ return self.errors
579
+ if enable_conditional:
580
+ # Conditional composition (allOf, anyOf, oneOf, not, if/then/else)
581
+ if ("JSONStructureConditionalComposition" in self.enabled_extensions or
582
+ is_validation or
583
+ (isinstance(schema, dict) and "$uses" in schema and "JSONStructureConditionalComposition" in schema["$uses"])):
584
+ self._validate_conditionals(schema, instance, path)
585
+ # Validation keywords (min/max, pattern, etc.)
586
+ if ("JSONStructureValidation" in self.enabled_extensions or
587
+ is_validation or
588
+ (isinstance(schema, dict) and "$uses" in schema and "JSONStructureValidation" in schema["$uses"])):
589
+ self._validate_validation_addins(schema, instance, path)
590
+
591
+ if "const" in schema:
592
+ if instance != schema["const"]:
593
+ self.errors.append(f"Value at {path} does not equal const {schema['const']}")
594
+ if "enum" in schema:
595
+ if instance not in schema["enum"]:
596
+ self.errors.append(f"Value at {path} not in enum {schema['enum']}")
597
+ return self.errors
598
+
599
+ def validate(self, instance, schema=None):
600
+ if schema is None:
601
+ schema = self.root_schema
602
+ errors = []
603
+ # Extended: conditional composition
604
+ if self.extended and "JSONStructureConditionalComposition" in self.enabled_extensions:
605
+ for key in ("allOf", "anyOf", "oneOf"):
606
+ if key in schema:
607
+ subschemas = schema[key]
608
+ if key == "allOf":
609
+ for idx, subschema in enumerate(subschemas):
610
+ errors += self.validate(instance, subschema)
611
+ elif key == "anyOf":
612
+ if not any(not self.validate(instance, subschema) for subschema in subschemas):
613
+ errors.append(f"Instance does not match anyOf at {key}")
614
+ elif key == "oneOf":
615
+ matches = sum(1 for subschema in subschemas if not self.validate(instance, subschema))
616
+ if matches != 1:
617
+ errors.append(f"Instance does not match exactly one subschema in oneOf at {key}")
618
+ if "not" in schema:
619
+ if not self.validate(instance, schema["not"]):
620
+ errors.append("Instance must not match 'not' subschema")
621
+ if "if" in schema:
622
+ if not self.validate(instance, schema["if"]):
623
+ if "else" in schema:
624
+ errors += self.validate(instance, schema["else"])
625
+ else:
626
+ if "then" in schema:
627
+ errors += self.validate(instance, schema["then"])
628
+ # Extended: validation keywords
629
+ if self.extended and "JSONStructureValidation" in self.enabled_extensions:
630
+ t = schema.get("type")
631
+ if t == "string":
632
+ if "minLength" in schema and isinstance(instance, str):
633
+ if len(instance) < schema["minLength"]:
634
+ errors.append(f"String shorter than minLength {schema['minLength']}")
635
+ if "pattern" in schema and isinstance(instance, str):
636
+ import re
637
+ if not re.match(schema["pattern"], instance):
638
+ errors.append(f"String does not match pattern {schema['pattern']}")
639
+ if t in ("number", "integer", "float", "double", "float8", "decimal",
640
+ "int8", "uint8", "int16", "uint16", "int32", "uint32",
641
+ "int64", "uint64", "int128", "uint128"):
642
+ if "minimum" in schema and instance < schema["minimum"]:
643
+ errors.append(f"Number less than minimum {schema['minimum']}")
644
+ if "maximum" in schema and instance > schema["maximum"]:
645
+ errors.append(f"Number greater than maximum {schema['maximum']}")
646
+ if "multipleOf" in schema and instance % schema["multipleOf"] != 0:
647
+ errors.append(f"Number not a multiple of {schema['multipleOf']}")
648
+ if t == "array":
649
+ if "minItems" in schema and len(instance) < schema["minItems"]:
650
+ errors.append(f"Array has fewer than minItems {schema['minItems']}")
651
+ if "maxItems" in schema and len(instance) > schema["maxItems"]:
652
+ errors.append(f"Array has more than maxItems {schema['maxItems']}")
653
+ if "uniqueItems" in schema and schema["uniqueItems"]:
654
+ if len(instance) != len(set(map(str, instance))):
655
+ errors.append("Array items are not unique")
656
+ return errors
657
+
658
+ def _validate_conditionals(self, schema, instance, path) -> bool:
659
+ """
660
+ Validates conditional composition keywords: allOf, anyOf, oneOf, not, if/then/else.
661
+ [Metaschema: JSON Structure Conditional Composition]
662
+ returns True if the instance contains any conditional composition keywords
663
+ """
664
+ hasConditionals = False
665
+ if "allOf" in schema:
666
+ hasConditionals = True
667
+ subschemas = schema["allOf"]
668
+ for idx, subschema in enumerate(subschemas):
669
+ backup = list(self.errors)
670
+ # Ensure subschema inherits validation context from parent
671
+ enhanced_subschema = dict(subschema)
672
+ if self.root_schema.get("$uses"):
673
+ if "$uses" not in enhanced_subschema:
674
+ enhanced_subschema["$uses"] = list(self.root_schema["$uses"])
675
+ else:
676
+ # Merge validation addins
677
+ for addin in self.root_schema["$uses"]:
678
+ if addin not in enhanced_subschema["$uses"]:
679
+ enhanced_subschema["$uses"].append(addin)
680
+ self.validate_instance(instance, enhanced_subschema, f"{path}/allOf[{idx}]")
681
+ if self.errors:
682
+ self.errors = backup + self.errors
683
+ if "anyOf" in schema:
684
+ hasConditionals = True
685
+ subschemas = schema["anyOf"]
686
+ valid = False
687
+ errors_any = []
688
+ for idx, subschema in enumerate(subschemas):
689
+ backup = list(self.errors)
690
+ self.errors = []
691
+ # Ensure subschema inherits validation context from parent
692
+ enhanced_subschema = dict(subschema)
693
+ if self.root_schema.get("$uses"):
694
+ if "$uses" not in enhanced_subschema:
695
+ enhanced_subschema["$uses"] = list(self.root_schema["$uses"])
696
+ else:
697
+ # Merge validation addins
698
+ for addin in self.root_schema["$uses"]:
699
+ if addin not in enhanced_subschema["$uses"]:
700
+ enhanced_subschema["$uses"].append(addin)
701
+ self.validate_instance(instance, enhanced_subschema, f"{path}/anyOf[{idx}]")
702
+ if not self.errors:
703
+ valid = True
704
+ break
705
+ else:
706
+ errors_any.append(f"anyOf[{idx}]: {self.errors}")
707
+ self.errors = backup
708
+ if not valid:
709
+ self.errors.append(f"Instance at {path} does not satisfy anyOf: {errors_any}")
710
+ if "oneOf" in schema:
711
+ hasConditionals = True
712
+ subschemas = schema["oneOf"]
713
+ valid_count = 0
714
+ errors_one = []
715
+ for idx, subschema in enumerate(subschemas):
716
+ backup = list(self.errors)
717
+ self.errors = []
718
+ # Ensure subschema inherits validation context from parent
719
+ enhanced_subschema = dict(subschema)
720
+ if self.root_schema.get("$uses"):
721
+ if "$uses" not in enhanced_subschema:
722
+ enhanced_subschema["$uses"] = list(self.root_schema["$uses"])
723
+ else:
724
+ # Merge validation addins
725
+ for addin in self.root_schema["$uses"]:
726
+ if addin not in enhanced_subschema["$uses"]:
727
+ enhanced_subschema["$uses"].append(addin)
728
+ self.validate_instance(instance, enhanced_subschema, f"{path}/oneOf[{idx}]")
729
+ if not self.errors:
730
+ valid_count += 1
731
+ else:
732
+ errors_one.append(f"oneOf[{idx}]: {self.errors}")
733
+ self.errors = backup
734
+ if valid_count != 1:
735
+ self.errors.append(
736
+ f"Instance at {path} must match exactly one subschema in oneOf; matched {valid_count}. Details: {errors_one}")
737
+ if "not" in schema:
738
+ hasConditionals = True
739
+ subschema = schema["not"]
740
+ backup = list(self.errors)
741
+ self.errors = []
742
+ self.validate_instance(instance, subschema, f"{path}/not")
743
+ if not self.errors:
744
+ self.errors = backup + [f"Instance at {path} should not validate against 'not' schema"]
745
+ else:
746
+ self.errors = backup
747
+ if "if" in schema:
748
+ hasConditionals = True
749
+ backup = list(self.errors)
750
+ self.errors = []
751
+ self.validate_instance(instance, schema["if"], f"{path}/if")
752
+ if_valid = not self.errors
753
+ self.errors = backup
754
+ if if_valid:
755
+ if "then" in schema:
756
+ self.validate_instance(instance, schema["then"], f"{path}/then")
757
+ else:
758
+ if "else" in schema:
759
+ self.validate_instance(instance, schema["else"], f"{path}/else")
760
+ return hasConditionals
761
+
762
+ def _validate_validation_addins(self, schema, instance, path):
763
+ """
764
+ Validates additional constraints defined by the JSONStructureValidation addins.
765
+ [Metaschema: JSON Structure JSONStructureValidation]
766
+ """
767
+ # Numeric constraints.
768
+ if schema.get("type") in ("number", "integer", "float", "double", "decimal",
769
+ "int8", "uint8", "int16", "uint16", "int32", "uint32",
770
+ "int64", "uint64", "int128", "uint128", "float8"):
771
+ if "minimum" in schema:
772
+ try:
773
+ if instance < schema["minimum"]:
774
+ self.errors.append(f"Value at {path} is less than minimum {schema['minimum']}")
775
+ except Exception:
776
+ self.errors.append(f"Cannot compare value at {path} with minimum constraint")
777
+ if "maximum" in schema:
778
+ try:
779
+ if instance > schema["maximum"]:
780
+ self.errors.append(f"Value at {path} is greater than maximum {schema['maximum']}")
781
+ except Exception:
782
+ self.errors.append(f"Cannot compare value at {path} with maximum constraint")
783
+ if schema.get("exclusiveMinimum") is True:
784
+ try:
785
+ if instance <= schema.get("minimum", float("-inf")):
786
+ self.errors.append(
787
+ f"Value at {path} is not greater than exclusive minimum {schema.get('minimum')}")
788
+ except Exception:
789
+ self.errors.append(f"Cannot evaluate exclusiveMinimum constraint at {path}")
790
+ if schema.get("exclusiveMaximum") is True:
791
+ try:
792
+ if instance >= schema.get("maximum", float("inf")): self.errors.append(
793
+ f"Value at {path} is not less than exclusive maximum {schema.get('maximum')}")
794
+ except Exception:
795
+ self.errors.append(f"Cannot evaluate exclusiveMaximum constraint at {path}")
796
+ if "multipleOf" in schema:
797
+ try:
798
+ # Handle floating point precision issues
799
+ multiple_of = schema["multipleOf"]
800
+ quotient = instance / multiple_of
801
+ # Check if the quotient is close to an integer within a small tolerance
802
+ if abs(quotient - round(quotient)) > 1e-10:
803
+ self.errors.append(f"Value at {path} is not a multiple of {schema['multipleOf']}")
804
+ except Exception:
805
+ self.errors.append(f"Cannot evaluate multipleOf constraint at {path}")
806
+
807
+ # String constraints.
808
+ if schema.get("type") == "string":
809
+ if "minLength" in schema:
810
+ try:
811
+ if len(instance) < schema["minLength"]:
812
+ self.errors.append(f"String at {path} shorter than minLength {schema['minLength']}")
813
+ except TypeError:
814
+ self.errors.append(f"Invalid minLength constraint at {path}")
815
+ if "maxLength" in schema:
816
+ try:
817
+ if len(instance) > schema["maxLength"]:
818
+ self.errors.append(f"String at {path} exceeds maxLength {schema['maxLength']}")
819
+ except TypeError:
820
+ self.errors.append(f"Invalid maxLength constraint at {path}")
821
+ if "pattern" in schema:
822
+ try:
823
+ pattern = re.compile(schema["pattern"])
824
+ if not pattern.search(instance):
825
+ self.errors.append(f"String at {path} does not match pattern {schema['pattern']}")
826
+ except (re.error, TypeError):
827
+ self.errors.append(f"Invalid pattern constraint at {path}")
828
+ if "format" in schema:
829
+ fmt = schema["format"]
830
+ try:
831
+ if fmt == "email":
832
+ # Simple email validation
833
+ if "@" not in instance or not re.match(r'^[^@]+@[^@]+\.[^@]+$', instance):
834
+ self.errors.append(f"String at {path} does not match format email")
835
+ elif fmt == "ipv4":
836
+ # IPv4 validation
837
+ parts = instance.split('.')
838
+ if len(parts) != 4 or not all(0 <= int(part) <= 255 for part in parts):
839
+ self.errors.append(f"String at {path} does not match format ipv4")
840
+ elif fmt == "ipv6":
841
+ # Basic IPv6 validation
842
+ if not re.match(r'^[0-9a-fA-F:]+$', instance):
843
+ self.errors.append(f"String at {path} does not match format ipv6")
844
+ elif fmt == "uri":
845
+ parsed = urlparse(instance)
846
+ if not parsed.scheme:
847
+ self.errors.append(f"String at {path} does not match format uri")
848
+ elif fmt == "hostname":
849
+ if not re.match(r'^[a-zA-Z0-9.-]+$', instance):
850
+ self.errors.append(f"String at {path} does not match format hostname")
851
+ # Add more format validations as needed
852
+ except (ValueError, TypeError):
853
+ self.errors.append(f"String at {path} does not match format {fmt}") # Array constraints.
854
+ if schema.get("type") == "array":
855
+ if "minItems" in schema:
856
+ if len(instance) < schema["minItems"]:
857
+ self.errors.append(f"Array at {path} has fewer items than minItems {schema['minItems']}")
858
+ if "maxItems" in schema:
859
+ if len(instance) > schema["maxItems"]:
860
+ self.errors.append(f"Array at {path} has more items than maxItems {schema['maxItems']}")
861
+ if schema.get("uniqueItems") is True:
862
+ serialized = [json.dumps(x, sort_keys=True) for x in instance]
863
+ if len(serialized) != len(set(serialized)):
864
+ self.errors.append(f"Array at {path} does not have unique items")
865
+
866
+ # contains validation
867
+ if "contains" in schema:
868
+ contains_schema = schema["contains"]
869
+ matches = []
870
+ for i, item in enumerate(instance):
871
+ temp_validator = JSONStructureInstanceValidator(contains_schema, import_map=self.import_map, allow_import=self.allow_import, external_schemas=list(self.external_schemas.values()) if self.external_schemas else None)
872
+ item_errors = temp_validator.validate_instance(item)
873
+ if not item_errors:
874
+ matches.append(i)
875
+
876
+ if not matches:
877
+ self.errors.append(f"Array at {path} does not contain required element")
878
+
879
+ # minContains validation
880
+ if "minContains" in schema:
881
+ if len(matches) < schema["minContains"]:
882
+ self.errors.append(f"Array at {path} contains fewer than minContains {schema['minContains']} matching elements")
883
+
884
+ # maxContains validation
885
+ if "maxContains" in schema:
886
+ if len(matches) > schema["maxContains"]:
887
+ self.errors.append(f"Array at {path} contains more than maxContains {schema['maxContains']} matching elements")
888
+ # Object constraints.
889
+ if schema.get("type") == "object":
890
+ if "minProperties" in schema:
891
+ if len(instance.keys()) < schema["minProperties"]:
892
+ self.errors.append(
893
+ f"Object at {path} has fewer properties than minProperties {schema['minProperties']}")
894
+ if "maxProperties" in schema:
895
+ if len(instance.keys()) > schema["maxProperties"]:
896
+ self.errors.append(
897
+ f"Object at {path} has more properties than maxProperties {schema['maxProperties']}")
898
+
899
+ # patternProperties validation
900
+ if "patternProperties" in schema and isinstance(schema["patternProperties"], dict):
901
+ for pattern_str, pattern_schema in schema["patternProperties"].items():
902
+ try:
903
+ pattern = re.compile(pattern_str)
904
+ for prop_name, prop_value in instance.items():
905
+ if pattern.search(prop_name):
906
+ self.validate_instance(prop_value, pattern_schema, f"{path}/{prop_name}")
907
+ except re.error:
908
+ self.errors.append(f"Invalid regular expression '{pattern_str}' in patternProperties at {path}")
909
+
910
+ # propertyNames validation
911
+ if "propertyNames" in schema:
912
+ property_names_schema = schema["propertyNames"]
913
+ if not isinstance(property_names_schema, dict) or property_names_schema.get("type") != "string":
914
+ self.errors.append(f"propertyNames schema must be of type string at {path}")
915
+ else:
916
+ for prop_name in instance.keys():
917
+ self.validate_instance(prop_name, property_names_schema, f"{path}/propertyName({prop_name})")
918
+
919
+ # dependencies (dependentRequired) validation
920
+ if "dependentRequired" in schema and isinstance(schema["dependentRequired"], dict):
921
+ for prop_name, required_deps in schema["dependentRequired"].items():
922
+ if prop_name in instance and isinstance(required_deps, list):
923
+ for dep in required_deps:
924
+ if dep not in instance:
925
+ self.errors.append(
926
+ f"Property '{prop_name}' at {path} requires dependent property '{dep}'") # Map constraints
927
+ if schema.get("type") == "map":
928
+ # minEntries and maxEntries validation
929
+ if "minEntries" in schema:
930
+ if len(instance) < schema["minEntries"]:
931
+ self.errors.append(f"Map at {path} has fewer than minEntries {schema['minEntries']}")
932
+ if "maxEntries" in schema:
933
+ if len(instance) > schema["maxEntries"]:
934
+ self.errors.append(f"Map at {path} has more than maxEntries {schema['maxEntries']}")
935
+
936
+ # patternKeys validation
937
+ if "patternKeys" in schema and isinstance(schema["patternKeys"], dict):
938
+ for pattern_str, pattern_schema in schema["patternKeys"].items():
939
+ try:
940
+ pattern = re.compile(pattern_str)
941
+ for key_name, key_value in instance.items():
942
+ if pattern.search(key_name):
943
+ self.validate_instance(key_value, pattern_schema, f"{path}/{key_name}")
944
+ except re.error:
945
+ self.errors.append(f"Invalid regular expression '{pattern_str}' in patternKeys at {path}")
946
+
947
+ # keyNames validation
948
+ if "keyNames" in schema:
949
+ key_names_schema = schema["keyNames"]
950
+ if not isinstance(key_names_schema, dict) or key_names_schema.get("type") != "string":
951
+ self.errors.append(f"keyNames schema must be of type string at {path}")
952
+ else:
953
+ for key_name in instance.keys():
954
+ # Ensure validation addins are enabled for keyNames schema validation
955
+ keynames_validation_schema = dict(key_names_schema)
956
+ if "$uses" not in keynames_validation_schema:
957
+ keynames_validation_schema["$uses"] = ["JSONStructureValidation"]
958
+ elif "JSONStructureValidation" not in keynames_validation_schema["$uses"]:
959
+ keynames_validation_schema["$uses"].append("JSONStructureValidation")
960
+
961
+ temp_validator = JSONStructureInstanceValidator(keynames_validation_schema, import_map=self.import_map, allow_import=self.allow_import, external_schemas=list(self.external_schemas.values()) if self.external_schemas else None)
962
+ key_errors = temp_validator.validate_instance(key_name)
963
+ if key_errors:
964
+ self.errors.append(f"Map key name '{key_name}' at {path} does not match keyNames constraint")
965
+
966
+ def _resolve_ref(self, ref):
967
+ """
968
+ Resolves a $ref within the root schema using JSON Pointer syntax.
969
+ [Metaschema: TypeReference]
970
+ :param ref: A JSON pointer string starting with '#'.
971
+ :return: The referenced schema object or None.
972
+ """
973
+ if not ref.startswith("#"):
974
+ return None
975
+ parts = ref.lstrip("#").split("/")
976
+ target = self.root_schema
977
+ for part in parts:
978
+ if part == "":
979
+ continue
980
+ part = part.replace("~1", "/").replace("~0", "~")
981
+ if isinstance(target, dict) and part in target:
982
+ target = target[part]
983
+ else:
984
+ return None
985
+ return target
986
+
987
+ def _rewrite_refs(self, obj, target_path):
988
+ """
989
+ Recursively rewrites $ref pointers in an imported schema to be relative to the target path.
990
+ When a schema is imported at path (e.g., #/definitions/People), all internal $ref pointers
991
+ like #/definitions/X or #/X need to be rewritten to point to target_path/X.
992
+ [Metaschema: JSONStructureImport extension - reference rewriting]
993
+ :param obj: The imported schema object to rewrite.
994
+ :param target_path: The JSON pointer path where the schema is being imported (e.g., "#/definitions/People").
995
+ """
996
+ if isinstance(obj, dict):
997
+ for key, value in obj.items():
998
+ if key == "$ref" and isinstance(value, str) and value.startswith("#"):
999
+ # Rewrite the $ref to be relative to target_path
1000
+ # Original ref like "#/definitions/Address" or "#/Address"
1001
+ # needs to become "target_path/Address"
1002
+ ref_parts = value.lstrip("#").split("/")
1003
+ # Get the final referenced name (last part of the path)
1004
+ if ref_parts and ref_parts[-1]:
1005
+ ref_name = ref_parts[-1]
1006
+ # Rewrite to point to the same name under target_path
1007
+ obj[key] = f"{target_path}/{ref_name}"
1008
+ elif key == "$extends" and isinstance(value, str) and value.startswith("#"):
1009
+ # Also rewrite $extends references
1010
+ ref_parts = value.lstrip("#").split("/")
1011
+ if ref_parts and ref_parts[-1]:
1012
+ ref_name = ref_parts[-1]
1013
+ obj[key] = f"{target_path}/{ref_name}"
1014
+ else:
1015
+ self._rewrite_refs(value, target_path)
1016
+ elif isinstance(obj, list):
1017
+ for item in obj:
1018
+ self._rewrite_refs(item, target_path)
1019
+
1020
+ def _process_imports(self, obj, path):
1021
+ """
1022
+ Recursively processes $import and $importdefs keywords in the schema.
1023
+ [Metaschema: JSONStructureImport extension constructs]
1024
+ Merges imported definitions appropriately:
1025
+ - If the import is at the root level, definitions go into obj["definitions"]
1026
+ - If the import is inside a namespace (e.g., definitions/People), definitions merge directly into obj
1027
+ Uses self.import_map if the URI is mapped to a local file.
1028
+ After merging, $ref pointers in the imported content are rewritten to point
1029
+ to their new locations in the merged document.
1030
+ """
1031
+ if isinstance(obj, dict):
1032
+ for key in list(obj.keys()):
1033
+ if key in ("$import", "$importdefs"):
1034
+ if not self.allow_import:
1035
+ self.errors.append(
1036
+ f"JSONStructureImport keyword '{key}' encountered but allow_import not enabled at {path}/{key}")
1037
+ continue
1038
+ uri = obj[key]
1039
+ if not isinstance(uri, str):
1040
+ self.errors.append(f"JSONStructureImport keyword '{key}' value must be a string URI at {path}/{key}")
1041
+ continue
1042
+ # Allow relative URIs if they're in import_map or external_schemas
1043
+ if not self.ABSOLUTE_URI_REGEX.search(uri):
1044
+ if uri not in self.import_map and uri not in self.external_schemas:
1045
+ self.errors.append(f"JSONStructureImport keyword '{key}' value must be an absolute URI at {path}/{key}")
1046
+ continue
1047
+ external = self._fetch_external_schema(uri)
1048
+ if external is None:
1049
+ self.errors.append(f"Unable to fetch external schema from {uri} at {path}/{key}")
1050
+ continue
1051
+ if key == "$import":
1052
+ imported_defs = {}
1053
+ if "type" in external and "name" in external:
1054
+ imported_defs[external["name"]] = external
1055
+ if "definitions" in external and isinstance(external["definitions"], dict):
1056
+ imported_defs.update(external["definitions"])
1057
+ else: # $importdefs
1058
+ if "definitions" in external and isinstance(external["definitions"], dict):
1059
+ imported_defs = external["definitions"]
1060
+ else:
1061
+ imported_defs = {}
1062
+ # Determine where to merge and the actual target path for ref rewriting
1063
+ if path == "#":
1064
+ # Root level import - put in definitions
1065
+ target_path = "#/definitions"
1066
+ if "definitions" not in obj:
1067
+ obj["definitions"] = {}
1068
+ merge_target = obj["definitions"]
1069
+ else:
1070
+ # Nested import (e.g., inside a namespace) - merge directly into current object
1071
+ target_path = path
1072
+ merge_target = obj
1073
+ # Rewrite $ref pointers in imported content to point to their new location
1074
+ for k, v in imported_defs.items():
1075
+ if isinstance(v, dict):
1076
+ # Deep copy to avoid modifying cached schemas
1077
+ import copy
1078
+ v = copy.deepcopy(v)
1079
+ self._rewrite_refs(v, target_path)
1080
+ imported_defs[k] = v
1081
+ # Merge imported definitions
1082
+ for k, v in imported_defs.items():
1083
+ if k not in merge_target:
1084
+ merge_target[k] = v
1085
+ del obj[key]
1086
+ for k, v in obj.items():
1087
+ self._process_imports(v, f"{path}/{k}")
1088
+ elif isinstance(obj, list):
1089
+ for idx, item in enumerate(obj):
1090
+ self._process_imports(item, f"{path}[{idx}]")
1091
+
1092
+ def _fetch_external_schema(self, uri):
1093
+ """
1094
+ Fetches an external schema from a URI.
1095
+ [Metaschema: JSONStructureImport extension resolution]
1096
+ Resolution order:
1097
+ 1. Check external_schemas (pre-loaded schemas matched by $id)
1098
+ 2. Check import_map (URI to file path mapping)
1099
+ """
1100
+ # First check sideloaded schemas by $id
1101
+ if uri in self.external_schemas:
1102
+ return self.external_schemas[uri]
1103
+ # Then check import_map for file paths
1104
+ if uri in self.import_map:
1105
+ try:
1106
+ with open(self.import_map[uri], "r", encoding="utf-8") as f:
1107
+ return json.load(f)
1108
+ except Exception as e:
1109
+ self.errors.append(f"Failed to load imported schema from {self.import_map[uri]}: {e}")
1110
+ return None
1111
+ # URI not found in external_schemas or import_map
1112
+ return None
1113
+
1114
+ def _apply_uses(self, schema, instance):
1115
+ """
1116
+ Applies add-in types to the effective schema if the instance declares "$uses".
1117
+ [Metaschema: $offers and $uses in SchemaDocument]
1118
+ The $uses keyword is expected to be an array of add-in names.
1119
+ The root schema must have a "$offers" mapping.
1120
+ :param schema: The current schema.
1121
+ :param instance: The instance dict containing "$uses".
1122
+ :return: The merged schema with add-ins applied.
1123
+ """
1124
+ uses = instance.get("$uses")
1125
+ if not uses:
1126
+ return schema
1127
+ if not isinstance(uses, list):
1128
+ uses = [uses]
1129
+ offers = self.root_schema.get("$offers", {})
1130
+ merged = dict(schema)
1131
+ merged.setdefault("properties", {})
1132
+ for use in [u for u in uses if not u in ["JSONStructureValidation", "JSONStructureConditionalComposition", "JSONStructureAlternateNames", "JSONStructureUnits"]]:
1133
+ if use not in offers:
1134
+ self.errors.append(f"Add-in '{use}' not offered in $offers")
1135
+ continue
1136
+ addin = offers[use]
1137
+ if isinstance(addin, list):
1138
+ for ref in addin:
1139
+ resolved = self._resolve_ref(ref) if isinstance(ref, str) else ref
1140
+ if isinstance(resolved, dict):
1141
+ addin_props = resolved.get("properties", {})
1142
+ for prop in addin_props:
1143
+ if prop in merged["properties"]:
1144
+ self.errors.append(
1145
+ f"Add-in property '{prop}' from add-in '{use}' conflicts with existing property")
1146
+ merged["properties"].update(addin_props)
1147
+ elif isinstance(addin, dict) and "$ref" in addin:
1148
+ resolved = self._resolve_ref(addin["$ref"])
1149
+ if isinstance(resolved, dict):
1150
+ addin_props = resolved.get("properties", {})
1151
+ for prop in addin_props:
1152
+ if prop in merged["properties"]:
1153
+ self.errors.append(
1154
+ f"Add-in property '{prop}' from add-in '{use}' conflicts with existing property")
1155
+ merged["properties"].update(addin_props)
1156
+ elif isinstance(addin, dict):
1157
+ addin_props = addin.get("properties", {})
1158
+ for prop in addin_props:
1159
+ if prop in merged["properties"]:
1160
+ self.errors.append(
1161
+ f"Add-in property '{prop}' from add-in '{use}' conflicts with existing property")
1162
+ merged["properties"].update(addin_props)
1163
+ else:
1164
+ self.errors.append(f"Invalid add-in definition for '{use}'")
1165
+ return merged
1166
+
1167
+
1168
+ def main():
1169
+ import argparse
1170
+ parser = argparse.ArgumentParser()
1171
+ parser.add_argument('instance_file')
1172
+ parser.add_argument('schema_file')
1173
+ parser.add_argument('--extended', action='store_true')
1174
+ args = parser.parse_args()
1175
+ import json
1176
+ with open(args.schema_file, 'r', encoding='utf-8') as f:
1177
+ schema = json.load(f)
1178
+ with open(args.instance_file, 'r', encoding='utf-8') as f:
1179
+ instance = json.load(f)
1180
+ validator = JSONStructureInstanceValidator(schema, extended=args.extended)
1181
+ errors = validator.validate(instance)
1182
+ if errors:
1183
+ print("Instance is invalid:")
1184
+ for err in errors:
1185
+ print(" -", err)
1186
+ exit(1)
1187
+ print("Instance is valid.")
1188
+
1189
+
1190
+ if __name__ == "__main__":
1191
+ main()