Skip to content

fix(zod): correct inline reusable schema emission (missing import + dropped defs) - #3468

Merged
melloware merged 2 commits into
orval-labs:masterfrom
z4o4z:fix/reusable-zod-inline-import-and-defs
May 28, 2026
Merged

fix(zod): correct inline reusable schema emission (missing import + dropped defs)#3468
melloware merged 2 commits into
orval-labs:masterfrom
z4o4z:fix/reusable-zod-inline-import-and-defs

Conversation

@z4o4z

@z4o4z z4o4z commented May 27, 2026

Copy link
Copy Markdown
Contributor

Summary

Two pre-existing bugs in the inline single-file reusable-schema writer (client: 'zod' + override.zod.generateReusableSchemas, with no schemas: directory). Both produce output that does not compile. Found while working on #3467; fixed here independently.

1. Missing import * as zod from 'zod'

The zod client's import is a usage-gated dependency import — emitted only when an operation's generated schema references the zod token. When every operation is a pure-$ref alias, e.g.

export const GetThingResponse = Thing

the client emits no zod import. The inline schema block also skipped it (it keyed off !hasOperations), so the file ended up referencing zod with no import at all.

Now the inline block supplies the import unless an operation actually references zod (mirroring the client's own gate), so there is always exactly one zod import.

2. Dropped definitions for sanitized names

The inline writer seeded reusable refs from builder.schemas, whose name is the sanitized model identifier (__schema0_Schema0). The resulting ref #/components/schemas/_Schema0 doesn't exist in components.schemas (the real key is __schema0), so the definition was silently dropped whenever the schema was reachable only from operations — leaving the operation wrapper that references it dangling. (It survived when another component schema referenced it, via transitive expansion, which masked the bug.)

Now it seeds from the raw components.schemas keys, exactly like the per-file writer writeZodSchemasReusable already does (see its comment, added in #3465).

Test plan

  • New unit test (write-zod-specs): generateZodSchemasInline emits a schema whose raw name needs sanitizing (__my_data_MyData)
  • New e2e test (generate-spec): a spec whose only operation is a pure-$ref alias yields exactly one from 'zod' import (previously zero)
  • Existing inline test (operation that does use zod) still asserts exactly one import — no double-import regression
  • Generated output type-checks under strict on zod v3 and v4 for both scenarios
  • lint, typecheck, and full orval suite (119 tests) pass

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Ensure Zod import is emitted only when generated operations require it (fixes missing/extra import for pure $ref responses).
    • Fix reusable-schema detection to correctly recognize component schemas from raw spec keys and eliminate leftover reference placeholders.
  • Tests

    • Added regression tests for inline schema generation with pure $ref operations and correct Zod import behavior.
    • Added tests for component schema naming edge cases to prevent sentinel markers.

Review Change Stack

Copilot AI review requested due to automatic review settings May 27, 2026 17:13
@coderabbitai

coderabbitai Bot commented May 27, 2026

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e7211a3b-b184-40ff-8022-88917e480222

📥 Commits

Reviewing files that changed from the base of the PR and between b21c699 and 36cee17.

📒 Files selected for processing (4)
  • packages/orval/src/generate-spec.test.ts
  • packages/orval/src/write-specs.ts
  • packages/orval/src/write-zod-specs.test.ts
  • packages/orval/src/write-zod-specs.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/orval/src/write-specs.ts
  • packages/orval/src/generate-spec.test.ts
  • packages/orval/src/write-zod-specs.ts
  • packages/orval/src/write-zod-specs.test.ts

📝 Walkthrough

Walkthrough

Seeds reusable Zod schemas from raw spec.components.schemas keys and gates whether the inline import { z as zod } is emitted by scanning operation implementations for a zod token. Adds tests ensuring pure $ref operation responses emit inline component exports, pure-alias response exports, a single zod import, and no __REF_ sentinels.

Changes

Inline Zod Reusable Schemas

Layer / File(s) Summary
Reusable schema seeding from raw spec components
packages/orval/src/write-zod-specs.ts, packages/orval/src/write-zod-specs.test.ts
generateZodSchemasInlineReusable now seeds reusable schemas from raw spec.components.schemas keys (building #/components/schemas/<rawKey> refs) instead of builder.schemas, and returns early only when no component refs exist; test ensures sanitized component names emit expected inline Zod definitions and no __REF_ sentinels remain.
Zod import detection based on operation usage
packages/orval/src/write-specs.ts, packages/orval/src/generate-spec.test.ts
writeSpecs now scans operation implementations for a zod token to decide whether the inline zod block should provide the zod binding (avoiding duplicate imports). Adds a regression test verifying inline schema emission, pure-alias operation exports (GetThingResponse = Thing), exactly one from 'zod' import, and absence of __REF_ sentinels.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • orval-labs/orval#3206: Introduced the inline Zod schema generation path that this PR refines further via schema seeding and import logic.
  • orval-labs/orval#3465: Modifies the same inline zod generation pipeline and import handling.
  • orval-labs/orval#3464: Addresses __REF_ sentinel elimination and emitted imports in Zod reusable-schema writing.

Suggested labels

zod

Suggested reviewers

  • melloware
  • snebjorn
  • soartec-lab

🐰 From raw keys I nibbled through,
Pure $refs hopped and needed glue,
One zod import, no sentinel sight,
Reusable schemas now sleep tight,
Tiny rabbit cheers the fix tonight!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically identifies the main fixes: correcting inline reusable schema emission by addressing a missing zod import and dropped definitions.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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

Note

Copilot was unable to run its full agentic suite in this review.

Fixes regressions in inline reusable Zod schema generation by correctly seeding component schema refs from raw OpenAPI keys, and by ensuring the generated output includes exactly one necessary Zod import even when operations are pure $ref aliases.

Changes:

  • Seed inline reusable schema refs from raw components.schemas keys to avoid dropping schemas with sanitized identifiers.
  • Adjust includeZodImport logic to depend on whether operations actually use the zod identifier.
  • Add targeted regression tests for sanitized-name schemas and for pure-$ref operations missing Zod imports.

Reviewed changes

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

File Description
packages/orval/src/write-zod-specs.ts Seeds refs from raw component schema keys to prevent silently dropped schemas.
packages/orval/src/write-zod-specs.test.ts Adds regression test covering raw-name vs sanitized-name mismatch.
packages/orval/src/write-specs.ts Makes Zod import emission conditional on whether operations reference zod.
packages/orval/src/generate-spec.test.ts Adds end-to-end regression test ensuring exactly one zod import for pure-$ref operations.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread packages/orval/src/write-zod-specs.ts
Comment thread packages/orval/src/write-specs.ts
Comment thread packages/orval/src/generate-spec.test.ts Outdated
@melloware melloware added the zod Zod schema client related issue label May 27, 2026
@melloware melloware added this to the 8.14.0 milestone May 27, 2026
@melloware

Copy link
Copy Markdown
Collaborator

looks like Conflicts now

z4o4z and others added 2 commits May 28, 2026 10:37
…ropped defs)

Two pre-existing bugs in the inline single-file reusable-schema writer
(`client: 'zod'` + `generateReusableSchemas`, no `schemas:` dir):

1. Missing `import * as zod from 'zod'`. The zod client's import is a
   usage-gated dependency import — emitted only when an operation's generated
   schema references the `zod` token. When every operation is a pure-`$ref`
   alias (`export const FooResponse = Bar`), the client emits no zod import, and
   the inline block also skipped it (it keyed off `!hasOperations`), leaving the
   generated schemas referencing an undefined `zod`. Now the inline block
   supplies the import unless an operation actually uses zod.

2. Dropped definitions for sanitized names. The inline writer seeded reusable
   refs from `builder.schemas`, whose names are the *sanitized* model
   identifiers (`__schema0` -> `_Schema0`). The resulting ref
   (`#/components/schemas/_Schema0`) doesn't exist in `components.schemas`, so
   the definition was silently dropped whenever the schema was reachable only
   from operations (it survived when another component referenced it, via
   transitive expansion). Now it seeds from the raw `components.schemas` keys,
   mirroring the per-file writer (`writeZodSchemasReusable`).

Both verified to type-check under strict on zod v3 and v4.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Match /from ['"]zod['"]/ so the single-import assertion survives generator
quote-style changes while still asserting exactly one zod module import.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@z4o4z
z4o4z force-pushed the fix/reusable-zod-inline-import-and-defs branch from b21c699 to 36cee17 Compare May 28, 2026 08:38
@melloware
melloware merged commit 08af226 into orval-labs:master May 28, 2026
5 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Aug 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

zod Zod schema client related issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants