Repository navigation
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughAdds input/output generics to middleware and parser types so middleware results carry typed payloads and parse/encode functions accept explicit input types; switches output handling to use an encoder ( Changes
Sequence Diagram(s)sequenceDiagram
participant Procedure
participant MiddlewareChain as Middleware Chain
participant OutputMiddleware
participant EncoderParser as Encoder / Parser
participant Client
Note over Procedure,Client: Output handling with new generics and encoder fallback
Procedure->>MiddlewareChain: returns result (includes data)
MiddlewareChain->>OutputMiddleware: forward result
rect rgb(245,250,255)
Note over OutputMiddleware: createOutputMiddleware<TOutputIn,TOutputOut>\ncasts result.data as TOutputIn
OutputMiddleware->>EncoderParser: encode/parse(data as TOutputIn)
end
rect rgb(235,255,235)
Note over EncoderParser: getEncodeFn / ParseFn\nencodeAsync/encode -> fallback to parse if needed\nTInput β TOutput
EncoderParser-->>OutputMiddleware: encoded/parsed value (TOutputOut)
end
OutputMiddleware->>Client: deliver transformed data (TOutputOut)
Estimated code review effortπ― 3 (Moderate) | β±οΈ ~25 minutes Suggested reviewers
Poem
Pre-merge checks and finishing touchesβ Failed checks (1 warning)
β Passed checks (4 passed)
β¨ Finishing touches
π§ͺ Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 0
π§Ή Nitpick comments (1)
packages/tests/server/outputParser.test.ts (1)
410-434: Consider documenting why theas unknowncast is necessary.The test correctly validates the preprocess functionality, but line 423 uses
as unknownto bypass type checking:return { count: '42' as unknown };While this may be intentional to demonstrate that the preprocess step handles the type coercion, it would be helpful to add a comment explaining why this cast is needed. Alternatively, if TypeScript should infer the correct input type automatically with the new changes, this cast might no longer be necessary.
π‘ Suggested improvement
q: trpc.procedure.output(stringToNumberSchema).query(() => { - // Resolver returns what the preprocess expects + // Resolver returns what the preprocess expects (string) + // The 'as unknown' cast is needed because TypeScript sees the final output type (number) + // but the preprocess step handles the string -> number conversion return { count: '42' as unknown }; }),
π Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
π Files selected for processing (3)
packages/server/src/unstable-core-do-not-import/middleware.tspackages/server/src/unstable-core-do-not-import/parser.tspackages/tests/server/outputParser.test.ts
π§° Additional context used
π Path-based instructions (5)
**/*.{ts,tsx}
π CodeRabbit inference engine (.cursor/rules/coding-guidelines.mdc)
**/*.{ts,tsx}: Always useimport typefor type-only imports
Separate type imports from value imports
Avoid overzealous object destructuring; prefer direct property access
Object destructuring is acceptable when a variable is used 3+ times
Prefer array destructuring
Avoid sparse array destructuring
Never destructure in function parameter declarations
Avoid destructuring potentially nullish nested properties
Maximum 3 parameters per function; use options objects when more
Type parameter names must match /^(T|$)(A-Z)?[0-9]*$/
Prefix unused variables, parameters, and caught errors with_
Prefer namespace imports for validation libraries and large modules (e.g.,import * as z from 'zod',import * as React from 'react')
Follow import order: test helpers, tRPC test imports, third-party, then relative
Never import from@trpc/*/src; import from the package root instead
Do not useSymbol.disposeorSymbol.asyncDispose; usemakeResource()/makeAsyncResource()
Always useawait usingfor resource cleanup
PrefermakeResource()/makeAsyncResource()over manual disposal logic
Avoid non-null assertions (!)
Use proper type guards and optional chaining instead of non-null assertions
Switch statements must be exhaustive for union types
Rely on TypeScript inference; avoid unnecessary explicit return/output types
Use explicit types at public API boundaries, for complex generic constraints, or when inference is insufficient/ambiguous
Use thesatisfiesoperator to retain inference while enforcing shapes
Useas constfor literal type inference when appropriate
Prefer explicit typing overany
Use type assertions sparingly
Leverage TypeScript strict mode features
Files:
packages/server/src/unstable-core-do-not-import/parser.tspackages/tests/server/outputParser.test.tspackages/server/src/unstable-core-do-not-import/middleware.ts
**/*.{ts,tsx,md,mdx}
π CodeRabbit inference engine (.cursor/rules/coding-guidelines.mdc)
Use camelCase for file names (with exceptions like TRPC/RPC/HTTP/JSON acronyms, .config.js, .d.ts, and tests)
Files:
packages/server/src/unstable-core-do-not-import/parser.tspackages/tests/server/outputParser.test.tspackages/server/src/unstable-core-do-not-import/middleware.ts
packages/**/*.{ts,tsx}
π CodeRabbit inference engine (.cursor/rules/coding-guidelines.mdc)
No
console.login packages; use proper logging instead
Files:
packages/server/src/unstable-core-do-not-import/parser.tspackages/tests/server/outputParser.test.tspackages/server/src/unstable-core-do-not-import/middleware.ts
**/*.test.ts
π CodeRabbit inference engine (.cursor/rules/test-patterns.mdc)
**/*.test.ts: ALWAYS useawait using ctx = testServerAndClientResource(...)in tests that need both server and client setup
NEVER use the deprecatedrouterToServerAndClientNew()in tests
ImporttestServerAndClientResourcefrom@trpc/client/__tests__/testClientResource
Create fresh mock instances per test using a factory (e.g.,getMockFetch())
Do not use global mocks that persist across tests
Configure mocks via theclientcallback intestServerAndClientResourceoptions
Usectx.clientfrom the test resource for making tRPC calls
Access server URLs viactx.httpUrlandctx.wssUrl
Configure server options via theserverproperty intestServerAndClientResourceoptions
Configure client options via theclientcallback intestServerAndClientResourceoptions
Use descriptive test names that explain the behavior under test
Focus test names on what the test validates, not just what it does
Use proper TypeScript typing for mocks
Clear mocks between tests when needed
Use factory functions for mock creation to ensure isolation
Files:
packages/tests/server/outputParser.test.ts
{**/*.test.{ts,tsx},**/__tests__/**/*.{ts,tsx}}
π CodeRabbit inference engine (.cursor/rules/coding-guidelines.mdc)
{**/*.test.{ts,tsx},**/__tests__/**/*.{ts,tsx}}: Do not use Testing LibrarywaitFor; usevi.waitForinstead
Tests may use non-null assertions
Tests may have unused variables
Tests may allow floating promises
Files:
packages/tests/server/outputParser.test.ts
π§ Learnings (14)
π Learning: 2025-09-05T15:16:48.745Z
Learnt from: CR
Repo: trpc/trpc PR: 0
File: .cursor/rules/test-patterns.mdc:0-0
Timestamp: 2025-09-05T15:16:48.745Z
Learning: Applies to **/*.test.ts : Import `testServerAndClientResource` from `trpc/client/__tests__/testClientResource`
Applied to files:
packages/tests/server/outputParser.test.ts
π Learning: 2025-09-05T15:17:32.520Z
Learnt from: CR
Repo: trpc/trpc PR: 0
File: .cursor/rules/upgrade-tests.mdc:0-0
Timestamp: 2025-09-05T15:17:32.520Z
Learning: Applies to packages/upgrade/**/*.{test,spec,trpc,snap}.tsx : For migration testing, exercise both legacy and modern patterns via ctx.rq and ctx.trq within the same test when relevant
Applied to files:
packages/tests/server/outputParser.test.ts
π Learning: 2025-09-05T15:16:48.745Z
Learnt from: CR
Repo: trpc/trpc PR: 0
File: .cursor/rules/test-patterns.mdc:0-0
Timestamp: 2025-09-05T15:16:48.745Z
Learning: Applies to **/*.test.ts : NEVER use the deprecated `routerToServerAndClientNew()` in tests
Applied to files:
packages/tests/server/outputParser.test.ts
π Learning: 2025-09-05T15:17:32.520Z
Learnt from: CR
Repo: trpc/trpc PR: 0
File: .cursor/rules/upgrade-tests.mdc:0-0
Timestamp: 2025-09-05T15:17:32.520Z
Learning: Applies to packages/upgrade/**/*.{test,spec,trpc,snap}.tsx : Do NOT import legacy-only helpers like createAppRouter from './__testHelpers' in upgrade-package tests
Applied to files:
packages/tests/server/outputParser.test.ts
π Learning: 2025-09-05T15:16:48.745Z
Learnt from: CR
Repo: trpc/trpc PR: 0
File: .cursor/rules/test-patterns.mdc:0-0
Timestamp: 2025-09-05T15:16:48.745Z
Learning: Applies to **/*.test.ts : Use `ctx.client` from the test resource for making tRPC calls
Applied to files:
packages/tests/server/outputParser.test.ts
π Learning: 2025-09-05T15:16:48.745Z
Learnt from: CR
Repo: trpc/trpc PR: 0
File: .cursor/rules/test-patterns.mdc:0-0
Timestamp: 2025-09-05T15:16:48.745Z
Learning: Applies to **/*.test.ts : Use proper TypeScript typing for mocks
Applied to files:
packages/tests/server/outputParser.test.ts
π Learning: 2025-09-05T15:16:48.745Z
Learnt from: CR
Repo: trpc/trpc PR: 0
File: .cursor/rules/test-patterns.mdc:0-0
Timestamp: 2025-09-05T15:16:48.745Z
Learning: Applies to **/*.test.ts : Configure server options via the `server` property in `testServerAndClientResource` options
Applied to files:
packages/tests/server/outputParser.test.ts
π Learning: 2025-09-05T16:48:06.982Z
Learnt from: CR
Repo: trpc/trpc PR: 0
File: .cursor/rules/coding-guidelines.mdc:0-0
Timestamp: 2025-09-05T16:48:06.982Z
Learning: Applies to {**/*.test.{ts,tsx},**/__tests__/**/*.{ts,tsx}} : Tests may allow floating promises
Applied to files:
packages/tests/server/outputParser.test.ts
π Learning: 2025-09-05T15:17:32.520Z
Learnt from: CR
Repo: trpc/trpc PR: 0
File: .cursor/rules/upgrade-tests.mdc:0-0
Timestamp: 2025-09-05T15:17:32.520Z
Learning: Applies to packages/upgrade/**/*.{test,spec,trpc,snap}.tsx : Import both 'trpc/react-query' as rq (legacy) and 'trpc/tanstack-react-query' as trq (modern) when writing migration tests
Applied to files:
packages/tests/server/outputParser.test.ts
π Learning: 2025-09-05T15:16:31.379Z
Learnt from: CR
Repo: trpc/trpc PR: 0
File: .cursor/rules/tanstack-react-query-tests.mdc:0-0
Timestamp: 2025-09-05T15:16:31.379Z
Learning: Applies to packages/tanstack-react-query/**/*.test.tsx : Use `ctx.useTRPCClient()` for direct (vanilla) tRPC client access in tests
Applied to files:
packages/tests/server/outputParser.test.ts
π Learning: 2025-09-05T15:16:01.878Z
Learnt from: CR
Repo: trpc/trpc PR: 0
File: .cursor/rules/react-query-tests.mdc:0-0
Timestamp: 2025-09-05T15:16:01.878Z
Learning: Applies to packages/react-query/**/*.test.tsx : Create the tRPC React client with createTRPCReact<typeof appRouter>()
Applied to files:
packages/tests/server/outputParser.test.ts
π Learning: 2025-09-05T15:16:48.745Z
Learnt from: CR
Repo: trpc/trpc PR: 0
File: .cursor/rules/test-patterns.mdc:0-0
Timestamp: 2025-09-05T15:16:48.745Z
Learning: Applies to **/*.test.ts : Configure client options via the `client` callback in `testServerAndClientResource` options
Applied to files:
packages/tests/server/outputParser.test.ts
π Learning: 2025-09-05T15:16:48.745Z
Learnt from: CR
Repo: trpc/trpc PR: 0
File: .cursor/rules/test-patterns.mdc:0-0
Timestamp: 2025-09-05T15:16:48.745Z
Learning: Applies to **/*.test.ts : ALWAYS use `await using ctx = testServerAndClientResource(...)` in tests that need both server and client setup
Applied to files:
packages/tests/server/outputParser.test.ts
π Learning: 2025-09-05T16:48:06.982Z
Learnt from: CR
Repo: trpc/trpc PR: 0
File: .cursor/rules/coding-guidelines.mdc:0-0
Timestamp: 2025-09-05T16:48:06.982Z
Learning: Applies to **/*.{ts,tsx} : Use explicit types at public API boundaries, for complex generic constraints, or when inference is insufficient/ambiguous
Applied to files:
packages/server/src/unstable-core-do-not-import/middleware.ts
𧬠Code graph analysis (1)
packages/server/src/unstable-core-do-not-import/middleware.ts (2)
packages/server/src/unstable-core-do-not-import/types.ts (1)
GetRawInputFn(168-168)packages/server/src/unstable-core-do-not-import/parser.ts (1)
ParseFn(82-84)
β° 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). (4)
- GitHub Check: Lint and auto-fix
- GitHub Check: typecheck
- GitHub Check: build
- GitHub Check: unit and integration tests
π Additional comments (9)
packages/server/src/unstable-core-do-not-import/parser.ts (3)
82-84: LGTM! Type signature correctly enables bidirectional transforms.The addition of the
TInputgeneric parameter with a default ofunknownallows output parsers to explicitly type their input while maintaining backward compatibility. This is essential for supporting codec-style schemas (e.g., Zod v4.1) that perform bidirectional transformations.
86-88: LGTM! Signature correctly propagates the new generic parameter.The updated signature is consistent with the
ParseFnchanges and correctly propagates bothTOutputandTInputtype parameters through the parser resolution logic.
124-130: Type assertion assumes TInput and TOutput are compatible, which the function signature doesn't enforce.The
parser.assert(value)call narrows the value toTInput(as declared inParserScaleEsque<TInput>), but the code returnsvalue as TOutput. SincegetParseFnallowsTInputandTOutputto be specified independently, this creates a type safety gap.
ParserScaleEsqueis designed as a single-type parserβitsinferParserinference treats both input and output as the same type. However, the function signature doesn't enforce this constraint, allowing callers to specify mismatched types likegetParseFn<TypeA, TypeB>(), which would bypass type safety.In normal tRPC usage, type inference via
inferParsershould ensureTInputandTOutputmatch. Consider either constraining the function signature to prevent misuse, or add a comment documenting that Scale-style parsers requireTInput === TOutput.packages/tests/server/outputParser.test.ts (2)
373-408: Excellent test coverage for the core bidirectional transform feature!This test comprehensively validates the key objective of the PR: procedures can return the schema's input type (bigint) while clients receive the transformed output type (string). The test includes both compile-time type assertions and runtime value checks, and the descriptive comments clearly explain the expected behavior.
436-463: LGTM! Comprehensive test of nested transformations.This test validates that multiple chained transforms work correctly, with the resolver returning the initial input type (string) and the client receiving the final transformed output type (number). The clear comment on line 460 effectively documents the transformation chain.
packages/server/src/unstable-core-do-not-import/middleware.ts (4)
21-39: LGTM! Type-safe data propagation through middleware results.The addition of the
TDatageneric parameter (defaulting tounknown) enables type-safe propagation of data through the middleware chain. The unused_TDataparameter inMiddlewareErrorResultis appropriately prefixed with an underscore per coding guidelines.
90-119: LGTM! Output type parameters enable proper type flow through middleware chains.The addition of
TOutputInandTOutputOutparameters allows middleware to track data transformations through the chain:
next()returns the input type that the current middleware will process (TOutputIn)- The middleware function itself returns its output type (
TOutputOut)This design correctly supports scenarios where middleware transforms data (e.g., output parsers that transform types).
121-129: LGTM! Correctly updated to match the new MiddlewareFunction signature.The expansion to seven
anyparameters aligns with the addition ofTOutputInandTOutputOutto theMiddlewareFunctionsignature.
226-237: The type assertion on line 237 is correct and necessary for this middleware pattern. The assertionresult.data as TOutputInproperly identifies the raw procedure output before passing it to the parse function, which transforms it fromTOutputIntoTOutputOut. This is the appropriate way to handle output validation in the middleware chain when the previous middleware returns an unvalidated result.
@trpc/client
@trpc/next
@trpc/react-query
@trpc/server
@trpc/tanstack-react-query
@trpc/upgrade
commit: |
39ce63c to
dcf806b
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and canβt be posted inline due to platform limitations.
β οΈ Outside diff range comments (1)
packages/server/src/unstable-core-do-not-import/middleware.ts (1)
90-119: MiddlewareBuilder needs updating to track output types through middleware chains.The new
TOutputInandTOutputOutparameters onMiddlewareFunctionenable output transformations, butMiddlewareBuilderwas not updated to propagate these types. The_middlewaresarray (lines 78-84) explicitly uses only 5 parameters, losing output type information. Theunstable_pipemethod also doesn't handle output type transformations. All three need updating:
- Add
TOutputInandTOutputOuttoMiddlewareBuildergeneric parameters- Update
_middlewaresfield to use these new parameters- Update
unstable_pipesignature and return type to track output types through piped middlewares
π Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
π Files selected for processing (3)
packages/server/src/unstable-core-do-not-import/middleware.tspackages/server/src/unstable-core-do-not-import/parser.tspackages/tests/server/outputParser.test.ts
π§ Files skipped from review as they are similar to previous changes (2)
- packages/server/src/unstable-core-do-not-import/parser.ts
- packages/tests/server/outputParser.test.ts
π§° Additional context used
π Path-based instructions (3)
**/*.{ts,tsx}
π CodeRabbit inference engine (.cursor/rules/coding-guidelines.mdc)
**/*.{ts,tsx}: Always useimport typefor type-only imports
Separate type imports from value imports
Avoid overzealous object destructuring; prefer direct property access
Object destructuring is acceptable when a variable is used 3+ times
Prefer array destructuring
Avoid sparse array destructuring
Never destructure in function parameter declarations
Avoid destructuring potentially nullish nested properties
Maximum 3 parameters per function; use options objects when more
Type parameter names must match /^(T|$)(A-Z)?[0-9]*$/
Prefix unused variables, parameters, and caught errors with_
Prefer namespace imports for validation libraries and large modules (e.g.,import * as z from 'zod',import * as React from 'react')
Follow import order: test helpers, tRPC test imports, third-party, then relative
Never import from@trpc/*/src; import from the package root instead
Do not useSymbol.disposeorSymbol.asyncDispose; usemakeResource()/makeAsyncResource()
Always useawait usingfor resource cleanup
PrefermakeResource()/makeAsyncResource()over manual disposal logic
Avoid non-null assertions (!)
Use proper type guards and optional chaining instead of non-null assertions
Switch statements must be exhaustive for union types
Rely on TypeScript inference; avoid unnecessary explicit return/output types
Use explicit types at public API boundaries, for complex generic constraints, or when inference is insufficient/ambiguous
Use thesatisfiesoperator to retain inference while enforcing shapes
Useas constfor literal type inference when appropriate
Prefer explicit typing overany
Use type assertions sparingly
Leverage TypeScript strict mode features
Files:
packages/server/src/unstable-core-do-not-import/middleware.ts
**/*.{ts,tsx,md,mdx}
π CodeRabbit inference engine (.cursor/rules/coding-guidelines.mdc)
Use camelCase for file names (with exceptions like TRPC/RPC/HTTP/JSON acronyms, .config.js, .d.ts, and tests)
Files:
packages/server/src/unstable-core-do-not-import/middleware.ts
packages/**/*.{ts,tsx}
π CodeRabbit inference engine (.cursor/rules/coding-guidelines.mdc)
No
console.login packages; use proper logging instead
Files:
packages/server/src/unstable-core-do-not-import/middleware.ts
π§ Learnings (2)
π Common learnings
Learnt from: CR
Repo: trpc/trpc PR: 0
File: .cursor/rules/coding-guidelines.mdc:0-0
Timestamp: 2025-09-05T16:48:06.982Z
Learning: Applies to **/*.{ts,tsx} : Use explicit types at public API boundaries, for complex generic constraints, or when inference is insufficient/ambiguous
π Learning: 2025-09-05T16:48:06.982Z
Learnt from: CR
Repo: trpc/trpc PR: 0
File: .cursor/rules/coding-guidelines.mdc:0-0
Timestamp: 2025-09-05T16:48:06.982Z
Learning: Applies to **/*.{ts,tsx} : Use explicit types at public API boundaries, for complex generic constraints, or when inference is insufficient/ambiguous
Applied to files:
packages/server/src/unstable-core-do-not-import/middleware.ts
𧬠Code graph analysis (1)
packages/server/src/unstable-core-do-not-import/middleware.ts (2)
packages/server/src/unstable-core-do-not-import/types.ts (1)
GetRawInputFn(168-168)packages/server/src/unstable-core-do-not-import/parser.ts (1)
ParseFn(82-84)
β° 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). (4)
- GitHub Check: build
- GitHub Check: typecheck
- GitHub Check: unit and integration tests
- GitHub Check: Lint and auto-fix
π Additional comments (7)
packages/server/src/unstable-core-do-not-import/middleware.ts (7)
21-26: LGTM: Clean addition of output data typing.The
TDatageneric parameter with a sensible default enables type-safe data flow through middleware results while maintaining backward compatibility.
28-32: LGTM: Proper handling of unused generic parameter.The
_TDataparameter maintains type system consistency withMiddlewareOKResultand correctly uses the underscore prefix per coding guidelines for unused parameters.
37-39: LGTM: Correct propagation of data type through result union.The
TDataparameter is properly threaded through both error and success result variants.
226-228: LGTM: Signature correctly binds resolver output to parser input.The explicit
TOutputInandTOutputOutgenerics oncreateOutputMiddlewarecorrectly implement the PR objective, allowing the parse function to transform from the procedure's return type (TOutputIn) to the client-facing type (TOutputOut).
44-85: MiddlewareBuilder doesn't propagate output type parameters through unstable_pipe, though MiddlewareFunction does support TOutputIn/TOutputOut. However, since middlewares primarily transform context and input rather than output, and MiddlewareFunction defaults these parameters to unknown when unspecified, this design choice may be intentional. Verify whether actual middleware usage in tests or real code attempts to transform output and would benefit from explicit type tracking.
237-237: No changes neededβthe type assertion is justified.The cast
result.data as TOutputInis necessary because TypeScript cannot infer the return type ofnext()without additional context. The assertion simply bridges to theparsefunction's required input type. The actual runtime validation occurs insideparse(), which will throw an error if the data doesn't match the expected schema. This is a legitimate use of type assertions at an API boundary where inference is insufficient.
121-129: AnyMiddlewareFunction correctly matches the MiddlewareFunction signature.The type definition uses 7 generic parameters (TContext, TMeta, TContextOverridesIn, $ContextOverridesOut, TInputOut, TOutputIn, TOutputOut) with appropriate
anyvalues. All existing usages in procedureBuilder.ts and middleware.ts are compatible with this type signature.
|
I don't think this will properly support codecs at runtime - https://zod.dev/codecs - it requires using .encode on the 'backward' pass. I had a fairly minimal example here https://github.com/lukeramsden/trpc/pull/1/changes#diff-dd323865a9c57111229561a1ffe12931bb744ad7956ca5b596173a488d1d517c |
KATT
left a comment
There was a problem hiding this comment.
Hey! Appreciate the work you did on this PR!
I need to look at the original issue to understand in what way we don't support this - I'll upgrade zod on another branch.
However, I don't see what this PR does, seeing that the tests seemingly pass even if I revert the files changed?
Even after doing the below, I don't see any type errors in the outputParser.test.ts
git checkout origin/main packages/server/src/unstable-core-do-not-import/middleware.ts packages/server/src/unstable-core-do-not-import/parser.tsbump zod - ref #7073 (review) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Chores** * Upgraded Zod to v4 across the repo and updated related form/resolver packages and typings. * Minor environment default adjusted (TYPEDOC). * **Documentation** * Added a new "zod v4" async-iterable validation example in subscriptions docs. * **Chores / Examples** * Removed one experimental react-hook-form factory/example from the demo app. * **Notes** * Tests and snapshots updated to reflect new validation error formatting; no other user-facing behavior changes expected. <sub>βοΈ Tip: You can customize this high-level summary in your review settings.</sub> <!-- end of auto-generated comment: release notes by coderabbit.ai -->
bump zod - ref trpc/trpc#7073 (review) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Chores** * Upgraded Zod to v4 across the repo and updated related form/resolver packages and typings. * Minor environment default adjusted (TYPEDOC). * **Documentation** * Added a new "zod v4" async-iterable validation example in subscriptions docs. * **Chores / Examples** * Removed one experimental react-hook-form factory/example from the demo app. * **Notes** * Tests and snapshots updated to reflect new validation error formatting; no other user-facing behavior changes expected. <sub>βοΈ Tip: You can customize this high-level summary in your review settings.</sub> <!-- end of auto-generated comment: release notes by coderabbit.ai -->
bump zod - ref trpc/trpc#7073 (review) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Chores** * Upgraded Zod to v4 across the repo and updated related form/resolver packages and typings. * Minor environment default adjusted (TYPEDOC). * **Documentation** * Added a new "zod v4" async-iterable validation example in subscriptions docs. * **Chores / Examples** * Removed one experimental react-hook-form factory/example from the demo app. * **Notes** * Tests and snapshots updated to reflect new validation error formatting; no other user-facing behavior changes expected. <sub>βοΈ Tip: You can customize this high-level summary in your review settings.</sub> <!-- end of auto-generated comment: release notes by coderabbit.ai -->
bump zod - ref trpc/trpc#7073 (review) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Chores** * Upgraded Zod to v4 across the repo and updated related form/resolver packages and typings. * Minor environment default adjusted (TYPEDOC). * **Documentation** * Added a new "zod v4" async-iterable validation example in subscriptions docs. * **Chores / Examples** * Removed one experimental react-hook-form factory/example from the demo app. * **Notes** * Tests and snapshots updated to reflect new validation error formatting; no other user-facing behavior changes expected. <sub>βοΈ Tip: You can customize this high-level summary in your review settings.</sub> <!-- end of auto-generated comment: release notes by coderabbit.ai -->
bump zod - ref trpc/trpc#7073 (review) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Chores** * Upgraded Zod to v4 across the repo and updated related form/resolver packages and typings. * Minor environment default adjusted (TYPEDOC). * **Documentation** * Added a new "zod v4" async-iterable validation example in subscriptions docs. * **Chores / Examples** * Removed one experimental react-hook-form factory/example from the demo app. * **Notes** * Tests and snapshots updated to reflect new validation error formatting; no other user-facing behavior changes expected. <sub>βοΈ Tip: You can customize this high-level summary in your review settings.</sub> <!-- end of auto-generated comment: release notes by coderabbit.ai -->
bump zod - ref trpc/trpc#7073 (review) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Chores** * Upgraded Zod to v4 across the repo and updated related form/resolver packages and typings. * Minor environment default adjusted (TYPEDOC). * **Documentation** * Added a new "zod v4" async-iterable validation example in subscriptions docs. * **Chores / Examples** * Removed one experimental react-hook-form factory/example from the demo app. * **Notes** * Tests and snapshots updated to reflect new validation error formatting; no other user-facing behavior changes expected. <sub>βοΈ Tip: You can customize this high-level summary in your review settings.</sub> <!-- end of auto-generated comment: release notes by coderabbit.ai -->
bump zod - ref trpc/trpc#7073 (review) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Chores** * Upgraded Zod to v4 across the repo and updated related form/resolver packages and typings. * Minor environment default adjusted (TYPEDOC). * **Documentation** * Added a new "zod v4" async-iterable validation example in subscriptions docs. * **Chores / Examples** * Removed one experimental react-hook-form factory/example from the demo app. * **Notes** * Tests and snapshots updated to reflect new validation error formatting; no other user-facing behavior changes expected. <sub>βοΈ Tip: You can customize this high-level summary in your review settings.</sub> <!-- end of auto-generated comment: release notes by coderabbit.ai -->
bump zod - ref trpc/trpc#7073 (review) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Chores** * Upgraded Zod to v4 across the repo and updated related form/resolver packages and typings. * Minor environment default adjusted (TYPEDOC). * **Documentation** * Added a new "zod v4" async-iterable validation example in subscriptions docs. * **Chores / Examples** * Removed one experimental react-hook-form factory/example from the demo app. * **Notes** * Tests and snapshots updated to reflect new validation error formatting; no other user-facing behavior changes expected. <sub>βοΈ Tip: You can customize this high-level summary in your review settings.</sub> <!-- end of auto-generated comment: release notes by coderabbit.ai -->
bump zod - ref trpc/trpc#7073 (review) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Chores** * Upgraded Zod to v4 across the repo and updated related form/resolver packages and typings. * Minor environment default adjusted (TYPEDOC). * **Documentation** * Added a new "zod v4" async-iterable validation example in subscriptions docs. * **Chores / Examples** * Removed one experimental react-hook-form factory/example from the demo app. * **Notes** * Tests and snapshots updated to reflect new validation error formatting; no other user-facing behavior changes expected. <sub>βοΈ Tip: You can customize this high-level summary in your review settings.</sub> <!-- end of auto-generated comment: release notes by coderabbit.ai -->
bump zod - ref trpc/trpc#7073 (review) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Chores** * Upgraded Zod to v4 across the repo and updated related form/resolver packages and typings. * Minor environment default adjusted (TYPEDOC). * **Documentation** * Added a new "zod v4" async-iterable validation example in subscriptions docs. * **Chores / Examples** * Removed one experimental react-hook-form factory/example from the demo app. * **Notes** * Tests and snapshots updated to reflect new validation error formatting; no other user-facing behavior changes expected. <sub>βοΈ Tip: You can customize this high-level summary in your review settings.</sub> <!-- end of auto-generated comment: release notes by coderabbit.ai -->
bump zod - ref trpc/trpc#7073 (review) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Chores** * Upgraded Zod to v4 across the repo and updated related form/resolver packages and typings. * Minor environment default adjusted (TYPEDOC). * **Documentation** * Added a new "zod v4" async-iterable validation example in subscriptions docs. * **Chores / Examples** * Removed one experimental react-hook-form factory/example from the demo app. * **Notes** * Tests and snapshots updated to reflect new validation error formatting; no other user-facing behavior changes expected. <sub>βοΈ Tip: You can customize this high-level summary in your review settings.</sub> <!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
I've bumped zod to v4 on |
- Add getEncodeFn() that uses .encode() for codecs, falls back to .parse() - Update procedureBuilder to use getEncodeFn for output validation - Add codec tests that verify the runtime behavior
|
@KATT @lukeramsden Thanks for the feedback! Updated the PR to add runtime .encode() support for Zod v4 codecs - added getEncodeFn() that uses .encode() when available and falls back to .parse() for unidirectional transforms. Also replaced the tests with actual z.codec() tests that fail without these changes |
There was a problem hiding this comment.
Actionable comments posted: 0
π§Ή Nitpick comments (1)
packages/tests/server/outputParser.test.ts (1)
443-488: Good coverage for nested codec transforms.The test verifies that codecs work correctly when nested within objects, which is important for real-world schemas. The use of
z.input<typeof schema>for the cast type (line 460, 471) is a nice pattern that ties the cast to the actual schema.Consider adding an edge case test for arrays of codec values (e.g.,
z.array(stringToBigint)) to ensure encoding works for collection types as well.
π Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
π Files selected for processing (3)
packages/server/src/unstable-core-do-not-import/parser.tspackages/server/src/unstable-core-do-not-import/procedureBuilder.tspackages/tests/server/outputParser.test.ts
π§° Additional context used
π Path-based instructions (5)
**/*.{ts,tsx}
π CodeRabbit inference engine (.cursor/rules/coding-guidelines.mdc)
**/*.{ts,tsx}: Always useimport typefor type-only imports
Separate type imports from value imports
Avoid overzealous object destructuring; prefer direct property access
Object destructuring is acceptable when a variable is used 3+ times
Prefer array destructuring
Avoid sparse array destructuring
Never destructure in function parameter declarations
Avoid destructuring potentially nullish nested properties
Maximum 3 parameters per function; use options objects when more
Type parameter names must match /^(T|$)(A-Z)?[0-9]*$/
Prefix unused variables, parameters, and caught errors with_
Prefer namespace imports for validation libraries and large modules (e.g.,import * as z from 'zod',import * as React from 'react')
Follow import order: test helpers, tRPC test imports, third-party, then relative
Never import from@trpc/*/src; import from the package root instead
Do not useSymbol.disposeorSymbol.asyncDispose; usemakeResource()/makeAsyncResource()
Always useawait usingfor resource cleanup
PrefermakeResource()/makeAsyncResource()over manual disposal logic
Avoid non-null assertions (!)
Use proper type guards and optional chaining instead of non-null assertions
Switch statements must be exhaustive for union types
Rely on TypeScript inference; avoid unnecessary explicit return/output types
Use explicit types at public API boundaries, for complex generic constraints, or when inference is insufficient/ambiguous
Use thesatisfiesoperator to retain inference while enforcing shapes
Useas constfor literal type inference when appropriate
Prefer explicit typing overany
Use type assertions sparingly
Leverage TypeScript strict mode features
Files:
packages/server/src/unstable-core-do-not-import/parser.tspackages/server/src/unstable-core-do-not-import/procedureBuilder.tspackages/tests/server/outputParser.test.ts
**/*.{ts,tsx,md,mdx}
π CodeRabbit inference engine (.cursor/rules/coding-guidelines.mdc)
Use camelCase for file names (with exceptions like TRPC/RPC/HTTP/JSON acronyms, .config.js, .d.ts, and tests)
Files:
packages/server/src/unstable-core-do-not-import/parser.tspackages/server/src/unstable-core-do-not-import/procedureBuilder.tspackages/tests/server/outputParser.test.ts
packages/**/*.{ts,tsx}
π CodeRabbit inference engine (.cursor/rules/coding-guidelines.mdc)
No
console.login packages; use proper logging instead
Files:
packages/server/src/unstable-core-do-not-import/parser.tspackages/server/src/unstable-core-do-not-import/procedureBuilder.tspackages/tests/server/outputParser.test.ts
**/*.test.ts
π CodeRabbit inference engine (.cursor/rules/test-patterns.mdc)
**/*.test.ts: ALWAYS useawait using ctx = testServerAndClientResource(...)in tests that need both server and client setup
NEVER use the deprecatedrouterToServerAndClientNew()in tests
ImporttestServerAndClientResourcefrom@trpc/client/__tests__/testClientResource
Create fresh mock instances per test using a factory (e.g.,getMockFetch())
Do not use global mocks that persist across tests
Configure mocks via theclientcallback intestServerAndClientResourceoptions
Usectx.clientfrom the test resource for making tRPC calls
Access server URLs viactx.httpUrlandctx.wssUrl
Configure server options via theserverproperty intestServerAndClientResourceoptions
Configure client options via theclientcallback intestServerAndClientResourceoptions
Use descriptive test names that explain the behavior under test
Focus test names on what the test validates, not just what it does
Use proper TypeScript typing for mocks
Clear mocks between tests when needed
Use factory functions for mock creation to ensure isolation
Files:
packages/tests/server/outputParser.test.ts
{**/*.test.{ts,tsx},**/__tests__/**/*.{ts,tsx}}
π CodeRabbit inference engine (.cursor/rules/coding-guidelines.mdc)
{**/*.test.{ts,tsx},**/__tests__/**/*.{ts,tsx}}: Do not use Testing LibrarywaitFor; usevi.waitForinstead
Tests may use non-null assertions
Tests may have unused variables
Tests may allow floating promises
Files:
packages/tests/server/outputParser.test.ts
π§ Learnings (4)
π Learning: 2025-09-05T15:16:48.745Z
Learnt from: CR
Repo: trpc/trpc PR: 0
File: .cursor/rules/test-patterns.mdc:0-0
Timestamp: 2025-09-05T15:16:48.745Z
Learning: Applies to **/*.test.ts : Use proper TypeScript typing for mocks
Applied to files:
packages/tests/server/outputParser.test.ts
π Learning: 2025-09-05T15:17:32.520Z
Learnt from: CR
Repo: trpc/trpc PR: 0
File: .cursor/rules/upgrade-tests.mdc:0-0
Timestamp: 2025-09-05T15:17:32.520Z
Learning: Applies to packages/upgrade/**/*.{test,spec,trpc,snap}.tsx : For migration testing, exercise both legacy and modern patterns via ctx.rq and ctx.trq within the same test when relevant
Applied to files:
packages/tests/server/outputParser.test.ts
π Learning: 2025-09-05T15:16:31.379Z
Learnt from: CR
Repo: trpc/trpc PR: 0
File: .cursor/rules/tanstack-react-query-tests.mdc:0-0
Timestamp: 2025-09-05T15:16:31.379Z
Learning: Applies to packages/tanstack-react-query/**/*.test.tsx : Use `ctx.useTRPCClient()` for direct (vanilla) tRPC client access in tests
Applied to files:
packages/tests/server/outputParser.test.ts
π Learning: 2025-09-05T15:16:48.745Z
Learnt from: CR
Repo: trpc/trpc PR: 0
File: .cursor/rules/test-patterns.mdc:0-0
Timestamp: 2025-09-05T15:16:48.745Z
Learning: Applies to **/*.test.ts : Import `testServerAndClientResource` from `trpc/client/__tests__/testClientResource`
Applied to files:
packages/tests/server/outputParser.test.ts
𧬠Code graph analysis (2)
packages/server/src/unstable-core-do-not-import/procedureBuilder.ts (2)
packages/server/src/unstable-core-do-not-import/parser.ts (1)
getEncodeFn(150-180)packages/server/src/unstable-core-do-not-import/middleware.ts (1)
createOutputMiddleware(226-252)
packages/tests/server/outputParser.test.ts (1)
packages/server/src/unstable-core-do-not-import/procedureBuilder.ts (2)
output(509-515)input(502-508)
β° 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). (4)
- GitHub Check: unit and integration tests
- GitHub Check: build
- GitHub Check: typecheck
- GitHub Check: Lint and auto-fix
π Additional comments (7)
packages/server/src/unstable-core-do-not-import/parser.ts (3)
82-88: LGTM - Type signature updates align with PR objectives.Adding
TInputtype parameter toParseFnandgetParseFncorrectly enables binding the procedure's return type to the output schema's input type, supporting Zod v4 codecs.
126-129: LGTM - Cast updated to match renamed type parameter.The double cast
value as unknown as TOutputis appropriate here sinceparser.assertonly narrows the type via assertion but doesn't return a typed value.
146-180: The suggested error handling improvements are not compatible with Zod v4's actual behavior.The current implementation correctly matches Zod v4's documented error message. Zod throws a plain
Error(not a custom error class with acodeproperty) with the message format: "Encountered unidirectional transform during encode: ZodTransform". The substring'unidirectional transform'is reliably present in this message.The suggested improvements introduce issues:
error.code === 'unidirectional_transform'will never matchβZod v4 throws a plainErrorwithout acodeproperty'cannot encode'is not part of Zod's actual error message format- The current
error.message.includes('unidirectional transform')check correctly handles the documented errorThe existing implementation is sound and requires no changes.
Likely an incorrect or invalid review comment.
packages/tests/server/outputParser.test.ts (2)
373-409: Good runtime verification test, but type casts indicate incomplete type inference.The test correctly validates that
getEncodeFnuses the codec's.encode()method at runtime. However, the cast on line 397 (as unknown as { value: string }) suggests the type system still expects the schema's output type rather than its input type.Per PR objectives, the resolver should be able to return
bigint(what encode expects) without casting, since the output schema's input type should bind to the resolver's return type.Is this a known limitation being addressed in a follow-up, or should the type inference be working at this point?
411-441: LGTM - Practical test case for Date serialization.This test demonstrates a common real-world use case (Date β ISO string for JSON transport). The test structure correctly validates both the encoded value and full object equality.
packages/server/src/unstable-core-do-not-import/procedureBuilder.ts (2)
15-15: LGTM - Import updated to includegetEncodeFn.
509-514: LGTM - Output handling correctly switched to encoding.The change from
getParseFntogetEncodeFnfor output processing enables Zod v4 codecs to work correctly. The variable rename fromparsertoencoderimproves code clarity by accurately describing its purpose.
| q: trpc.procedure.output(schema).query(() => { | ||
| // For codec output encoding, we return what encode() expects (bigint) | ||
| // and cast to satisfy the type system which expects the input type | ||
| return { value: 123n } as unknown as { value: string }; |
There was a problem hiding this comment.
wouldn't want to merge this without seeing that userland typesafety is better than this
|
given the age of this one (sorry we missed it) and the comment I've left I'm going to close, but happy to take an updated PR |
|
This pull request has been locked because we are very unlikely to see comments on closed issues. If you think, this PR is still necessary, create a new one with the same branch. Thank you. |
Closes #6978
π― Changes
This PR adds support for binding the return type of a procedure to the input type of the output schema, enabling proper type inference for Zod v4.1 Codecs and other bidirectional transform scenarios.
Problem
With Zod v4.1 Codecs (bidirectional transforms), schemas can have different input and output types. For example, a
stringToBigIntcodec would:bigintstringPreviously,
ParseFn<TType>tookunknownas input, losing type information about what the parse function expected. This caused type errors when using output transforms/codecs where the resolver should return the schema's input typeSolution
Updated
ParseFntype to support an input type parameter:type ParseFn<TOutput, TInput = unknown> = (value: TInput) => Promise | TOutput;
2. Added
TDatatype parameter toMiddlewareOKResult,MiddlewareErrorResult, andMiddlewareResultto properly track data types through the middleware chain.Updated
MiddlewareFunctionwithTOutputInandTOutputOuttype parameters for proper output type flow.Updated
createOutputMiddlewareto acceptParseFn<TOutputOut, TOutputIn>for correct type inference.Result
Now output transforms work correctly with proper type inference:
β Checklist
Summary by CodeRabbit
New Features
Tests
βοΈ Tip: You can customize this high-level summary in your review settings.