diff --git a/docs/wrapping-react/overview.md b/docs/wrapping-react/overview.md index 046725c29a5..803561fd035 100644 --- a/docs/wrapping-react/overview.md +++ b/docs/wrapping-react/overview.md @@ -137,6 +137,11 @@ private = rx.client_state("") # scoped to the component tree using it A **named** var resolves in one app-wide store, so any component can read and write it and `push`, `retrieve`, `global_value` and `global_set` all work against it. +A name is an ASCII identifier: letters, digits and underscores, not starting with a digit. +Several modules may each declare the same named var, but only with the same default; two +different defaults fail the compile, since only one of them could take effect. Declaring the +var once in a shared module and importing it is simplest. + An **unnamed** var gets a compile-time name and is scoped: the outermost page or `@rx.memo` whose body uses it owns it, so each instance of that component gets its own state, the way React's `useState` does. Nothing outside the tree can address it, and a page's unnamed vars diff --git a/news/+client-state-contract.bugfix.md b/news/+client-state-contract.bugfix.md new file mode 100644 index 00000000000..a5acfac1efc --- /dev/null +++ b/news/+client-state-contract.bugfix.md @@ -0,0 +1 @@ +The deprecated `rx._x.client_state` and `reflex.experimental.client_state.ClientStateVar.create` apply the same `name` rule as `rx.client_state` (an ASCII identifier without `$`), and an app whose pages declare one client state name with two different defaults now fails to compile with an error naming both declarations. diff --git a/packages/reflex-base/news/+client-state-contract.bugfix.md b/packages/reflex-base/news/+client-state-contract.bugfix.md new file mode 100644 index 00000000000..bb5e2fcf43c --- /dev/null +++ b/packages/reflex-base/news/+client-state-contract.bugfix.md @@ -0,0 +1 @@ +Tighten the `rx.client_state` contract. A `name` must be an ASCII identifier without `$` (letters, digits and underscores), and the error names the bad value. Declaring one name with two different defaults now fails the compile with both declaration sites instead of letting the first mounted one win, while identical declarations stay allowed. Names that differ only in case (`item`/`Item`) no longer break the build with a duplicate setter. The error for `push`/`retrieve`/`global_value`/`global_set` on an unnamed var now shows the right call, `rx.client_state(default, name="my_name")`, and points out a default that looks like a misplaced name. Compiled setters are now named `RxClientStateSet` instead of `set`. diff --git a/packages/reflex-base/src/reflex_base/client_state.py b/packages/reflex-base/src/reflex_base/client_state.py index 98986aa87e6..923a2d3d6e6 100644 --- a/packages/reflex-base/src/reflex_base/client_state.py +++ b/packages/reflex-base/src/reflex_base/client_state.py @@ -2,12 +2,15 @@ from __future__ import annotations +import contextlib import dataclasses import inspect import itertools import json import re -from collections.abc import Callable +import sys +from collections.abc import Callable, Iterable, Iterator +from contextvars import ContextVar from typing import TYPE_CHECKING, Any from reflex_base.components.client_state_context import get_client_state_app_wraps @@ -22,7 +25,7 @@ server_side, ) from reflex_base.utils import console, format -from reflex_base.utils.exceptions import VarTypeError +from reflex_base.utils.exceptions import ClientStateConflictError, VarTypeError from reflex_base.utils.imports import ImportVar from reflex_base.vars import VarData from reflex_base.vars.base import LiteralVar, Var @@ -56,42 +59,183 @@ # Raised for every path that addresses a var by name from outside its tree. _NOT_GLOBAL_MSG = ( - "Cannot {action}: this client state var is scoped to the component tree " - 'that uses it. Give it a name -- rx.client_state("my_name") -- to make it ' - "global and addressable." + "Cannot {action}: this client state var is unnamed, so it is scoped to the " + "component tree that uses it. Give it a name to make it global and " + 'addressable: rx.client_state(default, name="my_name").' +) + +# Appended to _NOT_GLOBAL_MSG when the default could have been meant as a name, +# as in the name-first order of the deprecated `rx._x.client_state`. +_NAME_AS_DEFAULT_MSG = ( + " Its default is {default}: the first positional argument is the default, " + "so if that was meant as the name, write " + "rx.client_state(default, name={default})." ) # Default prefix for generated names. _DEFAULT_NAME_PREFIX = "cs" -_VALID_NAME = re.compile(r"^[A-Za-z_$][A-Za-z0-9_$]*\Z") +# Names and prefixes are emitted inside javascript identifiers. `$` is left out: +# it separates a generated name's prefix from its counter, so a chosen name can +# never equal a generated one. +_VALID_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z") + +# The javascript bindings of a var are its name plus a fixed suffix each, so +# they are injective in the name and the three kinds never coincide (the +# getter ends in `State`, the others in `Set` and `Arg`). +_GETTER_SUFFIX = CAMEL_CASE_CLIENT_STATE_MARKER +_SETTER_SUFFIX = f"{CAMEL_CASE_CLIENT_STATE_MARKER}Set" +_PLACEHOLDER_SUFFIX = f"{CAMEL_CASE_CLIENT_STATE_MARKER}Arg" + +# A `useClientState` declaration: the default expression, which may span +# lines, then the name. +_DECLARATION = re.compile( + r'= useClientState\((.*), "([A-Za-z0-9_$]+)"(?:, true)?\)\Z', re.DOTALL +) + +# The declarations rendered so far in the current compile, by name. Unset +# outside a compile, where only declarations within one body are compared. +_compile_declarations: ContextVar[dict[str, str] | None] = ContextVar( + "_compile_declarations", default=None +) + +# Where each chosen-name declaration was last created, by its hook line, for +# the conflict error. Bounded by the distinct declarations written in source. +_declaration_sites: dict[str, str] = {} + +# Modules whose frames sit between the user's call and `_create`. +_FACTORY_MODULES = frozenset({__name__, "reflex.experimental.client_state"}) + + +def _validate_name(value: Any, kind: str) -> str: + """Check that a name or prefix can be emitted in a javascript identifier. + + Args: + value: The name or prefix. + kind: ``"name"`` or ``"prefix"``, for the error message. + + Returns: + The value, now known to be a valid string. + + Raises: + ValueError: If the value is not a string or breaks the naming rule. + """ + if isinstance(value, Var): + msg = ( + f"{kind} must be a string, not a Var. The name keys the client " + "state store and is embedded in the events that `push`, " + "`retrieve` and `global_set` send, so it has to be known at " + "compile time." + ) + raise ValueError(msg) + if not isinstance(value, str): + msg = f"{kind} must be a string, got {type(value).__name__}: {value!r}" + raise ValueError(msg) + if not _VALID_NAME.match(value): + msg = ( + f"{kind} {value!r} is not a valid client state {kind}: it must be " + "an ASCII identifier, a letter or underscore followed by letters, " + "digits or underscores. It must not contain '$', which is " + "reserved for generated names." + ) + raise ValueError(msg) + return value def _generate_name(prefix: str = _DEFAULT_NAME_PREFIX) -> str: """Build the name of an unnamed var from a prefix and the shared counter. ``$`` separates the two and is not allowed in the prefix, so two generated - names are equal only when both their prefixes and their counters are. + names are equal only when both their prefixes and their counters are, and + never equal a chosen name. Args: prefix: The readable part of the name. Returns: The generated name, a valid javascript identifier. + """ + return f"{_validate_name(prefix, 'prefix')}${next(_name_counter)}" + + +def _caller_site() -> str: + """Locate the user code that created a client state var. + + Returns: + ``file:line`` of the first frame outside the client state factories. + """ + frame = sys._getframe(1) + while frame.f_back is not None and frame.f_globals.get("__name__") in ( + _FACTORY_MODULES + ): + frame = frame.f_back + return f"{frame.f_code.co_filename}:{frame.f_lineno}" + + +def _describe_declaration(hook: str) -> str: + """Describe a declaration by its default and where it was created. + + Args: + hook: A ``useClientState`` hook line. + + Returns: + The default expression, and the creation site when known. + """ + match = _DECLARATION.search(hook) + default = f"`{match[1]}`" if match else repr(hook) + site = _declaration_sites.get(hook) + return f"{default} (declared at {site})" if site else default + + +def _check_declarations(hooks: Iterable[str]) -> None: + """Reject a client state name declared with two different defaults. + + Called on every body's hooks as it is rendered. During a compile (see + `_collect_declarations`) the comparison spans every body; otherwise it + covers the one body. + + Args: + hooks: The hook lines of one body. Raises: - ValueError: If the prefix contains ``$`` or is not an identifier. + ClientStateConflictError: If a name is declared with a different + default than before. """ - if "$" in prefix: - msg = f"prefix {prefix!r} must not contain '$', which separates it from the counter." - raise ValueError(msg) - if not _VALID_NAME.match(prefix): - msg = ( - f"prefix {prefix!r} is not a valid javascript identifier; it " - "is emitted as one in the compiled app." - ) - raise ValueError(msg) - return f"{prefix}${next(_name_counter)}" + seen = _compile_declarations.get() + if seen is None: + seen = {} + for hook in hooks: + if "= useClientState(" not in hook or not (match := _DECLARATION.search(hook)): + continue + name = match[2] + first = seen.setdefault(name, hook) + if first != hook: + msg = ( + f"Client state var {name!r} is declared with two different " + f"defaults: {_describe_declaration(first)} and " + f"{_describe_declaration(hook)}. A named client state var is " + "one app-wide value, so every declaration of it must use the " + "same default. Declare it once and import it where it is used, " + "or give the declarations different names." + ) + raise ClientStateConflictError(msg) + + +@contextlib.contextmanager +def _collect_declarations() -> Iterator[None]: + """Compare client state declarations across every body rendered inside. + + A fresh record per compile, so a declaration edited before a hot reload + is not compared against its old self. + + Yields: + Nothing; the record is dropped on exit. + """ + token = _compile_declarations.set({}) + try: + yield + finally: + _compile_declarations.reset(token) # The store's entry point on the global `refs` object. This is the only binding @@ -187,7 +331,7 @@ def _trace_updater(self, fn: Callable) -> Var: if num_args == 0: return Var.create(fn()) placeholder = Var( - _js_expr=f"prev{next(_placeholder_counter)}{CAMEL_CASE_CLIENT_STATE_MARKER}", + _js_expr=f"prev{next(_placeholder_counter)}{_PLACEHOLDER_SUFFIX}", _var_type=self._value_type, ).guess_type() return ArgsFunctionOperationBuilder.create( @@ -244,9 +388,12 @@ def create( Whether the state is shared app-wide follows from whether you name it: - - ``rx.client_state("my_name")`` is **global**. It resolves in one - app-wide store, so any component and the backend can read and write - it, and `push`, `retrieve`, `global_value` and `global_set` work. + - ``rx.client_state(default, name="my_name")`` is **global**. It + resolves in one app-wide store, so any component and the backend can + read and write it, and `push`, `retrieve`, `global_value` and + `global_set` work. The name must be an ASCII identifier without + ``$``. Declaring one name in several places is allowed only with the + same default; the compile fails on two different defaults. - ``rx.client_state()`` is **tree-scoped**. It gets a compile-time name and is owned by the outermost page or ``@rx.memo`` body that uses it, so each instance of that component gets its own state -- like @@ -282,25 +429,22 @@ def create( ValueError: If name or prefix is not a valid identifier string. """ # Named -> global, unnamed -> tree-scoped. - is_global = name is not None - var_name = _generate_name(prefix) if name is None else name - if isinstance(var_name, Var): - msg = ( - "name must be a string, not a Var. The name keys the client " - "state store and is embedded in the events that `push`, " - "`retrieve` and `global_set` send, so it has to be known at " - "compile time." - ) - raise ValueError(msg) - if not isinstance(var_name, str): - msg = "name must be a string." - raise ValueError(msg) - if not _VALID_NAME.match(var_name): - msg = ( - f"name {var_name!r} is not a valid javascript identifier; it " - "is emitted as one in the compiled app." - ) - raise ValueError(msg) + if name is None: + return cls._create(default, _generate_name(prefix), is_global=False) + return cls._create(default, _validate_name(name, "name"), is_global=True) + + @classmethod + def _create(cls, default: Any, var_name: str, *, is_global: bool) -> ClientStateVar: + """Build a client state var for an already validated name. + + Args: + default: The default value of the variable, or ``NoValue``. + var_name: The store key, a chosen or generated name. + is_global: Whether the name resolves in the app-wide root scope. + + Returns: + The client state var. + """ if default is NoValue: # Explicit `undefined` rather than an empty expression: the name is # passed as a second argument, so an empty first argument would emit @@ -310,18 +454,21 @@ def create( default_var = LiteralVar.create(default) else: default_var = default - # The marker keeps a user-chosen name from colliding with a JS reserved - # word; the store key stays the bare name. - getter_name = f"{var_name}{CAMEL_CASE_CLIENT_STATE_MARKER}" - setter_name = f"set{var_name[0].upper()}{var_name[1:]}" + # The suffixes keep a user-chosen name from colliding with a JS reserved + # word, and with each other; the store key stays the bare name. + getter_name = f"{var_name}{_GETTER_SUFFIX}" + setter_name = f"{var_name}{_SETTER_SUFFIX}" # The name is always passed: it identifies the slot within whichever # scope owns it. The trailing flag is what escapes to the root scope. args = f"{default_var!s}, {LiteralVar.create(var_name)!s}" if is_global: args += ", true" - hooks: dict[str, VarData | None] = { - f"const [{getter_name}, {setter_name}] = useClientState({args})": None, - } + hook = f"const [{getter_name}, {setter_name}] = useClientState({args})" + if is_global and "$" not in var_name: + # Only a chosen name can be declared twice (a generated one, `$` + # and all, is unique), so only its site is kept. + _declaration_sites[hook] = _caller_site() + hooks: dict[str, VarData | None] = {hook: None} app_wraps = get_client_state_app_wraps() return cls( _js_expr="null", @@ -348,6 +495,34 @@ def create( ), ) + def _require_global(self, action: str) -> None: + """Reject addressing an unnamed var by name. + + Args: + action: What the caller tried to do. + + Raises: + ValueError: If the var is unnamed, pointing out a default that + looks like a misplaced name. + """ + if self._is_global: + return + msg = _NOT_GLOBAL_MSG.format(action=action) + # Read back from the hook: this is an error path, so no field is + # spent on remembering the default. + for hook in self._var_data.hooks if self._var_data else (): + match = _DECLARATION.search(hook) + if match and match[2] == self._state_name: + default = match[1] + if ( + len(default) > 2 + and default[0] == default[-1] == '"' + and _VALID_NAME.match(default[1:-1]) + ): + msg += _NAME_AS_DEFAULT_MSG.format(default=default) + break + raise ValueError(msg) + @property def value(self) -> Var: """A placeholder for the Var. @@ -437,9 +612,7 @@ def global_value(self) -> Var: Raises: ValueError: If the ClientStateVar is not global. """ - if not self._is_global: - msg = _NOT_GLOBAL_MSG.format(action="read the value from outside the tree") - raise ValueError(msg) + self._require_global("read the value from outside the tree") return Var( _js_expr=f"getClientState({LiteralVar.create(self._state_name)!s})", _var_data=self._escape_var_data, @@ -459,9 +632,7 @@ def global_set(self) -> Var: Raises: ValueError: If the ClientStateVar is not global. """ - if not self._is_global: - msg = _NOT_GLOBAL_MSG.format(action="set the value from outside the tree") - raise ValueError(msg) + self._require_global("set the value from outside the tree") return Var( _js_expr=( f"((value) => setClientState({LiteralVar.create(self._state_name)!s}, value))" @@ -483,9 +654,7 @@ def retrieve(self, callback: EventHandler | Callable | None = None) -> EventSpec Raises: ValueError: If the ClientStateVar is not global. """ - if not self._is_global: - msg = _NOT_GLOBAL_MSG.format(action="retrieve the value") - raise ValueError(msg) + self._require_global("retrieve the value") callback_kwargs = {"callback": None} if callback is not None: callback_kwargs = { @@ -517,9 +686,7 @@ def push(self, value: Any) -> EventSpec: Raises: ValueError: If the ClientStateVar is not global. """ - if not self._is_global: - msg = _NOT_GLOBAL_MSG.format(action="push a value") - raise ValueError(msg) + self._require_global("push a value") if isinstance(value, Var): # A Var is a client-side expression, which cannot survive the JSON # event payload -- it would arrive as its own source text. Evaluate diff --git a/packages/reflex-base/src/reflex_base/compiler/templates.py b/packages/reflex-base/src/reflex_base/compiler/templates.py index 368d91010d2..345b52400eb 100644 --- a/packages/reflex-base/src/reflex_base/compiler/templates.py +++ b/packages/reflex-base/src/reflex_base/compiler/templates.py @@ -1201,4 +1201,8 @@ def _render_hooks(hooks: dict[str, VarData | None]) -> str: Returns: Rendered hooks code as string. """ + # Imported here: reflex_base.client_state imports this module. + from reflex_base.client_state import _check_declarations + + _check_declarations(hooks) return "\n".join(hooks) diff --git a/packages/reflex-base/src/reflex_base/utils/exceptions.py b/packages/reflex-base/src/reflex_base/utils/exceptions.py index c18e9d34769..cb389bec193 100644 --- a/packages/reflex-base/src/reflex_base/utils/exceptions.py +++ b/packages/reflex-base/src/reflex_base/utils/exceptions.py @@ -312,3 +312,7 @@ class UnretrievableVarValueError(ReflexError): class HybridPropertyError(ReflexError): """Raised when a hybrid property is misused while building its frontend var.""" + + +class ClientStateConflictError(ReflexError, ValueError): + """Raised when one client state name is declared with two different defaults.""" diff --git a/reflex/app.py b/reflex/app.py index d4c8a376a97..bf840e9d915 100644 --- a/reflex/app.py +++ b/reflex/app.py @@ -34,6 +34,7 @@ from typing import TYPE_CHECKING, Any, overload from reflex_base import constants, otel +from reflex_base.client_state import _collect_declarations from reflex_base.components.component import Component, ComponentStyle from reflex_base.config import get_config, reload_config from reflex_base.context.base import BaseContext @@ -1878,7 +1879,8 @@ def _compile( """ from reflex_base.utils.deterministic_hash import clear_hash_caches - with otel.compile_span(trigger, dry_run): + # One record of client state declarations spans the whole compile. + with otel.compile_span(trigger, dry_run), _collect_declarations(): ctx = TelemetryContext.start(trigger=trigger) try: if ctx is None: diff --git a/reflex/experimental/client_state.py b/reflex/experimental/client_state.py index 136fa509f15..a0d03ed2545 100644 --- a/reflex/experimental/client_state.py +++ b/reflex/experimental/client_state.py @@ -12,7 +12,7 @@ from reflex_base.client_state import ClientStateVar as _ClientStateVar from reflex_base.client_state import NoValue as NoValue -from reflex_base.client_state import _generate_name +from reflex_base.client_state import _generate_name, _validate_name from reflex_base.utils import console __all__ = ["ClientStateVar", "NoValue", "client_state"] @@ -36,27 +36,33 @@ def _deprecate(feature_name: str) -> None: ) -def _legacy_name(var_name: str | None, global_ref: bool | Any) -> str | None: - """Map the legacy ``(var_name, global_ref)`` pair onto the naming rules. +def _legacy_create( + cls: type[_ClientStateVar], + var_name: str | None, + default: Any, + global_ref: bool | Any, +) -> _ClientStateVar: + """Create a var from the legacy ``(var_name, default, global_ref)`` arguments. ``global_ref`` defaults to true and an omitted ``var_name`` is generated, so a legacy var is global unless ``global_ref=False`` is passed, in which case its name is dropped and the var is scoped. Args: + cls: The class to instantiate. var_name: The legacy name. + default: The default value of the variable. global_ref: The legacy global flag, or ``NoValue`` when not given. Returns: - The name to create the var with: ``None`` scopes it, anything else - makes it global. + The client state var. """ if global_ref is not NoValue and not global_ref: - return None - if var_name is None: - # Drawn from the same generator as scoped names, so the two never collide. - return _generate_name() - return var_name + return cls._create(default, _generate_name(), is_global=False) + # A generated name is drawn from the same generator as scoped names, so the + # two never collide; it is global only because the legacy API made it so. + name = _generate_name() if var_name is None else _validate_name(var_name, "name") + return cls._create(default, name, is_global=True) class ClientStateVar(_ClientStateVar): @@ -86,7 +92,7 @@ def create( # pyright: ignore [reportIncompatibleMethodOverride] The client state var. """ _deprecate("ClientStateVar.create") - return super().create(default, name=_legacy_name(var_name, global_ref)) + return _legacy_create(cls, var_name, default, global_ref) def client_state( @@ -107,4 +113,4 @@ def client_state( The client state var. """ _deprecate("rx._x.client_state") - return _ClientStateVar.create(default, name=_legacy_name(var_name, global_ref)) + return _legacy_create(_ClientStateVar, var_name, default, global_ref) diff --git a/tests/units/compiler/test_memoize_plugin.py b/tests/units/compiler/test_memoize_plugin.py index 64c99a44bd6..bbb22334e51 100644 --- a/tests/units/compiler/test_memoize_plugin.py +++ b/tests/units/compiler/test_memoize_plugin.py @@ -1881,7 +1881,7 @@ def page() -> Component: code for path, code in memo_files if Path(path).name == f"{wrapper_tag}.jsx" ) - assert "setCounter(42)" in memo_code, ( + assert "counterRxClientStateSet(42)" in memo_code, ( "Expected the memo body to call the client-state setter.\n" f"Memo code snippet: {memo_code[:2000]}" ) @@ -1945,7 +1945,7 @@ def page() -> Component: ) # A global var passes ``true`` as the third argument; a scoped var omits it. hook = re.search( - r'const \[[\w$]+, (set[\w$]+)\] = useClientState\("a", "([\w$]+)"(, true)?\)', + r'const \[[\w$]+, ([\w$]+RxClientStateSet)\] = useClientState\("a", "([\w$]+)"(, true)?\)', button_memo, ) assert hook is not None, button_memo diff --git a/tests/units/experimental/test_client_state.py b/tests/units/experimental/test_client_state.py index cf74f7d7425..7b7b41318ca 100644 --- a/tests/units/experimental/test_client_state.py +++ b/tests/units/experimental/test_client_state.py @@ -94,3 +94,21 @@ def test_legacy_unnamed_var_stays_global(legacy_call: str) -> None: cs.push("x") cs.retrieve() assert cs.global_value is not None + + +def test_legacy_name_follows_the_name_rules() -> None: + """The deprecated factory validates names like the new one.""" + with pytest.raises(ValueError, match="letter or underscore"): + rx._x.client_state("a$b", 0) + + +def test_legacy_create_with_only_a_name_still_names_the_var( + caplog: pytest.LogCaptureFixture, +) -> None: + """The old class keeps reading a lone positional string as the name.""" + from reflex.experimental.client_state import ClientStateVar + + cs = ClientStateVar.create("user_input_legacy") + assert cs._state_name == "user_input_legacy" + assert cs._is_global + assert "ClientStateVar.create" in caplog.text diff --git a/tests/units/reflex_base/test_client_state.py b/tests/units/reflex_base/test_client_state.py index 7c9e46cabc5..c36030f4db0 100644 --- a/tests/units/reflex_base/test_client_state.py +++ b/tests/units/reflex_base/test_client_state.py @@ -8,7 +8,7 @@ from reflex_base.components.client_state_context import CLIENT_STATE_APP_WRAP_PRIORITY from reflex_base.components.memo import MEMOS from reflex_base.constants import Dirs -from reflex_base.utils.exceptions import VarTypeError +from reflex_base.utils.exceptions import ClientStateConflictError, VarTypeError from reflex_base.vars.base import Var, VarData from reflex_base.vars.function import FunctionVar @@ -69,7 +69,7 @@ def test_single_hook_no_useState() -> None: cs = client_state(0, name="counter") hook = _hook(cs) assert hook == ( - 'const [counterRxClientState, setCounter] = useClientState(0, "counter", true)' + 'const [counterRxClientState, counterRxClientStateSet] = useClientState(0, "counter", true)' ) assert "useState(" not in hook assert "useId" not in hook @@ -87,7 +87,7 @@ def test_omitted_default_emits_valid_javascript() -> None: hook = _hook(cs) assert "(," not in hook assert hook == ( - "const [counterRxClientState, setCounter] = " + "const [counterRxClientState, counterRxClientStateSet] = " 'useClientState(undefined, "counter", true)' ) @@ -145,14 +145,14 @@ def test_set_bare_is_event_chain() -> None: from reflex_base.event import EventChain cs = client_state(0, name="counter") - assert str(cs.set) == "setCounter" + assert str(cs.set) == "counterRxClientStateSet" assert cs.set._var_type is EventChain def test_set_bound_value() -> None: """Calling ``set`` binds a value in a zero-arg wrapper.""" cs = client_state(0, name="counter") - assert str(cs.set(42)) == "(() => (setCounter(42)))" + assert str(cs.set(42)) == "(() => (counterRxClientStateSet(42)))" @pytest.mark.parametrize("name", ["counter", None]) @@ -186,17 +186,17 @@ def test_set_carries_hook_import_and_app_wrap(name: str | None) -> None: ( 0, lambda v: v + 1, - "(() => (setX(((prev{n}RxClientState) => (prev{n}RxClientState + 1)))))", + "(() => (xRxClientStateSet(((prev{n}RxClientStateArg) => (prev{n}RxClientStateArg + 1)))))", ), ( False, lambda v: ~v, # noqa: FURB118 - a lambda is what is under test - "(() => (setX(((prev{n}RxClientState) => !(prev{n}RxClientState)))))", + "(() => (xRxClientStateSet(((prev{n}RxClientStateArg) => !(prev{n}RxClientStateArg)))))", ), ( "", lambda v: v.upper(), - "(() => (setX(((prev{n}RxClientState) => prev{n}RxClientState.toUpperCase()))))", + "(() => (xRxClientStateSet(((prev{n}RxClientStateArg) => prev{n}RxClientStateArg.toUpperCase()))))", ), ], ) @@ -212,7 +212,7 @@ def test_set_functional_updater_is_typed(default: Any, fn: Any, expected: str) - def test_set_zero_arg_callable_is_plain_value() -> None: """A zero-argument callable is treated as the value, not an updater.""" cs = client_state(0, name="x") - assert str(cs.set(lambda: 7)) == "(() => (setX(7)))" + assert str(cs.set(lambda: 7)) == "(() => (xRxClientStateSet(7)))" def test_set_rejects_multi_arg_callable() -> None: @@ -226,7 +226,7 @@ def test_set_passes_function_var_through() -> None: """A FunctionVar is passed straight through as a runtime updater.""" cs = client_state(0, name="x") updater = Var("(p) => p + 1").to(FunctionVar) - assert str(cs.set(updater)) == "(() => (setX((p) => p + 1)))" + assert str(cs.set(updater)) == "(() => (xRxClientStateSet((p) => p + 1)))" def test_set_declares_event_arg() -> None: @@ -238,7 +238,7 @@ def test_set_declares_event_arg() -> None: # trigger's ``_e`` placeholder. fn: Any = lambda value: cs.set(value) # noqa: E731 chain = str(Var.create(EventChain.create(fn, args_spec=cast("Any", input_event)))) - assert '((_e) => (setX(_e?.["target"]?.["value"])))' in chain + assert '((_e) => (xRxClientStateSet(_e?.["target"]?.["value"])))' in chain def _bound(fn: Any, *arg_types: type) -> str: @@ -261,21 +261,25 @@ def _bound(fn: Any, *arg_types: type) -> str: def test_set_declares_event_arg_read_through_an_operation() -> None: """A trigger argument used in a compound value is declared by the wrapper.""" cs = client_state(0, name="x") - assert "((_ev_0) => (setX((_ev_0 + 42))))" in _bound(lambda x: cs.set(x + 42), int) + assert "((_ev_0) => (xRxClientStateSet((_ev_0 + 42))))" in _bound( + lambda x: cs.set(x + 42), int + ) def test_set_declares_every_trigger_arg_up_to_the_last_one_read() -> None: """Arguments arrive positionally, so the declaration keeps the trigger's order.""" cs = client_state(0, name="x") - assert "((_ev_0, _ev_1) => (setX((_ev_1 - _ev_0))))" in _bound( + assert "((_ev_0, _ev_1) => (xRxClientStateSet((_ev_1 - _ev_0))))" in _bound( lambda a, b: cs.set(b - a), int, int ) # A skipped leading argument is still declared, or the one read would bind # to the wrong position. - assert "((_ev_0, _ev_1) => (setX(_ev_1)))" in _bound( + assert "((_ev_0, _ev_1) => (xRxClientStateSet(_ev_1)))" in _bound( lambda a, b: cs.set(b), int, int ) - assert "((_ev_0) => (setX(_ev_0)))" in _bound(lambda a, b: cs.set(a), int, int) + assert "((_ev_0) => (xRxClientStateSet(_ev_0)))" in _bound( + lambda a, b: cs.set(a), int, int + ) def test_trigger_arg_inside_a_nested_lambda_is_declared() -> None: @@ -284,7 +288,7 @@ def test_trigger_arg_inside_a_nested_lambda_is_declared() -> None: items = Var.create([1, 2]).to(list[int]) chain = _bound(lambda e: cs.set(items.map(lambda item: item + e).length()), int) assert re.search( - r"\(\(_ev_0\) => \(setX\(\[1, 2\]\.map\(\(\(\w+\) => \(\w+ \+ _ev_0\)\)\)\.length\)\)\)", + r"\(\(_ev_0\) => \(xRxClientStateSet\(\[1, 2\]\.map\(\(\(\w+\) => \(\w+ \+ _ev_0\)\)\)\.length\)\)\)", chain, ), chain @@ -294,7 +298,7 @@ def test_updater_closing_over_a_trigger_arg_declares_it() -> None: cs = client_state(0, name="x") chain = _bound(lambda e: cs.set(lambda prev: prev + e), int) assert re.search( - r"\(\(_ev_0\) => \(setX\(\(\((prev\d+RxClientState)\) => \(\1 \+ _ev_0\)\)\)\)\)", + r"\(\(_ev_0\) => \(xRxClientStateSet\(\(\((prev\d+RxClientStateArg)\) => \(\1 \+ _ev_0\)\)\)\)\)", chain, ), chain @@ -303,7 +307,10 @@ def test_underscore_named_var_is_not_mistaken_for_event_arg() -> None: """A marked identifier is an in-scope binding, never a trigger parameter.""" private = client_state("", name="_private") other = client_state("", name="other") - assert str(other.set(private.value)) == "(() => (setOther(_privateRxClientState)))" + assert ( + str(other.set(private.value)) + == "(() => (otherRxClientStateSet(_privateRxClientState)))" + ) @pytest.mark.parametrize( @@ -508,13 +515,16 @@ def comp(value: rx.Var[str]) -> rx.Component: comp(value="x") cs = rx.client_state("", name="target") - assert str(cs.set(captured["value"])) == "(() => (setTarget(valueRxMemo)))" + assert ( + str(cs.set(captured["value"])) + == "(() => (targetRxClientStateSet(valueRxMemo)))" + ) def test_set_with_no_argument_is_the_bare_setter() -> None: """``cs.set()`` is the same forwarding setter as ``cs.set``.""" cs = client_state(0, name="counter") - assert str(cs.set()) == str(cs.set) == "setCounter" + assert str(cs.set()) == str(cs.set) == "counterRxClientStateSet" def test_hash_distinguishes_vars() -> None: @@ -561,7 +571,7 @@ def test_derived_var_default_brings_its_hook_and_import() -> None: # The declaration comes first; ``useClientState`` reading it comes last. assert _hooks_ending_with_client_state(cs) == [ "const seed = useSeed()", - 'const [seededRxClientState, setSeeded] = useClientState(seed, "seeded", true)', + 'const [seededRxClientState, seededRxClientStateSet] = useClientState(seed, "seeded", true)', ] var_data = cs._get_all_var_data() assert var_data is not None @@ -721,7 +731,9 @@ def test_generated_name_separates_prefix_from_counter() -> None: assert re.fullmatch(r"row\$\d+", client_state(0, prefix="row")._state_name) # The identifiers derived from it stay valid javascript. cs = client_state(0, prefix="row") - assert _hook(cs).startswith(f"const [{cs._state_name}RxClientState, setRow$") + assert _hook(cs).startswith( + f"const [{cs._state_name}RxClientState, {cs._state_name}RxClientStateSet]" + ) with pytest.raises(ValueError, match=r"must not contain '\$'"): client_state(0, prefix="row$1") @@ -750,3 +762,229 @@ def toggle() -> rx.Component: CLIENT_STATE_APP_WRAP_PRIORITY, "ClientStateProvider", ) in toggle()._get_app_wrap_components() + + +@pytest.mark.parametrize("accessor", ["push", "retrieve", "global_value", "global_set"]) +def test_not_global_hint_names_the_var_by_keyword(accessor: str) -> None: + """The hint must show a call that names the var. + + Regression: it said ``rx.client_state("my_name")``, which passes the + default, so following it made another unnamed var and the same error. + + Args: + accessor: The name-addressed path to exercise. + """ + cs = client_state(0) + with pytest.raises(ValueError) as err: + if accessor == "push": + cs.push(1) + elif accessor == "retrieve": + cs.retrieve() + else: + getattr(cs, accessor) + message = str(err.value) + assert 'rx.client_state(default, name="my_name")' in message + assert 'rx.client_state("my_name")' not in message + + +def test_create_docstring_names_the_var_by_keyword() -> None: + """The docstring's global example names the var with ``name=``.""" + doc = ClientStateVar.create.__doc__ + assert doc is not None + assert 'rx.client_state("my_name")' not in doc + assert 'rx.client_state(default, name="my_name")' in doc + + +def test_name_passed_as_the_default_is_pointed_out() -> None: + """The old name-first order makes the name the default; the error says so.""" + trap = ClientStateVar.create("user_input") + with pytest.raises(ValueError, match="default") as err: + trap.push("x") + assert 'name="user_input"' in str(err.value) + + +def test_non_identifier_string_default_gets_no_name_hint() -> None: + """Only a default that could be a name gets the name-first hint.""" + with pytest.raises(ValueError) as err: + client_state("hello world").push("x") + assert 'name="hello world"' not in str(err.value) + assert "first positional" not in str(err.value) + + +def _declared_identifiers(code: str) -> list[str]: + """Get every identifier a ``const [a, b] = ...`` line declares. + + Args: + code: Compiled javascript. + + Returns: + The identifiers, in order, duplicates kept. + """ + return [ + ident + for pair in re.findall(r"const \[([\w$]+), ([\w$]+)\]", code) + for ident in pair + ] + + +def test_case_only_names_get_distinct_identifiers() -> None: + """``item`` and ``Item`` must not share a setter binding. + + Regression: the setter was ``set`` plus the capitalized name, so both + became ``setItem`` and the module failed with a duplicate declaration. + """ + lower = client_state("lower", name="item") + upper = client_state("upper", name="Item") + identifiers = { + lower._getter_name, + lower._setter_name, + upper._getter_name, + upper._setter_name, + } + assert len(identifiers) == 4 + # Derived from the getter, which is the name plus a fixed marker. + assert lower._setter_name.startswith(lower._getter_name) + assert upper._setter_name.startswith(upper._getter_name) + + +@pytest.mark.usefixtures("preserve_memo_registries") +def test_case_only_names_compile_without_duplicate_declarations() -> None: + """Both setters on one element compile into one body without a clash.""" + lower = client_state("lower", name="item_cc") + upper = client_state("upper", name="Item_cc") + + @rx.memo + def both_setters() -> rx.Component: + return rx.el.button( + lower.value, + upper.value, + on_click=[lower.set("a"), upper.set("b")], + ) + + files, _ = compiler.compile_memo_components((MEMOS["BothSetters", __name__],)) + code = "\n".join(c for _, c in files) + identifiers = _declared_identifiers(code) + assert lower._setter_name in identifiers + assert upper._setter_name in identifiers + assert len(identifiers) == len(set(identifiers)), identifiers + + +def test_updater_placeholder_never_shadows_a_getter() -> None: + """A lambda's placeholder must not be spelled like another var's getter.""" + cs = client_state(0, name="x") + rendered = str(cs.set(lambda v: v + 1)) + placeholder = re.search(r"\(\(([\w$]+)\) =>", rendered) + assert placeholder is not None + # The name the next placeholder would draw, as a var name. + n = int(re.sub(r"\D", "", placeholder[1].split("RxClientState")[0])) + 1 + other = client_state(1, name=f"prev{n}") + rendered = str(cs.set(lambda v: v + other.value)) + placeholder = re.search(r"\(\(([\w$]+)\) =>", rendered) + assert placeholder is not None + assert placeholder[1] != other._getter_name + assert other._getter_name in rendered + + +@pytest.mark.parametrize( + "good", + ["color", "search_query", "picker_color", "icon_search", "_private", "myVar", "a1"], +) +def test_documented_names_stay_valid(good: str) -> None: + """The names the docs use, and ordinary identifiers, are accepted. + + Args: + good: A valid name. + """ + assert client_state("", name=good)._state_name == good + + +@pytest.mark.parametrize("bad", ["a$b", "cs$0", "$x", "é"]) +def test_name_rejects_dollar_and_non_ascii(bad: str) -> None: + """``$`` is reserved for generated names, so a chosen name cannot equal one. + + Regression: ``name="cs$0"`` was accepted and declared the same bindings as + the first unnamed var. + + Args: + bad: An invalid name. + """ + with pytest.raises(ValueError, match=re.escape(repr(bad))) as err: + client_state(0, name=bad) + assert "letter or underscore" in str(err.value) + + +def test_name_type_error_names_the_bad_value() -> None: + """A non-string name is rejected with the offending value in the message.""" + with pytest.raises(ValueError, match=r"must be a string, got int: 5"): + client_state(name=5) # pyright: ignore [reportArgumentType] + + +@pytest.mark.usefixtures("preserve_memo_registries") +def test_same_body_conflicting_defaults_fail_at_compile() -> None: + """One name declared twice with two defaults in one body is a clear error. + + Regression: with ``auto_memoize=False`` this emitted two ``const`` + declarations of the same binding and every route failed to load. + Creating the vars must not raise; only compiling them does. + """ + first = client_state(False, name="open_cc") + second = client_state(True, name="open_cc") + + @rx.memo + def conflicting() -> rx.Component: + return rx.el.div(first.value, second.value) + + with pytest.raises(ClientStateConflictError, match="'open_cc'") as err: + compiler.compile_memo_components((MEMOS["Conflicting", __name__],)) + message = str(err.value) + assert "`false`" in message + assert "`true`" in message + # Both declaration sites are named. + assert message.count(f"{__file__}:") == 2 + + +@pytest.mark.usefixtures("preserve_memo_registries") +def test_same_body_identical_declarations_compile() -> None: + """Declaring one name twice with the same default stays allowed.""" + first = client_state(False, name="same_cc") + second = client_state(False, name="same_cc") + + @rx.memo + def identical() -> rx.Component: + return rx.el.div(first.value, second.value) + + files, _ = compiler.compile_memo_components((MEMOS["Identical", __name__],)) + identifiers = _declared_identifiers("\n".join(c for _, c in files)) + assert identifiers.count(first._getter_name) == 1 + + +@pytest.mark.usefixtures("preserve_memo_registries") +def test_multiline_default_conflict_fails_at_compile() -> None: + """A default whose javascript spans lines is still compared. + + Regression: the declaration pattern did not match across newlines, so + such a default skipped the check. + """ + multiline = client_state(Var("(1 +\n2)").to(int), name="multi_cc") + plain = client_state(0, name="multi_cc") + + @rx.memo + def multiline_conflict() -> rx.Component: + return rx.el.div(multiline.value, plain.value) + + with pytest.raises(ClientStateConflictError, match="'multi_cc'"): + compiler.compile_memo_components((MEMOS["MultilineConflict", __name__],)) + + +def test_generated_global_names_record_no_declaration_site() -> None: + """Only chosen names can conflict, so only they keep a declaration site. + + Regression: every legacy unnamed global var added an entry that was never + released. + """ + from reflex_base import client_state as client_state_module + + before = len(client_state_module._declaration_sites) + for _ in range(3): + rx._x.client_state(default=0) + assert len(client_state_module._declaration_sites) == before diff --git a/tests/units/test_app.py b/tests/units/test_app.py index 34405f9b8ce..e666d9de0dc 100644 --- a/tests/units/test_app.py +++ b/tests/units/test_app.py @@ -6311,3 +6311,73 @@ async def echo_app(scope, receive, send): status, _, _ = await _asgi_http_call(app, "GET", "", b"") assert status == 200 + + +def test_client_state_conflicting_defaults_fail_the_compile( + compilable_app: tuple[App, Path], + mocker: MockerFixture, + clean_registration_context: RegistrationContext, +) -> None: + """One name declared on two pages with two defaults fails the compile. + + Regression: this compiled, and whichever page mounted first decided the + value silently. Creating the vars must still work (hot reload declares again + them), so the error comes from the compile and names both declarations. + """ + mocker.patch( + "reflex_base.config._get_config", + return_value=rx.Config(app_name="testing"), + ) + app, _ = compilable_app + closed = rx.client_state(False, name="open_app") + opened = rx.client_state(True, name="open_app") + app.add_page(lambda: rx.text(closed.value), route="/a") + app.add_page(lambda: rx.text(opened.value), route="/b") + + with pytest.raises(exceptions.ClientStateConflictError, match="'open_app'") as err: + app._compile(dry_run=True) + # A compile error, like the compiler's other app-level errors. + assert isinstance(err.value, exceptions.ReflexError) + message = str(err.value) + assert "`false`" in message + assert "`true`" in message + assert message.count(f"{__file__}:") == 2 + + +def test_client_state_identical_declarations_compile( + compilable_app: tuple[App, Path], + mocker: MockerFixture, + clean_registration_context: RegistrationContext, +) -> None: + """Two modules may each declare the same global var with the same default.""" + mocker.patch( + "reflex_base.config._get_config", + return_value=rx.Config(app_name="testing"), + ) + app, _ = compilable_app + first = rx.client_state(False, name="shared_app") + second = rx.client_state(False, name="shared_app") + app.add_page(lambda: rx.text(first.value), route="/a") + app.add_page(lambda: rx.text(second.value), route="/b") + app._compile(dry_run=True) + + +def test_client_state_conflicts_do_not_outlive_a_compile( + compilable_app: tuple[App, Path], + mocker: MockerFixture, + clean_registration_context: RegistrationContext, +) -> None: + """A var declared again with an edited default compiles again (hot reload).""" + mocker.patch( + "reflex_base.config._get_config", + return_value=rx.Config(app_name="testing"), + ) + app, _ = compilable_app + before = rx.client_state(False, name="edited_app") + app.add_page(lambda: rx.text(before.value), route="/a") + app._compile(dry_run=True) + + after = rx.client_state(True, name="edited_app") + app._unevaluated_pages.clear() + app.add_page(lambda: rx.text(after.value), route="/a") + app._compile(dry_run=True)