UNPKG

@restnfeel/agentc-starter-kit

Version:

한국어 기업용 CMS 모듈 - Task Master AI와 함께 빠르게 웹사이트를 구현할 수 있는 재사용 가능한 컴포넌트 시스템

124 lines (106 loc) 2.98 kB
/** * @fileoverview Utility functions for the RAG chatbot system * @module utils * * This module provides common utility functions used across the * RAG chatbot system. */ import type { ChatbotError } from "../core/contexts/ChatbotContext"; /** * Creates a standardized ChatbotError object */ export const createChatbotError = ( code: string, message: string, details?: any ): ChatbotError => ({ code, message, details, timestamp: new Date(), }); /** * Formats a file size in bytes to a human-readable string */ export const formatFileSize = (bytes: number): string => { if (bytes === 0) return "0 B"; const k = 1024; const sizes = ["B", "KB", "MB", "GB"]; const i = Math.floor(Math.log(bytes) / Math.log(k)); return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`; }; /** * Generates a unique ID for chatbot entities */ export const generateId = (prefix: string = "cb"): string => { return `${prefix}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; }; /** * Debounces a function call */ export const debounce = <T extends (...args: any[]) => any>( func: T, wait: number ): ((...args: Parameters<T>) => void) => { let timeout: NodeJS.Timeout; return (...args: Parameters<T>) => { clearTimeout(timeout); timeout = setTimeout(() => func(...args), wait); }; }; /** * Throttles a function call */ export const throttle = <T extends (...args: any[]) => any>( func: T, limit: number ): ((...args: Parameters<T>) => void) => { let inThrottle: boolean; return (...args: Parameters<T>) => { if (!inThrottle) { func(...args); inThrottle = true; setTimeout(() => (inThrottle = false), limit); } }; }; /** * Validates an email address */ export const isValidEmail = (email: string): boolean => { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailRegex.test(email); }; /** * Truncates text to a specified length */ export const truncateText = (text: string, maxLength: number): string => { if (text.length <= maxLength) return text; return text.substring(0, maxLength - 3) + "..."; }; /** * Safely parses JSON with error handling */ export const safeJsonParse = <T = any>(jsonString: string): T | null => { try { return JSON.parse(jsonString) as T; } catch { return null; } }; /** * Formats a timestamp to a relative time string */ export const formatRelativeTime = (timestamp: Date): string => { const now = new Date(); const diffMs = now.getTime() - timestamp.getTime(); const diffSeconds = Math.floor(diffMs / 1000); const diffMinutes = Math.floor(diffSeconds / 60); const diffHours = Math.floor(diffMinutes / 60); const diffDays = Math.floor(diffHours / 24); if (diffSeconds < 60) return "just now"; if (diffMinutes < 60) return `${diffMinutes}m ago`; if (diffHours < 24) return `${diffHours}h ago`; if (diffDays < 7) return `${diffDays}d ago`; return timestamp.toLocaleDateString(); };