Skip to content

fix(napi-derive): add paren for function types - #3044

Merged
Brooooooklyn merged 1 commit into
mainfrom
12-02-fix_napi-derive_add_paren_for_function_types
Dec 2, 2025
Merged

Brooooooklyn merged 1 commit into
mainfrom
12-02-fix_napi-derive_add_paren_for_function_types

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Dec 2, 2025 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features
    • Added optionalCallbackTypes() function supporting optional callback parameters that can be undefined or null.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Dec 2, 2025 •

Copy link
Copy Markdown

Walkthrough

This PR adds support for optional callback types in NAPI bindings. It modifies type generation logic to handle Option for struct fields differently, implements a new Rust function accepting optional callbacks, and exports this functionality across multiple JavaScript module systems with TypeScript declarations.

Changes

Cohort / File(s) Summary
Type Generation Logic
crates/backend/src/typegen.rs
Modified handle_option_type to immediately return for struct-field options, bypassing additional arg transformations. Non-struct cases with "=>" now wrap arguments as parenthesized expressions.
Rust Implementation
examples/napi/src/function.rs
Added new optional_callback_types function accepting Option<Function<String, UnknownReturnValue>> and invokes callback with "Hello" if provided. Updated imports to include UnknownReturnValue.
Module Exports
examples/napi/index.cjs
examples/napi/example.wasi.cjs
examples/napi/example.wasi-browser.js
Exposed optionalCallbackTypes export across CommonJS, WASI, and browser module systems, routing from native bindings.
TypeScript Type Definitions
examples/napi/index.d.cts
Added function declaration: export declare function optionalCallbackTypes(callback?: ((arg: string) => unknown) | undefined | null): void
Tests & Snapshots
examples/napi/__tests__/values.spec.ts
examples/napi/__tests__/__snapshots__/values.spec.ts.md
Added test cases verifying optionalCallbackTypes invocation with zero or one callback argument. Updated snapshot with new export declaration.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

  • crates/backend/src/typegen.rs: Requires careful review of control flow changes in handle_option_type to ensure struct-field options bypass transformations correctly and non-struct callback syntax preservation works as intended.
  • examples/napi/src/function.rs: Verify that optional callback handling and invocation logic is sound; confirm UnknownReturnValue import usage is correct.
  • Module export consistency: Confirm optionalCallbackTypes is consistently exposed across all module systems (CommonJS, WASI, browser) without missing bindings.

Poem

🐰 A callback that's optional, now that's quite the sight!
Through struct fields and WASI, TypeScript shines so bright,
From Rust to JavaScript, the binding flows with grace,
Optional arguments dancing through each export place!

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding parentheses for function types in napi-derive, which is evidenced by the typegen.rs modification that wraps callback arguments with parentheses when they contain '=>'.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 12-02-fix_napi-derive_add_paren_for_function_types

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Member Author

How to use the Graphite Merge Queue

Add either label to this PR to merge it via the merge queue:

  • ready-to-merge - adds this PR to the back of the merge queue
  • hotfix - for urgent hot fixes, skip the queue and merge this PR next

You must have a Graphite account in order to use the merge queue. Sign up using this link.

An organization admin has enabled the Graphite Merge Queue in this repository.

Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue.

This stack of pull requests is managed by Graphite. Learn more about stacking.

@coderabbitai coderabbitai 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.

Actionable comments posted: 0

🧹 Nitpick comments (1)
examples/napi/__tests__/values.spec.ts (1)

294-295: Tests exercise presence and basic calling of optionalCallbackTypes

The import and t.notThrows checks validate that the function is exported and callable both with and without a callback, which is a good minimal smoke test.

You might optionally strengthen this by asserting the callback is actually invoked with the expected "Hello" argument (e.g., via a spy), but it's not strictly necessary for this fix.

Also applies to: 536-539

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a673471 and 284e409.

