Skip to content

fix(better-auth): lazy-load schema-generator and expose as separate entry point#2611

Merged
ymc9 merged 1 commit intodevfrom
feat/better-auth-lazy-schema-generator
Apr 25, 2026
Merged

fix(better-auth): lazy-load schema-generator and expose as separate entry point#2611
ymc9 merged 1 commit intodevfrom
feat/better-auth-lazy-schema-generator

Conversation

@ymc9
Copy link
Copy Markdown
Member

@ymc9 ymc9 commented Apr 24, 2026

Summary

  • Converts the static import { generateSchema } in adapter.ts to a dynamic import() so the heavy ZModel schema-parsing code is only loaded when createSchema is actually invoked
  • Adds schema-generator as a dedicated build entry in tsdown.config.ts so it can be bundled and tree-shaken independently
  • Exposes ./schema-generator as a new package export in package.json for consumers who want to use it directly

Test plan

  • Verify better-auth adapter still works end-to-end with createSchema flow
  • Confirm the new ./schema-generator export resolves correctly in both CJS and ESM environments
  • Check that the adapter bundle size is reduced (schema-generator no longer eagerly loaded)

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Exposed schema generator as a publicly available module with dedicated ESM and CommonJS entry points.

…entry point

Converts the static import of schema-generator to a dynamic import to avoid
loading heavy ZModel parsing dependencies until createSchema is actually called.
Also exposes schema-generator as a separate package entry point for direct use.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@claude
Copy link
Copy Markdown
Contributor

claude Bot commented Apr 24, 2026

Claude finished @ymc9's task —— View job


PR Review: Lazy-load schema-generator Implementation

I've completed a thorough review of this pull request that implements lazy loading for the schema-generator to improve bundle size and performance.

Review Tasks:

  • Analyze the 3 changed files
  • Review code quality and implementation approach
  • Check for potential bugs or issues
  • Evaluate performance considerations
  • Look for security concerns
  • Assess test coverage needs
  • Provide comprehensive feedback

Overall Assessment

This is a well-implemented performance optimization that follows good practices for lazy loading. The changes are minimal, focused, and should deliver the intended benefits.

📋 Code Quality & Implementation

✅ Strengths:

  • Clean lazy loading pattern: Using dynamic import() in adapter.ts:211 is the standard approach for code splitting
  • Proper build configuration: The new entry point in tsdown.config.ts:3 enables independent bundling and tree-shaking
  • Comprehensive package exports: The new ./schema-generator export in package.json:42-51 properly supports both ESM and CJS
  • Minimal surface area: Only one line changed in the core adapter logic, reducing risk
  • Consistent naming: The entry name schema-generator matches the new export path

📝 Minor Observations:

  • The dynamic import pattern (await import('./schema-generator')).generateSchema is standard and safe
  • Build configuration correctly separates the heavy schema generation logic from the core adapter

🚀 Performance Considerations

✅ Benefits:

  • Significant bundle size reduction: The schema-generator includes heavy dependencies (@zenstackhq/language, @zenstackhq/common-helpers, AST processing) that are now lazy-loaded
  • Runtime efficiency: Schema generation only loads when createSchema is actually called
  • Tree-shaking friendly: Separate entry point allows bundlers to optimize more effectively

⚠️ Considerations:

  • First-call latency: Initial createSchema() calls will have slight delay due to dynamic import (expected trade-off)
  • Error handling: Dynamic imports can fail, but the error would bubble up naturally through the async call

🔒 Security Concerns

✅ No security issues identified:

  • Dynamic import uses relative path './schema-generator' (not user-controlled)
  • No new attack surfaces introduced
  • Maintains existing error handling patterns

🧪 Test Coverage Assessment

📋 Current Test Coverage:

  • Existing tests in test/cli-generate.test.ts validate schema generation end-to-end
  • Tests use the Better Auth CLI which exercises the createSchema flow

💡 Recommendations for Enhanced Testing:

  1. Bundle size verification: Consider adding a test that verifies the main adapter bundle excludes schema-generator code
  2. Dynamic import testing: Add unit tests that directly test the lazy loading behavior
  3. Export resolution testing: Verify the new ./schema-generator export works in both ESM/CJS environments
// Suggested test cases:
describe('Lazy loading', () => {
  it('should not load schema-generator until createSchema is called', () => {
    // Test that importing adapter doesn't pull in schema-generator
  });
  
  it('should resolve ./schema-generator export correctly', async () => {
    const { generateSchema } = await import('@zenstackhq/better-auth/schema-generator');
    expect(typeof generateSchema).toBe('function');
  });
});

