base.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. """Base file for constants that don't fit any other categories."""
  2. from __future__ import annotations
  3. import platform
  4. from enum import Enum
  5. from importlib import metadata
  6. from pathlib import Path
  7. from types import SimpleNamespace
  8. from typing import Literal
  9. from platformdirs import PlatformDirs
  10. from .utils import classproperty
  11. IS_WINDOWS = platform.system() == "Windows"
  12. IS_MACOS = platform.system() == "Darwin"
  13. IS_LINUX = platform.system() == "Linux"
  14. class Dirs(SimpleNamespace):
  15. """Various directories/paths used by Reflex."""
  16. # The frontend directories in a project.
  17. # The web folder where the NextJS app is compiled to.
  18. WEB = ".web"
  19. # The directory where uploaded files are stored.
  20. UPLOADED_FILES = "uploaded_files"
  21. # The name of the assets directory.
  22. APP_ASSETS = "assets"
  23. # The name of the assets directory for external resources (a subfolder of APP_ASSETS).
  24. EXTERNAL_APP_ASSETS = "external"
  25. # The name of the utils file.
  26. UTILS = "utils"
  27. # The name of the state file.
  28. STATE_PATH = "/".join([UTILS, "state"])
  29. # The name of the components file.
  30. COMPONENTS_PATH = "/".join([UTILS, "components"])
  31. # The name of the contexts file.
  32. CONTEXTS_PATH = "/".join([UTILS, "context"])
  33. # The name of the output static directory.
  34. STATIC = "_static"
  35. # The name of the public html directory served at "/"
  36. PUBLIC = "public"
  37. # The directory where styles are located.
  38. STYLES = "styles"
  39. # The name of the pages directory.
  40. PAGES = "pages"
  41. # The name of the env json file.
  42. ENV_JSON = "env.json"
  43. # The name of the reflex json file.
  44. REFLEX_JSON = "reflex.json"
  45. # The name of the postcss config file.
  46. POSTCSS_JS = "postcss.config.js"
  47. # The name of the states directory.
  48. STATES = ".states"
  49. # Where compilation artifacts for the backend are stored.
  50. BACKEND = "backend"
  51. # JSON-encoded list of page routes that need to be evaluated on the backend.
  52. STATEFUL_PAGES = "stateful_pages.json"
  53. # Marker file indicating that upload component was used in the frontend.
  54. UPLOAD_IS_USED = "upload_is_used"
  55. def _reflex_version() -> str:
  56. """Get the Reflex version.
  57. Returns:
  58. The Reflex version.
  59. """
  60. try:
  61. return metadata.version("reflex")
  62. except metadata.PackageNotFoundError:
  63. return "unknown"
  64. class Reflex(SimpleNamespace):
  65. """Base constants concerning Reflex."""
  66. # App names and versions.
  67. # The name of the Reflex package.
  68. MODULE_NAME = "reflex"
  69. # The current version of Reflex.
  70. VERSION = _reflex_version()
  71. # The reflex json file.
  72. JSON = "reflex.json"
  73. # Files and directories used to init a new project.
  74. # The directory to store reflex dependencies.
  75. # on windows, we use C:/Users/<username>/AppData/Local/reflex.
  76. # on macOS, we use ~/Library/Application Support/reflex.
  77. # on linux, we use ~/.local/share/reflex.
  78. # If user sets REFLEX_DIR envroment variable use that instead.
  79. DIR = PlatformDirs(MODULE_NAME, False).user_data_path
  80. LOGS_DIR = DIR / "logs"
  81. # The root directory of the reflex library.
  82. ROOT_DIR = Path(__file__).parents[2]
  83. RELEASES_URL = "https://api.github.com/repos/reflex-dev/templates/releases"
  84. # The reflex stylesheet language supported
  85. STYLESHEETS_SUPPORTED = ["css", "sass", "scss"]
  86. class ReflexHostingCLI(SimpleNamespace):
  87. """Base constants concerning Reflex Hosting CLI."""
  88. # The name of the Reflex Hosting CLI package.
  89. MODULE_NAME = "reflex-hosting-cli"
  90. class Templates(SimpleNamespace):
  91. """Constants related to Templates."""
  92. # The route on Reflex backend to query which templates are available and their URLs.
  93. APP_TEMPLATES_ROUTE = "/app-templates"
  94. # The default template
  95. DEFAULT = "blank"
  96. # The AI template
  97. AI = "ai"
  98. # The option for the user to choose a remote template.
  99. CHOOSE_TEMPLATES = "choose-templates"
  100. # The URL to find reflex templates.
  101. REFLEX_TEMPLATES_URL = "https://reflex.dev/templates"
  102. # Demo url for the default template.
  103. DEFAULT_TEMPLATE_URL = "https://blank-template.reflex.run"
  104. # The reflex.build frontend host
  105. REFLEX_BUILD_FRONTEND = "https://reflex.build"
  106. # The reflex.build backend host
  107. REFLEX_BUILD_BACKEND = "https://flexgen-prod-flexgen.fly.dev"
  108. @classproperty
  109. @classmethod
  110. def REFLEX_BUILD_URL(cls):
  111. """The URL to redirect to reflex.build.
  112. Returns:
  113. The URL to redirect to reflex.build.
  114. """
  115. from reflex.config import environment
  116. return (
  117. environment.REFLEX_BUILD_FRONTEND.get()
  118. + "/gen?reflex_init_token={reflex_init_token}"
  119. )
  120. @classproperty
  121. @classmethod
  122. def REFLEX_BUILD_POLL_URL(cls):
  123. """The URL to poll waiting for the user to select a generation.
  124. Returns:
  125. The URL to poll waiting for the user to select a generation.
  126. """
  127. from reflex.config import environment
  128. return environment.REFLEX_BUILD_BACKEND.get() + "/api/init/{reflex_init_token}"
  129. @classproperty
  130. @classmethod
  131. def REFLEX_BUILD_CODE_URL(cls):
  132. """The URL to fetch the generation's reflex code.
  133. Returns:
  134. The URL to fetch the generation's reflex code.
  135. """
  136. from reflex.config import environment
  137. return (
  138. environment.REFLEX_BUILD_BACKEND.get()
  139. + "/api/gen/{generation_hash}/refactored"
  140. )
  141. class Dirs(SimpleNamespace):
  142. """Folders used by the template system of Reflex."""
  143. # The template directory used during reflex init.
  144. BASE = Reflex.ROOT_DIR / Reflex.MODULE_NAME / ".templates"
  145. # The web subdirectory of the template directory.
  146. WEB_TEMPLATE = BASE / "web"
  147. # The jinja template directory.
  148. JINJA_TEMPLATE = BASE / "jinja"
  149. # Where the code for the templates is stored.
  150. CODE = "code"
  151. class Next(SimpleNamespace):
  152. """Constants related to NextJS."""
  153. # The NextJS config file
  154. CONFIG_FILE = "next.config.js"
  155. # The sitemap config file.
  156. SITEMAP_CONFIG_FILE = "next-sitemap.config.js"
  157. # The node modules directory.
  158. NODE_MODULES = "node_modules"
  159. # The package lock file.
  160. PACKAGE_LOCK = "package-lock.json"
  161. # Regex to check for message displayed when frontend comes up
  162. FRONTEND_LISTENING_REGEX = "Local:[\\s]+(.*)"
  163. # Color mode variables
  164. class ColorMode(SimpleNamespace):
  165. """Constants related to ColorMode."""
  166. NAME = "rawColorMode"
  167. RESOLVED_NAME = "resolvedColorMode"
  168. USE = "useColorMode"
  169. TOGGLE = "toggleColorMode"
  170. SET = "setColorMode"
  171. LITERAL_ENV = Literal["dev", "prod"]
  172. # Env modes
  173. class Env(str, Enum):
  174. """The environment modes."""
  175. DEV = "dev"
  176. PROD = "prod"
  177. # Log levels
  178. class LogLevel(str, Enum):
  179. """The log levels."""
  180. DEBUG = "debug"
  181. DEFAULT = "default"
  182. INFO = "info"
  183. WARNING = "warning"
  184. ERROR = "error"
  185. CRITICAL = "critical"
  186. @classmethod
  187. def from_string(cls, level: str | None) -> LogLevel | None:
  188. """Convert a string to a log level.
  189. Args:
  190. level: The log level as a string.
  191. Returns:
  192. The log level.
  193. """
  194. if not level:
  195. return None
  196. try:
  197. return LogLevel[level.upper()]
  198. except KeyError:
  199. return None
  200. def __le__(self, other: LogLevel) -> bool:
  201. """Compare log levels.
  202. Args:
  203. other: The other log level.
  204. Returns:
  205. True if the log level is less than or equal to the other log level.
  206. """
  207. levels = list(LogLevel)
  208. return levels.index(self) <= levels.index(other)
  209. def subprocess_level(self):
  210. """Return the log level for the subprocess.
  211. Returns:
  212. The log level for the subprocess
  213. """
  214. return self if self != LogLevel.DEFAULT else LogLevel.WARNING
  215. # Server socket configuration variables
  216. POLLING_MAX_HTTP_BUFFER_SIZE = 1000 * 1000
  217. class Ping(SimpleNamespace):
  218. """PING constants."""
  219. # The 'ping' interval
  220. INTERVAL = 25
  221. # The 'ping' timeout
  222. TIMEOUT = 120
  223. # Keys in the client_side_storage dict
  224. COOKIES = "cookies"
  225. LOCAL_STORAGE = "local_storage"
  226. SESSION_STORAGE = "session_storage"
  227. # Testing variables.
  228. # Testing os env set by pytest when running a test case.
  229. PYTEST_CURRENT_TEST = "PYTEST_CURRENT_TEST"
  230. APP_HARNESS_FLAG = "APP_HARNESS_FLAG"
  231. REFLEX_VAR_OPENING_TAG = "<reflex.Var>"
  232. REFLEX_VAR_CLOSING_TAG = "</reflex.Var>"