Skip to content

feat(server): bind procedure return type to output parser input - #7073

Closed
bas0N wants to merge 4 commits into
trpc:mainfrom
bas0N:feat/output-parser-input-type-binding-6978
Closed

bas0N wants to merge 4 commits into
trpc:mainfrom
bas0N:feat/output-parser-input-type-binding-6978

Conversation

@bas0N

@bas0N bas0N commented Dec 23, 2025 •

Copy link
Copy Markdown

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 stringToBigInt codec would:

  • Input type (what goes into the encoder): bigint
  • Output type (what comes out after encoding): string

Previously, ParseFn<TType> took unknown as 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 type

Solution

  1. Updated ParseFn type to support an input type parameter:

    type ParseFn<TOutput, TInput = unknown> = (value: TInput) => Promise | TOutput;
    2. Added TData type parameter to MiddlewareOKResult, MiddlewareErrorResult, and MiddlewareResult to properly track data types through the middleware chain.

  2. Updated MiddlewareFunction with TOutputIn and TOutputOut type parameters for proper output type flow.

  3. Updated createOutputMiddleware to accept ParseFn<TOutputOut, TOutputIn> for correct type inference.

Result

Now output transforms work correctly with proper type inference:

// Schema that transforms bigint β†’ string
const schema = z.object({ x: z.bigint().transform(x => x.toString()) });

procedure
  .output(schema)
  .query(() => {
    // Resolver returns bigint (schema input type)
    return { x: 123n };
    // Client receives { x: string } (schema output type)
  });

βœ… Checklist

  • I have followed the steps listed in the Contributing guide.
  • If necessary, I have added documentation related to the changes made.
  • I have added or updated the tests related to the changes made.

Summary by CodeRabbit

  • New Features

    • Improved type safety for middleware input/output and result payloads, making middleware pipelines' data shapes clearer.
    • Output handling now uses explicit encoding paths so server-to-client transforms are consistently applied.
  • Tests

    • Added tests verifying output encoding/serialization (including date, bigint, and nested transforms) to ensure resolverβ†’client values are correctly encoded.

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

@bas0N
bas0N requested a review from a team as a code owner December 23, 2025 00:21
@vercel

vercel Bot commented Dec 23, 2025 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Review Updated (UTC)
next-prisma-starter Ready Ready Preview Jan 3, 2026 10:15pm
og-image Ready Ready Preview, Comment Jan 3, 2026 10:15pm

@coderabbitai

coderabbitai Bot commented Dec 23, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds 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 (getEncodeFn) and threads output-input types through createOutputMiddleware. Runtime behavior is preserved.

Changes

Cohort / File(s) Summary
Middleware types
packages/server/src/unstable-core-do-not-import/middleware.ts
Added TData to MiddlewareOKResult/MiddlewareErrorResult; made MiddlewareResult generic; extended MiddlewareFunction with TOutputIn/TOutputOut and updated all next() overloads; widened AnyMiddlewareFunction; updated createOutputMiddleware<TOutputIn, TOutputOut> and cast result.data as TOutputIn before parsing.
Parser & encoder APIs
packages/server/src/unstable-core-do-not-import/parser.ts
Generalized ParseFn to ParseFn<TOutput, TInput = unknown>; updated getParseFn<TOutput, TInput = unknown>; added getEncodeFn<TOutput, TInput = unknown> which prefers encode/encodeAsync and falls back to parse; adjusted internal casts to value as unknown as TOutput.
Procedure builder
packages/server/src/unstable-core-do-not-import/procedureBuilder.ts
Imports getEncodeFn and now calls getEncodeFn(output) and passes the returned encoder into createOutputMiddleware instead of using getParseFn.
Tests
packages/tests/server/outputParser.test.ts
Added three tests validating Zod v4 codec/transform encoding behaviors (bidirectional transform, Date→ISO string, nested codec transforms) and ensuring client-observed encoded outputs.

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)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested reviewers

  • KATT

Poem

