Skip to content

Add schema infer, variants, Hono REST hooks#9

Merged
PatrickJS merged 1 commit into
mainfrom
codex/data-first-jsondb
May 14, 2026
Merged

Add schema infer, variants, Hono REST hooks#9
PatrickJS merged 1 commit into
mainfrom
codex/data-first-jsondb

Conversation

@PatrickJS
Copy link
Copy Markdown
Owner

@PatrickJS PatrickJS commented May 14, 2026

Introduce data-first schema tooling and REST extensibility: add a new CLI command schema infer [resource] [--out] and update help text; implement doctor guidance that suggests adding or removing schemas based on inferred data (new schema-guidance module). Extend schema normalization/inference to support discriminated object variants (discriminator + variants), propagate variants into manifests, validation, and generated types (emit variant aliases and variant object types). Export and implement registerRestRoutes with restRoutes options (prefix, resource include/exclude, methods, per-resource hooks and global hooks, and short-circuiting), wire it into Hono app creation, and update types and tests accordingly. Add JsonDbCollection.exists() to the API and implement it in both fixture and SQLite adapters. Update README and AGENTS to emphasize a data-first approach and document new workflow examples and usage. Tests updated to cover new behavior.

Summary by CodeRabbit

Release Notes

New Features

  • Added schema infer CLI command to infer and output resource schemas from seed data
  • Added collection.exists(id) method to check record existence
  • Implemented polymorphic type support via discriminators and variants
  • Enhanced Hono REST routes with configurable hooks (beforeCreate, beforePatch, etc.) and resource filtering
  • Schema doctor now provides recommendations for ambiguous polymorphic data

Documentation

  • Updated guidance emphasizing data-first schema approach with inference examples and expanded fixture doctor findings

Review Change Stack

Introduce data-first schema tooling and REST extensibility: add a new CLI command `schema infer [resource] [--out]` and update help text; implement doctor guidance that suggests adding or removing schemas based on inferred data (new schema-guidance module). Extend schema normalization/inference to support discriminated object variants (discriminator + variants), propagate variants into manifests, validation, and generated types (emit variant aliases and variant object types). Export and implement registerRestRoutes with restRoutes options (prefix, resource include/exclude, methods, per-resource hooks and global hooks, and short-circuiting), wire it into Hono app creation, and update types and tests accordingly. Add JsonDbCollection.exists() to the API and implement it in both fixture and SQLite adapters. Update README and AGENTS to emphasize a data-first approach and document new workflow examples and usage. Tests updated to cover new behavior.
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 14, 2026

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

This PR introduces discriminated union types with variants for polymorphic schema inference, adds a collection.exists() convenience method, implements schema infer CLI for exporting inferred schemas, extends the doctor tool with schema guidance findings, and makes REST route registration configurable with hook support for Hono.

Changes

Discriminated Union Types & Schema Features

Layer / File(s) Summary
Field inference for discriminated unions
src/features/schema/fields.js
Field normalization and inference now recognize discriminator strings and variants maps on objects. inferFieldFromSamples supports variant detection when inferVariants: true, and array items enable variant inference by default. Merged fields with matching discriminators delegate to specialized variant merging.
Schema validation for discriminated variants
src/features/schema/validation.js
Object field validation detects discriminator + variants and delegates to validateVariantObjectFields, which reads the discriminator value, ensures it maps to a configured variant, and validates the record against the variant's field schema merged with a discriminator enum constraint.
Manifest and type generation for variants
src/features/schema/manifest.js, src/types.js
Schema manifests now include discriminator and variants in field output. TypeScript type generation adds field-path awareness to produce deterministic nested enum/variant alias names, renders variant unions via renderVariantAlias, and merges duplicate enum alias values using set semantics.
Doctor schema guidance system
src/features/doctor/index.js, src/features/doctor/schema-guidance.js
Doctor now loads an inferred project and compares declared schemas against inferred data, emitting DOCTOR_SCHEMA_RECOMMENDED findings for ambiguous polymorphic arrays and DOCTOR_SCHEMA_MATCHES_INFERENCE when explicit schemas appear removable. Normalized comparison logic skips non-inferable contract details.
Schema infer CLI command
src/cli/commands/schema.js, src/cli/output.js
New schema infer [resource] [--out <file>] subcommand outputs inferred resource schemas as JSON or writes to a file. Includes resource resolution, positional argument parsing, and help text updates.
Collection existence check
src/features/runtime/collection.js, src/integrations/sqlite.js, src/index.d.ts
Adds exists(id) method to both runtime and SQLite collections, returning a boolean for record presence checks via get() comparison or SQLite SELECT query.
Variant integration tests
test/cli/cli.test.js, test/doctor/doctor.test.js, test/runtime/package-api.test.js, test/schema/sources.test.js, test/schema/validation.test.js, src/sqlite.test.js
Comprehensive test coverage for discriminated union inference, validation, type generation, doctor findings, CLI schema infer, and collection.exists behavior.

