feat: auto-rebuild native modules on Node.js version mismatch

When Node.js is updated, native modules like better-sqlite3 can become
   incompatible due to NODE_MODULE_VERSION differences. This change adds
   automatic detection and rebuild capability:

   - Add native-module-helper.js utility for detecting version errors
   - Lazy-load better-sqlite3 to catch import errors at runtime
   - Automatically run npm rebuild when version mismatch is detected
   - Clear require cache and retry loading after successful rebuild
   - Provide clear instructions if automatic rebuild fails

   Fixes the issue where users running via npx encounter module errors
   after updating Node.js.
This commit is contained in:
jgor20
2026-01-05 00:43:21 +00:00
parent ea3d3ca4a4
commit e6027ec5a6
3 changed files with 247 additions and 5 deletions

View File

@@ -101,7 +101,8 @@ src/
└── utils/ # Utilities
├── helpers.js # formatDuration, sleep
── logger.js # Structured logging
── logger.js # Structured logging
└── native-module-helper.js # Auto-rebuild for native modules
```
**Key Modules:**
@@ -109,7 +110,7 @@ src/
- **src/server.js**: Express server exposing Anthropic-compatible endpoints (`/v1/messages`, `/v1/models`, `/health`, `/account-limits`)
- **src/cloudcode/**: Cloud Code API client with retry/failover logic, streaming and non-streaming support
- **src/account-manager/**: Multi-account pool with sticky selection, rate limit handling, and automatic cooldown
- **src/auth/**: Authentication including Google OAuth, token extraction, and database access
- **src/auth/**: Authentication including Google OAuth, token extraction, database access, and auto-rebuild of native modules
- **src/format/**: Format conversion between Anthropic and Google Generative AI formats
- **src/constants.js**: API endpoints, model mappings, fallback config, OAuth config, and all configuration values
- **src/fallback-config.js**: Model fallback mappings (`getFallbackModel()`, `hasFallback()`)
@@ -144,6 +145,13 @@ src/
- For Gemini targets: strict validation - drops unknown or mismatched signatures
- For Claude targets: lenient - lets Claude validate its own signatures
**Native Module Auto-Rebuild:**
- When Node.js is updated, native modules like `better-sqlite3` may become incompatible
- The proxy automatically detects `NODE_MODULE_VERSION` mismatch errors
- On detection, it attempts to rebuild the module using `npm rebuild`
- If rebuild succeeds, the module is reloaded; if reload fails, a server restart is required
- Implementation in `src/utils/native-module-helper.js` and lazy loading in `src/auth/database.js`
## Testing Notes
- Tests require the server to be running (`npm start` in separate terminal)