🐰 I hopped through types with nimble paws,
Threaded outputs into inputs without a pause.
Encoders hum, parsers twirl,
Middleware links make types unfurl β€”
Tiny rabbit cheers, and munches carrots! πŸ₯•βœ¨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
βœ… Passed checks (4 passed)
Check name Status Explanation
Title check βœ… Passed The title clearly and concisely summarizes the main change: binding procedure return types to output parser input types.
Description check βœ… Passed The description is comprehensive with problem/solution/result structure, code examples, and completed checklist items, though documentation update is still pending.
Linked Issues check βœ… Passed The changes implement all core objectives: ParseFn now has input type parameter, middleware types support data type propagation, output middleware uses proper encoder, and tests validate codec scenarios.
Out of Scope Changes check βœ… Passed All changes directly support binding procedure return types to output parser input types; no unrelated modifications detected.
✨ Finishing touches
  • πŸ“ Generate docstrings
πŸ§ͺ Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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)
packages/tests/server/outputParser.test.ts (1)

410-434: Consider documenting why the as unknown cast is necessary.

The test correctly validates the preprocess functionality, but line 423 uses as unknown to 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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 305f6d2 and 39ce63c.

πŸ“’ Files selected for processing (3)
  • packages/server/src/unstable-core-do-not-import/middleware.ts
  • packages/server/src/unstable-core-do-not-import/parser.ts
  • packages/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 use import type for 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 use Symbol.dispose or Symbol.asyncDispose; use makeResource()/makeAsyncResource()
Always use await using for resource cleanup
Prefer makeResource()/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 the satisfies operator to retain inference while enforcing shapes
Use as const for literal type inference when appropriate
Prefer explicit typing over any
Use type assertions sparingly
Leverage TypeScript strict mode features

Files:

  • packages/server/src/unstable-core-do-not-import/parser.ts
  • packages/tests/server/outputParser.test.ts
  • 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/parser.ts
  • packages/tests/server/outputParser.test.ts
  • packages/server/src/unstable-core-do-not-import/middleware.ts
packages/**/*.{ts,tsx}

πŸ“„ CodeRabbit inference engine (.cursor/rules/coding-guidelines.mdc)

No console.log in packages; use proper logging instead

Files:

  • packages/server/src/unstable-core-do-not-import/parser.ts
  • packages/tests/server/outputParser.test.ts
  • packages/server/src/unstable-core-do-not-import/middleware.ts
**/*.test.ts

πŸ“„ CodeRabbit inference engine (.cursor/rules/test-patterns.mdc)

**/*.test.ts: ALWAYS use await using ctx = testServerAndClientResource(...) in tests that need both server and client setup
NEVER use the deprecated routerToServerAndClientNew() in tests
Import testServerAndClientResource from @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 the client callback in testServerAndClientResource options
Use ctx.client from the test resource for making tRPC calls
Access server URLs via ctx.httpUrl and ctx.wssUrl
Configure server options via the server property in testServerAndClientResource options
Configure client options via the client callback in testServerAndClientResource options
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 Library waitFor; use vi.waitFor instead
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 TInput generic parameter with a default of unknown allows 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 ParseFn changes and correctly propagates both TOutput and TInput type 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 to TInput (as declared in ParserScaleEsque<TInput>), but the code returns value as TOutput. Since getParseFn allows TInput and TOutput to be specified independently, this creates a type safety gap.

ParserScaleEsque is designed as a single-type parserβ€”its inferParser inference treats both input and output as the same type. However, the function signature doesn't enforce this constraint, allowing callers to specify mismatched types like getParseFn<TypeA, TypeB>(), which would bypass type safety.

In normal tRPC usage, type inference via inferParser should ensure TInput and TOutput match. Consider either constraining the function signature to prevent misuse, or add a comment documenting that Scale-style parsers require TInput === 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 TData generic parameter (defaulting to unknown) enables type-safe propagation of data through the middleware chain. The unused _TData parameter in MiddlewareErrorResult is appropriately prefixed with an underscore per coding guidelines.


90-119: LGTM! Output type parameters enable proper type flow through middleware chains.

The addition of TOutputIn and TOutputOut parameters 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 any parameters aligns with the addition of TOutputIn and TOutputOut to the MiddlewareFunction signature.


