Skip to content

feat: Support OpenAPI json generation for any tRPC appRouter - #7231

Merged
Nick-Lucas merged 68 commits into
mainfrom
feature/openapi
Mar 14, 2026
Merged

Nick-Lucas merged 68 commits into
mainfrom
feature/openapi

Conversation

@Nick-Lucas

@Nick-Lucas Nick-Lucas commented Mar 8, 2026 •

Copy link
Copy Markdown
Contributor

To see the RFC+Discussion: #7239 (comment)

🎯 Changes

What changes are made in this PR? Is it a feature or a bug fix?

Adds a TypeScript-compiler-driven OpenAPI 3.1 document generator to @trpc/openapi. The generator resolves fully-computed types (what the vanilla client proxy sees) rather than raw mapped/generic types, and emits a standards-compliant JSON spec, possible for use with any generator or consumer of such a document

This diff is big and it mostly doesn't matter because it's testing code which you can ignore!

Focus on:

  • packages/openapi/src/generate.ts
  • packages/openapi/test/generate.test.ts
  • examples/openapi-codegen (based on the minimal example)
  • The versions script has been updating to publish this package as 11.12.0-alpha and update the version number of releases

βœ… 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

    • Added OpenAPI generation for tRPC routers: generate OpenAPI 3.1 specs from tRPC AppRouter via generateOpenAPIDocument() function or CLI.
    • Added CLI tool with options for custom export names, titles, and versions.
    • Added integration with hey-api client generator to produce typed REST clients from generated specs.
    • Added helper to configure hey-api clients with data transformers (e.g., superjson).
  • Documentation

    • Added guide for OpenAPI/REST client generation workflow.
  • Examples

    • Added example project demonstrating end-to-end OpenAPI codegen and client usage.

Copilot AI review requested due to automatic review settings March 8, 2026 15:36
@Nick-Lucas
Nick-Lucas requested review from a team as code owners March 8, 2026 15:36
@vercel

vercel Bot commented Mar 8, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated (UTC)
next-prisma-starter Ready Ready Preview Mar 14, 2026 11:19pm
og-image Ready Ready Preview, Comment Mar 14, 2026 11:19pm

Request Review

@railway-app
railway-app Bot temporarily deployed to trpc-sse-and-websockets / trpc-pr-7231 March 8, 2026 15:36 Destroyed
@railway-app

railway-app Bot commented Mar 8, 2026 •

Copy link
Copy Markdown

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

Service Status Web Updated (UTC)
next-prisma-websockets-starter 😴 Sleeping (View Logs) Mar 14, 2026 at 11:30 pm
next-sse-chat βœ… Success (View Logs) Web Mar 14, 2026 at 11:25 pm

@coderabbitai

coderabbitai Bot commented Mar 8, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▢️ Resume reviews
  • πŸ” Trigger review

Walkthrough

New @trpc/openapi package enables OpenAPI 3.1.1 specification generation from tRPC routers through CLI and programmatic APIs. Includes TypeScript type-to-schema conversion with circular reference handling, hey-api client integration, and comprehensive test fixtures demonstrating complex tRPC types.

Changes

