diff --git a/.gitignore b/.gitignore index 4a5d92202..41d7c7960 100644 --- a/.gitignore +++ b/.gitignore @@ -174,3 +174,15 @@ _gs_split/ # Preserved local data archive (not the active profiles) /gamestringer_data_archive/ + +# Build e report locali: mai nel repo +native/build/ +release/*.msi +release/*.zip +release/*.exe +/dist/ +playwright-report/ +test-results/ +translation-audit-report.json +src-tauri/*.exe +src-tauri/*.pdb diff --git a/README.md b/README.md index 19e6d6f69..9d1e024f0 100644 --- a/README.md +++ b/README.md @@ -113,14 +113,16 @@ Get the latest release from **[GitHub Releases](https://github.com/rouges78/Game | Platform | File | Notes | |----------|------|-------| -| **Windows** | `GameStringer_1.15.0_x64-setup.exe` | Installer (recommended) | -| **Windows** | `GameStringer_1.15.0_x64-portable.zip` | No install needed | -| **Windows** | `GameStringer_1.15.0_x64_en-US.msi` | MSI alternative | -| **macOS** | `GameStringer_1.15.0_x64.dmg` | Intel Mac | -| **macOS** | `GameStringer_1.15.0_aarch64.dmg` | Apple Silicon | -| **Linux** | `GameStringer_1.15.0_amd64.AppImage` | Universal (recommended) | -| **Linux** | `GameStringer_1.15.0_amd64.deb` | Debian / Ubuntu | -| **Linux** | `GameStringer-1.15.0-1.x86_64.rpm` | Fedora / RHEL | +| **Windows** | `GameStringer_1.17.0_x64-setup.exe` | Installer (recommended) | +| **Windows** | `GameStringer_1.17.0_x64-portable.zip` | No install needed | +| **Windows** | `GameStringer_1.17.0_x64_en-US.msi` | MSI alternative | +| **macOS** | `GameStringer_1.17.0_x64.dmg` | Intel Mac | +| **macOS** | `GameStringer_1.17.0_aarch64.dmg` | Apple Silicon | +| **Linux** | `GameStringer_1.17.0_amd64.AppImage` | Universal (recommended) | +| **Linux** | `GameStringer_1.17.0_amd64.deb` | Debian / Ubuntu | +| **Linux** | `GameStringer-1.17.0-1.x86_64.rpm` | Fedora / RHEL | + +**Windows-only for now:** runtime translation (in-game hook, OCR overlay, screen capture) and the injector. The macOS and Linux builds include the library and the file-based methods, but String it has only been tested on Windows. **Requirements:** Windows 10+, macOS 10.15+, or Linux (Ubuntu 22.04+, Fedora 38+). 4 GB RAM (8 GB+ for local AI), 500 MB disk. Updates are **cryptographically signed** and delivered via Tauri Updater (the app verifies each update against a bundled public key). diff --git a/__tests__/components/notifications/notification-indicator.test.tsx b/__tests__/components/notifications/notification-indicator.test.tsx deleted file mode 100644 index 82419b0c9..000000000 --- a/__tests__/components/notifications/notification-indicator.test.tsx +++ /dev/null @@ -1,394 +0,0 @@ -import React from 'react'; -import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'; -import userEvent from '@testing-library/user-event'; -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import '@testing-library/jest-dom'; -import { NotificationIndicator } from '@/components/notifications/notification-indicator'; -import { useNotifications } from '@/hooks/use-notifications'; -import { announceNotificationCount } from '@/lib/notifications/notification-accessibility'; - -// Mock delle dipendenze -vi.mock('@/hooks/use-notifications', () => ({ - useNotifications: vi.fn() -})); - -vi.mock('@/lib/notifications/notification-accessibility', () => ({ - announceNotificationCount: vi.fn(), - createHelpText: vi.fn(() => 'Help text for notification indicator') -})); - -describe('NotificationIndicator', () => { - const mockUseNotifications = { - unreadCount: 0, - isLoading: false - }; - - beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(useNotifications).mockReturnValue(mockUseNotifications); - }); - - describe('Rendering', () => { - it('should render notification indicator', () => { - render(); - - const button = screen.getByRole('button'); - expect(button).toBeInTheDocument(); - expect(button).toHaveAttribute('type', 'button'); - }); - - it('should show bell icon when no notifications', () => { - render(); - - const button = screen.getByRole('button'); - expect(button).toHaveAttribute('aria-label', 'No unread notifications. Click to open notification center.'); - }); - - it('should show bell ring icon when has notifications', () => { - vi.mocked(useNotifications).mockReturnValue({ - ...mockUseNotifications, - unreadCount: 3 - }); - - render(); - - const button = screen.getByRole('button'); - expect(button).toHaveAttribute('aria-label', '3 unread notifications. Click to open notification center.'); - }); - - it('should show loading state', () => { - vi.mocked(useNotifications).mockReturnValue({ - ...mockUseNotifications, - isLoading: true - }); - - render(); - - const button = screen.getByRole('button'); - expect(button).toBeDisabled(); - expect(button).toHaveAttribute('aria-label', 'Loading notifications...'); - }); - }); - - describe('Badge Display', () => { - // Il badge attuale è un marker di alert ('!', aria-hidden): il conteggio - // è esposto via aria-label e descrizione sr-only, non come testo visibile. - it('should show alert badge when has notifications', () => { - vi.mocked(useNotifications).mockReturnValue({ - ...mockUseNotifications, - unreadCount: 5 - }); - - render(); - - expect(screen.getByText('!')).toBeInTheDocument(); - expect(screen.getByText('You have 5 unread notifications')).toBeInTheDocument(); - }); - - it('should expose the full count via aria-label when count exceeds maxCount', () => { - vi.mocked(useNotifications).mockReturnValue({ - ...mockUseNotifications, - unreadCount: 150 - }); - - render(); - - expect(screen.getByText('!')).toBeInTheDocument(); - expect(screen.getByRole('button')).toHaveAttribute( - 'aria-label', - '150 unread notifications. Click to open notification center.' - ); - }); - - it('should not show badge when showBadge is false', () => { - vi.mocked(useNotifications).mockReturnValue({ - ...mockUseNotifications, - unreadCount: 5 - }); - - render(); - - expect(screen.queryByText('5')).not.toBeInTheDocument(); - // Should show simple indicator dot instead - const button = screen.getByRole('button'); - const indicator = button.querySelector('.bg-red-500'); - expect(indicator).toBeInTheDocument(); - }); - - it('should not show badge when no notifications', () => { - render(); - - expect(screen.queryByText(/\d+/)).not.toBeInTheDocument(); - }); - }); - - describe('User Interactions', () => { - it('should call onClick when clicked', async () => { - const mockOnClick = vi.fn(); - const user = userEvent.setup(); - - render(); - - const button = screen.getByRole('button'); - await user.click(button); - - expect(mockOnClick).toHaveBeenCalled(); - }); - - it('should not call onClick when disabled', async () => { - const mockOnClick = vi.fn(); - const user = userEvent.setup(); - - vi.mocked(useNotifications).mockReturnValue({ - ...mockUseNotifications, - isLoading: true - }); - - render(); - - const button = screen.getByRole('button'); - await user.click(button); - - expect(mockOnClick).not.toHaveBeenCalled(); - }); - - it('should be keyboard accessible', async () => { - const mockOnClick = vi.fn(); - const user = userEvent.setup(); - - render(); - - const button = screen.getByRole('button'); - button.focus(); - await user.keyboard('{Enter}'); - - expect(mockOnClick).toHaveBeenCalled(); - }); - }); - - describe('Animations', () => { - beforeEach(() => { - vi.useFakeTimers(); - }); - - afterEach(() => { - vi.useRealTimers(); - }); - - // L'animazione attuale è 'animate-bounce' sull'icona BellRing - // (più 'scale-110' sul badge), non 'animate-pulse' sul bottone. - it('should animate when new notifications arrive', () => { - const { rerender } = render(); - - // Update with new notifications - vi.mocked(useNotifications).mockReturnValue({ - ...mockUseNotifications, - unreadCount: 2 - }); - - rerender(); - - const icon = screen.getByRole('button').querySelector('svg'); - expect(icon).toHaveClass('animate-bounce'); - - // Animation should stop after timeout - act(() => { - vi.advanceTimersByTime(1000); - }); - expect(screen.getByRole('button').querySelector('svg')).not.toHaveClass('animate-bounce'); - }); - - it('should not animate when animate is false', () => { - const { rerender } = render(); - - // Update with new notifications - vi.mocked(useNotifications).mockReturnValue({ - ...mockUseNotifications, - unreadCount: 2 - }); - - rerender(); - - const icon = screen.getByRole('button').querySelector('svg'); - expect(icon).not.toHaveClass('animate-bounce'); - }); - - it('should show animated indicator for new notifications', () => { - const { rerender } = render(); - - // Update with new notifications - vi.mocked(useNotifications).mockReturnValue({ - ...mockUseNotifications, - unreadCount: 1 - }); - - rerender(); - - // Il badge di alert viene ingrandito durante l'animazione - const badge = screen.getByText('!'); - expect(badge).toHaveClass('scale-110'); - }); - }); - - describe('Accessibility', () => { - it('should have proper ARIA attributes', () => { - render(); - - const button = screen.getByRole('button'); - expect(button).toHaveAttribute('aria-describedby', 'notification-help'); - }); - - it('should have proper ARIA attributes with notifications', () => { - vi.mocked(useNotifications).mockReturnValue({ - ...mockUseNotifications, - unreadCount: 3 - }); - - render(); - - const button = screen.getByRole('button'); - expect(button).toHaveAttribute('aria-describedby', 'notification-count-description notification-help'); - }); - - it('should have hidden description for screen readers', () => { - vi.mocked(useNotifications).mockReturnValue({ - ...mockUseNotifications, - unreadCount: 1 - }); - - render(); - - expect(screen.getByText('You have 1 unread notification')).toHaveClass('sr-only'); - }); - - it('should have plural description for multiple notifications', () => { - vi.mocked(useNotifications).mockReturnValue({ - ...mockUseNotifications, - unreadCount: 5 - }); - - render(); - - expect(screen.getByText('You have 5 unread notifications')).toHaveClass('sr-only'); - }); - - it('should announce new notifications to screen readers', () => { - const { rerender } = render(); - - // Update with new notifications - vi.mocked(useNotifications).mockReturnValue({ - ...mockUseNotifications, - unreadCount: 2 - }); - - rerender(); - - expect(vi.mocked(announceNotificationCount)).toHaveBeenCalledWith(2, 0); - }); - - it('should have focus styles', () => { - render(); - - const button = screen.getByRole('button'); - expect(button).toHaveClass('focus:outline-none', 'focus:ring-2', 'focus:ring-primary/50'); - }); - }); - - describe('Custom Styling', () => { - it('should apply custom className', () => { - render(); - - const button = screen.getByRole('button'); - expect(button).toHaveClass('custom-class'); - }); - - it('should maintain base classes with custom className', () => { - render(); - - const button = screen.getByRole('button'); - expect(button).toHaveClass('custom-class'); - expect(button).toHaveClass('relative', 'h-8', 'w-8', 'rounded-full'); - }); - }); - - describe('Badge Variants', () => { - it('should show red alert badge by default', () => { - vi.mocked(useNotifications).mockReturnValue({ - ...mockUseNotifications, - unreadCount: 1 - }); - - render(); - - const badge = screen.getByText('!'); - expect(badge).toHaveClass('bg-red-500'); - }); - - it('should handle zero count correctly', () => { - render(); - - expect(screen.queryByText('0')).not.toBeInTheDocument(); - }); - }); - - describe('Performance', () => { - it('should not re-render unnecessarily', () => { - const renderSpy = vi.fn(); - const TestComponent = () => { - renderSpy(); - return ; - }; - - const { rerender } = render(); - - // Same props should not cause re-render - rerender(); - - expect(renderSpy).toHaveBeenCalledTimes(2); // Initial + rerender - }); - }); - - describe('Edge Cases', () => { - it('should handle negative unread count', () => { - vi.mocked(useNotifications).mockReturnValue({ - ...mockUseNotifications, - unreadCount: -1 - }); - - render(); - - // Should treat negative as zero - const button = screen.getByRole('button'); - expect(button).toHaveAttribute('aria-label', 'No unread notifications. Click to open notification center.'); - }); - - it('should handle very large unread count', () => { - vi.mocked(useNotifications).mockReturnValue({ - ...mockUseNotifications, - unreadCount: 999999 - }); - - render(); - - // Il badge è un marker '!': il conteggio completo resta nell'aria-label - expect(screen.getByText('!')).toBeInTheDocument(); - expect(screen.getByRole('button')).toHaveAttribute( - 'aria-label', - '999999 unread notifications. Click to open notification center.' - ); - }); - - it('should handle undefined unread count', () => { - vi.mocked(useNotifications).mockReturnValue({ - ...mockUseNotifications, - unreadCount: undefined - }); - - render(); - - // Should treat undefined as zero - const button = screen.getByRole('button'); - expect(button).toHaveAttribute('aria-label', 'No unread notifications. Click to open notification center.'); - }); - }); -}); diff --git a/__tests__/components/translation-batch-editor-toasts.test.tsx b/__tests__/components/translation-batch-editor-toasts.test.tsx deleted file mode 100644 index e0bad7b44..000000000 --- a/__tests__/components/translation-batch-editor-toasts.test.tsx +++ /dev/null @@ -1,63 +0,0 @@ -import React from 'react'; -import { render, screen, fireEvent, waitFor } from '@testing-library/react'; -import { describe, it, expect, vi, beforeEach } from 'vitest'; - -const { toastMock } = vi.hoisted(() => ({ - toastMock: { success: vi.fn(), error: vi.fn() }, -})); - -vi.mock('sonner', () => ({ toast: toastMock })); - -import { TranslationBatchEditor } from '@/components/translation-batch-editor'; - -const translations = [ - { id: 't1', originalText: 'Hello', translatedText: 'Ciao', status: 'completed', filePath: 'a/b.txt' }, -]; - -function renderEditor(onSave = vi.fn().mockResolvedValue(undefined)) { - render( - - ); - fireEvent.click(screen.getByRole('checkbox')); -} - -function setClipboard(writeText: () => Promise) { - Object.defineProperty(navigator, 'clipboard', { value: { writeText, readText: vi.fn() }, configurable: true }); -} - -describe('TranslationBatchEditor toasts (sonner)', () => { - beforeEach(() => { - toastMock.success.mockReset(); - toastMock.error.mockReset(); - }); - - it('confirms the copy only after the clipboard accepted it', async () => { - setClipboard(vi.fn().mockResolvedValue(undefined)); - renderEditor(); - - fireEvent.click(screen.getByRole('button', { name: /Copy Originals/ })); - - await waitFor(() => expect(toastMock.success).toHaveBeenCalledWith('common.copiatoNegliAppunti', { description: 'common.originalsCopiedCount' })); - expect(toastMock.error).not.toHaveBeenCalled(); - }); - - it('reports a clipboard failure instead of a fake success', async () => { - setClipboard(vi.fn().mockRejectedValue(new Error('denied'))); - renderEditor(); - - fireEvent.click(screen.getByRole('button', { name: /Copy Originals/ })); - - await waitFor(() => expect(toastMock.error).toHaveBeenCalledWith('feedback.copyFailed')); - expect(toastMock.success).not.toHaveBeenCalled(); - }); - - it('reports a failed save as an error, not success', async () => { - renderEditor(vi.fn().mockRejectedValue(new Error('io'))); - - fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Salve' } }); - fireEvent.click(screen.getByRole('button', { name: /Save Selected/ })); - - await waitFor(() => expect(toastMock.error).toHaveBeenCalledWith('common.impossibileSalvareLeTraduzioni')); - expect(toastMock.success).not.toHaveBeenCalled(); - }); -}); diff --git a/__tests__/lib/api-schemas.test.ts b/__tests__/lib/api-schemas.test.ts deleted file mode 100644 index 80183f1b5..000000000 --- a/__tests__/lib/api-schemas.test.ts +++ /dev/null @@ -1,244 +0,0 @@ -import { describe, it, expect } from 'vitest'; -import { - translateRequestSchema, - batchTranslateRequestSchema, - secretsRequestSchema, - dictionaryAddSchema, - validateBody, -} from '@/lib/api-schemas'; - -describe('translateRequestSchema', () => { - it('should accept valid translation request', () => { - const result = validateBody(translateRequestSchema, { - text: 'Hello world', - targetLanguage: 'it', - }); - expect(result.success).toBe(true); - if (result.success) { - expect(result.data.text).toBe('Hello world'); - expect(result.data.targetLanguage).toBe('it'); - expect(result.data.sourceLanguage).toBe('auto'); - expect(result.data.provider).toBe('openai'); - } - }); - - it('should reject empty text', () => { - const result = validateBody(translateRequestSchema, { - text: '', - targetLanguage: 'it', - }); - expect(result.success).toBe(false); - }); - - it('should reject missing targetLanguage', () => { - const result = validateBody(translateRequestSchema, { - text: 'Hello', - }); - expect(result.success).toBe(false); - }); - - it('should reject text exceeding 50000 chars', () => { - const result = validateBody(translateRequestSchema, { - text: 'a'.repeat(50001), - targetLanguage: 'it', - }); - expect(result.success).toBe(false); - if (!result.success) { - expect(result.error).toContain('50000'); - } - }); - - it('should accept valid provider', () => { - const result = validateBody(translateRequestSchema, { - text: 'Hello', - targetLanguage: 'en', - provider: 'gemini', - }); - expect(result.success).toBe(true); - }); - - it('should reject context exceeding 5000 chars', () => { - const result = validateBody(translateRequestSchema, { - text: 'Hello', - targetLanguage: 'it', - context: 'x'.repeat(5001), - }); - expect(result.success).toBe(false); - }); - - it('should accept optional apiKey', () => { - const result = validateBody(translateRequestSchema, { - text: 'Hello', - targetLanguage: 'it', - apiKey: 'sk-test-key-123', - }); - expect(result.success).toBe(true); - }); -}); - -describe('batchTranslateRequestSchema', () => { - it('should accept valid batch request', () => { - const result = validateBody(batchTranslateRequestSchema, { - texts: ['Hello', 'World'], - targetLanguage: 'it', - }); - expect(result.success).toBe(true); - if (result.success) { - expect(result.data.texts).toHaveLength(2); - } - }); - - it('should reject empty texts array', () => { - const result = validateBody(batchTranslateRequestSchema, { - texts: [], - targetLanguage: 'it', - }); - expect(result.success).toBe(false); - }); - - it('should reject more than 20 texts', () => { - const result = validateBody(batchTranslateRequestSchema, { - texts: Array(21).fill('text'), - targetLanguage: 'it', - }); - expect(result.success).toBe(false); - }); - - it('should reject non-array texts', () => { - const result = validateBody(batchTranslateRequestSchema, { - texts: 'not an array', - targetLanguage: 'it', - }); - expect(result.success).toBe(false); - }); - - it('should reject individual text exceeding limit', () => { - const result = validateBody(batchTranslateRequestSchema, { - texts: ['a'.repeat(50001)], - targetLanguage: 'it', - }); - expect(result.success).toBe(false); - }); -}); - -describe('secretsRequestSchema', () => { - it('should accept valid API key name', () => { - const result = validateBody(secretsRequestSchema, { - key: 'OPENAI_API_KEY', - value: 'sk-test-123', - }); - expect(result.success).toBe(true); - }); - - it('should reject invalid API key name', () => { - const result = validateBody(secretsRequestSchema, { - key: 'INVALID_KEY', - value: 'test', - }); - expect(result.success).toBe(false); - }); - - it('should accept all allowed key names', () => { - const allowedKeys = [ - 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'GEMINI_API_KEY', - 'DEEPSEEK_API_KEY', 'MISTRAL_API_KEY', 'OPENROUTER_API_KEY', - ]; - for (const key of allowedKeys) { - const result = validateBody(secretsRequestSchema, { key, value: 'test' }); - expect(result.success).toBe(true); - } - }); - - it('should reject value exceeding 256 chars', () => { - const result = validateBody(secretsRequestSchema, { - key: 'OPENAI_API_KEY', - value: 'a'.repeat(257), - }); - expect(result.success).toBe(false); - }); - - it('should default value to empty string', () => { - const result = validateBody(secretsRequestSchema, { - key: 'OPENAI_API_KEY', - }); - expect(result.success).toBe(true); - if (result.success) { - expect(result.data.value).toBe(''); - } - }); -}); - -describe('dictionaryAddSchema', () => { - it('should accept valid dictionary entry', () => { - const result = validateBody(dictionaryAddSchema, { - original: 'Hello', - translated: 'Ciao', - gameId: 'game-123', - targetLanguage: 'it', - }); - expect(result.success).toBe(true); - }); - - it('should reject empty original text', () => { - const result = validateBody(dictionaryAddSchema, { - original: '', - translated: 'Ciao', - }); - expect(result.success).toBe(false); - }); - - it('should reject empty translated text', () => { - const result = validateBody(dictionaryAddSchema, { - original: 'Hello', - translated: '', - }); - expect(result.success).toBe(false); - }); - - it('should reject original exceeding 10000 chars', () => { - const result = validateBody(dictionaryAddSchema, { - original: 'a'.repeat(10001), - translated: 'Ciao', - }); - expect(result.success).toBe(false); - }); - - it('should default targetLanguage to it', () => { - const result = validateBody(dictionaryAddSchema, { - original: 'Hello', - translated: 'Ciao', - }); - expect(result.success).toBe(true); - if (result.success) { - expect(result.data.targetLanguage).toBe('it'); - } - }); -}); - -describe('validateBody', () => { - it('should return success with parsed data on valid input', () => { - const result = validateBody(translateRequestSchema, { - text: 'test', - targetLanguage: 'en', - }); - expect(result.success).toBe(true); - }); - - it('should return error message on invalid input', () => { - const result = validateBody(translateRequestSchema, {}); - expect(result.success).toBe(false); - if (!result.success) { - expect(typeof result.error).toBe('string'); - expect(result.error.length).toBeGreaterThan(0); - } - }); - - it('should include field path in error messages', () => { - const result = validateBody(translateRequestSchema, { text: 123 }); - expect(result.success).toBe(false); - if (!result.success) { - expect(result.error).toContain('text'); - } - }); -}); - diff --git a/__tests__/lib/auth-bridge-secret.test.ts b/__tests__/lib/auth-bridge-secret.test.ts new file mode 100644 index 000000000..f7924f85c --- /dev/null +++ b/__tests__/lib/auth-bridge-secret.test.ts @@ -0,0 +1,231 @@ +/** + * Ponte auth community: la password dell'account Supabase è un segreto casuale + * per profilo, non più la vecchia password derivata dall'ID GS (indovinabile). + * - primo accesso: segreto generato, salvato, usato per il sign-up e poi riusato; + * - account legacy: accesso una sola volta con la password derivata, rotazione + * immediata via updateUser, e da lì in poi la password legacy non si usa più. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; + +const GS_ID = 'profile-42'; +const EMAIL = `gs_${GS_ID}@gamestringer.local`; +const LEGACY = `gs_community_${GS_ID}_!Str1ng3r`; + +type AuthResult = { data: Record; error: { message: string; status?: number } | null }; + +const state = vi.hoisted(() => ({ + client: null as unknown, + secureStore: new Map(), + secureReadFails: false, +})); + +vi.mock('@/lib/social/community-hub-backend', () => ({ + getSupabase: async () => state.client, + isBackendEnabled: () => true, +})); +vi.mock('@/lib/client-logger', () => ({ + clientLogger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})); +vi.mock('@/lib/secure-key-store', () => ({ + getSecureKey: async (name: string) => { + if (state.secureReadFails) throw new Error('Decryption failed'); + return state.secureStore.get(name) ?? null; + }, + setSecureKey: async (name: string, value: string) => { state.secureStore.set(name, value); }, + removeSecureKey: async (name: string) => { state.secureStore.delete(name); }, +})); + +/** + * Finto GoTrue: un solo account per email con la sua password; tiene traccia di + * ogni password provata e delle chiamate updateUser. + */ +function fakeSupabase(opts: { existingPassword?: string } = {}) { + let password = opts.existingPassword ?? null; + let session = false; + const uid = 'uid-supabase'; + const signInPasswords: string[] = []; + const signUpPasswords: string[] = []; + const updateUser = vi.fn(async ({ password: next }: { password: string }): Promise => { + if (!session) return { data: {}, error: { message: 'not authenticated' } }; + password = next; + return { data: { user: { id: uid } }, error: null }; + }); + const builder = { + select: () => builder, + eq: () => builder, + maybeSingle: async () => ({ data: { id: uid }, error: null }), + }; + const client = { + auth: { + getUser: async () => ({ data: { user: session ? { id: uid } : null } }), + signInWithPassword: async ({ email, password: p }: { email: string; password: string }): Promise => { + signInPasswords.push(p); + if (email === EMAIL && password !== null && p === password) { + session = true; + return { data: { user: { id: uid }, session: {} }, error: null }; + } + return { data: { user: null, session: null }, error: { message: 'Invalid login credentials', status: 400 } }; + }, + signUp: async ({ password: p }: { password: string }): Promise => { + signUpPasswords.push(p); + if (password !== null) return { data: {}, error: { message: 'User already registered', status: 422 } }; + password = p; + session = true; + return { data: { user: { id: uid }, session: {} }, error: null }; + }, + updateUser, + signOut: async () => { session = false; }, + }, + from: () => builder, + rpc: async () => ({ data: null, error: null }), + }; + return { + client, + signInPasswords, + signUpPasswords, + updateUser, + serverPassword: () => password, + endSession: () => { session = false; }, + }; +} + +async function runSync(): Promise { + const { autoSyncGSToSupabase } = await import('@/lib/social/auth-bridge'); + return autoSyncGSToSupabase(); +} + +const secretKeyName = `COMMUNITY_AUTH_SECRET_${GS_ID}`; + +beforeEach(() => { + vi.resetModules(); + localStorage.clear(); + state.secureStore.clear(); + state.secureReadFails = false; + localStorage.setItem('gamestringer_current_profile', JSON.stringify({ id: GS_ID, name: 'Tester' })); +}); + +afterEach(() => { + delete (window as unknown as Record).__TAURI_INTERNALS__; +}); + +describe('segreto community per profilo', () => { + it('primo accesso: genera un segreto casuale (≥32 byte, base64url), lo salva e lo riusa', async () => { + const sb = fakeSupabase(); + state.client = sb.client; + + expect(await runSync()).toBe('uid-supabase'); + + const secret = localStorage.getItem(`communityBridge:secret:${GS_ID}`); + expect(secret).toMatch(/^[A-Za-z0-9_-]{43,}$/); + expect(secret).not.toContain(GS_ID); + expect(sb.signUpPasswords).toEqual([secret]); + expect(sb.serverPassword()).toBe(secret); + + // Nuovo avvio, sessione scaduta → stesso segreto, nessun nuovo sign-up. + sb.endSession(); + vi.resetModules(); + expect(await runSync()).toBe('uid-supabase'); + expect(localStorage.getItem(`communityBridge:secret:${GS_ID}`)).toBe(secret); + expect(sb.signInPasswords.at(-1)).toBe(secret); + expect(sb.signUpPasswords).toHaveLength(1); + }); + + it('in Tauri il segreto va nello store cifrato, non in localStorage', async () => { + (window as unknown as Record).__TAURI_INTERNALS__ = {}; + const sb = fakeSupabase(); + state.client = sb.client; + + expect(await runSync()).toBe('uid-supabase'); + + const secret = state.secureStore.get(secretKeyName); + expect(secret).toMatch(/^[A-Za-z0-9_-]{43,}$/); + expect(localStorage.getItem(`communityBridge:secret:${GS_ID}`)).toBeNull(); + expect(sb.serverPassword()).toBe(secret); + }); + + it('store cifrato illeggibile → nessun nuovo segreto né sign-up (non sovrascrive quello vero)', async () => { + (window as unknown as Record).__TAURI_INTERNALS__ = {}; + state.secureStore.set(secretKeyName, 'segreto-vero'); + state.secureReadFails = true; + const sb = fakeSupabase({ existingPassword: 'segreto-vero' }); + state.client = sb.client; + + expect(await runSync()).toBeNull(); + expect(sb.signInPasswords).toHaveLength(0); + expect(sb.signUpPasswords).toHaveLength(0); + expect(state.secureStore.get(secretKeyName)).toBe('segreto-vero'); + }); + + it('due profili non condividono mai lo stesso segreto', async () => { + const a = fakeSupabase(); + state.client = a.client; + await runSync(); + const s1 = localStorage.getItem(`communityBridge:secret:${GS_ID}`); + + localStorage.removeItem(`communityBridge:secret:${GS_ID}`); + const b = fakeSupabase(); + state.client = b.client; + vi.resetModules(); + await runSync(); + const s2 = localStorage.getItem(`communityBridge:secret:${GS_ID}`); + expect(s1).not.toBe(s2); + }); +}); + +describe('migrazione account legacy', () => { + it('accede con la password derivata, la ruota con updateUser e poi non la usa più', async () => { + const sb = fakeSupabase({ existingPassword: LEGACY }); + state.client = sb.client; + + expect(await runSync()).toBe('uid-supabase'); + + expect(sb.signInPasswords).toEqual([LEGACY]); + expect(sb.updateUser).toHaveBeenCalledTimes(1); + const rotated = sb.updateUser.mock.calls[0][0].password; + expect(rotated).not.toBe(LEGACY); + expect(rotated).toMatch(/^[A-Za-z0-9_-]{43,}$/); + expect(localStorage.getItem(`communityBridge:secret:${GS_ID}`)).toBe(rotated); + expect(sb.serverPassword()).toBe(rotated); + + // Avvii successivi (sessione scaduta): solo il nuovo segreto, mai più la legacy. + for (let i = 0; i < 2; i++) { + sb.endSession(); + vi.resetModules(); + expect(await runSync()).toBe('uid-supabase'); + } + expect(sb.signInPasswords.slice(1)).toEqual([rotated, rotated]); + expect(sb.signInPasswords.filter((p) => p === LEGACY)).toHaveLength(1); + expect(sb.updateUser).toHaveBeenCalledTimes(1); + expect(sb.signUpPasswords).toHaveLength(0); + }); + + it('se updateUser fallisce il segreto non viene tenuto (si ritenta al prossimo avvio)', async () => { + const sb = fakeSupabase({ existingPassword: LEGACY }); + sb.updateUser.mockResolvedValueOnce({ data: {}, error: { message: 'boom' } }); + state.client = sb.client; + + expect(await runSync()).toBe('uid-supabase'); + expect(localStorage.getItem(`communityBridge:secret:${GS_ID}`)).toBeNull(); + expect(sb.serverPassword()).toBe(LEGACY); + + sb.endSession(); + vi.resetModules(); + expect(await runSync()).toBe('uid-supabase'); + expect(sb.updateUser).toHaveBeenCalledTimes(2); + expect(localStorage.getItem(`communityBridge:secret:${GS_ID}`)).toBe(sb.serverPassword()); + expect(sb.serverPassword()).not.toBe(LEGACY); + }); + + it('community disabilitata → nessuna richiesta di auth', async () => { + vi.doMock('@/lib/social/community-hub-backend', () => ({ + getSupabase: async () => state.client, + isBackendEnabled: () => false, + })); + const sb = fakeSupabase({ existingPassword: LEGACY }); + state.client = sb.client; + expect(await runSync()).toBeNull(); + expect(sb.signInPasswords).toHaveLength(0); + vi.doUnmock('@/lib/social/community-hub-backend'); + }); +}); diff --git a/__tests__/lib/string-it-restore.test.ts b/__tests__/lib/string-it-restore.test.ts new file mode 100644 index 000000000..9ef5496bc --- /dev/null +++ b/__tests__/lib/string-it-restore.test.ts @@ -0,0 +1,50 @@ +/** + * Annulla String it: i wrapper chiamano il comando giusto con `gamePath` + * (camelCase, come vuole `rename_all = "camelCase"` sul comando Rust) e + * restituiscono la risposta così com'è. + */ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +const invokeMock = vi.fn(); + +vi.mock('@/lib/tauri-api', () => ({ + invoke: (cmd: string, args?: Record) => invokeMock(cmd, args), +})); + +import { probeStringItRestore, restoreStringIt } from '@/lib/string-it/restore'; + +beforeEach(() => { + invokeMock.mockReset(); +}); + +describe('probeStringItRestore', () => { + it('chiama string_it_restore_probe con gamePath', async () => { + const probe = { + restorable: [{ method: 'rpgmaker', detail: 'www/data/Map001.json' }], + manual: [{ method: 'unity-xunity', reason: 'BepInEx non provato nostro' }], + }; + invokeMock.mockResolvedValueOnce(probe); + + await expect(probeStringItRestore('C:\\Games\\Foo')).resolves.toEqual(probe); + expect(invokeMock).toHaveBeenCalledWith('string_it_restore_probe', { gamePath: 'C:\\Games\\Foo' }); + }); +}); + +describe('restoreStringIt', () => { + it('chiama string_it_restore con gamePath e restituisce il report', async () => { + const report = { + restored: [{ method: 'renpy', detail: 'ripristinato: game/tl/it (2 file)' }], + skipped: [], + errors: [{ method: 'gamemaker', error: 'data.win: accesso negato' }], + }; + invokeMock.mockResolvedValueOnce(report); + + await expect(restoreStringIt('/games/bar')).resolves.toEqual(report); + expect(invokeMock).toHaveBeenCalledWith('string_it_restore', { gamePath: '/games/bar' }); + }); + + it('propaga l\'errore del comando', async () => { + invokeMock.mockRejectedValueOnce(new Error('Cartella del gioco non trovata: x')); + await expect(restoreStringIt('x')).rejects.toThrow('Cartella del gioco non trovata'); + }); +}); diff --git a/__tests__/lib/string-it-route.test.ts b/__tests__/lib/string-it-route.test.ts new file mode 100644 index 000000000..ae21b4877 --- /dev/null +++ b/__tests__/lib/string-it-route.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from 'vitest'; + +import { engineMatches, hasDirectRoute, pageRouteFor } from '@/lib/string-it/route'; + +describe('String it: ramo per motore', () => { + it('riconosce i motori con ramo dedicato, senza badare alle maiuscole', () => { + expect(engineMatches('Unity', 'unity')).toBe(true); + expect(engineMatches('Unreal Engine 5', 'unreal')).toBe(true); + expect(engineMatches("Ren'Py", 'renpy')).toBe(true); + expect(engineMatches('RenPy', 'renpy')).toBe(true); + expect(engineMatches('Spike Chunsoft', 'danganronpa')).toBe(true); + expect(engineMatches('NW.js', 'tyrano')).toBe(true); + expect(engineMatches('Electron', 'tyrano')).toBe(true); + expect(engineMatches('RPG Maker MV', 'rpgmaker')).toBe(true); + expect(engineMatches('Hendrix_Localization', 'hendrix')).toBe(true); + expect(engineMatches('Visionaire Studio', 'visionaire')).toBe(true); + expect(engineMatches('Godot 4', 'godot')).toBe(true); + }); + + it('non confonde motori diversi', () => { + expect(engineMatches('Unreal Engine', 'unity')).toBe(false); + expect(engineMatches('GameMaker', 'rpgmaker')).toBe(false); + }); + + it('i motori senza ramo dedicato vanno al workflow generico', () => { + expect(hasDirectRoute('GameMaker')).toBe(false); + expect(hasDirectRoute('RE Engine')).toBe(false); + expect(hasDirectRoute('')).toBe(false); + expect(hasDirectRoute('Unity')).toBe(true); + }); + + it('manda Wolf RPG, Bethesda, CRI e Telltale alla loro pagina', () => { + expect(pageRouteFor('Wolf RPG Editor')?.href).toBe('/wolfrpg-patcher'); + expect(pageRouteFor('Creation Engine')?.href).toBe('/bethesda-patcher'); + expect(pageRouteFor('CRI Middleware')?.href).toBe('/cri-patcher'); + expect(pageRouteFor('Telltale Tool')?.href).toBe('/telltale-patcher'); + }); + + it('non scambia Wolfenstein per Wolf RPG né un nome con "cri" dentro per CRI', () => { + expect(pageRouteFor('id Tech (Wolfenstein)')).toBeUndefined(); + expect(pageRouteFor('Cricket Engine')).toBeUndefined(); + }); +}); diff --git a/__tests__/lib/string-it-run-log.test.ts b/__tests__/lib/string-it-run-log.test.ts new file mode 100644 index 000000000..1648209ea --- /dev/null +++ b/__tests__/lib/string-it-run-log.test.ts @@ -0,0 +1,64 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { appendEntry, loadRunResult, recordingToast, saveRunResult, type RunLogEntry } from '@/lib/string-it/run-log'; + +function fakeToast() { + const base = Object.assign(vi.fn(() => 'plain'), { + success: vi.fn(() => 's'), + error: vi.fn(() => 'e'), + info: vi.fn(() => 'i'), + warning: vi.fn(() => 'w'), + loading: vi.fn(() => 'l'), + dismiss: vi.fn(), + }); + return base; +} + +describe('recordingToast', () => { + it('mostra il toast e registra gli esiti, non i loading', () => { + const base = fakeToast(); + const seen: RunLogEntry[] = []; + const t = recordingToast(base, e => seen.push(e)); + + expect(t.success('Fatto', { description: '291 testi' })).toBe('s'); + t.error('Fallito'); + t.loading('Sto lavorando'); + t('Messaggio neutro'); + + expect(base.success).toHaveBeenCalledWith('Fatto', { description: '291 testi' }); + expect(base.loading).toHaveBeenCalled(); + expect(base).toHaveBeenCalledWith('Messaggio neutro', undefined); + expect(seen.map(e => [e.level, e.message, e.description])).toEqual([ + ['success', 'Fatto', '291 testi'], + ['error', 'Fallito', undefined], + ['info', 'Messaggio neutro', undefined], + ]); + }); + + it('ignora i messaggi che non sono testo', () => { + const seen: RunLogEntry[] = []; + const t = recordingToast(fakeToast(), e => seen.push(e)); + t.info({ jsx: true } as unknown as string); + expect(seen).toHaveLength(0); + }); +}); + +describe('persistenza esito', () => { + beforeEach(() => localStorage.clear()); + + it('salva e rilegge per gioco, tenendo al massimo 40 voci', () => { + let run = { startedAt: 1, entries: [] as RunLogEntry[] }; + for (let i = 0; i < 45; i++) run = appendEntry(run, { level: 'info', message: `m${i}`, at: i }); + saveRunResult('game-1', run); + + const back = loadRunResult('game-1'); + expect(back?.entries).toHaveLength(40); + expect(back?.entries[0].message).toBe('m5'); + expect(loadRunResult('game-2')).toBeNull(); + }); + + it('un valore rovinato in localStorage non rompe la scheda', () => { + localStorage.setItem('gs.stringit.lastRun.x', '{non json'); + expect(loadRunResult('x')).toBeNull(); + }); +}); diff --git a/__tests__/middleware.test.ts b/__tests__/middleware.test.ts deleted file mode 100644 index aba77d16c..000000000 --- a/__tests__/middleware.test.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; - -// Mock NextResponse and NextRequest -vi.mock('next/server', () => { - const headers = new Map(); - return { - NextResponse: { - next: () => ({ - headers: { - set: (key: string, value: string) => headers.set(key, value), - get: (key: string) => headers.get(key), - }, - }), - json: (body: unknown, init?: { status?: number; headers?: Record }) => ({ - body, - status: init?.status || 200, - headers: init?.headers || {}, - }), - }, - }; -}); - -// We need to test the middleware logic directly -// Since middleware.ts uses Edge Runtime patterns, we test the core logic -describe('Middleware Security', () => { - describe('CSP Headers', () => { - // TODO: riabilitare quando la CSP sarà ristretta (audit H12). - // Questo test codifica lo STATO DESIDERATO: il middleware contiene ancora - // 'unsafe-eval' (sia nella policy dev sia in quella production). Debito noto - // dall'audit di maggio (criticità H12). NON indebolire le assertion e NON - // irrigidire la CSP alla cieca (rischio rottura WebView Tauri). - it.skip('should define a CSP policy without unsafe-eval', async () => { - // Read the middleware source to verify CSP content - const fs = await import('fs'); - const content = fs.readFileSync('middleware.ts', 'utf-8'); - - expect(content).toContain("script-src 'self' 'unsafe-inline'"); - expect(content).not.toContain("'unsafe-eval'"); - expect(content).toContain("default-src 'self'"); - }); - - // TODO: riabilitare quando la CSP sarà ristretta (audit H12). - // Stato desiderato: img-src limitato a host Steam specifici - // (steamcdn-a.akamaihd.net, cdn.steamgriddb.com). Il middleware attuale usa - // wildcard (https://*.akamaihd.net, https://*.steamgriddb.com) e in dev - // addirittura `img-src *`. Stesso debito H12: non annacquare il test. - it.skip('should restrict img-src to specific Steam domains', async () => { - const fs = await import('fs'); - const content = fs.readFileSync('middleware.ts', 'utf-8'); - - expect(content).toContain('steamcdn-a.akamaihd.net'); - expect(content).toContain('cdn.steamgriddb.com'); - // Should NOT allow all https/http - expect(content).not.toMatch(/img-src[^;]*https:\s+http:/); - }); - }); - - describe('CSRF Protection', () => { - it('should define allowed origins including Tauri', async () => { - const fs = await import('fs'); - const content = fs.readFileSync('middleware.ts', 'utf-8'); - - expect(content).toContain('tauri://localhost'); - expect(content).toContain('https://tauri.localhost'); - }); - - it('should check X-GS-Client header for mutative methods', async () => { - const fs = await import('fs'); - const content = fs.readFileSync('middleware.ts', 'utf-8'); - - expect(content).toContain("x-gs-client"); - expect(content).toContain("gamestringer"); - expect(content).toContain('POST'); - expect(content).toContain('DELETE'); - }); - }); - - describe('Rate Limiting', () => { - it('should define rate limits for different routes', async () => { - const fs = await import('fs'); - const content = fs.readFileSync('middleware.ts', 'utf-8'); - - // Auth should have stricter limits - expect(content).toContain("'/api/auth/'"); - // Translation should have higher limits for OCR - expect(content).toContain("'/api/translate'"); - // Secrets should have strict limits - expect(content).toContain("'/api/secrets'"); - }); - - it('should return 429 when rate limited', async () => { - const fs = await import('fs'); - const content = fs.readFileSync('middleware.ts', 'utf-8'); - - expect(content).toContain('429'); - expect(content).toContain('Rate limit exceeded'); - expect(content).toContain('Retry-After'); - }); - }); - - describe('Security Headers', () => { - it('should set standard security headers', async () => { - const fs = await import('fs'); - const content = fs.readFileSync('middleware.ts', 'utf-8'); - - expect(content).toContain('X-Content-Type-Options'); - expect(content).toContain('nosniff'); - expect(content).toContain('X-Frame-Options'); - expect(content).toContain('DENY'); - expect(content).toContain('Referrer-Policy'); - }); - }); - - describe('Localhost Protection', () => { - it('should block non-localhost API requests', async () => { - const fs = await import('fs'); - const content = fs.readFileSync('middleware.ts', 'utf-8'); - - expect(content).toContain('API accessible only from localhost'); - expect(content).toContain('403'); - }); - }); -}); - diff --git a/__tests__/progress/progress-batch-integration.test.ts b/__tests__/progress/progress-batch-integration.test.ts deleted file mode 100644 index ad4e824d6..000000000 --- a/__tests__/progress/progress-batch-integration.test.ts +++ /dev/null @@ -1,275 +0,0 @@ -import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest'; -import { ProgressBatchProcessor, createProgressBatchProcessor } from '@/lib/batch/progress-batch-processor'; -import type { BatchItem } from '@/lib/batch/batch-processor'; -import type { ProgressState } from '@/lib/types/progress'; - -// Mock del BatchProcessor -vi.mock('@/lib/batch/batch-processor', () => ({ - // `function` e non arrow: da Vitest 4 un mock usato con `new` deve essere costruibile. - BatchProcessor: vi.fn().mockImplementation(function (options, callbacks) { return { - processBatch: vi.fn().mockImplementation(async (items, processor, operationType) => { - // Simula elaborazione batch - const results = []; - - for (let i = 0; i < items.length; i++) { - const item = items[i]; - - // Simula callbacks di progresso - callbacks?.onItemStart?.(item.id); - callbacks?.onProgress?.((i / items.length) * 100, `Processing ${i + 1}/${items.length}`); - - try { - const result = await processor(item); - results.push({ - itemId: item.id, - success: true, - result - }); - callbacks?.onItemComplete?.(item.id, result); - } catch (error) { - results.push({ - itemId: item.id, - success: false, - error: error instanceof Error ? error.message : String(error) - }); - callbacks?.onItemError?.(item.id, error as Error, 1); - } - } - - const batchResult = { - operationId: `batch-${operationType}-${Date.now()}`, - totalItems: items.length, - successCount: results.filter(r => r.success).length, - failureCount: results.filter(r => !r.success).length, - results, - duration: 1000, - completedAt: new Date() - }; - - callbacks?.onComplete?.(batchResult); - return batchResult; - }), - cancel: vi.fn(), - isProcessing: vi.fn(() => false), - getCurrentOperationId: vi.fn(() => 'test-operation-id') - }; }) -})); - -describe('ProgressBatchProcessor Integration', () => { - let mockProgressState: ProgressState; - let processor: ProgressBatchProcessor; - - beforeEach(() => { - vi.clearAllMocks(); - - // Mock del ProgressState - mockProgressState = { - operations: new Map(), - startOperation: vi.fn(), - updateProgress: vi.fn(), - completeOperation: vi.fn(), - failOperation: vi.fn(), - cancelOperation: vi.fn(), - getOperation: vi.fn() - }; - - processor = new ProgressBatchProcessor(mockProgressState); - }); - - afterEach(() => { - vi.clearAllTimers(); - }); - - it('should integrate batch processing with progress tracking', async () => { - const items: BatchItem[] = [ - { id: 'item1', data: { text: 'Hello' } }, - { id: 'item2', data: { text: 'World' } }, - { id: 'item3', data: { text: 'Test' } } - ]; - - const mockProcessor = vi.fn().mockImplementation(async (item: BatchItem) => { - await new Promise(resolve => setTimeout(resolve, 100)); - return { translated: `Translated: ${item.data.text}` }; - }); - - const result = await processor.processBatch(items, mockProcessor, 'translate'); - - // Verifica che l'operazione sia stata avviata - expect(mockProgressState.startOperation).toHaveBeenCalledWith( - expect.stringContaining('batch-translate'), - expect.objectContaining({ - title: expect.stringContaining('Traduzione di 3 elementi'), - canMinimize: true, - canCancel: true - }) - ); - - // Verifica che il progresso sia stato aggiornato - expect(mockProgressState.updateProgress).toHaveBeenCalled(); - - // Verifica che l'operazione sia stata completata - expect(mockProgressState.completeOperation).toHaveBeenCalledWith( - expect.stringContaining('batch-translate'), - expect.objectContaining({ - totalItems: 3, - successCount: 3, - failureCount: 0 - }) - ); - - // Verifica il risultato - expect(result.totalItems).toBe(3); - expect(result.successCount).toBe(3); - expect(result.failureCount).toBe(0); - }); - - it('should handle batch processing errors', async () => { - const items: BatchItem[] = [ - { id: 'item1', data: { text: 'Hello' } }, - { id: 'item2', data: { text: 'Error' } } - ]; - - const mockProcessor = vi.fn().mockImplementation(async (item: BatchItem) => { - if (item.data.text === 'Error') { - throw new Error('Processing failed'); - } - return { translated: `Translated: ${item.data.text}` }; - }); - - const result = await processor.processBatch(items, mockProcessor, 'translate'); - - // Verifica che l'operazione sia stata completata anche con errori - expect(mockProgressState.completeOperation).toHaveBeenCalled(); - - // Verifica il risultato - expect(result.totalItems).toBe(2); - expect(result.successCount).toBe(1); - expect(result.failureCount).toBe(1); - }); - - it('should handle complete batch failure', async () => { - const items: BatchItem[] = [ - { id: 'item1', data: { text: 'Hello' } } - ]; - - const mockProcessor = vi.fn().mockRejectedValue(new Error('Complete failure')); - - // Mock del batch processor per simulare fallimento completo - const mockBatchProcessor = { - processBatch: vi.fn().mockRejectedValue(new Error('Batch processing failed')), - cancel: vi.fn(), - isProcessing: vi.fn(() => false), - getCurrentOperationId: vi.fn(() => 'test-operation-id') - }; - - // Sostituisci il batch processor interno - (processor as unknown).batchProcessor = mockBatchProcessor; - - await expect(processor.processBatch(items, mockProcessor, 'translate')).rejects.toThrow('Batch processing failed'); - - // Verifica che l'operazione sia stata marcata come fallita - expect(mockProgressState.failOperation).toHaveBeenCalledWith( - expect.stringContaining('batch-translate'), - expect.any(Error) - ); - }); - - it('should create processor with factory function', () => { - const factoryProcessor = createProgressBatchProcessor(mockProgressState, 'export'); - - expect(factoryProcessor).toBeInstanceOf(ProgressBatchProcessor); - }); - - it('should handle different operation types with correct configurations', async () => { - const exportProcessor = createProgressBatchProcessor(mockProgressState, 'export'); - const items: BatchItem[] = [{ id: 'item1', data: { content: 'test' } }]; - const mockProcessor = vi.fn().mockResolvedValue({ exported: true }); - - await exportProcessor.processBatch(items, mockProcessor, 'export'); - - // Verifica che sia stata usata la configurazione corretta per export - expect(mockProgressState.startOperation).toHaveBeenCalledWith( - expect.stringContaining('batch-export'), - expect.objectContaining({ - title: expect.stringContaining('Esportazione di 1 elementi'), - isBackground: false // Export non dovrebbe essere background - }) - ); - }); - - it('should handle cancellation', () => { - processor.cancel(); - - // Il cancel dovrebbe essere propagato al batch processor interno - expect(processor.isProcessing()).toBe(false); - }); - - it('should provide operation status', () => { - const isProcessing = processor.isProcessing(); - const operationId = processor.getCurrentOperationId(); - - expect(typeof isProcessing).toBe('boolean'); - expect(typeof operationId).toBe('string'); - }); - - it('should handle large batches as background operations', async () => { - // Crea un batch grande (>10 items) - const items: BatchItem[] = Array.from({ length: 15 }, (_, i) => ({ - id: `item${i}`, - data: { text: `Text ${i}` } - })); - - const mockProcessor = vi.fn().mockResolvedValue({ processed: true }); - - await processor.processBatch(items, mockProcessor, 'translate'); - - // Verifica che sia stata configurata come operazione background - expect(mockProgressState.startOperation).toHaveBeenCalledWith( - expect.any(String), - expect.objectContaining({ - isBackground: true - }) - ); - }); - - it('should update progress during batch processing', async () => { - const items: BatchItem[] = [ - { id: 'item1', data: { text: 'Hello' } }, - { id: 'item2', data: { text: 'World' } } - ]; - - const mockProcessor = vi.fn().mockResolvedValue({ processed: true }); - - await processor.processBatch(items, mockProcessor, 'translate'); - - // Verifica che updateProgress sia stato chiamato durante l'elaborazione - expect(mockProgressState.updateProgress).toHaveBeenCalledWith( - expect.any(String), - expect.any(Number), - expect.stringContaining('Processing') - ); - }); - - it('should handle custom progress configuration', async () => { - const items: BatchItem[] = [{ id: 'item1', data: { text: 'Hello' } }]; - const mockProcessor = vi.fn().mockResolvedValue({ processed: true }); - - const customConfig = { - title: 'Custom Operation', - description: 'Custom description', - canCancel: false - }; - - await processor.processBatch(items, mockProcessor, 'translate', customConfig); - - // Verifica che la configurazione personalizzata sia stata utilizzata - expect(mockProgressState.startOperation).toHaveBeenCalledWith( - expect.any(String), - expect.objectContaining({ - title: 'Custom Operation', - description: 'Custom description', - canCancel: false - }) - ); - }); -}); diff --git a/__tests__/translation-memory/database-performance.test.ts b/__tests__/translation-memory/database-performance.test.ts deleted file mode 100644 index 363413ae7..000000000 --- a/__tests__/translation-memory/database-performance.test.ts +++ /dev/null @@ -1,392 +0,0 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { - TranslationMemoryDatabase, - GlossaryDatabase, - DatabaseMaintenance -} from '@/lib/utils/database'; -import type { TranslationMemoryEntry, GlossaryEntry } from '@/lib/types/translation-memory'; - -// Mock Prisma client. -// `vi.hoisted` perché `vi.mock` viene hoistato sopra le `const` del modulo: -// senza, il factory accederebbe a `mockPrisma` prima dell'inizializzazione (TDZ). -// Si mocka `@prisma/client` (il costruttore) e NON `@/lib/utils/database`: -// le classi reali usano il client `db` module-local, quindi l'unico punto di -// intercettazione corretto è `new PrismaClient()`. -const mockPrisma = vi.hoisted(() => ({ - translationMemoryEntry: { - create: vi.fn(), - findFirst: vi.fn(), - findMany: vi.fn(), - update: vi.fn(), - count: vi.fn() - }, - glossaryEntry: { - create: vi.fn(), - findMany: vi.fn(), - count: vi.fn() - }, - translationProject: { - count: vi.fn() - }, - batchOperation: { - create: vi.fn(), - update: vi.fn(), - deleteMany: vi.fn() - } -})); - -vi.mock('@prisma/client', () => ({ - // `function` e non arrow: da Vitest 4 un mock usato con `new` deve essere costruibile. - PrismaClient: vi.fn(function () { return mockPrisma; }) -})); - -describe('Translation Memory Database Performance', () => { - beforeEach(() => { - vi.clearAllMocks(); - }); - - afterEach(() => { - vi.resetAllMocks(); - }); - - describe('TranslationMemoryDatabase Performance', () => { - it('should handle large batch of memory entries efficiently', async () => { - const startTime = Date.now(); - const batchSize = 1000; - - // Mock database responses - mockPrisma.translationMemoryEntry.findFirst.mockResolvedValue(null); - mockPrisma.translationMemoryEntry.create.mockImplementation(() => - Promise.resolve({ id: `entry-${Date.now()}` }) - ); - - // Add many entries - const promises = Array.from({ length: batchSize }, (_, i) => - TranslationMemoryDatabase.addEntry({ - sourceText: `Source text ${i}`, - targetText: `Target text ${i}`, - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: 0.9 - }) - ); - - await Promise.all(promises); - - const endTime = Date.now(); - const duration = endTime - startTime; - - // Should complete within reasonable time (adjust threshold as needed) - expect(duration).toBeLessThan(5000); // 5 seconds for 1000 entries - expect(mockPrisma.translationMemoryEntry.create).toHaveBeenCalledTimes(batchSize); - }); - - it('should efficiently search through large dataset', async () => { - const largeDataset = Array.from({ length: 10000 }, (_, i) => ({ - id: `entry-${i}`, - sourceText: `Source text ${i}`, - targetText: `Target text ${i}`, - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: Math.random(), - usageCount: Math.floor(Math.random() * 100), - createdAt: new Date(), - updatedAt: new Date(), - projectId: i % 10 === 0 ? 'project-1' : null - })); - - mockPrisma.translationMemoryEntry.findMany.mockResolvedValue(largeDataset.slice(0, 10)); - - const startTime = Date.now(); - - const results = await TranslationMemoryDatabase.searchEntries( - 'Source text', - 'en', - 'es', - 'project-1', - 10 - ); - - const endTime = Date.now(); - const duration = endTime - startTime; - - expect(duration).toBeLessThan(100); // Should be very fast with proper indexing - expect(results).toHaveLength(10); - expect(mockPrisma.translationMemoryEntry.findMany).toHaveBeenCalledWith({ - where: { - sourceLanguage: 'en', - targetLanguage: 'es', - projectId: 'project-1', - OR: [ - { sourceText: { contains: 'Source text' } }, - { sourceText: 'Source text' } - ] - }, - orderBy: [ - { usageCount: 'desc' }, - { confidence: 'desc' }, - { updatedAt: 'desc' } - ], - take: 10 - }); - }); - - it('should handle concurrent memory operations', async () => { - mockPrisma.translationMemoryEntry.findFirst.mockResolvedValue(null); - mockPrisma.translationMemoryEntry.create.mockImplementation(() => - Promise.resolve({ id: `entry-${Date.now()}-${Math.random()}` }) - ); - - const concurrentOperations = 50; - const startTime = Date.now(); - - // Simulate concurrent add operations - const promises = Array.from({ length: concurrentOperations }, (_, i) => - TranslationMemoryDatabase.addEntry({ - sourceText: `Concurrent source ${i}`, - targetText: `Concurrent target ${i}`, - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: 0.8 - }) - ); - - const results = await Promise.all(promises); - - const endTime = Date.now(); - const duration = endTime - startTime; - - expect(results).toHaveLength(concurrentOperations); - expect(duration).toBeLessThan(2000); // Should handle concurrent operations efficiently - expect(mockPrisma.translationMemoryEntry.create).toHaveBeenCalledTimes(concurrentOperations); - }); - - it('should efficiently update usage counts', async () => { - mockPrisma.translationMemoryEntry.update.mockResolvedValue({ id: 'entry-1' }); - - const updateOperations = 100; - const startTime = Date.now(); - - // Simulate many usage count updates - const promises = Array.from({ length: updateOperations }, () => - TranslationMemoryDatabase.incrementUsage('entry-1') - ); - - await Promise.all(promises); - - const endTime = Date.now(); - const duration = endTime - startTime; - - expect(duration).toBeLessThan(1000); // Should be fast - expect(mockPrisma.translationMemoryEntry.update).toHaveBeenCalledTimes(updateOperations); - }); - }); - - describe('GlossaryDatabase Performance', () => { - it('should handle large glossary efficiently', async () => { - const largeGlossary = Array.from({ length: 5000 }, (_, i) => ({ - id: `term-${i}`, - term: `Term ${i}`, - translation: `Translation ${i}`, - sourceLanguage: 'en', - targetLanguage: 'es', - approved: i % 2 === 0, - createdAt: new Date(), - updatedAt: new Date() - })); - - mockPrisma.glossaryEntry.findMany.mockResolvedValue(largeGlossary.slice(0, 20)); - - const startTime = Date.now(); - - const results = await GlossaryDatabase.searchTerms( - 'Term', - 'en', - 'es', - 'project-1' - ); - - const endTime = Date.now(); - const duration = endTime - startTime; - - expect(duration).toBeLessThan(50); // Should be very fast - expect(results.length).toBeGreaterThan(0); - }); - - it('should efficiently add multiple glossary terms', async () => { - mockPrisma.glossaryEntry.create.mockImplementation(() => - Promise.resolve({ id: `term-${Date.now()}` }) - ); - - const termCount = 500; - const startTime = Date.now(); - - const promises = Array.from({ length: termCount }, (_, i) => - GlossaryDatabase.addTerm({ - term: `Batch term ${i}`, - translation: `Batch translation ${i}`, - sourceLanguage: 'en', - targetLanguage: 'es' - }) - ); - - await Promise.all(promises); - - const endTime = Date.now(); - const duration = endTime - startTime; - - expect(duration).toBeLessThan(3000); // Should handle batch operations well - expect(mockPrisma.glossaryEntry.create).toHaveBeenCalledTimes(termCount); - }); - }); - - describe('DatabaseMaintenance Performance', () => { - it('should efficiently get memory statistics', async () => { - mockPrisma.translationMemoryEntry.count.mockResolvedValue(10000); - mockPrisma.glossaryEntry.count.mockResolvedValue(5000); - mockPrisma.translationProject.count.mockResolvedValue(10); - - const startTime = Date.now(); - - const stats = await DatabaseMaintenance.getMemoryStats(); - - const endTime = Date.now(); - const duration = endTime - startTime; - - expect(duration).toBeLessThan(100); // Should be very fast - expect(stats).toEqual({ - totalEntries: 10000, - totalGlossaryTerms: 5000, - totalProjects: 10 - }); - }); - - it('should efficiently cleanup old batch operations', async () => { - mockPrisma.batchOperation.deleteMany.mockResolvedValue({ count: 100 }); - - const startTime = Date.now(); - - await DatabaseMaintenance.cleanupOldBatchOperations(30); - - const endTime = Date.now(); - const duration = endTime - startTime; - - expect(duration).toBeLessThan(200); // Should be fast - expect(mockPrisma.batchOperation.deleteMany).toHaveBeenCalledWith({ - where: { - completedAt: { - lt: expect.any(Date) - }, - status: { - in: ['completed', 'failed', 'cancelled'] - } - } - }); - }); - }); - - describe('Memory Usage Tests', () => { - it('should not cause memory leaks with large datasets', async () => { - const initialMemory = process.memoryUsage().heapUsed; - - // Simulate processing large amounts of data - const largeDataset = Array.from({ length: 10000 }, (_, i) => ({ - id: `entry-${i}`, - sourceText: `Source text ${i}`.repeat(10), // Make strings longer - targetText: `Target text ${i}`.repeat(10), - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: Math.random(), - usageCount: Math.floor(Math.random() * 100), - createdAt: new Date(), - updatedAt: new Date() - })); - - mockPrisma.translationMemoryEntry.findMany.mockResolvedValue(largeDataset); - - // Process the data multiple times - for (let i = 0; i < 10; i++) { - await TranslationMemoryDatabase.searchEntries( - 'Source text', - 'en', - 'es', - undefined, - 1000 - ); - } - - // Force garbage collection if available - if (global.gc) { - global.gc(); - } - - const finalMemory = process.memoryUsage().heapUsed; - const memoryIncrease = finalMemory - initialMemory; - - // Memory increase should be reasonable (less than 50MB) - expect(memoryIncrease).toBeLessThan(50 * 1024 * 1024); - }); - }); - - describe('Database Query Optimization', () => { - it('should use proper indexes for search queries', async () => { - mockPrisma.translationMemoryEntry.findMany.mockResolvedValue([]); - - await TranslationMemoryDatabase.searchEntries( - 'test query', - 'en', - 'es', - 'project-1', - 10 - ); - - // Verify that the query uses indexed fields - expect(mockPrisma.translationMemoryEntry.findMany).toHaveBeenCalledWith({ - where: { - sourceLanguage: 'en', // Indexed field - targetLanguage: 'es', // Indexed field - projectId: 'project-1', // Indexed field - OR: [ - { sourceText: { contains: 'test query' } }, // Indexed field - { sourceText: 'test query' } - ] - }, - orderBy: [ - { usageCount: 'desc' }, // Indexed field - { confidence: 'desc' }, // Indexed field - { updatedAt: 'desc' } // Indexed field - ], - take: 10 - }); - }); - - it('should optimize glossary search queries', async () => { - mockPrisma.glossaryEntry.findMany.mockResolvedValue([]); - - await GlossaryDatabase.searchTerms( - 'test term', - 'en', - 'es', - 'project-1' - ); - - // Verify optimized query structure - expect(mockPrisma.glossaryEntry.findMany).toHaveBeenCalledWith({ - where: { - sourceLanguage: 'en', // Indexed field - targetLanguage: 'es', // Indexed field - projectId: 'project-1', // Indexed field - OR: [ - { term: { contains: 'test term' } }, // Indexed field - { translation: { contains: 'test term' } }, - { definition: { contains: 'test term' } } - ] - }, - orderBy: [ - { approved: 'desc' }, // Indexed field - { term: 'asc' } - ] - }); - }); - }); -}); diff --git a/__tests__/translation-memory/fuzzy-search.test.ts b/__tests__/translation-memory/fuzzy-search.test.ts deleted file mode 100644 index 2f386a1ca..000000000 --- a/__tests__/translation-memory/fuzzy-search.test.ts +++ /dev/null @@ -1,317 +0,0 @@ -import { describe, it, expect } from 'vitest'; -import { - levenshteinDistance, - calculateSimilarity, - jaccardSimilarity, - enhancedSimilarity, - fuzzySearchMemory, - findExactMatches, - highlightMatches, - extractContext -} from '@/lib/utils/fuzzy-search'; -import type { TranslationMemoryEntry, FuzzySearchOptions } from '@/lib/types/translation-memory'; - -describe('Fuzzy Search Algorithms', () => { - describe('levenshteinDistance', () => { - it('should calculate correct distance for identical strings', () => { - expect(levenshteinDistance('hello', 'hello')).toBe(0); - }); - - it('should calculate correct distance for completely different strings', () => { - expect(levenshteinDistance('hello', 'world')).toBe(4); - }); - - it('should calculate correct distance for single character difference', () => { - expect(levenshteinDistance('hello', 'hallo')).toBe(1); - }); - - it('should handle empty strings', () => { - expect(levenshteinDistance('', '')).toBe(0); - expect(levenshteinDistance('hello', '')).toBe(5); - expect(levenshteinDistance('', 'world')).toBe(5); - }); - - it('should be case sensitive', () => { - expect(levenshteinDistance('Hello', 'hello')).toBe(1); - }); - }); - - describe('calculateSimilarity', () => { - it('should return 1 for identical strings', () => { - expect(calculateSimilarity('hello world', 'hello world')).toBe(1); - }); - - it('should return 1 for identical empty strings and 0 for one empty', () => { - expect(calculateSimilarity('', '')).toBe(1); // Identical empty strings - expect(calculateSimilarity('hello', '')).toBe(0); - expect(calculateSimilarity('', 'hello')).toBe(0); - }); - - it('should return high similarity for similar strings', () => { - const similarity = calculateSimilarity('hello world', 'hello word'); - expect(similarity).toBeGreaterThan(0.8); - }); - - it('should be case insensitive', () => { - const similarity = calculateSimilarity('Hello World', 'hello world'); - expect(similarity).toBe(1); - }); - }); - - describe('jaccardSimilarity', () => { - it('should return 1 for identical word sets', () => { - expect(jaccardSimilarity('hello world', 'world hello')).toBe(1); - }); - - it('should return 0 for completely different word sets', () => { - expect(jaccardSimilarity('hello world', 'foo bar')).toBe(0); - }); - - it('should calculate correct similarity for partial overlap', () => { - const similarity = jaccardSimilarity('hello world test', 'hello world example'); - expect(similarity).toBeCloseTo(0.5, 1); // 2 common words out of 4 total unique words - }); - - it('should be case insensitive', () => { - expect(jaccardSimilarity('Hello World', 'hello world')).toBe(1); - }); - }); - - describe('enhancedSimilarity', () => { - it('should combine Levenshtein and Jaccard similarities', () => { - const similarity = enhancedSimilarity('hello world', 'hello word'); - expect(similarity).toBeGreaterThan(0); - expect(similarity).toBeLessThanOrEqual(1); - }); - - it('should return 1 for identical strings', () => { - expect(enhancedSimilarity('hello world', 'hello world')).toBe(1); - }); - - it('should handle different string lengths', () => { - const similarity = enhancedSimilarity('hello', 'hello world test'); - expect(similarity).toBeGreaterThan(0); - expect(similarity).toBeLessThan(1); - }); - }); - - describe('fuzzySearchMemory', () => { - const mockEntries: TranslationMemoryEntry[] = [ - { - id: '1', - sourceText: 'Hello world', - targetText: 'Hola mundo', - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: 0.9, - usageCount: 5, - createdAt: new Date('2024-01-01'), - updatedAt: new Date('2024-01-01'), - projectId: 'project1' - }, - { - id: '2', - sourceText: 'Hello there', - targetText: 'Hola ahí', - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: 0.8, - usageCount: 3, - createdAt: new Date('2024-01-02'), - updatedAt: new Date('2024-01-02'), - projectId: 'project1' - }, - { - id: '3', - sourceText: 'Goodbye world', - targetText: 'Adiós mundo', - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: 0.95, - usageCount: 2, - createdAt: new Date('2024-01-03'), - updatedAt: new Date('2024-01-03'), - projectId: 'project2' - } - ]; - - const defaultOptions: FuzzySearchOptions = { - threshold: 0.3, - maxResults: 10, - includeContext: true, - preferRecent: false - }; - - it('should find exact matches with highest similarity', () => { - const results = fuzzySearchMemory('Hello world', mockEntries, defaultOptions); - - expect(results.length).toBeGreaterThan(0); // Should find matches - expect(results[0].similarity).toBe(1); // Exact match should be first - expect(results[0].type).toBe('exact'); - - // Verify results are sorted by similarity - for (let i = 1; i < results.length; i++) { - expect(results[i - 1].similarity).toBeGreaterThanOrEqual(results[i].similarity); - } - }); - - it('should filter by threshold', () => { - const highThresholdOptions = { ...defaultOptions, threshold: 0.9 }; - const results = fuzzySearchMemory('Hello world', mockEntries, highThresholdOptions); - - expect(results.length).toBeLessThanOrEqual(mockEntries.length); - results.forEach(result => { - expect(result.similarity).toBeGreaterThanOrEqual(0.9); - }); - }); - - it('should respect maxResults limit', () => { - const limitedOptions = { ...defaultOptions, maxResults: 1 }; - const results = fuzzySearchMemory('Hello', mockEntries, limitedOptions); - - expect(results).toHaveLength(1); - }); - - it('should filter by projectId when provided', () => { - const projectOptions = { ...defaultOptions, projectId: 'project1' }; - const results = fuzzySearchMemory('Hello', mockEntries, projectOptions); - - results.forEach(result => { - const originalEntry = mockEntries.find(e => e.id === result.id); - expect(originalEntry?.projectId).toBe('project1'); - }); - }); - - it('should sort by similarity descending', () => { - const results = fuzzySearchMemory('Hello', mockEntries, defaultOptions); - - for (let i = 1; i < results.length; i++) { - expect(results[i - 1].similarity).toBeGreaterThanOrEqual(results[i].similarity); - } - }); - - it('should prefer recent entries when specified', () => { - const recentOptions = { ...defaultOptions, preferRecent: true }; - const results = fuzzySearchMemory('Hello', mockEntries, recentOptions); - - // When similarities are equal, should prefer more recent entries - expect(results.length).toBeGreaterThan(0); - }); - }); - - describe('findExactMatches', () => { - const mockEntries: TranslationMemoryEntry[] = [ - { - id: '1', - sourceText: 'Hello world', - targetText: 'Hola mundo', - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: 0.9, - usageCount: 5, - createdAt: new Date(), - updatedAt: new Date() - }, - { - id: '2', - sourceText: 'hello world', // Different case - targetText: 'Hola mundo 2', - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: 0.8, - usageCount: 3, - createdAt: new Date(), - updatedAt: new Date() - } - ]; - - it('should find exact matches case-insensitively', () => { - const results = findExactMatches('Hello World', mockEntries); - - expect(results).toHaveLength(2); - results.forEach(result => { - expect(result.similarity).toBe(1); - expect(result.type).toBe('exact'); - }); - }); - - it('should sort by usage count descending', () => { - const results = findExactMatches('Hello World', mockEntries); - - expect(results[0].usageCount).toBeGreaterThanOrEqual(results[1].usageCount); - }); - - it('should return empty array for no matches', () => { - const results = findExactMatches('No match', mockEntries); - expect(results).toHaveLength(0); - }); - }); - - describe('highlightMatches', () => { - it('should highlight matching words', () => { - const result = highlightMatches('Hello world test', 'world'); - - const matchingParts = result.filter(part => part.isMatch); - expect(matchingParts.length).toBeGreaterThan(0); - expect(matchingParts.some(part => part.text.includes('world'))).toBe(true); - }); - - it('should handle empty query', () => { - const result = highlightMatches('Hello world', ''); - - expect(result).toHaveLength(1); - expect(result[0].isMatch).toBe(false); - expect(result[0].text).toBe('Hello world'); - }); - - it('should be case insensitive', () => { - const result = highlightMatches('Hello World', 'hello'); - - const matchingParts = result.filter(part => part.isMatch); - expect(matchingParts.length).toBeGreaterThan(0); - }); - - it('should only highlight words longer than 2 characters', () => { - const result = highlightMatches('Hello a world', 'a'); - - const matchingParts = result.filter(part => part.isMatch); - expect(matchingParts).toHaveLength(0); - }); - }); - - describe('extractContext', () => { - const fullText = 'This is a very long text that contains the match word somewhere in the middle of the sentence.'; - - it('should extract context around match', () => { - const context = extractContext(fullText, 'match', 20); - - expect(context).toContain('match'); - expect(context.length).toBeLessThanOrEqual(fullText.length); - }); - - it('should add ellipsis when text is truncated', () => { - const context = extractContext(fullText, 'match', 10); - - expect(context).toContain('...'); - }); - - it('should handle match at beginning', () => { - const context = extractContext('match at the beginning', 'match', 10); - - expect(context).toContain('match'); - expect(context.endsWith('...')).toBe(true); - }); - - it('should handle match at end', () => { - const context = extractContext('text ending with match', 'match', 10); - - expect(context).toContain('match'); - expect(context.startsWith('...')).toBe(true); - }); - - it('should return empty string for no match', () => { - const context = extractContext(fullText, 'nomatch', 20); - expect(context).toBe(''); - }); - }); -}); diff --git a/__tests__/translation-memory/integration.test.ts b/__tests__/translation-memory/integration.test.ts deleted file mode 100644 index 05069ac71..000000000 --- a/__tests__/translation-memory/integration.test.ts +++ /dev/null @@ -1,362 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { - TranslationMemoryDatabase, - GlossaryDatabase, - DatabaseMaintenance -} from '@/lib/utils/database'; -import { - levenshteinDistance, - calculateSimilarity, - enhancedSimilarity, - fuzzySearchMemory, - findExactMatches -} from '@/lib/utils/fuzzy-search'; -import type { TranslationMemoryEntry, FuzzySearchOptions } from '@/lib/types/translation-memory'; - -// Mock the database -vi.mock('@/lib/utils/database', () => ({ - TranslationMemoryDatabase: { - addEntry: vi.fn(), - searchEntries: vi.fn(), - incrementUsage: vi.fn() - }, - GlossaryDatabase: { - addTerm: vi.fn(), - searchTerms: vi.fn() - }, - DatabaseMaintenance: { - getMemoryStats: vi.fn() - } -})); - -describe('Translation Memory Integration Tests', () => { - beforeEach(() => { - vi.clearAllMocks(); - }); - - describe('Core Functionality', () => { - it('should add and retrieve translation memory entries', async () => { - const mockAddEntry = vi.mocked(TranslationMemoryDatabase.addEntry); - const mockSearchEntries = vi.mocked(TranslationMemoryDatabase.searchEntries); - - mockAddEntry.mockResolvedValue('entry-1'); - mockSearchEntries.mockResolvedValue([ - { - id: 'entry-1', - sourceText: 'Hello world', - targetText: 'Hola mundo', - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: 0.9, - usageCount: 1, - createdAt: new Date(), - updatedAt: new Date() - } - ]); - - // Add entry - const entryId = await TranslationMemoryDatabase.addEntry({ - sourceText: 'Hello world', - targetText: 'Hola mundo', - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: 0.9 - }); - - expect(entryId).toBe('entry-1'); - expect(mockAddEntry).toHaveBeenCalledWith({ - sourceText: 'Hello world', - targetText: 'Hola mundo', - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: 0.9 - }); - - // Search entries - const results = await TranslationMemoryDatabase.searchEntries( - 'Hello', - 'en', - 'es' - ); - - expect(results).toHaveLength(1); - expect(results[0].sourceText).toBe('Hello world'); - expect(results[0].targetText).toBe('Hola mundo'); - }); - - it('should add and search glossary terms', async () => { - const mockAddTerm = vi.mocked(GlossaryDatabase.addTerm); - const mockSearchTerms = vi.mocked(GlossaryDatabase.searchTerms); - - mockAddTerm.mockResolvedValue('term-1'); - mockSearchTerms.mockResolvedValue([ - { - id: 'term-1', - term: 'Hello', - translation: 'Hola', - sourceLanguage: 'en', - targetLanguage: 'es', - approved: true, - createdAt: new Date(), - updatedAt: new Date() - } - ]); - - // Add term - const termId = await GlossaryDatabase.addTerm({ - term: 'Hello', - translation: 'Hola', - sourceLanguage: 'en', - targetLanguage: 'es', - approved: true - }); - - expect(termId).toBe('term-1'); - - // Search terms - const results = await GlossaryDatabase.searchTerms( - 'Hello', - 'en', - 'es' - ); - - expect(results).toHaveLength(1); - expect(results[0].term).toBe('Hello'); - expect(results[0].translation).toBe('Hola'); - }); - - it('should get memory statistics', async () => { - const mockGetStats = vi.mocked(DatabaseMaintenance.getMemoryStats); - - mockGetStats.mockResolvedValue({ - totalEntries: 100, - totalGlossaryTerms: 50, - totalProjects: 5 - }); - - const stats = await DatabaseMaintenance.getMemoryStats(); - - expect(stats.totalEntries).toBe(100); - expect(stats.totalGlossaryTerms).toBe(50); - expect(stats.totalProjects).toBe(5); - }); - }); - - describe('Fuzzy Search Integration', () => { - const mockEntries: TranslationMemoryEntry[] = [ - { - id: '1', - sourceText: 'Hello world', - targetText: 'Hola mundo', - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: 0.95, - usageCount: 10, - createdAt: new Date('2024-01-01'), - updatedAt: new Date('2024-01-01') - }, - { - id: '2', - sourceText: 'Hello there', - targetText: 'Hola ahí', - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: 0.8, - usageCount: 5, - createdAt: new Date('2024-01-02'), - updatedAt: new Date('2024-01-02') - }, - { - id: '3', - sourceText: 'Good morning', - targetText: 'Buenos días', - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: 0.9, - usageCount: 3, - createdAt: new Date('2024-01-03'), - updatedAt: new Date('2024-01-03') - } - ]; - - it('should perform fuzzy search with proper scoring', () => { - const options: FuzzySearchOptions = { - threshold: 0.3, - maxResults: 10, - includeContext: true, - preferRecent: false - }; - - const results = fuzzySearchMemory('Hello', mockEntries, options); - - // Should find entries containing "Hello" - expect(results.length).toBeGreaterThan(0); - - // Results should be sorted by similarity - for (let i = 1; i < results.length; i++) { - expect(results[i - 1].similarity).toBeGreaterThanOrEqual(results[i].similarity); - } - - // Should include similarity scores - results.forEach(result => { - expect(result.similarity).toBeGreaterThanOrEqual(0); - expect(result.similarity).toBeLessThanOrEqual(1); - }); - }); - - it('should find exact matches', () => { - const exactMatches = findExactMatches('Hello world', mockEntries); - - expect(exactMatches).toHaveLength(1); - expect(exactMatches[0].sourceText).toBe('Hello world'); - expect(exactMatches[0].similarity).toBe(1); - expect(exactMatches[0].type).toBe('exact'); - }); - - it('should calculate similarity correctly', () => { - // Identical strings - expect(calculateSimilarity('hello', 'hello')).toBe(1); - - // Completely different strings - expect(calculateSimilarity('hello', 'world')).toBeLessThan(0.5); - - // Similar strings - const similarity = calculateSimilarity('hello world', 'hello word'); - expect(similarity).toBeGreaterThan(0.8); - expect(similarity).toBeLessThan(1); - }); - - it('should handle edge cases in fuzzy search', () => { - const options: FuzzySearchOptions = { - threshold: 0.5, - maxResults: 5, - includeContext: true, - preferRecent: false - }; - - // Empty query - const emptyResults = fuzzySearchMemory('', mockEntries, options); - expect(emptyResults).toHaveLength(0); - - // Very short query - const shortResults = fuzzySearchMemory('H', mockEntries, options); - expect(shortResults.length).toBeLessThanOrEqual(mockEntries.length); - - // No matches - const noMatchResults = fuzzySearchMemory('xyz123', mockEntries, options); - expect(noMatchResults).toHaveLength(0); - }); - }); - - describe('Performance Characteristics', () => { - it('should handle large datasets efficiently', () => { - const largeDataset: TranslationMemoryEntry[] = Array.from({ length: 1000 }, (_, i) => ({ - id: `entry-${i}`, - sourceText: `Source text ${i}`, - targetText: `Target text ${i}`, - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: Math.random(), - usageCount: Math.floor(Math.random() * 100), - createdAt: new Date(), - updatedAt: new Date() - })); - - const options: FuzzySearchOptions = { - threshold: 0.3, - maxResults: 10, - includeContext: true, - preferRecent: false - }; - - const startTime = Date.now(); - const results = fuzzySearchMemory('Source text', largeDataset, options); - const endTime = Date.now(); - - // Should complete within reasonable time - expect(endTime - startTime).toBeLessThan(1000); // 1 second - expect(results.length).toBeLessThanOrEqual(10); - }); - - it('should calculate Levenshtein distance efficiently', () => { - const str1 = 'This is a longer string for testing performance'; - const str2 = 'This is a different longer string for testing performance'; - - const startTime = Date.now(); - const distance = levenshteinDistance(str1, str2); - const endTime = Date.now(); - - expect(distance).toBeGreaterThan(0); - expect(endTime - startTime).toBeLessThan(10); // Should be very fast - }); - }); - - describe('Error Handling', () => { - it('should handle database errors gracefully', async () => { - const mockAddEntry = vi.mocked(TranslationMemoryDatabase.addEntry); - mockAddEntry.mockRejectedValue(new Error('Database connection failed')); - - await expect(TranslationMemoryDatabase.addEntry({ - sourceText: 'Test', - targetText: 'Prueba', - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: 0.9 - })).rejects.toThrow('Database connection failed'); - }); - - it('should handle search errors gracefully', async () => { - const mockSearchEntries = vi.mocked(TranslationMemoryDatabase.searchEntries); - mockSearchEntries.mockRejectedValue(new Error('Search failed')); - - await expect(TranslationMemoryDatabase.searchEntries( - 'test', - 'en', - 'es' - )).rejects.toThrow('Search failed'); - }); - }); - - describe('Data Validation', () => { - it('should validate translation memory entry data', async () => { - const mockAddEntry = vi.mocked(TranslationMemoryDatabase.addEntry); - mockAddEntry.mockImplementation(async (entry) => { - // Simulate validation - if (!entry.sourceText || !entry.targetText) { - throw new Error('Source and target text are required'); - } - if (entry.confidence < 0 || entry.confidence > 1) { - throw new Error('Confidence must be between 0 and 1'); - } - return 'entry-1'; - }); - - // Valid entry should succeed - await expect(TranslationMemoryDatabase.addEntry({ - sourceText: 'Hello', - targetText: 'Hola', - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: 0.9 - })).resolves.toBe('entry-1'); - - // Invalid confidence should fail - await expect(TranslationMemoryDatabase.addEntry({ - sourceText: 'Hello', - targetText: 'Hola', - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: 1.5 - })).rejects.toThrow('Confidence must be between 0 and 1'); - - // Missing text should fail - await expect(TranslationMemoryDatabase.addEntry({ - sourceText: '', - targetText: 'Hola', - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: 0.9 - })).rejects.toThrow('Source and target text are required'); - }); - }); -}); diff --git a/__tests__/translation-memory/translation-memory-provider.test.tsx b/__tests__/translation-memory/translation-memory-provider.test.tsx deleted file mode 100644 index ffe3b3982..000000000 --- a/__tests__/translation-memory/translation-memory-provider.test.tsx +++ /dev/null @@ -1,497 +0,0 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen, waitFor, act } from '@testing-library/react'; -import userEvent from '@testing-library/user-event'; -import { TranslationMemoryDatabase, GlossaryDatabase, DatabaseMaintenance } from '@/lib/utils/database'; -import { fuzzySearchMemory, findExactMatches } from '@/lib/utils/fuzzy-search'; -import type { TranslationMemoryEntry, GlossaryEntry } from '@/lib/types/translation-memory'; - -// TODO: riabilitare quando la UI translation-memory sarà implementata. -// Il componente `@/components/translation-memory/translation-memory-provider` -// (provider + hook React) NON esiste nel codebase: l'unica implementazione attuale -// è il singleton non-React `lib/translation-memory.ts`. La suite è interamente -// skippata (`describe.skip` sotto); gli stub servono solo a mantenere il file -// collezionabile da vitest senza import rotti. -const TranslationMemoryProvider = (_props: { - children?: unknown; - projectId?: string; - gameId?: string; -}): null => null; -const useTranslationMemory = (): Record => { - throw new Error('useTranslationMemory: componente non implementato (suite skippata)'); -}; - -// Mock the database utilities -vi.mock('@/lib/utils/database', () => ({ - TranslationMemoryDatabase: { - addEntry: vi.fn(), - searchEntries: vi.fn(), - incrementUsage: vi.fn() - }, - GlossaryDatabase: { - addTerm: vi.fn(), - searchTerms: vi.fn() - }, - DatabaseMaintenance: { - getMemoryStats: vi.fn() - } -})); - -// Mock the fuzzy search utilities -vi.mock('@/lib/utils/fuzzy-search', () => ({ - fuzzySearchMemory: vi.fn(), - findExactMatches: vi.fn() -})); - -// Test component that uses the hook -function TestComponent() { - const { - addMemoryEntry, - searchMemory, - getExactMatches, - incrementUsage, - addGlossaryTerm, - searchGlossary, - getStats, - isLoading, - error - } = useTranslationMemory(); - - return ( -
-
{isLoading ? 'loading' : 'not-loading'}
-
{error || 'no-error'}
- - - - - - - -
- ); -} - -describe.skip('TranslationMemoryProvider', () => { - beforeEach(() => { - vi.clearAllMocks(); - }); - - afterEach(() => { - vi.resetAllMocks(); - }); - - it('should provide translation memory context', () => { - render( - - - - ); - - expect(screen.getByTestId('loading')).toHaveTextContent('not-loading'); - expect(screen.getByTestId('error')).toHaveTextContent('no-error'); - }); - - it('should throw error when used outside provider', () => { - // Suppress console.error for this test - const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); - - expect(() => { - render(); - }).toThrow('useTranslationMemory must be used within a TranslationMemoryProvider'); - - consoleSpy.mockRestore(); - }); - - describe('addMemoryEntry', () => { - it('should add memory entry successfully', async () => { - const mockAddEntry = vi.mocked(TranslationMemoryDatabase.addEntry); - mockAddEntry.mockResolvedValue('entry-1'); - - render( - - - - ); - - const addButton = screen.getByTestId('add-memory'); - await userEvent.click(addButton); - - await waitFor(() => { - expect(mockAddEntry).toHaveBeenCalledWith({ - sourceText: 'Hello', - targetText: 'Hola', - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: 0.9, - projectId: 'project-1', - gameId: 'game-1', - usageCount: 1 - }); - }); - }); - - it('should handle add memory entry error', async () => { - const mockAddEntry = vi.mocked(TranslationMemoryDatabase.addEntry); - mockAddEntry.mockRejectedValue(new Error('Database error')); - - render( - - - - ); - - const addButton = screen.getByTestId('add-memory'); - - await expect(async () => { - await userEvent.click(addButton); - await waitFor(() => { - expect(screen.getByTestId('error')).toHaveTextContent('Database error'); - }); - }).rejects.toThrow('Database error'); - }); - }); - - describe('searchMemory', () => { - it('should search memory with fuzzy matching', async () => { - const mockSearchEntries = vi.mocked(TranslationMemoryDatabase.searchEntries); - const mockFuzzySearch = vi.mocked(fuzzySearchMemory); - - const mockEntries: TranslationMemoryEntry[] = [{ - id: 'entry-1', - sourceText: 'Hello', - targetText: 'Hola', - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: 0.9, - usageCount: 1, - createdAt: new Date(), - updatedAt: new Date() - }]; - - const mockSuggestions = [{ - id: 'entry-1', - sourceText: 'Hello', - targetText: 'Hola', - confidence: 0.9, - similarity: 1, - usageCount: 1, - lastUsed: new Date(), - type: 'exact' as const - }]; - - mockSearchEntries.mockResolvedValue(mockEntries); - mockFuzzySearch.mockReturnValue(mockSuggestions); - - render( - - - - ); - - const searchButton = screen.getByTestId('search-memory'); - await userEvent.click(searchButton); - - await waitFor(() => { - expect(mockSearchEntries).toHaveBeenCalledWith('Hello', 'en', 'es', undefined, 20); - expect(mockFuzzySearch).toHaveBeenCalledWith('Hello', mockEntries, expect.objectContaining({ - threshold: 0.6, - maxResults: 10, - includeContext: true, - preferRecent: false - })); - }); - }); - - it('should handle search memory error', async () => { - const mockSearchEntries = vi.mocked(TranslationMemoryDatabase.searchEntries); - mockSearchEntries.mockRejectedValue(new Error('Search error')); - - render( - - - - ); - - const searchButton = screen.getByTestId('search-memory'); - await userEvent.click(searchButton); - - await waitFor(() => { - expect(screen.getByTestId('error')).toHaveTextContent('Search error'); - }); - }); - }); - - describe('getExactMatches', () => { - it('should get exact matches', async () => { - const mockSearchEntries = vi.mocked(TranslationMemoryDatabase.searchEntries); - const mockFindExactMatches = vi.mocked(findExactMatches); - - const mockEntries: TranslationMemoryEntry[] = [{ - id: 'entry-1', - sourceText: 'Hello', - targetText: 'Hola', - sourceLanguage: 'en', - targetLanguage: 'es', - confidence: 0.9, - usageCount: 1, - createdAt: new Date(), - updatedAt: new Date() - }]; - - const mockMatches = [{ - id: 'entry-1', - sourceText: 'Hello', - targetText: 'Hola', - confidence: 0.9, - similarity: 1, - usageCount: 1, - lastUsed: new Date(), - type: 'exact' as const - }]; - - mockSearchEntries.mockResolvedValue(mockEntries); - mockFindExactMatches.mockReturnValue(mockMatches); - - render( - - - - ); - - const exactButton = screen.getByTestId('get-exact'); - await userEvent.click(exactButton); - - await waitFor(() => { - expect(mockSearchEntries).toHaveBeenCalledWith('Hello', 'en', 'es', undefined, 5); - expect(mockFindExactMatches).toHaveBeenCalledWith('Hello', mockEntries, undefined); - }); - }); - }); - - describe('incrementUsage', () => { - it('should increment usage count', async () => { - const mockIncrementUsage = vi.mocked(TranslationMemoryDatabase.incrementUsage); - mockIncrementUsage.mockResolvedValue(); - - render( - - - - ); - - const incrementButton = screen.getByTestId('increment-usage'); - await userEvent.click(incrementButton); - - await waitFor(() => { - expect(mockIncrementUsage).toHaveBeenCalledWith('entry-1'); - }); - }); - - it('should handle increment usage error silently', async () => { - const mockIncrementUsage = vi.mocked(TranslationMemoryDatabase.incrementUsage); - mockIncrementUsage.mockRejectedValue(new Error('Increment error')); - - const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); - - render( - - - - ); - - const incrementButton = screen.getByTestId('increment-usage'); - await userEvent.click(incrementButton); - - await waitFor(() => { - expect(consoleSpy).toHaveBeenCalledWith('Failed to increment usage:', expect.any(Error)); - }); - - // Should not set error state for usage tracking failures - expect(screen.getByTestId('error')).toHaveTextContent('no-error'); - - consoleSpy.mockRestore(); - }); - }); - - describe('addGlossaryTerm', () => { - it('should add glossary term successfully', async () => { - const mockAddTerm = vi.mocked(GlossaryDatabase.addTerm); - mockAddTerm.mockResolvedValue('term-1'); - - render( - - - - ); - - const addButton = screen.getByTestId('add-glossary'); - await userEvent.click(addButton); - - await waitFor(() => { - expect(mockAddTerm).toHaveBeenCalledWith({ - term: 'Hello', - translation: 'Hola', - sourceLanguage: 'en', - targetLanguage: 'es', - project: 'project-1', - approved: false - }); - }); - }); - }); - - describe('searchGlossary', () => { - it('should search glossary terms', async () => { - const mockSearchTerms = vi.mocked(GlossaryDatabase.searchTerms); - - const mockTerms: GlossaryEntry[] = [{ - id: 'term-1', - term: 'Hello', - translation: 'Hola', - sourceLanguage: 'en', - targetLanguage: 'es', - createdAt: new Date(), - updatedAt: new Date() - }]; - - mockSearchTerms.mockResolvedValue(mockTerms); - - render( - - - - ); - - const searchButton = screen.getByTestId('search-glossary'); - await userEvent.click(searchButton); - - await waitFor(() => { - expect(mockSearchTerms).toHaveBeenCalledWith('Hello', 'en', 'es', undefined); - }); - }); - }); - - describe('getStats', () => { - it('should get memory statistics', async () => { - const mockGetMemoryStats = vi.mocked(DatabaseMaintenance.getMemoryStats); - mockGetMemoryStats.mockResolvedValue({ - totalEntries: 100, - totalGlossaryTerms: 50, - totalProjects: 5 - }); - - render( - - - - ); - - const statsButton = screen.getByTestId('get-stats'); - await userEvent.click(statsButton); - - await waitFor(() => { - expect(mockGetMemoryStats).toHaveBeenCalled(); - }); - }); - - it('should handle stats error gracefully', async () => { - const mockGetMemoryStats = vi.mocked(DatabaseMaintenance.getMemoryStats); - mockGetMemoryStats.mockRejectedValue(new Error('Stats error')); - - render( - - - - ); - - const statsButton = screen.getByTestId('get-stats'); - await userEvent.click(statsButton); - - await waitFor(() => { - expect(screen.getByTestId('error')).toHaveTextContent('Stats error'); - }); - }); - }); - - describe('loading states', () => { - it('should show loading state during operations', async () => { - const mockAddEntry = vi.mocked(TranslationMemoryDatabase.addEntry); - - // Create a promise that we can control - let resolvePromise: (value: string) => void; - const controlledPromise = new Promise((resolve) => { - resolvePromise = resolve; - }); - - mockAddEntry.mockReturnValue(controlledPromise); - - render( - - - - ); - - const addButton = screen.getByTestId('add-memory'); - await userEvent.click(addButton); - - // Should show loading - expect(screen.getByTestId('loading')).toHaveTextContent('loading'); - - // Resolve the promise - act(() => { - resolvePromise!('entry-1'); - }); - - // Should stop loading - await waitFor(() => { - expect(screen.getByTestId('loading')).toHaveTextContent('not-loading'); - }); - }); - }); -}); diff --git a/__tests__/tutorial/tutorial-integration.test.tsx b/__tests__/tutorial/tutorial-integration.test.tsx deleted file mode 100644 index defa6663f..000000000 --- a/__tests__/tutorial/tutorial-integration.test.tsx +++ /dev/null @@ -1,381 +0,0 @@ -import React from 'react'; -import { render, screen, fireEvent, waitFor } from '@testing-library/react'; -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { TutorialProvider } from '@/components/tutorial/tutorial-provider'; -import { TutorialOverlay } from '@/components/tutorial/tutorial-overlay'; -import { TutorialMenu } from '@/components/tutorial/tutorial-menu'; -import { useTutorialTrigger } from '@/hooks/use-tutorial-trigger'; -import { dashboardTutorial } from '@/lib/tutorial-configs'; - -// NOTE sull'implementazione ATTUALE coperta da questi test: -// - TutorialOverlay mostra il contatore "N / TOT" (non "Step N of TOT") e i -// bottoni usano le chiavi i18n tutorial.overlay.{skip,back,forward,done}. -// Il mock globale di useTranslation (src/test/setup.ts) restituisce la -// chiave stessa, quindi i bottoni si trovano con getByText('tutorial.overlay.*'). -// - useTutorialTrigger consuma useTutorial(): va chiamato DENTRO il -// TutorialProvider, altrimenti riceve il fallback no-op. -// - startTutorial() su un tutorial già attivo lo fa ripartire dallo step 0 -// (comportamento voluto, usato per il "restart"). - -// Mock dependencies -vi.mock('@/lib/utils/database', () => ({ - TutorialDatabase: { - updateProgress: vi.fn(), - markTutorialSkipped: vi.fn(), - getUserProgress: vi.fn().mockResolvedValue(null) - } -})); - -vi.mock('@/components/ui/use-toast', () => ({ - useToast: () => ({ - toast: vi.fn() - }) -})); - -vi.mock('@/lib/utils/ux-enhancements', () => ({ - createSystemEvent: vi.fn(), - elementExists: vi.fn().mockReturnValue(true), - getElementPosition: vi.fn().mockReturnValue({ - top: 100, - left: 100, - width: 200, - height: 50 - }), - scrollToElement: vi.fn(), - prefersReducedMotion: vi.fn().mockReturnValue(false), - LocalStorage: { - get: vi.fn().mockReturnValue(false), - set: vi.fn(), - remove: vi.fn() - } -})); - -vi.mock('next/navigation', () => ({ - usePathname: () => '/' -})); - -// Mock framer-motion to avoid animation issues in tests -vi.mock('framer-motion', () => ({ - motion: { - div: ({ - children, - initial: _initial, - animate: _animate, - exit: _exit, - transition: _transition, - ...props - }: Record & { children?: React.ReactNode }) => ( -
)}>{children}
- ) - }, - AnimatePresence: ({ children }: { children: React.ReactNode }) => <>{children} -})); - -const TOTAL_STEPS = dashboardTutorial.steps.length; // 9 -const stepCounter = (n: number) => `${n} / ${TOTAL_STEPS}`; - -const FORWARD = 'tutorial.overlay.forward'; -const DONE = 'tutorial.overlay.done'; -const SKIP = 'tutorial.overlay.skip'; - -// Deve stare DENTRO il TutorialProvider: useTutorialTrigger usa useTutorial() -function TutorialControls() { - const { startSpecificTutorial } = useTutorialTrigger({ autoStart: false }); - - return ( - - ); -} - -// Test component that integrates tutorial system. -// withTargets=false simula una pagina dove i target degli step non esistono. -function IntegratedTutorialApp({ withTargets = true }: { withTargets?: boolean }) { - return ( - -
-

