led-controller-version-3 3.0.2__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.
Files changed (52) hide show
  1. led_controller_version_3-3.0.2.dist-info/METADATA +172 -0
  2. led_controller_version_3-3.0.2.dist-info/RECORD +52 -0
  3. led_controller_version_3-3.0.2.dist-info/WHEEL +4 -0
  4. led_controller_version_3-3.0.2.dist-info/entry_points.txt +13 -0
  5. lefx/device/respeaker/__init__.py +35 -0
  6. lefx/device/respeaker/cli.py +146 -0
  7. lefx/device/respeaker/contention.py +523 -0
  8. lefx/device/respeaker/provider.py +158 -0
  9. lefx/device/respeaker/registration.py +130 -0
  10. lefx/device/respeaker/sink.py +108 -0
  11. lefx/device/respeaker/transport.py +344 -0
  12. lefx/device/respeaker/xvf.py +313 -0
  13. lefx/engine/__init__.py +110 -0
  14. lefx/engine/composer.py +203 -0
  15. lefx/engine/config.py +27 -0
  16. lefx/engine/errors.py +84 -0
  17. lefx/engine/inputs.py +196 -0
  18. lefx/engine/invocation.py +129 -0
  19. lefx/engine/layers.py +114 -0
  20. lefx/engine/library.py +181 -0
  21. lefx/engine/packages/__init__.py +45 -0
  22. lefx/engine/packages/loader.py +375 -0
  23. lefx/engine/packages/manifest.py +308 -0
  24. lefx/engine/registry.py +347 -0
  25. lefx/engine/renderer.py +63 -0
  26. lefx/engine/runtime.py +393 -0
  27. lefx/engine/store.py +125 -0
  28. lefx/interfaces/__init__.py +40 -0
  29. lefx/interfaces/api.py +301 -0
  30. lefx/interfaces/cli.py +380 -0
  31. lefx/interfaces/client.py +165 -0
  32. lefx/interfaces/config.py +305 -0
  33. lefx/interfaces/discovery.py +308 -0
  34. lefx/interfaces/hosting.py +123 -0
  35. lefx/interfaces/paths.py +79 -0
  36. lefx/interfaces/presentation.py +118 -0
  37. lefx/interfaces/service.py +468 -0
  38. lefx/sdk/__init__.py +176 -0
  39. lefx/sdk/calibration.py +202 -0
  40. lefx/sdk/color.py +108 -0
  41. lefx/sdk/context.py +72 -0
  42. lefx/sdk/definitions.py +526 -0
  43. lefx/sdk/effects.py +63 -0
  44. lefx/sdk/errors.py +90 -0
  45. lefx/sdk/parameters.py +469 -0
  46. lefx/sdk/ports.py +76 -0
  47. lefx/sdk/validation.py +150 -0
  48. lefx/sdk/values.py +212 -0
  49. lefx/sets/core_set/__init__.py +32 -0
  50. lefx/sets/core_set/core-set.lefxset +0 -0
  51. lefx/sets/smartspeaker_set/__init__.py +32 -0
  52. lefx/sets/smartspeaker_set/smartspeaker-set.lefxset +0 -0
