1
0

compiler.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. """Compiler for the reflex apps."""
  2. from __future__ import annotations
  3. from datetime import datetime
  4. from pathlib import Path
  5. from typing import TYPE_CHECKING, Iterable, Sequence, Type
  6. from reflex import constants
  7. from reflex.compiler import templates, utils
  8. from reflex.components.base.fragment import Fragment
  9. from reflex.components.component import (
  10. BaseComponent,
  11. Component,
  12. ComponentStyle,
  13. CustomComponent,
  14. StatefulComponent,
  15. )
  16. from reflex.config import environment, get_config
  17. from reflex.state import BaseState
  18. from reflex.style import SYSTEM_COLOR_MODE
  19. from reflex.utils.exec import is_prod_mode
  20. from reflex.utils.imports import ImportVar
  21. from reflex.utils.prerequisites import get_web_dir
  22. from reflex.vars.base import LiteralVar, Var
  23. def _compile_document_root(root: Component) -> str:
  24. """Compile the document root.
  25. Args:
  26. root: The document root to compile.
  27. Returns:
  28. The compiled document root.
  29. """
  30. return templates.DOCUMENT_ROOT.render(
  31. imports=utils.compile_imports(root._get_all_imports()),
  32. document=root.render(),
  33. )
  34. def _normalize_library_name(lib: str) -> str:
  35. """Normalize the library name.
  36. Args:
  37. lib: The library name to normalize.
  38. Returns:
  39. The normalized library name.
  40. """
  41. if lib == "react":
  42. return "React"
  43. return lib.replace("@", "").replace("/", "_").replace("-", "_")
  44. def _compile_app(app_root: Component) -> str:
  45. """Compile the app template component.
  46. Args:
  47. app_root: The app root to compile.
  48. Returns:
  49. The compiled app.
  50. """
  51. from reflex.components.dynamic import bundled_libraries
  52. window_libraries = [
  53. (_normalize_library_name(name), name) for name in bundled_libraries
  54. ] + [
  55. ("utils_context", f"$/{constants.Dirs.UTILS}/context"),
  56. ("utils_state", f"$/{constants.Dirs.UTILS}/state"),
  57. ]
  58. return templates.APP_ROOT.render(
  59. imports=utils.compile_imports(app_root._get_all_imports()),
  60. custom_codes=app_root._get_all_custom_code(),
  61. hooks=app_root._get_all_hooks(),
  62. window_libraries=window_libraries,
  63. render=app_root.render(),
  64. dynamic_imports=app_root._get_all_dynamic_imports(),
  65. )
  66. def _compile_theme(theme: str) -> str:
  67. """Compile the theme.
  68. Args:
  69. theme: The theme to compile.
  70. Returns:
  71. The compiled theme.
  72. """
  73. return templates.THEME.render(theme=theme)
  74. def _compile_contexts(state: Type[BaseState] | None, theme: Component | None) -> str:
  75. """Compile the initial state and contexts.
  76. Args:
  77. state: The app state.
  78. theme: The top-level app theme.
  79. Returns:
  80. The compiled context file.
  81. """
  82. appearance = getattr(theme, "appearance", None)
  83. if appearance is None or str(LiteralVar.create(appearance)) == '"inherit"':
  84. appearance = LiteralVar.create(SYSTEM_COLOR_MODE)
  85. last_compiled_time = str(datetime.now())
  86. return (
  87. templates.CONTEXT.render(
  88. initial_state=utils.compile_state(state),
  89. state_name=state.get_name(),
  90. client_storage=utils.compile_client_storage(state),
  91. is_dev_mode=not is_prod_mode(),
  92. last_compiled_time=last_compiled_time,
  93. default_color_mode=appearance,
  94. )
  95. if state
  96. else templates.CONTEXT.render(
  97. is_dev_mode=not is_prod_mode(),
  98. default_color_mode=appearance,
  99. last_compiled_time=last_compiled_time,
  100. )
  101. )
  102. def _compile_page(
  103. component: BaseComponent,
  104. state: Type[BaseState] | None,
  105. ) -> str:
  106. """Compile the component given the app state.
  107. Args:
  108. component: The component to compile.
  109. state: The app state.
  110. Returns:
  111. The compiled component.
  112. """
  113. imports = component._get_all_imports()
  114. imports = utils.compile_imports(imports)
  115. # Compile the code to render the component.
  116. kwargs = {"state_name": state.get_name()} if state is not None else {}
  117. return templates.PAGE.render(
  118. imports=imports,
  119. dynamic_imports=component._get_all_dynamic_imports(),
  120. custom_codes=component._get_all_custom_code(),
  121. hooks=component._get_all_hooks(),
  122. render=component.render(),
  123. **kwargs,
  124. )
  125. def compile_root_stylesheet(stylesheets: list[str]) -> tuple[str, str]:
  126. """Compile the root stylesheet.
  127. Args:
  128. stylesheets: The stylesheets to include in the root stylesheet.
  129. Returns:
  130. The path and code of the compiled root stylesheet.
  131. """
  132. output_path = utils.get_root_stylesheet_path()
  133. code = _compile_root_stylesheet(stylesheets)
  134. return output_path, code
  135. def _compile_root_stylesheet(stylesheets: list[str]) -> str:
  136. """Compile the root stylesheet.
  137. Args:
  138. stylesheets: The stylesheets to include in the root stylesheet.
  139. Returns:
  140. The compiled root stylesheet.
  141. Raises:
  142. FileNotFoundError: If a specified stylesheet in assets directory does not exist.
  143. """
  144. # Add tailwind css if enabled.
  145. sheets = (
  146. [constants.Tailwind.ROOT_STYLE_PATH]
  147. if get_config().tailwind is not None
  148. else []
  149. )
  150. for stylesheet in stylesheets:
  151. if not utils.is_valid_url(stylesheet):
  152. # check if stylesheet provided exists.
  153. stylesheet_full_path = (
  154. Path.cwd() / constants.Dirs.APP_ASSETS / stylesheet.strip("/")
  155. )
  156. if not stylesheet_full_path.exists():
  157. raise FileNotFoundError(
  158. f"The stylesheet file {stylesheet_full_path} does not exist."
  159. )
  160. stylesheet = f"../{constants.Dirs.PUBLIC}/{stylesheet.strip('/')}"
  161. sheets.append(stylesheet) if stylesheet not in sheets else None
  162. return templates.STYLE.render(stylesheets=sheets)
  163. def _compile_component(component: Component | StatefulComponent) -> str:
  164. """Compile a single component.
  165. Args:
  166. component: The component to compile.
  167. Returns:
  168. The compiled component.
  169. """
  170. return templates.COMPONENT.render(component=component)
  171. def _compile_components(
  172. components: set[CustomComponent],
  173. ) -> tuple[str, dict[str, list[ImportVar]]]:
  174. """Compile the components.
  175. Args:
  176. components: The components to compile.
  177. Returns:
  178. The compiled components.
  179. """
  180. imports = {
  181. "react": [ImportVar(tag="memo")],
  182. f"$/{constants.Dirs.STATE_PATH}": [ImportVar(tag="E"), ImportVar(tag="isTrue")],
  183. }
  184. component_renders = []
  185. # Compile each component.
  186. for component in components:
  187. component_render, component_imports = utils.compile_custom_component(component)
  188. component_renders.append(component_render)
  189. imports = utils.merge_imports(imports, component_imports)
  190. dynamic_imports = {
  191. comp_import: None
  192. for comp_render in component_renders
  193. if "dynamic_imports" in comp_render
  194. for comp_import in comp_render["dynamic_imports"]
  195. }
  196. custom_codes = {
  197. comp_custom_code: None
  198. for comp_render in component_renders
  199. for comp_custom_code in comp_render.get("custom_code", [])
  200. }
  201. # Compile the components page.
  202. return (
  203. templates.COMPONENTS.render(
  204. imports=utils.compile_imports(imports),
  205. components=component_renders,
  206. dynamic_imports=dynamic_imports,
  207. custom_codes=custom_codes,
  208. ),
  209. imports,
  210. )
  211. def _compile_stateful_components(
  212. page_components: list[BaseComponent],
  213. ) -> str:
  214. """Walk the page components and extract shared stateful components.
  215. Any StatefulComponent that is shared by more than one page will be rendered
  216. to a separate module and marked rendered_as_shared so subsequent
  217. renderings will import the component from the shared module instead of
  218. directly including the code for it.
  219. Args:
  220. page_components: The Components or StatefulComponents to compile.
  221. Returns:
  222. The rendered stateful components code.
  223. """
  224. all_import_dicts = []
  225. rendered_components = {}
  226. def get_shared_components_recursive(component: BaseComponent):
  227. """Get the shared components for a component and its children.
  228. A shared component is a StatefulComponent that appears in 2 or more
  229. pages and is a candidate for writing to a common file and importing
  230. into each page where it is used.
  231. Args:
  232. component: The component to collect shared StatefulComponents for.
  233. """
  234. for child in component.children:
  235. # Depth-first traversal.
  236. get_shared_components_recursive(child)
  237. # When the component is referenced by more than one page, render it
  238. # to be included in the STATEFUL_COMPONENTS module.
  239. # Skip this step in dev mode, thereby avoiding potential hot reload errors for larger apps
  240. if (
  241. isinstance(component, StatefulComponent)
  242. and component.references > 1
  243. and is_prod_mode()
  244. ):
  245. # Reset this flag to render the actual component.
  246. component.rendered_as_shared = False
  247. # Include dynamic imports in the shared component.
  248. if dynamic_imports := component._get_all_dynamic_imports():
  249. rendered_components.update(
  250. {dynamic_import: None for dynamic_import in dynamic_imports}
  251. )
  252. # Include custom code in the shared component.
  253. rendered_components.update(
  254. {code: None for code in component._get_all_custom_code()},
  255. )
  256. # Include all imports in the shared component.
  257. all_import_dicts.append(component._get_all_imports())
  258. # Indicate that this component now imports from the shared file.
  259. component.rendered_as_shared = True
  260. for page_component in page_components:
  261. get_shared_components_recursive(page_component)
  262. # Don't import from the file that we're about to create.
  263. all_imports = utils.merge_imports(*all_import_dicts)
  264. all_imports.pop(
  265. f"$/{constants.Dirs.UTILS}/{constants.PageNames.STATEFUL_COMPONENTS}", None
  266. )
  267. return templates.STATEFUL_COMPONENTS.render(
  268. imports=utils.compile_imports(all_imports),
  269. memoized_code="\n".join(rendered_components),
  270. )
  271. def _compile_tailwind(
  272. config: dict,
  273. ) -> str:
  274. """Compile the Tailwind config.
  275. Args:
  276. config: The Tailwind config.
  277. Returns:
  278. The compiled Tailwind config.
  279. """
  280. return templates.TAILWIND_CONFIG.render(
  281. **config,
  282. )
  283. def compile_document_root(
  284. head_components: list[Component],
  285. html_lang: str | None = None,
  286. html_custom_attrs: dict[str, Var | str] | None = None,
  287. ) -> tuple[str, str]:
  288. """Compile the document root.
  289. Args:
  290. head_components: The components to include in the head.
  291. html_lang: The language of the document, will be added to the html root element.
  292. html_custom_attrs: custom attributes added to the html root element.
  293. Returns:
  294. The path and code of the compiled document root.
  295. """
  296. # Get the path for the output file.
  297. output_path = utils.get_page_path(constants.PageNames.DOCUMENT_ROOT)
  298. # Create the document root.
  299. document_root = utils.create_document_root(
  300. head_components, html_lang=html_lang, html_custom_attrs=html_custom_attrs
  301. )
  302. # Compile the document root.
  303. code = _compile_document_root(document_root)
  304. return output_path, code
  305. def compile_app(app_root: Component) -> tuple[str, str]:
  306. """Compile the app root.
  307. Args:
  308. app_root: The app root component to compile.
  309. Returns:
  310. The path and code of the compiled app wrapper.
  311. """
  312. # Get the path for the output file.
  313. output_path = utils.get_page_path(constants.PageNames.APP_ROOT)
  314. # Compile the document root.
  315. code = _compile_app(app_root)
  316. return output_path, code
  317. def compile_theme(style: ComponentStyle) -> tuple[str, str]:
  318. """Compile the theme.
  319. Args:
  320. style: The style to compile.
  321. Returns:
  322. The path and code of the compiled theme.
  323. """
  324. output_path = utils.get_theme_path()
  325. # Create the theme.
  326. theme = utils.create_theme(style)
  327. # Compile the theme.
  328. code = _compile_theme(str(LiteralVar.create(theme)))
  329. return output_path, code
  330. def compile_contexts(
  331. state: Type[BaseState] | None,
  332. theme: Component | None,
  333. ) -> tuple[str, str]:
  334. """Compile the initial state / context.
  335. Args:
  336. state: The app state.
  337. theme: The top-level app theme.
  338. Returns:
  339. The path and code of the compiled context.
  340. """
  341. # Get the path for the output file.
  342. output_path = utils.get_context_path()
  343. return output_path, _compile_contexts(state, theme)
  344. def compile_page(
  345. path: str, component: BaseComponent, state: Type[BaseState] | None
  346. ) -> tuple[str, str]:
  347. """Compile a single page.
  348. Args:
  349. path: The path to compile the page to.
  350. component: The component to compile.
  351. state: The app state.
  352. Returns:
  353. The path and code of the compiled page.
  354. """
  355. # Get the path for the output file.
  356. output_path = utils.get_page_path(path)
  357. # Add the style to the component.
  358. code = _compile_page(component, state)
  359. return output_path, code
  360. def compile_components(
  361. components: set[CustomComponent],
  362. ) -> tuple[str, str, dict[str, list[ImportVar]]]:
  363. """Compile the custom components.
  364. Args:
  365. components: The custom components to compile.
  366. Returns:
  367. The path and code of the compiled components.
  368. """
  369. # Get the path for the output file.
  370. output_path = utils.get_components_path()
  371. # Compile the components.
  372. code, imports = _compile_components(components)
  373. return output_path, code, imports
  374. def compile_stateful_components(
  375. pages: Iterable[Component],
  376. ) -> tuple[str, str, list[BaseComponent]]:
  377. """Separately compile components that depend on State vars.
  378. StatefulComponents are compiled as their own component functions with their own
  379. useContext declarations, which allows page components to be stateless and avoid
  380. re-rendering along with parts of the page that actually depend on state.
  381. Args:
  382. pages: The pages to extract stateful components from.
  383. Returns:
  384. The path and code of the compiled stateful components.
  385. """
  386. output_path = utils.get_stateful_components_path()
  387. # Compile the stateful components.
  388. page_components = [StatefulComponent.compile_from(page) or page for page in pages]
  389. code = _compile_stateful_components(page_components)
  390. return output_path, code, page_components
  391. def compile_tailwind(
  392. config: dict,
  393. ):
  394. """Compile the Tailwind config.
  395. Args:
  396. config: The Tailwind config.
  397. Returns:
  398. The compiled Tailwind config.
  399. """
  400. # Get the path for the output file.
  401. output_path = str((get_web_dir() / constants.Tailwind.CONFIG).absolute())
  402. # Compile the config.
  403. code = _compile_tailwind(config)
  404. return output_path, code
  405. def remove_tailwind_from_postcss() -> tuple[str, str]:
  406. """If tailwind is not to be used, remove it from postcss.config.js.
  407. Returns:
  408. The path and code of the compiled postcss.config.js.
  409. """
  410. # Get the path for the output file.
  411. output_path = str(get_web_dir() / constants.Dirs.POSTCSS_JS)
  412. code = [
  413. line
  414. for line in Path(output_path).read_text().splitlines(keepends=True)
  415. if "tailwindcss: " not in line
  416. ]
  417. # Compile the config.
  418. return output_path, "".join(code)
  419. def purge_web_pages_dir():
  420. """Empty out .web/pages directory."""
  421. if not is_prod_mode() and environment.REFLEX_PERSIST_WEB_DIR.get():
  422. # Skip purging the web directory in dev mode if REFLEX_PERSIST_WEB_DIR is set.
  423. return
  424. # Empty out the web pages directory.
  425. utils.empty_dir(get_web_dir() / constants.Dirs.PAGES, keep_files=["_app.js"])
  426. if TYPE_CHECKING:
  427. from reflex.app import ComponentCallable, UnevaluatedPage
  428. def _into_component_once(component: Component | ComponentCallable) -> Component | None:
  429. """Convert a component to a Component.
  430. Args:
  431. component: The component to convert.
  432. Returns:
  433. The converted component.
  434. """
  435. if isinstance(component, Component):
  436. return component
  437. if isinstance(component, (Var, int, float, str)):
  438. return Fragment.create(component)
  439. if isinstance(component, Sequence):
  440. return Fragment.create(*component)
  441. return None
  442. def into_component(component: Component | ComponentCallable) -> Component:
  443. """Convert a component to a Component.
  444. Args:
  445. component: The component to convert.
  446. Returns:
  447. The converted component.
  448. Raises:
  449. TypeError: If the component is not a Component.
  450. # noqa: DAR401
  451. """
  452. if (converted := _into_component_once(component)) is not None:
  453. return converted
  454. try:
  455. if (
  456. callable(component)
  457. and (converted := _into_component_once(component())) is not None
  458. ):
  459. return converted
  460. except KeyError as e:
  461. key = e.args[0] if e.args else None
  462. if key is not None and isinstance(key, Var):
  463. raise TypeError(
  464. "Cannot access a primitive map with a Var. Consider calling rx.Var.create() on the map."
  465. ).with_traceback(e.__traceback__) from None
  466. raise
  467. except TypeError as e:
  468. message = e.args[0] if e.args else None
  469. if message and isinstance(message, str):
  470. if message.endswith("has no len()") and (
  471. "ArrayCastedVar" in message
  472. or "ObjectCastedVar" in message
  473. or "StringCastedVar" in message
  474. ):
  475. raise TypeError(
  476. "Cannot pass a Var to a built-in function. Consider using .length() for accessing the length of an iterable Var."
  477. ).with_traceback(e.__traceback__) from None
  478. if message.endswith(
  479. "indices must be integers or slices, not NumberCastedVar"
  480. ) or message.endswith(
  481. "indices must be integers or slices, not BooleanCastedVar"
  482. ):
  483. raise TypeError(
  484. "Cannot index into a primitive sequence with a Var. Consider calling rx.Var.create() on the sequence."
  485. ).with_traceback(e.__traceback__) from None
  486. if "CastedVar" in str(e):
  487. raise TypeError(
  488. "Cannot pass a Var to a built-in function. Consider moving the operation to the backend, using existing Var operations, or defining a custom Var operation."
  489. ).with_traceback(e.__traceback__) from None
  490. raise
  491. raise TypeError(f"Expected a Component, got {type(component)}")
  492. def compile_unevaluated_page(
  493. route: str,
  494. page: UnevaluatedPage,
  495. state: Type[BaseState] | None = None,
  496. style: ComponentStyle | None = None,
  497. theme: Component | None = None,
  498. ) -> tuple[Component, bool]:
  499. """Compiles an uncompiled page into a component and adds meta information.
  500. Args:
  501. route: The route of the page.
  502. page: The uncompiled page object.
  503. state: The state of the app.
  504. style: The style of the page.
  505. theme: The theme of the page.
  506. Returns:
  507. The compiled component and whether state should be enabled.
  508. """
  509. # Generate the component if it is a callable.
  510. component = into_component(page.component)
  511. component._add_style_recursive(style or {}, theme)
  512. enable_state = False
  513. # Ensure state is enabled if this page uses state.
  514. if state is None:
  515. if page.on_load or component._has_stateful_event_triggers():
  516. enable_state = True
  517. else:
  518. for var in component._get_vars(include_children=True):
  519. var_data = var._get_all_var_data()
  520. if not var_data:
  521. continue
  522. if not var_data.state:
  523. continue
  524. enable_state = True
  525. break
  526. from reflex.app import OverlayFragment
  527. from reflex.utils.format import make_default_page_title
  528. component = OverlayFragment.create(component)
  529. meta_args = {
  530. "title": (
  531. page.title
  532. if page.title is not None
  533. else make_default_page_title(get_config().app_name, route)
  534. ),
  535. "image": page.image,
  536. "meta": page.meta,
  537. }
  538. if page.description is not None:
  539. meta_args["description"] = page.description
  540. # Add meta information to the component.
  541. utils.add_meta(
  542. component,
  543. **meta_args,
  544. )
  545. return component, enable_state
  546. class ExecutorSafeFunctions:
  547. """Helper class to allow parallelisation of parts of the compilation process.
  548. This class (and its class attributes) are available at global scope.
  549. In a multiprocessing context (like when using a ProcessPoolExecutor), the content of this
  550. global class is logically replicated to any FORKED process.
  551. How it works:
  552. * Before the child process is forked, ensure that we stash any input data required by any future
  553. function call in the child process.
  554. * After the child process is forked, the child process will have a copy of the global class, which
  555. includes the previously stashed input data.
  556. * Any task submitted to the child process simply needs a way to communicate which input data the
  557. requested function call requires.
  558. Why do we need this? Passing input data directly to child process often not possible because the input data is not picklable.
  559. The mechanic described here removes the need to pickle the input data at all.
  560. Limitations:
  561. * This can never support returning unpicklable OUTPUT data.
  562. * Any object mutations done by the child process will not propagate back to the parent process (fork goes one way!).
  563. """
  564. COMPONENTS: dict[str, BaseComponent] = {}
  565. UNCOMPILED_PAGES: dict[str, UnevaluatedPage] = {}
  566. STATE: Type[BaseState] | None = None
  567. @classmethod
  568. def compile_page(cls, route: str) -> tuple[str, str]:
  569. """Compile a page.
  570. Args:
  571. route: The route of the page to compile.
  572. Returns:
  573. The path and code of the compiled page.
  574. """
  575. return compile_page(route, cls.COMPONENTS[route], cls.STATE)
  576. @classmethod
  577. def compile_unevaluated_page(
  578. cls,
  579. route: str,
  580. style: ComponentStyle,
  581. theme: Component | None,
  582. ) -> tuple[str, Component, tuple[str, str]]:
  583. """Compile an unevaluated page.
  584. Args:
  585. route: The route of the page to compile.
  586. style: The style of the page.
  587. theme: The theme of the page.
  588. Returns:
  589. The route, compiled component, and compiled page.
  590. """
  591. component, enable_state = compile_unevaluated_page(
  592. route, cls.UNCOMPILED_PAGES[route], cls.STATE, style, theme
  593. )
  594. return route, component, compile_page(route, component, cls.STATE)
  595. @classmethod
  596. def compile_theme(cls, style: ComponentStyle | None) -> tuple[str, str]:
  597. """Compile the theme.
  598. Args:
  599. style: The style to compile.
  600. Returns:
  601. The path and code of the compiled theme.
  602. Raises:
  603. ValueError: If the style is not set.
  604. """
  605. if style is None:
  606. raise ValueError("STYLE should be set")
  607. return compile_theme(style)