226-237: The type assertion on line 237 is correct and necessary for this middleware pattern. The assertion result.data as TOutputIn properly identifies the raw procedure output before passing it to the parse function, which transforms it from TOutputIn to TOutputOut. This is the appropriate way to handle output validation in the middleware chain when the previous middleware returns an unvalidated result.

@pkg-pr-new

pkg-pr-new Bot commented Dec 23, 2025 •

Copy link
Copy Markdown

Open in StackBlitz

@trpc/client

npm i https://pkg.pr.new/trpc/trpc/@trpc/client@7073

@trpc/next

npm i https://pkg.pr.new/trpc/trpc/@trpc/next@7073

@trpc/react-query

npm i https://pkg.pr.new/trpc/trpc/@trpc/react-query@7073

@trpc/server

npm i https://pkg.pr.new/trpc/trpc/@trpc/server@7073

@trpc/tanstack-react-query

npm i https://pkg.pr.new/trpc/trpc/@trpc/tanstack-react-query@7073

@trpc/upgrade

npm i https://pkg.pr.new/trpc/trpc/@trpc/upgrade@7073

commit: 79e4595

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 TOutputIn and TOutputOut parameters on MiddlewareFunction enable output transformations, but MiddlewareBuilder was not updated to propagate these types. The _middlewares array (lines 78-84) explicitly uses only 5 parameters, losing output type information. The unstable_pipe method also doesn't handle output type transformations. All three need updating:

  1. Add TOutputIn and TOutputOut to MiddlewareBuilder generic parameters
  2. Update _middlewares field to use these new parameters
  3. Update unstable_pipe signature and return type to track output types through piped middlewares
πŸ“œ Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 39ce63c and dcf806b.

πŸ“’ Files selected for processing (3)
  • packages/server/src/unstable-core-do-not-import/middleware.ts
  • packages/server/src/unstable-core-do-not-import/parser.ts
  • packages/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 use import type for 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 use Symbol.dispose or Symbol.asyncDispose; use makeResource()/makeAsyncResource()
Always use await using for resource cleanup
Prefer makeResource()/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 the satisfies operator to retain inference while enforcing shapes
Use as const for literal type inference when appropriate
Prefer explicit typing over any
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.log in 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 TData generic 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 _TData parameter maintains type system consistency with MiddlewareOKResult and correctly uses the underscore prefix per coding guidelines for unused parameters.


37-39: LGTM: Correct propagation of data type through result union.

The TData parameter is properly threaded through both error and success result variants.


226-228: LGTM: Signature correctly binds resolver output to parser input.

The explicit TOutputIn and TOutputOut generics on createOutputMiddleware correctly 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 TOutputIn is necessary because TypeScript cannot infer the return type of next() without additional context. The assertion simply bridges to the parse function's required input type. The actual runtime validation occurs inside parse(), 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 any values. All existing usages in procedureBuilder.ts and middleware.ts are compatible with this type signature.

@lukeramsden

Copy link
Copy Markdown

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

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

KATT added a commit that referenced this pull request Dec 23, 2025
bump 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 -->
trpc-bot pushed a commit to trpc/examples-next-formdata that referenced this pull request Dec 23, 2025
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 -->
trpc-bot pushed a commit to trpc/examples-minimal-react that referenced this pull request Dec 23, 2025
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 -->
trpc-bot pushed a commit to trpc/examples-next-app-dir that referenced this pull request Dec 23, 2025
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 -->
trpc-bot pushed a commit to trpc/examples-minimal that referenced this pull request Dec 23, 2025
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 -->
trpc-bot pushed a commit to trpc/examples-next-big-router that referenced this pull request Dec 23, 2025
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 -->
trpc-bot pushed a commit to trpc/examples-tanstack-start-sse-chat that referenced this pull request Dec 23, 2025
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 -->
trpc-bot pushed a commit to trpc/examples-next-prisma-websockets-starter that referenced this pull request Dec 23, 2025
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 -->
trpc-bot pushed a commit to trpc/examples-next-minimal-starter that referenced this pull request Dec 23, 2025
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 -->
trpc-bot pushed a commit to trpc/examples-next-prisma-todomvc that referenced this pull request Dec 23, 2025
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 -->
trpc-bot pushed a commit to trpc/examples-next-prisma-starter that referenced this pull request Dec 23, 2025
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 -->
@KATT

