Skip to content

Extract logic from zenko.ts to smaller functions and utilities#40

Merged
RawToast merged 2 commits intomasterfrom
claude/refactor-for-maintainability-01WsppUS2cCgMqGz7jchWuX2
Nov 24, 2025
Merged

Extract logic from zenko.ts to smaller functions and utilities#40
RawToast merged 2 commits intomasterfrom
claude/refactor-for-maintainability-01WsppUS2cCgMqGz7jchWuX2

Conversation

@RawToast
Copy link
Copy Markdown
Owner

@RawToast RawToast commented Nov 23, 2025

Summary by CodeRabbit

  • New Features

    • Added schema generation capabilities for creating Zod schemas from OpenAPI specifications
    • Enhanced OpenAPI parameter resolution and content-type inference utilities
    • Introduced configurable schema options for strict validation modes and optional handling
  • Tests

    • Added comprehensive test coverage for schema generation and OpenAPI utilities

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

claude and others added 2 commits November 23, 2025 12:52
This refactoring addresses the monolithic structure of the codebase by:

## Changes Made

### 1. Created shared utilities module
- **src/utils/schema-utils.ts**: Extracted duplicated functions
  - `CONTENT_TYPE_MAP`: Content type priority mapping
  - `findContentType()`: Finds appropriate content type from options
  - `resolveParameter()`: Resolves parameter references
- Eliminated code duplication between `zenko.ts` and `collect-referenced-schemas.ts`
- Added comprehensive test coverage (17 tests)

### 2. Extracted schema generation logic
- **src/core/schema-generator.ts**: Isolated all Zod schema building
  - `generateZodSchema()`: Generates complete Zod schema exports
  - `getZodTypeFromSchema()`: Converts OpenAPI to Zod types
  - `buildZodObject()`: Builds object schemas
  - `buildString()`, `buildNumber()`, `buildInteger()`: Primitive types
  - `applyStrictArrayBounds()`: Array constraints
  - `applyNumericBounds()`: Numeric bounds
  - `applyOptionalModifier()`: Optional/nullable/nullish modifiers
  - `isPrimitiveLike()`: Primitive type checking
- Reduced main file from 1,537 to 1,212 lines (325 lines extracted)
- Added comprehensive test coverage (63 tests)

## Impact
- **Better separation of concerns**: Each module has a single responsibility
- **Improved testability**: Individual functions can be tested in isolation
- **Reduced code duplication**: Shared utilities prevent maintenance issues
- **Maintained compatibility**: All 264 existing tests pass
- **Enhanced composability**: Functions are now more reusable

## Future Refactoring Opportunities
The following areas can be further improved:
- Extract operation parsing logic (parseOperations, collectParameters, etc.)
- Separate response type resolution (getResponseTypes, selectSuccessResponse)
- Isolate error handling logic (buildErrorGroups)
- Create dedicated generator modules for paths, headers, and operations
- Refactor the main orchestration logic into a cleaner pipeline

This is the first phase of a larger maintainability improvement initiative.
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Nov 23, 2025

Walkthrough

The PR refactors schema generation and content-type utilities from monolithic zenko.ts into dedicated modules: core/schema-generator and utils/schema-utils, with comprehensive test coverage. Exported types and functions are relocated but remain functionally identical; internal implementations move to new modules while zenko.ts imports them.

Changes