🎯 Recommendations

  1. Documentation: Consider updating README/docs to mention the new ./schema-generator export for advanced users
  2. Testing: Add bundle size regression tests to prevent accidentally breaking the lazy loading
  3. Type safety: The current implementation looks type-safe, but consider adding explicit return type annotations for the dynamic import if TypeScript inference needs help

📝 Implementation Details Review

adapter.ts (Line 211-212):

const generateSchema = (await import('./schema-generator')).generateSchema;
return generateSchema(file, tables, config, options);

✅ Correct pattern - preserves all parameters and return types

package.json (Lines 42-51):
✅ Proper dual package exports with correct type declarations

tsdown.config.ts (Line 3):
✅ Clean build configuration supporting multiple entry points


🏆 Final Verdict

This is an excellent performance optimization that follows TypeScript/Node.js best practices. The implementation is clean, safe, and should deliver meaningful bundle size improvements for consumers who don't use the schema generation features.

Approved with confidence! 🚀

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 24, 2026

📝 Walkthrough

Walkthrough

The better-auth package now exposes a new public entry point ./schema-generator with dual ESM and CommonJS module format support. This enables consumers to import the schema generator directly while converting its internal usage from static to dynamic imports for deferred module loading.

Changes

Cohort / File(s) Summary
Build Configuration
packages/auth-adapters/better-auth/package.json, packages/auth-adapters/better-auth/tsdown.config.ts
Added new ./schema-generator subpath export with separate ESM/CommonJS targets and corresponding build entry point configuration.
Module Loading
packages/auth-adapters/better-auth/src/adapter.ts
Replaced static import of generateSchema with dynamic runtime import within createSchema method invocation.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 A schema path emerges bright,
ESM and CommonJS in sight,
Dynamic loading, lean and spry,
No static chains to weigh us down,
Lazy loading wears the crown! 🌟

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Title check ✅ Passed The title accurately describes the main changes: implementing lazy-loading of schema-generator via dynamic import and exposing it as a separate entry point.

✏️ 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 feat/better-auth-lazy-schema-generator

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.

@ymc9 ymc9 changed the title feat(better-auth): lazy-load schema-generator and expose as separate entry point fix(better-auth): lazy-load schema-generator and expose as separate entry point Apr 24, 2026
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
packages/auth-adapters/better-auth/src/adapter.ts (1)

210-213: Dynamic import achieves the lazy-load goal; minor readability nit.

The change correctly defers loading of the ZModel schema-parsing code to the first createSchema call. Node/bundlers cache the imported module, so subsequent invocations won't re-parse it. Relative path './schema-generator' matches the new tsdown entry and the ./schema-generator subpath export, so both ESM and CJS consumers will resolve the sibling bundle correctly.

Optional: destructure at the await site for a touch more clarity.

♻️ Optional refactor
-                createSchema: async ({ file, tables }) => {
-                    const generateSchema = (await import('./schema-generator')).generateSchema;
-                    return generateSchema(file, tables, config, options);
-                },
+                createSchema: async ({ file, tables }) => {
+                    const { generateSchema } = await import('./schema-generator');
+                    return generateSchema(file, tables, config, options);
+                },
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/auth-adapters/better-auth/src/adapter.ts` around lines 210 - 213,
The createSchema handler lazily imports './schema-generator' but could be
clearer by destructuring the exported generateSchema at the await site; update
the createSchema implementation (function createSchema) to await
import('./schema-generator') and destructure { generateSchema } from the module
before calling generateSchema(file, tables, config, options) so the code is more
readable while preserving lazy-loading and caching behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/auth-adapters/better-auth/src/adapter.ts`:
- Around line 210-213: The createSchema handler lazily imports
'./schema-generator' but could be clearer by destructuring the exported
generateSchema at the await site; update the createSchema implementation
(function createSchema) to await import('./schema-generator') and destructure {
generateSchema } from the module before calling generateSchema(file, tables,
config, options) so the code is more readable while preserving lazy-loading and
caching behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: aaf68211-b580-4a79-9897-516fc7283748

📥 Commits

Reviewing files that changed from the base of the PR and between 9ed7d2a and 8ef5fb2.

📒 Files selected for processing (3)
  • packages/auth-adapters/better-auth/package.json
  • packages/auth-adapters/better-auth/src/adapter.ts
  • packages/auth-adapters/better-auth/tsdown.config.ts

@ymc9 ymc9 merged commit f2a1986 into dev Apr 25, 2026
9 checks passed
@ymc9 ymc9 deleted the feat/better-auth-lazy-schema-generator branch April 25, 2026 00:04
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