scim2-models 0.5.2__py3-none-any.whl → 0.6.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.
scim2_models/path.py ADDED
@@ -0,0 +1,731 @@
1
+ import re
2
+ from collections import UserString
3
+ from collections.abc import Iterator
4
+ from inspect import isclass
5
+ from typing import TYPE_CHECKING
6
+ from typing import Any
7
+ from typing import Generic
8
+ from typing import NamedTuple
9
+ from typing import TypeVar
10
+
11
+ from pydantic import GetCoreSchemaHandler
12
+ from pydantic_core import core_schema
13
+
14
+ from .base import BaseModel
15
+ from .utils import _find_field_name
16
+ from .utils import _to_camel
17
+
18
+ if TYPE_CHECKING:
19
+ from .annotations import Mutability
20
+ from .annotations import Required
21
+ from .resources.resource import Resource
22
+
23
+ from .exceptions import InvalidPathException
24
+ from .exceptions import PathNotFoundException
25
+
26
+ ResourceT = TypeVar("ResourceT", bound="Resource[Any]")
27
+
28
+ _VALID_PATH_PATTERN = re.compile(r'^[a-zA-Z][a-zA-Z0-9._:\-\[\]"=\s]*$')
29
+ _PATH_CACHE: dict[tuple[type, type], type] = {}
30
+
31
+
32
+ def _to_comparable(value: Any) -> Any:
33
+ """Convert a value to a comparable form (dict for BaseModel)."""
34
+ return value.model_dump() if isinstance(value, BaseModel) else value
35
+
36
+
37
+ def _values_match(value1: Any, value2: Any) -> bool:
38
+ """Check if two values match, handling BaseModel comparison."""
39
+ return bool(_to_comparable(value1) == _to_comparable(value2))
40
+
41
+
42
+ def _value_in_list(current_list: list[Any], new_value: Any) -> bool:
43
+ """Check if a value exists in a list, handling BaseModel comparison."""
44
+ return any(_values_match(item, new_value) for item in current_list)
45
+
46
+
47
+ def _require_field(model: type[BaseModel], name: str) -> str:
48
+ """Find field name or raise PathNotFoundException."""
49
+ if (field_name := _find_field_name(model, name)) is None:
50
+ raise PathNotFoundException(path=name, field=name)
51
+ return field_name
52
+
53
+
54
+ class _Resolution(NamedTuple):
55
+ """Result of instance path resolution."""
56
+
57
+ target: "BaseModel"
58
+ path_str: str
59
+ is_explicit_schema_path: bool = False
60
+
61
+
62
+ class URN(str):
63
+ """URN string type with validation."""
64
+
65
+ def __new__(cls, urn: str) -> "URN":
66
+ cls.check_syntax(urn)
67
+ return super().__new__(cls, urn)
68
+
69
+ @classmethod
70
+ def __get_pydantic_core_schema__(
71
+ cls,
72
+ _source: type[Any],
73
+ _handler: GetCoreSchemaHandler,
74
+ ) -> core_schema.CoreSchema:
75
+ return core_schema.no_info_after_validator_function(
76
+ cls,
77
+ core_schema.str_schema(),
78
+ serialization=core_schema.plain_serializer_function_ser_schema(
79
+ str,
80
+ ),
81
+ )
82
+
83
+ @classmethod
84
+ def check_syntax(cls, path: str) -> None:
85
+ """Validate URN-based path format.
86
+
87
+ :param path: The URN path to validate
88
+ :raises ValueError: If the URN format is invalid
89
+ """
90
+ if not path.startswith("urn:"):
91
+ raise ValueError("The URN does not start with urn:")
92
+
93
+ urn_segments = path.split(":")
94
+ if len(urn_segments) < 3:
95
+ raise ValueError("URNs must have at least 3 parts")
96
+
97
+
98
+ class Path(UserString, Generic[ResourceT]):
99
+ __scim_model__: type[BaseModel] | None = None
100
+
101
+ def __class_getitem__(cls, model: type[ResourceT]) -> type["Path[ResourceT]"]:
102
+ """Create a Path class bound to a specific model type."""
103
+ if not isclass(model) or not hasattr(model, "model_fields"):
104
+ return super().__class_getitem__(model) # type: ignore[misc,no-any-return]
105
+
106
+ cache_key = (cls, model)
107
+ if cache_key in _PATH_CACHE:
108
+ return _PATH_CACHE[cache_key]
109
+
110
+ new_class = type(f"Path[{model.__name__}]", (cls,), {"__scim_model__": model})
111
+ _PATH_CACHE[cache_key] = new_class
112
+ return new_class
113
+
114
+ @classmethod
115
+ def __get_pydantic_core_schema__(
116
+ cls,
117
+ _source_type: type[Any],
118
+ _handler: GetCoreSchemaHandler,
119
+ ) -> core_schema.CoreSchema:
120
+ def validate_path(value: Any) -> "Path[Any]":
121
+ if isinstance(value, Path):
122
+ return cls(str(value))
123
+ if isinstance(value, str):
124
+ return cls(value)
125
+ raise ValueError(f"Expected str or Path, got {type(value).__name__}")
126
+
127
+ return core_schema.no_info_plain_validator_function(
128
+ validate_path,
129
+ serialization=core_schema.plain_serializer_function_ser_schema(str),
130
+ )
131
+
132
+ def __init__(self, path: str):
133
+ self.check_syntax(path)
134
+ self.data = path
135
+
136
+ @classmethod
137
+ def check_syntax(cls, path: str) -> None:
138
+ """Check if path syntax is valid according to RFC 7644 simplified rules.
139
+
140
+ An empty string is valid and represents the resource root.
141
+
142
+ :param path: The path to validate
143
+ :raises ValueError: If the path syntax is invalid
144
+ """
145
+ if not path:
146
+ return
147
+
148
+ if path[0].isdigit():
149
+ raise ValueError("Paths cannot start with a digit")
150
+
151
+ if ".." in path:
152
+ raise ValueError("Paths cannot contain double dots")
153
+
154
+ if not _VALID_PATH_PATTERN.match(path):
155
+ raise ValueError("The path contains invalid characters")
156
+
157
+ if path.endswith(":"):
158
+ raise ValueError("Paths cannot end with a colon")
159
+
160
+ if ":" in path:
161
+ urn = path.rsplit(":", 1)[0]
162
+ try:
163
+ URN(urn.lower())
164
+ except ValueError as exc:
165
+ raise ValueError(f"The path is not a valid URN: {exc}") from exc
166
+
167
+ @property
168
+ def schema(self) -> str | None:
169
+ """The schema URN portion of the path.
170
+
171
+ For paths like "urn:...:User:userName", returns "urn:...:User".
172
+ For simple paths like "userName", returns None.
173
+ """
174
+ if ":" not in self.data:
175
+ return None
176
+ return self.data.rsplit(":", 1)[0]
177
+
178
+ @property
179
+ def attr(self) -> str:
180
+ """The attribute portion of the path.
181
+
182
+ For paths like "urn:...:User:userName", returns "userName".
183
+ For simple paths like "userName", returns "userName".
184
+ For schema-only paths like "urn:...:User", returns "".
185
+ """
186
+ if ":" not in self.data:
187
+ return self.data
188
+ return self.data.rsplit(":", 1)[1]
189
+
190
+ @property
191
+ def parts(self) -> tuple[str, ...]:
192
+ """The attribute path segments split by '.'.
193
+
194
+ For "name.familyName", returns ("name", "familyName").
195
+ For "userName", returns ("userName",).
196
+ For "", returns ().
197
+ """
198
+ attr = self.attr
199
+ if not attr:
200
+ return ()
201
+ return tuple(attr.split("."))
202
+
203
+ def is_prefix_of(self, other: "str | Path[Any]") -> bool:
204
+ """Check if this path is a prefix of another path.
205
+
206
+ A path is a prefix if the other path starts with this path
207
+ followed by a separator ("." or ":").
208
+
209
+ Examples::
210
+
211
+ Path("emails").is_prefix_of("emails.value") # True
212
+ Path("emails").is_prefix_of("emails") # False (equal, not prefix)
213
+ Path("urn:...:User").is_prefix_of("urn:...:User:name") # True
214
+ """
215
+ other_str = str(other).lower()
216
+ self_str = self.data.lower()
217
+
218
+ if self_str == other_str:
219
+ return False
220
+
221
+ return other_str.startswith(f"{self_str}.") or other_str.startswith(
222
+ f"{self_str}:"
223
+ )
224
+
225
+ def has_prefix(self, prefix: "str | Path[Any]") -> bool:
226
+ """Check if this path has the given prefix.
227
+
228
+ Examples::
229
+
230
+ Path("emails.value").has_prefix("emails") # True
231
+ Path("emails").has_prefix("emails") # False (equal, not prefix)
232
+ Path("urn:...:User:name").has_prefix("urn:...:User") # True
233
+ """
234
+ prefix_path = prefix if isinstance(prefix, Path) else Path(str(prefix))
235
+ return prefix_path.is_prefix_of(self)
236
+
237
+ @property
238
+ def model(self) -> type[BaseModel] | None:
239
+ """The target model type for this path.
240
+
241
+ Requires the Path to be bound to a model type via ``Path[Model]``.
242
+ Returns None if the path is unbound or invalid.
243
+
244
+ For "name.familyName" on Path[User], returns Name.
245
+ For "userName" on Path[User], returns User.
246
+ """
247
+ if (result := self._resolve_model()) is None:
248
+ return None
249
+ return result[0]
250
+
251
+ @property
252
+ def field_name(self) -> str | None:
253
+ """The Python attribute name (snake_case) for this path.
254
+
255
+ Requires the Path to be bound to a model type via ``Path[Model]``.
256
+ Returns None if the path is unbound or invalid.
257
+
258
+ For "name.familyName" on Path[User], returns "family_name".
259
+ For "userName" on Path[User], returns "user_name".
260
+ """
261
+ if (result := self._resolve_model()) is None:
262
+ return None
263
+ return result[1]
264
+
265
+ @property
266
+ def field_type(self) -> type | None:
267
+ """The Python type of the field this path points to.
268
+
269
+ Requires the Path to be bound to a model type via ``Path[Model]``.
270
+ Returns None if the path is unbound, invalid, or points to a schema-only path.
271
+
272
+ For "userName" on Path[User], returns str.
273
+ For "name" on Path[User], returns Name.
274
+ For "emails" on Path[User], returns Email.
275
+ """
276
+ if self.model is None or self.field_name is None:
277
+ return None
278
+ return self.model.get_field_root_type(self.field_name)
279
+
280
+ @property
281
+ def is_multivalued(self) -> bool | None:
282
+ """Whether this path points to a multi-valued attribute.
283
+
284
+ Requires the Path to be bound to a model type via ``Path[Model]``.
285
+ Returns None if the path is unbound, invalid, or points to a schema-only path.
286
+
287
+ For "emails" on Path[User], returns True.
288
+ For "userName" on Path[User], returns False.
289
+ """
290
+ if self.model is None or self.field_name is None:
291
+ return None
292
+ return self.model.get_field_multiplicity(self.field_name)
293
+
294
+ def get_annotation(self, annotation_type: type) -> Any:
295
+ """Get annotation value for this path's field.
296
+
297
+ Requires the Path to be bound to a model type via ``Path[Model]``.
298
+ Returns None if the path is unbound, invalid, or points to a schema-only path.
299
+
300
+ :param annotation_type: The annotation class (e.g., Required, Mutability).
301
+ :returns: The annotation value or None.
302
+
303
+ For "userName" on Path[User] with Required, returns Required.true.
304
+ """
305
+ if self.model is None or self.field_name is None:
306
+ return None
307
+ return self.model.get_field_annotation(self.field_name, annotation_type)
308
+
309
+ @property
310
+ def urn(self) -> str | None:
311
+ """The fully qualified URN for this path.
312
+
313
+ Requires the Path to be bound to a model type via ``Path[Model]``.
314
+ Returns None if the path is unbound or invalid.
315
+
316
+ For "userName" on Path[User], returns
317
+ "urn:ietf:params:scim:schemas:core:2.0:User:userName".
318
+ """
319
+ from .resources.resource import Resource
320
+
321
+ if self.__scim_model__ is None or self.model is None:
322
+ return None
323
+
324
+ schema = self.schema
325
+ if not schema and issubclass(self.__scim_model__, Resource):
326
+ schema = self.__scim_model__.__schema__
327
+
328
+ if not self.attr:
329
+ return schema if schema else None
330
+ return f"{schema}:{self.attr}" if schema else self.attr
331
+
332
+ def _resolve_model(self) -> tuple[type[BaseModel], str | None] | None:
333
+ """Resolve the path against the bound model type."""
334
+ from .resources.resource import Extension
335
+ from .resources.resource import Resource
336
+
337
+ model = self.__scim_model__
338
+ if model is None:
339
+ return None
340
+
341
+ attr_path = self.attr
342
+
343
+ if ":" in self and isclass(model) and issubclass(model, Resource | Extension):
344
+ path_lower = str(self).lower()
345
+
346
+ if model.__schema__ and path_lower == model.__schema__.lower():
347
+ return model, None
348
+ elif model.__schema__ and path_lower.startswith(model.__schema__.lower()):
349
+ attr_path = str(self)[len(model.__schema__) :].lstrip(":")
350
+ elif issubclass(model, Resource):
351
+ for (
352
+ extension_schema,
353
+ extension_model,
354
+ ) in model.get_extension_models().items():
355
+ schema_lower = extension_schema.lower()
356
+ if path_lower == schema_lower:
357
+ return extension_model, None
358
+ elif path_lower.startswith(schema_lower):
359
+ model = extension_model
360
+ break
361
+ else:
362
+ return None
363
+
364
+ if not attr_path:
365
+ return model, None
366
+
367
+ if "." in attr_path:
368
+ parts = attr_path.split(".")
369
+ current_model = model
370
+
371
+ for part in parts[:-1]:
372
+ if (field_name := _find_field_name(current_model, part)) is None:
373
+ return None
374
+ field_type = current_model.get_field_root_type(field_name)
375
+ if (
376
+ field_type is None
377
+ or not isclass(field_type)
378
+ or not issubclass(field_type, BaseModel)
379
+ ):
380
+ return None
381
+ current_model = field_type
382
+
383
+ if (field_name := _find_field_name(current_model, parts[-1])) is None:
384
+ return None
385
+ return current_model, field_name
386
+
387
+ if (field_name := _find_field_name(model, attr_path)) is None:
388
+ return None
389
+ return model, field_name
390
+
391
+ def _resolve_instance(
392
+ self, resource: BaseModel, *, create: bool = False
393
+ ) -> _Resolution | None:
394
+ """Resolve the target object and remaining path.
395
+
396
+ :param resource: The resource to resolve against.
397
+ :param create: If True, create extension instance if it doesn't exist.
398
+ :returns: Resolution with target object and path, or None if target doesn't exist.
399
+ :raises InvalidPathException: If the path references an unknown extension.
400
+ """
401
+ from .resources.resource import Extension
402
+ from .resources.resource import Resource
403
+
404
+ path_str = str(self)
405
+
406
+ if ":" not in path_str:
407
+ return _Resolution(resource, path_str)
408
+
409
+ model_schema = getattr(type(resource), "__schema__", "") or ""
410
+ path_lower = path_str.lower()
411
+
412
+ if isinstance(resource, Resource | Extension) and path_lower.startswith(
413
+ model_schema.lower()
414
+ ):
415
+ is_explicit = path_lower == model_schema.lower()
416
+ normalized = path_str[len(model_schema) :].lstrip(":")
417
+ return _Resolution(resource, normalized, is_explicit)
418
+
419
+ if isinstance(resource, Resource):
420
+ for ext_schema, ext_model in resource.get_extension_models().items():
421
+ ext_schema_lower = ext_schema.lower()
422
+ if path_lower == ext_schema_lower:
423
+ return _Resolution(resource, ext_model.__name__)
424
+ if path_lower.startswith(ext_schema_lower):
425
+ sub_path = path_str[len(ext_schema) :].lstrip(":")
426
+ ext_obj = getattr(resource, ext_model.__name__)
427
+ if create and ext_obj is None:
428
+ ext_obj = ext_model()
429
+ setattr(resource, ext_model.__name__, ext_obj)
430
+ if ext_obj is None:
431
+ return None
432
+ return _Resolution(ext_obj, sub_path)
433
+
434
+ raise InvalidPathException(path=str(self))
435
+
436
+ return None
437
+
438
+ def _walk_to_target(
439
+ self, obj: BaseModel, path_str: str
440
+ ) -> tuple[BaseModel, str] | None:
441
+ """Navigate to the target object and field.
442
+
443
+ :returns: (target_obj, field_name) or None if an intermediate is None.
444
+ """
445
+ if "." not in path_str:
446
+ return obj, _require_field(type(obj), path_str)
447
+
448
+ parts = path_str.split(".")
449
+ current_obj = obj
450
+
451
+ for part in parts[:-1]:
452
+ field_name = _require_field(type(current_obj), part)
453
+ if (current_obj := getattr(current_obj, field_name)) is None:
454
+ return None
455
+
456
+ return current_obj, _require_field(type(current_obj), parts[-1])
457
+
458
+ def _get(self, resource: ResourceT) -> Any:
459
+ """Get the value at this path from a resource."""
460
+ if (resolution := self._resolve_instance(resource)) is None:
461
+ return None
462
+
463
+ if not resolution.path_str:
464
+ return resolution.target
465
+
466
+ if (
467
+ result := self._walk_to_target(resolution.target, resolution.path_str)
468
+ ) is None:
469
+ return None
470
+
471
+ obj, field_name = result
472
+ return getattr(obj, field_name)
473
+
474
+ def get(self, resource: ResourceT, *, strict: bool = True) -> Any:
475
+ """Get the value at this path from a resource.
476
+
477
+ :param resource: The resource to get the value from.
478
+ :param strict: If True, raise exceptions for invalid paths.
479
+ :returns: The value at this path, or None if the value is absent.
480
+ :raises PathNotFoundException: If strict and the path references a non-existent field.
481
+ :raises InvalidPathException: If strict and the path references an unknown extension.
482
+ """
483
+ try:
484
+ return self._get(resource)
485
+ except InvalidPathException:
486
+ if strict:
487
+ raise
488
+ return None
489
+
490
+ def _set(self, resource: ResourceT, value: Any, *, is_add: bool = False) -> bool:
491
+ """Set a value at this path on a resource."""
492
+ if (resolution := self._resolve_instance(resource, create=True)) is None:
493
+ return False
494
+
495
+ obj = resolution.target
496
+ path_str = resolution.path_str
497
+ is_explicit_schema_path = resolution.is_explicit_schema_path
498
+
499
+ if not path_str:
500
+ if not isinstance(value, dict):
501
+ if is_explicit_schema_path:
502
+ raise InvalidPathException(path=str(self))
503
+ return False
504
+ filtered_value = {
505
+ k: v
506
+ for k, v in value.items()
507
+ if _find_field_name(type(obj), k) is not None
508
+ }
509
+ if not filtered_value:
510
+ return False
511
+ old_data = obj.model_dump()
512
+ updated_data = {**old_data, **filtered_value}
513
+ if updated_data == old_data:
514
+ return False
515
+ updated_obj = type(obj).model_validate(updated_data)
516
+ obj.__dict__.update(updated_obj.__dict__)
517
+ return True
518
+
519
+ if "." not in path_str:
520
+ field_name = _require_field(type(obj), path_str)
521
+ return self._set_field_value(obj, field_name, value, is_add)
522
+
523
+ parts = path_str.split(".")
524
+ current_obj = obj
525
+
526
+ for part in parts[:-1]:
527
+ field_name = _require_field(type(current_obj), part)
528
+ if (sub_obj := getattr(current_obj, field_name)) is None:
529
+ field_type = type(current_obj).get_field_root_type(field_name)
530
+ if field_type is None or field_type is Any or not isclass(field_type):
531
+ return False
532
+ sub_obj = field_type()
533
+ setattr(current_obj, field_name, sub_obj)
534
+ elif isinstance(sub_obj, list):
535
+ return False
536
+ current_obj = sub_obj
537
+
538
+ field_name = _require_field(type(current_obj), parts[-1])
539
+ return self._set_field_value(current_obj, field_name, value, is_add)
540
+
541
+ def set(
542
+ self,
543
+ resource: ResourceT,
544
+ value: Any,
545
+ *,
546
+ is_add: bool = False,
547
+ strict: bool = True,
548
+ ) -> bool:
549
+ """Set a value at this path on a resource.
550
+
551
+ :param resource: The resource to set the value on.
552
+ :param value: The value to set.
553
+ :param is_add: If True and the target is multi-valued, append to the
554
+ list instead of replacing. Duplicates are not added.
555
+ :param strict: If True, raise exceptions for invalid paths.
556
+ :returns: True if the value was set/added, False if unchanged.
557
+ :raises InvalidPathException: If strict and the path does not exist or is invalid.
558
+ """
559
+ try:
560
+ return self._set(resource, value, is_add=is_add)
561
+ except InvalidPathException:
562
+ if strict:
563
+ raise
564
+ return False
565
+
566
+ @staticmethod
567
+ def _set_field_value(
568
+ obj: BaseModel, field_name: str, value: Any, is_add: bool
569
+ ) -> bool:
570
+ """Set or add a value to a field."""
571
+ is_multivalued = obj.get_field_multiplicity(field_name)
572
+
573
+ if is_add and is_multivalued:
574
+ current_list = getattr(obj, field_name) or []
575
+ if isinstance(value, list):
576
+ new_values = [v for v in value if not _value_in_list(current_list, v)]
577
+ if not new_values:
578
+ return False
579
+ setattr(obj, field_name, current_list + new_values)
580
+ else:
581
+ if _value_in_list(current_list, value):
582
+ return False
583
+ current_list.append(value)
584
+ setattr(obj, field_name, current_list)
585
+ return True
586
+
587
+ if is_multivalued and not isinstance(value, list) and value is not None:
588
+ value = [value]
589
+
590
+ old_value = getattr(obj, field_name)
591
+ if old_value == value:
592
+ return False
593
+
594
+ setattr(obj, field_name, value)
595
+ return True
596
+
597
+ def _delete(self, resource: ResourceT, value: Any | None = None) -> bool:
598
+ """Delete a value at this path from a resource."""
599
+ if (resolution := self._resolve_instance(resource)) is None:
600
+ return False
601
+
602
+ if not resolution.path_str:
603
+ raise InvalidPathException(path=str(self))
604
+
605
+ if (
606
+ result := self._walk_to_target(resolution.target, resolution.path_str)
607
+ ) is None:
608
+ return False
609
+
610
+ obj, field_name = result
611
+ if (current_value := getattr(obj, field_name)) is None:
612
+ return False
613
+
614
+ if value is not None:
615
+ if not isinstance(current_value, list):
616
+ return False
617
+ new_list = [
618
+ item for item in current_value if not _values_match(item, value)
619
+ ]
620
+ if len(new_list) == len(current_value):
621
+ return False
622
+ setattr(obj, field_name, new_list if new_list else None)
623
+ return True
624
+
625
+ setattr(obj, field_name, None)
626
+ return True
627
+
628
+ def delete(
629
+ self, resource: ResourceT, value: Any | None = None, *, strict: bool = True
630
+ ) -> bool:
631
+ """Delete a value at this path from a resource.
632
+
633
+ If value is None, the entire attribute is set to None.
634
+ If value is provided and the attribute is multi-valued,
635
+ only matching values are removed from the list.
636
+
637
+ :param resource: The resource to delete the value from.
638
+ :param value: Optional specific value to remove from a list.
639
+ :param strict: If True, raise exceptions for invalid paths.
640
+ :returns: True if a value was deleted, False if unchanged.
641
+ :raises InvalidPathException: If strict and the path does not exist or is invalid.
642
+ """
643
+ try:
644
+ return self._delete(resource, value)
645
+ except InvalidPathException:
646
+ if strict:
647
+ raise
648
+ return False
649
+
650
+ @classmethod
651
+ def iter_paths(
652
+ cls,
653
+ include_subattributes: bool = True,
654
+ include_extensions: bool = True,
655
+ required: "list[Required] | None" = None,
656
+ mutability: "list[Mutability] | None" = None,
657
+ ) -> "Iterator[Path[ResourceT]]":
658
+ """Iterate over all paths for the bound model and its extensions.
659
+
660
+ Requires the Path to be bound to a model type via ``Path[Model]``.
661
+
662
+ :param include_subattributes: Whether to include sub-attribute paths.
663
+ :param include_extensions: Whether to include extension attributes.
664
+ :param required: Filter by Required annotation values (e.g., [Required.true]).
665
+ :param mutability: Filter by Mutability annotation values (e.g., [Mutability.read_write]).
666
+ :yields: Path instances for each attribute matching the filters.
667
+ """
668
+ from .annotations import Mutability
669
+ from .annotations import Required
670
+ from .attributes import ComplexAttribute
671
+ from .resources.resource import Extension
672
+ from .resources.resource import Resource
673
+
674
+ model = cls.__scim_model__
675
+ if model is None:
676
+ raise TypeError("iter_paths requires a bound Path type: Path[Model]")
677
+
678
+ def matches_filters(target_model: type[BaseModel], field_name: str) -> bool:
679
+ if required is not None:
680
+ field_required = target_model.get_field_annotation(field_name, Required)
681
+ if field_required not in required:
682
+ return False
683
+ if mutability is not None:
684
+ field_mutability = target_model.get_field_annotation(
685
+ field_name, Mutability
686
+ )
687
+ if field_mutability not in mutability:
688
+ return False
689
+ return True
690
+
691
+ def iter_model_paths(
692
+ target_model: type[Resource[Any] | Extension],
693
+ ) -> "Iterator[Path[ResourceT]]":
694
+ for field_name in target_model.model_fields:
695
+ if field_name in ("meta", "id", "schemas"):
696
+ continue
697
+
698
+ if not matches_filters(target_model, field_name):
699
+ continue
700
+
701
+ field_type = target_model.get_field_root_type(field_name)
702
+
703
+ urn: str
704
+ if isclass(field_type) and issubclass(field_type, Extension):
705
+ if not include_extensions:
706
+ continue
707
+ urn = field_type.__schema__ or ""
708
+ elif isclass(target_model) and issubclass(target_model, Extension):
709
+ urn = target_model().get_attribute_urn(field_name)
710
+ else:
711
+ urn = _to_camel(field_name)
712
+
713
+ yield cls(urn)
714
+
715
+ is_complex = (
716
+ field_type is not None
717
+ and isclass(field_type)
718
+ and issubclass(field_type, ComplexAttribute)
719
+ )
720
+ if include_subattributes and is_complex:
721
+ for sub_field_name in field_type.model_fields: # type: ignore[union-attr]
722
+ if not matches_filters(field_type, sub_field_name): # type: ignore[arg-type]
723
+ continue
724
+ sub_urn = f"{urn}.{_to_camel(sub_field_name)}"
725
+ yield cls(sub_urn)
726
+
727
+ yield from iter_model_paths(model) # type: ignore[arg-type]
728
+
729
+ if include_extensions and isclass(model) and issubclass(model, Resource):
730
+ for extension_model in model.get_extension_models().values():
731
+ yield from iter_model_paths(extension_model)