Feat: Login localization, design, märchenzauber feature complete webapp

This commit is contained in:
Till-JS 2025-11-25 02:19:40 +01:00
parent 9c584a2580
commit 84f9343d25
47 changed files with 3254 additions and 175 deletions

View file

@ -0,0 +1,840 @@
# ManaDeck: Migration zu PostgreSQL + Drizzle ORM
## Übersicht
Dieses Dokument beschreibt die Migration von ManaDeck von Supabase zu einer selbst-gehosteten PostgreSQL-Datenbank mit Drizzle ORM.
---
## Aktuelle Architektur
```
┌─────────────────┐ ┌─────────────────┐
│ ManaDeck Web │ │ ManaDeck Mobile │
│ (SvelteKit) │ │ (Expo) │
└────────┬────────┘ └────────┬────────┘
│ │
└───────────┬───────────┘
┌───────────▼───────────┐
│ ManaDeck Backend │
│ (NestJS) │
└───────────┬───────────┘
┌────────────────┼────────────────┐
│ │ │
▼ ▼ ▼
┌────────┐ ┌──────────┐ ┌──────────┐
│Supabase│ │Mana Core │ │ OpenAI │
│ DB │ │ (Auth) │ │ API │
└────────┘ └──────────┘ └──────────┘
```
---
## Ziel-Architektur
```
┌─────────────────┐ ┌─────────────────┐
│ ManaDeck Web │ │ ManaDeck Mobile │
│ (SvelteKit) │ │ (Expo) │
└────────┬────────┘ └────────┬────────┘
│ │
└───────────┬───────────┘
┌───────────▼───────────┐
│ ManaDeck Backend │
│ (NestJS + Drizzle) │
└───────────┬───────────┘
┌────────────────┼────────────────┐
│ │ │
▼ ▼ ▼
┌────────┐ ┌──────────┐ ┌──────────┐
│ PostgreSQL │ │Mana Core │ │ OpenAI │
│ (Self) │ │ (Auth) │ │ API │
└────────────┘ └──────────┘ └──────────┘
```
---
## Datenbank-Schema
### Tabellen
#### 1. `decks`
```sql
CREATE TABLE decks (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL, -- Mana Core User ID
title VARCHAR(255) NOT NULL,
description TEXT,
cover_image_url TEXT,
is_public BOOLEAN DEFAULT false,
is_featured BOOLEAN DEFAULT false,
featured_at TIMESTAMPTZ,
settings JSONB DEFAULT '{}',
tags TEXT[] DEFAULT '{}',
metadata JSONB DEFAULT '{}',
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_decks_user_id ON decks(user_id);
CREATE INDEX idx_decks_is_public ON decks(is_public);
CREATE INDEX idx_decks_is_featured ON decks(is_featured);
```
#### 2. `cards`
```sql
CREATE TABLE cards (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
deck_id UUID NOT NULL REFERENCES decks(id) ON DELETE CASCADE,
position INTEGER NOT NULL DEFAULT 0,
title VARCHAR(255),
content JSONB NOT NULL,
card_type VARCHAR(20) NOT NULL CHECK (card_type IN ('text', 'flashcard', 'quiz', 'mixed')),
ai_model VARCHAR(100),
ai_prompt TEXT,
version INTEGER DEFAULT 1,
is_favorite BOOLEAN DEFAULT false,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_cards_deck_id ON cards(deck_id);
CREATE INDEX idx_cards_position ON cards(deck_id, position);
```
#### 3. `study_sessions`
```sql
CREATE TABLE study_sessions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
deck_id UUID NOT NULL REFERENCES decks(id) ON DELETE CASCADE,
user_id UUID NOT NULL,
mode VARCHAR(20) NOT NULL CHECK (mode IN ('all', 'new', 'review', 'favorites', 'random')),
total_cards INTEGER NOT NULL DEFAULT 0,
completed_cards INTEGER NOT NULL DEFAULT 0,
correct_cards INTEGER NOT NULL DEFAULT 0,
started_at TIMESTAMPTZ DEFAULT NOW(),
completed_at TIMESTAMPTZ,
time_spent_seconds INTEGER DEFAULT 0
);
CREATE INDEX idx_study_sessions_user_id ON study_sessions(user_id);
CREATE INDEX idx_study_sessions_deck_id ON study_sessions(deck_id);
```
#### 4. `card_progress`
```sql
CREATE TABLE card_progress (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL,
card_id UUID NOT NULL REFERENCES cards(id) ON DELETE CASCADE,
ease_factor DECIMAL(4,2) DEFAULT 2.5,
interval INTEGER DEFAULT 0,
repetitions INTEGER DEFAULT 0,
last_reviewed TIMESTAMPTZ,
next_review TIMESTAMPTZ,
status VARCHAR(20) DEFAULT 'new' CHECK (status IN ('new', 'learning', 'review', 'relearning')),
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(user_id, card_id)
);
CREATE INDEX idx_card_progress_user_id ON card_progress(user_id);
CREATE INDEX idx_card_progress_next_review ON card_progress(next_review);
```
#### 5. `deck_templates`
```sql
CREATE TABLE deck_templates (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
title VARCHAR(255) NOT NULL,
description TEXT,
category VARCHAR(100),
template_data JSONB NOT NULL,
is_active BOOLEAN DEFAULT true,
is_public BOOLEAN DEFAULT true,
popularity INTEGER DEFAULT 0,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_deck_templates_category ON deck_templates(category);
CREATE INDEX idx_deck_templates_is_active ON deck_templates(is_active);
```
#### 6. `ai_generations`
```sql
CREATE TABLE ai_generations (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL,
deck_id UUID REFERENCES decks(id) ON DELETE SET NULL,
function_name VARCHAR(100) NOT NULL,
prompt TEXT NOT NULL,
model VARCHAR(100),
status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'completed', 'failed')),
metadata JSONB DEFAULT '{}',
completed_at TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_ai_generations_user_id ON ai_generations(user_id);
CREATE INDEX idx_ai_generations_status ON ai_generations(status);
```
#### 7. `user_stats` (für Leaderboard)
```sql
CREATE TABLE user_stats (
user_id UUID PRIMARY KEY,
total_wins INTEGER DEFAULT 0,
total_sessions INTEGER DEFAULT 0,
total_cards_studied INTEGER DEFAULT 0,
total_time_seconds INTEGER DEFAULT 0,
average_accuracy DECIMAL(5,2) DEFAULT 0,
streak_days INTEGER DEFAULT 0,
last_study_date DATE,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
```
---
## Drizzle Schema
### Dateistruktur
```
manadeck/
├── packages/
│ └── database/ # Neues shared database package
│ ├── src/
│ │ ├── schema/
│ │ │ ├── decks.ts
│ │ │ ├── cards.ts
│ │ │ ├── studySessions.ts
│ │ │ ├── cardProgress.ts
│ │ │ ├── deckTemplates.ts
│ │ │ ├── aiGenerations.ts
│ │ │ ├── userStats.ts
│ │ │ └── index.ts
│ │ ├── client.ts
│ │ ├── migrate.ts
│ │ └── index.ts
│ ├── drizzle/
│ │ └── migrations/
│ ├── drizzle.config.ts
│ ├── package.json
│ └── tsconfig.json
```
### Schema-Definitionen (Drizzle)
#### `schema/decks.ts`
```typescript
import { pgTable, uuid, varchar, text, boolean, timestamp, jsonb } from 'drizzle-orm/pg-core';
export const decks = pgTable('decks', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id').notNull(),
title: varchar('title', { length: 255 }).notNull(),
description: text('description'),
coverImageUrl: text('cover_image_url'),
isPublic: boolean('is_public').default(false),
isFeatured: boolean('is_featured').default(false),
featuredAt: timestamp('featured_at', { withTimezone: true }),
settings: jsonb('settings').default({}),
tags: text('tags').array().default([]),
metadata: jsonb('metadata').default({}),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow(),
});
export type Deck = typeof decks.$inferSelect;
export type NewDeck = typeof decks.$inferInsert;
```
#### `schema/cards.ts`
```typescript
import { pgTable, uuid, varchar, text, integer, boolean, timestamp, jsonb } from 'drizzle-orm/pg-core';
import { decks } from './decks';
export const cardTypeEnum = pgEnum('card_type', ['text', 'flashcard', 'quiz', 'mixed']);
export const cards = pgTable('cards', {
id: uuid('id').primaryKey().defaultRandom(),
deckId: uuid('deck_id').notNull().references(() => decks.id, { onDelete: 'cascade' }),
position: integer('position').notNull().default(0),
title: varchar('title', { length: 255 }),
content: jsonb('content').notNull(),
cardType: cardTypeEnum('card_type').notNull(),
aiModel: varchar('ai_model', { length: 100 }),
aiPrompt: text('ai_prompt'),
version: integer('version').default(1),
isFavorite: boolean('is_favorite').default(false),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow(),
});
export type Card = typeof cards.$inferSelect;
export type NewCard = typeof cards.$inferInsert;
```
#### `schema/index.ts`
```typescript
export * from './decks';
export * from './cards';
export * from './studySessions';
export * from './cardProgress';
export * from './deckTemplates';
export * from './aiGenerations';
export * from './userStats';
// Relations
export { decksRelations } from './decks';
export { cardsRelations } from './cards';
```
### Client Setup
#### `client.ts`
```typescript
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema';
const connectionString = process.env.DATABASE_URL!;
// For connection pooling in serverless environments
const client = postgres(connectionString, {
max: 10,
idle_timeout: 20,
connect_timeout: 10,
});
export const db = drizzle(client, { schema });
export type Database = typeof db;
```
---
## Migrationsschritte
### Phase 1: Setup (Tag 1-2)
#### 1.1 PostgreSQL Server aufsetzen
```bash
# Option A: Railway.app (empfohlen für Staging)
# Erstelle neues Projekt auf railway.app
# Füge PostgreSQL Plugin hinzu
# Option B: Docker lokal
docker run -d \
--name manadeck-postgres \
-e POSTGRES_USER=manadeck \
-e POSTGRES_PASSWORD=secure_password \
-e POSTGRES_DB=manadeck \
-p 5432:5432 \
postgres:16-alpine
# Option C: Neon.tech (Serverless)
# Erstelle neues Projekt auf neon.tech
```
#### 1.2 Database Package erstellen
```bash
cd /Users/tillschneider/Documents/__00__Code/manacore-monorepo
mkdir -p packages/manadeck-database
cd packages/manadeck-database
pnpm init
```
#### 1.3 Dependencies installieren
```bash
pnpm add drizzle-orm postgres
pnpm add -D drizzle-kit typescript @types/node
```
### Phase 2: Schema & Migration (Tag 2-3)
#### 2.1 Drizzle Schema erstellen
- Alle Tabellen wie oben definiert
- Relations definieren
- Indexes definieren
#### 2.2 Initial Migration generieren
```bash
pnpm drizzle-kit generate
pnpm drizzle-kit migrate
```
#### 2.3 Daten von Supabase exportieren
```bash
# In Supabase Dashboard: SQL Editor
# Export alle Tabellen als CSV oder pg_dump
# Oder via CLI:
pg_dump -h db.your-project.supabase.co \
-U postgres \
-d postgres \
--data-only \
--table=decks \
--table=cards \
--table=study_sessions \
--table=card_progress \
--table=deck_templates \
--table=ai_generations \
--table=user_stats \
> manadeck_data.sql
```
### Phase 3: Backend Migration (Tag 3-5)
#### 3.1 Repository Pattern implementieren
```typescript
// repositories/deck.repository.ts
import { db } from '@manadeck/database';
import { decks, cards } from '@manadeck/database/schema';
import { eq, and, or, desc } from 'drizzle-orm';
export class DeckRepository {
async findAllByUser(userId: string) {
return db.query.decks.findMany({
where: eq(decks.userId, userId),
orderBy: desc(decks.updatedAt),
with: {
cards: true,
},
});
}
async findById(id: string) {
return db.query.decks.findFirst({
where: eq(decks.id, id),
with: {
cards: {
orderBy: (cards, { asc }) => [asc(cards.position)],
},
},
});
}
async findPublicAndUserDecks(userId: string) {
return db.query.decks.findMany({
where: or(
eq(decks.userId, userId),
and(eq(decks.isPublic, true), eq(decks.isFeatured, true))
),
orderBy: desc(decks.updatedAt),
});
}
async create(data: NewDeck) {
const [deck] = await db.insert(decks).values(data).returning();
return deck;
}
async update(id: string, userId: string, data: Partial<NewDeck>) {
const [deck] = await db
.update(decks)
.set({ ...data, updatedAt: new Date() })
.where(and(eq(decks.id, id), eq(decks.userId, userId)))
.returning();
return deck;
}
async delete(id: string, userId: string) {
await db
.delete(decks)
.where(and(eq(decks.id, id), eq(decks.userId, userId)));
}
}
```
#### 3.2 Service Layer aktualisieren
```typescript
// services/deck.service.ts
import { DeckRepository } from '../repositories/deck.repository';
export class DeckService {
constructor(private deckRepo = new DeckRepository()) {}
async getUserDecks(userId: string) {
return this.deckRepo.findPublicAndUserDecks(userId);
}
async getDeck(id: string) {
return this.deckRepo.findById(id);
}
async createDeck(userId: string, data: CreateDeckInput) {
return this.deckRepo.create({
...data,
userId,
});
}
async updateDeck(id: string, userId: string, data: UpdateDeckInput) {
return this.deckRepo.update(id, userId, data);
}
async deleteDeck(id: string, userId: string) {
return this.deckRepo.delete(id, userId);
}
}
```
### Phase 4: Frontend Migration (Tag 5-7)
#### 4.1 API Client erstellen (ersetzt Supabase SDK)
```typescript
// lib/api/client.ts
import { getToken } from '$lib/auth';
const API_URL = import.meta.env.VITE_API_URL;
async function fetchApi<T>(
endpoint: string,
options: RequestInit = {}
): Promise<T> {
const token = getToken();
const response = await fetch(`${API_URL}${endpoint}`, {
...options,
headers: {
'Content-Type': 'application/json',
...(token && { Authorization: `Bearer ${token}` }),
...options.headers,
},
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || 'API Error');
}
return response.json();
}
export const api = {
get: <T>(endpoint: string) => fetchApi<T>(endpoint),
post: <T>(endpoint: string, data: unknown) =>
fetchApi<T>(endpoint, { method: 'POST', body: JSON.stringify(data) }),
put: <T>(endpoint: string, data: unknown) =>
fetchApi<T>(endpoint, { method: 'PUT', body: JSON.stringify(data) }),
delete: <T>(endpoint: string) =>
fetchApi<T>(endpoint, { method: 'DELETE' }),
};
```
#### 4.2 Deck Store migrieren
```typescript
// stores/deckStore.svelte.ts
import { api } from '$lib/api/client';
import type { Deck, CreateDeckInput, UpdateDeckInput } from '$lib/types/deck';
function createDeckStore() {
let decks = $state<Deck[]>([]);
let currentDeck = $state<Deck | null>(null);
let loading = $state(false);
let error = $state<string | null>(null);
return {
get decks() { return decks; },
get currentDeck() { return currentDeck; },
get loading() { return loading; },
get error() { return error; },
async fetchDecks() {
loading = true;
error = null;
try {
decks = await api.get<Deck[]>('/api/decks');
} catch (e) {
error = e instanceof Error ? e.message : 'Failed to fetch decks';
} finally {
loading = false;
}
},
async fetchDeck(id: string) {
loading = true;
error = null;
try {
currentDeck = await api.get<Deck>(`/api/decks/${id}`);
} catch (e) {
error = e instanceof Error ? e.message : 'Failed to fetch deck';
} finally {
loading = false;
}
},
async createDeck(data: CreateDeckInput) {
loading = true;
error = null;
try {
const deck = await api.post<Deck>('/api/decks', data);
decks = [deck, ...decks];
return deck;
} catch (e) {
error = e instanceof Error ? e.message : 'Failed to create deck';
throw e;
} finally {
loading = false;
}
},
async updateDeck(id: string, data: UpdateDeckInput) {
loading = true;
error = null;
try {
const deck = await api.put<Deck>(`/api/decks/${id}`, data);
decks = decks.map(d => d.id === id ? deck : d);
if (currentDeck?.id === id) currentDeck = deck;
return deck;
} catch (e) {
error = e instanceof Error ? e.message : 'Failed to update deck';
throw e;
} finally {
loading = false;
}
},
async deleteDeck(id: string) {
loading = true;
error = null;
try {
await api.delete(`/api/decks/${id}`);
decks = decks.filter(d => d.id !== id);
if (currentDeck?.id === id) currentDeck = null;
} catch (e) {
error = e instanceof Error ? e.message : 'Failed to delete deck';
throw e;
} finally {
loading = false;
}
},
};
}
export const deckStore = createDeckStore();
```
### Phase 5: Testing & Cutover (Tag 7-10)
#### 5.1 Integration Tests
```typescript
// tests/deck.integration.test.ts
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { db } from '@manadeck/database';
import { decks } from '@manadeck/database/schema';
import { DeckService } from '../services/deck.service';
describe('DeckService', () => {
const service = new DeckService();
const testUserId = 'test-user-id';
afterAll(async () => {
await db.delete(decks).where(eq(decks.userId, testUserId));
});
it('should create a deck', async () => {
const deck = await service.createDeck(testUserId, {
title: 'Test Deck',
description: 'A test deck',
});
expect(deck.id).toBeDefined();
expect(deck.title).toBe('Test Deck');
});
it('should fetch user decks', async () => {
const userDecks = await service.getUserDecks(testUserId);
expect(userDecks.length).toBeGreaterThan(0);
});
});
```
#### 5.2 Datenmigrations-Script
```typescript
// scripts/migrate-data.ts
import { db as newDb } from '@manadeck/database';
import { createClient } from '@supabase/supabase-js';
import { decks, cards } from '@manadeck/database/schema';
const supabase = createClient(
process.env.SUPABASE_URL!,
process.env.SUPABASE_SERVICE_KEY!
);
async function migrateDecks() {
console.log('Migrating decks...');
const { data: supabaseDecks, error } = await supabase
.from('decks')
.select('*');
if (error) throw error;
for (const deck of supabaseDecks) {
await newDb.insert(decks).values({
id: deck.id,
userId: deck.user_id,
title: deck.title,
description: deck.description,
coverImageUrl: deck.cover_image_url,
isPublic: deck.is_public,
isFeatured: deck.is_featured,
featuredAt: deck.featured_at,
settings: deck.settings,
tags: deck.tags,
metadata: deck.metadata,
createdAt: deck.created_at,
updatedAt: deck.updated_at,
}).onConflictDoNothing();
}
console.log(`Migrated ${supabaseDecks.length} decks`);
}
async function migrateCards() {
console.log('Migrating cards...');
const { data: supabaseCards, error } = await supabase
.from('cards')
.select('*');
if (error) throw error;
for (const card of supabaseCards) {
await newDb.insert(cards).values({
id: card.id,
deckId: card.deck_id,
position: card.position,
title: card.title,
content: card.content,
cardType: card.card_type,
aiModel: card.ai_model,
aiPrompt: card.ai_prompt,
version: card.version,
isFavorite: card.is_favorite,
createdAt: card.created_at,
updatedAt: card.updated_at,
}).onConflictDoNothing();
}
console.log(`Migrated ${supabaseCards.length} cards`);
}
async function main() {
try {
await migrateDecks();
await migrateCards();
// ... andere Tabellen
console.log('Migration completed successfully!');
} catch (error) {
console.error('Migration failed:', error);
process.exit(1);
}
}
main();
```
---
## Zeitplan
| Phase | Beschreibung | Dauer | Status |
|-------|--------------|-------|--------|
| 1 | Setup (PostgreSQL, Package) | 1-2 Tage | ⬜ Pending |
| 2 | Schema & Migration | 1-2 Tage | ⬜ Pending |
| 3 | Backend Migration | 2-3 Tage | ⬜ Pending |
| 4 | Frontend Migration | 2-3 Tage | ⬜ Pending |
| 5 | Testing & Cutover | 2-3 Tage | ⬜ Pending |
**Gesamtdauer: ~10-13 Tage**
---
## Checkliste
### Pre-Migration
- [ ] PostgreSQL Server aufgesetzt
- [ ] Database Package erstellt
- [ ] Drizzle Schema definiert
- [ ] Initial Migration durchgeführt
- [ ] Supabase Daten exportiert
### Backend
- [ ] Repository Pattern implementiert
- [ ] DeckRepository
- [ ] CardRepository
- [ ] StudySessionRepository
- [ ] CardProgressRepository
- [ ] DeckTemplateRepository
- [ ] AIGenerationRepository
- [ ] UserStatsRepository
- [ ] Service Layer aktualisiert
- [ ] Controller aktualisiert
- [ ] Authorization Middleware (ersetzt RLS)
### Frontend
- [ ] API Client erstellt
- [ ] deckStore migriert
- [ ] Supabase imports entfernt
- [ ] Environment Variables aktualisiert
### Testing
- [ ] Unit Tests für Repositories
- [ ] Integration Tests für Services
- [ ] E2E Tests für API
- [ ] Manual Testing aller Features
### Cutover
- [ ] Daten migriert (Script ausgeführt)
- [ ] DNS/Environment umgestellt
- [ ] Rollback Plan dokumentiert
- [ ] Monitoring eingerichtet
---
## Rollback Plan
Falls kritische Probleme auftreten:
1. **Environment Variables zurücksetzen** auf Supabase
2. **Feature Flag** für alte Implementierung aktivieren
3. **DNS** auf alten Service zeigen lassen
Supabase-Daten bleiben während der Migration unberührt.
---
## Kosten nach Migration
| Service | Geschätzte Kosten |
|---------|-------------------|
| PostgreSQL (Railway) | ~$5-20/Monat |
| PostgreSQL (Neon Free) | $0/Monat |
| Backup (optional) | ~$5/Monat |
| **Gesamt** | **$5-25/Monat** |
vs. Supabase Pro: $25-300/Monat
---
## Nächste Schritte
1. **Entscheidung**: PostgreSQL Hosting (Railway vs Neon vs Self-hosted)
2. **Setup**: Database Package im Monorepo erstellen
3. **Schema**: Drizzle Schema implementieren
4. **Start**: Phase 1 beginnen
Bereit zum Start?

