UNPKG

@pulzar/core

Version:

Next-generation Node.js framework for ultra-fast web applications with zero-reflection DI, GraphQL, WebSockets, events, and edge runtime support

543 lines (407 loc) 12.9 kB
<h1 align="center">Pulzar - Next-generation Node.js framework</h1> <div align="center"> <img src="https://raw.githubusercontent.com/Pulzar-Framework/.github/main/assets/logo.png" alt="Pulzar Logo" style="300px" width="300px" /> ### **Ultra-Fast • Edge-First • Zero-Reflection • Production-Ready** <div align="center"> [![npm version](https://badge.fury.io/js/@pulzar%2Fcore.svg)](https://badge.fury.io/js/@pulzar%2Fcore) [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com) [![Downloads](https://img.shields.io/npm/dm/@pulzar/core.svg)](https://www.npmjs.com/package/@pulzar/core) **Next-generation TypeScript framework for ultra-fast web applications** _Built on Fastify with zero-reflection dependency injection, GraphQL, WebSockets, events, and edge runtime support_ [**Documentation**](https://pulzar.dev) [**Quick Start**](#quick-start) [**Examples**](#examples) [**API Reference**](https://pulzar.dev/api) [**Discord**](https://discord.gg/pulzar) </div> </div> --- ## ✨ Why Pulzar Core? Pulzar Core is a **production-ready TypeScript framework** that combines the speed of Fastify with modern development patterns. Built for developers who need **blazing-fast performance** without sacrificing developer experience. ### 🎯 Key Features - **🚄 Ultra-Fast Performance** - Built on Fastify, one of the fastest Node.js frameworks - **💉 Zero-Reflection DI** - Lightning-fast dependency injection without runtime reflection - **🔐 Advanced Authentication** - JWT, OAuth2, session-based auth with role-based access control - **🌐 GraphQL Ready** - Built-in Mercurius integration with automatic schema generation - **📡 Real-time Events** - Kafka, NATS, Redis event streaming with schema validation - **🌊 WebSocket Support** - Full WebSocket gateway with uWS integration - **⚡ Edge Runtime** - Deploy to Cloudflare Workers, Vercel Edge, and Deno Deploy - **🔍 OpenAPI Generation** - Automatic API documentation from TypeScript types - **🔄 Hot Reload** - Development mode with instant code updates - **📊 Observability** - OpenTelemetry tracing, metrics, and structured logging - **🧪 Testing Utils** - Comprehensive testing utilities and mocking helpers --- ## 🚀 Quick Start ### Installation ```bash npm install @pulzar/core # or yarn add @pulzar/core # or pnpm add @pulzar/core ``` ### Basic Usage ```typescript import { Pulzar, Controller, Get, Injectable } from "@pulzar/core"; @Injectable() class UserService { getUsers() { return [ { id: 1, name: "Alice" }, { id: 2, name: "Bob" }, ]; } } @Controller("/api/users") class UserController { constructor(private userService: UserService) {} @Get("/") async getUsers() { return this.userService.getUsers(); } } const app = new Pulzar({ controllers: [UserController], providers: [UserService], }); app.listen(3000, () => { console.log("🚀 Server running at http://localhost:3000"); }); ``` ### With Authentication ```typescript import { JWTGuard, RequireAuth, RequireRoles } from "@pulzar/core"; @Controller("/api/admin") class AdminController { @Get("/users") @RequireAuth() @RequireRoles("admin") async getUsers() { return await this.userService.getUsers(); } } const app = new Pulzar({ auth: { jwt: { secret: process.env.JWT_SECRET, algorithm: "HS256", }, }, }); ``` --- ## 🏗️ Architecture & Features ### 💉 Dependency Injection Pulzar uses **zero-reflection DI** for maximum performance: ```typescript import { Injectable, Inject, Singleton, RequestScoped } from "@pulzar/core"; @Injectable({ scope: "singleton" }) class DatabaseService { query(sql: string) { return { result: "data" }; } } @Injectable({ scope: "request" }) class UserService { constructor( @Inject("DatabaseService") private db: DatabaseService, @Inject("LOGGER") private logger: Logger ) {} async getUser(id: string) { this.logger.info(`Getting user ${id}`); return this.db.query(`SELECT * FROM users WHERE id = ?`); } } ``` ### 🔐 Authentication & Authorization Comprehensive auth system with multiple strategies: ```typescript import { JWTGuard, SessionGuard, OAuth2Guard } from "@pulzar/core"; // JWT Authentication const jwtGuard = new JWTGuard({ secret: process.env.JWT_SECRET, algorithm: "HS256", issuer: "your-app", }); // Session-based Authentication const sessionGuard = new SessionGuard({ store: new RedisSessionStore(), secret: process.env.SESSION_SECRET, maxAge: 24 * 60 * 60 * 1000, // 24 hours }); // OAuth2 Integration @Controller("/auth") class AuthController { @Post("/login") async login(@Body() credentials: LoginDto) { const user = await this.authService.validateUser(credentials); return this.jwtGuard.signToken(user); } @Get("/profile") @RequireAuth() async getProfile(@CurrentUser() user: User) { return user; } } ``` ### 📡 Event System Powerful event streaming with multiple adapters: ```typescript import { EventBus, Event, EventHandler } from "@pulzar/core"; @Event("user.created") class UserCreatedEvent { constructor( public readonly userId: string, public readonly email: string ) {} } @EventHandler(UserCreatedEvent) class SendWelcomeEmailHandler { async handle(event: UserCreatedEvent) { await this.emailService.sendWelcomeEmail(event.email); } } // Emit events await this.eventBus.emit(new UserCreatedEvent("123", "user@example.com")); // Configure adapters const app = new Pulzar({ events: { adapter: "kafka", // or 'nats', 'redis', 'memory' kafka: { brokers: ["localhost:9092"], clientId: "pulzar-app", }, }, }); ``` ### 🌐 GraphQL Integration Built-in GraphQL support with automatic schema generation: ```typescript import { Resolver, Query, Mutation, Args } from "@pulzar/core"; @Resolver() class UserResolver { constructor(private userService: UserService) {} @Query(() => [User]) async users() { return this.userService.findAll(); } @Mutation(() => User) async createUser(@Args("input") input: CreateUserInput) { return this.userService.create(input); } } const app = new Pulzar({ graphql: { path: "/graphql", playground: true, introspection: true, }, }); ``` ### 🌊 WebSocket Gateway Real-time communication with WebSocket support: ```typescript import { WebSocketGateway, Subscribe, Emit } from "@pulzar/core"; @WebSocketGateway("/ws") class ChatGateway { @Subscribe("message") handleMessage(client: WebSocket, data: any) { // Broadcast to all clients this.broadcast("message", data); } @Emit("user-joined") onUserJoin(userId: string) { return { userId, timestamp: new Date() }; } } ``` ### ⚡ Edge Runtime Support Deploy to edge environments: ```typescript import { EdgeAdapter } from "@pulzar/core/edge"; // Cloudflare Workers export default EdgeAdapter.cloudflare(app); // Vercel Edge Functions export default EdgeAdapter.vercel(app); // Deno Deploy export default EdgeAdapter.deno(app); ``` --- ## 🔧 Configuration ### Environment Configuration ```typescript import { Config } from "@pulzar/core"; @Config() class AppConfig { @Env("PORT", { default: 3000 }) port: number; @Env("DATABASE_URL", { required: true }) databaseUrl: string; @Env("JWT_SECRET", { required: true }) jwtSecret: string; @Env("REDIS_URL", { default: "redis://localhost:6379" }) redisUrl: string; } ``` ### Application Setup ```typescript import { Pulzar } from "@pulzar/core"; const app = new Pulzar({ // Core configuration port: 3000, host: "0.0.0.0", // Database database: { url: process.env.DATABASE_URL, type: "postgresql", }, // Authentication auth: { jwt: { secret: process.env.JWT_SECRET, expiresIn: "1d", }, session: { store: "redis", secret: process.env.SESSION_SECRET, }, }, // Events events: { adapter: "kafka", kafka: { brokers: ["localhost:9092"], }, }, // GraphQL graphql: { path: "/graphql", playground: process.env.NODE_ENV === "development", }, // WebSockets websockets: { path: "/ws", cors: true, }, // OpenAPI openapi: { title: "My API", version: "1.0.0", path: "/docs", }, // Observability tracing: { enabled: true, serviceName: "my-app", }, }); ``` --- ## 📦 Exports ### Core Exports ```typescript // Main framework export * from "@pulzar/core"; // Edge runtime adapters export * from "@pulzar/core/edge"; // Testing utilities export * from "@pulzar/core/testing"; ``` ### Available Modules - **HTTP**: Fastify adapter, routing, middleware - **DI**: Dependency injection, decorators, scanning - **Auth**: JWT, sessions, OAuth2, guards - **Events**: Event bus, adapters (Kafka, NATS, Redis) - **GraphQL**: Mercurius integration, resolvers - **WebSockets**: Gateway, adapters (uWS, native) - **OpenAPI**: Schema generation, Swagger UI - **Database**: ORM integration, migrations - **Validation**: Zod integration, custom validators - **Logging**: Structured logging, OpenTelemetry - **Testing**: Mocking, utilities, helpers --- ## 🧪 Testing Comprehensive testing utilities included: ```typescript import { createTestApp, MockService } from "@pulzar/core/testing"; describe("UserController", () => { let app: TestApp; let userService: MockService<UserService>; beforeEach(async () => { app = await createTestApp({ controllers: [UserController], providers: [ { provide: UserService, useClass: MockService, }, ], }); userService = app.get(UserService); }); it("should get users", async () => { userService.getUsers.mockResolvedValue([{ id: 1, name: "Alice" }]); const response = await app.inject({ method: "GET", url: "/api/users", }); expect(response.statusCode).toBe(200); expect(response.json()).toEqual([{ id: 1, name: "Alice" }]); }); }); ``` --- ## 🚀 Performance Pulzar Core is built for speed: - **Fastify Foundation**: Up to 30,000 req/sec - **Zero-Reflection DI**: No runtime overhead - **Optimized Bundling**: Tree-shakeable modules - **Edge Ready**: Sub-100ms cold starts - **Memory Efficient**: Minimal footprint ### Benchmarks ```bash # Basic HTTP Stat 2.5% 50% 97.5% 99% Avg Stdev Max ├───────────┼───────┼───────┼───────┼───────┼─────────┼─────────┼──────────┤ Req/Sec 28,191 30,207 30,975 31,135 29,967 1,012.46 31,135 Latency 2ms 3ms 5ms 6ms 3.32ms 1.12ms 25ms ``` --- ## 🔗 Ecosystem Pulzar Core works great with: - **[@pulzar/cli](https://npm.im/@pulzar/cli)** - Development CLI tools - **[@pulzar/plugins](https://npm.im/@pulzar/plugins)** - Additional integrations - **[Prisma](https://prisma.io)** - Database ORM - **[Zod](https://zod.dev)** - Schema validation - **[Vitest](https://vitest.dev)** - Testing framework --- ## 📖 Documentation - **[Getting Started](https://pulzar.dev/getting-started)** - Installation and first steps - **[API Reference](https://pulzar.dev/api)** - Complete API documentation - **[Examples](https://pulzar.dev/examples)** - Real-world examples - **[Deployment](https://pulzar.dev/deployment)** - Production deployment guides - **[Migration Guide](https://pulzar.dev/migration)** - Migrating from other frameworks --- ## 🤝 Contributing We welcome contributions! Please see our [Contributing Guide](https://github.com/pulzar-framework/pulzar/blob/main/CONTRIBUTING.md). ### Development Setup ```bash git clone https://github.com/pulzar-framework/pulzar.git cd pulzar npm install npm run build npm test ``` --- ## 📄 License MIT © [Pulzar Team](https://github.com/pulzar) --- ## 🙏 Acknowledgments Built with ❤️ by the Pulzar team and powered by: - [Fastify](https://fastify.io) - Fast and low overhead web framework - [TypeScript](https://typescriptlang.org) - Language and tooling - [Zod](https://zod.dev) - Schema validation - [OpenTelemetry](https://opentelemetry.io) - Observability --- <div align="center"> **[ Star us on GitHub](https://github.com/pulzar-framework/pulzar)** **[💬 Join Discord](https://discord.gg/pulzar)** **[🐦 Follow on Twitter](https://twitter.com/pulzardev)** Made with ❤️ for the developer community </div>