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.0: Added SessionProxyService for managing proxy assignments to sessions with
320 lines • 11.4 kB
JavaScript
;
/**
* Validation utility functions
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValidationUtils = exports.ValidationError = void 0;
const common_types_1 = require("../types/common.types");
/**
* Validation error class
*/
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.field = field;
this.name = 'ValidationError';
}
}
exports.ValidationError = ValidationError;
/**
* Validation utility class
*/
class ValidationUtils {
/**
* Validate session ID format
*/
static validateSessionId(sessionId) {
if (!sessionId || typeof sessionId !== 'string') {
throw new ValidationError('Session ID is required and must be a string', 'sessionId');
}
if (sessionId.trim().length === 0) {
throw new ValidationError('Session ID cannot be empty', 'sessionId');
}
// Check if it matches expected format (session-uuid)
const sessionIdPattern = /^session-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
if (!sessionIdPattern.test(sessionId)) {
throw new ValidationError('Session ID format is invalid', 'sessionId');
}
}
/**
* Validate user UUID format
*/
static validateUserUuid(userUuid) {
if (!userUuid || typeof userUuid !== 'string') {
throw new ValidationError('User UUID is required and must be a string', 'userUuid');
}
const uuidPattern = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
if (!uuidPattern.test(userUuid)) {
throw new ValidationError('User UUID format is invalid', 'userUuid');
}
}
/**
* Validate thread ID
*/
static validateThreadId(threadId) {
if (!threadId || typeof threadId !== 'string') {
throw new ValidationError('Thread ID is required and must be a string', 'threadId');
}
if (threadId.trim().length === 0) {
throw new ValidationError('Thread ID cannot be empty', 'threadId');
}
}
/**
* Validate thread type
*/
static validateThreadType(threadType) {
if (!Object.values(common_types_1.ThreadType).includes(threadType)) {
throw new ValidationError(`Thread type must be one of: ${Object.values(common_types_1.ThreadType).join(', ')}`, 'threadType');
}
}
/**
* Validate message content
*/
static validateMessageContent(content) {
if (!content || typeof content !== 'string') {
throw new ValidationError('Message content is required and must be a string', 'content');
}
if (content.trim().length === 0) {
throw new ValidationError('Message content cannot be empty', 'content');
}
// Check maximum length (Zalo limit is typically 2000 characters)
if (content.length > 2000) {
throw new ValidationError('Message content exceeds maximum length of 2000 characters', 'content');
}
}
/**
* Validate URL format
*/
static validateUrl(url, fieldName = 'url') {
if (!url || typeof url !== 'string') {
throw new ValidationError(`${fieldName} is required and must be a string`, fieldName);
}
try {
new URL(url);
}
catch {
throw new ValidationError(`${fieldName} must be a valid URL`, fieldName);
}
}
/**
* Validate urgency level
*/
static validateUrgency(urgency) {
if (!Object.values(common_types_1.Urgency).includes(urgency)) {
throw new ValidationError(`Urgency must be one of: ${Object.values(common_types_1.Urgency).join(', ')}`, 'urgency');
}
}
/**
* Validate phone number format (Vietnamese)
*/
static validatePhoneNumber(phoneNumber) {
if (!phoneNumber || typeof phoneNumber !== 'string') {
throw new ValidationError('Phone number is required and must be a string', 'phoneNumber');
}
// Vietnamese phone number patterns
const patterns = [
/^(\+84|84|0)(3[2-9]|5[6|8|9]|7[0|6-9]|8[1-6|8|9]|9[0-4|6-9])[0-9]{7}$/, // Mobile
/^(\+84|84|0)(2[0-9])[0-9]{8}$/, // Landline
];
const isValid = patterns.some(pattern => pattern.test(phoneNumber.replace(/\s/g, '')));
if (!isValid) {
throw new ValidationError('Phone number format is invalid', 'phoneNumber');
}
}
/**
* Validate email format
*/
static validateEmail(email) {
if (!email || typeof email !== 'string') {
throw new ValidationError('Email is required and must be a string', 'email');
}
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
throw new ValidationError('Email format is invalid', 'email');
}
}
/**
* Validate array of IDs
*/
static validateIdArray(ids, fieldName, minLength = 1) {
if (!Array.isArray(ids)) {
throw new ValidationError(`${fieldName} must be an array`, fieldName);
}
if (ids.length < minLength) {
throw new ValidationError(`${fieldName} must contain at least ${minLength} item(s)`, fieldName);
}
ids.forEach((id, index) => {
if (!id || typeof id !== 'string' || id.trim().length === 0) {
throw new ValidationError(`${fieldName}[${index}] must be a non-empty string`, fieldName);
}
});
}
/**
* Validate pagination parameters
*/
static validatePagination(page, limit) {
if (page !== undefined) {
if (!Number.isInteger(page) || page < 1) {
throw new ValidationError('Page must be a positive integer', 'page');
}
}
if (limit !== undefined) {
if (!Number.isInteger(limit) || limit < 1 || limit > 100) {
throw new ValidationError('Limit must be an integer between 1 and 100', 'limit');
}
}
}
/**
* Validate file size
*/
static validateFileSize(size, maxSize = 50 * 1024 * 1024) {
// 50MB default
if (!Number.isInteger(size) || size < 0) {
throw new ValidationError('File size must be a non-negative integer', 'fileSize');
}
if (size > maxSize) {
throw new ValidationError(`File size exceeds maximum allowed size of ${this.formatFileSize(maxSize)}`, 'fileSize');
}
}
/**
* Validate timeout value
*/
static validateTimeout(timeout) {
if (!Number.isInteger(timeout) || timeout < 1000 || timeout > 300000) {
// 1s to 5min
throw new ValidationError('Timeout must be an integer between 1000 and 300000 milliseconds', 'timeout');
}
}
/**
* Validate delay value
*/
static validateDelay(delay) {
if (!Number.isInteger(delay) || delay < 0 || delay > 60000) {
// 0 to 1 minute
throw new ValidationError('Delay must be an integer between 0 and 60000 milliseconds', 'delay');
}
}
/**
* Validate batch size
*/
static validateBatchSize(batchSize) {
if (!Number.isInteger(batchSize) || batchSize < 1 || batchSize > 100) {
throw new ValidationError('Batch size must be an integer between 1 and 100', 'batchSize');
}
}
/**
* Validate retry count
*/
static validateRetryCount(retryCount) {
if (!Number.isInteger(retryCount) || retryCount < 0 || retryCount > 10) {
throw new ValidationError('Retry count must be an integer between 0 and 10', 'retryCount');
}
}
/**
* Validate SDK configuration
*/
static validateConfig(config) {
// Validate base URL
this.validateUrl(config.baseUrl, 'baseUrl');
// Validate optional numeric fields
if (config.timeout !== undefined) {
this.validateTimeout(config.timeout);
}
if (config.retryCount !== undefined) {
this.validateRetryCount(config.retryCount);
}
if (config.retryDelay !== undefined) {
this.validateDelay(config.retryDelay);
}
// Validate user agent
if (config.userAgent !== undefined && typeof config.userAgent !== 'string') {
throw new ValidationError('User agent must be a string', 'userAgent');
}
// Validate logging flag
if (config.logging !== undefined && typeof config.logging !== 'boolean') {
throw new ValidationError('Logging must be a boolean', 'logging');
}
}
/**
* Validate date string format
*/
static validateDateString(dateString, fieldName = 'date') {
if (!dateString || typeof dateString !== 'string') {
throw new ValidationError(`${fieldName} is required and must be a string`, fieldName);
}
const date = new Date(dateString);
if (isNaN(date.getTime())) {
throw new ValidationError(`${fieldName} must be a valid date string`, fieldName);
}
}
/**
* Validate date range
*/
static validateDateRange(startDate, endDate) {
this.validateDateString(startDate, 'startDate');
this.validateDateString(endDate, 'endDate');
const start = new Date(startDate);
const end = new Date(endDate);
if (start >= end) {
throw new ValidationError('Start date must be before end date');
}
}
/**
* Format file size for error messages
*/
static formatFileSize(bytes) {
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
if (bytes === 0)
return '0 Bytes';
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return Math.round((bytes / Math.pow(1024, i)) * 100) / 100 + ' ' + sizes[i];
}
/**
* Sanitize string input
*/
static sanitizeString(input) {
if (typeof input !== 'string') {
return '';
}
return input
.trim()
.replace(/[\x00-\x1F\x7F]/g, '') // Remove control characters
.replace(/\s+/g, ' '); // Normalize whitespace
}
/**
* Validate and sanitize message content
*/
static sanitizeMessageContent(content) {
const sanitized = this.sanitizeString(content);
this.validateMessageContent(sanitized);
return sanitized;
}
/**
* Check if value is empty
*/
static isEmpty(value) {
if (value === null || value === undefined) {
return true;
}
if (typeof value === 'string') {
return value.trim().length === 0;
}
if (Array.isArray(value)) {
return value.length === 0;
}
if (typeof value === 'object') {
return Object.keys(value).length === 0;
}
return false;
}
/**
* Validate required field
*/
static validateRequired(value, fieldName) {
if (this.isEmpty(value)) {
throw new ValidationError(`${fieldName} is required`, fieldName);
}
}
}
exports.ValidationUtils = ValidationUtils;
//# sourceMappingURL=validation.utils.js.map