# Claude Custom Instructions for JunoJS

## Framework Context

JunoJS is a modern, AI-native reactive engine built on native Web Components. It provides **two complementary reactivity systems**: `@State()` (Proxy-based, component-local) and `signal()` (fine-grained, auto-tracking, shareable). Mutations to `@State()` properties trigger atomic DOM reconciliation via Proxy. Signals integrate directly into the render cycle — any `.value` access during rendering auto-subscribes the component.

## Coding Style & Rules

- **Component Definition**: Always use the `@Component` decorator. Ensure `tag` names follow standard `kebab-case`.
- **Reactivity**: Two models available — `@State()` for simple component-local state (direct mutation e.g. `this.count++`), and `signal()` for shared/cross-service state (immutable updates for arrays/objects). Prefer `signal()` for service-level state.
- **Form Handling**: Use the built-in `FormModel` and decorator-based validators (@Required, @Email, etc.) for all input handling.
- **Services**: Use the singleton pattern for services and inject them using `@Use(ServiceClass)`.
- **Reconciliation**: Remember that the framework reconciles only what changed in the real DOM. No virtual layer is used.
- **Routing**: Use the `<router-outlet>` component for client-side navigation. Register routes with the `component` property mapping to your component's tag name.

## Hybrid Rendering & Island Architecture

JunoJS inherently supports Server-Side Rendering (SSR) and Static Site Generation (SSG). 
- Every component file **must** begin with a `"use server";` or `"use client";` directive. 
- Use `"use server";` to strip client-side overhead (event handlers like `@click` will be removed) for data-heavy components.
- Configure `@Component({ static: true })` to mark "use server" components for SSG via `JunoEngine.buildStatic()`.
- You can manually SSR with `JunoEngine.renderToString()`.


## Detailed Framework Specifications

### 1. Lifecycle Architecture

JunoJS provides three strategic lifecycle hooks for managing component state and DOM interaction:

- **`onInit()`**: The pre-render phase. This is the ideal place for asynchronous data fetching and initial state configuration. All properties are defined, but the Shadow DOM has not yet been rendered.
- **`onRender()`**: The post-render phase. Called immediately after the DOM has been reconciliation-patched. Use this for direct DOM manipulation, initializing third-party libraries, or focusing inputs.
- **`onDestroy()`**: The cleanup phase. Essential for removing event listeners, clearing intervals, and unsubscribing from singleton services to prevent memory leaks.

### 2. Advanced Template Syntax

The built-in `JunoEngine` processes structural tags with high efficiency:

- **Conditionals**:
  ```html
  <if condition="{isLoaded}">
    <p>Content goes here</p>
  <else>
    <p>Loading...</p>
  </if>
  ```
- **Loops**:
  ```html
  <for each="{user in users}">
    <li>{user.name} - {user.email | uppercase}</li>
  </for>
  ```
- **Pipes (Transforms)**: Use the `|` operator for template transformations (e.g., `{price | currency('USD')}`). Methods must be marked with `@Transform()` to be recognized.

### 3. Comprehensive Decorator API

- **`@State()`**: Native Proxy-based tracking for **component-local** state. Mutate properties directly (`this.count++`). Best for simple, self-contained component state.
- **`@Event('name')`**: Defines a framework-native `EventEmitter`. Used for component-to-component communication via bubbling CustomEvents (`this.myEvent.emit(data)`).
- **`signal<T>(v)`**: Fine-grained reactive atom. Use for **service-level or shared** state. Requires immutable updates for arrays/objects: `items.update(prev => [...prev, item])`.
- **`computed(fn)`**: Lazy derived signal. Re-evaluates only when dependencies change and value is read.
- **`effect(fn)`**: Auto-tracking side-effect. Re-runs when any signal it reads changes. Returns a dispose function.
- **`batch(fn)`**: Coalesces multiple signal writes into one subscriber flush.
- **`untracked(fn)`**: Read a signal inside an effect without creating a subscription.
- **`@Validate(predicate, message)`**: Property-level validation for complex logic.
- **`@Persist(storage)`**: Auto-syncs to `localStorage` or `sessionStorage`. Perfect for theme settings, auth tokens, or search-filter persistence.
- **`@Use(Service)`**: Simple, singleton-based dependency injection. Automatically resolves the service instance at the start of the `onInit` lifecycle.
- **`@Input()`**: Reactive property mapping for HTML attributes. Any changes to the host element's attributes (e.g., `<my-comp color="red">`) will trigger an automatic state update and re-render.

### 4. Reactive Form System

Form classes should extend `FormModel` and use these decorators for validation:

- **`@Required(message?)`**
- **`@Email(message?)`**
- **`@Pattern(regex, message?)`**
- **`@Match(otherField, message?)`** (e.g., password and confirm-password)
  Form state is fully reactive; use `form.isValid()` and `form.getErrors()` to drive the UI.

## Signal Reactivity Pattern

Signals are the recommended approach for **services and cross-component state**. The render cycle is automatically wrapped in a `ReactiveEffect` — any `Signal.value` accessed during template evaluation auto-subscribes the component for re-render. No extra wiring, no manual subscriptions.