@@ -0,0 +1,308 @@
1
+ """Serializing a definition into a package manifest, and checking it back.
2
+
3
+ The Python class is the source of truth for the contract. The manifest is a
4
+ serialized copy that lets tooling read a package without executing it — and,
5
+ more importantly, lets the loader prove that the metadata shipped in the archive
6
+ still describes the class inside it.
7
+
8
+ The check is a whole-structure comparison rather than a field walk: the
9
+ definition is re-serialized after import and the two dictionaries must be equal.
10
+ A field added later is therefore covered automatically instead of being
11
+ silently unchecked.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from typing import Any, Mapping
17
+
18
+ from lefx.sdk import (
19
+ MISSING,
20
+ ControlledOverlayDefinition,
21
+ DefinitionBase,
22
+ DefinitionKind,
23
+ EventDefinition,
24
+ ParamDefinition,
25
+ StateDefinition,
26
+ )
27
+
28
+ from ..errors import PackageError
29
+
30
+ PACKAGE_FORMAT = "lefx/3"
31
+ SET_FORMAT = "lefxset/3"
32
+
33
+ MANIFEST_NAME = "manifest.json"
34
+ SET_MANIFEST_NAME = "set-manifest.json"
35
+ PRESETS_NAME = "effect-presets.json"
36
+ HASHES_NAME = "hashes.json"
37
+ PAYLOAD_DIR = "payload"
38
+
39
+
40
+ def serialize_param(param: ParamDefinition) -> dict[str, Any]:
41
+ payload: dict[str, Any] = {
42
+ "name": param.name,
43
+ "type": param.type.value,
44
+ "required": param.required,
45
+ "description": param.description,
46
+ "minimum": param.minimum,
47
+ "maximum": param.maximum,
48
+ "enum_values": list(param.enum_values),
49
+ "unit": param.unit,
50
+ "nullable": param.nullable,
51
+ "aliases": list(param.aliases),
52
+ }
53
+ # "no default" and "defaults to null" are different states, so the key is
54
+ # present only when a default was actually declared.
55
+ if param.has_default:
56
+ payload["default"] = param.default
57
+ return payload
58
+
59
+
60
+ def serialize_schema(schema: Mapping[str, ParamDefinition]) -> dict[str, Any]:
61
+ return {name: serialize_param(param) for name, param in schema.items()}
62
+
63
+
64
+ def serialize_definition(definition: DefinitionBase) -> dict[str, Any]:
65
+ """The complete contract of one definition as plain JSON-compatible data."""
66
+ payload: dict[str, Any] = {
67
+ "kind": definition.kind.value,
68
+ "definition_type": definition.definition_type.value,
69
+ "overlay_mode": None
70
+ if definition.overlay_mode is None
71
+ else definition.overlay_mode.value,
72
+ "id": definition.id,
73
+ "title": definition.title,
74
+ "description": definition.description,
75
+ "version": definition.version,
76
+ "tags": list(definition.tags),
77
+ "visual": {
78
+ "color_model": definition.color_model.value,
79
+ "composition": definition.composition.value,
80
+ "animated": definition.animated,
81
+ "directional": definition.directional,
82
+ },
83
+ "parameter_schema": serialize_schema(definition.parameter_schema),
84
+ "runtime_input_schema": serialize_schema(definition.runtime_input_schema),
85
+ "input_sampling": None,
86
+ "form": {},
87
+ }
88
+
89
+ if isinstance(definition, StateDefinition):
90
+ payload["form"] = {
91
+ "slots": [slot.value for slot in definition.slots],
92
+ "restorable": definition.restorable,
93
+ }
94
+ elif isinstance(definition, ControlledOverlayDefinition):
95
+ policy = definition.sampling
96
+ payload["input_sampling"] = {
97
+ "mode": policy.mode.value,
98
+ "provider_id": policy.provider_id,
99
+ "interval_ms": policy.interval_ms,
100
+ "heartbeat_interval_ms": policy.heartbeat_interval_ms,
101
+ "max_missed_heartbeats": policy.max_missed_heartbeats,
102
+ "failure_after_ms": policy.failure_after_ms,
103
+ }
104
+ else:
105
+ payload["form"] = {
106
+ "duration_field": definition.duration_field.value, # type: ignore[attr-defined]
107
+ "supports_duration_override": definition.supports_duration_override, # type: ignore[attr-defined]
108
+ }
109
+ if isinstance(definition, EventDefinition):
110
+ payload["form"]["default_priority"] = definition.default_priority
111
+
112
+ return payload
113
+
114
+
115
+ def build_package_manifest(
116
+ definition: DefinitionBase,
117
+ *,
118
+ source_id: str,
119
+ package_id: str,
120
+ entry_module: str,
121
+ entry_class: str,
122
+ package_version: int = 1,
123
+ min_sdk_version: str = "3.0.0",
124
+ author: str | None = None,
125
+ vendor: str | None = None,
126
+ license_id: str | None = None,
127
+ built_at: str | None = None,
128
+ compatible_hardware: tuple[str, ...] = (),
129
+ ) -> dict[str, Any]:
130
+ manifest: dict[str, Any] = {
131
+ "format": PACKAGE_FORMAT,
132
+ "source_id": source_id,
133
+ "package_id": package_id,
134
+ "effect_id": definition.id,
135
+ "qualified_id": f"{source_id}::{definition.id}",
136
+ "package_version": package_version,
137
+ "min_sdk_version": min_sdk_version,
138
+ "runtime": "python",
139
+ "entry_module": entry_module,
140
+ "entry_class": entry_class,
141
+ "definition": serialize_definition(definition),
142
+ }
143
+ optional = {
144
+ "author": author,
145
+ "vendor": vendor,
146
+ "license": license_id,
147
+ "built_at": built_at,
148
+ }
149
+ manifest.update({key: value for key, value in optional.items() if value is not None})
150
+ if compatible_hardware:
151
+ manifest["compatible_hardware"] = list(compatible_hardware)
152
+ return manifest
153
+
154
+
155
+ _REQUIRED_PACKAGE_KEYS = (
156
+ "format",
157
+ "source_id",
158
+ "package_id",
159
+ "effect_id",
160
+ "package_version",
161
+ "entry_module",
162
+ "entry_class",
163
+ "definition",
164
+ )
165
+
166
+ _ALLOWED_PACKAGE_KEYS = frozenset(
167
+ _REQUIRED_PACKAGE_KEYS
168
+ + (
169
+ "qualified_id",
170
+ "min_sdk_version",
171
+ "runtime",
172
+ "author",
173
+ "vendor",
174
+ "license",
175
+ "built_at",
176
+ "compatible_hardware",
177
+ )
178
+ )
179
+
180
+
181
+ def parse_package_manifest(payload: Mapping[str, Any]) -> dict[str, Any]:
182
+ """Validate the envelope. Unknown keys are refused, never ignored."""
183
+ if not isinstance(payload, Mapping):
184
+ raise PackageError("Package manifest must be an object")
185
+ if payload.get("format") != PACKAGE_FORMAT:
186
+ raise PackageError(
187
+ f"Unsupported package format {payload.get('format')!r}; expected "
188
+ f"{PACKAGE_FORMAT!r}. V1 and V2 packages are not read by this runtime."
189
+ )
190
+ missing = [key for key in _REQUIRED_PACKAGE_KEYS if key not in payload]
191
+ if missing:
192
+ raise PackageError(f"Package manifest is missing: {', '.join(missing)}")
193
+ unknown = set(payload) - _ALLOWED_PACKAGE_KEYS
194
+ if unknown:
195
+ raise PackageError(f"Package manifest has unknown keys: {', '.join(sorted(unknown))}")
196
+ if not isinstance(payload["definition"], Mapping):
197
+ raise PackageError("Package manifest 'definition' must be an object")
198
+ return dict(payload)
199
+
200
+
201
+ _REQUIRED_SET_KEYS = ("format", "set_id", "source_id", "effects")
202
+ _ALLOWED_SET_KEYS = frozenset(
203
+ _REQUIRED_SET_KEYS
204
+ + (
205
+ "title",
206
+ "description",
207
+ "version",
208
+ "min_sdk_version",
209
+ "tags",
210
+ "author",
211
+ "vendor",
212
+ "license",
213
+ "built_at",
214
+ )
215
+ )
216
+
217
+
218
+ def parse_set_manifest(payload: Mapping[str, Any]) -> dict[str, Any]:
219
+ if not isinstance(payload, Mapping):
220
+ raise PackageError("Set manifest must be an object")
221
+ if payload.get("format") != SET_FORMAT:
222
+ raise PackageError(
223
+ f"Unsupported set format {payload.get('format')!r}; expected {SET_FORMAT!r}"
224
+ )
225
+ missing = [key for key in _REQUIRED_SET_KEYS if key not in payload]
226
+ if missing:
227
+ raise PackageError(f"Set manifest is missing: {', '.join(missing)}")
228
+ unknown = set(payload) - _ALLOWED_SET_KEYS
229
+ if unknown:
230
+ raise PackageError(f"Set manifest has unknown keys: {', '.join(sorted(unknown))}")
231
+ if not isinstance(payload["effects"], list) or not payload["effects"]:
232
+ raise PackageError("Set manifest must list at least one member")
233
+ return dict(payload)
234
+
235
+
236
+ def check_manifest_matches_definition(
237
+ manifest: Mapping[str, Any], definition: DefinitionBase
238
+ ) -> None:
239
+ """Refuse a package whose metadata drifted from the class it ships."""
240
+ declared = manifest["definition"]
241
+ actual = serialize_definition(definition)
242
+ if declared == actual:
243
+ return
244
+ differences = _describe_differences(declared, actual)
245
+ raise PackageError(
246
+ f"Package manifest does not match the definition in {manifest['effect_id']!r}: "
247
+ + "; ".join(differences)
248
+ )
249
+
250
+
251
+ def _describe_differences(declared: Any, actual: Any, path: str = "") -> list[str]:
252
+ if isinstance(declared, Mapping) and isinstance(actual, Mapping):
253
+ notes: list[str] = []
254
+ for key in sorted(set(declared) | set(actual)):
255
+ child = f"{path}.{key}" if path else str(key)
256
+ if key not in declared:
257
+ notes.append(f"{child} only in class")
258
+ elif key not in actual:
259
+ notes.append(f"{child} only in manifest")
260
+ else:
261
+ notes.extend(_describe_differences(declared[key], actual[key], child))
262
+ return notes
263
+ if declared != actual:
264
+ return [f"{path or 'definition'}: manifest {declared!r} != class {actual!r}"]
265
+ return []
266
+
267
+
268
+ def param_from_payload(payload: Mapping[str, Any]) -> ParamDefinition:
269
+ """Rebuild a declaration from manifest data, for tooling that inspects packages."""
270
+ from lefx.sdk import ParamType
271
+
272
+ return ParamDefinition(
273
+ name=payload["name"],
274
+ type=ParamType(payload["type"]),
275
+ default=payload["default"] if "default" in payload else MISSING,
276
+ required=bool(payload.get("required", False)),
277
+ description=payload.get("description", ""),
278
+ minimum=payload.get("minimum"),
279
+ maximum=payload.get("maximum"),
280
+ enum_values=tuple(payload.get("enum_values", ())),
281
+ unit=payload.get("unit"),
282
+ nullable=bool(payload.get("nullable", False)),
283
+ aliases=tuple(payload.get("aliases", ())),
284
+ )
285
+
286
+
287
+ def definition_kind_of(manifest: Mapping[str, Any]) -> DefinitionKind:
288
+ return DefinitionKind(manifest["definition"]["kind"])
289
+
290
+
291
+ __all__ = [
292
+ "HASHES_NAME",
293
+ "MANIFEST_NAME",
294
+ "PACKAGE_FORMAT",
295
+ "PAYLOAD_DIR",
296
+ "PRESETS_NAME",
297
+ "SET_FORMAT",
298
+ "SET_MANIFEST_NAME",
299
+ "build_package_manifest",
300
+ "check_manifest_matches_definition",
301
+ "definition_kind_of",
302
+ "param_from_payload",
303
+ "parse_package_manifest",
304
+ "parse_set_manifest",
305
+ "serialize_definition",
306
+ "serialize_param",
307
+ "serialize_schema",
308
+ ]
@@ -0,0 +1,347 @@
1
+ """What is loaded, and how a name turns into it.
2
+
3
+ Definition ids and preset ids share one public namespace, so a short name always
4
+ means one thing. Qualified forms exist for diagnostics and for choosing between
5
+ sources deliberately; they are exact aliases, never fuzzy matches.
6
+
7
+ Nothing is ever run on a guess. A miss suggests near matches, and an ambiguity
8
+ is refused outright.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass, field
14
+ from difflib import get_close_matches
15
+ from types import MappingProxyType
16
+ from typing import Any, Iterable, Mapping
17
+
18
+ from lefx.sdk import (
19
+ BaseEffect,
20
+ DefinitionBase,
21
+ DefinitionType,
22
+ ParameterValidationError,
23
+ resolve_configuration,
24
+ )
25
+
26
+ from .errors import (
27
+ AmbiguousTargetError,
28
+ RegistrationError,
29
+ TargetNotFoundError,
30
+ WrongTargetTypeError,
31
+ )
32
+
33
+
34
+ @dataclass(slots=True, frozen=True)
35
+ class Preset:
36
+ """A named starting point for one definition's configuration.
37
+
38
+ A preset is a convenience, never a restriction: a caller may take it as is
39
+ or override any value the schema allows. It cannot change type, placement or
40
+ lifecycle, and it carries no runtime inputs.
41
+ """
42
+
43
+ preset_id: str
44
+ source_id: str
45
+ effect_id: str
46
+ params: Mapping[str, Any] = field(default_factory=dict)
47
+ title: str = ""
48
+ description: str = ""
49
+ tags: tuple[str, ...] = ()
50
+
51
+ @property
52
+ def qualified_id(self) -> str:
53
+ return f"{self.source_id}::{self.preset_id}"
54
+
55
+ def to_dict(self) -> dict[str, Any]:
56
+ return {
57
+ "preset_id": self.preset_id,
58
+ "qualified_id": self.qualified_id,
59
+ "source_id": self.source_id,
60
+ "effect_id": self.effect_id,
61
+ "title": self.title or self.preset_id,
62
+ "description": self.description,
63
+ "tags": list(self.tags),
64
+ "config": dict(self.params),
65
+ }
66
+
67
+
68
+ @dataclass(slots=True, frozen=True)
69
+ class RegisteredEffect:
70
+ """One definition as the registry knows it, together with its origin."""
71
+
72
+ definition: DefinitionBase
73
+ effect_class: type[BaseEffect]
74
+ source_id: str
75
+ package_id: str | None = None
76
+ package_version: int | None = None
77
+
78
+ @property
79
+ def effect_id(self) -> str:
80
+ return self.definition.id
81
+
82
+ @property
83
+ def qualified_id(self) -> str:
84
+ return f"{self.source_id}::{self.definition.id}"
85
+
86
+
87
+ @dataclass(slots=True, frozen=True)
88
+ class ResolvedTarget:
89
+ """What a caller-supplied name turned out to mean."""
90
+
91
+ effect: RegisteredEffect
92
+ preset: Preset | None = None
93
+
94
+ @property
95
+ def kind(self) -> str:
96
+ return "preset" if self.preset is not None else "definition"
97
+
98
+ @property
99
+ def target_id(self) -> str:
100
+ return self.preset.preset_id if self.preset is not None else self.effect.effect_id
101
+
102
+
103
+ class EffectRegistry:
104
+ """Holds every loaded definition and preset and resolves names against them."""
105
+
106
+ def __init__(self) -> None:
107
+ self._effects: dict[str, RegisteredEffect] = {}
108
+ self._presets: dict[str, Preset] = {}
109
+ self._aliases: dict[str, str] = {}
110
+ self._preset_aliases: dict[str, str] = {}
111
+
112
+ # -- registration -------------------------------------------------------
113
+
114
+ def register_effect(
115
+ self,
116
+ effect_class: type[BaseEffect],
117
+ *,
118
+ source_id: str,
119
+ package_id: str | None = None,
120
+ package_version: int | None = None,
121
+ ) -> RegisteredEffect:
122
+ definition = _definition_of(effect_class)
123
+ if definition.id in self._effects:
124
+ existing = self._effects[definition.id]
125
+ raise RegistrationError(
126
+ f"Definition id {definition.id!r} is already registered from source "
127
+ f"{existing.source_id!r}; ids are globally unique"
128
+ )
129
+ if definition.id in self._presets:
130
+ raise RegistrationError(
131
+ f"Definition id {definition.id!r} collides with a preset of the same name"
132
+ )
133
+
134
+ registered = RegisteredEffect(
135
+ definition=definition,
136
+ effect_class=effect_class,
137
+ source_id=source_id,
138
+ package_id=package_id,
139
+ package_version=package_version,
140
+ )
141
+ self._effects[definition.id] = registered
142
+ self._aliases[registered.qualified_id] = definition.id
143
+ self._aliases[f"{source_id}.{definition.id}"] = definition.id
144
+ if package_id:
145
+ self._aliases[package_id] = definition.id
146
+ return registered
147
+
148
+ def register_preset(self, preset: Preset) -> Preset:
149
+ if preset.preset_id in self._presets:
150
+ existing = self._presets[preset.preset_id]
151
+ raise RegistrationError(
152
+ f"Preset id {preset.preset_id!r} is already registered from source "
153
+ f"{existing.source_id!r}; ids are globally unique"
154
+ )
155
+ if preset.preset_id in self._effects:
156
+ raise RegistrationError(
157
+ f"Preset id {preset.preset_id!r} collides with a definition of the same name"
158
+ )
159
+ effect = self._effects.get(preset.effect_id)
160
+ if effect is None:
161
+ raise RegistrationError(
162
+ f"Preset {preset.preset_id!r} references unknown definition "
163
+ f"{preset.effect_id!r}"
164
+ )
165
+ try:
166
+ # Presets are configuration and nothing else. Validating on
167
+ # registration means a broken one is found when it is loaded, not
168
+ # when somebody happens to activate it.
169
+ resolve_configuration(effect.definition, preset=preset.params)
170
+ except ParameterValidationError as exc:
171
+ raise RegistrationError(
172
+ f"Preset {preset.preset_id!r} does not satisfy the schema of "
173
+ f"{preset.effect_id!r}: {exc}"
174
+ ) from exc
175
+
176
+ self._presets[preset.preset_id] = preset
177
+ self._preset_aliases[preset.qualified_id] = preset.preset_id
178
+ self._preset_aliases[f"{preset.source_id}.{preset.preset_id}"] = preset.preset_id
179
+ return preset
180
+
181
+ def remove_source(self, source_id: str) -> None:
182
+ """Drop everything a source contributed, in one step."""
183
+ for effect_id in [
184
+ key for key, value in self._effects.items() if value.source_id == source_id
185
+ ]:
186
+ del self._effects[effect_id]
187
+ for preset_id in [
188
+ key for key, value in self._presets.items() if value.source_id == source_id
189
+ ]:
190
+ del self._presets[preset_id]
191
+ self._rebuild_aliases()
192
+
193
+ def clear(self) -> None:
194
+ self._effects.clear()
195
+ self._presets.clear()
196
+ self._aliases.clear()
197
+ self._preset_aliases.clear()
198
+
199
+ def _rebuild_aliases(self) -> None:
200
+ self._aliases.clear()
201
+ self._preset_aliases.clear()
202
+ for effect in self._effects.values():
203
+ self._aliases[effect.qualified_id] = effect.effect_id
204
+ self._aliases[f"{effect.source_id}.{effect.effect_id}"] = effect.effect_id
205
+ if effect.package_id:
206
+ self._aliases[effect.package_id] = effect.effect_id
207
+ for preset in self._presets.values():
208
+ self._preset_aliases[preset.qualified_id] = preset.preset_id
209
+ self._preset_aliases[f"{preset.source_id}.{preset.preset_id}"] = preset.preset_id
210
+
211
+ # -- lookup -------------------------------------------------------------
212
+
213
+ def get(self, effect_id: str) -> RegisteredEffect:
214
+ effect = self._effects.get(effect_id)
215
+ if effect is None:
216
+ raise TargetNotFoundError(effect_id, suggestions=self._suggest(effect_id))
217
+ return effect
218
+
219
+ def get_preset(self, preset_id: str) -> Preset:
220
+ preset = self._presets.get(preset_id)
221
+ if preset is None:
222
+ raise TargetNotFoundError(preset_id, suggestions=self._suggest(preset_id))
223
+ return preset
224
+
225
+ def resolve(
226
+ self, target: str, *, expected_type: DefinitionType | None = None
227
+ ) -> ResolvedTarget:
228
+ """Turn a caller-supplied name into a definition and optional preset."""
229
+ name = str(target or "").strip()
230
+ if not name:
231
+ raise TargetNotFoundError(target)
232
+
233
+ matches: list[ResolvedTarget] = []
234
+ registered = self._effects.get(name)
235
+ if registered is None:
236
+ aliased = self._aliases.get(name)
237
+ registered = None if aliased is None else self._effects.get(aliased)
238
+ if registered is not None:
239
+ matches.append(ResolvedTarget(effect=registered))
240
+
241
+ preset = self._presets.get(name)
242
+ if preset is None:
243
+ aliased = self._preset_aliases.get(name)
244
+ preset = None if aliased is None else self._presets[aliased]
245
+ if preset is not None:
246
+ matches.append(
247
+ ResolvedTarget(effect=self._effects[preset.effect_id], preset=preset)
248
+ )
249
+
250
+ if not matches:
251
+ raise TargetNotFoundError(name, suggestions=self._suggest(name))
252
+ if len(matches) > 1:
253
+ raise AmbiguousTargetError(
254
+ name, tuple(sorted(match.effect.qualified_id for match in matches))
255
+ )
256
+
257
+ resolved = matches[0]
258
+ if expected_type is not None:
259
+ actual = resolved.effect.definition.definition_type
260
+ if actual is not expected_type:
261
+ raise _wrong_type(name, actual, expected_type)
262
+ return resolved
263
+
264
+ def _suggest(self, name: str) -> tuple[str, ...]:
265
+ candidates = sorted(set(self._effects) | set(self._presets))
266
+ return tuple(get_close_matches(name, candidates, n=3, cutoff=0.55))
267
+
268
+ # -- listings -----------------------------------------------------------
269
+
270
+ def list_effects(
271
+ self, *, definition_type: DefinitionType | None = None, source_id: str | None = None
272
+ ) -> list[RegisteredEffect]:
273
+ items = [
274
+ effect
275
+ for effect in self._effects.values()
276
+ if (definition_type is None or effect.definition.definition_type is definition_type)
277
+ and (source_id is None or effect.source_id == source_id)
278
+ ]
279
+ return sorted(items, key=lambda effect: effect.effect_id)
280
+
281
+ def list_presets(
282
+ self, *, definition_type: DefinitionType | None = None, effect_id: str | None = None
283
+ ) -> list[Preset]:
284
+ items = []
285
+ for preset in self._presets.values():
286
+ if effect_id is not None and preset.effect_id != effect_id:
287
+ continue
288
+ if definition_type is not None:
289
+ effect = self._effects.get(preset.effect_id)
290
+ if effect is None or effect.definition.definition_type is not definition_type:
291
+ continue
292
+ items.append(preset)
293
+ return sorted(items, key=lambda preset: preset.preset_id)
294
+
295
+ def source_ids(self) -> list[str]:
296
+ return sorted({effect.source_id for effect in self._effects.values()})
297
+
298
+ @property
299
+ def effects(self) -> Mapping[str, RegisteredEffect]:
300
+ return MappingProxyType(self._effects)
301
+
302
+ def __len__(self) -> int:
303
+ return len(self._effects)
304
+
305
+
306
+ def _definition_of(effect_class: type[BaseEffect]) -> DefinitionBase:
307
+ definition = getattr(effect_class, "definition", None)
308
+ if not isinstance(definition, DefinitionBase):
309
+ raise RegistrationError(
310
+ f"{effect_class.__name__} does not declare a LEFX V3 definition"
311
+ )
312
+ if not callable(getattr(effect_class, "render", None)):
313
+ raise RegistrationError(f"{effect_class.__name__} does not implement render()")
314
+ return definition
315
+
316
+
317
+ def _wrong_type(
318
+ name: str, actual: DefinitionType, expected: DefinitionType
319
+ ) -> WrongTargetTypeError:
320
+ verbs = {
321
+ DefinitionType.STATE: "set state",
322
+ DefinitionType.OVERLAY: "set overlay",
323
+ DefinitionType.EVENT: "emit event",
324
+ }
325
+ return WrongTargetTypeError(
326
+ f"{name!r} is a {actual.value}, not a {expected.value}. "
327
+ f"Use '{verbs[actual]}' for it."
328
+ )
329
+
330
+
331
+ def build_registry(
332
+ effect_classes: Iterable[type[BaseEffect]] = (), *, source_id: str = "builtin"
333
+ ) -> EffectRegistry:
334
+ """Convenience for tests and embedders: a registry from plain classes."""
335
+ registry = EffectRegistry()
336
+ for effect_class in effect_classes:
337
+ registry.register_effect(effect_class, source_id=source_id)
338
+ return registry
339
+
340
+
341
+ __all__ = [
342
+ "EffectRegistry",
343
+ "Preset",
344
+ "RegisteredEffect",
345
+ "ResolvedTarget",
346
+ "build_registry",
347
+ ]