View file

@ -4,9 +4,12 @@ import { init, register, locale, waitLocale } from 'svelte-i18n';
// Register all available locales // Register all available locales
register('de', () => import('./locales/de.json')); register('de', () => import('./locales/de.json'));
register('en', () => import('./locales/en.json')); register('en', () => import('./locales/en.json'));
register('it', () => import('./locales/it.json'));
register('fr', () => import('./locales/fr.json'));
register('es', () => import('./locales/es.json'));
// List of supported locales // List of supported locales
export const supportedLocales = ['de', 'en'] as const; export const supportedLocales = ['de', 'en', 'it', 'fr', 'es'] as const;
export type SupportedLocale = (typeof supportedLocales)[number]; export type SupportedLocale = (typeof supportedLocales)[number];
// Default locale // Default locale

View file

@ -1,11 +1,16 @@
<script lang="ts"> <script lang="ts">
import { goto } from '$app/navigation'; import { goto } from '$app/navigation';
import { locale } from 'svelte-i18n';
import { LoginPage } from '@manacore/shared-auth-ui'; import { LoginPage } from '@manacore/shared-auth-ui';
import { StorytellerLogo } from '@manacore/shared-branding'; import { StorytellerLogo } from '@manacore/shared-branding';
import { getLoginTranslations } from '@manacore/shared-i18n';
import AppSlider from '$lib/components/AppSlider.svelte'; import AppSlider from '$lib/components/AppSlider.svelte';
import LanguageSelector from '$lib/components/LanguageSelector.svelte'; import LanguageSelector from '$lib/components/LanguageSelector.svelte';
import { authStore } from '$lib/stores/authStore.svelte'; import { authStore } from '$lib/stores/authStore.svelte';
// Get translations based on current locale
const translations = $derived(getLoginTranslations($locale || 'de'));
async function handleSignIn(email: string, password: string) { async function handleSignIn(email: string, password: string) {
return authStore.signIn(email, password); return authStore.signIn(email, password);
} }
@ -29,6 +34,7 @@
forgotPasswordPath="/forgot-password" forgotPasswordPath="/forgot-password"
lightBackground="#fff5f8" lightBackground="#fff5f8"
darkBackground="#1a1218" darkBackground="#1a1218"
{translations}
> >
{#snippet headerControls()} {#snippet headerControls()}
<LanguageSelector /> <LanguageSelector />

View file

@ -54,7 +54,8 @@
"@manacore/shared-ui": "workspace:*", "@manacore/shared-ui": "workspace:*",
"@manacore/shared-utils": "workspace:*", "@manacore/shared-utils": "workspace:*",
"@supabase/ssr": "^0.5.2", "@supabase/ssr": "^0.5.2",
"@supabase/supabase-js": "^2.81.1" "@supabase/supabase-js": "^2.81.1",
"svelte-i18n": "^4.0.0"
}, },
"type": "module" "type": "module"
} }

View file