REST Routes Configuration

Layer / File(s) Summary
REST routes type definitions
src/hono.d.ts
TypeScript types for REST configuration: JsonDbHonoRestMethod, JsonDbHonoRestHookContext, hook collections, per-resource options, and route-level controls including prefix, resource filters, method allowlists, and registerRestRoutes function declaration.
REST routes implementation with hooks
src/integrations/hono.js, src/hono.js
registerRestRoutes(app, db, options) now registers collection/document handlers with hook support (beforeList/beforeGet/beforeCreate/beforePatch/beforeDelete/beforePut). Includes resource filtering, method enforcement (405 responses), shaped response bodies, pagination control, and path construction helpers. Exported from src/hono.js.
REST routes tests and helpers
src/integrations/hono.test.js
Tests for resource-prefix filtering with hook short-circuiting and per-resource hooks that mutate request bodies. Includes fake Hono app and context helpers for route handler testing.

Documentation Updates

Layer / File(s) Summary
Product direction and usage guidance
AGENTS.md, README.md
Expanded "Product direction" section in AGENTS.md with data-first defaults and schema feature guidance. README updates include data-first introduction, schema infer examples with --out output, expanded doctor findings descriptions, collection.exists examples, and new Hono REST integration example with registerRestRoutes, prefix, resource filtering, and beforeCreate hook.

Sequence Diagram

sequenceDiagram
    participant App
    participant SchemaFields as Field Inference
    participant Validation as Validator
    participant Manifest as Manifest Gen
    participant Types as Type Gen
    participant Doctor as Doctor
    
    App->>SchemaFields: inferFieldFromSamples(polymorphic array, inferVariants=true)
    SchemaFields->>SchemaFields: inferDiscriminatedObjectField()
    SchemaFields-->>App: field with discriminator & variants
    
    App->>Validation: validateObjectFields(record, field with variants)
    Validation->>Validation: validateVariantObjectFields()
    Validation->>Validation: read discriminator value
    Validation->>Validation: merge variant schema with enum constraint
    Validation-->>App: validation result
    
    App->>Manifest: renderFieldManifest(field with variants)
    Manifest-->>App: manifest with variants map
    
    App->>Types: typeForField(field, fieldPath)
    Types->>Types: variantObjectType() for variant union
    Types-->>App: TypeScript variant union type
    
    App->>Doctor: runJsonDbDoctor(config)
    Doctor->>Doctor: load inferred project
    Doctor->>Doctor: schemaGuidanceFindings()
    Doctor-->>App: DOCTOR_SCHEMA_RECOMMENDED or DOCTOR_SCHEMA_MATCHES_INFERENCE
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

The PR spans multiple interconnected systems (schema inference, validation, type generation, CLI, doctor, REST routes) with significant logic density in variant merging, discriminator detection, normalized comparison, and REST hook orchestration. While individual layers follow clear patterns, the variant feature adds intricate recursive logic for nested structures, and the REST routes system introduces substantial option-driven configuration handling. Testing is comprehensive across new features.

Possibly related PRs

  • PatrickJS/jsondb#4: Introduces schema manifest output feature; this PR extends manifest generation with discriminator and variants field support.
  • PatrickJS/jsondb#3: Implements the doctor CLI and core findings logic; this PR augments doctor with schema guidance comparisons and integration into the findings pipeline.

Poem

🐰 Variants dance in polymorphic arrays,
Discriminators guide through type's many ways,
Inferred from data, validated with care,
REST hooks and exists, configuration everywhere! 🎉

🚥 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 accurately captures the three major feature additions in this PR: schema inference, schema variants support, and Hono REST route hooks.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/data-first-jsondb

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.

Warning

Review ran into problems

🔥 Problems

Stopped waiting for pipeline failures after 30000ms. One of your pipelines takes longer than our 30000ms fetch window to run, so review may not consider pipeline-failure results for inline comments if any failures occurred after the fetch window. Increase the timeout if you want to wait longer or run a @coderabbit review after the pipeline has finished.


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.

@PatrickJS PatrickJS merged commit 9586d5f into main May 14, 2026
3 of 4 checks passed
@PatrickJS PatrickJS deleted the codex/data-first-jsondb branch May 14, 2026 21:38
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.

1 participant