Utility functions for Morphsync applications including encoding, hashing, OTP generation, date formatting, and serialization.
- 🔐 SHA-1 hashing for passwords and tokens
- 🔢 Cryptographically secure OTP generation
- 📝 Base64 encoding and decoding
- 📅 Date formatting and manipulation
- 🧹 HTML entity decoding and text normalization
- 📏 String padding utilities
- 📦 Safe error serialization for logging
- ⚡ Zero configuration required
- 🎯 TypeScript-friendly
npm install @morphsync/utilsconst { sha1, generateOtp, base64Encode, date, addDate, serializeObject } = require('@morphsync/utils');
// Hash password
const hash = sha1('myPassword123');
// Generate OTP
const otp = generateOtp(6);
// Encode data
const encoded = base64Encode('Hello World');
// Format date
const formatted = date('YYYY-MM-DD HH:mm:ss');
// Add days to date
const tomorrow = addDate(null, 1, 'days');
// Serialize error
try {
throw new Error('Something went wrong');
} catch (error) {
const serialized = serializeObject(error);
console.log(JSON.stringify(serialized, null, 2));
}const { sha1 } = require('@morphsync/utils');
// Hash password
const hashedPassword = sha1('userPassword123');
// Verify password
if (sha1(inputPassword) === storedHash) {
console.log('Password correct');
}
// Generate verification token
const token = sha1(email + timestamp + secret);const { generateOtp } = require('@morphsync/utils');
// Generate 6-digit OTP (default)
const otp = generateOtp();
// Generate custom length OTP
const shortOtp = generateOtp(4);
const longOtp = generateOtp(8);
// Use in authentication
const userOtp = generateOtp(6);
await sendOtpEmail(userEmail, userOtp);const { base64Encode, base64Decode } = require('@morphsync/utils');
// Encode string
const encoded = base64Encode('Hello World');
// Decode string
const decoded = base64Decode('SGVsbG8gV29ybGQ=');
// Encode JSON
const token = base64Encode(JSON.stringify({ userId: 123 }));
// Decode JSON
const data = JSON.parse(base64Decode(token));const { convertToPlainText } = require('@morphsync/utils');
// Remove markdown formatting
const plain = convertToPlainText('*Hello* _world_');
// Decode HTML entities
const decoded = convertToPlainText('Hello & goodbye');
// Combined example
const text = convertToPlainText('*Bold* & _italic_');const { stringPad } = require('@morphsync/utils');
// Pad with zeros
const id = stringPad(1, 6, '0');
// Pad with custom character
const masked = stringPad(42, 8, '*');
// Generate formatted IDs
const orderId = `ORD-${stringPad(123, 8, '0')}`;
const invoiceNo = `INV-${stringPad(456, 6, '0')}`;const { date } = require('@morphsync/utils');
// Format current date
const now = date('YYYY-MM-DD HH:mm:ss');
// Format specific date
const formatted = date('MMMM DD, YYYY', '2023-11-22');
// Custom formats
const dateOnly = date('YYYY-MM-DD');
const timeOnly = date('HH:mm:ss');
const custom = date('DD/MM/YYYY hh:mm A');const { addDate, date } = require('@morphsync/utils');
// Add days
const tomorrow = addDate(null, 1, 'days');
const nextWeek = addDate(null, 7, 'days');
// Add months
const nextMonth = addDate('2023-11-22', 1, 'months');
// Subtract time
const yesterday = addDate(null, -1, 'days');
const lastYear = addDate(null, -1, 'years');
// Add hours/minutes
const nextHour = addDate(null, 1, 'hours');
const in30Minutes = addDate(null, 30, 'minutes');
// Combine with formatting
const expiryDate = date('YYYY-MM-DD', addDate(null, 30, 'days'));const { serializeObject } = require('@morphsync/utils');
// Serialize Error object
try {
throw new Error('Something went wrong');
} catch (error) {
const serialized = serializeObject(error);
console.log(JSON.stringify(serialized, null, 2));
}
// Serialize custom error
const customError = { message: 'Custom error', code: 500 };
const serialized = serializeObject(customError);
// Serialize primitive
const stringError = serializeObject('Simple error');Generates a SHA-1 hash for the given data.
Parameters:
data(string): The data to hash
Returns: SHA-1 hash in hexadecimal format (40 characters)
Generates a cryptographically secure OTP consisting of digits only.
Parameters:
length(number, optional): The length of the OTP (default: 6)
Returns: OTP as a string of digits
Encodes a string to Base64 format.
Parameters:
data(string): The string to encode
Returns: Base64 encoded string
Decodes a Base64 encoded string.
Parameters:
data(string): The Base64 encoded string to decode
Returns: Decoded UTF-8 string
Converts formatted text (markdown and HTML entities) into plain text.
Parameters:
formattedText(string): Text containing markdown and HTML entities
Returns: Plain text without formatting
Pads a number or string to a specified length with a given character.
Parameters:
num(number|string): The number or string to padlength(number): The desired total lengthchar(string): The character to use for padding
Returns: Padded string
Safely converts any error or object into a JSON-serializable object.
Parameters:
error(*): Any error or object to serialize
Returns: JSON-serializable object
Formats a date into a specified string format.
Parameters:
format(string, optional): Desired output format (default: 'YYYY-MM-DD HH:mm:ss')dateInput(string|Date, optional): Date to format (default: current date)
Returns: Formatted date string
Format tokens:
YYYY- 4-digit yearYY- 2-digit yearMMMM- Full month nameMMM- Short month nameMM- 2-digit monthM- Month numberDD- 2-digit dayHH- 24-hour formathh- 12-hour formatmm- Minutesss- SecondsA- AM/PM
Adds or subtracts time units to/from a date.
Parameters:
dateInput(string|Date, optional): Date to modify (default: current date)value(number): Amount to add (positive) or subtract (negative)unit(string, optional): Time unit (default: 'days')
Units: 'years', 'months', 'days', 'hours', 'minutes', 'seconds'
Returns: Modified Date object
const { sha1, generateOtp } = require('@morphsync/utils');
class AuthService {
async register(username, password) {
const hashedPassword = sha1(password);
await db.insert({ username, password: hashedPassword });
}
async sendLoginOtp(userId, password) {
const otp = generateOtp(6);
const loginKey = sha1(password + otp + Date.now());
await db.insert({
userId,
otp,
loginKey,
expiresAt: Date.now() + 300000
});
await sendOtpEmail(userEmail, otp);
return loginKey;
}
async verifyOtp(userId, otp, loginKey) {
const record = await db.findOne({ userId, otp, loginKey });
return record && record.expiresAt > Date.now();
}
}const { serializeObject } = require('@morphsync/utils');
const Logger = require('@morphsync/logger');
class ErrorHandler {
static async logError(error, context) {
const logger = new Logger();
const serialized = serializeObject(error);
const logData = {
...serialized,
context,
timestamp: new Date().toISOString()
};
logger.write(JSON.stringify(logData, null, 2), 'errors/app');
}
}
// Usage in Express
app.use((error, req, res, next) => {
ErrorHandler.logError(error, {
method: req.method,
url: req.url,
userId: req.user?.id
});
res.status(500).json({ message: 'Internal server error' });
});const { base64Encode, base64Decode, stringPad, convertToPlainText } = require('@morphsync/utils');
// Encode user data for URL
const userData = { userId: 123, role: 'admin' };
const encodedData = base64Encode(JSON.stringify(userData));
const url = `${baseUrl}/dashboard?data=${encodedData}`;
// Decode and parse
const decodedData = base64Decode(encodedData);
const user = JSON.parse(decodedData);
// Process email content for SMS
const emailBody = '*Important* notification & update';
const plainText = convertToPlainText(emailBody);
await sendSms(phoneNumber, plainText);
// Generate formatted IDs
const orderId = `ORD-${stringPad(123, 8, '0')}`;
const invoiceNo = `INV-${stringPad(456, 6, '0')}`;const { sha1, serializeObject } = require('@morphsync/utils');
const Logger = require('@morphsync/logger');
class UserController {
static async login(req, res) {
const logger = new Logger();
try {
const { username, password } = req.body;
const hashedPassword = sha1(password);
const user = await db.findOne({ username, password: hashedPassword });
if (!user) {
return res.status(401).json({ message: 'Invalid credentials' });
}
logger.write(`User ${username} logged in successfully`, 'auth/info');
res.json({ success: true, user });
} catch (error) {
const serialized = serializeObject(error);
logger.write(JSON.stringify(serialized, null, 2), 'auth/error');
res.status(500).json({ message: 'Login failed' });
}
}
}All functions handle errors gracefully:
try {
const hash = sha1('data');
const otp = generateOtp(6);
const encoded = base64Encode('text');
} catch (error) {
console.error('Operation failed:', error.message);
}- html-entities - HTML entity encoding/decoding
ISC
Morphsync
- @morphsync/logger - Logger utility with automatic file organization
- @morphsync/http-request - HTTP request utility
- @morphsync/mysql-db - MySQL query builder
For issues and questions, please visit the GitHub repository.