@ -3,13 +3,14 @@ import type { Session, SupabaseClient, User } from '@supabase/supabase-js';
declare global { declare global {
namespace App { namespace App {
interface Locals { interface Locals {
supabase: SupabaseClient<any, 'public', 'public', any, any>; supabase: SupabaseClient;
safeGetSession: () => Promise<{ session: Session | null; user: User | null }>; safeGetSession: () => Promise<{ session: Session | null; user: User | null }>;
session: Session | null; session: Session | null;
user: User | null; user: User | null;
} }
interface PageData { interface PageData {
session: Session | null; session: Session | null;
supabase?: SupabaseClient;
} }
// interface Error {} // interface Error {}
// interface Platform {} // interface Platform {}

View file

@ -4,9 +4,12 @@ import { init, register, locale, waitLocale } from 'svelte-i18n';
// Register all available locales // Register all available locales
register('de', () => import('./locales/de.json')); register('de', () => import('./locales/de.json'));
register('en', () => import('./locales/en.json')); register('en', () => import('./locales/en.json'));
register('it', () => import('./locales/it.json'));
register('fr', () => import('./locales/fr.json'));
register('es', () => import('./locales/es.json'));
// List of supported locales // List of supported locales
export const supportedLocales = ['de', 'en'] as const; export const supportedLocales = ['de', 'en', 'it', 'fr', 'es'] as const;
export type SupportedLocale = (typeof supportedLocales)[number]; export type SupportedLocale = (typeof supportedLocales)[number];
// Default locale // Default locale

View file

@ -29,7 +29,7 @@
<div class="mb-8"> <div class="mb-8">
<h1 class="text-2xl font-bold text-gray-900 dark:text-white">Dashboard</h1> <h1 class="text-2xl font-bold text-gray-900 dark:text-white">Dashboard</h1>
<p class="mt-1 text-sm text-gray-500 dark:text-gray-400"> <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
Welcome back, {data.profile?.first_name || data.user?.email} Welcome back, {data.profile?.first_name || data.session?.user?.email}
</p> </p>
</div> </div>

View file

@ -50,7 +50,7 @@
<Input <Input
type="email" type="email"
id="email" id="email"
value={data.user?.email || ''} value={data.session?.user?.email || ''}
disabled disabled
class="bg-gray-50 dark:bg-gray-900" class="bg-gray-50 dark:bg-gray-900"
/> />

View file

@ -1,11 +1,16 @@
<script lang="ts"> <script lang="ts">
import { goto } from '$app/navigation'; import { goto } from '$app/navigation';
import { locale } from 'svelte-i18n';
import { LoginPage } from '@manacore/shared-auth-ui'; import { LoginPage } from '@manacore/shared-auth-ui';
import { ManaCoreLogo } from '@manacore/shared-branding'; import { ManaCoreLogo } from '@manacore/shared-branding';
import { getLoginTranslations } from '@manacore/shared-i18n';
import AppSlider from '$lib/components/AppSlider.svelte'; import AppSlider from '$lib/components/AppSlider.svelte';
import LanguageSelector from '$lib/components/LanguageSelector.svelte'; import LanguageSelector from '$lib/components/LanguageSelector.svelte';
import { authStore } from '$lib/stores/authStore.svelte'; import { authStore } from '$lib/stores/authStore.svelte';
// Get translations based on current locale
const translations = $derived(getLoginTranslations($locale || 'de'));
async function handleSignIn(email: string, password: string) { async function handleSignIn(email: string, password: string) {
return authStore.signIn(email, password); return authStore.signIn(email, password);
} }
@ -24,6 +29,7 @@
forgotPasswordPath="/forgot-password" forgotPasswordPath="/forgot-password"
lightBackground="#f3f4f6" lightBackground="#f3f4f6"
darkBackground="#121212" darkBackground="#121212"
{translations}
> >
{#snippet headerControls()} {#snippet headerControls()}
<LanguageSelector /> <LanguageSelector />

View file

@ -1,7 +1,40 @@
import { waitLocale } from '$lib/i18n'; import { waitLocale } from '$lib/i18n';
import '$lib/i18n'; // This triggers the init() call at module scope import '$lib/i18n'; // This triggers the init() call at module scope
import { createBrowserClient } from '@supabase/ssr';
import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY } from '$env/static/public';
import type { LayoutLoad } from './$types';
export const load = async () => { export const load: LayoutLoad = async ({ data, depends }) => {
await waitLocale(); await waitLocale();
return {};
/**
* Declare a dependency so the layout will be invalidated when `invalidate('supabase:auth')` is called.
*/
depends('supabase:auth');
const supabase = createBrowserClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY, {
global: {
fetch
},
cookies: {
getAll() {
return data.cookies;
},
setAll(cookiesToSet) {
// Browser client handles cookies automatically through the browser
// This is a no-op as cookies are managed via document.cookie in the browser
}
}
});
/**
* It's fine to use `getSession` here, because on the client, `getSession` is
* safe, and on the server, it reads `session` from the `LayoutData`, which
* safely checked the session using `safeGetSession`.
*/
const {
data: { session }
} = await supabase.auth.getSession();
return { session, supabase };
}; };

View file

@ -4,9 +4,12 @@ import { init, register, locale, waitLocale } from 'svelte-i18n';
// Register all available locales // Register all available locales
register('de', () => import('./locales/de.json')); register('de', () => import('./locales/de.json'));
register('en', () => import('./locales/en.json')); register('en', () => import('./locales/en.json'));
register('it', () => import('./locales/it.json'));
register('fr', () => import('./locales/fr.json'));
register('es', () => import('./locales/es.json'));
// List of supported locales // List of supported locales
export const supportedLocales = ['de', 'en'] as const; export const supportedLocales = ['de', 'en', 'it', 'fr', 'es'] as const;
export type SupportedLocale = (typeof supportedLocales)[number]; export type SupportedLocale = (typeof supportedLocales)[number];
// Default locale // Default locale

View file

@ -1,11 +1,16 @@
<script lang="ts"> <script lang="ts">
import { goto } from '$app/navigation'; import { goto } from '$app/navigation';
import { locale } from 'svelte-i18n';
import { LoginPage } from '@manacore/shared-auth-ui'; import { LoginPage } from '@manacore/shared-auth-ui';
import { ManaDeckLogo } from '@manacore/shared-branding'; import { ManaDeckLogo } from '@manacore/shared-branding';
import { getLoginTranslations } from '@manacore/shared-i18n';
import AppSlider from '$lib/components/AppSlider.svelte'; import AppSlider from '$lib/components/AppSlider.svelte';
import LanguageSelector from '$lib/components/LanguageSelector.svelte'; import LanguageSelector from '$lib/components/LanguageSelector.svelte';
import { authStore } from '$lib/stores/authStore.svelte'; import { authStore } from '$lib/stores/authStore.svelte';
// Get translations based on current locale
const translations = $derived(getLoginTranslations($locale || 'de'));
async function handleSignIn(email: string, password: string) { async function handleSignIn(email: string, password: string) {
return authStore.signIn(email, password); return authStore.signIn(email, password);
} }
@ -24,6 +29,7 @@
forgotPasswordPath="/forgot-password" forgotPasswordPath="/forgot-password"
lightBackground="#faf5ff" lightBackground="#faf5ff"
darkBackground="#1a1625" darkBackground="#1a1625"
{translations}
> >
{#snippet headerControls()} {#snippet headerControls()}
<LanguageSelector /> <LanguageSelector />

View file

@ -2,7 +2,7 @@ import { browser } from '$app/environment';
import { init, register, locale, waitLocale } from 'svelte-i18n'; import { init, register, locale, waitLocale } from 'svelte-i18n';
// List of supported locales // List of supported locales
export const supportedLocales = ['de', 'en'] as const; export const supportedLocales = ['de', 'en', 'it', 'fr', 'es'] as const;
export type SupportedLocale = (typeof supportedLocales)[number]; export type SupportedLocale = (typeof supportedLocales)[number];
// Default locale // Default locale
@ -11,6 +11,9 @@ const defaultLocale = 'de';
// Register all available locales // Register all available locales
register('de', () => import('./locales/de.json')); register('de', () => import('./locales/de.json'));
register('en', () => import('./locales/en.json')); register('en', () => import('./locales/en.json'));
register('it', () => import('./locales/it.json'));
register('fr', () => import('./locales/fr.json'));
register('es', () => import('./locales/es.json'));
// Get initial locale from browser or localStorage // Get initial locale from browser or localStorage
function getInitialLocale(): SupportedLocale { function getInitialLocale(): SupportedLocale {

View file

@ -1,13 +1,18 @@
<script lang="ts"> <script lang="ts">
import { goto } from '$app/navigation'; import { goto } from '$app/navigation';
import { locale } from 'svelte-i18n';
import { LoginPage, setGoogleClientId, setAppleConfig } from '@manacore/shared-auth-ui'; import { LoginPage, setGoogleClientId, setAppleConfig } from '@manacore/shared-auth-ui';
import { MemoroLogo } from '@manacore/shared-branding'; import { MemoroLogo } from '@manacore/shared-branding';
import { getLoginTranslations } from '@manacore/shared-i18n';
import AppSlider from '$lib/components/AppSlider.svelte'; import AppSlider from '$lib/components/AppSlider.svelte';
import LanguageSelector from '$lib/components/LanguageSelector.svelte'; import LanguageSelector from '$lib/components/LanguageSelector.svelte';
import { auth } from '$lib/stores/auth'; import { auth } from '$lib/stores/auth';
import { env } from '$lib/config/env'; import { env } from '$lib/config/env';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
// Get translations based on current locale
const translations = $derived(getLoginTranslations($locale || 'de'));
// Configure OAuth on mount // Configure OAuth on mount
onMount(() => { onMount(() => {
if (env.oauth.googleClientId) { if (env.oauth.googleClientId) {
@ -42,6 +47,7 @@
forgotPasswordPath="/forgot-password" forgotPasswordPath="/forgot-password"
lightBackground="#dddddd" lightBackground="#dddddd"
darkBackground="#101010" darkBackground="#101010"
{translations}
> >
{#snippet headerControls()} {#snippet headerControls()}
<LanguageSelector /> <LanguageSelector />

View file

@ -0,0 +1,10 @@
# Database connection URL
# Format: postgresql://user:password@host:port/database
DATABASE_URL=postgresql://postgres:password@localhost:5432/manadeck
# Alternative name (used as fallback)
MANADECK_DATABASE_URL=postgresql://postgres:password@localhost:5432/manadeck
# Supabase credentials (only needed for migration)
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_SERVICE_KEY=your-service-role-key

23
packages/manadeck-database/.gitignore vendored Normal file
View file

@ -0,0 +1,23 @@
# Environment variables
.env
.env.local
.env.*.local
# Dependencies
node_modules/
# Build output
dist/
# Drizzle migrations (optional - can be tracked)
# drizzle/
# IDE
.idea/
.vscode/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db

View file

@ -0,0 +1,39 @@
services:
postgres:
image: postgres:16-alpine
container_name: manadeck-postgres
restart: unless-stopped
environment:
POSTGRES_USER: manadeck
POSTGRES_PASSWORD: manadeck_dev_password
POSTGRES_DB: manadeck
ports:
- "5433:5432"
volumes:
- manadeck_postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U manadeck -d manadeck"]
interval: 10s
timeout: 5s
retries: 5
# Optional: pgAdmin for database management UI
pgadmin:
image: dpage/pgadmin4:latest
container_name: manadeck-pgadmin
restart: unless-stopped
environment:
PGADMIN_DEFAULT_EMAIL: admin@manadeck.local
PGADMIN_DEFAULT_PASSWORD: admin
PGADMIN_CONFIG_SERVER_MODE: 'False'
ports:
- "5050:80"
volumes:
- manadeck_pgadmin_data:/var/lib/pgadmin
depends_on:
postgres:
condition: service_healthy
volumes:
manadeck_postgres_data:
manadeck_pgadmin_data:

View file

@ -0,0 +1,12 @@
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
schema: './src/schema/index.ts',
out: './drizzle',
dialect: 'postgresql',
dbCredentials: {
url: process.env.DATABASE_URL!,
},
verbose: true,
strict: true,
});

View file

@ -0,0 +1,39 @@
{
"name": "@manacore/manadeck-database",
"version": "1.0.0",
"private": true,
"type": "module",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts",
"./schema": "./src/schema/index.ts",
"./client": "./src/client.ts"
},
"scripts": {
"docker:up": "docker compose up -d",
"docker:down": "docker compose down",
"docker:logs": "docker compose logs -f postgres",
"db:generate": "dotenv -- drizzle-kit generate",
"db:migrate": "dotenv -- drizzle-kit migrate",
"db:push": "dotenv -- drizzle-kit push --force",
"db:studio": "dotenv -- drizzle-kit studio",
"db:seed": "dotenv -- tsx src/seed.ts",
"db:migrate-from-supabase": "dotenv -- tsx src/migrate-from-supabase.ts",
"db:reset": "docker compose down -v && docker compose up -d && sleep 3 && pnpm db:push",
"db:test": "dotenv -- tsx src/test-connection.ts",
"type-check": "tsc --noEmit"
},
"dependencies": {
"drizzle-orm": "^0.36.0",
"postgres": "^3.4.5"
},
"devDependencies": {
"@supabase/supabase-js": "^2.81.1",
"dotenv-cli": "^7.4.0",
"drizzle-kit": "^0.28.0",
"tsx": "^4.19.0",
"typescript": "^5.7.3",
"@types/node": "^22.10.0"
}
}

View file

@ -0,0 +1,73 @@
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema';
// Singleton instance for the database client
let dbInstance: ReturnType<typeof drizzle<typeof schema>> | null = null;
let pgClient: ReturnType<typeof postgres> | null = null;
/**
* Get the database URL from environment variables
*/
function getDatabaseUrl(): string {
const url = process.env.DATABASE_URL || process.env.MANADECK_DATABASE_URL;
if (!url) {
throw new Error(
'Database URL not found. Set DATABASE_URL or MANADECK_DATABASE_URL environment variable.'
);
}
return url;
}
/**
* Create a new database client
* Uses connection pooling with sensible defaults for serverless environments
*/
export function createClient(connectionString?: string) {
const url = connectionString || getDatabaseUrl();
const client = postgres(url, {
max: 10, // Maximum connections in the pool
idle_timeout: 20, // Close idle connections after 20 seconds
connect_timeout: 10, // Connection timeout in seconds
prepare: false, // Disable prepared statements for serverless
});
return drizzle(client, { schema });
}
/**
* Get the singleton database instance
* Creates a new instance if one doesn't exist
*/
export function getDb() {
if (!dbInstance) {
const url = getDatabaseUrl();
pgClient = postgres(url, {
max: 10,
idle_timeout: 20,
connect_timeout: 10,
prepare: false,
});
dbInstance = drizzle(pgClient, { schema });
}
return dbInstance;
}
/**
* Close the database connection
* Should be called when shutting down the application
*/
export async function closeDb() {
if (pgClient) {
await pgClient.end();
pgClient = null;
dbInstance = null;
}
}
// Export the database type for typing purposes
export type Database = ReturnType<typeof createClient>;
// Re-export commonly used Drizzle utilities
export { eq, ne, gt, gte, lt, lte, and, or, not, inArray, notInArray, isNull, isNotNull, like, ilike, sql, asc, desc, count, sum, avg, min, max } from 'drizzle-orm';

View file

@ -0,0 +1,34 @@
// Main entry point for @manacore/manadeck-database
// Export database client utilities
export { createClient, getDb, closeDb, type Database } from './client';
// Export Drizzle utilities
export {
eq,
ne,
gt,
gte,
lt,
lte,
and,
or,
not,
inArray,
notInArray,
isNull,
isNotNull,
like,
ilike,
sql,
asc,
desc,
count,
sum,
avg,
min,
max,
} from './client';
// Export all schemas and types
export * from './schema';

View file

@ -0,0 +1,237 @@
/**
* Migration script to move data from Supabase to the new PostgreSQL database
*
* Prerequisites:
* 1. Set SUPABASE_URL and SUPABASE_SERVICE_KEY environment variables
* 2. Set DATABASE_URL for the new PostgreSQL database
* 3. Run migrations on the new database first: pnpm db:migrate
*
* Usage:
* SUPABASE_URL=... SUPABASE_SERVICE_KEY=... DATABASE_URL=... tsx src/migrate-from-supabase.ts
*/
import { createClient as createSupabaseClient } from '@supabase/supabase-js';
import { getDb, closeDb } from './client';
import {
decks,
cards,
studySessions,
cardProgress,
deckTemplates,
aiGenerations,
userStats,
dailyProgress,
} from './schema';
// Initialize Supabase client
const supabaseUrl = process.env.SUPABASE_URL;
const supabaseServiceKey = process.env.SUPABASE_SERVICE_KEY;
if (!supabaseUrl || !supabaseServiceKey) {
console.error('Missing SUPABASE_URL or SUPABASE_SERVICE_KEY environment variables');
process.exit(1);
}
const supabase = createSupabaseClient(supabaseUrl, supabaseServiceKey);
const db = getDb();
interface MigrationStats {
table: string;
migrated: number;
errors: number;
}
const stats: MigrationStats[] = [];
async function migrateTable<T>(
tableName: string,
supabaseTableName: string,
drizzleTable: any,
transformer: (row: any) => T
) {
console.log(`\nMigrating ${tableName}...`);
let migrated = 0;
let errors = 0;
try {
// Fetch all data from Supabase
const { data, error } = await supabase.from(supabaseTableName).select('*');
if (error) {
console.error(`Error fetching ${tableName}:`, error);
stats.push({ table: tableName, migrated: 0, errors: 1 });
return;
}
if (!data || data.length === 0) {
console.log(`No data found in ${tableName}`);
stats.push({ table: tableName, migrated: 0, errors: 0 });
return;
}
console.log(`Found ${data.length} rows in ${tableName}`);
// Process in batches of 100
const batchSize = 100;
for (let i = 0; i < data.length; i += batchSize) {
const batch = data.slice(i, i + batchSize);
const transformed = batch.map(transformer);
try {
await db.insert(drizzleTable).values(transformed).onConflictDoNothing();
migrated += batch.length;
process.stdout.write(`\r Migrated ${migrated}/${data.length} rows`);
} catch (err) {
console.error(`\n Error inserting batch:`, err);
errors += batch.length;
}
}
console.log(`\n Completed: ${migrated} migrated, ${errors} errors`);
} catch (err) {
console.error(`Error migrating ${tableName}:`, err);
errors++;
}
stats.push({ table: tableName, migrated, errors });
}
async function main() {
console.log('=== ManaDeck Data Migration ===');
console.log('From: Supabase');
console.log('To: PostgreSQL (Drizzle)');
console.log('==============================\n');
try {
// 1. Migrate decks
await migrateTable('decks', 'decks', decks, (row) => ({
id: row.id,
userId: row.user_id,
title: row.title,
description: row.description,
coverImageUrl: row.cover_image_url,
isPublic: row.is_public ?? false,
isFeatured: row.is_featured ?? false,
featuredAt: row.featured_at ? new Date(row.featured_at) : null,
settings: row.settings ?? {},
tags: row.tags ?? [],
metadata: row.metadata ?? {},
createdAt: new Date(row.created_at),
updatedAt: new Date(row.updated_at),
}));
// 2. Migrate cards
await migrateTable('cards', 'cards', cards, (row) => ({
id: row.id,
deckId: row.deck_id,
position: row.position ?? 0,
title: row.title,
content: row.content,
cardType: row.card_type,
aiModel: row.ai_model,
aiPrompt: row.ai_prompt,
version: row.version ?? 1,
isFavorite: row.is_favorite ?? false,
createdAt: new Date(row.created_at),
updatedAt: new Date(row.updated_at),
}));
// 3. Migrate study sessions
await migrateTable('study_sessions', 'study_sessions', studySessions, (row) => ({
id: row.id,
deckId: row.deck_id,
userId: row.user_id,
mode: row.mode,
totalCards: row.total_cards ?? 0,
completedCards: row.completed_cards ?? 0,
correctCards: row.correct_cards ?? 0,
startedAt: new Date(row.started_at),
completedAt: row.completed_at ? new Date(row.completed_at) : null,
timeSpentSeconds: row.time_spent_seconds ?? 0,
}));
// 4. Migrate card progress
await migrateTable('card_progress', 'card_progress', cardProgress, (row) => ({
id: row.id,
userId: row.user_id,
cardId: row.card_id,
easeFactor: row.ease_factor?.toString() ?? '2.5',
interval: row.interval ?? 0,
repetitions: row.repetitions ?? 0,
lastReviewed: row.last_reviewed ? new Date(row.last_reviewed) : null,
nextReview: row.next_review ? new Date(row.next_review) : null,
status: row.status ?? 'new',
createdAt: new Date(row.created_at),
updatedAt: new Date(row.updated_at),
}));
// 5. Migrate deck templates
await migrateTable('deck_templates', 'deck_templates', deckTemplates, (row) => ({
id: row.id,
title: row.title,
description: row.description,
category: row.category,
templateData: row.template_data ?? { cards: [] },
isActive: row.is_active ?? true,
isPublic: row.is_public ?? true,
popularity: row.popularity ?? 0,
createdAt: new Date(row.created_at),
updatedAt: new Date(row.updated_at),
}));
// 6. Migrate AI generations
await migrateTable('ai_generations', 'ai_generations', aiGenerations, (row) => ({
id: row.id,
userId: row.user_id,
deckId: row.deck_id,
functionName: row.function_name,
prompt: row.prompt,
model: row.model,
status: row.status ?? 'pending',
metadata: row.metadata ?? {},
completedAt: row.completed_at ? new Date(row.completed_at) : null,
createdAt: new Date(row.created_at),
}));
// 7. Migrate user stats
await migrateTable('user_stats', 'user_stats', userStats, (row) => ({
userId: row.user_id,
totalWins: row.total_wins ?? 0,
totalSessions: row.total_sessions ?? 0,
totalCardsStudied: row.total_cards_studied ?? 0,
totalTimeSeconds: row.total_time_seconds ?? 0,
averageAccuracy: row.average_accuracy?.toString() ?? '0',
streakDays: row.streak_days ?? 0,
longestStreak: row.longest_streak ?? 0,
lastStudyDate: row.last_study_date,
createdAt: new Date(row.created_at),
updatedAt: new Date(row.updated_at),
}));
// Print summary
console.log('\n\n=== Migration Summary ===');
console.log('-------------------------');
let totalMigrated = 0;
let totalErrors = 0;
for (const stat of stats) {
console.log(`${stat.table}: ${stat.migrated} migrated, ${stat.errors} errors`);
totalMigrated += stat.migrated;
totalErrors += stat.errors;
}
console.log('-------------------------');
console.log(`Total: ${totalMigrated} rows migrated, ${totalErrors} errors`);
if (totalErrors === 0) {
console.log('\n✅ Migration completed successfully!');
} else {
console.log('\n⚠ Migration completed with some errors. Please review.');
}
} catch (error) {
console.error('Migration failed:', error);
process.exit(1);
} finally {
await closeDb();
}
}
main();

View file

@ -0,0 +1,23 @@
import { migrate } from 'drizzle-orm/postgres-js/migrator';
import { createClient } from './client';
import path from 'path';
async function runMigrations() {
console.log('Running migrations...');
const db = createClient();
try {
await migrate(db, {
migrationsFolder: path.join(__dirname, '../drizzle'),
});
console.log('Migrations completed successfully!');
} catch (error) {
console.error('Migration failed:', error);
process.exit(1);
}
process.exit(0);
}
runMigrations();

View file

@ -0,0 +1,63 @@
import {
pgTable,
uuid,
varchar,
text,
timestamp,
jsonb,
index,
pgEnum,
} from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
import { decks } from './decks';
// AI generation status enum
export const aiGenerationStatusEnum = pgEnum('ai_generation_status', [
'pending',
'processing',
'completed',
'failed',
]);
// AI generation metadata structure
export interface AIGenerationMetadata {
inputTokens?: number;
outputTokens?: number;
totalTokens?: number;
duration?: number;
error?: string;
cardCount?: number;
[key: string]: unknown;
}
export const aiGenerations = pgTable(
'ai_generations',
{
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id').notNull(),
deckId: uuid('deck_id').references(() => decks.id, { onDelete: 'set null' }),
functionName: varchar('function_name', { length: 100 }).notNull(),
prompt: text('prompt').notNull(),
model: varchar('model', { length: 100 }),
status: aiGenerationStatusEnum('status').default('pending').notNull(),
metadata: jsonb('metadata').default({}).$type<AIGenerationMetadata>(),
completedAt: timestamp('completed_at', { withTimezone: true }),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
},
(table) => [
index('idx_ai_generations_user_id').on(table.userId),
index('idx_ai_generations_deck_id').on(table.deckId),
index('idx_ai_generations_status').on(table.status),
index('idx_ai_generations_created_at').on(table.createdAt),
]
);
export const aiGenerationsRelations = relations(aiGenerations, ({ one }) => ({
deck: one(decks, {
fields: [aiGenerations.deckId],
references: [decks.id],
}),
}));
export type AIGeneration = typeof aiGenerations.$inferSelect;
export type NewAIGeneration = typeof aiGenerations.$inferInsert;

View file

@ -0,0 +1,57 @@
import {
pgTable,
uuid,
integer,
timestamp,
index,
pgEnum,
decimal,
unique,
} from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
import { cards } from './cards';
// Progress status enum (SM-2 algorithm states)
export const progressStatusEnum = pgEnum('progress_status', [
'new',
'learning',
'review',
'relearning',
]);
export const cardProgress = pgTable(
'card_progress',
{
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id').notNull(),
cardId: uuid('card_id')
.notNull()
.references(() => cards.id, { onDelete: 'cascade' }),
// SM-2 algorithm fields
easeFactor: decimal('ease_factor', { precision: 4, scale: 2 }).default('2.5').notNull(),
interval: integer('interval').default(0).notNull(), // Days until next review
repetitions: integer('repetitions').default(0).notNull(),
lastReviewed: timestamp('last_reviewed', { withTimezone: true }),
nextReview: timestamp('next_review', { withTimezone: true }),
status: progressStatusEnum('status').default('new').notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
},
(table) => [
index('idx_card_progress_user_id').on(table.userId),
index('idx_card_progress_card_id').on(table.cardId),
index('idx_card_progress_next_review').on(table.nextReview),
index('idx_card_progress_status').on(table.status),
unique('unique_user_card').on(table.userId, table.cardId),
]
);
export const cardProgressRelations = relations(cardProgress, ({ one }) => ({
card: one(cards, {
fields: [cardProgress.cardId],
references: [cards.id],
}),
}));
export type CardProgress = typeof cardProgress.$inferSelect;
export type NewCardProgress = typeof cardProgress.$inferInsert;

View file

@ -0,0 +1,82 @@
import {
pgTable,
uuid,
varchar,
text,
integer,
boolean,
timestamp,
jsonb,
index,
pgEnum,
} from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
import { decks } from './decks';
import { cardProgress } from './cardProgress';
// Card type enum
export const cardTypeEnum = pgEnum('card_type', ['text', 'flashcard', 'quiz', 'mixed']);
// Card content types
export interface TextContent {
text: string;
formatting?: {
bold?: boolean;
italic?: boolean;
underline?: boolean;
};
}
export interface FlashcardContent {
front: string;
back: string;
hint?: string;
}
export interface QuizContent {
question: string;
options: string[];
correctAnswer: number;
explanation?: string;
}
export interface MixedContent {
sections: Array<TextContent | FlashcardContent | QuizContent>;
}
export type CardContent = TextContent | FlashcardContent | QuizContent | MixedContent;
export const cards = pgTable(
'cards',
{
id: uuid('id').primaryKey().defaultRandom(),
deckId: uuid('deck_id')
.notNull()
.references(() => decks.id, { onDelete: 'cascade' }),
position: integer('position').notNull().default(0),
title: varchar('title', { length: 255 }),
content: jsonb('content').notNull().$type<CardContent>(),
cardType: cardTypeEnum('card_type').notNull(),
aiModel: varchar('ai_model', { length: 100 }),
aiPrompt: text('ai_prompt'),
version: integer('version').default(1).notNull(),
isFavorite: boolean('is_favorite').default(false).notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
},
(table) => [
index('idx_cards_deck_id').on(table.deckId),
index('idx_cards_position').on(table.deckId, table.position),
]
);
export const cardsRelations = relations(cards, ({ one, many }) => ({
deck: one(decks, {
fields: [cards.deckId],
references: [decks.id],
}),
progress: many(cardProgress),
}));
export type Card = typeof cards.$inferSelect;
export type NewCard = typeof cards.$inferInsert;

View file

@ -0,0 +1,35 @@
import {
pgTable,
uuid,
date,
integer,
decimal,
text,
timestamp,
index,
unique,
} from 'drizzle-orm/pg-core';
export const dailyProgress = pgTable(
'daily_progress',
{
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id').notNull(),
date: date('date').notNull(),
cardsStudied: integer('cards_studied').default(0).notNull(),
timeSpentMinutes: integer('time_spent_minutes').default(0).notNull(),
accuracyPercentage: decimal('accuracy_percentage', { precision: 5, scale: 2 }).default('0').notNull(),
decksStudied: text('decks_studied').array().default([]),
sessionsCompleted: integer('sessions_completed').default(0).notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
},
(table) => [
index('idx_daily_progress_user_id').on(table.userId),
index('idx_daily_progress_date').on(table.date),
unique('unique_user_date').on(table.userId, table.date),
]
);
export type DailyProgress = typeof dailyProgress.$inferSelect;
export type NewDailyProgress = typeof dailyProgress.$inferInsert;

View file

@ -0,0 +1,46 @@
import {
pgTable,
uuid,
varchar,
text,
boolean,
integer,
timestamp,
jsonb,
index,
} from 'drizzle-orm/pg-core';
// Template data structure
export interface DeckTemplateData {
cards: Array<{
title?: string;
content: Record<string, unknown>;
cardType: 'text' | 'flashcard' | 'quiz' | 'mixed';
}>;
settings?: Record<string, unknown>;
tags?: string[];
}
export const deckTemplates = pgTable(
'deck_templates',
{
id: uuid('id').primaryKey().defaultRandom(),
title: varchar('title', { length: 255 }).notNull(),
description: text('description'),
category: varchar('category', { length: 100 }),
templateData: jsonb('template_data').notNull().$type<DeckTemplateData>(),
isActive: boolean('is_active').default(true).notNull(),
isPublic: boolean('is_public').default(true).notNull(),
popularity: integer('popularity').default(0).notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
},
(table) => [
index('idx_deck_templates_category').on(table.category),
index('idx_deck_templates_is_active').on(table.isActive),
index('idx_deck_templates_popularity').on(table.popularity),
]
);
export type DeckTemplate = typeof deckTemplates.$inferSelect;
export type NewDeckTemplate = typeof deckTemplates.$inferInsert;

View file

@ -0,0 +1,48 @@
import {
pgTable,
uuid,
varchar,
text,
boolean,
timestamp,
jsonb,
index,
} from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
import { cards } from './cards';
import { studySessions } from './studySessions';
import { aiGenerations } from './aiGenerations';
export const decks = pgTable(
'decks',
{
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id').notNull(),
title: varchar('title', { length: 255 }).notNull(),
description: text('description'),
coverImageUrl: text('cover_image_url'),
isPublic: boolean('is_public').default(false).notNull(),
isFeatured: boolean('is_featured').default(false).notNull(),
featuredAt: timestamp('featured_at', { withTimezone: true }),
settings: jsonb('settings').default({}).$type<Record<string, unknown>>(),
tags: text('tags').array().default([]),
metadata: jsonb('metadata').default({}).$type<Record<string, unknown>>(),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
},
(table) => [
index('idx_decks_user_id').on(table.userId),
index('idx_decks_is_public').on(table.isPublic),
index('idx_decks_is_featured').on(table.isFeatured),
index('idx_decks_updated_at').on(table.updatedAt),
]
);
export const decksRelations = relations(decks, ({ many }) => ({
cards: many(cards),
studySessions: many(studySessions),
aiGenerations: many(aiGenerations),
}));
export type Deck = typeof decks.$inferSelect;
export type NewDeck = typeof decks.$inferInsert;

View file

@ -0,0 +1,16 @@
// Export all schemas
export * from './decks';
export * from './cards';
export * from './studySessions';
export * from './cardProgress';
export * from './deckTemplates';
export * from './aiGenerations';
export * from './userStats';
export * from './dailyProgress';
// Re-export relations for use with Drizzle query builder
export { decksRelations } from './decks';
export { cardsRelations } from './cards';
export { studySessionsRelations } from './studySessions';
export { cardProgressRelations } from './cardProgress';
export { aiGenerationsRelations } from './aiGenerations';

View file

@ -0,0 +1,47 @@
import {
pgTable,
uuid,
varchar,
integer,
timestamp,
index,
pgEnum,
} from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
import { decks } from './decks';
// Study mode enum
export const studyModeEnum = pgEnum('study_mode', ['all', 'new', 'review', 'favorites', 'random']);
export const studySessions = pgTable(
'study_sessions',
{
id: uuid('id').primaryKey().defaultRandom(),
deckId: uuid('deck_id')
.notNull()
.references(() => decks.id, { onDelete: 'cascade' }),
userId: uuid('user_id').notNull(),
mode: studyModeEnum('mode').notNull(),
totalCards: integer('total_cards').notNull().default(0),
completedCards: integer('completed_cards').notNull().default(0),
correctCards: integer('correct_cards').notNull().default(0),
startedAt: timestamp('started_at', { withTimezone: true }).defaultNow().notNull(),
completedAt: timestamp('completed_at', { withTimezone: true }),
timeSpentSeconds: integer('time_spent_seconds').default(0).notNull(),
},
(table) => [
index('idx_study_sessions_user_id').on(table.userId),
index('idx_study_sessions_deck_id').on(table.deckId),
index('idx_study_sessions_started_at').on(table.startedAt),
]
);
export const studySessionsRelations = relations(studySessions, ({ one }) => ({
deck: one(decks, {
fields: [studySessions.deckId],
references: [decks.id],
}),
}));
export type StudySession = typeof studySessions.$inferSelect;
export type NewStudySession = typeof studySessions.$inferInsert;

View file

@ -0,0 +1,33 @@
import {
pgTable,
uuid,
integer,
decimal,
date,
timestamp,
index,
} from 'drizzle-orm/pg-core';
export const userStats = pgTable(
'user_stats',
{
userId: uuid('user_id').primaryKey(),
totalWins: integer('total_wins').default(0).notNull(),
totalSessions: integer('total_sessions').default(0).notNull(),
totalCardsStudied: integer('total_cards_studied').default(0).notNull(),
totalTimeSeconds: integer('total_time_seconds').default(0).notNull(),
averageAccuracy: decimal('average_accuracy', { precision: 5, scale: 2 }).default('0').notNull(),
streakDays: integer('streak_days').default(0).notNull(),
longestStreak: integer('longest_streak').default(0).notNull(),
lastStudyDate: date('last_study_date'),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
},
(table) => [
index('idx_user_stats_total_wins').on(table.totalWins),
index('idx_user_stats_streak_days').on(table.streakDays),
]
);
export type UserStats = typeof userStats.$inferSelect;
export type NewUserStats = typeof userStats.$inferInsert;

View file

@ -0,0 +1,105 @@
import { getDb, closeDb } from './client';
import { deckTemplates } from './schema';
/**
* Seed the database with initial data
*/
async function seed() {
console.log('Seeding database...');
const db = getDb();
try {
// Seed deck templates
const templates = [
{
title: 'Language Basics',
description: 'Learn basic vocabulary and phrases for a new language',
category: 'languages',
templateData: {
cards: [
{
cardType: 'flashcard' as const,
content: { front: 'Hello', back: 'Hallo', hint: 'Greeting' },
},
{
cardType: 'flashcard' as const,
content: { front: 'Goodbye', back: 'Auf Wiedersehen' },
},
],
settings: { language: 'de' },
tags: ['language', 'basics', 'german'],
},
isActive: true,
isPublic: true,
popularity: 100,
},
{
title: 'Math Fundamentals',
description: 'Essential math concepts and formulas',
category: 'education',
templateData: {
cards: [
{
cardType: 'quiz' as const,
content: {
question: 'What is 2 + 2?',
options: ['3', '4', '5', '6'],
correctAnswer: 1,
explanation: '2 + 2 equals 4',
},
},
],
settings: { difficulty: 'beginner' },
tags: ['math', 'basics'],
},
isActive: true,
isPublic: true,
popularity: 80,
},
{
title: 'Programming Concepts',
description: 'Core programming concepts and terminology',
category: 'technology',
templateData: {
cards: [
{
cardType: 'flashcard' as const,
content: {
front: 'Variable',
back: 'A named storage location in memory that holds a value',
},
},
{
cardType: 'flashcard' as const,
content: {
front: 'Function',
back: 'A reusable block of code that performs a specific task',
},
},
],
settings: {},
tags: ['programming', 'coding', 'basics'],
},
isActive: true,
isPublic: true,
popularity: 90,
},
];
console.log('Inserting deck templates...');
await db.insert(deckTemplates).values(templates).onConflictDoNothing();
console.log('Seeding completed successfully!');
} catch (error) {
console.error('Seeding failed:', error);
throw error;
} finally {
await closeDb();
}
}
seed().catch((error) => {
console.error('Seed script failed:', error);
process.exit(1);
});

View file

@ -0,0 +1,44 @@
/**
* Test database connection
* Usage: pnpm db:test
*/
import { getDb, closeDb, sql } from './client';
async function testConnection() {
console.log('Testing database connection...\n');
try {
const db = getDb();
// Test basic connection
const result = await db.execute(sql`SELECT NOW() as current_time, version() as pg_version`);
console.log('✅ Connection successful!');
console.log(` Time: ${result[0].current_time}`);
console.log(` PostgreSQL: ${result[0].pg_version}\n`);
// List tables
const tables = await db.execute(sql`
SELECT tablename
FROM pg_tables
WHERE schemaname = 'public'
ORDER BY tablename
`);
if (tables.length > 0) {
console.log('📋 Tables in database:');
tables.forEach((t: any) => console.log(` - ${t.tablename}`));
} else {
console.log('📋 No tables found. Run "pnpm db:push" to create schema.');
}
console.log('\n✅ All tests passed!');
} catch (error) {
console.error('❌ Connection failed:', error);
process.exit(1);
} finally {
await closeDb();
}
}
testConnection();

View file

@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"esModuleInterop": true,
"strict": true,
"skipLibCheck": true,
"declaration": true,
"declarationMap": true,
"outDir": "./dist",
"rootDir": "./src",
"types": ["node"]
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}

View file

@ -37,5 +37,10 @@ export type {
IconName IconName
} from './types'; } from './types';
// Page Translation Types
export type { LoginTranslations } from './pages/LoginPage.svelte';
export type { RegisterTranslations } from './pages/RegisterPage.svelte';
export type { ForgotPasswordTranslations } from './pages/ForgotPasswordPage.svelte';
// Icon paths // Icon paths
export { iconPaths } from './icons/iconPaths'; export { iconPaths } from './icons/iconPaths';

View file

@ -5,6 +5,38 @@
type PageMode = 'form' | 'success'; type PageMode = 'form' | 'success';
/** Translation strings for the forgot password page */
export interface ForgotPasswordTranslations {
titleForm: string;
titleSuccess: string;
description: string;
emailPlaceholder: string;
sendResetLinkButton: string;
sending: string;
backToLogin: string;
resendEmail: string;
// Success message (uses template with email)
successMessage: string;
// Error messages
emailRequired: string;
sendFailed: string;
}
/** Default English translations */
const defaultTranslations: ForgotPasswordTranslations = {
titleForm: 'Reset Password',
titleSuccess: 'Email Sent',
description: "Enter your email address and we'll send you a link to reset your password.",
emailPlaceholder: 'Email',
sendResetLinkButton: 'Send Reset Link',
sending: 'Sending...',
backToLogin: 'Back to Login',
resendEmail: 'Resend Email',
successMessage: "We've sent a password reset link to {email}. Please check your inbox.",
emailRequired: 'Email is required',
sendFailed: 'Failed to send reset email'
};
interface Props { interface Props {
/** App name */ /** App name */
appName: string; appName: string;
@ -24,6 +56,8 @@
darkBackground?: string; darkBackground?: string;
/** App slider snippet */ /** App slider snippet */
appSlider?: Snippet; appSlider?: Snippet;
/** Translations for i18n support */
translations?: Partial<ForgotPasswordTranslations>;
} }
let { let {
@ -35,9 +69,18 @@
loginPath = '/login', loginPath = '/login',
lightBackground = '#f5f5f5', lightBackground = '#f5f5f5',
darkBackground = '#121212', darkBackground = '#121212',
appSlider appSlider,
translations = {}
}: Props = $props(); }: Props = $props();
// Merge provided translations with defaults
const t = $derived({ ...defaultTranslations, ...translations });
// Helper to interpolate success message with email
function getSuccessMessage(email: string): string {
return t.successMessage.replace('{email}', email);
}
let loading = $state(false); let loading = $state(false);
let error = $state<string | null>(null); let error = $state<string | null>(null);
let email = $state(''); let email = $state('');
@ -68,7 +111,7 @@
error = null; error = null;
if (!email) { if (!email) {
error = 'Email is required'; error = t.emailRequired;
loading = false; loading = false;
return; return;
} }
@ -82,7 +125,7 @@
email = ''; email = '';
mode = 'success'; mode = 'success';
} else { } else {
error = result.error || 'Failed to send reset email'; error = result.error || t.sendFailed;
} }
} }
</script> </script>
@ -121,7 +164,7 @@
class="mb-6 text-center text-xl font-semibold" class="mb-6 text-center text-xl font-semibold"
style="color: {isDark ? 'rgba(255, 255, 255, 0.9)' : 'rgba(0, 0, 0, 0.9)'};" style="color: {isDark ? 'rgba(255, 255, 255, 0.9)' : 'rgba(0, 0, 0, 0.9)'};"
> >
{mode === 'form' ? 'Reset Password' : 'Email Sent'} {mode === 'form' ? t.titleForm : t.titleSuccess}
</h2> </h2>
<!-- Error Messages --> <!-- Error Messages -->
@ -144,14 +187,14 @@
class="mb-4 text-sm" class="mb-4 text-sm"
style="color: {isDark ? 'rgba(255, 255, 255, 0.7)' : 'rgba(0, 0, 0, 0.7)'};" style="color: {isDark ? 'rgba(255, 255, 255, 0.7)' : 'rgba(0, 0, 0, 0.7)'};"
> >
Enter your email address and we'll send you a link to reset your password. {t.description}
</p> </p>
<div class="mb-4"> <div class="mb-4">
<input <input
type="email" type="email"
bind:value={email} bind:value={email}
placeholder="Email" placeholder={t.emailPlaceholder}
required required
class="h-14 w-full rounded-xl border px-4 text-lg transition-colors focus:outline-none focus:ring-2" class="h-14 w-full rounded-xl border px-4 text-lg transition-colors focus:outline-none focus:ring-2"
style="background-color: {isDark ? 'rgba(0, 0, 0, 0.2)' : 'rgba(255, 255, 255, 0.8)'}; border-color: {isDark ? 'rgba(255, 255, 255, 0.2)' : 'rgba(0, 0, 0, 0.1)'}; color: {isDark ? '#ffffff' : '#000000'}; --tw-ring-color: {primaryColor};" style="background-color: {isDark ? 'rgba(0, 0, 0, 0.2)' : 'rgba(255, 255, 255, 0.8)'}; border-color: {isDark ? 'rgba(255, 255, 255, 0.2)' : 'rgba(0, 0, 0, 0.1)'}; color: {isDark ? '#ffffff' : '#000000'}; --tw-ring-color: {primaryColor};"
@ -165,7 +208,7 @@
style="background-color: {primaryColor}60; border-color: {primaryColor}; color: {isDark ? '#ffffff' : '#000000'};" style="background-color: {primaryColor}60; border-color: {primaryColor}; color: {isDark ? '#ffffff' : '#000000'};"
> >
<Icon name="key" size={20} /> <Icon name="key" size={20} />
{loading ? 'Sending...' : 'Send Reset Link'} {loading ? t.sending : t.sendResetLinkButton}
</button> </button>
</form> </form>
@ -177,7 +220,7 @@
style="color: {isDark ? '#ffffff' : '#000000'};" style="color: {isDark ? '#ffffff' : '#000000'};"
> >
<Icon name="arrow-left" size={20} /> <Icon name="arrow-left" size={20} />
Back to Login {t.backToLogin}
</button> </button>
</div> </div>
@ -196,8 +239,7 @@
class="text-sm text-center px-2" class="text-sm text-center px-2"
style="color: {isDark ? 'rgba(255, 255, 255, 0.7)' : 'rgba(0, 0, 0, 0.7)'};" style="color: {isDark ? 'rgba(255, 255, 255, 0.7)' : 'rgba(0, 0, 0, 0.7)'};"
> >
We've sent a password reset link to <strong>{resetEmail}</strong>. Please check your {@html getSuccessMessage(resetEmail).replace(resetEmail, `<strong>${resetEmail}</strong>`)}
inbox.
</p> </p>
</div> </div>
@ -208,7 +250,7 @@
style="background-color: {primaryColor}60; border-color: {primaryColor}; color: {isDark ? '#ffffff' : '#000000'};" style="background-color: {primaryColor}60; border-color: {primaryColor}; color: {isDark ? '#ffffff' : '#000000'};"
> >
<Icon name="sign-in" size={20} /> <Icon name="sign-in" size={20} />
Back to Login {t.backToLogin}
</button> </button>
<button <button
@ -219,7 +261,7 @@
class="flex h-10 items-center justify-center gap-2 rounded-xl font-medium transition-all hover:opacity-80 border" class="flex h-10 items-center justify-center gap-2 rounded-xl font-medium transition-all hover:opacity-80 border"
style="background-color: {isDark ? 'rgba(255, 255, 255, 0.1)' : 'rgba(255, 255, 255, 0.8)'}; border-color: {isDark ? 'rgba(255, 255, 255, 0.2)' : 'rgba(0, 0, 0, 0.1)'}; color: {isDark ? '#ffffff' : '#000000'};" style="background-color: {isDark ? 'rgba(255, 255, 255, 0.1)' : 'rgba(255, 255, 255, 0.8)'}; border-color: {isDark ? 'rgba(255, 255, 255, 0.2)' : 'rgba(0, 0, 0, 0.1)'}; color: {isDark ? '#ffffff' : '#000000'};"
> >
Resend Email {t.resendEmail}
</button> </button>
</div> </div>
</div> </div>

View file

@ -5,6 +5,60 @@
import GoogleSignInButton from '../components/GoogleSignInButton.svelte'; import GoogleSignInButton from '../components/GoogleSignInButton.svelte';
import AppleSignInButton from '../components/AppleSignInButton.svelte'; import AppleSignInButton from '../components/AppleSignInButton.svelte';
/** Translation strings for the login page */
export interface LoginTranslations {
title: string;
subtitle: string;
emailPlaceholder: string;
passwordPlaceholder: string;
rememberMe: string;
forgotPassword: string;
signInButton: string;
signingIn: string;
success: string;
orDivider: string;
noAccount: string;
createAccount: string;
skipToForm: string;
showPassword: string;
hidePassword: string;
// Error messages
emailRequired: string;
emailInvalid: string;
passwordRequired: string;
signInFailed: string;
googleSignInFailed: string;
// Success messages
signInSuccess: string;
googleSignInSuccess: string;
}
/** Default English translations */
const defaultTranslations: LoginTranslations = {
title: 'Sign In',
subtitle: 'Sign in with your Mana account',
emailPlaceholder: 'Email',
passwordPlaceholder: 'Password',
rememberMe: 'Remember me',
forgotPassword: 'Forgot password?',
signInButton: 'Sign In',
signingIn: 'Signing in...',
success: 'Success!',
orDivider: 'or',
noAccount: "Don't have an account?",
createAccount: 'Create one',
skipToForm: 'Skip to login form',
showPassword: 'Show password',
hidePassword: 'Hide password',
emailRequired: 'Email is required',
emailInvalid: 'Please enter a valid email address',
passwordRequired: 'Password is required',
signInFailed: 'Sign in failed',
googleSignInFailed: 'Google sign in failed',
signInSuccess: 'Successfully signed in. Redirecting...',
googleSignInSuccess: 'Successfully signed in with Google. Redirecting...'
};
interface Props { interface Props {
/** App name */ /** App name */
appName: string; appName: string;
@ -38,6 +92,8 @@
appSlider?: Snippet; appSlider?: Snippet;
/** Header snippet for controls like theme toggle and language selector */ /** Header snippet for controls like theme toggle and language selector */
headerControls?: Snippet; headerControls?: Snippet;
/** Translations for i18n support */
translations?: Partial<LoginTranslations>;
} }
let { let {
@ -56,9 +112,13 @@
lightBackground = '#f5f5f5', lightBackground = '#f5f5f5',
darkBackground = '#121212', darkBackground = '#121212',
appSlider, appSlider,
headerControls headerControls,
translations = {}
}: Props = $props(); }: Props = $props();
// Merge provided translations with defaults
const t = $derived({ ...defaultTranslations, ...translations });
let loading = $state(false); let loading = $state(false);
let error = $state<string | null>(null); let error = $state<string | null>(null);
let errorField = $state<'email' | 'password' | 'general' | null>(null); let errorField = $state<'email' | 'password' | 'general' | null>(null);
@ -135,19 +195,19 @@
clearError(); clearError();
if (!email) { if (!email) {
setError('Email is required', 'email'); setError(t.emailRequired, 'email');
loading = false; loading = false;
return; return;
} }
if (!isValidEmail(email)) { if (!isValidEmail(email)) {
setError('Please enter a valid email address', 'email'); setError(t.emailInvalid, 'email');
loading = false; loading = false;
return; return;
} }
if (!password) { if (!password) {
setError('Password is required', 'password'); setError(t.passwordRequired, 'password');
loading = false; loading = false;
return; return;
} }
@ -159,12 +219,12 @@
if (result.success) { if (result.success) {
// Show success feedback before redirect // Show success feedback before redirect
showSuccess = true; showSuccess = true;
successAnnouncement = 'Successfully signed in. Redirecting...'; successAnnouncement = t.signInSuccess;
setTimeout(() => { setTimeout(() => {
goto(successRedirect); goto(successRedirect);
}, 600); }, 600);
} else { } else {
setError(result.error || 'Sign in failed', 'general'); setError(result.error || t.signInFailed, 'general');
} }
} }
@ -179,12 +239,12 @@
if (result.success) { if (result.success) {
showSuccess = true; showSuccess = true;
successAnnouncement = 'Successfully signed in with Google. Redirecting...'; successAnnouncement = t.googleSignInSuccess;
setTimeout(() => { setTimeout(() => {
goto(successRedirect); goto(successRedirect);
}, 600); }, 600);
} else { } else {
setError(result.error || 'Google sign in failed', 'general'); setError(result.error || t.googleSignInFailed, 'general');
} }
} }
@ -285,7 +345,7 @@
onclick={skipToForm} onclick={skipToForm}
type="button" type="button"
> >
Skip to login form {t.skipToForm}
</button> </button>
<!-- Screen reader announcements --> <!-- Screen reader announcements -->
@ -340,13 +400,13 @@
class="text-center text-xl font-semibold" class="text-center text-xl font-semibold"
style="color: {isDark ? 'rgba(255, 255, 255, 0.9)' : 'rgba(0, 0, 0, 0.9)'};" style="color: {isDark ? 'rgba(255, 255, 255, 0.9)' : 'rgba(0, 0, 0, 0.9)'};"
> >
Sign In {t.title}
</h2> </h2>
<p <p
class="mt-2 text-sm text-center" class="mt-2 text-sm text-center"
style="color: {isDark ? 'rgba(255, 255, 255, 0.6)' : 'rgba(0, 0, 0, 0.6)'};" style="color: {isDark ? 'rgba(255, 255, 255, 0.6)' : 'rgba(0, 0, 0, 0.6)'};"
> >
Sign in with your Mana account {t.subtitle}
</p> </p>
</div> </div>
@ -375,13 +435,13 @@
> >
<!-- Email Field --> <!-- Email Field -->
<div class="mb-3"> <div class="mb-3">
<label for="email" class="sr-only">Email address</label> <label for="email" class="sr-only">{t.emailPlaceholder}</label>
<input <input
id="email" id="email"
type="email" type="email"
bind:this={emailInput} bind:this={emailInput}
bind:value={email} bind:value={email}
placeholder="Email" placeholder={t.emailPlaceholder}
required required
autocomplete="email" autocomplete="email"
aria-invalid={errorField === 'email'} aria-invalid={errorField === 'email'}
@ -393,13 +453,13 @@
<!-- Password Field --> <!-- Password Field -->
<div class="mb-3 relative"> <div class="mb-3 relative">
<label for="password" class="sr-only">Password</label> <label for="password" class="sr-only">{t.passwordPlaceholder}</label>
<input <input
id="password" id="password"
type={showPassword ? 'text' : 'password'} type={showPassword ? 'text' : 'password'}
bind:this={passwordInput} bind:this={passwordInput}
bind:value={password} bind:value={password}
placeholder="Password" placeholder={t.passwordPlaceholder}
required required
autocomplete="current-password" autocomplete="current-password"
aria-invalid={errorField === 'password'} aria-invalid={errorField === 'password'}
@ -411,9 +471,9 @@
type="button" type="button"
onclick={() => (showPassword = !showPassword)} onclick={() => (showPassword = !showPassword)}
class="absolute right-3 top-1/2 -translate-y-1/2 p-2 rounded-lg hover:bg-black/10 dark:hover:bg-white/10 transition-colors touch-target flex items-center justify-center" class="absolute right-3 top-1/2 -translate-y-1/2 p-2 rounded-lg hover:bg-black/10 dark:hover:bg-white/10 transition-colors touch-target flex items-center justify-center"
aria-label={showPassword ? 'Hide password' : 'Show password'} aria-label={showPassword ? t.hidePassword : t.showPassword}
aria-pressed={showPassword} aria-pressed={showPassword}
title={showPassword ? 'Hide password' : 'Show password'} title={showPassword ? t.hidePassword : t.showPassword}
> >
<Icon <Icon
name={showPassword ? 'eye-off' : 'eye'} name={showPassword ? 'eye-off' : 'eye'}
@ -436,7 +496,7 @@
class="text-sm" class="text-sm"
style="color: {isDark ? 'rgba(255, 255, 255, 0.7)' : 'rgba(0, 0, 0, 0.7)'};" style="color: {isDark ? 'rgba(255, 255, 255, 0.7)' : 'rgba(0, 0, 0, 0.7)'};"
> >
Remember me {t.rememberMe}
</span> </span>
</label> </label>
@ -446,7 +506,7 @@
class="text-sm font-medium transition-opacity hover:opacity-70 touch-target flex items-center justify-center px-2" class="text-sm font-medium transition-opacity hover:opacity-70 touch-target flex items-center justify-center px-2"
style="color: {primaryColor};" style="color: {primaryColor};"
> >
Forgot password? {t.forgotPassword}
</button> </button>
</div> </div>
@ -470,13 +530,13 @@
<circle cx="12" cy="12" r="10" stroke-opacity="0.25" /> <circle cx="12" cy="12" r="10" stroke-opacity="0.25" />
<path d="M12 2a10 10 0 0 1 10 10" stroke-linecap="round" /> <path d="M12 2a10 10 0 0 1 10 10" stroke-linecap="round" />
</svg> </svg>
<span>Signing in...</span> <span>{t.signingIn}</span>
{:else if showSuccess} {:else if showSuccess}
<Icon name="check" size={20} /> <Icon name="check" size={20} />
<span>Success!</span> <span>{t.success}</span>
{:else} {:else}
<Icon name="sign-in" size={20} /> <Icon name="sign-in" size={20} />
<span>Sign In</span> <span>{t.signInButton}</span>
{/if} {/if}
</button> </button>
</form> </form>
@ -485,7 +545,7 @@
{#if enableGoogle || enableApple} {#if enableGoogle || enableApple}
<div class="my-4 flex items-center gap-3" role="separator" aria-orientation="horizontal"> <div class="my-4 flex items-center gap-3" role="separator" aria-orientation="horizontal">
<div class="flex-1 border-t" style="border-color: {isDark ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)'};"></div> <div class="flex-1 border-t" style="border-color: {isDark ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)'};"></div>
<span class="text-xs" style="color: {isDark ? 'rgba(255, 255, 255, 0.5)' : 'rgba(0, 0, 0, 0.5)'};">or</span> <span class="text-xs" style="color: {isDark ? 'rgba(255, 255, 255, 0.5)' : 'rgba(0, 0, 0, 0.5)'};">{t.orDivider}</span>
<div class="flex-1 border-t" style="border-color: {isDark ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)'};"></div> <div class="flex-1 border-t" style="border-color: {isDark ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)'};"></div>
</div> </div>
@ -505,14 +565,14 @@
class="text-sm" class="text-sm"
style="color: {isDark ? 'rgba(255, 255, 255, 0.6)' : 'rgba(0, 0, 0, 0.6)'};" style="color: {isDark ? 'rgba(255, 255, 255, 0.6)' : 'rgba(0, 0, 0, 0.6)'};"
> >
Don't have an account? {t.noAccount}
<button <button
type="button" type="button"
onclick={() => goto(registerPath)} onclick={() => goto(registerPath)}
class="font-medium transition-opacity hover:opacity-70 touch-target inline-flex items-center justify-center px-1" class="font-medium transition-opacity hover:opacity-70 touch-target inline-flex items-center justify-center px-1"
style="color: {primaryColor};" style="color: {primaryColor};"
> >
Create one {t.createAccount}
</button> </button>
</p> </p>
</div> </div>

View file

@ -5,6 +5,52 @@
import type { Snippet } from 'svelte'; import type { Snippet } from 'svelte';
/** Translation strings for the register page */
export interface RegisterTranslations {
title: string;
emailPlaceholder: string;
passwordPlaceholder: string;
confirmPasswordPlaceholder: string;
passwordRequirements: string;
createAccountButton: string;
creatingAccount: string;
backToLogin: string;
showPassword: string;
hidePassword: string;
// Error messages
emailRequired: string;
passwordRequired: string;
confirmPasswordRequired: string;
passwordsDoNotMatch: string;
passwordTooShort: string;
passwordStrengthError: string;
registrationFailed: string;
// Success messages
accountCreated: string;
}
/** Default English translations */
const defaultTranslations: RegisterTranslations = {
title: 'Create Account',
emailPlaceholder: 'Email',
passwordPlaceholder: 'Password',
confirmPasswordPlaceholder: 'Confirm Password',
passwordRequirements: 'Password must be at least 8 characters with lowercase, uppercase, number, and special character.',
createAccountButton: 'Create Account',
creatingAccount: 'Creating Account...',
backToLogin: 'Back to Login',
showPassword: 'Show password',
hidePassword: 'Hide password',
emailRequired: 'Email is required',
passwordRequired: 'Password is required',
confirmPasswordRequired: 'Please confirm your password',
passwordsDoNotMatch: 'Passwords do not match',
passwordTooShort: 'Password must be at least 8 characters',
passwordStrengthError: 'Password must include lowercase, uppercase, number, and special character',
registrationFailed: 'Registration failed',
accountCreated: 'Account created! Please check your email to verify your account.'
};
interface Props { interface Props {
/** App name */ /** App name */
appName: string; appName: string;
@ -26,6 +72,8 @@
darkBackground?: string; darkBackground?: string;
/** App slider snippet */ /** App slider snippet */
appSlider?: Snippet; appSlider?: Snippet;
/** Translations for i18n support */
translations?: Partial<RegisterTranslations>;
} }
let { let {
@ -38,9 +86,13 @@
loginPath = '/login', loginPath = '/login',
lightBackground = '#f5f5f5', lightBackground = '#f5f5f5',
darkBackground = '#121212', darkBackground = '#121212',
appSlider appSlider,
translations = {}
}: Props = $props(); }: Props = $props();
// Merge provided translations with defaults
const t = $derived({ ...defaultTranslations, ...translations });
let loading = $state(false); let loading = $state(false);
let error = $state<string | null>(null); let error = $state<string | null>(null);
let success = $state(false); let success = $state(false);
@ -98,31 +150,31 @@
// Validation // Validation
if (!email) { if (!email) {
error = 'Email is required'; error = t.emailRequired;
loading = false; loading = false;
return; return;
} }
if (!password) { if (!password) {
error = 'Password is required'; error = t.passwordRequired;
loading = false; loading = false;
return; return;
} }
if (!confirmPassword) { if (!confirmPassword) {
error = 'Please confirm your password'; error = t.confirmPasswordRequired;
loading = false; loading = false;
return; return;
} }
if (password !== confirmPassword) { if (password !== confirmPassword) {
error = 'Passwords do not match'; error = t.passwordsDoNotMatch;
loading = false; loading = false;
return; return;
} }
if (password.length < 8) { if (password.length < 8) {
error = 'Password must be at least 8 characters'; error = t.passwordTooShort;
loading = false; loading = false;
return; return;
} }
@ -134,7 +186,7 @@
const hasSymbol = /[^a-zA-Z0-9]/.test(password); const hasSymbol = /[^a-zA-Z0-9]/.test(password);
if (!hasLowercase || !hasUppercase || !hasDigit || !hasSymbol) { if (!hasLowercase || !hasUppercase || !hasDigit || !hasSymbol) {
error = 'Password must include lowercase, uppercase, number, and special character'; error = t.passwordStrengthError;
loading = false; loading = false;
return; return;
} }
@ -153,7 +205,7 @@
goto(successRedirect); goto(successRedirect);
} }
} else { } else {
error = result.error || 'Registration failed'; error = result.error || t.registrationFailed;
} }
} }
</script> </script>
@ -192,7 +244,7 @@
class="mb-6 text-center text-xl font-semibold" class="mb-6 text-center text-xl font-semibold"
style="color: {isDark ? 'rgba(255, 255, 255, 0.9)' : 'rgba(0, 0, 0, 0.9)'};" style="color: {isDark ? 'rgba(255, 255, 255, 0.9)' : 'rgba(0, 0, 0, 0.9)'};"
> >
Create Account {t.title}
</h2> </h2>
<!-- Error Messages --> <!-- Error Messages -->
@ -206,7 +258,7 @@
{#if success && needsVerification} {#if success && needsVerification}
<div class="mb-4 rounded-xl bg-green-500/20 border border-green-500/30 p-3"> <div class="mb-4 rounded-xl bg-green-500/20 border border-green-500/30 p-3">
<p class="text-sm text-green-500"> <p class="text-sm text-green-500">
Account created! Please check your email to verify your account. {t.accountCreated}
</p> </p>
</div> </div>
{/if} {/if}
@ -223,7 +275,7 @@
<input <input
type="email" type="email"
bind:value={email} bind:value={email}
placeholder="Email" placeholder={t.emailPlaceholder}
required required
class="h-14 w-full rounded-xl border px-4 text-lg transition-colors focus:outline-none focus:ring-2" class="h-14 w-full rounded-xl border px-4 text-lg transition-colors focus:outline-none focus:ring-2"
style="background-color: {isDark ? 'rgba(0, 0, 0, 0.2)' : 'rgba(255, 255, 255, 0.8)'}; border-color: {isDark ? 'rgba(255, 255, 255, 0.2)' : 'rgba(0, 0, 0, 0.1)'}; color: {isDark ? '#ffffff' : '#000000'}; --tw-ring-color: {primaryColor};" style="background-color: {isDark ? 'rgba(0, 0, 0, 0.2)' : 'rgba(255, 255, 255, 0.8)'}; border-color: {isDark ? 'rgba(255, 255, 255, 0.2)' : 'rgba(0, 0, 0, 0.1)'}; color: {isDark ? '#ffffff' : '#000000'}; --tw-ring-color: {primaryColor};"
@ -234,7 +286,7 @@
<input <input
type={showPassword ? 'text' : 'password'} type={showPassword ? 'text' : 'password'}
bind:value={password} bind:value={password}
placeholder="Password" placeholder={t.passwordPlaceholder}
required required
minlength={8} minlength={8}
class="h-14 w-full rounded-xl border px-4 pr-12 text-lg transition-colors focus:outline-none focus:ring-2" class="h-14 w-full rounded-xl border px-4 pr-12 text-lg transition-colors focus:outline-none focus:ring-2"
@ -244,6 +296,7 @@
type="button" type="button"
onclick={() => (showPassword = !showPassword)} onclick={() => (showPassword = !showPassword)}
class="absolute right-3 top-1/2 -translate-y-1/2 p-2 rounded-lg hover:bg-black/10 dark:hover:bg-white/10 transition-colors" class="absolute right-3 top-1/2 -translate-y-1/2 p-2 rounded-lg hover:bg-black/10 dark:hover:bg-white/10 transition-colors"
aria-label={showPassword ? t.hidePassword : t.showPassword}
> >
<Icon <Icon
name={showPassword ? 'eye-off' : 'eye'} name={showPassword ? 'eye-off' : 'eye'}
@ -257,7 +310,7 @@
<input <input
type={showConfirmPassword ? 'text' : 'password'} type={showConfirmPassword ? 'text' : 'password'}
bind:value={confirmPassword} bind:value={confirmPassword}
placeholder="Confirm Password" placeholder={t.confirmPasswordPlaceholder}
required required
minlength={8} minlength={8}
class="h-14 w-full rounded-xl border px-4 pr-12 text-lg transition-colors focus:outline-none focus:ring-2" class="h-14 w-full rounded-xl border px-4 pr-12 text-lg transition-colors focus:outline-none focus:ring-2"
@ -267,6 +320,7 @@
type="button" type="button"
onclick={() => (showConfirmPassword = !showConfirmPassword)} onclick={() => (showConfirmPassword = !showConfirmPassword)}
class="absolute right-3 top-1/2 -translate-y-1/2 p-2 rounded-lg hover:bg-black/10 dark:hover:bg-white/10 transition-colors" class="absolute right-3 top-1/2 -translate-y-1/2 p-2 rounded-lg hover:bg-black/10 dark:hover:bg-white/10 transition-colors"
aria-label={showConfirmPassword ? t.hidePassword : t.showPassword}
> >
<Icon <Icon
name={showConfirmPassword ? 'eye-off' : 'eye'} name={showConfirmPassword ? 'eye-off' : 'eye'}
@ -281,8 +335,7 @@
class="mb-4 mt-2 text-xs" class="mb-4 mt-2 text-xs"
style="color: {isDark ? 'rgba(255, 255, 255, 0.6)' : 'rgba(0, 0, 0, 0.6)'};" style="color: {isDark ? 'rgba(255, 255, 255, 0.6)' : 'rgba(0, 0, 0, 0.6)'};"
> >
Password must be at least 8 characters with lowercase, uppercase, number, and special {t.passwordRequirements}
character.
</p> </p>
<button <button
@ -292,7 +345,7 @@
style="background-color: {primaryColor}60; border-color: {primaryColor}; color: {isDark ? '#ffffff' : '#000000'};" style="background-color: {primaryColor}60; border-color: {primaryColor}; color: {isDark ? '#ffffff' : '#000000'};"
> >
<Icon name="user-plus" size={20} /> <Icon name="user-plus" size={20} />
{loading ? 'Creating Account...' : 'Create Account'} {loading ? t.creatingAccount : t.createAccountButton}
</button> </button>
</form> </form>
@ -304,7 +357,7 @@
style="color: {isDark ? '#ffffff' : '#000000'};" style="color: {isDark ? '#ffffff' : '#000000'};"
> >
<Icon name="arrow-left" size={20} /> <Icon name="arrow-left" size={20} />
Back to Login {t.backToLogin}
</button> </button>
</div> </div>
</div> </div>

View file

@ -45,5 +45,21 @@ export {
mergeWithCommon, mergeWithCommon,
} from './translations/common'; } from './translations/common';
// Auth translations
export {
en as authTranslationsEn,
de as authTranslationsDe,
it as authTranslationsIt,
fr as authTranslationsFr,
es as authTranslationsEs,
type AuthTranslations,
type AuthLocale,
authTranslations,
getAuthTranslations,
getLoginTranslations,
getRegisterTranslations,
getForgotPasswordTranslations,
} from './translations/auth';
// Components // Components
export { LanguageSelector } from './components'; export { LanguageSelector } from './components';