KATT commented Dec 23, 2025

Copy link
Copy Markdown
Member

I've bumped zod to v4 on main now so that should make it easier to make a real repro

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

bas0N commented Dec 24, 2025

Copy link
Copy Markdown
Author

@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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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)
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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between dcf806b and b4060bd.

πŸ“’ Files selected for processing (3)
  • packages/server/src/unstable-core-do-not-import/parser.ts
  • packages/server/src/unstable-core-do-not-import/procedureBuilder.ts
  • packages/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 use import type for 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 use Symbol.dispose or Symbol.asyncDispose; use makeResource()/makeAsyncResource()
Always use await using for resource cleanup
Prefer makeResource()/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 the satisfies operator to retain inference while enforcing shapes
Use as const for literal type inference when appropriate
Prefer explicit typing over any
Use type assertions sparingly
Leverage TypeScript strict mode features

Files:

  • packages/server/src/unstable-core-do-not-import/parser.ts
  • packages/server/src/unstable-core-do-not-import/procedureBuilder.ts
  • packages/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.ts
  • packages/server/src/unstable-core-do-not-import/procedureBuilder.ts
  • packages/tests/server/outputParser.test.ts
packages/**/*.{ts,tsx}

πŸ“„ CodeRabbit inference engine (.cursor/rules/coding-guidelines.mdc)

No console.log in packages; use proper logging instead

Files:

  • packages/server/src/unstable-core-do-not-import/parser.ts
  • packages/server/src/unstable-core-do-not-import/procedureBuilder.ts
  • packages/tests/server/outputParser.test.ts
**/*.test.ts

πŸ“„ CodeRabbit inference engine (.cursor/rules/test-patterns.mdc)

**/*.test.ts: ALWAYS use await using ctx = testServerAndClientResource(...) in tests that need both server and client setup
NEVER use the deprecated routerToServerAndClientNew() in tests
Import testServerAndClientResource from @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 the client callback in testServerAndClientResource options
Use ctx.client from the test resource for making tRPC calls
Access server URLs via ctx.httpUrl and ctx.wssUrl
Configure server options via the server property in testServerAndClientResource options
Configure client options via the client callback in testServerAndClientResource options
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 Library waitFor; use vi.waitFor instead
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 TInput type parameter to ParseFn and getParseFn correctly 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 TOutput is appropriate here since parser.assert only 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 a code property) 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 plain Error without a code property
  • 'cannot encode' is not part of Zod's actual error message format
  • The current error.message.includes('unidirectional transform') check correctly handles the documented error

The 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 getEncodeFn uses 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 include getEncodeFn.


509-514: LGTM - Output handling correctly switched to encoding.

The change from getParseFn to getEncodeFn for output processing enables Zod v4 codecs to work correctly. The variable rename from parser to encoder improves 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 };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

wouldn't want to merge this without seeing that userland typesafety is better than this

@Nick-Lucas

Copy link
Copy Markdown
Contributor

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

@Nick-Lucas Nick-Lucas closed this Sep 12, 2026
@github-actions

Copy link
Copy Markdown
Contributor

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.

@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Sep 13, 2026

This branch was successfully deployed

5 active deployments
Preview – www β€” 79e45953 Deployed Jan 3, 2026 by vercel[bot]
Preview – trpc-next-app-dir β€” 79e45953 Deployed Jan 3, 2026 by vercel[bot]
Preview – next-prisma-starter β€” 79e45953 Deployed Jan 3, 2026 by vercel[bot]
Preview – examples-todomvc β€” 79e45953 Deployed Jan 3, 2026 by vercel[bot]
Preview – og-image β€” 79e45953 Deployed Jan 3, 2026 by vercel[bot]
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: Bind return type of a procedure to the input type of the output schema

5 participants