GameStringer Dashboard

- - - - {/* Mock elements that tutorials target */} - {withTargets && ( - <> - - {/* eslint-disable-next-line @next/next/no-html-link-for-pages -- target del tutorial: gli step selezionano 'a[href="/library"]', serve un anchor reale */} - Library - Neural Translator - Editor - Patches - Settings -
System Status
- - )} - - -
-
- ); -} - -describe('Tutorial System Integration', () => { - beforeEach(() => { - vi.clearAllMocks(); - }); - - afterEach(() => { - vi.restoreAllMocks(); - document.body.innerHTML = ''; - }); - - it('should render tutorial system components without errors', () => { - render(); - - expect(screen.getByText('GameStringer Dashboard')).toBeInTheDocument(); - expect(screen.getByText('Start Dashboard Tutorial')).toBeInTheDocument(); - }); - - it('should start tutorial and show overlay', async () => { - render(); - - // Start tutorial - fireEvent.click(screen.getByText('Start Dashboard Tutorial')); - - // Should show tutorial overlay elements - await waitFor(() => { - expect(screen.getByText(stepCounter(1))).toBeInTheDocument(); - }); - expect(screen.getByText(dashboardTutorial.steps[0].title)).toBeInTheDocument(); - }); - - it('should navigate through tutorial steps', async () => { - render(); - - // Start tutorial - fireEvent.click(screen.getByText('Start Dashboard Tutorial')); - - await waitFor(() => { - expect(screen.getByText(stepCounter(1))).toBeInTheDocument(); - }); - - // Find and click next button - fireEvent.click(screen.getByText(FORWARD)); - - await waitFor(() => { - expect(screen.getByText(stepCounter(2))).toBeInTheDocument(); - }); - - // Back button - fireEvent.click(screen.getByText('tutorial.overlay.back')); - - await waitFor(() => { - expect(screen.getByText(stepCounter(1))).toBeInTheDocument(); - }); - }); - - it('should show tutorial menu with accessible trigger button', () => { - render(); - - // Il trigger del TutorialMenu è icon-only con aria-label i18n - // (il mock di useTranslation restituisce la chiave 'nav.tutorialAndGuide') - const tutorialButton = screen.getByRole('button', { name: 'nav.tutorialAndGuide' }); - expect(tutorialButton).toBeInTheDocument(); - }); - - it('should handle tutorial completion', async () => { - render(); - - // Start tutorial - fireEvent.click(screen.getByText('Start Dashboard Tutorial')); - - await waitFor(() => { - expect(screen.getByText(stepCounter(1))).toBeInTheDocument(); - }); - - // Naviga fino all'ultimo step (tutti i target esistono, nessuno step - // opzionale viene saltato) - for (let i = 0; i < TOTAL_STEPS - 1; i++) { - fireEvent.click(screen.getByText(FORWARD)); - await waitFor(() => { - expect(screen.getByText(stepCounter(i + 2))).toBeInTheDocument(); - }); - } - - // Sull'ultimo step il bottone forward diventa "done" - fireEvent.click(screen.getByText(DONE)); - - // Tutorial should be completed and overlay hidden - await waitFor(() => { - expect(screen.queryByText(/\d+ \/ \d+/)).not.toBeInTheDocument(); - }); - }); - - it('should handle tutorial skip functionality', async () => { - render(); - - // Start tutorial - fireEvent.click(screen.getByText('Start Dashboard Tutorial')); - - await waitFor(() => { - expect(screen.getByText(stepCounter(1))).toBeInTheDocument(); - }); - - // Skip tutorial - fireEvent.click(screen.getByText(SKIP)); - - // Tutorial should be hidden - await waitFor(() => { - expect(screen.queryByText(/\d+ \/ \d+/)).not.toBeInTheDocument(); - }); - }); - - it('should handle keyboard navigation', async () => { - render(); - - // Start tutorial - fireEvent.click(screen.getByText('Start Dashboard Tutorial')); - - await waitFor(() => { - expect(screen.getByText(stepCounter(1))).toBeInTheDocument(); - }); - - // Test right arrow key navigation - fireEvent.keyDown(document, { key: 'ArrowRight' }); - - await waitFor(() => { - expect(screen.getByText(stepCounter(2))).toBeInTheDocument(); - }); - - // Test left arrow key navigation - fireEvent.keyDown(document, { key: 'ArrowLeft' }); - - await waitFor(() => { - expect(screen.getByText(stepCounter(1))).toBeInTheDocument(); - }); - - // Test escape key to skip - fireEvent.keyDown(document, { key: 'Escape' }); - - await waitFor(() => { - expect(screen.queryByText(/\d+ \/ \d+/)).not.toBeInTheDocument(); - }); - }); - - it('should show progress indicator correctly', async () => { - render(); - - // Start tutorial - fireEvent.click(screen.getByText('Start Dashboard Tutorial')); - - await waitFor(() => { - expect(screen.getByText(stepCounter(1))).toBeInTheDocument(); - }); - - // Progress indicator should be visible and show correct progress - const progressElements = screen.getAllByText(/\d+ \/ \d+/); - expect(progressElements.length).toBeGreaterThan(0); - }); - - it('should handle tutorial restart after skip', async () => { - render(); - - // Start tutorial and advance - fireEvent.click(screen.getByText('Start Dashboard Tutorial')); - - await waitFor(() => { - expect(screen.getByText(stepCounter(1))).toBeInTheDocument(); - }); - - // Advance to step 2 - fireEvent.click(screen.getByText(FORWARD)); - - await waitFor(() => { - expect(screen.getByText(stepCounter(2))).toBeInTheDocument(); - }); - - // Skip tutorial to end it - fireEvent.click(screen.getByText(SKIP)); - - await waitFor(() => { - expect(screen.queryByText(/\d+ \/ \d+/)).not.toBeInTheDocument(); - }); - - // Restart tutorial - fireEvent.click(screen.getByText('Start Dashboard Tutorial')); - - await waitFor(() => { - expect(screen.getByText(stepCounter(1))).toBeInTheDocument(); - }); - }); - - it('should handle missing tutorial targets gracefully', async () => { - // Nessun target degli step esiste nel DOM: l'overlay deve degradare a - // card centrata senza highlight, senza crashare - render(); - - // Start tutorial - should not crash even with missing targets - fireEvent.click(screen.getByText('Start Dashboard Tutorial')); - - await waitFor(() => { - expect(screen.getByText(stepCounter(1))).toBeInTheDocument(); - }); - - // Should be able to navigate even with missing targets (lo step 2, - // target 'aside', non è opzionale: viene mostrato comunque) - fireEvent.click(screen.getByText(FORWARD)); - - await waitFor(() => { - expect(screen.getByText(stepCounter(2))).toBeInTheDocument(); - }); - }); - - it('should restart from first step when startTutorial is called while active', async () => { - render(); - - // Start tutorial and advance to step 2 - fireEvent.click(screen.getByText('Start Dashboard Tutorial')); - - await waitFor(() => { - expect(screen.getByText(stepCounter(1))).toBeInTheDocument(); - }); - - fireEvent.click(screen.getByText(FORWARD)); - - await waitFor(() => { - expect(screen.getByText(stepCounter(2))).toBeInTheDocument(); - }); - - // Comportamento attuale: ri-avviare il tutorial mentre è attivo lo fa - // ripartire dallo step 0 (non viene ignorato) - fireEvent.click(screen.getByText('Start Dashboard Tutorial')); - - await waitFor(() => { - expect(screen.getByText(stepCounter(1))).toBeInTheDocument(); - }); - }); - - it('should handle window resize during tutorial', async () => { - render(); - - // Start tutorial - fireEvent.click(screen.getByText('Start Dashboard Tutorial')); - - await waitFor(() => { - expect(screen.getByText(stepCounter(1))).toBeInTheDocument(); - }); - - // Simulate window resize - fireEvent(window, new Event('resize')); - - // Tutorial should still be visible and functional - expect(screen.getByText(stepCounter(1))).toBeInTheDocument(); - - // Should still be able to navigate - fireEvent.click(screen.getByText(FORWARD)); - - await waitFor(() => { - expect(screen.getByText(stepCounter(2))).toBeInTheDocument(); - }); - }); -}); diff --git a/app/ai-pipeline/page.tsx b/app/ai-pipeline/page.tsx deleted file mode 100644 index ec45a6790..000000000 --- a/app/ai-pipeline/page.tsx +++ /dev/null @@ -1,648 +0,0 @@ -"use client" - -import { useState, useCallback, useEffect } from "react" -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" -import { Button } from "@/components/ui/button" -import { Textarea } from "@/components/ui/textarea" -import { Label } from "@/components/ui/label" -import { Badge } from "@/components/ui/badge" -import { Input } from "@/components/ui/input" -import { Switch } from "@/components/ui/switch" -import { ScrollArea } from "@/components/ui/scroll-area" -import { Separator } from "@/components/ui/separator" -import { Progress } from "@/components/ui/progress" -import { - Workflow, - Play, - CheckCircle2, - XCircle, - Clock, - Loader2, - Sparkles, - Shield, - Wrench, - Eye, - BarChart3, - ChevronRight, - AlertTriangle, - Download, -} from "lucide-react" -import { cn } from "@/lib/utils" -import { - runPipeline, - runQuickPipeline, - runMaxQualityPipeline, - loadMultiAgentConfig, - saveMultiAgentConfig, - AGENT_PRESETS, - resolvePreset, - saveBenchmarkEntry, - loadBenchmarkHistory, - buildBenchmarkEntry, - type PipelineResult, - type PipelineStep, - type PipelineStepId, - type MultiAgentConfig, - type AgentModelConfig, - type BenchmarkEntry, -} from "@/lib/ai/ai-pipeline" -import { useTranslation } from '@/lib/i18n'; -import { clientLogger } from '@/lib/client-logger'; -import { ollamaFetch } from '@/lib/ai/ollama-http'; -import { useDefaultTargetLang } from '@/lib/translation/use-default-target-lang'; - -const STEP_ICONS: Record = { - harvest: Sparkles, - translate: ChevronRight, - qa_check: Shield, - auto_fix: Wrench, - review: Eye, - score: BarChart3, -} - -const STEP_COLORS: Record = { - pending: "text-muted-foreground", - running: "text-noir-400 animate-pulse", - completed: "text-emerald-400", - failed: "text-red-400", - skipped: "text-muted-foreground/50", -} - -const DEMO_TEXTS = [ - "New Game", - "Continue", - "Settings", - "Guard: Stop right there! You're not allowed in this area.", - "You dealt {damage} damage to {enemy_name}!", - "Press {key_interact} to interact with objects", - "The ancient temple loomed before you, its crumbling walls whispering secrets of a forgotten age.", - "Quest Updated: Find the Lost Artifact", - "Health Potion", - "Restores 50 HP. A basic healing concoction brewed by village herbalists.", - "CRITICAL HIT!", - "Achievement Unlocked: Dragon Slayer", - "Game saved successfully!", - "Loading...", - "Buy", - "Sell", -] - -export default function AIPipelinePage() { - const { t } = useTranslation(); - const [result, setResult] = useState(null) - const [steps, setSteps] = useState([]) - const [isRunning, setIsRunning] = useState(false) - const [inputText, setInputText] = useState(DEMO_TEXTS.join("\n")) - const [targetLang, setTargetLang] = useState("en") - useDefaultTargetLang(setTargetLang); - - useEffect(() => { - const saved = localStorage.getItem('gameStringerSettings'); - if (saved) { - try { - const s = JSON.parse(saved); - if (s.translation?.defaultTargetLang) setTargetLang(s.translation.defaultTargetLang); - } catch {} - } - }, []); - const [sourceLang, setSourceLang] = useState("en") - const [enableHarvest, setEnableHarvest] = useState(true) - const [enableAutoFix, setEnableAutoFix] = useState(true) - const [enableReview, setEnableReview] = useState(true) - const [pipelineMode, setPipelineMode] = useState<"quick" | "balanced" | "max">("balanced") - const [selectedString, setSelectedString] = useState(null) - - // Multi-Agent state - const [ollamaModels, setOllamaModels] = useState([]) - const [agentConfig, setAgentConfig] = useState({}) - const [showAgents, setShowAgents] = useState(false) - const [activePresetId, setActivePresetId] = useState('default') - const [benchmarkHistory, setBenchmarkHistory] = useState([]) - const [showBenchmark, setShowBenchmark] = useState(false) - - useEffect(() => { - // Load saved agent config - setAgentConfig(loadMultiAgentConfig()); - setBenchmarkHistory(loadBenchmarkHistory()); - // Fetch available Ollama models - ollamaFetch('/api/tags', { timeoutMs: 3000 }) - .then(r => r.ok ? r.json() : null) - .then(data => { - if (data?.models) { - setOllamaModels(data.models.map((m: { name: string }) => m.name as string).sort()); - } - }) - .catch(() => {}); - }, []); - - const applyPreset = useCallback((presetId: string) => { - const preset = AGENT_PRESETS.find(p => p.id === presetId); - if (!preset) return; - setActivePresetId(presetId); - const resolved = resolvePreset(preset, ollamaModels); - setAgentConfig(resolved); - saveMultiAgentConfig(resolved); - }, [ollamaModels]); - - const updateAgent = useCallback((role: keyof MultiAgentConfig, model: string) => { - const newConfig = { ...agentConfig }; - if (!model) { - delete newConfig[role]; - } else { - newConfig[role] = { model, label: model.split(':')[0] }; - } - setAgentConfig(newConfig); - saveMultiAgentConfig(newConfig); - }, [agentConfig]); - - const handleRun = useCallback(async () => { - const texts = inputText.split("\n").map(l => l.trim()).filter(l => l.length > 0) - if (texts.length === 0) return - - setIsRunning(true) - setResult(null) - setSteps([]) - setSelectedString(null) - - try { - let pipelineResult: PipelineResult - - const onStepChange = (step: PipelineStep, allSteps: PipelineStep[]) => { - setSteps([...allSteps]) - } - - switch (pipelineMode) { - case "quick": - pipelineResult = await runQuickPipeline(texts, sourceLang, targetLang) - break - case "max": - pipelineResult = await runMaxQualityPipeline(texts, sourceLang, targetLang, { onStepChange }) - break - default: - pipelineResult = await runPipeline({ - texts, - sourceLanguage: sourceLang, - targetLanguage: targetLang, - enableHarvest, - enableAutoFix, - enableReview, - agents: agentConfig, - onStepChange, - }) - } - - setResult(pipelineResult) - setSteps(pipelineResult.steps) - - // Salva benchmark - const presetName = AGENT_PRESETS.find(p => p.id === activePresetId)?.name || 'Custom'; - const entry = buildBenchmarkEntry(pipelineResult, agentConfig, activePresetId, presetName, sourceLang, targetLang); - saveBenchmarkEntry(entry); - setBenchmarkHistory(loadBenchmarkHistory()); - } catch (e: unknown) { - clientLogger.error("[Pipeline] Error:", e) - } finally { - setIsRunning(false) - } - }, [inputText, targetLang, sourceLang, enableHarvest, enableAutoFix, enableReview, pipelineMode, agentConfig, activePresetId]) - - const handleExport = useCallback(() => { - if (!result) return - const blob = new Blob([JSON.stringify(result, null, 2)], { type: "application/json" }) - const url = URL.createObjectURL(blob) - const a = document.createElement("a") - a.href = url - a.download = `pipeline-result-${Date.now()}.json` - a.click() - URL.revokeObjectURL(url) - }, [result]) - - const selectedReport = selectedString !== null ? result?.qaReports[selectedString] : null - - return ( -
- {/* Hero */} -
-
-
-
- -
-
-

{t('aiPipelinePage.title')}

-

{t('aiPipelinePage.multistepHarvestTranslateQaAut')}

-
-
- {result && ( - - {t('aiPipelinePage.avgScore')}: {result.averageScore}% - - )} -
-
- -
- {/* Config */} -
- - - {t('aiPipelinePage.inputStrings')} - {t('aiPipelinePage.inputDesc')} - - -