View file

@ -0,0 +1,59 @@
{
"login": {
"title": "Anmelden",
"subtitle": "Melde dich mit deinem Mana-Konto an",
"emailPlaceholder": "E-Mail",
"passwordPlaceholder": "Passwort",
"rememberMe": "Angemeldet bleiben",
"forgotPassword": "Passwort vergessen?",
"signInButton": "Anmelden",
"signingIn": "Anmeldung...",
"success": "Erfolgreich!",
"orDivider": "oder",
"noAccount": "Noch kein Konto?",
"createAccount": "Jetzt erstellen",
"skipToForm": "Zum Anmeldeformular springen",
"showPassword": "Passwort anzeigen",
"hidePassword": "Passwort verbergen",
"emailRequired": "E-Mail ist erforderlich",
"emailInvalid": "Bitte gib eine gültige E-Mail-Adresse ein",
"passwordRequired": "Passwort ist erforderlich",
"signInFailed": "Anmeldung fehlgeschlagen",
"googleSignInFailed": "Google-Anmeldung fehlgeschlagen",
"signInSuccess": "Erfolgreich angemeldet. Weiterleitung...",
"googleSignInSuccess": "Erfolgreich mit Google angemeldet. Weiterleitung..."
},
"register": {
"title": "Konto erstellen",
"emailPlaceholder": "E-Mail",
"passwordPlaceholder": "Passwort",
"confirmPasswordPlaceholder": "Passwort bestätigen",
"passwordRequirements": "Das Passwort muss mindestens 8 Zeichen mit Kleinbuchstaben, Großbuchstaben, Zahl und Sonderzeichen enthalten.",
"createAccountButton": "Konto erstellen",
"creatingAccount": "Konto wird erstellt...",
"backToLogin": "Zurück zur Anmeldung",
"showPassword": "Passwort anzeigen",
"hidePassword": "Passwort verbergen",
"emailRequired": "E-Mail ist erforderlich",
"passwordRequired": "Passwort ist erforderlich",
"confirmPasswordRequired": "Bitte bestätige dein Passwort",
"passwordsDoNotMatch": "Passwörter stimmen nicht überein",
"passwordTooShort": "Passwort muss mindestens 8 Zeichen lang sein",
"passwordStrengthError": "Passwort muss Kleinbuchstaben, Großbuchstaben, Zahl und Sonderzeichen enthalten",
"registrationFailed": "Registrierung fehlgeschlagen",
"accountCreated": "Konto erstellt! Bitte überprüfe deine E-Mails, um dein Konto zu bestätigen."
},
"forgotPassword": {
"titleForm": "Passwort zurücksetzen",
"titleSuccess": "E-Mail gesendet",
"description": "Gib deine E-Mail-Adresse ein und wir senden dir einen Link zum Zurücksetzen deines Passworts.",
"emailPlaceholder": "E-Mail",
"sendResetLinkButton": "Link senden",
"sending": "Wird gesendet...",
"backToLogin": "Zurück zur Anmeldung",
"resendEmail": "E-Mail erneut senden",
"successMessage": "Wir haben einen Link zum Zurücksetzen des Passworts an {email} gesendet. Bitte überprüfe deinen Posteingang.",
"emailRequired": "E-Mail ist erforderlich",
"sendFailed": "E-Mail konnte nicht gesendet werden"
}
}

