npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@social.dev/server-sdk

v0.0.1-alpha.75

Published

Server SDK for Social.dev - A comprehensive NestJS-based framework for building scalable social media server applications.

Readme

@social.dev/server-sdk

Server SDK for Social.dev - A comprehensive NestJS-based framework for building scalable social media server applications.

Overview

The @social.dev/server-sdk package provides:

  • 🏗️ NestJS Framework - Built on top of NestJS 11 for enterprise-grade applications
  • 🔐 Authentication System - Multiple auth methods including OIDC, JWT, and cookie-based sessions
  • 💾 Database Integration - TypeORM with PostgreSQL support and migration tools
  • 🔌 Plugin Architecture - Extensible plugin system for custom functionality
  • 💬 Chat System - Real-time messaging with conversation management
  • 👥 Community Features - Sub-communities with member management
  • 📝 Post Management - Content creation and interaction system
  • 🔔 Notifications - Push notification support with device management
  • 📁 File Storage - S3-compatible file storage integration
  • 📊 API Documentation - Auto-generated Swagger/OpenAPI documentation
  • 🌐 Multi-Network Support - Domain-based network isolation

Installation

# Using pnpm (recommended)
pnpm add @social.dev/server-sdk

# Using npm
npm install @social.dev/server-sdk

# Using yarn
yarn add @social.dev/server-sdk

Prerequisites

  • Node.js 18 or higher
  • PostgreSQL 14 or higher
  • Redis (optional, for caching)
  • S3-compatible storage (optional, for file uploads)

Quick Start

Basic Setup

Create a new file index.ts in your server application:

import { bootstrap } from '@social.dev/server-sdk/bootstrap';

// Initialize the server with minimal configuration
bootstrap({
  auth: {
    methods: ['password'], // Enable password authentication
  },
});

Advanced Setup with OIDC and Plugins

import { bootstrap } from '@social.dev/server-sdk/bootstrap';
import { AuthMethodEnum } from '@social.dev/server-sdk/auth/enums/auth-method.enum';
import { PluginFactory } from '@social.dev/server-sdk/core/plugin/plugin.factory';
import SocialDevAiPlugin from '@social.dev/plugin-ai';

// Register plugins before bootstrap
PluginFactory.addPlugin(
  SocialDevAiPlugin.forRoot({
    userIds: [3], // User IDs that can access AI features
  }),
);

// Bootstrap the server with comprehensive configuration
bootstrap({
  auth: {
    methods: [AuthMethodEnum.Oidc, AuthMethodEnum.Password],
    oidc: {
      providers: [
        {
          id: 'keycloak',
          name: 'Company Keycloak',
          issuer: 'https://keycloak.example.com/auth/realms/company',
          clientId: 'social-dev-app',
          clientSecret: process.env.OIDC_CLIENT_SECRET,
        },
      ],
    },
  },
  network: {
    domainAliasMap: {
      localhost: 1,
      'dev.example.com': 2,
      'staging.example.com': 3,
    },
  },
});

Configuration

Environment Variables

Create a .env file in your project root:

# Server Configuration
SOCIAL_DEV_SERVER_PORT=3000
NODE_ENV=development

# Database Configuration
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=socialdev
POSTGRES_PASSWORD=yourpassword
POSTGRES_DB=socialdev_db

# Authentication
JWT_SECRET=your-super-secret-jwt-key
JWT_EXPIRES_IN=7d

# OIDC Configuration (optional)
OIDC_CLIENT_SECRET=your-oidc-secret

# S3 Storage (optional)
AWS_ACCESS_KEY_ID=your-access-key
AWS_SECRET_ACCESS_KEY=your-secret-key
AWS_REGION=us-east-1
S3_BUCKET_NAME=socialdev-uploads

# Push Notifications (optional)
FCM_SERVER_KEY=your-fcm-server-key
APNS_KEY_ID=your-apns-key-id
APNS_TEAM_ID=your-apns-team-id

Bootstrap Configuration Options

interface BootstrapConfig {
  auth?: {
    // Available authentication methods
    methods: AuthMethodEnum[];

    // OIDC provider configuration
    oidc?: {
      providers: OidcProvider[];
    };

    // JWT configuration
    jwt?: {
      secret?: string;
      expiresIn?: string;
    };
  };

  network?: {
    // Map domains to network IDs for multi-tenant support
    domainAliasMap: { [domain: string]: number };
  };

  database?: {
    // Override default database configuration
    host?: string;
    port?: number;
    username?: string;
    password?: string;
    database?: string;
    synchronize?: boolean; // Auto-sync schema (dev only!)
  };

  storage?: {
    // S3 configuration
    accessKeyId?: string;
    secretAccessKey?: string;
    region?: string;
    bucket?: string;
  };
}

Core Modules

Authentication Module

The SDK supports multiple authentication methods:

