TypeScript-first foundational SDK for Node.js backends
LunarCore Node is a secure, type-safe foundational SDK for building Node.js backend applications. It provides essential utilities without framework coupling, making it perfect for any Node.js project.
- TypeScript-First - Built with strict TypeScript for maximum type safety
- Secure by Default - Security best practices baked in
- Zero Framework Coupling - Use with Express, Fastify, or any framework
- Modular Design - Import only what you need
- Production Ready - Comprehensive error handling and logging
npm install @lunarcore/node zodimport { createLogger, loadEnv, retry } from '@lunarcore/node';
import { z } from 'zod';
// Type-safe environment loading
const env = loadEnv(z.object({
PORT: z.string().transform(Number),
API_KEY: z.string(),
}));
// Structured logging
const logger = createLogger({ level: 'info' });
logger.info('Server starting', { port: env.PORT });
// Safe async operations
const data = await retry(() => fetchData(), { maxAttempts: 3 });Type-safe error classes with structured context:
import { AppError, ValidationError, isAppError } from '@lunarcore/node';
// Custom errors with context
throw new ValidationError('Invalid email', { email: 'test@' });
// Type-safe error handling
try {
await operation();
} catch (error) {
if (isAppError(error)) {
console.log(error.code, error.statusCode, error.context);
}
}Schema-based environment validation with Zod:
import { loadEnv, envNumber, envBoolean } from '@lunarcore/node';
import { z } from 'zod';
const env = loadEnv(z.object({
NODE_ENV: z.enum(['development', 'production', 'test']),
PORT: envNumber.default(3000),
ENABLE_CACHE: envBoolean.default(true),
ALLOWED_ORIGINS: envList, // Comma-separated lists
}));Flexible configuration loading with validation:
import { ConfigManager, createJsonLoader } from '@lunarcore/node';
const manager = new ConfigManager(
createJsonLoader('./config.json'),
(config) => validateConfig(config)
);
const config = await manager.load(); // Load and cache
const cached = manager.get(); // Get cached config
await manager.reload(); // Force reloadProduction-ready logging with context:
import { createLogger, LogLevel } from '@lunarcore/node';
const logger = createLogger({
level: LogLevel.INFO,
defaultContext: { service: 'api' },
});
logger.info('User login', { userId: 123, ip: '1.2.3.4' });
// Child loggers inherit context
const requestLogger = logger.child({ requestId: 'req-456' });
requestLogger.info('Processing'); // Includes requestIdSafe async operations with retry, timeout, and concurrency control:
import {
retry,
withTimeout,
asyncResult,
promiseLimit
} from '@lunarcore/node';
// Retry with exponential backoff
const data = await retry(
() => fetchData(),
{ maxAttempts: 3, initialDelay: 1000 }
);
// Add timeout
const result = await withTimeout(
slowOperation(),
5000,
'Operation timed out'
);
// Safe Result type (no throws)
const result = await asyncResult(riskyOperation());
if (result.ok) {
console.log(result.value);
} else {
console.error(result.error);
}
// Concurrency control
const results = await promiseLimit(
urls,
(url) => fetch(url),
5 // Max 5 concurrent requests
);Complete usage examples are available in the examples/ directory:
- env-loader.ts - Environment variable loading with schema validation
- logger.ts - Structured logging patterns
- error-handling.ts - Error handling and custom errors
- config-loader.ts - Configuration management strategies
- async-helpers.ts - Async utilities and patterns
Every API is designed with strict TypeScript in mind. No any types, comprehensive type inference, and full IntelliSense support.
- Input validation with Zod schemas
- No eval or code execution
- Safe error serialization (no sensitive data leaks)
- Security best practices in all utilities
LunarCore Node provides foundational utilities without coupling to specific frameworks. Use it with Express, Fastify, Koa, or any Node.js setup.
// Import only what you need
import { createLogger } from '@lunarcore/node/logger';
import { retry } from '@lunarcore/node/async';AppError- Base error classValidationError- Input validation errors (400)ConfigurationError- Configuration errors (500)NotFoundError- Resource not found (404)TimeoutError- Operation timeout (408)isAppError()- Type guardisOperationalError()- Check if error is operational
loadEnv()- Load and validate environmentsafeLoadEnv()- Non-throwing variantenvNumber- Parse number from stringenvBoolean- Parse boolean from stringenvList- Parse comma-separated listenvWithDefault()- Add default values
ConfigManager- Configuration managementJsonConfigLoader- Load from JSON filesObjectConfigLoader- Load from objectsCompositeConfigLoader- Merge multiple sources
createLogger()- Create logger instanceLogger- Logger classLogLevel- Log level enumConsoleTransport- Console outputJsonTransport- JSON output
asyncResult()- Wrap promise in Result typeretry()- Retry with exponential backoffwithTimeout()- Add timeout to promisesleep()- Promise-based delaypromiseLimit()- Concurrency controlbatchProcess()- Process items in batchesdebounce()- Debounce async functionthrottle()- Throttle async function
LunarCore Node requires strict TypeScript settings. Add to your tsconfig.json:
{
"compilerOptions": {
"strict": true,
"target": "ES2022",
"module": "commonjs",
"moduleResolution": "node",
"esModuleInterop": true
}
}We welcome contributions! Please see CONTRIBUTING.md for guidelines.
For security concerns, please see SECURITY.md.
See PUBLISHING.md for detailed instructions on publishing this package to npm as @lunarcore/node.
MIT © LunarBit Studios
- LunarCore Spec - Specification and design principles
- More LunarCore modules coming soon