View file

@ -0,0 +1,59 @@
{
"login": {
"title": "Sign In",
"subtitle": "Sign in with your Mana account",
"emailPlaceholder": "Email",
"passwordPlaceholder": "Password",
"rememberMe": "Remember me",
"forgotPassword": "Forgot password?",
"signInButton": "Sign In",
"signingIn": "Signing in...",
"success": "Success!",
"orDivider": "or",
"noAccount": "Don't have an account?",
"createAccount": "Create one",
"skipToForm": "Skip to login form",
"showPassword": "Show password",
"hidePassword": "Hide password",
"emailRequired": "Email is required",
"emailInvalid": "Please enter a valid email address",
"passwordRequired": "Password is required",
"signInFailed": "Sign in failed",
"googleSignInFailed": "Google sign in failed",
"signInSuccess": "Successfully signed in. Redirecting...",
"googleSignInSuccess": "Successfully signed in with Google. Redirecting..."
},
"register": {
"title": "Create Account",
"emailPlaceholder": "Email",
"passwordPlaceholder": "Password",
"confirmPasswordPlaceholder": "Confirm Password",
"passwordRequirements": "Password must be at least 8 characters with lowercase, uppercase, number, and special character.",
"createAccountButton": "Create Account",
"creatingAccount": "Creating Account...",
"backToLogin": "Back to Login",
"showPassword": "Show password",
"hidePassword": "Hide password",
"emailRequired": "Email is required",
"passwordRequired": "Password is required",
"confirmPasswordRequired": "Please confirm your password",
"passwordsDoNotMatch": "Passwords do not match",
"passwordTooShort": "Password must be at least 8 characters",
"passwordStrengthError": "Password must include lowercase, uppercase, number, and special character",
"registrationFailed": "Registration failed",
"accountCreated": "Account created! Please check your email to verify your account."
},
"forgotPassword": {
"titleForm": "Reset Password",
"titleSuccess": "Email Sent",
"description": "Enter your email address and we'll send you a link to reset your password.",
"emailPlaceholder": "Email",
"sendResetLinkButton": "Send Reset Link",
"sending": "Sending...",
"backToLogin": "Back to Login",
"resendEmail": "Resend Email",
"successMessage": "We've sent a password reset link to {email}. Please check your inbox.",
"emailRequired": "Email is required",
"sendFailed": "Failed to send reset email"
}
}

