Converts a Type to a json-schema.
(self, t: mi.Type, check_ref: bool = True)
| 225 | self.ref_template = ref_template |
| 226 | |
| 227 | def to_schema(self, t: mi.Type, check_ref: bool = True) -> dict[str, Any]: |
| 228 | """Converts a Type to a json-schema.""" |
| 229 | schema: dict[str, Any] = {} |
| 230 | |
| 231 | while isinstance(t, mi.Metadata): |
| 232 | schema = mi._merge_json(schema, t.extra_json_schema) |
| 233 | t = t.type |
| 234 | |
| 235 | if check_ref and hasattr(t, "cls"): |
| 236 | if name := self.name_map.get(t.cls): |
| 237 | schema["$ref"] = self.ref_template.format(name=name) |
| 238 | return schema |
| 239 | |
| 240 | if isinstance(t, (mi.AnyType, mi.RawType)): |
| 241 | pass |
| 242 | elif isinstance(t, mi.NoneType): |
| 243 | schema["type"] = "null" |
| 244 | elif isinstance(t, mi.BoolType): |
| 245 | schema["type"] = "boolean" |
| 246 | elif isinstance(t, (mi.IntType, mi.FloatType)): |
| 247 | schema["type"] = "integer" if isinstance(t, mi.IntType) else "number" |
| 248 | if t.ge is not None: |
| 249 | schema["minimum"] = t.ge |
| 250 | if t.gt is not None: |
| 251 | schema["exclusiveMinimum"] = t.gt |
| 252 | if t.le is not None: |
| 253 | schema["maximum"] = t.le |
| 254 | if t.lt is not None: |
| 255 | schema["exclusiveMaximum"] = t.lt |
| 256 | if t.multiple_of is not None: |
| 257 | schema["multipleOf"] = t.multiple_of |
| 258 | elif isinstance(t, mi.StrType): |
| 259 | schema["type"] = "string" |
| 260 | if t.max_length is not None: |
| 261 | schema["maxLength"] = t.max_length |
| 262 | if t.min_length is not None: |
| 263 | schema["minLength"] = t.min_length |
| 264 | if t.pattern is not None: |
| 265 | schema["pattern"] = t.pattern |
| 266 | elif isinstance(t, (mi.BytesType, mi.ByteArrayType, mi.MemoryViewType)): |
| 267 | schema["type"] = "string" |
| 268 | schema["contentEncoding"] = "base64" |
| 269 | if t.max_length is not None: |
| 270 | schema["maxLength"] = 4 * ((t.max_length + 2) // 3) |
| 271 | if t.min_length is not None: |
| 272 | schema["minLength"] = 4 * ((t.min_length + 2) // 3) |
| 273 | elif isinstance(t, mi.DateTimeType): |
| 274 | schema["type"] = "string" |
| 275 | if t.tz is True: |
| 276 | schema["format"] = "date-time" |
| 277 | elif isinstance(t, mi.TimeType): |
| 278 | schema["type"] = "string" |
| 279 | if t.tz is True: |
| 280 | schema["format"] = "time" |
| 281 | elif t.tz is False: |
| 282 | schema["format"] = "partial-time" |
| 283 | elif isinstance(t, mi.DateType): |
| 284 | schema["type"] = "string" |
no test coverage detected