⛔ Files ignored due to path filters (1)
  • examples/napi/__tests__/__snapshots__/values.spec.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (8)
  • crates/backend/src/typegen.rs (1 hunks)
  • examples/napi/__tests__/__snapshots__/values.spec.ts.md (1 hunks)
  • examples/napi/__tests__/values.spec.ts (2 hunks)
  • examples/napi/example.wasi-browser.js (1 hunks)
  • examples/napi/example.wasi.cjs (1 hunks)
  • examples/napi/index.cjs (1 hunks)
  • examples/napi/index.d.cts (1 hunks)
  • examples/napi/src/function.rs (2 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: CR
Repo: napi-rs/napi-rs PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-25T09:31:23.877Z
Learning: Applies to /crates/**/*.rs : Use `#[napi]` attribute on impl blocks to define classes exported to JavaScript/TypeScript
Learnt from: CR
Repo: napi-rs/napi-rs PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-25T09:31:23.877Z
Learning: Applies to /crates/**/*.rs : Use `#[napi(object)]` attribute for plain objects that should be mapped to TypeScript interfaces
Learnt from: CR
Repo: napi-rs/napi-rs PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-25T09:31:23.877Z
Learning: Applies to /crates/**/*.rs : Use `#[napi(js_name = "...")]` attribute to rename Rust items in JavaScript/TypeScript
📚 Learning: 2025-11-25T09:31:23.877Z
Learnt from: CR
Repo: napi-rs/napi-rs PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-25T09:31:23.877Z
Learning: Applies to /crates/**/*.rs : Use `#[napi]` attribute on impl blocks to define classes exported to JavaScript/TypeScript

Applied to files:

  • examples/napi/src/function.rs
  • examples/napi/example.wasi.cjs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (39)
  • GitHub Check: Build only test - riscv64gc-unknown-linux-gnu
  • GitHub Check: Build only test - loongarch64-unknown-linux-gnu
  • GitHub Check: Build only test - armv7-linux-androideabi
  • GitHub Check: Test node wasi target (--cfg tokio_unstable)
  • GitHub Check: Build only test - aarch64-unknown-linux-ohos
  • GitHub Check: x86_64-unknown-linux-gnu - node@24 - toolchain@ 1.88.0
  • GitHub Check: Test node wasi target
  • GitHub Check: stable - armv7-unknown-linux-gnueabihf - node@22
  • GitHub Check: Build only test - aarch64-linux-android
  • GitHub Check: i686-pc-windows-msvc - node@24 - toolchain@ stable
  • GitHub Check: build - x86_64-unknown-linux-gnu
  • GitHub Check: aarch64-apple-darwin - node@24 - toolchain@ stable
  • GitHub Check: x86_64-pc-windows-msvc - node@24 - toolchain@ stable
  • GitHub Check: build - aarch64-unknown-linux-gnu
  • GitHub Check: build - s390x-unknown-linux-gnu
  • GitHub Check: build - powerpc64le-unknown-linux-gnu
  • GitHub Check: aarch64-pc-windows-msvc - node@24 - toolchain@ stable
  • GitHub Check: i686-pc-windows-msvc - node@22 - toolchain@ stable
  • GitHub Check: x86_64-unknown-linux-gnu - node@22 - toolchain@ 1.88.0
  • GitHub Check: x86_64-unknown-linux-gnu - node@24 - toolchain@ stable
  • GitHub Check: x86_64-pc-windows-msvc - node@22 - toolchain@ stable
  • GitHub Check: aarch64-apple-darwin - node@22 - toolchain@ stable
  • GitHub Check: aarch64-pc-windows-msvc - node@22 - toolchain@ stable
  • GitHub Check: x86_64-pc-windows-msvc - node@20 - toolchain@ stable
  • GitHub Check: x86_64-unknown-linux-gnu - node@22 - toolchain@ stable
  • GitHub Check: aarch64-apple-darwin - node@20 - toolchain@ stable
  • GitHub Check: x86_64-unknown-linux-gnu - node@20 - toolchain@ stable
  • GitHub Check: build - x86_64-unknown-linux-musl
  • GitHub Check: build - aarch64-unknown-linux-musl
  • GitHub Check: Test freebsd target
  • GitHub Check: build-and-test-msys2 (UCRT64)
  • GitHub Check: build-and-test-msys2 (CLANG64)
  • GitHub Check: build-and-test-msys2 (MINGW64)
  • GitHub Check: ASAN - windows-latest
  • GitHub Check: ASAN - ubuntu-24.04
  • GitHub Check: Zig-Cross-Compile-On-Linux (aarch64-unknown-linux-musl)
  • GitHub Check: Memory leak detect job
  • GitHub Check: Zig-Cross-Compile-On-Linux (armv7-unknown-linux-musleabihf)
  • GitHub Check: Zig-Cross-Compile-On-Linux (aarch64-apple-darwin)
🔇 Additional comments (8)
examples/napi/src/function.rs (2)

3-5: Importing UnknownReturnValue is appropriate

The added import matches its use in optional_callback_types and the KNOWN_TYPES mapping; no issues.


152-160: optional_callback_types implementation looks correct

The API cleanly accepts an optional JS callback, calls it synchronously with "Hello" when present, and propagates JS errors via ?. Using Function<String, UnknownReturnValue> aligns with the index.d.cts declaration and keeps the return unconstrained.

Based on learnings, using #[napi] here correctly exposes this function to JS/TS.

crates/backend/src/typegen.rs (1)

476-500: Verify Option struct-field semantics and function-type parens

  • For non-struct uses, wrapping arg in ({arg}) when it contains => correctly fixes Option<fn> into ((...) => ...) | undefined | null instead of a union on the return type.
  • For struct fields, Option<T> now yields (arg.to_string(), true) directly, so TS becomes field?: T instead of field?: T | undefined | null. This is more idiomatic but slightly changes generated typings for all struct Option<T> fields.

Please confirm that this changed struct-field behavior (dropping explicit | undefined | null) is intentional and covered by snapshots, and that arg.contains("=>") is sufficient for all function-shaped Option arguments you care about.

examples/napi/example.wasi-browser.js (1)

300-304: WASI browser export wiring is consistent

optionalCallbackTypes is exported in the same pattern as neighboring bindings; wiring looks correct.

examples/napi/index.cjs (1)

809-813: CJS export for optionalCallbackTypes is correctly wired

The new property mirrors existing exports and forwards directly to the native binding; no issues.

examples/napi/index.d.cts (1)

891-899: optionalCallbackTypes declaration matches Rust & typegen logic

The declared type callback?: ((arg: string) => unknown) | undefined | null correctly reflects Option<Function<String, UnknownReturnValue>> with the fixed parentheses around the function type and a void return for Result<()>.

examples/napi/example.wasi.cjs (1)

345-349: WASI CJS export for optionalCallbackTypes is consistent

The new module.exports.optionalCallbackTypes binding follows the established export pattern; looks good.

examples/napi/__tests__/__snapshots__/values.spec.ts.md (1)

931-939: Snapshot update correctly reflects new API surface

The added snapshot entry for optionalCallbackTypes(callback?: ((arg: string) => unknown) | undefined | null): void matches the declaration in index.d.cts and will catch future regressions in Option type rendering.

@Brooooooklyn
Brooooooklyn merged commit 54a9654 into main Dec 2, 2025
@Brooooooklyn
Brooooooklyn deleted the 12-02-fix_napi-derive_add_paren_for_function_types branch December 2, 2025 06:56
@github-actions github-actions Bot mentioned this pull request Dec 2, 2025
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.

1 participant