View file

@ -0,0 +1,59 @@
{
"login": {
"title": "Iniciar Sesión",
"subtitle": "Inicia sesión con tu cuenta Mana",
"emailPlaceholder": "Correo electrónico",
"passwordPlaceholder": "Contraseña",
"rememberMe": "Recordarme",
"forgotPassword": "¿Olvidaste tu contraseña?",
"signInButton": "Iniciar Sesión",
"signingIn": "Iniciando sesión...",
"success": "¡Éxito!",
"orDivider": "o",
"noAccount": "¿No tienes cuenta?",
"createAccount": "Crear una",
"skipToForm": "Ir al formulario de inicio de sesión",
"showPassword": "Mostrar contraseña",
"hidePassword": "Ocultar contraseña",
"emailRequired": "El correo electrónico es obligatorio",
"emailInvalid": "Por favor ingresa un correo electrónico válido",
"passwordRequired": "La contraseña es obligatoria",
"signInFailed": "Error al iniciar sesión",
"googleSignInFailed": "Error al iniciar sesión con Google",
"signInSuccess": "Sesión iniciada correctamente. Redirigiendo...",
"googleSignInSuccess": "Sesión iniciada con Google correctamente. Redirigiendo..."
},
"register": {
"title": "Crear Cuenta",
"emailPlaceholder": "Correo electrónico",
"passwordPlaceholder": "Contraseña",
"confirmPasswordPlaceholder": "Confirmar Contraseña",
"passwordRequirements": "La contraseña debe tener al menos 8 caracteres con minúsculas, mayúsculas, números y caracteres especiales.",
"createAccountButton": "Crear Cuenta",
"creatingAccount": "Creando cuenta...",
"backToLogin": "Volver al inicio de sesión",
"showPassword": "Mostrar contraseña",
"hidePassword": "Ocultar contraseña",
"emailRequired": "El correo electrónico es obligatorio",
"passwordRequired": "La contraseña es obligatoria",
"confirmPasswordRequired": "Por favor confirma tu contraseña",
"passwordsDoNotMatch": "Las contraseñas no coinciden",
"passwordTooShort": "La contraseña debe tener al menos 8 caracteres",
"passwordStrengthError": "La contraseña debe incluir minúsculas, mayúsculas, números y caracteres especiales",
"registrationFailed": "Error en el registro",
"accountCreated": "¡Cuenta creada! Por favor revisa tu correo para verificar tu cuenta."
},
"forgotPassword": {
"titleForm": "Restablecer Contraseña",
"titleSuccess": "Correo Enviado",
"description": "Ingresa tu correo electrónico y te enviaremos un enlace para restablecer tu contraseña.",
"emailPlaceholder": "Correo electrónico",
"sendResetLinkButton": "Enviar Enlace",
"sending": "Enviando...",
"backToLogin": "Volver al inicio de sesión",
"resendEmail": "Reenviar correo",
"successMessage": "Hemos enviado un enlace de restablecimiento a {email}. Por favor revisa tu bandeja de entrada.",
"emailRequired": "El correo electrónico es obligatorio",
"sendFailed": "No se pudo enviar el correo"
}
}

