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

@encodeagent/platform-helper-api

v1.2509.1201722

Published

Comprehensive TypeScript utility library for the EncodeAgent platform with AI services, authentication, file handling, and more

Readme

@encodeagent/platform-helper-api

Shared utilities and common functions for web APIs and MCP servers in the EncodeAgent platform. This package provides reusable components for building consistent, well-structured APIs with TypeScript.

Copy whole sh folder to helper folder

Installation

npm install @encodeagent/platform-helper-api

Features

  • Configuration Management: Environment-based config with Zod validation
  • Structured Logging: Configurable logging with timestamps and levels
  • Response Utilities: Consistent API response formatting
  • Validation Middleware: Request validation with Zod schemas
  • Error Handling: Standardized error responses and middleware
  • CORS Support: Configurable cross-origin resource sharing
  • Type Safety: Full TypeScript support with comprehensive types

Quick Start

import { 
  parseApiConfig, 
  logger, 
  sendSuccess, 
  validateRequest 
} from '@encodeagent/platform-helper-api';

const config = parseApiConfig();
logger.info('Server starting...');

Core Utilities

Configuration Management

import { 
  parseApiConfig, 
  parseConfig, 
  createEnvironmentHelpers,
  apiConfigSchema 
} from '@encodeagent/platform-helper-api';

// Parse standard API configuration
const config = parseApiConfig();

// Parse custom configuration
const customConfig = parseConfig(mySchema);

// Environment helpers
const { isDevelopment, isProduction } = createEnvironmentHelpers(config.NODE_ENV);

Structured Logging

import { 
  logger, 
  createLogger, 
  LogLevel 
} from '@encodeagent/platform-helper-api';

// Use default logger
logger.info('Server started');
logger.error('Something went wrong', { error: err });

// Create custom logger
const customLogger = createLogger({ level: 'debug' });
customLogger.debug('Debug information');

Response Utilities

import { 
  sendSuccess, 
  sendError, 
  sendHealthResponse,
  handleValidationError 
} from '@encodeagent/platform-helper-api';

// Success response
sendSuccess(res, { message: 'Hello World' });

// Error response
sendError(res, 'Something went wrong', 400);

// Health check response
sendHealthResponse(res, '1.0.0');

// Validation error handling
handleValidationError(res, zodError);

Validation Middleware

import { 
  validateRequest, 
  validateQuery, 
  validateBody,
  commonSchemas 
} from '@encodeagent/platform-helper-api';
import { z } from 'zod';

const userSchema = z.object({
  name: commonSchemas.nonEmptyString,
  email: commonSchemas.email
});

// Validate request (query + body)
app.post('/users', validateRequest(userSchema), (req, res) => {
  const { name, email } = req.validatedData;
  sendSuccess(res, { name, email });
});

// Validate query parameters only
app.get('/users', validateQuery(commonSchemas.paginationQuery), handler);

// Validate body only
app.post('/users', validateBody(userSchema), handler);

Error Handling

import { 
  errorHandler, 
  notFoundHandler, 
  asyncHandler 
} from '@encodeagent/platform-helper-api';

// Global error handler
app.use(errorHandler);

// 404 handler
app.use(notFoundHandler);

// Async error wrapper
app.get('/users', asyncHandler(async (req, res) => {
  const users = await getUsersFromDB();
  sendSuccess(res, users);
}));

CORS Middleware

import { 
  defaultCorsMiddleware, 
  createCorsMiddleware, 
  mcpCorsMiddleware 
} from '@encodeagent/platform-helper-api';

// Default CORS
app.use(defaultCorsMiddleware);

// Custom CORS
app.use(createCorsMiddleware('https://myapp.com', ['X-Custom-Header']));

// MCP-specific CORS
app.use(mcpCorsMiddleware('Mcp-Session-Id'));

Common Schemas

The package includes pre-built Zod schemas for common validation patterns:

import { commonSchemas } from '@encodeagent/platform-helper-api';

// String validations
commonSchemas.nonEmptyString
commonSchemas.email
commonSchemas.url

// Number validations
commonSchemas.positiveNumber
commonSchemas.port

// Environment validations
commonSchemas.nodeEnv
commonSchemas.logLevel

// API specific
commonSchemas.apiVersion
commonSchemas.paginationQuery
commonSchemas.sortQuery

Utility Functions

String Utilities

import _ from 'lodash';

// Use lodash for common string operations
const camelCase = _.camelCase('hello-world'); // 'helloWorld'
const kebabCase = _.kebabCase('HelloWorld'); // 'hello-world'
const snakeCase = _.snakeCase('HelloWorld'); // 'hello_world'
const capitalized = _.capitalize('hello'); // 'Hello'
const truncated = _.truncate('Long text here', { length: 10 }); // 'Long te...'

Date Utilities

import { 
  getCurrentTimestamp, 
  formatDate, 
  parseDate,
  isValidDate,
  getDateDiff,
  addDays 
} from '@encodeagent/platform-helper-api';

const timestamp = getCurrentTimestamp(); // ISO string
const formatted = formatDate(new Date()); // ISO string
const parsed = parseDate('2023-01-01'); // Date object
const isValid = isValidDate(new Date()); // boolean
const diff = getDateDiff(date1, date2); // milliseconds
const future = addDays(new Date(), 7); // Date + 7 days

Complete Express.js Example

import express from 'express';
import { 
  parseApiConfig,
  createEnvironmentHelpers,
  logger,
  defaultCorsMiddleware,
  validateRequest,
  sendSuccess,
  sendHealthResponse,
  errorHandler,
  notFoundHandler,
  commonSchemas
} from '@encodeagent/platform-helper-api';
import { z } from 'zod';

const config = parseApiConfig();
const { isDevelopment } = createEnvironmentHelpers(config.NODE_ENV);

const app = express();

// Middleware
app.use(express.json());
app.use(defaultCorsMiddleware);

// Health check
app.get('/health', (req, res) => {
  sendHealthResponse(res, '1.0.0');
});

// API routes
const helloSchema = z.object({
  name: z.string().default('World')
});

app.get('/api/v1/hello', validateRequest(helloSchema), (req, res) => {
  const { name } = req.validatedData;
  sendSuccess(res, { greeting: `Hello, ${name}!` });
});

// Error handling
app.use(errorHandler);
app.use(notFoundHandler);

// Start server
app.listen(config.PORT, () => {
  logger.info(`Server listening on port ${config.PORT}`);
});

TypeScript Support

This library is written in TypeScript and includes comprehensive type definitions:

import type { 
  ApiResponse, 
  ApiFunction, 
  HealthResponse,
  ErrorResponse,
  BaseConfig,
  ApiConfig 
} from '@encodeagent/platform-helper-api';

// Extend Express Request type
declare global {
  namespace Express {
    interface Request {
      validatedData?: any;
    }
  }
}

Integration with MCP Servers

This package works seamlessly with MCP (Model Context Protocol) servers:

import { 
  mcpCorsMiddleware, 
  logger, 
  sendError 
} from '@encodeagent/platform-helper-api';

// MCP-specific CORS
app.use(mcpCorsMiddleware('Mcp-Session-Id'));

// MCP error handling
const handleMcpError = (error: any, res: Response) => {
  logger.error('MCP Error:', error);
  sendError(res, 'MCP operation failed', 500, 'MCP_ERROR');
};

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the UNLICENSED License.

Related Packages

  • @encodeagent/platform-helper-util - General utility functions
  • @encodeagent/api-context - Example API implementation using this package