any2tosca 0.1.0__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.
any2tosca/converter.py ADDED
@@ -0,0 +1,2060 @@
1
+ """
2
+ converter.py
3
+ ------------
4
+ Core logic for converting JSON Schema documents to TOSCA data types.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ __author__ = "Chris Lauwers"
10
+ __copyright__ = "Copyright (c) 2022-2026, Ubicity Corp."
11
+ __email__ = "info@ubicity.com"
12
+
13
+ import json
14
+ import re
15
+ import sys
16
+ from pathlib import Path
17
+ from typing import Any, NamedTuple
18
+
19
+ from referencing import Registry, Resource
20
+ from referencing.jsonschema import DRAFT7
21
+
22
+ from .yaml_utils import CommentedOut, FoldedStr
23
+
24
+ __all__ = ["Converter", "ConversionResult", "convert_schema", "build_tosca_document", "build_caps_document"]
25
+
26
+
27
+ class ConversionResult(NamedTuple):
28
+ """Holds the output of a schema conversion."""
29
+ data_types: dict[str, Any]
30
+ node_types: dict[str, Any]
31
+ imports: dict[str, str] = {} # namespace → tosca_file
32
+ relationship_types: dict[str, Any] = {} # name → TOSCA relationship type dict
33
+ interface_types: dict[str, Any] = {} # name → TOSCA interface type dict
34
+ capability_types: dict[str, Any] = {} # name → TOSCA capability type dict (for companion caps file)
35
+
36
+
37
+ class Converter:
38
+ """Converts JSON Schema documents to TOSCA data_types."""
39
+
40
+ #: Matches versioned JSON Schema filenames: ``BaseName.vX_Y_Z`` or ``BaseName.vX.Y.Z``.
41
+ _VER_RE = re.compile(r"^(.+)\.v(\d+)[._](\d+)[._](\d+)")
42
+
43
+ JSON_SCHEMA_TO_TOSCA_TYPE: dict[str, str] = {
44
+ "string": "string",
45
+ "integer": "integer",
46
+ "number": "float",
47
+ "boolean": "boolean",
48
+ "object": "map",
49
+ "array": "list",
50
+ "null": "string", # TOSCA has no null; fall back to string
51
+ }
52
+
53
+ #: TOSCA 2.0 built-in primitive and collection types — never node types.
54
+ _TOSCA_PRIMITIVES: frozenset[str] = frozenset({
55
+ "string", "integer", "float", "boolean", "bytes", "timestamp",
56
+ "list", "map",
57
+ "scalar-unit.size", "scalar-unit.time",
58
+ "scalar-unit.frequency", "scalar-unit.bitrate",
59
+ })
60
+
61
+ def __init__(self) -> None:
62
+ self._base_path: Path | None = None
63
+ self._search_paths: list[Path] = [] # additional schema search dirs
64
+ self._imports: dict[str, str] = {} # namespace → tosca_file
65
+ self._no_import_files: set[str] = set() # filenames whose types are treated as local
66
+ self._registry: Registry | None = None # referencing Registry
67
+ self._id_to_path: dict[str, Path] = {} # $id URI → local Path
68
+ self._current_filename: str = "" # filename of the schema being converted
69
+ # Persistent caches (survive across convert_schema calls for the same search dirs)
70
+ self._file_cache: dict[str, str] = {} # abs path → raw text
71
+ self._doc_cache: dict[str, dict[str, Any]] = {}# abs path → parsed JSON
72
+ self._fname_to_path: dict[str, Path | None] = {} # filename → abs Path (or None)
73
+ self._ref_fnames_cache: dict[str, frozenset[str]] = {} # abs path → ext fnames
74
+ self._reachable_cache: dict[str, frozenset[str]] = {} # start_fname → all reachable fnames
75
+ # Per-conversion cache (reset each convert_schema call)
76
+ self._transitive_back_cache: dict[str, bool] = {} # start_fname → bool (for current _current_filename)
77
+ self._back_import_cache: dict[tuple[str, str], bool] = {} # (fname, checking_for) → bool
78
+ # Per-conversion state (reset each convert_schema call)
79
+ self._current_file_refs: frozenset[str] = frozenset() # direct refs of current file (from root_schema)
80
+ self._expanded_link_types: set[str] = set() # types expanded from Links props
81
+ self._relationship_types: dict[str, Any] = {} # name → relationship type dict
82
+ self._interface_types: dict[str, Any] = {} # name → TOSCA interface type dict
83
+ self._capability_types: dict[str, Any] = {} # name → TOSCA capability type dict
84
+ self._type_to_caps: dict[str, tuple[str, str]] = {} # bare_type_name → (caps_ns, caps_file)
85
+ self._node_type_names: set[str] = set() # names that are node types in this file
86
+
87
+ def _all_dirs(self) -> list[Path]:
88
+ """All directories to search for schema files, base path first."""
89
+ dirs: list[Path] = []
90
+ if self._base_path is not None:
91
+ dirs.append(self._base_path)
92
+ dirs.extend(self._search_paths)
93
+ return dirs
94
+
95
+ def _resolve_fname(self, fname: str) -> "Path | None":
96
+ """Resolve *fname* to an absolute Path, caching the result."""
97
+ if fname in self._fname_to_path:
98
+ return self._fname_to_path[fname]
99
+ candidate = next(
100
+ (d / fname for d in self._all_dirs() if (d / fname).exists()), None
101
+ )
102
+ self._fname_to_path[fname] = candidate
103
+ return candidate
104
+
105
+ # ── Internal helpers ──────────────────────────────────────────────────────
106
+
107
+ def sanitize_name(self, name: str) -> str:
108
+ """Make a string safe for use as a TOSCA type / property name."""
109
+ return name.replace(" ", "_").replace("-", "_").replace(".", "_")
110
+
111
+ def _get_registry(self) -> tuple[Registry, dict[str, Path]]:
112
+ """
113
+ Lazily build a ``referencing.Registry`` from all ``.json`` files in
114
+ ``_base_path`` that declare a ``$id``. Also returns a
115
+ ``{$id URI → local Path}`` mapping used for namespace derivation.
116
+ Reset in ``convert_schema`` when ``_base_path`` changes.
117
+ """
118
+ if self._registry is not None:
119
+ return self._registry, self._id_to_path
120
+ self._id_to_path = {}
121
+ resources: list[tuple[str, Resource]] = []
122
+ for search_dir in self._all_dirs():
123
+ for json_file in search_dir.glob("*.json"):
124
+ try:
125
+ with open(json_file, encoding="utf-8") as fh:
126
+ schema = json.load(fh)
127
+ if isinstance(schema, dict) and "$id" in schema:
128
+ uri = schema["$id"]
129
+ self._id_to_path[uri] = json_file
130
+ resources.append((uri, Resource.from_contents(schema, default_specification=DRAFT7)))
131
+ except (OSError, json.JSONDecodeError):
132
+ pass
133
+ self._registry = Registry().with_resources(resources)
134
+ return self._registry, self._id_to_path
135
+
136
+ def _parse_ref(self, ref: str) -> tuple[str | None, str]:
137
+ """
138
+ Split a ``$ref`` into ``(file_part, type_name)``.
139
+
140
+ Returns ``(None, type_name)`` for local refs (``#/...``).
141
+ Returns ``(filename, type_name)`` for relative or URI file refs.
142
+ URI refs are resolved via the ``$id`` registry; unmatched URIs
143
+ return ``(None, "")``.
144
+ """
145
+ if ref.startswith("#"):
146
+ return None, self.sanitize_name(ref.split("/")[-1])
147
+
148
+ if "://" in ref:
149
+ uri_no_frag, _, fragment = ref.partition("#")
150
+ # Fast path: match by filename extracted from the URI (works for most schemas).
151
+ fname = Path(uri_no_frag).name
152
+ file_path = self._resolve_fname(fname)
153
+ # Slow path: consult the $id registry for schemas whose URI doesn't
154
+ # end with the same filename as the local file.
155
+ if file_path is None:
156
+ _, id_to_path = self._get_registry()
157
+ file_path = id_to_path.get(uri_no_frag)
158
+ if file_path is None:
159
+ return None, ""
160
+ type_name = self.sanitize_name(fragment.split("/")[-1]) if fragment else self.sanitize_name(file_path.stem)
161
+ return file_path.name, type_name
162
+
163
+ file_part, _, fragment = ref.partition("#")
164
+ if not file_part:
165
+ return None, ""
166
+ type_name = self.sanitize_name(fragment.split("/")[-1]) if fragment else self.sanitize_name(Path(file_part).stem)
167
+ return file_part, type_name
168
+
169
+ def _namespace_for(self, file_part: str) -> str:
170
+ """
171
+ Derive a short TOSCA namespace identifier (≤8 chars, lowercase) from
172
+ a JSON Schema filename.
173
+
174
+ Strategy:
175
+ 1. Strip version suffix (e.g. ``.v1_0_0``).
176
+ 2. Split PascalCase / separator-delimited string into words.
177
+ 3. If the joined words fit in 8 chars, return them joined.
178
+ 4. Otherwise contract each word by removing non-leading vowels.
179
+ 5. If still >8 chars, distribute 8 chars proportionally across words.
180
+ """
181
+ stem = Path(file_part).stem
182
+ base = re.sub(r"[._]v\d+(?:[._]\d+)*$", "", stem) or stem
183
+
184
+ # Split on PascalCase boundaries and non-alphanumeric separators
185
+ spaced = re.sub(r"([a-z])([A-Z])", r"\1 \2", base)
186
+ spaced = re.sub(r"[^a-zA-Z0-9]+", " ", spaced)
187
+ words = [w.lower() for w in spaced.split() if w]
188
+ if not words:
189
+ words = [base.lower()]
190
+
191
+ joined = "".join(words)
192
+ if len(joined) <= 8:
193
+ return joined
194
+
195
+ # Contract: remove non-leading vowels from each word
196
+ def _contract(w: str) -> str:
197
+ return w[0] + re.sub(r"[aeiou]", "", w[1:]) if len(w) > 1 else w
198
+
199
+ contracted = [_contract(w) for w in words]
200
+ result = "".join(contracted)
201
+ if len(result) <= 8:
202
+ return result
203
+
204
+ # Still too long: distribute 8 chars proportionally across contracted words
205
+ n = len(contracted)
206
+ base_len = 8 // n
207
+ extra = 8 % n
208
+ return "".join(w[:base_len + (1 if i < extra else 0)] for i, w in enumerate(contracted))
209
+
210
+ def _tosca_file_for(self, file_part: str) -> str:
211
+ """Derive the expected TOSCA output filename for a JSON Schema file."""
212
+ return Path(file_part).stem + ".yaml"
213
+
214
+ def _caps_file_for(self, file_ref: str) -> str:
215
+ """Derive the companion capability-types YAML filename for a schema or TOSCA file.
216
+
217
+ Strips any version suffix from the stem and appends ``_caps.yaml``.
218
+ Works with both JSON schema names (``Drive.v1_14_0.json``) and TOSCA
219
+ output names (``Drive.v1_14_0.yaml``) — all versions of the same
220
+ resource family share the same capability-types file (``Drive_caps.yaml``).
221
+ """
222
+ stem = Path(file_ref).stem
223
+ base = re.sub(r"[._]v\d+(?:[._]\d+)*$", "", stem) or stem
224
+ return f"{base}_caps.yaml"
225
+
226
+ def _requirement_capability_for(self, tosca_type: Any, kind: str) -> str:
227
+ """Return a TOSCA capability-type reference for a requirement on *tosca_type*.
228
+
229
+ *kind* is ``"Feature"`` (for ``core:DependsOn``-style requirements) or
230
+ ``"Containable"`` (for ``core:Contains``-style requirements).
231
+
232
+ For a namespaced type (``namespace:TypeName``) the corresponding caps
233
+ file is derived from the imported YAML filename and the caps import is
234
+ recorded in ``_imports``. For bare (unqualified) type names the
235
+ ``_type_to_caps`` lookup is used (populated by :meth:`_mark_no_import`
236
+ for circular-import losers). Falls back to ``core:{kind}`` when the
237
+ source file cannot be determined.
238
+ """
239
+ type_str = str(tosca_type) if isinstance(tosca_type, CommentedOut) else tosca_type
240
+ if ":" in type_str:
241
+ namespace, type_name = type_str.split(":", 1)
242
+ tosca_file = self._imports.get(namespace)
243
+ if tosca_file:
244
+ caps_file = self._caps_file_for(tosca_file)
245
+ caps_ns = self._namespace_for(caps_file)
246
+ self._imports[caps_ns] = caps_file
247
+ return f"{caps_ns}:{type_name}{kind}"
248
+ else:
249
+ # Bare type name — look up caps recorded when the file was marked no-import.
250
+ if type_str in self._type_to_caps:
251
+ caps_ns, caps_file = self._type_to_caps[type_str]
252
+ self._imports[caps_ns] = caps_file
253
+ return f"{caps_ns}:{type_str}{kind}"
254
+ # Local type defined in the current file — use the current file's caps.
255
+ if self._current_filename:
256
+ caps_file = self._caps_file_for(self._current_filename)
257
+ caps_ns = self._namespace_for(caps_file)
258
+ self._imports[caps_ns] = caps_file
259
+ return f"{caps_ns}:{type_str}{kind}"
260
+ return f"core:{kind}"
261
+
262
+ def _load_cached_doc(self, fname: str) -> dict[str, Any] | None:
263
+ """Find *fname* in the schema search dirs, read it (using ``_file_cache``), and parse JSON.
264
+
265
+ Returns the parsed document dict, or ``None`` if the file cannot be
266
+ found, read, or parsed. The raw text is always stored in
267
+ ``_file_cache`` so that text-search callers (e.g.
268
+ :meth:`_refs_back_to_current`) can reuse the cached content.
269
+ """
270
+ candidate = self._resolve_fname(fname)
271
+ if candidate is None:
272
+ return None
273
+ key = str(candidate)
274
+ if key not in self._file_cache:
275
+ try:
276
+ self._file_cache[key] = candidate.read_text(encoding="utf-8")
277
+ except OSError:
278
+ self._file_cache[key] = ""
279
+ if not self._file_cache[key]:
280
+ return None
281
+ if key in self._doc_cache:
282
+ return self._doc_cache[key]
283
+ try:
284
+ doc = json.loads(self._file_cache[key])
285
+ except json.JSONDecodeError:
286
+ return None
287
+ self._doc_cache[key] = doc
288
+ return doc
289
+
290
+ def _mark_no_import(self, fname: str) -> None:
291
+ """Add *fname* to ``_no_import_files`` and register its root type in ``_node_type_names``.
292
+
293
+ When a file is inlined to avoid a circular TOSCA import, any type that
294
+ the file designates as its root resource (via a top-level
295
+ ``$ref: "#/definitions/TypeName"``) is also added to
296
+ ``_node_type_names`` so that references to that type are recognised as
297
+ node-type references and converted to TOSCA requirements.
298
+ """
299
+ self._no_import_files.add(fname)
300
+ doc = self._load_cached_doc(fname)
301
+ if doc is None:
302
+ return
303
+ top_ref = doc.get("$ref", "")
304
+ if top_ref.startswith("#/definitions/"):
305
+ safe_name = self.sanitize_name(top_ref.split("/")[-1])
306
+ self._node_type_names.add(safe_name)
307
+ # Record the caps file for this type so _requirement_capability_for can
308
+ # use it even when the file is marked no-import (bare type names).
309
+ caps_file = self._caps_file_for(fname)
310
+ caps_ns = self._namespace_for(caps_file)
311
+ self._type_to_caps[safe_name] = (caps_ns, caps_file)
312
+
313
+ def _collect_no_import_files(self, root_schema: dict[str, Any]) -> None:
314
+ """
315
+ Pre-scan all ``$ref`` values in *root_schema* and add any external
316
+ files that would create a circular import to ``_no_import_files``.
317
+
318
+ Two cases are handled:
319
+
320
+ - **Versioned files** (``BaseName.vX_Y_Z``): checked directly — if
321
+ the file's content mentions the current filename, it references back.
322
+ - **Unversioned files** (e.g. ``LogEntry.json``): checked transitively
323
+ — if any versioned ref *inside* the unversioned file points to a file
324
+ that mentions the current filename, the whole unversioned file would
325
+ create a circular import chain and is suppressed.
326
+ """
327
+ if not self._current_filename:
328
+ return
329
+ _VER = self._VER_RE
330
+ seen: set[str] = set()
331
+
332
+ def _collect(obj: Any) -> None:
333
+ if isinstance(obj, dict):
334
+ if "$ref" in obj and isinstance(obj["$ref"], str):
335
+ seen.add(obj["$ref"])
336
+ for v in obj.values():
337
+ _collect(v)
338
+ elif isinstance(obj, list):
339
+ for item in obj:
340
+ _collect(item)
341
+
342
+ _collect(root_schema)
343
+
344
+ # Deduplicate to one representative ref per filename so each external
345
+ # file is read at most once regardless of how many fragment-refs point
346
+ # to it (e.g. Resource.json#/Description, Resource.json#/Name, …).
347
+ seen_files: dict[str, str] = {} # fname → first ref seen for that file
348
+ for ref in seen:
349
+ if ref.startswith("#"):
350
+ continue
351
+ uri = ref.partition("#")[0]
352
+ if not uri:
353
+ continue
354
+ fname = Path(uri).name
355
+ if fname and fname not in seen_files:
356
+ seen_files[fname] = ref
357
+
358
+ for fname, ref in seen_files.items():
359
+ if fname in self._no_import_files:
360
+ continue
361
+ stem = Path(fname).stem
362
+ if _VER.match(stem):
363
+ # Versioned file: direct check
364
+ if self._refs_back_to_current(ref):
365
+ self._mark_no_import(fname)
366
+ else:
367
+ # Unversioned file: transitive check through its versioned refs
368
+ if self._refs_back_to_current_transitive(ref):
369
+ self._mark_no_import(fname)
370
+
371
+ def _refs_back_to_current(self, ref: str) -> bool:
372
+ """
373
+ Return ``True`` if the external file identified by *ref* contains any
374
+ ``$ref`` pointing back to the file currently being converted.
375
+
376
+ This detects potential circular imports (e.g. ``Resource.json`` has
377
+ ``anyOf → Resource.v1_23_0.json``, but ``Resource.v1_23_0.json``
378
+ also references ``Resource.json`` for stable shared types). When a
379
+ circular import would result from using the versioned ref as
380
+ ``derived_from``, the caller should merge properties inline instead.
381
+ """
382
+ if not self._current_filename:
383
+ return False
384
+ file_no_frag = ref.partition("#")[0]
385
+ if not file_no_frag:
386
+ return False
387
+ fname = Path(file_no_frag).name
388
+ return self._current_filename in self._ref_fnames_for(fname)
389
+
390
+ def _collect_ref_fnames(self, obj: Any) -> set[str]:
391
+ """Collect all external JSON Schema filenames referenced in *obj*."""
392
+ fnames: set[str] = set()
393
+
394
+ def _walk(o: Any) -> None:
395
+ if isinstance(o, dict):
396
+ ref = o.get("$ref")
397
+ if isinstance(ref, str) and not ref.startswith("#"):
398
+ file_part = ref.partition("#")[0]
399
+ fname = Path(file_part).name if file_part else ""
400
+ if fname:
401
+ fnames.add(fname)
402
+ for v in o.values():
403
+ _walk(v)
404
+ elif isinstance(o, list):
405
+ for item in o:
406
+ _walk(item)
407
+
408
+ _walk(obj)
409
+ return fnames
410
+
411
+ def _ref_fnames_for(self, fname: str) -> frozenset[str]:
412
+ """Return the cached set of external filenames directly referenced by *fname*."""
413
+ candidate = self._resolve_fname(fname)
414
+ if candidate is None:
415
+ return frozenset()
416
+ key = str(candidate)
417
+ if key not in self._ref_fnames_cache:
418
+ doc = self._load_cached_doc(fname)
419
+ refs = (
420
+ frozenset(self._collect_ref_fnames(doc)) if doc is not None
421
+ else frozenset()
422
+ )
423
+ self._ref_fnames_cache[key] = refs
424
+ return self._ref_fnames_cache[key]
425
+
426
+ def _get_reachable_fnames(self, start_fname: str) -> frozenset[str]:
427
+ """Return all filenames transitively reachable from *start_fname* via ``$ref``.
428
+
429
+ The result is cached permanently per starting filename so the BFS is
430
+ only ever run once per unique starting file across all conversions.
431
+ """
432
+ if start_fname in self._reachable_cache:
433
+ return self._reachable_cache[start_fname]
434
+ visited: set[str] = set()
435
+ queue: list[str] = [start_fname]
436
+ while queue:
437
+ fname = queue.pop(0)
438
+ if fname in visited:
439
+ continue
440
+ visited.add(fname)
441
+ for nested in self._ref_fnames_for(fname):
442
+ if nested not in visited:
443
+ queue.append(nested)
444
+ result = frozenset(visited)
445
+ self._reachable_cache[start_fname] = result
446
+ return result
447
+
448
+ def _refs_back_to_current_transitive(self, ref: str) -> bool:
449
+ """
450
+ Return ``True`` if the current file is transitively reachable from
451
+ *ref* via any chain of external ``$ref`` pointers.
452
+
453
+ Uses a pre-computed persistent reachable-set so the BFS is performed
454
+ at most once per starting file across all conversions. The check
455
+ itself is an O(1) frozenset membership test: is ``_current_filename``
456
+ in the reachable set of ``start_fname``?
457
+
458
+ This handles arbitrarily deep chains such as::
459
+
460
+ CurrentFile.json → A.json → A.vX_Y_Z.json → B.json
461
+ → B.vX_Y_Z.json → CurrentFile.json
462
+ """
463
+ if not self._current_filename:
464
+ return False
465
+ file_no_frag = ref.partition("#")[0]
466
+ if not file_no_frag:
467
+ return False
468
+ start_fname = Path(file_no_frag).name
469
+ if not start_fname:
470
+ return False
471
+ if start_fname in self._transitive_back_cache:
472
+ return self._transitive_back_cache[start_fname]
473
+ # O(1) frozenset lookup: is _current_filename reachable from start_fname?
474
+ result = self._current_filename in self._get_reachable_fnames(start_fname)
475
+ self._transitive_back_cache[start_fname] = result
476
+ return result
477
+
478
+ def _rewrite_local_refs(self, obj: Any, file_part: str) -> Any:
479
+ """
480
+ Recursively rewrite ``$ref`` values that start with ``#/`` to be
481
+ prefixed with *file_part*, turning local refs into external file refs.
482
+
483
+ This is applied to properties inlined from external schemas so that
484
+ references to types defined in that external schema are expressed as
485
+ ``ExternalFile.json#/definitions/TypeName`` rather than the ambiguous
486
+ ``#/definitions/TypeName``.
487
+ """
488
+ if isinstance(obj, dict):
489
+ return {
490
+ k: (f"{file_part}{v}"
491
+ if k == "$ref" and isinstance(v, str) and v.startswith("#/")
492
+ else self._rewrite_local_refs(v, file_part))
493
+ for k, v in obj.items()
494
+ }
495
+ if isinstance(obj, list):
496
+ return [self._rewrite_local_refs(item, file_part) for item in obj]
497
+ return obj
498
+
499
+ def _resolve_for_merge(self, ref: str, root_schema: dict[str, Any]) -> dict[str, Any]:
500
+ """
501
+ Resolve *ref* for the purpose of inlining its properties.
502
+
503
+ For external refs, local ``#/…`` sub-refs inside the resolved schema
504
+ are rewritten to ``filename#/…`` so that the converter later generates
505
+ correctly namespaced TOSCA type references (and records the import).
506
+ """
507
+ resolved = self.resolve_ref(ref, root_schema)
508
+ if ref.startswith("#"):
509
+ return resolved
510
+ file_part, _ = self._parse_ref(ref)
511
+ if file_part:
512
+ resolved = self._rewrite_local_refs(resolved, file_part)
513
+ return resolved
514
+
515
+ def _ref_to_tosca_type(self, ref: str) -> str:
516
+ """
517
+ Convert a ``$ref`` to a TOSCA type name.
518
+
519
+ External file refs are registered in ``self._imports`` and returned
520
+ as ``namespace:TypeName``; local refs are returned as plain type names.
521
+ """
522
+ file_part, type_name = self._parse_ref(ref)
523
+ if not type_name:
524
+ print(f"Warning: cannot resolve $ref '{ref}' — using 'string'", file=sys.stderr)
525
+ return "string"
526
+ if file_part is None:
527
+ return type_name # local ref
528
+ # Ref points back to the file being converted — the type is defined in the
529
+ # same TOSCA output file, so no import is needed.
530
+ if self._current_filename and Path(file_part).name == self._current_filename:
531
+ return type_name
532
+ fname = Path(file_part).name
533
+ if fname in self._no_import_files:
534
+ return type_name
535
+ # On-demand circular-import check: catches refs inside files that were
536
+ # already inlined (and therefore not present in the root schema's refs,
537
+ # so missed by the initial _collect_no_import_files pre-scan).
538
+ stem = Path(fname).stem
539
+ if self._VER_RE.match(stem):
540
+ # If the unversioned base of this versioned schema is already
541
+ # no-import, this versioned schema is part of the same family
542
+ # and should also be treated as no-import. This prevents
543
+ # circular imports when an inlined circular schema's anyOf
544
+ # references versioned variants (e.g. inlined Control.json
545
+ # has anyOf → Control.v1_7_0.json, but Control.json is circular
546
+ # so all Control versioned schemas should be suppressed too).
547
+ base_fname = re.sub(r"\.v\d.*$", "", stem) + Path(fname).suffix
548
+ if base_fname in self._no_import_files:
549
+ self._mark_no_import(fname)
550
+ return type_name
551
+ if self._refs_back_to_current(ref):
552
+ self._mark_no_import(fname)
553
+ return type_name
554
+ elif (
555
+ self._would_create_back_import(fname, self._current_filename)
556
+ or self._refs_back_to_current_transitive(fname)
557
+ ):
558
+ self._mark_no_import(fname)
559
+ return type_name
560
+ namespace = self._namespace_for(file_part)
561
+ self._imports[namespace] = self._tosca_file_for(file_part)
562
+ return f"{namespace}:{type_name}"
563
+
564
+ def resolve_ref(self, ref: str, root_schema: dict[str, Any]) -> dict[str, Any]:
565
+ """
566
+ Resolve a ``$ref`` to its schema dict.
567
+
568
+ Local ``#/...`` refs are resolved directly against ``root_schema``.
569
+ External refs are resolved by filename first (fast path); the
570
+ ``referencing`` registry is only consulted as a fallback for schemas
571
+ whose URI does not end with the local filename.
572
+ """
573
+ if ref.startswith("#/"):
574
+ parts = ref.lstrip("#/").split("/")
575
+ node: Any = root_schema
576
+ for part in parts:
577
+ if isinstance(node, dict) and part in node:
578
+ node = node[part]
579
+ else:
580
+ return {}
581
+ return node if isinstance(node, dict) else {}
582
+
583
+ if self._base_path is None:
584
+ return {}
585
+
586
+ # Fast path: load file via cache, then navigate to the fragment.
587
+ file_no_frag, _, fragment = ref.partition("#")
588
+ if file_no_frag:
589
+ fname = Path(file_no_frag).name
590
+ doc = self._load_cached_doc(fname)
591
+ if doc is not None:
592
+ if fragment:
593
+ node: Any = doc
594
+ for part in fragment.lstrip("/").split("/"):
595
+ if isinstance(node, dict) and part in node:
596
+ node = node[part]
597
+ else:
598
+ node = {}
599
+ break
600
+ return node if isinstance(node, dict) else {}
601
+ return doc
602
+
603
+ # Slow path: consult the referencing.Registry for complex URI resolution.
604
+ registry, _ = self._get_registry()
605
+ base_uri = root_schema.get("$id", "")
606
+ try:
607
+ resolver = registry.resolver(base_uri=base_uri) if base_uri else registry.resolver()
608
+ contents = resolver.lookup(ref).contents
609
+ return contents if isinstance(contents, dict) else {}
610
+ except Exception:
611
+ pass
612
+
613
+ print(f"Warning: failed to resolve $ref '{ref}' — schema details will be missing", file=sys.stderr)
614
+ return {}
615
+
616
+ def get_tosca_type(
617
+ self,
618
+ json_type: str | list[str] | None,
619
+ schema_fragment: dict[str, Any],
620
+ root_schema: dict[str, Any],
621
+ ) -> str:
622
+ """Return the TOSCA primitive type string for a JSON Schema ``type`` value."""
623
+ if isinstance(json_type, list):
624
+ json_type = next((t for t in json_type if t != "null"), json_type[0])
625
+ if json_type == "array":
626
+ return "list"
627
+ return self.JSON_SCHEMA_TO_TOSCA_TYPE.get(json_type or "string", "string")
628
+
629
+ def build_validation(self, schema_fragment: dict[str, Any]) -> dict[str, Any] | None:
630
+ """Build a TOSCA 2.0 ``validation`` expression from JSON Schema validation keywords."""
631
+ clauses: list[dict[str, Any]] = []
632
+
633
+ if "minimum" in schema_fragment:
634
+ clauses.append({"$greater_or_equal": ["$value", schema_fragment["minimum"]]})
635
+ if "exclusiveMinimum" in schema_fragment:
636
+ clauses.append({"$greater_than": ["$value", schema_fragment["exclusiveMinimum"]]})
637
+ if "maximum" in schema_fragment:
638
+ clauses.append({"$less_or_equal": ["$value", schema_fragment["maximum"]]})
639
+ if "exclusiveMaximum" in schema_fragment:
640
+ clauses.append({"$less_than": ["$value", schema_fragment["exclusiveMaximum"]]})
641
+ if "minLength" in schema_fragment:
642
+ clauses.append({"$greater_or_equal": [{"$length": ["$value"]}, schema_fragment["minLength"]]})
643
+ if "maxLength" in schema_fragment:
644
+ clauses.append({"$less_or_equal": [{"$length": ["$value"]}, schema_fragment["maxLength"]]})
645
+ if "pattern" in schema_fragment:
646
+ clauses.append({"$matches": ["$value", schema_fragment["pattern"]]})
647
+ if "enum" in schema_fragment:
648
+ clauses.append({"$valid_values": ["$value", schema_fragment["enum"]]})
649
+
650
+ if not clauses:
651
+ return None
652
+ if len(clauses) == 1:
653
+ return clauses[0]
654
+ return {"$and": clauses}
655
+
656
+ def _classify_member(self, member: dict[str, Any]) -> str:
657
+ """
658
+ Classify an ``anyOf``/``oneOf``/``allOf`` member.
659
+
660
+ Returns one of:
661
+
662
+ - ``"local"`` — pure ``$ref`` to a local ``#/...`` target.
663
+ - ``"versioned"`` — pure ``$ref`` to a versioned external file
664
+ (``BaseName.vX_Y_Z``), including circular ones (they can still be
665
+ picked as ``derived_from`` via the file-root bypass).
666
+ - ``"circular"`` — pure ``$ref`` to a non-versioned external file
667
+ that is in ``_no_import_files`` or references the current file back.
668
+ - ``"unversioned"`` — pure ``$ref`` to any other external file.
669
+ - ``"inline"`` — member has no ``$ref``, or has ``$ref`` plus
670
+ additional keys (mixed schema).
671
+ """
672
+ if "$ref" not in member or len(member) != 1:
673
+ return "inline"
674
+ ref = member["$ref"]
675
+ if ref.startswith("#"):
676
+ return "local"
677
+ uri = ref.partition("#")[0]
678
+ fname = Path(uri).name
679
+ stem = Path(uri.split("/")[-1]).stem
680
+ if self._VER_RE.match(stem):
681
+ # Versioned refs are always classified as "versioned" regardless of
682
+ # circularity — _merge_allof uses the file-root bypass to import the
683
+ # winning version even when it back-refs the current file.
684
+ if self._refs_back_to_current(ref):
685
+ if fname:
686
+ self._mark_no_import(fname)
687
+ return "versioned"
688
+ else:
689
+ if fname in self._no_import_files:
690
+ return "circular"
691
+ if self._refs_back_to_current_transitive(ref):
692
+ if fname:
693
+ self._mark_no_import(fname)
694
+ return "circular"
695
+ return "unversioned"
696
+
697
+ def _merge_props_from(
698
+ self,
699
+ refs: list[str],
700
+ schemas: list[dict[str, Any]],
701
+ root_schema: dict[str, Any],
702
+ outer: dict[str, Any],
703
+ outer_wins: bool = False,
704
+ ) -> dict[str, Any]:
705
+ """
706
+ Resolve *refs* and merge *schemas* inline into *outer*.
707
+
708
+ Properties and ``required`` lists are accumulated; scalar metadata
709
+ (``description``, ``title``, ``type``) is lifted into *outer* only
710
+ when not already present.
711
+
712
+ When *outer_wins* is ``True`` the outer schema's existing properties
713
+ take precedence over those resolved from refs/schemas (used when
714
+ merging a single unversioned or circular ref whose properties are
715
+ treated as defaults). When ``False`` (the default), later-resolved
716
+ properties overwrite earlier ones.
717
+ """
718
+ result = dict(outer)
719
+ merged_props: dict[str, Any] = dict(result.pop("properties", {}))
720
+ merged_required: list[str] = list(result.pop("required", []))
721
+
722
+ for ref in refs:
723
+ resolved = self._resolve_for_merge(ref, root_schema)
724
+ if outer_wins:
725
+ merged_props = {**resolved.get("properties", {}), **merged_props}
726
+ else:
727
+ merged_props.update(resolved.get("properties", {}))
728
+ merged_required.extend(resolved.get("required", []))
729
+
730
+ for sub in schemas:
731
+ resolved = self._resolve_for_merge(sub["$ref"], root_schema) if "$ref" in sub else sub
732
+ merged_props.update(resolved.get("properties", {}))
733
+ merged_required.extend(resolved.get("required", []))
734
+ # Lift scalar metadata
735
+ for sub_src in (sub, resolved):
736
+ for key in ("description", "title", "type"):
737
+ if key in sub_src and key not in result:
738
+ result[key] = sub_src[key]
739
+
740
+ if merged_props:
741
+ result["properties"] = merged_props
742
+ if merged_required:
743
+ result["required"] = list(dict.fromkeys(merged_required))
744
+ return result
745
+
746
+ def _pick_latest_versioned_ref(self, refs: list[str]) -> str | None:
747
+ """
748
+ If every ref in *refs* points to a versioned variant of the same base
749
+ resource (``BaseName.vX_Y_Z`` filename pattern), return the ref with
750
+ the highest version tuple. Returns ``None`` if the pattern doesn't
751
+ match or the refs have different base names.
752
+ """
753
+ entries: list[tuple[str, tuple[int, int, int], str]] = []
754
+ for ref in refs:
755
+ uri = ref.partition("#")[0]
756
+ stem = Path(uri.split("/")[-1]).stem # last path component, no ext
757
+ m = self._VER_RE.match(stem)
758
+ if not m:
759
+ return None
760
+ base = m.group(1)
761
+ version = (int(m.group(2)), int(m.group(3)), int(m.group(4)))
762
+ entries.append((base, version, ref))
763
+ bases = {e[0] for e in entries}
764
+ if len(bases) != 1:
765
+ return None
766
+ return max(entries, key=lambda e: e[1])[2]
767
+
768
+ def _merge_allof(
769
+ self,
770
+ schema: dict[str, Any],
771
+ root_schema: dict[str, Any],
772
+ ) -> tuple[dict[str, Any], str | None]:
773
+ """
774
+ Flatten ``allOf``, ``anyOf``, or ``oneOf`` into a single merged schema.
775
+
776
+ Returns ``(merged_schema, derived_from)`` where ``derived_from`` is the
777
+ TOSCA type name chosen for inheritance, or ``None``.
778
+
779
+ Member classification (via :meth:`_classify_member`):
780
+
781
+ - ``"local"`` / ``"versioned"`` refs → candidate for ``derived_from``.
782
+ - ``"unversioned"`` / ``"circular"`` refs → properties merged inline.
783
+ - ``"inline"`` (no ``$ref`` or mixed) → properties + metadata merged inline.
784
+
785
+ ``anyOf`` / ``oneOf`` extra rules:
786
+
787
+ - Null-only members are stripped first.
788
+ - Among versioned refs, the latest version of the sole versioned-base
789
+ group wins as ``derived_from``; all unversioned / circular refs are
790
+ merged inline instead.
791
+ - If no versioned group exists, the first local ref becomes
792
+ ``derived_from``; remaining refs and inline schemas are merged.
793
+ """
794
+ keyword = next((k for k in ("allOf", "anyOf", "oneOf") if k in schema), None)
795
+ if keyword is None:
796
+ return schema, None
797
+
798
+ members: list[dict[str, Any]] = list(schema[keyword])
799
+ outer = {k: v for k, v in schema.items() if k != keyword}
800
+
801
+ # Strip null-only members for anyOf/oneOf
802
+ if keyword in ("anyOf", "oneOf"):
803
+ non_null = [m for m in members
804
+ if not (isinstance(m, dict) and m.get("type") == "null")]
805
+ if non_null:
806
+ members = non_null
807
+
808
+ # ── Classify all members ──────────────────────────────────────────────
809
+
810
+ versioned_groups: dict[str, list[str]] = {} # base-name → list of refs
811
+ to_merge_refs: list[str] = [] # refs to inline-merge
812
+ inline_schemas: list[dict[str, Any]] = [] # non-pure-ref members
813
+ first_local_ref: str | None = None
814
+
815
+ for member in members:
816
+ kind = self._classify_member(member)
817
+ ref = member.get("$ref", "")
818
+
819
+ if kind == "local":
820
+ if first_local_ref is None:
821
+ first_local_ref = ref
822
+ else:
823
+ to_merge_refs.append(ref)
824
+
825
+ elif kind in ("unversioned", "circular"):
826
+ to_merge_refs.append(ref)
827
+
828
+ elif kind == "versioned":
829
+ uri = ref.partition("#")[0]
830
+ m = self._VER_RE.match(Path(uri.split("/")[-1]).stem)
831
+ versioned_groups.setdefault(m.group(1), []).append(ref) # type: ignore[union-attr]
832
+
833
+ else: # "inline"
834
+ inline_schemas.append(member)
835
+
836
+ # ── Determine derived_from ────────────────────────────────────────────
837
+
838
+ derived_from: str | None = None
839
+
840
+ if len(versioned_groups) == 1:
841
+ best = self._pick_latest_versioned_ref(next(iter(versioned_groups.values())))
842
+ if best is not None:
843
+ derived_from = self._ref_to_tosca_type(best)
844
+ # If the best versioned ref was circular, _ref_to_tosca_type
845
+ # returned a bare type name (no import recorded). Try the
846
+ # file-root bypass: versioned files are always file-root types
847
+ # and the current file directly refs them (they're in its anyOf),
848
+ # so as long as the current file has an explicit root ($ref) or
849
+ # the versioned file doesn't ref the current file back in a way
850
+ # that would create a TOSCA cycle, we can force-import it.
851
+ if best and ":" not in derived_from:
852
+ file_part, type_name_from_ref = self._parse_ref(best)
853
+ bypassed = False
854
+ if file_part is not None:
855
+ fname_best = Path(file_part).name
856
+ if fname_best in self._no_import_files and self._is_file_root_type(fname_best, type_name_from_ref or ""):
857
+ _current_refs_fname = fname_best in self._current_file_refs
858
+ _current_is_explicit_root = self._is_explicit_file_root(self._current_filename)
859
+ _unsafe_bypass = _current_refs_fname and not _current_is_explicit_root
860
+ # Also block if the versioned file refs our own root type back —
861
+ # that would cause the versioned YAML to import ours when
862
+ # independently converted, creating a TOSCA cycle.
863
+ _back_imports = self._versioned_refs_our_root_type(fname_best)
864
+ # Block when fname_best's unversioned base is circular AND
865
+ # fname_best was not directly referenced by the current file.
866
+ # This catches inlined circular schema anyOf members:
867
+ # e.g. when Sensor.json (circular) is inlined and its anyOf
868
+ # has Sensor.v1_12_0.json — we block the bypass since the
869
+ # ref was discovered through inlining, not direct reference.
870
+ _base_circular = False
871
+ _base_fname = re.sub(r"\.v\d.*$", "", Path(fname_best).stem) + Path(fname_best).suffix
872
+ if _base_fname != fname_best and _base_fname in self._no_import_files and not _current_refs_fname:
873
+ _base_circular = True
874
+ if not _unsafe_bypass and not _back_imports and not _base_circular:
875
+ namespace = self._namespace_for(file_part)
876
+ self._imports[namespace] = self._tosca_file_for(file_part)
877
+ derived_from = f"{namespace}:{type_name_from_ref}"
878
+ bypassed = True
879
+ if not bypassed:
880
+ # Circular and not a file-root type (e.g. a sub-definition
881
+ # like AdditionalVersions inside a versioned file) — cannot
882
+ # import, so the bare derived_from would be a self-reference.
883
+ # Fall back to merging all versioned refs inline instead.
884
+ derived_from = None
885
+ to_merge_refs.extend(next(iter(versioned_groups.values())))
886
+ # Any local ref defers to the versioned winner — merge it inline
887
+ if first_local_ref:
888
+ to_merge_refs.append(first_local_ref)
889
+
890
+ elif versioned_groups:
891
+ # Multiple versioned-base groups: can't pick one parent, merge all inline
892
+ for refs in versioned_groups.values():
893
+ to_merge_refs.extend(refs)
894
+ if first_local_ref:
895
+ derived_from = self._ref_to_tosca_type(first_local_ref)
896
+
897
+ else:
898
+ # No versioned refs at all: first local ref (if any) is the parent
899
+ if first_local_ref:
900
+ derived_from = self._ref_to_tosca_type(first_local_ref)
901
+ # Otherwise: only unversioned/circular/inline members → no parent
902
+
903
+ # Warn when anyOf/oneOf has multiple refs whose union semantics are lost
904
+ if keyword in ("anyOf", "oneOf") and derived_from and to_merge_refs:
905
+ for ref in to_merge_refs:
906
+ if ref:
907
+ print(
908
+ f"Warning: {keyword} has multiple $ref alternatives — "
909
+ f"merging '{ref}' properties; semantic union is lost",
910
+ file=sys.stderr,
911
+ )
912
+ break # one warning per schema is enough
913
+
914
+ # ── Merge inline ──────────────────────────────────────────────────────
915
+
916
+ # For a single unversioned/circular ref the outer schema's properties
917
+ # take priority (outer_wins=True); for multi-ref merges last-ref wins.
918
+ outer_wins = (
919
+ not inline_schemas
920
+ and len(to_merge_refs) == 1
921
+ and not derived_from
922
+ )
923
+ return self._merge_props_from(
924
+ to_merge_refs, inline_schemas, root_schema, outer, outer_wins=outer_wins
925
+ ), derived_from
926
+
927
+ def collect_definitions(self, root_schema: dict[str, Any]) -> dict[str, Any]:
928
+ """Collect all named sub-schemas from ``definitions`` and ``$defs``."""
929
+ defs: dict[str, Any] = {}
930
+ defs.update(root_schema.get("definitions", {}))
931
+ defs.update(root_schema.get("$defs", {}))
932
+ return defs
933
+
934
+ # ── Node-type detection ───────────────────────────────────────────────────
935
+
936
+ def _is_file_root_type(self, fname: str, type_name: str) -> bool:
937
+ """Return True if *type_name* is the root definition of external file *fname*.
938
+
939
+ Two checks are applied (either is sufficient):
940
+
941
+ 1. The file's top-level ``$ref`` is ``"#/definitions/TypeName"`` — the
942
+ explicit Redfish convention for designating the file's resource type.
943
+ 2. The type name matches the file's base stem (version suffix stripped)
944
+ **and** the file is a Redfish schema (``$id`` contains
945
+ ``redfish.dmtf.org``). This covers Redfish utility schemas like
946
+ ``Resource.json`` that omit the top-level ``$ref``.
947
+ """
948
+ doc = self._load_cached_doc(fname)
949
+ if doc is None:
950
+ return False
951
+
952
+ # Definitive: explicit top-level $ref points to this definition.
953
+ if doc.get("$ref") == f"#/definitions/{type_name}":
954
+ return True
955
+
956
+ # Heuristic for Redfish schemas only: type name equals the base file stem.
957
+ if "redfish.dmtf.org" in doc.get("$id", ""):
958
+ stem = Path(fname).stem
959
+ base_stem = re.sub(r"[._]v\d+(?:[._]\d+)*$", "", stem) or stem
960
+ if self.sanitize_name(type_name) == self.sanitize_name(base_stem):
961
+ return True
962
+
963
+ return False
964
+
965
+ def _versioned_refs_our_root_type(self, versioned_fname: str) -> bool:
966
+ """Return True if *versioned_fname* contains a ``$ref`` pointing to the
967
+ current file's root definition (e.g.
968
+ ``EthernetInterface.json#/definitions/EthernetInterface``).
969
+
970
+ When this is true, the versioned file would import the current file's
971
+ YAML when independently converted (the file-root bypass would fire),
972
+ so using it as ``derived_from`` from the current file would create a
973
+ circular TOSCA import.
974
+ """
975
+ if not self._current_filename:
976
+ return False
977
+ cur_doc = self._load_cached_doc(self._current_filename)
978
+ if cur_doc is None:
979
+ return False
980
+ cur_root_ref = cur_doc.get("$ref", "")
981
+ if not cur_root_ref.startswith("#/definitions/"):
982
+ return False
983
+ cur_root_type = cur_root_ref[len("#/definitions/"):]
984
+ versioned_doc = self._load_cached_doc(versioned_fname)
985
+ if versioned_doc is None:
986
+ return False
987
+
988
+ def _has_root_ref(obj: Any) -> bool:
989
+ if isinstance(obj, dict):
990
+ ref = obj.get("$ref", "")
991
+ if ref:
992
+ fp, tn = self._parse_ref(ref)
993
+ if fp is not None and Path(fp).name == self._current_filename and tn == cur_root_type:
994
+ return True
995
+ return any(_has_root_ref(v) for v in obj.values())
996
+ if isinstance(obj, list):
997
+ return any(_has_root_ref(v) for v in obj)
998
+ return False
999
+
1000
+ return _has_root_ref(versioned_doc)
1001
+
1002
+ def _would_create_back_import(
1003
+ self,
1004
+ fname: str,
1005
+ checking_for: str,
1006
+ _stack: frozenset[tuple[str, str]] | None = None,
1007
+ ) -> bool:
1008
+ """Return True if independently converting *fname* would eventually produce
1009
+ a TOSCA import of *checking_for*, which would create a circular import.
1010
+
1011
+ This detects the pattern where:
1012
+ 1. *fname* has a versioned schema V that would be selected as ``derived_from``
1013
+ when *fname* is independently converted (i.e. V does NOT ref *fname*'s
1014
+ root definition type, so ``_versioned_refs_our_root_type`` would not block it).
1015
+ 2. That versioned schema V directly references *checking_for* or its
1016
+ unversioned base — meaning when V.yaml is generated, it would import
1017
+ checking_for.yaml (or its base's yaml, which in turn imports the versioned
1018
+ checking_for.yaml via derived_from).
1019
+
1020
+ Example: Sensor.json has Sensor.v1_12_0.json, which does NOT ref
1021
+ Sensor.json#/definitions/Sensor (so it would be selected as derived_from),
1022
+ and Sensor.v1_12_0.json directly refs Control.json (the base of
1023
+ Control.v1_7_0.json). When Sensor.v1_12_0.yaml is generated it imports
1024
+ Control.yaml, which imports Control.v1_7_0.yaml — creating the cycle
1025
+ Control.v1_7_0.yaml → Sensor.yaml → … → Control.v1_7_0.yaml.
1026
+
1027
+ Symmetric cycles are broken lexicographically: when mutual recursion is
1028
+ detected (the same ``(fname, checking_for)`` key appears in ``_stack``),
1029
+ the call returns ``fname > checking_base``. This means the
1030
+ lexicographically smaller family (e.g. Control) is the *winner* (returns
1031
+ False → allowed to import the other family), and the larger one (e.g.
1032
+ Sensor) is the *loser* (returns True → the node reference is commented out).
1033
+ """
1034
+ if _stack is None:
1035
+ _stack = frozenset()
1036
+ key = (fname, checking_for)
1037
+ if key in self._back_import_cache:
1038
+ return self._back_import_cache[key]
1039
+ # Mutual-recursion sentinel: same call already in the stack → cycle detected.
1040
+ # Break symmetry lexicographically: the larger fname loses.
1041
+ if key in _stack:
1042
+ checking_stem_r = Path(checking_for).stem
1043
+ if self._VER_RE.match(checking_stem_r):
1044
+ checking_base_r = re.sub(r"\.v\d.*$", "", checking_stem_r) + Path(checking_for).suffix
1045
+ else:
1046
+ checking_base_r = checking_for
1047
+ result = fname > checking_base_r
1048
+ self._back_import_cache[key] = result
1049
+ return result
1050
+ _stack = _stack | {key}
1051
+
1052
+ fname_doc = self._load_cached_doc(fname)
1053
+ if fname_doc is None:
1054
+ return False
1055
+ # Determine the unversioned "base" of checking_for
1056
+ checking_stem = Path(checking_for).stem
1057
+ if self._VER_RE.match(checking_stem):
1058
+ base_name = re.sub(r"\.v\d.*$", "", checking_stem)
1059
+ checking_base = base_name + Path(checking_for).suffix
1060
+ else:
1061
+ checking_base = checking_for
1062
+ # Iterate over versioned schemas directly referenced by fname.
1063
+ # We intentionally do NOT skip schemas that ref fname's root type
1064
+ # (which would block them as derived_from): even "blocked" versioned
1065
+ # schemas still have their properties merged into the converted type,
1066
+ # so any external refs they contain DO generate TOSCA imports.
1067
+ for versioned_fname in self._ref_fnames_for(fname):
1068
+ if not self._VER_RE.match(Path(versioned_fname).stem):
1069
+ continue
1070
+ # Check if this versioned schema directly refs checking_for or its unversioned base.
1071
+ v_direct_refs = self._ref_fnames_for(versioned_fname)
1072
+ if checking_for in v_direct_refs or checking_base in v_direct_refs:
1073
+ # Counter-check: would converting checking_base also create a
1074
+ # back-import of fname? If so the cycle is mutual and the
1075
+ # lexicographic loser (larger fname) is the one that's blocked.
1076
+ if self._would_create_back_import(checking_base, versioned_fname, _stack):
1077
+ continue # mutual cycle — this hop is already handled on the other side
1078
+ self._back_import_cache[key] = True
1079
+ return True
1080
+ self._back_import_cache[key] = False
1081
+ return False
1082
+
1083
+ def _is_explicit_file_root(self, fname: str) -> bool:
1084
+ """Return True only if *fname* has an explicit top-level ``$ref`` to a definition.
1085
+
1086
+ Unlike :meth:`_is_file_root_type`, this does **not** apply the Redfish
1087
+ heuristic (base-stem match). It is used to distinguish resource schemas
1088
+ with a definitive ``$ref: "#/definitions/Foo"`` (e.g.
1089
+ ``Container.v1_0_1.json``) from utility/library schemas that omit the
1090
+ top-level ``$ref`` (e.g. ``Resource.json``).
1091
+ """
1092
+ doc = self._load_cached_doc(fname)
1093
+ if doc is None:
1094
+ return False
1095
+ return "#/definitions/" in doc.get("$ref", "")
1096
+
1097
+ def _external_defn_has_node_props(self, fname: str, type_name: str) -> bool:
1098
+ """Return True if the definition *type_name* in external file *fname* has
1099
+ any properties whose item or value type is a file-root node type.
1100
+
1101
+ This handles the case where a non-root type (e.g. ``RedundantGroup`` in
1102
+ ``Redundancy.v1_7_0.json``) has list/single properties referencing other
1103
+ node types (e.g. lists of ``Resource.json#/definitions/Resource``).
1104
+ When converted independently, those properties become requirements, making
1105
+ the type a node type. We need to detect this here so we can classify the
1106
+ type correctly when processing a referencing file.
1107
+ """
1108
+ doc = self._load_cached_doc(fname)
1109
+ if doc is None:
1110
+ return False
1111
+ defn = doc.get("definitions", {}).get(type_name, {})
1112
+ props = defn.get("properties", {})
1113
+ for pdef in props.values():
1114
+ # Single $ref directly on property, or list via items.$ref
1115
+ ref = pdef.get("$ref") or pdef.get("items", {}).get("$ref")
1116
+ if not ref:
1117
+ continue
1118
+ fp, tn = self._parse_ref(ref)
1119
+ if fp is not None and tn and self._is_file_root_type(Path(fp).name, tn):
1120
+ return True
1121
+ return False
1122
+
1123
+ def _is_node_type_tosca(self, tosca_type: str) -> bool:
1124
+ """Return True if *tosca_type* refers to a TOSCA node type rather than a data type.
1125
+
1126
+ - TOSCA primitives are never node types.
1127
+ - ``CommentedOut`` values are always node types (only created for confirmed
1128
+ file-root node types in circular-import losers).
1129
+ - Local (unqualified) types are checked against ``_node_type_names``.
1130
+ - Namespaced types (``namespace:TypeName``) are checked against the
1131
+ root definition of the corresponding external JSON Schema file; if the
1132
+ type is not the file root, also check whether its definition has any
1133
+ properties that would become requirements (i.e. it would be classified
1134
+ as a node type when the external file is independently converted).
1135
+ """
1136
+ if isinstance(tosca_type, CommentedOut):
1137
+ return True
1138
+ if tosca_type in self._TOSCA_PRIMITIVES:
1139
+ return False
1140
+ if ":" in tosca_type:
1141
+ namespace, type_name = tosca_type.split(":", 1)
1142
+ tosca_file = self._imports.get(namespace)
1143
+ if tosca_file is None:
1144
+ return False
1145
+ fname = Path(tosca_file).stem + ".json"
1146
+ if self._is_file_root_type(fname, type_name):
1147
+ return True
1148
+ return self._external_defn_has_node_props(fname, type_name)
1149
+ return tosca_type in self._node_type_names
1150
+
1151
+ def _prop_to_requirement(
1152
+ self, prop_def: dict[str, Any]
1153
+ ) -> dict[str, Any] | None:
1154
+ """Return a TOSCA requirement dict if *prop_def* references a node type, else None.
1155
+
1156
+ Count range is derived from the property's ``required`` flag and whether
1157
+ it represents a collection (``type: list``) or a single reference:
1158
+
1159
+ - list + required=False → ``[0, UNBOUNDED]``
1160
+ - list + required=True → ``[1, UNBOUNDED]``
1161
+ - single + required=False → ``[0, 1]``
1162
+ - single + required=True → ``[1, 1]``
1163
+ """
1164
+ prop_type = prop_def.get("type", "")
1165
+ is_required = prop_def.get("required", False)
1166
+
1167
+ if prop_type == "list":
1168
+ entry_type = (prop_def.get("entry_schema") or {}).get("type", "")
1169
+ if not entry_type or not self._is_node_type_tosca(entry_type):
1170
+ return None
1171
+ node_type = entry_type
1172
+ count_range: list[Any] = [1, "UNBOUNDED"] if is_required else [0, "UNBOUNDED"]
1173
+ elif self._is_node_type_tosca(prop_type):
1174
+ node_type = prop_type
1175
+ count_range = [1, 1] if is_required else [0, 1]
1176
+ else:
1177
+ return None
1178
+
1179
+ self._imports["core"] = "Core.yaml"
1180
+ cap_ref = self._requirement_capability_for(node_type, "Containable")
1181
+ req: dict[str, Any] = {
1182
+ "node": node_type,
1183
+ "capability": cap_ref,
1184
+ "relationship": "core:Contains",
1185
+ "count_range": count_range,
1186
+ }
1187
+ description = prop_def.get("description")
1188
+ if description:
1189
+ req["description"] = description
1190
+ return req
1191
+
1192
+ def _split_props_and_requirements(
1193
+ self, properties: dict[str, Any]
1194
+ ) -> tuple[dict[str, Any], list[dict[str, Any]]]:
1195
+ """Split *properties* into plain TOSCA properties and node-type requirements.
1196
+
1197
+ Returns ``(plain_props, requirements)`` where ``requirements`` is a list
1198
+ of single-key dicts ``{name: req_def}`` suitable for TOSCA
1199
+ ``requirements`` sections.
1200
+ """
1201
+ plain_props: dict[str, Any] = {}
1202
+ requirements: list[dict[str, Any]] = []
1203
+ for pname, pdef in properties.items():
1204
+ req = self._prop_to_requirement(pdef)
1205
+ if req is not None:
1206
+ requirements.append({pname: req})
1207
+ else:
1208
+ plain_props[pname] = pdef
1209
+ return plain_props, requirements
1210
+
1211
+ def _expand_links_prop(
1212
+ self,
1213
+ node_type_name: str,
1214
+ links_ref: str,
1215
+ root_schema: dict[str, Any],
1216
+ data_types: dict[str, Any],
1217
+ ) -> list[dict[str, Any]]:
1218
+ """Expand a Redfish ``Links`` property into TOSCA ``DependsOn`` requirements.
1219
+
1220
+ Resolves the Links definition identified by *links_ref*, processes each
1221
+ of its properties, and returns a list of TOSCA requirement dicts for
1222
+ those that reference node types. The requirements use
1223
+ ``core:DependsOn`` / ``core:Feature`` (or a derived relationship type
1224
+ if the Links definition also contains non-reference properties).
1225
+
1226
+ Non-node-type properties from the Links definition are collected into a
1227
+ ``{NodeTypeName}DependsOn`` relationship type that derives from
1228
+ ``core:DependsOn`` and is stored in ``_relationship_types``.
1229
+
1230
+ Also records the type name in ``_expanded_link_types`` so the now-
1231
+ unused Links data/node type can be removed after conversion.
1232
+ """
1233
+ _, type_name = self._parse_ref(links_ref)
1234
+ if type_name:
1235
+ self._expanded_link_types.add(type_name)
1236
+
1237
+ resolved = self._resolve_for_merge(links_ref, root_schema)
1238
+
1239
+ # Separate node-type refs (→ requirements) from plain properties.
1240
+ pending: list[tuple[str, str, list[Any], str | None]] = [] # (safe_name, node_type, count_range, description)
1241
+ extra_props: dict[str, Any] = {}
1242
+
1243
+ for pname, pschema in resolved.get("properties", {}).items():
1244
+ safe_name = self.sanitize_name(pname)
1245
+ prop_def = self.schema_to_property(pname, pschema, [], root_schema, data_types)
1246
+ prop_type = prop_def.get("type", "")
1247
+ if prop_type == "list":
1248
+ entry_type = (prop_def.get("entry_schema") or {}).get("type", "")
1249
+ if not self._is_node_type_tosca(entry_type):
1250
+ extra_props[safe_name] = prop_def
1251
+ continue
1252
+ pending.append((safe_name, entry_type, [0, "UNBOUNDED"], prop_def.get("description")))
1253
+ elif self._is_node_type_tosca(prop_type):
1254
+ pending.append((safe_name, prop_type, [0, 1], prop_def.get("description")))
1255
+ else:
1256
+ extra_props[safe_name] = prop_def
1257
+
1258
+ self._imports["core"] = "Core.yaml"
1259
+
1260
+ # If there are extra (non-ref) properties, create a dedicated relationship
1261
+ # type that derives from core:DependsOn and carries those properties.
1262
+ if extra_props and pending:
1263
+ rel_type_name = f"{node_type_name}DependsOn"
1264
+ self._relationship_types[rel_type_name] = {
1265
+ "derived_from": "core:DependsOn",
1266
+ "properties": extra_props,
1267
+ }
1268
+ relationship = rel_type_name
1269
+ else:
1270
+ relationship = "core:DependsOn"
1271
+
1272
+ requirements: list[dict[str, Any]] = []
1273
+ for safe_name, node_type, count_range, description in pending:
1274
+ cap_ref = self._requirement_capability_for(node_type, "Feature")
1275
+ req: dict[str, Any] = {
1276
+ "node": node_type,
1277
+ "capability": cap_ref,
1278
+ "relationship": relationship,
1279
+ "count_range": count_range,
1280
+ }
1281
+ if description:
1282
+ req["description"] = description
1283
+ requirements.append({safe_name: req})
1284
+ return requirements
1285
+
1286
+ # ── Core conversion ───────────────────────────────────────────────────────
1287
+
1288
+ def _extract_actions_interface(
1289
+ self,
1290
+ node_type_name: str,
1291
+ actions_ref: str,
1292
+ root_schema: dict[str, Any],
1293
+ ) -> str | None:
1294
+ """
1295
+ Extract a Redfish ``Actions`` definition into a TOSCA interface type.
1296
+
1297
+ Each non-Oem property in the Actions definition (e.g.
1298
+ ``"#ComputerSystem.Reset"``) is resolved to its action definition and
1299
+ converted to a TOSCA operation:
1300
+
1301
+ - ``description`` / ``x-longDescription`` → operation ``description``
1302
+ - ``parameters`` → operation ``inputs``
1303
+
1304
+ For each parameter:
1305
+
1306
+ - ``$ref`` is converted via :meth:`_ref_to_tosca_type` (records import).
1307
+ - ``description`` / ``x-longDescription`` → input ``description``.
1308
+ - ``requiredParameter`` → input ``required``.
1309
+
1310
+ The generated interface type is stored in ``_interface_types`` under
1311
+ ``{node_type_name}Actions``. The ``Actions`` container type, any
1312
+ ``OemActions`` type, and every individual action definition (e.g.
1313
+ ``Reset``) are added to ``_expanded_link_types`` so they are removed
1314
+ from the data/node type output.
1315
+
1316
+ Returns the interface type name, or ``None`` if no operations were
1317
+ extracted.
1318
+ """
1319
+ resolved = self._resolve_for_merge(actions_ref, root_schema)
1320
+ # Mark the Actions container for removal from data/node types output.
1321
+ if actions_ref.startswith("#/definitions/"):
1322
+ self._expanded_link_types.add(self.sanitize_name(actions_ref.split("/")[-1]))
1323
+
1324
+ operations: dict[str, Any] = {}
1325
+ for pname, pschema in resolved.get("properties", {}).items():
1326
+ if not isinstance(pschema, dict) or "$ref" not in pschema:
1327
+ continue
1328
+ action_ref = pschema["$ref"]
1329
+
1330
+ if pname == "Oem":
1331
+ # Track OemActions for removal from output types.
1332
+ if action_ref.startswith("#/definitions/"):
1333
+ self._expanded_link_types.add(
1334
+ self.sanitize_name(action_ref.split("/")[-1])
1335
+ )
1336
+ continue
1337
+
1338
+ # Derive operation name: "#ComputerSystem.Reset" → "Reset"
1339
+ op_name = self.sanitize_name(pname.split(".")[-1] if "." in pname else pname)
1340
+
1341
+ action_def = self.resolve_ref(action_ref, root_schema)
1342
+ if not action_def:
1343
+ continue
1344
+
1345
+ # Track the action definition for removal from output types.
1346
+ if action_ref.startswith("#/definitions/"):
1347
+ self._expanded_link_types.add(
1348
+ self.sanitize_name(action_ref.split("/")[-1])
1349
+ )
1350
+
1351
+ operation: dict[str, Any] = {}
1352
+
1353
+ # description
1354
+ desc = action_def.get("description") or action_def.get("x-longDescription")
1355
+ if desc:
1356
+ operation["description"] = FoldedStr(desc)
1357
+
1358
+ # parameters → inputs
1359
+ params = action_def.get("parameters", {})
1360
+ if params:
1361
+ inputs: dict[str, Any] = {}
1362
+ for param_name, param_schema in params.items():
1363
+ if not isinstance(param_schema, dict):
1364
+ continue
1365
+ safe_param = self.sanitize_name(param_name)
1366
+ input_def: dict[str, Any] = {}
1367
+ if "$ref" in param_schema:
1368
+ input_type = self._ref_to_tosca_type(param_schema["$ref"])
1369
+ else:
1370
+ input_type = self.get_tosca_type(
1371
+ param_schema.get("type"), param_schema, root_schema
1372
+ )
1373
+ input_def["type"] = input_type
1374
+ param_desc = (
1375
+ param_schema.get("description")
1376
+ or param_schema.get("x-longDescription")
1377
+ )
1378
+ if param_desc:
1379
+ input_def["description"] = FoldedStr(param_desc)
1380
+ input_def["required"] = bool(param_schema.get("requiredParameter", False))
1381
+ inputs[safe_param] = input_def
1382
+ if inputs:
1383
+ operation["inputs"] = inputs
1384
+
1385
+ operations[op_name] = operation
1386
+
1387
+ if not operations:
1388
+ return None
1389
+
1390
+ interface_type_name = f"{node_type_name}Actions"
1391
+ self._interface_types[interface_type_name] = {"operations": operations}
1392
+ return interface_type_name
1393
+
1394
+ def _build_simple_prop_def(
1395
+ self,
1396
+ tosca_type: str,
1397
+ schema: dict[str, Any],
1398
+ prop_name: str,
1399
+ required_props: list[str],
1400
+ ) -> dict[str, Any]:
1401
+ """Build a basic TOSCA property dict with type, description, required, and default."""
1402
+ prop_def: dict[str, Any] = {"type": tosca_type}
1403
+ description = schema.get("description") or schema.get("title")
1404
+ if description:
1405
+ prop_def["description"] = FoldedStr(description)
1406
+ prop_def["required"] = prop_name in required_props
1407
+ if "default" in schema:
1408
+ prop_def["default"] = schema["default"]
1409
+ return prop_def
1410
+
1411
+ def _resolve_entry_type(
1412
+ self,
1413
+ item_schema: dict[str, Any],
1414
+ prop_name: str,
1415
+ root_schema: dict[str, Any],
1416
+ data_types: dict[str, Any],
1417
+ ) -> str:
1418
+ """
1419
+ Resolve the TOSCA type for a list ``items`` or map ``additionalProperties`` schema.
1420
+
1421
+ Handles circular-import files by inlining the referenced schema as a
1422
+ local data type rather than generating an external import.
1423
+ """
1424
+ if "$ref" in item_schema:
1425
+ ref = item_schema["$ref"]
1426
+ fp, type_name = self._parse_ref(ref)
1427
+ if fp is not None and Path(fp).name in self._no_import_files:
1428
+ # For list items (containment), force a namespaced import even
1429
+ # when the file is circular — node types cannot be inlined and
1430
+ # a collection must know its member type. Register the import
1431
+ # directly to bypass _ref_to_tosca_type's no-import guard.
1432
+ # Guard: only bypass when the current file directly references
1433
+ # fname — if the ref was discovered through an inline-merged
1434
+ # schema, bypassing would create a circular TOSCA import.
1435
+ fname = Path(fp).name
1436
+ _current_refs_fname = fname in self._current_file_refs
1437
+ _current_is_explicit_root = self._is_explicit_file_root(self._current_filename)
1438
+ _unsafe_bypass = _current_refs_fname and not _current_is_explicit_root
1439
+ _back_import = (
1440
+ not _unsafe_bypass
1441
+ and _current_refs_fname
1442
+ and self._would_create_back_import(fname, self._current_filename)
1443
+ )
1444
+ if self._is_file_root_type(fname, type_name or "") and not _unsafe_bypass and _current_refs_fname and not _back_import:
1445
+ namespace = self._namespace_for(fp)
1446
+ self._imports[namespace] = self._tosca_file_for(fp)
1447
+ return f"{namespace}:{type_name}"
1448
+ # Loser in a symmetric circular dependency: emit the type reference
1449
+ # as a commented-out value so the intent is visible in the output.
1450
+ if _back_import and self._is_file_root_type(fname, type_name or ""):
1451
+ return CommentedOut(f"{self._namespace_for(fp)}:{type_name}")
1452
+ # File-root node type discovered via an inlined external schema (not
1453
+ # a direct ref of the current file). We cannot inline a node type as
1454
+ # a data type, and importing would be circular. Emit CommentedOut.
1455
+ if (self._is_file_root_type(fname, type_name or "")
1456
+ and not _unsafe_bypass and not _current_refs_fname):
1457
+ return CommentedOut(f"{self._namespace_for(fp)}:{type_name}")
1458
+ resolved = self._resolve_for_merge(ref, root_schema)
1459
+ resolved = {**resolved, **{k: v for k, v in item_schema.items() if k != "$ref"}}
1460
+ return self._inline_type_or_primitive(type_name, resolved, root_schema, data_types)
1461
+ ret = self._ref_to_tosca_type(ref)
1462
+ # _ref_to_tosca_type may have just marked the file as no-import
1463
+ # on-the-fly (because _would_create_back_import returned True).
1464
+ # If the file was not directly referenced by the current schema,
1465
+ # the ref was discovered via an inlined external schema — emit
1466
+ # CommentedOut so the intent is visible rather than a bare type.
1467
+ fname = Path(fp).name if fp else ""
1468
+ if fname and fname in self._no_import_files and ":" not in ret:
1469
+ _current_refs_fname = fname in self._current_file_refs
1470
+ _current_is_explicit_root = self._is_explicit_file_root(self._current_filename)
1471
+ _unsafe_bypass = _current_refs_fname and not _current_is_explicit_root
1472
+ if (self._is_file_root_type(fname, type_name or "")
1473
+ and not _unsafe_bypass and not _current_refs_fname):
1474
+ return CommentedOut(f"{self._namespace_for(fp)}:{type_name}")
1475
+ return ret
1476
+ return self.get_tosca_type(item_schema.get("type"), item_schema, root_schema)
1477
+
1478
+ def _inline_type_or_primitive(
1479
+ self,
1480
+ type_name: str,
1481
+ schema: dict[str, Any],
1482
+ root_schema: dict[str, Any],
1483
+ data_types: dict[str, Any],
1484
+ ) -> str:
1485
+ """
1486
+ Given a schema resolved from a circular-import file, return an
1487
+ appropriate TOSCA type name without creating an external import.
1488
+
1489
+ - If the schema has ``properties``, create a local data type named
1490
+ *type_name* in *data_types* and return that name.
1491
+ - Otherwise return the TOSCA primitive that best matches the schema
1492
+ (e.g. ``"string"`` for enum types).
1493
+ """
1494
+ if any(k in schema for k in ("allOf", "anyOf", "oneOf")):
1495
+ schema, _ = self._merge_allof(schema, root_schema)
1496
+
1497
+ json_type = schema.get("type")
1498
+ if schema.get("properties"):
1499
+ safe_name = self.sanitize_name(type_name)
1500
+ # If this type is a known node type (e.g. it is the current file's
1501
+ # root type, or was promoted by _mark_no_import), don't create a
1502
+ # duplicate data type entry — the main conversion pass will define
1503
+ # it as a node type via _add.
1504
+ if safe_name in self._node_type_names:
1505
+ return safe_name
1506
+ if safe_name not in data_types:
1507
+ data_types[safe_name] = {} # sentinel: breaks recursive cycles
1508
+ data_types[safe_name] = self.schema_to_tosca_data_type(
1509
+ safe_name, schema, root_schema, data_types
1510
+ )
1511
+ return safe_name
1512
+ return self.get_tosca_type(json_type, schema, root_schema)
1513
+
1514
+ def schema_to_property(
1515
+ self,
1516
+ prop_name: str,
1517
+ prop_schema: dict[str, Any],
1518
+ required_props: list[str],
1519
+ root_schema: dict[str, Any],
1520
+ data_types: dict[str, Any],
1521
+ ) -> dict[str, Any]:
1522
+ """Convert a single JSON Schema property definition to a TOSCA property dict."""
1523
+ # allOf / anyOf / oneOf → merge sub-schemas first
1524
+ if any(k in prop_schema for k in ("allOf", "anyOf", "oneOf")):
1525
+ prop_schema, allof_type = self._merge_allof(prop_schema, root_schema)
1526
+ if allof_type and not prop_schema.get("properties"):
1527
+ return self._build_simple_prop_def(allof_type, prop_schema, prop_name, required_props)
1528
+ # otherwise fall through with the merged schema
1529
+
1530
+ # $ref → use the referenced TOSCA data type name directly
1531
+ if "$ref" in prop_schema:
1532
+ ref = prop_schema["$ref"]
1533
+ file_part, type_name_from_ref = self._parse_ref(ref)
1534
+ if file_part is not None and Path(file_part).name in self._no_import_files:
1535
+ # Referenced file is circular. For file-root node types (e.g.
1536
+ # a resource collection referenced as a scalar property) we can
1537
+ # still force the import — the independently-generated YAML for
1538
+ # that file will not import the current file back, because the
1539
+ # current file directly refs it and is therefore blocked from
1540
+ # the other file's perspective. This mirrors the same bypass
1541
+ # used in _resolve_entry_type for list items.
1542
+ #
1543
+ # Unsafe-bypass guard: skip the file-root bypass when the
1544
+ # referenced file directly refs the current file AND the current
1545
+ # file is not an explicit-root resource schema. This prevents
1546
+ # utility library schemas (e.g. Resource.json, which refs
1547
+ # LogEntry.json directly) from importing the current file back
1548
+ # when processing LogEntry.json — that would create a cycle:
1549
+ # LogEntry.yaml → Resource.yaml → LogEntry.yaml.
1550
+ fname = Path(file_part).name
1551
+ # Does the current file directly ref fname? Use _current_file_refs
1552
+ # (pre-computed from the in-memory root schema) so this works even
1553
+ # when the source file is not present on disk.
1554
+ _current_refs_fname = fname in self._current_file_refs
1555
+ _current_is_explicit_root = self._is_explicit_file_root(self._current_filename)
1556
+ # Unsafe-bypass guard: when the current file is a utility library
1557
+ # (no explicit top-level $ref) that directly refs fname, then
1558
+ # fname's independently-generated YAML would also import the
1559
+ # current file back — bypassing would create a cycle.
1560
+ _unsafe_bypass = _current_refs_fname and not _current_is_explicit_root
1561
+ # Back-import guard: also block when independently converting
1562
+ # fname.yaml would eventually produce a TOSCA import of current.yaml
1563
+ # (e.g. fname has a versioned schema that refs current's base schema,
1564
+ # creating a multi-hop cycle like Sensor→v1_12_0→Control→v1_7_0→Sensor).
1565
+ _back_import = (
1566
+ not _unsafe_bypass
1567
+ and self._would_create_back_import(fname, self._current_filename)
1568
+ )
1569
+ if self._is_file_root_type(fname, type_name_from_ref or "") and not _unsafe_bypass and not _back_import:
1570
+ namespace = self._namespace_for(file_part)
1571
+ self._imports[namespace] = self._tosca_file_for(file_part)
1572
+ ref_type_name = f"{namespace}:{type_name_from_ref}"
1573
+ ref_schema = self.resolve_ref(ref, root_schema)
1574
+ merged = {**ref_schema, **{k: v for k, v in prop_schema.items() if k != "$ref"}}
1575
+ return self._build_simple_prop_def(ref_type_name, merged, prop_name, required_props)
1576
+ # Loser in a symmetric circular dependency: emit the type reference
1577
+ # as a commented-out value so the intent is visible in the output.
1578
+ if _back_import and self._is_file_root_type(fname, type_name_from_ref or ""):
1579
+ namespace = self._namespace_for(file_part)
1580
+ ref_type_name = CommentedOut(f"{namespace}:{type_name_from_ref}")
1581
+ ref_schema = self.resolve_ref(ref, root_schema)
1582
+ merged = {**ref_schema, **{k: v for k, v in prop_schema.items() if k != "$ref"}}
1583
+ return self._build_simple_prop_def(ref_type_name, merged, prop_name, required_props)
1584
+ # Not a file-root type (or bypass blocked): check if fname
1585
+ # directly refs the current file — if so, a safe one-directional
1586
+ # import is possible (step-1 allow).
1587
+ # Example: Resource.json refs LogEntry.json directly, so when
1588
+ # converting LogEntry.json we can safely import Resource.yaml
1589
+ # because Resource.yaml itself won't import LogEntry.yaml back.
1590
+ # Guard: only allow when fname is NOT an explicit-root schema.
1591
+ # If fname is explicit-root (e.g. a versioned resource schema),
1592
+ # independently converting it will also import the current file
1593
+ # back (file-root bypass fires), creating a circular import.
1594
+ if not _unsafe_bypass and not _current_refs_fname and not self._is_explicit_file_root(fname) and self._current_filename in self._ref_fnames_for(fname):
1595
+ # fname directly refs the current file → safe to import
1596
+ namespace = self._namespace_for(file_part)
1597
+ self._imports[namespace] = self._tosca_file_for(file_part)
1598
+ ref_type_name = f"{namespace}:{type_name_from_ref}"
1599
+ ref_schema = self.resolve_ref(ref, root_schema)
1600
+ merged = {**ref_schema, **{k: v for k, v in prop_schema.items() if k != "$ref"}}
1601
+ return self._build_simple_prop_def(ref_type_name, merged, prop_name, required_props)
1602
+ # Inline the schema — resolve and fall through to normal type detection.
1603
+ # Use _resolve_for_merge (not resolve_ref) so that any local
1604
+ # #/... refs inside the resolved schema are rewritten to
1605
+ # filename#/... — otherwise they resolve against root_schema
1606
+ # where the types don't exist.
1607
+ ref_schema = self._resolve_for_merge(ref, root_schema)
1608
+ prop_schema = {**ref_schema, **{k: v for k, v in prop_schema.items() if k != "$ref"}}
1609
+ # fall through to inline processing below
1610
+ else:
1611
+ ref_type_name = self._ref_to_tosca_type(ref)
1612
+ # _ref_to_tosca_type may have just discovered this file is
1613
+ # circular (on-the-fly, not pre-scanned) and added it to
1614
+ # _no_import_files, returning only a bare type name. Detect
1615
+ # this case and apply the same circular handling as above
1616
+ # (including the unsafe-bypass guard and step-1 allow).
1617
+ fname = Path(file_part).name if file_part else ""
1618
+ if fname and fname in self._no_import_files:
1619
+ _current_refs_fname = fname in self._current_file_refs
1620
+ _current_is_explicit_root = self._is_explicit_file_root(self._current_filename)
1621
+ _unsafe_bypass = _current_refs_fname and not _current_is_explicit_root
1622
+ # On-the-fly bypass: only fire when the current file directly
1623
+ # refs fname (_current_refs_fname). If the ref was discovered
1624
+ # through an inline-merged schema (not a direct ref), we
1625
+ # cannot guarantee the independently-generated YAML for fname
1626
+ # won't import the current file back — so we inline instead.
1627
+ if self._is_file_root_type(fname, type_name_from_ref or "") and not _unsafe_bypass and _current_refs_fname:
1628
+ # Namespace was already registered by _ref_to_tosca_type
1629
+ # only if it was not circular — here it was circular so
1630
+ # ref_type_name is bare; rebuild with namespace.
1631
+ namespace = self._namespace_for(file_part)
1632
+ self._imports[namespace] = self._tosca_file_for(file_part)
1633
+ ref_type_name = f"{namespace}:{type_name_from_ref}"
1634
+ ref_schema = self.resolve_ref(ref, root_schema)
1635
+ merged = {**ref_schema, **{k: v for k, v in prop_schema.items() if k != "$ref"}}
1636
+ return self._build_simple_prop_def(ref_type_name, merged, prop_name, required_props)
1637
+ # On-the-fly loser: circular file-root type encountered via an
1638
+ # inlined schema (not a direct ref of the current file). A bare
1639
+ # type name would be unresolvable, so emit as CommentedOut so the
1640
+ # intent is visible in the output.
1641
+ if self._is_file_root_type(fname, type_name_from_ref or "") and not _unsafe_bypass and not _current_refs_fname:
1642
+ namespace = self._namespace_for(file_part)
1643
+ ref_type_name = CommentedOut(f"{namespace}:{type_name_from_ref}")
1644
+ ref_schema = self.resolve_ref(ref, root_schema)
1645
+ merged = {**ref_schema, **{k: v for k, v in prop_schema.items() if k != "$ref"}}
1646
+ return self._build_simple_prop_def(ref_type_name, merged, prop_name, required_props)
1647
+ # Step-1 allow: fname directly refs current file → safe import.
1648
+ # Only when fname is not explicit-root: if fname is explicit-root,
1649
+ # independently converting it would also import current back → cycle.
1650
+ if not _unsafe_bypass and not _current_refs_fname and not self._is_explicit_file_root(fname) and self._current_filename in self._ref_fnames_for(fname):
1651
+ namespace = self._namespace_for(file_part)
1652
+ self._imports[namespace] = self._tosca_file_for(file_part)
1653
+ ref_type_name = f"{namespace}:{type_name_from_ref}"
1654
+ ref_schema = self.resolve_ref(ref, root_schema)
1655
+ merged = {**ref_schema, **{k: v for k, v in prop_schema.items() if k != "$ref"}}
1656
+ return self._build_simple_prop_def(ref_type_name, merged, prop_name, required_props)
1657
+ # Not a file-root type and no safe import — inline the schema
1658
+ # instead of using the bare type name from _ref_to_tosca_type.
1659
+ ref_schema = self._resolve_for_merge(ref, root_schema)
1660
+ prop_schema = {**ref_schema, **{k: v for k, v in prop_schema.items() if k != "$ref"}}
1661
+ # fall through to inline processing below
1662
+ else:
1663
+ ref_schema = self.resolve_ref(ref, root_schema)
1664
+ merged = {**ref_schema, **{k: v for k, v in prop_schema.items() if k != "$ref"}}
1665
+ return self._build_simple_prop_def(ref_type_name, merged, prop_name, required_props)
1666
+
1667
+ json_type = prop_schema.get("type")
1668
+
1669
+ # Inline object with properties → create a named data type and reference it
1670
+ if prop_schema.get("properties") and json_type in ("object", None):
1671
+ nested_type_name = self.sanitize_name(prop_name)
1672
+ if nested_type_name not in data_types:
1673
+ data_types[nested_type_name] = {} # sentinel: breaks recursive cycles
1674
+ data_types[nested_type_name] = self.schema_to_tosca_data_type(
1675
+ nested_type_name, prop_schema, root_schema, data_types
1676
+ )
1677
+ return self._build_simple_prop_def(nested_type_name, prop_schema, prop_name, required_props)
1678
+
1679
+ # Primitive type — also carries validation and entry_schema
1680
+ tosca_type = self.get_tosca_type(json_type, prop_schema, root_schema)
1681
+ prop_def = self._build_simple_prop_def(tosca_type, prop_schema, prop_name, required_props)
1682
+
1683
+ validation = self.build_validation(prop_schema)
1684
+ if validation is not None:
1685
+ prop_def["validation"] = validation
1686
+
1687
+ if tosca_type == "list":
1688
+ prop_def["entry_schema"] = {"type": self._resolve_entry_type(
1689
+ prop_schema.get("items", {}), prop_name, root_schema, data_types,
1690
+ )}
1691
+
1692
+ if tosca_type == "map":
1693
+ add_props = prop_schema.get("additionalProperties", {})
1694
+ if isinstance(add_props, dict):
1695
+ prop_def["entry_schema"] = {"type": self._resolve_entry_type(
1696
+ add_props, prop_name, root_schema, data_types,
1697
+ )}
1698
+
1699
+ return prop_def
1700
+
1701
+ def _schema_to_tosca_type(
1702
+ self,
1703
+ type_name: str,
1704
+ schema: dict[str, Any],
1705
+ root_schema: dict[str, Any],
1706
+ data_types: dict[str, Any],
1707
+ is_node_type: bool = False,
1708
+ ) -> dict[str, Any]:
1709
+ """Shared implementation for data-type and node-type conversion."""
1710
+ schema, derived_from = self._merge_allof(schema, root_schema)
1711
+
1712
+ tosca_type: dict[str, Any] = {}
1713
+
1714
+ description = schema.get("description") or schema.get("title")
1715
+ if description:
1716
+ tosca_type["description"] = FoldedStr(description)
1717
+
1718
+ if derived_from:
1719
+ tosca_type["derived_from"] = derived_from
1720
+
1721
+ properties_schema = schema.get("properties", {})
1722
+ required_list: list[str] = schema.get("required", [])
1723
+
1724
+ if properties_schema:
1725
+ links_requirements: list[dict[str, Any]] = []
1726
+ actions_interface: str | None = None
1727
+ regular_props: dict[str, Any] = {}
1728
+ for pname, pschema in properties_schema.items():
1729
+ # Detect the Redfish Links pattern: a property named "Links"
1730
+ # whose $ref resolves to a type also named "Links". Expand
1731
+ # it into core:DependsOn requirements rather than a property.
1732
+ if (is_node_type and pname == "Links"
1733
+ and isinstance(pschema, dict) and "$ref" in pschema
1734
+ and self._parse_ref(pschema["$ref"])[1] == "Links"):
1735
+ links_requirements.extend(
1736
+ self._expand_links_prop(type_name, pschema["$ref"], root_schema, data_types)
1737
+ )
1738
+ # Detect the Redfish Actions pattern: a property named "Actions"
1739
+ # whose $ref resolves to a type also named "Actions". Convert
1740
+ # each action into a TOSCA interface operation.
1741
+ elif (is_node_type and pname == "Actions"
1742
+ and isinstance(pschema, dict) and "$ref" in pschema
1743
+ and self._parse_ref(pschema["$ref"])[1] == "Actions"):
1744
+ actions_interface = self._extract_actions_interface(
1745
+ type_name, pschema["$ref"], root_schema
1746
+ )
1747
+ else:
1748
+ regular_props[pname] = pschema
1749
+
1750
+ all_props = {
1751
+ self.sanitize_name(pname): self.schema_to_property(
1752
+ pname, pschema, required_list, root_schema, data_types
1753
+ )
1754
+ for pname, pschema in regular_props.items()
1755
+ }
1756
+ if is_node_type:
1757
+ # Properties referencing node types become TOSCA requirements.
1758
+ plain_props, requirements = self._split_props_and_requirements(all_props)
1759
+ requirements.extend(links_requirements)
1760
+ if plain_props:
1761
+ tosca_type["properties"] = plain_props
1762
+ if requirements:
1763
+ tosca_type["requirements"] = requirements
1764
+ if actions_interface:
1765
+ tosca_type["interfaces"] = {"Actions": {"type": actions_interface}}
1766
+ else:
1767
+ tosca_type["properties"] = all_props
1768
+
1769
+ # All node types expose a type-specific Feature capability so they can be
1770
+ # targeted by DependsOn requirements via the companion caps file.
1771
+ if is_node_type:
1772
+ self._imports["core"] = "Core.yaml"
1773
+ feat_name = f"{type_name}Feature"
1774
+ self._capability_types.setdefault(feat_name, {"derived_from": "core:Feature"})
1775
+ caps_file = self._caps_file_for(self._current_filename) if self._current_filename else "caps.yaml"
1776
+ caps_ns = self._namespace_for(caps_file)
1777
+ self._imports[caps_ns] = caps_file
1778
+ tosca_type["capabilities"] = {"feature": {"type": f"{caps_ns}:{feat_name}"}}
1779
+
1780
+ # Non-object named types (e.g. a string with enum constraints) — data types only
1781
+ if not is_node_type:
1782
+ json_type = schema.get("type")
1783
+ if json_type and json_type != "object" and not properties_schema:
1784
+ tosca_type["derived_from"] = self.get_tosca_type(json_type, schema, root_schema)
1785
+ validation = self.build_validation(schema)
1786
+ if validation is not None:
1787
+ tosca_type["validation"] = validation
1788
+ tosca_type.pop("properties", None)
1789
+
1790
+ return tosca_type
1791
+
1792
+ def schema_to_tosca_data_type(
1793
+ self,
1794
+ type_name: str,
1795
+ schema: dict[str, Any],
1796
+ root_schema: dict[str, Any],
1797
+ data_types: dict[str, Any],
1798
+ ) -> dict[str, Any]:
1799
+ """Convert a JSON Schema object definition to a TOSCA ``data_types`` entry."""
1800
+ return self._schema_to_tosca_type(type_name, schema, root_schema, data_types, is_node_type=False)
1801
+
1802
+ def schema_to_tosca_node_type(
1803
+ self,
1804
+ type_name: str,
1805
+ schema: dict[str, Any],
1806
+ root_schema: dict[str, Any],
1807
+ data_types: dict[str, Any],
1808
+ ) -> dict[str, Any]:
1809
+ """Convert a JSON Schema object definition to a TOSCA ``node_types`` entry."""
1810
+ return self._schema_to_tosca_type(type_name, schema, root_schema, data_types, is_node_type=True)
1811
+
1812
+ def convert_schema(
1813
+ self,
1814
+ root_schema: dict[str, Any],
1815
+ top_level_name: str,
1816
+ node_type_names: frozenset[str] | set[str] = frozenset(),
1817
+ base_path: Path | None = None,
1818
+ search_paths: list[Path] | None = None,
1819
+ source_path: Path | None = None,
1820
+ ) -> ConversionResult:
1821
+ """
1822
+ Convert an entire JSON Schema document to TOSCA types.
1823
+
1824
+ Parameters
1825
+ ----------
1826
+ root_schema:
1827
+ Parsed JSON Schema document (a Python dict).
1828
+ top_level_name:
1829
+ Name to use for the top-level schema object if it is an ``object`` type.
1830
+ Typically derived from the schema's ``title`` field or the file stem.
1831
+ base_path:
1832
+ Directory containing the schema file. When provided, external
1833
+ ``$ref`` values are resolved relative to this directory and the
1834
+ corresponding TOSCA files are recorded as imports.
1835
+ search_paths:
1836
+ Additional directories to search for referenced schema files,
1837
+ consulted after ``base_path``.
1838
+ source_path:
1839
+ Path to the source schema file being converted. Used to detect
1840
+ potential circular imports when the source file's filename cannot
1841
+ be inferred from the schema's ``$id`` (e.g. after normalization).
1842
+
1843
+ Returns
1844
+ -------
1845
+ ConversionResult
1846
+ Named tuple with ``data_types``, ``node_types``, and ``imports`` dicts.
1847
+ """
1848
+ new_search_paths = list(search_paths) if search_paths else []
1849
+ if base_path != self._base_path or new_search_paths != self._search_paths:
1850
+ # Search dirs changed: invalidate all path-dependent caches.
1851
+ self._registry = None
1852
+ self._id_to_path = {}
1853
+ self._file_cache = {}
1854
+ self._doc_cache = {}
1855
+ self._fname_to_path = {}
1856
+ self._ref_fnames_cache = {}
1857
+ self._reachable_cache = {}
1858
+ self._base_path = base_path
1859
+ self._search_paths = new_search_paths
1860
+ self._imports = {}
1861
+ self._no_import_files = set()
1862
+ self._expanded_link_types = set()
1863
+ self._relationship_types = {}
1864
+ self._interface_types = {}
1865
+ self._capability_types = {}
1866
+ self._type_to_caps = {}
1867
+ self._transitive_back_cache = {}
1868
+ self._back_import_cache = {}
1869
+ self._current_filename = (
1870
+ source_path.name if source_path
1871
+ else Path(root_schema.get("$id", "")).name
1872
+ )
1873
+ # Pre-compute direct refs from the in-memory root schema so that
1874
+ # _current_refs_fname checks work even when the source file is not
1875
+ # present on disk (where _ref_fnames_for would return empty).
1876
+ self._current_file_refs = frozenset(self._collect_ref_fnames(root_schema))
1877
+ self._node_type_names = set(node_type_names)
1878
+ self._collect_no_import_files(root_schema)
1879
+ data_types: dict[str, Any] = {}
1880
+ node_types: dict[str, Any] = {}
1881
+
1882
+ def _add(tosca_name: str, schema: dict[str, Any], root: dict[str, Any]) -> None:
1883
+ if tosca_name in self._node_type_names:
1884
+ node_types[tosca_name] = self.schema_to_tosca_node_type(
1885
+ tosca_name, schema, root, data_types
1886
+ )
1887
+ else:
1888
+ data_types[tosca_name] = self.schema_to_tosca_data_type(
1889
+ tosca_name, schema, root, data_types
1890
+ )
1891
+
1892
+ # Convert named definitions / $defs first
1893
+ for def_name, def_schema in self.collect_definitions(root_schema).items():
1894
+ if not isinstance(def_schema, dict):
1895
+ continue
1896
+ _add(self.sanitize_name(def_name), def_schema, root_schema)
1897
+
1898
+ # Convert the top-level schema if it is an object
1899
+ if root_schema.get("type") == "object" or root_schema.get("properties"):
1900
+ _add(self.sanitize_name(top_level_name), root_schema, root_schema)
1901
+
1902
+ # Post-processing: data types that have properties referencing node types
1903
+ # cannot be valid TOSCA data types. Promote them to node types so the
1904
+ # node-type property references can be expressed as TOSCA requirements.
1905
+ for name in list(data_types):
1906
+ props = data_types[name].get("properties") or {}
1907
+ plain_props, requirements = self._split_props_and_requirements(props)
1908
+ if not requirements:
1909
+ continue
1910
+ dtype = data_types.pop(name)
1911
+ node_type: dict[str, Any] = {k: v for k, v in dtype.items() if k != "properties"}
1912
+ if plain_props:
1913
+ node_type["properties"] = plain_props
1914
+ node_type["requirements"] = requirements
1915
+ node_types[name] = node_type
1916
+
1917
+ # Post-processing: data types whose derived_from resolves to a node type
1918
+ # must also be node types (TOSCA does not allow a data type to derive from
1919
+ # a node type). This covers cases like Redundancy.yaml's RedundantGroup
1920
+ # which derives from rdndncy:RedundantGroup (a node type in v1_7_0.yaml).
1921
+ for name in list(data_types):
1922
+ derived_from = data_types[name].get("derived_from", "")
1923
+ if derived_from and self._is_node_type_tosca(derived_from):
1924
+ dtype = data_types.pop(name)
1925
+ node_type = dict(dtype)
1926
+ self._imports["core"] = "Core.yaml"
1927
+ if "capabilities" not in node_type:
1928
+ caps_file = self._caps_file_for(self._current_filename) if self._current_filename else "caps.yaml"
1929
+ caps_ns = self._namespace_for(caps_file)
1930
+ self._imports[caps_ns] = caps_file
1931
+ feat_name = f"{name}Feature"
1932
+ cont_name = f"{name}Containable"
1933
+ self._capability_types.setdefault(feat_name, {"derived_from": "core:Feature"})
1934
+ self._capability_types.setdefault(cont_name, {"derived_from": "core:Containable"})
1935
+ node_type["capabilities"] = {
1936
+ "feature": {"type": f"{caps_ns}:{feat_name}"},
1937
+ "containable": {"type": f"{caps_ns}:{cont_name}"},
1938
+ }
1939
+ node_types[name] = node_type
1940
+
1941
+ # Post-processing: remove property redefinitions in derived types that
1942
+ # would relax a required:true constraint set by an ancestor. TOSCA
1943
+ # forbids relaxing constraints, so the inherited definition stands.
1944
+ all_types: dict[str, Any] = {**data_types, **node_types}
1945
+ for type_def in list(data_types.values()) + list(node_types.values()):
1946
+ derived_from = type_def.get("derived_from")
1947
+ if not derived_from:
1948
+ continue
1949
+ # Collect property names that are required:true in any ancestor.
1950
+ ancestor_required: set[str] = set()
1951
+ visited: set[str] = set()
1952
+ stack = [derived_from]
1953
+ while stack:
1954
+ ancestor_name = stack.pop()
1955
+ if ancestor_name in visited or ":" in ancestor_name:
1956
+ continue
1957
+ visited.add(ancestor_name)
1958
+ ancestor = all_types.get(ancestor_name)
1959
+ if not ancestor:
1960
+ continue
1961
+ for pname, pdef in ancestor.get("properties", {}).items():
1962
+ if pdef.get("required", False):
1963
+ ancestor_required.add(pname)
1964
+ if ancestor.get("derived_from"):
1965
+ stack.append(ancestor["derived_from"])
1966
+ # Drop any child property that relaxes a required:true ancestor constraint.
1967
+ child_props = type_def.get("properties", {})
1968
+ for pname in [p for p in child_props if p in ancestor_required
1969
+ and not child_props[p].get("required", False)]:
1970
+ del child_props[pname]
1971
+ if not child_props:
1972
+ type_def.pop("properties", None)
1973
+
1974
+ # Remove Links container types that were expanded inline into parent
1975
+ # node types as DependsOn requirements — they are no longer referenced.
1976
+ for name in self._expanded_link_types:
1977
+ data_types.pop(name, None)
1978
+ node_types.pop(name, None)
1979
+
1980
+ # Every node type can be the target of a core:Contains requirement,
1981
+ # so add a type-specific Containable capability to all of them.
1982
+ if node_types:
1983
+ self._imports["core"] = "Core.yaml"
1984
+ caps_file = self._caps_file_for(self._current_filename) if self._current_filename else "caps.yaml"
1985
+ caps_ns = self._namespace_for(caps_file)
1986
+ self._imports[caps_ns] = caps_file
1987
+ for nt_name, nt in node_types.items():
1988
+ cont_name = f"{nt_name}Containable"
1989
+ self._capability_types.setdefault(cont_name, {"derived_from": "core:Containable"})
1990
+ nt.setdefault("capabilities", {})["containable"] = {"type": f"{caps_ns}:{cont_name}"}
1991
+
1992
+ return ConversionResult(
1993
+ data_types=data_types,
1994
+ node_types=node_types,
1995
+ imports=dict(self._imports),
1996
+ relationship_types=dict(self._relationship_types),
1997
+ interface_types=dict(self._interface_types),
1998
+ capability_types=dict(self._capability_types),
1999
+ )
2000
+
2001
+ def build_tosca_document(
2002
+ self,
2003
+ data_types: dict[str, Any],
2004
+ node_types: dict[str, Any] | None = None,
2005
+ relationship_types: dict[str, Any] | None = None,
2006
+ interface_types: dict[str, Any] | None = None,
2007
+ imports: dict[str, str] | None = None,
2008
+ ) -> dict[str, Any]:
2009
+ """Wrap type dicts in a full TOSCA service-template skeleton."""
2010
+ doc: dict[str, Any] = {
2011
+ "tosca_definitions_version": "tosca_2_0",
2012
+ "description": FoldedStr("Types generated from JSON Schema by any2tosca"),
2013
+ }
2014
+ if imports:
2015
+ doc["imports"] = [{"url": file, "namespace": ns} for ns, file in imports.items()]
2016
+ if data_types:
2017
+ doc["data_types"] = data_types
2018
+ if relationship_types:
2019
+ doc["relationship_types"] = relationship_types
2020
+ if interface_types:
2021
+ doc["interface_types"] = interface_types
2022
+ if node_types:
2023
+ doc["node_types"] = node_types
2024
+ return doc
2025
+
2026
+
2027
+ # ── Module-level convenience functions ────────────────────────────────────────
2028
+
2029
+ def convert_schema(
2030
+ root_schema: dict[str, Any],
2031
+ top_level_name: str,
2032
+ node_type_names: frozenset[str] | set[str] = frozenset(),
2033
+ base_path: Path | None = None,
2034
+ search_paths: list[Path] | None = None,
2035
+ source_path: Path | None = None,
2036
+ ) -> ConversionResult:
2037
+ return Converter().convert_schema(root_schema, top_level_name, node_type_names,
2038
+ base_path, search_paths, source_path)
2039
+
2040
+
2041
+ def build_tosca_document(
2042
+ data_types: dict[str, Any],
2043
+ node_types: dict[str, Any] | None = None,
2044
+ relationship_types: dict[str, Any] | None = None,
2045
+ interface_types: dict[str, Any] | None = None,
2046
+ imports: dict[str, str] | None = None,
2047
+ ) -> dict[str, Any]:
2048
+ return Converter().build_tosca_document(
2049
+ data_types, node_types, relationship_types, interface_types, imports
2050
+ )
2051
+
2052
+
2053
+ def build_caps_document(capability_types: dict[str, Any]) -> dict[str, Any]:
2054
+ """Build a TOSCA document containing only capability type definitions."""
2055
+ return {
2056
+ "tosca_definitions_version": "tosca_2_0",
2057
+ "description": FoldedStr("Capability types generated from JSON Schema by any2tosca"),
2058
+ "imports": [{"url": "Core.yaml", "namespace": "core"}],
2059
+ "capability_types": capability_types,
2060
+ }