prerequisites.py 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076
  1. """Everything related to fetching or initializing build prerequisites."""
  2. from __future__ import annotations
  3. import contextlib
  4. import dataclasses
  5. import functools
  6. import importlib
  7. import importlib.metadata
  8. import importlib.util
  9. import io
  10. import json
  11. import os
  12. import platform
  13. import random
  14. import re
  15. import shutil
  16. import sys
  17. import tempfile
  18. import time
  19. import typing
  20. import zipfile
  21. from datetime import datetime
  22. from pathlib import Path
  23. from types import ModuleType
  24. from typing import Callable, NamedTuple, Sequence
  25. from urllib.parse import urlparse
  26. import httpx
  27. import typer
  28. from alembic.util.exc import CommandError
  29. from packaging import version
  30. from redis import Redis as RedisSync
  31. from redis.asyncio import Redis
  32. from redis.exceptions import RedisError
  33. from reflex import constants, model
  34. from reflex.compiler import templates
  35. from reflex.config import Config, environment, get_config
  36. from reflex.utils import console, net, path_ops, processes
  37. from reflex.utils.exceptions import (
  38. GeneratedCodeHasNoFunctionDefsError,
  39. SystemPackageMissingError,
  40. )
  41. from reflex.utils.format import format_library_name
  42. from reflex.utils.registry import get_npm_registry
  43. if typing.TYPE_CHECKING:
  44. from reflex.app import App
  45. class AppInfo(NamedTuple):
  46. """A tuple containing the app instance and module."""
  47. app: App
  48. module: ModuleType
  49. @dataclasses.dataclass(frozen=True)
  50. class Template:
  51. """A template for a Reflex app."""
  52. name: str
  53. description: str
  54. code_url: str
  55. demo_url: str | None = None
  56. @dataclasses.dataclass(frozen=True)
  57. class CpuInfo:
  58. """Model to save cpu info."""
  59. manufacturer_id: str | None
  60. model_name: str | None
  61. address_width: int | None
  62. def get_web_dir() -> Path:
  63. """Get the working directory for the next.js commands.
  64. Can be overridden with REFLEX_WEB_WORKDIR.
  65. Returns:
  66. The working directory.
  67. """
  68. return environment.REFLEX_WEB_WORKDIR.get()
  69. def get_states_dir() -> Path:
  70. """Get the working directory for the states.
  71. Can be overridden with REFLEX_STATES_WORKDIR.
  72. Returns:
  73. The working directory.
  74. """
  75. return environment.REFLEX_STATES_WORKDIR.get()
  76. def get_backend_dir() -> Path:
  77. """Get the working directory for the backend.
  78. Returns:
  79. The working directory.
  80. """
  81. return get_web_dir() / constants.Dirs.BACKEND
  82. def check_latest_package_version(package_name: str):
  83. """Check if the latest version of the package is installed.
  84. Args:
  85. package_name: The name of the package.
  86. """
  87. if environment.REFLEX_CHECK_LATEST_VERSION.get() is False:
  88. return
  89. try:
  90. console.debug(f"Checking for the latest version of {package_name}...")
  91. # Get the latest version from PyPI
  92. current_version = importlib.metadata.version(package_name)
  93. url = f"https://pypi.org/pypi/{package_name}/json"
  94. response = net.get(url)
  95. latest_version = response.json()["info"]["version"]
  96. console.debug(f"Latest version of {package_name}: {latest_version}")
  97. if get_or_set_last_reflex_version_check_datetime():
  98. # Versions were already checked and saved in reflex.json, no need to warn again
  99. return
  100. if version.parse(current_version) < version.parse(latest_version):
  101. # Show a warning when the host version is older than PyPI version
  102. console.warn(
  103. f"Your version ({current_version}) of {package_name} is out of date. Upgrade to {latest_version} with 'pip install {package_name} --upgrade'"
  104. )
  105. except Exception:
  106. console.debug(f"Failed to check for the latest version of {package_name}.")
  107. pass
  108. def get_or_set_last_reflex_version_check_datetime():
  109. """Get the last time a check was made for the latest reflex version.
  110. This is typically useful for cases where the host reflex version is
  111. less than that on Pypi.
  112. Returns:
  113. The last version check datetime.
  114. """
  115. reflex_json_file = get_web_dir() / constants.Reflex.JSON
  116. if not reflex_json_file.exists():
  117. return None
  118. # Open and read the file
  119. data = json.loads(reflex_json_file.read_text())
  120. last_version_check_datetime = data.get("last_version_check_datetime")
  121. if not last_version_check_datetime:
  122. data.update({"last_version_check_datetime": str(datetime.now())})
  123. path_ops.update_json_file(reflex_json_file, data)
  124. return last_version_check_datetime
  125. def set_last_reflex_run_time():
  126. """Set the last Reflex run time."""
  127. path_ops.update_json_file(
  128. get_web_dir() / constants.Reflex.JSON,
  129. {"last_reflex_run_datetime": str(datetime.now())},
  130. )
  131. def check_node_version() -> bool:
  132. """Check the version of Node.js.
  133. Returns:
  134. Whether the version of Node.js is valid.
  135. """
  136. current_version = get_node_version()
  137. return current_version is not None and current_version >= version.parse(
  138. constants.Node.MIN_VERSION
  139. )
  140. def get_node_version() -> version.Version | None:
  141. """Get the version of node.
  142. Returns:
  143. The version of node.
  144. """
  145. node_path = path_ops.get_node_path()
  146. if node_path is None:
  147. return None
  148. try:
  149. result = processes.new_process([node_path, "-v"], run=True)
  150. # The output will be in the form "vX.Y.Z", but version.parse() can handle it
  151. return version.parse(result.stdout)
  152. except (FileNotFoundError, TypeError):
  153. return None
  154. def get_bun_version() -> version.Version | None:
  155. """Get the version of bun.
  156. Returns:
  157. The version of bun.
  158. """
  159. bun_path = path_ops.get_bun_path()
  160. if bun_path is None:
  161. return None
  162. try:
  163. # Run the bun -v command and capture the output
  164. result = processes.new_process([str(bun_path), "-v"], run=True)
  165. return version.parse(str(result.stdout))
  166. except FileNotFoundError:
  167. return None
  168. except version.InvalidVersion as e:
  169. console.warn(
  170. f"The detected bun version ({e.args[0]}) is not valid. Defaulting to None."
  171. )
  172. return None
  173. def prefer_npm_over_bun() -> bool:
  174. """Check if npm should be preferred over bun.
  175. Returns:
  176. If npm should be preferred over bun.
  177. """
  178. return npm_escape_hatch() or (
  179. constants.IS_WINDOWS and windows_check_onedrive_in_path()
  180. )
  181. def get_nodejs_compatible_package_managers(
  182. raise_on_none: bool = True,
  183. ) -> Sequence[str]:
  184. """Get the package manager executable for installation. Typically, bun is used for installation.
  185. Args:
  186. raise_on_none: Whether to raise an error if the package manager is not found.
  187. Returns:
  188. The path to the package manager.
  189. Raises:
  190. FileNotFoundError: If the package manager is not found and raise_on_none is True.
  191. """
  192. bun_package_manager = (
  193. str(bun_path) if (bun_path := path_ops.get_bun_path()) else None
  194. )
  195. npm_package_manager = (
  196. str(npm_path) if (npm_path := path_ops.get_npm_path()) else None
  197. )
  198. if prefer_npm_over_bun():
  199. package_managers = [npm_package_manager, bun_package_manager]
  200. else:
  201. package_managers = [bun_package_manager, npm_package_manager]
  202. package_managers = list(filter(None, package_managers))
  203. if not package_managers and raise_on_none:
  204. raise FileNotFoundError(
  205. "Bun or npm not found. You might need to rerun `reflex init` or install either."
  206. )
  207. return package_managers
  208. def is_outdated_nodejs_installed():
  209. """Check if the installed Node.js version is outdated.
  210. Returns:
  211. If the installed Node.js version is outdated.
  212. """
  213. current_version = get_node_version()
  214. if current_version is not None and current_version < version.parse(
  215. constants.Node.MIN_VERSION
  216. ):
  217. console.warn(
  218. f"Your version ({current_version}) of Node.js is out of date. Upgrade to {constants.Node.MIN_VERSION} or higher."
  219. )
  220. return True
  221. return False
  222. def get_js_package_executor(raise_on_none: bool = False) -> Sequence[Sequence[str]]:
  223. """Get the paths to package managers for running commands. Ordered by preference.
  224. This is currently identical to get_install_package_managers, but may change in the future.
  225. Args:
  226. raise_on_none: Whether to raise an error if no package managers is not found.
  227. Returns:
  228. The paths to the package managers as a list of lists, where each list is the command to run and its arguments.
  229. Raises:
  230. FileNotFoundError: If no package managers are found and raise_on_none is True.
  231. """
  232. bun_package_manager = (
  233. [str(bun_path)] + (["--bun"] if is_outdated_nodejs_installed() else [])
  234. if (bun_path := path_ops.get_bun_path())
  235. else None
  236. )
  237. npm_package_manager = (
  238. [str(npm_path)] if (npm_path := path_ops.get_npm_path()) else None
  239. )
  240. if prefer_npm_over_bun():
  241. package_managers = [npm_package_manager, bun_package_manager]
  242. else:
  243. package_managers = [bun_package_manager, npm_package_manager]
  244. package_managers = list(filter(None, package_managers))
  245. if not package_managers and raise_on_none:
  246. raise FileNotFoundError(
  247. "Bun or npm not found. You might need to rerun `reflex init` or install either."
  248. )
  249. return package_managers
  250. def windows_check_onedrive_in_path() -> bool:
  251. """For windows, check if oneDrive is present in the project dir path.
  252. Returns:
  253. If oneDrive is in the path of the project directory.
  254. """
  255. return "onedrive" in str(Path.cwd()).lower()
  256. def npm_escape_hatch() -> bool:
  257. """If the user sets REFLEX_USE_NPM, prefer npm over bun.
  258. Returns:
  259. If the user has set REFLEX_USE_NPM.
  260. """
  261. return environment.REFLEX_USE_NPM.get()
  262. def _check_app_name(config: Config):
  263. """Check if the app name is set in the config.
  264. Args:
  265. config: The config object.
  266. Raises:
  267. RuntimeError: If the app name is not set in the config.
  268. """
  269. if not config.app_name:
  270. raise RuntimeError(
  271. "Cannot get the app module because `app_name` is not set in rxconfig! "
  272. "If this error occurs in a reflex test case, ensure that `get_app` is mocked."
  273. )
  274. def get_app(reload: bool = False) -> ModuleType:
  275. """Get the app module based on the default config.
  276. Args:
  277. reload: Re-import the app module from disk
  278. Returns:
  279. The app based on the default config.
  280. Raises:
  281. Exception: If an error occurs while getting the app module.
  282. """
  283. from reflex.utils import telemetry
  284. try:
  285. environment.RELOAD_CONFIG.set(reload)
  286. config = get_config()
  287. _check_app_name(config)
  288. module = config.module
  289. sys.path.insert(0, str(Path.cwd()))
  290. app = (
  291. __import__(module, fromlist=(constants.CompileVars.APP,))
  292. if not config.app_module
  293. else config.app_module
  294. )
  295. if reload:
  296. from reflex.state import reload_state_module
  297. # Reset rx.State subclasses to avoid conflict when reloading.
  298. reload_state_module(module=module)
  299. # Reload the app module.
  300. importlib.reload(app)
  301. except Exception as ex:
  302. telemetry.send_error(ex, context="frontend")
  303. raise
  304. else:
  305. return app
  306. def get_and_validate_app(reload: bool = False) -> AppInfo:
  307. """Get the app instance based on the default config and validate it.
  308. Args:
  309. reload: Re-import the app module from disk
  310. Returns:
  311. The app instance and the app module.
  312. Raises:
  313. RuntimeError: If the app instance is not an instance of rx.App.
  314. """
  315. from reflex.app import App
  316. app_module = get_app(reload=reload)
  317. app = getattr(app_module, constants.CompileVars.APP)
  318. if not isinstance(app, App):
  319. raise RuntimeError(
  320. "The app instance in the specified app_module_import in rxconfig must be an instance of rx.App."
  321. )
  322. return AppInfo(app=app, module=app_module)
  323. def validate_app(reload: bool = False) -> None:
  324. """Validate the app instance based on the default config.
  325. Args:
  326. reload: Re-import the app module from disk
  327. """
  328. get_and_validate_app(reload=reload)
  329. def get_compiled_app(reload: bool = False, export: bool = False) -> ModuleType:
  330. """Get the app module based on the default config after first compiling it.
  331. Args:
  332. reload: Re-import the app module from disk
  333. export: Compile the app for export
  334. Returns:
  335. The compiled app based on the default config.
  336. """
  337. app, app_module = get_and_validate_app(reload=reload)
  338. # For py3.9 compatibility when redis is used, we MUST add any decorator pages
  339. # before compiling the app in a thread to avoid event loop error (REF-2172).
  340. app._apply_decorated_pages()
  341. app._compile(export=export)
  342. return app_module
  343. def compile_app(reload: bool = False, export: bool = False) -> None:
  344. """Compile the app module based on the default config.
  345. Args:
  346. reload: Re-import the app module from disk
  347. export: Compile the app for export
  348. """
  349. get_compiled_app(reload=reload, export=export)
  350. def _can_colorize() -> bool:
  351. """Check if the output can be colorized.
  352. Copied from _colorize.can_colorize.
  353. https://raw.githubusercontent.com/python/cpython/refs/heads/main/Lib/_colorize.py
  354. Returns:
  355. If the output can be colorized
  356. """
  357. file = sys.stdout
  358. if not sys.flags.ignore_environment:
  359. if os.environ.get("PYTHON_COLORS") == "0":
  360. return False
  361. if os.environ.get("PYTHON_COLORS") == "1":
  362. return True
  363. if os.environ.get("NO_COLOR"):
  364. return False
  365. if os.environ.get("FORCE_COLOR"):
  366. return True
  367. if os.environ.get("TERM") == "dumb":
  368. return False
  369. if not hasattr(file, "fileno"):
  370. return False
  371. if sys.platform == "win32":
  372. try:
  373. import nt
  374. if not nt._supports_virtual_terminal():
  375. return False
  376. except (ImportError, AttributeError):
  377. return False
  378. try:
  379. return os.isatty(file.fileno())
  380. except io.UnsupportedOperation:
  381. return file.isatty()
  382. def compile_or_validate_app(compile: bool = False) -> bool:
  383. """Compile or validate the app module based on the default config.
  384. Args:
  385. compile: Whether to compile the app.
  386. Returns:
  387. If the app is compiled successfully.
  388. """
  389. try:
  390. if compile:
  391. compile_app()
  392. else:
  393. validate_app()
  394. except Exception as e:
  395. if isinstance(e, typer.Exit):
  396. return False
  397. import traceback
  398. sys_exception = sys.exception()
  399. try:
  400. colorize = _can_colorize()
  401. traceback.print_exception(e, colorize=colorize) # pyright: ignore[reportCallIssue]
  402. except Exception:
  403. traceback.print_exception(sys_exception)
  404. return False
  405. return True
  406. def get_redis() -> Redis | None:
  407. """Get the asynchronous redis client.
  408. Returns:
  409. The asynchronous redis client.
  410. """
  411. if (redis_url := parse_redis_url()) is not None:
  412. return Redis.from_url(
  413. redis_url,
  414. retry_on_error=[RedisError],
  415. )
  416. return None
  417. def get_redis_sync() -> RedisSync | None:
  418. """Get the synchronous redis client.
  419. Returns:
  420. The synchronous redis client.
  421. """
  422. if (redis_url := parse_redis_url()) is not None:
  423. return RedisSync.from_url(
  424. redis_url,
  425. retry_on_error=[RedisError],
  426. )
  427. return None
  428. def parse_redis_url() -> str | None:
  429. """Parse the REDIS_URL in config if applicable.
  430. Returns:
  431. If url is non-empty, return the URL as it is.
  432. Raises:
  433. ValueError: If the REDIS_URL is not a supported scheme.
  434. """
  435. config = get_config()
  436. if not config.redis_url:
  437. return None
  438. if not config.redis_url.startswith(("redis://", "rediss://", "unix://")):
  439. raise ValueError(
  440. "REDIS_URL must start with 'redis://', 'rediss://', or 'unix://'."
  441. )
  442. return config.redis_url
  443. async def get_redis_status() -> dict[str, bool | None]:
  444. """Checks the status of the Redis connection.
  445. Attempts to connect to Redis and send a ping command to verify connectivity.
  446. Returns:
  447. The status of the Redis connection.
  448. """
  449. try:
  450. status = True
  451. redis_client = get_redis_sync()
  452. if redis_client is not None:
  453. redis_client.ping()
  454. else:
  455. status = None
  456. except RedisError:
  457. status = False
  458. return {"redis": status}
  459. def validate_app_name(app_name: str | None = None) -> str:
  460. """Validate the app name.
  461. The default app name is the name of the current directory.
  462. Args:
  463. app_name: the name passed by user during reflex init
  464. Returns:
  465. The app name after validation.
  466. Raises:
  467. Exit: if the app directory name is reflex or if the name is not standard for a python package name.
  468. """
  469. app_name = app_name if app_name else Path.cwd().name.replace("-", "_")
  470. # Make sure the app is not named "reflex".
  471. if app_name.lower() == constants.Reflex.MODULE_NAME:
  472. console.error(
  473. f"The app directory cannot be named [bold]{constants.Reflex.MODULE_NAME}[/bold]."
  474. )
  475. raise typer.Exit(1)
  476. # Make sure the app name is standard for a python package name.
  477. if not re.match(r"^[a-zA-Z][a-zA-Z0-9_]*$", app_name):
  478. console.error(
  479. "The app directory name must start with a letter and can contain letters, numbers, and underscores."
  480. )
  481. raise typer.Exit(1)
  482. return app_name
  483. def rename_path_up_tree(full_path: str | Path, old_name: str, new_name: str) -> Path:
  484. """Rename all instances of `old_name` in the path (file and directories) to `new_name`.
  485. The renaming stops when we reach the directory containing `rxconfig.py`.
  486. Args:
  487. full_path: The full path to start renaming from.
  488. old_name: The name to be replaced.
  489. new_name: The replacement name.
  490. Returns:
  491. The updated path after renaming.
  492. """
  493. current_path = Path(full_path)
  494. new_path = None
  495. while True:
  496. directory, base = current_path.parent, current_path.name
  497. # Stop renaming when we reach the root dir (which contains rxconfig.py)
  498. if current_path.is_dir() and (current_path / "rxconfig.py").exists():
  499. new_path = current_path
  500. break
  501. if old_name == base.removesuffix(constants.Ext.PY):
  502. new_base = base.replace(old_name, new_name)
  503. new_path = directory / new_base
  504. current_path.rename(new_path)
  505. console.debug(f"Renamed {current_path} -> {new_path}")
  506. current_path = new_path
  507. else:
  508. new_path = current_path
  509. # Move up the directory tree
  510. current_path = directory
  511. return new_path
  512. def rename_app(new_app_name: str, loglevel: constants.LogLevel):
  513. """Rename the app directory.
  514. Args:
  515. new_app_name: The new name for the app.
  516. loglevel: The log level to use.
  517. Raises:
  518. Exit: If the command is not ran in the root dir or the app module cannot be imported.
  519. """
  520. # Set the log level.
  521. console.set_log_level(loglevel)
  522. if not constants.Config.FILE.exists():
  523. console.error(
  524. "No rxconfig.py found. Make sure you are in the root directory of your app."
  525. )
  526. raise typer.Exit(1)
  527. sys.path.insert(0, str(Path.cwd()))
  528. config = get_config()
  529. module_path = importlib.util.find_spec(config.module)
  530. if module_path is None:
  531. console.error(f"Could not find module {config.module}.")
  532. raise typer.Exit(1)
  533. if not module_path.origin:
  534. console.error(f"Could not find origin for module {config.module}.")
  535. raise typer.Exit(1)
  536. console.info(f"Renaming app directory to {new_app_name}.")
  537. process_directory(
  538. Path.cwd(),
  539. config.app_name,
  540. new_app_name,
  541. exclude_dirs=[constants.Dirs.WEB, constants.Dirs.APP_ASSETS],
  542. )
  543. rename_path_up_tree(Path(module_path.origin), config.app_name, new_app_name)
  544. console.success(f"App directory renamed to [bold]{new_app_name}[/bold].")
  545. def rename_imports_and_app_name(file_path: str | Path, old_name: str, new_name: str):
  546. """Rename imports the file using string replacement as well as app_name in rxconfig.py.
  547. Args:
  548. file_path: The file to process.
  549. old_name: The old name to replace.
  550. new_name: The new name to use.
  551. """
  552. file_path = Path(file_path)
  553. content = file_path.read_text()
  554. # Replace `from old_name.` or `from old_name` with `from new_name`
  555. content = re.sub(
  556. rf"\bfrom {re.escape(old_name)}(\b|\.|\s)",
  557. lambda match: f"from {new_name}{match.group(1)}",
  558. content,
  559. )
  560. # Replace `import old_name` with `import new_name`
  561. content = re.sub(
  562. rf"\bimport {re.escape(old_name)}\b",
  563. f"import {new_name}",
  564. content,
  565. )
  566. # Replace `app_name="old_name"` in rx.Config
  567. content = re.sub(
  568. rf'\bapp_name\s*=\s*["\']{re.escape(old_name)}["\']',
  569. f'app_name="{new_name}"',
  570. content,
  571. )
  572. # Replace positional argument `"old_name"` in rx.Config
  573. content = re.sub(
  574. rf'\brx\.Config\(\s*["\']{re.escape(old_name)}["\']',
  575. f'rx.Config("{new_name}"',
  576. content,
  577. )
  578. file_path.write_text(content)
  579. def process_directory(
  580. directory: str | Path,
  581. old_name: str,
  582. new_name: str,
  583. exclude_dirs: list | None = None,
  584. extensions: list | None = None,
  585. ):
  586. """Process files with specified extensions in a directory, excluding specified directories.
  587. Args:
  588. directory: The root directory to process.
  589. old_name: The old name to replace.
  590. new_name: The new name to use.
  591. exclude_dirs: List of directory names to exclude. Defaults to None.
  592. extensions: List of file extensions to process.
  593. """
  594. exclude_dirs = exclude_dirs or []
  595. extensions = extensions or [
  596. constants.Ext.PY,
  597. constants.Ext.MD,
  598. ] # include .md files, typically used in reflex-web.
  599. extensions_set = {ext.lstrip(".") for ext in extensions}
  600. directory = Path(directory)
  601. root_exclude_dirs = {directory / exclude_dir for exclude_dir in exclude_dirs}
  602. files = (
  603. p.resolve()
  604. for p in directory.glob("**/*")
  605. if p.is_file() and p.suffix.lstrip(".") in extensions_set
  606. )
  607. for file_path in files:
  608. if not any(
  609. file_path.is_relative_to(exclude_dir) for exclude_dir in root_exclude_dirs
  610. ):
  611. rename_imports_and_app_name(file_path, old_name, new_name)
  612. def create_config(app_name: str):
  613. """Create a new rxconfig file.
  614. Args:
  615. app_name: The name of the app.
  616. """
  617. # Import here to avoid circular imports.
  618. from reflex.compiler import templates
  619. config_name = f"{re.sub(r'[^a-zA-Z]', '', app_name).capitalize()}Config"
  620. console.debug(f"Creating {constants.Config.FILE}")
  621. constants.Config.FILE.write_text(
  622. templates.RXCONFIG.render(app_name=app_name, config_name=config_name)
  623. )
  624. def initialize_gitignore(
  625. gitignore_file: Path = constants.GitIgnore.FILE,
  626. files_to_ignore: set[str] | list[str] = constants.GitIgnore.DEFAULTS,
  627. ):
  628. """Initialize the template .gitignore file.
  629. Args:
  630. gitignore_file: The .gitignore file to create.
  631. files_to_ignore: The files to add to the .gitignore file.
  632. """
  633. # Combine with the current ignored files.
  634. current_ignore: list[str] = []
  635. if gitignore_file.exists():
  636. current_ignore = [ln.strip() for ln in gitignore_file.read_text().splitlines()]
  637. if files_to_ignore == current_ignore:
  638. console.debug(f"{gitignore_file} already up to date.")
  639. return
  640. files_to_ignore = [ln for ln in files_to_ignore if ln not in current_ignore]
  641. files_to_ignore += current_ignore
  642. # Write files to the .gitignore file.
  643. gitignore_file.touch(exist_ok=True)
  644. console.debug(f"Creating {gitignore_file}")
  645. gitignore_file.write_text("\n".join(files_to_ignore) + "\n")
  646. def initialize_requirements_txt() -> bool:
  647. """Initialize the requirements.txt file.
  648. If absent, generate one for the user.
  649. If the requirements.txt does not have reflex as dependency,
  650. generate a requirement pinning current version and append to
  651. the requirements.txt file.
  652. Returns:
  653. True if the requirements.txt file was created or updated, False otherwise.
  654. Raises:
  655. Exit: If the requirements.txt file cannot be read or written to.
  656. """
  657. requirements_file_path = Path(constants.RequirementsTxt.FILE)
  658. requirements_file_path.touch(exist_ok=True)
  659. for encoding in [None, "utf-8"]:
  660. try:
  661. content = requirements_file_path.read_text(encoding)
  662. break
  663. except UnicodeDecodeError:
  664. continue
  665. except Exception as e:
  666. console.error(f"Failed to read {requirements_file_path}.")
  667. raise typer.Exit(1) from e
  668. else:
  669. return False
  670. for line in content.splitlines():
  671. if re.match(r"^reflex[^a-zA-Z0-9]", line):
  672. console.debug(f"{requirements_file_path} already has reflex as dependency.")
  673. return True
  674. console.debug(
  675. f"Appending {constants.RequirementsTxt.DEFAULTS_STUB} to {requirements_file_path}"
  676. )
  677. with requirements_file_path.open("a", encoding=encoding) as f:
  678. f.write(
  679. "\n" + constants.RequirementsTxt.DEFAULTS_STUB + constants.Reflex.VERSION
  680. )
  681. return True
  682. def initialize_app_directory(
  683. app_name: str,
  684. template_name: str = constants.Templates.DEFAULT,
  685. template_code_dir_name: str | None = None,
  686. template_dir: Path | None = None,
  687. ):
  688. """Initialize the app directory on reflex init.
  689. Args:
  690. app_name: The name of the app.
  691. template_name: The name of the template to use.
  692. template_code_dir_name: The name of the code directory in the template.
  693. template_dir: The directory of the template source files.
  694. Raises:
  695. Exit: If template_name, template_code_dir_name, template_dir combination is not supported.
  696. """
  697. console.log("Initializing the app directory.")
  698. # By default, use the blank template from local assets.
  699. if template_name == constants.Templates.DEFAULT:
  700. if template_code_dir_name is not None or template_dir is not None:
  701. console.error(
  702. f"Only {template_name=} should be provided, got {template_code_dir_name=}, {template_dir=}."
  703. )
  704. raise typer.Exit(1)
  705. template_code_dir_name = constants.Templates.Dirs.CODE
  706. template_dir = Path(constants.Templates.Dirs.BASE, "apps", template_name)
  707. else:
  708. if template_code_dir_name is None or template_dir is None:
  709. console.error(
  710. f"For `{template_name}` template, `template_code_dir_name` and `template_dir` should both be provided."
  711. )
  712. raise typer.Exit(1)
  713. console.debug(f"Using {template_name=} {template_dir=} {template_code_dir_name=}.")
  714. # Remove __pycache__ dirs in template directory and current directory.
  715. for pycache_dir in [
  716. *template_dir.glob("**/__pycache__"),
  717. *Path.cwd().glob("**/__pycache__"),
  718. ]:
  719. shutil.rmtree(pycache_dir, ignore_errors=True)
  720. for file in template_dir.iterdir():
  721. # Copy the file to current directory but keep the name the same.
  722. path_ops.cp(str(file), file.name)
  723. # Rename the template app to the app name.
  724. path_ops.mv(template_code_dir_name, app_name)
  725. path_ops.mv(
  726. Path(app_name) / (template_name + constants.Ext.PY),
  727. Path(app_name) / (app_name + constants.Ext.PY),
  728. )
  729. # Fix up the imports.
  730. path_ops.find_replace(
  731. app_name,
  732. f"from {template_name}",
  733. f"from {app_name}",
  734. )
  735. def get_project_hash(raise_on_fail: bool = False) -> int | None:
  736. """Get the project hash from the reflex.json file if the file exists.
  737. Args:
  738. raise_on_fail: Whether to raise an error if the file does not exist.
  739. Returns:
  740. project_hash: The app hash.
  741. """
  742. json_file = get_web_dir() / constants.Reflex.JSON
  743. if not json_file.exists() and not raise_on_fail:
  744. return None
  745. data = json.loads(json_file.read_text())
  746. return data.get("project_hash")
  747. def initialize_web_directory():
  748. """Initialize the web directory on reflex init."""
  749. console.log("Initializing the web directory.")
  750. # Reuse the hash if one is already created, so we don't over-write it when running reflex init
  751. project_hash = get_project_hash()
  752. console.debug(f"Copying {constants.Templates.Dirs.WEB_TEMPLATE} to {get_web_dir()}")
  753. path_ops.cp(constants.Templates.Dirs.WEB_TEMPLATE, str(get_web_dir()))
  754. console.debug("Initializing the web directory.")
  755. initialize_package_json()
  756. console.debug("Initializing the bun config file.")
  757. initialize_bun_config()
  758. console.debug("Initializing the .npmrc file.")
  759. initialize_npmrc()
  760. console.debug("Initializing the public directory.")
  761. path_ops.mkdir(get_web_dir() / constants.Dirs.PUBLIC)
  762. console.debug("Initializing the next.config.js file.")
  763. update_next_config()
  764. console.debug("Initializing the reflex.json file.")
  765. # Initialize the reflex json file.
  766. init_reflex_json(project_hash=project_hash)
  767. def _turbopack_flag() -> str:
  768. return " --turbopack" if environment.REFLEX_USE_TURBOPACK.get() else ""
  769. def _compile_package_json():
  770. return templates.PACKAGE_JSON.render(
  771. scripts={
  772. "dev": constants.PackageJson.Commands.DEV + _turbopack_flag(),
  773. "export": constants.PackageJson.Commands.EXPORT,
  774. "export_sitemap": constants.PackageJson.Commands.EXPORT_SITEMAP,
  775. "prod": constants.PackageJson.Commands.PROD,
  776. },
  777. dependencies=constants.PackageJson.DEPENDENCIES,
  778. dev_dependencies=constants.PackageJson.DEV_DEPENDENCIES,
  779. overrides=constants.PackageJson.OVERRIDES,
  780. )
  781. def initialize_package_json():
  782. """Render and write in .web the package.json file."""
  783. output_path = get_web_dir() / constants.PackageJson.PATH
  784. output_path.write_text(_compile_package_json())
  785. def initialize_bun_config():
  786. """Initialize the bun config file."""
  787. bun_config_path = get_web_dir() / constants.Bun.CONFIG_PATH
  788. if (custom_bunfig := Path(constants.Bun.CONFIG_PATH)).exists():
  789. bunfig_content = custom_bunfig.read_text()
  790. console.info(f"Copying custom bunfig.toml inside {get_web_dir()} folder")
  791. else:
  792. best_registry = get_npm_registry()
  793. bunfig_content = constants.Bun.DEFAULT_CONFIG.format(registry=best_registry)
  794. bun_config_path.write_text(bunfig_content)
  795. def initialize_npmrc():
  796. """Initialize the .npmrc file."""
  797. npmrc_path = get_web_dir() / constants.Node.CONFIG_PATH
  798. if (custom_npmrc := Path(constants.Node.CONFIG_PATH)).exists():
  799. npmrc_content = custom_npmrc.read_text()
  800. console.info(f"Copying custom .npmrc inside {get_web_dir()} folder")
  801. else:
  802. best_registry = get_npm_registry()
  803. npmrc_content = constants.Node.DEFAULT_CONFIG.format(registry=best_registry)
  804. npmrc_path.write_text(npmrc_content)
  805. def init_reflex_json(project_hash: int | None):
  806. """Write the hash of the Reflex project to a REFLEX_JSON.
  807. Reuse the hash if one is already created, therefore do not
  808. overwrite it every time we run the reflex init command
  809. .
  810. Args:
  811. project_hash: The app hash.
  812. """
  813. if project_hash is not None:
  814. console.debug(f"Project hash is already set to {project_hash}.")
  815. else:
  816. # Get a random project hash.
  817. project_hash = random.getrandbits(128)
  818. console.debug(f"Setting project hash to {project_hash}.")
  819. # Write the hash and version to the reflex json file.
  820. reflex_json = {
  821. "version": constants.Reflex.VERSION,
  822. "project_hash": project_hash,
  823. }
  824. path_ops.update_json_file(get_web_dir() / constants.Reflex.JSON, reflex_json)
  825. def update_next_config(
  826. export: bool = False, transpile_packages: list[str] | None = None
  827. ):
  828. """Update Next.js config from Reflex config.
  829. Args:
  830. export: if the method run during reflex export.
  831. transpile_packages: list of packages to transpile via next.config.js.
  832. """
  833. next_config_file = get_web_dir() / constants.Next.CONFIG_FILE
  834. next_config = _update_next_config(
  835. get_config(), export=export, transpile_packages=transpile_packages
  836. )
  837. # Overwriting the next.config.js triggers a full server reload, so make sure
  838. # there is actually a diff.
  839. orig_next_config = next_config_file.read_text() if next_config_file.exists() else ""
  840. if orig_next_config != next_config:
  841. next_config_file.write_text(next_config)
  842. def _update_next_config(
  843. config: Config, export: bool = False, transpile_packages: list[str] | None = None
  844. ):
  845. next_config = {
  846. "basePath": config.frontend_path or "",
  847. "compress": config.next_compression,
  848. "trailingSlash": True,
  849. "staticPageGenerationTimeout": config.static_page_generation_timeout,
  850. "devIndicators": config.next_dev_indicators,
  851. }
  852. if transpile_packages:
  853. next_config["transpilePackages"] = list(
  854. {format_library_name(p) for p in transpile_packages}
  855. )
  856. if export:
  857. next_config["output"] = "export"
  858. next_config["distDir"] = constants.Dirs.STATIC
  859. next_config_json = re.sub(r'"([^"]+)"(?=:)', r"\1", json.dumps(next_config))
  860. return f"module.exports = {next_config_json};"
  861. def remove_existing_bun_installation():
  862. """Remove existing bun installation."""
  863. console.debug("Removing existing bun installation.")
  864. if Path(get_config().bun_path).exists():
  865. path_ops.rm(constants.Bun.ROOT_PATH)
  866. def download_and_run(url: str, *args, show_status: bool = False, **env):
  867. """Download and run a script.
  868. Args:
  869. url: The url of the script.
  870. args: The arguments to pass to the script.
  871. show_status: Whether to show the status of the script.
  872. env: The environment variables to use.
  873. """
  874. # Download the script
  875. console.debug(f"Downloading {url}")
  876. response = net.get(url)
  877. if response.status_code != httpx.codes.OK:
  878. response.raise_for_status()
  879. # Save the script to a temporary file.
  880. script = Path(tempfile.NamedTemporaryFile().name)
  881. script.write_text(response.text)
  882. # Run the script.
  883. env = {**os.environ, **env}
  884. process = processes.new_process(["bash", str(script), *args], env=env)
  885. show = processes.show_status if show_status else processes.show_logs
  886. show(f"Installing {url}", process)
  887. def install_bun():
  888. """Install bun onto the user's system.
  889. Raises:
  890. SystemPackageMissingError: If "unzip" is missing.
  891. """
  892. one_drive_in_path = windows_check_onedrive_in_path()
  893. if constants.IS_WINDOWS and one_drive_in_path:
  894. console.warn(
  895. "Creating project directories in OneDrive is not recommended for bun usage on windows. This will fallback to npm."
  896. )
  897. # Skip if bun is already installed.
  898. if (current_version := get_bun_version()) and current_version >= version.parse(
  899. constants.Bun.MIN_VERSION
  900. ):
  901. console.debug("Skipping bun installation as it is already installed.")
  902. return
  903. # if unzip is installed
  904. if constants.IS_WINDOWS:
  905. processes.new_process(
  906. [
  907. "powershell",
  908. "-c",
  909. f"irm {constants.Bun.WINDOWS_INSTALL_URL}|iex",
  910. ],
  911. env={
  912. "BUN_INSTALL": str(constants.Bun.ROOT_PATH),
  913. "BUN_VERSION": constants.Bun.VERSION,
  914. },
  915. shell=True,
  916. run=True,
  917. show_logs=console.is_debug(),
  918. )
  919. else:
  920. if path_ops.which("unzip") is None:
  921. raise SystemPackageMissingError("unzip")
  922. # Run the bun install script.
  923. download_and_run(
  924. constants.Bun.INSTALL_URL,
  925. f"bun-v{constants.Bun.VERSION}",
  926. BUN_INSTALL=str(constants.Bun.ROOT_PATH),
  927. BUN_VERSION=str(constants.Bun.VERSION),
  928. )
  929. def _write_cached_procedure_file(payload: str, cache_file: str | Path):
  930. cache_file = Path(cache_file)
  931. cache_file.write_text(payload)
  932. def _read_cached_procedure_file(cache_file: str | Path) -> str | None:
  933. cache_file = Path(cache_file)
  934. if cache_file.exists():
  935. return cache_file.read_text()
  936. return None
  937. def _clear_cached_procedure_file(cache_file: str | Path):
  938. cache_file = Path(cache_file)
  939. if cache_file.exists():
  940. cache_file.unlink()
  941. def cached_procedure(
  942. cache_file: str | None,
  943. payload_fn: Callable[..., str],
  944. cache_file_fn: Callable[[], str] | None = None,
  945. ):
  946. """Decorator to cache the runs of a procedure on disk. Procedures should not have
  947. a return value.
  948. Args:
  949. cache_file: The file to store the cache payload in.
  950. payload_fn: Function that computes cache payload from function args.
  951. cache_file_fn: Function that computes the cache file name at runtime.
  952. Returns:
  953. The decorated function.
  954. Raises:
  955. ValueError: If both cache_file and cache_file_fn are provided.
  956. """
  957. if cache_file and cache_file_fn is not None:
  958. raise ValueError("cache_file and cache_file_fn cannot both be provided.")
  959. def _inner_decorator(func: Callable):
  960. def _inner(*args, **kwargs):
  961. _cache_file = cache_file_fn() if cache_file_fn is not None else cache_file
  962. if not _cache_file:
  963. raise ValueError("Unknown cache file, cannot cache result.")
  964. payload = _read_cached_procedure_file(_cache_file)
  965. new_payload = payload_fn(*args, **kwargs)
  966. if payload != new_payload:
  967. _clear_cached_procedure_file(_cache_file)
  968. func(*args, **kwargs)
  969. _write_cached_procedure_file(new_payload, _cache_file)
  970. return _inner
  971. return _inner_decorator
  972. @cached_procedure(
  973. cache_file_fn=lambda: str(
  974. get_web_dir() / "reflex.install_frontend_packages.cached"
  975. ),
  976. payload_fn=lambda p, c: f"{sorted(p)!r},{c.json()}",
  977. cache_file=None,
  978. )
  979. def install_frontend_packages(packages: set[str], config: Config):
  980. """Installs the base and custom frontend packages.
  981. Args:
  982. packages: A list of package names to be installed.
  983. config: The config object.
  984. Example:
  985. >>> install_frontend_packages(["react", "react-dom"], get_config())
  986. """
  987. install_package_managers = get_nodejs_compatible_package_managers(
  988. raise_on_none=True
  989. )
  990. env = (
  991. {
  992. "NODE_TLS_REJECT_UNAUTHORIZED": "0",
  993. }
  994. if environment.SSL_NO_VERIFY.get()
  995. else {}
  996. )
  997. primary_package_manager = install_package_managers[0]
  998. fallbacks = install_package_managers[1:]
  999. processes.run_process_with_fallbacks(
  1000. [primary_package_manager, "install", "--legacy-peer-deps"],
  1001. fallbacks=fallbacks,
  1002. analytics_enabled=True,
  1003. show_status_message="Installing base frontend packages",
  1004. cwd=get_web_dir(),
  1005. shell=constants.IS_WINDOWS,
  1006. env=env,
  1007. )
  1008. if config.tailwind is not None:
  1009. processes.run_process_with_fallbacks(
  1010. [
  1011. primary_package_manager,
  1012. "add",
  1013. "--legacy-peer-deps",
  1014. "-d",
  1015. constants.Tailwind.VERSION,
  1016. *((config.tailwind or {}).get("plugins", [])),
  1017. ],
  1018. fallbacks=fallbacks,
  1019. analytics_enabled=True,
  1020. show_status_message="Installing tailwind",
  1021. cwd=get_web_dir(),
  1022. shell=constants.IS_WINDOWS,
  1023. env=env,
  1024. )
  1025. # Install custom packages defined in frontend_packages
  1026. if len(packages) > 0:
  1027. processes.run_process_with_fallbacks(
  1028. [primary_package_manager, "add", "--legacy-peer-deps", *packages],
  1029. fallbacks=fallbacks,
  1030. analytics_enabled=True,
  1031. show_status_message="Installing frontend packages from config and components",
  1032. cwd=get_web_dir(),
  1033. shell=constants.IS_WINDOWS,
  1034. env=env,
  1035. )
  1036. def check_running_mode(frontend: bool, backend: bool) -> tuple[bool, bool]:
  1037. """Check if the app is running in frontend or backend mode.
  1038. Args:
  1039. frontend: Whether to run the frontend of the app.
  1040. backend: Whether to run the backend of the app.
  1041. Returns:
  1042. The running modes.
  1043. """
  1044. if not frontend and not backend:
  1045. return True, True
  1046. return frontend, backend
  1047. def needs_reinit(frontend: bool = True) -> bool:
  1048. """Check if an app needs to be reinitialized.
  1049. Args:
  1050. frontend: Whether to check if the frontend is initialized.
  1051. Returns:
  1052. Whether the app needs to be reinitialized.
  1053. Raises:
  1054. Exit: If the app is not initialized.
  1055. """
  1056. if not constants.Config.FILE.exists():
  1057. console.error(
  1058. f"[cyan]{constants.Config.FILE}[/cyan] not found. Move to the root folder of your project, or run [bold]{constants.Reflex.MODULE_NAME} init[/bold] to start a new project."
  1059. )
  1060. raise typer.Exit(1)
  1061. # Don't need to reinit if not running in frontend mode.
  1062. if not frontend:
  1063. return False
  1064. # Make sure the .reflex directory exists.
  1065. if not environment.REFLEX_DIR.get().exists():
  1066. return True
  1067. # Make sure the .web directory exists in frontend mode.
  1068. if not get_web_dir().exists():
  1069. return True
  1070. # If the template is out of date, then we need to re-init
  1071. if not is_latest_template():
  1072. return True
  1073. if constants.IS_WINDOWS:
  1074. console.warn(
  1075. """Windows Subsystem for Linux (WSL) is recommended for improving initial install times."""
  1076. )
  1077. if windows_check_onedrive_in_path():
  1078. console.warn(
  1079. "Creating project directories in OneDrive may lead to performance issues. For optimal performance, It is recommended to avoid using OneDrive for your reflex app."
  1080. )
  1081. # No need to reinitialize if the app is already initialized.
  1082. return False
  1083. def is_latest_template() -> bool:
  1084. """Whether the app is using the latest template.
  1085. Returns:
  1086. Whether the app is using the latest template.
  1087. """
  1088. json_file = get_web_dir() / constants.Reflex.JSON
  1089. if not json_file.exists():
  1090. return False
  1091. app_version = json.loads(json_file.read_text()).get("version")
  1092. return app_version == constants.Reflex.VERSION
  1093. def validate_bun():
  1094. """Validate bun if a custom bun path is specified to ensure the bun version meets requirements.
  1095. Raises:
  1096. Exit: If custom specified bun does not exist or does not meet requirements.
  1097. """
  1098. bun_path = path_ops.get_bun_path()
  1099. if bun_path is None:
  1100. return
  1101. if not path_ops.samefile(bun_path, constants.Bun.DEFAULT_PATH):
  1102. console.info(f"Using custom Bun path: {bun_path}")
  1103. bun_version = get_bun_version()
  1104. if bun_version is None:
  1105. console.error(
  1106. "Failed to obtain bun version. Make sure the specified bun path in your config is correct."
  1107. )
  1108. raise typer.Exit(1)
  1109. elif bun_version < version.parse(constants.Bun.MIN_VERSION):
  1110. console.error(
  1111. f"Reflex requires bun version {constants.Bun.MIN_VERSION} or higher to run, but the detected version is "
  1112. f"{bun_version}. If you have specified a custom bun path in your config, make sure to provide one "
  1113. f"that satisfies the minimum version requirement."
  1114. )
  1115. raise typer.Exit(1)
  1116. def validate_frontend_dependencies(init: bool = True):
  1117. """Validate frontend dependencies to ensure they meet requirements.
  1118. Args:
  1119. init: whether running `reflex init`
  1120. Raises:
  1121. Exit: If the package manager is invalid.
  1122. """
  1123. if not init:
  1124. try:
  1125. get_js_package_executor(raise_on_none=True)
  1126. except FileNotFoundError as e:
  1127. raise typer.Exit(1) from e
  1128. if prefer_npm_over_bun():
  1129. if not check_node_version():
  1130. node_version = get_node_version()
  1131. console.error(
  1132. f"Reflex requires node version {constants.Node.MIN_VERSION} or higher to run, but the detected version is {node_version}",
  1133. )
  1134. raise typer.Exit(1)
  1135. else:
  1136. validate_bun()
  1137. def ensure_reflex_installation_id() -> int | None:
  1138. """Ensures that a reflex distinct id has been generated and stored in the reflex directory.
  1139. Returns:
  1140. Distinct id.
  1141. """
  1142. try:
  1143. console.debug("Ensuring reflex installation id.")
  1144. initialize_reflex_user_directory()
  1145. installation_id_file = environment.REFLEX_DIR.get() / "installation_id"
  1146. installation_id = None
  1147. if installation_id_file.exists():
  1148. with contextlib.suppress(Exception):
  1149. installation_id = int(installation_id_file.read_text())
  1150. # If anything goes wrong at all... just regenerate.
  1151. # Like what? Examples:
  1152. # - file not exists
  1153. # - file not readable
  1154. # - content not parseable as an int
  1155. if installation_id is None:
  1156. installation_id = random.getrandbits(128)
  1157. installation_id_file.write_text(str(installation_id))
  1158. except Exception as e:
  1159. console.debug(f"Failed to ensure reflex installation id: {e}")
  1160. return None
  1161. else:
  1162. # If we get here, installation_id is definitely set
  1163. return installation_id
  1164. def initialize_reflex_user_directory():
  1165. """Initialize the reflex user directory."""
  1166. console.debug(f"Creating {environment.REFLEX_DIR.get()}")
  1167. # Create the reflex directory.
  1168. path_ops.mkdir(environment.REFLEX_DIR.get())
  1169. def initialize_frontend_dependencies():
  1170. """Initialize all the frontend dependencies."""
  1171. # validate dependencies before install
  1172. console.debug("Validating frontend dependencies.")
  1173. validate_frontend_dependencies()
  1174. # Install the frontend dependencies.
  1175. console.debug("Installing or validating bun.")
  1176. install_bun()
  1177. # Set up the web directory.
  1178. initialize_web_directory()
  1179. def check_db_used() -> bool:
  1180. """Check if the database is used.
  1181. Returns:
  1182. True if the database is used.
  1183. """
  1184. return bool(get_config().db_url)
  1185. def check_redis_used() -> bool:
  1186. """Check if Redis is used.
  1187. Returns:
  1188. True if Redis is used.
  1189. """
  1190. return bool(get_config().redis_url)
  1191. def check_db_initialized() -> bool:
  1192. """Check if the database migrations are initialized.
  1193. Returns:
  1194. True if alembic is initialized (or if database is not used).
  1195. """
  1196. if (
  1197. get_config().db_url is not None
  1198. and not environment.ALEMBIC_CONFIG.get().exists()
  1199. ):
  1200. console.error(
  1201. "Database is not initialized. Run [bold]reflex db init[/bold] first."
  1202. )
  1203. return False
  1204. return True
  1205. def check_schema_up_to_date():
  1206. """Check if the sqlmodel metadata matches the current database schema."""
  1207. if get_config().db_url is None or not environment.ALEMBIC_CONFIG.get().exists():
  1208. return
  1209. with model.Model.get_db_engine().connect() as connection:
  1210. try:
  1211. if model.Model.alembic_autogenerate(
  1212. connection=connection,
  1213. write_migration_scripts=False,
  1214. ):
  1215. console.error(
  1216. "Detected database schema changes. Run [bold]reflex db makemigrations[/bold] "
  1217. "to generate migration scripts.",
  1218. )
  1219. except CommandError as command_error:
  1220. if "Target database is not up to date." in str(command_error):
  1221. console.error(
  1222. f"{command_error} Run [bold]reflex db migrate[/bold] to update database."
  1223. )
  1224. def prompt_for_template_options(templates: list[Template]) -> str:
  1225. """Prompt the user to specify a template.
  1226. Args:
  1227. templates: The templates to choose from.
  1228. Returns:
  1229. The template name the user selects.
  1230. Raises:
  1231. Exit: If the user does not select a template.
  1232. """
  1233. # Show the user the URLs of each template to preview.
  1234. console.print("\nGet started with a template:")
  1235. def format_demo_url_str(url: str | None) -> str:
  1236. return f" ({url})" if url else ""
  1237. # Prompt the user to select a template.
  1238. id_to_name = {
  1239. str(
  1240. idx
  1241. ): f"{template.name.replace('_', ' ').replace('-', ' ')}{format_demo_url_str(template.demo_url)} - {template.description}"
  1242. for idx, template in enumerate(templates)
  1243. }
  1244. for id in range(len(id_to_name)):
  1245. console.print(f"({id}) {id_to_name[str(id)]}")
  1246. template = console.ask(
  1247. "Which template would you like to use?",
  1248. choices=[str(i) for i in range(len(id_to_name))],
  1249. show_choices=False,
  1250. default="0",
  1251. )
  1252. if not template:
  1253. console.error("No template selected.")
  1254. raise typer.Exit(1)
  1255. try:
  1256. template_index = int(template)
  1257. except ValueError:
  1258. console.error("Invalid template selected.")
  1259. raise typer.Exit(1) from None
  1260. if template_index < 0 or template_index >= len(templates):
  1261. console.error("Invalid template selected.")
  1262. raise typer.Exit(1)
  1263. # Return the template.
  1264. return templates[template_index].name
  1265. def fetch_app_templates(version: str) -> dict[str, Template]:
  1266. """Fetch a dict of templates from the templates repo using github API.
  1267. Args:
  1268. version: The version of the templates to fetch.
  1269. Returns:
  1270. The dict of templates.
  1271. """
  1272. def get_release_by_tag(tag: str) -> dict | None:
  1273. response = net.get(constants.Reflex.RELEASES_URL)
  1274. response.raise_for_status()
  1275. releases = response.json()
  1276. for release in releases:
  1277. if release["tag_name"] == f"v{tag}":
  1278. return release
  1279. return None
  1280. release = get_release_by_tag(version)
  1281. if release is None:
  1282. console.warn(f"No templates known for version {version}")
  1283. return {}
  1284. assets = release.get("assets", [])
  1285. asset = next((a for a in assets if a["name"] == "templates.json"), None)
  1286. if asset is None:
  1287. console.warn(f"Templates metadata not found for version {version}")
  1288. return {}
  1289. else:
  1290. templates_url = asset["browser_download_url"]
  1291. templates_data = net.get(templates_url, follow_redirects=True).json()["templates"]
  1292. for template in templates_data:
  1293. if template["name"] == "blank":
  1294. template["code_url"] = ""
  1295. continue
  1296. template["code_url"] = next(
  1297. (
  1298. a["browser_download_url"]
  1299. for a in assets
  1300. if a["name"] == f"{template['name']}.zip"
  1301. ),
  1302. None,
  1303. )
  1304. filtered_templates = {}
  1305. for tp in templates_data:
  1306. if tp["hidden"] or tp["code_url"] is None:
  1307. continue
  1308. known_fields = {f.name for f in dataclasses.fields(Template)}
  1309. filtered_templates[tp["name"]] = Template(
  1310. **{k: v for k, v in tp.items() if k in known_fields}
  1311. )
  1312. return filtered_templates
  1313. def create_config_init_app_from_remote_template(app_name: str, template_url: str):
  1314. """Create new rxconfig and initialize app using a remote template.
  1315. Args:
  1316. app_name: The name of the app.
  1317. template_url: The path to the template source code as a zip file.
  1318. Raises:
  1319. Exit: If any download, file operations fail or unexpected zip file format.
  1320. """
  1321. # Create a temp directory for the zip download.
  1322. try:
  1323. temp_dir = tempfile.mkdtemp()
  1324. except OSError as ose:
  1325. console.error(f"Failed to create temp directory for download: {ose}")
  1326. raise typer.Exit(1) from ose
  1327. # Use httpx GET with redirects to download the zip file.
  1328. zip_file_path: Path = Path(temp_dir) / "template.zip"
  1329. try:
  1330. # Note: following redirects can be risky. We only allow this for reflex built templates at the moment.
  1331. response = net.get(template_url, follow_redirects=True)
  1332. console.debug(f"Server responded download request: {response}")
  1333. response.raise_for_status()
  1334. except httpx.HTTPError as he:
  1335. console.error(f"Failed to download the template: {he}")
  1336. raise typer.Exit(1) from he
  1337. try:
  1338. zip_file_path.write_bytes(response.content)
  1339. console.debug(f"Downloaded the zip to {zip_file_path}")
  1340. except OSError as ose:
  1341. console.error(f"Unable to write the downloaded zip to disk {ose}")
  1342. raise typer.Exit(1) from ose
  1343. # Create a temp directory for the zip extraction.
  1344. try:
  1345. unzip_dir = Path(tempfile.mkdtemp())
  1346. except OSError as ose:
  1347. console.error(f"Failed to create temp directory for extracting zip: {ose}")
  1348. raise typer.Exit(1) from ose
  1349. try:
  1350. zipfile.ZipFile(zip_file_path).extractall(path=unzip_dir)
  1351. # The zip file downloaded from github looks like:
  1352. # repo-name-branch/**/*, so we need to remove the top level directory.
  1353. except Exception as uze:
  1354. console.error(f"Failed to unzip the template: {uze}")
  1355. raise typer.Exit(1) from uze
  1356. if len(subdirs := list(unzip_dir.iterdir())) != 1:
  1357. console.error(f"Expected one directory in the zip, found {subdirs}")
  1358. raise typer.Exit(1)
  1359. template_dir = unzip_dir / subdirs[0]
  1360. console.debug(f"Template folder is located at {template_dir}")
  1361. # Move the rxconfig file here first.
  1362. path_ops.mv(str(template_dir / constants.Config.FILE), constants.Config.FILE)
  1363. new_config = get_config(reload=True)
  1364. # Get the template app's name from rxconfig in case it is different than
  1365. # the source code repo name on github.
  1366. template_name = new_config.app_name
  1367. create_config(app_name)
  1368. initialize_app_directory(
  1369. app_name,
  1370. template_name=template_name,
  1371. template_code_dir_name=template_name,
  1372. template_dir=template_dir,
  1373. )
  1374. req_file = Path("requirements.txt")
  1375. if req_file.exists() and len(req_file.read_text().splitlines()) > 1:
  1376. console.info(
  1377. "Run `pip install -r requirements.txt` to install the required python packages for this template."
  1378. )
  1379. # Clean up the temp directories.
  1380. shutil.rmtree(temp_dir)
  1381. shutil.rmtree(unzip_dir)
  1382. def initialize_default_app(app_name: str):
  1383. """Initialize the default app.
  1384. Args:
  1385. app_name: The name of the app.
  1386. """
  1387. create_config(app_name)
  1388. initialize_app_directory(app_name)
  1389. def validate_and_create_app_using_remote_template(
  1390. app_name: str, template: str, templates: dict[str, Template]
  1391. ):
  1392. """Validate and create an app using a remote template.
  1393. Args:
  1394. app_name: The name of the app.
  1395. template: The name of the template.
  1396. templates: The available templates.
  1397. Raises:
  1398. Exit: If the template is not found.
  1399. """
  1400. # If user selects a template, it needs to exist.
  1401. if template in templates:
  1402. from reflex_cli.v2.utils import hosting
  1403. authenticated_token = hosting.authenticated_token()
  1404. if not authenticated_token or not authenticated_token[0]:
  1405. console.print(
  1406. f"Please use `reflex login` to access the '{template}' template."
  1407. )
  1408. raise typer.Exit(3)
  1409. template_url = templates[template].code_url
  1410. else:
  1411. template_parsed_url = urlparse(template)
  1412. # Check if the template is a github repo.
  1413. if template_parsed_url.hostname == "github.com":
  1414. path = template_parsed_url.path.strip("/").removesuffix(".git")
  1415. template_url = f"https://github.com/{path}/archive/main.zip"
  1416. else:
  1417. console.error(f"Template `{template}` not found or invalid.")
  1418. raise typer.Exit(1)
  1419. if template_url is None:
  1420. return
  1421. create_config_init_app_from_remote_template(
  1422. app_name=app_name, template_url=template_url
  1423. )
  1424. def fetch_remote_templates(
  1425. template: str,
  1426. ) -> tuple[str, dict[str, Template]]:
  1427. """Fetch the available remote templates.
  1428. Args:
  1429. template: The name of the template.
  1430. Returns:
  1431. The selected template and the available templates.
  1432. """
  1433. available_templates = {}
  1434. try:
  1435. # Get the available templates
  1436. available_templates = fetch_app_templates(constants.Reflex.VERSION)
  1437. except Exception as e:
  1438. console.warn("Failed to fetch templates. Falling back to default template.")
  1439. console.debug(f"Error while fetching templates: {e}")
  1440. template = constants.Templates.DEFAULT
  1441. return template, available_templates
  1442. def initialize_app(app_name: str, template: str | None = None) -> str | None:
  1443. """Initialize the app either from a remote template or a blank app. If the config file exists, it is considered as reinit.
  1444. Args:
  1445. app_name: The name of the app.
  1446. template: The name of the template to use.
  1447. Returns:
  1448. The name of the template.
  1449. Raises:
  1450. Exit: If the template is not valid or unspecified.
  1451. """
  1452. # Local imports to avoid circular imports.
  1453. from reflex.utils import telemetry
  1454. # Check if the app is already initialized.
  1455. if constants.Config.FILE.exists():
  1456. telemetry.send("reinit")
  1457. return
  1458. templates: dict[str, Template] = {}
  1459. # Don't fetch app templates if the user directly asked for DEFAULT.
  1460. if template is not None and (template not in (constants.Templates.DEFAULT,)):
  1461. template, templates = fetch_remote_templates(template)
  1462. if template is None:
  1463. template = prompt_for_template_options(get_init_cli_prompt_options())
  1464. if template == constants.Templates.CHOOSE_TEMPLATES:
  1465. console.print(
  1466. f"Go to the templates page ({constants.Templates.REFLEX_TEMPLATES_URL}) and copy the command to init with a template."
  1467. )
  1468. raise typer.Exit(0)
  1469. # If the blank template is selected, create a blank app.
  1470. if template in (constants.Templates.DEFAULT,):
  1471. # Default app creation behavior: a blank app.
  1472. initialize_default_app(app_name)
  1473. else:
  1474. validate_and_create_app_using_remote_template(
  1475. app_name=app_name, template=template, templates=templates
  1476. )
  1477. telemetry.send("init", template=template)
  1478. return template
  1479. def get_init_cli_prompt_options() -> list[Template]:
  1480. """Get the CLI options for initializing a Reflex app.
  1481. Returns:
  1482. The CLI options.
  1483. """
  1484. return [
  1485. Template(
  1486. name=constants.Templates.DEFAULT,
  1487. description="A blank Reflex app.",
  1488. demo_url=constants.Templates.DEFAULT_TEMPLATE_URL,
  1489. code_url="",
  1490. ),
  1491. Template(
  1492. name=constants.Templates.AI,
  1493. description="Generate a template using AI [Experimental]",
  1494. demo_url="",
  1495. code_url="",
  1496. ),
  1497. Template(
  1498. name=constants.Templates.CHOOSE_TEMPLATES,
  1499. description="Choose an existing template.",
  1500. demo_url="",
  1501. code_url="",
  1502. ),
  1503. ]
  1504. def initialize_main_module_index_from_generation(app_name: str, generation_hash: str):
  1505. """Overwrite the `index` function in the main module with reflex.build generated code.
  1506. Args:
  1507. app_name: The name of the app.
  1508. generation_hash: The generation hash from reflex.build.
  1509. Raises:
  1510. GeneratedCodeHasNoFunctionDefsError: If the fetched code has no function definitions
  1511. (the refactored reflex code is expected to have at least one root function defined).
  1512. """
  1513. # Download the reflex code for the generation.
  1514. url = constants.Templates.REFLEX_BUILD_CODE_URL.format(
  1515. generation_hash=generation_hash
  1516. )
  1517. resp = net.get(url)
  1518. while resp.status_code == httpx.codes.SERVICE_UNAVAILABLE:
  1519. console.debug("Waiting for the code to be generated...")
  1520. time.sleep(1)
  1521. resp = net.get(url)
  1522. resp.raise_for_status()
  1523. # Determine the name of the last function, which renders the generated code.
  1524. defined_funcs = re.findall(r"def ([a-zA-Z_]+)\(", resp.text)
  1525. if not defined_funcs:
  1526. raise GeneratedCodeHasNoFunctionDefsError(
  1527. f"No function definitions found in generated code from {url!r}."
  1528. )
  1529. render_func_name = defined_funcs[-1]
  1530. def replace_content(_match: re.Match) -> str:
  1531. return "\n".join(
  1532. [
  1533. resp.text,
  1534. "",
  1535. "def index() -> rx.Component:",
  1536. f" return {render_func_name}()",
  1537. "",
  1538. "",
  1539. ],
  1540. )
  1541. main_module_path = Path(app_name, app_name + constants.Ext.PY)
  1542. main_module_code = main_module_path.read_text()
  1543. main_module_code = re.sub(
  1544. r"def index\(\).*:\n([^\n]\s+.*\n+)+",
  1545. replace_content,
  1546. main_module_code,
  1547. )
  1548. # Make the app use light mode until flexgen enforces the conversion of
  1549. # tailwind colors to radix colors.
  1550. main_module_code = re.sub(
  1551. r"app\s*=\s*rx\.App\(\s*\)",
  1552. 'app = rx.App(theme=rx.theme(color_mode="light"))',
  1553. main_module_code,
  1554. )
  1555. main_module_path.write_text(main_module_code)
  1556. def format_address_width(address_width: str | None) -> int | None:
  1557. """Cast address width to an int.
  1558. Args:
  1559. address_width: The address width.
  1560. Returns:
  1561. Address width int
  1562. """
  1563. try:
  1564. return int(address_width) if address_width else None
  1565. except ValueError:
  1566. return None
  1567. def _retrieve_cpu_info() -> CpuInfo | None:
  1568. """Retrieve the CPU info of the host.
  1569. Returns:
  1570. The CPU info.
  1571. """
  1572. platform_os = platform.system()
  1573. cpuinfo = {}
  1574. try:
  1575. if platform_os == "Windows":
  1576. cmd = 'powershell -Command "Get-CimInstance Win32_Processor | Select-Object -First 1 | Select-Object AddressWidth,Manufacturer,Name | ConvertTo-Json"'
  1577. output = processes.execute_command_and_return_output(cmd)
  1578. if output:
  1579. cpu_data = json.loads(output)
  1580. cpuinfo["address_width"] = cpu_data["AddressWidth"]
  1581. cpuinfo["manufacturer_id"] = cpu_data["Manufacturer"]
  1582. cpuinfo["model_name"] = cpu_data["Name"]
  1583. elif platform_os == "Linux":
  1584. output = processes.execute_command_and_return_output("lscpu")
  1585. if output:
  1586. lines = output.split("\n")
  1587. for line in lines:
  1588. if "Architecture" in line:
  1589. cpuinfo["address_width"] = (
  1590. 64 if line.split(":")[1].strip() == "x86_64" else 32
  1591. )
  1592. if "Vendor ID:" in line:
  1593. cpuinfo["manufacturer_id"] = line.split(":")[1].strip()
  1594. if "Model name" in line:
  1595. cpuinfo["model_name"] = line.split(":")[1].strip()
  1596. elif platform_os == "Darwin":
  1597. cpuinfo["address_width"] = format_address_width(
  1598. processes.execute_command_and_return_output("getconf LONG_BIT")
  1599. )
  1600. cpuinfo["manufacturer_id"] = processes.execute_command_and_return_output(
  1601. "sysctl -n machdep.cpu.brand_string"
  1602. )
  1603. cpuinfo["model_name"] = processes.execute_command_and_return_output(
  1604. "uname -m"
  1605. )
  1606. except Exception as err:
  1607. console.error(f"Failed to retrieve CPU info. {err}")
  1608. return None
  1609. return (
  1610. CpuInfo(
  1611. manufacturer_id=cpuinfo.get("manufacturer_id"),
  1612. model_name=cpuinfo.get("model_name"),
  1613. address_width=cpuinfo.get("address_width"),
  1614. )
  1615. if cpuinfo
  1616. else None
  1617. )
  1618. @functools.lru_cache(maxsize=None)
  1619. def get_cpu_info() -> CpuInfo | None:
  1620. """Get the CPU info of the underlining host.
  1621. Returns:
  1622. The CPU info.
  1623. """
  1624. cpu_info_file = environment.REFLEX_DIR.get() / "cpu_info.json"
  1625. if cpu_info_file.exists() and (cpu_info := json.loads(cpu_info_file.read_text())):
  1626. return CpuInfo(**cpu_info)
  1627. cpu_info = _retrieve_cpu_info()
  1628. if cpu_info:
  1629. cpu_info_file.parent.mkdir(parents=True, exist_ok=True)
  1630. cpu_info_file.write_text(json.dumps(dataclasses.asdict(cpu_info)))
  1631. return cpu_info
  1632. def is_generation_hash(template: str) -> bool:
  1633. """Check if the template looks like a generation hash.
  1634. Args:
  1635. template: The template name.
  1636. Returns:
  1637. True if the template is composed of 32 or more hex characters.
  1638. """
  1639. return re.match(r"^[0-9a-f]{32,}$", template) is not None
  1640. def get_user_tier():
  1641. """Get the current user's tier.
  1642. Returns:
  1643. The current user's tier.
  1644. """
  1645. from reflex_cli.v2.utils import hosting
  1646. authenticated_token = hosting.authenticated_token()
  1647. return (
  1648. authenticated_token[1].get("tier", "").lower()
  1649. if authenticated_token[0]
  1650. else "anonymous"
  1651. )