// Available authentication methods
enum AuthMethodEnum {
  Password = 'password',
  Oidc = 'oidc',
  Magic = 'magic', // Magic link via email
}

// OIDC Provider configuration
interface OidcProvider {
  id: string; // Unique identifier
  name: string; // Display name
  issuer: string; // OIDC issuer URL
  clientId: string; // OAuth client ID
  clientSecret: string; // OAuth client secret
  scope?: string; // OAuth scopes (default: 'openid profile email')
}

User Module

User management with profiles and authentication:

// User entity structure
interface User {
  id: number;
  username: string;
  email: string;
  name?: string;
  bio?: string;
  avatar?: string;
  verified: boolean;
  createdAt: Date;
  updatedAt: Date;
}

Post Module

Content creation and management:

// Post entity structure
interface Post {
  id: number;
  content: string;
  authorId: number;
  parentId?: number; // For replies
  attachments?: MediaAsset[];
  likes: number;
  comments: number;
  shares: number;
  createdAt: Date;
  updatedAt: Date;
}

Chat Module

Real-time messaging system:

// Conversation management
interface Conversation {
  id: number;
  participants: User[];
  lastMessage?: Message;
  unreadCount: number;
  createdAt: Date;
  updatedAt: Date;
}

// Message structure
interface Message {
  id: number;
  conversationId: number;
  senderId: number;
  content: string;
  attachments?: MediaAsset[];
  readBy: number[];
  createdAt: Date;
}

Community Module

Sub-communities (subs) management:

// Sub entity structure
interface Sub {
  id: number;
  name: string;
  description?: string;
  avatar?: string;
  banner?: string;
  memberCount: number;
  postCount: number;
  createdAt: Date;
}

// Member management
interface SubMember {
  subId: number;
  userId: number;
  role: 'owner' | 'moderator' | 'member';
  joinedAt: Date;
}

Notification Module

Push notification management:

// Device registration
interface NotificationDevice {
  id: number;
  userId: number;
  token: string;
  platform: 'ios' | 'android' | 'web';
  active: boolean;
}

// Notification sending
interface Notification {
  userId: number;
  title: string;
  body: string;
  data?: Record<string, any>;
  priority?: 'high' | 'normal';
}

Plugin System

The SDK supports a powerful plugin architecture for extending functionality:

Creating a Custom Plugin

// plugins/my-plugin/index.ts
import { Injectable, Module } from '@nestjs/common';
import { PluginInterface } from '@social.dev/server-sdk/core/plugin/plugin.interface';

@Injectable()
class MyPluginService {
  async processContent(content: string): Promise<string> {
    // Your plugin logic here
    return content.toUpperCase();
  }
}

@Module({
  providers: [MyPluginService],
  exports: [MyPluginService],
})
export class MyPlugin implements PluginInterface {
  static forRoot(options?: { enabled?: boolean }) {
    return {
      module: MyPlugin,
      providers: [
        {
          provide: 'MY_PLUGIN_OPTIONS',
          useValue: options || {},
        },
      ],
    };
  }
}

Registering Plugins

import { PluginFactory } from '@social.dev/server-sdk/core/plugin/plugin.factory';
import { MyPlugin } from './plugins/my-plugin';

// Register plugin before bootstrap
PluginFactory.addPlugin(
  MyPlugin.forRoot({
    enabled: true,
  }),
);

// Then bootstrap the server
bootstrap({
  /* ... */
});

Database Migrations

Generating Migrations

# Build the SDK first
pnpm build

# Generate a new migration based on entity changes
npx typeorm migration:generate \
  -d ./dist/manage-db.js \
  ./src/migrations/NewMigration

Running Migrations

# Run all pending migrations
npx typeorm migration:run \
  -d ./node_modules/@social.dev/server-sdk/dist/manage-db.js

# Revert the last migration
npx typeorm migration:revert \
  -d ./node_modules/@social.dev/server-sdk/dist/manage-db.js

Creating Custom Migrations

// migrations/1234567890-CustomMigration.ts
import { MigrationInterface, QueryRunner, Table } from 'typeorm';

export class CustomMigration1234567890 implements MigrationInterface {
  async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.createTable(
      new Table({
        name: 'custom_table',
        columns: [
          {
            name: 'id',
            type: 'int',
            isPrimary: true,
            isGenerated: true,
            generationStrategy: 'increment',
          },
          {
            name: 'name',
            type: 'varchar',
          },
        ],
      }),
      true,
    );
  }

  async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.dropTable('custom_table');
  }
}

API Documentation

The SDK automatically generates Swagger/OpenAPI documentation:

# Start your server
pnpm dev

# Access the documentation
open http://localhost:3000/schema

Custom API Endpoints

You can add custom endpoints by creating NestJS controllers:

