Skip to content

fix(napi-derive): only FnArgs unpacks tuple to variadic params - #3264

Merged
Brooooooklyn merged 4 commits into
mainfrom
fix/3261-function-tuple-args-typegen
Apr 27, 2026
Merged

Brooooooklyn merged 4 commits into
mainfrom
fix/3261-function-tuple-args-typegen

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Apr 27, 2026 •

Copy link
Copy Markdown
Member

Function<(T1, T2), R>, FunctionRef<(T1, T2), R>, and
ThreadsafeFunction<(T1, T2)> were emitting variadic TypeScript params
as if FnArgs had been used. Without FnArgs, the tuple is serialized
to a single JS array argument at runtime, so the typegen now emits
arg: [T1, T2] for those slots and reserves the variadic expansion
for FnArgs<(T1, T2)> only.

Close #3261

Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]


Note

Medium Risk
Changes core Rust→TypeScript type generation for Function/FunctionRef/ThreadsafeFunction, which can affect downstream typings and may surface new compile errors in consumer code. Runtime behavior is unchanged but mis-typed APIs may require adjustments.

Overview
Fixes typegen for Function<(T1, T2), R>, FunctionRef<(...) , R>, and ThreadsafeFunction<(...)> so tuples are emitted as a single TypeScript argument (e.g. arg: [T1, T2]) instead of being incorrectly expanded into variadic params; only FnArgs<(...)> keeps variadic expansion.

Adds new example exports/tests covering tuple-as-single-arg callbacks and nested function arguments, and updates generated snapshot typings accordingly. Separately, the WASI worker template now only declares errorOutputs when errorEvent handling is enabled (removing an unused variable in the default template).

Reviewed by Cursor Bugbot for commit 48bb33a. Bugbot is set up for automated code reviews on this repo. Configure here.

Summary by CodeRabbit

  • New Features

    • Added tuple-typed callback support across N-API/WASI bindings and four new exported APIs: callWithTupleArg, referenceWithTupleArg, acceptThreadsafeFunctionTupleNoFnArgs, and callWithNestedFunctionArg. TypeScript declarations updated to reflect these signatures.
  • Chores

    • Worker template no longer emits an unused errorOutputs variable unless an error handler is present; minor whitespace/formatting tweaks in examples.

`Function<(T1, T2), R>`, `FunctionRef<(T1, T2), R>`, and
`ThreadsafeFunction<(T1, T2)>` were emitting variadic TypeScript params
as if `FnArgs` had been used. Without `FnArgs`, the tuple is serialized
to a single JS array argument at runtime, so the typegen now emits
`arg: [T1, T2]` for those slots and reserves the variadic expansion
for `FnArgs<(T1, T2)>` only.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Apr 27, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 97f3c7b9-4929-426f-9c31-307bf88ed592

📥 Commits

Reviewing files that changed from the base of the PR and between 73121e7 and 48bb33a.

⛔ Files ignored due to path filters (1)
  • cli/src/api/__tests__/__snapshots__/templates.spec.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (1)
  • cli/src/api/__tests__/__snapshots__/templates.spec.ts.md
💤 Files with no reviewable changes (1)
  • cli/src/api/tests/snapshots/templates.spec.ts.md

📝 Walkthrough

Walkthrough

Tightens backend type generation to distinguish FnArgs<T> from other function-like generics, adds normalization helpers (wrap_fn_like_arg, is_fn_args_path), adjusts lifetime/return-slot logic, and adds example N-API exports and declaration snapshots exercising tuple-shaped and nested-function callback typings.

Changes