Cohort / File(s) Summary
Core OpenAPI Generation
packages/openapi/src/generate.ts, packages/openapi/src/cli.ts, packages/openapi/src/index.ts
Implements TypeScript type reflection to extract tRPC procedures and convert types to JSON schemas with named component extraction, error handling, and OpenAPI document assembly. CLI supports --export, --output, --title, --version flags.
Hey-API Integration
packages/openapi/src/heyapi/index.ts
Provides createTRPCHeyApiClientConfig helper to wire data transformers (superjson) with hey-api clients, handling query/body serialization and response transformation.
Package Configuration
packages/openapi/package.json, packages/openapi/tsconfig.json, packages/openapi/tsconfig.build.json, packages/openapi/tsdown.config.ts, packages/openapi/vitest.config.ts
Configures ESM/CJS exports, dual build entry points (main lib + CLI binary), TypeScript settings, and test execution with globalSetup codegen.
Test Fixtures & Routers
packages/openapi/test/routers/appRouter.ts, packages/openapi/test/routers/superjsonRouter.ts, packages/openapi/test/routers/errorFormatterRouter.ts
Comprehensive tRPC routers demonstrating enum/literal/union/intersection types, recursive structures, date handling, branded types, error formatting, and superjson transformer integration.
Codegen Scripts
packages/openapi/test/scripts/codegen.ts, packages/openapi/test/scripts/codegen.run.ts, packages/openapi/test/scripts/globalSetup.ts
Scripts to generate OpenAPI specs from test routers, invoke hey-api client generator, and wire global test setup for codegen execution.
Generated OpenAPI Specs
packages/openapi/test/routers/*.ts.json
Auto-generated OpenAPI 3.1.1 specifications for each test router with path definitions, component schemas, error response shapes, and request/response contracts.
Generated Hey-API Clients
packages/openapi/test/routers/*-heyapi/*
Auto-generated TypeScript SDK clients by @hey-api/openapi-ts including client factory, types, request/response handling, auth, SSE support, parameter serialization, and URL building utilities across multiple modules.
Test Suite
packages/openapi/test/generate.test.ts
Comprehensive tests validating OpenAPI generation, schema extraction, error formatting, recursive type handling, hey-api SDK generation/execution, superjson transformer integration, and HTTP endpoint testing.
Documentation & Configuration
www/docs/client/openapi.md, www/sidebars.ts, tsconfig.json, scripts/version.ts
New OpenAPI documentation covering CLI usage and programmatic generation, sidebar entry, path mappings, and prerelease version handling in dependency pinning.
Example Project
examples/openapi-codegen/*
Complete example demonstrating OpenAPI generation from tRPC router, SDK codegen, HTTP server setup, and typed client usage with transformers.

Sequence Diagram(s)

sequenceDiagram
    participant CLI as CLI/generateOpenAPIDocument
    participant TypeScript as TypeScript Compiler
    participant Generator as Schema Generator
    participant Components as Component Extractor
    participant Builder as Document Builder

    CLI->>TypeScript: Load TS program & find router export
    TypeScript-->>CLI: Router type symbol
    CLI->>Generator: Walk router type structure
    Generator->>Components: Extract named types as schemas
    Components-->>Generator: Schema references & components
    Generator-->>CLI: Procedures (queries/mutations) + Error schema
    CLI->>Builder: Assemble OpenAPI document
    Builder->>Builder: Build paths from procedures<br/>(wrap outputs in tRPC envelope)
    Builder->>Builder: Attach error responses<br/>& component schemas
    Builder-->>CLI: Complete OpenAPIDocument
    CLI-->>CLI: Write JSON file
Loading
sequenceDiagram
    participant Client as Generated SDK Client
    participant Config as createTRPCHeyApiClientConfig
    participant Serializer as Query Serializer
    participant HTTP as HTTP Layer
    participant Server as tRPC Server

    Client->>Config: Initialize with optional transformer
    Config->>Config: Normalize transformer<br/>(superjson)
    Config-->>Client: querySerializer + bodySerializer<br/>+ responseTransformer
    Client->>Serializer: Serialize query params<br/>(input field + transformer)
    Serializer-->>Client: URL-encoded params
    Client->>HTTP: Execute request with serialized params
    HTTP->>Server: GET /procedure?input=...
    Server-->>HTTP: JSON response with typed data
    HTTP->>Client: Response body
    Client->>Client: Apply responseTransformer<br/>(deserialize dates, etc.)
    Client-->>Client: Typed result
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Justification: The PR introduces substantial hand-written logic in generate.ts (~1100 lines) for TypeScript type reflection, schema extraction, and circular reference handlingβ€”requiring careful review of type traversal correctness and edge case handling. The CLI and hey-api integration modules are moderately complex. While the bulk of generated client code (5000+ lines) comes from @hey-api/openapi-ts and requires lighter review, the overall scope spans multiple cohorts with heterogeneous patterns (reflection logic, CLI argument parsing, helper integrations, codegen coordination). Test fixtures are straightforward but numerous. Configuration is standard. The complexity is concentrated in the core generation algorithm and its interaction with TypeScript's type system.

Possibly related PRs

Suggested labels

feature, documentation, packages

🐰 A spec is born from types so fair,
OpenAPI flows through the TypeScript air,
REST clients emerge from schemas divine,
Hey-API and tRPC in harmony align! ✨

✨ Finishing Touches
  • πŸ“ Generate docstrings (stacked PR)
  • πŸ“ Generate docstrings (commit on current branch)
πŸ§ͺ Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/openapi

Copilot AI 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.

Pull request overview

Adds a new @trpc/openapi package to generate OpenAPI documents from a tRPC router via TypeScript compiler type analysis, plus docs and test fixtures to support OpenAPI-driven REST client generation.

Changes:

  • Introduces @trpc/openapi with generateOpenAPIDocument, a CLI (trpc-openapi), and hey-api client helpers.
  • Adds a new docs page and sidebar entry for OpenAPI export and REST client generation.
  • Adds extensive OpenAPI generation tests and router fixtures (including hey-api codegen outputs).

Reviewed changes

Copilot reviewed 25 out of 28 changed files in this pull request and generated 10 comments.

Show a summary per file
File Description
www/sidebars.ts Adds the new OpenAPI doc page to the client docs sidebar.
www/docs/client/openapi.md New documentation page describing OpenAPI export and client generation workflow.
tsconfig.json Adds TS path aliases for @trpc/openapi package source.
scripts/version.ts Updates version pinning logic to preserve alpha/beta suffixes and pin deps to base version.
packages/openapi/vitest.config.ts Adds a per-package vitest config with global setup and watch triggers.
packages/openapi/tsdown.config.ts Build config for library entrypoints and CLI bundle output.
packages/openapi/tsconfig.json Package-local TS config for src/test compilation.
packages/openapi/tsconfig.build.json Build TS config for declarations output to dist.
packages/openapi/test/scripts/globalSetup.ts Intended vitest global setup hook to run hey-api codegen.
packages/openapi/test/scripts/codegen.ts Generates OpenAPI JSON + hey-api SDKs for all test routers.
packages/openapi/test/scripts/codegen.run.ts Node entrypoint to run the async codegen script.
packages/openapi/test/routers/superjsonRouter.ts.json Generated OpenAPI JSON artifact for superjsonRouter.
packages/openapi/test/routers/superjsonRouter.ts Router fixture using superjson transformer and z.date().
packages/openapi/test/routers/errorFormatterRouter.ts.json Generated OpenAPI JSON artifact for errorFormatterRouter.
packages/openapi/test/routers/errorFormatterRouter.ts Router fixture with custom errorFormatter shape.
packages/openapi/test/routers/appRouter.ts.json Large generated OpenAPI JSON artifact for the main fixture router.
packages/openapi/test/routers/appRouter.ts Comprehensive router fixture covering many TS/Zod type shapes.
packages/openapi/test/routers/.prettierignore Ignores generated subdirectories under test routers for prettier.
packages/openapi/test/routers/.gitignore Ignores generated subdirectories under test routers for git.
packages/openapi/test/routers/.eslintignore Ignores generated subdirectories under test routers for eslint.
packages/openapi/test/generate.test.ts New test suite validating spec generation + hey-api client roundtrips.
packages/openapi/src/index.ts Public entrypoint exports generator API + types.
packages/openapi/src/heyapi/index.ts Adds hey-api config helper to interop with tRPC query/body/envelopes.
packages/openapi/src/generate.ts Core TS-compiler-based router walker + JSON Schema/OpenAPI builder.
packages/openapi/src/cli.ts New trpc-openapi CLI for generating JSON specs.
packages/openapi/package.json New package definition, exports map, bin entry, scripts, deps/peers.
.prettierignore Adjusts ignore formatting and adds an ignore entry for an OpenAPI JSON path.

πŸ’‘ Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread packages/openapi/package.json Resolved
Comment thread packages/openapi/src/generate.ts Resolved
Comment thread packages/openapi/src/generate.ts Resolved
Comment thread .prettierignore Resolved
Comment thread scripts/version.ts Resolved
Comment thread packages/openapi/test/generate.test.ts Resolved
Comment thread packages/openapi/src/cli.ts 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: 9

🧹 Nitpick comments (6)
scripts/version.ts (1)

31-45: Numbered prereleases collapse to bare channel versions during version normalization.

Lines 32–36 extract only the channel name (alpha or beta) without preserving the full prerelease identifier. The regex pattern /-(alpha|beta)(\b|$)/ causes versions like 11.0.0-alpha.1 or 11.0.0-beta.2 to be rewritten as 11.0.0-alpha or 11.0.0-beta. Since this script runs from the version hook (package.json:29–30), this would mutate post-bump versions unintentionally.

Suggested fix
-  const prereleaseMatch = version.match(/-(alpha|beta)(\b|$)/);
+  const prereleaseMatch = version.match(
+    /-((alpha|beta)(?:[.-][0-9A-Za-z-]+)*)$/,
+  );

This captures the complete prerelease identifier including build metadata.

πŸ€– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@scripts/version.ts` around lines 31 - 45, The prerelease normalization
currently captures only the channel name via prereleaseMatch =
version.match(/-(alpha|beta)(\b|$)/) and rebuilds suffixedVersion as
`${baseVersion}-${suffix}`, which strips numeric identifiers like .1 or .2;
update the regex/search used in prereleaseMatch to capture the entire prerelease
token (e.g., include following dot/identifier segments) so that suffixedVersion
preserves the full identifier (use the captured full suffix when building
suffixedVersion and when replacing `"version": "${version}"` in content and
assigning version). Ensure you reference prereleaseMatch, suffix, baseVersion,
suffixedVersion, content.replace and version when making the change.
packages/openapi/test/routers/appRouter.ts (2)

623-672: Inconsistent pattern: simpleCases uses object literal instead of t.router().

Unlike the other nested routers (user, complexTypes, inferredReturns, namedTypes, recursiveTypes) which use t.router({...}), simpleCases is defined as a plain object literal. The OpenAPI generator handles both patterns (via walkType falling back to walkRecord for plain objects), but this inconsistency may confuse readers.

If intentional (to test generator behavior with plain RouterRecord objects), consider adding a comment. Otherwise:

♻️ Suggested fix for consistency
-  simpleCases: {
+  simpleCases: t.router({
     nullish: t.procedure
       // ...
     nullable: t.procedure
       // ...
-  },
+  }),
πŸ€– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/openapi/test/routers/appRouter.ts` around lines 623 - 672, The
simpleCases entry is defined as a plain object literal while other nested
routers use t.router(...), causing inconsistency; change the simpleCases
declaration to use t.router({...}) with the same procedures (simpleCases:
t.router({ nullish: t.procedure... , optional: ..., nullable: ... })) so the
shape matches other nested routers (refer to symbol simpleCases and t.router) or
alternatively add a clarifying comment above simpleCases indicating the plain
object is intentional to test walkRecord/walkType behavior.

1-1: Prefer namespace import for Zod.

♻️ Suggested fix
-import { z } from 'zod';
+import * as z from 'zod';
πŸ€– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/openapi/test/routers/appRouter.ts` at line 1, Replace the current
named import "import { z } from 'zod';" with a namespace import so all Zod
symbols are accessed via the namespace (e.g., change to a namespace-style import
and keep existing usages of "z" intact); update the import statement at the top
of the file where "z" is declared (so code referencing z.<something> continues
to work but now comes from the zod namespace).
packages/openapi/test/routers/errorFormatterRouter.ts (1)

1-1: Prefer namespace import for Zod.

♻️ Suggested fix
-import { z } from 'zod';
+import * as z from 'zod';
πŸ€– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/openapi/test/routers/errorFormatterRouter.ts` at line 1, Replace the
named import of Zod with a namespace import: change the import statement that
currently brings in "{ z }" from 'zod' to a namespace import (import * as z from
'zod') and update any references if necessary; locate the import line and adjust
it so the rest of the file (uses of z.object, z.string, etc.) continue to work
with the z namespace.
packages/openapi/test/routers/superjsonRouter.ts (1)

2-2: Prefer namespace import for Zod.

As per coding guidelines: "Prefer namespace imports for validation libraries and large modules (e.g., import * as z from 'zod')".

♻️ Suggested fix
-import { z } from 'zod';
+import * as z from 'zod';
πŸ€– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/openapi/test/routers/superjsonRouter.ts` at line 2, Change the
default import of Zod to a namespace import to follow the codebase convention:
replace the current "import { z } from 'zod'" with a namespace import (import *
as z from 'zod') so all Zod utilities are accessed via the z namespace; update
any usages that assume the named import (symbol z) if needed to work with the
namespace import.
packages/openapi/src/heyapi/index.ts (1)

78-91: Consider safer property access and reducing type assertions.

The current implementation assumes result.data and error.data always exist when their parent properties are present. If these nested properties are undefined, calling deserialize(undefined) may behave unexpectedly depending on the transformer (e.g., superjson throws on undefined input).

Additionally, the multiple (data as any) casts could be replaced with a narrower type assertion at the top.

♻️ Proposed improvement
       responseTransformer: async (data: unknown) => {
-        if (!!data && typeof data === 'object' && 'result' in data) {
-          (data as any).result.data = transformer.output.deserialize(
-            (data as any).result.data,
-          );
-        }
-        if (!!data && typeof data === 'object' && 'error' in data) {
-          (data as any).error.data = transformer.output.deserialize(
-            (data as any).error.data,
-          );
+        const response = data as Record<string, unknown> | null | undefined;
+        if (response && typeof response === 'object') {
+          const result = response.result as Record<string, unknown> | undefined;
+          if (result && 'data' in result) {
+            result.data = transformer.output.deserialize(result.data);
+          }
+          const error = response.error as Record<string, unknown> | undefined;
+          if (error && 'data' in error) {
+            error.data = transformer.output.deserialize(error.data);
+          }
         }

         return data;
       },
πŸ€– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/openapi/src/heyapi/index.ts` around lines 78 - 91, In
responseTransformer, avoid blanket any casts and calling
transformer.output.deserialize on possibly undefined nested properties; narrow
the top-level assertion once (e.g., const obj = data as Record<string, unknown>
| null) and then check that obj.result?.data !== undefined before calling
transformer.output.deserialize(obj.result.data) and similarly guard
obj.error?.data !== undefined before deserializing; update the code to only call
transformer.output.deserialize when the nested .data exists and assign back into
the same nested slot.
πŸ€– Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/openapi/package.json`:
- Around line 22-24: Remove the "postinstall": "pnpm run codegen" lifecycle from
packages/openapi's package.json so consumers of the published tarball won't run
a repo-only codegen step during install; keep the "codegen": "tsx
test/scripts/codegen.ts" script for local/dev use and move any automatic codegen
to repo-only hooks (CI or root-level scripts) or a "prepare" script that is
executed before publishing, but do not rely on postinstall in the published
package.

In `@packages/openapi/src/cli.ts`:
- Around line 85-86: Update the help text and JSDoc to reflect the actual output
version 3.1.1: change the HELP constant string (HELP) from "OpenAPI 3.0" to
"OpenAPI 3.1.1" and also update the JSDoc comment at the top of the file (the
JSDoc lines currently referencing OpenAPI 3.0) to state OpenAPI 3.1.1 so
documentation matches the generator output.

In `@packages/openapi/src/generate.ts`:
- Around line 983-986: The JSDoc above the TypeScript router analysis currently
says "OpenAPI 3.0 document" which is inaccurate because buildOpenAPIDocument
produces "openapi": "3.1.1"; update that JSDoc sentence (the comment starting
"Analyse the given TypeScript router file...") to state "OpenAPI 3.1.1 document"
or a generic "OpenAPI 3.x document" so it matches buildOpenAPIDocument.
- Around line 959-974: The response component name currently uses "Error" but
buildProcedureOperation expects a lowercase "error" $ref; rename the responses
key from "Error" to "error" (keeping the same description, content, schema that
references meta.errorSchema ?? DEFAULT_ERROR_SCHEMA) so the component name
matches the existing reference used by buildProcedureOperation and `$ref`
resolution works correctly.

In `@packages/openapi/test/generate.test.ts`:
- Around line 93-94: Rename the test title string in the failing test block that
currently reads "returns a valid tRPC OpenAPI 3.0 document" to accurately
reflect the asserted OpenAPI version (e.g., "returns a valid tRPC OpenAPI 3.1.1
document"); update the it(...) description in the test case surrounding the
assertion expect(doc.openapi).toBe('3.1.1') so the test name matches the
contract version being asserted.
- Around line 286-298: Replace the manual server lifecycle and direct mutation
of the generated client with the test harness helper: call
testServerAndClientResource({ router: AppRouter }) and await using ctx = ... to
get the server context, then configure the generated client using ctx.httpUrl
instead of creating a handler via createHTTPHandler and calling
heyapiClient.setConfig with baseUrl; keep transformerlessClientConfig merged
into the client config. Update the affected tests (the block around the current
createHTTPHandler/AppRouter usage and the other occurrences at the noted ranges)
to use ctx for setup/teardown so the server is started/stopped by the harness
and the client uses ctx.httpUrl (and ctx.wssUrl where appropriate).

In `@packages/openapi/test/scripts/codegen.run.ts`:
- Line 4: The script currently invokes the async function codegen() without
awaiting it, which can let the process exit before async work like
createClient() finishes; update the entry point to use top-level await (i.e.
await codegen()) so the promise is resolved before exit, and ensure the module
is executed in an environment that supports top-level await (ESM/compatible
runner) so the change takes effect.

In `@scripts/version.ts`:
- Around line 49-53: The global string replace using content.replace (creating
newContent) is overwriting all "@trpc/*" entries including peerDependencies and
thus pinning ranges; instead, parse the manifest JSON (use JSON.parse on
content), update only the dependencies, devDependencies, and
optionalDependencies objects by setting each "@trpc/*" entry to depVersion
(leave peerDependencies untouched), then serialize back with JSON.stringify to
produce newContent; locate the depVersion variable and the current
content.replace usage and replace that string-replace logic with JSON-based
manipulation that targets only those three dependency keys.

In `@www/docs/client/openapi.md`:
- Around line 8-11: The caution admonition (the :::caution block) contains
broken/missing words; replace the current two sentences with a clear alpha
disclaimer such as: "This package is an alpha release; APIs may change without
notice. Because it targets a specification, behavior and results are expected to
improve over time." Update the text inside the :::caution block to use that
complete, grammatically correct copy so the warning reads intentionally and
clearly.

---

Nitpick comments:
In `@packages/openapi/src/heyapi/index.ts`:
- Around line 78-91: In responseTransformer, avoid blanket any casts and calling
transformer.output.deserialize on possibly undefined nested properties; narrow
the top-level assertion once (e.g., const obj = data as Record<string, unknown>
| null) and then check that obj.result?.data !== undefined before calling
transformer.output.deserialize(obj.result.data) and similarly guard
obj.error?.data !== undefined before deserializing; update the code to only call
transformer.output.deserialize when the nested .data exists and assign back into
the same nested slot.

In `@packages/openapi/test/routers/appRouter.ts`:
- Around line 623-672: The simpleCases entry is defined as a plain object
literal while other nested routers use t.router(...), causing inconsistency;
change the simpleCases declaration to use t.router({...}) with the same
procedures (simpleCases: t.router({ nullish: t.procedure... , optional: ...,
nullable: ... })) so the shape matches other nested routers (refer to symbol
simpleCases and t.router) or alternatively add a clarifying comment above
simpleCases indicating the plain object is intentional to test
walkRecord/walkType behavior.
- Line 1: Replace the current named import "import { z } from 'zod';" with a
namespace import so all Zod symbols are accessed via the namespace (e.g., change
to a namespace-style import and keep existing usages of "z" intact); update the
import statement at the top of the file where "z" is declared (so code
referencing z.<something> continues to work but now comes from the zod
namespace).

In `@packages/openapi/test/routers/errorFormatterRouter.ts`:
- Line 1: Replace the named import of Zod with a namespace import: change the
import statement that currently brings in "{ z }" from 'zod' to a namespace
import (import * as z from 'zod') and update any references if necessary; locate
the import line and adjust it so the rest of the file (uses of z.object,
z.string, etc.) continue to work with the z namespace.

In `@packages/openapi/test/routers/superjsonRouter.ts`:
- Line 2: Change the default import of Zod to a namespace import to follow the
codebase convention: replace the current "import { z } from 'zod'" with a
namespace import (import * as z from 'zod') so all Zod utilities are accessed
via the z namespace; update any usages that assume the named import (symbol z)
if needed to work with the namespace import.

In `@scripts/version.ts`:
- Around line 31-45: The prerelease normalization currently captures only the
channel name via prereleaseMatch = version.match(/-(alpha|beta)(\b|$)/) and
rebuilds suffixedVersion as `${baseVersion}-${suffix}`, which strips numeric
identifiers like .1 or .2; update the regex/search used in prereleaseMatch to
capture the entire prerelease token (e.g., include following dot/identifier
segments) so that suffixedVersion preserves the full identifier (use the
captured full suffix when building suffixedVersion and when replacing
`"version": "${version}"` in content and assigning version). Ensure you
reference prereleaseMatch, suffix, baseVersion, suffixedVersion, content.replace
and version when making the change.

ℹ️ Review info
βš™οΈ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b0f98e59-3d68-4c57-876d-e26af2a11c13

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 2bf122d and 7b1d878.

β›” Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
πŸ“’ Files selected for processing (27)
  • .prettierignore
  • packages/openapi/package.json
  • packages/openapi/src/cli.ts
  • packages/openapi/src/generate.ts
  • packages/openapi/src/heyapi/index.ts
  • packages/openapi/src/index.ts
  • packages/openapi/test/generate.test.ts
  • packages/openapi/test/routers/.eslintignore
  • packages/openapi/test/routers/.gitignore
  • packages/openapi/test/routers/.prettierignore
  • packages/openapi/test/routers/appRouter.ts
  • packages/openapi/test/routers/appRouter.ts.json
  • packages/openapi/test/routers/errorFormatterRouter.ts
  • packages/openapi/test/routers/errorFormatterRouter.ts.json
  • packages/openapi/test/routers/superjsonRouter.ts
  • packages/openapi/test/routers/superjsonRouter.ts.json
  • packages/openapi/test/scripts/codegen.run.ts
  • packages/openapi/test/scripts/codegen.ts
  • packages/openapi/test/scripts/globalSetup.ts
  • packages/openapi/tsconfig.build.json
  • packages/openapi/tsconfig.json
  • packages/openapi/tsdown.config.ts
  • packages/openapi/vitest.config.ts
  • scripts/version.ts
  • tsconfig.json
  • www/docs/client/openapi.md
  • www/sidebars.ts

Comment thread packages/openapi/package.json Resolved
Comment thread packages/openapi/src/cli.ts Resolved
Comment thread packages/openapi/src/generate.ts Resolved
Comment thread packages/openapi/src/generate.ts Resolved
Comment thread packages/openapi/test/generate.test.ts Resolved
Comment thread packages/openapi/test/generate.test.ts Resolved
Comment thread scripts/version.ts Resolved
Comment thread www/docs/client/openapi.md 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: 1

🧹 Nitpick comments (3)
examples/openapi-codegen/openapi.json (1)

1-6: Consider adding security schemes for production use.

Static analysis flags missing security definitions (CKV_OPENAPI_4, CKV_OPENAPI_5). This is acceptable for a local development example, but production APIs should define appropriate security schemes.

If this example is intended to demonstrate security patterns as well, consider adding:

"components": {
  "securitySchemes": {
    "bearerAuth": {
      "type": "http",
      "scheme": "bearer"
    }
  }
}
πŸ€– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@examples/openapi-codegen/openapi.json` around lines 1 - 6, Add a
production-ready security scheme to the OpenAPI document by defining a
components.securitySchemes entry (e.g., "bearerAuth") and reference it in the
global security array; specifically update the top-level document (where
"openapi" and "info" are defined) to include a components object with
securitySchemes containing a bearer/http scheme and then add a top-level
"security" entry that uses "bearerAuth" so operations can require the scheme.
examples/openapi-codegen/src/client/index.ts (1)

34-40: Redundant querySerializer override.

The querySerializer is already configured globally via client.setConfig() on lines 14-17. Passing it again per-call is unnecessary and inconsistent with the other SDK calls (list, create) that don't include it.

♻️ Suggested simplification
   // Fetch the user by ID
   const byIdResult = await sdk.user.byId({
     query: {
       input: '1',
     },
-    querySerializer: createTRPCHeyApiClientConfig({ transformer }).querySerializer,
   });
πŸ€– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@examples/openapi-codegen/src/client/index.ts` around lines 34 - 40, The byId
call redundantly overrides querySerializer per-call; remove the querySerializer
property from the sdk.user.byId invocation so it relies on the global serializer
set via client.setConfig (referencing sdk.user.byId and
createTRPCHeyApiClientConfig) to match the other SDK calls (list, create) and
keep configuration consistent.
examples/openapi-codegen/src/scripts/codegen.ts (1)

34-35: Remove the as any type assertion from the input property.

Since doc is already properly typed as OpenAPIDocument (returned from generateOpenAPIDocument()), removing the as any escape hatch allows TypeScript to enforce the type contract between generateOpenAPIDocument() and @hey-api/openapi-ts. If the shapes drift, this will be caught at compile time rather than failing later during codegen. Alternatively, pass input: specPath as a string (the path to openapi.json written on line 28), which @hey-api/[email protected] also supports.

πŸ€– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@examples/openapi-codegen/src/scripts/codegen.ts` around lines 34 - 35, Remove
the unnecessary type assertion on the createClient call: use the strongly-typed
OpenAPIDocument returned by generateOpenAPIDocument() (the doc variable)
directly for the input property instead of casting to any, or alternatively pass
the specPath string (the path written earlier) which `@hey-api/openapi-ts`
supports; update the call to createClient({ input: doc }) or createClient({
input: specPath }) so TypeScript enforces the expected OpenAPIDocument shape.
πŸ€– Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@examples/openapi-codegen/src/scripts/codegen.ts`:
- Around line 31-47: The code currently deletes the existing SDK with
rmSync(outputDir, { recursive: true, force: true }) before awaiting
createClient(...), which risks leaving no SDK if generation fails; change the
flow to generate into a temporary directory (e.g., create a temp dir next to
outputDir), call createClient with output set to that temp dir, and only after
createClient completes successfully atomically replace or move the temp dir to
outputDir (removing or backing up the old outputDir as part of the swap). Use
the existing symbols rmSync, createClient, and outputDir to implement the
temp-generation-and-swap pattern and ensure cleanup on failure.

---

Nitpick comments:
In `@examples/openapi-codegen/openapi.json`:
- Around line 1-6: Add a production-ready security scheme to the OpenAPI
document by defining a components.securitySchemes entry (e.g., "bearerAuth") and
reference it in the global security array; specifically update the top-level
document (where "openapi" and "info" are defined) to include a components object
with securitySchemes containing a bearer/http scheme and then add a top-level
"security" entry that uses "bearerAuth" so operations can require the scheme.

In `@examples/openapi-codegen/src/client/index.ts`:
- Around line 34-40: The byId call redundantly overrides querySerializer
per-call; remove the querySerializer property from the sdk.user.byId invocation
so it relies on the global serializer set via client.setConfig (referencing
sdk.user.byId and createTRPCHeyApiClientConfig) to match the other SDK calls
(list, create) and keep configuration consistent.

In `@examples/openapi-codegen/src/scripts/codegen.ts`:
- Around line 34-35: Remove the unnecessary type assertion on the createClient
call: use the strongly-typed OpenAPIDocument returned by
generateOpenAPIDocument() (the doc variable) directly for the input property
instead of casting to any, or alternatively pass the specPath string (the path
written earlier) which `@hey-api/openapi-ts` supports; update the call to
createClient({ input: doc }) or createClient({ input: specPath }) so TypeScript
enforces the expected OpenAPIDocument shape.

ℹ️ Review info
βš™οΈ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8b420fd9-643c-4789-8127-09d261a9610f

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 7b1d878 and ac487be.

β›” Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
πŸ“’ Files selected for processing (11)
  • examples/openapi-codegen/.eslintignore
  • examples/openapi-codegen/.prettierignore
  • examples/openapi-codegen/openapi.json
  • examples/openapi-codegen/package.json
  • examples/openapi-codegen/src/client/index.ts
  • examples/openapi-codegen/src/scripts/codegen.ts
  • examples/openapi-codegen/src/server/db.ts
  • examples/openapi-codegen/src/server/index.ts
  • examples/openapi-codegen/src/server/trpc.ts
  • examples/openapi-codegen/src/shared/transformer.ts
  • examples/openapi-codegen/tsconfig.json
βœ… Files skipped from review due to trivial changes (1)
  • examples/openapi-codegen/.eslintignore

Copilot AI 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.

Pull request overview

Copilot reviewed 92 out of 185 changed files in this pull request and generated 6 comments.


πŸ’‘ Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread packages/openapi/test/edgeCases.test.ts Resolved
Comment thread packages/openapi/test/edgeCases.test.ts Resolved
Comment thread packages/openapi/src/heyapi/index.ts Resolved
Comment thread packages/openapi/src/heyapi/index.ts Resolved
Comment thread codecov.yml Resolved

Copilot AI 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.

Pull request overview

Copilot reviewed 92 out of 185 changed files in this pull request and generated 3 comments.


πŸ’‘ Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread packages/openapi/src/heyapi/index.ts Resolved
Comment thread packages/openapi/src/heyapi/index.ts Resolved
Comment thread packages/openapi/src/cli.ts Resolved
@coderabbitai coderabbitai Bot mentioned this pull request Mar 15, 2026
3 tasks
@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.

This branch was successfully deployed

5 active deployments
Preview – www β€” 0a588f57 Deployed Mar 14, 2026 by vercel[bot]
Preview – examples-todomvc β€” 0a588f57 Deployed Mar 14, 2026 by vercel[bot]
Preview – next-prisma-starter β€” 0a588f57 Deployed Mar 14, 2026 by vercel[bot]
Preview – og-image β€” 0a588f57 Deployed Mar 14, 2026 by vercel[bot]
Preview – trpc-next-app-dir β€” 0a588f57 Deployed Mar 14, 2026 by vercel[bot]
trpc-sse-and-websockets / trpc-pr-7231 β€” 0a588f57 Deployed Mar 14, 2026 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.

3 participants