Cohort / File(s) Change Summary
Core Schema Generator
packages/zenko/src/core/schema-generator.ts
New module exporting SchemaOptions type and functions for Zod schema generation: applyOptionalModifier, generateZodSchema, getZodTypeFromSchema, buildZodObject, buildString, buildNumber, buildInteger, applyStrictArrayBounds, isPrimitiveLike, applyNumericBounds. Handles enum, allOf, object, array, and primitive type conversion with support for strictness modes and optional handling.
Schema Generator Tests
packages/zenko/src/core/__tests__/schema-generator.test.ts
New comprehensive test suite covering all public functions and edge cases: optional/nullable/nullish modifiers, primitive detection, numeric bounds, string formatting and constraints, number/integer handling, array bounds, object building, ref resolution, enum generation, and schema generation state tracking.
Schema Utilities
packages/zenko/src/utils/schema-utils.ts
New module exporting CONTENT_TYPE_MAP constant, findContentType function (prioritizes application/json then mapped types), and resolveParameter function (resolves $ref against OpenAPI spec and merges overrides).
Schema Utilities Tests
packages/zenko/src/utils/__tests__/schema-utils.test.ts
New test suite validating CONTENT_TYPE_MAP values, findContentType behavior across content negotiation scenarios, and resolveParameter logic including ref resolution, merging, and edge cases.
Module Integration
packages/zenko/src/zenko.ts
Removed local declarations of SchemaOptions, schema-generation helpers (generateZodSchema, getZodTypeFromSchema, buildZodObject, buildString, buildNumber, buildInteger, applyStrictArrayBounds, isPrimitiveLike, applyNumericBounds), and content-type utilities (CONTENT_TYPE_MAP, findContentType, resolveParameter). Added imports from ./core/schema-generator and ./utils/schema-utils.
Helper Cleanup
packages/zenko/src/utils/collect-referenced-schemas.ts
Removed local imports of findContentType and resolveParameter; these functions now imported from schema-utils where they are defined.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • schema-generator.ts requires careful verification of Zod schema-building logic, especially allOf composition, ref resolution with nameMap, and optional modifier application across nested structures
  • schema-utils.ts logic appears straightforward but verify content-type prioritization and parameter resolution edge cases match intended behavior
  • zenko.ts refactoring is largely mechanical (imports replacing local code) but needs spot-checking to ensure no functional regressions where schema-generator functions are called
  • Strong test coverage for both new modules mitigates risk; focus on whether tests exercise all critical paths and whether mocked schemas in tests match production usage patterns

Possibly related PRs

Poem

🐰 Hops skip through the modules, files find their home,
Schema-gen and utils, no longer alone,
Tests cover the ground with a thorough gait,
Code organization—hoorah!—feels great! 🌟

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the primary change: extracting schema-generation logic and utility functions from zenko.ts into dedicated modules (schema-generator.ts and schema-utils.ts).
Docstring Coverage ✅ Passed Docstring coverage is 81.25% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch claude/refactor-for-maintainability-01WsppUS2cCgMqGz7jchWuX2

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 37685ac and 8a0e94b.

📒 Files selected for processing (6)
  • packages/zenko/src/core/__tests__/schema-generator.test.ts (1 hunks)
  • packages/zenko/src/core/schema-generator.ts (1 hunks)
  • packages/zenko/src/utils/__tests__/schema-utils.test.ts (1 hunks)
  • packages/zenko/src/utils/collect-referenced-schemas.ts (1 hunks)
  • packages/zenko/src/utils/schema-utils.ts (1 hunks)
  • packages/zenko/src/zenko.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-10-16T00:11:55.898Z
Learnt from: RawToast
Repo: RawToast/zenko PR: 15
File: packages/zenko/src/zenko.ts:917-921
Timestamp: 2025-10-16T00:11:55.898Z
Learning: In packages/zenko/src/zenko.ts, the `response` field in operation objects can contain TypeScript type expressions like `z.ZodArray<typeof SchemaName>` for inline array responses. These expressions are intended for type definitions and type checking, not for runtime validation. Users should not attempt to use these type expressions as runtime Zod schemas.

Applied to files:

  • packages/zenko/src/utils/schema-utils.ts
  • packages/zenko/src/core/__tests__/schema-generator.test.ts
  • packages/zenko/src/utils/collect-referenced-schemas.ts
  • packages/zenko/src/core/schema-generator.ts
  • packages/zenko/src/zenko.ts
📚 Learning: 2025-10-31T22:24:57.504Z
Learnt from: RawToast
Repo: RawToast/zenko PR: 34
File: packages/zenko/src/__tests__/config-options.test.ts:473-556
Timestamp: 2025-10-31T22:24:57.504Z
Learning: In the zenko package, the `optionalType` configuration option has three distinct behaviors aligned with Zod semantics: `optional` generates `.optional()` (field can be undefined/omitted), `nullable` generates `.nullable()` (field must be present but can be null), and `nullish` generates `.nullish()` (field can be undefined OR null). The `nullable` option intentionally does NOT add `.optional()`, as that would change the required/optional nature of the field.

