
Security News
Attackers Are Hunting High-Impact Node.js Maintainers in a Coordinated Social Engineering Campaign
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.
@gen2code/core
Advanced tools
The foundational package of the Gen2Code framework, providing shared utilities, types, configurations, and React hooks for building modern web applications.
npm install @gen2code/core
# or
yarn add @gen2code/core
# or
pnpm add @gen2code/core
Comprehensive TypeScript type definitions for the Gen2Code framework.
import type {
AuthUser,
AuthSession,
Permission,
Role,
AuthProvider
} from '@gen2code/core';
const user: AuthUser = {
id: 'user-123',
email: 'user@example.com',
emailVerified: true,
// ... other properties
};
const session: AuthSession = {
user,
accessToken: 'token',
refreshToken: 'refresh',
expiresAt: new Date(),
// ... other properties
};
import type {
User,
UserProfile,
UserSettings,
UserRole,
Avatar
} from '@gen2code/core';
const userProfile: UserProfile = {
firstName: 'John',
lastName: 'Doe',
bio: 'Software Developer',
avatar: {
url: 'https://example.com/avatar.jpg',
alt: 'John Doe'
}
};
import type {
Team,
TeamMember,
TeamInvitation,
TeamRole,
TeamPermission
} from '@gen2code/core';
const team: Team = {
id: 'team-123',
name: 'Development Team',
slug: 'dev-team',
// ... other properties
};
import type {
ApiResponse,
ApiError,
PaginatedResponse,
RequestConfig
} from '@gen2code/core';
const response: ApiResponse<User[]> = {
data: users,
success: true,
message: 'Users retrieved successfully'
};
Comprehensive validation utilities with TypeScript support and detailed error reporting.
import {
validateEmail,
normalizeEmail,
extractEmailDomain,
isDisposableEmail,
validateEmailDomain
} from '@gen2code/core';
// Basic email validation
const isValid = validateEmail('user@example.com'); // true
// Normalize email (lowercase, trim)
const normalized = normalizeEmail(' USER@EXAMPLE.COM '); // 'user@example.com'
// Extract domain
const domain = extractEmailDomain('user@example.com'); // 'example.com'
// Check for disposable email providers
const isDisposable = isDisposableEmail('user@tempmail.com'); // true
// Validate specific domains
const isDomainValid = validateEmailDomain('example.com', {
allowedDomains: ['example.com', 'company.com']
}); // true
import {
validatePassword,
getPasswordStrengthDescription,
getPasswordStrengthColor,
generatePasswordSuggestions,
detectPasswordPatterns,
estimatePasswordCrackTime
} from '@gen2code/core';
// Comprehensive password validation
const result = validatePassword('MySecurePassword123!', {
minLength: 8,
requireUppercase: true,
requireLowercase: true,
requireNumbers: true,
requireSymbols: true,
maxLength: 128
});
console.log(result.isValid); // true
console.log(result.strength); // 0-5 strength score
console.log(result.feedback); // Array of feedback messages
// Get human-readable strength description
const description = getPasswordStrengthDescription(result.strength); // 'Very Strong'
// Get color for UI display
const color = getPasswordStrengthColor(result.strength); // '#22c55e'
// Generate improvement suggestions
const suggestions = generatePasswordSuggestions('weak123');
// ['Add uppercase letters', 'Add symbols', 'Increase length']
// Detect common patterns
const patterns = detectPasswordPatterns('password123');
// ['common_word', 'sequential_numbers']
// Estimate crack time
const crackTime = estimatePasswordCrackTime('MySecurePassword123!');
// { seconds: 1.2e+15, display: 'centuries' }
import { validateUrl, validatePhone } from '@gen2code/core';
// URL validation with protocol checking
const isValidUrl = validateUrl('https://example.com', {
protocols: ['http', 'https'],
requireProtocol: true
}); // true
// International phone number validation
const isValidPhone = validatePhone('+1-555-123-4567', {
country: 'US',
format: 'international'
}); // true
import {
validateRequired,
validateLength,
validateRange,
validateArray,
validateObject,
validateEnum,
validateDate,
validateBoolean,
validateFields
} from '@gen2code/core';
// Individual field validation
const requiredResult = validateRequired('value'); // { isValid: true }
const lengthResult = validateLength('hello', { min: 3, max: 10 }); // { isValid: true }
const rangeResult = validateRange(25, { min: 18, max: 65 }); // { isValid: true }
// Validate multiple fields at once
const fieldsResult = validateFields({
email: { value: 'user@example.com', validators: ['required', 'email'] },
age: { value: 25, validators: ['required', { type: 'range', min: 18, max: 65 }] }
});
import {
validateSchema,
validateSchemaSafe,
createEmailSchema,
createPasswordSchema,
createUserRegistrationSchema,
createUserLoginSchema,
createTeamSchema
} from '@gen2code/core';
// Use pre-built schemas
const registrationSchema = createUserRegistrationSchema();
const result = validateSchema(registrationSchema, {
email: 'user@example.com',
password: 'SecurePassword123!',
firstName: 'John',
lastName: 'Doe'
});
if (result.isValid) {
console.log('Valid user data:', result.data);
} else {
console.log('Validation errors:', result.errors);
}
// Safe validation (doesn't throw)
const safeResult = validateSchemaSafe(registrationSchema, userData);
// Create custom schemas
const emailSchema = createEmailSchema({
allowedDomains: ['company.com'],
blockDisposable: true
});
const passwordSchema = createPasswordSchema({
minLength: 12,
requireSymbols: true
});
Utilities for formatting dates, numbers, text, and other data types.
import { formatDate, formatRelativeTime } from '@gen2code/core';
// Format dates with timezone support
const formatted = formatDate(new Date(), {
format: 'yyyy-MM-dd HH:mm:ss',
timezone: 'America/New_York',
locale: 'en-US'
}); // '2024-01-15 14:30:00'
// Relative time formatting
const relative = formatRelativeTime(new Date(Date.now() - 3600000)); // '1 hour ago'
import {
formatNumber,
formatCurrency,
formatFileSize,
formatPercentage
} from '@gen2code/core';
// Number formatting with locale support
const number = formatNumber(1234567.89, {
locale: 'en-US',
minimumFractionDigits: 2
}); // '1,234,567.89'
// Currency formatting
const price = formatCurrency(99.99, {
currency: 'USD',
locale: 'en-US'
}); // '$99.99'
// File size formatting
const size = formatFileSize(1024 * 1024 * 2.5); // '2.5 MB'
// Percentage formatting
const percent = formatPercentage(0.1234, { decimals: 2 }); // '12.34%'
import {
truncateText,
generateSlug,
capitalizeWords,
formatInitials,
formatPhoneNumber
} from '@gen2code/core';
// Text truncation with ellipsis
const truncated = truncateText('This is a very long text', {
maxLength: 20,
ellipsis: '...'
}); // 'This is a very long...'
// URL-friendly slug generation
const slug = generateSlug('Hello World! This is a Test'); // 'hello-world-this-is-a-test'
// Capitalize words
const capitalized = capitalizeWords('hello world'); // 'Hello World'
// Generate initials
const initials = formatInitials('John Doe Smith'); // 'JDS'
// Format phone numbers
const phone = formatPhoneNumber('+15551234567', {
format: 'national'
}); // '(555) 123-4567'
Secure cryptographic utilities for password hashing, data encryption, and token generation.
import {
hashPassword,
verifyPassword,
generateSalt
} from '@gen2code/core';
// Hash password with automatic salt generation
const hashedPassword = await hashPassword('userPassword123');
// Verify password against hash
const isValid = await verifyPassword('userPassword123', hashedPassword); // true
// Generate custom salt
const salt = generateSalt(16); // 16-byte salt
import {
encryptData,
decryptData,
generateEncryptionKey
} from '@gen2code/core';
// Generate encryption key
const key = generateEncryptionKey();
// Encrypt sensitive data
const encrypted = encryptData('sensitive information', key);
// Decrypt data
const decrypted = decryptData(encrypted, key); // 'sensitive information'
import {
generateToken,
generateSecureString,
generateChecksum,
verifyChecksum,
constantTimeCompare
} from '@gen2code/core';
// Generate secure tokens
const token = generateToken(32); // 32-byte random token
const secureString = generateSecureString(16); // 16-character secure string
// Generate and verify checksums
const data = 'important data';
const checksum = generateChecksum(data);
const isValid = verifyChecksum(data, checksum); // true
// Constant-time string comparison (prevents timing attacks)
const isEqual = constantTimeCompare('secret1', 'secret2'); // false
Comprehensive configuration management system with environment variable handling and validation.
import {
ConfigManager,
config,
getConfig,
getConfigValue,
updateConfig,
validateConfig,
initializeConfig
} from '@gen2code/core';
// Initialize configuration
await initializeConfig({
environment: 'development',
configPath: './config'
});
// Get configuration values
const dbConfig = getConfig('database');
const apiUrl = getConfigValue('api.baseUrl', 'http://localhost:3000');
// Update configuration
await updateConfig('features.enableNewUI', true);
// Validate configuration
const validation = validateConfig();
if (!validation.isValid) {
console.error('Configuration errors:', validation.errors);
}
import {
EnvManager,
env,
getEnvString,
getEnvNumber,
getEnvBoolean,
getEnvArray,
getEnvJson,
getEnvUrl,
loadEnvFiles,
getCurrentEnvironment,
isDevelopment,
isProduction
} from '@gen2code/core';
// Load environment files
await loadEnvFiles(['.env', '.env.local']);
// Get typed environment variables
const dbUrl = getEnvString('DATABASE_URL', 'postgresql://localhost:5432/db');
const port = getEnvNumber('PORT', 3000);
const enableFeature = getEnvBoolean('ENABLE_FEATURE', false);
const allowedOrigins = getEnvArray('ALLOWED_ORIGINS', []);
const config = getEnvJson('APP_CONFIG', {});
const apiUrl = getEnvUrl('API_URL');
// Environment detection
const currentEnv = getCurrentEnvironment(); // 'development' | 'production' | 'test' | 'staging'
const isDev = isDevelopment(); // true in development
const isProd = isProduction(); // true in production
Production-ready React hooks for common functionality.
import {
useApi,
useMutation,
useQuery,
usePagination,
useWebSocket
} from '@gen2code/core';
// Generic API hook with loading states
const { data, loading, error, execute } = useApi<User[]>({
url: '/api/users',
method: 'GET'
});
// Mutation hook for data modifications
const { mutate, loading: mutating } = useMutation<User>({
url: '/api/users',
method: 'POST',
onSuccess: (user) => console.log('User created:', user),
onError: (error) => console.error('Failed to create user:', error)
});
// Query hook with caching
const { data: users, refetch } = useQuery<User[]>({
queryKey: 'users',
url: '/api/users',
cacheTime: 5 * 60 * 1000 // 5 minutes
});
// Pagination hook
const {
data,
currentPage,
totalPages,
nextPage,
prevPage,
goToPage
} = usePagination<User>({
url: '/api/users',
pageSize: 20
});
// WebSocket hook
const {
data,
sendMessage,
readyState,
connect,
disconnect
} = useWebSocket('ws://localhost:8080', {
onMessage: (message) => console.log('Received:', message),
reconnectAttempts: 3
});
import {
useAuth,
useSession,
usePermissions,
useAuthRedirect,
useAuthForm
} from '@gen2code/core';
// Authentication state management
const {
user,
isAuthenticated,
login,
logout,
register,
loading
} = useAuth();
// Session management
const {
session,
refreshSession,
clearSession,
isExpired
} = useSession();
// Permission checking
const {
hasPermission,
hasRole,
canAccess,
permissions
} = usePermissions();
// Automatic redirect for protected routes
useAuthRedirect({
redirectTo: '/login',
requireAuth: true,
requiredRoles: ['admin']
});
// Form handling for auth forms
const {
formData,
errors,
isValid,
handleChange,
handleSubmit,
reset
} = useAuthForm({
initialData: { email: '', password: '' },
validationSchema: loginSchema,
onSubmit: async (data) => await login(data)
});
import {
useLocalStorage,
useDebounce,
useTheme,
useMediaQuery,
useClipboard
} from '@gen2code/core';
// Local storage with TypeScript support
const [user, setUser] = useLocalStorage<User>('user', null);
// Debounce values and callbacks
const debouncedValue = useDebounce(searchTerm, 500);
const debouncedCallback = useDebounceCallback(
(query: string) => searchUsers(query),
300
);
// Theme management
const {
theme,
setTheme,
resolvedTheme,
systemTheme
} = useTheme();
// Media queries and responsive design
const isMobile = useMediaQuery('(max-width: 768px)');
const { isMobile: mobile, isTablet, isDesktop } = useBreakpoints();
// Clipboard operations
const {
copy,
copied,
copyFormatted,
isSupported
} = useClipboard({
timeout: 2000
});
// Usage
await copy('Text to copy');
console.log(copied); // true for 2 seconds
Comprehensive API utilities with error handling, caching, and retry logic.
import {
createHttpClient,
HttpApiError,
NetworkError,
handleApiError
} from '@gen2code/core';
// Create configured HTTP client
const client = createHttpClient({
baseURL: 'https://api.example.com',
timeout: 10000,
retries: 3,
headers: {
'Authorization': 'Bearer token'
}
});
// Make requests with automatic error handling
try {
const response = await client.get<User[]>('/users');
console.log(response.data);
} catch (error) {
if (error instanceof HttpApiError) {
console.error('API Error:', error.message, error.statusCode);
} else if (error instanceof NetworkError) {
console.error('Network Error:', error.message);
}
}
import {
createCache,
createRetryConfig,
isRetryableError
} from '@gen2code/core';
// Create cache instance
const cache = createCache({
maxSize: 100,
ttl: 5 * 60 * 1000 // 5 minutes
});
// Cache API responses
cache.set('users', usersData);
const cachedUsers = cache.get('users');
// Retry configuration
const retryConfig = createRetryConfig({
attempts: 3,
delay: 1000,
backoff: 'exponential',
retryCondition: (error) => isRetryableError(error)
});
Comprehensive error handling system with logging, reporting, and user-friendly messages.
import {
AppError,
ValidationError,
AuthenticationError,
AuthorizationError,
HttpApiError
} from '@gen2code/core';
// Create custom application errors
throw new AppError('Something went wrong', 'APP_ERROR', {
userId: '123',
action: 'updateProfile'
});
// Validation errors with field details
throw new ValidationError('Invalid input', {
email: ['Invalid email format'],
password: ['Password too weak']
});
// Authentication errors
throw new AuthenticationError('Invalid credentials', 'INVALID_CREDENTIALS');
// Authorization errors
throw new AuthorizationError('Insufficient permissions', 'INSUFFICIENT_PERMISSIONS');
import {
ErrorLogger,
logError,
logWarn,
logInfo,
reportError,
createUserFriendlyError
} from '@gen2code/core';
// Log errors with context
logError('Database connection failed', {
database: 'users',
host: 'localhost',
port: 5432
});
// Log warnings and info
logWarn('API rate limit approaching');
logInfo('User logged in successfully');
// Report errors to external service
await reportError(error, {
userId: '123',
userAgent: navigator.userAgent,
url: window.location.href
});
// Create user-friendly error messages
const friendlyError = createUserFriendlyError(error);
console.log(friendlyError.message); // User-friendly message
console.log(friendlyError.actions); // Suggested actions
This package is built with TypeScript and provides comprehensive type definitions:
// Example of generic type support
import type { ApiResponse, PaginatedResponse } from '@gen2code/core';
interface CustomData {
id: string;
name: string;
}
// Fully typed API response
const response: ApiResponse<CustomData[]> = await fetchData();
// Fully typed paginated response
const paginatedResponse: PaginatedResponse<CustomData> = await fetchPaginatedData();
The package includes comprehensive test coverage:
# Run all tests
pnpm test
# Run tests with coverage
pnpm test --coverage
# Run specific test suite
pnpm test validation
# Watch mode for development
pnpm test --watch
This package is part of the Gen2Code framework. Please refer to the main repository for contribution guidelines.
MIT License - see the LICENSE file for details.
@gen2code/api-framework - API documentation and standards@gen2code/access-control - Authentication and authorization@gen2code/user-management - User profiles and settings@gen2code/team-management - Multi-tenant organization managementBuilt with ❤️ by the Gen2Code team
FAQs
Core utilities, types, and configurations for the Gen2Code framework
The npm package @gen2code/core receives a total of 0 weekly downloads. As such, @gen2code/core popularity was classified as not popular.
We found that @gen2code/core demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.

Security News
Node.js has paused its bug bounty program after funding ended, removing payouts for vulnerability reports but keeping its security process unchanged.