Merge origin/master and resolve conflicts

This commit is contained in:
2026-01-25 19:31:32 +01:00
199 changed files with 67308 additions and 24361 deletions
+93
View File
@@ -0,0 +1,93 @@
'use server';
import { validateCsrfToken } from '@/lib/csrf/server';
interface ContactFormData {
name: string;
email: string;
message: string;
}
interface ContactFormResult {
success: boolean;
error?: string;
errors?: Partial<Record<keyof ContactFormData, string>>;
}
/**
* Server action to handle contact form submissions
* Validates CSRF token and form data before processing
*/
export async function submitContactForm(
formData: FormData
): Promise<ContactFormResult> {
// Extract CSRF token from form data
const csrfToken = formData.get('csrfToken');
// Validate CSRF token
if (!csrfToken || typeof csrfToken !== 'string') {
return {
success: false,
error: 'CSRF token is missing',
};
}
const isValidToken = await validateCsrfToken(csrfToken);
if (!isValidToken) {
return {
success: false,
error: 'Invalid CSRF token',
};
}
// Extract and validate form fields
const name = formData.get('name')?.toString() || '';
const email = formData.get('email')?.toString() || '';
const message = formData.get('message')?.toString() || '';
// Validation
const errors: Partial<Record<keyof ContactFormData, string>> = {};
if (!name.trim()) {
errors.name = 'Name is required';
}
if (!email.trim()) {
errors.email = 'Email is required';
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
errors.email = 'Invalid email format';
}
if (!message.trim()) {
errors.message = 'Message is required';
}
if (Object.keys(errors).length > 0) {
return {
success: false,
errors,
};
}
try {
// TODO: Implement actual email sending logic here
// For now, we'll simulate successful submission
// In production, this would integrate with an email service like:
// - Supabase Edge Functions
// - SendGrid
// - AWS SES
// - Resend
// Simulate processing delay
await new Promise(resolve => setTimeout(resolve, 500));
return {
success: true,
};
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : 'Failed to send message',
};
}
}
+1 -226
View File
@@ -5,6 +5,7 @@ import Link from 'next/link';
import Image from 'next/image';
import type { Metadata } from 'next';
import { getAllBlogPosts, BlogPost } from '@/lib/blog';
import { legacyBlogPosts } from '@/data/legacyBlogPosts';
const POSTS_PER_PAGE = 12;
@@ -13,232 +14,6 @@ type Props = {
searchParams: Promise<{ page?: string }>;
};
// Legacy blog posts with translations (these have manual translations)
const legacyBlogPosts: Record<string, BlogPost[]> = {
de: [
{
slug: 'n8n-automatisierung-tutorial',
title: 'n8n Tutorial: Workflows automatisieren ohne Code - Schritt für Schritt',
date: '2026-01-18',
excerpt: 'Lernen Sie, wie Sie mit n8n leistungsstarke Automatisierungen erstellen. Von der Installation bis zum ersten produktiven Workflow - inklusive Best Practices.',
category: 'Automatisierung',
tags: ['n8n', 'Tutorial', 'Automatisierung', 'Workflow', 'No-Code', 'Self-Hosted'],
coverImage: '/images/posts/n8n-automatisierung-tutorial/cover.jpg',
},
{
slug: 'geo-generative-engine-optimization',
title: 'GEO: Generative Engine Optimization - SEO für die KI-Ära',
date: '2026-01-17',
excerpt: 'Wie Sie Ihre Inhalte für ChatGPT, Perplexity und andere KI-Suchmaschinen optimieren. Der neue Standard nach klassischem SEO.',
category: 'Marketing',
tags: ['GEO', 'SEO', 'KI', 'ChatGPT', 'Perplexity', 'Content Marketing', 'AEO'],
coverImage: '/images/posts/geo-generative-engine-optimization/cover.jpg',
},
{
slug: 'gpt-api-integration-praxisguide',
title: 'GPT API Integration: Vom API-Key zur produktionsreifen Anwendung',
date: '2026-01-16',
excerpt: 'Praktische Anleitung zur Integration von OpenAI GPT-4 in Ihre Anwendungen. Token-Optimierung, Fehlerbehandlung und Best Practices.',
category: 'KI-Entwicklung',
tags: ['GPT-4', 'OpenAI', 'API', 'Integration', 'Python', 'LLM', 'Prompt Engineering'],
coverImage: '/images/posts/gpt-api-integration-praxisguide/cover.jpg',
},
{
slug: 'ki-agenten-unternehmen-guide',
title: 'KI-Agenten für Unternehmen: Der ultimative Praxisguide 2026',
date: '2026-01-15',
excerpt: 'Wie Unternehmen KI-Agenten einsetzen können, um Prozesse zu automatisieren, Kosten zu senken und Wettbewerbsvorteile zu gewinnen.',
category: 'KI-Entwicklung',
tags: ['KI-Agenten', 'Automatisierung', 'GPT-4', 'Claude', 'LLM', 'Unternehmen'],
coverImage: '/images/posts/ki-agenten-unternehmen-guide/cover.jpg',
},
{
slug: 'n8n-make-zapier-vergleich',
title: 'n8n vs Make vs Zapier: Welches Automatisierungstool passt zu Ihnen?',
date: '2026-01-10',
excerpt: 'Ein detaillierter Vergleich der führenden Workflow-Automatisierungstools mit Vor- und Nachteilen für verschiedene Anwendungsfälle.',
category: 'Automatisierung',
tags: ['n8n', 'Make', 'Zapier', 'Workflow', 'Automatisierung', 'No-Code'],
coverImage: '/images/posts/n8n-make-zapier-vergleich/cover.jpg',
},
{
slug: 'voice-ai-kundenservice-trends',
title: 'Voice AI im Kundenservice: Trends und Best Practices 2026',
date: '2026-01-05',
excerpt: 'Wie Voice AI den Kundenservice revolutioniert und welche Technologien Sie für Ihr Unternehmen evaluieren sollten.',
category: 'Voice AI',
tags: ['Voice AI', 'Sprachassistent', 'Kundenservice', 'NLP', 'Chatbot', 'Vapi'],
coverImage: '/images/posts/voice-ai-kundenservice-trends/cover.jpg',
},
{
slug: 'saas-mvp-entwicklung-4-wochen',
title: 'SaaS MVP in 4 Wochen: Von der Idee zum Launch',
date: '2025-12-20',
excerpt: 'Schritt-für-Schritt Anleitung zur schnellen Entwicklung eines SaaS MVP mit Next.js, Prisma und modernen Cloud-Diensten.',
category: 'SaaS-Entwicklung',
tags: ['SaaS', 'MVP', 'Next.js', 'Startup', 'Produktentwicklung', 'React'],
coverImage: '/images/posts/saas-mvp-entwicklung-4-wochen/cover.jpg',
},
{
slug: 'erp-integration-breuninger',
title: 'ApparelMagic und TradeByte: Analyse komplexer Integrationen',
date: '2024-02-09',
excerpt: 'Detaillierte Analyse einer E-Commerce-Integration zwischen Apparel Magic und Breuninger via TradeByte',
category: 'System Integration',
tags: ['ERP', 'Apparel Magic', 'TradeByte', 'API Integration', 'Python', 'MariaDB'],
coverImage: '/images/posts/erp-integration-breuninger/cover.jpg',
},
],
en: [
{
slug: 'n8n-automatisierung-tutorial',
title: 'n8n Tutorial: Automate Workflows Without Code - Step by Step',
date: '2026-01-18',
excerpt: 'Learn how to create powerful automations with n8n. From installation to your first production workflow - including best practices.',
category: 'Automation',
tags: ['n8n', 'Tutorial', 'Automation', 'Workflow', 'No-Code', 'Self-Hosted'],
coverImage: '/images/posts/n8n-automatisierung-tutorial/cover.jpg',
},
{
slug: 'geo-generative-engine-optimization',
title: 'GEO: Generative Engine Optimization - SEO for the AI Era',
date: '2026-01-17',
excerpt: 'How to optimize your content for ChatGPT, Perplexity and other AI search engines. The new standard after traditional SEO.',
category: 'Marketing',
tags: ['GEO', 'SEO', 'AI', 'ChatGPT', 'Perplexity', 'Content Marketing', 'AEO'],
coverImage: '/images/posts/geo-generative-engine-optimization/cover.jpg',
},
{
slug: 'gpt-api-integration-praxisguide',
title: 'GPT API Integration: From API Key to Production-Ready Application',
date: '2026-01-16',
excerpt: 'Practical guide to integrating OpenAI GPT-4 into your applications. Token optimization, error handling and best practices.',
category: 'AI Development',
tags: ['GPT-4', 'OpenAI', 'API', 'Integration', 'Python', 'LLM', 'Prompt Engineering'],
coverImage: '/images/posts/gpt-api-integration-praxisguide/cover.jpg',
},
{
slug: 'ki-agenten-unternehmen-guide',
title: 'AI Agents for Business: The Ultimate Practical Guide 2026',
date: '2026-01-15',
excerpt: 'How companies can use AI agents to automate processes, reduce costs and gain competitive advantages.',
category: 'AI Development',
tags: ['AI Agents', 'Automation', 'GPT-4', 'Claude', 'LLM', 'Enterprise'],
coverImage: '/images/posts/ki-agenten-unternehmen-guide/cover.jpg',
},
{
slug: 'n8n-make-zapier-vergleich',
title: 'n8n vs Make vs Zapier: Which Automation Tool is Right for You?',
date: '2026-01-10',
excerpt: 'A detailed comparison of leading workflow automation tools with pros and cons for different use cases.',
category: 'Automation',
tags: ['n8n', 'Make', 'Zapier', 'Workflow', 'Automation', 'No-Code'],
coverImage: '/images/posts/n8n-make-zapier-vergleich/cover.jpg',
},
{
slug: 'voice-ai-kundenservice-trends',
title: 'Voice AI in Customer Service: Trends and Best Practices 2026',
date: '2026-01-05',
excerpt: 'How Voice AI is revolutionizing customer service and which technologies you should evaluate for your business.',
category: 'Voice AI',
tags: ['Voice AI', 'Voice Assistant', 'Customer Service', 'NLP', 'Chatbot', 'Vapi'],
coverImage: '/images/posts/voice-ai-kundenservice-trends/cover.jpg',
},
{
slug: 'saas-mvp-entwicklung-4-wochen',
title: 'SaaS MVP in 4 Weeks: From Idea to Launch',
date: '2025-12-20',
excerpt: 'Step-by-step guide to quickly developing a SaaS MVP with Next.js, Prisma and modern cloud services.',
category: 'SaaS Development',
tags: ['SaaS', 'MVP', 'Next.js', 'Startup', 'Product Development', 'React'],
coverImage: '/images/posts/saas-mvp-entwicklung-4-wochen/cover.jpg',
},
{
slug: 'erp-integration-breuninger',
title: 'ApparelMagic and TradeByte: Complex Integration Analysis',
date: '2024-02-09',
excerpt: 'Detailed analysis of an e-commerce integration between Apparel Magic and Breuninger via TradeByte',
category: 'System Integration',
tags: ['ERP', 'Apparel Magic', 'TradeByte', 'API Integration', 'Python', 'MariaDB'],
coverImage: '/images/posts/erp-integration-breuninger/cover.jpg',
},
],
sr: [
{
slug: 'n8n-automatisierung-tutorial',
title: 'n8n Tutorial: Automatizujte Radne Tokove Bez Koda - Korak po Korak',
date: '2026-01-18',
excerpt: 'Naučite kako da kreirate moćne automatizacije sa n8n. Od instalacije do prvog produktivnog radnog toka - uključujući najbolje prakse.',
category: 'Automatizacija',
tags: ['n8n', 'Tutorial', 'Automatizacija', 'Workflow', 'No-Code', 'Self-Hosted'],
coverImage: '/images/posts/n8n-automatisierung-tutorial/cover.jpg',
},
{
slug: 'geo-generative-engine-optimization',
title: 'GEO: Generative Engine Optimization - SEO za AI Eru',
date: '2026-01-17',
excerpt: 'Kako da optimizujete sadržaj za ChatGPT, Perplexity i druge AI pretraživače. Novi standard posle klasičnog SEO-a.',
category: 'Marketing',
tags: ['GEO', 'SEO', 'AI', 'ChatGPT', 'Perplexity', 'Content Marketing', 'AEO'],
coverImage: '/images/posts/geo-generative-engine-optimization/cover.jpg',
},
{
slug: 'gpt-api-integration-praxisguide',
title: 'GPT API Integracija: Od API Ključa do Produkcione Aplikacije',
date: '2026-01-16',
excerpt: 'Praktični vodič za integraciju OpenAI GPT-4 u vaše aplikacije. Optimizacija tokena, rukovanje greškama i najbolje prakse.',
category: 'AI Razvoj',
tags: ['GPT-4', 'OpenAI', 'API', 'Integracija', 'Python', 'LLM', 'Prompt Engineering'],
coverImage: '/images/posts/gpt-api-integration-praxisguide/cover.jpg',
},
{
slug: 'ki-agenten-unternehmen-guide',
title: 'AI Agenti za Preduzeća: Ultimativni Praktični Vodič 2026',
date: '2026-01-15',
excerpt: 'Kako kompanije mogu koristiti AI agente za automatizaciju procesa, smanjenje troškova i sticanje konkurentskih prednosti.',
category: 'AI Razvoj',
tags: ['AI Agenti', 'Automatizacija', 'GPT-4', 'Claude', 'LLM', 'Preduzeća'],
coverImage: '/images/posts/ki-agenten-unternehmen-guide/cover.jpg',
},
{
slug: 'n8n-make-zapier-vergleich',
title: 'n8n vs Make vs Zapier: Koji Alat za Automatizaciju je Pravi za Vas?',
date: '2026-01-10',
excerpt: 'Detaljna uporedna analiza vodećih alata za automatizaciju radnih tokova sa prednostima i manama za različite slučajeve upotrebe.',
category: 'Automatizacija',
tags: ['n8n', 'Make', 'Zapier', 'Workflow', 'Automatizacija', 'No-Code'],
coverImage: '/images/posts/n8n-make-zapier-vergleich/cover.jpg',
},
{
slug: 'voice-ai-kundenservice-trends',
title: 'Voice AI u Korisničkoj Službi: Trendovi i Najbolje Prakse 2026',
date: '2026-01-05',
excerpt: 'Kako Voice AI revolucioniše korisničku službu i koje tehnologije treba da evaluirate za vaš posao.',
category: 'Voice AI',
tags: ['Voice AI', 'Glasovni Asistent', 'Korisnička Služba', 'NLP', 'Chatbot', 'Vapi'],
coverImage: '/images/posts/voice-ai-kundenservice-trends/cover.jpg',
},
{
slug: 'saas-mvp-entwicklung-4-wochen',
title: 'SaaS MVP za 4 Nedelje: Od Ideje do Lansiranja',
date: '2025-12-20',
excerpt: 'Korak-po-korak vodič za brz razvoj SaaS MVP-a sa Next.js, Prisma i modernim cloud servisima.',
category: 'SaaS Razvoj',
tags: ['SaaS', 'MVP', 'Next.js', 'Startup', 'Razvoj Proizvoda', 'React'],
coverImage: '/images/posts/saas-mvp-entwicklung-4-wochen/cover.jpg',
},
{
slug: 'erp-integration-breuninger',
title: 'ApparelMagic i TradeByte: Analiza kompleksnih integracija',
date: '2024-02-09',
excerpt: 'Detaljna analiza e-commerce integracije izmedu Apparel Magic i Breuninger putem TradeByte',
category: 'Sistemska Integracija',
tags: ['ERP', 'Apparel Magic', 'TradeByte', 'API Integracija', 'Python', 'MariaDB'],
coverImage: '/images/posts/erp-integration-breuninger/cover.jpg',
},
],
};
const BASE_URL = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
export async function generateMetadata({ params }: Props): Promise<Metadata> {
+1 -1
View File
@@ -20,7 +20,7 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
const descriptions: Record<string, string> = {
de: 'Impressum und rechtliche Informationen für die Portfolio-Website von Damjan Savić, KI Entwickler und Automation Specialist aus Köln.',
en: 'Legal notice and contact information for Damjan Savić portfolio website, AI Developer and Automation Specialist.',
sr: 'Pravno obavestenje i kontakt informacije za portfolio veb sajt Damjana Savica, AI Developer i Automation Specialist.',
sr: 'Pravno obavestenje i kontakt informacije za portfolio veb sajt Damjana Savića, AI Developer i Automation Specialist.',
};
const localePath = locale === 'de' ? '/imprint' : `/${locale}/imprint`;
+6 -6
View File
@@ -31,15 +31,15 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
const BASE_URL = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const titles: Record<Locale, string> = {
de: 'Damjan Savić | AI & Automation Specialist aus Köln',
en: 'Damjan Savić | AI & Automation Specialist from Cologne',
sr: 'Damjan Savić | AI & Automation Specialist iz Kelna',
de: 'Damjan Savić | Fullstack Developer aus Köln',
en: 'Damjan Savić | Fullstack Developer from Cologne',
sr: 'Damjan Savić | Fullstack Developer iz Kelna',
};
const descriptions: Record<Locale, string> = {
de: 'Entwicklung von KI-Agenten und Automatisierungslösungen. Von Voice-AI-Plattformen bis zu autonomen Web-Agenten.',
en: 'Building AI agents and automation solutions. From voice AI platforms to autonomous web agents.',
sr: 'Razvoj AI agenata i resenja za automatizaciju. Od voice AI platformi do autonomnih web agenata.',
de: 'Fullstack Entwicklung für Websites, Apps und SaaS mit Next.js, React und TypeScript.',
en: 'Fullstack development for websites, apps and SaaS with Next.js, React and TypeScript.',
sr: 'Fullstack razvoj za web stranice, aplikacije i SaaS sa Next.js, React i TypeScript.',
};
// Generate alternates using localeMetadata
+2 -2
View File
@@ -4,9 +4,9 @@ import './globals.css';
export const metadata: Metadata = {
title: {
template: '%s | Damjan Savić',
default: 'Damjan Savić | AI & Automation Specialist',
default: 'Damjan Savić | Fullstack Developer',
},
description: 'AI & Automation Specialist - Building AI agents and automation solutions.',
description: 'Fullstack Developer - Building websites, apps and SaaS with Next.js, React and TypeScript.',
metadataBase: new URL(process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com'),
};
+20 -18
View File
@@ -1,23 +1,25 @@
import Link from 'next/link';
import { getTranslations } from 'next-intl/server';
import { defaultLocale } from '@/i18n/config';
export default async function NotFound() {
const t = await getTranslations('pages.notfound');
export default function NotFound() {
return (
<html lang="de">
<body className="bg-zinc-900 text-zinc-50 min-h-screen flex items-center justify-center">
<div className="text-center px-4">
<h1 className="text-6xl font-bold mb-4">404</h1>
<h2 className="text-2xl font-semibold mb-4">Page Not Found</h2>
<p className="text-zinc-400 mb-8">
The page you are looking for does not exist or has been moved.
</p>
<Link
href="/de"
className="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors inline-block"
>
Go to Homepage
</Link>
</div>
</body>
</html>
<div className="bg-zinc-900 text-zinc-50 min-h-screen flex items-center justify-center">
<div className="text-center px-4">
<h1 className="text-6xl font-bold mb-4">404</h1>
<h2 className="text-2xl font-semibold mb-4">{t('title')}</h2>
<p className="text-zinc-400 mb-8">
{t('description')}
</p>
<Link
href={`/${defaultLocale}`}
className="px-6 py-3 bg-white text-zinc-900 hover:bg-zinc-200 rounded-lg transition-colors inline-block font-medium"
>
{t('backHome')}
</Link>
</div>
</div>
);
}
+186
View File
@@ -0,0 +1,186 @@
'use client';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useState } from 'react';
interface UserSettings {
theme: 'light' | 'dark';
notifications: boolean;
language: string;
}
export default function TestLocalStoragePage() {
// Test 1: Simple string value
const [name, setName, removeName] = useLocalStorage('test-name', 'Guest');
// Test 2: Complex object
const [settings, setSettings, removeSettings] = useLocalStorage<UserSettings>(
'test-settings',
{
theme: 'light',
notifications: true,
language: 'en',
}
);
// Test 3: Array
const [items, setItems, removeItems] = useLocalStorage<string[]>('test-items', []);
// Test 4: Number
const [count, setCount, removeCount] = useLocalStorage('test-count', 0);
const [newItem, setNewItem] = useState('');
return (
<div style={{ padding: '2rem', maxWidth: '800px', margin: '0 auto' }}>
<h1>useLocalStorage Hook Test Page</h1>
<p style={{ color: '#666', marginBottom: '2rem' }}>
Open DevTools (F12) Application Local Storage to see values update in real-time.
Refresh the page to verify persistence.
</p>
{/* Test 1: String */}
<div style={{ marginBottom: '2rem', padding: '1rem', border: '1px solid #ddd', borderRadius: '8px' }}>
<h2>Test 1: String Value</h2>
<p>Current Name: <strong>{name}</strong></p>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter your name"
style={{ padding: '0.5rem', marginRight: '0.5rem' }}
/>
<button onClick={() => removeName()} style={{ padding: '0.5rem' }}>
Reset
</button>
<p style={{ fontSize: '0.875rem', color: '#666', marginTop: '0.5rem' }}>
localStorage key: <code>test-name</code>
</p>
</div>
{/* Test 2: Complex Object */}
<div style={{ marginBottom: '2rem', padding: '1rem', border: '1px solid #ddd', borderRadius: '8px' }}>
<h2>Test 2: Complex Object</h2>
<div style={{ marginBottom: '1rem' }}>
<p>Theme: <strong>{settings.theme}</strong></p>
<button
onClick={() => setSettings((prev) => ({ ...prev, theme: prev.theme === 'light' ? 'dark' : 'light' }))}
style={{ padding: '0.5rem', marginRight: '0.5rem' }}
>
Toggle Theme
</button>
</div>
<div style={{ marginBottom: '1rem' }}>
<label>
<input
type="checkbox"
checked={settings.notifications}
onChange={(e) => setSettings((prev) => ({ ...prev, notifications: e.target.checked }))}
/>
{' '}Enable Notifications
</label>
</div>
<div style={{ marginBottom: '1rem' }}>
<label>Language: </label>
<select
value={settings.language}
onChange={(e) => setSettings((prev) => ({ ...prev, language: e.target.value }))}
style={{ padding: '0.5rem' }}
>
<option value="en">English</option>
<option value="de">German</option>
<option value="es">Spanish</option>
</select>
</div>
<button onClick={() => removeSettings()} style={{ padding: '0.5rem' }}>
Reset Settings
</button>
<p style={{ fontSize: '0.875rem', color: '#666', marginTop: '0.5rem' }}>
localStorage key: <code>test-settings</code>
</p>
</div>
{/* Test 3: Array */}
<div style={{ marginBottom: '2rem', padding: '1rem', border: '1px solid #ddd', borderRadius: '8px' }}>
<h2>Test 3: Array Value</h2>
<p>Items ({items.length}):</p>
<ul style={{ minHeight: '60px' }}>
{items.map((item, index) => (
<li key={index}>
{item}{' '}
<button
onClick={() => setItems((prev) => prev.filter((_, i) => i !== index))}
style={{ padding: '0.25rem 0.5rem', fontSize: '0.875rem' }}
>
Remove
</button>
</li>
))}
</ul>
<div>
<input
type="text"
value={newItem}
onChange={(e) => setNewItem(e.target.value)}
onKeyPress={(e) => {
if (e.key === 'Enter' && newItem.trim()) {
setItems((prev) => [...prev, newItem.trim()]);
setNewItem('');
}
}}
placeholder="Add new item"
style={{ padding: '0.5rem', marginRight: '0.5rem' }}
/>
<button
onClick={() => {
if (newItem.trim()) {
setItems((prev) => [...prev, newItem.trim()]);
setNewItem('');
}
}}
style={{ padding: '0.5rem', marginRight: '0.5rem' }}
>
Add Item
</button>
<button onClick={() => removeItems()} style={{ padding: '0.5rem' }}>
Clear All
</button>
</div>
<p style={{ fontSize: '0.875rem', color: '#666', marginTop: '0.5rem' }}>
localStorage key: <code>test-items</code>
</p>
</div>
{/* Test 4: Number */}
<div style={{ marginBottom: '2rem', padding: '1rem', border: '1px solid #ddd', borderRadius: '8px' }}>
<h2>Test 4: Number Value</h2>
<p>Count: <strong>{count}</strong></p>
<button onClick={() => setCount((prev) => prev + 1)} style={{ padding: '0.5rem', marginRight: '0.5rem' }}>
Increment
</button>
<button onClick={() => setCount((prev) => prev - 1)} style={{ padding: '0.5rem', marginRight: '0.5rem' }}>
Decrement
</button>
<button onClick={() => removeCount()} style={{ padding: '0.5rem' }}>
Reset
</button>
<p style={{ fontSize: '0.875rem', color: '#666', marginTop: '0.5rem' }}>
localStorage key: <code>test-count</code>
</p>
</div>
{/* Instructions */}
<div style={{ marginTop: '2rem', padding: '1rem', backgroundColor: '#f0f9ff', borderRadius: '8px' }}>
<h3>Verification Checklist:</h3>
<ul>
<li> Open DevTools Application Local Storage http://localhost:3000</li>
<li> Interact with the controls above and watch localStorage update in real-time</li>
<li> Refresh the page (F5) - all values should persist</li>
<li> Check Console for hydration errors (there should be none)</li>
<li> Check Console for any errors (there should be none)</li>
<li> Verify TypeScript has no errors in your editor</li>
</ul>
</div>
</div>
);
}
+26 -11
View File
@@ -111,7 +111,7 @@ export function ContactForm() {
<div className="relative w-24 h-24 rounded-full overflow-hidden border-2 border-zinc-700 flex-shrink-0">
<Image
src="/images/headshot.webp"
alt="Damjan Savić"
alt="Damjan Savić - Full-Stack Web Developer"
fill
sizes="96px"
className="object-cover"
@@ -135,7 +135,7 @@ export function ContactForm() {
className="flex items-start gap-4"
>
<div className="p-3 bg-zinc-800/50 rounded-lg">
<MapPin className="h-6 w-6 text-zinc-400" />
<MapPin className="h-6 w-6 text-zinc-400" aria-hidden="true" />
</div>
<div>
<h3 className="text-sm font-medium text-zinc-300 mb-1">
@@ -154,7 +154,7 @@ export function ContactForm() {
className="flex items-start gap-4"
>
<div className="p-3 bg-zinc-800/50 rounded-lg">
<Phone className="h-6 w-6 text-zinc-400" />
<Phone className="h-6 w-6 text-zinc-400" aria-hidden="true" />
</div>
<div>
<h3 className="text-sm font-medium text-zinc-300 mb-1">
@@ -176,7 +176,7 @@ export function ContactForm() {
className="flex items-start gap-4"
>
<div className="p-3 bg-zinc-800/50 rounded-lg">
<Mail className="h-6 w-6 text-zinc-400" />
<Mail className="h-6 w-6 text-zinc-400" aria-hidden="true" />
</div>
<div>
<h3 className="text-sm font-medium text-zinc-300 mb-1">
@@ -210,7 +210,7 @@ export function ContactForm() {
>
<div className="bg-zinc-800/30 border border-zinc-800 rounded-xl p-6 md:p-8">
<div className="flex items-center gap-2 mb-2">
<Mail className="h-5 w-5 text-zinc-400" />
<Mail className="h-5 w-5 text-zinc-400" aria-hidden="true" />
<h2 className="text-xl font-semibold text-white">
{t('contactForm.title')}
</h2>
@@ -233,10 +233,13 @@ export function ContactForm() {
onChange={handleChange}
placeholder={t('contactForm.name.placeholder')}
disabled={isSubmitting}
aria-required="true"
aria-invalid={!!errors.name}
aria-describedby={errors.name ? 'name-error' : undefined}
className="w-full h-12 px-4 bg-zinc-900/50 border border-zinc-800 rounded-lg text-white placeholder:text-zinc-500 focus:outline-none focus:ring-2 focus:ring-zinc-600 disabled:opacity-50"
/>
{errors.name && (
<p className="text-sm text-red-400">{errors.name}</p>
<p id="name-error" role="alert" className="text-sm text-red-400">{errors.name}</p>
)}
</div>
@@ -252,10 +255,13 @@ export function ContactForm() {
onChange={handleChange}
placeholder={t('contactForm.email.placeholder')}
disabled={isSubmitting}
aria-required="true"
aria-invalid={!!errors.email}
aria-describedby={errors.email ? 'email-error' : undefined}
className="w-full h-12 px-4 bg-zinc-900/50 border border-zinc-800 rounded-lg text-white placeholder:text-zinc-500 focus:outline-none focus:ring-2 focus:ring-zinc-600 disabled:opacity-50"
/>
{errors.email && (
<p className="text-sm text-red-400">{errors.email}</p>
<p id="email-error" role="alert" className="text-sm text-red-400">{errors.email}</p>
)}
</div>
@@ -271,10 +277,13 @@ export function ContactForm() {
placeholder={t('contactForm.message.placeholder')}
rows={6}
disabled={isSubmitting}
aria-required="true"
aria-invalid={!!errors.message}
aria-describedby={errors.message ? 'message-error' : undefined}
className="w-full px-4 py-3 bg-zinc-900/50 border border-zinc-800 rounded-lg text-white placeholder:text-zinc-500 focus:outline-none focus:ring-2 focus:ring-zinc-600 disabled:opacity-50 resize-none"
/>
{errors.message && (
<p className="text-sm text-red-400">{errors.message}</p>
<p id="message-error" role="alert" className="text-sm text-red-400">{errors.message}</p>
)}
</div>
</div>
@@ -283,9 +292,11 @@ export function ContactForm() {
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
role="alert"
aria-live="polite"
className="flex items-center gap-2 p-3 bg-green-900/20 border border-green-900/50 rounded-lg"
>
<CheckCircle2 className="h-4 w-4 text-green-500" />
<CheckCircle2 className="h-4 w-4 text-green-500" aria-hidden="true" />
<p className="text-green-400 text-sm">
{t('contactForm.successMessage')}
</p>
@@ -296,6 +307,8 @@ export function ContactForm() {
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
role="alert"
aria-live="assertive"
className="p-3 bg-red-900/20 border border-red-900/50 rounded-lg"
>
<p className="text-red-400 text-sm">
@@ -307,13 +320,15 @@ export function ContactForm() {
<button
type="submit"
disabled={isSubmitting}
aria-busy={isSubmitting}
aria-label={isSubmitting ? t('contactForm.submitting') : undefined}
className="w-full h-12 bg-zinc-100 hover:bg-white text-zinc-900 font-medium rounded-lg transition-colors duration-300 flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
>
{isSubmitting ? (
<Loader2 className="h-5 w-5 animate-spin" />
<Loader2 className="h-5 w-5 animate-spin" aria-hidden="true" />
) : (
<>
<Send className="h-5 w-5" />
<Send className="h-5 w-5" aria-hidden="true" />
{t('contactForm.submit')}
</>
)}
+1 -1
View File
@@ -26,7 +26,7 @@ const Hero = async () => {
<div className="md:hidden absolute inset-x-0 bottom-0 h-[60%] bg-gradient-to-t from-zinc-950 via-zinc-950/80 via-40% to-transparent z-10 pointer-events-none" />
{/* Social Links - Top */}
<div className="absolute top-8 left-6 sm:left-12 lg:left-20 flex gap-4 z-20">
<div className="absolute top-8 left-6 sm:left-12 lg:left-20 flex gap-4 z-30">
<a
href="https://www.linkedin.com/in/damjan-savi%C4%87-720288127/"
target="_blank"
+60 -55
View File
@@ -2,15 +2,54 @@
import { useState, useEffect } from 'react';
import { useTranslations } from 'next-intl';
import { motion, AnimatePresence } from 'framer-motion';
import { motion } from 'framer-motion';
import { Database, Server, Code2, Bot, Workflow, FileCode2 } from 'lucide-react';
interface Skill {
name: string;
level: number;
description: string;
}
interface SkeletonProps {
className?: string;
}
const Skeleton: React.FC<SkeletonProps> = ({ className }) => (
<div className={`animate-pulse bg-zinc-700/50 rounded ${className}`}></div>
);
const SkillsSkeleton = () => (
<section id="skills" className="py-24 relative" aria-label="Loading skills" aria-busy="true">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<Skeleton className="h-8 w-48 mb-12" />
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
{/* Skills Progress Bars Skeleton */}
<div className="space-y-6">
{[1, 2, 3, 4, 5, 6, 7, 8].map((i) => (
<div key={i} className="space-y-2">
<div className="flex justify-between items-center">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-4 w-12" />
</div>
<Skeleton className="h-2 w-full rounded-full" />
</div>
))}
</div>
{/* Skills Icons Grid Skeleton */}
<div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
{[1, 2, 3, 4, 5, 6].map((i) => (
<div key={i} className="p-6 rounded-xl bg-zinc-800/30 backdrop-blur-sm">
<Skeleton className="w-8 h-8 mx-auto mb-3" />
<Skeleton className="h-4 w-16 mx-auto" />
</div>
))}
</div>
</div>
</div>
</section>
);
const iconMap: Record<string, React.ReactNode> = {
'AI & LLMs': <Bot className="w-8 h-8" />,
'Automation': <Workflow className="w-8 h-8" />,
@@ -25,23 +64,27 @@ const iconMap: Record<string, React.ReactNode> = {
const Skills = () => {
const t = useTranslations('pages.home.skills');
const [selectedSkill, setSelectedSkill] = useState<string | null>(null);
const [skills, setSkills] = useState<Skill[]>([]);
useEffect(() => {
try {
const translatedSkills = t.raw('skills') as Skill[];
if (Array.isArray(translatedSkills)) {
setSkills(translatedSkills);
// Temporary delay to see skeleton loading state
const timer = setTimeout(() => {
try {
const translatedSkills = t.raw('skills') as Skill[];
if (Array.isArray(translatedSkills)) {
setSkills(translatedSkills);
}
} catch (error) {
console.error('Error loading skills:', error);
setSkills([]);
}
} catch (error) {
console.error('Error loading skills:', error);
setSkills([]);
}
}, 2000);
return () => clearTimeout(timer);
}, [t]);
if (skills.length === 0) {
return <div className="py-24 text-center text-zinc-400">Loading skills...</div>;
return <SkillsSkeleton />;
}
return (
@@ -96,54 +139,16 @@ const Skills = () => {
{skills.map((skill, idx) => (
<motion.div
key={skill.name}
className="relative"
initial={{ opacity: 0, scale: 0.8 }}
whileInView={{ opacity: 1, scale: 1 }}
viewport={{ once: true }}
transition={{ duration: 0.5, delay: idx * 0.1 }}
className="p-6 rounded-xl bg-zinc-800/30 backdrop-blur-sm flex flex-col items-center justify-center gap-3"
>
<motion.div
className={`relative p-6 rounded-xl bg-zinc-800/30 backdrop-blur-sm flex flex-col items-center justify-center gap-3 cursor-pointer transition-colors duration-300 hover:bg-zinc-700/50 ${
selectedSkill === skill.name ? 'ring-2 ring-zinc-500 z-20' : ''
}`}
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.98 }}
onHoverStart={() => setSelectedSkill(skill.name)}
onHoverEnd={() => setSelectedSkill(null)}
role="button"
>
<motion.div
className={selectedSkill === skill.name ? 'text-zinc-500' : 'text-white'}
animate={{
rotate: selectedSkill === skill.name ? [0, -10, 10, 0] : 0,
scale: selectedSkill === skill.name ? 1.1 : 1
}}
transition={{ duration: 0.4 }}
>
{iconMap[skill.name] || <Code2 className="w-8 h-8" />}
</motion.div>
<span className="text-white text-sm text-center">{skill.name}</span>
<AnimatePresence>
{selectedSkill === skill.name && (
<motion.div
className="absolute left-1/2 top-0 -translate-x-1/2 bg-zinc-800/80 backdrop-blur-sm rounded-lg px-4 py-2 text-zinc-300 text-xs text-center shadow-xl pointer-events-none"
initial={{ opacity: 0, y: 5 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 5 }}
transition={{ duration: 0.15 }}
style={{
whiteSpace: 'nowrap',
transform: 'translate(-50%, calc(-100% - 12px))',
zIndex: 999
}}
>
{skill.description}
<div className="absolute left-1/2 bottom-0 translate-y-1/2 -translate-x-1/2 w-0 h-0 border-l-[6px] border-l-transparent border-r-[6px] border-r-transparent border-t-[6px] border-t-zinc-800" />
</motion.div>
)}
</AnimatePresence>
</motion.div>
<div className="text-white">
{iconMap[skill.name] || <Code2 className="w-8 h-8" />}
</div>
<span className="text-white text-sm text-center">{skill.name}</span>
</motion.div>
))}
</div>
-758
View File
@@ -1,758 +0,0 @@
import { type Locale } from '@/i18n/config';
interface JsonLdProps {
locale: Locale;
}
export function PersonJsonLd({ locale }: JsonLdProps) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema = {
'@context': 'https://schema.org',
'@type': 'Person',
'@id': `${baseUrl}/#person`,
name: 'Damjan Savić',
givenName: 'Damjan',
familyName: 'Savić',
jobTitle: locale === 'de'
? 'AI & Automation Specialist | Fullstack Entwickler'
: locale === 'sr'
? 'AI & Automation Specialist | Fullstack Developer'
: 'AI & Automation Specialist | Fullstack Developer',
description: locale === 'de'
? 'Entwicklung von KI-Agenten und Automatisierungslösungen. Von Voice-AI-Plattformen bis zu autonomen Web-Agenten.'
: locale === 'sr'
? 'Razvoj AI agenata i rešenja za automatizaciju. Od voice AI platformi do autonomnih web agenata.'
: 'Remote AI developer building AI agents and automation solutions for clients in USA, UK and Europe. From voice AI platforms to autonomous web agents.',
url: baseUrl,
image: `${baseUrl}/images/og-image.jpg`,
email: 'info@damjan-savic.com',
telephone: '+491756950979',
address: {
'@type': 'PostalAddress',
addressLocality: locale === 'sr' ? 'Keln' : locale === 'en' ? 'Cologne' : 'Köln',
addressRegion: 'NRW',
addressCountry: 'DE',
},
sameAs: [
'https://www.linkedin.com/in/damjansavic/',
'https://github.com/damjansavic',
],
knowsAbout: [
'Artificial Intelligence',
'Machine Learning',
'Process Automation',
'Voice AI',
'Web Development',
'Python',
'TypeScript',
'React',
'Next.js',
'n8n',
'SaaS Development',
],
alumniOf: [
{
'@type': 'EducationalOrganization',
name: 'FOM Hochschule für Ökonomie & Management',
},
],
hasCredential: [
{
'@type': 'EducationalOccupationalCredential',
name: 'M.A. Software Development',
credentialCategory: 'degree',
},
{
'@type': 'EducationalOccupationalCredential',
name: 'B.Sc. Wirtschaftsinformatik',
credentialCategory: 'degree',
},
],
};
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
export function ProfessionalServiceJsonLd({ locale }: JsonLdProps) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const serviceNames = {
de: [
'KI-Entwicklung',
'Prozessautomatisierung',
'Voice AI Entwicklung',
'SaaS Entwicklung',
'Fullstack Webentwicklung',
'n8n Automatisierung',
],
en: [
'AI Development',
'Process Automation',
'Voice AI Development',
'SaaS Development',
'Fullstack Web Development',
'n8n Automation',
],
sr: [
'AI Razvoj',
'Automatizacija procesa',
'Voice AI Razvoj',
'SaaS Razvoj',
'Fullstack Web Razvoj',
'n8n Automatizacija',
],
};
const schema = {
'@context': 'https://schema.org',
'@type': 'ProfessionalService',
'@id': `${baseUrl}/#business`,
name: 'Damjan Savić - AI & Automation Specialist',
description: locale === 'de'
? 'Freelance AI & Automation Specialist aus Köln. Spezialisiert auf KI-Agenten, Voice AI, Prozessautomatisierung und SaaS-Entwicklung.'
: locale === 'sr'
? 'Freelance AI & Automation Specialist iz Kelna. Specijalizovan za AI agente, Voice AI, automatizaciju procesa i SaaS razvoj.'
: 'Remote AI & Automation Specialist based in Germany, serving clients in USA, UK and Europe. Specialized in AI agents, Voice AI, n8n process automation and custom SaaS development.',
url: baseUrl,
logo: `${baseUrl}/images/og-image.jpg`,
image: `${baseUrl}/images/og-image.jpg`,
email: 'info@damjan-savic.com',
telephone: '+491756950979',
priceRange: '€€€',
address: {
'@type': 'PostalAddress',
streetAddress: 'Rotdornallee',
addressLocality: locale === 'sr' ? 'Keln' : locale === 'en' ? 'Cologne' : 'Köln',
addressRegion: 'NRW',
postalCode: '50769',
addressCountry: 'DE',
},
geo: {
'@type': 'GeoCoordinates',
latitude: 50.9375,
longitude: 6.9603,
},
areaServed: [
// Germany
{ '@type': 'City', name: 'Cologne' },
{ '@type': 'City', name: 'Düsseldorf' },
{ '@type': 'City', name: 'Frankfurt' },
{ '@type': 'City', name: 'Munich' },
{ '@type': 'City', name: 'Berlin' },
{ '@type': 'City', name: 'Hamburg' },
{ '@type': 'Country', name: 'Germany' },
// USA
{ '@type': 'City', name: 'New York' },
{ '@type': 'City', name: 'Los Angeles' },
{ '@type': 'City', name: 'San Francisco' },
{ '@type': 'City', name: 'Miami' },
{ '@type': 'City', name: 'Chicago' },
{ '@type': 'Country', name: 'United States' },
// UK
{ '@type': 'City', name: 'London' },
{ '@type': 'Country', name: 'United Kingdom' },
// Europe
{ '@type': 'Country', name: 'Austria' },
{ '@type': 'Country', name: 'Switzerland' },
],
hasOfferCatalog: {
'@type': 'OfferCatalog',
name: locale === 'de' ? 'Dienstleistungen' : locale === 'sr' ? 'Usluge' : 'Services',
itemListElement: serviceNames[locale].map((service, index) => ({
'@type': 'Offer',
itemOffered: {
'@type': 'Service',
name: service,
},
position: index + 1,
})),
},
founder: {
'@id': `${baseUrl}/#person`,
},
sameAs: [
'https://www.linkedin.com/in/damjansavic/',
'https://github.com/damjansavic',
],
};
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
export function BreadcrumbJsonLd({
items,
locale,
}: {
items: { name: string; url: string }[];
locale: Locale;
}) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema = {
'@context': 'https://schema.org',
'@type': 'BreadcrumbList',
inLanguage: locale === 'de' ? 'de-DE' : locale === 'sr' ? 'sr-RS' : 'en-US',
itemListElement: items.map((item, index) => ({
'@type': 'ListItem',
position: index + 1,
name: item.name,
item: item.url.startsWith('http') ? item.url : `${baseUrl}${item.url}`,
})),
};
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
export function WebPageJsonLd({
title,
description,
url,
locale,
}: {
title: string;
description: string;
url: string;
locale: Locale;
}) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema = {
'@context': 'https://schema.org',
'@type': 'WebPage',
name: title,
description: description,
url: url.startsWith('http') ? url : `${baseUrl}${url}`,
inLanguage: locale === 'de' ? 'de-DE' : locale === 'sr' ? 'sr-RS' : 'en-US',
isPartOf: {
'@type': 'WebSite',
name: 'Damjan Savić',
url: baseUrl,
},
author: {
'@id': `${baseUrl}/#person`,
},
};
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
interface FAQItem {
question: string;
answer: string;
}
export function FAQJsonLd({ items, locale }: { items: FAQItem[]; locale?: Locale }) {
const schema = {
'@context': 'https://schema.org',
'@type': 'FAQPage',
inLanguage: locale ? (locale === 'de' ? 'de-DE' : locale === 'sr' ? 'sr-RS' : 'en-US') : 'de-DE',
mainEntity: items.map((item) => ({
'@type': 'Question',
name: item.question,
acceptedAnswer: {
'@type': 'Answer',
text: item.answer,
},
})),
};
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
interface ServiceJsonLdProps {
name: string;
description: string;
url: string;
locale: Locale;
areaServed?: string[];
}
export function ServiceJsonLd({
name,
description,
url,
locale,
areaServed = ['Köln', 'Düsseldorf', 'Frankfurt', 'Deutschland'],
}: ServiceJsonLdProps) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema = {
'@context': 'https://schema.org',
'@type': 'Service',
name: name,
description: description,
url: url.startsWith('http') ? url : `${baseUrl}${url}`,
inLanguage: locale === 'de' ? 'de-DE' : locale === 'sr' ? 'sr-RS' : 'en-US',
availableLanguage: ['de-DE', 'en-US', 'sr-RS'],
provider: {
'@id': `${baseUrl}/#business`,
},
areaServed: areaServed.map((area) => ({
'@type': 'City',
name: area,
})),
serviceType: name,
};
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
// Organization Schema
export function OrganizationJsonLd({ locale }: JsonLdProps) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema = {
'@context': 'https://schema.org',
'@type': 'Organization',
'@id': `${baseUrl}/#organization`,
name: 'Damjan Savić - AI & Automation Specialist',
alternateName: 'Damjan Savić',
url: baseUrl,
logo: {
'@type': 'ImageObject',
url: `${baseUrl}/images/og-image.jpg`,
width: 1200,
height: 630,
},
image: `${baseUrl}/images/og-image.jpg`,
description: locale === 'de'
? 'Freelance KI-Entwickler und Automatisierungsspezialist aus Köln. Spezialisiert auf KI-Agenten, Voice AI, Prozessautomatisierung mit n8n und SaaS-Entwicklung.'
: locale === 'sr'
? 'Freelance AI developer i specijalista za automatizaciju iz Kelna. Specijalizovan za AI agente, Voice AI, automatizaciju procesa sa n8n i SaaS razvoj.'
: 'Remote AI developer and automation specialist based in Germany. Working with clients in USA, UK & Europe. Specialized in AI agents, Voice AI, n8n automation and SaaS development.',
email: 'info@damjan-savic.com',
telephone: '+491756950979',
address: {
'@type': 'PostalAddress',
streetAddress: 'Rotdornallee',
addressLocality: locale === 'sr' ? 'Keln' : locale === 'en' ? 'Cologne' : 'Köln',
addressRegion: 'NRW',
postalCode: '50769',
addressCountry: 'DE',
},
geo: {
'@type': 'GeoCoordinates',
latitude: 50.9375,
longitude: 6.9603,
},
areaServed: [
// DACH Region
{ '@type': 'Country', name: 'Germany' },
{ '@type': 'Country', name: 'Austria' },
{ '@type': 'Country', name: 'Switzerland' },
// International (Remote)
{ '@type': 'Country', name: 'United States' },
{ '@type': 'Country', name: 'United Kingdom' },
{ '@type': 'Country', name: 'Serbia' },
// Major International Cities
{ '@type': 'City', name: 'New York' },
{ '@type': 'City', name: 'London' },
{ '@type': 'City', name: 'San Francisco' },
{ '@type': 'City', name: 'Los Angeles' },
],
founder: {
'@id': `${baseUrl}/#person`,
},
sameAs: [
'https://www.linkedin.com/in/damjansavic/',
'https://github.com/damjansavic',
],
contactPoint: {
'@type': 'ContactPoint',
contactType: 'customer service',
email: 'info@damjan-savic.com',
telephone: '+491756950979',
availableLanguage: ['German', 'English', 'Serbian'],
},
};
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
// Article Schema for Blog Posts
interface ArticleJsonLdProps {
title: string;
description: string;
url: string;
imageUrl: string;
datePublished: string;
dateModified?: string;
authorName?: string;
tags?: string[];
locale: Locale;
}
export function ArticleJsonLd({
title,
description,
url,
imageUrl,
datePublished,
dateModified,
authorName = 'Damjan Savić',
tags = [],
locale,
}: ArticleJsonLdProps) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema = {
'@context': 'https://schema.org',
'@type': 'Article',
headline: title,
description: description,
image: imageUrl.startsWith('http') ? imageUrl : `${baseUrl}${imageUrl}`,
url: url.startsWith('http') ? url : `${baseUrl}${url}`,
datePublished: datePublished,
dateModified: dateModified || datePublished,
author: {
'@type': 'Person',
'@id': `${baseUrl}/#person`,
name: authorName,
url: baseUrl,
},
publisher: {
'@type': 'Organization',
'@id': `${baseUrl}/#organization`,
name: 'Damjan Savić',
logo: {
'@type': 'ImageObject',
url: `${baseUrl}/images/og-image.jpg`,
},
},
mainEntityOfPage: {
'@type': 'WebPage',
'@id': url.startsWith('http') ? url : `${baseUrl}${url}`,
},
inLanguage: locale === 'de' ? 'de-DE' : locale === 'sr' ? 'sr-RS' : 'en-US',
keywords: tags.join(', '),
articleSection: 'Technology',
};
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
// HowTo Schema for Tutorials
interface HowToStep {
name: string;
text: string;
url?: string;
image?: string;
}
interface HowToJsonLdProps {
name: string;
description: string;
steps: HowToStep[];
totalTime?: string; // ISO 8601 duration format, e.g., "PT30M" for 30 minutes
estimatedCost?: { currency: string; value: string };
tools?: string[];
supplies?: string[];
image?: string;
locale: Locale;
}
export function HowToJsonLd({
name,
description,
steps,
totalTime,
estimatedCost,
tools,
supplies,
image,
locale,
}: HowToJsonLdProps) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema: Record<string, unknown> = {
'@context': 'https://schema.org',
'@type': 'HowTo',
name: name,
description: description,
step: steps.map((step, index) => ({
'@type': 'HowToStep',
position: index + 1,
name: step.name,
text: step.text,
...(step.url && { url: step.url.startsWith('http') ? step.url : `${baseUrl}${step.url}` }),
...(step.image && { image: step.image.startsWith('http') ? step.image : `${baseUrl}${step.image}` }),
})),
inLanguage: locale === 'de' ? 'de-DE' : locale === 'sr' ? 'sr-RS' : 'en-US',
};
if (totalTime) {
schema.totalTime = totalTime;
}
if (estimatedCost) {
schema.estimatedCost = {
'@type': 'MonetaryAmount',
currency: estimatedCost.currency,
value: estimatedCost.value,
};
}
if (tools && tools.length > 0) {
schema.tool = tools.map((tool) => ({
'@type': 'HowToTool',
name: tool,
}));
}
if (supplies && supplies.length > 0) {
schema.supply = supplies.map((supply) => ({
'@type': 'HowToSupply',
name: supply,
}));
}
if (image) {
schema.image = image.startsWith('http') ? image : `${baseUrl}${image}`;
}
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
// ProfilePage Schema for About Page
interface ProfilePageJsonLdProps {
locale: Locale;
}
export function ProfilePageJsonLd({ locale }: ProfilePageJsonLdProps) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema = {
'@context': 'https://schema.org',
'@type': 'ProfilePage',
dateCreated: '2024-01-01',
dateModified: new Date().toISOString().split('T')[0],
mainEntity: {
'@id': `${baseUrl}/#person`,
},
name: locale === 'de'
? 'Über Damjan Savić - KI-Entwickler & Automatisierungsspezialist'
: locale === 'sr'
? 'O Damjanu Saviću - AI Developer & Specijalista za automatizaciju'
: 'About Damjan Savić - AI Developer & Automation Specialist',
description: locale === 'de'
? 'Erfahren Sie mehr über Damjan Savić, Freelance KI-Entwickler und Automatisierungsspezialist aus Köln. Expertise in KI-Agenten, Voice AI, n8n und SaaS-Entwicklung.'
: locale === 'sr'
? 'Saznajte više o Damjanu Saviću, freelance AI developeru i specijalisti za automatizaciju iz Kelna. Ekspertiza u AI agentima, Voice AI, n8n i SaaS razvoju.'
: 'Learn more about Damjan Savić, freelance AI developer and automation specialist from Cologne. Expertise in AI agents, Voice AI, n8n and SaaS development.',
url: `${baseUrl}/${locale}/about`,
inLanguage: locale === 'de' ? 'de-DE' : locale === 'sr' ? 'sr-RS' : 'en-US',
};
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
// VideoObject Schema for embedded videos
interface VideoJsonLdProps {
name: string;
description: string;
thumbnailUrl: string;
uploadDate: string;
duration?: string; // ISO 8601 format, e.g., "PT1M30S"
contentUrl?: string;
embedUrl?: string;
locale: Locale;
}
export function VideoJsonLd({
name,
description,
thumbnailUrl,
uploadDate,
duration,
contentUrl,
embedUrl,
locale,
}: VideoJsonLdProps) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema: Record<string, unknown> = {
'@context': 'https://schema.org',
'@type': 'VideoObject',
name: name,
description: description,
thumbnailUrl: thumbnailUrl.startsWith('http') ? thumbnailUrl : `${baseUrl}${thumbnailUrl}`,
uploadDate: uploadDate,
inLanguage: locale === 'de' ? 'de-DE' : locale === 'sr' ? 'sr-RS' : 'en-US',
author: {
'@id': `${baseUrl}/#person`,
},
};
if (duration) {
schema.duration = duration;
}
if (contentUrl) {
schema.contentUrl = contentUrl;
}
if (embedUrl) {
schema.embedUrl = embedUrl;
}
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
// SoftwareApplication Schema for tools/projects
interface SoftwareAppJsonLdProps {
name: string;
description: string;
applicationCategory: string;
operatingSystem?: string;
offers?: {
price: string;
priceCurrency: string;
};
aggregateRating?: {
ratingValue: string;
ratingCount: string;
};
locale: Locale;
}
export function SoftwareAppJsonLd({
name,
description,
applicationCategory,
operatingSystem = 'Web',
offers,
aggregateRating,
locale,
}: SoftwareAppJsonLdProps) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema: Record<string, unknown> = {
'@context': 'https://schema.org',
'@type': 'SoftwareApplication',
name: name,
description: description,
applicationCategory: applicationCategory,
operatingSystem: operatingSystem,
author: {
'@id': `${baseUrl}/#person`,
},
inLanguage: locale === 'de' ? 'de-DE' : locale === 'sr' ? 'sr-RS' : 'en-US',
};
if (offers) {
schema.offers = {
'@type': 'Offer',
price: offers.price,
priceCurrency: offers.priceCurrency,
};
}
if (aggregateRating) {
schema.aggregateRating = {
'@type': 'AggregateRating',
ratingValue: aggregateRating.ratingValue,
ratingCount: aggregateRating.ratingCount,
};
}
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
// WebSite Schema for Search Box
export function WebSiteJsonLd({ locale }: JsonLdProps) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema = {
'@context': 'https://schema.org',
'@type': 'WebSite',
'@id': `${baseUrl}/#website`,
name: 'Damjan Savić',
alternateName: locale === 'de'
? 'Damjan Savić - KI Entwickler Köln'
: locale === 'sr'
? 'Damjan Savić - AI Developer Keln'
: 'Damjan Savić - AI Developer Cologne',
url: baseUrl,
description: locale === 'de'
? 'Portfolio und Blog von Damjan Savić - KI-Entwickler und Automatisierungsspezialist aus Köln'
: locale === 'sr'
? 'Portfolio i blog Damjana Savića - AI developer i specijalista za automatizaciju iz Kelna'
: 'Portfolio and blog of Damjan Savić - AI Developer and Automation Specialist from Cologne',
publisher: {
'@id': `${baseUrl}/#organization`,
},
inLanguage: [
{ '@type': 'Language', name: 'German', alternateName: 'de' },
{ '@type': 'Language', name: 'English', alternateName: 'en' },
{ '@type': 'Language', name: 'Serbian', alternateName: 'sr' },
],
};
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
+1 -1
View File
@@ -12,4 +12,4 @@ export {
ProfilePageJsonLd,
VideoJsonLd,
SoftwareAppJsonLd,
} from './JsonLd';
} from './schemas';
@@ -0,0 +1,67 @@
import { type Locale } from '@/i18n/config';
interface ArticleJsonLdProps {
title: string;
description: string;
url: string;
imageUrl: string;
datePublished: string;
dateModified?: string;
authorName?: string;
tags?: string[];
locale: Locale;
}
export function ArticleJsonLd({
title,
description,
url,
imageUrl,
datePublished,
dateModified,
authorName = 'Damjan Savić',
tags = [],
locale,
}: ArticleJsonLdProps) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema = {
'@context': 'https://schema.org',
'@type': 'Article',
headline: title,
description: description,
image: imageUrl.startsWith('http') ? imageUrl : `${baseUrl}${imageUrl}`,
url: url.startsWith('http') ? url : `${baseUrl}${url}`,
datePublished: datePublished,
dateModified: dateModified || datePublished,
author: {
'@type': 'Person',
'@id': `${baseUrl}/#person`,
name: authorName,
url: baseUrl,
},
publisher: {
'@type': 'Organization',
'@id': `${baseUrl}/#organization`,
name: 'Damjan Savić',
logo: {
'@type': 'ImageObject',
url: `${baseUrl}/images/og-image.jpg`,
},
},
mainEntityOfPage: {
'@type': 'WebPage',
'@id': url.startsWith('http') ? url : `${baseUrl}${url}`,
},
inLanguage: locale === 'de' ? 'de-DE' : locale === 'sr' ? 'sr-RS' : 'en-US',
keywords: tags.join(', '),
articleSection: 'Technology',
};
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
@@ -0,0 +1,30 @@
import { type Locale } from '@/i18n/config';
export function BreadcrumbJsonLd({
items,
locale,
}: {
items: { name: string; url: string }[];
locale: Locale;
}) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema = {
'@context': 'https://schema.org',
'@type': 'BreadcrumbList',
inLanguage: locale === 'de' ? 'de-DE' : locale === 'sr' ? 'sr-RS' : 'en-US',
itemListElement: items.map((item, index) => ({
'@type': 'ListItem',
position: index + 1,
name: item.name,
item: item.url.startsWith('http') ? item.url : `${baseUrl}${item.url}`,
})),
};
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
+29
View File
@@ -0,0 +1,29 @@
import { type Locale } from '@/i18n/config';
interface FAQItem {
question: string;
answer: string;
}
export function FAQJsonLd({ items, locale }: { items: FAQItem[]; locale?: Locale }) {
const schema = {
'@context': 'https://schema.org',
'@type': 'FAQPage',
inLanguage: locale ? (locale === 'de' ? 'de-DE' : locale === 'sr' ? 'sr-RS' : 'en-US') : 'de-DE',
mainEntity: items.map((item) => ({
'@type': 'Question',
name: item.question,
acceptedAnswer: {
'@type': 'Answer',
text: item.answer,
},
})),
};
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
@@ -0,0 +1,87 @@
import { type Locale } from '@/i18n/config';
interface HowToStep {
name: string;
text: string;
url?: string;
image?: string;
}
interface HowToJsonLdProps {
name: string;
description: string;
steps: HowToStep[];
totalTime?: string; // ISO 8601 duration format, e.g., "PT30M" for 30 minutes
estimatedCost?: { currency: string; value: string };
tools?: string[];
supplies?: string[];
image?: string;
locale: Locale;
}
export function HowToJsonLd({
name,
description,
steps,
totalTime,
estimatedCost,
tools,
supplies,
image,
locale,
}: HowToJsonLdProps) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema: Record<string, unknown> = {
'@context': 'https://schema.org',
'@type': 'HowTo',
name: name,
description: description,
step: steps.map((step, index) => ({
'@type': 'HowToStep',
position: index + 1,
name: step.name,
text: step.text,
...(step.url && { url: step.url.startsWith('http') ? step.url : `${baseUrl}${step.url}` }),
...(step.image && { image: step.image.startsWith('http') ? step.image : `${baseUrl}${step.image}` }),
})),
inLanguage: locale === 'de' ? 'de-DE' : locale === 'sr' ? 'sr-RS' : 'en-US',
};
if (totalTime) {
schema.totalTime = totalTime;
}
if (estimatedCost) {
schema.estimatedCost = {
'@type': 'MonetaryAmount',
currency: estimatedCost.currency,
value: estimatedCost.value,
};
}
if (tools && tools.length > 0) {
schema.tool = tools.map((tool) => ({
'@type': 'HowToTool',
name: tool,
}));
}
if (supplies && supplies.length > 0) {
schema.supply = supplies.map((supply) => ({
'@type': 'HowToSupply',
name: supply,
}));
}
if (image) {
schema.image = image.startsWith('http') ? image : `${baseUrl}${image}`;
}
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
@@ -0,0 +1,81 @@
import { type Locale } from '@/i18n/config';
interface JsonLdProps {
locale: Locale;
}
export function OrganizationJsonLd({ locale }: JsonLdProps) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema = {
'@context': 'https://schema.org',
'@type': 'Organization',
'@id': `${baseUrl}/#organization`,
name: 'Damjan Savić - AI & Automation Specialist',
alternateName: 'Damjan Savić',
url: baseUrl,
logo: {
'@type': 'ImageObject',
url: `${baseUrl}/images/og-image.jpg`,
width: 1200,
height: 630,
},
image: `${baseUrl}/images/og-image.jpg`,
description: locale === 'de'
? 'Freelance KI-Entwickler und Automatisierungsspezialist aus Köln. Spezialisiert auf KI-Agenten, Voice AI, Prozessautomatisierung mit n8n und SaaS-Entwicklung.'
: locale === 'sr'
? 'Freelance AI developer i specijalista za automatizaciju iz Kelna. Specijalizovan za AI agente, Voice AI, automatizaciju procesa sa n8n i SaaS razvoj.'
: 'Remote AI developer and automation specialist based in Germany. Working with clients in USA, UK & Europe. Specialized in AI agents, Voice AI, n8n automation and SaaS development.',
email: 'info@damjan-savic.com',
telephone: '+491756950979',
address: {
'@type': 'PostalAddress',
streetAddress: 'Rotdornallee',
addressLocality: locale === 'sr' ? 'Keln' : locale === 'en' ? 'Cologne' : 'Köln',
addressRegion: 'NRW',
postalCode: '50769',
addressCountry: 'DE',
},
geo: {
'@type': 'GeoCoordinates',
latitude: 50.9375,
longitude: 6.9603,
},
areaServed: [
// DACH Region
{ '@type': 'Country', name: 'Germany' },
{ '@type': 'Country', name: 'Austria' },
{ '@type': 'Country', name: 'Switzerland' },
// International (Remote)
{ '@type': 'Country', name: 'United States' },
{ '@type': 'Country', name: 'United Kingdom' },
{ '@type': 'Country', name: 'Serbia' },
// Major International Cities
{ '@type': 'City', name: 'New York' },
{ '@type': 'City', name: 'London' },
{ '@type': 'City', name: 'San Francisco' },
{ '@type': 'City', name: 'Los Angeles' },
],
founder: {
'@id': `${baseUrl}/#person`,
},
sameAs: [
'https://www.linkedin.com/in/damjansavic/',
'https://github.com/damjansavic',
],
contactPoint: {
'@type': 'ContactPoint',
contactType: 'customer service',
email: 'info@damjan-savic.com',
telephone: '+491756950979',
availableLanguage: ['German', 'English', 'Serbian'],
},
};
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
@@ -0,0 +1,80 @@
import { type Locale } from '@/i18n/config';
interface JsonLdProps {
locale: Locale;
}
export function PersonJsonLd({ locale }: JsonLdProps) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema = {
'@context': 'https://schema.org',
'@type': 'Person',
'@id': `${baseUrl}/#person`,
name: 'Damjan Savić',
givenName: 'Damjan',
familyName: 'Savić',
jobTitle: locale === 'de'
? 'AI & Automation Specialist | Fullstack Entwickler'
: locale === 'sr'
? 'AI & Automation Specialist | Fullstack Developer'
: 'AI & Automation Specialist | Fullstack Developer',
description: locale === 'de'
? 'Entwicklung von KI-Agenten und Automatisierungslösungen. Von Voice-AI-Plattformen bis zu autonomen Web-Agenten.'
: locale === 'sr'
? 'Razvoj AI agenata i rešenja za automatizaciju. Od voice AI platformi do autonomnih web agenata.'
: 'Remote AI developer building AI agents and automation solutions for clients in USA, UK and Europe. From voice AI platforms to autonomous web agents.',
url: baseUrl,
image: `${baseUrl}/images/og-image.jpg`,
email: 'info@damjan-savic.com',
telephone: '+491756950979',
address: {
'@type': 'PostalAddress',
addressLocality: locale === 'sr' ? 'Keln' : locale === 'en' ? 'Cologne' : 'Köln',
addressRegion: 'NRW',
addressCountry: 'DE',
},
sameAs: [
'https://www.linkedin.com/in/damjansavic/',
'https://github.com/damjansavic',
],
knowsAbout: [
'Artificial Intelligence',
'Machine Learning',
'Process Automation',
'Voice AI',
'Web Development',
'Python',
'TypeScript',
'React',
'Next.js',
'n8n',
'SaaS Development',
],
alumniOf: [
{
'@type': 'EducationalOrganization',
name: 'FOM Hochschule für Ökonomie & Management',
},
],
hasCredential: [
{
'@type': 'EducationalOccupationalCredential',
name: 'M.A. Software Development',
credentialCategory: 'degree',
},
{
'@type': 'EducationalOccupationalCredential',
name: 'B.Sc. Wirtschaftsinformatik',
credentialCategory: 'degree',
},
],
};
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
@@ -0,0 +1,116 @@
import { type Locale } from '@/i18n/config';
interface JsonLdProps {
locale: Locale;
}
export function ProfessionalServiceJsonLd({ locale }: JsonLdProps) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const serviceNames = {
de: [
'KI-Entwicklung',
'Prozessautomatisierung',
'Voice AI Entwicklung',
'SaaS Entwicklung',
'Fullstack Webentwicklung',
'n8n Automatisierung',
],
en: [
'AI Development',
'Process Automation',
'Voice AI Development',
'SaaS Development',
'Fullstack Web Development',
'n8n Automation',
],
sr: [
'AI Razvoj',
'Automatizacija procesa',
'Voice AI Razvoj',
'SaaS Razvoj',
'Fullstack Web Razvoj',
'n8n Automatizacija',
],
};
const schema = {
'@context': 'https://schema.org',
'@type': 'ProfessionalService',
'@id': `${baseUrl}/#business`,
name: 'Damjan Savić - AI & Automation Specialist',
description: locale === 'de'
? 'Freelance AI & Automation Specialist aus Köln. Spezialisiert auf KI-Agenten, Voice AI, Prozessautomatisierung und SaaS-Entwicklung.'
: locale === 'sr'
? 'Freelance AI & Automation Specialist iz Kelna. Specijalizovan za AI agente, Voice AI, automatizaciju procesa i SaaS razvoj.'
: 'Remote AI & Automation Specialist based in Germany, serving clients in USA, UK and Europe. Specialized in AI agents, Voice AI, n8n process automation and custom SaaS development.',
url: baseUrl,
logo: `${baseUrl}/images/og-image.jpg`,
image: `${baseUrl}/images/og-image.jpg`,
email: 'info@damjan-savic.com',
telephone: '+491756950979',
priceRange: '€€€',
address: {
'@type': 'PostalAddress',
streetAddress: 'Rotdornallee',
addressLocality: locale === 'sr' ? 'Keln' : locale === 'en' ? 'Cologne' : 'Köln',
addressRegion: 'NRW',
postalCode: '50769',
addressCountry: 'DE',
},
geo: {
'@type': 'GeoCoordinates',
latitude: 50.9375,
longitude: 6.9603,
},
areaServed: [
// Germany
{ '@type': 'City', name: 'Cologne' },
{ '@type': 'City', name: 'Düsseldorf' },
{ '@type': 'City', name: 'Frankfurt' },
{ '@type': 'City', name: 'Munich' },
{ '@type': 'City', name: 'Berlin' },
{ '@type': 'City', name: 'Hamburg' },
{ '@type': 'Country', name: 'Germany' },
// USA
{ '@type': 'City', name: 'New York' },
{ '@type': 'City', name: 'Los Angeles' },
{ '@type': 'City', name: 'San Francisco' },
{ '@type': 'City', name: 'Miami' },
{ '@type': 'City', name: 'Chicago' },
{ '@type': 'Country', name: 'United States' },
// UK
{ '@type': 'City', name: 'London' },
{ '@type': 'Country', name: 'United Kingdom' },
// Europe
{ '@type': 'Country', name: 'Austria' },
{ '@type': 'Country', name: 'Switzerland' },
],
hasOfferCatalog: {
'@type': 'OfferCatalog',
name: locale === 'de' ? 'Dienstleistungen' : locale === 'sr' ? 'Usluge' : 'Services',
itemListElement: serviceNames[locale].map((service, index) => ({
'@type': 'Offer',
itemOffered: {
'@type': 'Service',
name: service,
},
position: index + 1,
})),
},
founder: {
'@id': `${baseUrl}/#person`,
},
sameAs: [
'https://www.linkedin.com/in/damjansavic/',
'https://github.com/damjansavic',
],
};
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
@@ -0,0 +1,38 @@
import { type Locale } from '@/i18n/config';
interface ProfilePageJsonLdProps {
locale: Locale;
}
export function ProfilePageJsonLd({ locale }: ProfilePageJsonLdProps) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema = {
'@context': 'https://schema.org',
'@type': 'ProfilePage',
dateCreated: '2024-01-01',
dateModified: new Date().toISOString().split('T')[0],
mainEntity: {
'@id': `${baseUrl}/#person`,
},
name: locale === 'de'
? 'Über Damjan Savić - KI-Entwickler & Automatisierungsspezialist'
: locale === 'sr'
? 'O Damjanu Saviću - AI Developer & Specijalista za automatizaciju'
: 'About Damjan Savić - AI Developer & Automation Specialist',
description: locale === 'de'
? 'Erfahren Sie mehr über Damjan Savić, Freelance KI-Entwickler und Automatisierungsspezialist aus Köln. Expertise in KI-Agenten, Voice AI, n8n und SaaS-Entwicklung.'
: locale === 'sr'
? 'Saznajte više o Damjanu Saviću, freelance AI developeru i specijalisti za automatizaciju iz Kelna. Ekspertiza u AI agentima, Voice AI, n8n i SaaS razvoju.'
: 'Learn more about Damjan Savić, freelance AI developer and automation specialist from Cologne. Expertise in AI agents, Voice AI, n8n and SaaS development.',
url: `${baseUrl}/${locale}/about`,
inLanguage: locale === 'de' ? 'de-DE' : locale === 'sr' ? 'sr-RS' : 'en-US',
};
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
@@ -0,0 +1,44 @@
import { type Locale } from '@/i18n/config';
interface ServiceJsonLdProps {
name: string;
description: string;
url: string;
locale: Locale;
areaServed?: string[];
}
export function ServiceJsonLd({
name,
description,
url,
locale,
areaServed = ['Köln', 'Düsseldorf', 'Frankfurt', 'Deutschland'],
}: ServiceJsonLdProps) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema = {
'@context': 'https://schema.org',
'@type': 'Service',
name: name,
description: description,
url: url.startsWith('http') ? url : `${baseUrl}${url}`,
inLanguage: locale === 'de' ? 'de-DE' : locale === 'sr' ? 'sr-RS' : 'en-US',
availableLanguage: ['de-DE', 'en-US', 'sr-RS'],
provider: {
'@id': `${baseUrl}/#business`,
},
areaServed: areaServed.map((area) => ({
'@type': 'City',
name: area,
})),
serviceType: name,
};
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
@@ -0,0 +1,65 @@
import { type Locale } from '@/i18n/config';
interface SoftwareAppJsonLdProps {
name: string;
description: string;
applicationCategory: string;
operatingSystem?: string;
offers?: {
price: string;
priceCurrency: string;
};
aggregateRating?: {
ratingValue: string;
ratingCount: string;
};
locale: Locale;
}
export function SoftwareAppJsonLd({
name,
description,
applicationCategory,
operatingSystem = 'Web',
offers,
aggregateRating,
locale,
}: SoftwareAppJsonLdProps) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema: Record<string, unknown> = {
'@context': 'https://schema.org',
'@type': 'SoftwareApplication',
name: name,
description: description,
applicationCategory: applicationCategory,
operatingSystem: operatingSystem,
author: {
'@id': `${baseUrl}/#person`,
},
inLanguage: locale === 'de' ? 'de-DE' : locale === 'sr' ? 'sr-RS' : 'en-US',
};
if (offers) {
schema.offers = {
'@type': 'Offer',
price: offers.price,
priceCurrency: offers.priceCurrency,
};
}
if (aggregateRating) {
schema.aggregateRating = {
'@type': 'AggregateRating',
ratingValue: aggregateRating.ratingValue,
ratingCount: aggregateRating.ratingCount,
};
}
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
@@ -0,0 +1,58 @@
import { type Locale } from '@/i18n/config';
// VideoObject Schema for embedded videos
interface VideoJsonLdProps {
name: string;
description: string;
thumbnailUrl: string;
uploadDate: string;
duration?: string; // ISO 8601 format, e.g., "PT1M30S"
contentUrl?: string;
embedUrl?: string;
locale: Locale;
}
export function VideoJsonLd({
name,
description,
thumbnailUrl,
uploadDate,
duration,
contentUrl,
embedUrl,
locale,
}: VideoJsonLdProps) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema: Record<string, unknown> = {
'@context': 'https://schema.org',
'@type': 'VideoObject',
name: name,
description: description,
thumbnailUrl: thumbnailUrl.startsWith('http') ? thumbnailUrl : `${baseUrl}${thumbnailUrl}`,
uploadDate: uploadDate,
inLanguage: locale === 'de' ? 'de-DE' : locale === 'sr' ? 'sr-RS' : 'en-US',
author: {
'@id': `${baseUrl}/#person`,
},
};
if (duration) {
schema.duration = duration;
}
if (contentUrl) {
schema.contentUrl = contentUrl;
}
if (embedUrl) {
schema.embedUrl = embedUrl;
}
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
@@ -0,0 +1,39 @@
import { type Locale } from '@/i18n/config';
export function WebPageJsonLd({
title,
description,
url,
locale,
}: {
title: string;
description: string;
url: string;
locale: Locale;
}) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema = {
'@context': 'https://schema.org',
'@type': 'WebPage',
name: title,
description: description,
url: url.startsWith('http') ? url : `${baseUrl}${url}`,
inLanguage: locale === 'de' ? 'de-DE' : locale === 'sr' ? 'sr-RS' : 'en-US',
isPartOf: {
'@type': 'WebSite',
name: 'Damjan Savić',
url: baseUrl,
},
author: {
'@id': `${baseUrl}/#person`,
},
};
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
@@ -0,0 +1,43 @@
import { type Locale } from '@/i18n/config';
interface JsonLdProps {
locale: Locale;
}
// WebSite Schema for Search Box
export function WebSiteJsonLd({ locale }: JsonLdProps) {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';
const schema = {
'@context': 'https://schema.org',
'@type': 'WebSite',
'@id': `${baseUrl}/#website`,
name: 'Damjan Savić',
alternateName: locale === 'de'
? 'Damjan Savić - KI Entwickler Köln'
: locale === 'sr'
? 'Damjan Savić - AI Developer Keln'
: 'Damjan Savić - AI Developer Cologne',
url: baseUrl,
description: locale === 'de'
? 'Portfolio und Blog von Damjan Savić - KI-Entwickler und Automatisierungsspezialist aus Köln'
: locale === 'sr'
? 'Portfolio i blog Damjana Savića - AI developer i specijalista za automatizaciju iz Kelna'
: 'Portfolio and blog of Damjan Savić - AI Developer and Automation Specialist from Cologne',
publisher: {
'@id': `${baseUrl}/#organization`,
},
inLanguage: [
{ '@type': 'Language', name: 'German', alternateName: 'de' },
{ '@type': 'Language', name: 'English', alternateName: 'en' },
{ '@type': 'Language', name: 'Serbian', alternateName: 'sr' },
],
};
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
/>
);
}
+13
View File
@@ -0,0 +1,13 @@
export { PersonJsonLd } from './PersonJsonLd';
export { WebSiteJsonLd } from './WebSiteJsonLd';
export { ProfessionalServiceJsonLd } from './ProfessionalServiceJsonLd';
export { BreadcrumbJsonLd } from './BreadcrumbJsonLd';
export { WebPageJsonLd } from './WebPageJsonLd';
export { FAQJsonLd } from './FAQJsonLd';
export { ServiceJsonLd } from './ServiceJsonLd';
export { OrganizationJsonLd } from './OrganizationJsonLd';
export { ArticleJsonLd } from './ArticleJsonLd';
export { HowToJsonLd } from './HowToJsonLd';
export { ProfilePageJsonLd } from './ProfilePageJsonLd';
export { VideoJsonLd } from './VideoJsonLd';
export { SoftwareAppJsonLd } from './SoftwareAppJsonLd';
+228
View File
@@ -0,0 +1,228 @@
import type { BlogPost } from '@/lib/blog';
export type LegacyBlogPostsData = Record<string, BlogPost[]>;
export const legacyBlogPosts: LegacyBlogPostsData = {
de: [
{
slug: 'n8n-automatisierung-tutorial',
title: 'n8n Tutorial: Workflows automatisieren ohne Code - Schritt für Schritt',
date: '2026-01-18',
excerpt: 'Lernen Sie, wie Sie mit n8n leistungsstarke Automatisierungen erstellen. Von der Installation bis zum ersten produktiven Workflow - inklusive Best Practices.',
category: 'Automatisierung',
tags: ['n8n', 'Tutorial', 'Automatisierung', 'Workflow', 'No-Code', 'Self-Hosted'],
coverImage: '/images/posts/n8n-automatisierung-tutorial/cover.jpg',
},
{
slug: 'geo-generative-engine-optimization',
title: 'GEO: Generative Engine Optimization - SEO für die KI-Ära',
date: '2026-01-17',
excerpt: 'Wie Sie Ihre Inhalte für ChatGPT, Perplexity und andere KI-Suchmaschinen optimieren. Der neue Standard nach klassischem SEO.',
category: 'Marketing',
tags: ['GEO', 'SEO', 'KI', 'ChatGPT', 'Perplexity', 'Content Marketing', 'AEO'],
coverImage: '/images/posts/geo-generative-engine-optimization/cover.jpg',
},
{
slug: 'gpt-api-integration-praxisguide',
title: 'GPT API Integration: Vom API-Key zur produktionsreifen Anwendung',
date: '2026-01-16',
excerpt: 'Praktische Anleitung zur Integration von OpenAI GPT-4 in Ihre Anwendungen. Token-Optimierung, Fehlerbehandlung und Best Practices.',
category: 'KI-Entwicklung',
tags: ['GPT-4', 'OpenAI', 'API', 'Integration', 'Python', 'LLM', 'Prompt Engineering'],
coverImage: '/images/posts/gpt-api-integration-praxisguide/cover.jpg',
},
{
slug: 'ki-agenten-unternehmen-guide',
title: 'KI-Agenten für Unternehmen: Der ultimative Praxisguide 2026',
date: '2026-01-15',
excerpt: 'Wie Unternehmen KI-Agenten einsetzen können, um Prozesse zu automatisieren, Kosten zu senken und Wettbewerbsvorteile zu gewinnen.',
category: 'KI-Entwicklung',
tags: ['KI-Agenten', 'Automatisierung', 'GPT-4', 'Claude', 'LLM', 'Unternehmen'],
coverImage: '/images/posts/ki-agenten-unternehmen-guide/cover.jpg',
},
{
slug: 'n8n-make-zapier-vergleich',
title: 'n8n vs Make vs Zapier: Welches Automatisierungstool passt zu Ihnen?',
date: '2026-01-10',
excerpt: 'Ein detaillierter Vergleich der führenden Workflow-Automatisierungstools mit Vor- und Nachteilen für verschiedene Anwendungsfälle.',
category: 'Automatisierung',
tags: ['n8n', 'Make', 'Zapier', 'Workflow', 'Automatisierung', 'No-Code'],
coverImage: '/images/posts/n8n-make-zapier-vergleich/cover.jpg',
},
{
slug: 'voice-ai-kundenservice-trends',
title: 'Voice AI im Kundenservice: Trends und Best Practices 2026',
date: '2026-01-05',
excerpt: 'Wie Voice AI den Kundenservice revolutioniert und welche Technologien Sie für Ihr Unternehmen evaluieren sollten.',
category: 'Voice AI',
tags: ['Voice AI', 'Sprachassistent', 'Kundenservice', 'NLP', 'Chatbot', 'Vapi'],
coverImage: '/images/posts/voice-ai-kundenservice-trends/cover.jpg',
},
{
slug: 'saas-mvp-entwicklung-4-wochen',
title: 'SaaS MVP in 4 Wochen: Von der Idee zum Launch',
date: '2025-12-20',
excerpt: 'Schritt-für-Schritt Anleitung zur schnellen Entwicklung eines SaaS MVP mit Next.js, Prisma und modernen Cloud-Diensten.',
category: 'SaaS-Entwicklung',
tags: ['SaaS', 'MVP', 'Next.js', 'Startup', 'Produktentwicklung', 'React'],
coverImage: '/images/posts/saas-mvp-entwicklung-4-wochen/cover.jpg',
},
{
slug: 'erp-integration-breuninger',
title: 'ApparelMagic und TradeByte: Analyse komplexer Integrationen',
date: '2024-02-09',
excerpt: 'Detaillierte Analyse einer E-Commerce-Integration zwischen Apparel Magic und Breuninger via TradeByte',
category: 'System Integration',
tags: ['ERP', 'Apparel Magic', 'TradeByte', 'API Integration', 'Python', 'MariaDB'],
coverImage: '/images/posts/erp-integration-breuninger/cover.jpg',
},
],
en: [
{
slug: 'n8n-automatisierung-tutorial',
title: 'n8n Tutorial: Automate Workflows Without Code - Step by Step',
date: '2026-01-18',
excerpt: 'Learn how to create powerful automations with n8n. From installation to your first production workflow - including best practices.',
category: 'Automation',
tags: ['n8n', 'Tutorial', 'Automation', 'Workflow', 'No-Code', 'Self-Hosted'],
coverImage: '/images/posts/n8n-automatisierung-tutorial/cover.jpg',
},
{
slug: 'geo-generative-engine-optimization',
title: 'GEO: Generative Engine Optimization - SEO for the AI Era',
date: '2026-01-17',
excerpt: 'How to optimize your content for ChatGPT, Perplexity and other AI search engines. The new standard after traditional SEO.',
category: 'Marketing',
tags: ['GEO', 'SEO', 'AI', 'ChatGPT', 'Perplexity', 'Content Marketing', 'AEO'],
coverImage: '/images/posts/geo-generative-engine-optimization/cover.jpg',
},
{
slug: 'gpt-api-integration-praxisguide',
title: 'GPT API Integration: From API Key to Production-Ready Application',
date: '2026-01-16',
excerpt: 'Practical guide to integrating OpenAI GPT-4 into your applications. Token optimization, error handling and best practices.',
category: 'AI Development',
tags: ['GPT-4', 'OpenAI', 'API', 'Integration', 'Python', 'LLM', 'Prompt Engineering'],
coverImage: '/images/posts/gpt-api-integration-praxisguide/cover.jpg',
},
{
slug: 'ki-agenten-unternehmen-guide',
title: 'AI Agents for Business: The Ultimate Practical Guide 2026',
date: '2026-01-15',
excerpt: 'How companies can use AI agents to automate processes, reduce costs and gain competitive advantages.',
category: 'AI Development',
tags: ['AI Agents', 'Automation', 'GPT-4', 'Claude', 'LLM', 'Enterprise'],
coverImage: '/images/posts/ki-agenten-unternehmen-guide/cover.jpg',
},
{
slug: 'n8n-make-zapier-vergleich',
title: 'n8n vs Make vs Zapier: Which Automation Tool is Right for You?',
date: '2026-01-10',
excerpt: 'A detailed comparison of leading workflow automation tools with pros and cons for different use cases.',
category: 'Automation',
tags: ['n8n', 'Make', 'Zapier', 'Workflow', 'Automation', 'No-Code'],
coverImage: '/images/posts/n8n-make-zapier-vergleich/cover.jpg',
},
{
slug: 'voice-ai-kundenservice-trends',
title: 'Voice AI in Customer Service: Trends and Best Practices 2026',
date: '2026-01-05',
excerpt: 'How Voice AI is revolutionizing customer service and which technologies you should evaluate for your business.',
category: 'Voice AI',
tags: ['Voice AI', 'Voice Assistant', 'Customer Service', 'NLP', 'Chatbot', 'Vapi'],
coverImage: '/images/posts/voice-ai-kundenservice-trends/cover.jpg',
},
{
slug: 'saas-mvp-entwicklung-4-wochen',
title: 'SaaS MVP in 4 Weeks: From Idea to Launch',
date: '2025-12-20',
excerpt: 'Step-by-step guide to quickly developing a SaaS MVP with Next.js, Prisma and modern cloud services.',
category: 'SaaS Development',
tags: ['SaaS', 'MVP', 'Next.js', 'Startup', 'Product Development', 'React'],
coverImage: '/images/posts/saas-mvp-entwicklung-4-wochen/cover.jpg',
},
{
slug: 'erp-integration-breuninger',
title: 'ApparelMagic and TradeByte: Complex Integration Analysis',
date: '2024-02-09',
excerpt: 'Detailed analysis of an e-commerce integration between Apparel Magic and Breuninger via TradeByte',
category: 'System Integration',
tags: ['ERP', 'Apparel Magic', 'TradeByte', 'API Integration', 'Python', 'MariaDB'],
coverImage: '/images/posts/erp-integration-breuninger/cover.jpg',
},
],
sr: [
{
slug: 'n8n-automatisierung-tutorial',
title: 'n8n Tutorial: Automatizujte Radne Tokove Bez Koda - Korak po Korak',
date: '2026-01-18',
excerpt: 'Naučite kako da kreirate moćne automatizacije sa n8n. Od instalacije do prvog produktivnog radnog toka - uključujući najbolje prakse.',
category: 'Automatizacija',
tags: ['n8n', 'Tutorial', 'Automatizacija', 'Workflow', 'No-Code', 'Self-Hosted'],
coverImage: '/images/posts/n8n-automatisierung-tutorial/cover.jpg',
},
{
slug: 'geo-generative-engine-optimization',
title: 'GEO: Generative Engine Optimization - SEO za AI Eru',
date: '2026-01-17',
excerpt: 'Kako da optimizujete sadržaj za ChatGPT, Perplexity i druge AI pretraživače. Novi standard posle klasičnog SEO-a.',
category: 'Marketing',
tags: ['GEO', 'SEO', 'AI', 'ChatGPT', 'Perplexity', 'Content Marketing', 'AEO'],
coverImage: '/images/posts/geo-generative-engine-optimization/cover.jpg',
},
{
slug: 'gpt-api-integration-praxisguide',
title: 'GPT API Integracija: Od API Ključa do Produkcione Aplikacije',
date: '2026-01-16',
excerpt: 'Praktični vodič za integraciju OpenAI GPT-4 u vaše aplikacije. Optimizacija tokena, rukovanje greškama i najbolje prakse.',
category: 'AI Razvoj',
tags: ['GPT-4', 'OpenAI', 'API', 'Integracija', 'Python', 'LLM', 'Prompt Engineering'],
coverImage: '/images/posts/gpt-api-integration-praxisguide/cover.jpg',
},
{
slug: 'ki-agenten-unternehmen-guide',
title: 'AI Agenti za Preduzeća: Ultimativni Praktični Vodič 2026',
date: '2026-01-15',
excerpt: 'Kako kompanije mogu koristiti AI agente za automatizaciju procesa, smanjenje troškova i sticanje konkurentskih prednosti.',
category: 'AI Razvoj',
tags: ['AI Agenti', 'Automatizacija', 'GPT-4', 'Claude', 'LLM', 'Preduzeća'],
coverImage: '/images/posts/ki-agenten-unternehmen-guide/cover.jpg',
},
{
slug: 'n8n-make-zapier-vergleich',
title: 'n8n vs Make vs Zapier: Koji Alat za Automatizaciju je Pravi za Vas?',
date: '2026-01-10',
excerpt: 'Detaljna uporedna analiza vodećih alata za automatizaciju radnih tokova sa prednostima i manama za različite slučajeve upotrebe.',
category: 'Automatizacija',
tags: ['n8n', 'Make', 'Zapier', 'Workflow', 'Automatizacija', 'No-Code'],
coverImage: '/images/posts/n8n-make-zapier-vergleich/cover.jpg',
},
{
slug: 'voice-ai-kundenservice-trends',
title: 'Voice AI u Korisničkoj Službi: Trendovi i Najbolje Prakse 2026',
date: '2026-01-05',
excerpt: 'Kako Voice AI revolucioniše korisničku službu i koje tehnologije treba da evaluirate za vaš posao.',
category: 'Voice AI',
tags: ['Voice AI', 'Glasovni Asistent', 'Korisnička Služba', 'NLP', 'Chatbot', 'Vapi'],
coverImage: '/images/posts/voice-ai-kundenservice-trends/cover.jpg',
},
{
slug: 'saas-mvp-entwicklung-4-wochen',
title: 'SaaS MVP za 4 Nedelje: Od Ideje do Lansiranja',
date: '2025-12-20',
excerpt: 'Korak-po-korak vodič za brz razvoj SaaS MVP-a sa Next.js, Prisma i modernim cloud servisima.',
category: 'SaaS Razvoj',
tags: ['SaaS', 'MVP', 'Next.js', 'Startup', 'Razvoj Proizvoda', 'React'],
coverImage: '/images/posts/saas-mvp-entwicklung-4-wochen/cover.jpg',
},
{
slug: 'erp-integration-breuninger',
title: 'ApparelMagic i TradeByte: Analiza kompleksnih integracija',
date: '2024-02-09',
excerpt: 'Detaljna analiza e-commerce integracije izmedu Apparel Magic i Breuninger putem TradeByte',
category: 'Sistemska Integracija',
tags: ['ERP', 'Apparel Magic', 'TradeByte', 'API Integracija', 'Python', 'MariaDB'],
coverImage: '/images/posts/erp-integration-breuninger/cover.jpg',
},
],
};
+348
View File
@@ -0,0 +1,348 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { renderHook, waitFor } from '@testing-library/react';
import { useAsync } from './useAsync';
import * as errorHandling from '../utils/errorHandling';
// Mock the errorHandling module
vi.mock('../utils/errorHandling', async () => {
const actual = await vi.importActual('../utils/errorHandling');
return {
...actual,
handleError: vi.fn((error: unknown) => {
if (error instanceof Error) {
return error;
}
return new Error('Handled error');
})
};
});
describe('useAsync', () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe('initial state', () => {
it('should initialize with null data, null error, and loading false', () => {
const { result } = renderHook(() => useAsync<string>());
expect(result.current.data).toBeNull();
expect(result.current.error).toBeNull();
expect(result.current.loading).toBe(false);
});
it('should provide an execute function', () => {
const { result } = renderHook(() => useAsync<string>());
expect(result.current.execute).toBeInstanceOf(Function);
});
});
describe('loading states', () => {
it('should set loading to true when executing', async () => {
const { result } = renderHook(() => useAsync<string>());
const asyncFn = vi.fn(() => new Promise<string>((resolve) => {
setTimeout(() => resolve('test data'), 100);
}));
result.current.execute(asyncFn);
// Loading should be true immediately after execute is called
expect(result.current.loading).toBe(true);
expect(result.current.data).toBeNull();
expect(result.current.error).toBeNull();
await waitFor(() => {
expect(result.current.loading).toBe(false);
});
});
it('should set loading to false after successful execution', async () => {
const { result } = renderHook(() => useAsync<string>());
const asyncFn = vi.fn(async () => 'test data');
await result.current.execute(asyncFn);
expect(result.current.loading).toBe(false);
expect(result.current.data).toBe('test data');
expect(result.current.error).toBeNull();
});
it('should set loading to false after failed execution', async () => {
const { result } = renderHook(() => useAsync<string>());
const error = new Error('Test error');
const asyncFn = vi.fn(async () => {
throw error;
});
try {
await result.current.execute(asyncFn);
} catch (e) {
// Expected to throw
}
expect(result.current.loading).toBe(false);
expect(result.current.data).toBeNull();
expect(result.current.error).toBe(error);
});
it('should reset data and error when starting new execution', async () => {
const { result } = renderHook(() => useAsync<string>());
// First execution with data
await result.current.execute(async () => 'first data');
expect(result.current.data).toBe('first data');
expect(result.current.error).toBeNull();
// Second execution that will take some time
const slowAsyncFn = vi.fn(() => new Promise<string>((resolve) => {
setTimeout(() => resolve('second data'), 100);
}));
result.current.execute(slowAsyncFn);
// Immediately after calling execute, state should be reset
expect(result.current.data).toBeNull();
expect(result.current.error).toBeNull();
expect(result.current.loading).toBe(true);
await waitFor(() => {
expect(result.current.loading).toBe(false);
});
});
});
describe('data flow', () => {
it('should set data on successful execution', async () => {
const { result } = renderHook(() => useAsync<string>());
const testData = 'success data';
const asyncFn = vi.fn(async () => testData);
await result.current.execute(asyncFn);
expect(result.current.data).toBe(testData);
expect(result.current.error).toBeNull();
expect(result.current.loading).toBe(false);
expect(asyncFn).toHaveBeenCalledTimes(1);
});
it('should handle different data types', async () => {
// Test with number
const { result: numberResult } = renderHook(() => useAsync<number>());
await numberResult.current.execute(async () => 42);
expect(numberResult.current.data).toBe(42);
// Test with object
const { result: objectResult } = renderHook(() => useAsync<{ id: number; name: string }>());
const testObject = { id: 1, name: 'test' };
await objectResult.current.execute(async () => testObject);
expect(objectResult.current.data).toEqual(testObject);
// Test with array
const { result: arrayResult } = renderHook(() => useAsync<string[]>());
const testArray = ['a', 'b', 'c'];
await arrayResult.current.execute(async () => testArray);
expect(arrayResult.current.data).toEqual(testArray);
});
it('should return data from execute function', async () => {
const { result } = renderHook(() => useAsync<string>());
const testData = 'returned data';
const asyncFn = vi.fn(async () => testData);
const returnedData = await result.current.execute(asyncFn);
expect(returnedData).toBe(testData);
});
it('should handle null data', async () => {
const { result } = renderHook(() => useAsync<string | null>());
const asyncFn = vi.fn(async () => null);
await result.current.execute(asyncFn);
expect(result.current.data).toBeNull();
expect(result.current.error).toBeNull();
expect(result.current.loading).toBe(false);
});
it('should replace previous data with new data', async () => {
const { result } = renderHook(() => useAsync<string>());
await result.current.execute(async () => 'first');
expect(result.current.data).toBe('first');
await result.current.execute(async () => 'second');
expect(result.current.data).toBe('second');
await result.current.execute(async () => 'third');
expect(result.current.data).toBe('third');
});
});
describe('error handling', () => {
it('should set error on failed execution', async () => {
const { result } = renderHook(() => useAsync<string>());
const error = new Error('Test error');
const asyncFn = vi.fn(async () => {
throw error;
});
try {
await result.current.execute(asyncFn);
} catch (e) {
// Expected to throw
}
expect(result.current.data).toBeNull();
expect(result.current.error).toBe(error);
expect(result.current.loading).toBe(false);
});
it('should call handleError with error and context', async () => {
const { result } = renderHook(() => useAsync<string>());
const error = new Error('Test error');
const asyncFn = vi.fn(async () => {
throw error;
});
try {
await result.current.execute(asyncFn);
} catch (e) {
// Expected to throw
}
expect(errorHandling.handleError).toHaveBeenCalledWith(error, 'Async Operation');
});
it('should re-throw the handled error', async () => {
const { result } = renderHook(() => useAsync<string>());
const originalError = new Error('Test error');
const asyncFn = vi.fn(async () => {
throw originalError;
});
await expect(result.current.execute(asyncFn)).rejects.toThrow();
});
it('should handle errors of different types', async () => {
const { result } = renderHook(() => useAsync<string>());
// Test with Error object
const error1 = new Error('Error object');
await expect(result.current.execute(async () => {
throw error1;
})).rejects.toThrow();
// Test with string error
await expect(result.current.execute(async () => {
throw 'String error';
})).rejects.toThrow();
// Test with number error
await expect(result.current.execute(async () => {
throw 404;
})).rejects.toThrow();
});
it('should clear error on successful subsequent execution', async () => {
const { result } = renderHook(() => useAsync<string>());
// First execution fails
try {
await result.current.execute(async () => {
throw new Error('First error');
});
} catch (e) {
// Expected to throw
}
expect(result.current.error).not.toBeNull();
// Second execution succeeds
await result.current.execute(async () => 'success');
expect(result.current.error).toBeNull();
expect(result.current.data).toBe('success');
});
it('should replace previous error with new error', async () => {
const { result } = renderHook(() => useAsync<string>());
const error1 = new Error('First error');
const error2 = new Error('Second error');
// First execution fails
try {
await result.current.execute(async () => {
throw error1;
});
} catch (e) {
// Expected to throw
}
expect(result.current.error).toBe(error1);
// Second execution also fails
try {
await result.current.execute(async () => {
throw error2;
});
} catch (e) {
// Expected to throw
}
expect(result.current.error).toBe(error2);
});
});
describe('execute function stability', () => {
it('should maintain the same execute function reference', () => {
const { result, rerender } = renderHook(() => useAsync<string>());
const firstExecute = result.current.execute;
rerender();
const secondExecute = result.current.execute;
expect(firstExecute).toBe(secondExecute);
});
});
describe('concurrent executions', () => {
it('should handle multiple concurrent executions', async () => {
const { result } = renderHook(() => useAsync<string>());
const slowAsyncFn = vi.fn(() => new Promise<string>((resolve) => {
setTimeout(() => resolve('slow result'), 100);
}));
const fastAsyncFn = vi.fn(() => new Promise<string>((resolve) => {
setTimeout(() => resolve('fast result'), 10);
}));
// Start slow execution
const slowPromise = result.current.execute(slowAsyncFn);
// Start fast execution (will reset state)
const fastPromise = result.current.execute(fastAsyncFn);
// Fast one should complete
await fastPromise;
expect(result.current.data).toBe('fast result');
// Slow one should also complete, but will override the fast result
await slowPromise;
// Note: In the current implementation, the last executed function will set the final state
});
});
});
+235
View File
@@ -0,0 +1,235 @@
import { renderHook, act } from '@testing-library/react';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { useLocalStorage } from './useLocalStorage';
// Mock the error handling utility
vi.mock('../utils/errorHandling', () => ({
handleError: vi.fn()
}));
// Mock localStorage
const localStorageMock = (() => {
let store: Record<string, string> = {};
return {
getItem: (key: string) => store[key] || null,
setItem: (key: string, value: string) => {
store[key] = value.toString();
},
removeItem: (key: string) => {
delete store[key];
},
clear: () => {
store = {};
}
};
})();
describe('useLocalStorage', () => {
beforeEach(() => {
// Setup localStorage mock
Object.defineProperty(window, 'localStorage', {
value: localStorageMock,
writable: true
});
localStorageMock.clear();
});
afterEach(() => {
vi.clearAllMocks();
});
it('should return initial value when localStorage is empty', () => {
const { result } = renderHook(() => useLocalStorage('test-key', 'initial-value'));
const [value] = result.current;
expect(value).toBe('initial-value');
});
it('should return initial value from function when localStorage is empty', () => {
const initializer = vi.fn(() => 'computed-value');
const { result } = renderHook(() => useLocalStorage('test-key', initializer));
const [value] = result.current;
expect(value).toBe('computed-value');
expect(initializer).toHaveBeenCalled();
});
it('should set value in localStorage', () => {
const { result } = renderHook(() => useLocalStorage('test-key', 'initial'));
act(() => {
const [, setValue] = result.current;
setValue('new-value');
});
const [value] = result.current;
expect(value).toBe('new-value');
expect(JSON.parse(localStorage.getItem('test-key')!)).toBe('new-value');
});
it('should handle updater function in setValue', () => {
const { result } = renderHook(() => useLocalStorage('test-key', 10));
act(() => {
const [, setValue] = result.current;
setValue((prev) => prev + 5);
});
const [value] = result.current;
expect(value).toBe(15);
});
it('should read existing value from localStorage', () => {
localStorage.setItem('test-key', JSON.stringify('existing-value'));
const { result } = renderHook(() => useLocalStorage('test-key', 'initial-value'));
const [value] = result.current;
expect(value).toBe('existing-value');
});
it('should handle complex objects', () => {
const complexObject = { name: 'John', age: 30, hobbies: ['reading', 'coding'] };
const { result } = renderHook(() => useLocalStorage('test-key', complexObject));
act(() => {
const [, setValue] = result.current;
setValue({ ...complexObject, age: 31 });
});
const [value] = result.current;
expect(value).toEqual({ name: 'John', age: 31, hobbies: ['reading', 'coding'] });
});
it('should remove value from localStorage', () => {
localStorage.setItem('test-key', JSON.stringify('existing-value'));
const { result } = renderHook(() => useLocalStorage('test-key', 'initial-value'));
act(() => {
const [, , removeValue] = result.current;
removeValue();
});
const [value] = result.current;
expect(value).toBe('initial-value');
expect(localStorage.getItem('test-key')).toBeNull();
});
it('should handle invalid JSON in localStorage', () => {
localStorage.setItem('test-key', 'invalid-json{');
const { result } = renderHook(() => useLocalStorage('test-key', 'fallback-value'));
const [value] = result.current;
expect(value).toBe('fallback-value');
});
it('should be SSR-safe (no window)', () => {
const originalWindow = global.window;
// @ts-ignore - Temporarily remove window for SSR test
delete global.window;
const { result } = renderHook(() => useLocalStorage('test-key', 'ssr-value'));
const [value] = result.current;
expect(value).toBe('ssr-value');
// Restore window
global.window = originalWindow;
});
it('should handle localStorage quota exceeded', () => {
const { handleError } = require('../utils/errorHandling');
// Mock setItem to throw quota exceeded error
const originalSetItem = localStorage.setItem;
localStorage.setItem = vi.fn(() => {
throw new DOMException('QuotaExceededError');
});
const { result } = renderHook(() => useLocalStorage('test-key', 'initial'));
act(() => {
const [, setValue] = result.current;
setValue('new-value');
});
expect(handleError).toHaveBeenCalled();
// Restore original setItem
localStorage.setItem = originalSetItem;
});
it('should serialize and deserialize arrays', () => {
const initialArray = [1, 2, 3, 4, 5];
const { result } = renderHook(() => useLocalStorage('test-key', initialArray));
act(() => {
const [, setValue] = result.current;
setValue([...initialArray, 6]);
});
const [value] = result.current;
expect(value).toEqual([1, 2, 3, 4, 5, 6]);
expect(JSON.parse(localStorage.getItem('test-key')!)).toEqual([1, 2, 3, 4, 5, 6]);
});
it('should handle boolean values', () => {
const { result } = renderHook(() => useLocalStorage('test-key', false));
act(() => {
const [, setValue] = result.current;
setValue(true);
});
const [value] = result.current;
expect(value).toBe(true);
expect(JSON.parse(localStorage.getItem('test-key')!)).toBe(true);
});
it('should handle number values', () => {
const { result } = renderHook(() => useLocalStorage('test-key', 0));
act(() => {
const [, setValue] = result.current;
setValue(42);
});
const [value] = result.current;
expect(value).toBe(42);
expect(JSON.parse(localStorage.getItem('test-key')!)).toBe(42);
});
it('should handle null values', () => {
const { result } = renderHook(() => useLocalStorage<string | null>('test-key', null));
const [value] = result.current;
expect(value).toBe(null);
});
it('should update localStorage when key changes', () => {
const { result, rerender } = renderHook(
({ key, value }) => useLocalStorage(key, value),
{ initialProps: { key: 'key1', value: 'value1' } }
);
act(() => {
const [, setValue] = result.current;
setValue('updated-value1');
});
expect(localStorage.getItem('key1')).toBe(JSON.stringify('updated-value1'));
// Change the key
rerender({ key: 'key2', value: 'value2' });
act(() => {
const [, setValue] = result.current;
setValue('updated-value2');
});
expect(localStorage.getItem('key2')).toBe(JSON.stringify('updated-value2'));
});
});
+99
View File
@@ -0,0 +1,99 @@
import { useState, useEffect, useCallback } from 'react';
import { handleError } from '../utils/errorHandling';
/**
* Function type for updating the stored value
* @template T - The type of the stored value
* @param value - Either a new value of type T or an updater function that takes the current value and returns a new value
*/
type SetValue<T> = (value: T | ((val: T) => T)) => void;
/**
* Custom hook for managing state in localStorage with automatic serialization
*
* @template T - The type of the stored value
* @param {string} key - The localStorage key to use
* @param {T | (() => T)} initialValue - The initial value or a function that returns the initial value
* @returns {[T, SetValue<T>, () => void]} A tuple containing:
* - The current stored value
* - A function to update the stored value
* - A function to remove the value from storage
*
* @example
* ```tsx
* const [theme, setTheme, removeTheme] = useLocalStorage('theme', 'light');
* setTheme('dark'); // Updates both state and localStorage
* removeTheme(); // Removes from localStorage and resets to initial value
* ```
*
* @remarks
* - SSR-safe: Returns initial value during server-side rendering
* - Automatically serializes/deserializes JSON
* - Handles localStorage quota exceeded errors
* - Handles invalid JSON gracefully
*/
export function useLocalStorage<T>(
key: string,
initialValue: T | (() => T)
): [T, SetValue<T>, () => void] {
// Get initial value - SSR safe
const getInitialValue = useCallback((): T => {
// Check if we're in a browser environment
if (typeof window === 'undefined') {
return initialValue instanceof Function ? initialValue() : initialValue;
}
try {
const item = window.localStorage.getItem(key);
if (item) {
return JSON.parse(item) as T;
}
} catch (error) {
handleError(error, `LocalStorage Read (key: ${key})`);
}
return initialValue instanceof Function ? initialValue() : initialValue;
}, [key, initialValue]);
const [storedValue, setStoredValue] = useState<T>(getInitialValue);
// Update localStorage whenever storedValue changes
useEffect(() => {
if (typeof window === 'undefined') {
return;
}
try {
window.localStorage.setItem(key, JSON.stringify(storedValue));
} catch (error) {
handleError(error, `LocalStorage Write (key: ${key})`);
}
}, [key, storedValue]);
// Set value function that supports both direct values and updater functions
const setValue: SetValue<T> = useCallback((value) => {
try {
setStoredValue((prevValue) => {
const newValue = value instanceof Function ? value(prevValue) : value;
return newValue;
});
} catch (error) {
handleError(error, `LocalStorage Update (key: ${key})`);
}
}, [key]);
// Remove value from localStorage and reset to initial value
const removeValue = useCallback(() => {
try {
if (typeof window !== 'undefined') {
window.localStorage.removeItem(key);
}
const resetValue = initialValue instanceof Function ? initialValue() : initialValue;
setStoredValue(resetValue);
} catch (error) {
handleError(error, `LocalStorage Remove (key: ${key})`);
}
}, [key, initialValue]);
return [storedValue, setValue, removeValue];
}
+1 -1
View File
@@ -7,7 +7,7 @@ export const meta = {
keywords: [
// Name & Branding
'Damjan Savić',
'Damjan Savic',
'Damjan Savić',
'CoderConda',
// Voice AI & Agenten
+1 -1
View File
@@ -7,7 +7,7 @@ export const meta = {
keywords: [
// Name & Branding
'Damjan Savić',
'Damjan Savic',
'Damjan Savić',
'CoderConda',
// Voice AI & Agents
+463
View File
@@ -0,0 +1,463 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { getAllBlogPosts, getBlogPostBySlug, getBlogPostSlugs, type BlogPost } from './blog';
import fs from 'fs';
import path from 'path';
// Mock fs and path modules
vi.mock('fs');
vi.mock('path');
describe('blog', () => {
const mockBlogPostsDir = '/mock/blog-posts';
beforeEach(() => {
vi.clearAllMocks();
// Mock path.join to return predictable paths
vi.mocked(path.join).mockImplementation((...args) => args.join('/'));
// Mock process.cwd
vi.stubGlobal('process', {
...process,
cwd: () => '/mock'
});
});
describe('getAllBlogPosts', () => {
it('should return empty array when directory does not exist', () => {
vi.mocked(fs.existsSync).mockReturnValue(false);
const posts = getAllBlogPosts();
expect(posts).toEqual([]);
expect(fs.existsSync).toHaveBeenCalled();
});
it('should return empty array when directory is empty', () => {
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue([]);
const posts = getAllBlogPosts();
expect(posts).toEqual([]);
});
it('should parse and return blog posts from markdown files', () => {
const mockContent = `# Test Blog Post
**Meta-Description:** This is a test blog post about testing.
**Keywords:** testing, vitest, typescript
## Einführung
This is the introduction to the blog post. It provides an overview of what will be covered.
## Main Content
Here is the main content of the blog post.`;
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue(['001-test-blog-post.md'] as any);
vi.mocked(fs.readFileSync).mockReturnValue(mockContent);
const posts = getAllBlogPosts();
expect(posts).toHaveLength(1);
expect(posts[0]).toMatchObject({
slug: 'test-blog-post',
title: 'Test Blog Post',
excerpt: 'This is a test blog post about testing.',
tags: ['testing', 'vitest', 'typescript'],
category: 'Web Development'
});
expect(posts[0].date).toBe('2026-01-19');
expect(posts[0].coverImage).toBe('/images/posts/test-blog-post/cover.jpg');
expect(posts[0].content).toBe(mockContent);
});
it('should sort posts by date descending (newest first)', () => {
const mockContent1 = '# Post 1\n\n**Meta-Description:** First post';
const mockContent2 = '# Post 2\n\n**Meta-Description:** Second post';
const mockContent3 = '# Post 3\n\n**Meta-Description:** Third post';
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue([
'001-first-post.md',
'002-second-post.md',
'003-third-post.md'
] as any);
vi.mocked(fs.readFileSync)
.mockReturnValueOnce(mockContent1)
.mockReturnValueOnce(mockContent2)
.mockReturnValueOnce(mockContent3);
const posts = getAllBlogPosts();
expect(posts).toHaveLength(3);
// Posts should be sorted newest first (higher numbers = older posts)
expect(posts[0].slug).toBe('first-post');
expect(posts[1].slug).toBe('second-post');
expect(posts[2].slug).toBe('third-post');
expect(new Date(posts[0].date).getTime()).toBeGreaterThanOrEqual(new Date(posts[1].date).getTime());
expect(new Date(posts[1].date).getTime()).toBeGreaterThanOrEqual(new Date(posts[2].date).getTime());
});
it('should filter out non-markdown files', () => {
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue([
'001-test-post.md',
'README.txt',
'image.png',
'002-another-post.md',
'config.json'
] as any);
const mockContent = '# Test\n\n**Meta-Description:** Test';
vi.mocked(fs.readFileSync).mockReturnValue(mockContent);
const posts = getAllBlogPosts();
expect(posts).toHaveLength(2);
expect(fs.readFileSync).toHaveBeenCalledTimes(2);
});
it('should detect category from filename - AI Agents', () => {
const mockContent = '# AI Agent Post\n\n**Meta-Description:** About AI agents';
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue(['001-agentic-workflow.md'] as any);
vi.mocked(fs.readFileSync).mockReturnValue(mockContent);
const posts = getAllBlogPosts();
expect(posts[0].category).toBe('KI-Agenten');
});
it('should detect category from filename - Voice AI', () => {
const mockContent = '# Voice AI Post\n\n**Meta-Description:** About voice technology';
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue(['001-vapi-integration.md'] as any);
vi.mocked(fs.readFileSync).mockReturnValue(mockContent);
const posts = getAllBlogPosts();
expect(posts[0].category).toBe('Voice AI');
});
it('should detect category from content when not in filename', () => {
const mockContent = `# My Post
**Meta-Description:** A post about automation
I love using n8n for automation workflows.`;
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue(['001-my-post.md'] as any);
vi.mocked(fs.readFileSync).mockReturnValue(mockContent);
const posts = getAllBlogPosts();
expect(posts[0].category).toBe('Automatisierung');
});
it('should use default category when no keywords match', () => {
const mockContent = '# Generic Post\n\n**Meta-Description:** Generic content';
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue(['001-generic-post.md'] as any);
vi.mocked(fs.readFileSync).mockReturnValue(mockContent);
const posts = getAllBlogPosts();
expect(posts[0].category).toBe('Technologie');
});
it('should extract tags from keywords field', () => {
const mockContent = `# Test Post
**Meta-Description:** Test description
**Keywords:** javascript, typescript, testing, vitest, unit-tests, integration-tests, extra-tag`;
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue(['001-test.md'] as any);
vi.mocked(fs.readFileSync).mockReturnValue(mockContent);
const posts = getAllBlogPosts();
// Should limit to 6 tags
expect(posts[0].tags).toHaveLength(6);
expect(posts[0].tags).toEqual([
'javascript',
'typescript',
'testing',
'vitest',
'unit-tests',
'integration-tests'
]);
});
it('should handle posts without keywords', () => {
const mockContent = '# Test Post\n\n**Meta-Description:** Test';
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue(['001-test.md'] as any);
vi.mocked(fs.readFileSync).mockReturnValue(mockContent);
const posts = getAllBlogPosts();
expect(posts[0].tags).toEqual([]);
});
it('should use introduction as excerpt when meta description is missing', () => {
const mockContent = `# Test Post
## Einführung
This is a very long introduction that should be truncated to 200 characters. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris.
## Main Content`;
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue(['001-test.md'] as any);
vi.mocked(fs.readFileSync).mockReturnValue(mockContent);
const posts = getAllBlogPosts();
expect(posts[0].excerpt).toHaveLength(203); // 200 chars + '...'
expect(posts[0].excerpt).toContain('This is a very long introduction');
expect(posts[0].excerpt).toMatch(/\.\.\.$/);
});
it('should use title as excerpt when both meta description and introduction are missing', () => {
const mockContent = '# Test Post Title\n\nSome content';
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue(['001-test.md'] as any);
vi.mocked(fs.readFileSync).mockReturnValue(mockContent);
const posts = getAllBlogPosts();
expect(posts[0].excerpt).toBe('Test Post Title');
});
it('should handle posts without H1 title', () => {
const mockContent = 'No title here\n\n**Meta-Description:** Test';
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue(['001-fallback-title.md'] as any);
vi.mocked(fs.readFileSync).mockReturnValue(mockContent);
const posts = getAllBlogPosts();
expect(posts[0].title).toBe('001-fallback-title');
});
it('should skip posts that fail to parse', () => {
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue([
'001-good-post.md',
'002-bad-post.md'
] as any);
vi.mocked(fs.readFileSync)
.mockReturnValueOnce('# Good Post\n\n**Meta-Description:** Good')
.mockImplementationOnce(() => {
throw new Error('File read error');
});
const posts = getAllBlogPosts();
expect(posts).toHaveLength(1);
expect(posts[0].title).toBe('Good Post');
});
it('should generate correct dates based on post numbers', () => {
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue([
'001-first.md',
'005-fifth.md',
'010-tenth.md'
] as any);
const mockContent = '# Post\n\n**Meta-Description:** Test';
vi.mocked(fs.readFileSync).mockReturnValue(mockContent);
const posts = getAllBlogPosts();
// Post 001 should be 2026-01-19
expect(posts.find(p => p.slug === 'first')?.date).toBe('2026-01-19');
// Post 005 should be 4 days earlier (2026-01-15)
expect(posts.find(p => p.slug === 'fifth')?.date).toBe('2026-01-15');
// Post 010 should be 9 days earlier (2026-01-10)
expect(posts.find(p => p.slug === 'tenth')?.date).toBe('2026-01-10');
});
it('should trim whitespace from extracted fields', () => {
const mockContent = `# Test Post With Spaces
**Meta-Description:** Description with spaces
**Keywords:** tag1 , tag2 , tag3 `;
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue(['001-test.md'] as any);
vi.mocked(fs.readFileSync).mockReturnValue(mockContent);
const posts = getAllBlogPosts();
expect(posts[0].title).toBe('Test Post With Spaces');
expect(posts[0].excerpt).toBe('Description with spaces');
expect(posts[0].tags).toEqual(['tag1', 'tag2', 'tag3']);
});
});
describe('getBlogPostBySlug', () => {
it('should return post when slug matches', () => {
const mockContent = '# Test Post\n\n**Meta-Description:** Test';
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue(['001-test-post.md'] as any);
vi.mocked(fs.readFileSync).mockReturnValue(mockContent);
const post = getBlogPostBySlug('test-post');
expect(post).not.toBeNull();
expect(post?.slug).toBe('test-post');
expect(post?.title).toBe('Test Post');
});
it('should return null when slug does not match', () => {
const mockContent = '# Test Post\n\n**Meta-Description:** Test';
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue(['001-test-post.md'] as any);
vi.mocked(fs.readFileSync).mockReturnValue(mockContent);
const post = getBlogPostBySlug('non-existent-slug');
expect(post).toBeNull();
});
it('should return null when no posts exist', () => {
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue([]);
const post = getBlogPostBySlug('any-slug');
expect(post).toBeNull();
});
it('should return null when directory does not exist', () => {
vi.mocked(fs.existsSync).mockReturnValue(false);
const post = getBlogPostBySlug('any-slug');
expect(post).toBeNull();
});
it('should return correct post when multiple posts exist', () => {
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue([
'001-first-post.md',
'002-second-post.md',
'003-third-post.md'
] as any);
vi.mocked(fs.readFileSync)
.mockReturnValueOnce('# First Post\n\n**Meta-Description:** First')
.mockReturnValueOnce('# Second Post\n\n**Meta-Description:** Second')
.mockReturnValueOnce('# Third Post\n\n**Meta-Description:** Third');
const post = getBlogPostBySlug('second-post');
expect(post).not.toBeNull();
expect(post?.slug).toBe('second-post');
expect(post?.title).toBe('Second Post');
expect(post?.excerpt).toBe('Second');
});
it('should return post with all content included', () => {
const mockContent = `# Full Post
**Meta-Description:** Description
**Keywords:** tag1, tag2
## Einführung
Introduction text
## Main Content
This is the main content of the post with lots of details.`;
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue(['001-full-post.md'] as any);
vi.mocked(fs.readFileSync).mockReturnValue(mockContent);
const post = getBlogPostBySlug('full-post');
expect(post?.content).toBe(mockContent);
});
});
describe('getBlogPostSlugs', () => {
it('should return all post slugs', () => {
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue([
'001-first-post.md',
'002-second-post.md',
'003-third-post.md'
] as any);
const mockContent = '# Post\n\n**Meta-Description:** Test';
vi.mocked(fs.readFileSync).mockReturnValue(mockContent);
const slugs = getBlogPostSlugs();
expect(slugs).toHaveLength(3);
expect(slugs).toContain('first-post');
expect(slugs).toContain('second-post');
expect(slugs).toContain('third-post');
});
it('should return empty array when no posts exist', () => {
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue([]);
const slugs = getBlogPostSlugs();
expect(slugs).toEqual([]);
});
it('should return empty array when directory does not exist', () => {
vi.mocked(fs.existsSync).mockReturnValue(false);
const slugs = getBlogPostSlugs();
expect(slugs).toEqual([]);
});
it('should return slugs in date order (newest first)', () => {
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readdirSync).mockReturnValue([
'003-third.md',
'001-first.md',
'002-second.md'
] as any);
const mockContent = '# Post\n\n**Meta-Description:** Test';
vi.mocked(fs.readFileSync).mockReturnValue(mockContent);
const slugs = getBlogPostSlugs();
expect(slugs).toEqual(['first', 'second', 'third']);
});
});
});
+26 -6
View File
@@ -1,5 +1,6 @@
import fs from 'fs';
import path from 'path';
import { cache } from '@/utils/cache';
export interface BlogPost {
slug: string;
@@ -130,6 +131,14 @@ function parseMarkdownPost(filename: string, content: string): BlogPost | null {
}
export function getAllBlogPosts(): BlogPost[] {
const cacheKey = 'blog:all-posts';
// Check cache first
const cachedPosts = cache.get<BlogPost[]>(cacheKey);
if (cachedPosts) {
return cachedPosts;
}
if (!fs.existsSync(BLOG_POSTS_DIR)) {
console.warn('Blog posts directory not found:', BLOG_POSTS_DIR);
return [];
@@ -142,16 +151,27 @@ export function getAllBlogPosts(): BlogPost[] {
const posts: BlogPost[] = [];
for (const file of files) {
const filePath = path.join(BLOG_POSTS_DIR, file);
const content = fs.readFileSync(filePath, 'utf-8');
const post = parseMarkdownPost(file, content);
if (post) {
posts.push(post);
try {
const filePath = path.join(BLOG_POSTS_DIR, file);
const content = fs.readFileSync(filePath, 'utf-8');
const post = parseMarkdownPost(file, content);
if (post) {
posts.push(post);
}
} catch (error) {
// Skip files that fail to parse
console.warn(`Failed to parse blog post: ${file}`, error);
continue;
}
}
// Sort by date descending (newest first)
return posts.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
const sortedPosts = posts.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
// Cache the results
cache.set(cacheKey, sortedPosts);
return sortedPosts;
}
export function getBlogPostBySlug(slug: string): BlogPost | null {
+17
View File
@@ -0,0 +1,17 @@
const CSRF_META_TAG_NAME = 'csrf-token';
/**
* Get the CSRF token from the meta tag in the document head
* The server should render: <meta name="csrf-token" content="..." />
*/
export function getCsrfToken(): string | null {
if (typeof document === 'undefined') {
return null;
}
const metaTag = document.querySelector<HTMLMetaElement>(
`meta[name="${CSRF_META_TAG_NAME}"]`
);
return metaTag?.content || null;
}
+94
View File
@@ -0,0 +1,94 @@
import { cookies } from 'next/headers';
import { randomBytes } from 'crypto';
const CSRF_TOKEN_COOKIE_NAME = 'csrf_token';
const CSRF_TOKEN_LENGTH = 32;
/**
* Generate a cryptographically secure CSRF token
*/
export function generateCsrfToken(): string {
return randomBytes(CSRF_TOKEN_LENGTH).toString('base64url');
}
/**
* Get the current CSRF token from cookies or generate a new one
*/
export async function getCsrfToken(): Promise<string> {
const cookieStore = await cookies();
const existingToken = cookieStore.get(CSRF_TOKEN_COOKIE_NAME);
if (existingToken?.value) {
return existingToken.value;
}
const newToken = generateCsrfToken();
await setCsrfToken(newToken);
return newToken;
}
/**
* Set the CSRF token in an httpOnly cookie
*/
export async function setCsrfToken(token: string): Promise<void> {
const cookieStore = await cookies();
try {
cookieStore.set(CSRF_TOKEN_COOKIE_NAME, token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
maxAge: 60 * 60 * 24, // 24 hours
path: '/',
});
} catch {
// Handle server component context where cookies can't be set
}
}
/**
* Validate a CSRF token against the stored token in cookies
*/
export async function validateCsrfToken(token: string): Promise<boolean> {
const cookieStore = await cookies();
const storedToken = cookieStore.get(CSRF_TOKEN_COOKIE_NAME);
if (!storedToken?.value || !token) {
return false;
}
// Constant-time comparison to prevent timing attacks
return timingSafeEqual(
Buffer.from(storedToken.value),
Buffer.from(token)
);
}
/**
* Timing-safe string comparison to prevent timing attacks
*/
function timingSafeEqual(a: Buffer, b: Buffer): boolean {
if (a.length !== b.length) {
return false;
}
let result = 0;
for (let i = 0; i < a.length; i++) {
result |= a[i] ^ b[i];
}
return result === 0;
}
/**
* Delete the CSRF token cookie
*/
export async function deleteCsrfToken(): Promise<void> {
const cookieStore = await cookies();
try {
cookieStore.delete(CSRF_TOKEN_COOKIE_NAME);
} catch {
// Handle server component context
}
}
+1
View File
@@ -395,6 +395,7 @@
"placeholder": "Ihre Nachricht an mich..."
},
"submit": "Nachricht senden",
"submitting": "Nachricht wird gesendet...",
"successMessage": "Vielen Dank für Ihre Nachricht! Ich werde mich so schnell wie möglich bei Ihnen melden.",
"errorMessage": "Entschuldigung, beim Senden Ihrer Nachricht ist ein Fehler aufgetreten."
}
+1
View File
@@ -410,6 +410,7 @@
"placeholder": "Your message to me..."
},
"submit": "Send Message",
"submitting": "Sending message...",
"successMessage": "Thank you for your message! I will get back to you as soon as possible.",
"errorMessage": "Sorry, there was an error sending your message."
}
+1
View File
@@ -417,6 +417,7 @@
"placeholder": "Vasa poruka za mene..."
},
"submit": "Posalji poruku",
"submitting": "Slanje poruke...",
"successMessage": "Hvala vam na poruci! Javicu vam se sto je pre moguce.",
"errorMessage": "Izvinite, doslo je do greske prilikom slanja vase poruke."
}
+34 -1
View File
@@ -1,12 +1,45 @@
import { NextRequest, NextResponse } from 'next/server';
import createMiddleware from 'next-intl/middleware';
import { locales, defaultLocale } from './i18n/config';
import { randomBytes } from 'crypto';
export default createMiddleware({
const CSRF_TOKEN_COOKIE_NAME = 'csrf_token';
const CSRF_TOKEN_LENGTH = 32;
const intlMiddleware = createMiddleware({
locales,
defaultLocale,
localePrefix: 'always',
});
export default function middleware(request: NextRequest) {
// Run the i18n middleware first
const response = intlMiddleware(request);
// Check if CSRF token exists in cookies
const existingToken = request.cookies.get(CSRF_TOKEN_COOKIE_NAME);
// Generate and set CSRF token if it doesn't exist
if (!existingToken) {
const newToken = randomBytes(CSRF_TOKEN_LENGTH).toString('base64url');
// Create a new response or clone the existing one
const finalResponse = response || NextResponse.next();
finalResponse.cookies.set(CSRF_TOKEN_COOKIE_NAME, newToken, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
maxAge: 60 * 60 * 24, // 24 hours
path: '/',
});
return finalResponse;
}
return response;
}
export const config = {
matcher: [
'/',
+282
View File
@@ -0,0 +1,282 @@
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
import { cache } from './cache';
describe('Cache', () => {
beforeEach(() => {
vi.useFakeTimers();
cache.clear(); // Clear cache before each test
});
afterEach(() => {
vi.useRealTimers();
cache.clear(); // Clean up after each test
});
describe('set and get', () => {
it('should set and retrieve a value', () => {
cache.set('key', 'value');
expect(cache.get('key')).toBe('value');
});
it('should set multiple values with different keys', () => {
cache.set('key1', 'value1');
cache.set('key2', 'value2');
cache.set('key3', 'value3');
expect(cache.get('key1')).toBe('value1');
expect(cache.get('key2')).toBe('value2');
expect(cache.get('key3')).toBe('value3');
});
it('should overwrite existing value for same key', () => {
cache.set('key', 'value1');
expect(cache.get('key')).toBe('value1');
cache.set('key', 'value2');
expect(cache.get('key')).toBe('value2');
});
it('should return null for non-existing key', () => {
expect(cache.get('nonexistent')).toBeNull();
});
it('should store different types of values', () => {
cache.set('string', 'text');
cache.set('number', 42);
cache.set('boolean', true);
cache.set('object', { name: 'test' });
cache.set('array', [1, 2, 3]);
cache.set('null', null);
expect(cache.get('string')).toBe('text');
expect(cache.get('number')).toBe(42);
expect(cache.get('boolean')).toBe(true);
expect(cache.get('object')).toEqual({ name: 'test' });
expect(cache.get('array')).toEqual([1, 2, 3]);
expect(cache.get('null')).toBeNull();
});
});
describe('TTL expiration', () => {
it('should use default TTL of 5 minutes', () => {
cache.set('test', 'value');
// Should be available before TTL expires
expect(cache.get('test')).toBe('value');
// Advance time by 4 minutes 59 seconds
vi.advanceTimersByTime(4 * 60 * 1000 + 59 * 1000);
expect(cache.get('test')).toBe('value');
// Advance time by 2 more seconds (total 5 minutes 1 second)
vi.advanceTimersByTime(2 * 1000);
expect(cache.get('test')).toBeNull();
});
it('should accept custom TTL per item', () => {
cache.set('short', 'value', 1000); // 1 second TTL
cache.set('long', 'value', 10000); // 10 seconds TTL
// Both should be available initially
expect(cache.get('short')).toBe('value');
expect(cache.get('long')).toBe('value');
// After 1.5 seconds, short should expire but long should remain
vi.advanceTimersByTime(1500);
expect(cache.get('short')).toBeNull();
expect(cache.get('long')).toBe('value');
// After 9 more seconds (total 10.5), long should expire
vi.advanceTimersByTime(9000);
expect(cache.get('long')).toBeNull();
});
it('should return null for expired item', () => {
cache.set('key', 'value', 1000);
// Should be available initially
expect(cache.get('key')).toBe('value');
// Should be null after expiration
vi.advanceTimersByTime(1001);
expect(cache.get('key')).toBeNull();
});
it('should delete expired item from storage', () => {
cache.set('key', 'value', 1000);
// Item should exist
expect(cache.get('key')).toBe('value');
// After expiration, get should delete it
vi.advanceTimersByTime(1001);
expect(cache.get('key')).toBeNull();
// Subsequent get should also return null (item was deleted)
expect(cache.get('key')).toBeNull();
});
it('should return value at exact TTL boundary', () => {
cache.set('key', 'value', 1000);
// At exactly TTL time, should still be valid
vi.advanceTimersByTime(1000);
expect(cache.get('key')).toBe('value');
// One millisecond later, should expire
vi.advanceTimersByTime(1);
expect(cache.get('key')).toBeNull();
});
it('should respect different TTLs for different items', () => {
cache.set('item1', 'value1', 1000);
cache.set('item2', 'value2', 2000);
cache.set('item3', 'value3', 3000);
// All items should be available initially
expect(cache.get('item1')).toBe('value1');
expect(cache.get('item2')).toBe('value2');
expect(cache.get('item3')).toBe('value3');
// After 1.5 seconds, item1 should expire
vi.advanceTimersByTime(1500);
expect(cache.get('item1')).toBeNull();
expect(cache.get('item2')).toBe('value2');
expect(cache.get('item3')).toBe('value3');
// After 1 more second (total 2.5), item2 should expire
vi.advanceTimersByTime(1000);
expect(cache.get('item1')).toBeNull();
expect(cache.get('item2')).toBeNull();
expect(cache.get('item3')).toBe('value3');
// After 1 more second (total 3.5), item3 should expire
vi.advanceTimersByTime(1000);
expect(cache.get('item1')).toBeNull();
expect(cache.get('item2')).toBeNull();
expect(cache.get('item3')).toBeNull();
});
it('should reset TTL when item is overwritten', () => {
cache.set('key', 'value1', 1000);
// Advance time by 500ms
vi.advanceTimersByTime(500);
// Overwrite with new value and new TTL
cache.set('key', 'value2', 2000);
// After 1500ms more (total 2000ms from first set), should still be available
// because TTL was reset
vi.advanceTimersByTime(1500);
expect(cache.get('key')).toBe('value2');
// After 600ms more (2100ms from second set), should expire
vi.advanceTimersByTime(600);
expect(cache.get('key')).toBeNull();
});
it('should handle zero TTL', () => {
cache.set('key', 'value', 0);
// Should expire immediately
vi.advanceTimersByTime(1);
expect(cache.get('key')).toBeNull();
});
it('should handle very long TTL', () => {
const oneDayInMs = 24 * 60 * 60 * 1000;
cache.set('key', 'value', oneDayInMs);
// Should be available after 23 hours
vi.advanceTimersByTime(23 * 60 * 60 * 1000);
expect(cache.get('key')).toBe('value');
// Should still be available at exactly 24 hours
vi.advanceTimersByTime(60 * 60 * 1000);
expect(cache.get('key')).toBe('value');
// Should expire after 24 hours + 1ms
vi.advanceTimersByTime(1);
expect(cache.get('key')).toBeNull();
});
});
describe('has', () => {
it('should return true for existing key', () => {
cache.set('key', 'value');
expect(cache.has('key')).toBe(true);
});
it('should return false for non-existing key', () => {
expect(cache.has('nonexistent')).toBe(false);
});
it('should return false for expired key', () => {
cache.set('key', 'value', 1000);
expect(cache.has('key')).toBe(true);
vi.advanceTimersByTime(1001);
expect(cache.has('key')).toBe(false);
});
it('should return false for null values', () => {
cache.set('key', null);
expect(cache.has('key')).toBe(false);
});
});
describe('delete', () => {
it('should delete existing key', () => {
cache.set('key', 'value');
expect(cache.get('key')).toBe('value');
cache.delete('key');
expect(cache.get('key')).toBeNull();
});
it('should handle deleting non-existing key', () => {
expect(() => cache.delete('nonexistent')).not.toThrow();
expect(cache.get('nonexistent')).toBeNull();
});
it('should only delete specified key', () => {
cache.set('key1', 'value1');
cache.set('key2', 'value2');
cache.set('key3', 'value3');
cache.delete('key2');
expect(cache.get('key1')).toBe('value1');
expect(cache.get('key2')).toBeNull();
expect(cache.get('key3')).toBe('value3');
});
});
describe('clear', () => {
it('should clear all items from cache', () => {
cache.set('key1', 'value1');
cache.set('key2', 'value2');
cache.set('key3', 'value3');
cache.clear();
expect(cache.get('key1')).toBeNull();
expect(cache.get('key2')).toBeNull();
expect(cache.get('key3')).toBeNull();
});
it('should handle clearing empty cache', () => {
expect(() => cache.clear()).not.toThrow();
});
it('should allow setting items after clear', () => {
cache.set('key', 'value1');
cache.clear();
cache.set('key', 'value2');
expect(cache.get('key')).toBe('value2');
});
});
});
+2 -2
View File
@@ -22,7 +22,7 @@ export const CURRENT_ROLE = {
export const PROFILE = {
name: "Damjan Savić",
title: "AI & Automation Specialist",
subtitle: "Building AI agents and automation solutions",
title: "Fullstack Developer",
subtitle: "Building websites, apps and SaaS with Next.js, React and TypeScript",
languages: ["German", "English", "Serbian", "French", "Spanish", "Russian"]
} as const;
+165
View File
@@ -0,0 +1,165 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { AppError, errorCodes, handleError, createAPIError } from './errorHandling';
import * as analytics from './analytics';
// Mock the analytics module
vi.mock('./analytics', () => ({
trackEvent: vi.fn()
}));
describe('errorHandling', () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe('AppError', () => {
it('should create an AppError with all properties', () => {
const error = new AppError('Test error', 'TEST_CODE', 'error', { key: 'value' });
expect(error).toBeInstanceOf(Error);
expect(error).toBeInstanceOf(AppError);
expect(error.message).toBe('Test error');
expect(error.code).toBe('TEST_CODE');
expect(error.severity).toBe('error');
expect(error.metadata).toEqual({ key: 'value' });
expect(error.name).toBe('AppError');
});
it('should create an AppError with default severity', () => {
const error = new AppError('Test error', 'TEST_CODE');
expect(error.severity).toBe('error');
expect(error.metadata).toBeUndefined();
});
it('should create an AppError with warning severity', () => {
const error = new AppError('Test warning', 'TEST_CODE', 'warning');
expect(error.severity).toBe('warning');
});
it('should create an AppError with info severity', () => {
const error = new AppError('Test info', 'TEST_CODE', 'info');
expect(error.severity).toBe('info');
});
});
describe('errorCodes', () => {
it('should have all error codes defined', () => {
expect(errorCodes.NETWORK_ERROR).toBe('ERR_NETWORK');
expect(errorCodes.API_ERROR).toBe('ERR_API');
expect(errorCodes.AUTH_ERROR).toBe('ERR_AUTH');
expect(errorCodes.VALIDATION_ERROR).toBe('ERR_VALIDATION');
expect(errorCodes.UNKNOWN_ERROR).toBe('ERR_UNKNOWN');
});
});
describe('handleError', () => {
it('should handle AppError and return it unchanged', () => {
const originalError = new AppError('Test error', 'TEST_CODE', 'error', { foo: 'bar' });
const result = handleError(originalError, 'test-context');
expect(result).toBe(originalError);
expect(result.message).toBe('Test error');
expect(result.code).toBe('TEST_CODE');
expect(result.severity).toBe('error');
expect(result.metadata).toEqual({ foo: 'bar' });
expect(analytics.trackEvent).toHaveBeenCalledWith(
'Error',
'TEST_CODE',
'test-context: Test error'
);
});
it('should convert regular Error to AppError', () => {
const originalError = new Error('Regular error');
const result = handleError(originalError, 'test-context');
expect(result).toBeInstanceOf(AppError);
expect(result.message).toBe('Regular error');
expect(result.code).toBe(errorCodes.UNKNOWN_ERROR);
expect(result.severity).toBe('error');
expect(result.metadata).toEqual({ originalError });
expect(analytics.trackEvent).toHaveBeenCalledWith(
'Error',
errorCodes.UNKNOWN_ERROR,
'test-context: Regular error'
);
});
it('should handle unknown error types', () => {
const result = handleError('string error', 'test-context');
expect(result).toBeInstanceOf(AppError);
expect(result.message).toBe('An unexpected error occurred');
expect(result.code).toBe(errorCodes.UNKNOWN_ERROR);
expect(result.severity).toBe('error');
expect(result.metadata).toEqual({ originalError: 'string error' });
expect(analytics.trackEvent).toHaveBeenCalledWith(
'Error',
errorCodes.UNKNOWN_ERROR,
'test-context: An unexpected error occurred'
);
});
it('should handle null error', () => {
const result = handleError(null, 'test-context');
expect(result).toBeInstanceOf(AppError);
expect(result.message).toBe('An unexpected error occurred');
expect(result.code).toBe(errorCodes.UNKNOWN_ERROR);
expect(result.metadata).toEqual({ originalError: null });
});
it('should handle undefined error', () => {
const result = handleError(undefined, 'test-context');
expect(result).toBeInstanceOf(AppError);
expect(result.message).toBe('An unexpected error occurred');
expect(result.code).toBe(errorCodes.UNKNOWN_ERROR);
expect(result.metadata).toEqual({ originalError: undefined });
});
it('should track error in analytics', () => {
const error = new AppError('Analytics test', 'ANALYTICS_CODE');
handleError(error, 'analytics-context');
expect(analytics.trackEvent).toHaveBeenCalledTimes(1);
expect(analytics.trackEvent).toHaveBeenCalledWith(
'Error',
'ANALYTICS_CODE',
'analytics-context: Analytics test'
);
});
});
describe('createAPIError', () => {
it('should create an API error with status code', () => {
const error = createAPIError(404, 'Not found');
expect(error).toBeInstanceOf(AppError);
expect(error.message).toBe('Not found');
expect(error.code).toBe(errorCodes.API_ERROR);
expect(error.severity).toBe('error');
expect(error.metadata).toEqual({ status: 404 });
});
it('should create an API error for 500 status', () => {
const error = createAPIError(500, 'Internal server error');
expect(error).toBeInstanceOf(AppError);
expect(error.message).toBe('Internal server error');
expect(error.code).toBe(errorCodes.API_ERROR);
expect(error.metadata).toEqual({ status: 500 });
});
it('should create an API error for 401 status', () => {
const error = createAPIError(401, 'Unauthorized');
expect(error).toBeInstanceOf(AppError);
expect(error.message).toBe('Unauthorized');
expect(error.metadata).toEqual({ status: 401 });
});
});
});