Repository navigation
Import JavaScript modules from Python and call their exports by name - #7950
FarhanAliRaza wants to merge 100 commits into
Conversation
`from my_app.scripts.party import celebrate` now finds my_app/scripts/party.js (or .ts) when no Python module of that name exists. Each named export becomes a JsFunction; calling it returns a `_call_js` event naming the module and the function, with the arguments as JSON. It works in event triggers, returned or yielded from handlers, and uncalled as a trigger (it takes the trigger's arguments, like a handler). An event handler argument arrives as its full name, for `env.addEvents([env.event(name, payload)])`. The compiler copies each imported module, with the .js/.ts files beside it so relative imports resolve, under utils/script_modules, and utils/scripts.js re-exports it under a key `$` makes unique. The frontend imports that index on the first call, so nothing is evaluated and an app that never calls a module does not fetch the chunk: it works under a CSP without unsafe-eval. npm packages the modules import are installed with the app. A stub (party.pyi) with untyped arguments is written next to the module, so type checkers resolve the import; typed stubs come next. The finder is stdlib-only and reflex_base.js is lazy, so `import reflex`, which installs it, still does not load the event system. The function's return value is not sent back: results will come from awaiting the event, a separate design. Part of ENG-9127. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
…arwin-dx76ek-js-modules
Confidence Score: 5/5
[Medium impact] The reviewed changes appear safe to merge, with no new blocking issue found. SummaryThis PR lets Python import JavaScript module functions and call them through browser events without evaluating code strings.
Reviews (31) · Last reviewed commit: "Merge remote-tracking branch 'upstream/p..." · Reviewed by Greptile |
Merging this PR will improve performance by 4.64%2 warnings
Performance Changes
Tip Curious why performance improved? Comment Comparing Footnotes
|
…t reflex cheap
Review fixes for the JavaScript module import:
- Exports and imports are read from tokens (reflex_base/js/source.py) instead
of regular expressions over the source. Text inside strings, template
literals, regular expressions and comments is never read as code, so a
string such as "/api/*" no longer hides the exports after it. Every name of
`export const a = ..., b = ...` is found, as are destructured exports, TS
annotations with commas, and `"string" as name` export lists. Imports are
found wherever line breaks fall, including dynamic `import("x")`.
- The compiler copies the module and the local files it imports, followed
transitively and resolved as the bundler does (extensionless, index files,
`.js` naming a `.ts`), at their paths from the directory of the module's
package, instead of the script files beside it. Nested helpers and imported
CSS now resolve, and unused siblings are no longer bundled or installed. A
file outside the package's directory is a clear error.
- RegistrationContext.fork() copies script_modules, so an app built in a fork
still compiles the modules imported before it.
- The finder no longer imports pathlib, importlib.abc or typing, which
`import reflex` does not load otherwise (CodSpeed: test_import_reflex
+1.6ms); a test pins it.
- Test docstrings.
Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
…arwin-dx76ek-js-modules
Review fixes: - Files a module imports that are not scripts (stylesheets, images, fonts) were read as UTF-8 into the compile output, so `import logo from "./logo.png"` stopped the compile with UnicodeDecodeError. compile_script_modules now returns them as (source, target) copies, which compile_app copies byte for byte after the dry-run return, skipping targets that are up to date. - A copied stylesheet's `@import` and `url(...)` references are followed too, so `./theme.css` and `./bg.png` used by an imported `party.css` are bundled. Absolute paths, URLs, data URIs and fragments are left alone. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
CodSpeed still showed test_import_reflex about 15% slower on c0ebd9c. The benchmark clears the reflex modules and imports `reflex` again in the same process, so it measures module execution: importing the lazy reflex_base.js package and its finder module on every `import reflex` cost about 200us of about 1300us. It also showed a bug: install() matched the finder with isinstance, and a re-imported finder module is a new class, so every fresh import appended another finder to sys.meta_path (205 after 200 rounds). reflex_base/__init__.py, which every Reflex import loads first, now registers a small finder class that loads reflex_base.js.finder only on the first import no other finder found, matched by name so a fresh import never adds a second. `import reflex` loads no module for it (about 12us of execution), and reflex/__init__.py is back to its previous form, so the generated reflex/__init__.pyi stays free of runtime code. Tests pin one finder after a re-import and that `import reflex` does not load reflex_base.js. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
Review fixes: - call_event_fn counted `*args` as one required parameter and passed only as many arguments as the callable declared, so an uncalled JS module function failed to compile on a trigger with no arguments (`on_mount=initialize`) and got only the first argument of one with several. The same broke any `lambda *args: ...`. Variadic parameters are no longer required, and a `*args` callable gets every argument. - A relative import with a query or fragment (Vite's `./message.txt?raw`, `./logo.png?url`) resolves to its file again, so the file is copied with the module, which keeps the import as written. Package specifiers drop the query before install. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
…arwin-dx76ek-js-modules Keep reflex_base.js a package: the base's js.py becomes js/api.py, whose ref, add_events and library the package re-exports lazily, since the module finder `import reflex` registers lives in the package too. The obsolete environment.py goes, test_js.py moves to js/test_api.py, and the JavaScript module tests, docs and demo use `reflex` from $/utils/reflex. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
A callable taking `**kwargs` or a keyword-only parameter was called with one argument per parameter, so `lambda key, **kw: ...` on on_key_down got two positional arguments and raised TypeError. Count only positional parameters, both to call the function and to check that the trigger provides enough arguments; `*args` still takes all of them. The varargs test moves next to the new one in the event module's test file. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
Scope: the finder only claims modules of the app's package, the package rxconfig's app_name names, so a third-party package's .js file is never imported or registered. The config loads only once a file is found, and the finder is now a function the stub in reflex_base calls. Parsing: one scanner serves tokenize, template expressions and JSX, and each file is read and tokenized once per compile (module_files returns each script's text, exports and imports). `=>`, `++` and `--` are single tokens, so annotations like `() => Map<K, V>` and `i++ / 2` read right; `.jsx`/`.tsx` files skip JSX text; type items of export lists, generic arrow functions, `import type` and `export type` are handled. A `const` bound to a literal is a value, not a function. Every new function stays within a complexity of 8. Compile: files must be inside the app package's directory, not merely the project's. utils/scripts.js now maps each module's Python name, as a JSON string, to a loader, so any module name or path is safe in the generated code. Specifiers with a scheme, `#` or `@/` are not installed, and Node.js built-ins fail the compile with what to do instead. Errors: importing a missing function names the file and its functions; importing a value says only functions can be called; the browser error for a missing function gives both causes and both fixes. Frontend: state.js loads the app's modules with the page and caches them, so a `_call_js` runs its function before awaiting anything and the next event, even one processEvent starts concurrently, sees its effect. An app without modules loads nothing. Errors of event code are reported through one helper. Public API: the module helpers are private (_CALL_JS, _JsFunction, _load_module, _render_stub, _package_imports), module_key is gone, and RegistrationContext.script_modules is _script_modules. Tests follow the module layout: test_finder.py, test_modules.py, test_source.py, and reflex_base/test_init.py. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
A handler yields a module function and then a script that reads what it wrote; each arrives in a message of its own. With the module loaded on demand, the script ran first and read the old text. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
The section leads with a runnable app, then the rules (the app package is the scope, files must be inside it, what is installed, arguments as JSON, how to get a value back, JSX only in .jsx/.tsx) and each error with its fix. News fragments say the same for downstream users. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
The helper that reports errors of event code now serves four blocks, so a test pins what each logs and reports, with and without window.onerror. A string after `from` always ends an import or export clause in valid code, so finding the clause's keyword needs no bail-out branches. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
Loading the modules at page load does not guarantee they finish before events arrive. While a _call_js waits for its module, processEvent now holds the events after it, in the order they arrived, until the call has run, so they see what its function did. Nothing waits once the module has loaded. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
The tokenizer skipped the expressions of templates and JSX without keeping
their tokens, so an import("./x.js") in ${...} or {...} was never copied.
A literal's token now holds the tokens of its expressions, and the import
search walks them; the export search still sees one token per literal.
Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
An event that waited for one pending module call could run ahead of the next one: the event before it may be a module call that only starts waiting for its module once the first has run. processEvent now waits until no call is pending. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
|
CodSpeed reports
So the code under that benchmark is byte-for-byte the same in both runs. Generated by Claude Code |
…nv' into farhan/focused-darwin-dx76ek-js-modules
Every module call is a _call_js event, and addEvents keyed timers by event name only, so two different functions using .debounce() or .throttle() cancelled or suppressed each other. The key now names the module and the function.
…*args The argument check counts only named parameters, but the payload still named the trigger's values after every parameter, so a handler such as `def handle(self, value, *args, required)` was accepted on a two-argument trigger and then got an `args` key and no `required`.
… them OtelPlugin inserts its react-dom alias where mainFields is followed by the alias list; preserveSymlinks above mainFields hid that block and the compile failed with render_timing on.
Dropping variadic parameters first and the state parameter after removed the first named parameter of a handler that takes its state in *args.
Generated by Claude Code |
Linking the app's package into .web dropped the `loops` field of 5879cd2: script-modules.js lists files by the path their import names, so `party.js` importing `./link/party.js` with `link -> .` reached `link/link/party.js` and so on until stat threw ELOOP, and the compiler told the user to delete node_modules or report a bug. Vite, which does not follow links, would read each of those paths as a module of its own. script-modules.js again remembers the import that first reached each file and stops when a chain reaches the same real file from a directory below the one it was in that is the same directory through a link. It lists the import and the link under `loops`, and the compiler raises an error naming the importing file, the file and the link. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
Without `has_location`, importlib set no `__file__` on the module, and `inspect.getfile(module)` raised that it is a built-in module. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
`hasattr(module, "x")` records `x` like an import does, so it is always true, and the compile then fails if the module does not export `x`. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
…ectly processEvent waits for a module call's module to settle before applying it, but applyEvent is exported: called directly while the module loaded, it read `"error" in undefined` and reported a TypeError. It now waits for the load, and still calls a settled module's function before awaiting. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
`get_node_path() or get_bun_path()` can be None, which subprocess ran as the program 'None', failing with a bare `FileNotFoundError: 'None'`. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
…nked The Uvicorn dev backend now reloads for .js, .jsx, .mjs, .ts, .tsx, .mts and .css files, which needs a news entry. The comment on SCRIPT_MODULES_PATH still said the modules are copied there; the app's package is linked there instead. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
A package imported by name, by a component or a JavaScript module, and pinned in `frontend_packages` reached the package manager as both the name and the pin. bun then fetched the name from the registry, which fails with a 404 for a `file:` package, and which of the two specs won for a registry package depended on set order. The unpinned import is now dropped when `frontend_packages` pins the package, as it already was when another import pinned it. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
The CallScript app's module now imports an npm package of .web (isbot), a frontend package installed from a `file:` directory beside the app's package, and a stylesheet that `@import`s another, and has a function bound uncalled to an input's `on_change`. The test checks each result in the page. The app now runs in dev and prod, so the production bundle is built through the link to the app's package too. Without `resolve.preserveSymlinks` the prod build fails to resolve "isbot" from the module and the dev page misses the stylesheet. With npm, which links the `file:` package into .web/node_modules, both modes pass as well. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
Scoping it to utils/script_modules with a resolver plugin is not possible: Vite resolves a stylesheet's `@import` and `url()`, workers and pre-bundled dependencies with an internal resolver of the alias and resolve plugins only, which reads `resolve.preserveSymlinks` from the config. The reflex-base fragment now says that it applies to every link in .web, a `file:` or `npm link` package in node_modules included, which the integration test builds. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
…6ek-js-modules Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
|
Thanks @masenf. Addressed (merged #7949's latest into this branch too, dff0216):
Checks: the frontend Generated by Claude Code |
The generated vite.config.js set resolve.preserveSymlinks for every app. Under bun's isolated linker, whose node_modules entries are links, that breaks the build of an app that imports no module: a package's own dependencies are no longer found from its real directory. The compile now writes it only when the app imports a module, and the docs and the news say such an app cannot use the isolated linker.
The stub declared each export as a function returning an EventSpec, but the object Python gets is an event handler, so a type checker rejected the uncalled form with an event action, such as echo.debounce(300), which works at runtime. Each export is now typed as EventHandler, whose call takes any arguments and returns an EventSpec.
…6ek-js-modules Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
script-modules.js dropped a relative import it could not resolve, so the compile passed and the bundler failed later, in the build or the dev server. It now reports each such import of a script, and each relative @import of a stylesheet, and the compile stops with the importing file and the path. A url() of no file is still left to the browser, as Vite leaves it.
The error for a relative import of no file also covers a stylesheet's @import, so it now says "The file" instead of "The JavaScript file".
…t modules The first compile of an app that imports a JavaScript module installs the parser before reading the modules, without the packages only the modules import. That install pruned them, so a fresh checkout with a saved reflex.lock dropped their pins and the next install added them again at the newest version. Only the install with every import prunes. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
Type of change
Description
Second of the ENG-9127 stack, on top of #7949.
Problem. More than a line of JavaScript ends up as strings passed to
rx.call_script. Those strings get no editor support or lint, the browser evals them, and they break under a Content Security Policy withoutunsafe-eval.Change. Write the JavaScript in a
.js,.ts,.jsxor.tsxfile in your app package, and import its exported functions from Python:Each named export becomes a Python function that returns an event. Use it in an event trigger, or return or yield it from a handler. Passed to a trigger without being called, it receives the trigger's arguments. The browser receives the module, the function name and the arguments as JSON, and evaluates nothing.
Rules.
.jsfiles in other installed packages are never claimed../helpers.js, CSS with its@import/url()references, images) are bundled with it, resolved by Vite itself. They must be inside the app package's directory.virtual:,#…,@/…and type-only imports. A Node built-in with no browser package (fs,node:*) stops the compile with an error.reflex.addEvents.from module import *is not supported: Python does not read the file, so it cannot list its exports.callback=, insiderx.cond, returned from a handler, and with event actions such as.debounce()(each function keeps its own debounce and throttle timer). An event handler argument arrives as its full name, and a bound event as{name, payload}, also inside lists and dicts, from a trigger and from a handler alike.Errors. Each one states the problem, its cause and the fix, and is pinned by an exact test. All are raised when the app compiles:
nope): names the file, lists its functions, and shows theexport function nope() { ... }to add.export const notAFunction = 5used from Python: it is a value, not a function, which Python cannot call.file:line:columnand the parser's message.Design.
__getattr__returns a function for any name and records the name. The backend needs no parser and no Node.js:--backend-onlydeployments are unaffected.script-modules.jsruns in.webwith the oxc parser that ships with rolldown, which Vite 8 installs in every app. It reports each module's function and value exports, its local files and its npm imports, so JS, TS, JSX and TSX are parsed exactly. This replaces an earlier hand-written tokenizer (~890 lines). The compile then checks every name Python used. The node call takes ~40 ms, and only for apps that import a module. The first compile of such an app installs the frontend packages before reading the modules, because the parser comes with them.import reflexdoesn't load the event system. It sits beforePathFinderand runs its search first: a Python module always wins, and a directory without__init__.pyno longer hides a script of its name. It claims a module only if a matching script exists under the app package, reads the config only then, and declines whilerxconfig.pyitself loads..web/utils/script_modules/<package>is a link to the app package (a directory junction on Windows), and Vite resolves withpreserveSymlinks, so the module's imports,.js→.tsxmapping, CSS@imports and assets are resolved by Vite, a deleted file is gone at once, and nothing is copied or cleaned up. A build must run where the app package is: one that copies only.webelsewhere breaks the link.utils/scripts.jsmaps module names to() => import(...)with JSON-escaped strings, so each module is its own lazy chunk in the production build. Loading starts at page load and is cached, so a module function runs before anything awaited after it.state_connection.test.jspins those). The function is then called without awaiting the promise it returns, so a slow or never-settling function holds up no later event. The misleading comment above its empty-queue check now says what the check does.*args/**kwargsfix for callables passed to triggers comes from there, merged in until it lands.Tests
test_finder.py,test_modules.py,test_compiler_utils.py,test_compiler.py): the import scope, name recording, the compile-time checks and their exact messages, the folder limit, generated module names, npm detection, the script runner (real Node), and install ordering.script-modules.json fixtures (TS, JSX/TSX, CSS, assets, dynamic imports,export *, type-only exports),_call_js, and the ordering of a module function before the next event.test_call_script.py: module functions from a trigger and from a handler, an async function, an npm package, CSS, an uncalledon_change, and the ordering.npm run checkare clean.https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf