Skip to content

Generate Typescript types for Rust JSG Bindings - #8077

Merged
nathanwhit merged 3 commits into
mainfrom
nathanwhit/rust-rtti
Nov 3, 2026
Merged

nathanwhit merged 3 commits into
mainfrom
nathanwhit/rust-rtti

Conversation

@nathanwhit

@nathanwhit nathanwhit commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

Motivation

@cloudflare/workers-types is generated from the RTTI export (workerd:rtti), which only knows about C++ bindings. Rust modules register a callback the exporter can't inspect, and its overload for them is a TODO that does nothing. As more APIs are written in Rust, they need to show up in the generated types like C++ ones do.

Design

1. Members are added to a registry

To describe a resource, the RTTI export needs the list of members that the resource's JavaScript class actually gets.
Resource::members now
adds each member to a registry instead of returning a list, like the Registry parameter of C++ registerMembers:

// before
fn members(flags: compatibility_flags::Reader<'_>) -> Vec<Member>
// after
fn members(registry: &mut impl MemberRegistry, flags: compatibility_flags::Reader<'_>)

Template creation and the RTTI export run the same members, each with its own registry. Template creation keeps the
callbacks and never builds a type description; RTTI keeps the type descriptions and never builds a callback. So the
TypeScript declarations match what each resource registers under the export's compatibility flags, including choices like
those above.

2. TypeInfo describes Rust types

jsg::TypeInfo describes how a Rust type looks in JavaScript, using the existing rtti.capnp schema and without an isolate. #[jsg_resource], #[jsg_struct] and #[jsg_oneof] generate the implementation; built-in and custom conversion types implement it by hand. The types/ generator is unchanged.

#[jsg_struct(name = "LookupResult")]
struct ResultData {
    pub label: String,
    pub detail: jsg::Nullable<String>,
}

#[jsg_resource(name = "Example", ts_root)]
struct Example;

#[jsg_resource]
impl Example {
    #[jsg_method(name = "lookup")]
    fn lookup_value(&self, label: String, detail: jsg::Nullable<String>) -> jsg::Result<ResultData> { /* ... */ }

    #[jsg_method]
    fn hint(&self, hint: Option<jsg::Nullable<String>>) -> Option<jsg::Nullable<String>> { /* ... */ }

    #[jsg_property(prototype, name = "title", readonly)]
    fn get_label(&self) -> String { /* ... */ }
}
interface LookupResult {
  label: string;
  detail: string | null;
}
declare class Example {
  lookup(label: string, detail: string | null): LookupResult;
  hint(hint?: string | null): string | null | undefined;
  get title(): string;
}

Here are the type translations:

Rust TypeScript
Option<T> T | undefined (optional)
jsg::Nullable<T> T | null (input also reads undefined as null; the parameter is required)
jsg::NullOrUndefined<T>, jsg::Lenient<T> T | null | undefined (optional)
Vec<T>, &[T] T[] (numbers included)
jsg::Dict<V> Record<string, V>
v8::Local<v8::Uint8Array> and other typed arrays Uint8Array, etc.
Result<T, E> T
SystemTime Date (arguments also accept number)
v8::Local<v8::Date> Date
i64, u64, v8::Local<BigInt> number | bigint (as C++ describes int64_t)
v8::Local<Promise> Promise<any> (arguments also accept plain values, as in C++)

3. Module types are included in the export

To describe a module, the exporter needs its exports type without running the module. So module callbacks now return the exports resource, and registration converts it to JS:

// before
jsg::modules::add_builtin(registry, "node-internal:dns", |lock| DnsUtil::new().to_js(lock), ModuleType::Internal);
// after
jsg::modules::add_builtin(registry, "node-internal:dns", |_lock| Ok(DnsUtil::new()), ModuleType::Internal);

Callbacks still capture nothing, and an error a callback returns is still thrown to the importer.

Registration passes the C++ registry a second function pointer next to the callback, which describes the exports type. RustModuleRegistry uses an if constexpr to check whether the wrapped registry has addRustBuiltinModule; only the exporter does.

  • The exporter calls the describe pointer and never runs the module. It describes every Rust module into one shared context under the export's compatibility flags, then adds the result to the C++ types and modules.
  • Runtime registries ignore the describe pointer.

Commits

  1. Register Rust resource members through a MemberRegistry. Runtime only; contains the API change.
  2. Describe Rust JSG bindings through TypeInfo.
  3. Include Rust module types in the RTTI export.

Not in this PR

  • JSG_TS_OVERRIDE / JSG_TS_DEFINE equivalents: a follow-up PR.

@nathanwhit
nathanwhit requested review from a team as code owners October 28, 2026 21:53
@nathanwhit
nathanwhit requested a review from edmundhung October 28, 2026 21:53
@clanky-the-clanker

clanky-the-clanker Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

This pull request's reviews are posted as pull request reviews: see the review of 7e5be9c5.

@ask-bonk

ask-bonk Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Since last review: 2 resolved, 0 still open, 0 new.
LGTM!

Not re-run: kj-style (no author changes in their files since the last review)


Reviewed commit: b8b3d091 · github run

Comment thread src/rust/jsg-macros/resource.rs Resolved
Comment thread src/rust/jsg-macros/lib.rs Resolved
@nathanwhit
nathanwhit force-pushed the nathanwhit/rust-rtti branch 2 times, most recently from b8b3d09 to 3b8788e Compare October 28, 2026 23:00
@codecov-commenter

codecov-commenter commented Oct 28, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 69.12442% with 134 lines in your changes missing coverage. Please review.
✅ Project coverage is 68.45%. Comparing base (fef2309) to head (4dab5f4).

Files with missing lines Patch % Lines
src/rust/jsg/rtti.rs 64.33% 97 Missing ⚠️
src/workerd/api/api-rtti-test.c++ 75.86% 0 Missing and 14 partials ⚠️
src/rust/jsg/feature_flags.rs 0.00% 12 Missing ⚠️
src/rust/jsg/resource.rs 80.85% 9 Missing ⚠️
src/workerd/api/rtti.c++ 92.30% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #8077      +/-   ##
==========================================
- Coverage   68.46%   68.45%   -0.01%     
==========================================
  Files         731      732       +1     
  Lines      191130   191548     +418     
  Branches    29842    29871      +29     
==========================================
+ Hits       130854   131124     +270     
- Misses      42785    42916     +131     
- Partials    17491    17508      +17     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@guybedford guybedford left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, this is a great start in the right direction to iterate on. Running the same members() registration for both template creation and RTTI is a nice way to keep the types in line with what each resource registers under a given set of flags.

Comment thread src/rust/jsg/resource.rs Resolved
Comment thread src/rust/jsg/rtti.rs Resolved
@nathanwhit
nathanwhit force-pushed the nathanwhit/rust-rtti branch 2 times, most recently from da05ca2 to 7e5be9c Compare November 2, 2026 21:53

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the review of 17a18708.

This review, of 7e5be9c5

💬 Approved with comments — Nothing changed since the last review is unsafe to merge. One INFO note: a v8::Local<v8::BigInt> parameter is declared more permissively than the runtime accepts, and nothing uses it as a parameter yet.

Findings: 1 info (1 is an inline comment on the diff)

Not opened by the correctness review: 4 changed files it was meant to read
  • src/rust/jsg-cpp/ffi.rs
  • src/rust/jsg/lib.rs
  • src/workerd/io/io-context/BUILD.bazel
  • types/src/generator/type.ts

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


📋 Code Quality: 💬 1 info

One INFO note on how v8::BigInt is described as a parameter; everything else is consistent.

Recommendation: 💬 Optional Nits

  • [INFO] A v8::Local<v8::BigInt> parameter is declared number | bigint, but conversion accepts only a BigInt. (src/rust/jsg/rtti.rs:554)
View full review
  • CppResource::fully_qualified_name: every implementor implements it. The TypeInfo for Ref<T> impl refers to the C++ class's description by that name.
  • Resource::members(registry, flags), add_builtin and addBuiltinModule: every caller and override uses the new forms.
  • rtti.c++: the Rust RTTI context is encoded once and appended. setWithCaveats copies the data, so the reader's lifetime is safe.
  • Macros: the offsets for this and the lock are correct. Duplicate parameter names are a compile error. Only public struct fields are described, which matches what to_js and from_js convert.
  • One note: v8::Local<v8::BigInt> is described as jsg::JsBigInt (number | bigint), which is wider than what conversion accepts when it is a parameter.

✅ All other checks passed

🔒 Security: ✅ LGTM

The change describes types for the RTTI export and changes how module exports are registered. No untrusted input reaches new code, and it does not touch authentication or authorization.


📖 AGENTS.md: ✅ LGTM

No new issues. One note from earlier reviews is still open.


⚡ Performance: ✅ LGTM

The runtime cost does not change. Only the RTTI exporter builds type descriptions.


📝 Documentation: ✅ LGTM

The README updates match the members(registry, flags) API, the module callback shape, ts_root and the TypeInfo mappings.


Reviewed commit: 7e5be9c5

Comment thread src/rust/jsg/rtti.rs Resolved
@nathanwhit
nathanwhit force-pushed the nathanwhit/rust-rtti branch from 7e5be9c to 17a1870 Compare November 2, 2026 21:57

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the review of dcc716be.

This review, of 17a18708

💬 Approved with comments — The changes to src/rust/jsg/rtti.rs since the last review introduce no new problems. One INFO note remains: a v8::Local<v8::BigInt> parameter is declared more permissively than the runtime accepts, but nothing takes one as a parameter yet.

Findings: 1 info

Not opened by the correctness review: 3 changed files it was meant to read
  • src/rust/jsg-cpp/ffi.rs
  • src/rust/jsg/lib.rs
  • src/workerd/io/io-context/BUILD.bazel

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


📋 Code Quality: 💬 1 info

One INFO note remains open. The changes to rtti.rs introduce no new problems.

Recommendation: 💬 Optional Nits

  • [INFO] A v8::Local<v8::BigInt> parameter is declared number | bigint, but conversion accepts only a BigInt. (src/rust/jsg/rtti.rs:555)
View full review
  • src/rust/jsg/rtti.rs:555 (primitive!(v8::BigInt, Type::BigInt)) is encoded as jsg::JsBigInt (line 297), and the generator declares that type as number | bigint. When the type is a parameter, conversion accepts only a real BigInt, so the declaration is wider than what the runtime accepts. @​edmundhung [approver] raised the same point. Nothing takes this type as a parameter yet, so it does not block the change.

The other changes in this revision look correct and match the coverage in rtti-test.rs and rust.spec.ts: the i64/u64 handling, the interning in Context::structure, the registry-based member description and the guard against nested-type cycles in write_structure.


✅ All other checks passed

🔒 Security: ✅ LGTM

The change describes types for the RTTI export and changes how module exports are registered. No untrusted input reaches the new code.


📖 AGENTS.md: ✅ LGTM

The updates to src/rust/AGENTS.md and types/AGENTS.md match the change.


⚡ Performance: ✅ LGTM

The new code runs only in the RTTI export, not at request time. A guard stops nested structures from cycling, and the interning lookups take constant time.


📝 Documentation: ✅ LGTM

The README updates match the members(registry, flags) API, the module callback shape, ts_root and the TypeInfo mappings.


Reviewed commit: 17a18708

@nathanwhit
nathanwhit force-pushed the nathanwhit/rust-rtti branch from 17a1870 to dcc716b Compare November 2, 2026 22:36

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the review of ca6dceb1.

This review, of dcc716be

✅ Approved — Nothing changed since the last review has a problem. The only open item is an earlier informational note about how a BigInt parameter is declared, and nothing uses that type as a parameter yet.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

The changed code builds type descriptions for the RTTI export. No untrusted input reaches it.


📖 AGENTS.md: ✅ LGTM

The updates to src/rust/AGENTS.md and types/AGENTS.md match the change.


📋 Code Quality: ✅ LGTM

Checked and correct:

  • Module registration: the trampoline converts the module's exports with callback(lock).and_then(|e| e.to_js(lock)). Errors from the callback and from the conversion are both still thrown to the importer.
  • C++ registry: RustModuleRegistry uses if constexpr to choose between describing a module and adding it to a runtime registry. Runtime registries ignore the describe pointer.
  • RTTI export merge: the Rust groups and modules are appended to the export, and both counts include them. The message is checked to be a whole number of Cap'n Proto words before it is copied into a word-aligned array.
  • Structure interning: Context::structure adds a type before it visits the type's members, so resources that refer to each other are handled. write_structure stops when a nested type refers back to itself.
  • Build wiring: the proc_macro_deps added in src/workerd/io/io-context/BUILD.bazel and the fully_qualified_name requirement in src/rust/jsg-cpp/ffi.rs match how the code uses them.

One earlier note is still open: a v8::Local<v8::BigInt> parameter is declared wider than the runtime accepts (src/rust/jsg/rtti.rs:557).


⚡ Performance: ✅ LGTM

The new code runs only in the RTTI export, at build time, not when a request is handled. Interning uses hash map lookups, and the cycle guard means describing nested structures always finishes.


📝 Documentation: ✅ LGTM

The READMEs match the code: the members(registry, flags) API, the module callback shape, ts_root and the TypeInfo mappings.


Reviewed commit: dcc716be

Resource::members adds each member to a registry, members(registry,
flags), instead of returning a Vec<Member>, like the Registry parameter
of C++ registerMembers. Generated member factories return
`impl jsg::MemberDefinition`, which template creation builds into a
Member; a hand-built Member is also a MemberDefinition.

This prepares for RTTI: an RTTI registry can run the same registration
code and collect type descriptions instead of callbacks, so TypeScript
declarations follow the members a resource registers under a given set
of compatibility flags.
@nathanwhit
nathanwhit force-pushed the nathanwhit/rust-rtti branch from dcc716b to ca6dceb Compare November 3, 2026 01:59

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the review of 4dab5f49.

This review, of ca6dceb1

✅ Approved — Nothing changed since the last review has a problem. The only open item is an earlier informational note about how a BigInt parameter is declared, and nothing uses that type as a parameter yet.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

The changed code builds type descriptions for the RTTI export. No untrusted input reaches it.


📖 AGENTS.md: ✅ LGTM

The updates to src/rust/AGENTS.md and types/AGENTS.md match the change.


📋 Code Quality: ✅ LGTM

Checked and correct:

  • Module registration: the trampoline converts the module's exports with callback(lock).and_then(|e| e.to_js(lock)). Errors from the callback and from the conversion are both still thrown to the importer.
  • C++ registry: RustModuleRegistry uses if constexpr to choose between describing a module and adding it to a runtime registry. Runtime registries ignore the describe pointer.
  • RTTI export merge: the Rust groups and modules are appended to the export, and both counts include them. The message is checked to be a whole number of Cap'n Proto words before it is copied into a word-aligned array.
  • Structure interning: Context::structure adds a type before it visits the type's members, so resources that refer to each other are handled. write_structure stops when a nested type refers back to itself.
  • Build wiring: the proc_macro_deps added in src/workerd/io/io-context/BUILD.bazel and the fully_qualified_name requirement in src/rust/jsg-cpp/ffi.rs match how the code uses them.

One earlier note is still open: a v8::Local<v8::BigInt> parameter is declared wider than the runtime accepts (src/rust/jsg/rtti.rs:557).


⚡ Performance: ✅ LGTM

The new code runs only in the RTTI export, at build time, not when a request is handled. Interning uses hash map lookups, and the cycle guard means describing nested structures always finishes.


📝 Documentation: ✅ LGTM

The READMEs match the code: the members(registry, flags) API, the module callback shape, ts_root and the TypeInfo mappings.


Reviewed commit: ca6dceb1 — same changes as dcc716be, so this is that commit's review (no new review was run; line numbers are as of dcc716be)

Add jsg::TypeInfo, which describes a binding type's JavaScript
representation in the shared rtti.capnp schema without an isolate.
#[jsg_resource], #[jsg_struct] and #[jsg_oneof] generate it; built-in
conversion types implement it by hand, as custom conversion types must.

A resource is described with the members it registers. Member factories
return a definition that can both build the member and describe it, and
RTTI runs Resource::members with its own registry under the
compatibility flags of the jsg::rtti::Context, as C++ runs
registerMembers with the RTTI builder's flags. Template creation never
runs the descriptions, and RTTI never builds callbacks. As in C++, a
nested type is described with its whole structure, through which the
generator reaches it, and inspect properties, wildcard properties and
other hand-built members have no description.

The Context interns named types by TypeId before describing their
members, so shared and recursive types are emitted once. Their type
names identify them to the generator, so two types with one type name
are rejected.
Declaration names follow `name = "..."` separately, and ts_root marks a
root of the ambient declarations, like JSG_TS_ROOT. Parameter names are
camelCased, lose unused-parameter underscores and escape TypeScript
reserved words; parameters whose names collide are rejected.

Cover the mappings with an end-to-end test that runs a Rust fixture's
RTTI through the types/ generator and type-checks the result. The
fixture runs as test data in the target configuration, to avoid building
V8 again as an exec-configuration tool. Teach the formatter to cover
Rust sources under types/.
The RTTI export could not describe Rust builtin modules: they register
an opaque callback, and its EncoderModuleRegistryImpl overload for
module callbacks does nothing.

Have module callbacks return their exports resource, jsg::Result<Rc<T>>,
which registration converts, so the exports type is known statically.
Registration passes the C++ registry a second function pointer next to
the callback, which describes T in a jsg::rtti::Context. The
RustModuleRegistry adapter hands it to registries that define
addRustBuiltinModule, which only the workerd:rtti encoder does, and
runtime registries ignore it. The encoder thus collects every module's
types in one Context, under the export's compatibility flags, without
running module code, and merges the encoded groups and modules with the
C++ ones. Callbacks still capture nothing, and an error one returns is
still thrown to the importer.

api-rtti-test checks that the export discovers node-internal:dns, its
exports type and the structs that type returns.
@nathanwhit
nathanwhit force-pushed the nathanwhit/rust-rtti branch from ca6dceb to 4dab5f4 Compare November 3, 2026 02:43

@clanky-the-clanker clanky-the-clanker Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💬 Approved with comments — Nothing changed since the last review has a problem. The only open item is an earlier INFO about how a BigInt parameter is declared, which is deferred to a follow-up and affects no existing API.

Findings: 1 info (1 is an inline comment on the diff)

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


📋 Code Quality: 💬 1 info

No new problems. One earlier INFO about BigInt parameter typing is still open and deferred to a follow-up.

Recommendation: 💬 Optional Nits

  • [INFO] A v8::Local<v8::BigInt> parameter is declared number | bigint, but conversion accepts only a BigInt. Deferred by @​nathanwhit [author] to a follow-up as an existing generator bug that also affects C++; nothing takes this type as a parameter yet. (src/rust/jsg/rtti.rs:554)
View full review

Checked at this commit and correct:

  • Module trampoline: errors from the callback and from the to_js conversion are both thrown to the importer. Runtime registries ignore the describe pointer, and the if constexpr branch picks the exporter correctly.
  • RTTI export merge: registerModules runs before groups are counted, so the Rust groups and modules are included in both counts. The size check comes before the word-aligned copy.
  • Macro expansion: jsg_struct describes the same public fields it projects to JS. describe_args skips this and the lock in the same way the callbacks do, and colliding parameter names are rejected at compile time, which a compile test covers. Property readonly and prototype settings match the generated member factory.
  • Cycle handling: a structure is interned before its members are visited, and write_structure stops when a type nests itself.
  • Generator test: the assertions in types/test/generator/rust.spec.ts match the fixture in types/rtti-fixture/main.rs.

Still open: a v8::Local<v8::BigInt> parameter is declared wider than the runtime accepts. @​nathanwhit [author] says this is an existing generator bug that also affects C++ bindings and will be fixed in a follow-up.


✅ All other checks passed

🔒 Security: ✅ LGTM

The changed code builds type descriptions for the RTTI export at build time, and no untrusted input reaches it. The byte copy in src/workerd/api/rtti.c++ is guarded by a check that the message is a whole number of Cap'n Proto words.


📖 AGENTS.md: ✅ LGTM

The updates to src/rust/AGENTS.md and types/AGENTS.md match the change.


⚡ Performance: ✅ LGTM

The new code runs only during the RTTI export at build time, never while a request is handled.


📝 Documentation: ✅ LGTM

The updated src/rust/jsg-macros/README.md matches the macro behaviour at this commit.


Reviewed commit: 4dab5f49

Comment thread src/rust/jsg/rtti.rs Resolved
@nathanwhit
nathanwhit merged commit e95bded into main Nov 3, 2026
23 of 24 checks passed
@nathanwhit
nathanwhit deleted the nathanwhit/rust-rtti branch November 3, 2026 03:39
bartlomieju added a commit that referenced this pull request Nov 9, 2026
The C++ Hyperdrive stays registered with the isolate, so the RTTI export describes it while the
RUST_HYPERDRIVE autogate makes bindings of the Rust one. The parity test pins what runs, but not
what only the types say, such as argument and return types.

rtti-test.c++ compares the C++ jsg::rtti::Builder's Structure for api::Hyperdrive with the one
the Rust Hyperdrive describes through jsg::TypeInfo (#8077), which a testonly bridge crate,
rtti-test-bridge, encodes. Both are compared as the TypeScript generator reads them: without the
fully qualified name and tsName, the C++ jsg::Lock argument, the C++ type names of strings and
numbers, fastApiCompatible and argNames, and with members in name order, since the Rust macro
registers methods before properties. Neither order is observable in JS, and the generated types
take Hyperdrive's member order from types/defines/hyperdrive.d.ts.

The hyperdrive crate now lists its sources, so that it does not compile the bridge.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants