UNPKG

redai-automation-web-sdk

Version:

TypeScript SDK for RedAI Automation Web API - Zalo Personal automation, messaging, advanced sticker search, and bulk operations. 100% compatible with automation-web backend. v1.8.1: Updated GroupInfo interface to match backend controller with complete gro

312 lines 9.74 kB
"use strict"; /** * Formatting utility functions */ Object.defineProperty(exports, "__esModule", { value: true }); exports.FormatUtils = void 0; /** * Formatting utilities class */ class FormatUtils { /** * Format timestamp to readable string */ static formatTimestamp(timestamp) { const date = new Date(typeof timestamp === 'string' ? parseInt(timestamp) : timestamp); return date.toLocaleString(); } /** * Format duration in milliseconds to human readable format */ static formatDuration(ms) { if (ms < 1000) { return `${ms}ms`; } const seconds = Math.floor(ms / 1000); if (seconds < 60) { return `${seconds}s`; } const minutes = Math.floor(seconds / 60); const remainingSeconds = seconds % 60; if (minutes < 60) { return remainingSeconds > 0 ? `${minutes}m ${remainingSeconds}s` : `${minutes}m`; } const hours = Math.floor(minutes / 60); const remainingMinutes = minutes % 60; return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`; } /** * Format file size in bytes to human readable format */ static formatFileSize(bytes) { const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; if (bytes === 0) return '0 Bytes'; const i = Math.floor(Math.log(bytes) / Math.log(1024)); const size = bytes / Math.pow(1024, i); return `${Math.round(size * 100) / 100} ${sizes[i]}`; } /** * Format phone number for display */ static formatPhoneNumber(phoneNumber) { // Remove all non-digit characters const cleaned = phoneNumber.replace(/\D/g, ''); // Vietnamese phone number formatting if (cleaned.startsWith('84')) { // International format const number = cleaned.substring(2); if (number.length === 9) { return `+84 ${number.substring(0, 3)} ${number.substring(3, 6)} ${number.substring(6)}`; } } else if (cleaned.startsWith('0')) { // Domestic format if (cleaned.length === 10) { return `${cleaned.substring(0, 4)} ${cleaned.substring(4, 7)} ${cleaned.substring(7)}`; } } return phoneNumber; // Return original if can't format } /** * Truncate text with ellipsis */ static truncateText(text, maxLength) { if (text.length <= maxLength) { return text; } return text.substring(0, maxLength - 3) + '...'; } /** * Capitalize first letter of each word */ static capitalizeWords(text) { return text.replace(/\b\w/g, char => char.toUpperCase()); } /** * Convert camelCase to kebab-case */ static camelToKebab(text) { return text.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$1-$2').toLowerCase(); } /** * Convert kebab-case to camelCase */ static kebabToCamel(text) { return text.replace(/-([a-z])/g, (_, char) => char.toUpperCase()); } /** * Format percentage */ static formatPercentage(value, decimals = 1) { return `${(value * 100).toFixed(decimals)}%`; } /** * Format number with thousand separators */ static formatNumber(num) { return num.toLocaleString(); } /** * Create styled text with formatting */ static createStyledText(text, styles) { const styleMap = { bold: 'font-weight:bold', italic: 'font-style:italic', underline: 'text-decoration:underline', strikethrough: 'text-decoration:line-through', }; const formattedStyles = styles.map(style => ({ start: style.start, len: style.length, st: styleMap[style.style], })); return { content: text, styles: formattedStyles, }; } /** * Create mentions in text */ static createMentions(text, mentions) { const formattedMentions = mentions.map(mention => ({ uid: mention.userId, start: mention.start, len: mention.displayName.length, })); return { content: text, mentions: formattedMentions, }; } /** * Extract mentions from text (e.g., @username) */ static extractMentions(text) { const mentionRegex = /@(\w+)/g; const mentions = []; let match; while ((match = mentionRegex.exec(text)) !== null) { mentions.push({ username: match[1], start: match.index, length: match[0].length, }); } return mentions; } /** * Extract hashtags from text */ static extractHashtags(text) { const hashtagRegex = /#(\w+)/g; const hashtags = []; let match; while ((match = hashtagRegex.exec(text)) !== null) { hashtags.push({ hashtag: match[1], start: match.index, length: match[0].length, }); } return hashtags; } /** * Extract URLs from text */ static extractUrls(text) { const urlRegex = /(https?:\/\/[^\s]+)/g; const urls = []; let match; while ((match = urlRegex.exec(text)) !== null) { urls.push({ url: match[1], start: match.index, length: match[0].length, }); } return urls; } /** * Clean text by removing special characters */ static cleanText(text) { return text .replace(/[^\w\s\u00C0-\u024F\u1E00-\u1EFF]/g, '') // Keep alphanumeric, spaces, and Vietnamese characters .replace(/\s+/g, ' ') // Normalize whitespace .trim(); } /** * Generate random string */ static generateRandomString(length) { const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let result = ''; for (let i = 0; i < length; i++) { result += chars.charAt(Math.floor(Math.random() * chars.length)); } return result; } /** * Generate UUID v4 */ static generateUuid() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { const r = Math.random() * 16 | 0; const v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } /** * Escape HTML characters */ static escapeHtml(text) { const htmlEscapes = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '/': '&#x2F;', }; return text.replace(/[&<>"'/]/g, (char) => htmlEscapes[char]); } /** * Unescape HTML characters */ static unescapeHtml(text) { const htmlUnescapes = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#x27;': "'", '&#x2F;': '/', }; return text.replace(/&(?:amp|lt|gt|quot|#x27|#x2F);/g, (entity) => htmlUnescapes[entity]); } /** * Convert text to slug format */ static toSlug(text) { return text .toLowerCase() .normalize('NFD') .replace(/[\u0300-\u036f]/g, '') // Remove diacritics .replace(/[^a-z0-9\s-]/g, '') // Remove special characters .replace(/\s+/g, '-') // Replace spaces with hyphens .replace(/-+/g, '-') // Replace multiple hyphens with single .trim() .replace(/^-+|-+$/g, ''); // Remove leading/trailing hyphens } /** * Format relative time (e.g., "2 hours ago") */ static formatRelativeTime(timestamp) { const now = Date.now(); const time = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp; const diff = now - time; const seconds = Math.floor(diff / 1000); const minutes = Math.floor(seconds / 60); const hours = Math.floor(minutes / 60); const days = Math.floor(hours / 24); const weeks = Math.floor(days / 7); const months = Math.floor(days / 30); const years = Math.floor(days / 365); if (seconds < 60) return 'just now'; if (minutes < 60) return `${minutes} minute${minutes > 1 ? 's' : ''} ago`; if (hours < 24) return `${hours} hour${hours > 1 ? 's' : ''} ago`; if (days < 7) return `${days} day${days > 1 ? 's' : ''} ago`; if (weeks < 4) return `${weeks} week${weeks > 1 ? 's' : ''} ago`; if (months < 12) return `${months} month${months > 1 ? 's' : ''} ago`; return `${years} year${years > 1 ? 's' : ''} ago`; } /** * Mask sensitive information */ static maskSensitiveInfo(text, type, customPattern) { switch (type) { case 'phone': return text.replace(/(\d{3})\d{4}(\d{3})/, '$1****$2'); case 'email': return text.replace(/(.{2}).*@(.*)/, '$1***@$2'); case 'custom': if (customPattern) { return text.replace(customPattern, '***'); } return text; default: return text; } } } exports.FormatUtils = FormatUtils; //# sourceMappingURL=format.utils.js.map