View file

@ -0,0 +1,59 @@
{
"login": {
"title": "Connexion",
"subtitle": "Connectez-vous avec votre compte Mana",
"emailPlaceholder": "Email",
"passwordPlaceholder": "Mot de passe",
"rememberMe": "Se souvenir de moi",
"forgotPassword": "Mot de passe oublié ?",
"signInButton": "Se connecter",
"signingIn": "Connexion...",
"success": "Succès !",
"orDivider": "ou",
"noAccount": "Pas encore de compte ?",
"createAccount": "Créer un compte",
"skipToForm": "Aller au formulaire de connexion",
"showPassword": "Afficher le mot de passe",
"hidePassword": "Masquer le mot de passe",
"emailRequired": "L'email est requis",
"emailInvalid": "Veuillez entrer une adresse email valide",
"passwordRequired": "Le mot de passe est requis",
"signInFailed": "Échec de la connexion",
"googleSignInFailed": "Échec de la connexion Google",
"signInSuccess": "Connexion réussie. Redirection...",
"googleSignInSuccess": "Connexion Google réussie. Redirection..."
},
"register": {
"title": "Créer un compte",
"emailPlaceholder": "Email",
"passwordPlaceholder": "Mot de passe",
"confirmPasswordPlaceholder": "Confirmer le mot de passe",
"passwordRequirements": "Le mot de passe doit contenir au moins 8 caractères avec des minuscules, majuscules, chiffres et caractères spéciaux.",
"createAccountButton": "Créer un compte",
"creatingAccount": "Création du compte...",
"backToLogin": "Retour à la connexion",
"showPassword": "Afficher le mot de passe",
"hidePassword": "Masquer le mot de passe",
"emailRequired": "L'email est requis",
"passwordRequired": "Le mot de passe est requis",
"confirmPasswordRequired": "Veuillez confirmer votre mot de passe",
"passwordsDoNotMatch": "Les mots de passe ne correspondent pas",
"passwordTooShort": "Le mot de passe doit contenir au moins 8 caractères",
"passwordStrengthError": "Le mot de passe doit contenir des minuscules, majuscules, chiffres et caractères spéciaux",
"registrationFailed": "Échec de l'inscription",
"accountCreated": "Compte créé ! Veuillez vérifier votre email pour activer votre compte."
},
"forgotPassword": {
"titleForm": "Réinitialiser le mot de passe",
"titleSuccess": "Email envoyé",
"description": "Entrez votre adresse email et nous vous enverrons un lien pour réinitialiser votre mot de passe.",
"emailPlaceholder": "Email",
"sendResetLinkButton": "Envoyer le lien",
"sending": "Envoi en cours...",
"backToLogin": "Retour à la connexion",
"resendEmail": "Renvoyer l'email",
"successMessage": "Nous avons envoyé un lien de réinitialisation à {email}. Veuillez vérifier votre boîte de réception.",
"emailRequired": "L'email est requis",
"sendFailed": "Impossible d'envoyer l'email"
}
}

