Skip to content

chore(recipe): get json schema for procedure - #6696

Merged
juliusmarminge merged 12 commits into
mainfrom
issues/6691-jsonschema
Jun 3, 2025
Merged

juliusmarminge merged 12 commits into
mainfrom
issues/6691-jsonschema

Conversation

@KATT

@KATT KATT commented Apr 11, 2025 •

Copy link
Copy Markdown
Member

Closes #6691

🎯 Changes

How to get json schema for procedure

test('recipe: get json schemas for procedure', async () => {
const t = initTRPC.create();
const publicProcedure = t.procedure;
function getRouter() {
return appRouter as AnyRouter; // Needs to be type-casted to AnyRouter to avoid circular references
}
const appRouter = t.router({
single: publicProcedure
.input(
z.object({
foo: z.string(),
}),
)
.query((opts) => {
return opts.input;
// ^?
}),
list: publicProcedure
.input(
z.object({
foo: z.array(z.string()),
}),
)
.input(
z.object({
bar: z.array(z.string()),
}),
)
.query((opts) => {
return opts.input;
// ^?
}),
getJsonSchemas: publicProcedure
.input(
z.object({
path: z.string(),
}),
)
.query(async (opts) => {
const proc = await getProcedureAtPath(
// Needs to be type-casted to AnyRouter to avoid circular references
appRouter as AnyRouter,
opts.input.path,
);
expectTypeOf(proc).toMatchTypeOf<AnyProcedure | null>();
if (!proc) {
return null;
}
return proc._def.inputs.map((input) => z.toJSONSchema(input as any));
}),
});
await using ctx = testServerAndClientResource(appRouter);
const client = ctx.client;
expect(await client.getJsonSchemas.query({ path: 'single' }))
.toMatchInlineSnapshot(`
Array [
Object {
"properties": Object {
"foo": Object {
"type": "string",
},
},
"required": Array [
"foo",
],
"type": "object",
},
]
`);
expect(
await client.getJsonSchemas.query({ path: 'list' }),
).toMatchInlineSnapshot(`
Array [
Object {
"properties": Object {
"foo": Object {
"items": Object {
"type": "string",
},
"type": "array",
},
},
"required": Array [
"foo",
],
"type": "object",
},
Object {
"properties": Object {
"bar": Object {
"items": Object {
"type": "string",
},
"type": "array",
},
},
"required": Array [
"bar",
],
"type": "object",
},
]
`);
});

Summary by CodeRabbit

  • Chores

    • Updated the version of a popular data validation library across multiple projects to a newer minor and patch release, ensuring compatibility with recent improvements.
    • Updated related form-data validation library versions in select projects.
  • Tests

    • Added new test cases covering both v3 and v4 versions of the data validation library, including JSON schema generation for procedures, improving validation coverage and reliability.

@KATT
KATT requested review from a team as code owners April 11, 2025 10:02
@coderabbitai

coderabbitai Bot commented Apr 11, 2025 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Review was skipped due to path filters

β›” Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request updates the version specification for the Zod dependency in multiple projects from "^3.24.4" to "^3.25.49". It adds a new import and property (inputs: Parser[]) to the Procedure interface and introduces a test case that retrieves JSON schemas for procedures, enabling exposure of JSON schemas for inputs/outputs.

Changes

File(s) Change Summary
Multiple package.json files under examples/, packages/, www/, and root package.json Updated the Zod dependency version from "^3.24.4" to "^3.25.49". Also updated zod-form-data from ^2.0.1 to ^3.0.0 in two places.
packages/server/src/unstable-core-do-not-import/procedure.ts Added import of Parser type and added inputs: Parser[] property to the Procedure interface.
packages/tests/server/validators.test.ts Added new test case recipe: get json schemas for procedure to validate JSON schema extraction from procedure inputs.
packages/react-query/package.json, examples/next-formdata/package.json Updated both zod and zod-form-data dependencies to newer versions (zod to ^3.25.49, zod-form-data to ^3.0.0).
packages/react-query/test/formData.test.tsx Changed import of zod from 'zod' to 'zod/v4'.

Sequence Diagram(s)

sequenceDiagram
  participant C as Client
  participant R as TRPC Router
  participant P as Procedure
  participant Z as Zod Converter

  C->>R: Request getJsonSchemas(endpointPath)
  R->>P: Retrieve procedure via getProcedureAtPath()
  P->>Z: Convert input parsers to JSON schemas
  Z-->>P: Return JSON schema
  P-->>R: Forward JSON schema
  R-->>C: Return JSON schema response
Loading

Assessment against linked issues

