Repository navigation
chore(recipe): get json schema for procedure - #6696
Conversation
|
Important Review skippedReview was skipped due to path filters β Files ignored due to path filters (1)
CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including You can disable this status message by setting the WalkthroughThis pull request updates the version specification for the Zod dependency in multiple projects from Changes
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
Assessment against linked issues
Poem
πͺ§ TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
|
π Deployed to the trpc-pr-6696 environment in trpc-sse-and-websockets
|
|
The latest updates on your projects. Learn more about Vercel for Git βοΈ
|
@trpc/client
@trpc/next
@trpc/react-query
@trpc/server
@trpc/tanstack-react-query
@trpc/upgrade
commit: |
There was a problem hiding this comment.
Actionable comments posted: 1
π§Ή Nitpick comments (21)
examples/minimal-react/server/package.json (1)
13-13: Unify Zod Dependency for Minimal React ServerThe 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 UpdateThe 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 AdjustmentBy setting
"zod": "next"in the rootpackage.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 thenexttag 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 versionexamples/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-releaseSwitching
"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 UpdatedThe 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 unusedgetRouter()function.This function is defined but never called in the test. It appears to be redundant since the test directly references
appRouter as AnyRouterinstead.- function getRouter() { - return appRouter as AnyRouter; // Needs to be type-casted to AnyRouter to avoid circular references - }
723-723: Avoid usinganytype assertion.The
as anytype assertion is used when callingz.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
β Files ignored due to path filters (1)
pnpm-lock.yamlis 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 forzodhas 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 thezoddependency 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, thezoddependency 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 forzodin 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 VersionThe
"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 RuntimeThe 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 GatewayThe 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 ConsistencySwitching
"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
inputsproperty 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
inputsproperty is verified.
- The new
inputs: Parser[]declaration inpackages/server/src/unstable-core-do-not-import/procedure.tsis correctly introduced.- Searches confirm that the property is appropriately used in
procedureBuilder.tsand 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.jsonis currently set to"next". While our initial search in*.test.tsfiles didnβt return any results, please run the above script to verify if any test files (e.g., files matching*test*.tsor*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.jsonis 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*.tsand*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-tagsLength of output: 240
Action Required: Validate the Use of Zod Pre-Release
The
zoddependency inpackages/tanstack-react-query/package.jsonis 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 withawait using.Using the
await usingstatement 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.
There was a problem hiding this comment.
Actionable comments posted: 2
π Outside diff range comments (1)
packages/tests/server/validators.test.ts (1)
99-142:β οΈ Potential issueRemove 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
π 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/v3andzod/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
zodtozod3maintains 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
| 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", | ||
| }, | ||
| ] | ||
| `); | ||
| }); |
There was a problem hiding this comment.
π‘ 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:
-
Unstable API Usage: The test uses
getProcedureAtPathfrom an unstable import, which is appropriate for a test demonstrating this functionality. -
Internal API Access: Line 828 accesses
proc._def.inputswhich is a private/internal property. This could be fragile if the internal structure changes. -
Type Casting: The test uses
as anywhen callingzod4.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 pullinggetProcedureAtPathfrom@trpc/server/unstable-core-do-not-import, which is explicitly marked@internal.
β’ Suggestions: add a// TODOor 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 ofproc._def.inputswas 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 callzod4.toJSONSchema(input as any)silences type errors but loses compileβtime guarantees.
β’ Suggestions: narrow the cast toZodTypeAny(e.g.input as ZodTypeAny) or write a small wrapper function that enforces the correct Zod type before callingtoJSONSchema.
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.
| 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.
|
This pull request has been locked because we are very unlikely to see comments on closed issues. If you think, this PR is still necessary, create a new one with the same branch. Thank you. |
Closes #6691
π― Changes
How to get json schema for procedure
trpc/packages/tests/server/validators.test.ts
Lines 669 to 782 in 0c492c4
Summary by CodeRabbit
Chores
Tests