@tummycrypt/tsd
v0.1.5
Published
Translation Service for SvelteKit with LibreTranslate and gRPC support
Downloads
71
Maintainers
Readme
TSd - Translation Service Demo
A production-ready translation service for SvelteKit applications with gRPC-Web, LibreTranslate, and Kubernetes support.
Table of Contents
- Quick Start
- Demo Quick Start
- Testing Guide
- Full Evaluation Suite
- Browser Testing
- Development Environments
- Production Deployment
- Architecture
- Configuration
Quick Start
1. Add TSd to Your SvelteKit Project
npm install @tummycrypt/tsdAdd to your vite.config.ts:
import { sveltekit } from '@sveltejs/kit/vite';
import { tsdPlugin } from '@tinyland/tsd/vite';
export default {
plugins: [
sveltekit(),
tsdPlugin({
defaultLocale: 'en',
supportedLocales: ['en', 'es', 'fr', 'de'],
translationProvider: {
type: 'libretranslate',
endpoint: process.env.LIBRETRANSLATE_URL || 'http://localhost:5000'
}
})
]
};Use in your Svelte components:
<script>
import { page } from '$app/stores';
</script>
<tsd native="en">Welcome to our application</tsd>
<tsd native="en">Current locale: {$page.params.locale}</tsd>Demo Quick Start
Want to see TSd in action immediately? Run these commands:
# 1. Simple demo (no containers needed)
nx run tsd-demo:serve
# Open http://localhost:5173/en/tsd-demo
# 2. With real translations (requires podman)
nx run tsd-demo:compose:up # Start LibreTranslate
nx run tsd-demo:serve:http # Start with translation API
# Open http://localhost:5173/en/tsd-demo
# 3. Production-like demo
nx run tsd-demo:compose:prod:up
# Open http://localhost:8080/en/tsd-demoTesting Guide
Unit & Integration Tests
# Run core TSd package tests with coverage
nx run @tinyland/tsd:test --coverage
# Test results (Current: 58 tests, 83.45% coverage):
# ✓ Translation Monad (10 tests) - Functional programming patterns
# ✓ Translation System (15 tests) - Core manager functionality
# ✓ gRPC Integration (12 tests) - gRPC-Web communication
# ✓ Function Map Verification (8 tests) - Locale expansion
# ✓ Async Text Demo (13 tests) - Real-time updatesE2E Test Suite
# Run all E2E tests in different modes
nx run tsd-demo-e2e:e2e:http # Test with HTTP/JSON API
nx run tsd-demo-e2e:e2e:compose # Test with local LibreTranslate
nx run tsd-demo-e2e:e2e:grpc # Test with gRPC-Web + Envoy
# Run E2E tests with specific browsers
nx run tsd-demo-e2e:e2e --browser=chromium
nx run tsd-demo-e2e:e2e --browser=firefox
nx run tsd-demo-e2e:e2e --browser=webkit
# Debug mode with visual browser
npx playwright test --headed --project=chromium
# Or use Nx with proper Playwright config
nx run tsd-demo-e2e:e2e-local -- --headedFull Evaluation Suite
TSd provides comprehensive Nx-based evaluation commands that cover all testing aspects required by Zentaisei's test-strict paradigm. Run these commands to validate the complete adoption lifecycle:
🚀 Complete Evaluation
# Run the full evaluation suite (recommended for releases)
nx run @tinyland/tsd:eval:full
# Includes:
# - Unit tests with coverage (58 tests, 83.45% coverage)
# - E2E tests (HTTP, Compose, gRPC modes)
# - Property-based testing (PBT)
# - Lifecycle testing
# - Test-driven development validation⚡ Quick Evaluation
# Fast validation for development (5-10 minutes)
nx run @tinyland/tsd:eval:quick
# Includes:
# - Core unit tests
# - Basic E2E testing
# - Lifecycle validation🔬 Property-Based Testing (PBT)
# Run comprehensive property-based tests
nx run @tinyland/tsd:eval:pbt
# Tests property invariants:
# - Translation idempotency
# - Locale consistency
# - Cache coherence
# - Error resilience🐳 Container Lifecycle Testing
# Test all container deployment scenarios
nx run @tinyland/tsd:eval:container
# Validates:
# - LibreTranslate container startup/shutdown
# - Full development stack (Envoy + gRPC)
# - Production deployment
# - Container health checks📋 Adoption Lifecycle Testing
# Validate complete package adoption lifecycle
nx run @tinyland/tsd:eval:adoption
# Tests:
# - Package registry integration
# - Dependency resolution (@tinyland/* namespace)
# - Version compatibility
# - Security compliance (package signing, SBOM)
# - Verdaccio local registry functionality🔄 CI/CD Evaluation
# Optimized for continuous integration
nx run @tinyland/tsd:eval:ci
# Streamlined for CI environments:
# - Fast unit tests with coverage
# - Critical E2E scenarios
# - Code quality checks (lint)
# - Essential adoption lifecycle validationIndividual Test Categories
# Core package tests
nx run @tinyland/tsd:test # Unit tests only
nx run @tinyland/tsd:test:coverage # Unit tests with coverage report
nx run @tinyland/tsd:test:e2e # Package-level E2E tests
# Demo application E2E tests
nx run tsd-demo-e2e:e2e:http # HTTP/JSON API testing
nx run tsd-demo-e2e:e2e:compose # With LibreTranslate container
nx run tsd-demo-e2e:e2e:grpc # gRPC-Web + Envoy testing
nx run tsd-demo-e2e:e2e:lifecycle # Adoption lifecycle scenarios
nx run tsd-demo-e2e:e2e:property # Property-based testing
# Test-driven development
nx run tsd-demo-e2e:tdd:development # Iterative TDD (2 iterations)
nx run tsd-demo-e2e:tdd:full # Complete TDD (10 iterations)
nx run tsd-demo-e2e:tdd:ci # CI-optimized TDD (3 iterations)Evaluation Quick Reference
| Command | Duration | Coverage | Use Case |
|---------|----------|----------|----------|
| nx run @tinyland/tsd:eval:quick | 5-10 min | Core functionality | Development validation |
| nx run @tinyland/tsd:eval:full | 20-30 min | Complete suite | Pre-release validation |
| nx run @tinyland/tsd:eval:pbt | 10-15 min | Property invariants | Quality assurance |
| nx run @tinyland/tsd:eval:container | 15-20 min | Deployment scenarios | DevOps validation |
| nx run @tinyland/tsd:eval:adoption | 25-35 min | Package lifecycle | Security compliance |
| nx run @tinyland/tsd:eval:ci | 8-12 min | Critical paths | Continuous integration |
Prerequisites
# Required tools
npm install -g nx
podman --version # For container testing
wait-on --version # For service synchronization
# Optional for enhanced testing
grpcurl --version # For direct gRPC testingBrowser Testing
1. Simple Development Mode (HTTP/JSON)
# Start dev server with mock translations
nx run tsd-demo:serve
# Access at http://localhost:5173
# Features to test:
# - Language switcher (6 languages: en, es, fr, de, ja, zh)
# - Real-time translation updates
# - Cache persistence (refresh to see cached translations)
# - Browser console shows detailed logs2. Local LibreTranslate Mode
# Start LibreTranslate container and dev server
nx run tsd-demo:compose:up
nx run tsd-demo:serve:http
# Access at http://localhost:5173
# LibreTranslate UI at http://localhost:5000
# Features to test:
# - Real translations from LibreTranslate
# - Translation quality for different languages
# - API response times in console3. gRPC-Web Mode with Envoy
# Start full gRPC stack
nx run tsd-demo:compose:grpc:up
nx run tsd-demo:serve:grpc
# Access at http://localhost:5173
# Envoy admin at http://localhost:9901
# Features to test:
# - gRPC-Web binary protocol (check Network tab)
# - Envoy proxy detection in UI
# - Server-sent events for real-time updates
# - Performance improvements over HTTP/JSON4. Full Production Stack
# Build and run production containers
nx run tsd-demo:compose:prod:up
# Services available:
# - Main app: http://localhost:8080
# - HTTPS app: https://localhost:8443 (self-signed cert)
# - Health check: http://localhost:8080/health
# - API endpoint: http://localhost:8080/api/translate
# Monitor services:
nx run tsd-demo:compose:prod:ps # Check container status
nx run tsd-demo:compose:prod:logs # View all logs
# Features to test:
# - Production build optimization
# - Caddy reverse proxy
# - SSL/TLS termination
# - Container health checks
# - Load balancing (if replicas > 1)5. Full Development Stack
# Complete stack with all services
nx run tsd-demo:compose:full:up
# Services:
# - App with Caddy: http://localhost:3000
# - gRPC service: localhost:50051
# - gRPC health: http://localhost:50052/health
# - Envoy proxy: http://localhost:8080
# - Envoy admin: http://localhost:9901
# Test gRPC directly:
grpcurl -plaintext localhost:50051 list
grpcurl -plaintext localhost:50051 translation.TranslationService/GetHealthDevelopment Environments
Quick Reference
| Mode | Command | Services | Use Case |
|---------|-----------------------------------|-----------------------------|-------------------------|
| Dev | nx run tsd-demo:serve | SvelteKit only | Quick development |
| HTTP | nx run tsd-demo:serve:http | SvelteKit + LibreTranslate | Testing translations |
| gRPC | nx run tsd-demo:serve:grpc | Full gRPC stack | Production-like testing |
| Compose | nx run tsd-demo:compose:full:up | All services | Integration testing |
| Prod | nx run tsd-demo:compose:prod:up | Production stack | Pre-deployment testing |
Environment Variables
# Use external LibreTranslate instance
LIBRETRANSLATE_URL=https://libretranslate.com \
LIBRETRANSLATE_API_KEY=your-key \
nx run tsd-demo:serve:http:external
# Configure Envoy endpoint
VITE_ENVOY_ENDPOINT=http://your-envoy:8080 \
nx run tsd-demo:serve
# Kubernetes namespace (for auto-discovery)
K8S_NAMESPACE=translation \
K8S_SERVICE_NAME=tsd-service \
nx run tsd-demo:serveTesting Checklist
When testing TSd in the browser, verify these features:
Basic Functionality
- [ ] Language switcher changes URL and content
- [ ] All text elements translate correctly
- [ ] Browser back/forward navigation works
- [ ] Page refresh maintains selected language
- [ ] No console errors during navigation
Translation Features
- [ ] Real-time translation for new text
- [ ] Cached translations load instantly
- [ ] Fallback to native text on API errors
- [ ] Special characters display correctly
- [ ] RTL languages (if applicable) render properly
Performance & Monitoring
- [ ] Initial page load < 3 seconds
- [ ] Translation requests < 500ms (cached)
- [ ] Console shows detailed timing logs
- [ ] Network tab shows proper caching headers
- [ ] Memory usage remains stable
gRPC-Web Features (when using Envoy)
- [ ] Binary protocol in Network tab
- [ ] Server-sent events connection established
- [ ] Envoy detection shown in UI
- [ ] Graceful fallback if Envoy unavailable
- [ ] Connection recovery after network issues
Production Features
- [ ] HTTPS redirect works correctly
- [ ] Health endpoint returns 200 OK
- [ ] API rate limiting (if configured)
- [ ] Error pages show translated content
- [ ] Metrics endpoint accessible
Production Deployment
Podman Compose (Test Production Locally)
# Build and run production stack
nx run tsd-demo:compose:prod:up
# Services included:
# - LibreTranslate on :5000
# - Envoy proxy on :8080
# - SvelteKit app on :3000
# - Caddy on :80/:443Kubernetes Deployment
Step 1: Build container image
podman build -f apps/tsd-demo/Dockerfile -t your-registry/tsd-app:latest .
podman push your-registry/tsd-app:latestStep 2: Deploy to Kubernetes
apiVersion: apps/v1
kind: Deployment
metadata:
name: tsd-app
spec:
replicas: 3
selector:
matchLabels:
app: tsd-app
template:
metadata:
labels:
app: tsd-app
spec:
containers:
- name: app
image: your-registry/tsd-app:latest
ports:
- containerPort: 3000
env:
- name: LIBRETRANSLATE_URL
value: "http://libretranslate-service:5000"
---
apiVersion: v1
kind: Service
metadata:
name: tsd-app-service
spec:
selector:
app: tsd-app
ports:
- port: 80
targetPort: 3000Architecture & Composability
Monadic Translation System
TSd uses a monadic pattern for composable, error-safe translations:
// Translation monad ensures safe composition
const translation = manager
.getOrCreateTranslation('Hello', 'en', 'es')
.map(text => text.trim())
.map(text => `¡${text}!`)
.getOrElse('Translation failed');Function Map Expansion
The core uses function map expansion for locale management:
// Automatically expands translations across all locales
const key = manager.addTranslationRequest('New feature', 'en');
// Triggers parallel translation to all supported localesNx Monorepo Integration
packages/tsd/ # Core library
├── src/
│ ├── lib/ # Monad implementation
│ ├── vite/ # Vite plugin & gRPC server
│ └── types.ts # TypeScript interfaces
├── tests/
│ └── e2e/ # Comprehensive E2E tests
└── dist/ # Built package
apps/tsd-demo/ # Demo application
├── src/routes/
│ └── [locale]/ # Locale-based routing
├── Dockerfile # Production container
└── podman-compose-*.yml # Deployment configsKey Design Principles
- Monad-based Safety: All translations wrapped in monads for error handling
- Function Composition: Reduce-based transformation pipelines
- Cache-first: Persistent translation cache with filesystem backing
- Protocol Flexibility: HTTP/JSON for dev, gRPC-Web for production
- Zero-config HMR: Automatic hot module replacement in development
Configuration Options
interface TsdConfig {
defaultLocale: string;
supportedLocales: string[];
translationProvider: {
type: 'libretranslate';
endpoint: string;
apiKey?: string;
};
cacheDir?: string; // Default: .tsd-cache
envoy?: {
autoDiscover: boolean; // Auto-detect Kubernetes/Envoy
endpoint?: string; // Override Envoy endpoint
};
}Demo Application Features
Main Demo Page (/[locale]/tsd-demo)
The demo showcases all TSd features in an interactive interface:
Language Switcher
- Dropdown with 6 languages: English, Spanish, French, German, Japanese, Chinese
- URL changes to reflect locale (e.g.,
/en/tsd-demo,/es/tsd-demo) - Smooth transitions between languages
- Browser history integration
Translation Examples
- Simple Text - Basic phrases like "Hello, world!"
- Common Phrases - Everyday expressions (Welcome, Thank you, etc.)
- Longer Text - Paragraph translations demonstrating context preservation
Connection Status Display
- Current locale indicator
- API type (HTTP/JSON or gRPC-Web)
- Transport protocol detection
- Environment information
- Proxy status (Direct HTTP or Envoy)
Debug Console
- Toggle button to show/hide console instructions
- Real-time logs include:
- 🚀 Envoy proxy detection
- 📤 Translation requests with timing
- 📥 Translation responses
- 🔔 Real-time update notifications
- ⚡ Performance metrics
Architecture Information
- Live display of active gRPC-Web APIs
- Protocol switching (HTTP/JSON ↔ gRPC binary)
- Performance comparison between modes
API Endpoints
Test these endpoints directly:
# Health check
curl http://localhost:5173/health
# Translation API (POST)
curl -X POST http://localhost:5173/api/translate \
-H "Content-Type: application/json" \
-d '{
"text": "Hello, world!",
"source": "en",
"target": "es"
}'
# When using production stack:
curl https://localhost:8443/api/translate \
--insecure \
-H "Content-Type: application/json" \
-d '{"text": "Test", "source": "en", "target": "fr"}'Translation Cache Issues
# Clear translation cache
rm -rf .tsd-cache
# Clear browser cache
# Chrome: Cmd+Shift+R (Mac) / Ctrl+Shift+R (Windows/Linux)Container Runtime Issues
If you're seeing Podman connection errors:
# Quick diagnostic
nx run @tinyland/tsd:check-podman
# Interactive fix (can install/reinstall Podman)
nx run @tinyland/tsd:doctor
# Manual restart
podman machine restartE2E Tests Failing
# Run in debug mode to see what's happening
cd apps/tsd-demo-e2e && npx playwright test --headed
# For specific test file
cd apps/tsd-demo-e2e && npx playwright test tsd-service.spec.ts --headed
# Check if services are running
podman ps -a | grep tsd
# View test traces
npx playwright show-trace test-results/*/trace.zipReduce Startup Time
# Use fast mode with only 2 languages
nx run tsd-demo:compose:fast:upEnable Production Mode
# Build optimized version
NODE_ENV=production nx run tsd-demo:build
# Serve production build
nx run tsd-demo:previewMonitor Resource Usage
# Check container stats
podman stats
# View detailed logs with timestamps
nx run tsd-demo:compose:prod:logs -t