# franciscomoretti/sparka architecture

> Architecture diagram of the GitHub repository franciscomoretti/sparka, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-08-04). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/franciscomoretti/sparka
- Repository: https://github.com/franciscomoretti/sparka

## Overview

##### Project Type & Purpose
- This is a full-stack, production-ready AI chat application built on Next.js 15 App Router.
- It provides a unified interface to 70+ AI models (Claude, GPT-4, Gemini, Grok, etc.) with features like document analysis, image generation, code execution, chat branches, resumable streams, deep research, and chat sharing.
- Key tech: Next.js (React Server Components), TypeScript, Tailwind, Vercel AI SDK, tRPC, Drizzle ORM, PostgreSQL, Redis.

##### File-Structure Analysis
- **app/**: Next.js App Router folder with top-level routes and nested layouts.
- `(auth)` and `(chat)` segments partition authorization and chat UIs.
- `app/api/...`: API routes for NextAuth, custom chat-model calls, cron tasks, file uploads, tRPC endpoint.
- **components/**: Shared React components & UI primitives.
- **lib/**: Core services & domain logic: AI integration (`lib/ai`), DB (Drizzle in `lib/db`), credit/reservation, artifacts, utilities.
- **trpc/**: tRPC initialization, client, server, and routers.
- **providers/**: React context providers (model selection, chat state).
- **scripts/**: utilities (e.g., fetch-models).
- **config files**: `drizzle.config.ts`, `next.config.ts`, `vercel.json`, Docker/TOML for deployment.

##### README Insights
- Frontend & backend stacks are clearly separated.
- Emphasis on “unified AI provider integration” through Vercel AI SDK Gateway and fallback logic.
- DB migrations (Drizzle ORM) and optional Redis for real-time features/caching.

##### Main Components
a. **Client / Browser**
- Next.js React components (client & server-component mix)
- Zustand state for UI/UX state
b. **Next.js Server**
- React Server Components & SSR/Streaming
- App Router serving pages under `app/`
- API routes: NextAuth (`app/api/auth`), file upload, chat-model passthrough, cron cleanup
c. **tRPC Layer**
- tRPC server (`trpc/server.tsx`) & routers (`trpc/routers/*.ts`)
- tRPC client (`trpc/query-client.ts`) inside frontend
d. **Business-Logic & Services**
- AI integration service (`lib/ai/*`) using Vercel AI SDK Gateway
- Tooling logic (`lib/ai/tools/…`), prompts, token utils, model features
- Artifact management, credits reservation, chat-branch utils
e. **Data Layer**
- PostgreSQL via Drizzle ORM (`lib/db/client.ts`, `migrations/`, `queries.ts`)
- Redis (caching, rate limiting, resumable streams)
f. **External Services**
- AI providers (OpenAI, Anthropic, Google, etc.) through AI SDK Gateway
- Optional blob storage (file attachments) or Vercel’s built-in storage
- Email/sso providers via NextAuth

##### Relationships & Data Flow
- Client ⇄ Next.js Server (page requests, RSC streaming, hydration)
- Client → tRPC Client → tRPC Server → Business Logic
- Business Logic ↔ AI SDK Gateway ↔ External AI Providers
- Business Logic ↔ Drizzle ORM ↔ PostgreSQL
- Business Logic ↔ Redis (cache tokens, stream cursors, rate-limit)
- API routes for attachments and cron tasks interact directly with services and DB
- Cron cleanup triggered by serverless functions scheduled in Vercel

##### Architectural Patterns & Design Principles
- **Server Components (Next.js)** to minimize client bundle
- **tRPC** for end-to-end type safety between frontend & backend
- **Layered Architecture**: UI → API / Controllers → Services → Data Access
- **Provider Pattern** in React for model, chat, and settings contexts
- **Hexagonal-ish** separation: core logic in `lib/` never directly tied to Next.js
- **Streaming & Resumability** using React streams + Redis to persist cursors

## Diagram (Mermaid)

```mermaid
flowchart TD
  %% Presentation Layer
  subgraph "Presentation Layer"
    direction TB
    UI["Parallelogram: Browser UI"]:::presentation
    ReactComps["Rectangle: React Components"]:::presentation
    Components["Folder: components/"]:::presentation
    Providers["Rectangle: React Context Providers"]:::presentation
    Zustand["Rectangle: Zustand State"]:::presentation
  end

  %% API Layer
  subgraph "API Layer"
    direction TB
    NextServer["Rectangle: Next.js Server"]:::api
    subgraph "App Router Segments"
      direction TB
      AuthSeg["Parallelogram: (auth) UI"]:::api
      ChatSeg["Parallelogram: (chat) UI"]:::api
    end
    subgraph "API Routes"
      direction TB
      NextAuthAPI["Rectangle: NextAuth API"]:::api
      ChatModelAPI["Rectangle: Chat-Model Passthrough"]:::api
      ChatCRUD["Rectangle: Chat CRUD"]:::api
      ChatStream["Rectangle: Chat Stream"]:::api
      FileUploadAPI["Rectangle: File Upload"]:::api
      CronCleanup["Rectangle: Cron Cleanup"]:::api
    end
    subgraph "tRPC"
      direction TB
      TRPCClient["Rectangle: tRPC Client"]:::api
      TRPCReact["Rectangle: tRPC React Binding"]:::api
      TRPCServer["Rectangle: tRPC Server"]:::api
      subgraph "Routers"
        direction TB
        ChatRouter["Rectangle: chat.router.ts"]:::api
        CreditsRouter["Rectangle: credits.router.ts"]:::api
        DocumentRouter["Rectangle: document.router.ts"]:::api
        ModelsRouter["Rectangle: models.router.ts"]:::api
        VoteRouter["Rectangle: vote.router.ts"]:::api
      end
    end
  end

  %% Service Layer
  subgraph "Service Layer"
    direction TB
    AIService["Rectangle: AI Integration Service"]:::service
    Tools["Folder: lib/ai/tools/"]:::service
    Artifacts["Rectangle: Artifact Management"]:::service
    ArtifactFolder["Folder: artifacts/"]:::service
    CreditsService["Rectangle: Credit Reservation"]:::service
    RateLimit["Rectangle: Rate Limit Utility"]:::service
    StreamStore["Rectangle: Streaming State Store"]:::service
  end

  %% Data Layer
  subgraph "Data Layer"
    direction TB
    Postgres["Cylinder: PostgreSQL"]:::data
    Redis["Cylinder: Redis"]:::data
  end

  %% External Services Layer
  subgraph "External Services"
    direction TB
    AIProviders["Cloud: AI Providers"]:::external
    OAuth["Cloud: OAuth Providers"]:::external
    Storage["Cloud: Blob Storage"]:::external
  end

  %% Connections
  UI -->|"HTTP(S) Page Requests / Streaming"| NextServer
  UI -->|"RPC Calls"| TRPCClient
  ReactComps --> UI
  Components --> ReactComps
  Providers --> ReactComps
  Zustand --> ReactComps

  NextServer -->|renders App Router| AuthSeg
  NextServer -->|renders App Router| ChatSeg

  NextServer -->|HTTP| NextAuthAPI
  NextServer -->|HTTP| ChatModelAPI
  ChatSeg -->|HTTP| ChatCRUD
  ChatSeg -->|HTTP| ChatStream
  ChatSeg -->|HTTP| FileUploadAPI
  CronCleanup -->|scheduled| NextServer

  TRPCClient -->|"tRPC Protocol"| TRPCServer
  TRPCReact --> TRPCClient
  NextServer --> TRPCServer
  TRPCServer --> ChatRouter
  TRPCServer --> CreditsRouter
  TRPCServer --> DocumentRouter
  TRPCServer --> ModelsRouter
  TRPCServer --> VoteRouter

  TRPCServer --> AIService
  TRPCServer --> Artifacts
  TRPCServer --> CreditsService
  TRPCServer --> RateLimit

  AIService -->|SDK Gateway| AIProviders
  AIService -->|uses| Tools

  Artifacts --> Storage
  Artifacts -->|reads/writes| Postgres

  CreditsService -->|reads/writes| Postgres
  RateLimit -->|reads/writes| Redis
  StreamStore -->|reads/writes| Redis

  ChatStream --> StreamStore

  AIService --> Postgres
  DocumentRouter --> AIService

  %% Data Layer
  AIService --> Postgres
  CreditsService --> Postgres

  %% Cron Cleanup direct DB
  CronCleanup -->|cleanup tasks| Postgres

  %% Click Events
  click AuthSeg "https://github.com/franciscomoretti/sparka/tree/main/app/(auth)/"
  click ChatSeg "https://github.com/franciscomoretti/sparka/tree/main/app/(chat)/"
  click NextAuthAPI "https://github.com/franciscomoretti/sparka/blob/main/app/(auth)/api/auth/[...nextauth]/route.ts"
  click ChatModelAPI "https://github.com/franciscomoretti/sparka/blob/main/app/api/chat-model/route.ts"
  click ChatCRUD "https://github.com/franciscomoretti/sparka/blob/main/app/(chat)/api/chat/route.ts"
  click ChatStream "https://github.com/franciscomoretti/sparka/blob/main/app/(chat)/api/chat/[id]/stream/route.ts"
  click FileUploadAPI "https://github.com/franciscomoretti/sparka/blob/main/app/(chat)/api/files/upload/route.ts"
  click CronCleanup "https://github.com/franciscomoretti/sparka/blob/main/app/api/cron/cleanup/route.ts"
  click TRPCServer "https://github.com/franciscomoretti/sparka/blob/main/trpc/server.tsx"
  click TRPCClient "https://github.com/franciscomoretti/sparka/blob/main/trpc/query-client.ts"
  click TRPCReact "https://github.com/franciscomoretti/sparka/blob/main/trpc/react.tsx"
  click ChatRouter "https://github.com/franciscomoretti/sparka/blob/main/trpc/routers/chat.router.ts"
  click CreditsRouter "https://github.com/franciscomoretti/sparka/blob/main/trpc/routers/credits.router.ts"
  click DocumentRouter "https://github.com/franciscomoretti/sparka/blob/main/trpc/routers/document.router.ts"
  click ModelsRouter "https://github.com/franciscomoretti/sparka/blob/main/trpc/routers/models.router.ts"
  click VoteRouter "https://github.com/franciscomoretti/sparka/blob/main/trpc/routers/vote.router.ts"
  click AIService "https://github.com/franciscomoretti/sparka/blob/main/lib/ai/providers.ts"
  click Tools "https://github.com/franciscomoretti/sparka/tree/main/lib/ai/tools/"
  click Artifacts "https://github.com/franciscomoretti/sparka/blob/main/lib/artifacts/server.ts"
  click ArtifactFolder "https://github.com/franciscomoretti/sparka/tree/main/artifacts/"
  click CreditsService "https://github.com/franciscomoretti/sparka/blob/main/lib/credits/reserveCredits.ts"
  click RateLimit "https://github.com/franciscomoretti/sparka/blob/main/lib/utils/rate-limit.ts"
  click StreamStore "https://github.com/franciscomoretti/sparka/blob/main/lib/stores/chat-store.ts"
  click Components "https://github.com/franciscomoretti/sparka/tree/main/components/"
  click Providers "https://github.com/franciscomoretti/sparka/blob/main/providers/chat-id-provider.tsx"
  click Providers "https://github.com/franciscomoretti/sparka/blob/main/providers/chat-input-provider.tsx"
  click Providers "https://github.com/franciscomoretti/sparka/blob/main/providers/default-model-provider.tsx"
  click Providers "https://github.com/franciscomoretti/sparka/blob/main/providers/message-tree-provider.tsx"
  click Artifacts "https://github.com/franciscomoretti/sparka/tree/main/artifacts/code/"
  click Artifacts "https://github.com/franciscomoretti/sparka/tree/main/artifacts/sheet/"
  click Artifacts "https://github.com/franciscomoretti/sparka/tree/main/artifacts/text/"

  %% Styles
  classDef presentation fill:#E3F2FD,stroke:#90CAF9,color:#0D47A1
  classDef api fill:#FFF3E0,stroke:#FFB74D,color:#E65100
  classDef service fill:#E8F5E9,stroke:#66BB6A,color:#1B5E20
  classDef data fill:#F3E5F5,stroke:#BA68C8,color:#4A148C
  classDef external fill:#ECEFF1,stroke:#90A4AE,color:#263238
```
