# Getting Started

# Getting Started

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [.env](.env)
- [.githooks/pre-commit](.githooks/pre-commit)
- [.windsurfintructions](.windsurfintructions)
- [.windsurfrules](.windsurfrules)
- [AGENTS.md](AGENTS.md)
- [README.md](README.md)
- [docs/ai/README.md](docs/ai/README.md)
- [docs/ai/SKILLS.md](docs/ai/SKILLS.md)
- [docs/ai/patterns.md](docs/ai/patterns.md)
- [docs/gitflow.md](docs/gitflow.md)
- [package.json](package.json)
- [pnpm-lock.yaml](pnpm-lock.yaml)
- [scripts/version-sync.mjs](scripts/version-sync.mjs)
- [src/hooks.server.ts](src/hooks.server.ts)
- [src/lib/api.ts](src/lib/api.ts)
- [src/routes/(app)/system/settings/modules/+page.svelte](src/routes/(app)/system/settings/modules/+page.svelte)
- [src/routes/(app)/system/settings/templates/+page.svelte](src/routes/(app)/system/settings/templates/+page.svelte)
- [src/routes/login/+page.svelte](src/routes/login/+page.svelte)
- [vite.config.ts](vite.config.ts)

</details>



This page provides the technical onboarding documentation for the Primebrick v3 frontend. It covers the prerequisites, workspace configuration, and the development lifecycle for engineers joining the project.

## Development Environment

The Primebrick frontend is built using **SvelteKit** and **Svelte 5**, leveraging **TypeScript** for type safety and **TailwindCSS** for styling [package.json:20-44](). The project utilizes a monorepo-ready structure managed by **pnpm**.

### Prerequisites
*   **Node.js**: Version 20 or higher.
*   **pnpm**: Version 9 or higher (mandatory for workspace management) [pnpm-lock.yaml:1-10]().
*   **Git**: Required for branch management following the GitFlow convention [docs/gitflow.md:1-4]().

### Setup & Installation
From the repository root, initialize the workspace:
```bash
pnpm install
```
This command installs dependencies for the entire workspace, including shared dev tools and SvelteKit primitives [README.md:25-26]().

### Core Commands
| Command | Purpose | Implementation |
| :--- | :--- | :--- |
| `pnpm run dev` | Starts the Vite development server with API proxying. | [package.json:7]() |
| `pnpm run check` | Runs `svelte-check` and `tsc` for full type validation. | [package.json:13]() |
| `pnpm run build` | Bundles the application for production. | [package.json:10]() |
| `pnpm run version:auto` | Manually triggers the version synchronization script. | [package.json:8]() |

**Sources:** [package.json:6-14](), [README.md:24-31](), [pnpm-lock.yaml:1-10]()

---

## The Vite Proxy & API Integration

To facilitate local development without CORS issues, the Vite dev server is configured to proxy requests starting with `/api` to a backend origin.

### Implementation Details
The proxy target is determined dynamically during startup:
1.  Vite loads environment variables using `loadEnv` [vite.config.ts:6]().
2.  It looks for `API_ORIGIN` in `.env`. If missing, it defaults to `http://localhost:3001` [vite.config.ts:7]().
3.  Any request to `/api/*` is forwarded to this target with `changeOrigin: true` [vite.config.ts:24-29]().

### API URL Resolution Diagram
This diagram shows how `apiFetch` resolves URLs differently depending on whether it is running in the browser or during Server-Side Rendering (SSR).

Title: API Request Flow and URL Resolution
```mermaid
graph TD
    subgraph "Natural Language Space"
        A["Client Code"] -- "calls" --> B["apiFetch('/api/v1/...')"]
    end

    subgraph "Code Entity Space"
        B --> C{"Is SSR?"}
        C -- "Yes (Node.js)" --> D["Prepend PUBLIC_API_ORIGIN"]
        C -- "No (Browser)" --> E["Use Relative Path"]
        
        D --> F["fetch(Full URL)"]
        E --> G["Vite Dev Proxy"]
        G --> H["Backend Server"]
    end
    
    style B stroke-width:2px
    style D stroke-width:2px
    style G stroke-width:2px
```
**Sources:** [vite.config.ts:5-31](), [src/lib/api.ts:139-146]()

---

## Versioning & Prebuild Hooks