Objective Addressed Explanation
Expose JSON schemas for all inputs/outputs [#6691] βœ…

Poem

I'm a little rabbit, hopping in the night,
Updating Zod to a version just right.
JSON schemas bloom like carrots in the ground,
In every procedure, magic schemas are found.
With a twitch of my nose and a joyful little tune,
I celebrate our code under the coding moon. 🐰πŸ₯•


πŸͺ§ Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@railway-app

railway-app Bot commented Apr 11, 2025 •

Copy link
Copy Markdown

πŸš… Deployed to the trpc-pr-6696 environment in trpc-sse-and-websockets

Service Status Web Updated (UTC)
next-prisma-websockets-starter ◻️ Removed (View Logs) Jun 3, 2025 at 12:56 pm
next-sse-chat ◻️ Removed (View Logs) Web Jun 3, 2025 at 12:56 pm

@vercel

vercel Bot commented Apr 11, 2025 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for Git β†—οΈŽ

Name Status Preview Comments Updated (UTC)
next-prisma-starter βœ… Ready (Inspect) Visit Preview Jun 3, 2025 0:50am
og-image βœ… Ready (Inspect) Visit Preview πŸ’¬ Add feedback Jun 3, 2025 0:50am
www βœ… Ready (Inspect) Visit Preview πŸ’¬ Add feedback Jun 3, 2025 0:50am

@pkg-pr-new

pkg-pr-new Bot commented Apr 11, 2025 •

Copy link
Copy Markdown

Open in StackBlitz

@trpc/client

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

@trpc/next

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

@trpc/react-query

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

@trpc/server

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

@trpc/tanstack-react-query

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

@trpc/upgrade

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

commit: 50f01da

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

🧹 Nitpick comments (21)
examples/minimal-react/server/package.json (1)

13-13: Unify Zod Dependency for Minimal React Server

The dependency update to "zod": "next" ensures consistency with other examples. Please double-check that integrations with other dependencies remain stable with this pre-release version.

examples/minimal-content-types/server/package.json (1)

13-13: Switch Zod Dependency to Pre-Release "next"

Changing the version from "^3.24.2" to "next" shifts to a pre-release version. Confirm that the updated Zod API meets the expected behavior for schema validations and doesn’t introduce regressions.

examples/next-edge-runtime/package.json (1)

19-19: Dependency Update: Zod version bumped to "next"
The "zod" dependency has been updated from "^3.24.2" to "next", aligning this project with the latest pre-release/experimental version of Zod. Please monitor for any potential breaking changes due to the less predictable stability of the "next" channel.

examples/express-server/package.json (1)

21-21: Dependency Update: Zod version updated to "next"
Updating "zod": "next" here is consistent with the overall project strategy. Ensure that the express server environment and any middleware that rely on Zod validations are tested thoroughly after this change to catch integration issues early.

examples/.test/monotest-api/package.json (1)

20-20: Dependency Update Applied: Zod version set to "next"
This change updates the Zod dependency to "next", thereby allowing the project to access the latest pre-release features. Verify that all JSON schema validations in the test suite remain compatible with this version, as experimental changes in Zod may introduce subtle differences in behavior.

examples/.experimental/next-app-dir/package.json (1)

35-35: Dependency Update: "zod" bumped to "next"
In this experimental project, switching to the "next" version of Zod is in line with the broader dependency update. Given the experimental nature of both the project and the Zod version, please ensure that any related features (such as JSON schema handling) are thoroughly validated under real-world scenarios.

packages/server/package.json (1)

147-147: DevDependency Update: "zod" updated to "next"
The update to "zod": "next" in the devDependencies ensures consistency across the repository. Confirm that type validation, schema generation, and any tooling relying on Zod (for instance, procedures that generate JSON schemas) are still functioning as expected given potential changes in the API of the "next" release.

examples/minimal/package.json (1)

17-17: Dependency Version Update: "zod" set to "next"

Changing the "zod" dependency from a fixed semantic version ("^3.24.2") to "next" means that the project will now track the latest pre-release version. This could introduce newer features as well as breaking changes, so please ensure that this aligns with your stability and compatibility requirementsβ€”especially given that other parts of the system (such as JSON schema generation) might interact with this dependency.

examples/next-formdata/package.json (1)

22-22: Review "zod" Dependency Update

The update to "zod": "next" means that the dependency will now always resolve to the latest available version in the next release channel. This may expose your project to pre-release behavior and potential API changes. Please confirm that the change is fully compatible with the existing implementation and that your tests are robust enough to catch any regressions.

package.json (1)

91-91: Confirm "zod" Dependency Adjustment

By setting "zod": "next" in the root package.json, you have shifted your dependency resolution strategy to favor the latest pre-release version. Verify that your overall build process, integration tests, and any JSON schema generation logic are compatible with possible changes introduced by upcoming versions of Zod.

www/og-image/package.json (1)

14-14: Dependency Update for Zod Version
The dependency for Zod has been updated from a fixed range ("^3.24.2") to "next", which will always pull the latest pre-release version. This allows you to leverage new features and improvements; however, it also introduces a risk of breaking changes that could affect functionality, especially if any JSON schema-related code depends on specific behaviors of Zod. Please ensure your tests (including those for retrieving JSON schemas for procedures) thoroughly cover this change.

examples/standalone-server/package.json (1)

21-21: Switch to Latest Zod Version
Updating "zod" to "next" in this file aligns with the broader initiative. Since using a pre-release branch might sometimes lead to unexpected behavior, please confirm that all server-side validations (which might depend on Zod) are functioning as expected under the new dependency version.

examples/lazy-load/package.json (1)

16-16: Aligning Zod Version Usage
The "zod": "next" update here continues the uniform upgrade across the repository. Since the next tag refers to a dynamic version, it's important to verify that this does not inadvertently break any logicβ€”especially in parts of the code that might rely on stable behavior for JSON schema generation. Consider pinning a specific pre-release version if reproducibility becomes an issue.

examples/next-prisma-websockets-starter/package.json (1)

57-57: Consider specifying version constraints for dependency.

Using "next" for zod in example projects may cause inconsistent behavior if the library undergoes significant changes. Consider maintaining a stable version or documenting that this is using a pre-release version.

-    "zod": "next"
+    "zod": "^3.24.2" # or specify another stable version
examples/fastify-server/package.json (1)

26-26: Zod Version Update to "next"

Updating the dependency "zod": "next" switches from a fixed version range to tracking the latest pre-release version. This change can introduce instability or unexpected breaking changes in the API. Ensure that you have tested the integration thoroughly and consider monitoring compatibility as new pre-release features emerge.

examples/.test/diagnostics-big-router/package.json (1)

18-18: Zod Dependency Updated to "next"

The dependency "zod": "next" is now referenced instead of a fixed version. Verify that this change aligns with your test cases and that the project is compatible with any new or unstable APIs introduced in the pre-release version.

examples/.test/monotest-api-router01/package.json (1)

19-19: Bump Zod to the Latest Pre-release

Switching "zod": "next" may expose the project to breaking changes inherent in pre-release versions. Please confirm with adequate tests that the current use-cases handle any potential API modifications introduced in this version.

packages/react-query/package.json (1)

98-98: Zod Dependency in DevDependencies Updated

The change to "zod": "next" in the devDependencies means that the development environment will now use the latest pre-release of Zod. Ensure that any schema validations and type definitions relying on Zod are still consistent and that you have contingency plans if the pre-release introduces breaking changes.

examples/tanstack-start/package.json (1)

29-29: Updated Zod Reference to "next"

By setting "zod": "next", this project now depends on the latest pre-release version of Zod, which might include non-finalized or breaking features. Please make sure that comprehensive testing is in place to catch any regressions and that the upgrade aligns with your long-term stability requirements.

packages/tests/server/validators.test.ts (2)

673-675: Remove unused getRouter() function.

This function is defined but never called in the test. It appears to be redundant since the test directly references appRouter as AnyRouter instead.

-  function getRouter() {
-    return appRouter as AnyRouter; // Needs to be type-casted to AnyRouter to avoid circular references
-  }

723-723: Avoid using any type assertion.

The as any type assertion is used when calling z.toJSONSchema(). This bypasses TypeScript's type checking and can lead to runtime errors if the input isn't compatible. Consider strengthening this typing.

-        return proc._def.inputs.map((input) => z.toJSONSchema(input as any));
+        return proc._def.inputs.map((input) => {
+          // Only apply toJSONSchema to Zod schemas
+          if ('parse' in input && 'safeParse' in input) {
+            return z.toJSONSchema(input as ZodType);
+          }
+          return null;
+        }).filter(Boolean);
πŸ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between bd28640 and 0c492c4.

β›” Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
πŸ“’ Files selected for processing (36)
  • examples/.experimental/next-app-dir/package.json (1 hunks)
  • examples/.test/diagnostics-big-router/package.json (1 hunks)
  • examples/.test/monotest-api-router01/package.json (1 hunks)
  • examples/.test/monotest-api/package.json (1 hunks)
  • examples/.test/ssg-infinite-serialization/package.json (1 hunks)
  • examples/.test/ssg/package.json (1 hunks)
  • examples/cloudflare-workers/package.json (1 hunks)
  • examples/express-minimal/package.json (1 hunks)
  • examples/express-server/package.json (1 hunks)
  • examples/fastify-server/package.json (1 hunks)
  • examples/lambda-api-gateway/package.json (1 hunks)
  • examples/lazy-load/package.json (1 hunks)
  • examples/minimal-content-types/server/package.json (1 hunks)
  • examples/minimal-react/server/package.json (1 hunks)
  • examples/minimal/package.json (1 hunks)
  • examples/next-big-router/package.json (1 hunks)
  • examples/next-edge-runtime/package.json (1 hunks)
  • examples/next-formdata/package.json (1 hunks)
  • examples/next-minimal-starter/package.json (1 hunks)
  • examples/next-prisma-starter/package.json (1 hunks)
  • examples/next-prisma-todomvc/package.json (1 hunks)
  • examples/next-prisma-websockets-starter/package.json (1 hunks)
  • examples/next-sse-chat/package.json (1 hunks)
  • examples/standalone-server/package.json (1 hunks)
  • examples/tanstack-start/package.json (1 hunks)
  • examples/vercel-edge-runtime/package.json (1 hunks)
  • package.json (1 hunks)
  • packages/next/package.json (1 hunks)
  • packages/react-query/package.json (1 hunks)
  • packages/server/package.json (1 hunks)
  • packages/server/src/unstable-core-do-not-import/procedure.ts (2 hunks)
  • packages/tanstack-react-query/package.json (1 hunks)
  • packages/tests/server/validators.test.ts (3 hunks)
  • packages/upgrade/package.json (1 hunks)
  • www/og-image/package.json (1 hunks)
  • www/package.json (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
packages/server/src/unstable-core-do-not-import/procedure.ts (1)
packages/server/src/unstable-core-do-not-import/parser.ts (1)
  • Parser (62-62)
packages/tests/server/validators.test.ts (3)
packages/server/src/unstable-core-do-not-import/router.ts (1)
  • getProcedureAtPath (351-374)
packages/server/src/unstable-core-do-not-import/procedure.ts (1)
  • AnyProcedure (77-80)
packages/client/src/__tests__/testClientResource.ts (1)
  • testServerAndClientResource (47-141)
⏰ Context from checks skipped due to timeout of 90000ms (20)
  • GitHub Check: E2E-tests (.test/ssg)
  • GitHub Check: E2E-tests (nuxt)
  • GitHub Check: E2E-tests (next-prisma-starter)
  • GitHub Check: E2E-tests (next-prisma-todomvc)
  • GitHub Check: E2E-tests (.experimental/next-app-dir)
  • GitHub Check: E2E-tests (fastify-server)
  • GitHub Check: E2E-tests (tanstack-start)
  • GitHub Check: E2E-tests (next-minimal-starter)
  • GitHub Check: E2E-tests (.test/internal-types-export)
  • GitHub Check: E2E-tests (cloudflare-workers)
  • GitHub Check: E2E-tests (express-minimal)
  • GitHub Check: E2E-tests (next-prisma-websockets-starter)
  • GitHub Check: e2e-legacy-node (next-prisma-todomvc, 20.x)
  • GitHub Check: e2e-legacy-node (next-prisma-websockets-starter, 20.x)
  • GitHub Check: e2e-legacy-node (next-prisma-starter, 20.x)
  • GitHub Check: Release using pkg.pr.new
  • GitHub Check: E2E-tests (Bun) (bun, ubuntu-latest)
  • GitHub Check: E2E-tests (Deno) (deno-deploy)
  • GitHub Check: test
  • GitHub Check: Lint and auto-fix
πŸ”‡ Additional comments (19)
examples/.test/ssg/package.json (1)

23-23: Dependency Version Update for Zod
The dependency for zod has been updated from the fixed version range "^3.24.2" to "next". This change indicates a shift towards using the latest pre-release version of Zod. Please ensure that this change is compatible with the rest of the codebaseβ€”especially with any routines that generate or validate JSON schemasβ€”as pre-release versions might introduce breaking changes.

examples/express-minimal/package.json (1)

21-21: Zod Dependency Update
The "zod" dependency is now set to "next", aligning with the broader update across projects. Ensure that the transition to a pre-release version has been thoroughly validated in the context of the express-minimal example, and consider documenting any adjustments required due to potential API changes in Zod.

examples/next-big-router/package.json (1)

21-21: Updated Zod Version in Next-Big-Router Example
The update from "^3.24.2" to "next" for the zod dependency is consistent with changes made elsewhere. Verify that downstream codeβ€”particularly any JSON schema generation or validation logicβ€”remains fully functional with Zod's "next" release.

packages/upgrade/package.json (1)

51-51: Zod Dependency Update in Upgrade Package
In the devDependencies section, the zod dependency has been updated to "next". This change should be cross-verified with any upgrade scripts or tooling that depend on Zod’s API. Given the potential for breaking changes in pre-release versions, additional testing or runtime verification might be worthwhile.

examples/cloudflare-workers/package.json (1)

13-13: Cloudflare Workers Zod Dependency Change
The dependency for zod in the Cloudflare Workers example has been updated to "next". As the Cloudflare environment might be particularly sensitive to API changes, please ensure that all functionalities relying on Zodβ€”especially those pertaining to JSON schema derivation for proceduresβ€”are tested against this "next" version for compatibility and stability.

examples/next-minimal-starter/package.json (1)

20-20: Update Zod Dependency Version

The "zod" dependency is now set to "next" instead of the stable version constraint ("^3.24.2"). Please verify that using this pre-release version satisfies your compatibility and stability requirements across the project.

examples/vercel-edge-runtime/package.json (1)

13-13: Apply Zod "next" Version in Edge Runtime

The Zod version has been updated to "next". Given the edge runtime context, ensure that this pre-release version does not introduce any breaking changes or runtime issues.

examples/lambda-api-gateway/package.json (1)

18-18: Update Zod Version for Lambda API Gateway

The update to "zod": "next" aligns with changes across the repository. Since this example is used in a serverless context, please ensure that the pre-release version is stable within your serverless framework and passes all integration tests.

examples/next-sse-chat/package.json (1)

34-34: Assess Impact of Upgrading "zod" to "next"

Upgrading to "zod": "next" means that the dependency may change frequently and include experimental features. It’s important to ensure that any module relying on Zod (such as those involved in JSON schema procedures) functions correctly with these potential changes.

examples/.test/ssg-infinite-serialization/package.json (1)

23-23: Verify "zod" Version Change Consistency

Switching "zod" from "^3.24.2" to "next" will automatically pull in the latest pre-release version. Please double-check that this change does not interfere with your tests, particularly those related to schema generation or validation routines, and that all related components are updated accordingly.

examples/next-prisma-todomvc/package.json (1)

37-37: Consistent Zod Version Change
The change to "zod": "next" is consistent with the updates in other parts of the repository. Verify that integrating the pre-release version of Zod does not introduce compatibility issues, particularly in areas where JSON schemas are generated or validated. Regular cross-project testing is recommended.

examples/next-prisma-starter/package.json (1)

45-45: Zod Dependency Upgrade
The upgrade of the Zod dependency to "next" from "^3.24.2" should bring in the latest features needed for advanced schema generation, including the JSON schema functionalities referenced in this PR. Be mindful that this change might lead to minor API deviations; please ensure that your usage of Zod in the context of procedures and their JSON schemas is fully compatible with the new version.

packages/server/src/unstable-core-do-not-import/procedure.ts (2)

2-2: Import looks good.

The addition of the Parser import is necessary for the new property.


41-44:

Details

βœ… Verification successful

Good addition for schema support.

Adding the inputs property to the Procedure interface will allow for retrieving JSON schemas for procedures, aligning with the PR objective.


🏁 Script executed:

#!/bin/bash
# Check where the inputs property is being used
grep -r "inputs:" --include="*.ts" packages/server/src/

Length of output: 637


Approval: The integration of the inputs property is verified.

  • The new inputs: Parser[] declaration in packages/server/src/unstable-core-do-not-import/procedure.ts is correctly introduced.
  • Searches confirm that the property is appropriately used in procedureBuilder.ts and referenced consistently elsewhere, fulfilling the goal of supporting JSON schema retrieval for procedures.
packages/next/package.json (1)

111-111:

Details

❓ Verification inconclusive

Consider specifying version constraints for dependency.

Changing to the "next" tag for zod might introduce compatibility issues across different installations. For a published package like @trpc/next, it's generally better to use fixed versions or version ranges to ensure consistent behavior.


🏁 Script executed:

#!/bin/bash
# Check if any tests might be affected by the zod version change
grep -r "zod" --include="*.test.ts" packages/next/

Length of output: 50


Action Required: Specify Version Constraints for Zod Dependency

The dependency for zod in packages/next/package.json is currently set to "next". While our initial search in *.test.ts files didn’t return any results, please run the above script to verify if any test files (e.g., files matching *test*.ts or *spec*.ts) reference zod. Using the "next" tag risks compatibility issues across different installations. For a published package like @trpc/next, it is safer to use fixed versions or version ranges to ensure consistent behavior.

  • Location: packages/next/package.json (Line 111, "zod": "next")
  • Recommendation: Change this dependency to a specific version (or a version range) to mitigate potential compatibility issues.
  • Action: After verifying with additional test file searches, please update the dependency accordingly and run further integration testing if necessary.

---

🏁 Script executed:

```shell

#!/bin/bash
# Broader search for 'zod' in potential test files within packages/next
find packages/next/ -type f \( -name "*test*.ts" -or -name "*spec*.ts" \) -exec grep -H "zod" {} \;

Length of output: 226


Action Required: Specify Fixed Version Constraints for Zod Dependency

The dependency for zod in packages/next/package.json is still set to "next", which may lead to compatibility issues. Our recent expanded search for references to zod in test files (including files matching *test*.ts and *spec*.ts) did not return any results; however, this outcome alone doesn't conclusively prove that the change is harmless.

  • Location: packages/next/package.json (Line 111 – "zod": "next")
  • Investment: Change this dependency to a fixed version or version range (e.g., "zod": "^3.XX.X"), and then manually verify that no tests or other parts of the codebase are adversely affected.
  • Next Step: Please perform a manual review of the affected areas to ensure that this dependency change does not introduce subtle issues.
packages/tanstack-react-query/package.json (1)

74-74:

Details

❓ Verification inconclusive

Consider the implications of using "next" as version specifier.

Switching from a specific version range (^3.24.2) to the "next" tag means you'll always use the latest pre-release version of Zod. While this allows you to access cutting-edge features needed for JSON schema extraction, it could lead to unexpected behavior if the "next" version introduces breaking changes.


🏁 Script executed:

#!/bin/bash
# Check what version the "next" tag currently resolves to and if it's stable
npm view zod@next version
npm view zod@next dist-tags

Length of output: 240


Action Required: Validate the Use of Zod Pre-Release

The zod dependency in packages/tanstack-react-query/package.json is specified as "next", which currently resolves to the pre-release version 4.0.0-beta.20250411T005215 as confirmed by the npm output. This is a significant shift from the previous stable version (^3.24.2). While leveraging the pre-release version may offer cutting-edge features (e.g., for JSON schema extraction), please evaluate the following:

  • Stability Risk: Pre-release versions (beta releases) can introduce breaking changes unexpectedly.
  • Feature Needs: Confirm that the new features in version 4.0.0-beta are essential for your use-case.
  • Testing: Ensure comprehensive testing is in place to catch any regressions or issues introduced by this beta version.

Please verify that this change aligns with your stability requirements and development strategy before merging.

packages/tests/server/validators.test.ts (3)

704-724: Good implementation of JSON schema extraction.

This procedure elegantly accesses procedure input validators and converts them to JSON schema. This implements the core functionality needed for issue #6691, providing a way to get the JSON schema for a procedure.


727-727: Good use of resource management with await using.

Using the await using statement for the test resource ensures proper cleanup of resources even if the test fails. This is a modern approach to resource management in JavaScript/TypeScript.


669-782: Great test implementation for retrieving JSON schemas.

This comprehensive test demonstrates how to retrieve and validate JSON schemas for procedures with different input types. It shows that the feature works with both simple objects and arrays, and handles multiple inputs on a single procedure. The test aligns perfectly with the PR objective of providing a method to obtain JSON schemas for procedures.

Comment thread www/package.json Resolved

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

πŸ”­ Outside diff range comments (1)
packages/tests/server/validators.test.ts (1)

99-142: ⚠️ Potential issue

Remove duplicate test case.

There are two identical "zod v4 transform mixed input/output" test cases. The second one (lines 206-249) should be removed as it's a complete duplicate of the first one (lines 99-142).

-test('zod v4 transform mixed input/output', async () => {
-  const t = initTRPC.create();
-  const input = zod4.object({
-    length: zod4.string().transform((s) => s.length),
-  });
-
-  const router = t.router({
-    num: t.procedure.input(input).query(({ input }) => {
-      expectTypeOf(input.length).toBeNumber();
-      return {
-        input,
-      };
-    }),
-  });
-
-  const { close, client } = routerToServerAndClientNew(router);
-
-  await expect(client.num.query({ length: '123' })).resolves
-    .toMatchInlineSnapshot(`
-            Object {
-              "input": Object {
-                "length": 3,
-              },
-            }
-          `);
-
-  await expect(
-    // @ts-expect-error this should only accept a string
-    client.num.query({ length: 123 }),
-  ).rejects.toMatchInlineSnapshot(`
-    [TRPCClientError: [
-      {
-        "expected": "string",
-        "code": "invalid_type",
-        "path": [
-          "length"
-        ],
-        "message": "Invalid input: expected string, received number"
-      }
-    ]]
-  `);
-
-  await close();
-});

Also applies to: 206-249

πŸ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 734cbd9 and c1bc729.

πŸ“’ Files selected for processing (2)
  • packages/react-query/test/formData.test.tsx (1 hunks)
  • packages/tests/server/validators.test.ts (8 hunks)
βœ… Files skipped from review due to trivial changes (1)
  • packages/react-query/test/formData.test.tsx
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: test
  • GitHub Check: Lint and auto-fix
  • GitHub Check: Analyze (typescript)
πŸ”‡ Additional comments (6)
packages/tests/server/validators.test.ts (6)

3-3: Import additions look good.

The new imports for test utilities, types, and the unstable core function are appropriate for the new test functionality being added.

Also applies to: 5-5, 7-7


17-18: Good explicit versioning for Zod imports.

Using explicit version imports (zod/v3 and zod/v4) makes it clear which version is being tested and prevents confusion between the different Zod versions.


36-36: Test renamed appropriately for clarity.

The rename from "zod" to "zod v3" and corresponding usage change from zod to zod3 maintains backward compatibility testing while making version-specific behavior explicit.

Also applies to: 40-40


66-66: Consistent v3 test naming and usage.

Good consistency with the previous test rename pattern.

Also applies to: 68-68


734-734: Consistent migration to zod3.

Good update to maintain consistency with the explicit versioning approach.


895-895: Consistent migration to zod3 in regression test.

Good consistency with the explicit versioning approach in the regression test.

Also applies to: 897-898

Comment on lines +774 to +892
test('recipe: get json schemas for procedure', async () => {
const t = initTRPC.create();
const publicProcedure = t.procedure;

function getRouter() {
return appRouter as AnyRouter; // Needs to be type-casted to AnyRouter to avoid circular references
}

const appRouter = t.router({
single: publicProcedure
.input(
zod4.object({
foo: zod4.string(),
}),
)
.query((opts) => {
return opts.input;
// ^?
}),
list: publicProcedure
.input(
zod4.object({
foo: zod4.array(zod4.string()),
}),
)
.input(
zod4.object({
bar: zod4.array(zod4.string()),
}),
)
.query((opts) => {
return opts.input;
// ^?
}),

getJsonSchemas: publicProcedure
.input(
zod4.object({
path: zod4.string(),
}),
)
.query(async (opts) => {
const proc = await getProcedureAtPath(
// Needs to be type-casted to AnyRouter to avoid circular references
appRouter as AnyRouter,
opts.input.path,
);

expectTypeOf(proc).toMatchTypeOf<AnyTRPCProcedure | null>();

if (!proc) {
return null;
}

return proc._def.inputs.map((input) => zod4.toJSONSchema(input as any));
}),
});

await using ctx = testServerAndClientResource(appRouter);

const client = ctx.client;

expect(await client.getJsonSchemas.query({ path: 'single' }))
.toMatchInlineSnapshot(`
Array [
Object {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"additionalProperties": false,
"properties": Object {
"foo": Object {
"type": "string",
},
},
"required": Array [
"foo",
],
"type": "object",
},
]
`);

expect(await client.getJsonSchemas.query({ path: 'list' }))
.toMatchInlineSnapshot(`
Array [
Object {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"additionalProperties": false,
"properties": Object {
"foo": Object {
"items": Object {
"type": "string",
},
"type": "array",
},
},
"required": Array [
"foo",
],
"type": "object",
},
Object {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"additionalProperties": false,
"properties": Object {
"bar": Object {
"items": Object {
"type": "string",
},
"type": "array",
},
},
"required": Array [
"bar",
],
"type": "object",
},
]
`);
});

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.

πŸ’‘ Verification agent

🧩 Analysis chain

Review usage of unstable API and test implementation.

The new test demonstrates a useful feature for getting JSON schemas from procedures. However, there are several considerations:

  1. Unstable API Usage: The test uses getProcedureAtPath from an unstable import, which is appropriate for a test demonstrating this functionality.

  2. Internal API Access: Line 828 accesses proc._def.inputs which is a private/internal property. This could be fragile if the internal structure changes.

  3. Type Casting: The test uses as any when calling zod4.toJSONSchema(input as any), which bypasses type safety.

Consider documenting the fragility of this approach since it relies on internal APIs. Verify that this pattern is intended for public use:


🏁 Script executed:

#!/bin/bash
# Description: Check if there are other usages of _def.inputs pattern in the codebase

echo "=== Searching for _def.inputs usage ==="
rg -A 3 -B 3 '_def\.inputs' 

echo "=== Searching for getProcedureAtPath usage ==="
rg -A 3 -B 3 'getProcedureAtPath'

Length of output: 6441


Improve test resilience around internal APIs

The new test effectively verifies JSON‐schema generation, but it relies on unstable and private implementation details that could easily break with internal changes. Please address the following:

  • Unstable import
    β€’ We’re pulling getProcedureAtPath from @trpc/server/unstable-core-do-not-import, which is explicitly marked @internal.
    β€’ Suggestions: add a // TODO or JSDoc comment noting this fragility, or consider exposing a stable helper in core for this use case.

  • Accessing private _def.inputs
    β€’ No other codebase usage of proc._def.inputs was foundβ€”this property is entirely internal.
    β€’ Suggestions: likewise document that this may change, or wrap this logic in your own test‐only helper that can be easily updated if TRPC internals evolve.

  • Bypassing type safety with as any
    β€’ The call zod4.toJSONSchema(input as any) silences type errors but loses compile‐time guarantees.
    β€’ Suggestions: narrow the cast to ZodTypeAny (e.g. input as ZodTypeAny) or write a small wrapper function that enforces the correct Zod type before calling toJSONSchema.

File: packages/tests/server/validators.test.ts
Lines: ~828

- return proc._def.inputs.map((input) => zod4.toJSONSchema(input as any));
+ // TODO: relies on private `_def.inputs`β€”update if TRPC internals change
+ return proc._def.inputs
+   .map((input: import('zod').ZodTypeAny) => zod4.toJSONSchema(input));
πŸ“ Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
test('recipe: get json schemas for procedure', async () => {
const t = initTRPC.create();
const publicProcedure = t.procedure;
function getRouter() {
return appRouter as AnyRouter; // Needs to be type-casted to AnyRouter to avoid circular references
}
const appRouter = t.router({
single: publicProcedure
.input(
zod4.object({
foo: zod4.string(),
}),
)
.query((opts) => {
return opts.input;
// ^?
}),
list: publicProcedure
.input(
zod4.object({
foo: zod4.array(zod4.string()),
}),
)
.input(
zod4.object({
bar: zod4.array(zod4.string()),
}),
)
.query((opts) => {
return opts.input;
// ^?
}),
getJsonSchemas: publicProcedure
.input(
zod4.object({
path: zod4.string(),
}),
)
.query(async (opts) => {
const proc = await getProcedureAtPath(
// Needs to be type-casted to AnyRouter to avoid circular references
appRouter as AnyRouter,
opts.input.path,
);
expectTypeOf(proc).toMatchTypeOf<AnyTRPCProcedure | null>();
if (!proc) {
return null;
}
return proc._def.inputs.map((input) => zod4.toJSONSchema(input as any));
}),
});
await using ctx = testServerAndClientResource(appRouter);
const client = ctx.client;
expect(await client.getJsonSchemas.query({ path: 'single' }))
.toMatchInlineSnapshot(`
Array [
Object {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"additionalProperties": false,
"properties": Object {
"foo": Object {
"type": "string",
},
},
"required": Array [
"foo",
],
"type": "object",
},
]
`);
expect(await client.getJsonSchemas.query({ path: 'list' }))
.toMatchInlineSnapshot(`
Array [
Object {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"additionalProperties": false,
"properties": Object {
"foo": Object {
"items": Object {
"type": "string",
},
"type": "array",
},
},
"required": Array [
"foo",
],
"type": "object",
},
Object {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"additionalProperties": false,
"properties": Object {
"bar": Object {
"items": Object {
"type": "string",
},
"type": "array",
},
},
"required": Array [
"bar",
],
"type": "object",
},
]
`);
});
if (!proc) {
return null;
}
// TODO: relies on private `_def.inputs`β€”update if TRPC internals change
return proc._def.inputs
.map((input: import('zod').ZodTypeAny) => zod4.toJSONSchema(input));
πŸ€– Prompt for AI Agents
In packages/tests/server/validators.test.ts around line 828, the test uses
unstable and internal APIs: it imports getProcedureAtPath from an internal
unstable module, accesses the private property proc._def.inputs, and casts
inputs with 'as any' which bypasses type safety. To fix this, add clear comments
or TODOs documenting the fragility and internal nature of these usages, consider
wrapping the proc._def.inputs access in a test-only helper function for easier
future maintenance, and replace the 'as any' cast with a narrower cast to
ZodTypeAny or create a small wrapper function that enforces correct Zod types
before calling zod4.toJSONSchema. This will improve test resilience and
maintainability.

@github-actions

github-actions Bot commented Jun 4, 2025

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.

This branch was successfully deployed

5 active deployments
Preview – www β€” 50f01da1 Deployed Jun 3, 2025 by vercel[bot]
Preview – trpc-next-app-dir β€” 50f01da1 Deployed Jun 3, 2025 by vercel[bot]
Preview – next-prisma-starter β€” 50f01da1 Deployed Jun 3, 2025 by vercel[bot]
Preview – examples-todomvc β€” 50f01da1 Deployed Jun 3, 2025 by vercel[bot]
Preview – og-image β€” 50f01da1 Deployed Jun 3, 2025 by vercel[bot]
trpc-pr-6696 β€” 50f01da1 Deployed Jun 3, 2025 by railway-app[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: expose JSON schemas for all inputs/outputs

2 participants