json-structure 0.1.9__tar.gz → 0.1.11__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: json-structure
3
- Version: 0.1.9
3
+ Version: 0.1.11
4
4
  Summary: Validators for JSON Structure schemas and instances
5
5
  Project-URL: Homepage, https://json-structure.org
6
6
  Project-URL: Documentation, https://github.com/json-structure/sdk
@@ -28,7 +28,7 @@ version_tuple: VERSION_TUPLE
28
28
  commit_id: COMMIT_ID
29
29
  __commit_id__: COMMIT_ID
30
30
 
31
- __version__ = version = '0.1.9'
32
- __version_tuple__ = version_tuple = (0, 1, 9)
31
+ __version__ = version = '0.1.11'
32
+ __version_tuple__ = version_tuple = (0, 1, 11)
33
33
 
34
34
  __commit_id__ = commit_id = None
@@ -101,14 +101,73 @@ class JSONStructureSchemaCoreValidator:
101
101
  # Build lookup for external schemas by $id
102
102
  self.external_schemas = {}
103
103
  if external_schemas:
104
+ import copy
104
105
  for schema in external_schemas:
105
106
  if isinstance(schema, dict) and "$id" in schema:
106
- self.external_schemas[schema["$id"]] = schema
107
+ # Deep copy to avoid modifying the original
108
+ self.external_schemas[schema["$id"]] = copy.deepcopy(schema)
109
+ # Process imports in external schemas (they may import each other)
110
+ # Do multiple passes to handle chained imports
111
+ if allow_import:
112
+ for _ in range(len(self.external_schemas)):
113
+ for schema_id, schema in self.external_schemas.items():
114
+ self._process_imports_in_external_schema(schema)
107
115
  if allow_dollar:
108
116
  self.identifier_regex = re.compile(r'^[A-Za-z_$][A-Za-z0-9_$]*$')
109
117
  else:
110
118
  self.identifier_regex = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$')
111
119
 
120
+ def _process_imports_in_external_schema(self, obj):
121
+ """
122
+ Processes $import and $importdefs in an external schema during initialization.
123
+ This is a simplified version that doesn't track errors, just merges definitions.
124
+ Called on external_schemas during __init__ to ensure imported definitions are available.
125
+ """
126
+ if not isinstance(obj, dict):
127
+ return
128
+
129
+ for key in list(obj.keys()):
130
+ if key in ("$import", "$importdefs"):
131
+ uri = obj[key]
132
+ if not isinstance(uri, str):
133
+ continue
134
+ # Try to fetch from external_schemas
135
+ external = self.external_schemas.get(uri)
136
+ if external is None:
137
+ continue
138
+
139
+ if key == "$import":
140
+ imported_defs = {}
141
+ if "type" in external and "name" in external:
142
+ imported_defs[external["name"]] = external
143
+ if "definitions" in external and isinstance(external["definitions"], dict):
144
+ imported_defs.update(external["definitions"])
145
+ else: # $importdefs
146
+ if "definitions" in external and isinstance(external["definitions"], dict):
147
+ imported_defs = external["definitions"]
148
+ else:
149
+ imported_defs = {}
150
+
151
+ # Merge into definitions at root level
152
+ target_path = "#/definitions"
153
+ if "definitions" not in obj:
154
+ obj["definitions"] = {}
155
+ merge_target = obj["definitions"]
156
+
157
+ # Rewrite refs and merge
158
+ import copy
159
+ for k, v in imported_defs.items():
160
+ if isinstance(v, dict):
161
+ v = copy.deepcopy(v)
162
+ self._rewrite_refs(v, target_path)
163
+ imported_defs[k] = v
164
+
165
+ for k, v in imported_defs.items():
166
+ if k not in merge_target:
167
+ merge_target[k] = v
168
+
169
+ del obj[key]
170
+
112
171
  def validate(self, doc, source_text=None):
113
172
  """
114
173
  Main entry point for validating a JSON Structure Core document.
@@ -220,30 +279,39 @@ class JSONStructureSchemaCoreValidator:
220
279
  def _rewrite_refs(self, obj, target_path):
221
280
  """
222
281
  Recursively rewrites $ref pointers in an imported schema to be relative to the target path.