View file

@ -0,0 +1,123 @@
/**
* Auth translations exports
*/
import en from './en.json';
import de from './de.json';
import it from './it.json';
import fr from './fr.json';
import es from './es.json';
export { en, de, it, fr, es };
/**
* Auth translations type structure
*/
export interface AuthTranslations {
login: {
title: string;
subtitle: string;
emailPlaceholder: string;
passwordPlaceholder: string;
rememberMe: string;
forgotPassword: string;
signInButton: string;
signingIn: string;
success: string;
orDivider: string;
noAccount: string;
createAccount: string;
skipToForm: string;
showPassword: string;
hidePassword: string;
emailRequired: string;
emailInvalid: string;
passwordRequired: string;
signInFailed: string;
googleSignInFailed: string;
signInSuccess: string;
googleSignInSuccess: string;
};
register: {
title: string;
emailPlaceholder: string;
passwordPlaceholder: string;
confirmPasswordPlaceholder: string;
passwordRequirements: string;
createAccountButton: string;
creatingAccount: string;
backToLogin: string;
showPassword: string;
hidePassword: string;
emailRequired: string;
passwordRequired: string;
confirmPasswordRequired: string;
passwordsDoNotMatch: string;
passwordTooShort: string;
passwordStrengthError: string;
registrationFailed: string;
accountCreated: string;
};
forgotPassword: {
titleForm: string;
titleSuccess: string;
description: string;
emailPlaceholder: string;
sendResetLinkButton: string;
sending: string;
backToLogin: string;
resendEmail: string;
successMessage: string;
emailRequired: string;
sendFailed: string;
};
}
/**
* Supported auth locales
*/
export type AuthLocale = 'en' | 'de' | 'it' | 'fr' | 'es';
/**
* All auth translations by locale
*/
export const authTranslations: Record<AuthLocale, AuthTranslations> = {
en,
de,
it,
fr,
es
};
/**
* Get auth translations by locale
*/
export function getAuthTranslations(locale: string): AuthTranslations {
const supportedLocale = locale as AuthLocale;
if (supportedLocale in authTranslations) {
return authTranslations[supportedLocale];
}
// Default to English
return authTranslations.en;
}
/**
* Get login translations for a specific locale
*/
export function getLoginTranslations(locale: string): AuthTranslations['login'] {
return getAuthTranslations(locale).login;
}
/**
* Get register translations for a specific locale
*/
export function getRegisterTranslations(locale: string): AuthTranslations['register'] {
return getAuthTranslations(locale).register;
}
/**
* Get forgot password translations for a specific locale
*/
export function getForgotPasswordTranslations(locale: string): AuthTranslations['forgotPassword'] {
return getAuthTranslations(locale).forgotPassword;
}

View file

@ -0,0 +1,59 @@
{
"login": {
"title": "Accedi",
"subtitle": "Accedi con il tuo account Mana",
"emailPlaceholder": "Email",
"passwordPlaceholder": "Password",
"rememberMe": "Ricordami",
"forgotPassword": "Password dimenticata?",
"signInButton": "Accedi",
"signingIn": "Accesso in corso...",
"success": "Successo!",
"orDivider": "oppure",
"noAccount": "Non hai un account?",
"createAccount": "Creane uno",
"skipToForm": "Vai al modulo di accesso",
"showPassword": "Mostra password",
"hidePassword": "Nascondi password",
"emailRequired": "L'email è obbligatoria",
"emailInvalid": "Inserisci un indirizzo email valido",
"passwordRequired": "La password è obbligatoria",
"signInFailed": "Accesso fallito",
"googleSignInFailed": "Accesso con Google fallito",
"signInSuccess": "Accesso effettuato. Reindirizzamento...",
"googleSignInSuccess": "Accesso con Google effettuato. Reindirizzamento..."
},
"register": {
"title": "Crea Account",
"emailPlaceholder": "Email",
"passwordPlaceholder": "Password",
"confirmPasswordPlaceholder": "Conferma Password",
"passwordRequirements": "La password deve contenere almeno 8 caratteri con minuscole, maiuscole, numeri e caratteri speciali.",
"createAccountButton": "Crea Account",
"creatingAccount": "Creazione account...",
"backToLogin": "Torna al login",
"showPassword": "Mostra password",
"hidePassword": "Nascondi password",
"emailRequired": "L'email è obbligatoria",
"passwordRequired": "La password è obbligatoria",
"confirmPasswordRequired": "Conferma la tua password",
"passwordsDoNotMatch": "Le password non corrispondono",
"passwordTooShort": "La password deve contenere almeno 8 caratteri",
"passwordStrengthError": "La password deve contenere minuscole, maiuscole, numeri e caratteri speciali",
"registrationFailed": "Registrazione fallita",
"accountCreated": "Account creato! Controlla la tua email per verificare il tuo account."
},
"forgotPassword": {
"titleForm": "Reimposta Password",
"titleSuccess": "Email Inviata",
"description": "Inserisci il tuo indirizzo email e ti invieremo un link per reimpostare la password.",
"emailPlaceholder": "Email",
"sendResetLinkButton": "Invia Link",
"sending": "Invio in corso...",
"backToLogin": "Torna al login",
"resendEmail": "Invia di nuovo",
"successMessage": "Abbiamo inviato un link per reimpostare la password a {email}. Controlla la tua casella di posta.",
"emailRequired": "L'email è obbligatoria",
"sendFailed": "Impossibile inviare l'email"
}
}

713
pnpm-lock.yaml generated

File diff suppressed because it is too large Load diff