This document explains the blog validation and diagnostics system implemented for the WordPress integration in the Losi Chat application.
The blog system is designed to handle WordPress content with robust error handling, validation, and hydration compatibility. The system consists of several utilities that work together to ensure reliable rendering of blog content.
lib/diagnostics.ts)A collection of utilities for diagnosing API issues and debugging data structures:
safeInspect: Safely inspect complex objects with depth limits to prevent circular reference errorslogApiError: Detailed logging for API errors with context informationvalidateWordPressPost: Validate WordPress post structure and report issuesdiagnoseJsonParseError: Provides detailed information about JSON parsing errors, including position and common issuesisValidUrl: Validate URL stringslib/blog-validation.ts)Utilities for validating and sanitizing WordPress blog post data:
validatePostBeforeRender: Validates a WordPress post and attempts to fix common issuessanitizeHtmlContent: Sanitizes HTML content to prevent XSS and other security issuesprocessPostContentForToc: Processes post content to add IDs to headings for table of contentscalculateReadingTime: Calculates reading time based on content lengthfixHydrationIssues: Fixes common issues that cause React hydration mismatches, such as HTML entities and self-closing tagslib/wordpress.ts)Enhanced WordPress API communication with robust error handling:
handleFetch: Generic fetch handler with improved error handlingfetchPosts, fetchPost, etc.: WordPress API operations with validation and error recoverytransformPost: Transforms WordPress post data into a consistent formatWordPress content can cause React hydration mismatches due to:
’ vs. ')<br/> vs. <br>)class="")The fixHydrationIssues function addresses these by:
The validation system is implemented in:
When fetching WordPress content:
When rendering content:
// Fetch data with error handlingconst post = await fetchPost(slug);
// Transform data safelyconst transformed = await transformPost(post);// Client component with hydration fixesconst { isValid, issues, fixedPost } = validatePostBeforeRender(post);const sanitized = sanitizeHtmlContent(post.content.rendered);const hydrationFixed = fixHydrationIssues(sanitized);