223
- When a schema is imported at path (e.g., #/definitions/People), all internal $ref pointers
282
+ When a schema is imported at path (e.g., #/definitions), all internal $ref pointers
224
283
  like #/definitions/X or #/X need to be rewritten to point to target_path/X.
284
+ References to nested paths like #/definitions/features/Y are preserved with their structure.
225
285
  [Metaschema: JSONStructureImport extension - reference rewriting]
226
286
  :param obj: The imported schema object to rewrite.
227
- :param target_path: The JSON pointer path where the schema is being imported (e.g., "#/definitions/People").
287
+ :param target_path: The JSON pointer path where the schema is being imported (e.g., "#/definitions").
228
288
  """
229
289
  if isinstance(obj, dict):
230
290
  for key, value in obj.items():
231
291
  if key == "$ref" and isinstance(value, str) and value.startswith("#"):
232
292
  # Rewrite the $ref to be relative to target_path
233
- # Original ref like "#/definitions/Address" or "#/Address"
234
- # needs to become "target_path/Address"
235
- ref_parts = value.lstrip("#").split("/")
236
- # Get the final referenced name (last part of the path)
237
- if ref_parts and ref_parts[-1]:
238
- ref_name = ref_parts[-1]
239
- # Rewrite to point to the same name under target_path
240
- obj[key] = f"{target_path}/{ref_name}"
293
+ # Strip the "#" and split
294
+ ref_parts = value.lstrip("#").lstrip("/").split("/")
295
+ if ref_parts and ref_parts[0]:
296
+ # Skip 'definitions' if present at the start since we're importing into definitions
297
+ if ref_parts[0] == "definitions" and len(ref_parts) > 1:
298
+ # Keep everything after 'definitions'
299
+ remaining_path = "/".join(ref_parts[1:])
300
+ obj[key] = f"{target_path}/{remaining_path}"
301
+ else:
302
+ # For other refs, just append the full path
303
+ remaining_path = "/".join(ref_parts)
304
+ obj[key] = f"{target_path}/{remaining_path}"
241
305
  elif key == "$extends" and isinstance(value, str) and value.startswith("#"):
242
306
  # Also rewrite $extends references
243
- ref_parts = value.lstrip("#").split("/")
244
- if ref_parts and ref_parts[-1]:
245
- ref_name = ref_parts[-1]
246
- obj[key] = f"{target_path}/{ref_name}"
307
+ ref_parts = value.lstrip("#").lstrip("/").split("/")
308
+ if ref_parts and ref_parts[0]:
309
+ if ref_parts[0] == "definitions" and len(ref_parts) > 1:
310
+ remaining_path = "/".join(ref_parts[1:])
311
+ obj[key] = f"{target_path}/{remaining_path}"
312
+ else:
313
+ remaining_path = "/".join(ref_parts)
314
+ obj[key] = f"{target_path}/{remaining_path}"
247
315
  else:
248
316
  self._rewrite_refs(value, target_path)
249
317
  elif isinstance(obj, list):
@@ -317,8 +385,12 @@ class JSONStructureSchemaCoreValidator:
317
385
  if k not in merge_target:
318
386
  merge_target[k] = v
319
387
  del obj[key]
320
- # Recurse into all values.
388
+ # Recurse into all values, but skip recursing into 'properties' values
389
+ # since those contain property name definitions, not import directives
321
390
  for key, value in obj.items():
391
+ # Skip processing inside 'properties' - $import/$importdefs there are property names, not directives
392
+ if key == "properties":
393
+ continue
322
394
  self._process_imports(value, f"{path}/{key}")
323
395
  elif isinstance(obj, list):
324
396
  for idx, item in enumerate(obj):
@@ -330,6 +402,8 @@ class JSONStructureSchemaCoreValidator:
330
402
  Resolution order:
331
403
  1. Check external_schemas (pre-loaded schemas matched by $id)
332
404
  2. Check import_map (URI to file path mapping)
405
+
406
+ When loading from file, recursively processes imports in the loaded schema.
333
407
  """
334
408
  # First check sideloaded schemas by $id
335
409
  if uri in self.external_schemas:
@@ -338,7 +412,15 @@ class JSONStructureSchemaCoreValidator:
338
412
  if uri in self.import_map:
339
413
  try:
340
414
  with open(self.import_map[uri], "r", encoding="utf-8") as f:
341
- return json.load(f)
415
+ import copy
416
+ schema = json.load(f)
417
+ # Deep copy to avoid modifying the original
418
+ schema = copy.deepcopy(schema)
419
+ # Recursively process imports in the loaded schema
420
+ self._process_imports(schema, "#")
421
+ # Cache the processed schema for future use
422
+ self.external_schemas[uri] = schema
423
+ return schema
342
424
  except Exception as e:
343
425
  self._err(f"Failed to load imported schema from {self.import_map[uri]}: {e}", "#/import")
344
426
  return None