reflex 0.6.8a2__py3-none-any.whl → 0.7.0a1__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.

Potentially problematic release.


This version of reflex might be problematic. Click here for more details.

Files changed (154) hide show
  1. reflex/.templates/jinja/custom_components/pyproject.toml.jinja2 +1 -1
  2. reflex/.templates/jinja/web/pages/_app.js.jinja2 +7 -7
  3. reflex/.templates/jinja/web/pages/utils.js.jinja2 +2 -2
  4. reflex/.templates/web/components/reflex/radix_themes_color_mode_provider.js +1 -4
  5. reflex/.templates/web/utils/state.js +65 -36
  6. reflex/__init__.py +4 -17
  7. reflex/__init__.pyi +1 -2
  8. reflex/app.py +244 -109
  9. reflex/app_mixins/lifespan.py +9 -9
  10. reflex/app_mixins/middleware.py +6 -6
  11. reflex/app_module_for_backend.py +3 -7
  12. reflex/base.py +7 -7
  13. reflex/compiler/compiler.py +8 -0
  14. reflex/compiler/utils.py +35 -6
  15. reflex/components/base/bare.py +1 -1
  16. reflex/components/base/error_boundary.py +2 -1
  17. reflex/components/base/error_boundary.pyi +2 -1
  18. reflex/components/base/meta.py +2 -2
  19. reflex/components/base/strict_mode.py +10 -0
  20. reflex/components/base/strict_mode.pyi +57 -0
  21. reflex/components/component.py +38 -77
  22. reflex/components/core/banner.py +83 -4
  23. reflex/components/core/banner.pyi +86 -0
  24. reflex/components/core/breakpoints.py +3 -1
  25. reflex/components/core/client_side_routing.py +1 -1
  26. reflex/components/core/client_side_routing.pyi +1 -1
  27. reflex/components/core/cond.py +9 -10
  28. reflex/components/core/debounce.py +1 -1
  29. reflex/components/core/foreach.py +23 -3
  30. reflex/components/core/html.py +1 -1
  31. reflex/components/core/match.py +5 -5
  32. reflex/components/core/sticky.py +160 -0
  33. reflex/components/core/sticky.pyi +449 -0
  34. reflex/components/core/upload.py +2 -2
  35. reflex/components/datadisplay/code.py +5 -14
  36. reflex/components/datadisplay/dataeditor.py +7 -4
  37. reflex/components/datadisplay/logo.py +13 -8
  38. reflex/components/datadisplay/shiki_code_block.py +14 -9
  39. reflex/components/dynamic.py +22 -3
  40. reflex/components/el/constants/reflex.py +1 -1
  41. reflex/components/el/element.py +1 -1
  42. reflex/components/el/elements/forms.py +4 -4
  43. reflex/components/el/elements/forms.pyi +4 -4
  44. reflex/components/lucide/icon.py +46 -8
  45. reflex/components/lucide/icon.pyi +54 -0
  46. reflex/components/markdown/markdown.py +10 -8
  47. reflex/components/moment/moment.py +2 -2
  48. reflex/components/next/image.py +16 -4
  49. reflex/components/next/image.pyi +4 -2
  50. reflex/components/next/link.py +1 -1
  51. reflex/components/plotly/plotly.py +5 -5
  52. reflex/components/props.py +3 -3
  53. reflex/components/radix/__init__.pyi +1 -1
  54. reflex/components/radix/primitives/accordion.py +9 -5
  55. reflex/components/radix/primitives/accordion.pyi +3 -1
  56. reflex/components/radix/primitives/drawer.py +5 -2
  57. reflex/components/radix/primitives/drawer.pyi +4 -4
  58. reflex/components/radix/primitives/form.pyi +6 -6
  59. reflex/components/radix/primitives/progress.py +1 -1
  60. reflex/components/radix/primitives/slider.py +1 -1
  61. reflex/components/radix/themes/color_mode.py +11 -9
  62. reflex/components/radix/themes/components/alert_dialog.py +3 -0
  63. reflex/components/radix/themes/components/card.py +1 -1
  64. reflex/components/radix/themes/components/card.pyi +1 -1
  65. reflex/components/radix/themes/components/context_menu.py +5 -0
  66. reflex/components/radix/themes/components/dialog.py +3 -0
  67. reflex/components/radix/themes/components/dropdown_menu.py +5 -0
  68. reflex/components/radix/themes/components/hover_card.py +3 -0
  69. reflex/components/radix/themes/components/icon_button.py +2 -2
  70. reflex/components/radix/themes/components/icon_button.pyi +1 -0
  71. reflex/components/radix/themes/components/popover.py +3 -0
  72. reflex/components/radix/themes/components/radio_cards.py +2 -0
  73. reflex/components/radix/themes/components/radio_group.py +1 -1
  74. reflex/components/radix/themes/components/select.py +3 -0
  75. reflex/components/radix/themes/components/tabs.py +3 -0
  76. reflex/components/radix/themes/components/text_area.py +12 -0
  77. reflex/components/radix/themes/components/text_area.pyi +2 -0
  78. reflex/components/radix/themes/components/text_field.py +1 -1
  79. reflex/components/radix/themes/components/tooltip.py +3 -1
  80. reflex/components/radix/themes/components/tooltip.pyi +1 -0
  81. reflex/components/radix/themes/layout/__init__.pyi +1 -1
  82. reflex/components/radix/themes/layout/list.py +2 -2
  83. reflex/components/radix/themes/layout/stack.py +2 -2
  84. reflex/components/radix/themes/typography/link.py +1 -1
  85. reflex/components/radix/themes/typography/text.py +2 -2
  86. reflex/components/react_player/react_player.py +1 -1
  87. reflex/components/recharts/__init__.py +2 -0
  88. reflex/components/recharts/__init__.pyi +2 -0
  89. reflex/components/recharts/charts.py +15 -15
  90. reflex/components/recharts/general.py +19 -4
  91. reflex/components/recharts/general.pyi +55 -4
  92. reflex/components/recharts/polar.py +2 -2
  93. reflex/components/recharts/recharts.py +4 -4
  94. reflex/components/sonner/toast.py +15 -13
  95. reflex/components/sonner/toast.pyi +6 -6
  96. reflex/components/suneditor/editor.py +6 -4
  97. reflex/components/suneditor/editor.pyi +2 -2
  98. reflex/components/tags/iter_tag.py +3 -3
  99. reflex/components/tags/tag.py +25 -3
  100. reflex/config.py +48 -15
  101. reflex/constants/__init__.py +1 -0
  102. reflex/constants/base.py +4 -1
  103. reflex/constants/compiler.py +5 -2
  104. reflex/constants/config.py +8 -1
  105. reflex/constants/installer.py +9 -9
  106. reflex/constants/style.py +1 -1
  107. reflex/custom_components/custom_components.py +9 -7
  108. reflex/event.py +130 -161
  109. reflex/experimental/__init__.py +19 -11
  110. reflex/experimental/client_state.py +53 -28
  111. reflex/experimental/hooks.py +5 -5
  112. reflex/experimental/layout.py +8 -5
  113. reflex/experimental/layout.pyi +1 -1
  114. reflex/experimental/misc.py +3 -3
  115. reflex/istate/wrappers.py +1 -1
  116. reflex/middleware/hydrate_middleware.py +2 -2
  117. reflex/model.py +11 -6
  118. reflex/page.py +3 -3
  119. reflex/reflex.py +90 -19
  120. reflex/route.py +1 -1
  121. reflex/state.py +358 -401
  122. reflex/style.py +27 -3
  123. reflex/testing.py +29 -23
  124. reflex/utils/build.py +6 -2
  125. reflex/utils/codespaces.py +1 -4
  126. reflex/utils/compat.py +6 -5
  127. reflex/utils/console.py +52 -16
  128. reflex/utils/exceptions.py +76 -26
  129. reflex/utils/exec.py +69 -74
  130. reflex/utils/export.py +6 -1
  131. reflex/utils/format.py +7 -39
  132. reflex/utils/imports.py +2 -2
  133. reflex/utils/lazy_loader.py +7 -1
  134. reflex/utils/path_ops.py +28 -14
  135. reflex/utils/prerequisites.py +324 -65
  136. reflex/utils/processes.py +45 -32
  137. reflex/utils/pyi_generator.py +30 -25
  138. reflex/utils/registry.py +4 -4
  139. reflex/utils/serializers.py +1 -1
  140. reflex/utils/telemetry.py +5 -4
  141. reflex/utils/types.py +42 -18
  142. reflex/vars/base.py +650 -333
  143. reflex/vars/datetime.py +6 -7
  144. reflex/vars/dep_tracking.py +344 -0
  145. reflex/vars/function.py +11 -5
  146. reflex/vars/number.py +31 -43
  147. reflex/vars/object.py +63 -62
  148. reflex/vars/sequence.py +79 -67
  149. {reflex-0.6.8a2.dist-info → reflex-0.7.0a1.dist-info}/METADATA +7 -8
  150. {reflex-0.6.8a2.dist-info → reflex-0.7.0a1.dist-info}/RECORD +153 -149
  151. {reflex-0.6.8a2.dist-info → reflex-0.7.0a1.dist-info}/WHEEL +1 -1
  152. reflex/experimental/assets.py +0 -37
  153. {reflex-0.6.8a2.dist-info → reflex-0.7.0a1.dist-info}/LICENSE +0 -0
  154. {reflex-0.6.8a2.dist-info → reflex-0.7.0a1.dist-info}/entry_points.txt +0 -0