### Service with Signals

```typescript
// src/services/todo.service.ts
import { signal, computed } from '@junojs/core';

export class TodoService {
  static instance = new TodoService();

  todos = signal<Todo[]>([]);
  doneCount = computed(() => this.todos.value.filter(t => t.done).length);

  add(title: string) {
    this.todos.update(prev => [...prev, { id: Date.now(), title, done: false }]);
  }

  toggle(id: number) {
    this.todos.update(prev =>
      prev.map(t => t.id === id ? { ...t, done: !t.done } : t)
    );
  }
}
```

### Component Using a Signal Service

```typescript
"use client";
import { Component, Use, bootstrap } from '@junojs/core';
import { TodoService } from '../services/todo.service';

@Component({
  tag: 'todo-list',
  template: `
    <div>
      <p>Completed: {doneCount}</p>
      <for each="{(todo, i) in allTodos}">
        <div key="{todo.id}">
          <span>{todo.title}</span>
          <button @click="toggle(todo.id)">Toggle</button>
        </div>
      </for>
    </div>
  `
})
export class TodoList {
  @Use(TodoService) svc!: TodoService;

  // Getters expose signal values — framework tracks them automatically
  get allTodos() { return this.svc.todos.value; }
  get doneCount() { return this.svc.doneCount.value; }

  toggle(id: number) { this.svc.toggle(id); }
}

bootstrap(TodoList);
```

### Decision Guide: Signals vs. @State

| Scenario | Prefer |
|---|---|
| Simple local counter, toggle, flag | `@State()` |
| Shared list/object across components | `signal()` in a service |
| Derived/computed values | `computed()` |
| Side-effects (logging, storage sync) | `effect()` |
| Batch many changes at once | `batch()` |

## Event Handling & Vibe Coding

JunoJS implements a powerful event delegation system that supports both method calls and inline expressions.

- **Event Modifiers**: Use dot notation to add modifiers: `@submit.prevent`, `@click.stop`, `@keyup.enter`.
- **Expressions**: Templates support direct property mutation: `@click="isOpen = !isOpen"`.
- **Arguments**: Pass the native event using `e` or `$event`.

```html
<form @submit.prevent="save">
  <input @input="search = e.target.value" @keyup.enter="submit" />
  <button @click="reset($event)">Reset</button>
</form>
```

## Slot-Based Routing & Navigation (v0.4.0)
JunoJS uses a declarative, slot-based routing system centered around the `<router-outlet>`.

1. **Route Registration**:
   ```typescript
   RouterService.instance.register([
     { path: '/', component: 'home-page' },
     { path: '/user/:id', component: 'user-page' }
   ]);
   ```
2. **Dynamic Views**: Place `<router-outlet></router-outlet>` in your template. The framework automatically listens to route changes and injects the matched component.
3. **Param Injection**: Route parameters are automatically synchronized to `@Input()` properties of the target component (e.g., `:id` maps to `this.id`).
4. **Navigation**: Inject the `RouterService` using the `@Use` decorator for programmatic navigation:
   - `this.router.navigate('/path')` / `this.router.replace('/path')`
   - `this.router.back()` / `this.router.forward()`

## Prohibited Patterns

- **NO Ternary Logic for HTML**: Avoid `count > 0 ? '<div>' : '<span>'`. Use `<if>` tags for structural changes.
- **NO manual setAttribute**: Let `@Input()` handled attribute synchronization.
- **NO Virtual DOM terminology**: Do not mention "reconciliation loops" or "re-renders" in the React sense; use "DOM reconciliation" and "atomic updates".

## Project Structure

```
src/
├── components/          # Reusable, atomic UI components
├── pages/               # Routing-level views linked to the RouterService
├── services/            # Singleton business logic and data providers
├── models/              # Data models and validation schemas
├── assets/              # Static assets (images, fonts, etc.)
├── styles/              # Global styles and design tokens
├── utils/               # Utility functions and helpers
├── types/               # TypeScript type definitions
├── app.html             # Root HTML template
├── main.ts              # Application entry point
├── vite.config.ts       # Vite configuration
├── tsconfig.json        # TypeScript configuration
├── package.json         # Project dependencies and scripts
└── README.md            # Project documentation
```

## CLI Commands
Use the JunoJS CLI for scaffolding and development tasks:
- **`juno new <project> [--tailwind] [--ui]`**: Create a new JunoJS project. Use flags to include Tailwind CSS or the @junojs/ui library.
- **`juno generate component <name>`** (or `juno g c`): Generate a new component.
- **`juno generate service <name>`** (or `juno g s`): Generate a new service.
- **`juno generate page <name>`** (or `juno g p`): Generate a new routed page.
- **`juno generate model <name>`** (or `juno g m`): Generate a new data model.
- **`juno dev`**: Start the development server.
- **`juno build`**: Build for production (Bundle + SSG).
- **`juno preview`**: Preview the production build.
- **`juno version`**: Show CLI version.
