@casoon/auditmysite
Version:
Professional website analysis suite with robust accessibility testing, Core Web Vitals performance monitoring, SEO analysis, and content optimization insights. Features isolated browser contexts, retry mechanisms, and comprehensive API endpoints for profe
183 lines • 5.98 kB
JavaScript
;
/**
* 🏗️ Base Types for Modular Audit Architecture
*
* Common interfaces, types, and utilities used across all analysis groups.
* Provides consistent scoring, grading, and recommendation patterns.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.PerformanceTimer = exports.DEFAULT_CONFIG = void 0;
exports.calculateGrade = calculateGrade;
exports.calculateCertificateLevel = calculateCertificateLevel;
exports.calculateWeightedScore = calculateWeightedScore;
exports.calculateOverallScore = calculateOverallScore;
exports.validateScore = validateScore;
exports.createBaseResult = createBaseResult;
exports.withTiming = withTiming;
exports.isValidUrl = isValidUrl;
exports.extractDomain = extractDomain;
exports.isSecureUrl = isSecureUrl;
// =============================================================================
// SCORING UTILITIES
// =============================================================================
/** Standard grade calculation based on score */
function calculateGrade(score) {
if (score >= 90)
return 'A';
if (score >= 80)
return 'B';
if (score >= 70)
return 'C';
if (score >= 60)
return 'D';
return 'F';
}
/** Standard certificate level calculation based on score */
function calculateCertificateLevel(score) {
if (score >= 95)
return 'PLATINUM';
if (score >= 85)
return 'GOLD';
if (score >= 70)
return 'SILVER';
if (score >= 60)
return 'BRONZE';
return 'NEEDS_IMPROVEMENT';
}
/** Calculate weighted average score */
function calculateWeightedScore(scores) {
const totalWeight = scores.reduce((sum, item) => sum + item.weight, 0);
if (totalWeight === 0)
return 0;
const weightedSum = scores.reduce((sum, item) => sum + (item.score * item.weight), 0);
return Math.round(weightedSum / totalWeight);
}
/** Calculate overall score from multiple category scores */
function calculateOverallScore(categoryScores, weights) {
const categories = Object.keys(categoryScores);
if (categories.length === 0)
return 0;
if (!weights) {
// Equal weighting
const totalScore = categories.reduce((sum, category) => sum + categoryScores[category], 0);
return Math.round(totalScore / categories.length);
}
// Weighted scoring
const weightedScores = categories.map(category => ({
score: categoryScores[category],
weight: weights[category] || 1
}));
return calculateWeightedScore(weightedScores);
}
// =============================================================================
// VALIDATION UTILITIES
// =============================================================================
/** Validate that a score is within the valid range */
function validateScore(score, context) {
if (typeof score !== 'number' || isNaN(score)) {
console.warn(`Invalid score in ${context || 'unknown context'}: ${score}. Using 0.`);
return 0;
}
if (score < 0) {
console.warn(`Score below 0 in ${context || 'unknown context'}: ${score}. Using 0.`);
return 0;
}
if (score > 100) {
console.warn(`Score above 100 in ${context || 'unknown context'}: ${score}. Using 100.`);
return 100;
}
return Math.round(score);
}
/** Create a base analysis result with common fields */
function createBaseResult(overallScore, partialResult) {
const validScore = validateScore(overallScore);
const baseResult = {
overallScore: validScore,
grade: calculateGrade(validScore),
certificate: calculateCertificateLevel(validScore),
analyzedAt: new Date().toISOString(),
duration: 0, // Should be set by analyzer
status: 'completed'
};
return { ...baseResult, ...partialResult };
}
/** Default configuration values */
exports.DEFAULT_CONFIG = {
verbose: false,
maxAnalysisTime: 300000, // 5 minutes
retries: 2,
userAgent: 'AuditMySite/2.0 (Web Audit Tool)',
viewport: {
width: 1920,
height: 1080
}
};
// =============================================================================
// TIMING UTILITIES
// =============================================================================
/** Simple performance timer */
class PerformanceTimer {
constructor() {
this.startTime = performance.now();
}
/** Get elapsed time in milliseconds */
getElapsed() {
return Math.round(performance.now() - this.startTime);
}
/** Reset the timer */
reset() {
this.startTime = performance.now();
}
}
exports.PerformanceTimer = PerformanceTimer;
/** Create a timer-enabled wrapper for async operations */
async function withTiming(operation, context) {
const timer = new PerformanceTimer();
try {
const result = await operation();
const duration = timer.getElapsed();
if (context) {
console.log(`⏱️ ${context}: ${duration}ms`);
}
return { result, duration };
}
catch (error) {
const duration = timer.getElapsed();
if (context) {
console.error(`❌ ${context} failed after ${duration}ms:`, error);
}
throw error;
}
}
// =============================================================================
// URL UTILITIES
// =============================================================================
/** Validate URL format */
function isValidUrl(urlString) {
try {
new URL(urlString);
return true;
}
catch {
return false;
}
}
/** Extract domain from URL */
function extractDomain(url) {
try {
return new URL(url).hostname;
}
catch {
return 'unknown';
}
}
/** Check if URL uses HTTPS */
function isSecureUrl(url) {
try {
return new URL(url).protocol === 'https:';
}
catch {
return false;
}
}
//# sourceMappingURL=base-types.js.map