Cohort / File(s) Summary
Core Type Generation Logic
crates/backend/src/typegen.rs
Refactors process_generic_arguments to detect FnArgs<T> vs other function-like generics; introduces is_fn_args, is_fn_like, wrap_fn_like_arg, and is_fn_args_path; uses is_fn_like for return-slot logic and only unpacks tuples for FnArgs.
N-API Example Implementations
examples/napi/src/function.rs, examples/napi/src/threadsafe_function.rs
Adds exports exercising tuple and nested-function callback signatures: call_with_tuple_arg, reference_with_tuple_arg, call_with_nested_function_arg, and accept_threadsafe_function_tuple_no_fn_args.
Type Declarations & Snapshots
examples/napi/index.d.cts, examples/napi/__tests__/__snapshots__/values.spec.ts.md
Adds TypeScript declaration entries and snapshot updates for the new exports reflecting tuple-shaped and nested-function callback typings.
JS/WASI Example Wiring
examples/napi/index.cjs, examples/napi/example.wasi.cjs, examples/napi/example.wasi-browser.js
Wires new native exports to JS/WASI wrappers and module exports (adds the four new exported functions); one whitespace-only edit in wasi-worker-browser.mjs.
WASI Worker Template & Snapshot
cli/src/api/templates/wasi-worker-template.ts, cli/src/api/__tests__/__snapshots__/templates.spec.ts.md
Makes errorOutputs emission conditional on errorEvent; snapshot updated to reflect omission when errorEvent is false.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

Poem

🐰 I hopped through generics, sniffed the FnArgs trail,
I nudged tuples gently so callbacks tell the tale,
I wrapped function-like bits and kept the return in sight,
Now TS declarations match the native hop just right,
A tiny rabbit cheer for types that compile bright!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and clearly summarizes the main change: restricting tuple unpacking to only FnArgs generics, not plain Function/ThreadsafeFunction tuples.
Linked Issues check ✅ Passed All code changes address the linked issue #3261: typegen now emits tuple-as-single-arg for Function/ThreadsafeFunction without FnArgs, and reserves variadic expansion for FnArgs only.
Out of Scope Changes check ✅ Passed The errorOutputs template change and snapshot updates are minor supporting changes that align with the broader objective of normalizing empty tuples and template consistency.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/3261-function-tuple-args-typegen

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 changes, fast-track this PR to the front of the merge queue

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.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 512c9676cc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/backend/src/typegen.rs Resolved

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

🧹 Nitpick comments (1)
crates/backend/src/typegen.rs (1)

722-740: Heads-up: the ':' heuristic can mis-detect "already-named" types.

ty.contains(':') is used to skip wrapping when ty looks pre-named, but it also matches inline TS shapes like { foo: number } or Record<K, V>-derived structures that happen to print with a colon. In that case we'd emit (({ foo: number }) => R) instead of (arg: { foo: number }) => R, which is invalid as a TS function-type parameter. This mirrors the same pre-existing heuristic in handle_threadsafe_function_type (line 560), so it's not a regression — just worth keeping in mind for a follow-up if/when inline object types start showing up here. Most user-facing types currently resolve to a bare identifier (struct/class name, primitive, alias), so this is a low-priority nit.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/backend/src/typegen.rs` around lines 722 - 740, The current heuristic
in wrap_fn_like_arg using ty.contains(':') incorrectly treats inline object
types as "already-named" and avoids adding an argument name; change the check to
detect a true TypeScript identifier/qualified/generic name instead of looking
for ':'—e.g., replace the colon test with a validation that ty matches a TS
identifier or dotted/templated identifier pattern (letters/_, $, digits after
first char, optional generics and dot-qualified parts) and only skip wrapping
when that validation succeeds; apply the same fix where the same heuristic is
used in handle_threadsafe_function_type so inline object shapes like "{ foo:
number }" will be wrapped as "arg: { foo: number }" while genuine names like
"MyType" or "Namespace.MyType<T>" remain unwrapped.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@crates/backend/src/typegen.rs`:
- Around line 722-740: The current heuristic in wrap_fn_like_arg using
ty.contains(':') incorrectly treats inline object types as "already-named" and
avoids adding an argument name; change the check to detect a true TypeScript
identifier/qualified/generic name instead of looking for ':'—e.g., replace the
colon test with a validation that ty matches a TS identifier or dotted/templated
identifier pattern (letters/_, $, digits after first char, optional generics and
dot-qualified parts) and only skip wrapping when that validation succeeds; apply
the same fix where the same heuristic is used in handle_threadsafe_function_type
so inline object shapes like "{ foo: number }" will be wrapped as "arg: { foo:
number }" while genuine names like "MyType" or "Namespace.MyType<T>" remain
unwrapped.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d9e94ab4-0286-47c1-909c-d08e06e44fda

