compiler.py 26 KB

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