reflex/style.py CHANGED
@@ -78,7 +78,7 @@ def set_color_mode(
78
78
  _var_data=VarData.merge(
79
79
  base_setter._get_all_var_data(), new_color_mode._get_all_var_data()
80
80
  ),
81
- ).to(FunctionVar, EventChain) # type: ignore
81
+ ).to(FunctionVar, EventChain)
82
82
 
83
83
 
84
84
  # Var resolves to the current color mode for the app ("light", "dark" or "system")
@@ -182,7 +182,9 @@ def convert(
182
182
  var_data = None # Track import/hook data from any Vars in the style dict.
183
183
  out = {}
184
184
 
185
- def update_out_dict(return_value, keys_to_update):
185
+ def update_out_dict(
186
+ return_value: Var | dict | list | str, keys_to_update: tuple[str, ...]
187
+ ):
186
188
  for k in keys_to_update:
187
189
  out[k] = return_value
188
190
 
@@ -287,9 +289,31 @@ class Style(dict):
287
289
  _var = LiteralVar.create(value)
288
290
  if _var is not None:
289
291
  # Carry the imports/hooks when setting a Var as a value.
290
- self._var_data = VarData.merge(self._var_data, _var._get_all_var_data())
292
+ self._var_data = VarData.merge(
293
+ getattr(self, "_var_data", None), _var._get_all_var_data()
294
+ )
291
295
  super().__setitem__(key, value)
292
296
 
297
+ def __or__(self, other: Style | dict) -> Style:
298
+ """Combine two styles.
299
+
300
+ Args:
301
+ other: The other style to combine.
302
+
303
+ Returns:
304
+ The combined style.
305
+ """
306
+ other_var_data = None
307
+ if not isinstance(other, Style):
308
+ other_dict, other_var_data = convert(other)
309
+ else:
310
+ other_dict, other_var_data = other, other._var_data
311
+
312
+ new_style = Style(super().__or__(other_dict))
313
+ if self._var_data or other_var_data:
314
+ new_style._var_data = VarData.merge(self._var_data, other_var_data)
315
+ return new_style
316
+
293
317
 
294
318
  def _format_emotion_style_pseudo_selector(key: str) -> str:
295
319
  """Format a pseudo selector for emotion CSS-in-JS.
reflex/testing.py CHANGED
@@ -80,17 +80,17 @@ T = TypeVar("T")
80
80
  TimeoutType = Optional[Union[int, float]]
81
81
 
82
82
  if platform.system() == "Windows":
83
- FRONTEND_POPEN_ARGS["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore
83
+ FRONTEND_POPEN_ARGS["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # pyright: ignore [reportAttributeAccessIssue]
84
84
  FRONTEND_POPEN_ARGS["shell"] = True
85
85
  else:
86
86
  FRONTEND_POPEN_ARGS["start_new_session"] = True
87
87
 
88
88
 
89
89
  # borrowed from py3.11
90
- class chdir(contextlib.AbstractContextManager):
90
+ class chdir(contextlib.AbstractContextManager): # noqa: N801
91
91
  """Non thread-safe context manager to change the current working directory."""
92
92
 
93
- def __init__(self, path):
93
+ def __init__(self, path: str | Path):
94
94
  """Prepare contextmanager.
95
95
 
96
96
  Args:
@@ -258,7 +258,7 @@ class AppHarness:
258
258
  if self.app_source is not None:
259
259
  app_globals = self._get_globals_from_signature(self.app_source)
260
260
  if isinstance(self.app_source, functools.partial):
261
- self.app_source = self.app_source.func # type: ignore
261
+ self.app_source = self.app_source.func
262
262
  # get the source from a function or module object
263
263
  source_code = "\n".join(
264
264
  [
@@ -282,6 +282,7 @@ class AppHarness:
282
282
  before_decorated_pages = reflex.app.DECORATED_PAGES[self.app_name].copy()
283
283
  # Ensure the AppHarness test does not skip State assignment due to running via pytest
284
284
  os.environ.pop(reflex.constants.PYTEST_CURRENT_TEST, None)
285
+ os.environ[reflex.constants.APP_HARNESS_FLAG] = "true"
285
286
  self.app_module = reflex.utils.prerequisites.get_compiled_app(
286
287
  # Do not reload the module for pre-existing apps (only apps generated from source)
287
288
  reload=self.app_source is not None
@@ -293,11 +294,15 @@ class AppHarness:
293
294
  if p not in before_decorated_pages
294
295
  ]
295
296
  self.app_instance = self.app_module.app
296
- if isinstance(self.app_instance._state_manager, StateManagerRedis):
297
+ if self.app_instance and isinstance(
298
+ self.app_instance._state_manager, StateManagerRedis
299
+ ):
297
300
  # Create our own redis connection for testing.
298
- self.state_manager = StateManagerRedis.create(self.app_instance.state)
301
+ self.state_manager = StateManagerRedis.create(self.app_instance._state) # pyright: ignore [reportArgumentType]
299
302
  else:
300
- self.state_manager = self.app_instance._state_manager
303
+ self.state_manager = (
304
+ self.app_instance._state_manager if self.app_instance else None
305
+ )
301
306
 
302
307
  def _reload_state_module(self):
303
308
  """Reload the rx.State module to avoid conflict when reloading."""
@@ -322,8 +327,8 @@ class AppHarness:
322
327
 
323
328
  return _shutdown_redis
324
329
 
325
- def _start_backend(self, port=0):
326
- if self.app_instance is None:
330
+ def _start_backend(self, port: int = 0):
331
+ if self.app_instance is None or self.app_instance.api is None:
327
332
  raise RuntimeError("App was not initialized.")
328
333
  self.backend = uvicorn.Server(
329
334
  uvicorn.Config(
@@ -352,12 +357,12 @@ class AppHarness:
352
357
  self.app_instance.state_manager,
353
358
  StateManagerRedis,
354
359
  )
355
- and self.app_instance.state is not None
360
+ and self.app_instance._state is not None
356
361
  ):
357
362
  with contextlib.suppress(RuntimeError):
358
363
  await self.app_instance.state_manager.close()
359
364
  self.app_instance._state_manager = StateManagerRedis.create(
360
- state=self.app_instance.state,
365
+ state=self.app_instance._state,
361
366
  )
362
367
  if not isinstance(self.app_instance.state_manager, StateManagerRedis):
363
368
  raise RuntimeError("Failed to reset state manager.")
@@ -425,7 +430,7 @@ class AppHarness:
425
430
  return self
426
431
 
427
432
  @staticmethod
428
- def get_app_global_source(key, value):
433
+ def get_app_global_source(key: str, value: Any):
429
434
  """Get the source code of a global object.
430
435
  If value is a function or class we render the actual
431
436
  source of value otherwise we assign value to key.
@@ -620,23 +625,23 @@ class AppHarness:
620
625
  want_headless = True
621
626
  if driver_clz is None:
622
627
  requested_driver = environment.APP_HARNESS_DRIVER.get()
623
- driver_clz = getattr(webdriver, requested_driver)
628
+ driver_clz = getattr(webdriver, requested_driver) # pyright: ignore [reportPossiblyUnboundVariable]
624
629
  if driver_options is None:
625
- driver_options = getattr(webdriver, f"{requested_driver}Options")()
626
- if driver_clz is webdriver.Chrome:
630
+ driver_options = getattr(webdriver, f"{requested_driver}Options")() # pyright: ignore [reportPossiblyUnboundVariable]
631
+ if driver_clz is webdriver.Chrome: # pyright: ignore [reportPossiblyUnboundVariable]
627
632
  if driver_options is None:
628
- driver_options = webdriver.ChromeOptions()
633
+ driver_options = webdriver.ChromeOptions() # pyright: ignore [reportPossiblyUnboundVariable]
629
634
  driver_options.add_argument("--class=AppHarness")
630
635
  if want_headless:
631
636
  driver_options.add_argument("--headless=new")
632
- elif driver_clz is webdriver.Firefox:
637
+ elif driver_clz is webdriver.Firefox: # pyright: ignore [reportPossiblyUnboundVariable]
633
638
  if driver_options is None:
634
- driver_options = webdriver.FirefoxOptions()
639
+ driver_options = webdriver.FirefoxOptions() # pyright: ignore [reportPossiblyUnboundVariable]
635
640
  if want_headless:
636
641
  driver_options.add_argument("-headless")
637
- elif driver_clz is webdriver.Edge:
642
+ elif driver_clz is webdriver.Edge: # pyright: ignore [reportPossiblyUnboundVariable]
638
643
  if driver_options is None:
639
- driver_options = webdriver.EdgeOptions()
644
+ driver_options = webdriver.EdgeOptions() # pyright: ignore [reportPossiblyUnboundVariable]
640
645
  if want_headless:
641
646
  driver_options.add_argument("headless")
642
647
  if driver_options is None:
@@ -652,7 +657,7 @@ class AppHarness:
652
657
  driver_options.set_capability(key, value)
653
658
  if driver_kwargs is None:
654
659
  driver_kwargs = {}
655
- driver = driver_clz(options=driver_options, **driver_kwargs) # type: ignore
660
+ driver = driver_clz(options=driver_options, **driver_kwargs) # pyright: ignore [reportOptionalCall, reportArgumentType]
656
661
  driver.get(self.frontend_url)
657
662
  self._frontends.append(driver)
658
663
  return driver
@@ -884,8 +889,8 @@ class Subdir404TCPServer(socketserver.TCPServer):
884
889
  request,
885
890
  client_address,
886
891
  self,
887
- directory=str(self.root), # type: ignore
888
- error_page_map=self.error_page_map, # type: ignore
892
+ directory=str(self.root), # pyright: ignore [reportCallIssue]
893
+ error_page_map=self.error_page_map, # pyright: ignore [reportCallIssue]
889
894
  )
890
895
 
891
896
 
@@ -932,6 +937,7 @@ class AppHarnessProd(AppHarness):
932
937
  frontend=True,
933
938
  backend=False,
934
939
  loglevel=reflex.constants.LogLevel.INFO,
940
+ env=reflex.constants.Env.PROD,
935
941
  )
936
942
 
937
943
  self.frontend_thread = threading.Thread(target=self._run_frontend)
reflex/utils/build.py CHANGED
@@ -13,17 +13,21 @@ from rich.progress import MofNCompleteColumn, Progress, TimeElapsedColumn
13
13
  from reflex import constants
14
14
  from reflex.config import get_config
15
15
  from reflex.utils import console, path_ops, prerequisites, processes
16
+ from reflex.utils.exec import is_in_app_harness
16
17
 
17
18
 
18
19
  def set_env_json():
19
20
  """Write the upload url to a REFLEX_JSON."""
20
21
  path_ops.update_json_file(
21
22
  str(prerequisites.get_web_dir() / constants.Dirs.ENV_JSON),
22
- {endpoint.name: endpoint.get_url() for endpoint in constants.Endpoint},
23
+ {
24
+ **{endpoint.name: endpoint.get_url() for endpoint in constants.Endpoint},
25
+ "TEST_MODE": is_in_app_harness(),
26
+ },
23
27
  )
24
28
 
25
29
 
26
- def generate_sitemap_config(deploy_url: str, export=False):
30
+ def generate_sitemap_config(deploy_url: str, export: bool = False):
27
31
  """Generate the sitemap config file.
28
32
 
29
33
  Args:
@@ -42,10 +42,7 @@ def codespaces_port_forwarding_domain() -> str | None:
42
42
  Returns:
43
43
  The domain for port forwarding in Github Codespaces, or None if not running in Codespaces.
44
44
  """
45
- GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN = os.getenv(
46
- "GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN"
47
- )
48
- return GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN
45
+ return os.getenv("GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN")
49
46
 
50
47
 
51
48
  def is_running_in_codespaces() -> bool:
reflex/utils/compat.py CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  import contextlib
4
4
  import sys
5
+ from typing import Any
5
6
 
6
7
 
7
8
  async def windows_hot_reload_lifespan_hack():
@@ -50,11 +51,11 @@ def pydantic_v1_patch():
50
51
  ]
51
52
  originals = {module: sys.modules.get(module) for module in patched_modules}
52
53
  try:
53
- import pydantic.v1 # type: ignore
54
+ import pydantic.v1
54
55
 
55
- sys.modules["pydantic.fields"] = pydantic.v1.fields # type: ignore
56
- sys.modules["pydantic.main"] = pydantic.v1.main # type: ignore
57
- sys.modules["pydantic.errors"] = pydantic.v1.errors # type: ignore
56
+ sys.modules["pydantic.fields"] = pydantic.v1.fields # pyright: ignore [reportAttributeAccessIssue]
57
+ sys.modules["pydantic.main"] = pydantic.v1.main # pyright: ignore [reportAttributeAccessIssue]
58
+ sys.modules["pydantic.errors"] = pydantic.v1.errors # pyright: ignore [reportAttributeAccessIssue]
58
59
  sys.modules["pydantic"] = pydantic.v1
59
60
  yield
60
61
  except (ImportError, AttributeError):
@@ -74,7 +75,7 @@ with pydantic_v1_patch():
74
75
  import sqlmodel as sqlmodel
75
76
 
76
77
 
77
- def sqlmodel_field_has_primary_key(field) -> bool:
78
+ def sqlmodel_field_has_primary_key(field: Any) -> bool:
78
79
  """Determines if a field is a priamary.
79
80
 
80
81
  Args:
reflex/utils/console.py CHANGED
@@ -2,6 +2,11 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import inspect
6
+ import shutil
7
+ from pathlib import Path
8
+ from types import FrameType
9
+
5
10
  from rich.console import Console
6
11
  from rich.progress import MofNCompleteColumn, Progress, TimeElapsedColumn
7
12
  from rich.prompt import Prompt
@@ -46,20 +51,12 @@ def set_log_level(log_level: LogLevel):
46
51
  log_level: The log level to set.
47
52
 
48
53
  Raises:
49
- ValueError: If the log level is invalid.
54
+ TypeError: If the log level is a string.
50
55
  """
51
56
  if not isinstance(log_level, LogLevel):
52
- deprecate(
53
- feature_name="Passing a string to set_log_level",
54
- reason="use reflex.constants.LogLevel enum instead",
55
- deprecation_version="0.6.6",
56
- removal_version="0.7.0",
57
+ raise TypeError(
58
+ f"log_level must be a LogLevel enum value, got {log_level} of type {type(log_level)} instead."
57
59
  )
58
- try:
59
- log_level = getattr(LogLevel, log_level.upper())
60
- except AttributeError as ae:
61
- raise ValueError(f"Invalid log level: {log_level}") from ae
62
-
63
60
  global _LOG_LEVEL
64
61
  _LOG_LEVEL = log_level
65
62
 
@@ -188,6 +185,33 @@ def warn(msg: str, dedupe: bool = False, **kwargs):
188
185
  print(f"[orange1]Warning: {msg}[/orange1]", **kwargs)
189
186
 
190
187
 
188
+ def _get_first_non_framework_frame() -> FrameType | None:
189
+ import click
190
+ import typer
191
+ import typing_extensions
192
+
193
+ import reflex as rx
194
+
195
+ # Exclude utility modules that should never be the source of deprecated reflex usage.
196
+ exclude_modules = [click, rx, typer, typing_extensions]
197
+ exclude_roots = [
198
+ p.parent.resolve()
199
+ if (p := Path(m.__file__)).name == "__init__.py" # pyright: ignore [reportArgumentType]
200
+ else p.resolve()
201
+ for m in exclude_modules
202
+ ]
203
+ # Specifically exclude the reflex cli module.
204
+ if reflex_bin := shutil.which(b"reflex"):
205
+ exclude_roots.append(Path(reflex_bin.decode()))
206
+
207
+ frame = inspect.currentframe()
208
+ while frame := frame and frame.f_back:
209
+ frame_path = Path(inspect.getfile(frame)).resolve()
210
+ if not any(frame_path.is_relative_to(root) for root in exclude_roots):
211
+ break
212
+ return frame
213
+
214
+
191
215
  def deprecate(
192
216
  feature_name: str,
193
217
  reason: str,
@@ -206,15 +230,27 @@ def deprecate(
206
230
  dedupe: If True, suppress multiple console logs of deprecation message.
207
231
  kwargs: Keyword arguments to pass to the print function.
208
232
  """
209
- if feature_name not in _EMITTED_DEPRECATION_WARNINGS:
233
+ dedupe_key = feature_name
234
+ loc = ""
235
+
236
+ # See if we can find where the deprecation exists in "user code"
237
+ origin_frame = _get_first_non_framework_frame()
238
+ if origin_frame is not None:
239
+ filename = Path(origin_frame.f_code.co_filename)
240
+ if filename.is_relative_to(Path.cwd()):
241
+ filename = filename.relative_to(Path.cwd())
242
+ loc = f"{filename}:{origin_frame.f_lineno}"
243
+ dedupe_key = f"{dedupe_key} {loc}"
244
+
245
+ if dedupe_key not in _EMITTED_DEPRECATION_WARNINGS:
210
246
  msg = (
211
247
  f"{feature_name} has been deprecated in version {deprecation_version} {reason.rstrip('.')}. It will be completely "
212
- f"removed in {removal_version}"
248
+ f"removed in {removal_version}. ({loc})"
213
249
  )
214
250
  if _LOG_LEVEL <= LogLevel.WARNING:
215
251
  print(f"[yellow]DeprecationWarning: {msg}[/yellow]", **kwargs)
216
252
  if dedupe:
217
- _EMITTED_DEPRECATION_WARNINGS.add(feature_name)
253
+ _EMITTED_DEPRECATION_WARNINGS.add(dedupe_key)
218
254
 
219
255
 
220
256
  def error(msg: str, dedupe: bool = False, **kwargs):
@@ -239,7 +275,7 @@ def ask(
239
275
  choices: list[str] | None = None,
240
276
  default: str | None = None,
241
277
  show_choices: bool = True,
242
- ) -> str:
278
+ ) -> str | None:
243
279
  """Takes a prompt question and optionally a list of choices
244
280
  and returns the user input.
245
281
 
@@ -254,7 +290,7 @@ def ask(
254
290
  """
255
291
  return Prompt.ask(
256
292
  question, choices=choices, default=default, show_choices=show_choices
257
- ) # type: ignore
293
+ )
258
294
 
259
295
 
260
296
  def progress():
@@ -1,6 +1,6 @@
1
1
  """Custom Exceptions."""
2
2
 
3
- from typing import NoReturn
3
+ from typing import Any
4
4
 
5
5
 
6
6
  class ReflexError(Exception):
@@ -11,7 +11,7 @@ class ConfigError(ReflexError):
11
11
  """Custom exception for config related errors."""
12
12
 
13
13
 
14
- class InvalidStateManagerMode(ReflexError, ValueError):
14
+ class InvalidStateManagerModeError(ReflexError, ValueError):
15
15
  """Raised when an invalid state manager mode is provided."""
16
16
 
17
17
 
@@ -31,6 +31,22 @@ class ComponentTypeError(ReflexError, TypeError):
31
31
  """Custom TypeError for component related errors."""
32
32
 
33
33
 
34
+ class ChildrenTypeError(ComponentTypeError):
35
+ """Raised when the children prop of a component is not a valid type."""
36
+
37
+ def __init__(self, component: str, child: Any):
38
+ """Initialize the exception.
39
+
40
+ Args:
41
+ component: The name of the component.
42
+ child: The child that caused the error.
43
+ """
44
+ super().__init__(
45
+ f"Component {component} received child {child} of type {type(child)}. "
46
+ "Accepted types are other components, state vars, or primitive Python types (dict excluded)."
47
+ )
48
+
49
+
34
50
  class EventHandlerTypeError(ReflexError, TypeError):
35
51
  """Custom TypeError for event handler related errors."""
36
52
 
@@ -59,6 +75,34 @@ class VarAttributeError(ReflexError, AttributeError):
59
75
  """Custom AttributeError for var related errors."""
60
76
 
61
77
 
78
+ class UntypedVarError(ReflexError, TypeError):
79
+ """Custom TypeError for untyped var errors."""
80
+
81
+
82
+ class UntypedComputedVarError(ReflexError, TypeError):
83
+ """Custom TypeError for untyped computed var errors."""
84
+
85
+ def __init__(self, var_name: str):
86
+ """Initialize the UntypedComputedVarError.
87
+
88
+ Args:
89
+ var_name: The name of the computed var.
90
+ """
91
+ super().__init__(f"Computed var '{var_name}' must have a type annotation.")
92
+
93
+
94
+ class MissingAnnotationError(ReflexError, TypeError):
95
+ """Custom TypeError for missing annotations."""
96
+
97
+ def __init__(self, var_name: str):
98
+ """Initialize the MissingAnnotationError.
99
+
100
+ Args:
101
+ var_name: The name of the var.
102
+ """
103
+ super().__init__(f"Var '{var_name}' must have a type annotation.")
104
+
105
+
62
106
  class UploadValueError(ReflexError, ValueError):
63
107
  """Custom ValueError for upload related errors."""
64
108
 
@@ -95,43 +139,43 @@ class MatchTypeError(ReflexError, TypeError):
95
139
  """Raised when the return types of match cases are different."""
96
140
 
97
141
 
98
- class EventHandlerArgTypeMismatch(ReflexError, TypeError):
142
+ class EventHandlerArgTypeMismatchError(ReflexError, TypeError):
99
143
  """Raised when the annotations of args accepted by an EventHandler differs from the spec of the event trigger."""
100
144
 
101
145
 
102
- class EventFnArgMismatch(ReflexError, TypeError):
146
+ class EventFnArgMismatchError(ReflexError, TypeError):
103
147
  """Raised when the number of args required by an event handler is more than provided by the event trigger."""
104
148
 
105
149
 
106
- class DynamicRouteArgShadowsStateVar(ReflexError, NameError):
150
+ class DynamicRouteArgShadowsStateVarError(ReflexError, NameError):
107
151
  """Raised when a dynamic route arg shadows a state var."""
108
152
 
109
153
 
110
- class ComputedVarShadowsStateVar(ReflexError, NameError):
154
+ class ComputedVarShadowsStateVarError(ReflexError, NameError):
111
155
  """Raised when a computed var shadows a state var."""
112
156
 
113
157
 
114
- class ComputedVarShadowsBaseVars(ReflexError, NameError):
158
+ class ComputedVarShadowsBaseVarsError(ReflexError, NameError):
115
159
  """Raised when a computed var shadows a base var."""
116
160
 
117
161
 
118
- class EventHandlerShadowsBuiltInStateMethod(ReflexError, NameError):
162
+ class EventHandlerShadowsBuiltInStateMethodError(ReflexError, NameError):
119
163
  """Raised when an event handler shadows a built-in state method."""
120
164
 
121
165
 
122
- class GeneratedCodeHasNoFunctionDefs(ReflexError):
166
+ class GeneratedCodeHasNoFunctionDefsError(ReflexError):
123
167
  """Raised when refactored code generated with flexgen has no functions defined."""
124
168
 
125
169
 
126
- class PrimitiveUnserializableToJSON(ReflexError, ValueError):
170
+ class PrimitiveUnserializableToJSONError(ReflexError, ValueError):
127
171
  """Raised when a primitive type is unserializable to JSON. Usually with NaN and Infinity."""
128
172
 
129
173
 
130
- class InvalidLifespanTaskType(ReflexError, TypeError):
174
+ class InvalidLifespanTaskTypeError(ReflexError, TypeError):
131
175
  """Raised when an invalid task type is registered as a lifespan task."""
132
176
 
133
177
 
134
- class DynamicComponentMissingLibrary(ReflexError, ValueError):
178
+ class DynamicComponentMissingLibraryError(ReflexError, ValueError):
135
179
  """Raised when a dynamic component is missing a library."""
136
180
 
137
181
 
@@ -147,7 +191,7 @@ class EnvironmentVarValueError(ReflexError, ValueError):
147
191
  """Raised when an environment variable is set to an invalid value."""
148
192
 
149
193
 
150
- class DynamicComponentInvalidSignature(ReflexError, TypeError):
194
+ class DynamicComponentInvalidSignatureError(ReflexError, TypeError):
151
195
  """Raised when a dynamic component has an invalid signature."""
152
196
 
153
197
 
@@ -163,26 +207,32 @@ class StateSerializationError(ReflexError):
163
207
  """Raised when the state cannot be serialized."""
164
208
 
165
209
 
210
+ class StateMismatchError(ReflexError, ValueError):
211
+ """Raised when the state retrieved does not match the expected state."""
212
+
213
+
166
214
  class SystemPackageMissingError(ReflexError):
167
215
  """Raised when a system package is missing."""
168
216
 
217
+ def __init__(self, package: str):
218
+ """Initialize the SystemPackageMissingError.
169
219
 
170
- def raise_system_package_missing_error(package: str) -> NoReturn:
171
- """Raise a SystemPackageMissingError.
220
+ Args:
221
+ package: The missing package.
222
+ """
223
+ from reflex.constants import IS_MACOS
172
224
 
173
- Args:
174
- package: The name of the missing system package.
225
+ extra = (
226
+ f" You can do so by running 'brew install {package}'." if IS_MACOS else ""
227
+ )
228
+ super().__init__(
229
+ f"System package '{package}' is missing."
230
+ f" Please install it through your system package manager.{extra}"
231
+ )
175
232
 
176
- Raises:
177
- SystemPackageMissingError: The raised exception.
178
- """
179
- from reflex.constants import IS_MACOS
180
233
 
181
- raise SystemPackageMissingError(
182
- f"System package '{package}' is missing."
183
- " Please install it through your system package manager."
184
- + (f" You can do so by running 'brew install {package}'." if IS_MACOS else "")
185
- )
234
+ class EventDeserializationError(ReflexError, ValueError):
235
+ """Raised when an event cannot be deserialized."""
186
236
 
187
237
 
188
238
  class InvalidLockWarningThresholdError(ReflexError):