// src/custom/custom.controller.ts
import { Controller, Get, Post, Body, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { AuthGuard } from '@social.dev/server-sdk/auth/auth.guard';

@ApiTags('custom')
@Controller('custom')
export class CustomController {
  @Get('public')
  getPublicData() {
    return { message: 'This is public' };
  }

  @Post('protected')
  @UseGuards(AuthGuard)
  @ApiBearerAuth()
  createProtectedResource(@Body() data: any) {
    return { success: true, data };
  }
}

// Register in a module
@Module({
  controllers: [CustomController],
})
export class CustomModule {}

Development Scripts

# Install dependencies
pnpm install

# Development mode with hot reload
pnpm dev

# Build for production
pnpm build

# Start production server
pnpm start:prod

# Run tests
pnpm test

# Run tests with coverage
pnpm test:cov

# Lint code
pnpm lint

# Format code
pnpm format

Production Deployment

Using PM2

// ecosystem.config.js
module.exports = {
  apps: [
    {
      name: 'social-dev-server',
      script: './dist/index.js',
      instances: 'max',
      exec_mode: 'cluster',
      env: {
        NODE_ENV: 'production',
        SOCIAL_DEV_SERVER_PORT: 3000,
      },
    },
  ],
};
# Build and start with PM2
pnpm build
pm2 start ecosystem.config.js

Using Docker

# Dockerfile
FROM node:18-alpine AS builder

WORKDIR /app
COPY package*.json pnpm-lock.yaml ./
RUN npm install -g pnpm
RUN pnpm install --frozen-lockfile

COPY . .
RUN pnpm build

FROM node:18-alpine

WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./

EXPOSE 3000
CMD ["node", "dist/index.js"]

Using Vercel

// vercel.json
{
  "version": 2,
  "builds": [
    {
      "src": "api/index.ts",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "/api"
    }
  ]
}
// api/index.ts
import { bootstrap } from '@social.dev/server-sdk/bootstrap';

export default async function handler(req, res) {
  const app = await bootstrap({
    // Your configuration
  });
  return app.getHttpAdapter().getInstance()(req, res);
}

Multi-Network Support

The SDK supports running multiple isolated networks on a single server instance:

bootstrap({
  network: {
    domainAliasMap: {
      'network1.example.com': 1,
      'network2.example.com': 2,
      'api.company.com': 3,
    },
  },
});

// Each domain will have isolated:
// - Users and authentication
// - Posts and content
// - Communities
// - Chat conversations
// - Notifications

Security Best Practices

  1. Environment Variables: Never commit .env files to version control
  2. Database: Always disable synchronize in production
  3. CORS: Configure allowed origins in production
  4. Rate Limiting: Implement rate limiting for API endpoints
  5. Input Validation: Use DTOs with class-validator for all inputs
  6. Authentication: Use strong JWT secrets and appropriate expiration times
  7. HTTPS: Always use HTTPS in production

TypeScript Support

The SDK is written in TypeScript and provides full type definitions:

import type {
  User,
  Post,
  Sub,
  Message,
  Conversation,
  AuthMethodEnum,
  OidcProvider,
  Configs,
} from '@social.dev/server-sdk';

Examples

Check out the apps/server directory for a complete implementation example using the SDK.

Example Server Implementation

// apps/server/index.ts
import SocialDevAiPlugin from '@social.dev/plugin-ai';
import { AuthMethodEnum } from '@social.dev/server-sdk/auth/enums/auth-method.enum';
import { PluginFactory } from '@social.dev/server-sdk/core/plugin/plugin.factory';

// Initialize plugins
PluginFactory.addPlugin(
  SocialDevAiPlugin.forRoot({
    userIds: [3],
  }),
);

// Initialize the server
import('@social.dev/server-sdk/bootstrap').then(({ bootstrap }) => {
  bootstrap({
    auth: {
      methods: [AuthMethodEnum.Oidc],
      oidc: {
        providers: [
          {
            id: 'minds-inc',
            name: 'Minds Keycloak',
            issuer: 'https://keycloak.minds.com/auth/realms/minds-inc',
            clientId: 'demo-social-dev',
            clientSecret: process.env.SOCIAL_DEV_OIDC_SECRET,
          },
        ],
      },
    },
    network: {
      domainAliasMap: {
        localhost: 2,
      },
    },
  });
});

Troubleshooting

Common Issues

  1. Database Connection Failed

    • Check PostgreSQL is running
    • Verify database credentials in .env
    • Ensure database exists
  2. Port Already in Use

    • Change SOCIAL_DEV_SERVER_PORT in .env
    • Kill existing process: lsof -i :3000
  3. Migration Errors

    • Build the SDK first: pnpm build
    • Check database permissions
    • Review migration SQL for conflicts
  4. OIDC Authentication Failed

    • Verify issuer URL is accessible
    • Check client ID and secret
    • Ensure redirect URIs are configured

Contributing

Contributions are welcome! Please read our contributing guidelines before submitting PRs.

License

MIT

Support