Primebrick uses an automated versioning system to ensure `package.json` stays in sync with Git tags and branch names. This is enforced by the `scripts/version-sync.mjs` script.

### `version-sync.mjs` Logic
The script executes as a `prebuild` hook [package.json:9](). It performs the following checks:
*   **Branch Detection**: It identifies if the current branch is `release/x.y.z` or `hotfix/x.y.z` [scripts/version-sync.mjs:69-73]().
*   **Validation**: It calculates the expected version based on the latest Git tag. A `release/` branch must increment the **minor** version, while a `hotfix/` branch must increment the **patch** version [scripts/version-sync.mjs:48-52]().
*   **Sync**: If the branch name is valid but `package.json` is outdated, it automatically updates the version field [scripts/version-sync.mjs:97-104]().

Title: Automated Versioning Pipeline
```mermaid
sequenceDiagram
    participant Developer
    participant Git as Git Branch
    participant Sync as version-sync.mjs
    participant Pkg as package.json

    Developer->>Git: checkout release/0.32.0
    Developer->>Sync: pnpm run build (triggers prebuild)
    Sync->>Git: latestTagVersion()
    Git-->>Sync: 0.31.0
    Sync->>Sync: nextVersion("release", 0.31.0) -> 0.32.0
    Sync->>Pkg: read version
    alt version != 0.32.0
        Sync->>Pkg: write version "0.32.0"
    end
    Sync-->>Developer: Success
```
**Sources:** [scripts/version-sync.mjs:1-107](), [package.json:8-9](), [docs/gitflow.md:46-66]()

---

## Svelte 5 Development Standards

Developers must strictly adhere to Svelte 5 Runes. Traditional Svelte 4 syntax (e.g., `export let`, `writable` stores for local state) is prohibited.

### Key Patterns
1.  **Reactive State**: Defined via `let x = $state(initialValue)` [AGENTS.md:15]().
2.  **Derived State**: Use `$derived(a + b)` for simple logic. For complex logic, use `$derived.by(() => { ... })` [AGENTS.md:19-21]().
3.  **Component Props**: Destructured directly from `$props()` with explicit TypeScript interfaces [AGENTS.md:16-18]().
4.  **Event Handling**: Do not use `createEventDispatcher`. Pass callback functions as props (e.g., `onclick: () => void`) [AGENTS.md:22-23]().
5.  **Composition**: Use the `Snippet` type to pass UI fragments as children [AGENTS.md:24-25]().

### Validation Commands
To ensure code quality and type safety, the following commands are used:
*   **Svelte Check**: `svelte-check --tsconfig ./tsconfig.json` validates Svelte files and Runes usage [package.json:13]().
*   **TypeScript Check**: `tsc -p tsconfig.node.json` validates configuration and build scripts [package.json:13]().

**Sources:** [AGENTS.md:12-26](), [.windsurfintructions:1-16](), [package.json:13]()

---

## Authentication & Session Lifecycle

The frontend implements a Single Page Application (SPA) authentication flow using `sveltekit-superforms` [src/routes/login/+page.svelte:41-45]().

### Login Flow
1.  **Validation**: The login form uses a **Zod** schema (`loginSchema`) to validate credentials on the client [src/routes/login/+page.svelte:34-37]().
2.  **Submission**: Data is sent to `/api/v1/auth/login` via `apiFetch` [src/routes/login/+page.svelte:56-63]().
3.  **Session Storage**: On success, user profile data is persisted in `sessionStorage` via the `userProfileStore` [src/routes/login/+page.svelte:118-119]().
4.  **Redirection**: The system checks `getAndClearRedirectUrl()` to return the user to their intended destination [src/routes/login/+page.svelte:123-124]().

### Token Maintenance
The `apiFetch` wrapper automatically handles token expiration:
*   **Proactive Refresh**: If a 401 response is received and a local session exists, it triggers `triggerRefresh()` to call `/api/v1/auth/refresh` [src/lib/api.ts:177-202]().
*   **Concurrency**: `refreshPromise` ensures multiple failing requests only trigger a single refresh call [src/lib/api.ts:21-22, 99-106]().

**Sources:** [src/routes/login/+page.svelte:33-133](), [src/lib/api.ts:20-106, 177-215]()

---