📥 Commits

Reviewing files that changed from the base of the PR and between f3466fa and 512c967.

⛔ Files ignored due to path filters (1)
  • examples/napi/__tests__/__snapshots__/values.spec.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (5)
  • crates/backend/src/typegen.rs
  • examples/napi/__tests__/__snapshots__/values.spec.ts.md
  • examples/napi/index.d.cts
  • examples/napi/src/function.rs
  • examples/napi/src/threadsafe_function.rs

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 512c967. Configure here.

Comment thread crates/backend/src/typegen.rs Resolved
Brooooooklyn and others added 2 commits April 27, 2026 11:21
The previous `ty.contains(':')` heuristic in `wrap_fn_like_arg` was too
broad — it skipped wrapping for any inner result containing a colon,
including legitimate function-type-notation like `(arg: number) => number`,
producing invalid TypeScript such as `((arg: number) => number) => R`
for `Function<Function<u32, u32>, R>`.

Replace the heuristic with a syntactic `is_fn_args_path(generic_ty)`
check, since `FnArgs<T>` is the only generic that already produces a
parameter binding form. Adds a regression fixture exercising
`Function<Function<u32, u32>, u32>`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The wasi-worker-browser template emitted `const errorOutputs = []`
unconditionally, but the array is only used inside the `printErr`
override and the `onError` handler — both of which are only generated
when `errorEvent: true`. Without that flag the variable is declared but
never read, which trips lint on regenerated outputs.

Gate the declaration on the same `errorEvent` flag and regenerate the
example's wasi-worker-browser.mjs.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@examples/napi/wasi-worker-browser.mjs`:
- Line 6: Remove the unused top-level declaration errorOutputs (delete the line
"const errorOutputs = []") and also revert the unrelated
trailing-whitespace-only edits in the file so the diff only contains the
intended FnArgs/tuple typegen changes; ensure no other references to
errorOutputs remain and run lint to confirm no no-unused-vars violations.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8514344d-304a-4e2e-bc6a-ac47afd91934

📥 Commits

Reviewing files that changed from the base of the PR and between 512c967 and 0e7091d.

⛔ 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
  • examples/napi/__tests__/__snapshots__/values.spec.ts.md
  • examples/napi/example.wasi-browser.js
  • examples/napi/example.wasi.cjs
  • examples/napi/index.cjs
  • examples/napi/index.d.cts
  • examples/napi/src/function.rs
  • examples/napi/wasi-worker-browser.mjs
✅ Files skipped from review due to trivial changes (2)
  • examples/napi/example.wasi-browser.js
  • examples/napi/index.cjs
🚧 Files skipped from review as they are similar to previous changes (2)
  • examples/napi/index.d.cts
  • examples/napi/src/function.rs

Comment thread examples/napi/wasi-worker-browser.mjs Resolved
The wasi-worker template now only emits `const errorOutputs = []` when
errorEvent is enabled (commit 73121e7). The snapshot for the default
(errorEvent: false) case lagged behind the template change.
@Brooooooklyn
Brooooooklyn merged commit 1ca6522 into main Apr 27, 2026
74 checks passed
@Brooooooklyn
Brooooooklyn deleted the fix/3261-function-tuple-args-typegen branch April 27, 2026 03:49
@github-actions github-actions Bot mentioned this pull request Apr 27, 2026
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.

Function and ThreadsafeFunction not using FnArgs generates wrong type in d.ts

1 participant