Applied to files:

  • packages/zenko/src/core/__tests__/schema-generator.test.ts
  • packages/zenko/src/core/schema-generator.ts
  • packages/zenko/src/zenko.ts
🧬 Code graph analysis (3)
packages/zenko/src/utils/__tests__/schema-utils.test.ts (2)
packages/zenko/src/utils/schema-utils.ts (3)
  • CONTENT_TYPE_MAP (7-14)
  • findContentType (23-40)
  • resolveParameter (50-66)
packages/zenko/src/zenko.ts (1)
  • OpenAPISpec (32-41)
packages/zenko/src/core/__tests__/schema-generator.test.ts (1)
packages/zenko/src/core/schema-generator.ts (11)
  • SchemaOptions (4-8)
  • applyOptionalModifier (13-25)
  • isPrimitiveLike (285-290)
  • applyNumericBounds (295-317)
  • buildString (180-225)
  • buildNumber (230-242)
  • buildInteger (247-251)
  • applyStrictArrayBounds (256-280)
  • buildZodObject (152-175)
  • getZodTypeFromSchema (85-146)
  • generateZodSchema (31-79)
packages/zenko/src/core/schema-generator.ts (2)
packages/zenko/src/utils/topological-sort.ts (1)
  • extractRefName (62-64)
packages/zenko/src/utils/property-name.ts (1)
  • formatPropertyName (91-93)
🔇 Additional comments (6)
packages/zenko/src/utils/__tests__/schema-utils.test.ts (1)

1-231: LGTM! Excellent test coverage.

The test suite is comprehensive and well-structured, covering all edge cases for CONTENT_TYPE_MAP, findContentType, and resolveParameter. The tests validate content-type priority logic, parameter resolution, and proper handling of edge cases like empty inputs, missing references, and override merging.

packages/zenko/src/utils/schema-utils.ts (1)

1-66: LGTM! Clean utility module with proper documentation.

The extracted utilities are well-organized and documented. The content-type priority logic is clear, and the parameter resolution with override merging is correctly implemented. The comment explaining binary/ambiguous type handling adds valuable context.

packages/zenko/src/core/__tests__/schema-generator.test.ts (1)

1-580: LGTM! Comprehensive test coverage for schema generation.

The test suite thoroughly validates all schema-generator functions across multiple scenarios. Tests properly verify the strictDates and strictNumeric gating behavior, optional modifier application, numeric bounds, array constraints, and complex schema composition (allOf, enums, objects). The use of a shared defaultOptions object improves maintainability.

packages/zenko/src/core/schema-generator.ts (1)

1-317: LGTM! Well-architected schema generation module.

The schema generator is properly structured with focused, single-purpose functions. The recursive handling of nested schemas, proper support for OpenAPI constructs (allOf, enums, refs), and conditional application of strict validation modes demonstrate solid design. The JSDoc comments provide clear context for each function's purpose.

packages/zenko/src/zenko.ts (1)

11-20: LGTM! Clean refactoring with proper imports.

The imports correctly reference the newly extracted modules (utils/schema-utils and core/schema-generator). This refactoring improves code organization by centralizing schema generation and utility functions while maintaining the same public API and behavior.

packages/zenko/src/utils/collect-referenced-schemas.ts (1)

2-2: I need to verify that the exported functions actually exist in schema-utils.ts. The ast-grep results were missing, so let me search directly for these functions:

Refactoring verified—imports are working correctly.

The comprehensive test suite (16 tests) all pass successfully, which confirms that:

  • findContentType and resolveParameter are properly exported from schema-utils.ts
  • The import statement on line 2 correctly references these functions
  • The functions are used as expected on lines 66 and 110

The passing tests serve as definitive verification that this refactoring has no import or signature issues. The module correctly relocates these utilities without breaking functionality or public API.


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.

@RawToast RawToast merged commit c950ef1 into master Nov 24, 2025
4 checks passed
@RawToast RawToast deleted the claude/refactor-for-maintainability-01WsppUS2cCgMqGz7jchWuX2 branch November 24, 2025 05:12
This was referenced Dec 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants