Repository navigation
Type the stubs of imported JavaScript modules from TypeScript and JSDoc - #7951
FarhanAliRaza wants to merge 93 commits into
Conversation
The stub written next to an imported JavaScript module typed every function as `(*args: Any)`. It now reads each export's call signatures with the TypeScript checker, from annotations in a .ts file or JSDoc in a .js file, through script-signatures.js, which ships to .web beside the other build scripts an app runs: /** @PARAM {number} count @PARAM {string} elementId @PARAM {boolean} [loud] */ export function celebrate(count, elementId, loud = false) {} def celebrate(count: float | Var[float], elementId: str | Var[str] | EventCallback[*tuple[Any, ...]], loud: bool | Var[bool] = ..., /) -> EventSpec: ... Arguments are positional-only, as JavaScript passes them. JSON types map to Python (number to float, T[] to Sequence, unions, literals, `| null`); types with no JSON form become Any. A string parameter also takes an event handler, which the call sends as its name. Overloads become @overload, rest parameters *args, and exports that are not functions are left out. typescript (pinned to the version reflex-frontend checks itself with, which a test keeps equal) is installed only with apps that import a module, and runs after the install, once for every stale module. The stub's header records a digest of the module and the scripts beside it, so typescript does not run while they are unchanged. When the types cannot be read (no node or bun, or the script fails) the stub stays untyped, with a warning, and is retried on the next compile. Part of ENG-9127. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
Confidence Score: 5/5
[Medium impact] The PR appears safe to merge; no new actionable issue was established. SummaryAdds typed Python stubs for imported JavaScript and TypeScript modules during development.
Reviews (35) · Last reviewed commit: "Merge farhan/focused-darwin-dx76ek-js-mo..." · Reviewed by Greptile |
Merging this PR will degrade performance by 4.14%2 warnings
Warning Please fix the performance issues or acknowledge them on CodSpeed. Performance Changes
Tip Investigate this regression by commenting Comparing Footnotes
|
…cused-darwin-dx76ek-js-stubs # Conflicts: # packages/reflex-base/src/reflex_base/js/modules.py # reflex/compiler/utils.py # tests/units/compiler/test_compiler_utils.py # tests/units/reflex_base/js/test_modules.py
…s, cache key - A parameter renamed from a non-identifier (`$value` -> `arg0`) no longer takes the name of another parameter, which made the stub invalid Python. - Only trailing optional parameters get defaults: in `f(prefix = "", count)` Python cannot omit `prefix`, so both are required. - A tuple rest parameter (`...args: [number, string]`) has no single element type and becomes `*args: Any` instead of `*args: Sequence[Any]`, which rejected the valid call. - An export of unknown type (`any`, e.g. re-exported from a package without declarations) keeps an untyped def instead of disappearing from the stub. - The stub digest covers the local files the module imports (as copied by the compiler) and the app's package.json, so a package upgrade re-reads the types; paths are hashed relative to the module, so the header is the same on every machine. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
…cused-darwin-dx76ek-js-stubs
…cused-darwin-dx76ek-js-stubs # Conflicts: # reflex/compiler/utils.py # tests/units/compiler/test_compiler_utils.py
…cused-darwin-dx76ek-js-stubs # Conflicts: # tests/units/reflex_base/js/test_modules.py
…cused-darwin-dx76ek-js-stubs
Review fixes:
- The stub imports the types it uses under private aliases (`_str`, `_Var`,
`_Sequence`, ...), so an export named `str`, `Var` or `Sequence` no longer
replaces the type its annotations name; parameters keep their own names. An
export named like one of the aliases is left out of the stub. Checked with
pyright: a stub exporting `str`, `Var` and `any` type-checks, and calls are
checked against it.
- The stub digest, through module_files, also covers the files a module takes
types from: `.d.ts` files an import resolves to, JSDoc `import("./types")`
and `/// <reference path>`. Editing them rewrites the stub.
Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
An earlier merge left conflict markers, then indented by the formatter, in compile_script_modules's Returns section; it now describes the three returned values once. The stub tests that compared only the last line or two of the rendered stub compare the complete output. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
…de it Trying `.d.ts` before `.js` when resolving `./helpers` picked helpers.d.ts whenever both existed, so helpers.js was not copied and a clean frontend build could not resolve the import. Runtime files resolve as the bundler does again, and the declaration file that types an import (helpers.d.ts for `./helpers` or `./helpers.js`, or alone for a types-only import) is tracked beside it, for the stub digest. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
Dropping .d.ts from runtime resolution also dropped the lookup of types/index.d.ts for `./types`, so editing it left the stub digest unchanged. The declaration lookup now tries it after types.d.ts. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
|
The CodSpeed failure on 7c653f1 is not from this change. All three regressions are
So this is runner variance. Nothing to fix in the diff; it can be acknowledged on CodSpeed. Generated by Claude Code |
test_js_module_stub failed when another test module had already run an app named `callscript` in the same process: the harness reloads that package, which keeps its first directory, so page_script.js and its stub live there, not under this harness's app_path. The test now takes the module's path from the imported module, and normalizes the digest in the header, which depends on the app's package.json (its value is covered by the unit tests), before comparing the whole stub. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
Adapt the stubs to the reworked module API. A stub declares only the names
ScriptSource.functions lists, and names TypeScript reports as types only are
dropped too. module_files is the copy walk again: the files a module reads
types from (declarations beside its imports, type-only imports, JSDoc
import("...") and triple-slash references) are found by type_files, only for
the digest, so a type reference outside the package no longer fails the
compile and type-only files are not copied into .web. The digest hashes the
scripts the copy walk already read.
script-signatures.js now classifies each parameter's type with the checker
into the JSON value Python can send (a small type tree with sorted unions), and
stubs.py only renders it, importing just the aliases a stub uses. Stubs are
written in development only, a stub whose module the app stopped importing is
removed, and failures to read types say what happened and how to fix it.
Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
Read the kind of every import, type-only ones included, through the base's new walk of template and JSX expressions. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
Granian watched .pyi files, so each stub Reflex wrote next to a JavaScript module restarted the backend once more. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
The Type Stubs section shows what a JSDoc signature becomes, maps each TypeScript type to its Python type (Any included), says the stubs are written in development only and recommends committing them, and lists the warnings a compile can print with their fixes. The news fragments say what changed for users instead of naming internal files. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
The record in .web kept what each stub was made from, but not the stub, so a stub restored from git after its module changed, which has the same header, matched the record and was kept with its old signatures until an input changed or it was deleted. The record now also keeps the digest of the stub's text, read as text so line endings written on Windows compare the same, and a stub whose text no longer matches is made again. The tests that compared the record compare its stub digest too, and the two that checked the end of a rewritten stub compare all of it. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
…s-modules' into farhan/focused-darwin-dx76ek-js-stubs # Conflicts: # docs/api-reference/browser_javascript.md # packages/reflex-base/src/reflex_base/js/modules.py # reflex/compiler/compiler.py # reflex/compiler/utils.py # tests/units/compiler/test_compiler.py # tests/units/compiler/test_compiler_utils.py
…s-stubs' into farhan/focused-darwin-dx76ek-js-stubs # Conflicts: # reflex/compiler/utils.py # tests/units/compiler/test_compiler_utils.py
…s-modules' into farhan/focused-darwin-dx76ek-js-stubs
…s-modules' into farhan/focused-darwin-dx76ek-js-stubs
…s-modules' into farhan/focused-darwin-dx76ek-js-stubs
…s-modules' into farhan/focused-darwin-dx76ek-js-stubs
…s-modules' into farhan/focused-darwin-dx76ek-js-stubs
|
Design is solid and the tests are thorough. One crash blocks it:
CI for unit/integration/pre-commit has not run on this PR (feature-branch target). Generated by Claude Code |
`export function setup({ id, color }) {}` has a parameter whose object
type TypeScript synthesizes without a symbol, and `isOpaque` read its
`flags`, so script-signatures.js threw and every stale module in the
compile got an untyped stub. Such an object is now a mapping of any
value, and a parameter whose classification throws accepts any value
instead of failing the whole run.
Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
A tuple with an optional element, `[string, string?]`, classified its
items as `str` and the union `None | str`, and `union` kept the inner
union as a member, so the stub read `_str | _str | None` and split a
union's literals around it. A union member now adds its members, each
once, so the items are `_str | None` and `["b", ("c" | "a")?]` gives
`_Literal["a", "b", "c"] | None`.
Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
…be encoded A JavaScript string literal can hold a lone surrogate, which `_render_literal` copied into the stub as it was, so writing the stub raised UnicodeEncodeError, not an OSError, and aborted the dev compile. It is now escaped as `\ud800`, which Python reads back as the same string, and the rest of the literal stays as it is. `_write_stub` warns about an encode error, as it does an OSError, instead of raising. `write_file` read an existing file as UTF-8 to skip an unchanged write, so a stub with Reflex's header and bytes that are not UTF-8 after it aborted the compile too: such a file now differs from any content and is replaced. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
…odules per module When script-signatures.js failed or timed out, write_script_stubs rewrote every stale module's stub as one that takes any arguments, so a timeout on a slow machine turned a committed, typed stub into a source diff and lost its checks. A stub already there is now left as it is; only a module without one gets the untyped fallback. Either way its record is cleared, so the next compile reads the types again. script-signatures.js also assumed TypeScript loaded every file it was given, so a module deleted between the parse and the stub step threw and failed the run for all of them. It now leaves out a module it finds no file for, and the compiler warns about that module alone, leaving the others typed. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
Only `.web/script_stubs.json` told the compiler which stubs it wrote, so deleting `.web` and then a module left its generated stub in the source tree, where it kept type checkers accepting an import that fails. Each compile now also looks in the directories of the modules the app imports or the record lists, and removes a stub whose header names a module that no longer exists. Only those directories are listed, a stub of an imported module is never touched, and a `.pyi` without Reflex's header, such as one written by hand, is kept as before. The docs say when a stub is removed, which one stays without the record, and that stubs are generated and safe to commit, delete or ignore. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
…win-dx76ek-js-stubs Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf # Conflicts: # reflex/compiler/utils.py # tests/integration/tests_playwright/test_call_script.py
|
Thanks @masenf. Addressed; each test below failed before its fix. #7950's fixes are merged in (919c301).
Checks on the merged branch:
Generated by Claude Code |
A formatter rewrote a committed stub, and the next compile wrote it back, so the two changed the file in turn. The lines after the header now turn off ruff, black and isort for the stub.
A var passed for a literal type must hold that literal type, and a string[] parameter also accepts a single string.
When an import also pinned the package, as the typescript that reads the types of JavaScript modules does, both pins reached the package manager, which kept whichever came first in set order. The pin in frontend_packages now replaces the import's.
…win-dx76ek-js-stubs Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
…win-dx76ek-js-stubs Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf # Conflicts: # reflex/compiler/compiler.py # tests/units/compiler/test_compiler.py
…win-dx76ek-js-stubs The base types each export of a JavaScript module as an EventHandler, so the uncalled form with an event action, such as echo.debounce(300), type-checks. The stubs here typed each export as a function, which has no event actions. Each export with a signature is now a private EventHandler subclass whose __call__ takes the typed positional arguments and returns EventSpec, so an event action returns that subclass and the call stays typed. An export with no signature is a bare EventHandler, as in the base. tests/type_checking/js.py checks these types with assert_type against jsdoc.pyi, the stub of the jsdoc.js fixture, which test_stubs.py keeps equal to what Reflex renders.
Type of change
Description
Third of the ENG-9127 stack, on top of #7950.
Problem. Python can now import a JavaScript module's functions, but nothing checks the calls. A wrong argument type, or a missing argument, shows up only in the browser.
Change. In dev mode, Reflex writes a type stub (
party.pyi) next to each imported JS/TS module, so pyright and mypy check every call:becomes
Argument types come from TypeScript annotations or, in
.jsfiles, from JSDoc. The TypeScript checker classifies each type. Nothing is parsed out of printed type strings.stringstr(also accepts an event handler, which is sent as its name)number/booleanfloat/boolT[], tuplesSequence[...]Record<string, T>Mapping[str, T]Literal[...]Set,Map,bigint,Promise, functions, classes, DOM types, untypedAny, because arguments arrive as JSONRules.
(*args: Any). Names re-exported withexport *are not declared; re-export them by name.reflex.lock/is the same afterreflex runandreflex export. It never reaches the browser bundle..pyiextension is ignored by hot reload, so writing a stub doesn't restart the backend.# Generated by Reflex from party.ts; do not edit., so a Reflex upgrade, a port change or a fresh clone rewrites nothing whose declarations are the same. What decides whether TypeScript runs again (the module's files, the app files and package.json of the packages its types read, the Reflex version and the generator) is cached in.web/script_stubs.json, not in the committed stub. A stub without the marker is the user's and is never touched. To regenerate one by hand, delete it..pyiis never touched.import("…"),/// <reference>,import type,.d.ts) count toward the stub but are never copied into.web, and never raise the outside-the-package error.Design.
script-signatures.jsstays separate from #7950'sscript-modules.js. It needs typescript and is slow, so it runs only for modules whose digest changed. A steady compile doesn't start it: 0.47 s against 1.07 s when it re-reads types. Merging the two would load typescript on every compile, production included.Warnings. Each states the problem, its cause and the fix. When the types can't be read, the stubs accept any arguments and the app still runs:
Tests
script-signatures.jsfrom a fixture that vitest also checks. The failure paths run a real subprocess: a non-zero exit and a timeout. The digest is compared exactly, orphaned stubs are removed, and a production compile writes no stub. One test runs both real scripts from a.tsand a JSDoc module through to the stub. It needs the frontend packages, so it is skipped where they are not installed.script-signatures.jsis fully covered.test_call_script.py: the stub generated for a module is checked against its exact text.npm run checkare clean.https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf