Technical Specifications
System Architecture Overview
MyStoryFlow is built as a modern monorepo with multiple applications serving different purposes:
Application Structure
my-story-flow/
├── apps/
│ ├── web-app/ # Main user interface (Next.js)
│ ├── marketing-site/ # Public website and landing pages
│ ├── admin-app/ # Administrative interface
│ ├── docs-app/ # Documentation site (Nextra)
│ └── tools-app/ # Internal tools and utilities
├── packages/
│ ├── auth/ # Authentication components
│ ├── database/ # Database utilities and types
│ ├── ui/ # Shared UI components
│ └── shared/ # Common utilities
└── lib/ # Shared libraries
``` -->
## Database Schema & Data Models
### Core Tables
#### Campaigns Table
```sql
create table campaigns (
id uuid primary key default gen_random_uuid(),
user_id uuid references auth.users not null,
storyteller_name text not null,
storyteller_email text,
storyteller_phone text,
relationship text not null check (relationship in ('grandparent', 'parent', 'partner', 'other')),
status text not null default 'active' check (status in ('active', 'paused', 'completed')),
prompts_sent integer default 0,
stories_collected integer default 0,
created_at timestamp with time zone default now(),
updated_at timestamp with time zone default now()
);
``` -->
#### Stories Table
```sql
create table stories (
id uuid primary key default gen_random_uuid(),
campaign_id uuid references campaigns on delete cascade not null,
prompt text not null,
response_text text,
response_audio_url text,
response_type text not null check (response_type in ('text', 'voice')),
created_at timestamp with time zone default now(),
updated_at timestamp with time zone default now()
);
``` -->
#### User Profiles
```sql
create table profiles (
id uuid primary key references auth.users on delete cascade,
full_name text,
subscription_tier text default 'free' check (subscription_tier in ('free', 'starter', 'family', 'premium')),
stripe_customer_id text,
created_at timestamp with time zone default now(),
updated_at timestamp with time zone default now()
);
``` -->
### Enhanced Data Models (Planned)
#### Campaign Creator Profile
```typescript
interface CampaignCreator {
id: string
email: string
name: string
// Personalization fields
relationship_to_storyteller:
| 'child'
| 'grandchild'
| 'spouse'
| 'sibling'
| 'friend'
| 'caregiver'
motivation:
| 'preserve_family_history'
| 'gift_giving'
| 'memorial'
| 'bonding'
| 'therapy'
urgency_level: 'casual' | 'moderate' | 'urgent' | 'end_of_life'
tech_comfort: 'beginner' | 'intermediate' | 'advanced'
// AI personalization
communication_style: 'formal' | 'casual' | 'warm' | 'direct'
preferred_prompt_length: 'short' | 'medium' | 'detailed'
interests: string[]
}
``` -->
#### Storyteller Profile
```typescript
interface Storyteller {
id: string
name: string
email: string
// Demographics for AI personalization
age_range: '18-30' | '31-50' | '51-70' | '71-85' | '85+'
gender: 'male' | 'female' | 'non_binary' | 'prefer_not_to_say'
generation:
| 'silent_generation'
| 'baby_boomer'
| 'gen_x'
| 'millennial'
| 'gen_z'
// Background for prompt customization
profession_era: string
life_experiences: string[]
cultural_background: string[]
// Communication preferences
preferred_response_length:
| 'brief'
| 'moderate'
| 'detailed'
| 'storyteller_choice'
comfort_with_technology: 'very_low' | 'low' | 'moderate' | 'high'
response_style: 'voice_preferred' | 'text_preferred' | 'mixed'
// Accessibility needs
visual_impairment: boolean
hearing_impairment: boolean
mobility_limitations: boolean
cognitive_considerations: boolean
// AI voice profile
voice_sample_url?: string
speech_patterns?: {
pace: 'slow' | 'normal' | 'fast'
accent: string
common_phrases: string[]
}
}
``` -->
## AI-Powered Features
### Voice Processing Pipeline
#### Voice Sample Collection
```typescript
interface VoiceOnboarding {
sample_recordings: {
reading_passage: string
natural_speech: string
voice_characteristics: {
pitch_range: number[]
speaking_rate: number
emotional_baseline: 'warm' | 'neutral' | 'energetic'
}
}
voice_profile: {
age_estimation: number
accent_detected: string
speech_clarity: 'excellent' | 'good' | 'needs_support'
background_noise_tolerance: number
}
}
``` -->
#### Real-Time Voice Enhancement
```typescript
interface VoiceProcessing {
raw_transcription: string
enhanced_transcription: string
confidence_score: number
speaker_identification: boolean
emotion_detection: 'happy' | 'sad' | 'excited' | 'nostalgic' | 'neutral'
suggested_clarifications: string[]
auto_paragraph_breaks: boolean
punctuation_enhancement: boolean
}
``` -->
### AI Prompt Generation
#### Context-Aware Prompts
```typescript
interface AIPromptGenerator {
base_prompt: string
personalized_intro: string
cultural_context: string
follow_up_questions: string[]
language_complexity: 'simple' | 'moderate' | 'complex'
examples_provided: boolean
voice_prompt_available: boolean
image_prompts: string[]
}
``` -->
#### Intelligent Follow-Up Generation
```typescript
interface AIFollowUp {
response_analysis: {
topics_mentioned: string[]
emotional_moments: string[]
incomplete_thoughts: string[]
interesting_details: string[]
}
suggested_questions: {
text: string
reason:
| 'clarification'
| 'emotional_depth'
| 'related_story'
| 'factual_detail'
priority: 'high' | 'medium' | 'low'
}[]
next_session_prep: string[]
}
``` -->
## Authentication & Security
### Supabase Authentication
- **Provider**: Supabase Auth
- **Methods**: Email/password, OAuth (Google, GitHub)
- **Row Level Security**: Enabled on all tables
- **Session Management**: JWT tokens with refresh
### Security Policies
```sql
-- Users can only access their own campaigns
create policy "Users can view own campaigns" on campaigns
for select using (auth.uid() = user_id);
-- Users can only access stories from their campaigns
create policy "Users can view stories from own campaigns" on stories
for select using (
exists (
select 1 from campaigns
where campaigns.id = stories.campaign_id
and campaigns.user_id = auth.uid()
)
);
``` -->
## Subscription & Billing
### Freemium Strategy
#### Free Tier: "Memory Starter"
```typescript
interface FreeTier {
campaigns_allowed: 1
prompts_per_campaign: 10
storyteller_responses: 'unlimited'
family_members: 3
voice_minutes: 30
ai_enhancements: 'basic'
book_pages: 20
export_formats: ['pdf']
}
``` -->
#### Paid Tiers
```typescript
interface PaidTiers {
starter: {
price: '$9.99/month'
campaigns_allowed: 3
prompts_per_campaign: 50
family_members: 10
voice_minutes: 180
ai_enhancements: 'advanced'
book_pages: 100
}
family: {
price: '$19.99/month'
campaigns_allowed: 'unlimited'
prompts_per_campaign: 'unlimited'
family_members: 25
voice_minutes: 600
ai_enhancements: 'premium'
book_pages: 'unlimited'
}
}
``` -->
### Stripe Integration
- **Payment Processing**: Stripe
- **Subscription Management**: Stripe Billing
- **Webhooks**: Real-time subscription updates
- **Customer Portal**: Self-service billing management
## API Architecture
### RESTful Endpoints
#### Campaign Management
```typescript
// GET /api/campaigns
// POST /api/campaigns
// GET /api/campaigns/[id]
// PUT /api/campaigns/[id]
// DELETE /api/campaigns/[id]
interface CampaignAPI {
create: (data: CreateCampaignRequest) => Promise<Campaign>
update: (id: string, data: UpdateCampaignRequest) => Promise<Campaign>
delete: (id: string) => Promise<void>
list: (userId: string) => Promise<Campaign[]>
get: (id: string) => Promise<Campaign>
}
``` -->
#### Story Management
```typescript
// GET /api/campaigns/[id]/stories
// POST /api/campaigns/[id]/stories
// GET /api/stories/[id]
// PUT /api/stories/[id]
interface StoryAPI {
create: (campaignId: string, data: CreateStoryRequest) => Promise<Story>
update: (id: string, data: UpdateStoryRequest) => Promise<Story>
list: (campaignId: string) => Promise<Story[]>
get: (id: string) => Promise<Story>
}
``` -->
#### AI Services
```typescript
// POST /api/ai/generate-prompt
// POST /api/ai/enhance-response
// POST /api/ai/transcribe-voice
interface AIAPI {
generatePrompt: (context: PromptContext) => Promise<GeneratedPrompt>
enhanceResponse: (response: string) => Promise<EnhancedResponse>
transcribeVoice: (audioFile: File) => Promise<Transcription>
}
``` -->
## File Storage & Media
### Backblaze B2 Integration
```typescript
interface StorageConfig {
provider: 'backblaze-b2'
bucket: 'mystoryflow-media'
endpoint: 'https://s3.us-west-004.backblazeb2.com'
fileTypes: {
voice_recordings: '.mp3, .wav, .m4a'
photos: '.jpg, .jpeg, .png, .heic'
documents: '.pdf, .docx'
}
limits: {
max_file_size: '50MB'
max_voice_duration: '30 minutes'
storage_per_user: '1GB (free), 10GB (paid)'
}
}
``` -->
### CDN & Optimization
- **Image Optimization**: Next.js Image component with automatic WebP conversion
- **Audio Compression**: Automatic compression for voice recordings
- **Progressive Upload**: Chunked uploads for large files
## Frontend Architecture
### Next.js 14 App Router
```typescript
// Route structure
interface RouteStructure {
'/(auth)': 'Authentication pages'
'/(dashboard)': 'Role-based dashboards'
'/campaigns': 'Campaign management'
'/stories': 'Story collection'
'/books': 'Book creation'
'/family': 'Family member management'
'/billing': 'Subscription management'
'/settings': 'User preferences'
}
``` -->
### State Management
- **Server State**: TanStack Query (React Query)
- **Client State**: React useState + useContext
- **Form State**: React Hook Form with Zod validation
- **Authentication State**: Supabase Auth hooks
### UI Components
```typescript
// Shared component library
interface UIComponents {
forms: 'React Hook Form + Zod validation'
styling: 'Tailwind CSS + shadcn/ui'
animations: 'Framer Motion'
charts: 'Recharts'
notifications: 'React Hot Toast'
modals: 'Radix UI Dialog'
tables: 'TanStack Table'
}
``` -->
## Development Environment
### Technical Requirements
- **Node.js**: 18.18.0+ or 20+
- **Package Manager**: npm or yarn
- **Database**: Supabase (PostgreSQL)
- **Deployment**: Vercel
### Environment Variables
```bash
# Database
NEXT_PUBLIC_SUPABASE_URL=
SUPABASE_SERVICE_ROLE_KEY=
# Authentication
NEXTAUTH_SECRET=
NEXTAUTH_URL=
# Payments
STRIPE_SECRET_KEY=
STRIPE_WEBHOOK_SECRET=
# Storage
BACKBLAZE_APPLICATION_KEY_ID=
BACKBLAZE_APPLICATION_KEY=
BACKBLAZE_BUCKET_ID=
# AI Services
OPENAI_API_KEY=
``` -->
### Development Tools
- **TypeScript**: Full type safety
- **ESLint**: Code linting
- **Prettier**: Code formatting
- **Husky**: Git hooks
- **Jest**: Unit testing
- **Playwright**: E2E testing
## Performance & Monitoring
### Optimization Strategies
- **Server-Side Rendering**: Next.js SSR for SEO
- **Static Generation**: Pre-built pages where possible
- **Image Optimization**: Automatic WebP/AVIF conversion
- **Code Splitting**: Dynamic imports for large components
- **Database Indexing**: Optimized queries with proper indexes
### Monitoring & Analytics
- **Error Tracking**: Sentry
- **Performance**: Vercel Analytics
- **User Analytics**: PostHog
- **Uptime Monitoring**: Uptime Robot
## Deployment & Infrastructure
### Vercel Deployment
```typescript
interface DeploymentConfig {
platform: 'Vercel'
regions: ['iad1', 'sfo1'] // Multi-region deployment
environments: {
production: 'main branch'
staging: 'develop branch'
preview: 'feature branches'
}
build_settings: {
framework: 'Next.js'
node_version: '20.x'
build_command: 'npm run build'
output_directory: '.next'
}
}
``` -->
### CI/CD Pipeline
```yaml
# GitHub Actions workflow
name: Deploy to Vercel
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '20'
- run: npm ci
- run: npm run test
- run: npm run build
``` -->
## Security & Compliance
### Data Protection
- **Encryption**: All data encrypted at rest and in transit
- **GDPR Compliance**: Data portability and deletion rights
- **CCPA Compliance**: California privacy rights
- **HIPAA Considerations**: Secure handling of personal stories
### Privacy Controls
```typescript
interface PrivacySettings {
data_retention: '7 years default, user configurable'
sharing_controls: 'Granular family member permissions'
data_export: 'Full data export in JSON/PDF formats'
account_deletion: 'Complete data removal within 30 days'
}
``` -->
## Integration APIs
### Third-Party Services
```typescript
interface ExternalIntegrations {
email: 'SendGrid for transactional emails'
sms: 'Twilio for SMS notifications'
printing: 'Printful for book printing'
analytics: 'PostHog for user analytics'
support: 'Intercom for customer support'
}
``` -->
### Webhook System
```typescript
interface WebhookConfig {
stripe_webhooks: 'Payment and subscription events'
supabase_webhooks: 'Database change notifications'
custom_webhooks: 'Campaign completion, story milestones'
}
``` -->
This technical specification serves as the foundation for MyStoryFlow's architecture and will be updated as new features are implemented.