# WRNexusJS documentation 0.5.13

Status: Private Developer Preview. This site documents 31 release-aligned packages.

# WrNexus

> WrNexus is an SSR-first, **Bun-native** full-stack web framework. UI is written in
> `.wrn` files (its own component language — NOT React/JSX/Vue). Routing is file-based.
> This document teaches an AI how to write correct WrNexus code. It is private and
> post-dates model training data, so rely on THIS document, not prior web-framework
> assumptions.

## Golden rules

- **Pages, components, and layouts are `.wrn` files.** Do NOT write `.tsx`/`.jsx`/React
  for UI. Do NOT use `useState`, hooks, JSX, or a client bundler.
- **Routing is file-based** under `app/`. The filename is the route. No router config.
- **Interactivity** lives in `state` + `{expr}` + `@event` inside `.wrn`. Components render
  on the server and hydrate automatically — you never write client-side JS islands.
- **Runtime is Bun only** (uses `Bun.serve`, `bun:sqlite`, `Bun.password`, …). Node is not supported.
- To add files, prefer the CLI: `wrnexus generate page <Name>` / `component <name>` / `api <path>` / `schema <name>`.

## Project layout

```
app/
  pages/       *.wrn  → routes: index.wrn = "/", about.wrn = "/about", blog/[slug].wrn = "/blog/:slug"
  components/  *.wrn  → reusable UI, mounted in a page/component via <div data-component="name" ...props>
  layouts/     *.wrn  → named layouts; a page opts in with  layout = "name"
  api/         *.ts   → HTTP handlers: export const GET/POST/PUT/PATCH/DELETE = async (ctx) => Response
  middleware/  *.ts   → export default async (ctx, next) => next()
  realtime/    *.ts   → export default defineRoom({ ... }) from "@wrnexus/core"  (ws://host/realtime/<name>)
  schemas/     *.ts   → validation schemas (the `v` builder), used by forms + parseBody
  locales/     *.json → i18n messages per language
  db/          schema.ts, queries/*.sql, migrations/*.sql
  styles/      global.css  → Tailwind (default) or plain CSS
wrnexus.config.ts    → app config (AppConfig from "@wrnexus/styles")
public/              → static assets served at /
```

## `.wrn` page

```wrn
page Home {
  layout = "public"          // optional: a component in app/layouts/<name>.wrn ("none" to skip)

  state count = 0            // optional: seeds client-reactive state (omit for pure SSR)

  seo {
    title = "Home"
    description = "..."
    canonical = "/"
  }

  view {
    <h1>Hello</h1>
    <p>Count is {count}, doubled is {count * 2}.</p>
    <button @click="count++">Increment</button>
    <div data-component="counter" start="5" label="Clicks"></div>
  }

  style {
    h1 { color: var(--wire-color-text); }
  }
}
```

## `.wrn` component

```wrn
component Counter {
  props {                    // props come from mount attributes; each is coerced to the
    start = 0                // TYPE of its default (so start="5" arrives as the number 5)
    label = "Count"
  }
  state count = start        // state may reference props
  view {
    <button @click="count++">{label}: {count}</button>
  }
}
```

Mount it from any page/component: `<div data-component="counter" start="0" label="Clicks"></div>`.
Components render on the server with their props, then hydrate — no per-component JS.

## The `view { }` block (plain HTML + a few directives)

- `{expr}` — interpolate a JS expression. Reactive if it references `state`: `{count}`, `{count * 2}`, `{user.name}`.
- `@event="expr"` — bind a DOM event; the expression runs in the reactive scope: `@click="count++"`, `@input="name = event.target.value"`.
- `<div data-component="name" prop="v">` — mount a component (attrs become string props, coerced).
- `<slot></slot>` / `<slot name="x"></slot>` — component/layout slots; fill with `<div data-slot="x">…</div>`.
- **Server loop (DB/list/table):** `{#each <list> as <item>[, <i>]} …rows… {:empty} …fallback… {/each}` — iterates SSR data on the server and renders markup per item. `{item.field}` interpolates (HTML-escaped, XSS-safe). `<list>` is a JS expression, usually an `ssr` data binding (see "Data-driven tables" below). This is how you render a database table in `.wrn`.
- **Server conditional:** `{#if <expr>} … {:else if <expr>} … {:else} … {/if}` — renders the first truthy branch on the server. `<expr>` can reference `ssr` data, or the `item`/`index` of an enclosing `{#each}`. Works at page level and inside loops (e.g. `{#if r.active}<span>●</span>{:else}<span>○</span>{/if}` per row). For client-side show/hide based on reactive `state`, use `data-show="expr"` instead.
- i18n: `{t:home.title}` in text, `t:placeholder="form.name"` on attributes — resolved per request from `app/locales/`.
- Theme: any element with `data-wire-theme-toggle` toggles light/dark; `data-wire-theme-set="dark"` sets it.
- Void/self-closing tags are fine: `<br />`, `<img src="..." />`.
- Only `{` and `}` are special (interpolation). Don't use a bare `}` in view text.

## Data-driven tables / lists (server-rendered `.wrn`)

Use an `ssr` data binding to fetch rows on the server, then `{#each}` to render them.
This renders on the **server** (SSR-first) and is HTML-escaped by default.

```wrn
page Admin {
  layout = "dashboard"

  // Fetch on the server. The api handler at /api/contacts returns { contacts: [...] };
  // this block's `return contacts` exposes that array (via `$data`) as the binding `rows`.
  ssr {
    api rows GET /api/contacts { return contacts }
  }

  view {
    <table>
      <tbody>
        {#each rows as r, i}
          <tr>
            <td>#{i}</td>
            <td>{r.name}</td>
            <td><a href="mailto:{r.email}">{r.email}</a></td>
          </tr>
        {:empty}
          <tr><td colspan="3">No submissions yet.</td></tr>
        {/each}
      </tbody>
    </table>
  }
}
```

The matching API returns the array under a key the `ssr` block reads:

```ts
// app/api/contacts.ts  → GET /api/contacts
import { getDb } from "@wrnexus/db";
export const GET = async () => {
  const contacts = await getDb().all("SELECT id, name, email FROM contacts ORDER BY id DESC");
  return Response.json({ contacts });   // ssr block does `return contacts`
};
```

**Prefer this `.wrn` + `{#each}` approach for DB-backed tables and lists.** (`.ts`/`.tsx`
pages returning an HTML string are also supported for fully-custom programmatic rendering,
but a `.wrn` page with `ssr` data + `{#each}` is the idiomatic, SSR-first way.)

## API routes (`app/api/*.ts`)

```ts
// app/api/users/list.ts  → GET /api/users/list
import { getDb } from "@wrnexus/db";

export const GET = async (ctx) => {
  return Response.json({ users: await ListUsers(getDb()) });
};

export const POST = async (ctx) => {
  const body = await ctx.req.json();
  return Response.json({ ok: true, body }, { status: 201 });
};
```

`ctx` (the `Context` from `@wrnexus/core`) has:
`req: Request`, `url: URL`, `params: Record<string,string>` (dynamic route params, e.g. `/users/[id]` → `ctx.params.id`),
`lang: string`, `t(key, params?)` (i18n), `cookies` (get/set), `session` (get/set). Auth: `getUser(ctx)` after `sessionAuth`/`logIn`.

When an SSO forward-auth verifier needs the URL that originally reached the gateway, use
`@wrnexus/helpers` instead of constructing it from untrusted headers:

```ts
import { redirectToLogin } from "@wrnexus/helpers";

return redirectToLogin(ctx, "/login", {
  allowedHosts: ["admin.localhost:3000", "reports.localhost:3000"],
});
```

The package also exports `getOriginalRequestUrl`, `getOriginalRequestOrigin`,
`getOriginalRequestPath`, and `getOriginalRequestMethod`. Always pass `allowedHosts` when
using forwarded gateway URLs; the helper rejects untrusted redirect destinations.

## Middleware & realtime

```ts
// app/middleware/logger.ts
export default async function logger(ctx, next) {
  console.log(ctx.req.method, ctx.url.pathname);
  return next();               // return a Response WITHOUT calling next() to short-circuit
}
```

```ts
// app/realtime/chat.ts  → ws://host/realtime/chat
import { defineRoom } from "@wrnexus/core";
export default defineRoom({
  onConnect(client) { client.send({ type: "system", text: "connected" }); },
  onMessage(client, msg) { client.room.broadcast({ type: "message", data: msg }); },
});
```
Client side: a page opts in with `data-room="chat"` (handled by the realtime runtime).

## Config (`wrnexus.config.ts`)

```ts
import type { AppConfig } from "@wrnexus/styles";
const config: AppConfig = {
  seo: { title: "App", titleTemplate: "%s | App", description: "..." },
  styles: { entry: "app/styles/global.css", process: async ({ entryPath, mode }) => /* Tailwind */ "" },
  fonts: { sans: '"Inter", system-ui, sans-serif', google: [{ family: "Inter", weights: [400, 600] }] },
  theme: { default: "dark", themes: { light: { "color-primary": "#2563eb" } } },
  i18n: { default: "en", locales: ["en", "es"] },
  db: { driver: "sqlite", url: "file:./dev.db" },
  security: { cors: { enabled: true, origin: ["http://localhost:5173"] } },
  // profiles: { production: { db: { driver: "postgres", url: process.env.DATABASE_URL } } },
};
export default config;
```

## Database (`@wrnexus/db`)

```ts
// app/db/schema.ts
import { v, table } from "@wrnexus/db";
export const users = table("users", {
  id: v.id(),
  name: v.string(),
  email: v.string().unique(),
  createdAt: v.timestamp(),
});
```
- Queries: write `app/db/queries/*.sql` with `-- name: ListUsers :many` blocks; `wrnexus db generate` emits typed functions.
- Access at runtime: `import { getDb } from "@wrnexus/db"; const rows = await ListUsers(getDb());`
- Migrations in `app/db/migrations/`; run `wrnexus db migrate` (dev auto-migrates sqlite).

## Validation (`@wrnexus/validation`)

```ts
// app/schemas/login.ts
import { v } from "@wrnexus/validation";
export default v.object({
  email: v.string().email(),
  password: v.string().min(8),
});
```
In an API route: `import s from "../schemas/login"; import { parseBody } from "@wrnexus/validation"; const r = await parseBody(s, ctx.req);` → `r.ok ? r.value : r.response`.
In a form: `<form data-schema="login" action="/api/login" method="post">` + `<span data-error="email"></span>` (client + server validation wired automatically).

## AI / LLM (`@wrnexus/ai`)

```ts
// app/api/ai.ts
import { createAI } from "@wrnexus/ai";
const ai = createAI();                     // reads ANTHROPIC_API_KEY; default model claude-opus-4-8
export const POST = async (ctx) => {
  const { prompt } = await ctx.req.json();
  return ai.streamResponse(prompt);        // or: return Response.json({ text: await ai.generate(prompt) })
};
```

## CLI

```
wrnexus dev .                 # dev server + HMR
wrnexus build .               # production build → dist/server.js
bun dist/server.js            # run the production server (or npm start)
wrnexus create <name>         # scaffold a new app
wrnexus update --latest       # deps + syntax/config migrations + verification
wrnexus generate page <Name>  # scaffold a page   (aliases: g p)
wrnexus generate component <name> | api <path> | schema <name>
wrnexus db migrate | rollback | status | new [--from-models] | generate | seed
wrnexus eject <component>     # copy a Wire UI component's .wrn into app/components to customize
```

## When asked to "create a page/component/feature"

1. Create the `.wrn` file under `app/pages/` (or `app/components/`) with a `page`/`component` block — or run `wrnexus generate page <Name>`.
2. Put markup in `view { }`, interactive bits in `state` + `{expr}` + `@event`, reusable UI as components mounted via `data-component`.
3. For data, add an `app/api/*.ts` route and `getDb()`; for forms, add an `app/schemas/*.ts` and `data-schema`.
4. Style with Tailwind utility classes in the view, or theme tokens (`var(--wire-*)`), or `style { }`.
5. Never emit React/JSX, a manual router, or client-side island JS — the framework handles hydration.

Release: WRNexusJS 0.5.13

# Canonical documentation locations

- Framework and package documentation: https://wrnexusjs.dev/
- Interactive UI component showcase and examples: https://component.wrnexusjs.dev/

# Installed package documentation

The following README files and declarations come from the installed private 0.5.13 release.

## @wrnexus/ai

Documentation URL: https://wrnexusjs.dev/packages/ai

# @wrnexus/ai

> A tiny, zero-dependency Claude (Anthropic) client for WrNexus apps — generate and stream text with Claude from any server-side code.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

`@wrnexus/ai` is a thin, dependency-free wrapper over the Anthropic **Messages API**,
built on `fetch` (Bun-native, no SDK). Use it in API routes, jobs, or middleware to
call Claude. It defaults to the most capable model, **`claude-opus-4-8`**, reads your
key from `ANTHROPIC_API_KEY`, and supports both one-shot generation and streaming.

## Installation

```bash
bun add @wrnexus/ai
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported).

Set your key in the environment (e.g. `.env`):

```
ANTHROPIC_API_KEY=sk-ant-...
```

## API

### `createAI(config?)`

Creates a client. The key is read at call time, so it's safe to create at import.

```ts
import { createAI } from "@wrnexus/ai";
const ai = createAI(); // or createAI({ apiKey, model, maxTokens, baseURL, version })
```

`AIConfig` fields (all optional):

| Field       | Default                     | Description                |
| ----------- | --------------------------- | -------------------------- |
| `apiKey`    | `ANTHROPIC_API_KEY`         | Anthropic API key          |
| `model`     | `"claude-opus-4-8"`         | Model id                   |
| `maxTokens` | `4096`                      | Default max output tokens  |
| `baseURL`   | `https://api.anthropic.com` | API base URL               |
| `version`   | `"2023-06-01"`              | `anthropic-version` header |

### `ai.generate(prompt, opts?): Promise<string>`

One-shot text generation. `prompt` is a string or a `Message[]` history.

```ts
const text = await ai.generate("Write a haiku about Bun.");

const reply = await ai.generate(
  [
    { role: "user", content: "My name is Ada." },
    { role: "assistant", content: "Hi Ada!" },
    { role: "user", content: "What's my name?" },
  ],
  { system: "You are concise." },
);
```

### `ai.stream(prompt, opts?): AsyncGenerator<string>`

Yields text deltas as they arrive.

```ts
for await (const chunk of ai.stream("Tell me a story.")) {
  process.stdout.write(chunk);
}
```

### `ai.streamResponse(prompt, opts?): Response`

Returns a streaming `text/plain` `Response` — drop it straight into an API route.

```ts
// app/api/chat.ts
import { createAI } from "@wrnexus/ai";
const ai = createAI();

export const POST = async (ctx) => {
  const { prompt } = await ctx.req.json();
  return ai.streamResponse(prompt);
};
```

### `GenerateOptions`

| Option      | Type                                              | Description                                          |
| ----------- | ------------------------------------------------- | ---------------------------------------------------- |
| `system`    | `string`                                          | System prompt                                        |
| `model`     | `string`                                          | Override the model for this call                     |
| `maxTokens` | `number`                                          | Override max output tokens                           |
| `thinking`  | `boolean`                                         | Enable adaptive extended thinking (deeper reasoning) |
| `effort`    | `"low" \| "medium" \| "high" \| "xhigh" \| "max"` | Reasoning effort / token spend                       |
| `messages`  | `Message[]`                                       | Full history — supersedes `prompt`                   |
| `signal`    | `AbortSignal`                                     | Cancel the request                                   |

> `temperature` / `top_p` are intentionally **not** exposed — the current Claude
> models reject them (400). Steer output with prompting instead.

### `AIError`

Thrown on non-2xx responses or a model refusal. Carries `.status` and `.type`
(e.g. `"authentication_error"`, `"rate_limit_error"`, `"refusal"`).

```ts
import { AIError } from "@wrnexus/ai";
try {
  await ai.generate("...");
} catch (e) {
  if (e instanceof AIError && e.type === "rate_limit_error") {
    /* back off */
  }
}
```

## Usage

### Return generated JSON from an API route

```ts
// app/api/summarize.ts — summarize posted text
import { createAI } from "@wrnexus/ai";
const ai = createAI();

export const POST = async (ctx) => {
  const { text } = await ctx.req.json().catch(() => ({}));
  if (!text) return Response.json({ error: "Provide 'text'." }, { status: 400 });
  const summary = await ai.generate(`Summarize in one sentence:\n\n${text}`, {
    system: "You are a precise summarizer.",
  });
  return Response.json({ summary });
};
```

### Stream a chat response to the browser

```ts
// app/api/chat.ts
import { createAI } from "@wrnexus/ai";

const ai = createAI({ model: "claude-sonnet-5" });

export const POST = async (ctx) => {
  const { messages } = await ctx.req.json();
  return ai.streamResponse(messages, {
    system: "Answer using concise Markdown.",
    maxTokens: 1_500,
  });
};
```

## Requirements / Notes

- **Bun-only.** Uses `fetch`, `ReadableStream`, `TextDecoder`/`TextEncoder`, and
  reads `ANTHROPIC_API_KEY` from `Bun.env` (falls back to `process.env`).
- **Zero dependencies** — no `@anthropic-ai/sdk`; talks to the Messages API directly.
- Defaults to `claude-opus-4-8`. Pass `{ model }` for a different model (e.g.
  `"claude-sonnet-5"` for speed/cost, `"claude-haiku-4-5"` for the fastest).

### Exported TypeScript declarations

```ts
interface AIUsage {
    inputTokens?: number;
    outputTokens?: number;
    totalTokens?: number;
}
interface AIResult<T = string> {
    value: T;
    provider: string;
    model?: string;
    usage?: AIUsage;
    finishReason?: string;
    raw?: unknown;
}
interface AIProvider {
    name: string;
    generate(prompt: string | Message[], options?: GenerateOptions): Promise<AIResult<string>>;
    stream?(prompt: string | Message[], options?: GenerateOptions): AsyncGenerator<string, void, unknown>;
}
interface AIClientOptions {
    providers: AIProvider[];
    fallback?: boolean;
    onAttempt?: (provider: string, error?: unknown) => void | Promise<void>;
}
interface AIClient {
    generate(prompt: string | Message[], options?: GenerateOptions & {
        provider?: string;
    }): Promise<AIResult<string>>;
    generateObject<T>(prompt: string | Message[], options?: GenerateOptions & {
        provider?: string;
        validate?: (value: unknown) => value is T;
    }): Promise<AIResult<T>>;
    stream(prompt: string | Message[], options?: GenerateOptions & {
        provider?: string;
    }): AsyncGenerator<string, void, unknown>;
}
declare function anthropicProvider(config?: AIConfig): AIProvider;
declare function aiProvider(name: string, client: AI): AIProvider;
declare function createAIClient(options: AIClientOptions): AIClient;

/**
 * @wrnexus/ai — a tiny, zero-dependency Claude (Anthropic) client for WrNexus apps.
 *
 * Use it in API routes, jobs, or anywhere server-side to generate text with Claude.
 * It talks to the Anthropic Messages API over `fetch` (no SDK dependency, Bun-native),
 * and defaults to the most capable model, `claude-opus-4-8`.
 *
 *   import { createAI } from "@wrnexus/ai";
 *   const ai = createAI();                       // reads ANTHROPIC_API_KEY
 *   const text = await ai.generate("Write a haiku about Bun.");
 *
 * Streaming (great for API routes):
 *   export const POST = async (ctx) => ai.streamResponse(await ctx.req.text());
 */
type Role = "user" | "assistant";
interface Message {
    role: Role;
    content: string;
}
/** Reasoning effort — higher means deeper thinking + more tokens. */
type Effort = "low" | "medium" | "high" | "xhigh" | "max";
interface AIConfig {
    /** Anthropic API key. Default: `ANTHROPIC_API_KEY` from the environment. */
    apiKey?: string;
    /** Model id. Default: `claude-opus-4-8` (the most capable Claude model). */
    model?: string;
    /** Default max output tokens. Default: 4096. */
    maxTokens?: number;
    /** API base URL. Default: `https://api.anthropic.com`. */
    baseURL?: string;
    /** `anthropic-version` header. Default: `2023-06-01`. */
    version?: string;
}
interface GenerateOptions {
    /** System prompt — sets the assistant's role/behavior. */
    system?: string;
    /** Override the model for this call. */
    model?: string;
    /** Override max output tokens for this call. */
    maxTokens?: number;
    /** Enable adaptive extended thinking (slower, deeper reasoning). */
    thinking?: boolean;
    /** Reasoning effort / token spend (`output_config.effort`). */
    effort?: Effort;
    /** Full message history — supersedes the `prompt` argument when provided. */
    messages?: Message[];
    /** Abort the request. */
    signal?: AbortSignal;
}
/** Thrown when the API returns a non-2xx response or refuses the request. */
declare class AIError extends Error {
    readonly status: number;
    readonly type: string;
    constructor(message: string, status?: number, type?: string);
}
interface AI {
    /** Generate a full text response (non-streaming). */
    generate(prompt: string | Message[], opts?: GenerateOptions): Promise<string>;
    /** Stream the response as text deltas, as they arrive. */
    stream(prompt: string | Message[], opts?: GenerateOptions): AsyncGenerator<string, void, unknown>;
    /** Stream straight to a `Response` (text/plain) — drop-in for an API route return. */
    streamResponse(prompt: string | Message[], opts?: GenerateOptions): Response;
}
/** Create a Claude client. Reads `ANTHROPIC_API_KEY` from the environment by default. */
declare function createAI(config?: AIConfig): AI;

export { type AI, type AIClient, type AIClientOptions, type AIConfig, AIError, type AIProvider, type AIResult, type AIUsage, type Effort, type GenerateOptions, type Message, type Role, aiProvider, anthropicProvider, createAI, createAIClient };
```

---

## @wrnexus/auth

Documentation URL: https://wrnexusjs.dev/packages/auth

# @wrnexus/auth

Framework-native authentication, identity, account-security, and session management for WRNexusJS.

## Capabilities

- Password registration, login, recovery, reset, and authenticated password changes
- Email, phone, and username identities with verification and generic resend responses
- Magic links and passwordless email/SMS OTP login
- MFA transactions using verified email OTP, verified SMS OTP, TOTP, or recovery codes
- RFC 6238 TOTP with counter replay protection
- One-use recovery codes; regeneration invalidates previous unused codes
- Passkey/WebAuthn registration and strong passwordless sign-in through a provider contract
- OAuth account linking and provider sign-in
- Invitations, session rotation, idle and absolute expiry, revocation, and trusted devices
- Deny-by-default audited support impersonation
- Adaptive risk scoring, CAPTCHA escalation, temporary lockout, and optional login alerts
- Memory and SQL stores
- Optional encryption-keyring protection for TOTP and OAuth secrets
- Automatic API routes, middleware, browser schemas, components, runtime, migrations, and DevToolbar checks

Passkeys are a strong sign-in method. They are not currently exposed as a selectable second step in `TwoFactorChallenge`; the implemented MFA methods are email OTP, SMS OTP, TOTP, and recovery codes.

## Install

```bash
bun add @wrnexus/auth
```

WRNexusJS discovers the package automatically. Do not copy package components, client scripts, schemas, or standard `/api/auth/*` route files into the application.

## Default configuration

Create the engine:

```ts
// app/lib/auth.ts
import { createAuthEngine, MemoryAuthStore } from "@wrnexus/auth";

export const auth = createAuthEngine({
  store: new MemoryAuthStore(),
  secret: process.env.AUTH_SECRET!,
  issuer: "My application",
  onSignedIn(ctx, returnTo) {
    const safe = returnTo?.startsWith("/") && !returnTo.startsWith("//") ? returnTo : "/account";
    return Response.redirect(new URL(safe, ctx.url), 303);
  },
  onSignedOut(ctx) {
    return Response.redirect(new URL("/sign-in", ctx.url), 303);
  },
  onSuccessfulSignUp() {
    return {
      autoSignIn: true,
      redirectTo: "/account",
    };
  },
  delivery: {
    async send(message) {
      // Queue email/SMS through your provider. Never log message.code or message.token.
    },
  },
});
```

Authentication behavior belongs in this engine definition: delivery, token URL
mapping, successful sign-in/sign-out responses, password policy, risk thresholds,
MFA, passkeys, and auditing can all be configured in one server-only location.
The older `config.auth.onSignedIn` and `config.auth.onSignedOut` fields remain
supported as compatibility overrides, but new applications should configure
these hooks on `createAuthEngine`.

### Successful signup behavior

Without `onSuccessfulSignUp`, a successful package registration redirects to
`/sign-in`.

To sign in immediately after registration:

```ts
onSuccessfulSignUp(ctx, user) {
  return {
    autoSignIn: true,
    redirectTo: "/account",
  };
}
```

Automatic sign-in runs the normal login policy. It does not bypass required
email or phone verification, CAPTCHA, MFA, account status, or risk checks. The
hook may also return a `Response` for a completely custom HTTP result, or return
`{ redirectTo: "/welcome" }` to redirect without creating a session.

Register it through application configuration:

```ts
// wrnexus.config.ts
import type { AuthConfig } from "@wrnexus/auth";
import type { AppConfig } from "@wrnexus/styles";
import { auth } from "./app/lib/auth.ts";

const config = {
  auth: {
    engine: auth,
    routes: true,
    middleware: true,
    migrations: false,
  },
} satisfies AppConfig & { auth: AuthConfig };

export default config;
```

That configuration automatically activates package routes, auth-session middleware, components, browser validation schemas, and the auth client runtime. `setDefaultAuthEngine()` remains available only for advanced manual integrations and tests.

## SQL production configuration

```ts
import { createAuthEngine, SqlAuthStore } from "@wrnexus/auth";
import { getDb } from "@wrnexus/db";

export const auth = createAuthEngine({
  store: new SqlAuthStore(getDb()),
  secret: process.env.AUTH_SECRET!,
});
```

```ts
export default {
  db: {
    // Application database configuration.
  },
  auth: {
    engine: auth,
    routes: true,
    middleware: true,
    migrations: true,
  },
};
```

The package contributes both ordered migrations:

```text
001_auth.sql
002_auth_otp_purpose.sql
```

Migrations are enabled automatically only when `auth.engine` and a default `config.db` are present. Set `auth.migrations` explicitly when an application needs different behavior.

## Delivered action URLs

By default, the engine builds links from the supplied `baseUrl` and token purpose. Applications can map those links to their own page structure without replacing package APIs:

```ts
const auth = createAuthEngine({
  store: new SqlAuthStore(getDb()),
  secret: process.env.AUTH_SECRET!,
  tokenUrl({ purpose, token, baseUrl }) {
    if (!baseUrl) return undefined;

    const paths = {
      "verify-email": `/verify-email?token=${encodeURIComponent(token)}`,
      "verify-phone": `/verify-phone?token=${encodeURIComponent(token)}`,
      "password-reset": `/recover/reset?token=${encodeURIComponent(token)}`,
      "magic-link": `/magic-link?token=${encodeURIComponent(token)}`,
      invite: `/invitation?token=${encodeURIComponent(token)}`,
    };

    const path = paths[purpose as keyof typeof paths];
    return path ? new URL(path, baseUrl).toString() : undefined;
  },
});
```

Returning `undefined` intentionally omits the URL while still delivering the raw token. The callback runs only in trusted server code.

## Built-in validation

Every packaged auth form has a built-in `@wrnexus/validation` schema. The same resolved schema is used by the browser and the package API handler.

Default use requires no `app/schemas` files:

```wrn
<SignUp />
<SignIn />
<ForgotPassword />
<ResetPassword token='{token}' />
<TwoFactorChallenge />
```

To customize one schema, extend the package default and register only that override:

```ts
// app/schemas/custom-password-request.ts
import { authSchemas } from "@wrnexus/auth";
import { v } from "@wrnexus/validation";

export default authSchemas.passwordResetRequest.extend({
  identifier: v
    .string()
    .trim()
    .required("Enter your registered email address")
    .email("Enter a valid registered email address"),
});
```

```ts
import customPasswordRequest from "./app/schemas/custom-password-request.ts";

export default {
  auth: {
    engine: auth,
    schemas: {
      passwordResetRequest: customPasswordRequest,
    },
  },
};
```

`<ForgotPassword />` can keep its default `schema="auth-password-request"`. The plugin automatically publishes the overridden browser descriptor under that same built-in schema ID. All other forms continue using package defaults.

## Route controls

Use a boolean to enable or disable all package routes:

```ts
auth: {
  engine: auth,
  routes: true,
}
```

Or control feature groups:

```ts
routes: {
  enabled: true,
  registration: true,
  login: true,
  verification: true,
  password: true,
  invitations: true,
  magicLink: true,
  otp: true,
  mfa: true,
  sessions: true,
  impersonation: false,
  passkeys: true,
}
```

Application routes have normal framework precedence. Disable a package group only when the application intentionally owns every endpoint in that group; no `excludeRoutes` list is required.

## Package endpoints

```text
POST     /api/auth/register
POST     /api/auth/login
POST     /api/auth/logout
POST     /api/auth/verification/request
GET|POST /api/auth/verify/email
POST     /api/auth/verify/phone
POST     /api/auth/password/request
POST     /api/auth/password/reset
POST     /api/auth/password/change
POST     /api/auth/invitations/accept
POST     /api/auth/magic-link/request
GET|POST /api/auth/magic-link
POST     /api/auth/otp/login/request
POST     /api/auth/otp/login/complete
POST     /api/auth/otp
POST     /api/auth/otp/verify
POST     /api/auth/totp/setup
POST     /api/auth/totp/confirm
POST     /api/auth/totp/disable
POST     /api/auth/recovery-codes
POST     /api/auth/mfa/otp
POST     /api/auth/mfa/complete
GET      /api/auth/sessions
POST     /api/auth/sessions/revoke
POST     /api/auth/impersonation/start
POST     /api/auth/impersonation/stop
POST     /api/auth/passkeys/register/options
POST     /api/auth/passkeys/register/verify
POST     /api/auth/passkeys/login/options
POST     /api/auth/passkeys/login/verify
```

Each URL uses a route-specific module, so rewritten framework request URLs cannot make the handler fall through to a shared-dispatcher `404`.

Unsafe package routes validate the framework CSRF token by default. Set `auth.csrf: false` only when an external API gateway provides an equivalent protection model.

## Components

```wrn
<SignIn />
<SignUp />
<ForgotPassword />
<ResetPassword token='{token}' />
<OtpSignIn method="email-otp" />
<MagicLinkSignIn />
<PasskeyButton mode="authenticate" />
<TwoFactorChallenge mfaToken='{mfaToken}' challengeId='{challengeId}' />
<AuthenticatorSetup credentialId='{credentialId}' secret='{secret}' uri='{uri}' />
<RecoveryCodes codes='{codes}' />
<DeviceSessions sessions='{sessions}' currentSessionId='{currentSessionId}' />
<VerifyEmail token='{token}' identifier='{identifier}' />
<VerifyPhone token='{token}' identifier='{identifier}' />
<InvitationAccept token='{token}' />
<ImpersonationBanner targetName='{targetName}' />
<AccountStatus status='{account.status}' />
```

`identifier` is optional on verification components. Supply it when an unauthenticated verification page should support resending a token. The response remains generic whether the account exists or not.

## CAPTCHA and risk

The HTTP handlers never trust a browser `captchaVerified` field. CAPTCHA completion is accepted only from server-populated `ctx.locals.captcha.success` or `ctx.locals.captchaVerified === true`.

Rate limiting remains an application or gateway responsibility. Apply it to registration, login, reset, magic-link, OTP, verification, passkey, invitation, and impersonation endpoints.

## MFA

1. Password, OAuth, magic-link, or OTP login may return `code: "mfa-required"` with a short-lived `mfaToken`.
2. The response lists only methods actually available to that user.
3. Email/SMS MFA is offered only for verified linked identities.
4. `beginMfaOtp()` issues an MFA-bound OTP when needed.
5. `completeMfa()` consumes the one-time transaction and creates the session.

## Passkeys

The browser runtime coordinates `navigator.credentials.create()` and `navigator.credentials.get()`. A configured server-side `PasskeyProvider` must verify the challenge, RP ID, origin, signature, user presence or verification, counter, and credential ownership.

Multi-process deployments must provide a shared `PasskeyChallengeStore`; the default memory implementation is process-local. Missing passkey providers return a controlled `503` response rather than crashing the route.

## Protect long-lived secrets

```ts
import { createAuthSecretProtector } from "@wrnexus/auth";
import { createKeyring } from "@wrnexus/encryption";

const keyring = createKeyring([
  {
    id: "auth-2026-01",
    secret: process.env.AUTH_ENCRYPTION_KEY!,
    active: true,
  },
]);

const auth = createAuthEngine({
  store: new SqlAuthStore(getDb()),
  secret: process.env.AUTH_SECRET!,
  secretProtector: createAuthSecretProtector(keyring),
});
```

TOTP seeds and OAuth access/refresh tokens are protected before persistence. Keep old keys available during rotation.

## Custom HTTP integration

`createAuthHttpHandlers()` remains available for custom route paths or response behavior. Prefer package routes for standard flows; copied application API files are unnecessary.

## Development

```bash
bun run auth:dev
bun run validate:auth
```

Read [SECURITY.md](./SECURITY.md) before production deployment.

### Exported TypeScript declarations

```ts
export { A as AuthEngine, c as createAuthEngine, i as inferIdentityType, n as normalizeEmail, a as normalizeIdentity, b as normalizePhone, d as normalizeUsername, p as publicUser, s as safeAuthReturnTo } from './engine-ZXtjHSyW.js';
import { n as AuthRiskSignals, l as AuthRiskDecision } from './types-CbJKeaWh.js';
export { A as AuthAccountStatus, a as AuthClock, b as AuthDeliveryMessage, c as AuthDeliveryProvider, d as AuthEngineOptions, e as AuthIdentity, f as AuthIdentityType, g as AuthImpersonationDecision, h as AuthMfaMethod, i as AuthPublicUser, j as AuthRandom, k as AuthResult, m as AuthRiskLevel, o as AuthSecretProtector, p as AuthSecurityEvent, q as AuthSession, r as AuthSessionVerificationHandler, s as AuthSignedInHandler, t as AuthSignedOutHandler, N as AuthStore, u as AuthSuccessfulSignUpAction, v as AuthSuccessfulSignUpHandler, w as AuthTokenPurpose, x as AuthTokenUrlInput, y as AuthUser, z as AuthenticatedContext, L as LoginAttempt, B as LoginInput, Q as MemoryPasskeyChallengeStore, O as OAuthAccount, C as OneTimeToken, D as OtpChallenge, P as PasskeyAuthenticationOptions, S as PasskeyChallengeKind, U as PasskeyChallengeRecord, V as PasskeyChallengeStore, E as PasskeyCredential, F as PasskeyProvider, G as PasskeyRegistrationOptions, H as PasskeyVerificationResult, I as PasswordBreachProvider, J as PasswordCredential, R as RecoveryCodeRecord, K as RegisterInput, T as TotpCredential, M as TrustedDevice, W as assertPasskeyProvider } from './types-CbJKeaWh.js';
export { MemoryAuthStore } from './stores/memory.js';
export { SqlAuthStore } from './stores/sql.js';
export { AUTH_SESSION_KEY, authSession, clearAuthSession, establishAuthSession, getAuthSession, getAuthUser, isAuthenticatedContext, requireAuth } from './middleware.js';
export { A as AuthHttpOptions, a as AuthPasskeyHttpOptions, b as AuthSchemaOverrides, c as AuthSchemaSet, d as authBrowserSchemaDescriptors, e as authBrowserSchemaMap, f as authSchemas, g as authenticatorConfirmSchema, h as authenticatorDisableSchema, i as authenticatorSetupSchema, j as changePasswordSchema, k as createAuthHttpHandlers, l as emptyActionSchema, m as impersonationStartSchema, n as invitationAcceptSchema, o as loginSchema, p as magicLinkConsumeSchema, q as magicLinkRequestSchema, r as mfaOtpRequestSchema, s as mfaSchema, t as otpIssueSchema, u as otpLoginCompleteSchema, v as otpLoginRequestSchema, w as otpSchema, x as passkeyAuthenticationOptionsSchema, y as passkeyAuthenticationVerifySchema, z as passkeyRegistrationOptionsSchema, B as passkeyRegistrationVerifySchema, C as passwordResetRequestSchema, D as passwordResetSchema, E as recoveryCodesSchema, F as registerSchema, G as resolveAuthSchemas, H as sessionRevokeSchema, I as signUpSchema, J as verificationRequestSchema, K as verificationTokenSchema } from './index-DS1geh2P.js';
export { AuthAuditIssue, AuthConfig, AuthPluginOptions, AuthRoutesConfig, authComponentsDir, authPlugin } from './plugin.js';
export { DefaultAuthRouteOptions, clearDefaultAuthEngine, getDefaultAuthEngine, getDefaultAuthRouteOptions, getDefaultAuthSchemas, hasDefaultAuthEngine, setDefaultAuthEngine, setDefaultAuthRouteOptions, setDefaultAuthSchemas, tryGetDefaultAuthEngine } from './runtime.js';
export { createAuthSecretProtector } from './protector.js';
export { decodeBase32, encodeBase32, generateTotp, generateTotpSecret, totpUri, verifyTotp } from './totp/index.js';
import '@wrnexus/oauth';
import '@wrnexus/core';
import '@wrnexus/db';
import '@wrnexus/validation';
import '@wrnexus/plugin';
import '@wrnexus/encryption';

interface RiskPolicy {
    captchaThreshold: number;
    mfaThreshold: number;
    blockThreshold: number;
}
declare function evaluateAuthRisk(signals?: AuthRiskSignals, policy?: RiskPolicy): AuthRiskDecision;

export { AuthRiskDecision, AuthRiskSignals, type RiskPolicy, evaluateAuthRisk };
```

---

## @wrnexus/authz

Documentation URL: https://wrnexusjs.dev/packages/authz

# @wrnexus/authz

> Composable authorization for WrNexus — role-based (RBAC), policy-based (PBAC), and attribute-based (ABAC) access control that reduces to a boolean check plus an `authorize()` guard.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

`@wrnexus/authz` is a small, server-side authorization toolkit. It gives you three
interchangeable models — RBAC (roles → permissions), PBAC (policy predicates), and
ABAC (attribute matchers) — that all collapse to a `boolean | Promise<boolean>` decision.
Wrap any decision in a `Middleware` guard (`authorize`, `requireRole`, `requirePermission`)
to protect WrNexus routes. Reach for it whenever a route or action needs to be gated on who
the user is, what roles they hold, or attributes of the user and the resource. It plugs into
`@wrnexus/core` by reading `ctx.user` as the authorization subject.

## Installation

```bash
bun add @wrnexus/authz
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported).

## API

The package has a single entry point (`@wrnexus/authz`) exporting the following.

### Types

| Symbol                             | Description                                                                                   |
| ---------------------------------- | --------------------------------------------------------------------------------------------- |
| `Subject`                          | The authorized principal: `{ id?: string; roles?: string[]; [attribute: string]: unknown }`.  |
| `Rbac`                             | An RBAC checker: `{ can(subject, permission): boolean; permissionsFor(roles): Set<string> }`. |
| `Policy<S = Subject, R = unknown>` | A predicate `(subject: S, resource?: R) => boolean \| Promise<boolean>`.                      |

### RBAC

#### `defineRbac(roles: Record<string, string[]>): Rbac`

Builds an RBAC checker from a role → permissions map. Supported permission forms:

- `"*"` — grants every permission.
- `"ns:*"` — namespace wildcard (e.g. `"post:*"` grants `"post:write"`).
- `"role:<name>"` — inherits all permissions of another role (resolved recursively, cycle-safe).

The returned `Rbac` provides:

- `can(subject, permission)` — `true` if any of `subject.roles` grants `permission` (honouring `*` and namespace wildcards). Returns `false` when the subject has no roles.
- `permissionsFor(roles)` — the resolved `Set<string>` of all permissions granted to a set of roles.

#### `hasRole(subject: Subject | undefined, ...required: string[]): boolean`

`true` if the subject holds **all** of the given roles.

### PBAC / ABAC combinators

- `any<S, R>(...policies: Policy<S, R>[]): Policy<S, R>` — allow if **any** policy passes (OR); awaits async policies.
- `all<S, R>(...policies: Policy<S, R>[]): Policy<S, R>` — allow only if **all** policies pass (AND); awaits async policies.
- `attr<S extends Subject>(name: string, match: unknown | ((value: unknown) => boolean)): Policy<S>` — ABAC helper that allows when `subject[name]` equals `match`, or when `match` is a function, when `match(value)` is truthy.

### Guards (middleware)

Each guard returns a `@wrnexus/core` `Middleware`. A denied request short-circuits with
`Response.json({ ok: false, error: "Forbidden" }, { status: 403 })`.

- `authorize(policy: (ctx: Context) => boolean | Promise<boolean>): Middleware` — runs `policy` against the request `Context`; calls `next()` when it resolves truthy, otherwise returns 403.
- `requireRole(...roles: string[]): Middleware` — allows when `ctx.user` holds **any** of the listed roles.
- `requirePermission(rbac: Rbac, permission: string): Middleware` — allows when `rbac.can(ctx.user, permission)` is `true`.

## Usage

### RBAC

```ts
import { defineRbac, hasRole } from "@wrnexus/authz";

const rbac = defineRbac({
  admin: ["*"],
  editor: ["post:read", "post:write"],
  viewer: ["post:read"],
  // role inheritance: lead gets everything an editor has, plus post:publish
  lead: ["role:editor", "post:publish"],
});

const user = { id: "u1", roles: ["editor"] };

rbac.can(user, "post:write"); // true
rbac.can(user, "post:delete"); // false
rbac.permissionsFor(["lead"]); // Set { "post:read", "post:write", "post:publish" }
hasRole(user, "editor"); // true
```

### Guarding routes

```ts
import { authorize, requireRole, requirePermission, defineRbac } from "@wrnexus/authz";

const rbac = defineRbac({ admin: ["*"], editor: ["post:read", "post:write"] });

// Only admins or editors
app.get("/dashboard", requireRole("admin", "editor"), handler);

// Requires a specific permission
app.post("/posts", requirePermission(rbac, "post:write"), handler);

// Arbitrary policy over the request context
app.delete(
  "/posts/:id",
  authorize((ctx) => hasRole(ctx.user, "admin")),
  handler,
);
```

### PBAC / ABAC policies

```ts
import { any, all, attr, authorize, type Policy } from "@wrnexus/authz";

interface User {
  id: string;
  department?: string;
  roles?: string[];
}
interface Post {
  authorId: string;
}

// Ownership policy (subject + resource)
const ownsPost: Policy<User, Post> = (u, post) => u.id === post?.authorId;

// ABAC: attribute equality, or a predicate
const inEngineering = attr<User>("department", "engineering");
const isVerified = attr<User>("verified", (v) => v === true);

// Compose: allow if the user owns the post OR is in engineering AND verified
const canEdit = any(ownsPost, all(inEngineering, isVerified));

app.put(
  "/posts/:id",
  authorize((ctx) => canEdit(ctx.user as User, loadPost(ctx))),
  handler,
);
```

## Requirements / Notes

- **Bun-only** — like the rest of WrNexus, this package targets the Bun runtime; Node is not supported.
- Works with [`@wrnexus/core`](../core) — the guards return `Middleware` and read the subject from `ctx.user` on the request `Context`. Both types are imported from `@wrnexus/core`.
- Policy combinators (`any`, `all`) and `authorize` are async-aware, so policies may return a `Promise<boolean>` (e.g. for a database ownership check).

### Exported TypeScript declarations

```ts
import { Context, Middleware } from '@wrnexus/core';

interface AuthorizationDecision {
    allowed: boolean;
    reason?: string;
    policy?: string;
    metadata?: Record<string, unknown>;
}
type DecisionPolicy<S = Subject, R = unknown> = (subject: S, resource?: R) => AuthorizationDecision | Promise<AuthorizationDecision>;
declare function allow(reason?: string, metadata?: Record<string, unknown>): AuthorizationDecision;
declare function deny(reason?: string, metadata?: Record<string, unknown>): AuthorizationDecision;
declare function decision<S, R>(name: string, policy: Policy<S, R>, denial?: string): DecisionPolicy<S, R>;
declare function owner<SubjectType extends Subject, Resource extends Record<string, unknown>>(subjectKey?: keyof SubjectType, resourceKey?: keyof Resource | string): DecisionPolicy<SubjectType, Resource>;
declare function anyDecision<S, R>(...policies: DecisionPolicy<S, R>[]): DecisionPolicy<S, R>;
declare function allDecisions<S, R>(...policies: DecisionPolicy<S, R>[]): DecisionPolicy<S, R>;
declare function authorizeDecision(evaluate: (ctx: Context) => AuthorizationDecision | Promise<AuthorizationDecision>): Middleware;
declare function filterAuthorized<S, R>(subject: S, values: readonly R[], policy: Policy<S, R>): Promise<R[]>;

/**
 * @wrnexus/authz — authorization: role-based (RBAC), policy-based (PBAC), and
 * attribute-based (ABAC). Compose freely; all three reduce to a boolean check
 * plus an `authorize()` guard middleware.
 *
 *   const rbac = defineRbac({ admin: ["*"], editor: ["post:read", "post:write"] });
 *   rbac.can(user, "post:write");
 *
 *   // PBAC/ABAC: a policy is a predicate over subject + resource + attributes
 *   const ownsPost: Policy<User, Post> = (u, post) => u.id === post.authorId;
 *   authorize((ctx) => ownsPost(ctx.user, resource))  // middleware
 */

interface Subject {
    id?: string;
    roles?: string[];
    [attribute: string]: unknown;
}
interface Rbac {
    /** True if any of the subject's roles grants `permission` (supports "*" and "ns:*"). */
    can(subject: Subject | undefined, permission: string): boolean;
    /** All permissions granted to a set of roles. */
    permissionsFor(roles: string[]): Set<string>;
}
/** Build an RBAC checker from a role → permissions map. */
declare function defineRbac(roles: Record<string, string[]>): Rbac;
/** True if the subject has ALL of the given roles. */
declare function hasRole(subject: Subject | undefined, ...required: string[]): boolean;
/** A policy predicate: subject (+ optional resource/attributes) → allowed. */
type Policy<S = Subject, R = unknown> = (subject: S, resource?: R) => boolean | Promise<boolean>;
/** Combine policies: allow if ANY passes (OR). */
declare function any<S, R>(...policies: Policy<S, R>[]): Policy<S, R>;
/** Combine policies: allow only if ALL pass (AND). */
declare function all<S, R>(...policies: Policy<S, R>[]): Policy<S, R>;
/** ABAC helper: allow when an attribute matches (equality or predicate). */
declare function attr<S extends Subject>(name: string, match: unknown | ((value: unknown) => boolean)): Policy<S>;
/** Guard a route with a policy over `ctx` (reads `ctx.user` as the subject). */
declare function authorize(policy: (ctx: Context) => boolean | Promise<boolean>): Middleware;
/** Guard requiring one of the given roles. */
declare function requireRole(...roles: string[]): Middleware;
/** Guard requiring an RBAC permission. */
declare function requirePermission(rbac: Rbac, permission: string): Middleware;

export { type AuthorizationDecision, type DecisionPolicy, type Policy, type Rbac, type Subject, all, allDecisions, allow, any, anyDecision, attr, authorize, authorizeDecision, decision, defineRbac, deny, filterAuthorized, hasRole, owner, requirePermission, requireRole };
```

---

## @wrnexus/captcha

Documentation URL: https://wrnexusjs.dev/packages/captcha

# @wrnexus/captcha

A first-class CAPTCHA and anti-automation package for WRNexusJS. It supports self-hosted challenges, a managed WRNexus service, external providers, form submission guards, page gates, accessible audio, adaptive risk checks, and a Tailwind-only `.wrn` component.

## Install

```bash
bun add @wrnexus/captcha
```

WRNexusJS automatically discovers the package plugin, component, client runtime, styles, and DevToolbar audit. Use `<Captcha />` directly after installation. The browser runtime is injected once only on responses that render a CAPTCHA; no script tag, public-file copy, or manual plugin registration is required. Call `captchaPlugin(options)` explicitly only when an application needs to override the discovered package configuration.

## Included challenge modes

- Number, alphabet, and alphanumeric image challenges
- Addition, subtraction, multiplication, and exact-division calculations
- Generated shape-selection image challenges
- Audio alternatives for text, numbers, and calculations
- Honeypot and minimum-completion-time invisible checks
- Self-hosted “I’m not a robot” checkbox challenge with one-time server verification
- Always, once-per-session, and adaptive page gates
- Cloudflare Turnstile, Google reCAPTCHA, hCaptcha, managed, and custom providers

## Create the self-hosted engine

```ts
import {
  createCaptchaEngine,
  createCaptchaHttpHandlers,
  RedisCaptchaStore,
} from "@wrnexus/captcha/server";

const engine = createCaptchaEngine({
  secret: process.env.CAPTCHA_SECRET!,
  store: new RedisCaptchaStore(redis),
  basePath: "/api/captcha",
  challengeTtlMs: 2 * 60_000,
  responseTokenTtlMs: 5 * 60_000,
  maxAttempts: 3,
  minCompletionMs: 800,
});

export const handlers = createCaptchaHttpHandlers(engine);
```

Mount the handlers from an API catch-all route:

```ts
import type { Context } from "@wrnexus/core";
import { handlers } from "../../lib/captcha.ts";

export async function POST(ctx: Context) {
  return (await handlers.handle(ctx.req, ctx)) ?? new Response("Not Found", { status: 404 });
}
export const GET = POST;
export const HEAD = POST;
```

## Use the component

```wrn
<Captcha
  type="alphanumeric"
  action="signup"
  endpoint="/api/captcha/challenge"
  verifyEndpoint="/api/captcha/verify"
  difficulty="normal"
  disturbance="50"
  imageStyle="random"
  allowedStyles="classic,snow,distortion,wave"
  size="normal"
  showAudio="true"
  showListen="true"
  @success='captchaToken = event.detail.responseToken'
  @failure='formError = event.detail.extra.message'
/>
```

The component uses Tailwind utilities and `--wire-*` theme variables. It has no companion component CSS file.

### Main props

`provider`, `siteKey`, `type`, `action`, `presentation`, `difficulty`, `disturbance`, `imageStyle`, `allowedStyles`, `excludedStyles`, `randomizeStyle`, `locale`, `size`, `color`, `class`, `name`, `endpoint`, `verifyEndpoint`, `responseField`, labels/messages, `autoLoad`, `autoVerify`, `showVerify`, `showRefresh`, `showAudio`, `showListen`, `showStatus`, `disabled`, `required`, and the backward-compatible `compact` alias.

### Component sizes

Use one of the three supported display modes:

```wrn
<Captcha size="compact" action="small-form" />
<Captcha size="normal" action="standard-form" />
<Captcha size="big" action="security-page" />
```

`small`/`sm` are accepted as aliases for `compact`, while `large`/`lg` are accepted as aliases for `big`. The old `compact="true"` prop still forces compact mode.

### Listen button visibility

Audio remains available by default. Hide the Listen and Use audio controls with either of these props:

```wrn
<Captcha showListen="false" action="without-listen-button" />
<Captcha showAudio="false" action="without-audio-alternative" />
```

`showListen` is the direct UI switch. `showAudio` remains the broader backward-compatible audio switch.

### I’m not a robot checkbox

```wrn
<Captcha
  type="not-robot"
  action="contact-submit"
  size="compact"
  showListen="false"
/>
```

The checkbox is not a client-only boolean. Clicking it completes a self-hosted invisible challenge that is time-limited, attempt-limited, one-time-use, action-bound, optionally session/hostname/IP-bound, and verified on the server. It is a low-friction anti-automation layer; use adaptive escalation to a visual or external provider for high-risk traffic.

### Visual disturbance

Use `disturbance` for visual and image-selection challenges. It accepts an integer from `25` through `75`:

- `25`: light disturbance and easiest readability
- `50`: balanced default
- `75`: maximum supported dots, line crossings, glyph movement, and image-tile noise

The browser sends this value to the challenge API, and the server validates the range before generating the challenge. It is also returned in challenge metadata.

### Generated image renderer styles

Text, number, alphanumeric, and calculation CAPTCHA images support 18 concrete renderers plus a random mode:

`classic`, `collision`, `snow`, `corrosion`, `spiderweb`, `cross-shadow`, `split`, `split2`, `cut`, `darts`, `distortion`, `stitch`, `striped`, `wave`, `grid-noise`, `scribble`, `pixel`, and `broken-lines`.

Use a fixed style:

```wrn
<Captcha
  type="alphanumeric"
  action="signup"
  imageStyle="spiderweb"
  disturbance="55"
/>
```

Use a new random style whenever the challenge is refreshed:

```wrn
<Captcha
  type="number"
  action="login"
  imageStyle="random"
  difficulty="normal"
/>
```

Control the random pool with comma-separated component props or arrays in the TypeScript API:

```wrn
<Captcha
  type="alphanumeric"
  action="checkout"
  imageStyle="random"
  allowedStyles="classic,snow,distortion,wave"
  excludedStyles="collision"
/>
```

```ts
const challenge = await engine.create({
  action: "checkout",
  type: "alphanumeric",
  imageStyle: "random",
  allowedStyles: ["classic", "snow", "distortion", "wave"],
  excludedStyles: ["collision"],
});
```

Set `randomizeStyle: true` to force random selection even when `imageStyle` names a concrete renderer. The resolved style, requested style, and active pool are returned in challenge metadata. The answer is never embedded in metadata or browser JavaScript.

### Events

`@ready`, `@challenge`, `@input`, `@verify`, `@success`, `@failure`, `@expired`, `@refresh`, `@audioStart`, `@audioEnd`, and `@error`.

## Protect a validated form API

Validate a cloned request first, then consume the CAPTCHA response token. This prevents a valid token from being consumed when ordinary field validation fails.

```ts
import { captchaGuard } from "@wrnexus/captcha/server";
import { parseBody } from "@wrnexus/validation";
import contactSchema from "../schemas/contact.ts";
import { engine } from "../lib/captcha.ts";

const guard = captchaGuard({
  action: "contact-submit",
  engine,
  bindHostname: true,
  bindSession: true,
});

export async function POST(ctx) {
  const validation = await parseBody(contactSchema, ctx.req.clone());
  if (!validation.ok) return validation.response;

  return guard(ctx, async () => Response.json({ ok: true, submission: validation.value }));
}
```

The CAPTCHA runtime binds its required-form check in the capture phase, so a `data-schema` validator cannot submit the form before CAPTCHA verification. After a successful form request, the component automatically creates a fresh challenge.

### Retryable operations such as login

A login may consume a valid CAPTCHA and then fail because the password is
incorrect. Configure a short action-bound session grant so the user can correct
their credentials without solving CAPTCHA again:

```ts
const guard = captchaGuard({
  action: "auth-login",
  engine,
  bindHostname: true,
  bindSession: true,
  verifiedForMs: 5 * 60_000,
});
```

Keep the verified widget state for non-CAPTCHA form errors:

```wrn
<Captcha
  action="auth-login"
  required="true"
  resetOnError="false"
/>
```

The grant is stored in the current session and bound to the configured action.
Expired grants and CAPTCHA-specific errors still require and load a fresh
challenge. Keep login rate limits and authentication lockout enabled;
`verifiedForMs` removes repeated human verification, not credential-abuse
controls.

## Validate a schema and CAPTCHA together

```ts
const result = await parseWithCaptcha(signupSchema, body, ctx, {
  action: "signup",
  engine,
});

if (!result.ok) return Response.json({ ok: false, errors: result.errors }, { status: 400 });
```

## Page gate

```ts
export default captchaPageGate({
  action: "reports-access",
  engine,
  challengePath: "/captcha",
  policy: {
    mode: "session",
    verifiedForMs: 15 * 60_000,
    routeGroups: ["/reports"],
  },
});
```

Use `mode: "always"` for every visit, `mode: "session"` for a temporary grant, or `mode: "adaptive"` with `signals(ctx)`.

The challenge page should post the return path as a normal hidden field instead of constructing JavaScript inside the HTML `action` attribute:

```wrn
<form method="post" action="/api/page-grant">
  <input type="hidden" name="returnTo" value='{returnTo}' />
  <Captcha action="reports-access" />
  <button type="submit">Continue</button>
</form>
```

The `/api/page-grant` route reads `returnTo`, restricts it to the current origin, and redirects only after `captchaPageGate()` has verified and stored the temporary session grant.

## External providers

```ts
const turnstile = turnstileProvider({
  secretKey: process.env.TURNSTILE_SECRET!,
  siteKey: process.env.PUBLIC_TURNSTILE_SITE_KEY!,
  expectedHostnames: ["example.com"],
  expectedAction: "signup",
});
```

```wrn
<Captcha
  provider="turnstile"
  siteKey="PUBLIC_SITE_KEY"
  action="signup"
/>
```

Use the matching provider in `captchaGuard({ provider: turnstile })`. reCAPTCHA and hCaptcha adapters follow the same pattern.

## Managed provider

```ts
const managed = managedCaptchaProvider({
  baseUrl: "https://captcha.example.com",
  siteKey: process.env.PUBLIC_CAPTCHA_SITE_KEY!,
  secretKey: process.env.CAPTCHA_SECRET_KEY!,
});
```

For direct browser challenge creation, configure the component’s `endpoint` as the managed `/v1/challenges` URL and its `verifyEndpoint` as `/v1/solve`. Keep the secret key only in the server provider.

## Stores

- `MemoryCaptchaStore`: development and one-process applications
- `SqliteCaptchaStore`: adapter for SQLite-like `prepare().run/get/all()` clients
- `RedisCaptchaStore`: shared TTL storage with Lua-backed atomic consumption when `eval` is available
- `CaptchaStore`: implement this interface for PostgreSQL, MySQL, MongoDB, or another backend

## Audio

`AssetAudioRenderer` concatenates bundled English PCM WAV clips without calling an external service. Supply a custom `CaptchaAudioRenderer` for recorded voices, Hindi or other languages, or managed text-to-speech.

## DevToolbar

The automatically discovered CAPTCHA plugin registers its DevToolbar audit panel. It checks for likely client-side secrets, missing action bindings, missing provider site keys, optional CAPTCHA fields, accessible alternatives, and server-verification reminders. Explicit `captchaPlugin(options)` registration is needed only to override automatic configuration.

## Testing

Use deterministic custom generators in unit tests. Never require users or CI to solve random CAPTCHA images. The package includes engine, provider, policy, HTTP, storage, replay, expiry, binding, and audio authorization tests.

## Custom challenge generator

```ts
import { defineCaptchaGenerator, createCaptchaEngine } from "@wrnexus/captcha";

const wordChallenge = defineCaptchaGenerator({
  type: "word" as const,
  generate(context) {
    const answer = "NEXUS";
    return {
      type: "word",
      presentation: "visual",
      prompt: "Enter the displayed word",
      answer,
      answerKind: "text",
      image: renderYourImage(answer),
      inputMode: "text",
    };
  },
});

const engine = createCaptchaEngine({ secret, generators: [wordChallenge] });
```

Applications may also implement `CaptchaStore`, `CaptchaAudioRenderer`, or use `defineCaptchaProvider()` for a completely custom service.

### Exported TypeScript declarations

```ts
export { CaptchaAudioRenderer, CaptchaBinding, CaptchaChallenge, CaptchaChallengeGenerator, CaptchaChallengeRecord, CaptchaChallengeType, CaptchaConcreteImageStyle, CaptchaDifficulty, CaptchaEngine, CaptchaEngineOptions, CaptchaFailureCode, CaptchaGeneratorContext, CaptchaGuardOptions, CaptchaHttpHandlers, CaptchaImageItem, CaptchaImageStyle, CaptchaMiddleware, CaptchaPageGateOptions, CaptchaPolicyMode, CaptchaPolicyOptions, CaptchaPresentation, CaptchaProvider, CaptchaProviderClientConfig, CaptchaProviderName, CaptchaResponseTokenRecord, CaptchaRiskResult, CaptchaRiskSignals, CaptchaStore, CaptchaVerificationResult, CreateCaptchaOptions, GeneratedCaptchaChallenge, VerifyCaptchaInput } from './types.js';
export { CaptchaHttpOptions, CaptchaParseResult, CaptchaSessionGrant, DefaultCaptchaEngine, ParseWithCaptchaOptions, bindingHash, bytesToBase64Url, captchaGuard, captchaPageGate, clearCaptchaGrants, constantTimeEqual, createCaptchaEngine, createCaptchaHttpHandlers, defaultRandomBytes, evaluateCaptchaRisk, hmacSha256, parseWithCaptcha, randomId, sha256, shouldRequireCaptcha, validCaptchaGrant } from './server/index.js';
export { CaptchaAuditIssue, CaptchaPluginOptions, captchaComponentsDir, captchaPlugin } from './plugin.js';
export { MemoryCaptchaStore, MemoryCaptchaStoreOptions, createMemoryCaptchaStore } from './stores/memory.js';
export { SqliteCaptchaStore, SqliteCaptchaStoreOptions, SqliteDatabaseLike, SqliteStatementLike, createSqliteCaptchaStore } from './stores/sqlite.js';
export { RedisCaptchaClient, RedisCaptchaStore, RedisCaptchaStoreOptions, createRedisCaptchaStore } from './stores/redis.js';
export { SelfHostedCaptchaProvider, selfHostedProvider } from './providers/self-hosted.js';
export { S as SiteverifyCaptchaProvider, a as SiteverifyPreset, b as SiteverifyProviderOptions } from './siteverify-Cg3TTAp4.js';
export { TurnstileCaptchaProvider, turnstileProvider } from './providers/turnstile.js';
export { RecaptchaProvider, recaptchaProvider } from './providers/recaptcha.js';
export { HcaptchaProvider, hcaptchaProvider } from './providers/hcaptcha.js';
export { ManagedCaptchaProvider, ManagedCaptchaProviderOptions, managedCaptchaProvider } from './providers/managed.js';
export { defineCaptchaProvider } from './providers/custom.js';
export { CAPTCHA_CONCRETE_IMAGE_STYLES, CAPTCHA_IMAGE_STYLES, CalculationCaptchaGenerator, ImageCaptchaGenerator, InvisibleCaptchaGenerator, ResolveCaptchaImageStyleOptions, ResolvedCaptchaImageStyle, Rgba, RgbaImage, TextCaptchaGenerator, alphaCaptchaGenerator, alphanumericCaptchaGenerator, bytesToBase64, calculationCaptchaGenerator, createImage, defaultCaptchaGenerators, defineCaptchaGenerator, drawGlyph, drawLine, drawText, encodePng, fillCircle, fillPolygon, fillRect, honeypotCaptchaGenerator, imageCaptchaGenerator, isCaptchaImageStyle, normalizeCaptchaImageStyle, normalizeCaptchaImageStyleList, notRobotCaptchaGenerator, numberCaptchaGenerator, pngDataUri, resolveCaptchaImageStyle, setPixel, timingCaptchaGenerator } from './challenges/index.js';
export { AssetAudioRenderer, AssetAudioRendererOptions, createAssetAudioRenderer, resolveCaptchaAudioAssetsDir } from './audio/index.js';
import '@wrnexus/core';
import '@wrnexus/validation';
import '@wrnexus/plugin';
```

---

## @wrnexus/cli

Documentation URL: https://wrnexusjs.dev/packages/cli

# @wrnexus/cli

> The `wrnexus` command-line tool that scaffolds, runs, builds, tests, and manages WrNexus apps.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

`@wrnexus/cli` provides the `wrnexus` executable — the single entry point for developing a WrNexus app. It runs the HMR dev server, produces a self-contained production build, scaffolds apps/pages/components, drives database migrations, regenerates typed routes and queries, runs tests, and manages configuration profiles. It also scaffolds multi-app monorepos and serves them behind a domain-routing gateway. This is a CLI/build-time package (it shells out to the Bun binary for the dev child and tests) and it also exports the workspace config types via a subpath.

## Installation

```bash
bun add @wrnexus/cli
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported).

Once installed, invoke it from an app directory:

```bash
bunx wrnexus dev
# or add scripts: "dev": "wrnexus dev .", "build": "wrnexus build ."
```

## Commands

Every command accepts an optional `[app-dir]` (defaults to `.`). Commands that read config or `.env` also accept `--profile=<name>` (see [Profiles](#profiles)).

| Command                               | Purpose                                                                |
| ------------------------------------- | ---------------------------------------------------------------------- |
| `wrnexus dev [app-dir] [--port=3000]` | Start the development server with live reload / HMR.                   |
| `wrnexus build [app-dir]`             | Build a self-contained production server bundle + assets into `dist/`. |
| `wrnexus create <app-name>`           | Scaffold a new single app from an inline template.                     |
| `wrnexus workspace <name>`            | Scaffold a monorepo (`apps/*` + shared `packages/*`).                  |
| `wrnexus workspace add <name>`        | Add and register an app in the current workspace.                      |
| `wrnexus gateway [--port=3000]`       | Serve every workspace app behind one port, routed by domain.           |
| `wrnexus production [workspace-dir]`  | Build, migrate, and serve every workspace app in production.           |
| `wrnexus generate <type> <name>`      | Scaffold a `page` \| `component` \| `api` \| `schema`.                 |
| `wrnexus generate routes`             | Regenerate the typed routes file (`app/routes.gen.ts`).                |
| `wrnexus generate docker`             | Scaffold `Dockerfile`, `.dockerignore`, and `docker-compose.yml`.      |
| `wrnexus generate mobile`             | Scaffold a Capacitor shell for iOS and Android.                        |
| `wrnexus mobile add <package...>`     | Install Capacitor plugins and sync native projects.                    |
| `wrnexus eject <name...>`             | Copy Wire UI component `.wrn` sources into `app/components/`.          |
| `wrnexus db <cmd>`                    | Database migrations and tooling (see [db](#wrnexus-db)).               |
| `wrnexus test [app-dir] [--watch]`    | Run the app's tests via `bun test` (defaults to the `test` profile).   |
| `wrnexus profiles [app-dir]`          | List config profiles and their `.env` files, marking the active one.   |
| `wrnexus help`                        | Print usage.                                                           |

`wrnexus g` is an alias for `wrnexus generate`.

### `wrnexus dev`

Supervises a child dev-server process (from `@wrnexus/dev-server`). The child owns file watching and HMR: CSS and client-island edits update the live page over a WebSocket with no restart; when a server module changes, the child exits with a restart code and the supervisor respawns it (the browser reconnects and morphs in the new HTML). On startup it regenerates typed DB queries and typed routes (best effort). Use `--port=` to change the port (default `3000`).

```bash
wrnexus dev . --port=8080
```

### `wrnexus build`

Emits into `<app-dir>/dist/`:

- `server.js` — a single, minified, self-contained Bun server with a **static** manifest of every page / api / realtime / middleware / component / layout module (no runtime filesystem scan or on-the-fly bundling).
- `reactive.js`, `theme.css`, `theme.js`, `ui.css`, and (if present) `styles.css` — hashed, minified browser assets.
- `public/` — copied verbatim.

Before bundling, it regenerates typed queries for the default and every named database. Run the output with:

```bash
bun dist/server.js   # PORT env var optional
# Generated apps also provide: npm start
# Build and start together: npm run production
```

### `wrnexus create`

Scaffolds a new app from an inline (dependency-free) template — `package.json`, `.gitignore`, config, and starter `app/` files. Use `npm run dev` during development, `npm run build && npm start` for production, or `npm run production` to build and start in one command. The generated production server currently requires Bun even when npm is used to manage packages and scripts.

### `wrnexus update`

`wrnexus update --latest` performs a complete project upgrade. It hands control to the exact target CLI, backs up important project files under `.wrnexus/update-backups/`, updates every `@wrnexus/*` dependency, refreshes framework-owned references, and applies every versioned syntax/config/file migration between the project version and target version. After installation it runs the project's `check` and `build` scripts; the new version is recorded only after verification succeeds.

Use `--dry-run` to preview an upgrade or `--no-verify` when verification is intentionally handled elsewhere. Migrations never overwrite user-owned configuration wholesale: each release must provide a focused, idempotent transformation for any changed syntax or config contract.

```bash
wrnexus create my-app
```

### `wrnexus generate`

Scaffolds a single file from a template, refusing to overwrite an existing file. Types (with aliases): `page`/`p`, `component`/`c`, `api`/`a`, `schema`/`s`. Nested names create nested paths.

```bash
wrnexus generate page about          # app/pages/about.wrn
wrnexus generate component user-card # app/components/user-card.wrn
wrnexus generate api users/list      # app/api/users/list.ts
wrnexus generate schema signup       # app/schemas/signup.ts
wrnexus generate routes              # regenerate app/routes.gen.ts
wrnexus generate docker              # Dockerfile + compose + .dockerignore
wrnexus generate mobile --mode=webview --app-id=com.example.app --app-name="Example" --url=https://app.example.com
wrnexus generate mobile --mode=native
```

The mobile generator creates a separate `mobile/` package and reads
`config.mobile.mode`. `webview` creates a Capacitor shell that renders the hosted
WrNexus application. `native` creates a WebView-free Expo/React Native app whose
screens call the shared backend through `mobile/src/wrnexus.ts`. Native screens
do not render `.wrn` HTML. In either mode, run `bun install` in `mobile/`; iOS
device builds require macOS and Xcode.

Install official or community Capacitor plugins through the root CLI:

```bash
wrnexus mobile add @capacitor/camera @capacitor/haptics
wrnexus mobile sync
wrnexus mobile assets # generate native icons from config.mobile.icon
```

In native mode, `mobile add` runs `expo install` and `mobile sync` runs Expo
prebuild. In WebView mode they retain the Capacitor install/sync behavior.
`wrnexus mobile compile` maps portable `app/pages/**/*.wrn` pages to Expo Router
TSX routes. Native `bun run start` invokes this compilation automatically.

Browser code can access installed plugins through the SSR-safe
`@wrnexus/mobile` bridge. The command adds each plugin to both the WrNexus app
(JavaScript proxy) and `mobile/` (native synchronization).

`wrnexus mobile sync` also configures Android so only true network failures use
the local connection-error screen. HTTP errors such as 404 and 500 keep their
WrNexus response pages.

### `wrnexus eject`

Copies a Wire UI component's `.wrn` source out of `@wrnexus/ui` into `app/components/`, so the app owns and can edit it (the app copy shadows the library one by name). Run with no names to list available components. It skips components that already exist in the app.

```bash
wrnexus eject button card modal
```

### `wrnexus db`

Database migrations and tooling. Without a flag, commands target the **default** database (`db` in `wrnexus.config.ts`, files under `app/db/`). Pass `--db=<name>` to target a named database (`databases.<name>`, files under `app/db/<name>/`).

| Subcommand                      | Purpose                                                                             |
| ------------------------------- | ----------------------------------------------------------------------------------- |
| `db new <name> [--from-models]` | Scaffold a migration; `--from-models` derives it from the TS models in `schema.ts`. |
| `db migrate`                    | Apply all pending migrations.                                                       |
| `db rollback`                   | Revert the last applied migration.                                                  |
| `db status`                     | List applied / pending migrations.                                                  |
| `db generate`                   | Regenerate typed queries (`queries/*.sql` → `queries.gen.ts`).                      |
| `db seed`                       | Run the database's `seed.ts` (default export / `seed` function).                    |
| `db studio [table]`             | Inspect tables — list row counts, or dump the first 50 rows of one table.           |

```bash
wrnexus db new create_users --from-models
wrnexus db migrate
wrnexus db studio users
wrnexus db status --db=analytics
```

### `wrnexus workspace` and `wrnexus gateway`

`workspace <name>` scaffolds a monorepo: several WrNexus apps under `apps/*` and shared libraries under `packages/*`, plus a `wrnexus.workspace.ts` that maps each app to the domains it serves. `gateway` runs every app behind one port and routes by `Host` header, with optional per-app auth and gateway-wide security (trusted hosts, rate limit, security headers, access log).

```bash
wrnexus workspace acme
wrnexus gateway --port=3000
```

For a complete production start, use the first-class workspace orchestrator:

```bash
wrnexus production --host=0.0.0.0 --port=3000
```

It builds every registered app, applies default and named-database SQL migrations
when present, and starts the production gateway only after preparation succeeds.
Use `--prepare-only`, `--no-build`, or `--no-migrate` when deployment stages are
managed separately; `--environment=<name>` selects another workspace environment.

From a workspace root, add and register another app in one command:

```bash
wrnexus workspace add reports --domain=reports.localhost
bun install
```

Development gateways bind to `127.0.0.1` by default for reliable access on Windows,
macOS, and Linux. Open the configured app domain on the gateway port (for example
`http://localhost:3000` or `http://admin.localhost:3000`), not the internal child ports
printed while apps start. Pass `--host=0.0.0.0` to accept connections from other devices.

### `wrnexus test`

Runs the app's tests with `bun test`. Defaults to the `test` profile (config + `.env.test`). Pass `--watch` to re-run on change; extra flags pass straight through to `bun test`.

```bash
wrnexus test . --watch
```

## Usage

### Create and run a single application

```bash
bunx @wrnexus/cli create customer-portal
cd customer-portal
bun install
bun run dev
```

### Add routes and shared UI to an existing app

```bash
wrnexus generate page reports/monthly
wrnexus generate api reports/export
wrnexus generate component report-filter
wrnexus generate routes
```

### Create a multi-app workspace and add another app

```bash
wrnexus workspace company-suite
cd company-suite
wrnexus workspace add reports --domain=reports.localhost
bun install
wrnexus gateway --port=3000
```

Open `http://reports.localhost:3000`; the gateway selects `apps/reports` from the
request host.

### Upgrade with migrations and verification

```bash
wrnexus update --latest --dry-run
wrnexus update --latest
wrnexus doctor
```

## Profiles

Pass `--profile=<name>` to `dev`, `build`, `db` (or set `WRNEXUS_PROFILE`) to select a config profile. The CLI publishes `WRNEXUS_PROFILE` so config loaders and the dev child pick it up, and loads that profile's `.env` cascade (`.env`, `.env.local`, `.env.<profile>`, `.env.<profile>.local`) into `process.env`.

```bash
wrnexus dev --profile=uat
wrnexus profiles          # ● development  (config, .env.development)
                          # ○ production
                          # ○ uat          (config, .env.uat)
```

## Subpath exports

`@wrnexus/cli/workspace` exposes the workspace configuration types used by `wrnexus.workspace.ts`:

```ts
import type { WorkspaceConfig, WorkspaceApp } from "@wrnexus/cli/workspace";

const config: WorkspaceConfig = {
  security: { trustedHostsOnly: true, headers: true, accessLog: true },
  apps: [{ name: "web", dir: "apps/web", domains: ["localhost", "web.localhost"] }],
};

export default config;
```

## Requirements / Notes

- **Bun-only.** The CLI runs on Bun, spawns the Bun binary for the dev child and `bun test`, and the production build uses `Bun.build`. Node is not supported.
- Orchestrates the rest of the framework: `@wrnexus/dev-server` (dev/prod server + gateway), `@wrnexus/router` (route + typed-routes codegen), `@wrnexus/compiler` (`.wrn` → `.ts`), `@wrnexus/db` (migrations, typed queries), `@wrnexus/styles` (config, profiles, `.env`, themes, styles), `@wrnexus/ui` (ejectable Wire UI components), `@wrnexus/validation`, `@wrnexus/csr`, and `@wrnexus/i18n`.
- Reads `wrnexus.config.ts` for `db` / `databases`, `theme`, `styles`, `seo`, `security`, `i18n`, and `profiles`, and `wrnexus.workspace.ts` for the gateway.

### Exported TypeScript declarations

```ts
#!/usr/bin/env bun
```

---

## @wrnexus/compiler

Documentation URL: https://wrnexusjs.dev/packages/compiler

# @wrnexus/compiler

> Compiler for the `.wrn` language — tokenizes, parses, and lowers `.wrn` page and component files to TypeScript.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

`@wrnexus/compiler` turns `.wrn` source into TypeScript that targets the framework's runtime primitives. A `.wrn` file declares either a `page` (a route) or a `component` (a reusable, prop-driven fragment) with blocks for `state`, `view` (plain HTML), `seo`, `style`, `functions`, `api`, `ssr`/`client` data bindings, and `realtime` websocket handlers. The pipeline is `source → Lexer → parse() → PageAst → generate() → TypeScript`. It is a build/server-side library — the WrNexus dev loader calls it to compile `.wrn` files on the fly, surfacing `ParseError` as a readable error page.

Static ES module imports may appear before the root declaration. Imported values are
available to server-rendered expressions, including component props:

```wrn
import { appUrl } from "@wrnexus/helpers";

layout PublicLayout {
  view {
    <PublicHeader signInHref="{appUrl('sso', '/sign-in')}" />
  }
}
```

## Installation

```bash
bun add @wrnexus/compiler
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported).

## API

All exports come from the package root (`@wrnexus/compiler`).

### `compileWireFile(source: string): string`

Compile `.wrn` source to a TypeScript module string. Throws `ParseError` on invalid input. The output is prefixed with a `// compiled from .wrn` comment.

### `compile(source: string): CompileResult`

Richer entry point that returns the generated code, the AST, and any diagnostics.

```ts
interface CompileResult {
  code: string;
  ast: PageAst;
  diagnostics: string[];
}
```

On a `ParseError` it pushes the message into `diagnostics` and re-throws.

### `parse(source: string): PageAst`

Run the lexer + recursive-descent parser and return the AST. Throws `ParseError` (lexer `LexError`s are caught and rethrown as `ParseError`).

### `generate(ast: PageAst): string`

Lower a `PageAst` to TypeScript. `page` ASTs become a default-export page component (plus `meta`, optional `layout`, `__wrnexusApi`/method handlers, `websocket`, and SSR/CSR data bindings); `component` ASTs become a module exporting `render(props)` and `__wrnexusComponent`.

### `Lexer`

On-demand lexer for `.wrn`. Yields structural tokens and exposes raw-span readers for the parser.

```ts
class Lexer {
  pos: number;
  constructor(src: string);
  next(): Token; // consume next structural token
  peek(): Token; // look ahead without consuming
  readPath(): string; // route path, e.g. /users/[id]
  readToLineEnd(): string; // rest of line (state/prop initializers)
  readBalancedBraces(): string; // inner text of a { ... } block, string-aware
}
```

`Token` is `{ type: TokenType; value: string; pos: number }`, where `TokenType` is one of `ident`, `string`, `lbrace`, `rbrace`, `lparen`, `rparen`, `at`, `eq`, `comma`, `eof`.

### Errors

| Class        | Thrown by                                         | Meaning                                                         |
| ------------ | ------------------------------------------------- | --------------------------------------------------------------- |
| `ParseError` | `parse`, `compile`, `compileWireFile`, `generate` | Invalid `.wrn` grammar or (rewrapped) lex failure.              |
| `LexError`   | `Lexer`                                           | Unexpected character / unterminated string / unbalanced braces. |

### AST types

Exported type-only symbols describing the parsed tree:

| Type                 | Description                                                                                                                                                   |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `PageAst`            | Root node including top-level `imports`, `kind`, `name`, `types`, typed `props`, typed `states`, `view`, styles, functions, data APIs, lifecycle, and routes. |
| `ViewNode`           | `{ type: "text"; value }` or `{ type: "element"; tag; attrs; children }`.                                                                                     |
| `Attr`               | `{ name; value; event; boolean? }` — `event` marks `@event` bindings.                                                                                         |
| `StateDecl`          | `{ name; valueType?; expr }` — a typed `state x: Type = <expr>` declaration.                                                                                  |
| `PropDecl`           | `{ name; valueType?; required; default }` — a typed prop declaration.                                                                                         |
| `SeoBlock`           | `Record<string, string>` from the `seo { ... }` block.                                                                                                        |
| `ApiBlock`           | `{ method; path; body }` — a top-level `api METHOD /path { ... }`.                                                                                            |
| `DataApiBlock`       | `{ mode; name; method; path; body }` — an `api` inside an `ssr`/`client` block.                                                                               |
| `DataMode`           | `"ssr" \| "client"`.                                                                                                                                          |
| `ModeFunctionsBlock` | `{ mode; body }` — a `functions { ... }` inside an `ssr`/`client` block.                                                                                      |
| `RealtimeBlock`      | `{ name; handlers }` — a `realtime <name> { on evt(args) { ... } }` block.                                                                                    |

## Usage

Compile a page:

```ts
import { compileWireFile } from "@wrnexus/compiler";

const ts = compileWireFile(`
page Home {
  state count = 0
  seo { title = "Home" description = "Welcome" }
  view {
    <button @click="count++">Clicked {count} times</button>
  }
}
`);
// ts is a TypeScript module: exports `meta`, and a default page component
// returning an HTML string, wrapped in a data-scope for the reactive runtime.
```

Inspect the AST and diagnostics:

```ts
import { compile, ParseError } from "@wrnexus/compiler";

try {
  const { code, ast, diagnostics } = compile(source);
  console.log(ast.kind, ast.name, ast.states.length);
} catch (err) {
  if (err instanceof ParseError) console.error(err.message);
}
```

Drive the parse/codegen stages directly:

```ts
import { parse, generate } from "@wrnexus/compiler";

const ast = parse(componentSource); // ast.kind === "component"
const module = generate(ast); // exports render(props) + __wrnexusComponent
```

Use the lexer standalone:

```ts
import { Lexer } from "@wrnexus/compiler";

const lx = new Lexer("page Home {");
lx.next(); // { type: "ident", value: "page", pos: 0 }
lx.next(); // { type: "ident", value: "Home", pos: 5 }
lx.next(); // { type: "lbrace", value: "{", pos: 10 }
```

## The `.wrn` language (as parsed)

A file opens with `page <Name>` or `component <Name>` followed by a `{ ... }` body containing zero or more members:

- `layout = "<name>"` — selects `app/layouts/<name>.wrn` (pages only).
- `types { <TypeScript declarations> }` — reusable interfaces and aliases for the current file.
- `props { name: Type = <default> ... }` — typed component props. Omit `= <default>` to make a prop required. Legacy inferred props remain supported.
- `@event name = function` inside `props` — declares a public component event. Emit it from component behavior with `name(detail)` or `$emit("name", detail)`, and consume it with `<Component @name="handler(event)" />`.
- `state <ident>: Type = <expr>` — typed reactive state seeded from a raw JS expression, including native array and object literals. The annotation is optional for backward compatibility.
- `view { <html> }` — plain HTML with `{expr}` interpolation in text and attributes, JSX-style component props such as `items={items}`, `items={[...]}`, and `options={{...}}`, hyphenated attributes, boolean attributes, `@event="..."` client bindings, and `<!-- comments -->`. Structured component props are serialized safely for SSR; expressions that reference `state` retain their initial value and update reactively in the browser.
- `seo { key = "value" ... }` — metadata merged into the generated `meta`.
- `style { <raw css> }` — inlined page/component stylesheet (repeatable).
- `functions { <TypeScript> }` — helpers with typed parameters and return values. Types remain in server output and are safely erased from browser behavior code.
- `api <METHOD> <path> { <raw js> }` — route handler, lowered to a `METHOD` export (repeatable).
- `ssr { ... }` / `client { ... }` — data blocks holding `api <name> <METHOD> <path> { ... }` bindings and their own `functions { ... }`.
- `realtime <name> { on <evt>(<args>) { <raw js> } ... }` — websocket handlers, lowered to a `websocket` export.

`view` markup is parsed by a lenient dedicated HTML parser (`parseHtmlView`); HTML void elements (`<br>`, `<img>`, …) take no closing tag. Line comments (`//`) are skipped by the lexer.

## Requirements / Notes

- Pure TypeScript with no runtime dependencies; runs under **Bun** as part of the WrNexus toolchain (Node is not supported).
- Generated modules target WrNexus runtime primitives (`data-scope`, `data-text`, `data-on-*`, `data-for`, `data-component`, `__wrnexus*`/`__wire*` helpers) — consume the output within a WrNexus app, e.g. via `@wrnexus/core`'s dev loader.

### Exported TypeScript declarations

```ts
import { PageAst as PageAst$1, WrnDiagnostic } from '@wrnexus/syntax';
export { ActionBlock, ApiBlock, Attr, ComputedDecl, DataApiBlock, DataMode, EffectBlock, EventDecl, LexError, Lexer, LoadBlock, ModeFunctionsBlock, PageAst, ParseError, PropDecl, RealtimeBlock, SeoBlock, StateDecl, ViewNode, WrnDiagnostic, assertValidAst, diagnose, diagnosticFromError, eraseFunctionTypes, formatDiagnostic, inferredRuntimeType, parse, runtimeTypeOf } from '@wrnexus/syntax';
import { PageAst } from '@wrnexus/syntax/parser';

/**
 * Code generation: lower a `.wrn` AST to TypeScript that targets the framework's
 * existing primitives.
 *
 *   state              -> a `data-scope` declaration consumed by the runtime
 *   view               -> an HTML string returned by a page component
 *   @event="..."       -> data-on-<event>="..."
 *   "...{expr}..."     -> text kept verbatim ({expr} is mustache for runtime)
 *   api="<name>"       -> SSR/client data binding declared in a mode block
 *   ssrGet/ssrText     -> legacy server-side API fetch + render
 *   csrGet/csrText     -> legacy browser-side API fetch + render
 *   style              -> an inline page stylesheet
 *   functions          -> server-only helpers for API/realtime code
 *   api M /p {b}       -> export const M = async (ctx) => { b }
 *   realtime {..}      -> export const websocket = { evt(ws, ...args) { b } }
 */

declare function generate(ast: PageAst): string;

declare class NativeCompileError extends Error {
    constructor(message: string);
}
/** Compile a parsed `.wrn` page to an Expo Router React Native screen. */
declare function generateNative(ast: PageAst): string;

interface CompilationCacheEntry extends CompileResult {
    key: string;
    file: string;
    sourceHash: string;
    createdAt: number;
}
interface CompilationCacheOptions {
    maxEntries?: number;
    now?: () => number;
}
interface CompilationCache {
    compile(source: string, file?: string, salt?: string): CompilationCacheEntry;
    get(key: string): CompilationCacheEntry | undefined;
    invalidate(file?: string): number;
    clear(): void;
    size(): number;
    stats(): {
        hits: number;
        misses: number;
        entries: number;
    };
}
declare function compilationKey(source: string, file?: string, salt?: string): string;
declare function createCompilationCache(options?: CompilationCacheOptions): CompilationCache;
declare class DependencyGraph {
    #private;
    set(file: string, dependencies: Iterable<string>): void;
    remove(file: string): void;
    dependencies(file: string): string[];
    dependents(file: string): string[];
    affected(file: string): string[];
}

/**
 * @wrnexus/compiler — the `.wrn` language compiler.
 *
 * Parsing and language diagnostics are provided by the canonical
 * `@wrnexus/syntax` package. This package owns platform-specific codegen.
 */

interface CompileResult {
    code: string;
    ast: PageAst$1;
    /** Backward-compatible plain diagnostic messages. */
    diagnostics: string[];
    /** Structured diagnostics for editors, CI, and the DevToolbar. */
    richDiagnostics: WrnDiagnostic[];
}
/** Compile `.wrn` source into an Expo Router React Native screen. */
declare function compileNativeWireFile(source: string): string;
/**
 * Compile `.wrn` source into TypeScript source. Errors include a stable code,
 * source location, code frame, and actionable hint whenever available.
 */
declare function compileWireFile(source: string, filePath?: string): string;
/** Richer entry point returning the AST and structured diagnostics. */
declare function compile(source: string, filePath?: string): CompileResult;

export { type CompilationCache, type CompilationCacheEntry, type CompilationCacheOptions, type CompileResult, DependencyGraph, NativeCompileError, compilationKey, compile, compileNativeWireFile, compileWireFile, createCompilationCache, generate, generateNative };
```

---

## @wrnexus/core

Documentation URL: https://wrnexusjs.dev/packages/core

# @wrnexus/core

> The framework core: the request `Context`, middleware contract, and the security, session, caching, streaming, realtime, and JSX primitives every other WrNexus package builds on.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

`@wrnexus/core` is the shared foundation of WrNexus. It defines the `Context`
object that flows through every middleware, page, and API route, plus the
`Middleware`/`Next` contract they implement. On top of that it ships the
building blocks a real app needs: cookie-backed sessions, password auth, CSRF
protection, rate limiting, request logging, HTTP + in-memory caching, file
uploads, streaming/SSE responses, WebSocket "rooms", security headers/CORS, and
a server-side JSX runtime that renders to HTML strings. Everything here is
**server-side** and Bun-native (it uses `Bun.password`, `Bun.write`, the
web-standard `Request`/`Response`, and `crypto`). You depend on it directly and
transitively through the rest of the framework.

## Installation

```bash
bun add @wrnexus/core
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported).

## API

### Context & middleware — `@wrnexus/core`

The `Context` (`ctx`) is the single value passed to middleware and handlers.

| Export                         | Kind | Description                                                                                                              |
| ------------------------------ | ---- | ------------------------------------------------------------------------------------------------------------------------ |
| `Context`                      | type | Per-request object: `req`, `url`, `lang`, `t`, `params`, `locals`, `user?`, `ip?`, `cookies`, `session`, `localStorage`. |
| `Next`                         | type | `() => Promise<Response> \| Response` — invokes the next middleware/handler.                                             |
| `Middleware`                   | type | `(ctx, next) => Promise<Response> \| Response`. Return `next()` to continue, or a `Response` to short-circuit.           |
| `createContext(req, url)`      | fn   | Build a fresh `Context` for an incoming request (wires up cookies, session, localStorage snapshot).                      |
| `withContextHeaders(ctx, res)` | fn   | Apply accumulated headers (e.g. `Set-Cookie`) from the context onto a response.                                          |
| `PageComponent`                | type | `(ctx) => string \| Promise<string>` — a page module's default export.                                                   |
| `PageMeta` / `SeoConfig`       | type | `<head>` metadata: `title`, `description`, `canonical`, `robots`, `image`, `twitterCard`, `themeColor`, …                |
| `TFunction`                    | type | `(key, params?) => string` — translate a key for `ctx.lang`, interpolating `{param}` placeholders.                       |

Key `Context` fields:

- `ctx.locals` — per-request scratch space for passing values between middleware.
- `ctx.user` — the authenticated user (populated by `sessionAuth`/`logIn`), or `null`.
- `ctx.ip` — the direct socket peer IP (not spoofable via headers).
- `ctx.cookies` / `ctx.session` / `ctx.localStorage` — see **Storage** below.

### Authentication — `@wrnexus/core`

Passwords are hashed with argon2id via `Bun.password`; sessions ride the
cookie-backed `SessionStore`.

| Export                           | Signature                              | Notes                                                                                                                 |
| -------------------------------- | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `hashPassword(password)`         | `(string) => Promise<string>`          | argon2id hash to store.                                                                                               |
| `verifyPassword(password, hash)` | `(string, string) => Promise<boolean>` | Constant-safe; returns `false` on bad/empty hash.                                                                     |
| `logIn(ctx, user)`               | `(Context, U) => void`                 | Regenerates the session id (fixation defense), stores the user, sets `ctx.user`.                                      |
| `logOut(ctx)`                    | `(Context) => void`                    | Clears the session and `ctx.user`.                                                                                    |
| `getUser(ctx)`                   | `(Context) => U \| null`               | Current user from `ctx.user`, falling back to the session.                                                            |
| `sessionAuth()`                  | `() => Middleware`                     | Hydrates `ctx.user` from the session each request. Register early.                                                    |
| `requireAuth(options?)`          | `(RequireAuthOptions?) => Middleware`  | Guard: API/fetch requests get `401 JSON`, page navigations get `302` to `loginPath` (default `/login`) with `?next=`. |
| `SESSION_USER_KEY`               | `"user"`                               | Session key holding the user.                                                                                         |

`RequireAuthOptions`: `{ loginPath?: string }`.

### CSRF — `@wrnexus/core`

Double-submit cookie pattern: a readable `wire-csrf` cookie is echoed in an
`x-csrf-token` header on unsafe requests.

| Export                        | Signature                        | Notes                                                                                                            |
| ----------------------------- | -------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `csrfToken(ctx)`              | `(Context) => string`            | Ensures the CSRF cookie exists and returns its token.                                                            |
| `verifyCsrf(ctx)`             | `(Context) => boolean`           | Safe methods (GET/HEAD/OPTIONS) pass; otherwise header/`ctx.locals._csrf` must match the cookie (constant-time). |
| `csrfProtection()`            | `() => Middleware`               | 403s unsafe requests with a missing/mismatched token.                                                            |
| `CSRF_COOKIE` / `CSRF_HEADER` | `"wire-csrf"` / `"x-csrf-token"` | Cookie & header names.                                                                                           |

### Rate limiting — `@wrnexus/core`

Fixed-window limiter that returns `429` with `Retry-After` and emits
`RateLimit-Limit`/`-Remaining`/`-Reset` headers.

| Export                | Signature                           | Notes                                                                  |
| --------------------- | ----------------------------------- | ---------------------------------------------------------------------- |
| `rateLimit(options?)` | `(RateLimitOptions?) => Middleware` | Main middleware.                                                       |
| `peerKey(ctx)`        | `(Context) => string`               | Non-spoofable key from `ctx.ip` (default).                             |
| `proxyKey(ctx)`       | `(Context) => string`               | Trusts `x-forwarded-for`/`x-real-ip`. Use only behind a trusted proxy. |
| `defaultKey`          | —                                   | **Deprecated** alias of `proxyKey`.                                    |

`RateLimitOptions`: `windowMs` (default `60_000`), `max` (default `60`),
`key`, `trustProxy` (default `false` → keys on `peerKey`; `true` → `proxyKey`),
`message`, `headers` (default `true`), `store`.

`RateLimitStore` is pluggable — implement `hit(key, windowMs, now) => Bucket | Promise<Bucket>`
(a `Bucket` is `{ count, resetAt }`) to back limits with Redis/SQL across
instances. The default store is process-local memory.

### Request logging — `@wrnexus/core`

| Export                    | Signature                               | Notes                                                                            |
| ------------------------- | --------------------------------------- | -------------------------------------------------------------------------------- |
| `requestLogger(options?)` | `(RequestLoggerOptions?) => Middleware` | One record per request with a request id (stored on `ctx.locals[requestIdKey]`). |

`RequestLoggerOptions`: `format` (`"pretty"` default \| `"json"`), `sink(line, record)`
(default `console.log`), `requestIdKey` (default `"requestId"`), `now`.
`RequestRecord` = `{ time, id, method, path, status, durationMs }`.

### Caching — `@wrnexus/core`

| Export                           | Kind  | Notes                                                                                                                                      |
| -------------------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `TTLCache<V>`                    | class | In-memory TTL cache: `get`, `set`, `getOrLoad(key, loader, ttlMs?)`, `delete`, `clear`, `size`. Constructor takes a default `ttlMs` (60s). |
| `cacheControl(options)`          | fn    | Build a `Cache-Control` value from `CacheControlOptions`.                                                                                  |
| `withCacheControl(res, options)` | fn    | Apply `Cache-Control` to a response.                                                                                                       |
| `etag(body, weak?)`              | fn    | Stable quoted FNV-1a ETag (weak by default).                                                                                               |
| `notModified(req, tag)`          | fn    | `true` when `If-None-Match` matches — send a `304`.                                                                                        |

`CacheControlOptions`: `maxAge`, `sMaxAge`, `private`, `noStore`, `noCache`,
`staleWhileRevalidate`, `immutable`.

### File uploads — `@wrnexus/core`

Bun parses `multipart/form-data` via `Request.formData()`; these helpers
validate and persist the resulting `File`s.

| Export                      | Signature                                           | Notes                                                                                  |
| --------------------------- | --------------------------------------------------- | -------------------------------------------------------------------------------------- |
| `collectUploads(form)`      | `(FormData) => { field, file }[]`                   | Every non-empty `File` in a parsed form.                                               |
| `saveUpload(file, options)` | `(File, SaveUploadOptions) => Promise<SavedUpload>` | Validates size/type, sanitizes the name, writes via `Bun.write`. Throws `UploadError`. |
| `sanitizeFilename(name)`    | `(string) => string`                                | Strips separators, traversal, control/illegal chars; caps at 255.                      |
| `UploadError`               | class                                               | Thrown on rejected uploads.                                                            |

`SaveUploadOptions`: `dir` (required), `maxBytes`, `allowedTypes` (MIME types
like `"image/png"` and/or extensions like `".png"`), `filename(file)`.
`SavedUpload` = `{ path, filename, size, type }`.

### Streaming & SSE — `@wrnexus/core`

| Export                          | Signature                                                                        | Notes                                                               |
| ------------------------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
| `streamResponse(source, init?)` | `(Iterable\|AsyncIterable<string\|Uint8Array>, StreamResponseInit?) => Response` | Streaming `Response` from a chunk source (basis for streaming SSR). |
| `sse(source)`                   | `(Iterable\|AsyncIterable<ServerSentEvent>) => Response`                         | `text/event-stream` response.                                       |

`StreamResponseInit`: `status`, `headers`, `contentType` (default
`"text/html; charset=utf-8"`). `ServerSentEvent`: `{ data, event?, id?, retry? }`.

### Realtime rooms — `@wrnexus/core`

WebSocket rooms. A file in `app/realtime/` exports
`default defineRoom({ ... })` and is served at `ws://host/realtime/<name>`.

| Export                                  | Signature                                                | Notes                                                                |
| --------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------------------- |
| `defineRoom(handlers)`                  | `(RoomHandlers) => RoomDefinition`                       | Define a room. Export the result as `default`.                       |
| `isRoomDefinition(value)`               | `(unknown) => boolean`                                   | Type guard for a room definition.                                    |
| `createRealtimeRegistry()`              | `() => RealtimeRegistry`                                 | Server-side connection manager mapping sockets ↔ rooms.              |
| `bridgeRealtime(registry, bus, topic?)` | `(RealtimeRegistry, RealtimeBus, string?) => () => void` | Bridge broadcasts/`toUser` sends across processes via a pub/sub bus. |

`RoomHandlers`: `authorize(info) => boolean` (gate before accept — return
`false` to reject with 403), `onConnect(client)`, `onMessage(client, message)`
(JSON auto-parsed), `onLeave(client)`. A handler receives a `RoomClient` with
`id`, `user`, `query`, `data`, `room`, and `send` / `broadcast` /
`to(id)` / `toUser(user)` / `close`. The `Room` API adds `state`, `clients()`,
`count()`, and `broadcast`. `RealtimeBus` is structurally satisfied by
`@wrnexus/pubsub`. Legacy `RealtimeHandler`/`RealtimeSocket` raw handlers are
still exported. Connection-targeted sends (`send`, `to(id)`) stay local; room
broadcasts and `toUser` cross the bridge.

### Error pages — `@wrnexus/core`

| Export                         | Signature                        | Notes                                                 |
| ------------------------------ | -------------------------------- | ----------------------------------------------------- |
| `renderError(err, mode)`       | `(unknown, Mode) => Response`    | Dev page (with stack) or generic prod page by `mode`. |
| `renderDevError(err, status?)` | `(unknown, number?) => Response` | Readable HTML error page including the stack trace.   |
| `renderProdError(status?)`     | `(number?) => Response`          | Generic page that never leaks file paths.             |
| `renderNotFound()`             | `() => Response`                 | Simple 404 page.                                      |

`Mode` = `"development" | "production"`.

### Security headers & CORS — `@wrnexus/core`

| Export                                                   | Signature            | Notes                                                                                                                                                    |
| -------------------------------------------------------- | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `withSecurityHeaders(req, res, mode, security?, nonce?)` | → `Response`         | Applies CORS + CSP, HSTS, `X-Frame-Options`, `X-Content-Type-Options`, `Referrer-Policy`, `Permissions-Policy`, COOP, Trusted Types, and `extraHeaders`. |
| `createCorsPreflightResponse(req, security?)`            | → `Response \| null` | Builds a `204`/`403` preflight response for CORS `OPTIONS` requests.                                                                                     |
| `isWebSocketOriginAllowed(req, security?)`               | → `boolean`          | Guards WS upgrades against cross-site hijacking (allows same-origin, configured CORS origins, and non-browser clients).                                  |

Config types: `SecurityConfig` (top-level), `CorsConfig`/`CorsOrigin`,
`ContentSecurityPolicyConfig`/`CspDirectiveValue`, `HstsConfig`,
`TrustedTypesConfig`, `PermissionsPolicyConfig`. WrNexus applies sensible
defaults (self-only CSP, `frame-ancestors 'none'`, restrictive Permissions-Policy,
HSTS in production, Trusted Types in production); each is individually
overridable or disable-able via `false`.

### Storage: cookies, sessions, localStorage — `@wrnexus/core`

These back the `ctx.cookies`, `ctx.session`, and `ctx.localStorage` fields.

| Export                                                    | Kind              | Notes                                                                                                                                                             |
| --------------------------------------------------------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `setSessionBackend(backend)`                              | fn                | Swap the **sync** session persistence backend (`SessionBackend`) — e.g. `bun:sqlite`. Default is process-local memory. Call once at startup.                      |
| `loadSession(backend, options?)`                          | fn → `Middleware` | Back `ctx.session` with an **async** store (`AsyncSessionBackend`: `load`/`save`/`destroy`) — loads before the request, saves after. `options.ttlMs` default 24h. |
| `CookieStore`                                             | type              | `get`/`getAll`/`has`/`set(name, value, opts?)`/`delete`/`headers`.                                                                                                |
| `SessionStore`                                            | type              | `id`/`get`/`getAll`/`set`/`delete`/`regenerate`/`clear`.                                                                                                          |
| `LocalStorageSnapshot`                                    | type              | Read-only view of the browser's localStorage sent via header for CSR bindings.                                                                                    |
| `CookieOptions`                                           | type              | `path`, `domain`, `maxAge`, `expires`, `httpOnly`, `secure`, `sameSite`.                                                                                          |
| `SessionEntry` / `SessionBackend` / `AsyncSessionBackend` | types             | Session persistence contracts.                                                                                                                                    |

### Low-level security helpers — `@wrnexus/core`

| Export                        | Signature             | Notes                                               |
| ----------------------------- | --------------------- | --------------------------------------------------- |
| `escapeHtml(value)`           | `(string) => string`  | Escape for HTML text/attributes.                    |
| `isSafeIslandName(name)`      | `(string) => boolean` | Allow only a conservative `[A-Za-z0-9_-]+` charset. |
| `isSafeRequestPath(pathname)` | `(string) => boolean` | Reject NULs, `..` traversal, and backslashes.       |

### JSX runtime — `@wrnexus/core`, `@wrnexus/core/jsx-runtime`, `@wrnexus/core/jsx-dev-runtime`

A server-side JSX runtime that renders to HTML **strings** (no virtual DOM).
Point `tsconfig`'s `jsxImportSource` at `@wrnexus/core`.

| Export                                     | Kind   | Notes                                                                                   |
| ------------------------------------------ | ------ | --------------------------------------------------------------------------------------- |
| `jsx` / `jsxs`                             | fn     | The runtime factory (TypeScript calls these automatically). Returns an `Html` instance. |
| `Fragment`                                 | symbol | JSX fragment marker.                                                                    |
| `Html`                                     | class  | Wraps a raw, already-safe HTML string (`toString()` returns it).                        |
| `mustache(expr)`                           | fn     | Emit a `{{expr}}` placeholder (tagged-template or string form) for the client binder.   |
| `JSXComponent` / `JSXProps` / `Renderable` | types  | Component signature and renderable value types.                                         |

Values interpolated as children are HTML-escaped unless they are an `Html`
instance; use `dangerouslySetInnerHTML={{ __html }}` for trusted markup. Void
elements render without a closing tag; `className`→`class`, `htmlFor`→`for`, and
`style` objects are serialized to CSS text.

The subpath exports map to the runtime TypeScript's JSX transform expects:

```jsonc
// tsconfig.json
{
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "@wrnexus/core",
  },
}
```

## Usage

### A minimal middleware chain

```ts
import {
  createContext,
  withContextHeaders,
  sessionAuth,
  requireAuth,
  requestLogger,
  rateLimit,
  csrfProtection,
  type Middleware,
} from "@wrnexus/core";

const chain: Middleware[] = [
  requestLogger({ format: "json" }),
  rateLimit({ max: 100, windowMs: 60_000 }),
  csrfProtection(),
  sessionAuth(),
  requireAuth({ loginPath: "/login" }),
];
```

### Password auth

```ts
import { hashPassword, verifyPassword, logIn, getUser } from "@wrnexus/core";

// Registration
const passwordHash = await hashPassword(form.password);

// Login
if (await verifyPassword(form.password, user.passwordHash)) {
  logIn(ctx, { id: user.id, email: user.email });
}

const current = getUser<{ id: string }>(ctx); // or null
```

### HTTP caching with ETags

```ts
import { etag, notModified, withCacheControl } from "@wrnexus/core";

const body = JSON.stringify(data);
const tag = etag(body);
if (notModified(ctx.req, tag)) {
  return new Response(null, { status: 304, headers: { ETag: tag } });
}
const res = new Response(body, { headers: { ETag: tag, "content-type": "application/json" } });
return withCacheControl(res, { maxAge: 60, staleWhileRevalidate: 300 });
```

### Streaming SSE

```ts
import { sse } from "@wrnexus/core";

async function* ticks() {
  for (let n = 0; ; n++) {
    yield { event: "tick", data: String(n) };
    await Bun.sleep(1000);
  }
}
export default (ctx) => sse(ticks());
```

### A realtime room

```ts
// app/realtime/chat.ts
import { defineRoom } from "@wrnexus/core";

export default defineRoom({
  authorize: (info) => !!info.user, // require auth
  onConnect(client) {
    client.user = client.query.user;
    client.room.broadcast({ type: "join", id: client.id });
  },
  onMessage(client, msg) {
    client.broadcast({ type: "say", from: client.id, text: msg.text });
  },
});
```

Scale it across processes:

```ts
import { createRealtimeRegistry, bridgeRealtime } from "@wrnexus/core";
import { createPubSub } from "@wrnexus/pubsub";
import { redisDriver } from "@wrnexus/pubsub/redis";

const registry = createRealtimeRegistry();
bridgeRealtime(registry, createPubSub(redisDriver(process.env.REDIS_URL)));
```

### JSX rendering

```tsx
import { Html } from "@wrnexus/core";

function Card({ title, body }: { title: string; body: string }) {
  return (
    <article class="card">
      <h2>{title}</h2>
      <p>{body}</p>
    </article>
  );
}

const html: Html = <Card title="Hi" body="<b>escaped</b> automatically" />;
return new Response(html.toString(), { headers: { "content-type": "text/html" } });
```

## Requirements / Notes

- **Bun-only.** Uses `Bun.password` (argon2id), `Bun.write`, web-standard
  `Request`/`Response`/`FormData`/`ReadableStream`, and the global `crypto`.
  Node is not supported.
- Session and rate-limit backends default to **process-local memory**. For
  multi-instance deployments, swap in a shared backend: `setSessionBackend` (sync,
  e.g. `bun:sqlite`) or `loadSession` (async, e.g. Redis) for sessions, a custom
  `RateLimitStore` for limits, and `bridgeRealtime` for realtime.
- Works with the rest of the framework: realtime bridging is structurally
  compatible with [`@wrnexus/pubsub`](../pubsub); the security, auth, and JSX
  primitives here are consumed by the WrNexus server/router packages.
- Subpath exports: `@wrnexus/core/jsx-runtime` and `@wrnexus/core/jsx-dev-runtime`
  for TypeScript's automatic JSX transform.

### Exported TypeScript declarations

```ts
export { Fragment, Html, Component as JSXComponent, Props as JSXProps, Renderable, jsx, jsxs, mustache } from './jsx-runtime.js';

interface Tenant {
    id: string;
    slug?: string;
    name?: string;
    metadata?: Record<string, unknown>;
}
type TenantResolver = (ctx: Context) => Tenant | null | Promise<Tenant | null>;
interface TenantMiddlewareOptions {
    required?: boolean;
    status?: number;
}
declare function tenantMiddleware(resolveTenant: TenantResolver, options?: TenantMiddlewareOptions): Middleware;
declare function tenantFromSubdomain(lookup: (slug: string, ctx: Context) => Tenant | null | Promise<Tenant | null>, rootDomains?: string[]): TenantResolver;
declare function requireTenant(ctx: Context): Tenant;
/** Wrap a repository so every operation receives the current tenant id. */
declare function tenantScope<T extends object>(tenant: Tenant, repository: T): T & {
    tenantId: string;
};

interface SpanRecord {
    name: string;
    startTime: number;
    endTime?: number;
    durationMs?: number;
    status?: "ok" | "error";
    attributes: Record<string, string | number | boolean>;
    error?: unknown;
}
interface Tracer {
    startSpan(name: string, attributes?: SpanRecord["attributes"]): Span;
    records(): readonly SpanRecord[];
}
interface Span {
    setAttribute(name: string, value: string | number | boolean): void;
    end(status?: "ok" | "error", error?: unknown): SpanRecord;
}
declare function createTracer(clock?: () => number): Tracer;
declare function withSpan<T>(tracer: Tracer, name: string, run: (span: Span) => T | Promise<T>, attributes?: SpanRecord["attributes"]): Promise<T>;
interface TracingMiddlewareOptions {
    /** Include W3C Server-Timing response headers. Defaults to true. */
    serverTiming?: boolean;
    /** Fraction of requests to trace, from 0 to 1. Defaults to 1. */
    sampleRate?: number;
    /** Called after a traced response completes. */
    onComplete?: (ctx: Context, records: readonly SpanRecord[]) => void | Promise<void>;
}
declare function tracingMiddleware(tracerFactory?: (ctx: Context) => Tracer, options?: TracingMiddlewareOptions): Middleware;

interface CookieOptions {
    path?: string;
    domain?: string;
    maxAge?: number;
    expires?: Date | string;
    httpOnly?: boolean;
    secure?: boolean;
    sameSite?: "Strict" | "Lax" | "None" | "strict" | "lax" | "none";
}
interface CookieStore {
    get(name: string): string | undefined;
    getAll(): Record<string, string>;
    has(name: string): boolean;
    set(name: string, value: string, options?: CookieOptions): void;
    delete(name: string, options?: CookieOptions): void;
    headers(): string[];
}
interface SessionStore {
    id(): string;
    get<T = unknown>(key: string): T | undefined;
    getAll(): Record<string, unknown>;
    set(key: string, value: unknown): void;
    delete(key: string): void;
    /** Issue a fresh session id, keeping the data — defends against fixation. */
    regenerate(): void;
    clear(): void;
}
interface LocalStorageSnapshot {
    get(key: string): string | undefined;
    getAll(): Record<string, string>;
    has(key: string): boolean;
}
/** A stored session: its data plus an absolute expiry timestamp (ms). */
interface SessionEntry {
    data: Record<string, unknown>;
    expiresAt: number;
}
/**
 * Pluggable session persistence. The default is process-local memory; swap in a
 * shared backend (Redis, SQL, etc.) via `setSessionBackend` so sessions survive
 * restarts and work across multiple instances. Methods are synchronous, so a
 * backend must be sync (e.g. `bun:sqlite`); async stores need a load/save
 * wrapper around the request (future work).
 */
interface SessionBackend {
    get(id: string): SessionEntry | undefined;
    set(id: string, entry: SessionEntry): void;
    delete(id: string): void;
    /** Optional: drop expired entries. Called periodically by the store. */
    gc?(now: number): void;
}
/** Replace the session persistence backend (call once at startup). */
declare function setSessionBackend(backend: SessionBackend): void;
/**
 * An ASYNC session store (Redis, a remote DB). Use it via the `loadSession`
 * middleware, which loads the session before the request and saves it after —
 * keeping the `ctx.session` API synchronous while persistence is shared across
 * instances.
 */
interface AsyncSessionBackend {
    load(id: string): Promise<SessionEntry | undefined>;
    save(id: string, entry: SessionEntry): Promise<void>;
    destroy(id: string): Promise<void>;
}
/**
 * Back `ctx.session` with an async store. Register early (before anything reads
 * `ctx.session`). Loads once at the start of the request and saves once at the
 * end; regenerate/clear destroy the old id.
 */
declare function loadSession(backend: AsyncSessionBackend, options?: {
    ttlMs?: number;
}): Middleware;

/**
 * Core request context and middleware contracts.
 *
 * The `Context` object is the single value that flows through middleware,
 * pages and API routes. It is intentionally small and framework-agnostic so
 * it can later be reused by the `.wrn` compiler output.
 */

/** Translate a key for the active language, interpolating `{param}` placeholders. */
type TFunction = (key: string, params?: Record<string, string | number>) => string;
type Context = {
    /** The raw incoming web-standard Request. */
    req: Request;
    /** Parsed URL of the request (pathname, query, etc.). */
    url: URL;
    /** Active language for this request (resolved by the runtime); "" if i18n is unused. */
    lang: string;
    /** Translate a key for the active language (identity until the runtime sets it). */
    t: TFunction;
    /** Dynamic route params, e.g. `/users/[id]` -> `{ id: "42" }`. */
    params: Record<string, string>;
    /**
     * Per-request scratch space. Middleware can attach values here
     * (e.g. the authenticated user) and downstream handlers can read them.
     */
    locals: Record<string, unknown>;
    /**
     * The authenticated user for this request, or null when anonymous. Populated
     * by the `sessionAuth` middleware (or `logIn`); read via `getUser(ctx)`.
     */
    user?: unknown;
    /** Active tenant/workspace resolved by tenant middleware. */
    tenant?: Tenant;
    /** Request tracer installed by observability middleware. */
    tracer?: Tracer;
    /**
     * The direct socket peer IP, set by the server from `server.requestIP`. This
     * is NOT spoofable by request headers — prefer it over `x-forwarded-for` for
     * rate limiting unless you run behind a trusted proxy.
     */
    ip?: string;
    /** Read/write HTTP cookies for the current response. */
    cookies: CookieStore;
    /** In-memory cookie-backed session store. */
    session: SessionStore;
    /** Read-only localStorage snapshot sent by the browser for CSR data bindings. */
    localStorage: LocalStorageSnapshot;
};
/** Calls the next middleware in the chain (or the final route handler). */
type Next = () => Promise<Response> | Response;
/**
 * Middleware runs before pages and API routes. It can:
 *  - inspect/modify `ctx`
 *  - short-circuit by returning a `Response` without calling `next()`
 *  - continue by returning `await next()`
 */
type Middleware = (ctx: Context, next: Next) => Promise<Response> | Response;
/** SEO metadata rendered into the document `<head>`. */
type SeoConfig = {
    /** BCP 47 document language used on `<html lang>` (default: `en`). */
    lang?: string;
    title?: string;
    titleTemplate?: string;
    description?: string;
    canonical?: string;
    canonicalBase?: string;
    robots?: string;
    keywords?: string | string[];
    image?: string;
    siteName?: string;
    type?: string;
    locale?: string;
    twitterCard?: string;
    twitterSite?: string;
    themeColor?: string;
};
/** Page metadata rendered into the document `<head>`. */
type PageMeta = SeoConfig;
/** A page module's default export. Returns an HTML string for the body. */
type PageComponent = (ctx: Context) => string | Promise<string>;
/** Create a fresh context for an incoming request. */
declare function createContext(req: Request, url: URL): Context;
/** Apply headers accumulated on the context, such as Set-Cookie. */
declare function withContextHeaders(ctx: Context, res: Response): Response;

/**
 * Small, dependency-free security helpers shared across packages.
 */
/**
 * Escape a string for safe interpolation into HTML text or attributes.
 * Used for page metadata (title/description) so untrusted values can't
 * break out of an attribute or inject markup.
 */
declare function escapeHtml(value: string): string;
declare function isSafeIslandName(name: string): boolean;
/**
 * Reject obvious path-traversal in a request path before it is ever used to
 * resolve a file. The router never builds file paths from request input
 * (routes are resolved against a pre-scanned table), but this is a cheap
 * defense-in-depth guard.
 */
declare function isSafeRequestPath(pathname: string): boolean;

/**
 * CSRF protection via the double-submit cookie pattern.
 *
 * The framework sets a readable `wire-csrf` cookie on page loads; the client
 * echoes it in an `x-csrf-token` header on unsafe requests (the Wire UI form
 * runtime does this automatically). The server checks header === cookie. A
 * cross-site attacker can't read the cookie to forge the header, so the request
 * is rejected — while same-origin requests pass.
 */

declare const CSRF_COOKIE = "wire-csrf";
declare const CSRF_HEADER = "x-csrf-token";
/** Ensure the CSRF cookie exists (readable by JS) and return its token. */
declare function csrfToken(ctx: Context): string;
/**
 * Verify an unsafe request's CSRF token against the cookie. Safe methods
 * (GET/HEAD/OPTIONS) always pass. The token may arrive in the `x-csrf-token`
 * header or a `_csrf` field already parsed onto `ctx.locals`.
 */
declare function verifyCsrf(ctx: Context): boolean;
/** Middleware that 403s unsafe requests with a missing/mismatched CSRF token. */
declare function csrfProtection(): Middleware;

/**
 * Authentication primitives.
 *
 * Passwords are hashed with argon2id via `Bun.password`. Sessions ride on the
 * existing cookie-backed `SessionStore`: logging a user in stores a serializable
 * user object under the "user" key, and `sessionAuth` hydrates `ctx.user` from
 * it on every request. `requireAuth` is a guard middleware for protected routes.
 */

/** Session key under which the authenticated user is stored. */
declare const SESSION_USER_KEY = "user";
/** Hash a plaintext password (argon2id). Store the returned string. */
declare function hashPassword(password: string): Promise<string>;
/** Verify a plaintext password against a stored hash. Safe against bad hashes. */
declare function verifyPassword(password: string, hash: string): Promise<boolean>;
/** Persist the authenticated user in the session and on the context. */
declare function logIn<U = unknown>(ctx: Context, user: U): void;
/** Clear the session and forget the current user. */
declare function logOut(ctx: Context): void;
/**
 * The currently-authenticated user, or null. Reads `ctx.user` first (set by
 * `sessionAuth`/`logIn`), falling back to the session store.
 */
declare function getUser<U = unknown>(ctx: Context): U | null;
/**
 * Hydrate `ctx.user` from the session for every request. Register this early in
 * the middleware chain so downstream pages and API routes can read `ctx.user`.
 */
declare function sessionAuth(): Middleware;
interface RequireAuthOptions {
    /** Where to redirect unauthenticated page requests. Default "/login". */
    loginPath?: string;
}
/**
 * Guard that requires an authenticated user. Unauthenticated requests that look
 * like an API/fetch call get a 401 JSON response; page navigations get a 302
 * redirect to the login page with the original target preserved as `?next=`.
 */
declare function requireAuth(options?: RequireAuthOptions): Middleware;

/**
 * Fixed-window rate limiting middleware. Keeps an in-memory counter per key
 * (client IP by default, read from `x-forwarded-for` / `x-real-ip`) and rejects
 * requests over the limit with a 429 and a `Retry-After` header. Sets the
 * `RateLimit-Limit` / `RateLimit-Remaining` / `RateLimit-Reset` headers.
 *
 * The store is process-local; behind multiple instances use a shared store
 * (out of scope here). Suitable as-is for single-process apps and dev.
 */

interface RateLimitOptions {
    /** Window length in milliseconds. Default 60_000 (1 minute). */
    windowMs?: number;
    /** Max requests allowed per key per window. Default 60. */
    max?: number;
    /** Derive the bucket key from the request. Default: client IP. */
    key?: (ctx: Context) => string;
    /**
     * Trust `x-forwarded-for` / `x-real-ip` for the client IP. Default false —
     * those headers are attacker-spoofable, so by default we key on the direct
     * socket peer (`ctx.ip`). Enable ONLY when behind a proxy that overwrites
     * these headers (nginx, a load balancer, Cloudflare).
     */
    trustProxy?: boolean;
    /** Body returned on 429. Default "Too Many Requests". */
    message?: string;
    /** Emit RateLimit-* headers. Default true. */
    headers?: boolean;
    /** Persistence for the counters. Default: process-local memory. */
    store?: RateLimitStore;
    /** Maximum in-memory keys before oldest buckets are evicted. Ignored for custom stores. */
    maxKeys?: number;
}
interface Bucket {
    count: number;
    resetAt: number;
}
/**
 * Pluggable rate-limit counter store. The default is process-local memory; swap
 * in a shared store (Redis/SQL) so limits hold across instances. `hit` records
 * one request for `key` in the current window and returns the running bucket.
 * It may be async (e.g. a Redis INCR + PEXPIRE) — the middleware awaits it.
 */
interface RateLimitStore {
    hit(key: string, windowMs: number, now: number): Bucket | Promise<Bucket>;
}
declare function rateLimit(options?: RateLimitOptions): Middleware;
/** Non-spoofable key: the direct socket peer IP (set by the server). */
declare function peerKey(ctx: Context): string;
/** Proxy-aware key: trusts `x-forwarded-for` / `x-real-ip`, else the peer IP. */
declare function proxyKey(ctx: Context): string;
/** @deprecated Use `peerKey` (default) or `proxyKey`. Kept for compatibility. */
declare const defaultKey: typeof proxyKey;

/**
 * Structured request logging middleware. Emits one record per request with a
 * request id, method, path, status, and duration — as pretty text (dev) or JSON
 * (production/log aggregation). The request id is stored on `ctx.locals` so
 * downstream handlers can correlate their own logs.
 */

interface RequestRecord {
    time: string;
    id: string;
    method: string;
    path: string;
    status: number;
    durationMs: number;
}
interface RequestLoggerOptions {
    /** "pretty" (default) for humans, "json" for machines. */
    format?: "pretty" | "json";
    /** Where each finished record goes. Default console.log. */
    sink?: (line: string, record: RequestRecord) => void;
    /** ctx.locals key for the request id. Default "requestId". */
    requestIdKey?: string;
    /** Clock injection for tests. Default Date.now. */
    now?: () => number;
}
declare function requestLogger(options?: RequestLoggerOptions): Middleware;

/**
 * Caching primitives:
 *  - `TTLCache` — a small in-memory time-to-live cache with `getOrLoad`, for
 *    memoising expensive data (query results, computed pages).
 *  - HTTP helpers — `cacheControl` to build a directive, `withCacheControl` to
 *    apply it, and `etag` / `notModified` for conditional requests (304s).
 */
declare class TTLCache<V = unknown> {
    private readonly ttlMs;
    private store;
    private loading;
    private revisions;
    private generation;
    constructor(ttlMs?: number);
    get(key: string): V | undefined;
    set(key: string, value: V, ttlMs?: number): void;
    /** Return the cached value or compute, cache, and return it. */
    getOrLoad(key: string, loader: () => Promise<V> | V, ttlMs?: number): Promise<V>;
    delete(key: string): void;
    clear(): void;
    get size(): number;
}
interface CacheControlOptions {
    /** max-age in seconds. */
    maxAge?: number;
    /** s-maxage (shared/CDN cache) in seconds. */
    sMaxAge?: number;
    /** Mark private (per-user) rather than public. */
    private?: boolean;
    /** no-store: never cache. Overrides other directives. */
    noStore?: boolean;
    /** no-cache: revalidate before use. */
    noCache?: boolean;
    /** stale-while-revalidate window in seconds. */
    staleWhileRevalidate?: number;
    immutable?: boolean;
}
/** Build a Cache-Control header value from options. */
declare function cacheControl(options: CacheControlOptions): string;
/** Apply a Cache-Control header to a response (returns the same response). */
declare function withCacheControl(res: Response, options: CacheControlOptions): Response;
/** A stable, quoted ETag for a string/bytes body (FNV-1a, weak by default). */
declare function etag(body: string | ArrayBuffer | Uint8Array, weak?: boolean): string;
/** True when the request's If-None-Match matches the given ETag (send a 304). */
declare function notModified(req: Request, tag: string): boolean;

/**
 * File upload helpers. Bun parses `multipart/form-data` natively via
 * `Request.formData()`, yielding web `File` objects; these helpers validate and
 * persist them safely (size/type limits, filename sanitisation to prevent path
 * traversal).
 */
declare class UploadError extends Error {
    constructor(message: string);
}
interface SaveUploadOptions {
    /** Destination directory. */
    dir: string;
    /** Reject files larger than this many bytes. */
    maxBytes?: number;
    /** Allowed MIME types (e.g. "image/png") and/or extensions (e.g. ".png"). */
    allowedTypes?: string[];
    /** Choose the stored filename. Default: the sanitised original name. */
    filename?: (file: File) => string;
}
interface SavedUpload {
    path: string;
    filename: string;
    size: number;
    type: string;
}
/** All `File` values in a parsed form, with their field names. */
declare function collectUploads(form: FormData): {
    field: string;
    file: File;
}[];
/** Validate and write one uploaded file to disk. Throws `UploadError` on reject. */
declare function saveUpload(file: File, options: SaveUploadOptions): Promise<SavedUpload>;
/** Strip directory separators, traversal, and control chars from a filename. */
declare function sanitizeFilename(name: string): string;

/**
 * Streaming response primitives.
 *
 * `streamResponse` turns a (sync or async) iterable of strings/bytes into a
 * streaming `Response` — the basis for streaming SSR (send the shell, then flush
 * page chunks as they render) and any progressively-generated output. `sse`
 * builds a Server-Sent Events stream from an async iterable of events.
 *
 * API routes and pages can already return a `Response` with a `ReadableStream`
 * body and the framework streams it unbuffered; these helpers just make the
 * common cases ergonomic.
 */
interface StreamResponseInit {
    status?: number;
    headers?: HeadersInit;
    /** Content-Type; default "text/html; charset=utf-8". */
    contentType?: string;
}
type Chunk = string | Uint8Array;
type ChunkSource = Iterable<Chunk> | AsyncIterable<Chunk>;
/** Build a streaming Response from an (async) iterable of chunks. */
declare function streamResponse(source: ChunkSource, init?: StreamResponseInit): Response;
interface ServerSentEvent {
    data: string;
    event?: string;
    id?: string;
    /** Client reconnection hint in milliseconds. */
    retry?: number;
}
/** Build a Server-Sent Events (text/event-stream) Response from events. */
declare function sse(source: Iterable<ServerSentEvent> | AsyncIterable<ServerSentEvent>): Response;

/**
 * Realtime rooms.
 *
 * A file in `app/realtime/` exports `default defineRoom({ onConnect, onMessage,
 * onLeave })` and is served at `ws://host/realtime/<name>`. The framework's
 * client runtime (`/__wrnexus/realtime.js`) handles the browser side, so pages
 * ship NO hand-written WebSocket code.
 *
 * Handlers get a `RoomClient` with everything you need:
 *   client.send(msg)                 → this connection
 *   client.broadcast(msg)            → everyone else in the room
 *   client.room.broadcast(msg)       → everyone (incl. sender)
 *   client.to(id | ids).send(msg)    → specific connection(s)
 *   client.toUser(u | users).send()  → a user / selected users (all their tabs)
 *   client.user = "u1"               → identify a connection for targeting
 *   client.data / client.room.state  → per-connection / shared room state
 *
 * The dynamic route `app/realtime/[room].ts` gives one handler many independent
 * rooms — `/realtime/lobby` and `/realtime/game-7` are separate room instances.
 */
interface RawSocket {
    send(data: string): unknown;
    close(code?: number, reason?: string): void;
}
interface RealtimeSocket<Data = unknown> {
    readonly data: Data;
    send(data: string | Uint8Array): number;
    subscribe(topic: string): void;
    unsubscribe(topic: string): void;
    publish(topic: string, data: string | Uint8Array): number;
    isSubscribed(topic: string): boolean;
    close(code?: number, reason?: string): void;
}
interface RealtimeHandler<Data = unknown> {
    open?(ws: RealtimeSocket<Data>): void | Promise<void>;
    message?(ws: RealtimeSocket<Data>, message: string | Uint8Array): void | Promise<void>;
    close?(ws: RealtimeSocket<Data>, code?: number, reason?: string): void | Promise<void>;
    drain?(ws: RealtimeSocket<Data>): void | Promise<void>;
}
interface Target {
    /** Send a message (objects are JSON-serialized). */
    send(message: unknown): void;
}
interface Room<TData = Record<string, unknown>> {
    readonly name: string;
    /** Shared, in-memory room state (lives while ≥1 client is connected). */
    readonly state: Record<string, unknown>;
    /** All connected clients. */
    clients(): RoomClient<TData>[];
    /** Number of connected clients. */
    count(): number;
    /** Send to everyone in the room, including the sender. */
    broadcast(message: unknown): void;
    /** Target specific connection id(s). */
    to(id: string | string[]): Target;
    /** Target a user / users by identity (reaches all their connections). */
    toUser(user: string | string[]): Target;
}
interface RoomClient<TData = Record<string, unknown>> {
    /** Unique per connection (a tab). */
    readonly id: string;
    /** App identity for targeting; assign it in `onConnect`. */
    user: string | undefined;
    /** Query params from the connection URL. */
    readonly query: Record<string, string>;
    /** Per-connection scratch state. */
    readonly data: TData;
    readonly room: Room<TData>;
    /** Send to THIS connection. */
    send(message: unknown): void;
    /** Send to everyone else in the room. */
    broadcast(message: unknown): void;
    /** Target specific connection id(s). */
    to(id: string | string[]): Target;
    /** Target a user / users by identity. */
    toUser(user: string | string[]): Target;
    /** Close this connection. */
    close(code?: number, reason?: string): void;
}
/** Info available when authorizing a connection, before it is accepted. */
interface RoomAuthInfo {
    /** Authenticated session user id, or `?user=` — undefined when anonymous. */
    user?: string;
    /** Connection URL query params. */
    query: Record<string, string>;
    /** The upgrade request's headers (cookies, etc.). */
    headers: Headers;
}
interface RoomHandlers<TData = Record<string, unknown>> {
    /**
     * Gate the connection BEFORE it is accepted. Return false to reject the
     * upgrade with 403 (e.g. `authorize: (info) => !!info.user` to require auth).
     */
    authorize?(info: RoomAuthInfo): boolean | Promise<boolean>;
    /** A client connected (a new tab joined the room). */
    onConnect?(client: RoomClient<TData>): void | Promise<void>;
    /** A message arrived (JSON is parsed; non-JSON arrives as a string). */
    onMessage?(client: RoomClient<TData>, message: any): void | Promise<void>;
    /** A client disconnected. */
    onLeave?(client: RoomClient<TData>): void | Promise<void>;
}
interface RoomDefinition<TData = Record<string, unknown>> {
    readonly __wrnexusRoom: true;
    readonly handlers: RoomHandlers<TData>;
}
/** Define a realtime room. Export the result as the `default` of a realtime file. */
declare function defineRoom<TData = Record<string, unknown>>(handlers: RoomHandlers<TData>): RoomDefinition<TData>;
declare function isRoomDefinition(value: unknown): value is RoomDefinition;
interface RealtimeConnectMeta {
    room: string;
    def: RoomDefinition;
    query?: Record<string, string>;
    user?: string;
}
/** One cross-instance message: a room broadcast, or a targeted user send. */
interface RealtimeEnvelope {
    room: string;
    /** If set, deliver only to these user identities; otherwise the whole room. */
    users?: string[];
    message: unknown;
}
/**
 * A pub/sub bridge for horizontal scaling. Wire the registry to a shared bus
 * (Redis pub/sub, NATS, …): local broadcasts/`toUser` sends are published to
 * peers, and messages received from peers are delivered via `registry.deliver`.
 * Connection-targeted sends (`send`, `to(id)`) stay local (ids are per-process).
 */
interface RealtimeBridge {
    publish(envelope: RealtimeEnvelope): void;
}
interface RealtimeRegistry {
    open(socket: RawSocket, meta: RealtimeConnectMeta): void | Promise<void>;
    message(socket: RawSocket, raw: string | Uint8Array): void | Promise<void>;
    close(socket: RawSocket): void | Promise<void>;
    /** Attach a cross-instance bridge (call once at startup). */
    setBridge(bridge: RealtimeBridge): void;
    /** Deliver an envelope received from a peer to LOCAL connections only. */
    deliver(envelope: RealtimeEnvelope): void;
    /** Number of live connections (across all rooms) — for tests/metrics. */
    size(): number;
}
/** Create the registry that maps sockets ↔ rooms and drives room handlers. */
declare function createRealtimeRegistry(): RealtimeRegistry;
/**
 * A minimal pub/sub bus (structurally satisfied by `@wrnexus/pubsub`). Used to
 * bridge realtime broadcasts across processes without a hard dependency.
 */
interface RealtimeBus {
    publish(topic: string, message: unknown): void | Promise<void>;
    subscribe(topic: string, handler: (message: unknown, topic: string) => void): () => void;
}
/**
 * Bridge a realtime registry across processes/instances via a pub/sub bus (use
 * the Redis driver so it crosses machines). After this, `client.room.broadcast`
 * and `client.toUser(...)` reach connected clients on **every** app process/
 * instance subscribed to the same bus — the foundation for realtime that works
 * with multiple running apps behind the gateway. Connection-targeted sends
 * (`send`, `to(id)`) stay local. Returns an unsubscribe function.
 *
 *   import { createRealtimeRegistry, bridgeRealtime } from "@wrnexus/core";
 *   import { createPubSub } from "@wrnexus/pubsub";
 *   import { redisDriver } from "@wrnexus/pubsub/redis";
 *   bridgeRealtime(registry, createPubSub(redisDriver(process.env.REDIS_URL)));
 */
declare function bridgeRealtime(registry: RealtimeRegistry, bus: RealtimeBus, topic?: string): () => void;

/**
 * Error + status pages. Every page here is a self-contained HTML document —
 * inline CSS only, no external stylesheet, no JavaScript (so it renders under the
 * strict CSP, even when the app's assets are what failed). Theme-aware via
 * `prefers-color-scheme`, styled in the WrNexus design language (ink-navy,
 * azure, a faint blueprint grid + glow). Development shows the stack trace;
 * production never leaks internal paths.
 */
type Mode = "development" | "production";
/** A beautiful, self-contained HTML page for any 4xx/5xx status. */
declare function renderStatusPage(status: number): Response;
/** Readable, styled development error page — includes the stack trace. */
declare function renderDevError(err: unknown, status?: number): Response;
/** Generic production error page — no stack, no file paths. */
declare function renderProdError(status?: number): Response;
/** Pick the right error page for the current mode. */
declare function renderError(err: unknown, mode: Mode): Response;
/** Beautiful 404 page. */
declare function renderNotFound(): Response;

type CorsOrigin = "*" | string | string[];
interface CorsConfig {
    /** Enable CORS headers and preflight handling. Defaults to false. */
    enabled?: boolean;
    /** Allowed origins. Use "*" for public APIs. Defaults to "*". */
    origin?: CorsOrigin;
    /** Allowed methods for preflight responses. */
    methods?: string[];
    /** Allowed request headers. Defaults to the browser's requested headers. */
    allowedHeaders?: string[];
    /** Response headers exposed to browser JavaScript. */
    exposedHeaders?: string[];
    /** Whether to send Access-Control-Allow-Credentials. */
    credentials?: boolean;
    /** Access-Control-Max-Age, in seconds. */
    maxAge?: number;
}
type CspDirectiveValue = string | string[] | false | null | undefined;
interface ContentSecurityPolicyConfig {
    /** Defaults to true. */
    enabled?: boolean;
    /** Use Content-Security-Policy-Report-Only instead of enforcing. */
    reportOnly?: boolean;
    /** Merge or remove directives. Set a directive to false/null to remove it. */
    directives?: Record<string, CspDirectiveValue>;
    /** Set false to start from an empty policy instead of WrNexus defaults. */
    useDefaults?: boolean;
}
interface HstsConfig {
    /** Defaults to true in production, false in development. */
    enabled?: boolean;
    /** Defaults to 31536000 seconds (1 year). */
    maxAge?: number;
    /** Defaults to true. */
    includeSubDomains?: boolean;
    /** Defaults to true. */
    preload?: boolean;
}
interface TrustedTypesConfig {
    /** Defaults to true in production, false in development. */
    enabled?: boolean;
    /**
     * Defaults to ["*"] in production so browser extensions and dev tooling can
     * create their own policies without noisy console errors. Set this to a
     * concrete list, e.g. ["wrnexus", "default"], for stricter deployments.
     */
    policyNames?: string[];
    /** Defaults to true. */
    requireForScript?: boolean;
    /** Adds "allow-duplicates" to the trusted-types directive. */
    allowDuplicates?: boolean;
}
type PermissionsPolicyConfig = Record<string, string | string[] | false | null | undefined>;
interface SecurityConfig {
    /** Set false to skip all framework security headers except explicitly enabled CORS. */
    headers?: boolean;
    /**
     * Trust `X-Forwarded-Proto` / `X-Forwarded-Host` when building `ctx.url` — set
     * this when the app runs behind a TLS-terminating reverse proxy (nginx, the
     * WrNexus gateway, a load balancer). Without it, a proxied app sees the internal
     * `http://` request and marks cookies (e.g. CSRF/session) non-`Secure`. Default
     * false; enable ONLY when a trusted proxy actually sets these headers.
     */
    trustProxy?: boolean;
    cors?: boolean | CorsConfig;
    contentSecurityPolicy?: false | ContentSecurityPolicyConfig;
    hsts?: false | HstsConfig;
    trustedTypes?: false | TrustedTypesConfig;
    /** Defaults to "same-origin". */
    crossOriginOpenerPolicy?: false | "same-origin" | "same-origin-allow-popups" | "unsafe-none";
    /** Defaults to "DENY". */
    frameOptions?: false | "DENY" | "SAMEORIGIN";
    /** Defaults to "strict-origin-when-cross-origin". */
    referrerPolicy?: false | string;
    /** Defaults to a restrictive browser capability policy. */
    permissionsPolicy?: false | PermissionsPolicyConfig;
    /** Extra static headers applied last. */
    extraHeaders?: Record<string, string>;
}
/**
 * Guard a WebSocket upgrade against Cross-Site WebSocket Hijacking: browsers
 * always send an `Origin` header on a WS handshake, and — unlike fetch — WS is
 * NOT subject to CORS, so cookies would otherwise flow cross-site. We allow
 * same-origin (Origin host === Host header), configured CORS origins, and
 * non-browser clients (no Origin, which also carry no ambient cookies).
 */
declare function isWebSocketOriginAllowed(req: Request, security?: SecurityConfig): boolean;
declare function createCorsPreflightResponse(req: Request, security?: SecurityConfig): Response | null;
/**
 * Build the request URL, honoring `X-Forwarded-Proto` / `X-Forwarded-Host` when
 * `trustProxy` is set (app behind a TLS-terminating reverse proxy). This makes
 * `ctx.url.protocol` reflect the EXTERNAL scheme, so protocol-dependent logic —
 * `Secure` cookies, canonical URLs — is correct behind nginx / the gateway.
 * Security checks that compare the raw `Host`/`Origin` headers don't use this URL,
 * so they are unaffected. An invalid forwarded value is ignored by the URL setter.
 */
declare function resolveRequestUrl(req: Request, trustProxy?: boolean): URL;
declare function withSecurityHeaders(req: Request, res: Response, mode: Mode, security?: SecurityConfig, nonce?: string): Response;

interface SchemaLike<T> {
    parse(input: unknown): T;
}
interface EndpointErrorBody {
    code: string;
    message: string;
    details?: unknown;
}
declare class EndpointError extends Error {
    readonly status: number;
    readonly code: string;
    readonly details?: unknown | undefined;
    constructor(status: number, code: string, message: string, details?: unknown | undefined);
}
interface EndpointDefinition<I, O> {
    input?: SchemaLike<I>;
    output?: SchemaLike<O>;
    auth?: "optional" | "required";
    description?: string;
    tags?: string[];
    handler(input: I, ctx: Context): O | Promise<O>;
}
interface DefinedEndpoint<I, O> {
    readonly definition: EndpointDefinition<I, O>;
    (ctx: Context, input?: unknown): Promise<Response>;
}
/** Define a validated, typed endpoint that can also drive SDK/OpenAPI generation. */
declare function defineEndpoint<I = unknown, O = unknown>(definition: EndpointDefinition<I, O>): DefinedEndpoint<I, O>;
interface RpcClientOptions {
    baseUrl?: string;
    fetch?: typeof globalThis.fetch;
    headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
}
/** Create a tiny typed RPC caller for endpoints exposed by a WrNexus app. */
declare function createRpcClient(options?: RpcClientOptions): <I, O>(path: string, input: I) => Promise<O>;

interface CachePolicy {
    ttlMs?: number;
    staleWhileRevalidateMs?: number;
    tags?: string[] | ((ctx: Context) => string[]);
}
interface LoaderDefinition<T> {
    cache?: CachePolicy;
    load(ctx: Context): T | Promise<T>;
}
interface ActionDefinition<I, O> {
    csrf?: boolean;
    run(input: I, ctx: Context): O | Promise<O>;
    invalidate?: string[] | ((output: O, ctx: Context) => string[]);
}
interface DefinedLoader<T> {
    readonly definition: LoaderDefinition<T>;
    (ctx: Context): Promise<T>;
}
interface DefinedAction<I, O> {
    readonly definition: ActionDefinition<I, O>;
    (input: I, ctx: Context): Promise<O>;
}
declare function defineLoader<T>(definition: LoaderDefinition<T>): DefinedLoader<T>;
declare function defineAction<I, O>(definition: ActionDefinition<I, O>): DefinedAction<I, O>;
/** Request-local fetch deduplication keyed by a stable string. */
declare function dedupe<T>(ctx: Context, key: string, load: () => T | Promise<T>): Promise<T>;

type FeatureValue = boolean | string | number;
type FeatureRule = FeatureValue | ((ctx: Context) => FeatureValue | Promise<FeatureValue>);
interface FeatureFlags {
    get(name: string, ctx: Context): Promise<FeatureValue | undefined>;
    enabled(name: string, ctx: Context): Promise<boolean>;
}
declare function defineFeatureFlags(rules: Record<string, FeatureRule>): FeatureFlags;

interface PerformanceBudgets {
    routeJsBytes?: number;
    routeCssBytes?: number;
    htmlBytes?: number;
    imageBytes?: number;
    hydrationMs?: number;
    serverRenderMs?: number;
}
interface PerformanceMeasurement {
    routeJsBytes?: number;
    routeCssBytes?: number;
    htmlBytes?: number;
    imageBytes?: number;
    hydrationMs?: number;
    serverRenderMs?: number;
}
interface BudgetViolation {
    metric: keyof PerformanceBudgets;
    budget: number;
    actual: number;
    overBy: number;
}
declare function checkPerformanceBudgets(budgets: PerformanceBudgets, measurement: PerformanceMeasurement): BudgetViolation[];

interface ProblemDetails {
    type: string;
    title: string;
    status: number;
    detail?: string;
    instance?: string;
    code?: string;
    [key: string]: unknown;
}
interface ProblemDetailsInput {
    type?: string;
    title: string;
    status: number;
    detail?: string;
    instance?: string;
    code?: string;
    [key: string]: unknown;
}
declare function problem(details: ProblemDetailsInput, headers?: HeadersInit): Response;
type ServiceToken<T> = string | symbol | {
    readonly key: symbol;
    readonly __type?: T;
};
declare function serviceToken<T>(description: string): ServiceToken<T>;
declare class ServiceContainer {
    #private;
    private readonly parent?;
    constructor(parent?: ServiceContainer | undefined);
    set<T>(token: ServiceToken<T>, value: T): this;
    has<T>(token: ServiceToken<T>): boolean;
    get<T>(token: ServiceToken<T>): T;
    tryGet<T>(token: ServiceToken<T>): T | undefined;
    scope(): ServiceContainer;
}
type LifecyclePhase = "starting" | "started" | "stopping" | "stopped";
type LifecycleHandler = (signal: AbortSignal) => void | Promise<void>;
declare class ApplicationLifecycle {
    #private;
    on(phase: LifecyclePhase, handler: LifecycleHandler): () => void;
    run(phase: LifecyclePhase): Promise<void>;
    get signal(): AbortSignal;
}
interface HealthCheckResult {
    status: "up" | "down" | "degraded";
    message?: string;
    details?: unknown;
    durationMs?: number;
}
type HealthCheck = () => HealthCheckResult | Promise<HealthCheckResult>;
declare class HealthRegistry {
    #private;
    register(name: string, check: HealthCheck): () => void;
    check(): Promise<{
        status: "up" | "down" | "degraded";
        checks: Record<string, HealthCheckResult>;
    }>;
}
declare function requestId(headers: Headers, preferred?: string): string;
interface IdempotencyRecord<T = unknown> {
    key: string;
    value: T;
    expiresAt: number;
}
interface IdempotencyStore<T = unknown> {
    get(key: string): Promise<IdempotencyRecord<T> | null>;
    set(record: IdempotencyRecord<T>): Promise<void>;
    delete(key: string): Promise<void>;
}
declare function memoryIdempotencyStore<T = unknown>(now?: () => number): IdempotencyStore<T>;
declare function withIdempotency<T>(store: IdempotencyStore<T>, key: string, execute: () => Promise<T>, ttlMs?: number): Promise<{
    value: T;
    replayed: boolean;
}>;

export { type ActionDefinition, ApplicationLifecycle, type AsyncSessionBackend, type Bucket, type BudgetViolation, CSRF_COOKIE, CSRF_HEADER, type CacheControlOptions, type CachePolicy, type ContentSecurityPolicyConfig, type Context, type CookieOptions, type CookieStore, type CorsConfig, type CorsOrigin, type CspDirectiveValue, type DefinedAction, type DefinedEndpoint, type DefinedLoader, type EndpointDefinition, EndpointError, type EndpointErrorBody, type FeatureFlags, type FeatureRule, type FeatureValue, type HealthCheck, type HealthCheckResult, HealthRegistry, type HstsConfig, type IdempotencyRecord, type IdempotencyStore, type LifecycleHandler, type LifecyclePhase, type LoaderDefinition, type LocalStorageSnapshot, type Middleware, type Mode, type Next, type PageComponent, type PageMeta, type PerformanceBudgets, type PerformanceMeasurement, type PermissionsPolicyConfig, type ProblemDetails, type ProblemDetailsInput, type RateLimitOptions, type RateLimitStore, type RawSocket, type RealtimeBridge, type RealtimeBus, type RealtimeConnectMeta, type RealtimeEnvelope, type RealtimeHandler, type RealtimeRegistry, type RealtimeSocket, type RequestLoggerOptions, type RequestRecord, type RequireAuthOptions, type Room, type RoomAuthInfo, type RoomClient, type RoomDefinition, type RoomHandlers, type RpcClientOptions, SESSION_USER_KEY, type SaveUploadOptions, type SavedUpload, type SchemaLike, type SecurityConfig, type SeoConfig, type ServerSentEvent, ServiceContainer, type ServiceToken, type SessionBackend, type SessionEntry, type SessionStore, type Span, type SpanRecord, type StreamResponseInit, type TFunction, TTLCache, type Target, type Tenant, type TenantMiddlewareOptions, type TenantResolver, type Tracer, type TrustedTypesConfig, UploadError, bridgeRealtime, cacheControl, checkPerformanceBudgets, collectUploads, createContext, createCorsPreflightResponse, createRealtimeRegistry, createRpcClient, createTracer, csrfProtection, csrfToken, dedupe, defaultKey, defineAction, defineEndpoint, defineFeatureFlags, defineLoader, defineRoom, escapeHtml, etag, getUser, hashPassword, isRoomDefinition, isSafeIslandName, isSafeRequestPath, isWebSocketOriginAllowed, loadSession, logIn, logOut, memoryIdempotencyStore, notModified, peerKey, problem, proxyKey, rateLimit, renderDevError, renderError, renderNotFound, renderProdError, renderStatusPage, requestId, requestLogger, requireAuth, requireTenant, resolveRequestUrl, sanitizeFilename, saveUpload, serviceToken, sessionAuth, setSessionBackend, sse, streamResponse, tenantFromSubdomain, tenantMiddleware, tenantScope, tracingMiddleware, verifyCsrf, verifyPassword, withCacheControl, withContextHeaders, withIdempotency, withSecurityHeaders, withSpan };
```

---

## @wrnexus/csr

Documentation URL: https://wrnexusjs.dev/packages/csr

# @wrnexus/csr

> The browser-side client runtime for WrNexus — generic, self-contained JS that hydrates server-rendered pages with reactivity, client-side navigation, and realtime rooms.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

`@wrnexus/csr` holds the three client runtimes that WrNexus serves to the browser. Components are authored as `.wrn` files and rendered on the **server**; this package provides the single, generic runtime that **hydrates** that HTML in the browser — there are no per-component browser bundles. Each runtime is exported as a plain-JS string (no build step, no imports) intended to be served verbatim from a well-known URL:

- **reactive** at `/__wrnexus/reactive.js` — reactive directives (`data-scope`, `data-text`, `data-for`, …)
- **nav** at `/__wrnexus/nav.js` — SPA-style client navigation with graceful fallback
- **realtime** at `/__wrnexus/realtime.js` — WebSocket "rooms", declarative or programmatic

The package itself runs on the server (it just returns strings); the strings it returns run in the browser. A dev/prod server (see `@wrnexus/core`) is responsible for actually serving them.

## Installation

```bash
bun add @wrnexus/csr
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported).

## API

All exports come from the package root (`@wrnexus/csr`). The runtime source is delivered as strings, so the "API" on the server side is small; the real surface is the browser directives/globals each string installs.

### Runtime strings

| Export             | Type     | Served at                | Contents                       |
| ------------------ | -------- | ------------------------ | ------------------------------ |
| `REACTIVE_RUNTIME` | `string` | `/__wrnexus/reactive.js` | Reactive directive runtime     |
| `NAV_RUNTIME`      | `string` | `/__wrnexus/nav.js`      | Client-side navigation runtime |
| `REALTIME_RUNTIME` | `string` | `/__wrnexus/realtime.js` | Realtime rooms runtime         |

### Accessor functions

Convenience getters that return the same strings.

```ts
getReactiveRuntime(): string   // → REACTIVE_RUNTIME
getNavRuntime(): string        // → NAV_RUNTIME
getRealtimeRuntime(): string   // → REALTIME_RUNTIME
```

### Browser: reactive directives

Applied to any subtree containing `data-scope`. Expressions are parsed by a tiny eval-free evaluator, so a strict CSP with no `unsafe-eval` works.

| Directive                                                | Purpose                                                                 |
| -------------------------------------------------------- | ----------------------------------------------------------------------- |
| `data-scope="count: 0, name: 'x'"`                       | Declare reactive state on a subtree                                     |
| `data-on-<event>="count++"`                              | Run a statement in scope on a DOM event                                 |
| `data-text="expr"`                                       | Bind an element's `textContent` to an expression                        |
| `data-show="expr"`                                       | Toggle visibility (`display`) on truthiness                             |
| `data-for="item in list"` (opt. index and `key item.id`) | Per-item rendering; stable keys preserve DOM identity during reorder    |
| `data-key="item.id"`                                     | Alternative key declaration for `data-for` templates                    |
| `{{expr}}` or `{expr}`                                   | Interpolation inside text nodes and attribute values                    |
| `data-wrnexus-csr="id"`                                  | Target for a generated CSR fetch binding (fetches `/__wrnexus/csr?...`) |

Supported expression features: literals, identifiers, member access (`a.b`, `a[b]`), function/method calls, arrays, objects, arithmetic, comparison, equality, logical (`&& ||`), unary (`! - +`), and ternary. Statements support `++`/`--`, assignment operators (`= += -= *= /= %=`), and bare expression/method calls. Rendering is dependency-tracked: a signal change only re-runs the renderers that actually read it.

Browser globals installed: `window.__wrnexusHydrateScopes(root)` and `window.__wrnexusHydrateCsrFetches(root)` — both idempotent, so re-running after a DOM swap or HMR morph is safe. Both run automatically on `DOMContentLoaded`.

### Browser: navigation

Intercepts same-origin `<a>` clicks, fetches the target page, and swaps the `#app` container in place (via `importNode` — not `innerHTML` — so it works under a Trusted-Types CSP), updating history, title, and scroll, then re-hydrates. Cross-origin links, modified clicks, `download`/`data-no-nav`/`rel="external"`/`target` links, non-HTML responses, or a missing `#app` fall back to a full browser navigation.

- Programmatic navigation: `window.__wrnexusNavigate(url)`
- Emits a `wrnexus:navigated` `CustomEvent` (`detail.url`) after each swap
- Sends `x-wrnexus-nav: 1` on fetches so the server can return the page fragment
- Appends any `/__wrnexus/*` runtime scripts the incoming page needs but the current document lacks

### Browser: realtime rooms

Connects to `/realtime/<name>` over WebSocket (`ws`/`wss` chosen from `location.protocol`). Two usage modes.

Programmatic API via `window.wire`:

```ts
wire.room(name): Room          // open (or reuse) a room connection
wire.bindRooms(root?)          // (re)bind declarative [data-room] containers

interface Room {
  name: string;
  send(obj: object | string): Room;         // JSON-stringifies objects; queues until open
  on(type: string, cb): Room;               // filter by msg.type; "*" or a fn = all messages
  on(cb): Room;
  close(): Room;
}
```

Internal lifecycle messages are emitted to listeners as `{ type }`: `__open`, `__close`, `__error`, and `__raw` (non-JSON frames, with `data`). Reconnect uses exponential backoff capped at 5s; queued sends flush on reconnect.

Declarative binding (zero JS) on a `data-room="<name>"` container:

| Attribute                            | On              | Purpose                                                                  |
| ------------------------------------ | --------------- | ------------------------------------------------------------------------ |
| `data-room="<name>"`                 | container       | Connect to room `<name>`                                                 |
| `data-room-user="<id>"`              | container       | Identify the connection (`?user=<id>`)                                   |
| `data-room-log`                      | element         | Where incoming messages are appended                                     |
| `<template data-room-item="<type>">` | template        | Row template for messages of that `type` (empty = fallback)              |
| `%field%`                            | inside template | Placeholder filled from the message field (text/attr only, HTML-escaped) |
| `data-room-status`                   | element         | Reflects connection state text (`connected`/`disconnected`/`error`)      |
| `data-room-status-class`             | status element  | Base class; a state variant (`is-connected`, …) is appended              |
| `<form data-room-send>`              | form            | Submits named fields as a JSON message                                   |
| `data-room-reset`                    | form field      | Clears that field after send                                             |

Rebinds on `wrnexus:navigated` and closes rooms whose container has left the page.

## Usage

Server side — serve the runtime strings from your router (example with `Bun.serve`):

```ts
import { getReactiveRuntime, getNavRuntime, getRealtimeRuntime } from "@wrnexus/csr";

const routes: Record<string, string> = {
  "/__wrnexus/reactive.js": getReactiveRuntime(),
  "/__wrnexus/nav.js": getNavRuntime(),
  "/__wrnexus/realtime.js": getRealtimeRuntime(),
};

Bun.serve({
  fetch(req) {
    const body = routes[new URL(req.url).pathname];
    if (body) {
      return new Response(body, {
        headers: { "content-type": "text/javascript; charset=utf-8" },
      });
    }
    return new Response("Not found", { status: 404 });
  },
});
```

Browser side — server-rendered HTML that the reactive runtime hydrates:

```html
<div data-scope="count: 0, showPassword: false">
  <button data-on-click="count++">+1</button>
  <span data-text="count"></span>
  <p>Total: {{count}}</p>
  <input type="{showPassword ? 'text' : 'password'}" />
  <button
    data-on-click="showPassword = !showPassword"
    aria-label="{showPassword ? 'Hide password' : 'Show password'}"
  >
    Toggle password
  </button>
</div>
<script src="/__wrnexus/reactive.js"></script>
```

State interpolation in ordinary attributes is reactive. The compiler keeps the
initial SSR value and emits an internal binding so attributes such as `type`,
`aria-label`, `aria-pressed`, `class`, and `href` update after state changes.

A realtime chat, fully declarative:

```html
<div data-room="lobby" data-room-user="ada">
  <div data-room-status></div>
  <ul data-room-log></ul>
  <template data-room-item="chat"><li>%user%: %text%</li></template>
  <form data-room-send>
    <input name="text" data-room-reset />
    <input type="hidden" name="type" value="chat" />
    <button>Send</button>
  </form>
</div>
<script src="/__wrnexus/realtime.js"></script>
```

Or drive a room from code:

```ts
const room = wire.room("lobby");
room.on("chat", (msg) => console.log(msg.user, msg.text));
room.send({ type: "chat", user: "ada", text: "hi" });
```

## Requirements / Notes

- **Bun-only** on the server (the package integrates with Bun-based WrNexus servers); the emitted strings are plain browser JS with no dependencies.
- Browser runtimes are **self-contained** (no imports, no build step) and **idempotent**, so re-hydration after navigation or HMR is safe.
- Designed for a **strict CSP**: the reactive expression evaluator avoids `eval`/`new Function` (no `unsafe-eval`), and DOM swaps use `importNode`/attribute writes rather than `innerHTML` (Trusted-Types friendly).
- Peer packages: rendered `.wrn` components and the serving layer come from `@wrnexus/core` (the sole dependency); pages are rendered by the WrNexus dev/prod server.

### Exported TypeScript declarations

```ts
/**
 * Browser reactive runtime (Point 2: reactive directives).
 *
 * Served verbatim at `/__wrnexus/reactive.js` for any page that contains a
 * `data-scope`. It is plain browser JS (no build step) and self-contained: it
 * inlines a tiny `signal()` so it has no imports to resolve.
 *
 * Supported directives (this is exactly what the `.wrn` compiler emits):
 *   data-scope="count: 0, name: 'x'"   declare reactive state on a subtree
 *   data-on-<event>="count++"          run a statement in scope on an event
 *   data-text="expr"                   element textContent follows an expression
 *   data-wrn-loop-locals="base64-json"   preserves SSR {#each} item/index values
 *   data-wrnexus-csr="id"                 target for generated CSR fetch bindings
 *   {{expr}} or {expr}                 interpolation inside text nodes
 *
 * Expressions are evaluated by a tiny parser instead of `eval`/`new Function`,
 * so production can use a strong CSP without `unsafe-eval`.
 */
declare const REACTIVE_RUNTIME: string;

/**
 * Client-side navigation runtime, served at `/__wrnexus/nav.js`.
 *
 * Progressive enhancement over normal links: intercepts same-origin `<a>`
 * clicks, fetches the target page's HTML, swaps the `#app` container in place,
 * updates history/title/scroll, ensures any framework runtimes the new page
 * needs are present, and re-hydrates.
 *
 * Before replacing the current page, component lifecycle behaviors are
 * explicitly disposed. This ensures `unmount` hooks and watcher cleanups run
 * before the old DOM is removed.
 *
 * Programmatic navigation is exposed as:
 *
 *   window.__wrnexusNavigate(url)
 */
declare const NAV_RUNTIME: string;

/**
 * Client realtime runtime, served at `/__wrnexus/realtime.js`.
 *
 * Two ways to use it — no hand-written WebSocket code either way:
 *
 * 1. Declarative (zero JS). Put `data-room="<name>"` on a container; the runtime
 *    connects, appends incoming messages to `[data-room-log]` using a
 *    `<template data-room-item="<type>">` (fields via `%field%`, HTML-escaped),
 *    reflects connection state on `[data-room-status]`, and sends a
 *    `<form data-room-send>`'s named fields as JSON on submit (fields marked
 *    `data-room-reset` clear after send). Optional `data-room-user` identifies
 *    the connection.
 *
 * 2. Programmatic: `const room = wire.room("chat"); room.on("chat", fn);
 *    room.send({ type: "chat", text })`. Handles connect, JSON, reconnect.
 *
 * Rebinds on `wrnexus:navigated` (client-side nav) and closes rooms whose
 * container has left the page.
 */
declare const REALTIME_RUNTIME: string;

/**
 * @wrnexus/csr — the browser reactive runtime.
 *
 * Components are `.wrn` files rendered on the SERVER (see @wrnexus/dev-server)
 * and hydrated in the browser by this single, generic runtime — served once at
 * `/__wrnexus/reactive.js` for any page that contains a `data-scope`. There are
 * no per-component browser bundles: SSR stays cleanly separated from CSR.
 */

/** The reactive runtime served at `/__wrnexus/reactive.js` (plain browser JS). */
declare function getReactiveRuntime(): string;
/** The client-side navigation runtime served at `/__wrnexus/nav.js`. */
declare function getNavRuntime(): string;
/** The realtime client runtime served at `/__wrnexus/realtime.js`. */
declare function getRealtimeRuntime(): string;

export { NAV_RUNTIME, REACTIVE_RUNTIME, REALTIME_RUNTIME, getNavRuntime, getReactiveRuntime, getRealtimeRuntime };
```

---

## @wrnexus/db

Documentation URL: https://wrnexusjs.dev/packages/db

# @wrnexus/db

> The database layer for WrNexus: TS models as the single source of truth for DDL, validation, and result typing, plus a driver-based `Db` client, migrations, and a sqlc-style query generator.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

`@wrnexus/db` is the server-side data layer. You describe tables as TypeScript
models (the `v` column builder + `table()`); those models drive migrations,
coerce raw DB rows into typed objects, and feed the query generator. A thin
`Driver` interface is implemented by adapters for SQLite (`bun:sqlite`),
Postgres/MySQL (`Bun.SQL`), and MongoDB. The `Db` client adds ergonomics —
model-mapped `all`/`one`, transactions, `createTable`, pagination, and batched
relation loading. A process-wide registry (`getDb`/`setDb`) exposes configured
connections to pages and API routes. Reach for it whenever a WrNexus app needs
persistence.

## Installation

```bash
bun add @wrnexus/db
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported).

## API

The core entry (`@wrnexus/db`) is dependency-free; adapters and connectors live
in subpaths so importing the core doesn't pull in every driver.

| Subpath                | Exports                                                                                                                                           |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `@wrnexus/db`          | `v`, `table`, `Column`, `createDb`, `createTableSql`, the client registry (`setDb`/`getDb`/…), migrations, the query generator, and query helpers |
| `@wrnexus/db/connect`  | `connectFromConfig`, `resolveDbUrl`, `DbConfig` — resolve a config to a live SQL `Db`                                                             |
| `@wrnexus/db/session`  | `sqliteSessionStore` — a `bun:sqlite` session backend for `@wrnexus/core`                                                                         |
| `@wrnexus/db/sqlite`   | `sqlite(url?)` driver                                                                                                                             |
| `@wrnexus/db/postgres` | `postgres(url)` driver                                                                                                                            |
| `@wrnexus/db/mysql`    | `mysql(url)` driver                                                                                                                               |
| `@wrnexus/db/mongo`    | `mongo(url, dbName?)` document API                                                                                                                |

### Schema — `v`, `table`, `Column`

`table(name, columns)` returns a `Model<T>`. Columns are built with `v`:

```ts
import { v, table } from "@wrnexus/db";

const users = table("users", {
  id: v.id(), // auto-increment primary key
  email: v.text().unique(),
  name: v.text().optional(), // NULLable
  age: v.int().default(0),
  active: v.bool().default(true),
  createdAt: v.timestamp().default("now"), // CURRENT_TIMESTAMP
});
```

Column builders: `v.id`, `v.text` (alias `v.string`), `v.int`, `v.real` (alias
`v.number`), `v.bool` (alias `v.boolean`), `v.timestamp`, `v.json`. `BaseType`
values are `"id" | "text" | "int" | "real" | "bool" | "timestamp" | "json"`.

`Column` modifiers (chainable): `.optional()`, `.unique()`, `.default(value)`
(use the sentinel `"now"` for a current-timestamp default), `.primaryKey()`,
`.references(table, column = "id")`. `.coerce(raw)` converts a raw DB value to
its JS type.

A `Model<T>` exposes: `name`, `columns`, `parse(row)` (coerces a raw row into a
typed `T`; unknown columns pass through), and `describe()` (returns each
column's `ColumnDef`, for migrations and the generator).

### Driver & client — `createDb`, `Db`, `Driver`

```ts
createDb(driver: Driver): Db
```

A `Driver` (implemented by adapters) exposes `dialect`, `query(sql, params?)`,
`exec(sql, params?)`, `transaction(fn)`, and `close()`. `createDb` wraps it in a
`Db`:

- `all<T>(sql, params?, model?)` — all rows, mapped through `model.parse` when a model is given.
- `one<T>(sql, params?, model?)` — first row or `null`.
- `exec(sql, params?)` — `Promise<ExecResult>` (`{ changes, lastInsertId? }`).
- `tx(fn)` — run `fn(db)` in a transaction; rolls back on throw. Nested `tx` reuses the current transaction.
- `createTable(model)` — runs the model's `CREATE TABLE IF NOT EXISTS` DDL.
- `close()`.

Every query is parameterized (positional params). `createTableSql(model, dialect, ifNotExists?)`
renders `CREATE TABLE` directly; `Dialect` is `"sqlite" | "postgres" | "mysql"`.

### Client registry — `getDb` / `setDb`

A process-wide registry the runtime configures at startup from `wrnexus.config.ts`
(the `db` setting is the default; `databases.<name>` entries are named).

- `setDb(db)` / `setDb(name, db)` — set the default or a named connection.
- `registerDb(name, db)` — alias of `setDb(name, db)`.
- `getDb(name = "default")` — the default or a named `Db` (throws if unconfigured).
- `hasDb(name?)`, `databaseNames()`, `closeDatabases()`.

```ts
const users = await getDb().all("SELECT * FROM users");
const events = await getDb("analytics").all("SELECT * FROM hits");
```

### Adapters

- `@wrnexus/db/sqlite` — `sqlite(url = ":memory:")`. `url` may be `file:./dev.db`, a raw path, or `:memory:`. Built on `bun:sqlite`; no external service.
- `@wrnexus/db/postgres` — `postgres(url)` (e.g. `postgres://user:pass@host:5432/db`, placeholders `$N`).
- `@wrnexus/db/mysql` — `mysql(url)` (e.g. `mysql://user:pass@host:3306/db`, placeholders `?`). Postgres/MySQL both use Bun's native `Bun.SQL` client and its pooled `begin()` for transactions.
- `@wrnexus/db/mongo` — `mongo(url, dbName?)`. A document API, not SQL: `db.collection(model)` returns a `MongoRepo<T>` with `find`, `findOne`, `insert`, `insertMany`, `update`, `delete`, `count`. Reads are coerced through `model.parse` (`_id` is mapped to `id`). The `mongodb` driver is imported lazily — install it to use Mongo.

### Migrations

Migrations are `.sql` files (in e.g. `app/db/migrations`), each split into
`-- +up` and `-- +down` sections. A file with no markers is treated entirely as
`up`. Applied names are recorded in a `_wire_migrations` table so each runs once.

- `parseMigration(name, content)` → `Migration` (`{ name, up, down }`).
- `loadMigrations(dir)` — parse all `.sql` files, sorted by filename.
- `appliedMigrations(db)` — applied names, oldest first.
- `migrate(db, dir)` — apply all pending (each in a transaction); returns applied names.
- `rollback(db, dir)` — roll back the most recent; returns its name or `null`.
- `status(db, dir)` — `{ name, applied }[]` for every migration file.
- `scaffoldMigration(dir, name, dialect, models?)` — write a new numbered migration; with `models` it generates `CREATE`/`DROP` for every table (referenced tables first via topological sort). Returns the file path.

### Query generator (sqlc-style)

Turns annotated SQL into typed TS functions; params and result types are
inferred from the models, and rows map back through `model.parse` when the
selected columns are model columns.

- `parseQueries(content)` → `QueryDef[]` from `-- name: X :one|:many|:exec` blocks.
- `generateQueriesFile(queries, models, dialect)` → the `queries.gen.ts` source. `models` is a `ModelRef[]` (`{ varName, model }`). Rewrites `:name` placeholders to positional (`$N`/`?`) form.

`QueryKind` is `"one" | "many" | "exec"`.

### Query helpers

- `paginate(db, { sql, params?, countSql?, model? }, opts?)` — offset pagination. Pass the base SELECT **without** a LIMIT; it appends the page window and derives `total` via a COUNT subquery. `PageOptions`: `{ page?, perPage?, maxPerPage? }` (defaults page 1, perPage 20, maxPerPage 100). Returns `Paginated<T>` (`items, page, perPage, total, totalPages, hasNext, hasPrev`).
- `loadRelated(db, parents, opts)` — load a relation for many parents in ONE query and attach it (no N+1). `RelationOptions`: `{ table, foreignKey, as, localKey?, single?, model? }` — `single: true` attaches one child (belongsTo), otherwise an array (hasMany). Table/foreign-key names are validated as identifiers.

### Session store

`@wrnexus/db/session` exports `sqliteSessionStore(path = "sessions.db")`, a
persistent, process-shared `SessionBackend` (from `@wrnexus/core`) backed by
`bun:sqlite` (WAL mode). Sessions survive restarts and are shared by every
worker on the same file.

## Usage

Define models, connect, create tables, and query with typed results:

```ts
import { v, table, createDb } from "@wrnexus/db";
import { sqlite } from "@wrnexus/db/sqlite";

const users = table<{ id: number; email: string; name: string | null }>("users", {
  id: v.id(),
  email: v.text().unique(),
  name: v.text().optional(),
  createdAt: v.timestamp().default("now"),
});

const db = createDb(sqlite("file:./dev.db"));
await db.createTable(users);

await db.exec("INSERT INTO users (email) VALUES (?)", ["a@b.com"]);
const list = await db.all("SELECT * FROM users", [], users); // rows typed + coerced
const one = await db.one("SELECT * FROM users WHERE id = ?", [1], users);

await db.tx(async (tx) => {
  await tx.exec("UPDATE users SET name = ? WHERE id = ?", ["Ada", 1]);
});
```

Resolve a config to a live SQL `Db`, and register it:

```ts
import { connectFromConfig } from "@wrnexus/db/connect";
import { setDb, getDb } from "@wrnexus/db";

setDb(connectFromConfig({ driver: "sqlite", url: "file:./dev.db" }, process.cwd()));
const rows = await getDb().all("SELECT * FROM users");
```

Run migrations and paginate:

```ts
import { migrate, paginate } from "@wrnexus/db";

await migrate(db, "app/db/migrations");
const pageTwo = await paginate(
  db,
  { sql: "SELECT * FROM users ORDER BY id", model: users },
  { page: 2 },
);
```

MongoDB (document API):

```ts
import { mongo } from "@wrnexus/db/mongo";

const mdb = await mongo(process.env.MONGO_URL!, "app");
const repo = mdb.collection(users);
await repo.insert({ email: "a@b.com" });
const active = await repo.find({ active: true });
```

## Configuration

`connectFromConfig` (and the runtime) read a `DbConfig` (`{ driver, url }`)
where `driver` is `sqlite | postgres | mysql`. `resolveDbUrl(url, appRoot?)`
resolves a relative `file:`/`sqlite:` URL against the app root. MongoDB is not a
SQL driver — use `@wrnexus/db/mongo` directly.

## Requirements / Notes

- **Bun-only.** Uses `bun:sqlite` (SQLite adapter + session store) and `Bun.SQL`
  (Postgres/MySQL). Migrations/scaffolding use `node:fs`/`node:path`.
- Works with `@wrnexus/core` — `sqliteSessionStore` implements its
  `SessionBackend`; `getDb`/`setDb` are wired by the WrNexus runtime from
  `wrnexus.config.ts`.
- The `mongodb` npm package is an optional, lazily-imported peer — install it
  only if you use `@wrnexus/db/mongo`. The core package stays dependency-free.

### Exported TypeScript declarations

```ts
import { M as Model } from './schema-tVurYsbL.js';
export { B as BaseType, C as Column, a as ColumnDef, b as Columns, t as table, v } from './schema-tVurYsbL.js';
import { a as Db, b as Dialect, R as Row } from './driver-DA53QHkO.js';
export { D as Driver, E as ExecResult, T as TxHandle, c as createDb, d as createTableSql } from './driver-DA53QHkO.js';

/**
 * A process-wide database registry. The framework configures it at server
 * startup from `wrnexus.config.ts`: the `db` setting becomes the **default**
 * connection, and each entry under `databases` becomes a **named** connection.
 * Pages and API routes then call `getDb()` for the default, or `getDb("<name>")`
 * for a named one, to run queries (including the generated typed functions).
 *
 *   const users = await getDb().all("SELECT * FROM users");            // default db
 *   const events = await getDb("analytics").all("SELECT * FROM hits"); // named db
 */

type DbFactory = () => Db;
/** Set the default database (called by the runtime at startup). */
declare function setDb(db: Db): Db;
/** Set a named database (from `databases.<name>` in config). */
declare function setDb(name: string, db: Db): Db;
/** Register a named database. Alias of `setDb(name, db)` for readability. */
declare function registerDb(name: string, db: Db): Db;
/**
 * Register a named database without opening its connection pool. The first
 * `getDb(name)` call creates and caches the connection.
 */
declare function registerLazyDb(name: string, factory: DbFactory): void;
/** The default database, or a named one. Throws if it isn't configured. */
declare function getDb(name?: string): Db;
/** Whether the default (or a named) database has been configured. */
declare function hasDb(name?: string): boolean;
/** Names of all configured databases (the default appears as "default"). */
declare function databaseNames(): string[];
/** Close every configured database and clear the registry. */
declare function closeDatabases(): Promise<void>;

/**
 * Migration runner. Migrations are `.sql` files in `app/db/migrations`, each
 * split into `-- +up` and `-- +down` sections. Applied migrations are recorded
 * in a `_wire_migrations` table so they run exactly once, newest-last.
 *
 * `scaffoldMigration(..., models)` writes an initial migration straight from the
 * TS models — the source of truth — so you don't hand-write the first schema.
 */

interface Migration {
    name: string;
    up: string;
    down: string;
}
/** Split a migration file into its `up` and `down` SQL sections. */
declare function parseMigration(name: string, content: string): Migration;
/** Load and parse all migration files in a directory, sorted by filename. */
declare function loadMigrations(dir: string): Migration[];
/** Names of already-applied migrations, oldest first. */
declare function appliedMigrations(db: Db): Promise<string[]>;
/** Apply an ordered migration list (each in a transaction). Returns applied names. */
declare function applyMigrations(db: Db, migrations: readonly Migration[]): Promise<string[]>;
/** Apply all pending migrations from a directory. */
declare function migrate(db: Db, dir: string): Promise<string[]>;
/** Roll back the most recently applied migration. Returns its name, or null. */
declare function rollback(db: Db, dir: string): Promise<string | null>;
/** Full status: every migration file with whether it has been applied. */
declare function status(db: Db, dir: string): Promise<{
    name: string;
    applied: boolean;
}[]>;
/**
 * Write a new migration file. With `models`, the `up`/`down` are generated from
 * the TS models (create/drop every table); otherwise empty stubs are written.
 * Returns the created file path.
 */
declare function scaffoldMigration(dir: string, name: string, dialect: Dialect, models?: Model[]): string;

/**
 * sqlc-style query generator. Annotated SQL in `app/db/queries/*.sql` becomes
 * typed TS functions whose params + results are inferred from the TS models and
 * whose rows are mapped back through `model.parse`.
 *
 *   -- name: GetUserByEmail :one
 *   SELECT * FROM users WHERE email = :email;
 *
 * →  GetUserByEmail(db, { email: string }): Promise<{…} | null>
 *
 * Type inference is best-effort (comparisons + INSERT column lists + SELECT list
 * vs the model); anything it can't resolve becomes `unknown`.
 */

type QueryKind = "one" | "many" | "exec";
interface QueryDef {
    name: string;
    kind: QueryKind;
    sql: string;
}
/** A model plus the variable name it is exported under (for imports). */
interface ModelRef {
    varName: string;
    model: Model;
}
/** Parse annotated queries from one `.sql` file's contents. */
declare function parseQueries(content: string): QueryDef[];
/** Generate the full `queries.gen.ts` source. */
declare function generateQueriesFile(queries: QueryDef[], models: ModelRef[], dialect: Dialect): string;

/**
 * Query ergonomics built on the `Db` client: offset pagination and a batched
 * relation loader (avoids N+1). Both are dialect-aware — placeholders follow the
 * driver's style (`$N` for Postgres, `?` for SQLite/MySQL).
 */

interface PageOptions {
    page?: number;
    perPage?: number;
    /** Upper bound on perPage. Default 100. */
    maxPerPage?: number;
}
interface Paginated<T> {
    items: T[];
    page: number;
    perPage: number;
    total: number;
    totalPages: number;
    hasNext: boolean;
    hasPrev: boolean;
}
/**
 * Paginate a SELECT. Pass the base query WITHOUT a LIMIT; the helper appends the
 * page window and derives the total with a COUNT over the same query.
 *
 *   await paginate(db, { sql: "SELECT * FROM users ORDER BY name", model: users }, { page: 2 })
 */
declare function paginate<T = Row>(db: Db, query: {
    sql: string;
    params?: unknown[];
    countSql?: string;
    model?: Model<T>;
}, opts?: PageOptions): Promise<Paginated<T>>;
interface RelationOptions<C> {
    /** Parent field whose value matches the child's foreign key. Default "id". */
    localKey?: string;
    /** Child table to load from. */
    table: string;
    /** Child column that references the parent. */
    foreignKey: string;
    /** Property name to attach on each parent. */
    as: string;
    /** true → attach a single child (belongsTo); false → an array (hasMany). */
    single?: boolean;
    /** Map child rows through a model. */
    model?: Model<C>;
}
/**
 * Load a relation for a set of parent rows in ONE query and attach it to each
 * parent (no N+1). Returns the same parents, each with `opts.as` populated.
 *
 *   await loadRelated(db, users, { table: "posts", foreignKey: "userId", as: "posts" })
 */
declare function loadRelated<P extends Row, C extends Row = Row>(db: Db, parents: P[], opts: RelationOptions<C>): Promise<(P & Record<string, C | C[] | null>)[]>;

interface CursorPageOptions {
    limit?: number;
    after?: string;
    before?: string;
    column?: string;
    direction?: "asc" | "desc";
    maxLimit?: number;
}
interface CursorPage<T> {
    items: T[];
    nextCursor?: string;
    previousCursor?: string;
    hasMore: boolean;
}
declare function cursorPaginate<T extends Row = Row>(db: Db, query: {
    sql: string;
    params?: unknown[];
    model?: Model<T>;
}, options?: CursorPageOptions): Promise<CursorPage<T>>;
declare function optimisticUpdate(db: Db, input: {
    table: string;
    idColumn?: string;
    id: unknown;
    versionColumn?: string;
    version: number;
    values: Record<string, unknown>;
}): Promise<number>;
declare function tenantScope(sql: string, tenantId: unknown, dialect: Dialect, existingParams?: number, column?: string): {
    sql: string;
    params: unknown[];
};
declare function softDeleteClause(column?: string): string;

export { type CursorPage, type CursorPageOptions, Db, Dialect, type Migration, Model, type ModelRef, type PageOptions, type Paginated, type QueryDef, type QueryKind, type RelationOptions, Row, appliedMigrations, applyMigrations, closeDatabases, cursorPaginate, databaseNames, generateQueriesFile, getDb, hasDb, loadMigrations, loadRelated, migrate, optimisticUpdate, paginate, parseMigration, parseQueries, registerDb, registerLazyDb, rollback, scaffoldMigration, setDb, softDeleteClause, status, tenantScope };
```

---

## @wrnexus/dev-server

Documentation URL: https://wrnexusjs.dev/packages/dev-server

# @wrnexus/dev-server

> The WrNexus HTTP + WebSocket server runtime — request dispatch, SSR document assembly, live-reload (HMR), and the portable production handler.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

This package is the server runtime that powers a WrNexus app in both development and production. A single **request runtime** (`createHandlers`) owns HTTP/WebSocket dispatch and SSR document assembly; it knows nothing about _how_ modules and assets are produced, so the dev and prod entry points wire in different backends: dev uses dynamic module loading plus on-the-fly bundling and injects a live-reload client; prod uses a static, pre-built manifest with cache-immutable assets. The package also ships a multi-app **gateway** (route several apps by `Host` header behind one port) and a portable `node:http` adapter for WinterCG hosts. It is entirely server-side and Bun-native (`Bun.serve`, `Bun.file`, `Bun.gzipSync`).

## Installation

```bash
bun add @wrnexus/dev-server
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported for the full server; the `node:http` adapter is for WinterCG embedding only).

## API

### Main entry (`@wrnexus/dev-server`)

| Export                                                    | Kind                      | Purpose                                                                                                                               |
| --------------------------------------------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `startServer(opts: ServeOptions)`                         | `Promise<RunningServer>`  | Start the dev server on `Bun.serve`: builds the router, connects/migrates databases, wires assets + HMR, and starts the file watcher. |
| `createHandlers(deps: RuntimeDeps)`                       | `Handlers`                | The shared request runtime (fetch + websocket handlers). Re-exported from `runtime.ts`.                                               |
| `createProductionServer(manifest, opts)`                  | `Bun.Server`              | Start the production server from a precompiled manifest.                                                                              |
| `createProductionHandlers(manifest, opts)`                | `Handlers`                | Build the portable prod fetch/websocket handlers with no server bound (the deployment-adapter seam).                                  |
| `startGateway(opts: GatewayOptions)`                      | `Promise<RunningGateway>` | Boot multiple apps as child processes and route by `Host`.                                                                            |
| `toRequest`, `writeResponse`, `nodeListener`, `serveNode` | functions                 | `node:http` ↔ WinterCG `Request`/`Response` adapter.                                                                                  |
| `RESTART_EXIT_CODE`                                       | `number` (`97`)           | Exit code the dev child uses to ask the supervisor for a fresh process.                                                               |
| `STYLES_HREF`, `HMR_CLIENT_JS`                            | constants                 | The global stylesheet URL and the inline HMR client script.                                                                           |

Exported types: `ServeOptions`, `RunningServer`, `RuntimeDeps`, `AssetServer`, `WsData`, `GatewayApp`, `GatewayOptions`, `GatewayAuth`, `GatewaySecurity`, `RunningGateway`, `FetchHandler`.

### `startServer(opts)`

```ts
interface ServeOptions {
  appDir: string; // absolute/relative path to the app/ dir
  port?: number; // default 3000
  hostname?: string; // default "localhost"
  mode?: Mode; // "development" | "production"; default "development"
  hmr?: boolean; // inject live-reload client; default (mode === "development")
  styleEntry?: string | null; // resolved absolute path to the global CSS entry
  stylesConfig?: StylesConfig; // custom styles processor (e.g. Tailwind/PostCSS)
  head?: string; // raw HTML appended to every page <head>
  seo?: SeoConfig; // global SEO defaults
  security?: SecurityConfig; // security headers + CORS policy
  theme?: ThemeConfig; // design-token theme (merged over built-in light/dark)
  i18n?: I18nConfig; // default language + supported locales
  db?: { driver: string; url: string }; // default db → getDb(); dev auto-migrates
  databases?: Record<string, { driver: string; url: string }>; // named dbs → getDb("<name>")
  realtime?: { scale?: boolean; redisUrl?: string }; // bridge rooms over Redis across processes
}

interface RunningServer {
  port: number;
  hostname: string;
  url: string;
  router: Router;
  stop(): void;
}
```

In development, `startServer` also connects `app/db/migrations` (and `app/db/<name>/migrations`) and auto-applies migrations, then starts an in-process file watcher. CSS edits hot-swap live. Page, component, layout, API, middleware, realtime, schema, locale, and public-asset edits invalidate only their cached modules, rescan routes where necessary, and morph fresh HTML through the existing HMR WebSocket. The server process and active gateway stay running.

### `createHandlers(deps)`

The core runtime shared by dev and prod. It handles CORS preflight, `/healthz` and `/__wrnexus/health`, request-body size limits (413), HMR socket upgrades (`/__wrnexus/hmr`), realtime WebSocket upgrades (`defineRoom` default export or a raw `websocket` export), the middleware pipeline, API routes (`/api/*`), framework assets (`/__wrnexus/*`), public assets, and full SSR page rendering (component mounts, layouts, slots, i18n markers, per-page script selection, ETag/304, gzip).

```ts
interface RuntimeDeps {
  mode: Mode;
  hmr: boolean; // inject the live-reload client into pages
  router: Router;
  loadModule(file: string): Promise<Record<string, unknown>>;
  getMiddleware(): Promise<Middleware[]>;
  assets: AssetServer; // serves /__wrnexus/* (islands, reactive, hmr)
  hasStyles?: boolean; // inject the global stylesheet link
  hasUi?: boolean; // inject the Wire UI stylesheet (/__wrnexus/ui.css)
  theme?: ResolvedTheme; // enables /__wrnexus/theme.css + <html data-theme>
  i18n?: ResolvedI18n; // enables ctx.t, <html lang>, {t:key} markers
  inlineStyles?: string; // inline small prod stylesheets into <head>
  assetVersion?: string; // cache-busting ?v= on framework asset URLs
  head?: string; // raw HTML appended to every page <head>
  seo?: SeoConfig;
  security?: SecurityConfig;
  maxBodyBytes?: number; // 413 above this; default 10 MB
  hub?: HmrHub; // browser HMR sockets (dev only)
  realtimeBus?: RealtimeBus; // cross-process room bridge (Redis pub/sub)
}

interface Handlers {
  fetch(req: Request, server: UpgradeServer): Promise<Response | undefined>;
  websocket: { open; message; close; drain };
}
```

`WsData` is the per-connection socket tag — a discriminated union of `{ kind: "realtime"; handler }`, `{ kind: "room"; meta }`, or `{ kind: "hmr" }`.

### `createProductionServer(manifest, opts)` / `createProductionHandlers(manifest, opts)`

Production runs the _same_ request runtime as dev, but with no filesystem scan and no runtime bundling. `wrnexus build` emits an entry that statically imports every route/component/layout module and passes them as a `ProdManifest`; the route-matching tables are rebuilt from the raw patterns.

```ts
interface ProdManifest {
  pages: { raw: string; mod: RouteModule }[];
  api: { raw: string; mod: RouteModule }[];
  realtime: { raw: string; mod: RouteModule }[];
  middleware: Middleware[];
  components: { name: string; mod: RouteModule }[];
  layouts: { name: string; mod: RouteModule }[];
}

interface ProdOptions {
  stylesPath?: string;
  inlineStyles?: string;
  reactivePath?: string;
  themePath?: string;
  themeJsPath?: string;
  theme?: ResolvedTheme;
  uiCssPath?: string;
  schemasJs?: string;
  i18n?: ResolvedI18n;
  db?: { driver: string; url: string };
  databases?: Record<string, { driver: string; url: string }>;
  realtime?: { scale?: boolean; redisUrl?: string };
  assetVersion?: string;
  publicDir?: string;
  head?: string;
  seo?: SeoConfig;
  security?: SecurityConfig;
  port?: number;
  hostname?: string;
  maxBodyBytes?: number;
}
```

`createProductionServer` also loads the `.env` cascade for the `production` profile, installs `SIGTERM`/`SIGINT` graceful shutdown, and binds `0.0.0.0` (port from `opts.port` or `$PORT`, default 3000). Migrations are **not** run here — apply them first (`wrnexus db migrate`). `createProductionHandlers` returns the bare handlers for edge/serverless/`node:http` deployment.

### `startGateway(opts)` — multi-app gateway

Serves several apps behind one port and routes each request to the right app by its `Host` header. Each app runs as its own child process (full isolation); the gateway is a thin host-based reverse proxy for HTTP and WebSocket. In development, normal application edits are applied inside the existing child and sent through its existing HMR connection. The child supervisor remains as crash recovery rather than the normal update path. Apps communicate at runtime via `@wrnexus/pubsub` (use the Redis driver so messages cross processes).

```ts
interface GatewayOptions {
  port?: number; // default 3000
  hostname?: string; // dev: "127.0.0.1"; production: "0.0.0.0"
  mode?: "development" | "production";
  apps: GatewayApp[];
  security?: GatewaySecurity;
}

interface GatewayApp {
  name: string; // app id (for logs)
  dir: string; // app root (contains app/ + wrnexus.config.ts)
  domains: string[]; // host names routed here
  port?: number; // fixed internal port; else assigned
  auth?: GatewayAuth; // per-app edge access control
}

interface GatewayAuth {
  basic?: { user: string; pass: string } | Array<{ user: string; pass: string }>;
  allowIps?: string[]; // exact-match IP allowlist
  forward?: { url: string }; // forward-auth (SSO): 2xx allows
}

interface GatewaySecurity {
  trustedHostsOnly?: boolean; // 404 unknown hosts instead of first app
  rateLimit?: { max: number; windowMs?: number }; // global by client IP (429)
  headers?: boolean; // add baseline edge security headers
  forwardedHeaders?: boolean; // set X-Forwarded-* (default true)
  accessLog?: boolean;
}
```

Forward auth is a verification hook, not a login page. Configure `forward.url` with a
dedicated endpoint such as `http://sso.localhost:3000/api/verify`. The gateway forwards
the request's `Cookie` and `Authorization` headers plus `X-Forwarded-Host`,
`X-Forwarded-Proto`, `X-Original-Method`, and `X-Original-Uri` (including its query
string). The verifier must return 2xx only for an authenticated session and 401/403
otherwise. Pointing forward auth at an SSO home page that always returns 200 allows
every request and does not implement SSO.

For browser SSO, the verifier may return a `302`/`303`/`307`/`308` with a `Location`
header pointing to its login page. The gateway passes that redirect to the browser. The
login flow should validate a signed `returnTo` value before redirecting back; API clients
should receive `401`/`403` instead of an HTML login redirect.

Open the gateway URL (normally `http://127.0.0.1:3000`), not an app's internal
port. The gateway exposes `/__gateway/health` (JSON list of routed apps) and returns a
`RunningGateway` (`{ port, url, stop() }`). Use `--host=0.0.0.0` when other devices need
to reach a development gateway.

### `node:http` adapter (from `./adapters/node.ts`)

For embedding the WinterCG handler behind an existing Node server or a WinterCG host. Note the full app still needs Bun-compatible globals (`Bun.file`, `bun:sqlite`, etc.); only the `Request`/`Response` conversion is fully portable.

```ts
type FetchHandler = (req: Request) => Response | undefined | Promise<Response | undefined>;

toRequest(req: IncomingMessage, opts?): Promise<Request>
writeResponse(res: ServerResponse, response: Response): Promise<void>  // preserves multiple Set-Cookie
nodeListener(handler: FetchHandler, opts?): (req, res) => Promise<void>
serveNode(handler: FetchHandler, opts?): Promise<Server>
```

### Subpath export: `@wrnexus/dev-server/serve-entry`

The child process the dev supervisor launches:

```bash
bun run serve-entry.ts <appDir> <port> <mode>
```

It loads the optional `wrnexus.config.ts`, resolves the style entry, calls `startServer`, and prints the route table (Pages / API / Realtime / Components). Because it runs in its own process, every restart re-imports all route modules fresh — that is how the supervisor delivers live reload of edited server code. `startGateway` resolves this entry via `import.meta.resolve("@wrnexus/dev-server/serve-entry")` to spawn each dev app.

## Usage

### Programmatic dev server

```ts
import { startServer } from "@wrnexus/dev-server";

const server = await startServer({
  appDir: "./app",
  port: 3000,
  mode: "development",
  theme: {/* design tokens */},
  db: { driver: "sqlite", url: "file:./data/app.db" },
});

console.log(`Running at ${server.url}`);
// server.stop();
```

### Production server from a build manifest

```ts
import { createProductionServer } from "@wrnexus/dev-server";
import { manifest } from "./dist/manifest.js"; // generated by `wrnexus build`

createProductionServer(manifest, {
  stylesPath: "./dist/styles.css",
  reactivePath: "./dist/reactive.js",
  assetVersion: process.env.BUILD_ID,
  db: { driver: "postgres", url: process.env.DATABASE_URL! },
  port: Number(process.env.PORT) || 3000,
});
```

### Embedding the handler on `node:http`

```ts
import { createProductionHandlers, serveNode } from "@wrnexus/dev-server";

const handlers = createProductionHandlers(manifest, opts);
await serveNode(handlers.fetch, { port: 8080 });
```

### Multi-app gateway

```ts
import { startGateway } from "@wrnexus/dev-server";

await startGateway({
  port: 3000,
  apps: [
    { name: "web", dir: "./apps/web", domains: ["localhost", "web.localhost"] },
    {
      name: "admin",
      dir: "./apps/admin",
      domains: ["admin.localhost"],
      auth: { basic: { user: "root", pass: "s3cret" } },
    },
  ],
  security: { trustedHostsOnly: true, rateLimit: { max: 600 } },
});
```

## Framework asset routes

The runtime serves these framework-owned paths (dev builds them live; prod serves pre-built/immutable versions):

- `/__wrnexus/nav.js`, `/__wrnexus/reactive.js`, `/__wrnexus/realtime.js` — client runtimes
- `/__wrnexus/validate.js`, `/__wrnexus/schemas.js`, `/__wrnexus/i18n.js` — validation + i18n runtimes
- `/__wrnexus/theme.css`, `/__wrnexus/theme.js`, `/__wrnexus/ui.css`, `/__wrnexus/styles.css` — styles
- `/__wrnexus/hmr` — dev-only HMR WebSocket
- `/__wrnexus/csr` — server-evaluated CSR bindings for browser-side API fetches

Pages get only the scripts they use: `nav.js` always, `reactive.js` when a page has a `data-scope`/CSR fetch, plus theme/validation/i18n/realtime runtimes when the relevant markup is present.

## Requirements / Notes

- **Bun-only.** Uses `Bun.serve` (HTTP + WebSocket), `Bun.file`, and `Bun.gzipSync`. The full app also relies on `bun:sqlite` / `Bun.SQL` via `@wrnexus/db`.
- Orchestrates the whole framework: `@wrnexus/core` (context, security, realtime registry), `@wrnexus/router`, `@wrnexus/ssr` (`renderDocument`), `@wrnexus/csr` (client runtimes), `@wrnexus/compiler` (`.wrn` → TS), `@wrnexus/styles`, `@wrnexus/ui`, `@wrnexus/validation`, `@wrnexus/i18n`, `@wrnexus/db`, and `@wrnexus/pubsub` (Redis-backed cross-process realtime).
- `.wrn` files are compiled to TypeScript into a hidden sibling `.wrnexus/` cache dir and dynamically imported; the module cache means each edited server module needs a fresh process (dev) — hence the restart-on-change model.
- Responses are gzipped when the client accepts it and the body is a buffered, compressible payload ≥ 1 KB; streaming/SSE responses opt out via `Cache-Control: no-transform`.
</content>

</invoke>

### Exported TypeScript declarations

```ts
import { Mode, Middleware, SeoConfig, SecurityConfig, RealtimeBus, RealtimeConnectMeta } from '@wrnexus/core';
import { Router } from '@wrnexus/router';
import { ResolvedTheme, MobileConfig, PwaConfig, ObservabilityConfig, TenancyConfig, NavigationConfig, StylesConfig, ThemeConfig } from '@wrnexus/styles';
import { ResolvedI18n, I18nConfig } from '@wrnexus/i18n';
import { StorageConfig } from '@wrnexus/uploader';
import { DevToolbarConfig, DevToolbarPlatformSnapshot, DevToolbarPanel } from '@wrnexus/dev-toolbar/types';
import { ClientRuntimeDefinition, PluginInput } from '@wrnexus/plugin';
import { DevToolbarCollector } from '@wrnexus/dev-toolbar/server';
import { IncomingMessage, ServerResponse, Server } from 'node:http';

/** Exit code a dev-server child uses to request a clean supervisor restart. */
declare const RESTART_EXIT_CODE = 97;

/**
 * HMR hub — tracks connected browser HMR sockets and broadcasts update events.
 *
 * Each open page holds one WebSocket to `/__wrnexus/hmr`. The in-process file
 * watcher (see index.ts) classifies a change and broadcasts a typed message:
 *
 *   { type: "css" }     -> the browser hot-swaps the stylesheet (no reload)
 *   { type: "reload" }  -> the browser asks for fresh HTML over the HMR socket
 *
 * Page/component/API/middleware/realtime changes invalidate their modules and
 * broadcast `reload` without closing the server or WebSocket. The browser asks
 * the same process for fresh HTML and performs a soft DOM morph.
 */
type HmrMessage = {
    type: "css";
    version: number;
} | {
    type: "reload";
    version: number;
};
/** Minimal shape of a Bun ServerWebSocket we rely on. */
interface Socket {
    send(data: string): unknown;
}
declare class HmrHub {
    private sockets;
    private version;
    add(ws: Socket): void;
    remove(ws: Socket): void;
    broadcastJson(message: unknown): void;
    broadcast(message: HmrMessage): void;
    get size(): number;
    css(): void;
    reload(): void;
}

/**
 * Shared request runtime used by BOTH the dev server and the production server.
 *
 * It owns the HTTP/WebSocket dispatch and the SSR document assembly, but knows
 * nothing about *how* modules or assets are produced — those come in via
 * `RuntimeDeps`. Dev wires in dynamic module loading + on-the-fly bundling;
 * prod wires in a static manifest + pre-built chunks on disk.
 */

/** A realtime module's `websocket` export: a bag of optional lifecycle hooks. */
type WsHandler = Record<string, (...args: any[]) => unknown>;
/**
 * Per-connection socket data. A socket is either an app realtime connection or
 * an internal HMR connection — discriminated by `kind`.
 */
type WsData = {
    kind: "realtime";
    handler: WsHandler;
} | {
    kind: "room";
    meta: RealtimeConnectMeta;
} | {
    kind: "hmr";
    baseUrl: string;
    headers: [string, string][];
};
type RouteModule$1 = Record<string, unknown>;
/** Serves framework-owned assets under `/__wrnexus/*` (islands, reactive, hmr). */
interface AssetServer {
    serve(pathname: string): Promise<Response | null>;
}
interface RuntimeDeps {
    mode: Mode;
    /** When true, inject the live-reload client into rendered pages. */
    hmr: boolean;
    router: Router;
    /** Load a route module by absolute path (dev: dynamic import; prod: manifest). */
    loadModule(file: string): Promise<RouteModule$1>;
    /** Resolve the ordered middleware chain. */
    getMiddleware(): Promise<Middleware[]>;
    /** Serve `/__wrnexus/*` assets. */
    assets: AssetServer;
    /** When true, inject the global stylesheet link into every page head. */
    hasStyles?: boolean;
    /** When true, inject the Wire UI stylesheet link (`/__wrnexus/ui.css`). */
    hasUi?: boolean;
    /** Production build combined theme + UI stylesheet. */
    hasFrameworkStyles?: boolean;
    /** App stylesheet already contains theme + UI CSS and is the only CSS request needed. */
    stylesIncludeFramework?: boolean;
    /** Resolved theme config: enables `/__wrnexus/theme.css` + `<html data-theme>`. */
    theme?: ResolvedTheme;
    /** Resolved i18n bundle: enables `ctx.t`, `<html lang>`, and `{t:key}` markers. */
    i18n?: ResolvedI18n;
    /** Small production stylesheets can be inlined to avoid a render-blocking request. */
    inlineStyles?: string;
    /** Production cache-busting version appended to framework asset URLs. */
    assetVersion?: string;
    /** Package browser runtimes resolved by the plugin system. */
    clientRuntimes?: ClientRuntimeDefinition[];
    /** Page navigation strategy. `document` disables same-origin link interception. */
    navigation?: {
        mode?: "client" | "document";
    };
    /** Raw HTML appended to every page head (e.g. CDN framework links). */
    head?: string;
    /** Global SEO defaults. */
    seo?: SeoConfig;
    mobile?: MobileConfig;
    pwa?: PwaConfig | false;
    /** Framework security headers and CORS policy. */
    security?: SecurityConfig;
    /** Built-in request tracing and Server-Timing policy. */
    observability?: ObservabilityConfig;
    /** Built-in tenant identity resolution. */
    tenancy?: TenancyConfig;
    /** Max request body size in bytes (413 above this). Default 10 MB. */
    maxBodyBytes?: number;
    /** HMR hub for browser live-update sockets (dev only). */
    hub?: HmrHub;
    /**
     * Cross-process realtime bus. When provided, room broadcasts/`toUser` sends are
     * bridged to it so they reach clients on every app process/instance sharing the
     * bus (use the Redis pub/sub driver). Enables realtime across multiple apps.
     */
    realtimeBus?: RealtimeBus;
    devToolbar?: {
        config: DevToolbarConfig;
        collector: DevToolbarCollector;
        root: string;
        platform?: DevToolbarPlatformSnapshot;
        panels?: DevToolbarPanel[];
    };
}
interface UpgradeServer {
    upgrade(req: Request, opts: {
        data: WsData;
    }): boolean;
    /** Bun's per-request socket peer address (used for the non-spoofable client IP). */
    requestIP?(req: Request): {
        address: string;
    } | null;
}
/** The subset of Bun's ServerWebSocket the runtime touches. */
interface Ws {
    data: WsData;
    send(data: string | Uint8Array): unknown;
    close(code?: number, reason?: string): void;
}
interface Handlers {
    fetch(req: Request, server: UpgradeServer): Promise<Response | undefined>;
    websocket: {
        open(ws: Ws): void;
        message(ws: Ws, message: string | Uint8Array): void;
        close(ws: Ws, code?: number, reason?: string): void;
        drain(ws: Ws): void;
    };
}
/** Build the fetch + websocket handlers from a set of dependencies. */
declare function createHandlers(deps: RuntimeDeps): Handlers;

/**
 * The multi-app **gateway** — serves several WrNexus apps behind one port and
 * routes each request to the right app by its `Host` header (domain). This is how
 * a monorepo becomes a multi-domain SaaS: `app-a.com` → apps/a, `app-b.com` → apps/b.
 *
 * Each app runs as its own **process** (full isolation — its own database
 * registry, pubsub, in-memory state), and the gateway is a thin host-based
 * reverse proxy for both HTTP and WebSocket. Apps talk to each other at runtime
 * via @wrnexus/pubsub (use the Redis driver so messages cross processes).
 */
type GatewayForwardAuth = ({
    url: string;
    app?: never;
    path?: never;
} | {
    app: string;
    path?: string;
    url?: never;
}) & {
    headers?: string[];
};
interface GatewayAuth {
    basic?: {
        user: string;
        pass: string;
    } | Array<{
        user: string;
        pass: string;
    }>;
    allowIps?: string[];
    forward?: GatewayForwardAuth;
}
interface GatewayApp {
    /** App id (for logs). */
    name: string;
    /** Path to the app root (the dir containing `app/` and wrnexus.config.ts). */
    dir: string;
    /** Host names routed to this app (e.g. ["localhost", "web.localhost"]). */
    domains: string[];
    publicOrigin?: string;
    /** Optional fixed internal port; otherwise assigned from the gateway port. */
    port?: number;
    /** Access control enforced at the edge for this app. */
    auth?: GatewayAuth;
}
/** Gateway-wide security controls, enforced for every app. */
interface GatewaySecurity {
    /** Reject requests whose Host matches no app (404) instead of routing to the first. */
    trustedHostsOnly?: boolean;
    /** Global rate limit by client IP (429 over the limit). */
    rateLimit?: {
        max: number;
        windowMs?: number;
    };
    /** Add baseline security headers to responses (only where the app didn't set them). */
    headers?: boolean;
    /** Set X-Forwarded-For/Host/Proto so apps see the real client. Default true. */
    forwardedHeaders?: boolean;
    /** Log each request (host → app, method, path, status). */
    accessLog?: boolean;
}
interface GatewayOptions {
    port?: number;
    hostname?: string;
    mode?: "development" | "production";
    environment?: string;
    hmr?: boolean;
    apps: GatewayApp[];
    security?: GatewaySecurity;
}
interface RunningGateway {
    port: number;
    url: string;
    stop(): void;
}
/** Boot every app as a child process, then route by Host on one gateway port. */
declare function startGateway(opts: GatewayOptions): Promise<RunningGateway>;

/**
 * @wrnexus/dev-server/prod — the production server (Point 4).
 *
 * Unlike dev, there is NO filesystem scan and NO on-the-fly bundling at runtime.
 * `wrnexus build` generates an entry that statically imports every route and
 * component module and hands them here as a manifest. We rebuild the (cheap)
 * route-matching tables from the raw patterns and run the exact same request
 * runtime as dev — just with production error pages and no live-reload client.
 */

type RouteModule = Record<string, unknown>;
interface ManifestRoute {
    /** URL pattern, e.g. `/users/[id]`. */
    raw: string;
    /** The statically-imported route module. */
    mod: RouteModule;
}
interface ProdManifest {
    pages: ManifestRoute[];
    api: ManifestRoute[];
    realtime: ManifestRoute[];
    middleware: Middleware[];
    /** Server-rendered components, statically imported and keyed by name. */
    components: {
        name: string;
        mod: RouteModule;
    }[];
    /** Named page layouts (from app/layouts/*.wrn). */
    layouts: {
        name: string;
        mod: RouteModule;
    }[];
}
interface ProductionPluginAsset {
    path: string;
    contentType: string;
    immutable?: boolean;
}
interface ProdOptions {
    /** Absolute path to the pre-built global stylesheet, if any. */
    stylesPath?: string;
    /** Small production stylesheet inlined into the document head. */
    inlineStyles?: string;
    /** `stylesPath` contains theme + UI + app CSS in cascade order. */
    stylesIncludeFramework?: boolean;
    /** Absolute path to the pre-built reactive runtime. */
    reactivePath?: string;
    /** Absolute path to the pre-built theme stylesheet (`theme.css`). */
    themePath?: string;
    /** Absolute path to the pre-built theme runtime (`theme.js`). */
    themeJsPath?: string;
    /** Resolved theme config: enables `<html data-theme>` + `theme.css` link. */
    theme?: ResolvedTheme;
    /** Absolute path to the pre-built Wire UI stylesheet (`ui.css`). */
    uiCssPath?: string;
    /** Combined production theme + Wire UI stylesheet. */
    frameworkCssPath?: string;
    /** Pre-built `window.__wireSchemas = {...}` script for client validation. */
    schemasJs?: string;
    /** Resolved i18n bundle (default lang + locale messages). */
    i18n?: ResolvedI18n;
    /** Default database connection (driver + url); enables `getDb()`. */
    db?: {
        driver: string;
        url: string;
    };
    /** Named databases, reached with `getDb("<name>")`. */
    databases?: Record<string, {
        driver: string;
        url: string;
    }>;
    /**
     * Absolute path to the default db's migrations bundled into the build
     * (`dist/migrations`). When set, they are applied on startup — like dev.
     */
    migrationsDir?: string;
    /** Bundled migrations dirs for named dbs (name → `dist/db/<name>/migrations`). */
    databaseMigrationDirs?: Record<string, string>;
    /**
     * Auto-apply bundled migrations on server startup (default: true). Set false
     * for deploys that migrate in a separate release step (e.g. multiple instances
     * behind a load balancer, where you migrate once before rolling out).
     */
    autoMigrate?: boolean;
    /** Realtime scaling: bridge room broadcasts over Redis across app processes. */
    realtime?: {
        scale?: boolean;
        redisUrl?: string;
    };
    /** File-upload storage: named stores (local dir / S3). Local dirs resolve against cwd. */
    storage?: StorageConfig;
    /** Cache-busting version appended to framework asset URLs. */
    assetVersion?: string;
    /** Package browser runtimes already emitted by the production build. */
    clientRuntimes?: ClientRuntimeDefinition[];
    /** Public URL to emitted package asset metadata. */
    pluginAssets?: Record<string, ProductionPluginAsset>;
    /** Absolute path to copied public assets, if any. */
    publicDir?: string;
    /** Raw HTML appended to every page head. */
    head?: string;
    /** Global SEO defaults. */
    seo?: SeoConfig;
    mobile?: MobileConfig;
    pwa?: PwaConfig | false;
    /** Framework security headers and CORS policy. */
    security?: SecurityConfig;
    /** Built-in request tracing and Server-Timing policy. */
    observability?: ObservabilityConfig;
    /** Built-in tenant identity resolution. */
    tenancy?: TenancyConfig;
    /** Page navigation strategy. */
    navigation?: NavigationConfig;
    port?: number;
    hostname?: string;
    maxBodyBytes?: number;
}
/**
 * Build the portable request handler from a precompiled manifest — a
 * WinterCG-style `fetch(request) => Response` plus the websocket handlers, with
 * NO server bound. This is the deployment-adapter seam: `createProductionServer`
 * wraps it in `Bun.serve`, `serveNode` bridges it onto `node:http`, and edge or
 * serverless targets can call `fetch` directly.
 */
declare function createProductionHandlers(manifest: ProdManifest, opts: ProdOptions): ReturnType<typeof createHandlers>;
/** Start the production server on Bun from a precompiled manifest. */
declare function createProductionServer(manifest: ProdManifest, opts: ProdOptions): Promise<Bun.Server<WsData>>;

/**
 * node:http adapter — bridge a WinterCG `fetch(request) => Response` handler
 * onto a Node HTTP server, with no external dependencies. Converts a Node
 * `IncomingMessage` into a web `Request` and writes a web `Response` back into a
 * `ServerResponse` (preserving multiple `Set-Cookie` headers).
 *
 * Caveat: the production handler uses Bun-native APIs (Bun.file for assets,
 * Bun.serve for websockets, Bun.SQL / bun:sqlite for the database), so running
 * the FULL app under plain Node needs Bun-compatible globals. This adapter is
 * for WinterCG hosts and for embedding the handler behind an existing
 * `node:http` server; the Request/Response conversion itself is fully portable.
 */

type FetchHandler = (req: Request) => Response | undefined | Promise<Response | undefined>;
/** Convert a Node IncomingMessage into a web Request (buffers the body). */
declare function toRequest(req: IncomingMessage, opts?: {
    origin?: string;
}): Promise<Request>;
/** Write a web Response into a Node ServerResponse. */
declare function writeResponse(res: ServerResponse, response: Response): Promise<void>;
/** A `node:http` request listener that dispatches to a fetch handler. */
declare function nodeListener(handler: FetchHandler, opts?: {
    origin?: string;
}): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
/** Create and start a `node:http` server for a fetch handler. */
declare function serveNode(handler: FetchHandler, opts?: {
    port?: number;
    hostname?: string;
}): Promise<Server>;

/**
 * @wrnexus/dev-server — the development HTTP + WebSocket server.
 *
 * Thin Bun.serve wrapper around the shared runtime (runtime.ts). Dynamic module
 * loading and targeted cache invalidation keep page/component/API edits inside
 * the running process while the HMR socket morphs fresh HTML into the browser.
 */

interface ServeOptions {
    appDir: string;
    port?: number;
    hostname?: string;
    mode?: Mode;
    /** Inject the live-reload client (defaults to true in development). */
    hmr?: boolean;
    appConfig?: Record<string, unknown>;
    /** Resolved absolute path to the global CSS entry, or null. */
    styleEntry?: string | null;
    /** Custom styles config (e.g. a Tailwind/PostCSS processor). */
    stylesConfig?: StylesConfig;
    /** Raw HTML appended to every page head (from wrnexus.config.ts). */
    head?: string;
    /** Global SEO defaults. */
    seo?: SeoConfig;
    /** Framework security headers and CORS policy. */
    security?: SecurityConfig;
    /** Design-token theme config (merged over the built-in light/dark). */
    theme?: ThemeConfig;
    /** i18n config (default language + supported locales). */
    i18n?: I18nConfig;
    /** Default database connection (driver + url). Enables `getDb()` and dev auto-migrate. */
    db?: {
        driver: string;
        url: string;
    };
    /** Named databases, reached with `getDb("<name>")`; migrations under app/db/<name>/. */
    databases?: Record<string, {
        driver: string;
        url: string;
    }>;
    /** Realtime scaling: bridge room broadcasts over Redis across app processes. */
    realtime?: {
        scale?: boolean;
        redisUrl?: string;
    };
    /** File-upload storage: named stores (local dir / S3), reached with `getStore()`. */
    storage?: StorageConfig;
    mobile?: MobileConfig;
    pwa?: PwaConfig | false;
    devToolbar?: boolean | DevToolbarConfig;
    plugins?: PluginInput;
    observability?: ObservabilityConfig;
    tenancy?: TenancyConfig;
    navigation?: NavigationConfig;
}
interface RunningServer {
    port: number;
    hostname: string;
    url: string;
    router: Router;
    stop(): void;
}
declare function startServer(opts: ServeOptions): Promise<RunningServer>;

export { type AssetServer, type FetchHandler, type GatewayApp, type GatewayAuth, type GatewayOptions, type GatewaySecurity, RESTART_EXIT_CODE, type RunningGateway, type RunningServer, type RuntimeDeps, type ServeOptions, type WsData, createHandlers, createProductionHandlers, createProductionServer, nodeListener, serveNode, startGateway, startServer, toRequest, writeResponse };
```

---

## @wrnexus/dev-toolbar

Documentation URL: https://wrnexusjs.dev/packages/dev-toolbar

# @wrnexus/dev-toolbar

Development-only page quality toolbar for WRNexusJS.

## Features

- Runtime, resource and unhandled promise error capture
- Accessibility, SEO, image, media, color, HTML, form, link, responsive and security checks
- Performance and network observations
- Element highlighting and issue filtering
- Server-side issue collector
- Development-only asset strings for direct serving by `@wrnexus/dev-server`
- Safe open-in-editor helper

## Dev-server integration

Serve `DEV_TOOLBAR_RUNTIME` at `/__wrnexus/dev-toolbar.js` and `DEV_TOOLBAR_CSS` at `/__wrnexus/dev-toolbar.css`, then inject this before `</body>` in development:

```html
<script type="module" src="/__wrnexus/dev-toolbar.js" data-wrnexus-dev-toolbar></script>
```

The browser runtime exposes `window.__wrnexusDevToolbar`.

### Exported TypeScript declarations

```ts
export { DevToolbarCategory, DevToolbarClientApi, DevToolbarConfig, DevToolbarElementTarget, DevToolbarFix, DevToolbarIssue, DevToolbarMetrics, DevToolbarPageReport, DevToolbarPanel, DevToolbarPlatformSnapshot, DevToolbarServerMessage, DevToolbarSeverity, DevToolbarSourceLocation } from './types.js';
export { DEV_TOOLBAR_RULES, DevToolbarRule, DevToolbarRuleContext, accessibilityRules, accessibleName, colorRules, contrastRatio, createFingerprint, createIssue, effectiveBackground, formRules, getStableSelector, htmlRules, imageRules, isVisible, linkRules, luminance, mediaRules, parseRgb, parseSource, performanceRules, responsiveRules, runDevToolbarRules, securityRules, seoRules } from './rules/index.js';
export { DevToolbarApp, DevToolbarCollector, DevToolbarIssueListener, DevToolbarRegistry, DevToolbarRouteOptions, OpenEditorOptions, OpenEditorRequest, buildEditorCommand, createDevToolbarCollector, createDevToolbarRegistry, createServerIssue, handleDevToolbarRoute, issueFromError, openInEditor, resolveEditorFile, serializeDevToolbarJson } from './server/index.js';
export { DEV_TOOLBAR_CSS, DEV_TOOLBAR_RUNTIME } from './client/index.js';
```

---

## @wrnexus/encryption

Documentation URL: https://wrnexusjs.dev/packages/encryption

# @wrnexus/encryption

> Dependency-free crypto helpers for WrNexus: authenticated symmetric encryption (AES-256-GCM), hashing, and HMAC signing.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

This package provides small, focused cryptographic primitives for server-side use: encrypting secrets/tokens/database fields at rest with AES-256-GCM, deriving keys from passwords via PBKDF2, computing SHA-256 digests, and signing/verifying payloads with HMAC-SHA256. It is built entirely on the standard **Web Crypto API** (`crypto.subtle`) plus `btoa`/`atob` and `TextEncoder`/`TextDecoder` — no third-party dependencies. Reach for it whenever you need to protect sensitive values or verify webhook signatures. All functions are `async` (Web Crypto is promise-based).

## Installation

```bash
bun add @wrnexus/encryption
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported).

## API

All keys are exchanged as **base64 strings** and all digests/signatures as **hex strings**.

| Export        | Signature                                                               | Description                                                                                                           |
| ------------- | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `generateKey` | `() => Promise<string>`                                                 | Generate a random 256-bit AES key, base64-encoded. Store it as a secret.                                              |
| `deriveKey`   | `(password: string, salt: string) => Promise<string>`                   | Derive a base64 AES-256 key from a password + salt using PBKDF2 (100,000 iterations, SHA-256).                        |
| `encrypt`     | `(plaintext: string, key: string) => Promise<string>`                   | AES-256-GCM encrypt a string. Returns base64 of `iv(12 bytes) ‖ ciphertext+tag`. A fresh random IV is used each call. |
| `decrypt`     | `(payload: string, key: string) => Promise<string>`                     | Decrypt a value produced by `encrypt`. Throws if the key is wrong or the data was tampered with.                      |
| `sha256`      | `(data: string) => Promise<string>`                                     | SHA-256 hex digest of a string (e.g. content hashing, dedup keys).                                                    |
| `hmacSign`    | `(data: string, secret: string) => Promise<string>`                     | HMAC-SHA256 hex signature of `data` with `secret` (e.g. signing webhooks).                                            |
| `hmacVerify`  | `(data: string, secret: string, signature: string) => Promise<boolean>` | Constant-time verify of an HMAC-SHA256 hex signature.                                                                 |

Notes:

- `generateKey` produces a 32-byte (256-bit) key via `crypto.getRandomValues`.
- `encrypt`/`decrypt` require a base64-encoded 256-bit key; anything else throws `"Encryption key must be a base64 256-bit key"`.
- `decrypt` throws `"Invalid ciphertext"` if the payload is shorter than the 12-byte IV, and the underlying Web Crypto call throws on any authentication (tag) mismatch.
- `hmacVerify` compares in constant time (length check plus XOR accumulation) to avoid timing leaks.

## Usage

Symmetric encryption of a secret at rest:

```ts
import { generateKey, encrypt, decrypt } from "@wrnexus/encryption";

const key = await generateKey(); // store this safely (env/secret manager)

const box = await encrypt("card #1234", key); // opaque base64 string, safe to persist
const plain = await decrypt(box, key); // "card #1234"
```

Deriving a key from a user password instead of a random key:

```ts
import { deriveKey, encrypt } from "@wrnexus/encryption";

const key = await deriveKey("correct horse battery staple", "per-user-salt");
const box = await encrypt("secret note", key);
```

Hashing and webhook signature verification:

```ts
import { sha256, hmacSign, hmacVerify } from "@wrnexus/encryption";

const digest = await sha256("some content"); // 64-char hex string

const signature = await hmacSign(rawBody, webhookSecret);
const ok = await hmacVerify(rawBody, webhookSecret, incomingSignatureHeader);
if (!ok) throw new Error("Invalid webhook signature");
```

## Requirements / Notes

- **Bun-only.** Relies on the Web Crypto API (`crypto.subtle`, `crypto.getRandomValues`) and the global `btoa`/`atob`, `TextEncoder`/`TextDecoder` — all available in Bun's runtime.
- **No dependencies.** The package has an empty dependency set; nothing is bundled beyond standard runtime APIs.
- Algorithms: AES-256-GCM (encryption), PBKDF2 with 100k SHA-256 iterations (key derivation), SHA-256 (digest), HMAC-SHA256 (signing).
- Keep generated/derived keys and HMAC secrets out of source control; treat them as first-class secrets.

### Exported TypeScript declarations

```ts
interface EncryptionKey {
    id: string;
    secret: string;
    active?: boolean;
    createdAt?: number;
}
interface EncryptionKeyring {
    active(): EncryptionKey;
    get(id: string): EncryptionKey | undefined;
    keys(): EncryptionKey[];
    rotate(key?: EncryptionKey): Promise<EncryptionKey>;
    remove(id: string): boolean;
}
declare function createKeyring(initial: EncryptionKey[]): EncryptionKeyring;
/** Versioned payload: `wrn1.<key-id>.<aes-gcm-payload>`. */
declare function seal(plaintext: string, keyring: EncryptionKeyring): Promise<string>;
declare function open(sealed: string, keyring: EncryptionKeyring): Promise<string>;
declare function sealedKeyId(sealed: string): string | null;
declare function needsRotation(sealed: string, keyring: EncryptionKeyring): boolean;

/**
 * @wrnexus/encryption — authenticated symmetric encryption (AES-256-GCM) via
 * WebCrypto, dependency-free. Use it to encrypt secrets, tokens, or database
 * fields at rest.
 *
 *   const key = await generateKey();                 // store this safely
 *   const box = await encrypt("card #1234", key);    // opaque base64 string
 *   const plain = await decrypt(box, key);           // "card #1234"
 *
 * A key derived from a password (PBKDF2) is also supported via `deriveKey`.
 */
/** SHA-256 hex digest of a string (e.g. content hashing, dedup keys). */
declare function sha256(data: string): Promise<string>;
/** HMAC-SHA256 hex signature of `data` with `secret` (e.g. signing webhooks). */
declare function hmacSign(data: string, secret: string): Promise<string>;
/** Constant-time verify of an HMAC-SHA256 signature. */
declare function hmacVerify(data: string, secret: string, signature: string): Promise<boolean>;
/** Generate a random 256-bit key, base64-encoded. Store it as a secret. */
declare function generateKey(): Promise<string>;
/**
 * Encrypt a string. Output is base64 of `iv(12) || ciphertext+tag`, safe to
 * store or transmit. Each call uses a fresh random IV.
 */
declare function encrypt(plaintext: string, key: string): Promise<string>;
/** Decrypt a value produced by `encrypt`. Throws if the key is wrong or data tampered. */
declare function decrypt(payload: string, key: string): Promise<string>;
/** Derive a base64 AES key from a password + salt (PBKDF2, 100k iterations). */
declare function deriveKey(password: string, salt: string): Promise<string>;

export { type EncryptionKey, type EncryptionKeyring, createKeyring, decrypt, deriveKey, encrypt, generateKey, hmacSign, hmacVerify, needsRotation, open, seal, sealedKeyId, sha256 };
```

---

## @wrnexus/helpers

Documentation URL: https://wrnexusjs.dev/packages/helpers

# @wrnexus/helpers

Safe convenience helpers for common WrNexus application flows. The package uses
standard `Context`, `URL`, and `Response` values and has no runtime dependency beyond
`@wrnexus/core`.

## Installation

```bash
bun add @wrnexus/helpers
```

The package is private, so the machine must be authenticated to the `wrnexus` npm
organization.

## Usage

### Redirect an unauthenticated forward-auth request

The gateway calls an SSO verifier on a different URL from the original application.
These helpers reconstruct the original URL from the gateway headers and safely place it
in the login redirect:

```ts
import type { Context } from "@wrnexus/core";
import { redirectToLogin } from "@wrnexus/helpers";

export const GET = async (ctx: Context) => {
  if (await hasValidSession(ctx)) {
    return new Response(null, { status: 204 });
  }

  return redirectToLogin(ctx, "/login", {
    allowedHosts: ["admin.localhost:3000", "reports.localhost:3000"],
  });
};
```

This creates a response such as:

```text
Location: http://sso.localhost:3000/login?returnTo=http%3A%2F%2Fadmin.localhost%3A3000%2F
```

Always list the application hosts that are valid redirect destinations. Forwarded host
headers are rejected when `allowedHosts` is absent or does not match, preventing an open
redirect.

The SSO hostname is the login destination, not an `allowedHosts` entry. For example,
when protecting `admin.localhost:3000`, keep `admin.localhost:3000` in the allowlist even
though the verifier runs at `sso.localhost:3000`. WRNexus preserves both hosts across a
nested gateway request.

### Support dynamic tenant domains

```ts
import type { Context } from "@wrnexus/core";
import { getOriginalRequestOrigin, redirectToLogin } from "@wrnexus/helpers";

export const GET = async (ctx: Context) => {
  const allowedHosts = (host: string) => host === "example.test" || host.endsWith(".example.test");

  console.info("Authentication requested by", getOriginalRequestOrigin(ctx, { allowedHosts }));
  return redirectToLogin(ctx, "https://auth.example.test/login", {
    allowedHosts,
    returnToParam: "continue",
    status: 303,
  });
};
```

## API

- `getOriginalRequestUrl(ctx, options): URL` — reconstruct the gateway URL.
- `getOriginalRequestOrigin(ctx, options): string` — return only its origin.
- `getOriginalRequestPath(ctx): string` — return its path and query string.
- `getOriginalRequestMethod(ctx): string` — return its HTTP method.
- `redirectToLogin(ctx, loginUrl, options): Response` — create a login redirect with an
  encoded `returnTo` parameter.

For direct requests without gateway headers, URL helpers use `ctx.url`.

### Exported TypeScript declarations

```ts
import { Context } from '@wrnexus/core';

declare function appOrigin(appName: string): string;
declare function appUrl(appName: string, path?: string): string;
declare function currentAppName(): string | undefined;
declare function currentAppOrigin(): string | undefined;
declare function workspaceAppOrigins(): Readonly<Record<string, string>>;
/** Shared DNS suffix for configured workspace apps (for example `staging.example.com`). */
declare function workspaceRootDomain(): string;

interface RetryOptions {
    attempts?: number;
    minDelayMs?: number;
    maxDelayMs?: number;
    factor?: number;
    jitter?: number;
    signal?: AbortSignal;
    retryIf?: (error: unknown, attempt: number) => boolean | Promise<boolean>;
    onRetry?: (error: unknown, attempt: number, delayMs: number) => void | Promise<void>;
}
declare function backoffDelay(attempt: number, options?: Pick<RetryOptions, "minDelayMs" | "maxDelayMs" | "factor" | "jitter">): number;
declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
declare function retry<T>(operation: (attempt: number, signal?: AbortSignal) => Promise<T>, options?: RetryOptions): Promise<T>;
declare function withTimeout<T>(promise: Promise<T>, timeoutMs: number, message?: string, signal?: AbortSignal): Promise<T>;
declare function stableStringify(value: unknown): string;
declare function safeJsonParse<T>(value: string, fallback: T): T;
declare function clamp(value: number, min: number, max: number): number;
declare function once<T extends (...args: any[]) => any>(fn: T): T;

/**
 * @wrnexus/helpers — safe conveniences for common WrNexus application flows.
 *
 * Helpers stay small and composable. They accept the standard WrNexus Context
 * and return web-platform values such as URL and Response.
 */

type RequestContext = Pick<Context, "req" | "url">;
type AllowedHosts = readonly string[] | ReadonlySet<string> | ((host: string, ctx: RequestContext) => boolean);
interface OriginalRequestOptions {
    /**
     * Hosts that the application permits as redirect destinations. This is
     * required when a proxy supplied X-Forwarded-Host is present.
     */
    allowedHosts?: AllowedHosts;
}
interface LoginRedirectOptions extends OriginalRequestOptions {
    /** Query parameter that receives the original absolute URL. */
    returnToParam?: string;
    /** Browser redirect status. Defaults to 302. */
    status?: 301 | 302 | 303 | 307 | 308;
}
/** Get the original path and query string seen by the gateway. */
declare function getOriginalRequestPath(ctx: RequestContext): string;
/** Get the original HTTP method seen by the gateway. */
declare function getOriginalRequestMethod(ctx: RequestContext): string;
/**
 * Reconstruct the absolute URL that reached the gateway.
 *
 * Forwarded hosts are never trusted implicitly: pass allowedHosts when this is
 * used behind the WrNexus gateway. Direct requests fall back to ctx.url.
 */
declare function getOriginalRequestUrl(ctx: RequestContext, options?: OriginalRequestOptions): URL;
/** Get the original request origin, for example http://admin.localhost:3000. */
declare function getOriginalRequestOrigin(ctx: RequestContext, options?: OriginalRequestOptions): string;
/**
 * Redirect to a login page with the original absolute URL encoded as returnTo.
 * Relative login URLs resolve against the current app (normally the SSO app).
 */
declare function redirectToLogin(ctx: RequestContext, loginUrl: string | URL, options?: LoginRedirectOptions): Response;

export { type AllowedHosts, type LoginRedirectOptions, type OriginalRequestOptions, type RequestContext, type RetryOptions, appOrigin, appUrl, backoffDelay, clamp, currentAppName, currentAppOrigin, getOriginalRequestMethod, getOriginalRequestOrigin, getOriginalRequestPath, getOriginalRequestUrl, once, redirectToLogin, retry, safeJsonParse, sleep, stableStringify, withTimeout, workspaceAppOrigins, workspaceRootDomain };
```

---

## @wrnexus/i18n

Documentation URL: https://wrnexusjs.dev/packages/i18n

# @wrnexus/i18n

> Per-request translations plus locale-aware number, date, and currency formatting for WrNexus apps.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

`@wrnexus/i18n` loads locale files from `app/locales/<lang>.json`, resolves the
active language for each request (cookie → `Accept-Language` → default), and
builds a `t(key, params)` translator used both in server code and in `.wrn`
views. It also ships Intl-based formatting helpers and a tiny client runtime that
wires up a language switcher. Translation lookup, language resolution, and HTML
marker rewriting run server-side; only the small `I18N_RUNTIME` snippet runs in
the browser.

## Installation

```bash
bun add @wrnexus/i18n
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported).

## API

### Loading & resolving

| Export        | Signature                                                                                          | Description                                                                                                                             |
| ------------- | -------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `loadLocales` | `(dir: string) => Record<string, Messages>`                                                        | Reads every `<lang>.json` in `dir` into a `{ lang: messages }` map. Missing dir → `{}`; a bad file is warned and skipped.               |
| `resolveI18n` | `(messages: Record<string, Messages>, config?: I18nConfig) => ResolvedI18n`                        | Merges loaded messages + config into a resolved bundle (default lang, supported langs, messages).                                       |
| `resolveLang` | `(i18n: ResolvedI18n, cookieValue: string \| undefined, acceptLanguage: string \| null) => string` | Picks the active language: matching cookie → best `Accept-Language` tag (falls back to base tag, e.g. `en-US` → `en`) → `i18n.default`. |
| `makeT`       | `(i18n: ResolvedI18n, lang: string) => TFunction`                                                  | Builds a translator resolving current language → default → the key itself, with `{param}` interpolation.                                |

### Types & constants

| Export         | Kind        | Notes                                                                          |
| -------------- | ----------- | ------------------------------------------------------------------------------ |
| `Messages`     | `type`      | `Record<string, unknown>` — a locale's messages (supports nested/dotted keys). |
| `I18nConfig`   | `interface` | `{ default?: string; locales?: string[] }`.                                    |
| `ResolvedI18n` | `interface` | `{ default: string; langs: string[]; messages: Record<string, Messages> }`.    |
| `LANG_COOKIE`  | `const`     | `"wire-lang"` — the cookie the language is read from / written to.             |
| `I18N_JS_HREF` | `const`     | `"/__wrnexus/i18n.js"` — URL the client runtime is served at.                  |

### HTML & client runtime

| Export           | Signature                                      | Description                                                                                                                                                                                                                 |
| ---------------- | ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `translateHtml`  | `(html: string, t: TFunction) => string`       | Rewrites markers in rendered HTML: `t:<attr>="key"` → `<attr>="<translation>"` (attribute-escaped) and `<tag data-t="key">…</tag>` → element text becomes the translation (HTML-escaped). No-op unless a marker is present. |
| `renderI18nData` | `(i18n: ResolvedI18n, lang: string) => string` | JS snippet setting `window.__wireI18n = { lang, langs, default }` for the client switcher.                                                                                                                                  |
| `I18N_RUNTIME`   | `const string`                                 | Browser IIFE that binds `[data-wire-lang-set="es"]` clicks and `select[data-wire-lang]` changes to set the `wire-lang` cookie and reload. Exposes `window.__wireLang.set(lang)`.                                            |

### Formatting helpers (re-exported from `./format.ts`)

| Export               | Signature                                                                                         | Example                                        |
| -------------------- | ------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
| `formatNumber`       | `(value: number, lang: string, options?: Intl.NumberFormatOptions) => string`                     | `1234.5 → "1,234.5"`                           |
| `formatCurrency`     | `(value: number, currency: string, lang: string) => string`                                       | `9.99, "USD" → "$9.99"`                        |
| `formatDate`         | `(value: Date \| number \| string, lang: string, options?: Intl.DateTimeFormatOptions) => string` | defaults to `{ dateStyle: "medium" }`          |
| `formatRelativeTime` | `(value: number, unit: Intl.RelativeTimeFormatUnit, lang: string) => string`                      | `-3, "day" → "3 days ago"` (`numeric: "auto"`) |
| `plural`             | `(count: number, forms: Partial<Record<Intl.LDMLPluralRule, string>>, lang: string) => string`    | picks CLDR form; `#` is replaced by `count`    |

## Usage

### Server: load, resolve, translate

```ts
import {
  loadLocales,
  resolveI18n,
  resolveLang,
  makeT,
  translateHtml,
  LANG_COOKIE,
} from "@wrnexus/i18n";

// app/locales/en.json, app/locales/es.json
const messages = loadLocales("app/locales");
const i18n = resolveI18n(messages, { default: "en", locales: ["en", "es"] });

// Per request:
const lang = resolveLang(i18n, req.cookies?.[LANG_COOKIE], req.headers.get("accept-language"));
const t = makeT(i18n, lang);

t("nav.home"); // dotted key → "Home"
t("greeting", { name: "Ada" }); // "Hello, {name}" → "Hello, Ada"

// After rendering a .wrn view, resolve translation markers in the HTML:
const finalHtml = translateHtml(renderedHtml, t);
```

`app/locales/en.json`:

```json
{
  "nav": { "home": "Home" },
  "greeting": "Hello, {name}"
}
```

### Views: translation markers

```html
<h1 data-t="nav.home">Home</h1>
<input t:placeholder="search.placeholder" />
```

`translateHtml` replaces the element text for `data-t` and the attribute value for
any `t:<attr>` (e.g. `t:placeholder`, `t:aria-label`).

### Client: language switcher

```ts
import { renderI18nData, I18N_RUNTIME, I18N_JS_HREF } from "@wrnexus/i18n";

// In the document <head>:
const head = `
  <script>${renderI18nData(i18n, lang)}</script>
  <script src="${I18N_JS_HREF}"></script>
`;

// Serve I18N_RUNTIME at I18N_JS_HREF; then in markup:
// <button data-wire-lang-set="es">Español</button>
// <select data-wire-lang>…</select>
```

### Formatting

```ts
import {
  formatNumber,
  formatCurrency,
  formatDate,
  formatRelativeTime,
  plural,
} from "@wrnexus/i18n";

formatNumber(1234.5, lang); // "1,234.5"
formatCurrency(9.99, "USD", lang); // "$9.99"
formatDate(Date.now(), lang); // "Jul 4, 2026"
formatRelativeTime(-3, "day", lang); // "3 days ago"
plural(2, { one: "# item", other: "# items" }, lang); // "2 items"
```

## Configuration

`resolveI18n` accepts an `I18nConfig`:

- `default` — fallback language; used when nothing else matches. Ignored if it has
  no loaded messages, in which case the first supported language is used.
- `locales` — explicit supported-language list; defaults to the loaded locale names.

Language resolution order at request time (`resolveLang`): a supported `wire-lang`
cookie value → the first matching `Accept-Language` tag (or its base subtag) → the
resolved default.

## Requirements / Notes

- **Bun-only.** Locale loading uses `node:fs` (`existsSync`, `readdirSync`,
  `readFileSync`) and `node:path`; formatting relies on the platform `Intl` APIs.
- Works with [`@wrnexus/core`](../core) — `TFunction` (the `t(key, params)` type)
  comes from core, and the resolved translator is exposed as `ctx.t` / `ctx.lang`
  in request handling.
- Nested message objects are supported: keys are looked up whole first, then split
  on `.` to walk the object tree.

### Exported TypeScript declarations

```ts
import { TFunction } from '@wrnexus/core';

/**
 * Locale-aware formatting helpers (Intl-based) + pluralization. Pair with the
 * request language (`ctx.lang`) so numbers, dates, and currencies render right
 * for each user.
 */
/** Format a number for a locale (e.g. 1234.5 → "1,234.5"). */
declare function formatNumber(value: number, lang: string, options?: Intl.NumberFormatOptions): string;
/** Format a currency amount (e.g. 9.99, "USD" → "$9.99"). */
declare function formatCurrency(value: number, currency: string, lang: string): string;
/** Format a date/timestamp for a locale. */
declare function formatDate(value: Date | number | string, lang: string, options?: Intl.DateTimeFormatOptions): string;
/** Relative time, e.g. -3 days → "3 days ago" (localized). */
declare function formatRelativeTime(value: number, unit: Intl.RelativeTimeFormatUnit, lang: string): string;
/**
 * Pick a plural form for `count` in `lang` using CLDR rules, e.g.
 * `plural(n, { one: "1 item", other: "# items" }, lang)` — "#" is replaced by n.
 */
declare function plural(count: number, forms: Partial<Record<Intl.LDMLPluralRule, string>>, lang: string): string;

declare function flattenMessages(messages: Messages, prefix?: string, output?: Record<string, string>): Record<string, string>;
declare function localeFallbacks(locale: string, fallback?: string): string[];
declare function translationCoverage(i18n: ResolvedI18n): Record<string, {
    translated: number;
    total: number;
    percentage: number;
    missing: string[];
    extra: string[];
}>;
interface LocaleFormatter {
    number(value: number, options?: Intl.NumberFormatOptions): string;
    currency(value: number, currency: string, options?: Omit<Intl.NumberFormatOptions, "style" | "currency">): string;
    date(value: Date | number | string, options?: Intl.DateTimeFormatOptions): string;
    relative(value: number, unit: Intl.RelativeTimeFormatUnit, options?: Intl.RelativeTimeFormatOptions): string;
    list(values: string[], options?: Intl.ListFormatOptions): string;
}
declare function createLocaleFormatter(locale: string, timeZone?: string): LocaleFormatter;
/** Lightweight plural templates: `{count, plural, one {# item} other {# items}}`. */
declare function formatMessage(template: string, params: Record<string, string | number>, locale: string): string;

/**
 * @wrnexus/i18n — translations for pages and API responses.
 *
 * Locales live in `app/locales/<lang>.json`. Per request the active language is
 * resolved from the `wire-lang` cookie, then Accept-Language, then the default.
 * `ctx.t(key, params)` translates on the server; in `.wrn` views `{t:key}` and
 * `t:attr="key"` markers are resolved by `translateHtml` before the HTML is sent.
 */

type Messages = Record<string, unknown>;
/** Load `<dir>/<lang>.json` files into a `{ lang: messages }` map. */
declare function loadLocales(dir: string): Record<string, Messages>;
interface I18nConfig {
    /** Default language, used as the fallback and when nothing else matches. */
    default?: string;
    /** Explicit set of supported languages (defaults to the loaded locale names). */
    locales?: string[];
}
interface ResolvedI18n {
    default: string;
    langs: string[];
    messages: Record<string, Messages>;
}
declare const LANG_COOKIE = "wire-lang";
declare const I18N_JS_HREF = "/__wrnexus/i18n.js";
/** Merge loaded locale messages + config into a resolved i18n bundle. */
declare function resolveI18n(messages: Record<string, Messages>, config?: I18nConfig): ResolvedI18n;
/** Build a `t()` for a language: current → default → the key itself. */
declare function makeT(i18n: ResolvedI18n, lang: string): TFunction;
/** Resolve the active language from a cookie, Accept-Language, then default. */
declare function resolveLang(i18n: ResolvedI18n, cookieValue: string | undefined, acceptLanguage: string | null): string;
/**
 * Resolve translation markers in rendered HTML:
 *   t:<attr>="key"        → <attr>="<translation>"   (e.g. t:placeholder, t:aria-label)
 *   <tag data-t="key">…</tag> → element text becomes the translation
 * Only runs when the HTML actually contains a marker.
 */
declare function translateHtml(html: string, t: TFunction): string;
/** `window.__wireI18n = { lang, langs }` for the client language switcher. */
declare function renderI18nData(i18n: ResolvedI18n, lang: string): string;
/**
 * Client runtime: binds `[data-wire-lang-set="es"]` elements to set the
 * `wire-lang` cookie and reload, so the server re-renders in the new language.
 */
declare const I18N_RUNTIME: string;

export { I18N_JS_HREF, I18N_RUNTIME, type I18nConfig, LANG_COOKIE, type LocaleFormatter, type Messages, type ResolvedI18n, createLocaleFormatter, flattenMessages, formatCurrency, formatDate, formatMessage, formatNumber, formatRelativeTime, loadLocales, localeFallbacks, makeT, plural, renderI18nData, resolveI18n, resolveLang, translateHtml, translationCoverage };
```

---

## @wrnexus/jwt

Documentation URL: https://wrnexusjs.dev/packages/jwt

# @wrnexus/jwt

> Dependency-free JSON Web Tokens (HS256) via Web Crypto, plus a bearer-token auth middleware for WrNexus.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

`@wrnexus/jwt` signs and verifies stateless JSON Web Tokens using the **HS256**
(HMAC-SHA-256) algorithm. It has no runtime dependencies — signing and
verification are implemented directly on the standard **Web Crypto** API
(`crypto.subtle`), which Bun provides natively. It runs server-side and pairs
with the session-based auth in `@wrnexus/core`, giving you a stateless option
for API and mobile clients. Reach for it when you need bearer-token auth rather
than cookie sessions.

## Installation

```bash
bun add @wrnexus/jwt
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported).

## API

Single entry point (`@wrnexus/jwt`). All functions are async and return Promises.

| Export                                  | Kind      | Description                                                     |
| --------------------------------------- | --------- | --------------------------------------------------------------- |
| `signJwt(payload, secret, options?)`    | function  | Sign claims into an HS256 token string.                         |
| `verifyJwt<T>(token, secret, options?)` | function  | Verify a token and return its claims, or throw.                 |
| `jwtAuth(options)`                      | function  | Middleware that verifies a bearer JWT and sets `ctx.user`.      |
| `JwtError`                              | class     | Error thrown on any signature/payload/expiry failure.           |
| `JwtClaims`                             | interface | Claims shape (`sub`, `iat`, `exp`, `nbf`, plus arbitrary keys). |
| `SignOptions`                           | interface | Options for `signJwt`.                                          |
| `JwtAuthOptions`                        | interface | Options for `jwtAuth`.                                          |

### `signJwt(payload, secret, options?)`

```ts
function signJwt(payload: JwtClaims, secret: string, options?: SignOptions): Promise<string>;
```

Signs `payload` with `secret` using HS256 and returns the encoded token
(`header.body.signature`). An `iat` (issued-at) claim is always added.

`SignOptions`:

- `expiresIn?: number` — seconds until expiry; sets the `exp` claim.
- `now?: number` — override the issued-at time (seconds), useful for testing.

### `verifyJwt<T>(token, secret, options?)`

```ts
function verifyJwt<T extends JwtClaims = JwtClaims>(
  token: string,
  secret: string,
  options?: { now?: number },
): Promise<T>;
```

Verifies the HS256 signature and returns the decoded claims typed as `T`.
Throws `JwtError` when the token is malformed, the signature is invalid, the
payload is not valid JSON, the token is expired (`exp`), or not yet valid
(`nbf`). Pass `now` (seconds) to override the reference time for the `exp`/`nbf`
checks.

### `jwtAuth(options)`

```ts
function jwtAuth(options: JwtAuthOptions): Middleware;
```

Returns a WrNexus `Middleware` that reads a token, verifies it, and assigns the
claims to `ctx.user`.

`JwtAuthOptions`:

- `secret: string` — the HMAC secret used to verify tokens.
- `getToken?: (ctx: Context) => string | undefined` — how to extract the token.
  Defaults to reading `Authorization: Bearer <token>`.
- `required?: boolean` — when `true` (default), a missing or invalid token
  responds with `401 { ok: false, error: "Unauthorized" }`. When `false`,
  requests pass through and `ctx.user` is only set if a valid token is present.

## Usage

```ts
import { signJwt, verifyJwt, jwtAuth, JwtError } from "@wrnexus/jwt";

const secret = process.env.JWT_SECRET!;

// Sign a token that expires in one hour
const token = await signJwt({ sub: user.id, role: "admin" }, secret, {
  expiresIn: 3600,
});

// Verify it later
try {
  const claims = await verifyJwt<{ sub: string; role: string }>(token, secret);
  console.log(claims.sub, claims.role);
} catch (err) {
  if (err instanceof JwtError) {
    // invalid signature, expired, malformed, etc.
  }
}
```

Protecting routes with the middleware:

```ts
import { jwtAuth } from "@wrnexus/jwt";

// Require a valid bearer token; ctx.user holds the verified claims
app.use(jwtAuth({ secret: process.env.JWT_SECRET! }));

// Optional auth — populate ctx.user when present, but don't 401
app.use(jwtAuth({ secret: process.env.JWT_SECRET!, required: false }));
```

## Requirements / Notes

- **Bun-only.** Uses the standard Web Crypto API (`crypto.subtle.importKey`,
  `sign`, `verify`) plus `btoa`/`atob` and `TextEncoder`/`TextDecoder` — all
  provided by Bun. No third-party crypto dependency.
- **Algorithm:** HS256 (HMAC with SHA-256) only. Asymmetric algorithms (RS/ES)
  are not supported.
- Integrates with [`@wrnexus/core`](../core) for `Context`, `Middleware`, and
  `ctx.user`; it complements the framework's cookie/session auth with a
  stateless bearer-token flow for API and mobile clients.

### Exported TypeScript declarations

```ts
import { Context, Middleware } from '@wrnexus/core';

interface JwtKey {
    id: string;
    secret: string;
    active?: boolean;
}
interface JwtKeyring {
    active(): JwtKey;
    resolve(id: string): JwtKey | undefined;
    keys(): JwtKey[];
}
declare function decodeJwt(token: string): {
    header: Record<string, unknown>;
    claims: JwtClaims;
};
declare function createJwtKeyring(keys: JwtKey[]): JwtKeyring;
declare function signWithKeyring(claims: JwtClaims, keyring: JwtKeyring, options?: SignOptions): Promise<string>;
declare function verifyWithKeyring<T extends JwtClaims = JwtClaims>(token: string, keyring: JwtKeyring, options?: VerifyOptions): Promise<T>;

/**
 * @wrnexus/jwt — dependency-free JSON Web Tokens (HS256) via WebCrypto, plus a
 * bearer-token auth middleware. Pairs with the session auth in @wrnexus/core for
 * stateless (API/mobile) authentication.
 *
 *   const token = await signJwt({ sub: user.id, role: "admin" }, secret, { expiresIn: 3600 });
 *   const claims = await verifyJwt(token, secret); // throws JwtError if invalid/expired
 */

declare class JwtError extends Error {
    constructor(message: string);
}
interface JwtClaims {
    /** Subject (user id). */
    sub?: string;
    /** Issued-at (seconds). */
    iat?: number;
    /** Expiry (seconds). */
    exp?: number;
    /** Not-before (seconds). */
    nbf?: number;
    [key: string]: unknown;
}
interface SignOptions {
    /** Seconds until expiry (sets `exp`). */
    expiresIn?: number;
    /** Override issued-at (seconds). */
    now?: number;
    issuer?: string;
    audience?: string | string[];
    jwtId?: string;
    /** Key identifier placed in the protected header. */
    keyId?: string;
}
interface VerifyOptions {
    now?: number;
    clockTolerance?: number;
    issuer?: string;
    audience?: string | string[];
    maxAge?: number;
}
/** Sign a payload into a JWT (HS256). */
declare function signJwt(payload: JwtClaims, secret: string, options?: SignOptions): Promise<string>;
/** Verify a JWT and return its claims. Throws `JwtError` on any failure. */
declare function verifyJwt<T extends JwtClaims = JwtClaims>(token: string, secret: string, options?: VerifyOptions): Promise<T>;
interface JwtAuthOptions {
    secret: string;
    /** Where to read the token. Default: `Authorization: Bearer <token>`. */
    getToken?: (ctx: Context) => string | undefined;
    /** Reject unauthenticated requests with 401. Default true. */
    required?: boolean;
}
/**
 * Middleware that verifies a bearer JWT and sets `ctx.user` to its claims.
 * When `required` (default), a missing/invalid token gets a 401.
 */
declare function jwtAuth(options: JwtAuthOptions): Middleware;

export { type JwtAuthOptions, type JwtClaims, JwtError, type JwtKey, type JwtKeyring, type SignOptions, type VerifyOptions, createJwtKeyring, decodeJwt, jwtAuth, signJwt, signWithKeyring, verifyJwt, verifyWithKeyring };
```

---

## @wrnexus/mobile

Documentation URL: https://wrnexusjs.dev/packages/mobile

# @wrnexus/mobile

> SSR-safe access to Capacitor plugins from WRNexusJS browser code.

## Overview

`@wrnexus/mobile` keeps optional native imports out of server rendering while giving
browser-owned modules one consistent registry for Capacitor plugins. During SSR,
`mobile.isNative()` is `false` and `mobile.platform()` is `"web"`.

## Installation

Install a plugin through the WRNexusJS CLI so the web and native projects stay aligned:

```bash
wrnexus mobile add @capacitor/camera @capacitor/haptics
```

## Usage

### Register and invoke a Capacitor plugin

Import Capacitor packages only from browser-owned code, never from API routes or SSR
helpers.

```ts
import { Camera, CameraResultType } from "@capacitor/camera";
import { mobile } from "@wrnexus/mobile";

mobile.registerPlugin("Camera", Camera);

export async function takePhoto() {
  if (!mobile.isNative()) return null;
  return mobile.invoke("Camera", "getPhoto", {
    quality: 85,
    resultType: CameraResultType.Uri,
  });
}
```

### Provide a browser fallback

`whenNative` runs the first callback only in a Capacitor WebView and can return a
web/SSR-safe fallback everywhere else.

```ts
import { Haptics, ImpactStyle } from "@capacitor/haptics";
import { mobile } from "@wrnexus/mobile";

mobile.registerPlugin("Haptics", Haptics);

export const confirmAction = () =>
  mobile.whenNative(
    () => mobile.invoke("Haptics", "impact", { style: ImpactStyle.Medium }),
    () => navigator.vibrate?.(30),
  );
```

### Read an optional plugin without throwing

```ts
import type { NetworkPlugin } from "@capacitor/network";
import { mobile } from "@wrnexus/mobile";

const network = mobile.plugin<NetworkPlugin>("Network");
const status = network ? await network.getStatus() : { connected: true, connectionType: "unknown" };
```

## API

- `registerPlugin(name, instance)` registers a browser-imported plugin.
- `plugin(name)` returns a plugin or `undefined`; `requirePlugin(name)` throws when absent.
- `invoke(plugin, method, options?)` calls a registered method and returns its result.
- `whenNative(native, fallback?)` selects native behavior without breaking SSR.
- `isNative()` and `platform()` report the current Capacitor environment.

Unavailable required plugins throw `MobileUnavailableError` with an actionable message.

## Requirements / Notes

- Capacitor plugin imports must remain in browser-owned modules.
- `@wrnexus/mobile` re-exports `native` from `@wrnexus/native` for applications that
  prefer the higher-level cross-platform capability API.

### Exported TypeScript declarations

```ts
export { native } from '@wrnexus/native';

interface DeepLink {
    url: URL;
    path: string;
    query: URLSearchParams;
}
declare function parseDeepLink(value: string, schemes?: string[]): DeepLink | null;
interface OfflineTask<T = unknown> {
    id: string;
    type: string;
    payload: T;
    createdAt: number;
    attempts: number;
}
interface OfflineTaskStore {
    load(): Promise<OfflineTask[]>;
    save(tasks: OfflineTask[]): Promise<void>;
}
declare function memoryOfflineTaskStore(): OfflineTaskStore;
declare class OfflineQueue {
    #private;
    private readonly store;
    constructor(store?: OfflineTaskStore);
    process<T>(type: string, handler: (payload: T) => Promise<void>): void;
    add<T>(type: string, payload: T): Promise<OfflineTask<T>>;
    sync(limit?: number): Promise<{
        completed: number;
        failed: number;
    }>;
    size(): Promise<number>;
}
interface MobileEnvironment {
    platform: string;
    native: boolean;
    online: boolean;
    userAgent?: string;
}
declare function mobileEnvironment(): MobileEnvironment;

/** @wrnexus/mobile — SSR-safe access to Capacitor's native bridge. */

type MobilePlatform = "ios" | "android" | "web" | string;
interface CapacitorBridge {
    isNativePlatform?: () => boolean;
    getPlatform?: () => MobilePlatform;
    Plugins?: Record<string, unknown>;
}
declare class MobileUnavailableError extends Error {
    constructor(message?: string);
}
/** Register a plugin imported by browser-only application code. */
declare function registerPlugin<T extends object>(name: string, instance: T): T;
/** True only inside a native Capacitor iOS or Android WebView. SSR-safe. */
declare function isNative(): boolean;
/** Current Capacitor platform, falling back to `web` during SSR and in browsers. */
declare function platform(): MobilePlatform;
/** Return an injected Capacitor plugin, or undefined when it is unavailable. */
declare function plugin<T extends object>(name: string): T | undefined;
/** Require an installed native plugin and produce a useful error when absent. */
declare function requirePlugin<T extends object>(name: string): T;
/** Invoke a plugin method without importing native code into an SSR module. */
declare function invoke<TResult = unknown>(pluginName: string, method: string, options?: unknown): Promise<TResult>;
/** Run native behavior when available, with an optional SSR/web fallback. */
declare function whenNative<T>(native: () => T | Promise<T>, fallback?: () => T | Promise<T>): Promise<T | undefined>;
declare const mobile: {
    isNative: typeof isNative;
    platform: typeof platform;
    registerPlugin: typeof registerPlugin;
    plugin: typeof plugin;
    requirePlugin: typeof requirePlugin;
    invoke: typeof invoke;
    whenNative: typeof whenNative;
};

export { type CapacitorBridge, type DeepLink, type MobileEnvironment, type MobilePlatform, MobileUnavailableError, OfflineQueue, type OfflineTask, type OfflineTaskStore, invoke, isNative, memoryOfflineTaskStore, mobile, mobileEnvironment, parseDeepLink, platform, plugin, registerPlugin, requirePlugin, whenNative };
```

---

## @wrnexus/native

Documentation URL: https://wrnexusjs.dev/packages/native

# @wrnexus/native

> Cross-platform capabilities for browsers, Capacitor WebViews, and compiled native apps.

## Overview

`@wrnexus/native` exposes capabilities by name so application code can ask what the
current platform supports before presenting an action. Browser capabilities use Web
APIs; mobile capabilities use installed Capacitor plugins. `platform()` returns
`"server"` during SSR, `"browser"` on the web, and the Capacitor platform in a native
WebView.

## Installation

```bash
bun add @wrnexus/native
```

## Usage

### Share a page when the platform supports it

```ts
import { native } from "@wrnexus/native";

export async function shareCurrentPage() {
  if (!native.supports("share")) return false;
  await native.run("share", {
    title: document.title,
    url: location.href,
  });
  return true;
}
```

### Register an application-specific capability

`register` returns an unregister function, which is useful for tests and temporary
feature modules.

```ts
import { native } from "@wrnexus/native";

const unregister = native.register("orders.scan", {
  browser: {
    supported: () => typeof window !== "undefined",
    run: async ({ orderId }: { orderId: string }) => {
      const code = window.prompt(`Scan code for order ${orderId}`);
      return { code };
    },
  },
});

const result = await native.run<{ code: string | null }>("orders.scan", { orderId: "ord_42" });
unregister();
```

### Target browser or mobile behavior explicitly

```ts
import { native } from "@wrnexus/native";

const canUseMobileCamera = native.supports("camera", "mobile");
const position = await native.run(
  "geolocation",
  { enableHighAccuracy: true },
  { target: "browser" },
);
```

## API

- `supports(name, target?)` checks availability without running the capability.
- `run(name, options?, runOptions?)` executes it or rejects with `NativeUnavailableError`.
- `register(name, capability)` adds or overrides a capability and returns cleanup.
- `registered()` lists capability names; `clearRegistry()` resets the registry.
- `isMobile()` and `platform()` report the current target safely during SSR.

Built-ins include `camera`, `clipboard.write`, `share`, `geolocation`, `network`,
`haptics`, storage, filesystem, notifications, and device information.

## Requirements / Notes

Use `supports()` before showing optional controls. Mobile capabilities require their
matching Capacitor plugins to be installed and registered by the application.

### Exported TypeScript declarations

```ts
import { N as NativePlatform, a as NativeCapability, b as NativeRunOptions, c as NativeTarget } from './types-CDShWg0i.js';
export { d as NativeAdapter, e as NativeBrowserRuntime } from './types-CDShWg0i.js';
export { browserCapabilities } from './browser.js';
export { mobileCapabilities } from './mobile.js';

declare class NativeUnavailableError extends Error {
    constructor(message: string);
}
declare function isMobile(): boolean;
declare function platform(): NativePlatform;
declare function register<TOptions = unknown, TResult = unknown>(name: string, capability: NativeCapability<TOptions, TResult>): () => void;
declare function registered(): string[];
declare function supports(name: string, target?: NativeTarget): boolean;
declare function run<TResult = unknown>(name: string, options?: unknown, runOptions?: NativeRunOptions): Promise<TResult>;
declare function clearRegistry(): void;

interface NativeCapabilityManifestEntry {
    name: string;
    description?: string;
    permissions?: string[];
    targets?: NativeTarget[];
    optional?: boolean;
}
interface NativeCapabilityManifest {
    name: string;
    version?: string;
    capabilities: NativeCapabilityManifestEntry[];
}
declare function defineNativeManifest<T extends NativeCapabilityManifest>(manifest: T): T;
declare function inspectNativeCapabilities(target?: NativeTarget): Array<{
    name: string;
    supported: boolean;
}>;
declare function missingNativeCapabilities(manifest: NativeCapabilityManifest, target?: NativeTarget): NativeCapabilityManifestEntry[];
interface PermissionAdapter {
    query(name: string): Promise<"granted" | "denied" | "prompt" | "unavailable">;
    request?(name: string): Promise<"granted" | "denied">;
}
declare class PermissionManager {
    private readonly adapter;
    constructor(adapter: PermissionAdapter);
    query(name: string): Promise<"denied" | "granted" | "prompt" | "unavailable">;
    ensure(name: string): Promise<boolean>;
}

declare const native: {
    isMobile: typeof isMobile;
    platform: typeof platform;
    register: typeof register;
    registered: typeof registered;
    run: typeof run;
    supports: typeof supports;
};

export { NativeCapability, type NativeCapabilityManifest, type NativeCapabilityManifestEntry, NativePlatform, NativeRunOptions, NativeTarget, NativeUnavailableError, type PermissionAdapter, PermissionManager, clearRegistry, defineNativeManifest, inspectNativeCapabilities, isMobile, missingNativeCapabilities, native, platform, register, registered, run, supports };
```

---

## @wrnexus/oauth

Documentation URL: https://wrnexusjs.dev/packages/oauth

# @wrnexus/oauth

> Dependency-free OAuth 2.0 sign-in for any provider, with PKCE and presets for Google, GitHub, and Discord.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

`@wrnexus/oauth` implements the OAuth 2.0 Authorization Code flow (with PKCE) for
server-side sign-in. It ships ready-made provider presets and a `defineProvider`
helper for custom providers, then gives you two flow functions — `startAuth`
(build the redirect) and `completeAuth` (exchange the code and fetch the user's
profile). It has no runtime dependencies: it uses the platform `fetch` and
WebCrypto only. Pairs naturally with `@wrnexus/core`'s `logIn` to establish a
session once you have a normalized profile.

## Installation

```bash
bun add @wrnexus/oauth
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported).

## API

### Providers

Each preset takes `ProviderCredentials` and returns an `OAuthProvider`.

```ts
interface ProviderCredentials {
  clientId: string;
  clientSecret: string;
  scopes?: string[]; // override the preset's default scopes
}
```

| Export                   | Default scopes               | Notes                                                              |
| ------------------------ | ---------------------------- | ------------------------------------------------------------------ |
| `google(creds)`          | `openid`, `email`, `profile` | Sets `access_type: offline` for refresh tokens.                    |
| `github(creds)`          | `read:user`, `user:email`    | Maps `name` (falls back to `login`) and `avatar_url`.              |
| `discord(creds)`         | `identify`, `email`          | Builds the avatar CDN URL from the user id + hash.                 |
| `defineProvider(config)` | —                            | Pass a full `OAuthProvider` to define a custom OAuth 2.0 provider. |

An `OAuthProvider` describes the endpoints, scopes, credentials, optional extra
authorize params, and a `mapProfile` normalizer:

```ts
interface OAuthProvider {
  name: string;
  authorizeUrl: string;
  tokenUrl: string;
  userInfoUrl: string;
  scopes: string[];
  clientId: string;
  clientSecret: string;
  authorizeParams?: Record<string, string>; // e.g. access_type, prompt
  mapProfile: (raw: Record<string, unknown>) => OAuthProfile;
}
```

### Flow

#### `startAuth(provider, options): Promise<StartAuthResult>`

Builds the authorize redirect URL with a generated PKCE challenge and CSRF
`state`. Store the returned `state` and `verifier` (session/cookie), then 302 the
user to `url`.

```ts
interface StartAuthOptions {
  redirectUri: string;
  state?: string; // reuse a state instead of generating one
  params?: Record<string, string>; // extra authorize params, merged last
}

interface StartAuthResult {
  url: string; // authorize URL to redirect to
  state: string; // CSRF state — verify on callback
  verifier: string; // PKCE code verifier — pass to completeAuth
}
```

#### `completeAuth(provider, options): Promise<{ tokens, profile }>`

On the callback: exchanges the authorization `code` for tokens, then fetches and
normalizes the user profile. Convenience wrapper over `exchangeCode` +
`fetchProfile`.

```ts
interface CompleteAuthOptions {
  code: string;
  redirectUri: string;
  verifier?: string; // the PKCE verifier from startAuth
  fetch?: typeof fetch; // inject a fetch implementation (tests)
}
```

#### Lower-level helpers

| Export                                   | Signature                 | Purpose                                                         |
| ---------------------------------------- | ------------------------- | --------------------------------------------------------------- |
| `exchangeCode(provider, options)`        | `→ Promise<OAuthTokens>`  | Exchange an authorization code for tokens.                      |
| `fetchProfile(provider, tokens, fetch?)` | `→ Promise<OAuthProfile>` | Fetch + normalize the user's profile.                           |
| `randomToken(bytes?)`                    | `→ string`                | Random URL-safe token (default 32 bytes) for `state`/verifiers. |

### Types

```ts
interface OAuthTokens {
  access_token: string;
  token_type?: string;
  refresh_token?: string;
  expires_in?: number;
  id_token?: string;
  scope?: string;
}

interface OAuthProfile {
  id: string;
  email?: string;
  name?: string;
  avatar?: string;
  raw: Record<string, unknown>;
}
```

## Usage

```ts
import { google, startAuth, completeAuth } from "@wrnexus/oauth";
import { logIn } from "@wrnexus/core";

const provider = google({
  clientId: process.env.GOOGLE_CLIENT_ID!,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
});

const redirectUri = "https://example.com/auth/callback";

// 1. Kick off sign-in: redirect the user to the provider.
async function beginLogin(ctx) {
  const { url, state, verifier } = await startAuth(provider, { redirectUri });
  // Persist state + verifier in the session, then redirect.
  ctx.session.set("oauth_state", state);
  ctx.session.set("oauth_verifier", verifier);
  return Response.redirect(url, 302);
}

// 2. Handle the callback.
async function handleCallback(ctx, code: string, state: string) {
  if (state !== ctx.session.get("oauth_state")) throw new Error("bad state");

  const { profile } = await completeAuth(provider, {
    code,
    redirectUri,
    verifier: ctx.session.get("oauth_verifier"),
  });

  logIn(ctx, { id: profile.id, email: profile.email });
}
```

Custom provider with `defineProvider`:

```ts
import { defineProvider, startAuth } from "@wrnexus/oauth";

const gitlab = defineProvider({
  name: "gitlab",
  authorizeUrl: "https://gitlab.com/oauth/authorize",
  tokenUrl: "https://gitlab.com/oauth/token",
  userInfoUrl: "https://gitlab.com/api/v4/user",
  scopes: ["read_user"],
  clientId: process.env.GITLAB_CLIENT_ID!,
  clientSecret: process.env.GITLAB_CLIENT_SECRET!,
  mapProfile: (raw) => ({
    id: String(raw.id),
    email: raw.email as string | undefined,
    name: raw.name as string | undefined,
    avatar: raw.avatar_url as string | undefined,
    raw,
  }),
});
```

## Requirements / Notes

- **Bun-only.** Relies on the global `fetch` and WebCrypto (`crypto.getRandomValues`,
  `crypto.subtle.digest`) — no other runtime dependencies.
- The flow is stateless by design: you are responsible for storing `state` and
  `verifier` between `startAuth` and `completeAuth` (session or signed cookie).
- Pairs with [`@wrnexus/core`](../core) — feed the normalized `OAuthProfile` into
  `logIn` to establish a session.

### Exported TypeScript declarations

```ts
interface OAuthStateRecord {
    state: string;
    verifier: string;
    redirectUri: string;
    returnTo?: string;
    expiresAt: number;
}
interface OAuthStateStore {
    set(record: OAuthStateRecord): Promise<void>;
    consume(state: string): Promise<OAuthStateRecord | null>;
}
declare function memoryOAuthStateStore(now?: () => number): OAuthStateStore;
declare function createOAuthState(store: OAuthStateStore, input: Omit<OAuthStateRecord, "state" | "expiresAt"> & {
    ttlMs?: number;
}): Promise<OAuthStateRecord>;
declare function refreshOAuthTokens(provider: OAuthProvider, refreshToken: string, fetchImpl?: typeof fetch): Promise<OAuthTokens>;
interface OidcDiscovery {
    issuer: string;
    authorization_endpoint: string;
    token_endpoint: string;
    userinfo_endpoint?: string;
    jwks_uri: string;
    revocation_endpoint?: string;
}
declare function discoverOidc(issuer: string, fetchImpl?: typeof fetch): Promise<OidcDiscovery>;
declare function validateOAuthReturnTo(value: string | undefined, origin: string, fallback?: string): string;

/**
 * @wrnexus/oauth — OAuth 2.0 sign-in with any provider. Ships presets for Google,
 * GitHub, and Discord, and `defineProvider` for a custom one. Dependency-free
 * (uses `fetch` + WebCrypto for PKCE). Pairs with @wrnexus/core's `logIn`.
 *
 *   const provider = google({ clientId, clientSecret });
 *   // 1. send the user to the provider:
 *   const { url, state, verifier } = await startAuth(provider, { redirectUri });
 *   // (store `state` + `verifier` in the session, then 302 to `url`)
 *   // 2. on the callback:
 *   const { profile } = await completeAuth(provider, { code, redirectUri, verifier });
 *   logIn(ctx, { id: profile.id, email: profile.email });
 */
interface OAuthTokens {
    access_token: string;
    token_type?: string;
    refresh_token?: string;
    expires_in?: number;
    id_token?: string;
    scope?: string;
}
interface OAuthProfile {
    id: string;
    email?: string;
    name?: string;
    avatar?: string;
    raw: Record<string, unknown>;
}
interface OAuthProvider {
    name: string;
    authorizeUrl: string;
    tokenUrl: string;
    userInfoUrl: string;
    scopes: string[];
    clientId: string;
    clientSecret: string;
    /** Extra params for the authorize request (e.g. `access_type`, `prompt`). */
    authorizeParams?: Record<string, string>;
    /** Normalize the provider's raw userinfo into an OAuthProfile. */
    mapProfile: (raw: Record<string, unknown>) => OAuthProfile;
}
interface ProviderCredentials {
    clientId: string;
    clientSecret: string;
    scopes?: string[];
}
type FetchLike = typeof fetch;
declare function google(creds: ProviderCredentials): OAuthProvider;
declare function github(creds: ProviderCredentials): OAuthProvider;
declare function discord(creds: ProviderCredentials): OAuthProvider;
/** Define a custom OAuth2 provider. */
declare function defineProvider(config: OAuthProvider): OAuthProvider;
/** A random URL-safe token (for `state` and the PKCE verifier). */
declare function randomToken(bytes?: number): string;
interface StartAuthOptions {
    redirectUri: string;
    /** Provide to reuse a state (else one is generated). */
    state?: string;
    /** Extra authorize params (merged over the provider's). */
    params?: Record<string, string>;
}
interface StartAuthResult {
    /** The full authorize URL to redirect the user to. */
    url: string;
    /** CSRF state — store it (session/cookie) and verify on callback. */
    state: string;
    /** PKCE code verifier — store it and pass to `completeAuth`. */
    verifier: string;
}
/** Build the authorize redirect (with PKCE + state). */
declare function startAuth(provider: OAuthProvider, options: StartAuthOptions): Promise<StartAuthResult>;
interface CompleteAuthOptions {
    code: string;
    redirectUri: string;
    /** The PKCE verifier from `startAuth`. */
    verifier?: string;
    /** Inject a fetch implementation (tests). */
    fetch?: FetchLike;
}
/** Exchange the authorization code for tokens, then fetch the user profile. */
declare function completeAuth(provider: OAuthProvider, options: CompleteAuthOptions): Promise<{
    tokens: OAuthTokens;
    profile: OAuthProfile;
}>;
/** Exchange an authorization code for tokens. */
declare function exchangeCode(provider: OAuthProvider, options: CompleteAuthOptions): Promise<OAuthTokens>;
/** Fetch + normalize the user's profile from the provider. */
declare function fetchProfile(provider: OAuthProvider, tokens: OAuthTokens, fetchImpl?: FetchLike): Promise<OAuthProfile>;

export { type CompleteAuthOptions, type OAuthProfile, type OAuthProvider, type OAuthStateRecord, type OAuthStateStore, type OAuthTokens, type OidcDiscovery, type ProviderCredentials, type StartAuthOptions, type StartAuthResult, completeAuth, createOAuthState, defineProvider, discord, discoverOidc, exchangeCode, fetchProfile, github, google, memoryOAuthStateStore, randomToken, refreshOAuthTokens, startAuth, validateOAuthReturnTo };
```

---

## @wrnexus/plugin

Documentation URL: https://wrnexusjs.dev/packages/plugin

# @wrnexus/plugin

Deterministic WRNexusJS plugin contracts for configuration, AST/code transforms,
diagnostics, development servers, production builds, and DevToolbar extensions.

Use `definePlugin()` and declare `enforce`, `before`, or `after` when ordering matters.
Duplicate names and dependency cycles are rejected.

### Exported TypeScript declarations

```ts
export { PageAst, WrnDiagnostic } from '@wrnexus/syntax';
import { WrnexusPlugin, PluginInput, PluginContext, PluginRunner } from './types.js';
export { ClientRuntimeDefinition, ClientRuntimeInject, ClientRuntimeLoad, ClientRuntimeType, PackageAssetDefinition, PackageMigrationDefinition, PackagePluginManifest, PackageRouteDefinition, PackageStyleDefinition, PluginCommand, PluginContributions, PluginDevToolbarPanel, PluginOrder, TransformContext, WrnexusPackageManifest } from './types.js';
export { assertContributionId, contentTypeForPath, defaultClientRuntimePath, defaultPackageAssetPath, definePackageManifest, normalizeClientRuntime, normalizePackageAsset, validateStyleIds } from './manifest.js';
export { DiscoverPluginOptions, discoverPlugins } from './discovery.js';

declare function definePlugin(plugin: WrnexusPlugin): WrnexusPlugin;
declare function flattenPlugins(input: PluginInput, output?: WrnexusPlugin[]): WrnexusPlugin[];

/** Resolve plugin order deterministically and reject duplicates/cycles. */
declare function resolvePlugins(input: PluginInput): WrnexusPlugin[];
declare function createPluginRunner(input: PluginInput, context: PluginContext): PluginRunner;

export { PluginContext, PluginInput, PluginRunner, WrnexusPlugin, createPluginRunner, definePlugin, flattenPlugins, resolvePlugins };
```

---

## @wrnexus/pubsub

Documentation URL: https://wrnexusjs.dev/packages/pubsub

# @wrnexus/pubsub

> Topic-based publish/subscribe with a pluggable driver — in-process by default, Redis for cross-process messaging.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

`@wrnexus/pubsub` is a small server-side pub/sub bus. You publish messages to a
topic and subscribe with topic patterns; handlers fire for matching topics. The
default driver keeps everything in-process, and you can swap in the Redis driver
(`@wrnexus/pubsub/redis`) to fan messages out across processes or hosts. It also
backs `@wrnexus/core`'s realtime bridge for horizontal scaling.

## Installation

```bash
bun add @wrnexus/pubsub
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported).

## API

### `createPubSub(driver?): PubSub`

Creates a bus over a driver. Defaults to `memoryDriver()` (in-process).

```ts
interface PubSub {
  publish<T = unknown>(topic: string, message: T): Promise<void>;
  subscribe<T = unknown>(pattern: string, handler: Handler<T>): () => void;
}

type Handler<T = unknown> = (message: T, topic: string) => void | Promise<void>;
```

- `publish(topic, message)` — resolves once the driver has dispatched the message.
- `subscribe(pattern, handler)` — returns an unsubscribe function.

### Pattern matching

Subscription patterns match in three ways:

- **Exact** — `"order:created"` matches only that topic.
- **Prefix** — `"order:*"` matches any topic starting with `"order:"`.
- **Everything** — `"*"` matches all topics.

### `memoryDriver(): PubSubDriver`

The default in-process driver. Handlers are invoked synchronously (fire-and-forget
for async handlers) whenever a published topic matches a registered pattern.

```ts
interface PubSubDriver {
  publish(topic: string, message: unknown): void | Promise<void>;
  subscribe(pattern: string, handler: Handler): () => void;
}
```

### `@wrnexus/pubsub/redis` — `redisDriver(url?)`

A cross-process driver backed by Redis. It speaks RESP over a raw TCP socket via
`Bun.connect`, so it adds **no npm dependency**. `url` defaults to `$REDIS_URL`,
then `redis://localhost:6379`. The URL may carry a password and a database index
(e.g. `redis://:secret@host:6379/2`).

```ts
function redisDriver(url?: string): PubSubDriver & { close(): void };
```

- Exact topics use Redis `SUBSCRIBE`; wildcard patterns (`ns:*`, `*`) use
  `PSUBSCRIBE`, whose glob semantics line up with this library's matching.
- Messages are JSON-stringified on publish and `JSON.parse`d on receipt; a payload
  that isn't valid JSON is delivered as the raw string.
- `close()` tears down both the subscriber and publisher connections.

### RESP codec (internal)

`redis.ts` uses a minimal RESP implementation exported from `resp.ts`
(`encodeCommand`, `parseReply`, `concat`, and the `RespValue` type). These are
implementation details of the Redis driver, not part of the public package entry.

## Usage

In-process (default):

```ts
import { createPubSub } from "@wrnexus/pubsub";

const bus = createPubSub();

const off = bus.subscribe("order:*", (msg, topic) => {
  console.log(topic, msg);
});

await bus.publish("order:created", { id: 7 });

off(); // unsubscribe
```

Cross-process with Redis:

```ts
import { createPubSub } from "@wrnexus/pubsub";
import { redisDriver } from "@wrnexus/pubsub/redis";

const driver = redisDriver("redis://localhost:6379");
const bus = createPubSub(driver);

bus.subscribe("order:*", (msg, topic) => {
  // received on any app process subscribed to this pattern
});

await bus.publish("order:created", { id: 7 });

// on shutdown
driver.close();
```

## Requirements / Notes

- **Bun-only.** The Redis driver depends on `Bun.connect`; it throws
  `redisDriver requires the Bun runtime (Bun.connect).` outside Bun. The default
  in-memory driver has no runtime dependencies.
- The Redis driver reads `REDIS_URL` from the environment when no `url` is passed.
- Backs [`@wrnexus/core`](../core)'s realtime bridge for horizontal scaling.
- No external npm dependencies — the Redis client is a self-contained RESP codec.

### Exported TypeScript declarations

```ts
interface MessageEnvelope<T = unknown> {
    id: string;
    topic: string;
    data: T;
    timestamp: number;
    attempts: number;
}
interface ResilientPubSubOptions {
    retries?: number;
    retryDelayMs?: number;
    onError?: (error: unknown, envelope: MessageEnvelope) => void;
}
declare function createResilientPubSub(driver: PubSubDriver, options?: ResilientPubSubOptions): PubSub;
interface PresenceMember {
    id: string;
    metadata?: Record<string, unknown>;
    joinedAt: number;
    expiresAt: number;
}
declare class PresenceChannel {
    #private;
    private readonly ttlMs;
    private readonly now;
    constructor(ttlMs?: number, now?: () => number);
    touch(id: string, metadata?: Record<string, unknown>): PresenceMember;
    leave(id: string): boolean;
    list(): PresenceMember[];
    prune(): number;
}

/**
 * @wrnexus/pubsub — topic-based publish/subscribe with a pluggable driver.
 * The default is in-process; swap in a Redis/NATS driver for cross-instance
 * messaging (it also backs @wrnexus/core's realtime bridge).
 *
 *   const bus = createPubSub();
 *   const off = bus.subscribe("order:*", (msg, topic) => {...});
 *   await bus.publish("order:created", { id: 7 });
 *
 * Subscriptions match exact topics, "ns:*" prefixes, and "*" (everything).
 */
type Handler<T = unknown> = (message: T, topic: string) => void | Promise<void>;
interface PubSubDriver {
    publish(topic: string, message: unknown): void | Promise<void>;
    subscribe(pattern: string, handler: Handler): () => void;
}
interface PubSub {
    publish<T = unknown>(topic: string, message: T): Promise<void>;
    subscribe<T = unknown>(pattern: string, handler: Handler<T>): () => void;
}
/** In-process pub/sub driver (default). */
declare function memoryDriver(): PubSubDriver;
/** Create a pub/sub bus over a driver (in-memory by default). */
declare function createPubSub(driver?: PubSubDriver): PubSub;

export { type Handler, type MessageEnvelope, PresenceChannel, type PresenceMember, type PubSub, type PubSubDriver, type ResilientPubSubOptions, createPubSub, createResilientPubSub, memoryDriver };
```

---

## @wrnexus/queue

Documentation URL: https://wrnexusjs.dev/packages/queue

# @wrnexus/queue

> A background job queue with delays, retries + exponential backoff, recurring jobs, and concurrent workers.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

`@wrnexus/queue` is a server-side in-process job queue. You register named
workers, enqueue jobs (optionally delayed or recurring), and let the queue poll
and run them on a timer — with per-job retry limits and doubling backoff between
attempts. The default store lives in memory; the design allows a pluggable driver
to back it with Redis/SQL for durability across restarts. Reach for it when you
need to defer work (emails, webhooks, cleanup) off the request path without a
heavyweight external broker. Tests can drive it deterministically via `drain()`.

## Installation

```bash
bun add @wrnexus/queue
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported).

## API

The package exports a single factory plus its supporting types.

### `createQueue(options?): Queue`

Creates a new queue instance.

```ts
function createQueue(options?: QueueOptions): Queue;
```

#### `QueueOptions`

| Option        | Type                                 | Default    | Description                                              |
| ------------- | ------------------------------------ | ---------- | -------------------------------------------------------- |
| `maxAttempts` | `number`                             | `3`        | Default max attempts per job before it is dead-lettered. |
| `backoffMs`   | `number`                             | `1000`     | Base retry backoff in ms; doubles per attempt.           |
| `pollMs`      | `number`                             | `250`      | Poll interval used once `start()` is called (ms).        |
| `onFailed`    | `(job: Job, error: unknown) => void` | —          | Called when a job exhausts its attempts.                 |
| `now`         | `() => number`                       | `Date.now` | Clock injection for deterministic tests.                 |

### `Queue`

The object returned by `createQueue`.

| Method    | Signature                                                      | Description                                                    |
| --------- | -------------------------------------------------------------- | -------------------------------------------------------------- |
| `add`     | `add<T>(name, data: T, options?: AddOptions): Promise<Job<T>>` | Enqueue a job under a worker name. Returns the created job.    |
| `process` | `process<T>(name, handler: JobHandler<T>): void`               | Register the worker that runs jobs of the given name.          |
| `drain`   | `drain(now?: number): Promise<number>`                         | Run every job whose `runAt ≤ now`, once. Returns how many ran. |
| `start`   | `start(): void`                                                | Begin polling every `pollMs`. No-op if already started.        |
| `stop`    | `stop(): void`                                                 | Stop the poll timer.                                           |
| `size`    | `size(): number`                                               | Number of jobs currently queued.                               |

#### `AddOptions`

| Option        | Type     | Description                                                                |
| ------------- | -------- | -------------------------------------------------------------------------- |
| `delayMs`     | `number` | Delay before the job becomes runnable (ms).                                |
| `maxAttempts` | `number` | Max attempts before dead-lettering. Defaults to the queue's `maxAttempts`. |
| `repeat`      | `number` | Re-enqueue this job this many ms after each successful run (recurring).    |

#### `JobHandler<T>`

```ts
type JobHandler<T = unknown> = (job: Job<T>) => void | Promise<void>;
```

#### `Job<T>`

```ts
interface Job<T = unknown> {
  id: string; // e.g. "job_1"
  name: string;
  data: T;
  attempts: number;
  maxAttempts: number;
  runAt: number; // epoch ms; job runs when now ≥ runAt
  repeat?: number; // if set, re-enqueue this many ms after each success
}
```

## Usage

Register workers, enqueue jobs, then start the poller:

```ts
import { createQueue } from "@wrnexus/queue";

const queue = createQueue({ maxAttempts: 3, backoffMs: 1000 });

// Register a worker for the "email" job name.
queue.process<{ to: string }>("email", async (job) => {
  await send(job.data.to);
});

// Enqueue a delayed job with up to 3 attempts.
await queue.add("email", { to: "a@b.com" }, { delayMs: 5000, maxAttempts: 3 });

queue.start(); // begin polling; queue.stop() to halt
```

### Recurring jobs

Pass `repeat` to re-enqueue a job a fixed interval after each successful run:

```ts
queue.process("heartbeat", async () => ping());
await queue.add("heartbeat", {}, { repeat: 60_000 }); // runs ~every minute
```

### Handling permanent failures

When a job's `attempts` reaches `maxAttempts`, it is dropped and `onFailed`
fires instead of retrying:

```ts
const queue = createQueue({
  onFailed: (job, error) => {
    console.error(`job ${job.id} (${job.name}) gave up`, error);
  },
});
```

### Deterministic testing

Instead of `start()`, inject a clock and drive the queue with `drain()`:

```ts
let clock = 0;
const queue = createQueue({ now: () => clock });

queue.process("task", async () => {
  /* ... */
});
await queue.add("task", {}, { delayMs: 5000 });

clock = 5000;
const ran = await queue.drain(); // => 1
```

## Retry & backoff behavior

- On a thrown handler error, the job is retried while `attempts < maxAttempts`.
- The next `runAt` is set to `now + backoffMs * 2^(attempts - 1)` (exponential
  backoff): with `backoffMs: 1000` the delays are 1s, 2s, 4s, …
- A job whose worker name has no registered handler stays queued until one is
  registered (it is not counted as runnable by `drain`).
- `drain` is re-entrant-safe: overlapping calls are skipped while one is running.

## Requirements / Notes

- **Bun-only** runtime (Node is not supported), consistent with the rest of the
  WrNexus framework. The queue itself relies only on standard timers
  (`setInterval`/`clearInterval`) and has no runtime dependencies.
- The default store is in-process, so queued jobs do not survive a restart; a
  pluggable driver is intended for backing it with Redis/SQL for durability.
- Works alongside `@wrnexus/core` for offloading work from the request path.

### Exported TypeScript declarations

```ts
/**
 * Persistence contract for the durable queue.
 *
 * Distributed drivers should implement `claim()` atomically and exclude leased
 * jobs from `due()` until their lease expires. Calling `put()` must replace the
 * stored record and release any previous lease for that job.
 */
interface QueueStore {
    put(job: Job): Promise<void>;
    get(id: string): Promise<Job | null>;
    remove(id: string): Promise<void>;
    due(now: number, limit: number): Promise<Job[]>;
    list(name?: string): Promise<Job[]>;
    claim?(id: string, worker: string, leaseUntil: number): Promise<boolean>;
}
declare function memoryQueueStore(): QueueStore;
interface DurableQueueOptions {
    store?: QueueStore;
    workerId?: string;
    maxAttempts?: number;
    concurrency?: number;
    leaseMs?: number;
    backoff?: (attempt: number) => number;
    now?: () => number;
    onDeadLetter?: (job: Job, error: unknown) => void | Promise<void>;
}
interface DurableQueue {
    add<T>(name: string, data: T, options?: AddOptions): Promise<Job<T>>;
    process<T>(name: string, handler: JobHandler<T>): void;
    drain(): Promise<number>;
    failed(): Job[];
    retry(id: string): Promise<boolean>;
}
declare function createDurableQueue(options?: DurableQueueOptions): DurableQueue;

/**
 * @wrnexus/queue — a background job queue with delays, retries + backoff, and
 * concurrent workers. The default store is in-process; a pluggable driver lets
 * you back it with Redis/SQL for durability across restarts.
 *
 *   const queue = createQueue();
 *   queue.process("email", async (job) => { await send(job.data); });
 *   await queue.add("email", { to: "a@b.com" }, { delayMs: 5000, maxAttempts: 3 });
 *   queue.start();                 // begin polling; queue.stop() to halt
 *
 * Tests can drive it deterministically with `await queue.drain(now)`.
 */
interface Job<T = unknown> {
    id: string;
    name: string;
    data: T;
    attempts: number;
    maxAttempts: number;
    runAt: number;
    /** If set, re-enqueue this job this many ms after each successful run. */
    repeat?: number;
    priority: number;
    idempotencyKey?: string;
    createdAt: number;
}
type JobHandler<T = unknown> = (job: Job<T>) => void | Promise<void>;
interface AddOptions {
    /** Delay before the job becomes runnable (ms). */
    delayMs?: number;
    /** Max attempts before it's dead-lettered. Default from queue options. */
    maxAttempts?: number;
    /** Re-enqueue this job this many ms after each successful run (recurring). */
    repeat?: number;
    /** Higher-priority jobs run first when multiple jobs are due. */
    priority?: number;
    /** Prevent duplicate queued work with the same stable key. */
    idempotencyKey?: string;
}
interface QueueOptions {
    /** Default max attempts per job. Default 3. */
    maxAttempts?: number;
    /** Base retry backoff (ms); doubles per attempt. Default 1000. */
    backoffMs?: number;
    /** Poll interval when started (ms). Default 250. */
    pollMs?: number;
    /** Called when a job exhausts its attempts. */
    onFailed?: (job: Job, error: unknown) => void;
    /** Maximum jobs executed in one drain. Default: unlimited. */
    concurrency?: number;
    /** Clock injection (tests). Default Date.now. */
    now?: () => number;
}
interface Queue {
    add<T>(name: string, data: T, options?: AddOptions): Promise<Job<T>>;
    process<T>(name: string, handler: JobHandler<T>): void;
    /** Run every job whose runAt ≤ now, once. Returns how many ran. */
    drain(now?: number): Promise<number>;
    start(): void;
    stop(): void;
    size(): number;
    get(id: string): Job | undefined;
    list(name?: string): Job[];
    cancel(id: string): boolean;
}
interface JobDefinition<I> {
    name: string;
    options?: Omit<AddOptions, "idempotencyKey">;
    run: JobHandler<I>;
}
declare function defineJob<I>(definition: JobDefinition<I>): JobDefinition<I>;
interface WorkflowStep<I, O> {
    name: string;
    run(input: I): O | Promise<O>;
}
declare function defineWorkflow<T>(name: string, steps: Array<WorkflowStep<any, any>>): {
    name: string;
    steps: WorkflowStep<any, any>[];
    run(input: T): Promise<unknown>;
};
declare function cronToInterval(cron: string): number;
declare function createQueue(options?: QueueOptions): Queue;

export { type AddOptions, type DurableQueue, type DurableQueueOptions, type Job, type JobDefinition, type JobHandler, type Queue, type QueueOptions, type QueueStore, type WorkflowStep, createDurableQueue, createQueue, cronToInterval, defineJob, defineWorkflow, memoryQueueStore };
```

---

## @wrnexus/reactive

Documentation URL: https://wrnexusjs.dev/packages/reactive

# @wrnexus/reactive

> Tiny, type-safe reactive primitives (signals) with zero dependencies.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

`@wrnexus/reactive` is the seed of WrNexus's reactivity layer: a minimal `signal`
primitive that holds a value, notifies subscribers when it changes, and hands back
an unsubscribe function. It is deliberately small and framework-agnostic — it powers
nothing on its own, but is shaped so client islands (and later the `.wrn` compiler's
`state` blocks) can build reactive bindings on top of it. Reach for it when you need
observable state without pulling in a full reactivity library.

## Installation

```bash
bun add @wrnexus/reactive
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported).

## API

The package has a single entry point (`.`) exporting one function and three types.

### `signal<T>(initial: T): Signal<T>`

Creates a reactive signal seeded with `initial`. Returns a `Signal<T>`:

| Member      | Signature                          | Description                                                                                              |
| ----------- | ---------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `get`       | `(): T`                            | Read the current value.                                                                                  |
| `set`       | `(next: T): void`                  | Write a new value. Subscribers run **only when the value actually changes** (compared with `Object.is`). |
| `update`    | `(fn: (current: T) => T): void`    | Apply a function to the current value; equivalent to `set(fn(get()))`.                                   |
| `subscribe` | `(fn: Subscriber<T>): Unsubscribe` | Register a subscriber; returns a function that removes it.                                               |

### Types

```ts
type Subscriber<T> = (value: T) => void;
type Unsubscribe = () => void;

interface Signal<T> {
  get(): T;
  set(next: T): void;
  update(fn: (current: T) => T): void;
  subscribe(fn: Subscriber<T>): Unsubscribe;
}
```

Notes on semantics:

- **No-op updates are skipped.** `set` compares the incoming value to the current
  one with `Object.is`; identical values do not notify subscribers.
- **Safe unsubscribe during notification.** Subscribers are iterated over a copy of
  the subscriber set, so a subscriber may call its own (or another's) unsubscribe
  while a notification is in flight.

## Usage

```ts
import { signal } from "@wrnexus/reactive";

const count = signal(0);

count.get(); // 0

// Subscribe; the returned function unsubscribes.
const off = count.subscribe((value) => {
  console.log("count is now", value);
});

count.set(1); // logs: count is now 1
count.set(1); // no-op — value unchanged, no notification
count.update((n) => n + 1); // logs: count is now 2

off(); // stop listening
count.set(3); // nothing logged
```

Typed signals infer `T` from the initial value, or can be annotated explicitly:

```ts
import { signal, type Signal } from "@wrnexus/reactive";

const user: Signal<{ name: string } | null> = signal(null);
user.set({ name: "Ada" });
```

## Requirements / Notes

- **Bun-only.** Distributed as TypeScript source (`main`/`exports` point at
  `src/index.ts`); consume it under Bun, which runs `.ts` directly.
- **Zero dependencies.** The only runtime API used is the standard `Object.is`.
- Foundational primitive for WrNexus client islands and the forthcoming `.wrn`
  compiler `state` blocks.

### Exported TypeScript declarations

```ts
/**
 * Fine-grained reactive primitives shared by server utilities and client code.
 * Updates are synchronous by default and coalesced inside `batch()`.
 */
type Subscriber<T> = (value: T, previous?: T) => void;
type Unsubscribe = () => void;
type Cleanup = () => void;
interface Signal<T> {
    get(): T;
    set(next: T): void;
    update(fn: (current: T) => T): void;
    subscribe(fn: Subscriber<T>): Unsubscribe;
}
interface ReadonlySignal<T> {
    get(): T;
    subscribe(fn: Subscriber<T>): Unsubscribe;
}
/** Coalesce every signal notification made by `fn` into one flush. */
declare function batch<T>(fn: () => T): T;
/** Read reactive values without recording dependencies. */
declare function untrack<T>(fn: () => T): T;
declare function signal<T>(initial: T): Signal<T>;
/**
 * Run a dependency-tracked side effect. Dependencies are rebuilt after every
 * execution, preventing stale subscriptions when conditional reads change.
 */
declare function effect(run: () => void | Cleanup): Cleanup;
/** Create a lazily readable derived signal with automatic dependency tracking. */
declare function computed<T>(read: () => T): ReadonlySignal<T>;

interface WatchOptions<T> {
    immediate?: boolean;
    equals?: (left: T, right: T) => boolean;
}
declare function watch<T>(read: () => T, listener: (value: T, previous: T | undefined) => void | Cleanup, options?: WatchOptions<T>): Cleanup;
type ResourceStatus = "idle" | "pending" | "success" | "error";
interface Resource<T> {
    data: ReadonlySignal<T | undefined>;
    error: ReadonlySignal<unknown>;
    status: ReadonlySignal<ResourceStatus>;
    loading: ReadonlySignal<boolean>;
    run(): Promise<T | undefined>;
    abort(reason?: unknown): void;
    reset(): void;
}
interface ResourceOptions<T> {
    initial?: T;
    immediate?: boolean;
    keepPrevious?: boolean;
}
declare function resource<T>(loader: (signal: AbortSignal) => Promise<T>, options?: ResourceOptions<T>): Resource<T>;
interface ReactiveScope {
    add(cleanup: Cleanup): Cleanup;
    dispose(): void;
    readonly disposed: boolean;
}
declare function createScope(): ReactiveScope;

export { type Cleanup, type ReactiveScope, type ReadonlySignal, type Resource, type ResourceOptions, type ResourceStatus, type Signal, type Subscriber, type Unsubscribe, type WatchOptions, batch, computed, createScope, effect, resource, signal, untrack, watch };
```

---

## @wrnexus/router

Documentation URL: https://wrnexusjs.dev/packages/router

# @wrnexus/router

> File-based router that maps an `app/` directory onto route tables and matches request paths against them.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

`@wrnexus/router` scans an application's `app/` directory once at startup and builds route tables for pages, API endpoints, realtime channels, middleware, server-rendered `.wrn` components, layouts, and validation schemas. It also compiles URL patterns (`/users/[id]`) into RegExps and matches request paths against them. Request input is never turned into a file path, which makes the router immune to path traversal. This is a server-side package used by the WrNexus runtime to resolve incoming requests, plus a codegen helper for compile-time typed links.

## Installation

```bash
bun add @wrnexus/router
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported).

## Directory conventions

The router maps files under `appDir` onto routes:

```
app/pages/index.tsx        -> GET /
app/pages/about.tsx        -> GET /about
app/pages/users/[id].tsx   -> GET /users/:id
app/api/hello.ts           -> /api/hello
app/realtime/chat.ts       -> /realtime/chat
app/pages/*.wrn  (api)    -> embedded /api/* routes
app/pages/*.wrn  (rt)     -> embedded /realtime/* routes
app/middleware/*.ts        -> global middleware (alphabetical)
app/components/*.wrn      -> server-rendered components (by basename)
app/layouts/*.wrn         -> named page layouts
app/schemas/*.ts           -> validation schemas
```

Allowed route extensions are `.ts`, `.tsx`, and `.wrn`. Dotfiles and underscore-prefixed files are ignored. A trailing `index` segment is dropped from the route. `.wrn` pages may embed `api` and `realtime` blocks, which the router extracts and mounts under `/api/*` and `/realtime/*`.

## API

### `buildRouter(appDir, opts?): Router`

Scan an app directory and build all route tables.

```ts
function buildRouter(appDir: string, opts?: RouterOptions): Router;

interface RouterOptions {
  /** Extra dirs scanned for `.wrn` components (e.g. `@wrnexus/ui`), before
   *  `app/components`, so an app component of the same name wins. */
  componentDirs?: string[];
}
```

The returned `Router` exposes the built tables plus per-kind matchers:

```ts
interface Router {
  pages: Route[];
  api: Route[];
  realtime: Route[];
  /** Absolute paths of middleware modules, in execution order (alphabetical). */
  middlewareFiles: string[];
  /** Server-rendered `.wrn` components, mounted via `data-component`. */
  components: ComponentRef[];
  /** Named page layouts (`app/layouts/<name>.wrn`); a page picks one via `layout`. */
  layouts: ComponentRef[];
  /** Validation schemas (`app/schemas/<name>.ts`) shared by API + forms. */
  schemas: ComponentRef[];
  matchPage(pathname: string): RouteMatch | null;
  matchApi(pathname: string): RouteMatch | null;
  matchRealtime(pathname: string): RouteMatch | null;
}

interface ComponentRef {
  /** Validated component name (matches a `data-component` attribute). */
  name: string;
  /** Absolute path to the component's `.wrn` module. */
  file: string;
}
```

Component, layout, and schema names are validated with `isSafeIslandName` from `@wrnexus/core`; unsafe names are skipped with a warning. Realtime channel names are validated the same way.

### Route matching

| Export                | Signature                                                   | Description                                                                                                         |
| --------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `compileRoutePattern` | `(raw: string) => Pick<Route, "regex" \| "paramNames">`     | Compile a `/users/[id]` pattern into a RegExp (with optional trailing slash) plus ordered param names.              |
| `matchRoute`          | `(routes: Route[], pathname: string) => RouteMatch \| null` | Return the first route whose regex matches; captured params are `decodeURIComponent`-decoded.                       |
| `sortRoutes`          | `(routes: Route[]) => Route[]`                              | Order routes so static routes win over dynamic ones (fewer params first), then longer/more specific patterns first. |

```ts
interface Route {
  raw: string; // e.g. "/users/[id]"
  file: string; // absolute path to the handling module
  regex: RegExp; // compiled matcher
  paramNames: string[]; // ordered dynamic param names
}

interface RouteMatch {
  route: Route;
  params: Record<string, string>;
}
```

### Typed-routes codegen

```ts
function generateRoutesFile(pages: Route[]): string;
```

Emits the source for `app/routes.gen.ts`: a `Routes` map (each page path → its `[param]` types), a `RoutePath` union, and an `href()` builder that fills params and rejects unknown paths at compile time. Entries are de-duplicated and sorted by path.

### Re-exports

`Middleware` (the type from `@wrnexus/core`) is re-exported for callers that load middleware modules themselves.

## Usage

```ts
import { buildRouter } from "@wrnexus/router";

const router = buildRouter("./app", {
  componentDirs: ["./node_modules/@wrnexus/ui/components"],
});

// Resolve an incoming request.
const match = router.matchPage("/users/42");
if (match) {
  console.log(match.route.file); // absolute path to the page module
  console.log(match.params); // { id: "42" }
}

const api = router.matchApi("/api/hello");
const rt = router.matchRealtime("/realtime/chat");
```

Generating the typed-routes file (as `wrnexus dev` does):

```ts
import { generateRoutesFile } from "@wrnexus/router";
import { writeFileSync } from "node:fs";

const router = buildRouter("./app");
writeFileSync("./app/routes.gen.ts", generateRoutesFile(router.pages));
```

```ts
// Then, in app code, links are checked at compile time:
import { href } from "./routes.gen.ts";

href("/users/[id]", { id: "42" }); // "/users/42"
href("/about"); // "/about"
href("/nope"); // type error: unknown path
```

Lower-level pattern matching, if you need it directly:

```ts
import { compileRoutePattern, matchRoute, sortRoutes, type Route } from "@wrnexus/router";

const { regex, paramNames } = compileRoutePattern("/posts/[slug]");
const routes = sortRoutes([{ raw: "/posts/[slug]", file: "…", regex, paramNames }]);
const m = matchRoute(routes, "/posts/hello"); // { route, params: { slug: "hello" } }
```

## Requirements / Notes

- Scanning uses `node:fs` (`existsSync`, `readdirSync`, `statSync`) and `node:path` — runs under Bun.
- Depends on [`@wrnexus/compiler`](../compiler) to `parse` `.wrn` pages and extract embedded `api` / `realtime` blocks.
- Depends on [`@wrnexus/core`](../core) for `isSafeIslandName` (name validation) and the `Middleware` type.
- Missing route directories are tolerated — a route kind you don't use simply yields an empty table.

### Exported TypeScript declarations

```ts
export { Middleware } from '@wrnexus/core';

/**
 * Route compilation + matching.
 *
 * Supported segments:
 *   [id]          required parameter
 *   [id?]         optional parameter
 *   [[id]]        optional parameter (directory-friendly form)
 *   [...slug]     required catch-all
 *   [[...slug]]   optional catch-all
 */
interface RouteParam {
    name: string;
    optional: boolean;
    catchAll: boolean;
}
interface Route {
    /** The human-readable route pattern, e.g. `/users/[id]`. */
    raw: string;
    /** Absolute path to the module that handles this route. */
    file: string;
    /** Compiled matcher. */
    regex: RegExp;
    /** Ordered names of dynamic params captured by `regex`. */
    paramNames: string[];
    /** Rich parameter metadata. Optional for compatibility with old manifests. */
    paramMeta?: RouteParam[];
}
interface RouteMatch {
    route: Route;
    params: Record<string, string>;
}
/** Return parameter metadata without requiring callers to inspect the regex. */
declare function getRouteParams(raw: string): RouteParam[];
/** Compile a WRNexus route pattern into a RegExp + parameter metadata. */
declare function compileRoutePattern(raw: string): Pick<Route, "regex" | "paramNames" | "paramMeta">;
/**
 * Order routes so static and constrained routes win over optional/catch-all
 * routes. The ordering remains deterministic for identical specificity.
 */
declare function sortRoutes(routes: Route[]): Route[];
/** Find duplicate URL patterns before request handling starts. */
declare function findRouteConflicts(routes: Route[]): Array<{
    raw: string;
    files: string[];
}>;
/** Find the first route whose pattern matches `pathname`. */
declare function matchRoute(routes: Route[], pathname: string): RouteMatch | null;

/**
 * Typed-routes codegen. From the scanned page routes, emit `app/routes.gen.ts`
 * with a `Routes` map (path -> param types) and an `href()` builder.
 */

declare function generateRoutesFile(pages: Route[]): string;

interface NamedRoute extends Route {
    name: string;
    metadata?: Record<string, unknown>;
}
interface RouteManifestEntry {
    name: string;
    path: string;
    file: string;
    params: ReturnType<typeof getRouteParams>;
    metadata?: Record<string, unknown>;
}
declare function routeName(raw: string): string;
declare function nameRoutes(routes: readonly Route[], metadata?: Record<string, Record<string, unknown>>): NamedRoute[];
declare function createRouteManifest(routes: readonly NamedRoute[]): RouteManifestEntry[];
declare function routeUrl(route: Pick<NamedRoute, "raw" | "paramMeta">, params?: Record<string, string | number | Array<string | number> | null | undefined>, query?: Record<string, string | number | boolean | null | undefined>): string;
declare function findNamedRoute(routes: readonly NamedRoute[], name: string): NamedRoute;

/**
 * @wrnexus/router — file-based router.
 *
 * Maps the `app/` directory onto route tables:
 *   app/pages/index.tsx     -> GET /
 *   app/pages/about.tsx     -> GET /about
 *   app/pages/users/[id].tsx-> GET /users/:id
 *   app/api/hello.ts        -> /api/hello
 *   app/realtime/chat.ts    -> /realtime/chat
 *   app/pages/*.wrn api      -> embedded /api/* routes
 *   app/pages/*.wrn realtime -> embedded /realtime/* routes
 *   app/middleware/*.ts     -> global middleware (alphabetical)
 *   app/components/*.wrn   -> server-rendered components (by declaration),
 *                              mounted in a page via data-component="<name>"
 */

interface ComponentRef {
    /** Validated component name (matches a `data-component` attribute). */
    name: string;
    /** Absolute path to the component's `.wrn` module. */
    file: string;
}
interface Router {
    pages: Route[];
    api: Route[];
    realtime: Route[];
    /** Absolute paths of middleware modules, in execution order. */
    middlewareFiles: string[];
    /** Server-rendered `.wrn` components, mounted via `data-component`. */
    components: ComponentRef[];
    /** Named page layouts (`app/layouts/<name>.wrn`); a page picks one via `layout`. */
    layouts: ComponentRef[];
    /** Validation schemas (`app/schemas/<name>.ts`) shared by API + forms. */
    schemas: ComponentRef[];
    matchPage(pathname: string): RouteMatch | null;
    matchApi(pathname: string): RouteMatch | null;
    matchRealtime(pathname: string): RouteMatch | null;
}
interface ExternalRouteDefinition {
    kind: "page" | "api" | "realtime";
    path: string;
    entry: string;
    name?: string;
}
interface RouterOptions {
    /**
     * Extra directories to scan for `.wrn` components (e.g. `@wrnexus/ui`).
     * Scanned before `app/components`, so an app component of the same name wins.
     */
    componentDirs?: string[];
    /** Package-owned routes registered by the plugin contribution system. */
    externalRoutes?: ExternalRouteDefinition[];
    /** Package-owned middleware executed before app/middleware. */
    middlewareFiles?: string[];
}
/**
 * Convert a scanned file's relative path into a URL route pattern.
 *  - strips the extension
 *  - drops a trailing `index` segment
 *  - prefixes with `prefix` (e.g. "/api")
 */
declare function fileToRoute(rel: string, prefix?: string): string;
/** Scan an app directory and build all route tables. */
declare function buildRouter(appDir: string, opts?: RouterOptions): Router;

export { type ComponentRef, type ExternalRouteDefinition, type NamedRoute, type Route, type RouteManifestEntry, type RouteMatch, type Router, type RouterOptions, buildRouter, compileRoutePattern, createRouteManifest, fileToRoute, findNamedRoute, findRouteConflicts, generateRoutesFile, getRouteParams, matchRoute, nameRoutes, routeName, routeUrl, sortRoutes };
```

---

## @wrnexus/ssr

Documentation URL: https://wrnexusjs.dev/packages/ssr

# @wrnexus/ssr

> Server-side rendering: wraps a page's HTML body in a complete HTML document with a metadata-driven `<head>`.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

Pages in WrNexus return an HTML string for the body. `@wrnexus/ssr` takes that body and produces a full HTML document — building the `<head>` from page metadata and global SEO defaults, resolving canonical/Open Graph/Twitter tags, and injecting module preloads and `<script type="module">` tags. It is deliberately server-only: nothing in this package touches the DOM or ships to the browser, keeping server code genuinely server-only. Reach for it on the server when turning a rendered page body into a response document.

## Installation

```bash
bun add @wrnexus/ssr
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported).

## API

The package has a single export.

### `renderDocument(opts: RenderOptions): string`

Renders a complete HTML document as a string, beginning with `<!doctype html>`. All metadata is HTML-escaped (via `escapeHtml` from `@wrnexus/core`), so a malicious title or description cannot break out of its element or attribute. The body is placed inside `<div id="app">`.

#### `RenderOptions`

| Field          | Type        | Description                                                                                                                                    |
| -------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `meta`         | `PageMeta`  | Page metadata for the document head (required).                                                                                                |
| `body`         | `string`    | Rendered HTML for the body, placed inside `#app` (required).                                                                                   |
| `seo`          | `SeoConfig` | Global SEO defaults, typically from `wrnexus.config.ts`.                                                                                       |
| `url`          | `URL`       | Current request URL, used to resolve canonical/Open Graph URLs.                                                                                |
| `scripts`      | `string[]`  | URLs of `<script type="module">` tags to load (e.g. per-island chunks or the reactive runtime). Each also gets a `<link rel="modulepreload">`. |
| `defaultTitle` | `string`    | Default document title used when `meta.title` is absent.                                                                                       |
| `extraHead`    | `string`    | Raw HTML injected at the end of `<head>` (trusted, framework-controlled — not escaped).                                                        |
| `extraBody`    | `string`    | Raw HTML injected at the end of `<body>` (trusted, framework-controlled — not escaped).                                                        |
| `htmlAttrs`    | `string`    | Attributes for the `<html>` element, e.g. ` data-theme="dark"` (trusted).                                                                      |

`PageMeta` and `SeoConfig` come from `@wrnexus/core`. `PageMeta` is an alias of `SeoConfig`, whose fields are all optional:

```ts
type SeoConfig = {
  title?: string;
  titleTemplate?: string; // e.g. "%s — My Site"; %s is replaced with the page title
  description?: string;
  canonical?: string;
  canonicalBase?: string; // origin used to absolutize canonical/image URLs
  robots?: string;
  keywords?: string | string[];
  image?: string;
  siteName?: string;
  type?: string; // Open Graph type; defaults to "website"
  locale?: string;
  twitterCard?: string; // defaults to "summary"
  twitterSite?: string;
  themeColor?: string;
};
```

#### Metadata resolution

`renderDocument` merges page metadata (`meta`) over global defaults (`seo`), field by field, so per-page values win. Notable behavior:

- **Title**: uses `meta.title`, else `seo.title`, else `defaultTitle`, else `"WrNexus"`. When the page sets its own title and `seo.titleTemplate` contains `%s`, the template is applied.
- **Canonical / image URLs**: resolved against `canonicalBase` (or the request `url`'s origin) into absolute URLs when possible.
- **Keywords**: an array is joined with `", "`.
- **Emitted tags**: `<title>`, and as applicable `description`, `robots`, `keywords`, `theme-color`, and `canonical` link, plus Open Graph (`og:title`, `og:description`, `og:type`, `og:url`, `og:site_name`, `og:locale`, `og:image`) and Twitter (`twitter:card`, `twitter:title`, `twitter:description`, `twitter:image`, `twitter:site`) meta tags. The document always includes `charset`, `viewport`, and a `/favicon.ico` icon link.

## Usage

### Render an SEO-ready application page

```ts
import { renderDocument } from "@wrnexus/ssr";

const html = renderDocument({
  meta: {
    title: "About Us",
    description: "Learn more about our team.",
  },
  seo: {
    titleTemplate: "%s — Acme",
    siteName: "Acme",
    canonicalBase: "https://acme.example",
    twitterSite: "@acme",
  },
  url: new URL("https://acme.example/about"),
  body: "<h1>About Us</h1>",
  scripts: ["/_wire/runtime.js", "/_wire/islands/about.js"],
  htmlAttrs: ' data-theme="dark"',
});

return new Response(html, {
  headers: { "content-type": "text/html; charset=utf-8" },
});
```

The produced document has `<title>About Us — Acme</title>`, the SEO/Open Graph/Twitter tags derived from the merged metadata, a `modulepreload` link and module `<script>` for each entry in `scripts`, and the body wrapped in `<div id="app">`.

### Add trusted framework assets and boot data

Use `extraHead` and `extraBody` only for HTML generated by your application or the
framework. User-provided values belong in `meta`, where they are escaped.

```ts
const html = renderDocument({
  meta: { title: "Dashboard", robots: "noindex" },
  body: dashboardHtml,
  url: ctx.url,
  extraHead: '<link rel="stylesheet" href="/_wrnexus/admin.css">',
  extraBody: `<script type="application/json" id="boot">${JSON.stringify(bootData).replaceAll("<", "\\u003c")}</script>`,
});

return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } });
```

## Requirements / Notes

- **Server-only.** This module never imports or touches the DOM and is safe to keep out of client bundles.
- **Depends on [`@wrnexus/core`](../core)** for `escapeHtml` and the `PageMeta` / `SeoConfig` types.
- **Bun-only** — like the rest of WrNexus, this package targets the Bun runtime (Node is not supported).

### Exported TypeScript declarations

```ts
import { PageMeta, SeoConfig } from '@wrnexus/core';

/**
 * @wrnexus/ssr — server-side rendering.
 *
 * Pages return an HTML string for the body; this module wraps that body in a
 * full document with a `<head>` built from page metadata. It is intentionally
 * isolated from any client runtime: nothing here touches the DOM or ships to
 * the browser, which keeps "server-only code" genuinely server-only.
 */

interface ScriptAsset {
    src: string;
    /** Module scripts are the default for backward compatibility. */
    type?: "module" | "classic";
    async?: boolean;
    defer?: boolean;
    integrity?: string;
    crossOrigin?: "anonymous" | "use-credentials";
    nonce?: string;
    attributes?: Record<string, string | boolean>;
}
type RenderScript = string | ScriptAsset;
interface RenderOptions {
    /** Page metadata for the document head. */
    meta: PageMeta;
    /** Global SEO defaults from `wrnexus.config.ts`. */
    seo?: SeoConfig;
    /** Current request URL, used to resolve canonical/Open Graph URLs. */
    url?: URL;
    /** Rendered HTML for the body (placed inside `#app`). */
    body: string;
    /**
     * URLs of `<script type="module">` tags to load (e.g. per-island chunks or
     * the reactive runtime). Only the scripts a page actually needs are passed.
     */
    scripts?: RenderScript[];
    /** Optional default document title used when meta.title is absent. */
    defaultTitle?: string;
    /** Raw HTML injected at the end of `<head>` (trusted, framework-controlled). */
    extraHead?: string;
    /** Raw HTML injected at the end of `<body>` (trusted, framework-controlled). */
    extraBody?: string;
    /** Attributes for the `<html>` element, e.g. ` data-theme="dark"` (trusted). */
    htmlAttrs?: string;
    /**
     * Optional application-authored full document shell. It must contain
     * `<html>`, `<head>`, and `<body>`. Framework metadata, assets, and scripts
     * are merged into it instead of wrapping the rendered body again.
     */
    documentTemplate?: string;
}
/**
 * Render a complete HTML document.
 *
 * Metadata is HTML-escaped so a malicious title/description can never break
 * out of its element or attribute.
 */
declare function renderDocument(opts: RenderOptions): string;
interface StreamRenderOptions extends Omit<RenderOptions, "body"> {
    body: string | Promise<string> | AsyncIterable<string>;
}
/**
 * Stream a complete document while preserving the exact head/body contract of
 * `renderDocument`. Async iterables can flush a shell, primary content, and
 * slower fragments without buffering the entire route.
 */
declare function renderDocumentStream(opts: StreamRenderOptions): ReadableStream<Uint8Array>;
declare function streamDocumentResponse(opts: StreamRenderOptions, init?: ResponseInit): Response;

export { type RenderOptions, type RenderScript, type ScriptAsset, type StreamRenderOptions, renderDocument, renderDocumentStream, streamDocumentResponse };
```

---

## @wrnexus/styles

Documentation URL: https://wrnexusjs.dev/packages/styles

# @wrnexus/styles

> Global CSS bundling, the `--wire-*` design-token theme system, and the `wrnexus.config.ts` app-config loader for WrNexus apps.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

This package owns three server-side concerns that shape every page a WrNexus app renders:

1. **Global stylesheet pipeline** — finds `app/styles/global.css` (or aggregates `app/styles/*.css`), bundles it with Bun's CSS bundler (which resolves `@import`, including from `node_modules`), and produces one stylesheet that is `<link>`ed into every page's `<head>`. Because it is a plain global sheet, it styles server-rendered markup and hydrated client islands identically. A custom `process` hook lets you swap in Tailwind / PostCSS / Sass.
2. **Theme system** — design tokens exposed as CSS custom properties (`--wire-<key>`), with built-in `light`/`dark` sets, deep-merged user overrides, an SSR `<html data-theme>` render (no flash), and a tiny client runtime to toggle/persist the choice.
3. **App config** — loads `wrnexus.config.ts` (the `AppConfig` type), applies named profile overrides, and loads the `.env` cascade.

It runs server-side / at build time. Reach for it when configuring an app, defining themes, or customising how global CSS is produced.

## Installation

```bash
bun add @wrnexus/styles
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported).

## API

Everything is exported from the package root (`@wrnexus/styles`).

### Config loading

| Export           | Signature                                                      | Purpose                                                                                                                               |
| ---------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `loadAppConfig`  | `(appRoot: string, profile?: string) => Promise<AppConfig>`    | Load `wrnexus.config.*` with the active profile deep-merged in (`profiles` stripped from the result).                                 |
| `loadRawConfig`  | `(appRoot: string) => Promise<AppConfig>`                      | Load the raw config with the `profiles` map intact; returns `{}` if no config file exists.                                            |
| `resolveProfile` | `(options?: { explicit?; mode? }) => string`                   | Resolve the active profile: explicit arg > `WRNEXUS_PROFILE` env var > mode-based default (`production` in prod, else `development`). |
| `loadEnv`        | `(appRoot: string, profile: string) => Record<string, string>` | Load the `.env` cascade for a profile into `process.env` without clobbering real env vars. Returns what it loaded.                    |
| `headToString`   | `(head?: string \| string[]) => string`                        | Flatten `AppConfig.head` into a single HTML string.                                                                                   |

Config file names probed, in order: `wrnexus.config.ts`, `wrnexus.config.js`, `wrnexus.config.mjs`.

`.env` cascade precedence (low → high): `.env` < `.env.<profile>` < `.env.local` < `.env.<profile>.local`. Variables already present in the real environment always win.

### `AppConfig`

The type of the object your `wrnexus.config.ts` default-exports. Every field is optional.

| Field       | Type                                                                    | Description                                                                                                                                                          |
| ----------- | ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `head`      | `string \| string[]`                                                    | Raw HTML appended to every page's `<head>` (e.g. CDN stylesheet/script links).                                                                                       |
| `seo`       | `SeoConfig`                                                             | Global SEO defaults, merged with each page's exported `meta`. (from `@wrnexus/core`)                                                                                 |
| `security`  | `SecurityConfig`                                                        | Framework security headers and optional CORS policy. (from `@wrnexus/core`)                                                                                          |
| `styles`    | `StylesConfig`                                                          | Global stylesheet pipeline config (see below).                                                                                                                       |
| `theme`     | `ThemeConfig`                                                           | Design-token themes, deep-merged over the built-in light/dark.                                                                                                       |
| `i18n`      | `{ default?: string; locales?: string[] }`                              | Default language + supported locales (strings live in `app/locales/*.json`).                                                                                         |
| `db`        | `{ driver: "sqlite" \| "postgres" \| "mysql" \| "mongo"; url: string }` | Default database connection; reached with `getDb()`.                                                                                                                 |
| `databases` | `Record<string, { driver; url }>`                                       | Additional named databases, reached with `getDb("<name>")`; each has its own `app/db/<name>/` migrations/queries.                                                    |
| `realtime`  | `{ scale?: boolean; redisUrl?: string }`                                | When `scale` is true (or `redisUrl` is set), room broadcasts bridge over Redis pub/sub so they reach clients on every app process.                                   |
| `port`      | `number`                                                                | Default server port.                                                                                                                                                 |
| `profiles`  | `Record<string, Partial<Omit<AppConfig, "profiles">>>`                  | Named profiles (dev, prod, uat, test, …). The active profile's overrides are deep-merged over the base config. Selected via `--profile=<name>` or `WRNEXUS_PROFILE`. |

### Styles pipeline

| Export           | Signature                                                              | Purpose                                                                                                                                                                                                     |
| ---------------- | ---------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `findStyleEntry` | `(appDir, appRoot, override?) => string \| null`                       | Resolve the CSS entry: `override` (relative to `appRoot`) → `app/styles/global.css` → an aggregate of all `app/styles/*.css` (written to `app/.wrnexus/styles-entry.css`). `null` if the app has no styles. |
| `bundleCss`      | `(entryPath: string, mode: Mode) => Promise<string>`                   | Bundle an entry with `Bun.build` (CSS bundler). Resolves `@import` (local + node_modules), handles nesting, minifies when `mode === "production"`.                                                          |
| `renderStyles`   | `(ctx: StyleProcessContext, styles?: StylesConfig) => Promise<string>` | Produce final CSS: runs `styles.process(ctx)` if provided, else `bundleCss`. Returns `""` when `ctx.entryPath` is null.                                                                                     |

`StylesConfig`:

```ts
interface StylesConfig {
  /** CSS entry path relative to the app root. Default: app/styles/global.css */
  entry?: string;
  /** Custom processor — return the final CSS string (Tailwind/PostCSS/Sass). */
  process?: (ctx: StyleProcessContext) => string | Promise<string>;
}

interface StyleProcessContext {
  entryPath: string | null; // resolved absolute CSS entry, or null
  appDir: string;
  appRoot: string;
  mode: Mode; // "development" | "production"
}
```

### Theme system

| Export               | Type / Signature                                                     | Purpose                                                                                                                                    |
| -------------------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `DEFAULT_THEMES`     | `Record<string, ThemeTokens>`                                        | Built-in `light` and `dark` token maps.                                                                                                    |
| `THEME_COOKIE`       | `"wire-theme"`                                                       | Cookie the resolved theme is read from / persisted to.                                                                                     |
| `THEME_CSS_HREF`     | `"/__wrnexus/theme.css"`                                             | URL the generated theme stylesheet is served at.                                                                                           |
| `THEME_JS_HREF`      | `"/__wrnexus/theme.js"`                                              | URL the client theme runtime is served at.                                                                                                 |
| `resolveThemeConfig` | `(config?: ThemeConfig) => ResolvedTheme`                            | Deep-merge the user's `theme` config over the defaults; pick the default theme (config's `default` if valid, else `dark`, else the first). |
| `resolveThemeName`   | `(cookieValue: string \| undefined, theme: ResolvedTheme) => string` | Pick a valid theme name from a cookie, falling back to `theme.default`.                                                                    |
| `renderThemeCss`     | `(theme: ResolvedTheme) => string`                                   | Generate the theme stylesheet: a `:root{…}` default plus one `[data-theme="<name>"]{…}` block per theme.                                   |
| `renderThemeRuntime` | `(theme: ResolvedTheme) => string`                                   | Generate the client runtime (see below).                                                                                                   |

Tokens are emitted as `--wire-<key>` custom properties, **except** the reserved key `color-scheme`, which is emitted as the native `color-scheme` CSS property so form controls and scrollbars match the theme.

`ThemeConfig` / `ThemeTokens` / `ResolvedTheme`:

```ts
type ThemeTokens = Record<string, string>;

interface ThemeConfig {
  palette?: ThemePaletteName | CustomThemePalette;
  default?: string; // theme used when no cookie is present
  themes?: Record<string, ThemeTokens>; // deep-merged over built-in light/dark
}

interface ResolvedTheme {
  default: string;
  names: string[];
  themes: Record<string, ThemeTokens>;
}
```

Built-in palettes are `blue`, `indigo`, `violet`, `emerald`, `cyan`, `rose`,
`amber`, and `slate`. Each supplies primary, secondary, info, success, warning,
danger/error, hover, and contrast colors to every light/dark theme. Built-in
token keys also include surfaces, text, borders, radii, fonts, and shadows.

A custom palette is intentionally complete, so components never fall back to an
unrelated blue status or action color:

```ts
theme: {
  palette: {
    primary: "#7c3aed",
    primaryHover: "#6d28d9",
    primaryContrast: "#ffffff",
    secondary: "#db2777",
    secondaryHover: "#be185d",
    secondaryContrast: "#ffffff",
    info: "#2563eb",
    success: "#059669",
    warning: "#d97706",
    danger: "#dc2626",
  },
}
```

The client runtime (`renderThemeRuntime`) exposes `window.wireTheme` with `{ get, set, toggle, bind, themes }`, wires up any `[data-wire-theme-toggle]` and `[data-wire-theme-set]` elements on load, and persists the choice to the `wire-theme` cookie (`max-age` 1 year, `samesite=lax`). `toggle()` cycles through the configured theme names in order.

## Usage

### `wrnexus.config.ts`

```ts
import type { AppConfig } from "@wrnexus/styles";

export default {
  head: [
    '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5/dist/css/bootstrap.min.css">',
  ],
  port: 3000,
  db: { driver: "sqlite", url: "app.db" },
  theme: {
    palette: "violet",
    default: "dark",
    themes: {
      light: { "color-primary": "#7c3aed" }, // override one token; rest inherited
      brand: {
        // add a whole new theme
        "color-scheme": "dark",
        "color-bg": "#0a0a0a",
        "color-primary": "#22d3ee",
      },
    },
  },
  styles: {
    entry: "app/styles/main.css",
  },
  profiles: {
    production: {
      db: { driver: "postgres", url: process.env.DATABASE_URL! },
    },
  },
} satisfies AppConfig;
```

### Loading config + producing CSS

```ts
import {
  loadAppConfig,
  resolveProfile,
  loadEnv,
  findStyleEntry,
  renderStyles,
} from "@wrnexus/styles";

const appRoot = process.cwd();
const mode = "production" as const;

const profile = resolveProfile({ mode });
loadEnv(appRoot, profile);

const config = await loadAppConfig(appRoot, profile);

const appDir = `${appRoot}/app`;
const entryPath = findStyleEntry(appDir, appRoot, config.styles?.entry);
const css = await renderStyles({ entryPath, appDir, appRoot, mode }, config.styles);
```

### Rendering the theme

```ts
import {
  resolveThemeConfig,
  resolveThemeName,
  renderThemeCss,
  renderThemeRuntime,
  THEME_COOKIE,
} from "@wrnexus/styles";

const theme = resolveThemeConfig(config.theme);

// Server: pick the active theme from the request cookie (no flash).
const active = resolveThemeName(cookies[THEME_COOKIE], theme);
// → render <html data-theme={active}>

const themeCss = renderThemeCss(theme); // served at THEME_CSS_HREF
const themeJs = renderThemeRuntime(theme); // served at THEME_JS_HREF
```

In templates, consume tokens via the custom properties:

```css
.card {
  background: var(--wire-color-surface);
  color: var(--wire-color-text);
  border: 1px solid var(--wire-color-border);
  border-radius: var(--wire-radius);
  box-shadow: var(--wire-shadow-1);
}
```

```html
<button data-wire-theme-toggle>Toggle theme</button>
<button data-wire-theme-set="brand">Brand theme</button>
```

## Requirements / Notes

- **Bun-only.** `bundleCss` uses `Bun.build`'s CSS bundler for `@import` resolution, nesting, and minification. Node is not supported.
- Config and env loading use `node:fs` / `node:path` / `node:url` and read from `process.env`.
- Peer package: `@wrnexus/core` supplies the `SeoConfig` and `SecurityConfig` types referenced by `AppConfig`.
- The bundled global stylesheet, the theme stylesheet (`THEME_CSS_HREF`), and the theme runtime (`THEME_JS_HREF`) are wired into pages by the framework's server; this package only produces their contents.

### Exported TypeScript declarations

```ts
import { PerformanceBudgets, SeoConfig, SecurityConfig } from '@wrnexus/core';
import { PluginInput } from '@wrnexus/plugin';
import { StorageConfig } from '@wrnexus/uploader';

/**
 * Theme system - design tokens that work SSR and client-side.
 *
 * Tokens are plain CSS custom properties (`--wire-<key>`) so they cascade and
 * can be overridden by user CSS. Each theme is a flat token map; the framework
 * ships default `light`/`dark` sets and the user's config deep-merges over them.
 *
 * The server renders both `<html data-theme="...">` and
 * `<html data-accent="...">` from cookies, so the correct theme and accent are
 * present before the first paint. The reserved token key `color-scheme` is
 * emitted as the native CSS property instead of a custom property.
 */
type ThemeTokens = Record<string, string>;
declare const THEME_PALETTE_NAMES: readonly ["blue", "indigo", "violet", "emerald", "cyan", "rose", "amber", "slate"];
type ThemePaletteName = (typeof THEME_PALETTE_NAMES)[number];
/** Required semantic colors for a custom application palette. */
interface CustomThemePalette {
    primary: string;
    primaryHover: string;
    primaryContrast: string;
    secondary: string;
    secondaryHover: string;
    secondaryContrast: string;
    info: string;
    success: string;
    warning: string;
    danger: string;
}
interface ThemeAccentConfig {
    /**
     * Accent used when no `wire-accent` cookie is present.
     *
     * - Omitted: use the named `palette`, or `blue` when no palette is configured.
     * - `false`: keep the configured base palette until the user explicitly picks an accent.
     */
    default?: ThemePaletteName | false;
    /** Runtime-selectable accent names. Defaults to every built-in THEME_PALETTE. */
    options?: ThemePaletteName[];
}
interface ThemeConfig {
    /** Built-in palette name, or a complete custom semantic color palette. */
    palette?: ThemePaletteName | CustomThemePalette;
    /** Runtime accent/palette switcher configuration. */
    accent?: ThemeAccentConfig;
    /** Name of the theme used when no `wire-theme` cookie is present. */
    default?: string;
    /** Named token maps. Deep-merged over the framework's built-in light/dark. */
    themes?: Record<string, ThemeTokens>;
}
interface ResolvedTheme {
    default: string;
    names: string[];
    themes: Record<string, ThemeTokens>;
    defaultAccent?: ThemePaletteName;
    accentNames: ThemePaletteName[];
}
/** Cookies used by the SSR renderer and client runtime. */
declare const THEME_COOKIE = "wire-theme";
declare const ACCENT_COOKIE = "wire-accent";
declare const THEME_CSS_HREF = "/__wrnexus/theme.css";
declare const THEME_JS_HREF = "/__wrnexus/theme.js";
/**
 * Single source of truth for both configured palettes and runtime accents.
 * Do not create a second hard-coded ACCENTS map in the browser runtime.
 */
declare const THEME_PALETTES: Record<ThemePaletteName, CustomThemePalette>;
/** Built-in themes so components have tokens out of the box. */
declare const DEFAULT_THEMES: Record<string, ThemeTokens>;
/** Merge the user's theme config over the built-in defaults. */
declare function resolveThemeConfig(config?: ThemeConfig): ResolvedTheme;
/** Pick a valid theme name from a cookie value, falling back to the default. */
declare function resolveThemeName(cookieValue: string | undefined, theme: ResolvedTheme): string;
/** Pick a valid accent name from a cookie value, falling back to the configured default. */
declare function resolveAccentName(cookieValue: string | undefined, theme: ResolvedTheme): ThemePaletteName | undefined;
/**
 * Generate the theme stylesheet.
 *
 * Theme selectors are emitted first. Accent selectors are emitted afterwards,
 * so a selected accent consistently overrides every semantic palette token,
 * including soft/muted/text variants, before the first paint.
 */
declare function renderThemeCss(theme: ResolvedTheme): string;
/**
 * Generate the client theme runtime. It exposes `window.wireTheme` and
 * `window.wireAccent`, and binds theme/accent controls.
 *
 * The runtime changes only data attributes and cookies. It never writes inline
 * CSS variables and never uses localStorage, so CSS and SSR remain the single
 * source of truth.
 */
declare function renderThemeRuntime(theme: ResolvedTheme): string;

/**
 * Font configuration.
 *
 * Declare fonts in `wrnexus.config.ts` under `fonts` and the framework emits
 * optimized `<head>` markup for you:
 *   - Google Fonts: `preconnect` hints + a single subsetted stylesheet request
 *     (only the weights you list) with `font-display`. The CSP is auto-extended
 *     so the fonts load under the default security policy (see loadAppConfig).
 *   - Self-hosted fonts: generated `@font-face` rules + optional `<link rel=preload>`
 *     for above-the-fold text (the fastest, no-third-party option).
 *   - Family stacks: `sans`/`mono`/`serif` become `--wrn-font-*` CSS variables,
 *     and `sans` is applied to `body`.
 */
type FontDisplay = "auto" | "block" | "swap" | "fallback" | "optional";
interface GoogleFont {
    /** Family name as it appears on fonts.google.com, e.g. "Inter". */
    family: string;
    /** Weights to load — ONLY these are fetched. Default: [400]. */
    weights?: (number | string)[];
    /** Also load italic styles for each weight. */
    italic?: boolean;
    /** Per-font `font-display` override (else the config default). */
    display?: FontDisplay;
}
interface LocalFontFace {
    /** `font-family` name this face defines. */
    family: string;
    /** URL to the font file, typically served from `public/` (e.g. "/fonts/inter.woff2"). */
    src: string;
    /** e.g. 400, "700", or "100 900" for a variable font. Default: 400. */
    weight?: number | string;
    style?: "normal" | "italic";
    /** CSS `src` format; inferred from the file extension when omitted. */
    format?: string;
    display?: FontDisplay;
    /** Emit `<link rel="preload" as="font">` — use for the primary above-the-fold face. */
    preload?: boolean;
    /** Optional `unicode-range` subset. */
    unicodeRange?: string;
}
interface FontConfig {
    /** Google Fonts, loaded with preconnect + weight subsetting + `font-display`. */
    google?: GoogleFont[];
    /** Self-hosted `@font-face` definitions (files served from `public/`). */
    local?: LocalFontFace[];
    /** Default `font-display` for faces that don't set their own. Default: "swap". */
    display?: FontDisplay;
    /** Body / default family stack → `--wrn-font-sans` + `body { font-family }`. */
    sans?: string;
    /** Monospace family stack → `--wrn-font-mono`. */
    mono?: string;
    /** Serif family stack → `--wrn-font-serif`. */
    serif?: string;
}
/**
 * Render all `<head>` markup for a font config. Returns "" when nothing is
 * configured. The output is trusted, framework-controlled HTML.
 */
declare function renderFontHead(fonts?: FontConfig): string;
/**
 * Production variant that inlines the small Google Fonts stylesheet at build
 * time. This removes a render-blocking CSS round trip while retaining the same
 * font files, `font-display`, CSP sources, and offline-safe fallback markup.
 */
declare function renderProductionFontHead(fonts?: FontConfig, fetcher?: (input: string, init?: RequestInit) => Promise<Response>): Promise<string>;
/**
 * CSP source hosts required by the configured fonts, so the policy can be
 * auto-extended (Google Fonts need their CSS + static hosts allow-listed).
 */
declare function fontCspSources(fonts?: FontConfig): {
    style: string[];
    font: string[];
};

/**
 * App configuration loader (`wrnexus.config.ts`).
 *
 * The config is optional. It lets an app inject arbitrary `<head>` HTML (ideal
 * for CDN-delivered CSS frameworks like Bootstrap or the Tailwind Play CDN) and
 * customise the global stylesheet pipeline (entry file or a custom processor for
 * Tailwind / PostCSS / Sass).
 */

type Mode = "development" | "production";
interface StyleProcessContext {
    /** Resolved absolute path to the CSS entry, or null if there is none. */
    entryPath: string | null;
    /** Original application entry when a package-aware wrapper was generated. */
    originalEntryPath?: string | null;
    /** Package component/style directories that processors should scan. */
    sources?: string[];
    /** Package-owned CSS entries automatically imported into the application bundle. */
    entries?: string[];
    appDir: string;
    appRoot: string;
    mode: Mode;
}
interface StylesConfig {
    /** Path to the CSS entry, relative to the app root. Default: app/styles/global.css */
    entry?: string;
    /**
     * Optional custom processor. Return the final CSS string. Use this to run
     * Tailwind, PostCSS, Sass, etc. When omitted, the built-in Bun CSS bundler is
     * used (which already resolves `@import`, including from node_modules).
     */
    process?: (ctx: StyleProcessContext) => string | Promise<string>;
    /** Automatically append package scan sources to custom processor input. Default true. */
    includePackageSources?: boolean;
    /** Production defaults to throw; development defaults to best-effort fallback. */
    failureMode?: "throw" | "fallback";
}
interface MobileConfig {
    enabled?: boolean;
    /** Mobile renderer. `webview` uses Capacitor; `native` scaffolds an Expo/React Native app. */
    mode?: "webview" | "native";
    appId?: string;
    appName?: string;
    serverUrl?: string;
    userAgent?: string;
    layout?: string;
    backgroundColor?: string;
    icon?: string;
    errorTitle?: string;
    errorMessage?: string;
    /** Base URL used by a fully native client for WrNexus API and realtime requests. */
    apiUrl?: string;
    /** URL scheme used for native deep links (defaults to a slug of appName). */
    scheme?: string;
    /** Advanced Expo app config fields merged into generated app.config.ts. */
    expo?: Record<string, unknown>;
    /** Advanced CapacitorConfig fields merged into generated capacitor.config.ts. */
    capacitor?: Record<string, unknown>;
}
interface PwaScreenshot {
    src: string;
    sizes: string;
    type?: string;
    formFactor?: "wide" | "narrow";
    label?: string;
}
interface PwaShortcut {
    name: string;
    shortName?: string;
    description?: string;
    url: string;
    icons?: Array<{
        src: string;
        sizes: string;
        type?: string;
        purpose?: string;
    }>;
}
interface PwaConfig {
    enabled?: boolean;
    id?: string;
    name?: string;
    shortName?: string;
    description?: string;
    startUrl?: string;
    scope?: string;
    lang?: string;
    display?: "standalone" | "fullscreen" | "minimal-ui" | "browser";
    orientation?: "any" | "natural" | "landscape" | "landscape-primary" | "landscape-secondary" | "portrait" | "portrait-primary" | "portrait-secondary";
    themeColor?: string;
    backgroundColor?: string;
    icons?: Array<{
        src: string;
        sizes: string;
        type?: string;
        purpose?: string;
    }>;
    categories?: string[];
    screenshots?: PwaScreenshot[];
    shortcuts?: PwaShortcut[];
    /** Disable service-worker registration while keeping the web manifest. */
    serviceWorker?: boolean;
    /** Navigation shown when both the network and requested page cache are unavailable. */
    offlineUrl?: string;
    /** Additional same-origin URLs precached during service-worker installation. */
    cacheUrls?: string[];
    /** Service-worker cache key. Change it to invalidate existing PWA caches. */
    cacheName?: string;
}
type DevToolbarPosition = "bottom-center" | "bottom-left" | "bottom-right";
interface DevToolbarConfig {
    enabled?: boolean;
    position?: DevToolbarPosition;
    defaultOpen?: boolean;
    keyboardShortcut?: string;
    scanOnNavigation?: boolean;
    scanOnHmr?: boolean;
    openEditor?: boolean;
    editor?: string;
    rules?: Partial<Record<string, boolean>>;
    severity?: Partial<Record<string, "error" | "warning" | "info" | "suggestion">>;
    ignoredRules?: string[];
    ignoredPaths?: string[];
    slowRequestMs?: number;
    largeImageBytes?: number;
    veryLargeImageBytes?: number;
}
interface ExperimentalConfig {
    serverComponents?: boolean;
    streaming?: boolean;
    partialHydration?: boolean;
    typedRpc?: boolean;
    pluginTransforms?: boolean;
    [feature: string]: boolean | undefined;
}
interface PerformanceConfig {
    budgets?: PerformanceBudgets;
    /** `warn` reports budget violations; `error` fails production builds. */
    enforcement?: "off" | "warn" | "error";
    analyze?: boolean;
}
interface ObservabilityConfig {
    enabled?: boolean;
    serviceName?: string;
    serverTiming?: boolean;
    sampleRate?: number;
    exporter?: "console" | "otlp" | "none";
    endpoint?: string;
}
interface TenancyConfig {
    mode?: "subdomain" | "domain" | "path" | "custom";
    required?: boolean;
    rootDomains?: string[];
    pathPrefix?: string;
}
interface BuildConfig {
    cache?: boolean;
    cacheDir?: string;
    sourceMaps?: boolean;
    report?: boolean;
    adapter?: "bun" | "node" | "static" | "serverless" | "edge" | string;
}
interface NavigationConfig {
    /**
     * `client` progressively enhances same-origin links with in-place page swaps.
     * `document` keeps normal browser navigation so every route performs a fresh
     * server-rendered document request.
     */
    mode?: "client" | "document";
}
interface AppConfig {
    /** Compiler/dev/build plugins, resolved in deterministic pre/normal/post order. */
    plugins?: PluginInput;
    /** Opt-in APIs that are not yet covered by stable compatibility guarantees. */
    experimental?: ExperimentalConfig;
    /** Route and asset budgets plus build analyzer behavior. */
    performance?: PerformanceConfig;
    /** Request tracing, Server-Timing, and exporter configuration. */
    observability?: ObservabilityConfig;
    /** First-class tenant resolution defaults. */
    tenancy?: TenancyConfig;
    /** Build cache, source map, report, and deployment adapter settings. */
    build?: BuildConfig;
    /** Page navigation strategy. Defaults to progressive client navigation. */
    navigation?: NavigationConfig;
    /** Development-only page diagnostics toolbar. Enabled by default in development. */
    devToolbar?: boolean | DevToolbarConfig;
    /** Raw HTML appended to every page's `<head>` (e.g. CDN stylesheet links). */
    head?: string | string[];
    /** Global SEO defaults merged with every page's exported `meta`. */
    seo?: SeoConfig;
    /** Framework security headers and optional CORS policy. */
    security?: SecurityConfig;
    styles?: StylesConfig;
    /** Capacitor/native shell defaults and mobile-only page rendering. */
    mobile?: MobileConfig;
    /** Progressive Web App metadata. Enabled by default unless set to false. */
    pwa?: PwaConfig | false;
    /**
     * Fonts. Declare Google Fonts (subsetted + preconnect + `font-display`) and/or
     * self-hosted `@font-face` (with preload), and set `sans`/`mono`/`serif` family
     * stacks. Google Fonts auto-extend the CSP so they load under the default policy.
     */
    fonts?: FontConfig;
    /** Design-token themes (deep-merged over the built-in light/dark). */
    theme?: ThemeConfig;
    /** i18n: default language + supported locales (strings live in app/locales/*.json). */
    i18n?: {
        default?: string;
        locales?: string[];
    };
    /** Default database connection (driver + url); reached with `getDb()`. */
    db?: {
        driver: "sqlite" | "postgres" | "mysql" | "mongo";
        url: string;
    };
    /**
     * File-upload storage. Declare named stores (local dir or S3-compatible),
     * upload with `handleUpload`/`upload` from `@wrnexus/uploader`, and serve
     * files back. Each store is `access: "public" | "private"`.
     */
    storage?: StorageConfig;
    /**
     * Additional named databases, reached with `getDb("<name>")`. Each has its own
     * migrations/queries under `app/db/<name>/`. Connect to as many as you like and
     * read/write to any of them per request.
     *
     *   databases: { analytics: { driver: "postgres", url: "…" } }
     */
    databases?: Record<string, {
        driver: "sqlite" | "postgres" | "mysql" | "mongo";
        url: string;
    }>;
    /**
     * Realtime scaling. When `scale` is true (or `redisUrl` is set), room
     * broadcasts are bridged over Redis pub/sub so they reach clients on **every**
     * app process/instance — realtime that works with multiple running apps.
     */
    realtime?: {
        scale?: boolean;
        redisUrl?: string;
    };
    /** Default server port. */
    port?: number;
    /**
     * Named config profiles (dev, prod, uat, test, …). When a profile is active
     * its overrides are DEEP-MERGED over the base config. Select with
     * `--profile=<name>` or the `WRNEXUS_PROFILE` env var.
     */
    profiles?: Record<string, Partial<Omit<AppConfig, "profiles">>>;
}
/**
 * Resolve the active profile name: explicit argument > `WRNEXUS_PROFILE` env var
 * > a mode-based default ("production" in prod, else "development").
 */
declare function resolveProfile(options?: {
    explicit?: string;
    mode?: Mode;
}): string;
/** Load the raw `wrnexus.config.*` (with the `profiles` map intact), or `{}`. */
declare function loadRawConfig(appRoot: string): Promise<AppConfig>;
/** Load `wrnexus.config.*`, applying the active profile's overrides. */
declare function loadAppConfig(appRoot: string, profile?: string): Promise<AppConfig>;
/**
 * Load the `.env` cascade for a profile into `process.env`, WITHOUT clobbering
 * variables already set in the real environment (which always win). Order, low
 * → high precedence: `.env` < `.env.<profile>` < `.env.local` < `.env.<profile>.local`.
 * Returns the variables it loaded.
 */
declare function loadEnv(appRoot: string, profile: string): Record<string, string>;
interface ConfigIssue {
    path: string;
    severity: "error" | "warning";
    message: string;
}
declare function defineConfig(config: AppConfig): AppConfig;
declare function validateAppConfig(config: AppConfig): ConfigIssue[];
interface ExplainedConfig {
    profile: string;
    config: AppConfig;
    issues: ConfigIssue[];
    sources: string[];
}
declare function explainAppConfig(appRoot: string, profile?: string): Promise<ExplainedConfig>;
/** Flatten a head config into a single HTML string. */
declare function headToString(head?: string | string[]): string;

/**
 * Global stylesheet pipeline.
 *
 * Convention: `app/styles/global.css` is the entry. If it is absent but other
 * `app/styles/*.css` files exist, they are aggregated into one entry. The entry
 * is bundled by Bun's CSS bundler, which resolves `@import` — including from
 * node_modules — so any npm CSS framework (Bootstrap, etc.) works by importing
 * it. A custom `process` hook can replace the bundler for Tailwind/PostCSS/Sass.
 */

/**
 * Resolve the CSS entry for an app.
 *  - `override` (from config.styles.entry) is resolved relative to `appRoot`.
 *  - otherwise prefer `app/styles/global.css`.
 *  - otherwise aggregate all `app/styles/*.css` into a generated entry.
 * Returns null when the app has no styles.
 */
declare function findStyleEntry(appDir: string, appRoot: string, override?: string): string | null;
/**
 * Bundle a CSS entry into a single stylesheet string using Bun's CSS bundler.
 * Resolves `@import` (local and node_modules), handles nesting, minifies in prod.
 */
declare function bundleCss(entryPath: string, mode: Mode): Promise<string>;

interface CssTokenAudit {
    declared: string[];
    used: string[];
    missing: string[];
    unused: string[];
}
/** Audit framework design-token declarations and var() references. */
declare function auditWireTokens(css: string): CssTokenAudit;
interface StyleSource {
    path: string;
    reason?: string;
}
/** Normalize/dedupe Tailwind scan sources without allowing line injection. */
declare function normalizeStyleSources(values: readonly (string | StyleSource)[]): StyleSource[];
declare function tailwindSourceDirectives(values: readonly (string | StyleSource)[]): string;
interface ContrastResult {
    ratio: number;
    level: "fail" | "aa-large" | "aa" | "aaa";
}
declare function contrast(foreground: string, background: string): ContrastResult | null;

/**
 * @wrnexus/styles — global stylesheet pipeline + app config.
 *
 * Works for SSR and CSR: the bundled stylesheet is `<link>`ed into every page's
 * `<head>`, so it styles server-rendered markup and hydrated client islands
 * alike. Use any CSS framework via `@import` in global.css (npm) or via a CDN
 * link in `wrnexus.config.ts`'s `head` field.
 */

/**
 * Produce the final CSS for an entry: run the config's custom processor if one
 * is provided (Tailwind/PostCSS/Sass), otherwise use the built-in Bun bundler.
 *
 * Development can fall back to best-effort CSS. Production throws by default so
 * a deployment cannot silently ship unprocessed Tailwind/PostCSS directives.
 */
declare function renderStyles(ctx: StyleProcessContext, styles?: StylesConfig): Promise<string>;

export { ACCENT_COOKIE, type AppConfig, type BuildConfig, type ConfigIssue, type ContrastResult, type CssTokenAudit, type CustomThemePalette, DEFAULT_THEMES, type DevToolbarConfig, type ExperimentalConfig, type ExplainedConfig, type FontConfig, type FontDisplay, type GoogleFont, type LocalFontFace, type MobileConfig, type Mode, type NavigationConfig, type ObservabilityConfig, type PerformanceConfig, type PwaConfig, type ResolvedTheme, type StyleProcessContext, type StyleSource, type StylesConfig, type Mode as StylesMode, THEME_COOKIE, THEME_CSS_HREF, THEME_JS_HREF, THEME_PALETTES, THEME_PALETTE_NAMES, type TenancyConfig, type ThemeAccentConfig, type ThemeConfig, type ThemePaletteName, type ThemeTokens, auditWireTokens, bundleCss, contrast, defineConfig, explainAppConfig, findStyleEntry, fontCspSources, headToString, loadAppConfig, loadEnv, loadRawConfig, normalizeStyleSources, renderFontHead, renderProductionFontHead, renderStyles, renderThemeCss, renderThemeRuntime, resolveAccentName, resolveProfile, resolveThemeConfig, resolveThemeName, tailwindSourceDirectives, validateAppConfig };
```

---

## @wrnexus/syntax

Documentation URL: https://wrnexusjs.dev/packages/syntax

# @wrnexus/syntax

Canonical WRN lexer, parser, AST, language metadata, source positions, and stable
diagnostics. Framework tooling should import this package instead of implementing a
separate `.wrn` parser.

See `docs/WRN-LANGUAGE-SPEC-1.0.md` in the WRNexusJS repository.

### Exported TypeScript declarations

```ts
export { LexError, Lexer } from './tokenizer.js';
export { ActionBlock, ApiBlock, Attr, ComputedDecl, DataApiBlock, DataMode, EffectBlock, EventDecl, LifecycleBlock, LoadBlock, ModeFunctionsBlock, PageAst, ParseError, PropDecl, RealtimeBlock, RealtimeHandler, SeoBlock, StateDecl, VOID_ELEMENTS, ViewNode, WatchBlock, parse, parseHtmlView } from './parser.js';
export { RuntimeType, eraseFunctionTypes, inferredRuntimeType, runtimeTypeOf, validateTypedInitializer } from './types.js';
import { WrnDiagnostic } from './diagnostics.js';
export { DiagnoseOptions, WrnDiagnosticSeverity, WrnSourcePosition, assertValidAst, classifyParseError, diagnose, diagnosticFromError, formatDiagnostic, isHydrationStrategy, isRuntimeTarget, positionAt } from './diagnostics.js';
export { WRN_DIAGNOSTIC_CODES, WRN_HYDRATION_STRATEGIES, WRN_LANGUAGE_VERSION, WRN_ROOT_KINDS, WRN_ROOT_MEMBERS, WRN_RUNTIME_TARGETS, WrnHydrationStrategy, WrnRootKind, WrnRootMember, WrnRuntimeTarget } from './spec.js';

/** Current stable syntax contract. Bump only when parsers/codegen need migration. */
declare const WRN_SYNTAX_VERSION: "0.4";
type WrnSyntaxFeature = "typed-declarations" | "layouts" | "server-client-blocks" | "effects" | "watch" | "lifecycle" | "embedded-api" | "realtime" | "runtime-markers";
declare const WRN_SYNTAX_FEATURES: Readonly<Record<WrnSyntaxFeature, boolean>>;
interface SourceRange {
    start: number;
    end: number;
}
declare function createSourceRange(start: number, end: number): SourceRange;
declare function sliceSource(source: string, range: SourceRange): string;
declare function diagnosticSummary(diagnostics: readonly WrnDiagnostic[]): {
    errors: number;
    warnings: number;
    info: number;
    codes: Record<string, number>;
};
declare function supportsSyntaxFeature(feature: string): feature is WrnSyntaxFeature;

export { type SourceRange, WRN_SYNTAX_FEATURES, WRN_SYNTAX_VERSION, WrnDiagnostic, type WrnSyntaxFeature, createSourceRange, diagnosticSummary, sliceSource, supportsSyntaxFeature };
```

---

## @wrnexus/test

Documentation URL: https://wrnexusjs.dev/packages/test

# @wrnexus/test

> Testing utilities for WrNexus apps — component rendering, reactive-DOM mounting, route handler calls, and a full in-process app harness, plus a one-import re-export of `bun:test`.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

`@wrnexus/test` is the server-side test toolkit you reach for when writing tests
for a WrNexus app. It runs under `bun test` (invoked via `wrnexus test`) and gives
you a single import surface: the `bun:test` primitives (`test`, `expect`, `mock`,
…) re-exported alongside WrNexus-aware helpers that compile `.wrn` components,
hydrate server HTML in a DOM, invoke API route handlers, and boot the real app on
an ephemeral port for integration tests.

## Installation

```bash
bun add @wrnexus/test
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported).

## API

### Re-exported test primitives

For one-import DX, the following are re-exported straight from `bun:test`:

`test`, `expect`, `describe`, `it`, `beforeEach`, `afterEach`, `beforeAll`,
`afterAll`, `mock`, `spyOn`.

`createContext` is also re-exported from `@wrnexus/core`.

### `renderComponent(source, props?)`

```ts
function renderComponent(source: string, props?: Record<string, unknown>): Promise<string>;
```

Compiles a `.wrn` component `source` string (via `@wrnexus/compiler`) and renders
it to an HTML string with the given `props`. Throws if the compiled module has no
`render` export.

### `mountHtml(html)`

```ts
function mountHtml(html: string): {
  document: Document;
  window: unknown;
  querySelector: (sel: string) => Element | null;
  querySelectorAll: (sel: string) => Element[];
};
```

Mounts server-rendered `html` in a `happy-dom` window with the reactive runtime
hydrated, so you can test `data-scope` / `data-text` / `data-for` / `data-show`
behaviour. Returns the window plus `document` and query helpers; assert on those.

> `happy-dom` is loaded lazily (via `require`), so importing this package never
> requires it unless you actually call `mountHtml`.

### `callRoute(handler, request)`

```ts
function callRoute(
  handler: (ctx: Context) => Response | Promise<Response>,
  request: Request,
): Promise<Response>;
```

Calls an API route `handler` with a `Context` built from a `Request` (using
`createContext`). Returns the handler's `Response`.

### `createHarness(projectRoot, options?)`

```ts
function createHarness(projectRoot: string, options?: HarnessOptions): Promise<Harness>;

interface HarnessOptions {
  /** Config/env profile. Default "test". */
  profile?: string;
}

interface Harness {
  /** Base URL of the ephemeral test server. */
  url: string;
  /** Fetch a path on the app (relative to `url`). */
  fetch(path: string, init?: RequestInit): Promise<Response>;
  /** The scanned router (pages/api/realtime/components). */
  router: unknown;
  /** Stop the server. */
  close(): void;
}
```

Boots the app at `projectRoot` on an ephemeral port (`port: 0`) for integration
tests covering pages, API routes, middleware, and the full request pipeline. Loads
env and app config for the given `profile` (default `"test"`) so it picks up your
test database/env. The server runs in `development` mode with HMR disabled.
Remember to `await app.close()` when done.

## Usage

```ts
import { test, expect, renderComponent, mountHtml, createHarness } from "@wrnexus/test";

test("counter renders its label", async () => {
  const html = await renderComponent(SRC, { start: 3, label: "Hits" });
  expect(html).toContain("Hits");
});

test("reactive scope hydrates", () => {
  const { querySelector } = mountHtml(serverHtml);
  expect(querySelector("[data-text]")?.textContent).toBe("3");
});

test("home page responds", async () => {
  const app = await createHarness("examples/basic-app");
  const res = await app.fetch("/");
  expect(res.status).toBe(200);
  await app.close();
});
```

Calling an API route handler directly:

```ts
import { test, expect, callRoute } from "@wrnexus/test";
import { GET } from "../app/api/health.ts";

test("health endpoint", async () => {
  const res = await callRoute(GET, new Request("http://test/api/health"));
  expect(res.status).toBe(200);
});
```

## Requirements / Notes

- **Bun-only.** Runs under `bun test` (via `wrnexus test`); uses Bun's module
  loading and the `bun:test` runtime.
- `mountHtml` requires **`happy-dom`** to be available in the workspace (loaded
  lazily; it's a dev dependency, not a runtime dependency of this package).
- Works with the rest of the WrNexus toolchain:
  [`@wrnexus/compiler`](../compiler) (compiles `.wrn` sources),
  [`@wrnexus/core`](../core) (`Context` / `createContext`),
  [`@wrnexus/csr`](../csr) (reactive runtime for `mountHtml`),
  [`@wrnexus/dev-server`](../dev-server) (`startServer` behind `createHarness`),
  and [`@wrnexus/styles`](../styles) (config/env/profile loading for the harness).

### Exported TypeScript declarations

```ts
import { ProblemDetails, Context } from '@wrnexus/core';
export { createContext } from '@wrnexus/core';
export { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, mock, spyOn, test } from 'bun:test';

interface TestRequestOptions extends Omit<RequestInit, "body"> {
    body?: BodyInit | Record<string, unknown> | URLSearchParams | FormData | null;
    baseUrl?: string;
}
/** Build a web-standard Request with convenient JSON/FormData handling. */
declare function testRequest(path?: string, options?: TestRequestOptions): Request;
/** Create a complete Context suitable for middleware and route unit tests. */
declare function testContext(path?: string, options?: TestRequestOptions): Context;
interface JsonResponse<T> {
    response: Response;
    body: T;
}
declare function readJsonResponse<T = unknown>(response: Response): Promise<JsonResponse<T>>;
declare function expectProblem(response: Response, status?: number): Promise<ProblemDetails>;
interface Deferred<T> {
    promise: Promise<T>;
    resolve(value: T | PromiseLike<T>): void;
    reject(reason?: unknown): void;
}
declare function deferred<T>(): Deferred<T>;
interface WaitForOptions {
    timeoutMs?: number;
    intervalMs?: number;
    signal?: AbortSignal;
}
/** Poll a condition without depending on fake timers or a browser runtime. */
declare function waitFor(condition: () => boolean | Promise<boolean>, options?: WaitForOptions): Promise<void>;
declare class MemoryCookieJar {
    #private;
    apply(response: Response): void;
    header(): string;
    request(path: string, options?: TestRequestOptions): Request;
    clear(): void;
}

/**
 * @wrnexus/test — testing utilities for WrNexus apps. Runs on `bun test` (via
 * `wrnexus test`). Import everything from one place:
 *
 *   import { test, expect, renderComponent, mountHtml, createHarness } from "@wrnexus/test";
 *
 *   test("counter renders its label", async () => {
 *     const html = await renderComponent(SRC, { start: 3, label: "Hits" });
 *     expect(html).toContain("Hits");
 *   });
 *
 *   test("home page responds", async () => {
 *     const app = await createHarness("examples/basic-app");
 *     const res = await app.fetch("/");
 *     expect(res.status).toBe(200);
 *     await app.close();
 *   });
 */

/** Compile a `.wrn` component source + render it to HTML with the given props. */
declare function renderComponent(source: string, props?: Record<string, unknown>): Promise<string>;
/**
 * Mount server-rendered HTML in a happy-dom window with the reactive runtime
 * hydrated, so you can test `data-scope`/`data-text`/`data-for`/`data-show`
 * behaviour. Returns the window; assert on `win.document`.
 */
declare function mountHtml(html: string): {
    document: Document;
    window: unknown;
    querySelector: (sel: string) => Element | null;
    querySelectorAll: (sel: string) => Element[];
};
/** Call an API route handler with a `Context` built from a Request. */
declare function callRoute(handler: (ctx: Context) => Response | Promise<Response>, request: Request): Promise<Response>;
interface Harness {
    /** Base URL of the ephemeral test server. */
    url: string;
    /** Fetch a path on the app (relative to `url`). */
    fetch(path: string, init?: RequestInit): Promise<Response>;
    /** The scanned router (pages/api/realtime/components). */
    router: unknown;
    /** Stop the server. */
    close(): void;
}
interface HarnessOptions {
    /** Config/env profile. Default "test". */
    profile?: string;
}
/**
 * Boot the app on an ephemeral port for integration tests (pages, API routes,
 * middleware, the full pipeline). Uses the "test" profile by default so it picks
 * up your test database/env. Remember to `await app.close()`.
 */
declare function createHarness(projectRoot: string, options?: HarnessOptions): Promise<Harness>;

export { type Deferred, type Harness, type HarnessOptions, type JsonResponse, MemoryCookieJar, type TestRequestOptions, type WaitForOptions, callRoute, createHarness, deferred, expectProblem, mountHtml, readJsonResponse, renderComponent, testContext, testRequest, waitFor };
```

---

## @wrnexus/tracking

Documentation URL: https://wrnexusjs.dev/packages/tracking

# @wrnexus/tracking

> Error tracking for WrNexus apps: capture exceptions manually or via middleware and fan them out to pluggable sinks.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

`@wrnexus/tracking` is a small, server-side error-capture layer. You create a
tracker with one or more **sinks**, then feed it errors — either manually with
`tracker.capture(err, context)` or automatically by mounting `tracker.middleware()`
in your request pipeline. A `consoleSink` is included; forwarding to Sentry,
Datadog, or any other backend is just a matter of writing a tiny sink. Reach for
it when you want a single, sink-agnostic place to route application errors. Sinks
run best-effort — a throwing sink never breaks the request.

## Installation

```bash
bun add @wrnexus/tracking
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported).

## API

### `createTracker(options?): Tracker`

Creates a tracker. `TrackerOptions`:

| Option       | Type                                        | Description                                                                 |
| ------------ | ------------------------------------------- | --------------------------------------------------------------------------- |
| `sinks`      | `ErrorSink[]`                               | Initial sinks to fan events out to. Defaults to `[]`.                       |
| `now`        | `() => number`                              | Clock used for `event.timestamp` (epoch ms). Defaults to `Date.now`.        |
| `beforeSend` | `(event: ErrorEvent) => ErrorEvent \| null` | Scrub/enrich an event before it reaches any sink. Return `null` to drop it. |

The returned `Tracker`:

| Member       | Signature                                                              | Description                                                                                                                                                                          |
| ------------ | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `capture`    | `(error: unknown, context?: Record<string, unknown>) => Promise<void>` | Normalizes any thrown value into an `Error`, builds an `ErrorEvent`, runs `beforeSend`, then dispatches to all sinks. Non-`Error` values are wrapped in an `Error` named `NonError`. |
| `addSink`    | `(sink: ErrorSink) => void`                                            | Registers an additional sink at runtime.                                                                                                                                             |
| `middleware` | `() => Middleware`                                                     | Returns a WrNexus `Middleware` that captures any error thrown downstream, then re-throws it so the framework's error handler still produces the response.                            |

The middleware attaches this context to captured events:

```ts
{ method: ctx.req.method, path: ctx.url.pathname, requestId: ctx.locals.requestId }
```

### `consoleSink: ErrorSink`

A built-in sink that logs a compact one-line message via `console.error`, e.g.
`[error] TypeError: cannot read x {"userId":42}`.

### Types

```ts
interface ErrorEvent {
  error: Error;
  context: Record<string, unknown>; // request info, user id, tags…
  timestamp: number; // epoch ms
}

interface ErrorSink {
  name?: string;
  capture(event: ErrorEvent): void | Promise<void>;
}
```

## Usage

Manual capture:

```ts
import { createTracker, consoleSink } from "@wrnexus/tracking";

const tracker = createTracker({ sinks: [consoleSink] });

try {
  await doWork();
} catch (err) {
  await tracker.capture(err, { userId: 42, op: "doWork" });
  throw err;
}
```

As request middleware:

```ts
import { createTracker, consoleSink } from "@wrnexus/tracking";

const tracker = createTracker({ sinks: [consoleSink] });

app.use(tracker.middleware()); // captures + re-throws downstream errors
```

A custom sink with `beforeSend` scrubbing:

```ts
import { createTracker, type ErrorSink } from "@wrnexus/tracking";

const sentrySink: ErrorSink = {
  name: "sentry",
  async capture(event) {
    await Sentry.captureException(event.error, { extra: event.context });
  },
};

const tracker = createTracker({
  sinks: [sentrySink],
  beforeSend(event) {
    delete event.context.password; // scrub secrets
    return event; // return null to drop the event entirely
  },
});

tracker.addSink(anotherSink); // add more sinks later
```

## Requirements / Notes

- Runs on **Bun** only (Node is not supported).
- Peer package: [`@wrnexus/core`](../core) — the `Context` and `Middleware` types
  used by `tracker.middleware()` come from there.
- Sink dispatch is fire-and-forget-safe: all sinks run via `Promise.all`, and a
  sink that throws is swallowed so it can never break the app.

### Exported TypeScript declarations

```ts
import { Middleware } from '@wrnexus/core';

type TelemetryKind = "error" | "event" | "metric" | "span";
interface TelemetryEnvelope {
    id: string;
    kind: TelemetryKind;
    name: string;
    timestamp: number;
    traceId?: string;
    userId?: string;
    tenantId?: string;
    attributes: Record<string, unknown>;
    payload?: unknown;
}
interface TelemetrySink {
    name?: string;
    send(events: TelemetryEnvelope[]): void | Promise<void>;
}
interface TelemetryPipeline {
    emit(input: Omit<TelemetryEnvelope, "id" | "timestamp"> & Partial<Pick<TelemetryEnvelope, "id" | "timestamp">>): Promise<void>;
    flush(): Promise<void>;
    close(): Promise<void>;
    size(): number;
}
interface TelemetryPipelineOptions {
    sinks: TelemetrySink[];
    batchSize?: number;
    flushIntervalMs?: number;
    maxQueueSize?: number;
    sampleRate?: number;
    beforeSend?: (event: TelemetryEnvelope) => TelemetryEnvelope | null;
    onSinkError?: (error: unknown, sink: TelemetrySink, events: readonly TelemetryEnvelope[]) => void | Promise<void>;
    now?: () => number;
    random?: () => number;
}
declare function createTelemetryPipeline(options: TelemetryPipelineOptions): TelemetryPipeline;
declare const telemetryConsoleSink: TelemetrySink;

/**
 * @wrnexus/tracking — error tracking with pluggable sinks. Capture exceptions
 * manually or via middleware, and fan them out to any sink (console by default;
 * write a small sink to forward to Sentry/Datadog/etc.).
 *
 *   const tracker = createTracker({ sinks: [consoleSink] });
 *   app-middleware: tracker.middleware()   // captures + re-throws request errors
 *   tracker.capture(err, { userId });      // manual
 */

interface ErrorEvent {
    error: Error;
    /** Arbitrary structured context (request info, user id, tags…). */
    context: Record<string, unknown>;
    /** Epoch ms. */
    timestamp: number;
}
interface ErrorSink {
    name?: string;
    capture(event: ErrorEvent): void | Promise<void>;
}
interface Tracker {
    capture(error: unknown, context?: Record<string, unknown>): Promise<void>;
    addSink(sink: ErrorSink): void;
    /** Middleware that captures errors thrown downstream, then re-throws them. */
    middleware(): Middleware;
}
interface TrackerOptions {
    sinks?: ErrorSink[];
    now?: () => number;
    /** Scrub/enrich an event before it hits sinks (return null to drop it). */
    beforeSend?: (event: ErrorEvent) => ErrorEvent | null;
}
/** A sink that logs a compact one-line error to the console. */
declare const consoleSink: ErrorSink;
declare function createTracker(options?: TrackerOptions): Tracker;

export { type ErrorEvent, type ErrorSink, type TelemetryEnvelope, type TelemetryKind, type TelemetryPipeline, type TelemetryPipelineOptions, type TelemetrySink, type Tracker, type TrackerOptions, consoleSink, createTelemetryPipeline, createTracker, telemetryConsoleSink };
```

---

## @wrnexus/ui

Documentation URL: https://wrnexusjs.dev/packages/ui

# @wrnexus/ui

> First-party Wire UI component library — a set of themeable `.wrn` components plus a single tokenized stylesheet.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

`@wrnexus/ui` ships a library of server-rendered `.wrn` components (layout, form
controls, and feedback UI) together with one themeable stylesheet, `ui.css`. The
components are **auto-discovered** by the framework router — you don't import them
in code. Once the package's component directory is on the router's scan path, you
mount any component in a page with `data-component="<name>"`. Every visual is
driven by `var(--wire-*)` theme tokens, so components restyle instantly when the
theme changes. The tiny JS surface (`src/index.ts`) exists only so the toolchain
(CLI build + dev server) can locate the component directory and stylesheet.

The complete PDF-aligned catalog currently contains **85 components**. The
generated `COMPONENTS.md` and `component-reference.json` files document every
mount name, prop, inferred type, default/required status, slot, event, category,
and source file directly from the packaged `.wrn` source.

## Installation

```bash
bun add @wrnexus/ui
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported).

In practice you rarely install this directly: `@wrnexus/cli` and
`@wrnexus/dev-server` already depend on it and wire it into the router for you
(see [Auto-discovery](#auto-discovery)).

## Components

Components live as `.wrn` files under `packages/ui/components/`. The canonical mount
name comes from the component declaration (for example, `component Button` mounts as
`data-component="Button"`). Component lookup is case-insensitive, so existing lowercase
mounts continue to work. Each component accepts a `class` prop (appended to its root
element), and most render their body from either a named prop or the default slot.

### Layout

| Name        | Purpose                            | Key props   |
| ----------- | ---------------------------------- | ----------- |
| `container` | Max-width centered content wrapper | `class`     |
| `stack`     | Vertical column with gap           | `gap` (0–8) |
| `hstack`    | Horizontal row with gap            | `gap` (0–8) |
| `grid`      | CSS grid container                 | see source  |
| `divider`   | Horizontal rule                    | `class`     |
| `spacer`    | Flexible/empty spacing element     | see source  |

### Core / feedback

| Name           | Purpose                                              | Key props                                                                                       |
| -------------- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `button`       | Button                                               | `label`, `variant` (`default`\|`primary`\|`danger`\|`ghost`), `size` (`sm`\|`md`\|`lg`), `type` |
| `input`        | Text input                                           | see source                                                                                      |
| `textarea`     | Multi-line input                                     | see source                                                                                      |
| `checkbox`     | Checkbox                                             | see source                                                                                      |
| `badge`        | Small status badge                                   | `label`, `variant`                                                                              |
| `alert`        | Callout box                                          | `variant` (`info`\|`success`\|`danger`\|`warning`), `title`, `message`                          |
| `card`         | Padded, bordered surface                             | `class`                                                                                         |
| `avatar`       | User avatar                                          | see source                                                                                      |
| `spinner`      | Loading indicator                                    | see source                                                                                      |
| `disclosure`   | Expandable details/summary                           | see source                                                                                      |
| `theme-toggle` | Theme switch button (binds `data-wire-theme-toggle`) | `label`                                                                                         |

### Additional controls & data display

Also shipped: `select`, `radio`, `switch`, `progress`, `tag`, `skeleton`,
`tooltip`, `table`, `FAQAccordion`, `AnnouncementBar`, and `BackToTop`.

The PDF-defined minimum release and essential build-first set also includes
typed typography, form primitives, loading actions, combobox and multi-select,
time/date-time and recurring schedule controls, confirmation dialogs, data
tables, filters, desktop/mobile navigation, mega menus, marketing/product/legal
page shells, product and metric cards, FAQ composition, pricing comparison,
SDK tabs, legal navigation, and cookie preferences.

`Seo` and `StructuredData` remain framework/page concerns rather than body
components: use the native page `seo { ... }` block and document-head APIs so
metadata is emitted in `<head>` instead of invalid component markup.

The authoritative, always-current list is `uiComponentNames()` (below), which reads
the component directory at runtime.

For the full catalog, see [`COMPONENTS.md`](./COMPONENTS.md). The machine-readable
equivalent is exported as `@wrnexus/ui/component-reference.json`.

## API

The JS module (`@wrnexus/ui`) exposes five helpers used by the build tooling to
locate the component assets. There is no component code to import — the components
are `.wrn` files rendered server-side.

| Export             | Signature                  | Returns                                                                                    |
| ------------------ | -------------------------- | ------------------------------------------------------------------------------------------ |
| `uiComponentsDir`  | `() => string`             | Absolute path to the `.wrn` component directory (feed to `buildRouter`'s `componentDirs`). |
| `uiCssPath`        | `() => string`             | Absolute path to `ui.css`.                                                                 |
| `uiCss`            | `() => string`             | The `ui.css` file contents (all `.wire-*` classes, themed via tokens).                     |
| `uiComponentNames` | `() => string[]`           | Sorted list of declared built-in component names.                                          |
| `uiComponentPath`  | `(name: string) => string` | Absolute source path for a declared component name or case-insensitive alias.              |

### `./ui.css` asset export

`package.json` also exposes the raw stylesheet as a subpath asset:

```json
"exports": {
  ".": "./src/index.ts",
  "./ui.css": "./ui.css"
}
```

The framework serves this stylesheet once at `/__wrnexus/ui.css`, so pages get all
component styles from a single request.

### Tailwind and motion

Components use static Tailwind utility classes alongside the shared `.wire-*`
layer. If the package is consumed by a separate Tailwind build, include its
component sources so every utility is generated:

```css
@import "tailwindcss";
@source "../node_modules/@wrnexus/ui/components/*.wrn";
```

The shared stylesheet gives all component boundaries consistent, GPU-friendly
entry and interaction motion. Override `--wire-motion-fast`,
`--wire-motion-base`, `--wire-motion-slow`, `--wire-ease-standard`, or
`--wire-ease-emphasized` to tune it. Hover lift is limited to precise pointing
devices and `prefers-reduced-motion` is honored automatically.

### Using the selected theme in application UI

The active theme and palette are not limited to `@wrnexus/ui` components. The
framework exposes the resolved values as semantic CSS custom properties, so
pages and custom `.wrn` components can use the same contract:

```css
.account-card {
  background: var(--wire-color-surface);
  color: var(--wire-color-text);
  border: 1px solid var(--wire-color-border);
}

.account-card__action {
  background: var(--wire-color-primary);
  color: var(--wire-color-primary-contrast);
}
```

Stable no-spacing helper classes are also available: `wire-bg-page`,
`wire-bg-surface`, `wire-bg-surface-2`, `wire-bg-primary`, `wire-bg-secondary`,
`wire-text`, `wire-text-muted`, `wire-text-primary`, `wire-text-success`,
`wire-text-warning`, `wire-text-danger`, and `wire-border`.

Tailwind-authored custom markup can continue using the palette families already
used by packaged components. `indigo-*` and `violet-*` resolve to primary,
`blue-*` to info, `emerald-*`/`green-*` to success, `amber-*` to warning, and
`red-*`/`rose-*` to danger. These aliases live at `:root`, so they work outside
a `[data-component]` boundary too.

## Usage

### Auto-discovery

The router scans extra `componentDirs` (in addition to the app's own
`app/components`) and keys components by name. Library dirs are scanned **first**
and `app/components` **last**, so an app component of the same name shadows the
library's. The CLI build (`@wrnexus/cli`) and dev server (`@wrnexus/dev-server`)
both wire the UI directory in for you:

```ts
import { buildRouter } from "@wrnexus/router";
import { uiComponentsDir } from "@wrnexus/ui";

const router = buildRouter(appDir, { componentDirs: [uiComponentsDir()] });
```

### Mounting components in a page

Once discovered, mount any component by name via `data-component`. Quoted
attributes (other than `data-component`) become string props:

```html
<div data-component="card">
  <div data-component="badge" label="New"></div>
  <button data-component="button" label="Save" variant="primary" size="lg"></button>
  <div data-component="alert" variant="success" title="Done" message="Saved."></div>
</div>
```

## Overrides

Ways to customize the components, in increasing order of power:

1. **Theme tokens** — override CSS custom properties such as `--wire-color-primary`,
   `--wire-color-surface`, `--wire-radius-sm`, etc. Every component style resolves
   through `var(--wire-*)`, so changing a token restyles everything instantly
   (including across theme switches).
2. **App CSS** — redefine a `.wire-*` class in your own stylesheet, which is loaded
   after `ui.css` and therefore wins.
3. **`class` prop** — pass a `class` prop to a component; it is appended to the
   component's root element, letting you add per-instance classes without touching
   the base styles.
4. **`wrnexus eject <name>`** — copy the component's `.wrn` source into your
   `app/components`, where (because app components shadow library ones) you fully
   own and can edit it. Use `uiComponentNames()` for the list of ejectable names.

## Requirements / Notes

- **Bun-only** — the package uses standard fs/path/url APIs but is published and
  consumed within the Bun-native WrNexus toolchain (Node is not supported).
- Peer packages: components are discovered and rendered by
  [`@wrnexus/router`](../router) (via `componentDirs`) and served by
  [`@wrnexus/dev-server`](../dev-server) / built by [`@wrnexus/cli`](../cli).
- Depends on [`@wrnexus/core`](../core) (`dependencies`).
- `theme-toggle` relies on the framework's theme runtime, which binds the
  `data-wire-theme-toggle` attribute — no per-component JS is required.

### Exported TypeScript declarations

```ts
interface UiComponentMetadata {
    name: string;
    mount: string;
    category?: string;
    purpose?: string;
    props?: Array<{
        name: string;
        default?: unknown;
    }>;
    events?: string[];
}
interface UiComponentReference {
    count: number;
    components: UiComponentMetadata[];
}
declare function uiComponentReference(): UiComponentReference;
declare function findUiComponent(name: string): UiComponentMetadata | undefined;
declare function auditUiComponents(): Array<{
    component: string;
    issue: string;
}>;

/**
 * @wrnexus/ui — the Wire UI component library.
 *
 * Components are `.wrn` files under `components/`, auto-discovered by the
 * framework (the router scans this directory in addition to the app's own
 * `app/components`). Mount them in any page with `data-component="<name>"`.
 * Their styles live in a single themeable stylesheet, `ui.css`, served once at
 * `/__wrnexus/ui.css` — every class uses `var(--wire-*)` theme tokens.
 *
 * Override, in increasing order of power:
 *   1. theme tokens (change `--wire-color-primary`, etc.)
 *   2. redefine a `.wire-*` class in your own CSS (loaded after ui.css)
 *   3. pass a `class` prop (appended to the component root)
 *   4. `wrnexus eject <name>` to copy the component into `app/components` and own it
 */
/** Absolute path to the directory of Wire UI component `.wrn` files. */
declare function uiComponentsDir(): string;
/** Absolute path to the Wire UI stylesheet. */
declare function uiCssPath(): string;
/** The Wire UI stylesheet contents (all `.wire-*` classes, themed via tokens). */
declare function uiCss(): string;
/** Names declared by the bundled components, independent of filename casing. */
declare function uiComponentNames(): string[];
/** Absolute path to a bundled component by its declared component name. */
declare function uiComponentPath(name: string): string;

export { type UiComponentMetadata, type UiComponentReference, auditUiComponents, findUiComponent, uiComponentNames, uiComponentPath, uiComponentReference, uiComponentsDir, uiCss, uiCssPath };
```

---

## @wrnexus/uploader

Documentation URL: https://wrnexusjs.dev/packages/uploader

# @wrnexus/uploader

Config-driven file uploads + serving for [WrNexus](https://www.npmjs.com/org/wrnexus). Declare
named **storage stores** (local disk or any S3-compatible backend) in `wrnexus.config.ts`, upload
with one function call, drop a drag-and-drop widget on a page, and serve files back — public or
private. Zero external dependencies (S3 is signed with a built-in AWS SigV4 implementation, like the
rest of the framework).

## Usage

### Configure local and S3 stores

```ts
// wrnexus.config.ts
import type { AppConfig } from "@wrnexus/styles";

const config: AppConfig = {
  storage: {
    default: "public",
    stores: {
      // Local disk, world-readable — served by the framework with a 1-year cache.
      public: {
        driver: "local",
        dir: "uploads/public", // relative to the app root (dev) / cwd (prod)
        access: "public",
        maxBytes: 10_000_000,
        accept: ["image/*", ".pdf"], // MIME, "type/*" wildcards, or ".ext"
      },
      // Private S3 (works with AWS, Cloudflare R2, Backblaze B2, MinIO, DO Spaces).
      docs: {
        driver: "s3",
        access: "private",
        bucket: "my-bucket",
        region: "auto",
        endpoint: "https://<acct>.r2.cloudflarestorage.com",
        accessKeyId: process.env.S3_KEY!,
        secretAccessKey: process.env.S3_SECRET!,
      },
    },
  },
};
export default config;
```

### Upload from an API route or server function

```ts
// app/api/upload.ts — one-liner
import { handleUpload } from "@wrnexus/uploader";
export const POST = handleUpload({ store: "public" });
// → { ok: true, files: [{ key, url, name, type, size }] }
```

```ts
// or drive it yourself, anywhere you have the request
import { upload, getStore } from "@wrnexus/uploader";
const { files } = await upload("docs", ctx.req, { prefix: "invoices" });
await getStore("docs").driver.delete(files[0].key);
```

Uploads are validated (size + type), stored under a random, collision-proof, path-safe key
(the client filename is never used as a path), and — for public stores — returned with a servable
`url`.

### Add a client upload widget

Drop the element anywhere; the runtime (drag-and-drop, per-file progress, success/failed states) is
auto-injected on pages that contain `data-uploader`:

```html
<div
  data-uploader="public"
  data-endpoint="/api/upload"
  data-accept="image/*"
  data-max="10000000"
  data-multiple
></div>
```

Or via the first-party UI component:

```html
<div
  data-component="file-upload"
  store="public"
  endpoint="/api/upload"
  accept="image/*"
  multiple="true"
></div>
```

It dispatches bubbling events you can listen for:

- `wrnexus:upload` — `detail: { file, result: { key, url, name, size, type } }`
- `wrnexus:upload-error` — `detail: { file, error }`

### Serve private files behind application authentication

- **Public + local** → served automatically at `/__wrnexus/uploads/<store>/<key>` (immutable cache).
- **Public + S3** → `url` is the bucket/CDN URL directly.
- **Private** (any driver) → mount a route and gate it with your auth middleware:

```ts
// app/api/files/[key].ts
import { serveFromStore } from "@wrnexus/uploader";
export const GET = serveFromStore("docs"); // your middleware decides who gets in
```

## API

| Export                                  | What                                                            |
| --------------------------------------- | --------------------------------------------------------------- |
| `handleUpload(opts)`                    | POST route handler → JSON `{ ok, files }`                       |
| `upload(store, req, opts)`              | Parse + validate + store; returns `{ files }`                   |
| `serveFromStore(store)`                 | Route handler that streams an object back (gate it for private) |
| `getStore(name?)` / `hasStorage(name?)` | Reach a store's `driver` (`put`/`get`/`delete`/`publicUrl`)     |
| `configureStorage(config, root)`        | Build the registry (the framework calls this at startup)        |
| `s3Driver` / `localDriver` / `signS3`   | Lower-level building blocks                                     |

## Notes

- Uploads count against the server's `maxBodyBytes`; per-file limits use each store's `maxBytes`.
- SigV4 signing is implemented from scratch (no `@aws-sdk`); tested against local S3 semantics.
  Live AWS/R2 connectivity depends on your credentials + bucket policy.
- v1 buffers each file in memory up to its size cap (fine for images/docs up to tens of MB).

### Exported TypeScript declarations

```ts
import { Context } from '@wrnexus/core';

/**
 * Storage driver contract + config types.
 *
 * A `StorageDriver` is the low-level object store (local disk, S3, …). It knows
 * how to put/get/delete raw bytes under a key — nothing about HTTP, multipart
 * parsing, validation, or URLs. The registry (`client.ts`) builds one driver per
 * configured store and the upload layer (`upload.ts`) drives them. This mirrors
 * `@wrnexus/db`'s driver/adapter split.
 */
/** Whether a store's objects are world-readable or served behind app auth. */
type StoreAccess = "public" | "private";
/** An object read back from a store. */
interface StoredObject {
    /** Object bytes as a web stream (preferred) or a buffer. */
    body: ReadableStream<Uint8Array> | Uint8Array;
    /** MIME type to serve with. */
    contentType: string;
    /** Size in bytes, when known. */
    size?: number;
}
/** Metadata passed alongside the bytes on `put`. */
interface PutMeta {
    contentType: string;
    /** Original client filename (informational only — NEVER used as a path). */
    filename?: string;
}
/** The low-level object store. Implementations: `adapters/local.ts`, `adapters/s3.ts`. */
interface StorageDriver {
    /** Persist `data` under `key` (overwrites). */
    put(key: string, data: Uint8Array, meta: PutMeta): Promise<void>;
    /** Fetch an object, or `null` if it doesn't exist. */
    get(key: string): Promise<StoredObject | null>;
    /** Remove an object. No error if it's already gone. */
    delete(key: string): Promise<void>;
    /**
     * A directly-servable absolute URL for a PUBLIC object (e.g. an S3/CDN URL), or
     * `null` when the framework should serve it (local public stores). Private
     * stores always return `null`.
     */
    publicUrl(key: string): string | null;
}
/** Local-disk store. `dir` is resolved against the app root when relative. */
interface LocalStoreConfig {
    driver: "local";
    access: StoreAccess;
    /** Directory the files live under (e.g. "uploads/public"). */
    dir: string;
    /** Reject files larger than this many bytes (per file). */
    maxBytes?: number;
    /** Allowed types: MIME (`"image/*"`, `"application/pdf"`) and/or extensions (`".pdf"`). */
    accept?: string[];
}
/** S3 / S3-compatible store (AWS, Cloudflare R2, Backblaze B2, MinIO, DO Spaces). */
interface S3StoreConfig {
    driver: "s3";
    access: StoreAccess;
    bucket: string;
    region: string;
    accessKeyId: string;
    secretAccessKey: string;
    /**
     * Custom endpoint for non-AWS services, e.g.
     * `https://<acct>.r2.cloudflarestorage.com`. Omit for AWS S3.
     */
    endpoint?: string;
    /** Force path-style URLs (`/bucket/key`). Defaults on for custom endpoints. */
    forcePathStyle?: boolean;
    /** Public base URL for `publicUrl()` (a CDN or public bucket domain). */
    publicBaseUrl?: string;
    maxBytes?: number;
    accept?: string[];
}
type StoreConfig = LocalStoreConfig | S3StoreConfig;
/** The `storage` block in `wrnexus.config.ts`. */
interface StorageConfig {
    /** Name of the store used when a call omits one. Defaults to the first store. */
    default?: string;
    /** Named stores, reached with `getStore("<name>")` / `upload("<name>", …)`. */
    stores: Record<string, StoreConfig>;
}

/**
 * Process-wide store registry, configured once at server startup from the
 * `storage` block in `wrnexus.config.ts` (mirrors `@wrnexus/db`'s registry).
 * Handlers then call `getStore("<name>")` — or omit the name for the default.
 */

interface Store {
    name: string;
    access: StoreAccess;
    driver: StorageDriver;
    config: StoreConfig;
}
/** Build a driver per configured store. Safe to call again (fully replaces). */
declare function configureStorage(config: StorageConfig | undefined, appRoot: string): void;
/** Whether the default (or a named) store is configured. */
declare function hasStorage(name?: string): boolean;
/** The default store, or a named one. Throws if it isn't configured. */
declare function getStore(name?: string): Store;
/** Names of all configured stores. */
declare function storeNames(): string[];

/**
 * The HTTP-facing upload + serve layer: parse multipart requests, validate,
 * store, and serve files back. Built on the store registry (`client.ts`).
 */

/** Reserved prefix the framework serves PUBLIC local objects from. */
declare const UPLOADS_PREFIX = "/__wrnexus/uploads/";
interface UploadedFile {
    /** Storage key — pass to `getStore().driver.get/delete` or a serve route. */
    key: string;
    /** A servable URL for public objects, or `null` for private stores. */
    url: string | null;
    /** Original (sanitized) client filename, for display. */
    name: string;
    type: string;
    size: number;
}
interface UploadOptions {
    /** Only read files from this form field (default: every file field). */
    field?: string;
    /** Override the store's `maxBytes`. */
    maxBytes?: number;
    /** Override the store's `accept` list. */
    accept?: string[];
    /** Key prefix, e.g. `"avatars"` → keys become `avatars/<yyyy>/<mm>/<rand>.<ext>`. */
    prefix?: string;
}
/** A 4xx-carrying error so `handleUpload` can map it to a status. */
declare class UploadError extends Error {
    readonly status: number;
    constructor(message: string, status?: number);
}
/** The servable URL for a stored object (public → URL, private → null). */
declare function storedUrl(store: Store, key: string): string | null;
/**
 * Read multipart file(s) from a request and store them. Throws `UploadError`
 * (4xx) on validation failures. Call it directly, or use `handleUpload`.
 */
declare function upload(storeName: string | undefined, req: Request, opts?: UploadOptions): Promise<{
    files: UploadedFile[];
}>;
/**
 * Ready-made POST handler:
 *
 *   // app/api/upload.ts
 *   export const POST = handleUpload({ store: "public" });
 *
 * Returns `{ ok:true, files:[…] }` on success, or `{ ok:false, error }` with a
 * 4xx/5xx status.
 */
declare function handleUpload(opts?: UploadOptions & {
    store?: string;
}): (ctx: Context) => Promise<Response>;
/**
 * Serve an object from a store as a route handler — mount it behind your auth
 * middleware to gate PRIVATE files:
 *
 *   // app/api/files/[key].ts
 *   export const GET = serveFromStore("docs");
 *
 * Reads the key from `ctx.params.key` (or `ctx.params.path`); it may contain `/`.
 */
declare function serveFromStore(storeName?: string, opts?: {
    param?: string;
}): (ctx: Context) => Promise<Response>;
/**
 * Framework asset hook: serve PUBLIC local objects at
 * `/__wrnexus/uploads/<store>/<key>`. Returns `null` for anything it doesn't
 * own (unknown/private/S3-backed store) so the caller falls through. Wired into
 * the dev + prod asset servers.
 */
declare function serveStoredFile(pathname: string): Promise<Response | null>;

/**
 * Client runtime for `<div data-uploader>` elements — drag-and-drop + file
 * input, per-file progress bars, and success/failed states. Injected by
 * `collectScripts` only on pages that contain `data-uploader` (same mechanism as
 * `validate.js`). Self-contained: it injects its own themed stylesheet (using
 * `--wire-*` tokens) and posts each file via XHR so upload progress is live.
 *
 * Markup it enhances (also a valid no-JS `<form>` fallback if you wrap it):
 *   <div data-uploader="public" data-endpoint="/api/upload"
 *        data-accept="image/*" data-max="10000000" data-multiple></div>
 *
 * Events dispatched on the element (bubble):
 *   wrnexus:upload        detail: { file, result: { key, url, name, size, type } }
 *   wrnexus:upload-error  detail: { file, error }
 *
 * NOTE: written with single/double quotes + string concatenation only — no
 * backticks and no ${...}, so it embeds safely in the exported template string.
 */
declare const UPLOAD_JS_HREF = "/__wrnexus/uploader.js";
declare const UPLOAD_RUNTIME = "\n(function () {\n  if (typeof document === \"undefined\") return;\n  var CSRF_COOKIE = \"wire-csrf\";\n\n  var CSS =\n    \".wire-uploader{display:block}\" +\n    \".wire-uploader-zone{display:flex;align-items:center;justify-content:center;text-align:center;\" +\n      \"min-height:8rem;padding:1.25rem;border:2px dashed var(--wire-border,#cbd5e1);border-radius:12px;\" +\n      \"background:var(--wire-surface,transparent);color:var(--wire-muted,#64748b);cursor:pointer;\" +\n      \"transition:border-color .15s ease,background-color .15s ease;position:relative}\" +\n    \".wire-uploader-zone:hover,.wire-uploader-zone:focus-visible{border-color:var(--wire-brand,#3f7dff);outline:none}\" +\n    \".wire-uploader-zone.is-drag{border-color:var(--wire-brand,#3f7dff);background:color-mix(in oklab,var(--wire-brand,#3f7dff) 8%,transparent)}\" +\n    \".wire-uploader-prompt{font-size:.9rem;pointer-events:none}\" +\n    \".wire-uploader-input{position:absolute;inset:0;width:100%;height:100%;opacity:0;cursor:pointer}\" +\n    \".wire-uploader-list{list-style:none;margin:.75rem 0 0;padding:0;display:flex;flex-direction:column;gap:.5rem}\" +\n    \".wire-uploader-item{display:grid;grid-template-columns:1fr auto;gap:.15rem .75rem;align-items:center;\" +\n      \"font-size:.82rem;padding:.5rem .7rem;border:1px solid var(--wire-border,#e2e8f0);border-radius:8px}\" +\n    \".wire-uploader-name{font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--wire-text,#0f172a)}\" +\n    \".wire-uploader-meta{color:var(--wire-muted,#94a3b8);font-variant-numeric:tabular-nums}\" +\n    \".wire-uploader-bar{grid-column:1/-1;height:5px;border-radius:999px;background:var(--wire-border,#e2e8f0);overflow:hidden}\" +\n    \".wire-uploader-fill{height:100%;width:0;border-radius:999px;background:var(--wire-brand,#3f7dff);transition:width .15s ease}\" +\n    \".wire-uploader-status{grid-column:1/-1;font-size:.75rem;color:var(--wire-muted,#94a3b8);font-variant-numeric:tabular-nums}\" +\n    \".wire-uploader-item.is-done .wire-uploader-fill{background:var(--wire-success,#16a34a)}\" +\n    \".wire-uploader-item.is-done .wire-uploader-status{color:var(--wire-success,#16a34a)}\" +\n    \".wire-uploader-item.is-error .wire-uploader-fill{background:var(--wire-danger,#dc2626)}\" +\n    \".wire-uploader-item.is-error .wire-uploader-status{color:var(--wire-danger,#dc2626)}\";\n\n  function injectCss() {\n    if (document.getElementById(\"wire-uploader-css\")) return;\n    var s = document.createElement(\"style\");\n    s.id = \"wire-uploader-css\";\n    s.textContent = CSS;\n    document.head.appendChild(s);\n  }\n\n  function cookie(name) {\n    var m = document.cookie.match(new RegExp(\"(?:^|; )\" + name + \"=([^;]*)\"));\n    return m ? decodeURIComponent(m[1]) : \"\";\n  }\n  function el(tag, cls, text) {\n    var e = document.createElement(tag);\n    if (cls) e.className = cls;\n    if (text != null) e.textContent = text;\n    return e;\n  }\n  function fmt(n) {\n    if (n < 1024) return n + \" B\";\n    if (n < 1048576) return (n / 1024).toFixed(1) + \" KB\";\n    return (n / 1048576).toFixed(1) + \" MB\";\n  }\n  function accepts(accept, file) {\n    var list = (accept || \"\").split(\",\").map(function (s) { return s.trim().toLowerCase(); }).filter(Boolean);\n    if (!list.length) return true;\n    var type = (file.type || \"\").toLowerCase();\n    var name = (file.name || \"\").toLowerCase();\n    var ext = name.indexOf(\".\") >= 0 ? name.slice(name.lastIndexOf(\".\")) : \"\";\n    return list.some(function (rule) {\n      if (rule.charAt(0) === \".\") return rule === ext;\n      if (rule.slice(-2) === \"/*\") return type.indexOf(rule.slice(0, -1)) === 0;\n      return rule === type;\n    });\n  }\n\n  function setup(root) {\n    if (root.__wrnexusUploader) return;\n    root.__wrnexusUploader = true;\n\n    var endpoint = root.getAttribute(\"data-endpoint\") || \"/api/upload\";\n    var multipleAttr = root.getAttribute(\"data-multiple\");\n    var multiple = root.hasAttribute(\"data-multiple\") && multipleAttr !== \"false\";\n    var accept = root.getAttribute(\"data-accept\") || \"\";\n    var maxBytes = parseInt(root.getAttribute(\"data-max\") || \"0\", 10) || 0;\n    var field = root.getAttribute(\"data-field\") || (multiple ? \"files\" : \"file\");\n    var promptText = root.getAttribute(\"data-label\") || \"Drag files here or click to browse\";\n\n    root.classList.add(\"wire-uploader\");\n    var zone = el(\"div\", \"wire-uploader-zone\");\n    zone.setAttribute(\"role\", \"button\");\n    zone.setAttribute(\"tabindex\", \"0\");\n    zone.appendChild(el(\"div\", \"wire-uploader-prompt\", promptText));\n    var input = document.createElement(\"input\");\n    input.type = \"file\";\n    input.className = \"wire-uploader-input\";\n    if (multiple) input.multiple = true;\n    if (accept) input.accept = accept;\n    zone.appendChild(input);\n    var listEl = el(\"ul\", \"wire-uploader-list\");\n    root.appendChild(zone);\n    root.appendChild(listEl);\n\n    zone.addEventListener(\"keydown\", function (e) {\n      if (e.key === \"Enter\" || e.key === \" \") { e.preventDefault(); input.click(); }\n    });\n    [\"dragenter\", \"dragover\"].forEach(function (ev) {\n      zone.addEventListener(ev, function (e) { e.preventDefault(); zone.classList.add(\"is-drag\"); });\n    });\n    [\"dragleave\", \"drop\"].forEach(function (ev) {\n      zone.addEventListener(ev, function (e) { e.preventDefault(); zone.classList.remove(\"is-drag\"); });\n    });\n    zone.addEventListener(\"drop\", function (e) {\n      if (e.dataTransfer && e.dataTransfer.files) handle(e.dataTransfer.files);\n    });\n    input.addEventListener(\"change\", function () {\n      if (input.files) handle(input.files);\n      input.value = \"\";\n    });\n\n    function handle(files) {\n      var arr = Array.prototype.slice.call(files);\n      if (!multiple) arr = arr.slice(0, 1);\n      arr.forEach(uploadOne);\n    }\n\n    function row(file) {\n      var li = el(\"li\", \"wire-uploader-item\");\n      li.appendChild(el(\"span\", \"wire-uploader-name\", file.name));\n      li.appendChild(el(\"span\", \"wire-uploader-meta\", fmt(file.size)));\n      var bar = el(\"div\", \"wire-uploader-bar\");\n      var fill = el(\"div\", \"wire-uploader-fill\");\n      bar.appendChild(fill);\n      li.appendChild(bar);\n      var status = el(\"span\", \"wire-uploader-status\", \"\");\n      li.appendChild(status);\n      listEl.appendChild(li);\n      return { li: li, fill: fill, status: status };\n    }\n\n    function uploadOne(file) {\n      var ui = row(file);\n      if (maxBytes && file.size > maxBytes) return fail(ui, \"Too large (max \" + fmt(maxBytes) + \")\", file);\n      if (!accepts(accept, file)) return fail(ui, \"Type not allowed\", file);\n\n      var fd = new FormData();\n      fd.append(field, file, file.name);\n      var xhr = new XMLHttpRequest();\n      xhr.open(\"POST\", endpoint, true);\n      var token = cookie(CSRF_COOKIE);\n      if (token) xhr.setRequestHeader(\"x-csrf-token\", token);\n      xhr.upload.addEventListener(\"progress\", function (e) {\n        if (e.lengthComputable) {\n          var pct = Math.round((e.loaded / e.total) * 100);\n          ui.fill.style.width = pct + \"%\";\n          ui.status.textContent = pct + \"%\";\n        }\n      });\n      xhr.addEventListener(\"load\", function () {\n        var data = null;\n        try { data = JSON.parse(xhr.responseText); } catch (e2) {}\n        if (xhr.status >= 200 && xhr.status < 300 && data && data.ok) {\n          done(ui, (data.files && data.files[0]) || null, file);\n        } else {\n          fail(ui, (data && data.error) || (\"Upload failed (\" + xhr.status + \")\"), file);\n        }\n      });\n      xhr.addEventListener(\"error\", function () { fail(ui, \"Network error\", file); });\n      xhr.send(fd);\n    }\n\n    function done(ui, info, file) {\n      ui.li.classList.remove(\"is-error\");\n      ui.li.classList.add(\"is-done\");\n      ui.fill.style.width = \"100%\";\n      ui.status.textContent = \"\\u2713 Uploaded\";\n      root.dispatchEvent(new CustomEvent(\"wrnexus:upload\", { bubbles: true, detail: { file: file, result: info } }));\n    }\n    function fail(ui, msg, file) {\n      ui.li.classList.add(\"is-error\");\n      ui.status.textContent = \"\\u2717 \" + msg;\n      root.dispatchEvent(new CustomEvent(\"wrnexus:upload-error\", { bubbles: true, detail: { file: file, error: msg } }));\n    }\n  }\n\n  function init() {\n    injectCss();\n    var nodes = document.querySelectorAll(\"[data-uploader]\");\n    for (var i = 0; i < nodes.length; i++) setup(nodes[i]);\n  }\n  if (document.readyState === \"loading\") document.addEventListener(\"DOMContentLoaded\", init);\n  else init();\n})();\n";

/**
 * Local-disk storage driver. Files live under a configured directory; keys map
 * to relative paths inside it. Path traversal is rejected — a key can never
 * escape the base dir.
 */

declare function localDriver(config: LocalStoreConfig, appRoot: string): StorageDriver;

/**
 * S3 (and S3-compatible) storage driver — zero deps, SigV4-signed `fetch`.
 * Works with AWS S3, Cloudflare R2, Backblaze B2, MinIO, DigitalOcean Spaces.
 *
 * Path-style vs virtual-hosted: AWS defaults to virtual-hosted
 * (`bucket.s3.region.amazonaws.com`); custom endpoints (R2/MinIO) default to
 * path-style (`endpoint/bucket/key`). Override with `forcePathStyle`.
 */

declare function s3Driver(config: S3StoreConfig): StorageDriver;

/**
 * AWS Signature Version 4 for S3 requests — zero external deps, built on
 * `node:crypto` + `fetch`. Matches the framework's zero-dep ethos (like
 * `@wrnexus/ai`) and works with any S3-compatible service (AWS, Cloudflare R2,
 * Backblaze B2, MinIO, DigitalOcean Spaces).
 *
 * Reference: docs.aws.amazon.com/general/latest/gr/sigv4_signing.html
 */
/** Hex-encoded SHA-256 of a payload. */
declare function sha256Hex(data: Uint8Array | string): string;
/**
 * Percent-encode an S3 object key for the request path. Every character except
 * the RFC 3986 unreserved set is encoded; `/` between segments is preserved.
 */
declare function encodeKey(key: string): string;
interface SignInput {
    method: string;
    host: string;
    /** Canonical URI — already `%`-encoded, begins with `/`. */
    path: string;
    region: string;
    accessKeyId: string;
    secretAccessKey: string;
    /** Hex SHA-256 of the body, or `"UNSIGNED-PAYLOAD"`. */
    payloadHash: string;
    /** Extra headers to sign (e.g. `content-type`). `host`/`x-amz-*` are added here. */
    headers?: Record<string, string>;
    date: Date;
    service?: string;
}
/**
 * Compute the signed header set for an S3 request. Returns the headers to send
 * (lowercased names, including `authorization`, `host`, `x-amz-date`,
 * `x-amz-content-sha256`).
 */
declare function signS3(input: SignInput): Record<string, string>;

/**
 * Minimal extension ↔ MIME mapping + `accept` matching. Zero-dep: just a table
 * big enough for the common upload types (images, docs, media, archives).
 */
/** Lowercased extension WITHOUT the dot (e.g. "png"), or "" if none. */
declare function extOf(name: string): string;
/** MIME type for a filename/key by its extension, or a safe default. */
declare function contentTypeOf(name: string, fallback?: string): string;
/** The conventional extension for a MIME type, or "" (used to name S3 keys). */
declare function extForType(type: string): string;
/**
 * Does `file` (its MIME `type` + `name`) satisfy an `accept` list? Each accept
 * entry is a MIME type (`"image/png"`), a wildcard MIME (`"image/*"`), or a
 * dotted extension (`".pdf"`). An empty/omitted list accepts everything.
 */
declare function accepts(accept: string[] | undefined, file: {
    type: string;
    name: string;
}): boolean;

interface UploadPolicy {
    maxBytes?: number;
    accept?: string[];
    requireChecksum?: boolean;
    filenamePattern?: RegExp;
}
interface UploadInspection {
    filename: string;
    contentType: string;
    size: number;
    sha256: string;
    extension: string;
}
declare class UploadPolicyError extends Error {
    readonly code: string;
    constructor(message: string, code: string);
}
declare function safeObjectKey(filename: string, prefix?: string): string;
declare function inspectUpload(filename: string, bytes: Uint8Array, declaredType?: string): Promise<UploadInspection>;
declare function enforceUploadPolicy(inspection: UploadInspection, policy: UploadPolicy, expectedChecksum?: string): void;
declare function sniffContentType(bytes: Uint8Array): string | null;
interface SignedFileToken {
    store: string;
    key: string;
    expiresAt: number;
    disposition?: "inline" | "attachment";
}
declare function createSignedFileToken(input: SignedFileToken, secret: string): Promise<string>;
declare function verifySignedFileToken(token: string, secret: string, now?: number): Promise<SignedFileToken | null>;

export { type LocalStoreConfig, type PutMeta, type S3StoreConfig, type SignedFileToken, type StorageConfig, type StorageDriver, type Store, type StoreAccess, type StoreConfig, type StoredObject, UPLOADS_PREFIX, UPLOAD_JS_HREF, UPLOAD_RUNTIME, UploadError, type UploadInspection, type UploadOptions, type UploadPolicy, UploadPolicyError, type UploadedFile, accepts, configureStorage, contentTypeOf, createSignedFileToken, encodeKey, enforceUploadPolicy, extForType, extOf, getStore, handleUpload, hasStorage, inspectUpload, localDriver, s3Driver, safeObjectKey, serveFromStore, serveStoredFile, sha256Hex, signS3, sniffContentType, storeNames, storedUrl, upload, verifySignedFileToken };
```

---

## @wrnexus/validation

Documentation URL: https://wrnexusjs.dev/packages/validation

# @wrnexus/validation

> One fluent schema, validated on the server (API bodies, env vars) and mirrored to an eval-free browser validator for forms.

Part of the **WrNexus** framework — an SSR-first, Bun-native full-stack web framework.

## Overview

Define a schema once with the fluent `v` builder, then reuse it in three places: `.parse()` runs server-side and returns coerced values plus per-field errors; `.describe()` emits a plain-JSON `SchemaDescriptor` that the browser runtime interprets (no `eval`, no bundled validator); and helpers like `parseBody` and `parseEnv` wire schemas straight into API routes and startup config. The server rule logic (`applyRule`/`checkField`) and the client runtime (`VALIDATE_RUNTIME`) mirror each other exactly, so a form validates identically in both places. Schemas are conventionally kept in `app/schemas/`.

## Installation

```bash
bun add @wrnexus/validation
```

> Private package — the machine must be authenticated to the `wrnexus` npm org
> (a read token in `~/.npmrc`). Requires **Bun** (Node is not supported).

## API

### The `v` builder

```ts
import { v } from "@wrnexus/validation";
```

| Factory            | Returns         | Field methods                                                                                                       |
| ------------------ | --------------- | ------------------------------------------------------------------------------------------------------------------- |
| `v.string()`       | `StringSchema`  | `email()`, `url()`, `uuid()`, `date()`, `length(n)`, `oneOf(string[])`, `pattern(re)`, `trim()`, `min(n)`, `max(n)` |
| `v.number()`       | `NumberSchema`  | `integer()`, `positive()`, `oneOf(number[])`, `min(n)`, `max(n)`                                                    |
| `v.boolean()`      | `BooleanSchema` | (base methods only)                                                                                                 |
| `v.object(fields)` | `ObjectSchema`  | `parse(input)`, `describe()`                                                                                        |

Every field schema is chainable and shares these base methods:

- `min(n, message?)` / `max(n, message?)` — for strings, bounds the length; for numbers, bounds the value.
- `required(message?)` — require a non-empty value and optionally replace the default `"Required"` message on both server and browser validation.
- `optional()` — an empty/missing value passes instead of erroring `"Required"`.
- `label(text)` — human label carried into the descriptor.
- `default(value)` — value substituted when the field is absent (implies `optional`).
- `refine(fn, message?)` — **server-only** predicate. `fn` returns `true` (ok), `false` (use `message`), or a `string` (that error). Not serialized to the client.

Each string rule accepts an optional trailing `message` to override the default error text.

### `ObjectSchema`

```ts
schema.parse(input: unknown): ParseResult
schema.describe(): SchemaDescriptor
```

`parse` coerces each field (strings stay strings, `v.number()` runs `Number()`, `v.boolean()` treats `true` / `"true"` / `"on"` as true), applies its rules and refinements, fills in `default()` values, and returns:

```ts
interface ParseResult<T = Record<string, unknown>> {
  ok: boolean; // true when errors is empty
  value: T; // coerced values (present pass or fail)
  errors: Record<string, string>; // field name → first failing message
}
```

`describe()` returns the JSON bridge for the client:

```ts
interface SchemaDescriptor {
  type: "object";
  fields: Record<string, FieldDescriptor>;
}
interface FieldDescriptor {
  type: "string" | "number" | "boolean";
  optional?: boolean;
  label?: string;
  trim?: boolean; // strings only
  rules: RuleDescriptor[];
}
```

### Rules and coercion

`RuleDescriptor` is a discriminated union of the serializable rules — `min`, `max`, `length`, `email`, `url`, `uuid`, `date`, `oneOf`, `pattern`, `integer`. Two exported functions apply them and are shared by the server (the client runtime reimplements the same logic):

- `applyRule(type, rule, value): string | null` — validate one already-coerced value against one rule.
- `checkField(desc, raw): { value, error }` — coerce and validate one field. Empty input (`undefined`/`null`/`""`) is `"Required"` unless `optional`. Strings with `trim` are trimmed first. Numbers that fail `Number()` yield `"Must be a number"`.

Notes on specific rules: `email`/`url`/`uuid` test built-in regexes; `date` uses `Date.parse`; `pattern` reconstructs a `RegExp` from its `source`/`flags` and passes silently if the pattern is invalid; `integer` requires `Number.isInteger`; `positive()` is implemented as `min(Number.MIN_VALUE)`.

### API helpers

```ts
invalid(errors: Record<string, string>): Response   // ready 400 { ok:false, errors }

parseBody<T>(schema, req):
  Promise<{ ok: true; value: T } | { ok: false; response: Response }>
```

`parseBody` reads the request body from JSON, `application/x-www-form-urlencoded`, or `multipart/form-data`, validates it, and on failure hands back a ready 400 `Response`.

### Environment config

```ts
parseEnv<T>(schema: ObjectSchema, source?): T
```

Validates env vars (from `Bun.env`, falling back to `process.env`) against a schema and coerces them (`PORT` → number, `DEBUG` → boolean). On any problem it throws **one** error listing every offending variable, so misconfiguration fails fast at startup.

### Client runtime (from `runtime.ts`)

```ts
renderSchemasScript(descriptors: Record<string, SchemaDescriptor>): string
VALIDATE_RUNTIME: string
```

- `renderSchemasScript` produces `window.__wireSchemas = { name: descriptor, … };` to inline in the page.
- `VALIDATE_RUNTIME` is a self-contained, eval-free IIFE string. Injected as a `<script>`, it binds every `form[data-schema]` and validates on submit and blur, writing messages into `[data-error="<field>"]` elements and toggling `aria-invalid` / `.wire-invalid`. On a valid submit it `fetch`es the form `action` as JSON (attaching the `wire-csrf` cookie as an `x-csrf-token` header), then follows `data-redirect` / a `redirect` in the response, surfaces server-side field errors, and fires `wire:success` / `wire:error` events. It exposes `window.__wireValidate.init(root)` and self-initializes on `DOMContentLoaded`.

## Usage

Define a schema and validate an API body:

```ts
import { v, parseBody } from "@wrnexus/validation";

export const signupSchema = v.object({
  email: v.string().required("Enter your email address").trim().email(),
  password: v.string().required("Enter your password").min(8).max(200),
  age: v.number().integer().min(13).max(120).optional(),
  role: v.string().oneOf(["user", "admin"]).default("user"),
  agree: v.boolean(),
});

// inside a route handler
const result = await parseBody(signupSchema, req);
if (!result.ok) return result.response; // ready 400 with field errors
const { email, password, role } = result.value;
```

Server-only refinement:

```ts
const schema = v.object({
  username: v
    .string()
    .min(3)
    .refine((name) => !RESERVED.has(String(name)), "That name is taken"),
});
```

Validate environment at startup:

```ts
import { v, parseEnv } from "@wrnexus/validation";

export const env = parseEnv(
  v.object({
    DATABASE_URL: v.string().min(1),
    PORT: v.number().integer().default(3000),
    DEBUG: v.boolean().optional(),
  }),
);
// throws one readable error listing every bad variable if misconfigured
```

Wire the same schema into the browser:

```ts
import { renderSchemasScript, VALIDATE_RUNTIME } from "@wrnexus/validation";
import { signupSchema } from "./app/schemas/signup.ts";

const head = `<script>${renderSchemasScript({ signup: signupSchema.describe() })}</script>
<script>${VALIDATE_RUNTIME}</script>`;
// render a <form data-schema="signup"> with [data-error="email"] etc.
```

## Requirements / Notes

- **Bun-only.** `parseEnv` reads `Bun.env` (falling back to `process.env`); `parseBody` and `invalid` use the Web `Request`/`Response` APIs that back `Bun.serve`.
- Refinements (`refine`) run only server-side and are never serialized — client and server agree on every other rule because both interpret the same `RuleDescriptor` list.
- No runtime dependencies. Ships as TypeScript source (`src/index.ts`) executed directly by Bun.
- Pairs with the WrNexus server (`@wrnexus/core`) for route handlers and the SSR layer that injects `renderSchemasScript` / `VALIDATE_RUNTIME`.

### Exported TypeScript declarations

```ts
/**
 * Client-side validation. `renderSchemasScript` bakes the discovered schema
 * descriptors into `window.__wireSchemas`; `VALIDATE_RUNTIME` is a generic,
 * eval-free validator that reads them and validates every `form[data-schema]`
 * on submit and blur, writing messages into `[data-error="<field>"]` elements.
 * The rule logic mirrors `checkField`/`applyRule` in index.ts.
 */

/** `window.__wireSchemas = { name: descriptor, ... }` for the client validator. */
declare function renderSchemasScript(descriptors: Record<string, SchemaDescriptor>): string;
declare const VALIDATE_RUNTIME: string;

interface AsyncValidationContext<T> {
    value: T;
    addIssue(field: keyof T | string, message: string): void;
    signal?: AbortSignal;
}
type AsyncRefinement<T> = (context: AsyncValidationContext<T>) => void | Promise<void>;
declare class AsyncObjectSchema<T extends Record<string, unknown> = Record<string, unknown>> {
    #private;
    readonly base: ObjectSchema;
    constructor(base: ObjectSchema);
    refine(refinement: AsyncRefinement<T>): this;
    describe(): SchemaDescriptor;
    parse(input: unknown, signal?: AbortSignal): Promise<ParseResult<T>>;
}
declare function asyncSchema<T extends Record<string, unknown> = Record<string, unknown>>(schema: ObjectSchema): AsyncObjectSchema<T>;
declare function parseBodyAsync<T extends Record<string, unknown>>(schema: AsyncObjectSchema<T>, request: Request, signal?: AbortSignal): Promise<{
    ok: true;
    value: T;
} | {
    ok: false;
    response: Response;
}>;
interface OpenApiSchema {
    type: "object";
    properties: Record<string, Record<string, unknown>>;
    required?: string[];
}
declare function schemaToOpenApi(schema: ObjectSchema | AsyncObjectSchema): OpenApiSchema;
declare function mergeValidationResults<T>(...results: ParseResult<T>[]): ParseResult<T>;

/**
 * @wrnexus/validation — one schema, validated on the server (API) and the browser
 * (forms). A schema is a fluent builder; `.parse()` runs server-side and returns
 * coerced values + field errors, while `.describe()` emits a JSON descriptor the
 * eval-free client validator interprets. Define schemas once in `app/schemas/`.
 */
type RuleDescriptor = {
    kind: "min";
    n: number;
    message?: string;
} | {
    kind: "max";
    n: number;
    message?: string;
} | {
    kind: "length";
    n: number;
    message?: string;
} | {
    kind: "email";
    message?: string;
} | {
    kind: "url";
    message?: string;
} | {
    kind: "uuid";
    message?: string;
} | {
    kind: "date";
    message?: string;
} | {
    kind: "oneOf";
    values: (string | number)[];
    message?: string;
} | {
    kind: "pattern";
    source: string;
    flags?: string;
    message?: string;
} | {
    kind: "integer";
    message?: string;
};
interface FieldDescriptor {
    type: "string" | "number" | "boolean" | "unknown";
    optional?: boolean;
    /** Message used when a required field is empty. Defaults to "Required". */
    requiredMessage?: string;
    label?: string;
    /** Trim string input before validating. */
    trim?: boolean;
    rules: RuleDescriptor[];
}
interface SchemaDescriptor {
    type: "object";
    fields: Record<string, FieldDescriptor>;
}
interface ParseResult<T = Record<string, unknown>> {
    ok: boolean;
    /** Coerced values (present whether or not validation passed). */
    value: T;
    /** Field name → message, only for fields that failed. */
    errors: Record<string, string>;
}
/**
 * Apply one rule to an already-coerced value. Shared by the server; the client
 * runtime (runtime.ts) mirrors this exactly. Returns an error message or null.
 */
declare function applyRule(type: string, rule: RuleDescriptor, value: unknown): string | null;
/** Coerce + validate one field against its descriptor. */
declare function checkField(desc: FieldDescriptor, raw: unknown): {
    value: unknown;
    error: string | null;
};
/** A server-only refinement (a predicate that can't be serialized to the client). */
type Refinement = {
    fn: (value: unknown) => boolean | string;
    message?: string;
};
declare abstract class FieldSchema {
    abstract readonly type: "string" | "number" | "boolean" | "unknown";
    protected _optional: boolean;
    protected _requiredMessage?: string;
    protected _label?: string;
    protected _default?: unknown;
    protected rules: RuleDescriptor[];
    protected refinements: Refinement[];
    optional(): this;
    /** Require a non-empty value and optionally replace the default message. */
    required(message?: string): this;
    label(label: string): this;
    /** Value used when the field is absent (implies optional). */
    default(value: unknown): this;
    min(n: number, message?: string): this;
    max(n: number, message?: string): this;
    /**
     * Custom SERVER-side validation. `fn` returns true (ok), false (use `message`),
     * or a string (that error). Not mirrored to the client validator.
     */
    refine(fn: (value: unknown) => boolean | string, message?: string): this;
    getDefault(): unknown;
    runRefinements(value: unknown): string | null;
    describe(): FieldDescriptor;
}
declare class StringSchema extends FieldSchema {
    readonly type: "string";
    private _trim;
    email(message?: string): this;
    url(message?: string): this;
    uuid(message?: string): this;
    date(message?: string): this;
    length(n: number, message?: string): this;
    oneOf(values: string[], message?: string): this;
    trim(): this;
    pattern(re: RegExp, message?: string): this;
    describe(): FieldDescriptor;
}
declare class NumberSchema extends FieldSchema {
    readonly type: "number";
    integer(message?: string): this;
    positive(message?: string): this;
    oneOf(values: number[], message?: string): this;
}
declare class BooleanSchema extends FieldSchema {
    readonly type: "boolean";
}
declare class UnknownSchema extends FieldSchema {
    readonly type: "unknown";
}
type AnyFieldSchema = StringSchema | NumberSchema | BooleanSchema | UnknownSchema;
declare class ObjectSchema {
    private readonly fields;
    constructor(fields: Record<string, FieldSchema>);
    /** Return a defensive copy of the schema fields. */
    getFields(): Readonly<Record<string, FieldSchema>>;
    /** Create a new schema with fields added or replaced. The original is unchanged. */
    extend(fields: Record<string, FieldSchema>): ObjectSchema;
    /** Create a new schema containing fields from both schemas. */
    merge(schema: ObjectSchema): ObjectSchema;
    /** Validate an input object; returns coerced values + per-field errors. */
    parse(input: unknown): ParseResult;
    describe(): SchemaDescriptor;
}
/** The fluent schema builder. */
declare const v: {
    string: () => StringSchema;
    number: () => NumberSchema;
    boolean: () => BooleanSchema;
    unknown: () => UnknownSchema;
    object: (fields: Record<string, FieldSchema>) => ObjectSchema;
};
/**
 * Validate environment variables against a schema at startup. Values are read
 * from `Bun.env` / `process.env` by default and coerced by the schema (so
 * `PORT` becomes a number, `DEBUG` a boolean). On any problem it throws ONE
 * readable error listing every offending variable, so misconfiguration fails
 * fast with an actionable message instead of surfacing deep inside the app.
 *
 *   export const env = parseEnv(v.object({
 *     DATABASE_URL: v.string().min(1),
 *     PORT: v.number(),
 *   }));
 */
declare function parseEnv<T = Record<string, unknown>>(schema: ObjectSchema, source?: Record<string, string | undefined>): T;
/** A 400 response carrying field errors, for API routes. */
declare function invalid(errors: Record<string, string>): Response;
/**
 * Parse a request's JSON body against a schema. On failure returns
 * `{ ok: false, response }` (a ready 400); on success `{ ok: true, value }`.
 */
declare function parseBody<T = Record<string, unknown>>(schema: ObjectSchema, req: Request): Promise<{
    ok: true;
    value: T;
} | {
    ok: false;
    response: Response;
}>;

export { type AnyFieldSchema, AsyncObjectSchema, type AsyncRefinement, type AsyncValidationContext, BooleanSchema, type FieldDescriptor, FieldSchema, NumberSchema, ObjectSchema, type OpenApiSchema, type ParseResult, type RuleDescriptor, type SchemaDescriptor, StringSchema, UnknownSchema, VALIDATE_RUNTIME, applyRule, asyncSchema, checkField, invalid, mergeValidationResults, parseBody, parseBodyAsync, parseEnv, renderSchemasScript, schemaToOpenApi, v };
```

# Complete @wrnexus/ui component reference and source contracts

## Accordion

Showcase: https://component.wrnexusjs.dev/
Mount: <Accordion /> (legacy: data-component="Accordion")
Category: base
Purpose: Theme-aware, responsive accordion component.
Props: size: string = "default", color: string = "primary", variant: string = "default", class: string = "", id: string = "accordion", items: string = [], defaultOpen: string = [], multiple: boolean = false, alwaysOpen: boolean = false, disabled: boolean = false, indicator: string = "plus", indicatorPosition: string = "start", showIndicator: boolean = true, bordered: boolean = false, separated: boolean = false, flush: boolean = false, contentItalic: boolean = false
Slots: none
Events: change, open, close

### Complete .wrn source contract

```wrn
component Accordion {
  props {
    size = "default"
    color = "primary"
    variant = "default"
    class = ""

    id = "accordion"
    items = []
    defaultOpen = []
    multiple = false
    alwaysOpen = false
    disabled = false

    indicator = "plus"
    indicatorPosition = "start"
    showIndicator = true
    bordered = false
    separated = false
    flush = false
    contentItalic = false

    @event change = function
    @event open = function
    @event close = function
  }

  state openValues = defaultOpen

  functions {
    function itemValue(item, index) {
      return item.value !== undefined && item.value !== ""
        ? String(item.value)
        : String(index)
    }

    function nestedValue(parent, parentIndex, item, index) {
      return itemValue(parent, parentIndex) + "." + itemValue(item, index)
    }

    function isOpen(value) {
      return openValues.includes(value)
    }

    function allowsMultiple() {
      return multiple || alwaysOpen
    }

    function dispatchAccordionEvent(sourceEvent, eventName, value, item, root, customEvent) {
      root = sourceEvent.currentTarget.closest("[data-wrn-accordion]")

      if (!root) {
        return
      }

      customEvent = document.createEvent("CustomEvent")
      customEvent.initCustomEvent(eventName, true, false, {
        component: "Accordion",
        value: value,
        item: item,
        open: isOpen(value),
        openValues: openValues
      })
      root.dispatchEvent(customEvent)
    }

    function toggleItem(sourceEvent, value, item, wasOpen) {
      if (disabled || item.disabled) {
        return
      }

      wasOpen = isOpen(value)

      if (wasOpen) {
        openValues = openValues.filter((entry) => entry !== value)
      } else if (allowsMultiple()) {
        openValues = openValues.concat([value])
      } else {
        openValues = [value]
      }

      dispatchAccordionEvent(
        sourceEvent,
        wasOpen ? "close" : "open",
        value,
        item
      )
      dispatchAccordionEvent(sourceEvent, "change", value, item)
    }

  }

  view {
    <div
      {...attrs}
      id="{id}"
      data-wrn-accordion
      data-variant="{variant}"
      data-indicator="{indicator}"
      data-multiple="{allowsMultiple() ? 'true' : 'false'}"
      class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--accordion wire-next--accordion-{variant} {bordered ? 'wire-next--accordion-bordered' : ''} {separated ? 'wire-next--accordion-separated' : ''} {flush ? 'wire-next--accordion-flush' : ''} {disabled ? 'wire-next--disabled' : ''} {class}"
    >
      {#each items as item, index}
        <section
          class="wire-next__accordion-item"
          data-open="{isOpen(itemValue(item, index)) ? 'true' : 'false'}"
          data-disabled="{disabled || item.disabled ? 'true' : 'false'}"
        >
          <h3 class="wire-next__accordion-heading">
            <button
              type="button"
              id="{id}-trigger-{index}"
              aria-expanded="{isOpen(itemValue(item, index)) ? 'true' : 'false'}"
              aria-controls="{id}-panel-{index}"
              disabled="{disabled || item.disabled}"
              @click="toggleItem(event, itemValue(item, index), item)"
            >
              {#if showIndicator && indicatorPosition === "start"}
                <span class="wire-next__accordion-indicator" aria-hidden="true">
                  {#if indicator === "chevron"}
                    <span class="icon-[lucide--chevron-down]"></span>
                  {:else}
                    <span>+</span>
                  {/if}
                </span>
              {/if}
              <span>{item.label || item.title}</span>
              {#if showIndicator && indicatorPosition === "end"}
                <span class="wire-next__accordion-indicator" aria-hidden="true">
                  {#if indicator === "chevron"}
                    <span class="icon-[lucide--chevron-down]"></span>
                  {:else}
                    <span>+</span>
                  {/if}
                </span>
              {/if}
            </button>
          </h3>

          <div
            id="{id}-panel-{index}"
            class="wire-next__accordion-panel"
            role="region"
            aria-labelledby="{id}-trigger-{index}"
            aria-hidden="{isOpen(itemValue(item, index)) ? 'false' : 'true'}"
          >
            <div>
              <div class="wire-next__accordion-content {contentItalic ? 'wire-next__accordion-content-italic' : ''}">
                {#if item.content}<p>{item.content}</p>{/if}

                {#if item.children && item.children.length > 0}
                  <div class="wire-next__accordion-nested">
                    {#each item.children as child, childIndex}
                      <section
                        class="wire-next__accordion-item"
                        data-open="{isOpen(nestedValue(item, index, child, childIndex)) ? 'true' : 'false'}"
                      >
                        <h4 class="wire-next__accordion-heading">
                          <button
                            type="button"
                            id="{id}-trigger-{index}-{childIndex}"
                            aria-expanded="{isOpen(nestedValue(item, index, child, childIndex)) ? 'true' : 'false'}"
                            aria-controls="{id}-panel-{index}-{childIndex}"
                            disabled="{disabled || child.disabled}"
                            @click="toggleItem(event, nestedValue(item, index, child, childIndex), child)"
                          >
                            {#if showIndicator}
                              <span class="wire-next__accordion-indicator" aria-hidden="true">
                                {#if indicator === "chevron"}
                                  <span class="icon-[lucide--chevron-down]"></span>
                                {:else}
                                  <span>+</span>
                                {/if}
                              </span>
                            {/if}
                            <span>{child.label || child.title}</span>
                          </button>
                        </h4>
                        <div
                          id="{id}-panel-{index}-{childIndex}"
                          class="wire-next__accordion-panel"
                          role="region"
                          aria-labelledby="{id}-trigger-{index}-{childIndex}"
                          aria-hidden="{isOpen(nestedValue(item, index, child, childIndex)) ? 'false' : 'true'}"
                        >
                          <div>
                            <div class="wire-next__accordion-content {contentItalic ? 'wire-next__accordion-content-italic' : ''}">
                              <p>{child.content}</p>
                            </div>
                          </div>
                        </div>
                      </section>
                    {/each}
                  </div>
                {/if}
              </div>
            </div>
          </div>
        </section>
      {/each}
    </div>
  }
}
```

---

## AdvancedDatePicker

Showcase: https://component.wrnexusjs.dev/
Mount: <AdvancedDatePicker /> (legacy: data-component="AdvancedDatePicker")
Category: integrations
Purpose: Theme-aware, responsive advanced date picker component.
Props: size: string = "default", color: string = "primary", title: string = "Advanced Date Picker", description: string = "", items: string = [], variant: string = "default", class: string = ""
Slots: default
Events: input, change, open, close, clear

### Complete .wrn source contract

```wrn
component AdvancedDatePicker {
  props {
    @event input = function
    @event change = function
    @event open = function
    @event close = function
    @event clear = function
    size = "default"
    color = "primary"
    title = "Advanced Date Picker"
    description = ""
    items = []
    variant = "default"
    class = ""
  }
  view {
    <section class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--advanced-date-picker wire-next--variant-{variant} {class}">
      {#if title}<strong>{title}</strong>{/if}
      {#if description}<p>{description}</p>{/if}
      {#if items}<div class="wire-next__items">{#each items as item}<span>{item.label}</span>{/each}</div>{/if}
      <slot />
    </section>
  }
}
```

---

## AdvancedRangeSlider

Showcase: https://component.wrnexusjs.dev/
Mount: <AdvancedRangeSlider /> (legacy: data-component="AdvancedRangeSlider")
Category: integrations
Purpose: Theme-aware, responsive advanced range slider component.
Props: size: string = "default", color: string = "primary", title: string = "Advanced Range Slider", description: string = "", items: string = [], variant: string = "default", class: string = ""
Slots: default
Events: input, change, start, end

### Complete .wrn source contract

```wrn
component AdvancedRangeSlider {
  props {
    @event input = function
    @event change = function
    @event start = function
    @event end = function
    size = "default"
    color = "primary"
    title = "Advanced Range Slider"
    description = ""
    items = []
    variant = "default"
    class = ""
  }
  view {
    <section class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--advanced-range-slider wire-next--variant-{variant} {class}">
      {#if title}<strong>{title}</strong>{/if}
      {#if description}<p>{description}</p>{/if}
      {#if items}<div class="wire-next__items">{#each items as item}<span>{item.label}</span>{/each}</div>{/if}
      <slot />
    </section>
  }
}
```

---

## AdvancedSelect

Showcase: https://component.wrnexusjs.dev/
Mount: <AdvancedSelect /> (legacy: data-component="AdvancedSelect")
Category: advanced-forms
Purpose: Theme-aware, responsive advanced select component.
Props: size: string = "default", color: string = "primary", label: string = "Advanced Select", name: string = "", value: string = "", values: string = [], options: string = [], groups: string = [], placeholder: string = "Select an option", placeholderIcon: string = "", searchPlaceholder: string = "Search options…", multiple: boolean = false, searchable: boolean = true, defaultOpen: boolean = false, clearable: boolean = true, allowEmpty: boolean = true, tags: boolean = false, disabled: boolean = false, required: boolean = false, invalid: boolean = false, validationMessage: string = "", helpText: string = "", loading: boolean = false, loadingLabel: string = "Loading options…", emptyLabel: string = "No options found", selectedOptionsLabel: string = "Selected options", clearLabel: string = "Clear selection", createLabel: string = "Create", loadMoreLabel: string = "Load more", searchMode: string = "contains", searchFields: string = "label,description", minSearchLength: number = 0, searchResultLimit: number = 0, maxSelections: number = 0, showCounter: boolean = false, counterTemplate: string = "{selected} selected", optionTemplate: string = "default", selectedTemplate: string = "default", closeOnSelect: boolean = true, scrollToSelected: boolean = true, fixed: boolean = false, placement: string = "bottom", remote: boolean = false, remoteUrl: string = "", remoteQueryParam: string = "q", remoteDebounce: number = 250, remoteAutoLoad: boolean = true, infinite: boolean = false, hasMore: boolean = false, page: number = 1, class: string = ""
Slots: none
Events: search, select, change, clear, open, close, load, error

### Complete .wrn source contract

```wrn
component AdvancedSelect {
  props {
    size = "default"
    color = "primary"
    label = "Advanced Select"
    name = ""
    value = ""
    values = []
    options = []
    groups = []
    placeholder = "Select an option"
    placeholderIcon = ""
    searchPlaceholder = "Search options…"
    multiple = false
    searchable = true
    defaultOpen = false
    clearable = true
    allowEmpty = true
    tags = false
    disabled = false
    required = false
    invalid = false
    validationMessage = ""
    helpText = ""
    loading = false
    loadingLabel = "Loading options…"
    emptyLabel = "No options found"
    selectedOptionsLabel = "Selected options"
    clearLabel = "Clear selection"
    createLabel = "Create"
    loadMoreLabel = "Load more"
    searchMode = "contains"
    searchFields = "label,description"
    minSearchLength = 0
    searchResultLimit = 0
    maxSelections = 0
    showCounter = false
    counterTemplate = "{selected} selected"
    optionTemplate = "default"
    selectedTemplate = "default"
    closeOnSelect = true
    scrollToSelected = true
    fixed = false
    placement = "bottom"
    remote = false
    remoteUrl = ""
    remoteQueryParam = "q"
    remoteDebounce = 250
    remoteAutoLoad = true
    infinite = false
    hasMore = false
    page = 1
    class = ""
    @event search = function
    @event select = function
    @event change = function
    @event clear = function
    @event open = function
    @event close = function
    @event load = function
    @event error = function
  }

  state open = defaultOpen
  state query = ""
  state activeIndex = -1
  state selectedValue = value
  state selectedValues = values

  functions {
    function allOptions() {
      return [...groups.flatMap((group) => group.options || []), ...options]
    }

    function searchableText(option) {
      return ((option.label || "") + " " + (option.description || "")).toLowerCase()
    }

    function matches(option) {
      if (!query || query.length < Number(minSearchLength || 0)) {
        return true
      }
      if (searchMode === "startsWith") {
        return searchableText(option).startsWith(query.toLowerCase())
      }
      if (searchMode === "exact") {
        return searchableText(option) === query.toLowerCase()
      }
      return searchableText(option).includes(query.toLowerCase())
    }

    function matchingOptions(list) {
      return list.filter((option) => matches(option))
    }

    function visibleOptions(list) {
      if (searchResultLimit > 0) {
        return matchingOptions(list).slice(0, Number(searchResultLimit))
      }
      return matchingOptions(list)
    }

    function flatVisibleOptions() {
      return visibleOptions(allOptions())
    }

    function isSelected(option) {
      return (
        multiple
        ? selectedValues.includes(option.value)
        : selectedValue === option.value
      )
    }

    function selectedOptions() {
      return allOptions().filter((option) => isSelected(option))
    }

    function selectedCount() {
      return multiple ? selectedValues.length : selectedValue ? 1 : 0
    }

    function counterText() {
      return (
        maxSelections
        ? selectedCount() + " / " + maxSelections + " selected"
        : selectedCount() + " selected"
      )
    }

    function selectedText() {
      return (
        multiple
        ? selectedValues.join(", ")
        : selectedOptions().length
          ? selectedOptions()[0].label
          : ""
      )
    }

    function triggerText() {
      return selectedCount() ? selectedText() : placeholder
    }

    function canSelect(option) {
      if (option.disabled) {
        return false
      }
      if (!multiple || isSelected(option)) {
        return true
      }
      if (maxSelections <= 0) {
        return true
      }
      return selectedCount() < maxSelections
    }

    function chooseSingle(option) {
      if (!canSelect(option)) {
        return
      }
      selectedValue = option.value
      query = ""
      if (closeOnSelect) {
        open = false
      }
    }

    function chooseMultiple(option) {
      if (!canSelect(option)) {
        return
      }
      if (isSelected(option)) {
        selectedValues = selectedValues.filter((item) => item !== option.value)
      } else {
        selectedValues = selectedValues.concat([option.value])
      }
      query = ""
    }

    function chooseOption(option) {
      if (multiple) {
        chooseMultiple(option)
        return
      }
      chooseSingle(option)
    }

    function clearSelection(event) {
      event.stopPropagation()
      selectedValue = ""
      selectedValues = []
      query = ""
      open = false
    }

    function toggle() {
      if (disabled) {
        return;
      };
      open = !open;
      activeIndex = open && flatVisibleOptions().length ? 0 : -1;
    }

    function moveActive(direction) {
      if (!flatVisibleOptions().length) {
        return
      }
      activeIndex = (activeIndex + direction + flatVisibleOptions().length) % flatVisibleOptions().length
    }

    function handleKeydown(event) {
      if (disabled) {
        return
      }
      if (event.key === "ArrowDown") {
        event.preventDefault()
        if (!open) {
          open = true
        }
        moveActive(1)
      } else if (event.key === "ArrowUp") {
        event.preventDefault()
        if (!open) {
          open = true
        }
        moveActive(-1)
      } else if (event.key === "Enter" || event.key === " ") {
        event.preventDefault()
        if (!open) {
          open = true
        } else if (activeIndex >= 0) {
          chooseOption(flatVisibleOptions()[activeIndex])
        }
      } else if (event.key === "Escape") {
        open = false
      } else if (event.key === "Home" && open) {
        event.preventDefault()
        activeIndex = 0
      } else if (event.key === "End" && open) {
        event.preventDefault()
        activeIndex = flatVisibleOptions().length - 1
      }
    }

    function optionIndex(option) {
      return flatVisibleOptions().findIndex((item) => item.value === option.value)
    }
  }

  view {
    <div
      class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--advanced-select {open ? 'wire-next--open' : ''} {fixed ? 'wire-next--advanced-select-fixed' : ''} {invalid ? 'wire-next--invalid' : ''} {disabled ? 'wire-next--disabled' : ''} {class}"
      data-placement="{placement}"
      data-search-mode="{searchMode}"
      data-remote="{remote ? 'true' : 'false'}"
      data-remote-url="{remoteUrl}"
      data-remote-query-param="{remoteQueryParam}"
      data-remote-debounce="{remoteDebounce}"
      data-remote-auto-load="{remoteAutoLoad ? 'true' : 'false'}"
      data-infinite="{infinite ? 'true' : 'false'}"
      data-page="{page}"
      data-wrn-select
      @focusout="if (!event.currentTarget.contains(event.relatedTarget)) { open = false }"
    >
      <div class="wire-next__row">
        <label id="{name}-label" for="{name}-trigger">{label}</label>
        <small data-show="showCounter" data-text="counterText()">{counterText()}</small>
      </div>

      <div class="wire-next__select-control">
        <button
          {...attrs}
          id="{name}-trigger"
          type="button"
          class="wire-next__select-trigger"
          role="combobox"
          aria-haspopup="listbox"
          aria-expanded="{open}"
          aria-controls="{name}-listbox"
          aria-labelledby="{name}-label"
          aria-invalid="{invalid}"
          disabled="{disabled}"
          @click="toggle()"
          @keydown="handleKeydown(event)"
        >
          <span class="wire-next__select-value">
            <span data-show="!multiple" data-text="triggerText()">{triggerText()}</span>
            <span
              data-show="multiple && selectedTemplate === 'count' && selectedCount() > 0"
              data-text="selectedCount() + ' selected'"
            >{selectedCount()} selected</span>
            <span
              data-show="multiple && selectedTemplate === 'text' && selectedCount() > 0"
              data-text="selectedText()"
            >{selectedText()}</span>
            <span
              class="wire-next__select-tags"
              aria-label="{selectedOptionsLabel}"
              data-show="multiple && selectedTemplate !== 'count' && selectedTemplate !== 'text' && selectedCount() > 0"
            >
              {#each allOptions() as option}
                <span data-show="isSelected(option)">
                  {#if optionTemplate === "icon" && option.icon}<i class="{option.icon}" aria-hidden="true"></i>{/if}
                  {#if optionTemplate === "avatar" && option.avatar}<img src="{option.avatar}" alt="" />{/if}
                  {#if optionTemplate === "color" && option.color}<i class="wire-next__color-dot" style="--option-color: {option.color}"></i>{/if}
                  {option.label}
                </span>
              {/each}
            </span>
            <span data-show="multiple && selectedCount() === 0">
              {#if placeholderIcon}<i class="{placeholderIcon}" aria-hidden="true"></i>{/if}
              <span class="wire-next__placeholder">{placeholder}</span>
            </span>
          </span>
          <span
            class="wire-next__select-chevron icon-[lucide--chevrons-up-down]"
            aria-hidden="true"
          ></span>
        </button>

        <button
          type="button"
          class="wire-next__clear-select"
          data-show="clearable && allowEmpty && selectedCount() > 0 && !disabled"
          aria-label="{clearLabel}"
          title="{clearLabel}"
          @click="clearSelection(event)"
        >
          <span class="icon-[lucide--x]" aria-hidden="true"></span>
        </button>
      </div>

      <div
        class="wire-next__select-dropdown {fixed ? 'wire-next__select-dropdown--fixed' : ''}"
        data-show="open"
        style="{open ? '' : 'display: none'}"
      >
          {#if searchable}
            <label class="wire-next__select-search">
              <span class="wire-visually-hidden">{searchPlaceholder}</span>
              <span class="wire-next__search-icon" aria-hidden="true">⌕</span>
              <input
                type="search"
                value="{query}"
                placeholder="{searchPlaceholder}"
                autocomplete="off"
                @input="query = event.target.value; activeIndex = flatVisibleOptions().length ? 0 : -1"
                @keydown="handleKeydown(event)"
              />
            </label>
          {/if}

          <div
            class="wire-next__select-message"
            data-show="remote && query.length !== 0 && query.length < minSearchLength"
          >Enter at least {minSearchLength} characters.</div>
          <div class="wire-next__select-message" data-show="loading" role="status">
            <i class="wire-spinner wire-spinner--inline" aria-hidden="true"></i>
            {loadingLabel}
          </div>
            <div
              id="{name}-listbox"
              class="wire-next__select-list"
              data-show="(!remote || (query.length === 0 && remoteAutoLoad) || query.length >= minSearchLength) && !loading"
              role="listbox"
              aria-multiselectable="{multiple}"
            >
              {#each groups as group}
                {#if visibleOptions(group.options || []).length}
                  <div class="wire-next__option-group" role="group" aria-label="{group.label}">
                    <div class="wire-next__group-label">{group.label}</div>
                    {#each group.options || [] as option}
                      <button
                        type="button"
                        class="wire-next__select-option {isSelected(option) ? 'wire-next__select-option--selected' : ''} {optionIndex(option) === activeIndex ? 'wire-next__select-option--active' : ''}"
                        data-option-value="{option.value}"
                        data-show="matches(option)"
                        role="option"
                        aria-selected="{isSelected(option)}"
                        disabled="{!canSelect(option)}"
                        @mouseenter="activeIndex = optionIndex(option)"
                        @click="chooseOption(option)"
                      >
                        {#if optionTemplate === "icon" && option.icon}<i class="{option.icon}" aria-hidden="true"></i>{/if}
                        {#if optionTemplate === "avatar" && option.avatar}<img src="{option.avatar}" alt="" />{/if}
                        {#if optionTemplate === "color" && option.color}<i class="wire-next__color-dot" style="--option-color: {option.color}"></i>{/if}
                        <span><strong>{option.label}</strong>{#if option.description}<small>{option.description}</small>{/if}</span>
                        <i
                          class="wire-next__check icon-[lucide--check]"
                          data-show="isSelected(option)"
                          aria-hidden="true"
                        ></i>
                      </button>
                    {/each}
                  </div>
                {/if}
              {/each}

              {#each options as option}
                <button
                  type="button"
                  class="wire-next__select-option {isSelected(option) ? 'wire-next__select-option--selected' : ''} {optionIndex(option) === activeIndex ? 'wire-next__select-option--active' : ''}"
                  data-option-value="{option.value}"
                  data-show="matches(option)"
                  role="option"
                  aria-selected="{isSelected(option)}"
                  disabled="{!canSelect(option)}"
                  @mouseenter="activeIndex = optionIndex(option)"
                  @click="chooseOption(option)"
                >
                  {#if optionTemplate === "icon" && option.icon}<i class="{option.icon}" aria-hidden="true"></i>{/if}
                  {#if optionTemplate === "avatar" && option.avatar}<img src="{option.avatar}" alt="" />{/if}
                  {#if optionTemplate === "color" && option.color}<i class="wire-next__color-dot" style="--option-color: {option.color}"></i>{/if}
                  <span><strong>{option.label}</strong>{#if option.description}<small>{option.description}</small>{/if}</span>
                  <i
                    class="wire-next__check icon-[lucide--check]"
                    data-show="isSelected(option)"
                    aria-hidden="true"
                  ></i>
                </button>
              {/each}

              {#if !loading && !flatVisibleOptions().length}
                <div class="wire-next__select-message">{emptyLabel}</div>
              {/if}
            </div>

          {#if tags && query && !allOptions().some((option) => option.label.toLowerCase() === query.toLowerCase())}
            <button type="button" class="wire-next__create-option">{createLabel} “{query}”</button>
          {/if}
          <button
            type="button"
            class="wire-next__load-more"
            data-wrn-select-load-more
            data-show="infinite && hasMore"
          >{loadMoreLabel}</button>
      </div>

      <input
        type="hidden"
        name="{name}"
        value="{multiple ? selectedValues.join(',') : selectedValue}"
        required="{required}"
        aria-describedby="{validationMessage ? `${name}-validation` : helpText ? `${name}-help` : ''}"
      />

      {#if helpText && !validationMessage}<small id="{name}-help">{helpText}</small>{/if}
      <small
        id="{name}-validation"
        class="wire-next__validation"
        data-error="{name}"
      >{validationMessage}</small>
    </div>
  }
}
```

---

## Alert

Showcase: https://component.wrnexusjs.dev/
Mount: <Alert /> (legacy: data-component="Alert")
Category: base
Purpose: Theme-aware, responsive alert component.
Props: size: string = "default", color: string = "info", variant: string = "soft", class: string = "", radius: string = "md", shadow: string = "sm", title: string = "Alert", description: string = "", items: string = [], actions: string = [], showIcon: boolean = false, icon: string = "", dismissible: boolean = false, dismissLabel: string = "Dismiss alert", role: string = "alert", live: string = "polite", linkLabel: string = "", linkHref: string = "", actionLabel: string = "", actionHref: string = "", compact: boolean = false
Slots: none
Events: dismiss, action

### Complete .wrn source contract

```wrn
component Alert {
  props {
    size = "default"
    color = "info"
    variant = "soft"
    class = ""
    radius = "md"
    shadow = "sm"

    title = "Alert"
    description = ""
    items = []
    actions = []

    showIcon = false
    icon = ""
    dismissible = false
    dismissLabel = "Dismiss alert"
    role = "alert"
    live = "polite"

    linkLabel = ""
    linkHref = ""
    actionLabel = ""
    actionHref = ""
    compact = false

    @event dismiss = function
    @event action = function
  }

  state visible = true

  functions {
    function dispatchAlertEvent(sourceEvent, eventName, action, root, customEvent) {
      root = sourceEvent.currentTarget.closest("[data-wrn-alert]")

      if (!root) {
        return
      }

      customEvent = document.createEvent("CustomEvent")
      customEvent.initCustomEvent(eventName, true, false, {
        component: "Alert",
        title: title,
        color: color,
        variant: variant,
        action: action
      })
      root.dispatchEvent(customEvent)
    }

    function dismissAlert(sourceEvent) {
      visible = false
      dispatchAlertEvent(sourceEvent, "dismiss", null)
    }

    function selectAction(sourceEvent, action) {
      dispatchAlertEvent(sourceEvent, "action", action)
    }
  }

  view {
    <section
      {...attrs}
      data-wrn-alert
      data-color="{color}"
      data-variant="{variant}"
      data-radius="{radius}"
      data-shadow="{shadow}"
      data-show="visible"
      aria-hidden="{visible ? 'false' : 'true'}"
      role="{role}"
      aria-live="{live}"
      class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--alert wire-next--alert-{variant} {compact ? 'wire-next--alert-compact' : ''} {class}"
    >
      {#if showIcon}
        <span class="wire-next__alert-icon" aria-hidden="true">
          {#if icon}
            <span class="{icon}"></span>
          {:else if color === "success"}
            <span class="icon-[lucide--circle-check]"></span>
          {:else if color === "danger"}
            <span class="icon-[lucide--circle-x]"></span>
          {:else if color === "warning"}
            <span class="icon-[lucide--triangle-alert]"></span>
          {:else}
            <span class="icon-[lucide--info]"></span>
          {/if}
        </span>
      {/if}

      <div class="wire-next__alert-body">
        {#if title}<strong class="wire-next__alert-title">{title}</strong>{/if}
        {#if description}<p>{description}</p>{/if}

        {#if items.length > 0}
          <ul>
            {#each items as item}<li>{item.label || item}</li>{/each}
          </ul>
        {/if}

        {#if actions.length > 0 || actionLabel || linkLabel}
          <div class="wire-next__alert-actions">
            {#each actions as item}
              <a
                href="{item.href || '#'}"
                data-variant="{item.variant || 'link'}"
                @click="selectAction(event, item)"
              >{item.label}</a>
            {/each}
            {#if actionLabel}
              <a
                href="{actionHref || '#'}"
                data-variant="action"
                @click="selectAction(event, { label: actionLabel, href: actionHref })"
              >{actionLabel}</a>
            {/if}
            {#if linkLabel}
              <a
                href="{linkHref || '#'}"
                data-variant="link"
                @click="selectAction(event, { label: linkLabel, href: linkHref })"
              >{linkLabel}</a>
            {/if}
          </div>
        {/if}
      </div>

      {#if dismissible}
        <button
          type="button"
          class="wire-next__alert-dismiss"
          aria-label="{dismissLabel}"
          @click="dismissAlert(event)"
        >
          <span class="icon-[lucide--x]" aria-hidden="true"></span>
        </button>
      {/if}
    </section>
  }
}
```

---

## AnnouncementBar

Showcase: https://component.wrnexusjs.dev/
Mount: <AnnouncementBar /> (legacy: data-component="AnnouncementBar")
Category: blocks
Purpose: Accessible public announcement, emergency, maintenance, or status bar.
Props: badge: string = "", badgeIcon: string = "", message: string = "Announcement", description: string = "", icon: string = "icon-[lucide--megaphone]", actionLabel: string = "", actionHref: string = "", actionIcon: string = "", dismissible: boolean = false, dismissLabel: string = "Dismiss announcement", sticky: boolean = false, compact: boolean = false, size: string = "default", color: string = "primary", variant: string = "soft", role: string = "status", live: string = "polite", class: string = ""
Slots: none
Events: none

### Complete .wrn source contract

```wrn
component AnnouncementBar {
  props {
    badge = ""
    badgeIcon = ""
    message = "Announcement"
    description = ""
    icon = "icon-[lucide--megaphone]"
    actionLabel = ""
    actionHref = ""
    actionIcon = ""
    dismissible = false
    dismissLabel = "Dismiss announcement"
    sticky = false
    compact = false
    size = "default"
    color = "primary"
    variant = "soft"
    role = "status"
    live = "polite"
    class = ""
  }

  state dismissed = false

  view {
    <aside
      data-ui-component="AnnouncementBar"
      role='{role}'
      aria-live='{live}'
      data-show='!dismissed'
      class='z-40 w-full border-y border-[var(--wire-color-border)] {class}'
      class:sticky='sticky'
      class:top-0='sticky'
      class:bg-[var(--wire-color-primary-soft)]='variant === "soft" && color === "primary"'
      class:border-[var(--wire-color-primary-muted)]='variant === "soft" && color === "primary"'
      class:bg-[var(--wire-color-info-soft)]='variant === "soft" && color === "info"'
      class:border-[var(--wire-color-info-muted)]='variant === "soft" && color === "info"'
      class:bg-[var(--wire-color-success-soft)]='variant === "soft" && color === "success"'
      class:border-[var(--wire-color-success-muted)]='variant === "soft" && color === "success"'
      class:bg-[var(--wire-color-warning-soft)]='variant === "soft" && color === "warning"'
      class:border-[var(--wire-color-warning-muted)]='variant === "soft" && color === "warning"'
      class:bg-[var(--wire-color-danger-soft)]='variant === "soft" && color === "danger"'
      class:border-[var(--wire-color-danger-muted)]='variant === "soft" && color === "danger"'
      class:bg-[var(--wire-color-primary)]='variant === "solid" && color === "primary"'
      class:text-[var(--wire-color-on-primary)]='variant === "solid" && color === "primary"'
      class:bg-[var(--wire-color-danger)]='variant === "solid" && color === "danger"'
      class:text-[var(--wire-color-on-danger)]='variant === "solid" && color === "danger"'
      class:bg-[var(--wire-color-surface-raised)]='variant === "default"'
    >
      <Container columns="1" maxWidth="xl" size="default">
        <div
          class="flex flex-col gap-4 py-4 sm:flex-row sm:items-center sm:justify-between"
          class:py-2.5='compact'
        >
          <div class="flex min-w-0 items-start gap-3 sm:items-center">
            {#if icon}
              <span
                class="flex size-10 shrink-0 items-center justify-center rounded-xl bg-[var(--wire-color-surface-raised)] text-[var(--wire-color-primary)] shadow-sm"
                class:size-8='compact'
                class:text-[var(--wire-color-danger)]='color === "danger"'
                class:text-[var(--wire-color-warning-text)]='color === "warning"'
                class:text-[var(--wire-color-success)]='color === "success"'
                class:text-[var(--wire-color-info)]='color === "info"'
              >
                <span class='{icon + " size-5"}' aria-hidden="true"></span>
              </span>
            {/if}

            <div class="min-w-0">
              <div class="flex flex-wrap items-center gap-2">
                {#if badge}
                  <Badge
                    label='{badge}'
                    icon='{badgeIcon}'
                    size="sm"
                    color='{color}'
                    variant='{variant === "solid" ? "outline" : "solid"}'
                  />
                {/if}

                <p
                  class="font-semibold"
                  class:text-sm='compact || size === "sm"'
                  class:text-base='!compact && size !== "sm"'
                  class:text-[var(--wire-color-text)]='variant !== "solid"'
                >
                  {message}
                </p>
              </div>

              {#if description && !compact}
                <p
                  class="mt-1 text-sm leading-6"
                  class:text-[var(--wire-color-text-muted)]='variant !== "solid"'
                  class:opacity-85='variant === "solid"'
                >
                  {description}
                </p>
              {/if}
            </div>
          </div>

          <div class="flex shrink-0 items-center gap-2 sm:justify-end">
            {#if actionLabel}
              <TextLink
                label='{actionLabel}'
                href='{actionHref}'
                icon='{actionIcon}'
                iconPosition="start"
                showArrow="true"
                color='{variant === "solid" ? "neutral" : color}'
                variant='{variant === "solid" ? "button" : "default"}'
              />
            {/if}

            {#if dismissible}
              <button
                type="button"
                aria-label='{dismissLabel}'
                class="inline-flex size-9 items-center justify-center rounded-lg text-[var(--wire-color-text-muted)] transition hover:bg-[var(--wire-color-surface-raised)] hover:text-[var(--wire-color-text)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--wire-color-focus)]"
                @click='dismissed = true; event.currentTarget.dispatchEvent(new CustomEvent("dismiss", { bubbles: true }))'
              >
                <span class="icon-[lucide--x] size-4" aria-hidden="true"></span>
              </button>
            {/if}
          </div>
        </div>
      </Container>
    </aside>
  }
}
```

---

## AuthForm

Showcase: https://component.wrnexusjs.dev/
Mount: <AuthForm /> (legacy: data-component="AuthForm")
Category: forms
Purpose: Reusable authentication form for sign-in, registration, recovery, reset, and MFA.
Props: size: string = "default", color: string = "primary", mode: string = "sign-in", action: string = "/api/auth/login", method: string = "post", title: string = "Sign in", description: string = "", returnTo: string = "", schema: string = "", showRemember: boolean = true, showName: boolean = true, submitLabel: string = "Continue", class: string = ""
Slots: default
Events: submit, change, input, focus, blur

### Complete .wrn source contract

```wrn
component AuthForm {
  props {
    @event submit = function
    @event change = function
    @event input = function
    @event focus = function
    @event blur = function
    size = "default"
    color = "primary"
    mode = "sign-in"
    action = "/api/auth/login"
    method = "post"
    title = "Sign in"
    description = ""
    returnTo = ""
    schema = ""
    showRemember = true
    showName = true
    submitLabel = "Continue"
    class = ""
  }

  functions {
    function schemaName() {
      if (schema) return schema
      if (mode === "sign-in") return "auth-login"
      if (mode === "register") return "auth-register"
      if (mode === "recover") return "auth-password-request"
      if (mode === "reset") return "auth-password-reset"
      if (mode === "mfa") return "auth-mfa"
      return "auth-empty"
    }

    function submitForm(event) {
      $emit("submit", { event: event, mode: mode, action: action })
    }
    function fieldEvent(type, event) {
      const detail = event.detail || {}
      $emit(type, { event: event, name: detail.name || "", value: detail.value || "" })
    }
  }

  view {
    <section class="wire-auth-form wire-next--color-{color} wire-next--size-{size} {class}">
      <header>
        <span class="wire-auth-form__icon icon-[lucide--fingerprint]" aria-hidden="true"></span>
        <div><h2>{title}</h2>{#if description}<p>{description}</p>{/if}</div>
      </header>
      <form
        action="{action}"
        method="{method}"
        data-schema="{schemaName()}"
        data-wrnexus-runtime="auth"
        novalidate="true"
        @submit="submitForm($event)"
      >
        {#if returnTo}<input type="hidden" name="returnTo" value="{returnTo}" />{/if}
        {#if mode === "register" && showName}
          <Input label="Full name" name="displayName" autocomplete="name" placeholder="Enter your full name" required="true" icon="icon-[lucide--user-round]" iconPosition="start" @change="fieldEvent('change', $event)" @input="fieldEvent('input', $event)" @focus="fieldEvent('focus', $event)" @blur="fieldEvent('blur', $event)" />
        {/if}
        {#if mode === "sign-in" || mode === "register" || mode === "recover"}
          <Input label="{mode === 'recover' ? 'Registered email or mobile' : 'Email, mobile, or username'}" name="{mode === 'recover' ? 'identifier' : mode === 'register' ? 'email' : 'identifier'}" type="{mode === 'register' ? 'email' : 'text'}" autocomplete="{mode === 'register' ? 'email' : 'username'}" placeholder="{mode === 'recover' ? 'Enter your registered identity' : 'Enter your identity'}" required="true" icon="icon-[lucide--at-sign]" iconPosition="start" @change="fieldEvent('change', $event)" @input="fieldEvent('input', $event)" @focus="fieldEvent('focus', $event)" @blur="fieldEvent('blur', $event)" />
        {/if}
        {#if mode === "sign-in" || mode === "register" || mode === "reset"}
          <Input label="{mode === 'reset' ? 'New password' : 'Password'}" name="password" type="password" autocomplete="{mode === 'sign-in' ? 'current-password' : 'new-password'}" placeholder="Enter your password" required="true" icon="icon-[lucide--lock-keyhole]" iconPosition="start" @change="fieldEvent('change', $event)" @input="fieldEvent('input', $event)" @focus="fieldEvent('focus', $event)" @blur="fieldEvent('blur', $event)" />
        {/if}
        {#if mode === "register" || mode === "reset"}
          <Input label="Confirm password" name="confirmPassword" type="password" autocomplete="new-password" placeholder="Enter the password again" required="true" icon="icon-[lucide--shield-check]" iconPosition="start" @change="fieldEvent('change', $event)" @input="fieldEvent('input', $event)" @focus="fieldEvent('focus', $event)" @blur="fieldEvent('blur', $event)" />
        {/if}
        {#if mode === "mfa"}
          <PinInput label="Verification code" name="code" length={6} inputMode="numeric" />
        {/if}
        {#if mode === "sign-in" && showRemember}
          <div class="wire-auth-form__options">
        <Checkbox label="Remember this device" name="rememberDevice" value="on" />
            <a href="/forgot-password">Forgot password?</a>
          </div>
        {/if}
        <Button type="submit" label="{submitLabel}" variant="default" color="{color}" size="lg" fullWidth="true" icon="icon-[lucide--arrow-right]" iconPosition="end" class="wire-auth-form__submit" />
      </form>
      <slot />
    </section>
  }
}
```

---

## AuthSplitLayout

Showcase: https://component.wrnexusjs.dev/
Mount: <AuthSplitLayout /> (legacy: data-component="AuthSplitLayout")
Category: layout
Purpose: Responsive 50/50 authentication layout with content and form regions.
Props: size: string = "default", color: string = "primary", eyebrow: string = "Secure identity", title: string = "Welcome back", description: string = "", brand: string = "Police Management System", features: string = [], class: string = ""
Slots: aside-extra, form
Events: none

### Complete .wrn source contract

```wrn
component AuthSplitLayout {
  props {
    size = "default"
    color = "primary"
    eyebrow = "Secure identity"
    title = "Welcome back"
    description = ""
    brand = "Police Management System"
    features = []
    class = ""
  }

  view {
    <main
      class="wire-auth-split wire-next--color-{color} wire-next--size-{size} {class}"
    >
      <section
        class="wire-auth-split__content"
      >
        <div
          class="wire-auth-split__brand"
        >
          <span
            class="icon-[lucide--shield-check]"
            aria-hidden="true"
          >
          </span>
          <span><strong>{brand}</strong><small>Unified identity and access</small></span>
        </div>
        <div
          class="wire-auth-split__message"
        >
          <span
            class="wire-auth-split__eyebrow"
          >
            {eyebrow}
          </span>
          <h1>{title}</h1>
          {#if description}
            <p>{description}</p>
          {/if}
          <div
            class="wire-auth-split__features"
          >
            {#each features as item}
              <article>
                <span
                  class="{item.icon || 'icon-[lucide--check-circle-2]'}"
                  aria-hidden="true"
                >
                </span>
                <span><strong>{item.label}</strong>
                  {#if item.description}
                    <small>{item.description}</small>
                  {/if}
                </span>
              </article>
            {/each}
          </div>
          <slot
            name="aside-extra"
          />
        </div>
        <small
          class="wire-auth-split__legal"
        >
          Authorised access only · Activity may be monitored and audited.
        </small>
      </section>
      <section
        class="wire-auth-split__form"
      >
        <div
          class="wire-auth-split__form-inner"
        >
          <slot
            name="form"
          />
        </div>
      </section>
    </main>
  }
}
```

---

## Avatar

Showcase: https://component.wrnexusjs.dev/
Mount: <Avatar /> (legacy: data-component="Avatar")
Category: base
Purpose: Theme-aware, responsive avatar component.
Props: src: string = "", alt: string = "", initials: string = "", size: string = "md", color: string = "primary", variant: string = "solid", shape: string = "circle", status: string = "", statusLabel: string = "", statusPosition: string = "bottom", badge: string = "", badgeIcon: string = "", badgeLabel: string = "", tooltip: string = "", name: string = "", description: string = "", loading: string = "lazy", class: string = ""
Slots: none
Events: load, error, click

### Complete .wrn source contract

```wrn
component Avatar {
  props {
    @event load = function
    @event error = function
    @event click = function
    src = ""
    alt = ""
    initials = ""
    size = "md"
    color = "primary"
    variant = "solid"
    shape = "circle"

    status = ""
    statusLabel = ""
    statusPosition = "bottom"

    badge = ""
    badgeIcon = ""
    badgeLabel = ""

    tooltip = ""
    name = ""
    description = ""
    loading = "lazy"
    class = ""
  }

  view {
    <span
      {...attrs}
      class="wire-next wire-next--avatar {description ? 'wire-next--avatar-media' : ''} {class}"
      data-wrn-avatar
    >
      <span
        class="wire-next__avatar-wrap"
        data-shape="{shape}"
        data-size="{size}"
        data-color="{color}"
        data-variant="{variant}"
        data-status-position="{statusPosition}"
        tabindex="{tooltip ? '0' : '-1'}"
        aria-label="{tooltip || name || alt || initials || 'Avatar'}"
      >
        <span class="wire-next__avatar">
          {#if src}
            <img src="{src}" alt="{alt || name}" loading="{loading}" />
          {:else if initials}
            <span class="wire-next__avatar-initials" aria-hidden="true">{initials}</span>
          {:else}
            <span class="wire-next__avatar-placeholder icon-[lucide--user-round]" aria-hidden="true"></span>
          {/if}
        </span>

        {#if status}
          <span
            class="wire-next__avatar-status"
            data-status="{status}"
            title="{statusLabel || status}"
            aria-label="{statusLabel || status}"
          ></span>
        {/if}

        {#if badgeIcon}
          <span class="wire-next__avatar-badge" aria-label="{badgeLabel || 'Linked account'}">
            <span class="{badgeIcon}" aria-hidden="true"></span>
          </span>
        {:else if badge}
          <span class="wire-next__avatar-badge wire-next__avatar-badge--text" aria-label="{badgeLabel || badge}">
            {badge}
          </span>
        {/if}

        {#if tooltip}
          <span class="wire-next__avatar-tooltip" role="tooltip">{tooltip}</span>
        {/if}
      </span>

      {#if description}
        <span class="wire-next__avatar-copy">
          <strong>{name || alt || initials}</strong>
          <span>{description}</span>
        </span>
      {/if}
    </span>
  }
}
```

---

## AvatarGroup

Showcase: https://component.wrnexusjs.dev/
Mount: <AvatarGroup /> (legacy: data-component="AvatarGroup")
Category: base
Purpose: Theme-aware, responsive avatar group component.
Props: items: string = [], size: string = "md", color: string = "primary", variant: string = "solid", shape: string = "circle", layout: string = "stack", maxVisible: number = 4, columns: number = 3, borderColor: string = "", showTooltips: boolean = true, overflowLabel: string = "Show remaining members", class: string = ""
Slots: none
Events: overflow

### Complete .wrn source contract

```wrn
component AvatarGroup {
  props {
    items = []
    size = "md"
    color = "primary"
    variant = "solid"
    shape = "circle"
    layout = "stack"
    maxVisible = 4
    columns = 3
    borderColor = ""
    showTooltips = true
    overflowLabel = "Show remaining members"
    class = ""

    @event overflow = function
  }

  state overflowOpen = false

  functions {
    function visibleMembers() {
      return items.slice(0, Number(maxVisible))
    }

    function hiddenMembers() {
      return items.slice(Number(maxVisible))
    }

    function toggleOverflow(sourceEvent, root, customEvent) {
      overflowOpen = !overflowOpen
      root = sourceEvent.currentTarget.closest("[data-wrn-avatar-group]")

      customEvent = document.createEvent("CustomEvent")
      customEvent.initCustomEvent("overflow", true, false, {
        component: "AvatarGroup",
        open: overflowOpen,
        hiddenCount: hiddenMembers().length
      })
      root.dispatchEvent(customEvent)
    }
  }

  view {
    <div
      {...attrs}
      class="wire-next wire-next--avatar-group {class}"
      data-wrn-avatar-group
      data-layout="{layout}"
      data-shape="{shape}"
      data-size="{size}"
      style="--wire-avatar-group-columns:{columns}; --wire-avatar-group-ring:{borderColor || 'var(--wire-color-bg)'}"
      role="group"
      aria-label="Avatar group"
    >
      <div
        class="wire-next__avatar-group-members"
      >
        {#each visibleMembers() as item}
          <span
            class="wire-next__avatar-group-member"
            data-size="{item.size || size}"
            data-shape="{item.shape || shape}"
            data-color="{item.color || color}"
            data-variant="{item.variant || variant}"
            tabindex="{showTooltips && (item.tooltip || item.name) ? '0' : '-1'}"
            aria-label="{item.name || item.alt || item.initials || 'Group member'}"
          >
            <span
              class="wire-next__avatar-group-avatar"
            >
              {#if item.src}
                <img
                  src="{item.src}"
                  alt="{item.alt || item.name || ''}"
                  loading="lazy"
                />
              {:else if item.initials}
                <span
                  aria-hidden="true"
                >
                  {item.initials}
                </span>
              {:else}
                <span
                  class="icon-[lucide--user-round]"
                  aria-hidden="true"
                >
                </span>
              {/if}
            </span>

            {#if showTooltips && (item.tooltip || item.name)}
              <span
                class="wire-next__avatar-group-tooltip"
                role="tooltip"
              >
                {item.tooltip || item.name}
              </span>
            {/if}
          </span>
        {/each}

        {#if hiddenMembers().length > 0}
          <span
            class="wire-next__avatar-group-overflow"
          >
            <button
              type="button"
              class="wire-next__avatar-group-overflow-button"
              aria-label="{overflowLabel}"
              aria-expanded="{overflowOpen ? 'true' : 'false'}"
              @click="toggleOverflow(event)"
            >
              +{hiddenMembers().length}
            </button>

            <span
              class="wire-next__avatar-group-menu"
              role="menu"
              data-show="overflowOpen"
              aria-hidden="{overflowOpen ? 'false' : 'true'}"
            >
              {#each hiddenMembers() as item}
                <span
                  class="wire-next__avatar-group-menu-item"
                  role="menuitem"
                >
                  <span
                    class="wire-next__avatar-group-menu-avatar"
                  >
                    {#if item.src}
                      <img
                        src="{item.src}"
                        alt=""
                        loading="lazy"
                      />
                    {:else}
                      <span>{item.initials || '?'}</span>
                    {/if}
                  </span>
                  <span>{item.name || item.alt || item.initials || 'Team member'}</span>
                </span>
              {/each}
            </span>
          </span>
        {/if}
      </div>
    </div>
  }
}
```

---

## BackToTop

Showcase: https://component.wrnexusjs.dev/
Mount: <BackToTop /> (legacy: data-component="BackToTop")
Category: navigation
Purpose: Accessible scroll-to-top control with visibility threshold.
Props: threshold: number = 500, label: string = "Back to top", ariaLabel: string = "Scroll back to top", icon: string = "icon-[lucide--arrow-up]", position: string = "right", offset: string = "md", behavior: string = "smooth", showProgress: boolean = false, size: string = "default", color: string = "primary", variant: string = "solid", class: string = ""
Slots: none
Events: none

### Complete .wrn source contract

```wrn
component BackToTop {
  props {
    threshold = 500
    label = "Back to top"
    ariaLabel = "Scroll back to top"
    icon = "icon-[lucide--arrow-up]"
    position = "right"
    offset = "md"
    behavior = "smooth"
    showProgress = false
    size = "default"
    color = "primary"
    variant = "solid"
    class = ""
  }

  state visible = false
  state progress = 0

  view {
    <button
      data-ui-component="BackToTop"
      type="button"
      aria-label='{ariaLabel}'
      title='{label}'
      data-show='visible'
      class='fixed z-50 inline-flex items-center justify-center rounded-full border border-[var(--wire-color-border)] shadow-xl backdrop-blur transition duration-200 hover:-translate-y-1 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--wire-color-focus)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--wire-color-background)] {class}'
      class:bottom-4='offset === "sm"'
      class:bottom-6='offset === "md"'
      class:bottom-8='offset === "lg"'
      class:right-4='position === "right" && offset === "sm"'
      class:right-6='position === "right" && offset === "md"'
      class:right-8='position === "right" && offset === "lg"'
      class:left-4='position === "left" && offset === "sm"'
      class:left-6='position === "left" && offset === "md"'
      class:left-8='position === "left" && offset === "lg"'
      class:left-1/2='position === "center"'
      class:-translate-x-1/2='position === "center"'
      class:size-10='size === "sm"'
      class:size-12='size === "default" || size === "md"'
      class:size-14='size === "lg"'
      class:bg-[var(--wire-color-primary)]='variant === "solid" && color === "primary"'
      class:text-[var(--wire-color-on-primary)]='variant === "solid" && color === "primary"'
      class:bg-[var(--wire-color-danger)]='variant === "solid" && color === "danger"'
      class:text-[var(--wire-color-on-danger)]='variant === "solid" && color === "danger"'
      class:bg-[var(--wire-color-surface-raised)]='variant === "outline" || variant === "soft"'
      class:text-[var(--wire-color-primary)]='variant === "outline" || variant === "soft"'
      style='--wire-back-to-top-progress: {progress}%;'
      @window:scroll='visible = window.scrollY >= threshold; progress = Math.min(100, Math.round((window.scrollY / Math.max(1, document.documentElement.scrollHeight - window.innerHeight)) * 100))'
      @click='window.scrollTo({ top: 0, behavior: behavior })'
    >
      {#if showProgress}
        <span class="wire-back-to-top-progress absolute inset-0 rounded-full" aria-hidden="true"></span>
      {/if}
      <span class='{icon + " relative z-10 size-5"}' aria-hidden="true"></span>
      <span class="sr-only">{label}</span>
    </button>
  }

  style {
    .wire-back-to-top-progress {
      background: conic-gradient(
        currentColor var(--wire-back-to-top-progress),
        transparent var(--wire-back-to-top-progress)
      );
      opacity: 0.22;
    }
  }
}
```

---

## Badge

Showcase: https://component.wrnexusjs.dev/
Mount: <Badge /> (legacy: data-component="Badge")
Category: base
Purpose: Theme-aware, responsive badge component.
Props: label: string = "Badge", size: string = "md", color: string = "primary", variant: string = "solid", shape: string = "pill", class: string = "", icon: string = "", iconPosition: string = "start", dot: boolean = false, dotOnly: boolean = false, dotLabel: string = "Status", animated: boolean = false, avatarSrc: string = "", avatarAlt: string = "", dismissible: boolean = false, dismissLabel: string = "Remove badge", truncate: boolean = false, maxWidth: string = "12rem", anchorLabel: string = "", anchorIcon: string = "", placement: string = "inline", anchorLabelText: string = "Badge anchor"
Slots: none
Events: dismiss

### Complete .wrn source contract

```wrn
component Badge {
  props {
    label = "Badge"
    size = "md"
    color = "primary"
    variant = "solid"
    shape = "pill"
    class = ""

    icon = ""
    iconPosition = "start"
    dot = false
    dotOnly = false
    dotLabel = "Status"
    animated = false

    avatarSrc = ""
    avatarAlt = ""
    dismissible = false
    dismissLabel = "Remove badge"
    truncate = false
    maxWidth = "12rem"

    anchorLabel = ""
    anchorIcon = ""
    placement = "inline"
    anchorLabelText = "Badge anchor"

    @event dismiss = function
  }

  state visible = true

  functions {
    function dismissBadge(sourceEvent, root, customEvent) {
      visible = false
      root = sourceEvent.currentTarget.closest("[data-wrn-badge]")
      customEvent = document.createEvent("CustomEvent")
      customEvent.initCustomEvent("dismiss", true, false, {
        component: "Badge",
        label: label
      })
      root.dispatchEvent(customEvent)
    }
  }

  view {
    <span
      {...attrs}
      class="wire-next wire-next--badge-root {anchorLabel || anchorIcon ? 'wire-next--badge-anchored' : ''} {class}"
      data-wrn-badge
      data-placement="{placement}"
      data-show="visible"
      aria-hidden="{visible ? 'false' : 'true'}"
    >
      {#if anchorLabel || anchorIcon}
        <button type="button" class="wire-next__badge-anchor" aria-label="{anchorLabelText}">
          {#if anchorIcon}<span class="{anchorIcon}" aria-hidden="true"></span>{/if}
          {#if anchorLabel}<span>{anchorLabel}</span>{/if}
        </button>
      {/if}

      <span
        class="wire-next__badge"
        data-size="{size}"
        data-color="{color}"
        data-variant="{variant}"
        data-shape="{shape}"
        data-animated="{animated ? 'true' : 'false'}"
        style="--wire-badge-max-width:{maxWidth}"
        role="{dotOnly ? 'status' : ''}"
        aria-label="{dotOnly ? dotLabel : ''}"
      >
        {#if animated}
          <span class="wire-next__badge-ping" aria-hidden="true"></span>
        {/if}
        {#if avatarSrc}
          <img class="wire-next__badge-avatar" src="{avatarSrc}" alt="{avatarAlt}" loading="lazy" />
        {/if}
        {#if dot || dotOnly}
          <span class="wire-next__badge-dot" aria-hidden="true"></span>
        {/if}
        {#if icon && iconPosition === "start"}
          <span class="wire-next__badge-icon {icon}" aria-hidden="true"></span>
        {/if}
        {#if !dotOnly}
          <span class="wire-next__badge-label {truncate ? 'wire-next__badge-label--truncate' : ''}">
            {label}
          </span>
        {/if}
        {#if icon && iconPosition === "end"}
          <span class="wire-next__badge-icon {icon}" aria-hidden="true"></span>
        {/if}
        {#if dismissible}
          <button type="button" class="wire-next__badge-dismiss" aria-label="{dismissLabel}" @click="dismissBadge(event)">
            <span class="icon-[lucide--x]" aria-hidden="true"></span>
          </button>
        {/if}
      </span>
    </span>
  }
}
```

---

## Blockquote

Showcase: https://component.wrnexusjs.dev/
Mount: <Blockquote /> (legacy: data-component="Blockquote")
Category: base
Purpose: Theme-aware, responsive blockquote component.
Props: quote: string = "I just wanted to say that I'm very happy with my purchase so far. The documentation is outstanding - clear and detailed.", citation: string = "", citationTitle: string = "", citationUrl: string = "", avatarSrc: string = "", avatarAlt: string = "", size: string = "md", color: string = "primary", align: string = "left", variant: string = "default", quoteMark: boolean = true, italic: boolean = true, class: string = ""
Slots: default
Events: none

### Complete .wrn source contract

```wrn
component Blockquote {
  props {
    quote = "I just wanted to say that I'm very happy with my purchase so far. The documentation is outstanding - clear and detailed."
    citation = ""
    citationTitle = ""
    citationUrl = ""
    avatarSrc = ""
    avatarAlt = ""
    size = "md"
    color = "primary"
    align = "left"
    variant = "default"
    quoteMark = true
    italic = true
    class = ""
  }

  view {
    <figure
      {...attrs}
      class="wire-next wire-next--blockquote wire-next--color-{color} wire-next--size-{size} {class}"
      data-size="{size}"
      data-color="{color}"
      data-align="{align}"
      data-variant="{variant}"
      data-italic="{italic}"
    >
      <blockquote cite="{citationUrl}">
        {#if quoteMark}
          <span class="wire-next__blockquote-mark" aria-hidden="true">“</span>
        {/if}

        <div class="wire-next__blockquote-copy">
          {#if quote}
            <p>{quote}</p>
          {:else}
            <slot />
          {/if}
        </div>
      </blockquote>

      {#if citation || citationTitle || avatarSrc}
        <figcaption class="wire-next__blockquote-citation">
          {#if avatarSrc}
            <img
              class="wire-next__blockquote-avatar"
              src="{avatarSrc}"
              alt="{avatarAlt}"
              loading="lazy"
            />
          {/if}

          <span class="wire-next__blockquote-attribution">
            {#if citation}
              {#if citationUrl}
                <cite><a href="{citationUrl}">{citation}</a></cite>
              {:else}
                <cite>{citation}</cite>
              {/if}
            {/if}
            {#if citationTitle}<span>{citationTitle}</span>{/if}
          </span>
        </figcaption>
      {/if}
    </figure>
  }
}
```

---

## Breadcrumb

Showcase: https://component.wrnexusjs.dev/
Mount: <Breadcrumb /> (legacy: data-component="Breadcrumb")
Category: navigation
Purpose: Theme-aware, responsive breadcrumb component.
Props: size: string = "default", color: string = "primary", label: string = "Breadcrumb", items: string = [], active: string = "", orientation: string = "horizontal", class: string = ""
Slots: default
Events: navigate, click

### Complete .wrn source contract

```wrn
component Breadcrumb {
  props {
    @event navigate = function
    @event click = function
    size = "default"
    color = "primary"
    label = "Breadcrumb"
    items = []
    active = ""
    orientation = "horizontal"
    class = ""
  }
  view {
    <nav class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--breadcrumb wire-next--{orientation} {class}" aria-label="{label}">
      {#each items as item}<a href="{item.href}" aria-current="{item.value === active ? 'page' : ''}">{item.label}</a>{/each}
      <slot />
    </nav>
  }
}
```

---

## Button

Showcase: https://component.wrnexusjs.dev/
Mount: <Button /> (legacy: data-component="Button")
Category: base
Purpose: Theme-aware, responsive button component.
Props: label: string = "Button", loadingLabel: string = "Loading…", description: string = "", as: string = "", href: string = "", target: string = "", rel: string = "", type: string = "button", variant: string = "default", color: string = "primary", size: string = "default", disabled: boolean = false, loading: boolean = false, pill: boolean = false, fullWidth: boolean = false, icon: string = "", iconPosition: string = "start", ariaLabel: string = "", ariaPressed: string = "", ariaExpanded: string = "", ariaControls: string = "", title: string = "", autofocus: boolean = false, controlClass: string = "", class: string = ""
Slots: default
Events: click, focus, blur

### Complete .wrn source contract

```wrn
component Button {
  props {
    @event click = function
    @event focus = function
    @event blur = function
    label = "Button"
    loadingLabel = "Loading…"
    description = ""
    as = ""
    href = ""
    target = ""
    rel = ""
    type = "button"
    variant = "default"
    color = "primary"
    size = "default"
    disabled = false
    loading = false
    pill = false
    fullWidth = false
    icon = ""
    iconPosition = "start"
    ariaLabel = ""
    ariaPressed = ""
    ariaExpanded = ""
    ariaControls = ""
    title = ""
    autofocus = false
    controlClass = ""
    class = ""
  }

  view {
    <span
      class="wire-action {fullWidth ? 'w-full' : ''} {class}"
    >
      {#if as === "a" || (as === "" && href)}
        <a
          {...attrs}
          href="{disabled || loading ? '' : href}"
          target="{target}"
          rel="{rel}"
          title="{title}"
          aria-label="{ariaLabel || ((size === 'icon' || size === 'icon-xs' || size === 'icon-sm' || size === 'icon-lg') ? label : '')}"
          aria-disabled="{disabled || loading}"
          aria-busy="{loading}"
          aria-pressed="{ariaPressed}"
          aria-expanded="{ariaExpanded}"
          aria-controls="{ariaControls}"
          tabindex="{disabled || loading ? '-1' : '0'}"
          class="wire-btn wire-btn--variant-{variant} wire-btn--color-{color} wire-btn--size-{size} {pill ? 'wire-btn--pill' : ''} {description ? 'wire-btn--with-description' : ''} {fullWidth ? 'w-full' : ''} {controlClass}"
        >
          {#if loading}
            <span
              class="wire-spinner wire-spinner--inline"
              aria-hidden="true"
            >
            </span>
          {/if}
          {#if icon && !loading && iconPosition === "start"}
            <span
              class="wire-btn__icon {icon}"
              aria-hidden="true"
            >
            </span>
          {/if}
          <span
            class="wire-btn__copy {(size === 'icon' || size === 'icon-xs' || size === 'icon-sm' || size === 'icon-lg') ? 'wire-visually-hidden' : ''}"
          >
            <span
              class="wire-btn__label"
            >
              <slot>{loading ? loadingLabel : label}</slot>
            </span>
            {#if description && !loading}
              <span
                class="wire-btn__description"
              >
                {description}
              </span>
            {/if}
          </span>
          {#if icon && !loading && iconPosition === "end"}
            <span
              class="wire-btn__icon {icon}"
              aria-hidden="true"
            >
            </span>
          {/if}
          {#if (size === "icon" || size === "icon-xs" || size === "icon-sm" || size === "icon-lg") && (ariaLabel || label)}
            <span
              class="wire-btn__tooltip"
              role="tooltip"
              aria-hidden="true"
            >
              {ariaLabel || label}
            </span>
          {/if}
        </a>
      {:else}
        <button
          {...attrs}
          type="{type}"
          title="{title}"
          autofocus="{autofocus}"
          disabled="{disabled || loading}"
          aria-label="{ariaLabel || ((size === 'icon' || size === 'icon-xs' || size === 'icon-sm' || size === 'icon-lg') ? label : '')}"
          aria-busy="{loading}"
          aria-pressed="{ariaPressed}"
          aria-expanded="{ariaExpanded}"
          aria-controls="{ariaControls}"
          class="wire-btn wire-btn--variant-{variant} wire-btn--color-{color} wire-btn--size-{size} {pill ? 'wire-btn--pill' : ''} {description ? 'wire-btn--with-description' : ''} {fullWidth ? 'w-full' : ''} {controlClass}"
        >
          {#if loading}
            <span
              class="wire-spinner wire-spinner--inline"
              aria-hidden="true"
            >
            </span>
          {/if}
          {#if icon && !loading && iconPosition === "start"}
            <span
              class="wire-btn__icon {icon}"
              aria-hidden="true"
            >
            </span>
          {/if}
          <span
            class="wire-btn__copy {(size === 'icon' || size === 'icon-xs' || size === 'icon-sm' || size === 'icon-lg') ? 'wire-visually-hidden' : ''}"
          >
            <span
              class="wire-btn__label"
            >
              <slot>{loading ? loadingLabel : label}</slot>
            </span>
            {#if description && !loading}
              <span
                class="wire-btn__description"
              >
                {description}
              </span>
            {/if}
          </span>
          {#if icon && !loading && iconPosition === "end"}
            <span
              class="wire-btn__icon {icon}"
              aria-hidden="true"
            >
            </span>
          {/if}
          {#if (size === "icon" || size === "icon-xs" || size === "icon-sm" || size === "icon-lg") && (ariaLabel || label)}
            <span
              class="wire-btn__tooltip"
              role="tooltip"
              aria-hidden="true"
            >
              {ariaLabel || label}
            </span>
          {/if}
        </button>
      {/if}
    </span>
  }
}
```

---

## ButtonGroup

Showcase: https://component.wrnexusjs.dev/
Mount: <ButtonGroup /> (legacy: data-component="ButtonGroup")
Category: base
Purpose: Theme-aware, responsive button group component.
Props: items: string = [], value: string = "", size: string = "md", color: string = "primary", variant: string = "default", orientation: string = "horizontal", responsive: boolean = false, attached: boolean = true, selectable: boolean = false, toolbar: boolean = false, disabled: boolean = false, ariaLabel: string = "Button group", class: string = ""
Slots: default
Events: click, select, change

### Complete .wrn source contract

```wrn
component ButtonGroup {
  props {
    @event click = function
    @event select = function
    @event change = function
    items = []
    value = ""
    size = "md"
    color = "primary"
    variant = "default"
    orientation = "horizontal"
    responsive = false
    attached = true
    selectable = false
    toolbar = false
    disabled = false
    ariaLabel = "Button group"
    class = ""
  }

  state selectedValue = value

  functions {
    function itemValue(item, index) {
      return item.value || item.label || String(index)
    }

    function selectItem(item, index) {
      previousValue = selectedValue
      nextValue = itemValue(item, index)

      $emit("select", {
        value: nextValue,
        previousValue: previousValue,
        item: item,
        index: index
      })

      if (selectable && previousValue !== nextValue) {
        selectedValue = nextValue
        $emit("change", {
          value: nextValue,
          previousValue: previousValue,
          item: item,
          index: index
        })
      }
    }
  }

  view {
    <div
      {...attrs}
      class="wire-next wire-next--button-group {class}"
      role="{toolbar ? 'toolbar' : 'group'}"
      aria-label="{ariaLabel}"
      aria-orientation="{orientation}"
      data-size="{size}"
      data-color="{color}"
      data-variant="{variant}"
      data-orientation="{orientation}"
      data-responsive="{responsive}"
      data-attached="{attached}"
      data-selectable="{selectable}"
      data-disabled="{disabled}"
    >
      {#if items}
        {#each items as item, index}
          <button
            type="{item.type || 'button'}"
            class="wire-btn wire-btn--variant-{item.variant || variant} wire-btn--color-{item.color || color} wire-btn--size-{item.size || size}"
            disabled="{disabled || item.disabled}"
            aria-label="{item.ariaLabel || item.label}"
            aria-pressed="{selectable ? (selectedValue === (item.value || item.label || String(index)) ? 'true' : 'false') : ''}"
            data-value="{item.value || item.label || String(index)}"
            data-selected="{selectable && selectedValue === (item.value || item.label || String(index)) ? 'true' : 'false'}"
            @click="selectItem(item, index)"
          >
            {#if item.icon}
              <span class="wire-btn__icon {item.icon}" aria-hidden="true"></span>
            {/if}
            <span class="wire-btn__label">{item.label}</span>
          </button>
        {/each}
      {/if}
      <slot />
    </div>
  }
}
```

---

## Card

Showcase: https://component.wrnexusjs.dev/
Mount: <Card /> (legacy: data-component="Card")
Category: base
Purpose: Theme-aware, responsive card component.
Props: title: string = "Card title", subtitle: string = "", description: string = "", header: string = "", footer: string = "", imageSrc: string = "", imageAlt: string = "", imagePosition: string = "top", actionLabel: string = "", actionHref: string = "", headerActions: string = [], navigation: string = [], activeNav: string = "", mobileNavigation: boolean = false, alertTitle: string = "", alertDescription: string = "", empty: boolean = false, emptyTitle: string = "No data to show", emptyIcon: string = "icon-[lucide--inbox]", items: string = [], size: string = "md", color: string = "primary", variant: string = "default", layout: string = "vertical", align: string = "left", hover: string = "none", scrollable: boolean = false, maxHeight: string = "18rem", dismissible: boolean = false, ariaLabel: string = "", class: string = ""
Slots: default
Events: click, action, navigate, dismiss, load, error

### Complete .wrn source contract

```wrn
component Card {
  props {
    @event click = function
    @event action = function
    @event navigate = function
    @event dismiss = function
    @event load = function
    @event error = function
    title = "Card title"
    subtitle = ""
    description = ""
    header = ""
    footer = ""
    imageSrc = ""
    imageAlt = ""
    imagePosition = "top"
    actionLabel = ""
    actionHref = ""
    headerActions = []
    navigation = []
    activeNav = ""
    mobileNavigation = false
    alertTitle = ""
    alertDescription = ""
    empty = false
    emptyTitle = "No data to show"
    emptyIcon = "icon-[lucide--inbox]"
    items = []
    size = "md"
    color = "primary"
    variant = "default"
    layout = "vertical"
    align = "left"
    hover = "none"
    scrollable = false
    maxHeight = "18rem"
    dismissible = false
    ariaLabel = ""
    class = ""
  }

  state dismissed = false

  functions {
    function dispatchCardNavigation(sourceEvent, item, index, root, customEvent) {
      root = sourceEvent.currentTarget.closest("[data-wrn-card]")

      if (!root) {
        return
      }

      customEvent = document.createEvent("CustomEvent")
      customEvent.initCustomEvent("navigate", true, false, {
        component: "Card",
        item: item,
        index: index
      })
      root.dispatchEvent(customEvent)
    }

    function dispatchCardNavigationValue(sourceEvent, root, customEvent) {
      root = sourceEvent.currentTarget.closest("[data-wrn-card]")

      if (!root) {
        return
      }

      customEvent = document.createEvent("CustomEvent")
      customEvent.initCustomEvent("navigate", true, false, {
        component: "Card",
        value: sourceEvent.currentTarget.value
      })
      root.dispatchEvent(customEvent)
    }

    function dispatchCardHeaderAction(sourceEvent, action, index, root, customEvent) {
      root = sourceEvent.currentTarget.closest("[data-wrn-card]")

      if (!root) {
        return
      }

      customEvent = document.createEvent("CustomEvent")
      customEvent.initCustomEvent("action", true, false, {
        component: "Card",
        action: action,
        index: index
      })
      root.dispatchEvent(customEvent)
    }

    function dismissCard(sourceEvent, root, customEvent) {
      dismissed = true
      root = sourceEvent.currentTarget.closest("[data-wrn-card]")

      if (!root) {
        return
      }

      customEvent = document.createEvent("CustomEvent")
      customEvent.initCustomEvent("dismiss", true, false, {
        component: "Card",
        title: title
      })
      root.dispatchEvent(customEvent)
    }
  }

  view {
    <div
      {...attrs}
      data-ui-component="Card"
      data-wrn-card
      data-size='{size}'
      data-color='{color}'
      data-variant='{variant}'
      data-layout='{layout}'
      data-hover='{hover}'
      data-align='{align}'
      class='wire-next wire-next--card wire-next--color-{color} wire-next--size-{size} wire-next--variant-{variant} {class}'
    >
      {#if items.length > 0}
        <div class="wire-next__card-group">
          {#each items as item, itemIndex}
            <article
              class="wire-next__card-panel"
              aria-label='{item.ariaLabel || item.title || item.label || "Card item"}'
              data-index='{itemIndex}'
            >
              {#if item.imageSrc || item.image}
                <div class="wire-next__card-media">
                  <img
                    src='{item.imageSrc || item.image}'
                    alt='{item.imageAlt || item.alt || ""}'
                    loading='{item.loading || "lazy"}'
                    decoding="async"
                    @load='event.currentTarget.dispatchEvent(new CustomEvent("load", { bubbles: true, detail: { item: item, index: itemIndex } }))'
                    @error='event.currentTarget.dispatchEvent(new CustomEvent("error", { bubbles: true, detail: { item: item, index: itemIndex } }))'
                  />
                </div>
              {/if}

              <div class="wire-next__card-content">
                {#if item.title || item.label}
                  <h3>{item.title || item.label}</h3>
                {/if}
                {#if item.subtitle}
                  <p class="wire-next__card-subtitle">{item.subtitle}</p>
                {/if}
                {#if item.description}
                  <p class="wire-next__card-description">{item.description}</p>
                {/if}
                {#if item.actionLabel || item.href}
                  <a
                    href='{item.actionHref || item.href || "#"}'
                    class="wire-next__card-action"
                    @click='event.currentTarget.dispatchEvent(new CustomEvent("action", { bubbles: true, detail: { item: item, index: itemIndex } }))'
                  >
                    <span>{item.actionLabel || "Learn more"}</span>
                    <span class="icon-[lucide--arrow-right]" aria-hidden="true"></span>
                  </a>
                {/if}
              </div>
            </article>
          {/each}
        </div>
      {:else}
        <article
          class="wire-next__card-panel"
          aria-label='{ariaLabel || title || "Card"}'
          hidden='{dismissed}'
        >
          {#if imageSrc && imagePosition === "overlay"}
            <div class="wire-next__card-overlay">
              <img
                src='{imageSrc}'
                alt='{imageAlt}'
                loading="lazy"
                decoding="async"
                @load='event.currentTarget.dispatchEvent(new CustomEvent("load", { bubbles: true, detail: { src: imageSrc } }))'
                @error='event.currentTarget.dispatchEvent(new CustomEvent("error", { bubbles: true, detail: { src: imageSrc } }))'
              />
              <div class="wire-next__card-overlay-shade" aria-hidden="true"></div>
            </div>
          {/if}

          {#if imageSrc && (imagePosition === "top" || imagePosition === "left")}
            <div class="wire-next__card-media wire-next__card-media--{imagePosition}">
              <img
                src='{imageSrc}'
                alt='{imageAlt}'
                loading="lazy"
                decoding="async"
                @load='event.currentTarget.dispatchEvent(new CustomEvent("load", { bubbles: true, detail: { src: imageSrc } }))'
                @error='event.currentTarget.dispatchEvent(new CustomEvent("error", { bubbles: true, detail: { src: imageSrc } }))'
              />
            </div>
          {/if}

          <div class="wire-next__card-content">
            {#if header || title || subtitle || headerActions.length > 0 || dismissible}
              <header class="wire-next__card-header">
                <div class="wire-next__card-heading">
                  {#if header}
                    <p class="wire-next__card-eyebrow">{header}</p>
                  {/if}
                  {#if title}
                    <h3>{title}</h3>
                  {/if}
                  {#if subtitle}
                    <p class="wire-next__card-subtitle">{subtitle}</p>
                  {/if}
                </div>

                {#if headerActions.length > 0 || dismissible}
                  <div class="wire-next__card-header-actions">
                    {#each headerActions as headerAction, actionIndex}
                      <button
                        type="button"
                        aria-label='{headerAction.ariaLabel || headerAction.label || "Card action"}'
                        @click='dispatchCardHeaderAction(event, headerAction, actionIndex)'
                      >
                        {#if headerAction.icon}
                          <span class='{headerAction.icon}' aria-hidden="true"></span>
                        {/if}
                        {#if headerAction.label && !headerAction.icon}
                          <span>{headerAction.label}</span>
                        {/if}
                      </button>
                    {/each}

                    {#if dismissible}
                      <button
                        type="button"
                        aria-label="Dismiss card"
                        @click='dismissCard(event)'
                      >
                        <span class="icon-[lucide--x]" aria-hidden="true"></span>
                      </button>
                    {/if}
                  </div>
                {/if}
              </header>
            {/if}

            {#if navigation.length > 0}
              <nav aria-label='{ariaLabel || title || "Card navigation"}' class="wire-next__card-navigation">
                {#if mobileNavigation}
                  <select
                    class="wire-next__card-navigation-select"
                    aria-label='{ariaLabel || title || "Card navigation"}'
                    @change='dispatchCardNavigationValue(event)'
                  >
                    {#each navigation as navItem}
                      <option
                        value='{navItem.value || navItem.href || navItem.label}'
                        selected='{activeNav === navItem.value || activeNav === navItem.href}'
                      >
                        {navItem.label}
                      </option>
                    {/each}
                  </select>
                {/if}

                <div class="wire-next__card-tabs" data-mobile-navigation='{mobileNavigation}'>
                  {#each navigation as navItem, navIndex}
                    <button
                      type="button"
                      aria-pressed='{activeNav === navItem.value || activeNav === navItem.href}'
                      @click='dispatchCardNavigation(event, navItem, navIndex)'
                    >
                      {#if navItem.icon}
                        <span class='{navItem.icon}' aria-hidden="true"></span>
                      {/if}
                      <span>{navItem.label}</span>
                      {#if navItem.badge}
                        <span class="wire-next__card-tab-badge">{navItem.badge}</span>
                      {/if}
                    </button>
                  {/each}
                </div>
              </nav>
            {/if}

            {#if alertTitle || alertDescription}
              <div class="wire-next__card-alert" role="status">
                {#if alertTitle}
                  <strong>{alertTitle}</strong>
                {/if}
                {#if alertDescription}
                  <p>{alertDescription}</p>
                {/if}
              </div>
            {/if}

            <div
              class="wire-next__card-body"
              data-scrollable='{scrollable}'
              style='max-height: {scrollable ? maxHeight : "none"};'
            >
              {#if empty}
                <div class="wire-next__card-empty">
                  <span class='{emptyIcon}' aria-hidden="true"></span>
                  <p>{emptyTitle}</p>
                </div>
              {:else}
                {#if description}
                  <p class="wire-next__card-description">{description}</p>
                {/if}
                <slot></slot>
              {/if}
            </div>

            {#if footer || actionLabel}
              <footer class="wire-next__card-footer">
                {#if footer}
                  <span>{footer}</span>
                {/if}
                {#if actionLabel}
                  <a
                    href='{actionHref || "#"}'
                    class="wire-next__card-action"
                    @click='event.currentTarget.dispatchEvent(new CustomEvent("action", { bubbles: true, detail: { href: actionHref, label: actionLabel } }))'
                  >
                    <span>{actionLabel}</span>
                    <span class="icon-[lucide--arrow-right]" aria-hidden="true"></span>
                  </a>
                {/if}
              </footer>
            {/if}
          </div>

          {#if imageSrc && (imagePosition === "bottom" || imagePosition === "right")}
            <div class="wire-next__card-media wire-next__card-media--{imagePosition}">
              <img
                src='{imageSrc}'
                alt='{imageAlt}'
                loading="lazy"
                decoding="async"
                @load='event.currentTarget.dispatchEvent(new CustomEvent("load", { bubbles: true, detail: { src: imageSrc } }))'
                @error='event.currentTarget.dispatchEvent(new CustomEvent("error", { bubbles: true, detail: { src: imageSrc } }))'
              />
            </div>
          {/if}
        </article>
      {/if}
    </div>
  }
}
```

---

## Carousel

Showcase: https://component.wrnexusjs.dev/
Mount: <Carousel /> (legacy: data-component="Carousel")
Category: base
Purpose: Theme-aware, responsive carousel component.
Props: size: string = "default", color: string = "primary", title: string = "", description: string = "", items: string = [], activeIndex: number = 0, slidesPerView: number = 1, gap: string = "0.75rem", showPagination: boolean = false, isAutoPlay: boolean = false, autoplayInterval: number = 4000, isInfiniteLoop: boolean = false, isRTL: boolean = false, isCentered: boolean = false, isDraggable: boolean = false, isAutoHeight: boolean = false, isSnap: boolean = false, showCounter: boolean = false, thumbnails: string = "none", ariaLabel: string = "Content carousel", variant: string = "default", class: string = ""
Slots: default
Events: initialize, change, previous, next, play, pause, reachStart, reachEnd, dragStart, dragEnd

### Complete .wrn source contract

```wrn
// Interactive, hydration-safe content carousel.
component Carousel {
  props {
    @event initialize = function
    @event change = function
    @event previous = function
    @event next = function
    @event play = function
    @event pause = function
    @event reachStart = function
    @event reachEnd = function
    @event dragStart = function
    @event dragEnd = function
    size = "default"
    color = "primary"
    title = ""
    description = ""
    items = []
    activeIndex = 0
    slidesPerView = 1
    gap = "0.75rem"
    showPagination = false
    isAutoPlay = false
    autoplayInterval = 4000
    isInfiniteLoop = false
    isRTL = false
    isCentered = false
    isDraggable = false
    isAutoHeight = false
    isSnap = false
    showCounter = false
    thumbnails = "none"
    ariaLabel = "Content carousel"
    variant = "default"
    class = ""
  }

  state currentIndex = activeIndex
  state playing = false
  state dragOrigin = null
  state dragOffset = 0
  state autoplayTimer = null
  state carouselRoot = null

  functions {
    function slideCount() {
      return items.length
    }

    function maximumIndex(count, visible) {
      count = slideCount()
      visible = Math.max(1, Number(slidesPerView) || 1)
      if (isCentered || isSnap) {
        return Math.max(0, count - 1)
      }
      return Math.max(0, count - visible)
    }

    function normalizedIndex(index, maximum) {
      maximum = maximumIndex()
      if (slideCount() === 0) {
        return 0
      }
      if (isInfiniteLoop) {
        if (index < 0) {
          return maximum
        }
        if (index > maximum) {
          return 0
        }
      }
      return Math.max(0, Math.min(index, maximum))
    }

    function rememberRoot(sourceEvent, root) {
      if (!sourceEvent || !sourceEvent.currentTarget) {
        return
      }
      root = sourceEvent.currentTarget.closest(".wire-next--carousel")
      if (root) {
        carouselRoot = root
      }
    }

    function syncNavigation(sourceEvent, index, root, viewport, slides, slide, thumbnails, thumbnail, rail) {
      rememberRoot(sourceEvent)
      root = carouselRoot
      if (!root) {
        return
      }
      if (isSnap) {
        viewport = root.querySelector(".wire-next__carousel-viewport")
        slides = root.querySelectorAll(".wire-next__carousel-slide")
        slide = slides[index]
        if (viewport && slide) {
          viewport.scrollTo({
            left: slide.offsetLeft - (viewport.clientWidth - slide.clientWidth) / 2,
            behavior: "smooth"
          })
        }
      }
      thumbnails = root.querySelectorAll(".wire-next__carousel-thumbnails button")
      if (thumbnails[index]) {
        thumbnail = thumbnails[index]
        rail = thumbnail.parentElement
        rail.scrollTo({
          left: thumbnail.offsetLeft - (rail.clientWidth - thumbnail.clientWidth) / 2,
          top: thumbnail.offsetTop - (rail.clientHeight - thumbnail.clientHeight) / 2,
          behavior: "smooth"
        })
      }
    }

    function handleSnapScroll(sourceEvent, slides, viewport, viewportCenter, closestIndex, closestDistance, slide, slideCenter, distance, previousIndex) {
      if (!isSnap) {
        return
      }
      rememberRoot(sourceEvent)
      viewport = sourceEvent.currentTarget
      slides = viewport.querySelectorAll(".wire-next__carousel-slide")
      viewportCenter = viewport.scrollLeft + viewport.clientWidth / 2
      closestIndex = currentIndex
      closestDistance = 1000000000
      slides.forEach(function (candidate, index) {
        slideCenter = candidate.offsetLeft + candidate.clientWidth / 2
        distance = Math.abs(slideCenter - viewportCenter)
        if (distance < closestDistance) {
          closestDistance = distance
          closestIndex = index
        }
      })
      closestIndex = normalizedIndex(closestIndex)
      if (closestIndex !== currentIndex) {
        previousIndex = currentIndex
        currentIndex = closestIndex
        $emit("change", {
          index: currentIndex,
          previousIndex: previousIndex,
          item: items[currentIndex],
          reason: "snap"
        })
        slides = carouselRoot.querySelectorAll(".wire-next__carousel-thumbnails button")
        slide = slides[currentIndex]
        if (slide) {
          viewport = slide.parentElement
          viewport.scrollTo({
            left: slide.offsetLeft - (viewport.clientWidth - slide.clientWidth) / 2,
            top: slide.offsetTop - (viewport.clientHeight - slide.clientHeight) / 2,
            behavior: "smooth"
          })
        }
      }
    }

    function selectSlide(index, reason, sourceEvent, previousIndex) {
      if (slideCount() === 0) {
        return
      }
      previousIndex = currentIndex
      currentIndex = normalizedIndex(Number(index))
      syncNavigation(sourceEvent, currentIndex)
      if (previousIndex === currentIndex && reason !== "initialize") {
        return
      }
      $emit("change", {
        index: currentIndex,
        previousIndex: previousIndex,
        item: items[currentIndex],
        reason: reason || "select"
      })
      if (currentIndex === 0) {
        $emit("reachStart", { index: currentIndex })
      }
      if (currentIndex === maximumIndex()) {
        $emit("reachEnd", { index: currentIndex })
      }
    }

    function previousSlide(sourceEvent, previousIndex) {
      previousIndex = currentIndex
      selectSlide(currentIndex - 1, "previous", sourceEvent)
      $emit("previous", {
        index: currentIndex,
        previousIndex: previousIndex,
        item: items[currentIndex]
      })
    }

    function nextSlide(sourceEvent, previousIndex) {
      previousIndex = currentIndex
      selectSlide(currentIndex + 1, "next", sourceEvent)
      $emit("next", {
        index: currentIndex,
        previousIndex: previousIndex,
        item: items[currentIndex]
      })
    }

    function handleKeydown(sourceEvent) {
      if (sourceEvent.key === "ArrowLeft") {
        sourceEvent.preventDefault()
        if (isRTL) {
          nextSlide(sourceEvent)
        } else {
          previousSlide(sourceEvent)
        }
      }
      if (sourceEvent.key === "ArrowRight") {
        sourceEvent.preventDefault()
        if (isRTL) {
          previousSlide(sourceEvent)
        } else {
          nextSlide(sourceEvent)
        }
      }
      if (sourceEvent.key === "Home") {
        sourceEvent.preventDefault()
        selectSlide(0, "keyboard", sourceEvent)
      }
      if (sourceEvent.key === "End") {
        sourceEvent.preventDefault()
        selectSlide(maximumIndex(), "keyboard", sourceEvent)
      }
    }

    function beginDrag(sourceEvent) {
      if (!isDraggable || isSnap) {
        return
      }
      sourceEvent.preventDefault()
      dragOrigin = sourceEvent.clientX
      dragOffset = 0
      sourceEvent.currentTarget.setPointerCapture(sourceEvent.pointerId)
      $emit("dragStart", { index: currentIndex, x: dragOrigin })
    }

    function moveDrag(sourceEvent) {
      if (!isDraggable || isSnap || dragOrigin === null) {
        return
      }
      sourceEvent.preventDefault()
      dragOffset = sourceEvent.clientX - dragOrigin
    }

    function cancelDrag() {
      dragOrigin = null
      dragOffset = 0
    }

    function endDrag(sourceEvent, distance) {
      if (!isDraggable || isSnap || dragOrigin === null) {
        return
      }
      sourceEvent.preventDefault()
      distance = dragOffset || sourceEvent.clientX - dragOrigin
      dragOrigin = null
      dragOffset = 0
      if (Math.abs(distance) > 20) {
        if ((distance < 0 && !isRTL) || (distance > 0 && isRTL)) {
          nextSlide(sourceEvent)
        } else {
          previousSlide(sourceEvent)
        }
      }
      $emit("dragEnd", {
        index: currentIndex,
        distance: distance
      })
    }

    function advanceAutoplay() {
      if (currentIndex >= maximumIndex()) {
        selectSlide(0, "autoplay")
      } else {
        selectSlide(currentIndex + 1, "autoplay")
      }
    }

    function startAutoplay() {
      if (!isAutoPlay || playing || slideCount() < 2) {
        return
      }
      playing = true
      autoplayTimer = setInterval(advanceAutoplay, Math.max(1000, Number(autoplayInterval)))
      $emit("play", { index: currentIndex, interval: autoplayInterval })
    }

    function pauseAutoplay() {
      if (autoplayTimer) {
        clearInterval(autoplayTimer)
      }
      autoplayTimer = null
      if (playing) {
        $emit("pause", { index: currentIndex })
      }
      playing = false
    }

  }

  lifecycle {
    mount {
      $emit("initialize", { index: currentIndex, count: slideCount() })
      startAutoplay()
    }
    unmount {
      if (autoplayTimer) {
        clearInterval(autoplayTimer)
      }
    }
  }

  view {
    <section
      {...attrs}
      class="wire-next wire-next--carousel wire-next--color-{color} wire-next--size-{size} wire-next--variant-{variant} {class}"
      data-rtl="{isRTL}"
      data-centered="{isCentered}"
      data-draggable="{isDraggable && !isSnap}"
      data-dragging="{dragOrigin !== null}"
      data-auto-height="{isAutoHeight}"
      data-snap="{isSnap}"
      data-thumbnails="{thumbnails}"
      dir="{isRTL ? 'rtl' : 'ltr'}"
      role="region"
      aria-roledescription="carousel"
      aria-label="{ariaLabel}"
      @keydown="handleKeydown(event)"
      @mouseenter="rememberRoot(event); pauseAutoplay()"
      @mouseleave="startAutoplay()"
      @focusin="rememberRoot(event); pauseAutoplay()"
      @focusout="startAutoplay()"
    >
      {#if title || description}
        <header class="wire-next__carousel-header">
          {#if title}<h3>{title}</h3>{/if}
          {#if description}<p>{description}</p>{/if}
        </header>
      {/if}

        <div class="wire-next__carousel-layout">
          {#if thumbnails === "vertical"}
            <div class="wire-next__carousel-thumbnails" aria-label="Choose a slide">
              {#each items as item, index}
                <button
                  type="button"
                  data-active="{index === currentIndex}"
                  aria-label="Show slide {index + 1}: {item.label || item.title}"
                  aria-current="{index === currentIndex ? 'true' : 'false'}"
                  @click="selectSlide(index, 'thumbnail', event)"
                >
                  {#if item.thumbnail}<img src="{item.thumbnail}" alt="" />{/if}
                  <span>{item.label || item.title || "Slide " + (index + 1)}</span>
                </button>
              {/each}
            </div>
          {/if}

          <div class="wire-next__carousel-main">
            <div class="wire-next__carousel-stage">
              <div
                class="wire-next__carousel-viewport"
                tabindex="0"
                @scroll="handleSnapScroll(event)"
                @pointerdown="beginDrag(event)"
                @pointermove="moveDrag(event)"
                @pointerup="endDrag(event)"
                @pointercancel="cancelDrag()"
                @lostpointercapture="cancelDrag()"
              >
                <div
                  class="wire-next__carousel-track"
                  style="--wire-carousel-index: {currentIndex}; --wire-carousel-per-view: {slidesPerView}; --wire-carousel-gap: {gap}; --wire-carousel-drag-offset: {dragOffset}px"
                >
                  {#each items as item, index}
                    <article
                      class="wire-next__carousel-slide"
                      data-active="{index === currentIndex}"
                      role="group"
                      aria-roledescription="slide"
                      aria-label="{index + 1} of {items.length}"
                      aria-hidden="{index === currentIndex ? 'false' : 'true'}"
                    >
                      {#if item.imageSrc}
                        <img src="{item.imageSrc}" alt="{item.imageAlt || item.title || ''}" />
                      {/if}
                      <div class="wire-next__carousel-slide-content">
                        {#if item.eyebrow}<span>{item.eyebrow}</span>{/if}
                        {#if item.title || item.label}<h4>{item.title || item.label}</h4>{/if}
                        {#if item.description}<p>{item.description}</p>{/if}
                        {#if item.actionLabel}
                          <a href="{item.actionHref || '#'}">{item.actionLabel}</a>
                        {/if}
                      </div>
                    </article>
                  {/each}
                  <slot />
                </div>
              </div>

              <button
                class="wire-next__carousel-control wire-next__carousel-control--previous"
                type="button"
                aria-label="Previous slide"
                disabled="{!isInfiniteLoop && currentIndex === 0}"
                @click="previousSlide(event)"
              >
                <span class="icon-[lucide--chevron-left]" aria-hidden="true"></span>
              </button>
              <button
                class="wire-next__carousel-control wire-next__carousel-control--next"
                type="button"
                aria-label="Next slide"
                disabled="{!isInfiniteLoop && currentIndex === maximumIndex()}"
                @click="nextSlide(event)"
              >
                <span class="icon-[lucide--chevron-right]" aria-hidden="true"></span>
              </button>

              {#if showCounter}
                <output class="wire-next__carousel-counter" aria-live="polite">
                  {currentIndex + 1} / {items.length}
                </output>
              {/if}
            </div>

            {#if showPagination}
              <div class="wire-next__carousel-pagination" aria-label="Choose a slide">
                {#each items as item, index}
                  <button
                    type="button"
                    data-active="{index === currentIndex}"
                    aria-label="Show slide {index + 1}"
                    aria-current="{index === currentIndex ? 'true' : 'false'}"
                    @click="selectSlide(index, 'pagination', event)"
                  ></button>
                {/each}
              </div>
            {/if}

            {#if thumbnails === "horizontal"}
              <div class="wire-next__carousel-thumbnails" aria-label="Choose a slide">
                {#each items as item, index}
                  <button
                    type="button"
                    data-active="{index === currentIndex}"
                    aria-label="Show slide {index + 1}: {item.label || item.title}"
                    aria-current="{index === currentIndex ? 'true' : 'false'}"
                    @click="selectSlide(index, 'thumbnail', event)"
                  >
                    {#if item.thumbnail}<img src="{item.thumbnail}" alt="" />{/if}
                    <span>{item.label || item.title || "Slide " + (index + 1)}</span>
                  </button>
                {/each}
              </div>
            {/if}
          </div>
        </div>
    </section>
  }
}
```

---

## Chart

Showcase: https://component.wrnexusjs.dev/
Mount: <Chart /> (legacy: data-component="Chart")
Category: integrations
Purpose: Theme-aware, responsive chart component.
Props: size: string = "default", color: string = "primary", title: string = "Chart", description: string = "", items: string = [], variant: string = "default", class: string = ""
Slots: default
Events: select, dataPointClick, legendToggle

### Complete .wrn source contract

```wrn
component Chart {
  props {
    @event select = function
    @event dataPointClick = function
    @event legendToggle = function
    size = "default"
    color = "primary"
    title = "Chart"
    description = ""
    items = []
    variant = "default"
    class = ""
  }
  view {
    <section class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--chart wire-next--variant-{variant} {class}">
      {#if title}<strong>{title}</strong>{/if}
      {#if description}<p>{description}</p>{/if}
      {#if items}<div class="wire-next__items">{#each items as item}<span>{item.label}</span>{/each}</div>{/if}
      <slot />
    </section>
  }
}
```

---

## ChatBubble

Showcase: https://component.wrnexusjs.dev/
Mount: <ChatBubble /> (legacy: data-component="ChatBubble")
Category: base
Purpose: Theme-aware, responsive chat bubble component.
Props: size: string = "default", color: string = "primary", title: string = "", description: string = "", items: string = [], oneSided: boolean = false, showAvatars: boolean = false, showMetadata: boolean = false, ariaLabel: string = "Conversation", variant: string = "default", class: string = ""
Slots: default
Events: action, messageClick, avatarClick, linkClick

### Complete .wrn source contract

```wrn
component ChatBubble {
  props {
    @event action = function
    @event messageClick = function
    @event avatarClick = function
    @event linkClick = function
    size = "default"
    color = "primary"
    title = ""
    description = ""
    items = []
    oneSided = false
    showAvatars = false
    showMetadata = false
    ariaLabel = "Conversation"
    variant = "default"
    class = ""
  }

  functions {
    function messageDirection(item) {
      return item.direction === "outgoing" ? "outgoing" : "incoming"
    }

    function selectMessage(item, index) {
      $emit("messageClick", {
        item: item,
        index: index,
        direction: messageDirection(item)
      })
    }

    function selectAvatar(sourceEvent, item, index) {
      sourceEvent.stopPropagation()
      $emit("avatarClick", {
        item: item,
        index: index,
        direction: messageDirection(item)
      })
    }

    function selectLink(sourceEvent, link, item, index) {
      sourceEvent.stopPropagation()
      $emit("linkClick", {
        link: link,
        item: item,
        index: index
      })
    }

    function selectAction(sourceEvent, item, index) {
      sourceEvent.stopPropagation()
      $emit("action", {
        action: item.action || "retry",
        item: item,
        index: index
      })
    }
  }

  view {
    <section
      {...attrs}
      class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--chat-bubble wire-next--variant-{variant} {class}"
      data-one-sided="{oneSided}"
      role="log"
      aria-label="{ariaLabel}"
      aria-live="polite"
    >
      {#if title || description}
        <header class="wire-next__chat-header">
          {#if title}<h3>{title}</h3>{/if}
          {#if description}<p>{description}</p>{/if}
        </header>
      {/if}

      {#if items.length}
        <div class="wire-next__chat-thread">
          {#each items as item, index}
            <article
              class="wire-next__chat-message"
              data-direction="{messageDirection(item)}"
              aria-label="{messageDirection(item) === 'outgoing' ? 'Sent message' : 'Received message'}"
            >
              <div class="wire-next__chat-row">
                {#if showAvatars && (item.avatarSrc || item.avatarFallback)}
                  <button
                    class="wire-next__chat-avatar"
                    type="button"
                    aria-label="{item.avatarLabel || item.author || 'Message author'}"
                    @click="selectAvatar(event, item, index)"
                  >
                    {#if item.avatarSrc}
                      <img src="{item.avatarSrc}" alt="{item.avatarAlt || ''}" />
                    {:else}
                      <span>{item.avatarFallback}</span>
                    {/if}
                  </button>
                {/if}

                <div
                  class="wire-next__chat-content"
                  role="button"
                  tabindex="0"
                  @click="selectMessage(item, index)"
                  @keydown="if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); selectMessage(item, index) }"
                >
                  {#if item.title}<h4>{item.title}</h4>{/if}
                  {#if item.text}<p>{item.text}</p>{/if}
                  {#if item.bullets && item.bullets.length}
                    <ul>
                      {#each item.bullets as bullet}<li>{bullet}</li>{/each}
                    </ul>
                  {/if}
                  {#if item.links && item.links.length}
                    <nav aria-label="Message links">
                      {#each item.links as link}
                        <a
                          href="{link.href || '#'}"
                          @click="selectLink(event, link, item, index)"
                        >{link.label}</a>
                      {/each}
                    </nav>
                  {/if}
                </div>
              </div>

              {#if showMetadata && (item.timestamp || item.status || item.actionLabel)}
                <footer class="wire-next__chat-meta" data-tone="{item.statusTone || 'muted'}">
                  {#if item.statusIcon}<span class="{item.statusIcon}" aria-hidden="true"></span>{/if}
                  {#if item.status}<span>{item.status}</span>{/if}
                  {#if item.timestamp}<time datetime="{item.datetime || ''}">{item.timestamp}</time>{/if}
                  {#if item.actionLabel}
                    <button type="button" @click="selectAction(event, item, index)">
                      {item.actionLabel}
                    </button>
                  {/if}
                </footer>
              {/if}
            </article>
          {/each}
        </div>
      {/if}
      <slot />
    </section>
  }
}
```

---

## Checkbox

Showcase: https://component.wrnexusjs.dev/
Mount: <Checkbox /> (legacy: data-component="Checkbox")
Category: forms
Purpose: Theme-aware, responsive checkbox component.
Props: size: string = "default", color: string = "primary", id: string = "", name: string = "", label: string = "Checkbox", hiddenLabel: boolean = false, placeholder: string = "", variant: string = "normal", icon: string = "", iconPosition: string = "start", value: string = "on", values: string = [], options: string = [], checked: boolean = false, indeterminate: boolean = false, orientation: string = "vertical", card: boolean = false, rightAligned: boolean = false, list: boolean = false, helperText: string = "", cornerHint: string = "", error: string = "", inline: boolean = false, readonly: boolean = false, disabled: boolean = false, required: boolean = false, class: string = ""
Slots: default
Events: input, change, focus, blur, invalid

### Complete .wrn source contract

```wrn
component Checkbox {
  props {
    @event input = function
    @event change = function
    @event focus = function
    @event blur = function
    @event invalid = function
    size = "default"
    color = "primary"
    id = ""
    name = ""
    label = "Checkbox"
    hiddenLabel = false
    placeholder = ""
    variant = "normal"
    icon = ""
    iconPosition = "start"
    value = "on"
    values = []
    options = []
    checked = false
    indeterminate = false
    orientation = "vertical"
    card = false
    rightAligned = false
    list = false
    helperText = ""
    cornerHint = ""
    error = ""
    inline = false
    readonly = false
    disabled = false
    required = false
    class = ""
  }
  functions {
    function emitField(nameEvent, sourceEvent) { sourceEvent.stopPropagation(); $emit(nameEvent, { checked: sourceEvent.currentTarget.checked, value: sourceEvent.currentTarget.value, values: values, name: name, sourceEvent: sourceEvent }) }
    function preventReadonly(sourceEvent) { if (readonly) sourceEvent.preventDefault() }
  }
  view {
    <div
      {...attrs}
      class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--choice-field wire-next--checkbox-field {class}"
      data-inline="{inline}"
      data-invalid="{error ? 'true' : 'false'}"
      data-orientation="{orientation}"
      data-card="{card}"
      data-list="{list}"
      data-right-aligned="{rightAligned}"
    >
      <div
        class="wire-next__field-heading"
      >
        {#if options.length || cornerHint}
          <span
            class="{hiddenLabel ? 'wire-next__sr-only' : ''}"
          >
            {label}
          </span>
          {#if cornerHint}
            <span
              class="wire-next__field-hint"
            >
              {cornerHint}
            </span>
          {/if}
        {/if}
      </div>
      {#if options.length}
        <div
          class="wire-next__checkbox-group"
          role="group"
          aria-label="{hiddenLabel ? label : ''}"
          aria-invalid="{error ? 'true' : 'false'}"
        >
          {#each options as option}
            <label
              class="wire-next__choice wire-next--checkbox"
              for="{id || name}-{option.value}"
              data-variant="{variant}"
              data-disabled="{disabled || option.disabled}"
            >
              <input
                id="{id || name}-{option.value}"
                type="checkbox"
                name="{name}"
                value="{option.value}"
                checked="{values.includes(option.value) || option.checked}"
                disabled="{disabled || option.disabled}"
                required="{required}"
                readonly="{readonly}"
                @click="preventReadonly(event)"
                @input="emitField('input', event)"
                @change="emitField('change', event)"
                @focus="emitField('focus', event)"
                @blur="emitField('blur', event)"
                @invalid="emitField('invalid', event)"
              />
              <span
                class="wire-next__choice-copy"
              >
                <strong>{option.label}</strong>
                {#if option.description}
                  <small>{option.description}</small>
                {/if}
              </span>
            </label>
          {/each}
        </div>
      {:else}
        <div
          class="wire-next__checkbox-content"
        >
          <label
            class="wire-next__choice wire-next--checkbox"
            for="{id || name}"
            data-variant="{variant}"
            data-icon-position="{iconPosition}"
          >
            <input
              id="{id || name}"
              type="checkbox"
              name="{name}"
              value="{value}"
              checked="{checked}"
              disabled="{disabled}"
              required="{required}"
              readonly="{readonly}"
              aria-checked="{indeterminate ? 'mixed' : (checked ? 'true' : 'false')}"
              aria-invalid="{error ? 'true' : 'false'}"
              @click="preventReadonly(event)"
              @input="emitField('input', event)"
              @change="emitField('change', event)"
              @focus="emitField('focus', event)"
              @blur="emitField('blur', event)"
              @invalid="emitField('invalid', event)"
            />
            {#if icon}
              <span
                class="{icon}"
                aria-hidden="true"
              >
              </span>
            {/if}
            <span
              class="{hiddenLabel || cornerHint ? 'wire-next__sr-only' : ''}"
            >
              {label}
            </span>
            <div
              class="wire-next__checkbox-slot"
            >
              <slot></slot>
            </div>
          </label>
        </div>
      {/if}
      {#if helperText}
        <small
          class="wire-next__field-help"
        >
          {helperText}
        </small>
      {/if}
      <small
        class="wire-next__field-error"
        data-error="{name}"
      >
        {error}
      </small>
    </div>
  }
}
```

---

## Clipboard

Showcase: https://component.wrnexusjs.dev/
Mount: <Clipboard /> (legacy: data-component="Clipboard")
Category: integrations
Purpose: Theme-aware, responsive clipboard component.
Props: size: string = "default", color: string = "primary", title: string = "Clipboard", description: string = "", items: string = [], variant: string = "default", class: string = ""
Slots: default
Events: copy, success, error

### Complete .wrn source contract

```wrn
component Clipboard {
  props {
    @event copy = function
    @event success = function
    @event error = function
    size = "default"
    color = "primary"
    title = "Clipboard"
    description = ""
    items = []
    variant = "default"
    class = ""
  }
  view {
    <section class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--clipboard wire-next--variant-{variant} {class}">
      {#if title}<strong>{title}</strong>{/if}
      {#if description}<p>{description}</p>{/if}
      {#if items}<div class="wire-next__items">{#each items as item}<span>{item.label}</span>{/each}</div>{/if}
      <slot />
    </section>
  }
}
```

---

## Collapse

Showcase: https://component.wrnexusjs.dev/
Mount: <Collapse /> (legacy: data-component="Collapse")
Category: base
Purpose: Theme-aware, responsive collapse component.
Props: size: string = "default", color: string = "primary", items: string = [], multiple: boolean = false, mode: string = "panel", initialOpenIndexes: string = [], ariaLabel: string = "Collapsible content", class: string = ""
Slots: default
Events: toggle, open, close

### Complete .wrn source contract

```wrn
component Collapse {
  props {
    @event toggle = function
    @event open = function
    @event close = function
    size = "default"
    color = "primary"
    items = []
    multiple = false
    mode = "panel"
    initialOpenIndexes = []
    ariaLabel = "Collapsible content"
    class = ""
  }

  state openIndexes = initialOpenIndexes

  functions {
    function isOpen(index) {
      return openIndexes.includes(index)
    }

    function toggleItem(index, item, opening) {
      if (item.disabled) {
        return
      }
      opening = !isOpen(index)
      if (opening) {
        if (multiple) {
          openIndexes = openIndexes.concat(index)
        } else {
          openIndexes = [index]
        }
        $emit("open", { index: index, item: item })
      } else {
        openIndexes = openIndexes.filter((openIndex) => openIndex !== index)
        $emit("close", { index: index, item: item })
      }
      $emit("toggle", {
        index: index,
        item: item,
        open: opening,
        openIndexes: openIndexes
      })
    }
  }

  view {
    <section
      {...attrs}
      class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--collapse {class}"
      data-mode="{mode}"
      aria-label="{ariaLabel}"
    >
      {#each items as item, index}
        <article class="wire-next__collapse-item" data-open="{isOpen(index)}">
          {#if mode === "inline" && item.preview}
            <p class="wire-next__collapse-preview">{item.preview}</p>
          {/if}

          <button
            class="wire-next__collapse-trigger"
            type="button"
            aria-expanded="{isOpen(index) ? 'true' : 'false'}"
            aria-controls="{item.id || 'collapse-panel-' + index}"
            disabled="{item.disabled}"
            @click="toggleItem(index, item)"
          >
            <span>{isOpen(index) ? (item.closeLabel || "Read less") : item.label}</span>
            <span class="icon-[lucide--chevron-down] wire-next__collapse-chevron" aria-hidden="true"></span>
          </button>

          <div
            id="{item.id || 'collapse-panel-' + index}"
            class="wire-next__collapse-panel"
            data-open="{isOpen(index)}"
            aria-hidden="{isOpen(index) ? 'false' : 'true'}"
            inert="{!isOpen(index)}"
          >
            <div class="wire-next__collapse-content">
              {#if item.title}<h4>{item.title}</h4>{/if}
              {#if item.content}<p>{item.content}</p>{/if}
              {#if item.links && item.links.length}
                <nav aria-label="Related links">
                  {#each item.links as link}<a href="{link.href || '#'}">{link.label}</a>{/each}
                </nav>
              {/if}
            </div>
          </div>
        </article>
      {/each}
      <slot />
    </section>
  }
}
```

---

## ColorPicker

Showcase: https://component.wrnexusjs.dev/
Mount: <ColorPicker /> (legacy: data-component="ColorPicker")
Category: forms
Purpose: Theme-aware, responsive color picker component.
Props: size: string = "default", color: string = "primary", id: string = "", name: string = "", label: string = "Color", hiddenLabel: boolean = false, placeholder: string = "", value: string = "#2563eb", icon: string = "", iconPosition: string = "start", helperText: string = "", cornerHint: string = "", error: string = "", inline: boolean = false, variant: string = "normal", readonly: boolean = false, disabled: boolean = false, required: boolean = false, class: string = ""
Slots: none
Events: input, change, focus, blur

### Complete .wrn source contract

```wrn
component ColorPicker {
  props {
    @event input = function
    @event change = function
    @event focus = function
    @event blur = function
    size = "default"
    color = "primary"
    id = ""
    name = ""
    label = "Color"
    hiddenLabel = false
    placeholder = ""
    value = "#2563eb"
    icon = ""
    iconPosition = "start"
    helperText = ""
    cornerHint = ""
    error = ""
    inline = false
    variant = "normal"
    readonly = false
    disabled = false
    required = false
    class = ""
  }
  functions {
    function emitField(nameEvent, sourceEvent) { sourceEvent.stopPropagation(); $emit(nameEvent, { value: sourceEvent.currentTarget.value, name: name, sourceEvent: sourceEvent }) }
    function preventReadonly(sourceEvent) { if (readonly) sourceEvent.preventDefault() }
  }
  view {
    <div {...attrs} class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--field wire-next--color-picker {class}" data-variant="{variant}" data-inline="{inline}" data-invalid="{error ? 'true' : 'false'}">
      <div class="wire-next__field-heading"><label class="{hiddenLabel ? 'wire-next__sr-only' : ''}" for="{id || name}">{label}</label>{#if cornerHint}<span class="wire-next__field-hint">{cornerHint}</span>{/if}</div>
      <div class="wire-next__color-control" data-icon-position="{iconPosition}">{#if icon}<span class="{icon}" aria-hidden="true"></span>{/if}<input id="{id || name}" type="color" name="{name}" value="{value}" disabled="{disabled}" required="{required}" readonly="{readonly}" aria-invalid="{error ? 'true' : 'false'}" @click="preventReadonly(event)" @input="emitField('input', event)" @change="emitField('change', event)" @focus="emitField('focus', event)" @blur="emitField('blur', event)" /><output>{value}</output></div>
      {#if helperText}<small class="wire-next__field-help">{helperText}</small>{/if}<small class="wire-next__field-error" data-error="{name}">{error}</small>
    </div>
  }
}
```

---

## Columns

Showcase: https://component.wrnexusjs.dev/
Mount: <Columns /> (legacy: data-component="Columns")
Category: layout
Purpose: Theme-aware, responsive columns component.
Props: size: string = "default", color: string = "primary", columns: number = 2, gap: string = "md", maxWidth: string = "xl", class: string = ""
Slots: default
Events: none

### Complete .wrn source contract

```wrn
component Columns {
  props {
    size = "default"
    color = "primary"
    columns = 2
    gap = "md"
    maxWidth = "xl"
    class = ""
  }

  view {
    <div
      data-ui-component="Columns"
      data-size='{size}'
      data-color='{color}'
      data-columns='{columns}'
      data-gap='{gap}'
      class='grid w-full grid-cols-1 items-start {class}'
      class:max-w-3xl='maxWidth === "md"'
      class:max-w-5xl='maxWidth === "lg"'
      class:max-w-7xl='maxWidth === "xl"'
      class:max-w-screen-2xl='maxWidth === "2xl"'
      class:max-w-none='maxWidth === "full"'
      class:md:grid-cols-2='columns >= 2'
      class:lg:grid-cols-3='columns === 3'
      class:lg:grid-cols-4='columns === 4'
      class:gap-3='gap === "sm"'
      class:gap-6='gap === "md"'
      class:gap-10='gap === "lg"'
      class:gap-14='gap === "xl"'
    >
      <slot></slot>
    </div>
  }
}
```

---

## ComboBox

Showcase: https://component.wrnexusjs.dev/
Mount: <ComboBox /> (legacy: data-component="ComboBox")
Category: advanced-forms
Purpose: Editable autocomplete combobox with local and remote suggestions.
Props: size: string = "default", color: string = "primary", label: string = "ComboBox", name: string = "", value: string = "", options: string = [], groups: string = [], placeholder: string = "Search or select an option", searchPlaceholder: string = "Start typing…", clearable: boolean = true, allowCustomValue: boolean = false, disabled: boolean = false, required: boolean = false, invalid: boolean = false, validationMessage: string = "", helpText: string = "", loading: boolean = false, loadingLabel: string = "Loading suggestions…", emptyLabel: string = "No matching options", clearLabel: string = "Clear value", toggleLabel: string = "Toggle suggestions", searchMode: string = "contains", searchFields: string = "label,description", minSearchLength: number = 0, searchResultLimit: number = 0, optionTemplate: string = "default", defaultOpen: boolean = false, closeOnSelect: boolean = true, fixed: boolean = false, placement: string = "bottom", autocomplete: string = "off", remote: boolean = false, remoteUrl: string = "", remoteQueryParam: string = "q", remoteDebounce: number = 250, remoteAutoLoad: boolean = true, infinite: boolean = false, hasMore: boolean = false, page: number = 1, loadMoreLabel: string = "Load more", class: string = ""
Slots: none
Events: search, select, change, clear, open, close, load, error

### Complete .wrn source contract

```wrn
component ComboBox {
  props {
    size = "default"
    color = "primary"
    label = "ComboBox"
    name = ""
    value = ""
    options = []
    groups = []
    placeholder = "Search or select an option"
    searchPlaceholder = "Start typing…"
    clearable = true
    allowCustomValue = false
    disabled = false
    required = false
    invalid = false
    validationMessage = ""
    helpText = ""
    loading = false
    loadingLabel = "Loading suggestions…"
    emptyLabel = "No matching options"
    clearLabel = "Clear value"
    toggleLabel = "Toggle suggestions"
    searchMode = "contains"
    searchFields = "label,description"
    minSearchLength = 0
    searchResultLimit = 0
    optionTemplate = "default"
    defaultOpen = false
    closeOnSelect = true
    fixed = false
    placement = "bottom"
    autocomplete = "off"
    remote = false
    remoteUrl = ""
    remoteQueryParam = "q"
    remoteDebounce = 250
    remoteAutoLoad = true
    infinite = false
    hasMore = false
    page = 1
    loadMoreLabel = "Load more"
    class = ""
    @event search = function
    @event select = function
    @event change = function
    @event clear = function
    @event open = function
    @event close = function
    @event load = function
    @event error = function
  }

  state open = defaultOpen
  state query = ""
  state selectedValue = value
  state activeIndex = -1

  functions {
    function allOptions() {
      return [...groups.flatMap((group) => group.options || []), ...options]
    }

    function searchableText(option) {
      return ((option.label || "") + " " + (option.description || "")).toLowerCase()
    }

    function matches(option) {
      if (!query || query.length < minSearchLength) {
        return true
      }
      if (searchMode === "startsWith") {
        return searchableText(option).startsWith(query.toLowerCase())
      }
      if (searchMode === "exact") {
        return searchableText(option) === query.toLowerCase()
      }
      return searchableText(option).includes(query.toLowerCase())
    }

    function matchingOptions(list) {
      return list.filter((option) => matches(option))
    }

    function visibleOptions(list) {
      if (searchResultLimit > 0) {
        return matchingOptions(list).slice(0, searchResultLimit)
      }
      return matchingOptions(list)
    }

    function flatVisibleOptions() {
      return visibleOptions(allOptions())
    }

    function isSelected(option) {
      return selectedValue === option.value
    }

    function selectedOptions() {
      return allOptions().filter((option) => isSelected(option))
    }

    function selectedText() {
      return selectedOptions().length ? selectedOptions()[0].label : selectedValue
    }

    function inputText() {
      return query || selectedText()
    }

    function shouldShowDropdown() {
      if (!open) {
        return false
      }
      if (loading) {
        return true
      }
      if (remote && query.length !== 0 && query.length < minSearchLength) {
        return true
      }
      if (flatVisibleOptions().length) {
        return true
      }
      return infinite && hasMore
    }

    function canSelect(option) {
      return !option.disabled
    }

    function chooseOption(option) {
      if (!canSelect(option)) {
        return
      }
      selectedValue = option.value
      query = option.label
      activeIndex = optionIndex(option)
      if (closeOnSelect) {
        open = false
      }
    }

    function updateQuery(event) {
      query = event.target.value
      selectedValue = allowCustomValue ? event.target.value : ""
      open = true
      activeIndex = flatVisibleOptions().length ? 0 : -1
    }

    function clearValue(event) {
      if (event) {
        event.stopPropagation()
      }
      query = ""
      selectedValue = ""
      activeIndex = -1
      open = false
    }

    function openDropdown() {
      if (!disabled) {
        open = true
        activeIndex = flatVisibleOptions().length ? 0 : -1
      }
    }

    function closeDropdown() {
      open = false
    }

    function toggle() {
      if (open) {
        closeDropdown()
      } else {
        openDropdown()
      }
    }

    function setValue(nextValue) {
      selectedValue = nextValue
      query = ""
    }

    function moveActive(direction) {
      if (!flatVisibleOptions().length) {
        return
      }
      activeIndex = (activeIndex + direction + flatVisibleOptions().length) % flatVisibleOptions().length
    }

    function handleKeydown(event) {
      if (disabled) {
        return
      }
      if (event.key === "ArrowDown") {
        event.preventDefault()
        openDropdown()
        moveActive(1)
      } else if (event.key === "ArrowUp") {
        event.preventDefault()
        openDropdown()
        moveActive(-1)
      } else if (event.key === "Enter" && open && activeIndex >= 0) {
        event.preventDefault()
        chooseOption(flatVisibleOptions()[activeIndex])
      } else if (event.key === "Escape") {
        closeDropdown()
      } else if (event.key === "Home" && open) {
        event.preventDefault()
        activeIndex = 0
      } else if (event.key === "End" && open) {
        event.preventDefault()
        activeIndex = flatVisibleOptions().length - 1
      }
    }

    function optionIndex(option) {
      return flatVisibleOptions().findIndex((item) => item.value === option.value)
    }
  }

  view {
    <div
      class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--advanced-select wire-next--combobox {open ? 'wire-next--open' : ''} {fixed ? 'wire-next--advanced-select-fixed' : ''} {invalid ? 'wire-next--invalid' : ''} {disabled ? 'wire-next--disabled' : ''} {class}"
      data-placement="{placement}"
      data-search-mode="{searchMode}"
      data-remote="{remote ? 'true' : 'false'}"
      data-remote-url="{remoteUrl}"
      data-remote-query-param="{remoteQueryParam}"
      data-remote-debounce="{remoteDebounce}"
      data-remote-auto-load="{remoteAutoLoad ? 'true' : 'false'}"
      data-infinite="{infinite ? 'true' : 'false'}"
      data-page="{page}"
      data-wrn-select
      data-wrn-combobox
      @focusout="if (!event.currentTarget.contains(event.relatedTarget)) { closeDropdown() }"
    >
      <label id="{name}-label" for="{name}-input">{label}</label>

      <div class="wire-next__select-control wire-next__combobox-control">
        <span class="wire-next__search-icon icon-[lucide--search]" aria-hidden="true"></span>
        <input
          {...attrs}
          id="{name}-input"
          class="wire-next__select-trigger wire-next__combobox-input"
          type="text"
          role="combobox"
          name="{allowCustomValue ? name : ''}"
          value="{inputText()}"
          placeholder="{placeholder}"
          autocomplete="{autocomplete}"
          aria-autocomplete="list"
          aria-haspopup="listbox"
          aria-expanded="{open}"
          aria-controls="{name}-listbox"
          aria-labelledby="{name}-label"
          aria-invalid="{invalid}"
          disabled="{disabled}"
          required="{required && allowCustomValue}"
          @focus="openDropdown()"
          @click="openDropdown()"
          @input="updateQuery(event)"
          @keydown="handleKeydown(event)"
        />

        <button
          type="button"
          class="wire-next__clear-select"
          data-show="clearable && inputText() && !disabled"
          aria-label="{clearLabel}"
          title="{clearLabel}"
          @click="clearValue(event)"
        >
          <span class="icon-[lucide--x]" aria-hidden="true"></span>
        </button>
        <button
          type="button"
          class="wire-next__combobox-toggle"
          aria-label="{toggleLabel}"
          tabindex="-1"
          disabled="{disabled}"
          @click="toggle()"
        >
          <span class="wire-next__select-chevron icon-[lucide--chevrons-up-down]" aria-hidden="true"></span>
        </button>
      </div>

      <div
        class="wire-next__select-dropdown {fixed ? 'wire-next__select-dropdown--fixed' : ''}"
        data-show="shouldShowDropdown()"
        style="{shouldShowDropdown() ? '' : 'display: none'}"
      >
        <div
          class="wire-next__select-message"
          data-show="remote && query.length !== 0 && query.length < minSearchLength"
        >Enter at least {minSearchLength} characters.</div>
        <div class="wire-next__select-message" data-show="loading" role="status">
          <i class="wire-spinner wire-spinner--inline" aria-hidden="true"></i>
          {loadingLabel}
        </div>

        <div
          id="{name}-listbox"
          class="wire-next__select-list"
          data-show="(!remote || (query.length === 0 && remoteAutoLoad) || query.length >= minSearchLength) && !loading"
          role="listbox"
        >
          {#each groups as group}
            {#if visibleOptions(group.options || []).length}
              <div class="wire-next__option-group" role="group" aria-label="{group.label}">
                <div class="wire-next__group-label">{group.label}</div>
                {#each group.options || [] as option}
                  <button
                    type="button"
                    class="wire-next__select-option {isSelected(option) ? 'wire-next__select-option--selected' : ''} {optionIndex(option) === activeIndex ? 'wire-next__select-option--active' : ''}"
                    data-option-value="{option.value}"
                    data-show="matches(option)"
                    role="option"
                    aria-selected="{isSelected(option)}"
                    disabled="{!canSelect(option)}"
                    @mouseenter="activeIndex = optionIndex(option)"
                    @mousedown="event.preventDefault()"
                    @click="chooseOption(option)"
                  >
                    {#if optionTemplate === "icon" && option.icon}<i class="{option.icon}" aria-hidden="true"></i>{/if}
                    {#if optionTemplate === "avatar" && option.avatar}<img src="{option.avatar}" alt="" />{/if}
                    {#if optionTemplate === "color" && option.color}<i class="wire-next__color-dot" style="--option-color: {option.color}"></i>{/if}
                    <span><strong>{option.label}</strong>{#if option.description}<small>{option.description}</small>{/if}</span>
                    <i class="wire-next__check icon-[lucide--check]" data-show="isSelected(option)" aria-hidden="true"></i>
                  </button>
                {/each}
              </div>
            {/if}
          {/each}

          {#each options as option}
            <button
              type="button"
              class="wire-next__select-option {isSelected(option) ? 'wire-next__select-option--selected' : ''} {optionIndex(option) === activeIndex ? 'wire-next__select-option--active' : ''}"
              data-option-value="{option.value}"
              data-show="matches(option)"
              role="option"
              aria-selected="{isSelected(option)}"
              disabled="{!canSelect(option)}"
              @mouseenter="activeIndex = optionIndex(option)"
              @mousedown="event.preventDefault()"
              @click="chooseOption(option)"
            >
              {#if optionTemplate === "icon" && option.icon}<i class="{option.icon}" aria-hidden="true"></i>{/if}
              {#if optionTemplate === "avatar" && option.avatar}<img src="{option.avatar}" alt="" />{/if}
              {#if optionTemplate === "color" && option.color}<i class="wire-next__color-dot" style="--option-color: {option.color}"></i>{/if}
              <span><strong>{option.label}</strong>{#if option.description}<small>{option.description}</small>{/if}</span>
              <i class="wire-next__check icon-[lucide--check]" data-show="isSelected(option)" aria-hidden="true"></i>
            </button>
          {/each}
        </div>

        <button
          type="button"
          class="wire-next__load-more"
          data-wrn-select-load-more
          data-show="infinite && hasMore"
        >{loadMoreLabel}</button>
      </div>

      {#if !allowCustomValue}
        <input
          type="hidden"
          name="{name}"
          value="{selectedValue}"
          required="{required}"
          data-error="{name}"
          aria-describedby="{validationMessage ? `${name}-validation` : helpText ? `${name}-help` : ''}"
        />
      {/if}

      {#if helpText && !validationMessage}<small id="{name}-help">{helpText}</small>{/if}
      <small
        id="{name}-validation"
        class="wire-next__validation"
        data-error="{name}"
      >{validationMessage}</small>
    </div>
  }
}
```

---

## Confetti

Showcase: https://component.wrnexusjs.dev/
Mount: <Confetti /> (legacy: data-component="Confetti")
Category: integrations
Purpose: Theme-aware, responsive confetti component.
Props: size: string = "default", color: string = "primary", title: string = "Confetti", description: string = "", items: string = [], variant: string = "default", class: string = ""
Slots: default
Events: start, complete

### Complete .wrn source contract

```wrn
component Confetti {
  props {
    @event start = function
    @event complete = function
    size = "default"
    color = "primary"
    title = "Confetti"
    description = ""
    items = []
    variant = "default"
    class = ""
  }
  view {
    <section class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--confetti wire-next--variant-{variant} {class}">
      {#if title}<strong>{title}</strong>{/if}
      {#if description}<p>{description}</p>{/if}
      {#if items}<div class="wire-next__items">{#each items as item}<span>{item.label}</span>{/each}</div>{/if}
      <slot />
    </section>
  }
}
```

---

## Container

Showcase: https://component.wrnexusjs.dev/
Mount: <Container /> (legacy: data-component="Container")
Category: layout
Purpose: Theme-aware, responsive container component.
Props: size: string = "default", color: string = "primary", columns: number = 2, gap: string = "md", maxWidth: string = "xl", class: string = ""
Slots: default
Events: none

### Complete .wrn source contract

```wrn
component Container {
  props {
    size = "default"
    color = "primary"
    columns = 2
    gap = "md"
    maxWidth = "xl"
    class = ""
  }

  view {
    <div
      data-ui-component="Container"
      data-size='{size}'
      data-color='{color}'
      data-columns='{columns}'
      data-gap='{gap}'
      data-max-width='{maxWidth}'
      class='mx-auto w-full {class}'
      class:max-w-3xl='maxWidth === "md"'
      class:max-w-5xl='maxWidth === "lg"'
      class:max-w-7xl='maxWidth === "xl" || maxWidth === "wide"'
      class:max-w-screen-2xl='maxWidth === "2xl"'
      class:max-w-none='maxWidth === "full"'
      class:px-4='size === "compact" || size === "default"'
      class:px-5='size === "comfortable"'
      class:px-6='size === "spacious"'
      class:sm:px-6='size !== "compact"'
      class:lg:px-8='size === "default" || size === "comfortable" || size === "spacious"'
      class:grid='columns > 1'
      class:grid-cols-1='columns > 1'
      class:sm:grid-cols-2='columns === 2 || columns === 3 || columns === 4 || columns === 5 || columns === 6'
      class:lg:grid-cols-3='columns === 3'
      class:lg:grid-cols-4='columns === 4'
      class:lg:grid-cols-5='columns === 5'
      class:lg:grid-cols-6='columns === 6'
      class:gap-2='gap === "xs"'
      class:gap-3='gap === "sm"'
      class:gap-5='gap === "md"'
      class:gap-8='gap === "lg"'
      class:gap-10='gap === "xl"'
    >
      <slot></slot>
    </div>
  }
}
```

---

## ContextMenu

Showcase: https://component.wrnexusjs.dev/
Mount: <ContextMenu /> (legacy: data-component="ContextMenu")
Category: overlays
Purpose: Theme-aware, responsive context menu component.
Props: size: string = "default", color: string = "primary", title: string = "Context Menu", description: string = "", open: boolean = false, placement: string = "bottom", closeLabel: string = "Close", class: string = ""
Slots: default
Events: open, close, select

### Complete .wrn source contract

```wrn
component ContextMenu {
  props {
    @event open = function
    @event close = function
    @event select = function
    size = "default"
    color = "primary"
    title = "Context Menu"
    description = ""
    open = false
    placement = "bottom"
    closeLabel = "Close"
    class = ""
  }
  view {
    <div data-show="{open}" class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--context-menu wire-next--placement-{placement} {class}" role="region" aria-modal="false" aria-label="{title}">
      <header><strong>{title}</strong><button type="button" aria-label="{closeLabel}">×</button></header>
      {#if description}<p>{description}</p>{/if}
      <slot />
    </div>
  }
}
```

---

## CopyMarkup

Showcase: https://component.wrnexusjs.dev/
Mount: <CopyMarkup /> (legacy: data-component="CopyMarkup")
Category: advanced-forms
Purpose: Theme-aware, responsive copy markup component.
Props: size: string = "default", color: string = "primary", label: string = "Copy Markup", name: string = "", value: string = "", placeholder: string = "", type: string = "text", min: string = "", max: string = "", step: string = "", disabled: boolean = false, required: boolean = false, class: string = ""
Slots: none
Events: copy, success, error

### Complete .wrn source contract

```wrn
component CopyMarkup {
  props {
    @event copy = function
    @event success = function
    @event error = function
    size = "default"
    color = "primary"
    label = "Copy Markup"
    name = ""
    value = ""
    placeholder = ""
    type = "text"
    min = ""
    max = ""
    step = ""
    disabled = false
    required = false
    class = ""
  }
  view {
    <label class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--field wire-next--copy-markup {class}"><span>{label}</span><input {...attrs} type="{type}" name="{name}" value="{value}" placeholder="{placeholder}" min="{min}" max="{max}" step="{step}" disabled="{disabled}" required="{required}" /></label>
  }
}
```

---

## CTASection

Showcase: https://component.wrnexusjs.dev/
Mount: <CTASection /> (legacy: data-component="CTASection")
Category: blocks
Purpose: Reusable closing call-to-action section with primary and secondary actions.
Props: eyebrow: string = "", title: string = "Ready to get started?", description: string = "", icon: string = "", align: string = "center", size: string = "default", color: string = "primary", variant: string = "solid", primaryLabel: string = "Get started", primaryHref: string = "#", primaryIcon: string = "", secondaryLabel: string = "", secondaryHref: string = "", secondaryIcon: string = "", backgroundImage: string = "", maxWidth: string = "xl", class: string = ""
Slots: default, actions, visual, footer
Events: none

### Complete .wrn source contract

```wrn
component CTASection {
  props {
    eyebrow = ""
    title = "Ready to get started?"
    description = ""
    icon = ""
    align = "center"
    size = "default"
    color = "primary"
    variant = "solid"
    primaryLabel = "Get started"
    primaryHref = "#"
    primaryIcon = ""
    secondaryLabel = ""
    secondaryHref = ""
    secondaryIcon = ""
    backgroundImage = ""
    maxWidth = "xl"
    class = ""
  }

  view {
    <Section
      spacing='{size === "compact" ? "md" : "lg"}'
      variant="default"
      color='{color}'
      maxWidth='{maxWidth}'
      class='{class}'
    >
      <div
        data-ui-component="CTASection"
        class="relative isolate overflow-hidden rounded-3xl border border-[var(--wire-color-border)] p-8 shadow-xl sm:p-10 lg:p-14"
        class:bg-[var(--wire-color-primary)]='variant === "solid" && color === "primary"'
        class:text-[var(--wire-color-on-primary)]='variant === "solid" && color === "primary"'
        class:bg-[var(--wire-color-danger)]='variant === "solid" && color === "danger"'
        class:text-[var(--wire-color-on-danger)]='variant === "solid" && color === "danger"'
        class:bg-[var(--wire-color-primary-soft)]='variant === "soft" && color === "primary"'
        class:bg-[var(--wire-color-success-soft)]='variant === "soft" && color === "success"'
        class:bg-[var(--wire-color-warning-soft)]='variant === "soft" && color === "warning"'
        class:bg-[var(--wire-color-danger-soft)]='variant === "soft" && color === "danger"'
        class:bg-[var(--wire-color-surface-raised)]='variant === "default" || variant === "outline"'
        class:bg-gradient-to-br='variant === "gradient"'
        class:from-[var(--wire-color-primary)]='variant === "gradient"'
        class:to-[var(--wire-color-secondary)]='variant === "gradient"'
        class:text-[var(--wire-color-on-primary)]='variant === "gradient"'
        class:text-center='align === "center"'
      >
        {#if backgroundImage}
          <img
            src='{backgroundImage}'
            alt=""
            aria-hidden="true"
            class="absolute inset-0 -z-20 h-full w-full object-cover opacity-15"
          />
        {/if}

        <div
          class="pointer-events-none absolute -right-20 -top-20 -z-10 size-72 rounded-full bg-white/15 blur-3xl"
          aria-hidden="true"
        ></div>
        <div
          class="pointer-events-none absolute -bottom-24 -left-20 -z-10 size-72 rounded-full bg-black/10 blur-3xl"
          aria-hidden="true"
        ></div>

        <div
          class="flex flex-col gap-8"
          class:items-center='align === "center"'
          class:lg:flex-row='align === "split"'
          class:lg:items-center='align === "split"'
          class:lg:justify-between='align === "split"'
        >
          <div class="max-w-3xl">
            {#if icon}
              <span
                class="mb-5 inline-flex size-12 items-center justify-center rounded-2xl bg-white/15"
                class:bg-[var(--wire-color-primary-soft)]='variant !== "solid" && variant !== "gradient"'
                class:text-[var(--wire-color-primary)]='variant !== "solid" && variant !== "gradient"'
              >
                <span class='{icon + " size-6"}' aria-hidden="true"></span>
              </span>
            {/if}

            {#if eyebrow}
              <p
                class="text-xs font-bold uppercase tracking-[0.18em]"
                class:text-[var(--wire-color-primary)]='variant !== "solid" && variant !== "gradient"'
                class:opacity-80='variant === "solid" || variant === "gradient"'
              >
                {eyebrow}
              </p>
            {/if}

            <h2
              class="mt-3 text-3xl font-bold leading-tight tracking-tight sm:text-4xl lg:text-5xl"
              class:text-[var(--wire-color-text)]='variant !== "solid" && variant !== "gradient"'
            >
              {title}
            </h2>

            {#if description}
              <p
                class="mt-4 text-base leading-7 sm:text-lg"
                class:text-[var(--wire-color-text-muted)]='variant !== "solid" && variant !== "gradient"'
                class:opacity-85='variant === "solid" || variant === "gradient"'
              >
                {description}
              </p>
            {/if}

            <slot></slot>
          </div>

          <HeroActions
            actions='{[
              {
                label: primaryLabel,
                href: primaryHref,
                icon: primaryIcon,
                variant: "default",
                color: color,
                controlClass: variant === "solid" || variant === "gradient" ? "!bg-white !text-[var(--wire-color-primary)] hover:!bg-white/90" : ""
              },
              {
                label: secondaryLabel,
                href: secondaryHref,
                icon: secondaryIcon,
                variant: "outline",
                color: color,
                controlClass: variant === "solid" || variant === "gradient" ? "!border-white/50 !text-white hover:!bg-white/10" : ""
              }
            ]}'
            align='{align === "center" ? "center" : "right"}'
            stackOnMobile="true"
            fullWidthMobile="true"
            size="lg"
            color='{color}'
            class="shrink-0"
          >
            <slot name="actions"></slot>
          </HeroActions>

          <slot name="visual"></slot>
        </div>

        <slot name="footer"></slot>
      </div>
    </Section>
  }
}
```

---

## CustomScrollbar

Showcase: https://component.wrnexusjs.dev/
Mount: <CustomScrollbar /> (legacy: data-component="CustomScrollbar")
Category: layout
Purpose: Theme-aware, responsive custom scrollbar component.
Props: size: string = "default", color: string = "primary", columns: number = 2, gap: string = "md", maxWidth: string = "xl", class: string = ""
Slots: default
Events: scroll

### Complete .wrn source contract

```wrn
component CustomScrollbar {
  props {
    @event scroll = function
    size = "default"
    color = "primary"
    columns = 2
    gap = "md"
    maxWidth = "xl"
    class = ""
  }
  view {
    <div class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--custom-scrollbar wire-next--gap-{gap} wire-next--columns-{columns} wire-next--max-{maxWidth} {class}"><slot /></div>
  }
}
```

---

## DataMap

Showcase: https://component.wrnexusjs.dev/
Mount: <DataMap /> (legacy: data-component="DataMap")
Category: integrations
Purpose: Theme-aware, responsive data map component.
Props: size: string = "default", color: string = "primary", title: string = "Data Map", description: string = "", items: string = [], variant: string = "default", class: string = ""
Slots: default
Events: select, change

### Complete .wrn source contract

```wrn
component DataMap {
  props {
    @event select = function
    @event change = function
    size = "default"
    color = "primary"
    title = "Data Map"
    description = ""
    items = []
    variant = "default"
    class = ""
  }
  view {
    <section class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--data-map wire-next--variant-{variant} {class}">
      {#if title}<strong>{title}</strong>{/if}
      {#if description}<p>{description}</p>{/if}
      {#if items}<div class="wire-next__items">{#each items as item}<span>{item.label}</span>{/each}</div>{/if}
      <slot />
    </section>
  }
}
```

---

## DataTable

Showcase: https://component.wrnexusjs.dev/
Mount: <DataTable /> (legacy: data-component="DataTable")
Category: integrations
Purpose: Theme-aware, responsive data table component.
Props: size: string = "default", color: string = "primary", caption: string = "Data Table", columns: string = [], rows: string = [], striped: boolean = true, class: string = ""
Slots: default
Events: sort, select, change, rowClick, pageChange

### Complete .wrn source contract

```wrn
component DataTable {
  props {
    @event sort = function
    @event select = function
    @event change = function
    @event rowClick = function
    @event pageChange = function
    size = "default"
    color = "primary"
    caption = "Data Table"
    columns = []
    rows = []
    striped = true
    class = ""
  }
  view {
    <div class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--table {class}"><table><caption>{caption}</caption><thead><tr>{#each columns as column}<th>{column.label}</th>{/each}</tr></thead><tbody>{#each rows as row}<tr>{#each columns as column}<td>{row[column.key]}</td>{/each}</tr>{/each}</tbody></table><slot /></div>
  }
}
```

---

## DatePicker

Showcase: https://component.wrnexusjs.dev/
Mount: <DatePicker /> (legacy: data-component="DatePicker")
Category: base
Purpose: Theme-aware, responsive date picker component.
Props: size: string = "default", color: string = "primary", label: string = "Date Picker", id: string = "", name: string = "", value: string = "", placeholder: string = "", type: string = "date", locale: string = "en-US", firstDayOfWeek: number = 0, months: string = [{ label: "Jan", value: "01" }, { label: "Feb", value: "02" }, { label: "Mar", value: "03" }, { label: "Apr", value: "04" }, { label: "May", value: "05" }, { label: "Jun", value: "06" }, { label: "Jul", value: "07" }, { label: "Aug", value: "08" }, { label: "Sep", value: "09" }, { label: "Oct", value: "10" }, { label: "Nov", value: "11" }, { label: "Dec", value: "12" }], days: string = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31], years: string = [2024, 2025, 2026, 2027, 2028, 2029, 2030], min: string = "", max: string = "", step: string = "", helperText: string = "", cornerHint: string = "", error: string = "", variant: string = "normal", inline: boolean = false, readonly: boolean = false, disabled: boolean = false, required: boolean = false, class: string = ""
Slots: none
Events: input, change, open, close, focus, blur, invalid

### Complete .wrn source contract

```wrn
component DatePicker {
  props {
    @event input = function
    @event change = function
    @event open = function
    @event close = function
    @event focus = function
    @event blur = function
    @event invalid = function
    size = "default"
    color = "primary"
    label = "Date Picker"
    id = ""
    name = ""
    value = ""
    placeholder = ""
    type = "date"
    locale = "en-US"
    firstDayOfWeek = 0
    months = [{ label: "Jan", value: "01" }, { label: "Feb", value: "02" }, { label: "Mar", value: "03" }, { label: "Apr", value: "04" }, { label: "May", value: "05" }, { label: "Jun", value: "06" }, { label: "Jul", value: "07" }, { label: "Aug", value: "08" }, { label: "Sep", value: "09" }, { label: "Oct", value: "10" }, { label: "Nov", value: "11" }, { label: "Dec", value: "12" }]
    days = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]
    years = [2024, 2025, 2026, 2027, 2028, 2029, 2030]
    min = ""
    max = ""
    step = ""
    helperText = ""
    cornerHint = ""
    error = ""
    variant = "normal"
    inline = false
    readonly = false
    disabled = false
    required = false
    class = ""
  }
  state currentValue = value
  state selectedYear = value ? value.split("-")[0] : ""
  state selectedMonth = value ? value.split("-")[1] : ""
  state selectedDay = value ? value.split("-")[2] : ""
  state expanded = false
  functions {
    function openCalendar(sourceEvent) { expanded = true; $emit("open", { value: currentValue, name: name, sourceEvent: sourceEvent }) }
    function updateDate(part, nextValue, sourceEvent, nextDate, detail) { if (part === "year") { selectedYear = String(nextValue) } if (part === "month") { selectedMonth = String(nextValue).padStart(2, "0") } if (part === "day") { selectedDay = String(nextValue).padStart(2, "0") } if (!selectedYear || !selectedMonth || !selectedDay) { return } nextDate = selectedYear + "-" + selectedMonth + "-" + selectedDay; if ((min && nextDate < min) || (max && nextDate > max)) { return } currentValue = nextDate; detail = { value: currentValue, year: selectedYear, month: selectedMonth, day: selectedDay, name: name, sourceEvent: sourceEvent }; $emit("input", detail); $emit("change", detail) }
    function finishDate(sourceEvent) { if (!currentValue) { return } expanded = false; $emit("close", { value: currentValue, name: name, sourceEvent: sourceEvent }) }
    function selectDay(sourceEvent, root, input, nextDate, trigger, detail) { root = sourceEvent.currentTarget.closest(".wire-next--date-picker"); input = root.querySelector(".wire-next__picker-value"); nextDate = input.getAttribute("value").slice(0, 5) + root.querySelector("select").getAttribute("value") + "-" + sourceEvent.currentTarget.dataset.value; currentValue = nextDate; input.setAttribute("value", nextDate); trigger = root.querySelector(".wire-next__date-trigger span"); if (trigger) { trigger.replaceChildren(nextDate) } sourceEvent.currentTarget.setAttribute("aria-pressed", "true"); detail = { value: nextDate, name: name, sourceEvent: sourceEvent }; $emit("input", detail); $emit("change", detail) }
    function clearDate(sourceEvent, detail) { if (disabled || readonly) { return } currentValue = ""; detail = { value: currentValue, name: name, sourceEvent: sourceEvent }; $emit("input", detail); $emit("change", detail) }
    function handleFocus(sourceEvent) { $emit("focus", { value: currentValue, name: name, sourceEvent: sourceEvent }) }
    function handleBlur(sourceEvent) { $emit("blur", { value: currentValue, name: name, sourceEvent: sourceEvent }) }
    function handleInvalid(sourceEvent) { $emit("invalid", { name: name, message: sourceEvent.currentTarget.validationMessage, sourceEvent: sourceEvent }) }
  }
  view {
    <div {...attrs} class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--field wire-next--date-picker {class}" data-variant="{variant}" data-inline="{inline}" data-invalid="{error ? 'true' : 'false'}" data-expanded="{expanded}">
      <div class="wire-next__field-heading"><label for="{id || name}">{label}</label>{#if cornerHint}<span class="wire-next__field-hint">{cornerHint}</span>{/if}</div>
      <div class="wire-next__picker-control"><input id="{id || name}" class="wire-next__sr-only wire-next__picker-value" type="text" name="{name}" value="{currentValue}" required="{required}" readonly aria-hidden="true" tabindex="-1" @invalid="handleInvalid(event)" /><button type="button" class="wire-next__date-trigger" disabled="{disabled || readonly}" aria-haspopup="dialog" aria-expanded="{expanded}" @click="openCalendar(event)" @focus="handleFocus(event)" @blur="handleBlur(event)"><span>{currentValue || placeholder || "Select date"}</span><i class="icon-[lucide--calendar-days]" aria-hidden="true"></i></button>{#if currentValue && !readonly && !disabled}<button type="button" class="wire-next__picker-clear" aria-label="Clear date" @click="clearDate(event)">×</button>{/if}</div>
      <div class="wire-next__calendar" role="dialog" aria-label="{label}"><div class="wire-next__date-selectors"><label>Month<select value="{selectedMonth}" @change="updateDate('month', event.currentTarget.value, event)">{#each months as month}<option value="{month.value}" selected="{month.value === selectedMonth}">{month.label}</option>{/each}</select></label><label>Year<select value="{selectedYear}" @change="updateDate('year', event.currentTarget.value, event)">{#each years as year}<option value="{year}" selected="{String(year) === selectedYear}">{year}</option>{/each}</select></label></div><div class="wire-next__calendar-grid">{#each days as day}<button type="button" data-value="{String(day).padStart(2, '0')}" aria-pressed="{String(day).padStart(2, '0') === selectedDay}" @click="selectDay(event)">{day}</button>{/each}</div><button type="button" class="wire-next__date-done" disabled="{!currentValue}" @click="finishDate(event)">Done</button></div>
      {#if helperText}<small class="wire-next__field-help">{helperText}</small>{/if}<small class="wire-next__field-error" data-error="{name}">{error}</small>
    </div>
  }
}
```

---

## DeviceFrame

Showcase: https://component.wrnexusjs.dev/
Mount: <DeviceFrame /> (legacy: data-component="DeviceFrame")
Category: base
Purpose: Theme-aware, responsive device frame component.
Props: size: string = "default", color: string = "primary", title: string = "Device Frame", description: string = "", items: string = [], variant: string = "default", device: string = "phone", orientation: string = "portrait", src: string = "", srcdoc: string = "", frameTitle: string = "Device preview", showToolbar: boolean = true, allow: string = "", class: string = ""
Slots: default
Events: change, rotate

### Complete .wrn source contract

```wrn
component DeviceFrame {
  props {
    @event change = function
    @event rotate = function
    size = "default"
    color = "primary"
    title = "Device Frame"
    description = ""
    items = []
    variant = "default"
    device = "phone"
    orientation = "portrait"
    src = ""
    srcdoc = ""
    frameTitle = "Device preview"
    showToolbar = true
    allow = ""
    class = ""
  }
  state currentOrientation = orientation
  functions {
    function setDevice(nextDevice, sourceEvent) { $emit("change", { device: nextDevice, orientation: currentOrientation, sourceEvent: sourceEvent }) }
    function rotateFrame(sourceEvent) { currentOrientation = currentOrientation === "portrait" ? "landscape" : "portrait"; $emit("rotate", { device: device, orientation: currentOrientation, sourceEvent: sourceEvent }); $emit("change", { device: device, orientation: currentOrientation, sourceEvent: sourceEvent }) }
  }
  view {
    <section {...attrs} class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--device-frame wire-next--variant-{variant} {class}" data-device="{device}" data-orientation="{currentOrientation}">
      <header><div>{#if title}<strong>{title}</strong>{/if}{#if description}<p>{description}</p>{/if}</div>{#if showToolbar}<div class="wire-next__device-actions" role="toolbar" aria-label="Preview device">{#each items as item}<button type="button" aria-pressed="{item.value === device}" @click="setDevice(item.value, event)">{item.label}</button>{/each}<button type="button" aria-label="Rotate preview" @click="rotateFrame(event)">↻</button></div>{/if}</header>
      <div class="wire-next__device-shell">{#if src || srcdoc}<iframe title="{frameTitle}" src="{src}" srcdoc="{srcdoc}" allow="{allow}"></iframe>{:else}<div class="wire-next__device-content"><slot /></div>{/if}</div>
    </section>
  }
}
```

---

## Divider

Showcase: https://component.wrnexusjs.dev/
Mount: <Divider /> (legacy: data-component="Divider")
Category: layout
Purpose: Theme-aware, responsive divider component.
Props: size: string = "default", color: string = "primary", label: string = "", orientation: string = "horizontal", class: string = ""
Slots: none
Events: none

### Complete .wrn source contract

```wrn
component Divider {
  props {
    size = "default"
    color = "primary"
    label = ""
    orientation = "horizontal"
    class = ""
  }

  view {
    <div
      {...attrs}
      data-ui-component="Divider"
      data-size='{size}'
      data-color='{color}'
      data-orientation='{orientation}'
      class='w-full {class}'
      class:h-full='orientation === "vertical"'
      class:w-auto='orientation === "vertical"'
    >
      {#if orientation === "vertical"}
        <div
          role="separator"
          aria-orientation="vertical"
          class="mx-3 h-full min-h-6 border-l border-[var(--wire-color-border)]"
          class:border-l-2='size === "lg"'
          class:border-[var(--wire-color-primary)]='color === "primary"'
          class:border-[var(--wire-color-secondary)]='color === "secondary"'
          class:border-[var(--wire-color-success)]='color === "success"'
          class:border-[var(--wire-color-warning)]='color === "warning"'
          class:border-[var(--wire-color-danger)]='color === "danger"'
        ></div>
      {:else}
        <div
          role="separator"
          aria-orientation="horizontal"
          class="flex w-full items-center gap-4"
        >
          <span
            class="h-px flex-1 bg-[var(--wire-color-border)]"
            class:h-0.5='size === "lg"'
            class:bg-[var(--wire-color-primary)]='color === "primary" && label !== ""'
            class:bg-[var(--wire-color-secondary)]='color === "secondary" && label !== ""'
            class:bg-[var(--wire-color-success)]='color === "success" && label !== ""'
            class:bg-[var(--wire-color-warning)]='color === "warning" && label !== ""'
            class:bg-[var(--wire-color-danger)]='color === "danger" && label !== ""'
            aria-hidden="true"
          ></span>

          {#if label}
            <span class="shrink-0 text-xs font-bold uppercase tracking-[0.16em] text-[var(--wire-color-text-muted)]">
              {label}
            </span>
            <span
              class="h-px flex-1 bg-[var(--wire-color-border)]"
              class:h-0.5='size === "lg"'
              class:bg-[var(--wire-color-primary)]='color === "primary"'
              class:bg-[var(--wire-color-secondary)]='color === "secondary"'
              class:bg-[var(--wire-color-success)]='color === "success"'
              class:bg-[var(--wire-color-warning)]='color === "warning"'
              class:bg-[var(--wire-color-danger)]='color === "danger"'
              aria-hidden="true"
            ></span>
          {/if}
        </div>
      {/if}
    </div>
  }
}
```

---

## DragAndDrop

Showcase: https://component.wrnexusjs.dev/
Mount: <DragAndDrop /> (legacy: data-component="DragAndDrop")
Category: integrations
Purpose: Theme-aware, responsive drag and drop component.
Props: size: string = "default", color: string = "primary", title: string = "Drag And Drop", description: string = "", items: string = [], variant: string = "default", class: string = ""
Slots: default
Events: dragStart, dragEnd, dragEnter, dragLeave, drop, change

### Complete .wrn source contract

```wrn
component DragAndDrop {
  props {
    @event dragStart = function
    @event dragEnd = function
    @event dragEnter = function
    @event dragLeave = function
    @event drop = function
    @event change = function
    size = "default"
    color = "primary"
    title = "Drag And Drop"
    description = ""
    items = []
    variant = "default"
    class = ""
  }
  view {
    <section class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--drag-and-drop wire-next--variant-{variant} {class}">
      {#if title}<strong>{title}</strong>{/if}
      {#if description}<p>{description}</p>{/if}
      {#if items}<div class="wire-next__items">{#each items as item}<span>{item.label}</span>{/each}</div>{/if}
      <slot />
    </section>
  }
}
```

---

## Drawer

Showcase: https://component.wrnexusjs.dev/
Mount: <Drawer /> (legacy: data-component="Drawer")
Category: overlays
Purpose: Theme-aware, responsive drawer component.
Props: size: string = "default", color: string = "primary", title: string = "Drawer", description: string = "", open: boolean = false, placement: string = "bottom", closeLabel: string = "Close", class: string = ""
Slots: default
Events: open, close

### Complete .wrn source contract

```wrn
component Drawer {
  props {
    @event open = function
    @event close = function
    size = "default"
    color = "primary"
    title = "Drawer"
    description = ""
    open = false
    placement = "bottom"
    closeLabel = "Close"
    class = ""
  }
  view {
    <div data-show="{open}" class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--drawer wire-next--placement-{placement} {class}" role="dialog" aria-modal="true" aria-label="{title}">
      <header><strong>{title}</strong><button type="button" aria-label="{closeLabel}">×</button></header>
      {#if description}<p>{description}</p>{/if}
      <slot />
    </div>
  }
}
```

---

## Dropdown

Showcase: https://component.wrnexusjs.dev/
Mount: <Dropdown /> (legacy: data-component="Dropdown")
Category: overlays
Purpose: Theme-aware, responsive dropdown component.
Props: size: string = "default", color: string = "primary", label: string = "Open menu", items: string = [], placement: string = "end", class: string = ""
Slots: trigger, header, footer
Events: toggle, open, close, select

### Complete .wrn source contract

```wrn
component Dropdown {
  props {
    @event toggle = function
    @event open = function
    @event close = function
    @event select = function
    size = "default"
    color = "primary"
    label = "Open menu"
    items = []
    placement = "end"
    class = ""
  }

  functions {
    function toggleMenu(event) {
      $emit("toggle", { open: event.currentTarget.open })
      $emit(event.currentTarget.open ? "open" : "close", { source: "trigger" })
    }

    function selectItem(item) {
      $emit("select", { item: item, value: item.value || "" })
    }
  }

  view {
    <details class="wire-dropdown wire-dropdown--{placement} wire-next--color-{color} wire-next--size-{size} {class}" data-wrn-dropdown @toggle="toggleMenu($event)">
      <summary aria-label="{label}">
        <slot name="trigger" />
        <span class="wire-dropdown__chevron icon-[lucide--chevron-down]" aria-hidden="true"></span>
      </summary>
      <div class="wire-dropdown__panel" role="menu" aria-label="{label}">
        <slot name="header" />
        {#each items as item}
          {#if item.type === "divider"}
            <hr />
          {:else}
            {#if item.type === "header"}
              <span class="wire-dropdown__heading">{item.label}</span>
            {:else}
              <a class="wire-dropdown__item {item.danger ? 'wire-dropdown__item--danger' : ''}" href="{item.href || '#'}" target="{item.target || ''}" rel="{item.rel || ''}" role="menuitem" @click="selectItem(item)">
                {#if item.icon}<span class="{item.icon}" aria-hidden="true"></span>{/if}
                <span><strong>{item.label}</strong>{#if item.description}<small>{item.description}</small>{/if}</span>
                {#if item.external}<span class="icon-[lucide--arrow-up-right]" aria-hidden="true"></span>{/if}
              </a>
            {/if}
          {/if}
        {/each}
        <slot name="footer" />
      </div>
    </details>
  }
}
```

---

## FeatureCard

Showcase: https://component.wrnexusjs.dev/
Mount: <FeatureCard /> (legacy: data-component="FeatureCard")
Category: blocks
Purpose: Reusable linked feature or service card with icon, badge, description, and action.
Props: icon: string = "", title: string = "Feature", description: string = "", href: string = "", actionLabel: string = "Learn more", actionIcon: string = "", badge: string = "", badgeColor: string = "primary", size: string = "default", color: string = "primary", variant: string = "default", hover: string = "lift", align: string = "left", disabled: boolean = false, class: string = ""
Slots: icon, default, footer
Events: none

### Complete .wrn source contract

```wrn
component FeatureCard {
  props {
    icon = ""
    title = "Feature"
    description = ""
    href = ""
    actionLabel = "Learn more"
    actionIcon = ""
    badge = ""
    badgeColor = "primary"
    size = "default"
    color = "primary"
    variant = "default"
    hover = "lift"
    align = "left"
    disabled = false
    class = ""
  }

  view {
    <article
      data-ui-component="FeatureCard"
      aria-disabled='{disabled}'
      class='group relative flex h-full min-w-0 flex-col overflow-hidden rounded-2xl border border-[var(--wire-color-border)] bg-[var(--wire-color-surface-raised)] shadow-sm transition duration-200 {class}'
      class:p-4='size === "sm"'
      class:p-6='size === "default" || size === "md"'
      class:p-8='size === "lg"'
      class:bg-[var(--wire-color-primary-soft)]='variant === "soft" && color === "primary"'
      class:bg-[var(--wire-color-success-soft)]='variant === "soft" && color === "success"'
      class:bg-[var(--wire-color-warning-soft)]='variant === "soft" && color === "warning"'
      class:bg-[var(--wire-color-danger-soft)]='variant === "soft" && color === "danger"'
      class:bg-transparent='variant === "ghost"'
      class:border-transparent='variant === "ghost"'
      class:shadow-none='variant === "ghost" || variant === "outline"'
      class:hover:-translate-y-1='hover === "lift" && !disabled'
      class:hover:shadow-xl='(hover === "lift" || hover === "shadow") && !disabled'
      class:hover:border-[var(--wire-color-primary)]='(hover === "lift" || hover === "border") && !disabled'
      class:text-center='align === "center"'
      class:items-center='align === "center"'
      class:text-right='align === "right"'
      class:items-end='align === "right"'
      class:opacity-60='disabled'
      class:pointer-events-none='disabled'
    >
      <div class="flex w-full items-start justify-between gap-4">
        <div
          class="flex size-12 shrink-0 items-center justify-center rounded-2xl bg-[var(--wire-color-primary-soft)] text-[var(--wire-color-primary)]"
          class:bg-[var(--wire-color-success-soft)]='color === "success"'
          class:text-[var(--wire-color-success)]='color === "success"'
          class:bg-[var(--wire-color-warning-soft)]='color === "warning"'
          class:text-[var(--wire-color-warning-text)]='color === "warning"'
          class:bg-[var(--wire-color-danger-soft)]='color === "danger"'
          class:text-[var(--wire-color-danger)]='color === "danger"'
          class:bg-[var(--wire-color-info-soft)]='color === "info"'
          class:text-[var(--wire-color-info)]='color === "info"'
          class:size-10='size === "sm"'
          class:size-14='size === "lg"'
        >
          <slot name="icon"></slot>
          {#if icon}
            <span class='{icon + " size-6"}' aria-hidden="true"></span>
          {/if}
        </div>

        {#if badge}
          <Badge
            label='{badge}'
            size="sm"
            color='{badgeColor}'
            variant="soft"
          />
        {/if}
      </div>

      <h3 class="mt-5 text-lg font-bold leading-tight text-[var(--wire-color-text)]" class:text-xl='size === "lg"'>
        {title}
      </h3>

      {#if description}
        <p class="mt-3 flex-1 text-sm leading-6 text-[var(--wire-color-text-muted)]" class:text-base='size === "lg"'>
          {description}
        </p>
      {/if}

      <slot></slot>

      <div class="mt-6 flex w-full items-center justify-between gap-3">
        <slot name="footer"></slot>

        {#if href && actionLabel}
          <TextLink
            label='{actionLabel}'
            href='{href}'
            icon='{actionIcon}'
            iconPosition="start"
            showArrow="true"
            size="sm"
            color='{color}'
            class="ml-auto"
          />
        {/if}
      </div>

      {#if href}
        <a
          href='{href}'
          aria-label='{title}'
          class="absolute inset-0 z-10 rounded-2xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--wire-color-focus)]"
        ></a>
      {/if}
    </article>
  }
}
```

---

## FeatureGrid

Showcase: https://component.wrnexusjs.dev/
Mount: <FeatureGrid /> (legacy: data-component="FeatureGrid")
Category: layout
Purpose: Responsive equal-height grid for feature and service cards.
Props: color: string = "primary", size: string = "default", columns: number = 3, tabletColumns: number = 2, mobileColumns: number = 1, gap: string = "md", minItemWidth: string = "", equalHeight: boolean = true, align: string = "stretch", maxWidth: string = "full", class: string = ""
Slots: default
Events: none

### Complete .wrn source contract

```wrn
component FeatureGrid {
  props {
    color = "primary"
    size = "default"
    columns = 3
    tabletColumns = 2
    mobileColumns = 1
    gap = "md"
    minItemWidth = ""
    equalHeight = true
    align = "stretch"
    maxWidth = "full"
    class = ""
  }

  view {
    <div
      data-ui-component="FeatureGrid"
      data-columns='{columns}'
      data-tablet-columns='{tabletColumns}'
      data-mobile-columns='{mobileColumns}'
      class='grid w-full {class}'
      class:wire-feature-grid-autofit='minItemWidth !== ""'
      class:grid-cols-1='mobileColumns === 1'
      class:grid-cols-2='mobileColumns === 2'
      class:sm:grid-cols-1='tabletColumns === 1'
      class:sm:grid-cols-2='tabletColumns === 2'
      class:sm:grid-cols-3='tabletColumns === 3'
      class:lg:grid-cols-2='columns === 2'
      class:lg:grid-cols-3='columns === 3'
      class:lg:grid-cols-4='columns === 4'
      class:lg:grid-cols-5='columns === 5'
      class:lg:grid-cols-6='columns === 6'
      class:gap-3='gap === "sm"'
      class:gap-5='gap === "md"'
      class:gap-8='gap === "lg"'
      class:gap-10='gap === "xl"'
      class:items-stretch='equalHeight || align === "stretch"'
      class:items-start='align === "start"'
      class:items-center='align === "center"'
      class:max-w-5xl='maxWidth === "lg"'
      class:max-w-7xl='maxWidth === "xl"'
      class:max-w-none='maxWidth === "full"'
      style='--wire-feature-grid-min: {minItemWidth || "16rem"};'
    >
      <slot></slot>
    </div>
  }

  style {
    .wire-feature-grid-autofit {
      grid-template-columns: repeat(auto-fit, minmax(var(--wire-feature-grid-min), 1fr));
    }
  }
}
```

---

## FeatureIconCard

Showcase: https://component.wrnexusjs.dev/
Mount: <FeatureIconCard /> (legacy: data-component="FeatureIconCard")
Category: blocks
Purpose: Feature card with a prominent themed icon treatment.
Props: icon: string = "icon-[lucide--sparkles]", iconSize: string = "md", iconVariant: string = "soft", title: string = "Feature", description: string = "", href: string = "", actionLabel: string = "Explore", badge: string = "", size: string = "default", color: string = "primary", variant: string = "default", align: string = "left", hover: string = "lift", class: string = ""
Slots: default, footer
Events: none

### Complete .wrn source contract

```wrn
component FeatureIconCard {
  props {
    icon = "icon-[lucide--sparkles]"
    iconSize = "md"
    iconVariant = "soft"
    title = "Feature"
    description = ""
    href = ""
    actionLabel = "Explore"
    badge = ""
    size = "default"
    color = "primary"
    variant = "default"
    align = "left"
    hover = "lift"
    class = ""
  }

  view {
    <article
      data-ui-component="FeatureIconCard"
      class='group relative flex h-full flex-col rounded-3xl border border-[var(--wire-color-border)] bg-[var(--wire-color-surface-raised)] p-6 shadow-sm transition duration-200 {class}'
      class:p-5='size === "sm"'
      class:p-8='size === "lg"'
      class:bg-[var(--wire-color-surface-soft)]='variant === "soft"'
      class:bg-transparent='variant === "ghost"'
      class:border-transparent='variant === "ghost"'
      class:shadow-none='variant === "ghost"'
      class:hover:-translate-y-1='hover === "lift"'
      class:hover:shadow-xl='hover === "lift" || hover === "shadow"'
      class:hover:border-[var(--wire-color-primary)]='hover === "lift" || hover === "border"'
      class:items-center='align === "center"'
      class:text-center='align === "center"'
    >
      <div
        class="relative flex size-14 items-center justify-center rounded-2xl bg-[var(--wire-color-primary-soft)] text-[var(--wire-color-primary)] ring-1 ring-inset ring-[var(--wire-color-primary-muted)]"
        class:size-12='iconSize === "sm"'
        class:size-16='iconSize === "lg"'
        class:bg-[var(--wire-color-primary)]='iconVariant === "solid" && color === "primary"'
        class:text-[var(--wire-color-on-primary)]='iconVariant === "solid" && color === "primary"'
        class:bg-[var(--wire-color-success-soft)]='color === "success" && iconVariant !== "solid"'
        class:text-[var(--wire-color-success)]='color === "success" && iconVariant !== "solid"'
        class:bg-[var(--wire-color-warning-soft)]='color === "warning" && iconVariant !== "solid"'
        class:text-[var(--wire-color-warning-text)]='color === "warning" && iconVariant !== "solid"'
        class:bg-[var(--wire-color-danger-soft)]='color === "danger" && iconVariant !== "solid"'
        class:text-[var(--wire-color-danger)]='color === "danger" && iconVariant !== "solid"'
      >
        <span class='{icon + " size-7"}' aria-hidden="true"></span>

        {#if badge}
          <span class="absolute -right-2 -top-2 rounded-full bg-[var(--wire-color-surface-raised)] px-2 py-1 text-[10px] font-bold uppercase tracking-wide text-[var(--wire-color-primary)] shadow-sm ring-1 ring-[var(--wire-color-border)]">
            {badge}
          </span>
        {/if}
      </div>

      <h3 class="mt-6 text-xl font-bold tracking-tight text-[var(--wire-color-text)]">{title}</h3>

      {#if description}
        <p class="mt-3 flex-1 text-sm leading-6 text-[var(--wire-color-text-muted)]">{description}</p>
      {/if}

      <slot></slot>

      {#if href}
        <TextLink
          label='{actionLabel}'
          href='{href}'
          color='{color}'
          size="sm"
          class="mt-6"
        />
      {/if}

      <slot name="footer"></slot>
    </article>
  }
}
```

---

## FileInput

Showcase: https://component.wrnexusjs.dev/
Mount: <FileInput /> (legacy: data-component="FileInput")
Category: forms
Purpose: Theme-aware, responsive file input component.
Props: size: string = "default", color: string = "primary", id: string = "", name: string = "", label: string = "File", hiddenLabel: boolean = false, placeholder: string = "Choose a file", value: string = "", icon: string = "icon-[lucide--upload]", iconPosition: string = "start", accept: string = "", multiple: boolean = false, helperText: string = "", cornerHint: string = "", error: string = "", inline: boolean = false, variant: string = "normal", readonly: boolean = false, disabled: boolean = false, required: boolean = false, class: string = ""
Slots: none
Events: input, change, focus, blur, select, clear, invalid

### Complete .wrn source contract

```wrn
component FileInput {
  props {
    @event input = function
    @event change = function
    @event focus = function
    @event blur = function
    @event select = function
    @event clear = function
    @event invalid = function
    size = "default"
    color = "primary"
    id = ""
    name = ""
    label = "File"
    hiddenLabel = false
    placeholder = "Choose a file"
    value = ""
    icon = "icon-[lucide--upload]"
    iconPosition = "start"
    accept = ""
    multiple = false
    helperText = ""
    cornerHint = ""
    error = ""
    inline = false
    variant = "normal"
    readonly = false
    disabled = false
    required = false
    class = ""
  }
  state selectedName = ""
  functions {
    function handleChange(sourceEvent) {
      sourceEvent.stopPropagation()
      selectedName = sourceEvent.currentTarget.files && sourceEvent.currentTarget.files.length ? sourceEvent.currentTarget.files[0].name : ""
      $emit("input", { files: sourceEvent.currentTarget.files, name: name, sourceEvent: sourceEvent })
      $emit("change", { files: sourceEvent.currentTarget.files, name: name, sourceEvent: sourceEvent })
      if (selectedName) $emit("select", { files: sourceEvent.currentTarget.files, name: name, sourceEvent: sourceEvent })
      else $emit("clear", { name: name, sourceEvent: sourceEvent })
    }
    function emitField(nameEvent, sourceEvent) { sourceEvent.stopPropagation(); $emit(nameEvent, { name: name, sourceEvent: sourceEvent }) }
    function preventReadonly(sourceEvent) { if (readonly) sourceEvent.preventDefault() }
  }
  view {
    <div {...attrs} class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--field wire-next--file-input {class}" data-variant="{variant}" data-inline="{inline}" data-invalid="{error ? 'true' : 'false'}">
      <div class="wire-next__field-heading"><label class="{hiddenLabel ? 'wire-next__sr-only' : ''}" for="{id || name}">{label}</label>{#if cornerHint}<span class="wire-next__field-hint">{cornerHint}</span>{/if}</div>
      <div class="wire-next__file-control" data-icon-position="{iconPosition}">{#if icon}<span class="{icon}" aria-hidden="true"></span>{/if}<span>{selectedName || value || placeholder}</span><input id="{id || name}" type="file" name="{name}" accept="{accept}" multiple="{multiple}" disabled="{disabled}" required="{required}" aria-readonly="{readonly}" aria-invalid="{error ? 'true' : 'false'}" @click="preventReadonly(event)" @input="handleChange(event)" @change="handleChange(event)" @focus="emitField('focus', event)" @blur="emitField('blur', event)" @invalid="emitField('invalid', event)" /></div>
      {#if helperText}<small class="wire-next__field-help">{helperText}</small>{/if}<small class="wire-next__field-error" data-error="{name}">{error}</small>
    </div>
  }
}
```

---

## FileUpload

Showcase: https://component.wrnexusjs.dev/
Mount: <FileUpload /> (legacy: data-component="FileUpload")
Category: integrations
Purpose: Theme-aware, responsive file upload component.
Props: size: string = "default", color: string = "primary", title: string = "File Upload", description: string = "", items: string = [], variant: string = "default", class: string = ""
Slots: default
Events: select, upload, progress, success, error, cancel, remove

### Complete .wrn source contract

```wrn
component FileUpload {
  props {
    @event select = function
    @event upload = function
    @event progress = function
    @event success = function
    @event error = function
    @event cancel = function
    @event remove = function
    size = "default"
    color = "primary"
    title = "File Upload"
    description = ""
    items = []
    variant = "default"
    class = ""
  }
  view {
    <section class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--file-upload wire-next--variant-{variant} {class}">
      {#if title}<strong>{title}</strong>{/if}
      {#if description}<p>{description}</p>{/if}
      {#if items}<div class="wire-next__items">{#each items as item}<span>{item.label}</span>{/each}</div>{/if}
      <slot />
    </section>
  }
}
```

---

## FileUploadProgress

Showcase: https://component.wrnexusjs.dev/
Mount: <FileUploadProgress /> (legacy: data-component="FileUploadProgress")
Category: base
Purpose: Theme-aware, responsive file upload progress component.
Props: size: string = "default", color: string = "primary", label: string = "Progress", value: number = 50, max: number = 100, showValue: boolean = true, fileName: string = "", fileSize: string = "", uploadedSize: string = "", status: string = "uploading", cancelLabel: string = "Cancel upload", retryLabel: string = "Retry upload", class: string = ""
Slots: none
Events: cancel, retry, complete

### Complete .wrn source contract

```wrn
component FileUploadProgress {
  props {
    @event cancel = function
    @event retry = function
    @event complete = function
    size = "default"
    color = "primary"
    label = "Progress"
    value = 50
    max = 100
    showValue = true
    fileName = ""
    fileSize = ""
    uploadedSize = ""
    status = "uploading"
    cancelLabel = "Cancel upload"
    retryLabel = "Retry upload"
    class = ""
  }
  state currentValue = value
  state currentStatus = status
  functions {
    function percent() { if (!Number(max)) { return 0 } return Math.max(0, Math.min(100, Math.round(Number(currentValue) / Number(max) * 100))) }
    function detail(sourceEvent) { return { value: currentValue, max: max, percent: percent(), status: currentStatus, fileName: fileName, sourceEvent: sourceEvent } }
    function cancelUpload(sourceEvent) { currentStatus = "cancelled"; $emit("cancel", detail(sourceEvent)) }
    function retryUpload(sourceEvent) { currentValue = 0; currentStatus = "uploading"; $emit("retry", detail(sourceEvent)) }
    function completeUpload(sourceEvent) { currentValue = max; currentStatus = "complete"; $emit("complete", detail(sourceEvent)) }
  }
  view {
    <div {...attrs} class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--file-upload-progress {class}" data-status="{currentStatus}" aria-live="polite">
      <div class="wire-next__row"><span>{#if fileName}<strong>{fileName}</strong><small>{#if uploadedSize || fileSize}{uploadedSize}{#if uploadedSize && fileSize} of {/if}{fileSize}{:else}{label}{/if}</small>{:else}<strong>{label}</strong>{/if}</span>{#if showValue}<strong>{percent()}%</strong>{/if}</div>
      <progress value="{currentValue}" max="{max}" aria-label="{label}"></progress>
      <div class="wire-next__upload-status"><span class="wire-next__upload-status-icon" aria-hidden="true"></span><span>{#if currentStatus === "uploading"}Uploading securely…{:else if currentStatus === "complete"}Upload complete{:else if currentStatus === "error"}Upload failed{:else}Upload cancelled{/if}</span></div>
      <div class="wire-next__upload-actions">{#if currentStatus === "uploading"}<button type="button" @click="cancelUpload(event)">{cancelLabel}</button><button type="button" @click="completeUpload(event)">Complete</button>{/if}{#if currentStatus === "error" || currentStatus === "cancelled"}<button type="button" @click="retryUpload(event)">{retryLabel}</button>{/if}</div>
    </div>
  }
}
```

---

## Footer

Showcase: https://component.wrnexusjs.dev/
Mount: <Footer /> (legacy: data-component="Footer")
Category: navigation
Purpose: Responsive application footer with structured links and pre/post content slots.
Props: size: string = "default", color: string = "primary", label: string = "Footer navigation", items: string = [], columns: number = 3, maxWidth: string = "compact", copyright: string = "", class: string = ""
Slots: pre-footer, post-footer, copyright-left, copyright-right
Events: select, action

### Complete .wrn source contract

```wrn
component Footer {
  props {
    @event select = function
    @event action = function

    size = "default"
    color = "primary"
    label = "Footer navigation"
    items = []
    columns = 3
    maxWidth = "compact"
    copyright = ""
    class = ""
  }

  view {
    <footer
      {...attrs}
      data-ui-component="Footer"
      data-size='{size}'
      data-color='{color}'
      class='wire-footer {maxWidth === "full" ? "wire-footer--width-full" : ""} {class}'
    >
      <div
        class="wire-footer__grid"
      >
        <div
          class="wire-footer__pre"
        >
          <slot
            name="pre-footer"
          >
          </slot>
        </div>

        {#if items.length > 0}
          <nav
            class='wire-footer__links wire-footer--columns-{columns}'
            aria-label='{label}'
          >
            {#each items as item, itemIndex}
              {#if item.type === "header"}
                <section
                  class="wire-footer__column"
                  aria-labelledby='footer-heading-{itemIndex}'
                >
                  {#if item.icon}
                    <span
                      class='{item.icon}'
                      aria-hidden="true"
                    >
                    </span>
                  {/if}

                  <h2
                    id='footer-heading-{itemIndex}'
                    class="wire-footer__heading"
                  >
                    {item.label || item.title}
                  </h2>

                  {#if item.description}
                    <p>
                      {item.description}
                    </p>
                  {/if}

                  {#if (item.items || item.links || []).length > 0}
                    <div
                      class="wire-footer__column-links"
                    >
                      {#each item.items || item.links || [] as child, childIndex}
                        <a
                          href='{child.href || "#"}'
                          target='{child.target || ""}'
                          rel='{child.external ? "noopener noreferrer" : (child.rel || "")}'
                          aria-current='{child.active ? "page" : ""}'
                          class="wire-footer__link"
                          @click='event.currentTarget.dispatchEvent(new CustomEvent("select", { bubbles: true, detail: { item: child, parent: item, itemIndex: childIndex, sectionIndex: itemIndex } })); child.action && event.currentTarget.dispatchEvent(new CustomEvent("action", { bubbles: true, detail: { item: child, parent: item, itemIndex: childIndex, sectionIndex: itemIndex } }))'
                        >
                          {#if child.icon}
                            <span
                              class='{child.icon}'
                              aria-hidden="true"
                            >
                            </span>
                          {/if}

                          <span>
                            {child.label || child.title}
                          </span>

                          {#if child.badge}
                            <span
                              class="wire-badge wire-badge--default"
                            >
                              {child.badge}
                            </span>
                          {/if}

                          {#if child.external}
                            <span
                              class="icon-[lucide--arrow-up-right]"
                              aria-hidden="true"
                            >
                            </span>
                          {/if}
                        </a>
                      {/each}
                    </div>
                  {/if}
                </section>

              {:else if item.type === "link" || item.href}
                <section
                  class="wire-footer__column"
                >
                  <div
                    class="wire-footer__column-links"
                  >
                    <a
                      href='{item.href || "#"}'
                      target='{item.target || ""}'
                      rel='{item.external ? "noopener noreferrer" : (item.rel || "")}'
                      aria-current='{item.active ? "page" : ""}'
                      class="wire-footer__link"
                      @click='event.currentTarget.dispatchEvent(new CustomEvent("select", { bubbles: true, detail: { item: item, itemIndex: itemIndex } })); item.action && event.currentTarget.dispatchEvent(new CustomEvent("action", { bubbles: true, detail: { item: item, itemIndex: itemIndex } }))'
                    >
                      {#if item.icon}
                        <span
                          class='{item.icon}'
                          aria-hidden="true"
                        >
                        </span>
                      {/if}

                      <span>
                        {item.label || item.title}
                      </span>

                      {#if item.badge}
                        <span
                          class="wire-badge wire-badge--default"
                        >
                          {item.badge}
                        </span>
                      {/if}

                      {#if item.external}
                        <span
                          class="icon-[lucide--arrow-up-right]"
                          aria-hidden="true"
                        >
                        </span>
                      {/if}
                    </a>
                  </div>
                </section>

              {:else}
                <section
                  class="wire-footer__column"
                  aria-labelledby='footer-heading-{itemIndex}'
                >
                  {#if item.icon}
                    <span
                      class='{item.icon}'
                      aria-hidden="true"
                    >
                    </span>
                  {/if}

                  {#if item.title || item.label}
                    <h2
                      id='footer-heading-{itemIndex}'
                      class="wire-footer__heading"
                    >
                      {item.title || item.label}
                    </h2>
                  {/if}

                  {#if item.description}
                    <p>
                      {item.description}
                    </p>
                  {/if}

                  {#if (item.items || item.links || []).length > 0}
                    <div
                      class="wire-footer__column-links"
                    >
                      {#each item.items || item.links || [] as child, childIndex}
                        <a
                          href='{child.href || "#"}'
                          target='{child.target || ""}'
                          rel='{child.external ? "noopener noreferrer" : (child.rel || "")}'
                          aria-current='{child.active ? "page" : ""}'
                          class="wire-footer__link"
                          @click='event.currentTarget.dispatchEvent(new CustomEvent("select", { bubbles: true, detail: { item: child, parent: item, itemIndex: childIndex, sectionIndex: itemIndex } })); child.action && event.currentTarget.dispatchEvent(new CustomEvent("action", { bubbles: true, detail: { item: child, parent: item, itemIndex: childIndex, sectionIndex: itemIndex } }))'
                        >
                          {#if child.icon}
                            <span
                              class='{child.icon}'
                              aria-hidden="true"
                            >
                            </span>
                          {/if}

                          <span>
                            {child.label || child.title}
                          </span>

                          {#if child.badge}
                            <span
                              class="wire-badge wire-badge--default"
                            >
                              {child.badge}
                            </span>
                          {/if}

                          {#if child.external}
                            <span
                              class="icon-[lucide--arrow-up-right]"
                              aria-hidden="true"
                            >
                            </span>
                          {/if}
                        </a>
                      {/each}
                    </div>
                  {/if}
                </section>
              {/if}
            {/each}
          </nav>
        {/if}

        <div
          class="wire-footer__post"
        >
          <slot
            name="post-footer"
          >
          </slot>
        </div>
      </div>

      <div
        class="wire-footer__bottom wire-footer__bottom--slots"
      >
        <div
          class="wire-footer__copyright-left"
        >
          <slot
            name="copyright-left"
          >
          </slot>
        </div>

        <div
          class="wire-footer__copyright-right"
        >
          <slot
            name="copyright-right"
          >
          </slot>
        </div>
      </div>

      {#if copyright}
        <div
          class="wire-footer__bottom"
        >
          <div></div>
          <p class="wire-footer__copyright">
            {copyright}
          </p>
          <div></div>
        </div>
      {/if}
    </footer>
  }
}
```

---

## Grid

Showcase: https://component.wrnexusjs.dev/
Mount: <Grid /> (legacy: data-component="Grid")
Category: layout
Purpose: Theme-aware, responsive grid component.
Props: size: string = "default", color: string = "primary", columns: number = 2, gap: string = "md", maxWidth: string = "xl", class: string = ""
Slots: default
Events: none

### Complete .wrn source contract

```wrn
component Grid {
  props {
    size = "default"
    color = "primary"
    columns = 2
    gap = "md"
    maxWidth = "xl"
    class = ""
  }

  view {
    <div
      data-ui-component="Grid"
      data-size='{size}'
      data-color='{color}'
      data-columns='{columns}'
      data-gap='{gap}'
      class='grid w-full grid-cols-1 {class}'
      class:max-w-3xl='maxWidth === "md"'
      class:max-w-5xl='maxWidth === "lg"'
      class:max-w-7xl='maxWidth === "xl"'
      class:max-w-screen-2xl='maxWidth === "2xl"'
      class:max-w-none='maxWidth === "full"'
      class:sm:grid-cols-2='columns >= 2'
      class:lg:grid-cols-3='columns === 3'
      class:lg:grid-cols-4='columns === 4'
      class:lg:grid-cols-5='columns === 5'
      class:lg:grid-cols-6='columns === 6'
      class:gap-2='gap === "xs"'
      class:gap-3='gap === "sm"'
      class:gap-5='gap === "md"'
      class:gap-8='gap === "lg"'
      class:gap-10='gap === "xl"'
      class:items-start='size === "compact"'
      class:items-stretch='size !== "compact"'
    >
      <slot></slot>
    </div>
  }
}
```

---

## Hero

Showcase: https://component.wrnexusjs.dev/
Mount: <Hero /> (legacy: data-component="Hero")
Category: blocks
Purpose: Reusable public-page hero with actions, trust items, badges, and visual slots.
Props: eyebrow: string = "", title: string = "Build something remarkable", highlight: string = "", description: string = "", align: string = "left", size: string = "default", color: string = "primary", variant: string = "default", primaryLabel: string = "", primaryHref: string = "", primaryIcon: string = "", secondaryLabel: string = "", secondaryHref: string = "", secondaryIcon: string = "", tertiaryLabel: string = "", tertiaryHref: string = "", badges: string = [], trustItems: string = [], maxWidth: string = "xl", class: string = ""
Slots: eyebrow, actions, trust, default, visual, footer
Events: none

### Complete .wrn source contract

```wrn
component Hero {
  props {
    eyebrow = ""
    title = "Build something remarkable"
    highlight = ""
    description = ""
    align = "left"
    size = "default"
    color = "primary"
    variant = "default"
    primaryLabel = ""
    primaryHref = ""
    primaryIcon = ""
    secondaryLabel = ""
    secondaryHref = ""
    secondaryIcon = ""
    tertiaryLabel = ""
    tertiaryHref = ""
    badges = []
    trustItems = []
    maxWidth = "xl"
    class = ""
  }

  view {
    <Section
      spacing='{size === "compact" ? "md" : (size === "large" ? "xl" : "lg")}'
      maxWidth='{maxWidth}'
      variant='{variant === "solid" ? "solid" : (variant === "soft" ? "soft" : "default")}'
      color='{color}'
      class='overflow-hidden {class}'
    >
      <div
        data-ui-component="Hero"
        class="relative isolate"
        class:text-center='align === "center"'
      >
        {#if variant === "gradient"}
          <div
            class="pointer-events-none absolute inset-0 -z-10 rounded-[2rem] opacity-80"
            style="background: radial-gradient(circle at 15% 20%, var(--wire-color-primary-muted), transparent 35%), radial-gradient(circle at 85% 75%, var(--wire-color-secondary-muted), transparent 36%);"
            aria-hidden="true"
          ></div>
        {/if}

        <div
          class="max-w-4xl"
          class:mx-auto='align === "center"'
          class:ml-auto='align === "right"'
        >
          <slot name="eyebrow"></slot>

          {#if eyebrow}
            <div
              class="mb-6 inline-flex items-center gap-2 rounded-full border border-[var(--wire-color-primary-muted)] bg-[var(--wire-color-primary-soft)] px-4 py-2 text-sm font-semibold text-[var(--wire-color-primary)]"
            >
              <span class="size-2 rounded-full bg-[var(--wire-color-primary)]" aria-hidden="true"></span>
              <span>{eyebrow}</span>
            </div>
          {/if}

          <h1
            class="font-bold leading-[1.06] tracking-[-0.04em]"
            class:text-4xl='size === "compact"'
            class:sm:text-5xl='size === "compact"'
            class:text-5xl='size === "default"'
            class:sm:text-6xl='size === "default"'
            class:lg:text-7xl='size === "default" || size === "large"'
            class:text-[var(--wire-color-text)]='variant !== "solid"'
          >
            <span>{title}</span>
            {#if highlight}
              <span class="block bg-gradient-to-r from-[var(--wire-color-primary)] to-[var(--wire-color-secondary)] bg-clip-text text-transparent">
                {highlight}
              </span>
            {/if}
          </h1>

          {#if description}
            <p
              class="mt-6 max-w-3xl text-base leading-8 text-[var(--wire-color-text-muted)] sm:text-lg"
              class:mx-auto='align === "center"'
              class:ml-auto='align === "right"'
              class:text-[var(--wire-color-on-primary)]='variant === "solid"'
              class:opacity-85='variant === "solid"'
            >
              {description}
            </p>
          {/if}

          {#if badges.length > 0}
            <div class="mt-6 flex flex-wrap gap-2" class:justify-center='align === "center"' class:justify-end='align === "right"'>
              {#each badges as badge}
                <Badge
                  label='{badge.label || badge.title || badge}'
                  icon='{badge.icon || ""}'
                  color='{badge.color || color}'
                  variant='{badge.variant || "soft"}'
                  size='{badge.size || "sm"}'
                />
              {/each}
            </div>
          {/if}

          <div class="mt-8">
            <HeroActions
              actions='{[
                { label: primaryLabel, href: primaryHref, icon: primaryIcon, variant: "default", color: color },
                { label: secondaryLabel, href: secondaryHref, icon: secondaryIcon, variant: "outline", color: color },
                { label: tertiaryLabel, href: tertiaryHref, variant: "ghost", color: color }
              ]}'
              align='{align}'
              stackOnMobile="true"
              fullWidthMobile="true"
              size='{size === "compact" ? "default" : "lg"}'
              color='{color}'
            >
              <slot name="actions"></slot>
            </HeroActions>
          </div>

          {#if trustItems.length > 0}
            <div
              class="mt-8 flex flex-wrap items-center gap-x-6 gap-y-3 text-sm text-[var(--wire-color-text-muted)]"
              class:justify-center='align === "center"'
              class:justify-end='align === "right"'
            >
              {#each trustItems as item}
                <span class="inline-flex items-center gap-2">
                  <span class='{(item.icon || "icon-[lucide--check-circle-2]") + " size-4 text-[var(--wire-color-primary)]"}' aria-hidden="true"></span>
                  <span>{item.label || item.title || item}</span>
                </span>
              {/each}
            </div>
          {/if}

          <slot name="trust"></slot>
          <slot></slot>
        </div>

        <div class="mt-10">
          <slot name="visual"></slot>
        </div>

        <slot name="footer"></slot>
      </div>
    </Section>
  }
}
```

---

## HeroActions

Showcase: https://component.wrnexusjs.dev/
Mount: <HeroActions /> (legacy: data-component="HeroActions")
Category: base
Purpose: Responsive action group for hero and call-to-action sections.
Props: actions: string = [], align: string = "left", orientation: string = "horizontal", stackOnMobile: boolean = true, fullWidthMobile: boolean = true, size: string = "default", color: string = "primary", class: string = ""
Slots: default
Events: none

### Complete .wrn source contract

```wrn
component HeroActions {
  props {
    actions = []
    align = "left"
    orientation = "horizontal"
    stackOnMobile = true
    fullWidthMobile = true
    size = "default"
    color = "primary"
    class = ""
  }

  view {
    <div
      data-ui-component="HeroActions"
      role="group"
      aria-label="Page actions"
      class='flex flex-wrap items-center gap-3 {class}'
      class:flex-col='orientation === "vertical" || stackOnMobile'
      class:sm:flex-row='orientation === "horizontal" && stackOnMobile'
      class:justify-center='align === "center"'
      class:justify-end='align === "right"'
      class:w-full='fullWidthMobile'
      class:sm:w-auto='fullWidthMobile'
    >
      {#each actions as action, index}
        {#if action.label}
          <Button
            label='{action.label}'
            href='{action.href || ""}'
            target='{action.target || ""}'
            rel='{action.rel || ""}'
            type='{action.type || "button"}'
            variant='{action.variant || (index === 0 ? "default" : "outline")}'
            color='{action.color || color}'
            size='{action.size || size}'
            disabled='{action.disabled || false}'
            loading='{action.loading || false}'
            icon='{action.icon || ""}'
            iconPosition='{action.iconPosition || "start"}'
            ariaLabel='{action.ariaLabel || action.label}'
            fullWidth='{fullWidthMobile}'
            controlClass='{action.controlClass || ""}'
            class='{"sm:w-auto " + (action.class || "")}'
          />
        {/if}
      {/each}

      <slot></slot>
    </div>
  }
}
```

---

## Image

Showcase: https://component.wrnexusjs.dev/
Mount: <Image /> (legacy: data-component="Image")
Category: layout
Purpose: Theme-aware, responsive image component.
Props: size: string = "default", color: string = "primary", src: string = "", alt: string = "", width: string = "", height: string = "", loading: string = "lazy", rounded: boolean = false, class: string = ""
Slots: default
Events: none

### Complete .wrn source contract

```wrn
component Image {
  props {
    size = "default"
    color = "primary"
    src = ""
    alt = ""
    width = ""
    height = ""
    loading = "lazy"
    rounded = false
    class = ""
  }

  view {
    <figure
      data-ui-component="Image"
      class='relative m-0 overflow-hidden bg-[var(--wire-color-surface-soft)] {class}'
      class:rounded-2xl='rounded'
    >
      {#if src}
        <img
          src='{src}'
          alt='{alt}'
          width='{width}'
          height='{height}'
          loading='{loading}'
          decoding="async"
          class="block h-auto w-full object-cover transition duration-300"
          class:aspect-square='size === "square"'
          class:aspect-video='size === "video"'
          class:aspect-[4/3]='size === "landscape"'
          class:aspect-[3/4]='size === "portrait"'
        />
      {:else}
        <div
          class="flex min-h-48 w-full items-center justify-center text-[var(--wire-color-text-muted)]"
          role="img"
          aria-label='{alt || "Image placeholder"}'
        >
          <span class="icon-[lucide--image] size-8" aria-hidden="true"></span>
        </div>
      {/if}

      <slot></slot>
    </figure>
  }
}
```

---

## Input

Showcase: https://component.wrnexusjs.dev/
Mount: <Input /> (legacy: data-component="Input")
Category: forms
Purpose: Theme-aware, responsive input component.
Props: size: string = "default", color: string = "primary", id: string = "", name: string = "", label: string = "Input", hiddenLabel: boolean = false, placeholder: string = "", value: string = "", type: string = "text", variant: string = "normal", icon: string = "", iconPosition: string = "start", helperText: string = "", cornerHint: string = "", error: string = "", inline: boolean = false, readonly: boolean = false, disabled: boolean = false, required: boolean = false, autocomplete: string = "", inputmode: string = "", minlength: string = "", maxlength: string = "", pattern: string = "", min: string = "", max: string = "", step: string = "", class: string = ""
Slots: none
Events: input, change, focus, blur, invalid, keydown, keyup

### Complete .wrn source contract

```wrn
component Input {
  props {
    @event input = function
    @event change = function
    @event focus = function
    @event blur = function
    @event invalid = function
    @event keydown = function
    @event keyup = function
    size = "default"
    color = "primary"
    id = ""
    name = ""
    label = "Input"
    hiddenLabel = false
    placeholder = ""
    value = ""
    type = "text"
    variant = "normal"
    icon = ""
    iconPosition = "start"
    helperText = ""
    cornerHint = ""
    error = ""
    inline = false
    readonly = false
    disabled = false
    required = false
    autocomplete = ""
    inputmode = ""
    minlength = ""
    maxlength = ""
    pattern = ""
    min = ""
    max = ""
    step = ""
    class = ""
  }
  functions {
    function detail(sourceEvent) {
      return { value: sourceEvent.currentTarget.value, name: name, sourceEvent: sourceEvent }
    }
    function handleInput(sourceEvent) { sourceEvent.stopPropagation(); $emit("input", detail(sourceEvent)) }
    function handleChange(sourceEvent) { sourceEvent.stopPropagation(); $emit("change", detail(sourceEvent)) }
    function handleFocus(sourceEvent) { sourceEvent.stopPropagation(); $emit("focus", detail(sourceEvent)) }
    function handleBlur(sourceEvent) { sourceEvent.stopPropagation(); $emit("blur", detail(sourceEvent)) }
    function handleInvalid(sourceEvent) { sourceEvent.stopPropagation(); $emit("invalid", { value: sourceEvent.currentTarget.value, name: name, message: sourceEvent.currentTarget.validationMessage, sourceEvent: sourceEvent }) }
    function handleKeydown(sourceEvent) { sourceEvent.stopPropagation(); $emit("keydown", { key: sourceEvent.key, value: sourceEvent.currentTarget.value, name: name, sourceEvent: sourceEvent }) }
    function handleKeyup(sourceEvent) { sourceEvent.stopPropagation(); $emit("keyup", { key: sourceEvent.key, value: sourceEvent.currentTarget.value, name: name, sourceEvent: sourceEvent }) }
  }
  view {
    <div {...attrs} class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--field wire-next--input {class}" data-variant="{variant}" data-inline="{inline}" data-floating="{variant === 'floating'}" data-invalid="{error ? 'true' : 'false'}">
      <div class="wire-next__field-heading">
        <label class="{hiddenLabel ? 'wire-next__sr-only' : ''}" for="{id || name}">{label}</label>
        {#if cornerHint}<span class="wire-next__field-hint">{cornerHint}</span>{/if}
      </div>
      <div class="wire-next__field-control" data-icon-position="{iconPosition}">
        {#if icon}<span class="{icon} wire-next__field-icon" aria-hidden="true"></span>{/if}
        <input
          id="{id || name}"
          type="{type}"
          name="{name}"
          value="{value}"
          placeholder="{variant === 'floating' ? ' ' : placeholder}"
          readonly="{readonly}"
          disabled="{disabled}"
          required="{required}"
          autocomplete="{autocomplete}"
          inputmode="{inputmode}"
          minlength="{minlength}"
          maxlength="{maxlength}"
          pattern="{pattern}"
          min="{min}"
          max="{max}"
          step="{step}"
          aria-invalid="{error ? 'true' : 'false'}"
          aria-describedby="{error ? (id || name) + '-error' : (helperText ? (id || name) + '-help' : '')}"
          @input="handleInput(event)"
          @change="handleChange(event)"
          @focus="handleFocus(event)"
          @blur="handleBlur(event)"
          @invalid="handleInvalid(event)"
          @keydown="handleKeydown(event)"
          @keyup="handleKeyup(event)"
        />
        {#if variant === "floating"}<span class="wire-next__field-floating-label">{label}</span>{/if}
      </div>
      {#if helperText}<small id="{(id || name) + '-help'}" class="wire-next__field-help">{helperText}</small>{/if}
      <small id="{(id || name) + '-error'}" class="wire-next__field-error" data-error="{name}">{error}</small>
    </div>
  }
}
```

---

## InputGroup

Showcase: https://component.wrnexusjs.dev/
Mount: <InputGroup /> (legacy: data-component="InputGroup")
Category: forms
Purpose: Theme-aware, responsive input group component.
Props: size: string = "default", color: string = "primary", id: string = "", name: string = "", label: string = "Input group", hiddenLabel: boolean = false, value: string = "", placeholder: string = "", type: string = "text", startText: string = "", endText: string = "", icon: string = "", iconPosition: string = "start", actionLabel: string = "", helperText: string = "", cornerHint: string = "", error: string = "", inline: boolean = false, variant: string = "normal", readonly: boolean = false, disabled: boolean = false, required: boolean = false, class: string = ""
Slots: none
Events: input, change, focus, blur, submit, action

### Complete .wrn source contract

```wrn
component InputGroup {
  props {
    @event input = function
    @event change = function
    @event focus = function
    @event blur = function
    @event submit = function
    @event action = function
    size = "default"
    color = "primary"
    id = ""
    name = ""
    label = "Input group"
    hiddenLabel = false
    value = ""
    placeholder = ""
    type = "text"
    startText = ""
    endText = ""
    icon = ""
    iconPosition = "start"
    actionLabel = ""
    helperText = ""
    cornerHint = ""
    error = ""
    inline = false
    variant = "normal"
    readonly = false
    disabled = false
    required = false
    class = ""
  }
  functions {
    function emitField(nameEvent, sourceEvent) { sourceEvent.stopPropagation(); $emit(nameEvent, { value: sourceEvent.currentTarget.value, name: name, sourceEvent: sourceEvent }) }
    function handleKeydown(sourceEvent) { if (sourceEvent.key === "Enter") { sourceEvent.stopPropagation(); $emit("submit", { value: sourceEvent.currentTarget.value, name: name, sourceEvent: sourceEvent }) } }
    function handleAction(sourceEvent) { $emit("action", { name: name, sourceEvent: sourceEvent }) }
  }
  view {
    <div {...attrs} class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--field wire-next--input-group {class}" data-variant="{variant}" data-inline="{inline}" data-invalid="{error ? 'true' : 'false'}">
      <div class="wire-next__field-heading"><label class="{hiddenLabel ? 'wire-next__sr-only' : ''}" for="{id || name}">{label}</label>{#if cornerHint}<span class="wire-next__field-hint">{cornerHint}</span>{/if}</div>
      <div class="wire-next__input-group-control">
        {#if startText}<span class="wire-next__input-addon">{startText}</span>{/if}
        {#if icon}<span class="{icon} wire-next__field-icon" data-position="{iconPosition}" aria-hidden="true"></span>{/if}
        <input id="{id || name}" type="{type}" name="{name}" value="{value}" placeholder="{placeholder}" readonly="{readonly}" disabled="{disabled}" required="{required}" aria-invalid="{error ? 'true' : 'false'}" @input="emitField('input', event)" @change="emitField('change', event)" @focus="emitField('focus', event)" @blur="emitField('blur', event)" @keydown="handleKeydown(event)" />
        {#if endText}<span class="wire-next__input-addon">{endText}</span>{/if}
        {#if actionLabel}<button type="button" disabled="{disabled}" @click="handleAction(event)">{actionLabel}</button>{/if}
      </div>
      {#if helperText}<small class="wire-next__field-help">{helperText}</small>{/if}<small class="wire-next__field-error" data-error="{name}">{error}</small>
    </div>
  }
}
```

---

## InputNumber

Showcase: https://component.wrnexusjs.dev/
Mount: <InputNumber /> (legacy: data-component="InputNumber")
Category: advanced-forms
Purpose: Theme-aware, responsive input number component.
Props: size: string = "default", color: string = "primary", variant: string = "default", class: string = "", id: string = "", name: string = "quantity", value: number = 0, min: string = "", max: string = "", step: number = 1, precision: string = "auto", label: string = "", description: string = "", helpText: string = "", error: string = "", invalid: boolean = false, prefix: string = "", suffix: string = "", placeholder: string = "", autocomplete: string = "off", inputMode: string = "decimal", ariaLabel: string = "", required: boolean = false, disabled: boolean = false, inputDisabled: boolean = false, buttonsDisabled: boolean = false, readonly: boolean = false, allowInput: boolean = true, keyboard: boolean = true, wheel: boolean = false, clamp: boolean = true, fullWidth: boolean = false, showButtons: boolean = true, showValidationMessage: boolean = true, decrementLabel: string = "Decrease value", incrementLabel: string = "Increase value", controlsLabel: string = "Quantity controls", requiredMessage: string = "A value is required.", minMessage: string = "Value is below the minimum.", maxMessage: string = "Value is above the maximum."
Slots: none
Events: input, change, increment, decrement

### Complete .wrn source contract

```wrn
component InputNumber {
    props {
        size = "default"
        color = "primary"
        variant = "default"
        class = ""

        id = ""
        name = "quantity"
        value = 0
        min = ""
        max = ""
        step = 1
        precision = "auto"

        label = ""
        description = ""
        helpText = ""
        error = ""
        invalid = false

        prefix = ""
        suffix = ""
        placeholder = ""
        autocomplete = "off"
        inputMode = "decimal"
        ariaLabel = ""

        required = false
        disabled = false
        inputDisabled = false
        buttonsDisabled = false
        readonly = false
        allowInput = true
        keyboard = true
        wheel = false
        clamp = true
        fullWidth = false
        showButtons = true
        showValidationMessage = true

        decrementLabel = "Decrease value"
        incrementLabel = "Increase value"
        controlsLabel = "Quantity controls"
        requiredMessage = "A value is required."
        minMessage = "Value is below the minimum."
        maxMessage = "Value is above the maximum."

        @event input = function
        @event change = function
        @event increment = function
        @event decrement = function
    }

    state currentValue = value
    state committedValue = value

    functions {
        function inputId() {
            if (id !== "") {
                return id
            }

            if (name !== "") {
                return name
            }

            return "input-number"
        }

        function descriptionId() {
            return inputId() + "-description"
        }

        function messageId() {
            return inputId() + "-message"
        }

        function componentColor() {
            if (color === "secondary") {
                return "var(--wire-color-secondary)"
            }

            if (color === "success") {
                return "var(--wire-color-success)"
            }

            if (color === "warning") {
                return "var(--wire-color-warning)"
            }

            if (color === "danger") {
                return "var(--wire-color-danger)"
            }

            if (color === "info") {
                return "var(--wire-color-info)"
            }

            return "var(--wire-color-primary)"
        }

        function hasMin() {
            return min !== "" && min !== null && min !== undefined
        }

        function hasMax() {
            return max !== "" && max !== null && max !== undefined
        }

        function isBlank() {
            return currentValue === "" || currentValue === null || currentValue === undefined
        }

        function normalizedStep() {
            return Number(step) > 0 ? Number(step) : 1
        }

        function inferredPrecision() {
            if (precision !== "auto" && precision !== "") {
                return Math.max(0, Number(precision) || 0)
            }

            if (String(normalizedStep()).includes(".")) {
                return String(normalizedStep()).split(".")[1].length
            }

            return 0
        }

        function precisionFactor() {
            return Math.pow(10, inferredPrecision())
        }

        function roundValue(nextValue) {
            return Math.round(Number(nextValue) * precisionFactor()) / precisionFactor()
        }

        function clampValue(nextValue) {
            nextValue = Number(nextValue)

            if (hasMin() && nextValue < Number(min)) {
                nextValue = Number(min)
            }

            if (hasMax() && nextValue > Number(max)) {
                nextValue = Number(max)
            }

            return roundValue(nextValue)
        }

        function isBelowMin() {
            return !isBlank() && hasMin() && Number(currentValue) < Number(min)
        }

        function isAboveMax() {
            return !isBlank() && hasMax() && Number(currentValue) > Number(max)
        }

        function isInvalid() {
            return (
                invalid ||
                error !== "" ||
                (required && isBlank()) ||
                isBelowMin() ||
                isAboveMax()
            )
        }

        function validationMessage() {
            if (error !== "") {
                return error
            }

            if (required && isBlank()) {
                return requiredMessage
            }

            if (isBelowMin()) {
                return minMessage
            }

            if (isAboveMax()) {
                return maxMessage
            }

            return ""
        }

        function hasMessage() {
            return (
                helpText !== "" ||
                (showValidationMessage && isInvalid() && validationMessage() !== "")
            )
        }

        function describedBy() {
            if (description !== "" && hasMessage()) {
                return descriptionId() + " " + messageId()
            }

            if (description !== "") {
                return descriptionId()
            }

            if (hasMessage()) {
                return messageId()
            }

            return ""
        }

        function decrementDisabled() {
            return (
                disabled ||
                readonly ||
                buttonsDisabled ||
                (hasMin() && !isBlank() && Number(currentValue) <= Number(min))
            )
        }

        function incrementDisabled() {
            return (
                disabled ||
                readonly ||
                buttonsDisabled ||
                (hasMax() && !isBlank() && Number(currentValue) >= Number(max))
            )
        }

        function dispatchInputNumberEvent(
            sourceEvent,
            eventName,
            action,
            previousValue,
            root,
            customEvent
        ) {
            root = sourceEvent.currentTarget.closest("[data-wrn-input-number]")

            if (!root && sourceEvent.target) {
                root = sourceEvent.target.closest("[data-wrn-input-number]")
            }

            if (!root) {
                return
            }

            customEvent = document.createEvent("CustomEvent")
            customEvent.initCustomEvent(eventName, true, false, {
                component: "InputNumber",
                name: name,
                value: currentValue,
                previousValue: previousValue,
                action: action,
                min: hasMin() ? Number(min) : null,
                max: hasMax() ? Number(max) : null,
                step: normalizedStep(),
                valid: !isInvalid()
            })
            root.dispatchEvent(customEvent)
        }

        function applyControlValue(nextValue, action, sourceEvent, previousValue) {
            previousValue = currentValue
            currentValue = clampValue(nextValue)
            committedValue = currentValue

            dispatchInputNumberEvent(
                sourceEvent,
                "input",
                action,
                previousValue
            )
            dispatchInputNumberEvent(
                sourceEvent,
                "change",
                action,
                previousValue
            )
            dispatchInputNumberEvent(
                sourceEvent,
                action,
                action,
                previousValue
            )
        }

        function incrementValue(sourceEvent, nextValue) {
            if (incrementDisabled()) {
                return
            }

            if (isBlank()) {
                nextValue = hasMin() ? Number(min) : normalizedStep()
            } else {
                nextValue =
                    Number(currentValue) +
                    normalizedStep() * (sourceEvent.shiftKey ? 10 : 1)
            }

            applyControlValue(nextValue, "increment", sourceEvent)
        }

        function decrementValue(sourceEvent, nextValue) {
            if (decrementDisabled()) {
                return
            }

            if (isBlank()) {
                nextValue = hasMax() ? Number(max) : -normalizedStep()
            } else {
                nextValue =
                    Number(currentValue) -
                    normalizedStep() * (sourceEvent.shiftKey ? 10 : 1)
            }

            applyControlValue(nextValue, "decrement", sourceEvent)
        }

        function handleInput(sourceEvent, previousValue, nextValue) {
            sourceEvent.stopPropagation()
            previousValue = currentValue
            nextValue = sourceEvent.target.value

            if (nextValue === "") {
                currentValue = ""
            } else if (!Number.isNaN(Number(nextValue))) {
                currentValue = roundValue(Number(nextValue))
            }

            dispatchInputNumberEvent(
                sourceEvent,
                "input",
                "input",
                previousValue
            )
        }

        function handleChange(sourceEvent, previousValue) {
            sourceEvent.stopPropagation()
            previousValue = committedValue

            if (!isBlank()) {
                currentValue = clamp
                    ? clampValue(currentValue)
                    : roundValue(currentValue)
            }

            committedValue = currentValue

            dispatchInputNumberEvent(
                sourceEvent,
                "change",
                "change",
                previousValue
            )
        }

        function handleKeydown(sourceEvent) {
            if (
                !keyboard ||
                disabled ||
                readonly ||
                inputDisabled ||
                !allowInput
            ) {
                return
            }

            if (sourceEvent.key === "ArrowUp") {
                sourceEvent.preventDefault()
                incrementValue(sourceEvent)
            } else if (sourceEvent.key === "ArrowDown") {
                sourceEvent.preventDefault()
                decrementValue(sourceEvent)
            } else if (sourceEvent.key === "Home" && hasMin()) {
                sourceEvent.preventDefault()
                applyControlValue(Number(min), "decrement", sourceEvent)
            } else if (sourceEvent.key === "End" && hasMax()) {
                sourceEvent.preventDefault()
                applyControlValue(Number(max), "increment", sourceEvent)
            }
        }

        function handleWheel(sourceEvent) {
            if (
                !wheel ||
                disabled ||
                readonly ||
                inputDisabled ||
                !allowInput
            ) {
                return
            }

            sourceEvent.preventDefault()

            if (sourceEvent.deltaY < 0) {
                incrementValue(sourceEvent)
            } else if (sourceEvent.deltaY > 0) {
                decrementValue(sourceEvent)
            }
        }
    }

    view {
        <div
            {...attrs}
            data-wrn-input-number
            data-variant='{variant}'
            data-size='{size}'
            data-color='{color}'
            data-value='{currentValue}'
            data-invalid='{isInvalid() ? "true" : "false"}'
            data-disabled='{disabled ? "true" : "false"}'
            style='--input-number-accent: {componentColor()};'
            class='relative flex flex-col gap-1.5 text-[var(--wire-color-text)] {fullWidth ? "w-full" : variant === "compact" ? "w-fit max-w-full" : "w-full max-w-sm"} {disabled ? "opacity-60" : ""} {class}'
        >
            {#if label !== "" && variant !== "labeled" && variant !== "seat"}
            <label
                for='{inputId()}'
                class='inline-flex items-center gap-1 text-sm font-semibold leading-5 text-[var(--wire-color-text)]'
            >
                <span>{label}</span>
                {#if required}
                <span
                    aria-hidden="true"
                    class='text-[var(--wire-color-danger)]'
                >*</span>
                {/if}
            </label>
            {/if}

            {#if description !== "" && variant !== "labeled" && variant !== "seat"}
            <p
                id='{descriptionId()}'
                class='m-0 text-xs leading-5 text-[var(--wire-color-muted)]'
            >
                {description}
            </p>
            {/if}

            <div
                class='group flex min-w-0 overflow-hidden border bg-[var(--wire-color-surface)] text-[var(--wire-color-text)] shadow-[var(--wire-shadow-1)] transition-[border-color,box-shadow,background-color] duration-[var(--wire-motion-base)] ease-[var(--wire-ease-standard)] focus-within:border-[var(--input-number-accent)] focus-within:shadow-[0_0_0_3px_color-mix(in_srgb,var(--input-number-accent)_18%,transparent)] {variant === "compact" ? "rounded-full" : "rounded-[var(--wire-radius-sm)]"} {size === "xs" ? "min-h-8 text-xs" : size === "sm" ? "min-h-9 text-sm" : size === "lg" ? "min-h-12 text-base" : size === "xl" ? "min-h-14 text-lg" : "min-h-10 text-sm"} {isInvalid() ? "border-[var(--wire-color-danger)] focus-within:border-[var(--wire-color-danger)] focus-within:shadow-[0_0_0_3px_color-mix(in_srgb,var(--wire-color-danger)_18%,transparent)]" : "border-[var(--wire-color-border)]"} {disabled ? "cursor-not-allowed bg-[var(--wire-color-surface-2)]" : ""}'
            >
                {#if variant === "horizontal" && showButtons}
                <button
                    type="button"
                    aria-label='{decrementLabel}'
                    aria-controls='{inputId()}'
                    disabled='{decrementDisabled()}'
                    @click='decrementValue(event)'
                    class='inline-flex shrink-0 items-center justify-center border-r border-[var(--wire-color-border)] bg-transparent text-[var(--wire-color-muted)] transition-[color,background-color] duration-[var(--wire-motion-fast)] hover:bg-[var(--wire-color-surface-2)] hover:text-[var(--input-number-accent)] focus-visible:z-10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--input-number-accent)] disabled:cursor-not-allowed disabled:opacity-40 {size === "xs" ? "w-8" : size === "sm" ? "w-9" : size === "lg" ? "w-12" : size === "xl" ? "w-14" : "w-10"}'
                >
                    <span
                        aria-hidden="true"
                        class='icon-[lucide--minus] size-4'
                    ></span>
                </button>
                {/if}

                <div
                    class='flex min-w-0 flex-1 {variant === "labeled" ? "flex-col items-stretch justify-center gap-0.5" : variant === "seat" ? "items-center justify-between gap-3" : "items-center"} {size === "xs" ? "px-2" : size === "sm" ? "px-2.5" : size === "lg" ? "px-4" : size === "xl" ? "px-5" : "px-3"}'
                >
                    {#if variant === "labeled" || variant === "seat"}
                    <div class='min-w-0 flex-1'>
                        {#if label !== ""}
                        <label
                            for='{inputId()}'
                            class='block truncate font-semibold leading-4 text-[var(--wire-color-text)] {variant === "labeled" ? "text-xs font-medium text-[var(--wire-color-muted)]" : "text-sm"}'
                        >
                            {label}
                            {#if required}
                            <span
                                aria-hidden="true"
                                class='ml-0.5 text-[var(--wire-color-danger)]'
                            >*</span>
                            {/if}
                        </label>
                        {/if}

                        {#if description !== ""}
                        <span
                            id='{descriptionId()}'
                            class='block truncate text-xs leading-4 text-[var(--wire-color-muted)]'
                        >
                            {description}
                        </span>
                        {/if}
                    </div>
                    {/if}

                    <div
                        class='flex min-w-0 items-center {variant === "seat" ? "w-auto shrink-0" : "w-full"}'
                    >
                        {#if prefix !== ""}
                        <span
                            aria-hidden="true"
                            class='shrink-0 pr-1.5 text-[var(--wire-color-muted)]'
                        >
                            {prefix}
                        </span>
                        {/if}

                        <input
                            id='{inputId()}'
                            name='{name}'
                            type="number"
                            value='{currentValue}'
                            min='{min}'
                            max='{max}'
                            step='{normalizedStep()}'
                            placeholder='{placeholder}'
                            autocomplete='{autocomplete}'
                            inputmode='{inputMode}'
                            aria-label='{ariaLabel !== "" ? ariaLabel : label !== "" ? label : name}'
                            aria-describedby='{describedBy()}'
                            aria-invalid='{isInvalid() ? "true" : "false"}'
                            aria-required='{required ? "true" : "false"}'
                            aria-disabled='{disabled || inputDisabled ? "true" : "false"}'
                            required='{required}'
                            disabled='{disabled}'
                            readonly='{readonly || inputDisabled || !allowInput}'
                            tabindex='{inputDisabled ? "-1" : "0"}'
                            @input='handleInput(event)'
                            @change='handleChange(event)'
                            @keydown='handleKeydown(event)'
                            @wheel='handleWheel(event)'
                            class='min-w-0 flex-1 appearance-none border-0 bg-transparent p-0 font-medium leading-none text-[var(--wire-color-text)] outline-none placeholder:text-[var(--wire-color-muted)] read-only:cursor-default disabled:cursor-not-allowed [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none {variant === "horizontal" || variant === "compact" || variant === "seat" ? "text-center" : "text-left"} {variant === "seat" ? "w-10 flex-none" : "w-full"}'
                        />

                        {#if suffix !== ""}
                        <span
                            aria-hidden="true"
                            class='shrink-0 pl-1.5 text-[var(--wire-color-muted)]'
                        >
                            {suffix}
                        </span>
                        {/if}
                    </div>
                </div>

                {#if variant === "horizontal" && showButtons}
                <button
                    type="button"
                    aria-label='{incrementLabel}'
                    aria-controls='{inputId()}'
                    disabled='{incrementDisabled()}'
                    @click='incrementValue(event)'
                    class='inline-flex shrink-0 items-center justify-center border-l border-[var(--wire-color-border)] bg-transparent text-[var(--wire-color-muted)] transition-[color,background-color] duration-[var(--wire-motion-fast)] hover:bg-[var(--wire-color-surface-2)] hover:text-[var(--input-number-accent)] focus-visible:z-10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--input-number-accent)] disabled:cursor-not-allowed disabled:opacity-40 {size === "xs" ? "w-8" : size === "sm" ? "w-9" : size === "lg" ? "w-12" : size === "xl" ? "w-14" : "w-10"}'
                >
                    <span
                        aria-hidden="true"
                        class='icon-[lucide--plus] size-4'
                    ></span>
                </button>
                {:else}
                {#if showButtons}
                <div
                    role="group"
                    aria-label='{controlsLabel}'
                    class='flex shrink-0 border-l border-[var(--wire-color-border)] {variant === "vertical" ? "flex-col" : "flex-row"}'
                >
                    <button
                        type="button"
                        aria-label='{decrementLabel}'
                        aria-controls='{inputId()}'
                        disabled='{decrementDisabled()}'
                        @click='decrementValue(event)'
                        class='inline-flex items-center justify-center bg-transparent text-[var(--wire-color-muted)] transition-[color,background-color] duration-[var(--wire-motion-fast)] hover:bg-[var(--wire-color-surface-2)] hover:text-[var(--input-number-accent)] focus-visible:z-10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--input-number-accent)] disabled:cursor-not-allowed disabled:opacity-40 {variant === "vertical" ? "flex-1 border-b border-[var(--wire-color-border)]" : "border-r border-[var(--wire-color-border)]"} {size === "xs" ? "w-8" : size === "sm" ? "w-9" : size === "lg" ? "w-12" : size === "xl" ? "w-14" : "w-10"}'
                    >
                        <span
                            aria-hidden="true"
                            class='icon-[lucide--minus] size-4'
                        ></span>
                    </button>

                    <button
                        type="button"
                        aria-label='{incrementLabel}'
                        aria-controls='{inputId()}'
                        disabled='{incrementDisabled()}'
                        @click='incrementValue(event)'
                        class='inline-flex items-center justify-center bg-transparent text-[var(--wire-color-muted)] transition-[color,background-color] duration-[var(--wire-motion-fast)] hover:bg-[var(--wire-color-surface-2)] hover:text-[var(--input-number-accent)] focus-visible:z-10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--input-number-accent)] disabled:cursor-not-allowed disabled:opacity-40 {variant === "vertical" ? "flex-1" : ""} {size === "xs" ? "w-8" : size === "sm" ? "w-9" : size === "lg" ? "w-12" : size === "xl" ? "w-14" : "w-10"}'
                    >
                        <span
                            aria-hidden="true"
                            class='icon-[lucide--plus] size-4'
                        ></span>
                    </button>
                </div>
                {/if}
                {/if}
            </div>

            {#if showValidationMessage && isInvalid() && validationMessage() !== ""}
            <p
                id='{messageId()}'
                role="alert"
                aria-live="polite"
                class='m-0 flex items-center gap-1.5 text-xs leading-5 text-[var(--wire-color-danger)]'
            >
                <span
                    aria-hidden="true"
                    class='icon-[lucide--circle-alert] size-3.5 shrink-0'
                ></span>
                <span>{validationMessage()}</span>
            </p>
            {/if}

            {#if (!showValidationMessage || !isInvalid() || validationMessage() === "") && helpText !== ""}
            <p
                id='{messageId()}'
                class='m-0 text-xs leading-5 text-[var(--wire-color-muted)]'
            >
                {helpText}
            </p>
            {/if}
        </div>
    }
}
```

---

## Kbd

Showcase: https://component.wrnexusjs.dev/
Mount: <Kbd /> (legacy: data-component="Kbd")
Category: layout
Purpose: Theme-aware, responsive kbd component.
Props: size: string = "default", color: string = "primary", label: string = "⌘ K", class: string = ""
Slots: default
Events: none

### Complete .wrn source contract

```wrn
component Kbd {
  props {
    size = "default"
    color = "primary"
    label = "⌘ K"
    class = ""
  }
  view { <kbd class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--kbd {class}"><slot>{label}</slot></kbd> }
}
```

---

## LayoutSplitter

Showcase: https://component.wrnexusjs.dev/
Mount: <LayoutSplitter /> (legacy: data-component="LayoutSplitter")
Category: layout
Purpose: Theme-aware, responsive layout splitter component.
Props: size: string = "default", color: string = "primary", columns: number = 2, gap: string = "md", maxWidth: string = "xl", class: string = ""
Slots: default
Events: resizeStart, resize, resizeEnd

### Complete .wrn source contract

```wrn
component LayoutSplitter {
  props {
    @event resizeStart = function
    @event resize = function
    @event resizeEnd = function
    size = "default"
    color = "primary"
    columns = 2
    gap = "md"
    maxWidth = "xl"
    class = ""
  }
  view {
    <div class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--layout-splitter wire-next--gap-{gap} wire-next--columns-{columns} wire-next--max-{maxWidth} {class}"><slot /></div>
  }
}
```

---

## LegendIndicator

Showcase: https://component.wrnexusjs.dev/
Mount: <LegendIndicator /> (legacy: data-component="LegendIndicator")
Category: base
Purpose: Theme-aware, responsive legend indicator component.
Props: size: string = "default", color: string = "primary", title: string = "Legend Indicator", description: string = "", items: string = [], variant: string = "default", class: string = ""
Slots: default
Events: toggle, select

### Complete .wrn source contract

```wrn
component LegendIndicator {
  props {
    @event toggle = function
    @event select = function
    size = "default"
    color = "primary"
    title = "Legend Indicator"
    description = ""
    items = []
    variant = "default"
    class = ""
  }
  view {
    <section class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--legend-indicator wire-next--variant-{variant} {class}">
      {#if title}<strong>{title}</strong>{/if}
      {#if description}<p>{description}</p>{/if}
      {#if items}<div class="wire-next__items">{#each items as item}<span>{item.label}</span>{/each}</div>{/if}
      <slot />
    </section>
  }
}
```

---

## Link

Showcase: https://component.wrnexusjs.dev/
Mount: <Link /> (legacy: data-component="Link")
Category: layout
Purpose: Theme-aware, responsive link component.
Props: size: string = "default", color: string = "primary", label: string = "Link", href: string = "#", target: string = "", rel: string = "", external: boolean = false, class: string = ""
Slots: default
Events: none

### Complete .wrn source contract

```wrn
component Link {
  props {
    size = "default"
    color = "primary"
    label = "Link"
    href = "#"
    target = ""
    rel = ""
    external = false
    class = ""
  }

  view {
    <a
      data-ui-component="Link"
      href='{href}'
      target='{target}'
      rel='{external ? (rel || "noopener noreferrer") : rel}'
      class='inline-flex min-w-0 items-center gap-1.5 rounded-md font-semibold underline-offset-4 outline-none transition-colors focus-visible:ring-2 focus-visible:ring-[var(--wire-color-focus)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--wire-color-background)] {class}'
      class:text-xs='size === "xs"'
      class:text-sm='size === "sm" || size === "default"'
      class:text-base='size === "md"'
      class:text-lg='size === "lg"'
      class:text-[var(--wire-color-primary)]='color === "primary"'
      class:hover:text-[var(--wire-color-primary-hover)]='color === "primary"'
      class:text-[var(--wire-color-secondary)]='color === "secondary"'
      class:hover:text-[var(--wire-color-secondary-hover)]='color === "secondary"'
      class:text-[var(--wire-color-success)]='color === "success"'
      class:text-[var(--wire-color-warning-text)]='color === "warning"'
      class:text-[var(--wire-color-danger)]='color === "danger"'
      class:text-[var(--wire-color-info)]='color === "info"'
      class:text-[var(--wire-color-text)]='color === "neutral"'
      class:hover:underline='external === false'
    >
      <span class="truncate">{label}</span>

      {#if external}
        <span
          class="icon-[lucide--external-link] size-3.5 shrink-0"
          aria-hidden="true"
        ></span>
      {/if}

      <slot></slot>
    </a>
  }
}
```

---

## List

Showcase: https://component.wrnexusjs.dev/
Mount: <List /> (legacy: data-component="List")
Category: base
Purpose: Theme-aware, responsive list component.
Props: size: string = "default", color: string = "primary", title: string = "List", description: string = "", items: string = [], variant: string = "default", class: string = ""
Slots: default
Events: none

### Complete .wrn source contract

```wrn
component List {
  props {
    size = "default"
    color = "primary"
    title = "List"
    description = ""
    items = []
    variant = "default"
    class = ""
  }

  view {
    <section
      data-ui-component="List"
      aria-label='{title}'
      class='w-full {class}'
    >
      {#if title || description}
        <header class="mb-4">
          {#if title}
            <h3 class="text-lg font-bold text-[var(--wire-color-text)]">{title}</h3>
          {/if}
          {#if description}
            <p class="mt-1 text-sm leading-6 text-[var(--wire-color-text-muted)]">{description}</p>
          {/if}
        </header>
      {/if}

      <ul
        class="overflow-hidden"
        class:divide-y='variant === "default" || variant === "divided"'
        class:divide-[var(--wire-color-border)]='variant === "default" || variant === "divided"'
        class:rounded-2xl='variant === "card"'
        class:border='variant === "card"'
        class:border-[var(--wire-color-border)]='variant === "card"'
        class:bg-[var(--wire-color-surface-raised)]='variant === "card"'
        class:space-y-3='variant === "separated"'
      >
        {#each items as item, index}
          <li
            class="group min-w-0"
            class:rounded-xl='variant === "separated"'
            class:border='variant === "separated"'
            class:border-[var(--wire-color-border)]='variant === "separated"'
            class:bg-[var(--wire-color-surface-raised)]='variant === "separated"'
          >
            {#if item.href}
              <a
                href='{item.href}'
                class="flex min-w-0 items-start gap-3 px-4 py-3 outline-none transition hover:bg-[var(--wire-color-surface-soft)] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--wire-color-focus)]"
                class:px-3='size === "sm"'
                class:py-2.5='size === "sm"'
                class:px-5='size === "lg"'
                class:py-4='size === "lg"'
                @click='event.currentTarget.dispatchEvent(new CustomEvent("select", { bubbles: true, detail: { item: item, index: index } }))'
              >
                {#if item.icon}
                  <span class="flex size-10 shrink-0 items-center justify-center rounded-xl bg-[var(--wire-color-primary-soft)] text-[var(--wire-color-primary)]">
                    <span class='{item.icon + " size-5"}' aria-hidden="true"></span>
                  </span>
                {/if}
                {#if item.imageSrc}
                  <img src='{item.imageSrc}' alt='{item.imageAlt || ""}' class="size-12 shrink-0 rounded-xl object-cover" loading="lazy" />
                {/if}
                <div class="min-w-0 flex-1">
                  <div class="flex items-start justify-between gap-3">
                    <p class="truncate font-semibold text-[var(--wire-color-text)]">{item.title || item.label}</p>
                    {#if item.meta}
                      <span class="shrink-0 text-xs text-[var(--wire-color-text-muted)]">{item.meta}</span>
                    {/if}
                  </div>
                  {#if item.description}
                    <p class="mt-1 line-clamp-2 text-sm leading-5 text-[var(--wire-color-text-muted)]">{item.description}</p>
                  {/if}
                  {#if item.badge}
                    <span class="mt-2 inline-flex rounded-full bg-[var(--wire-color-primary-soft)] px-2.5 py-1 text-xs font-semibold text-[var(--wire-color-primary)]">{item.badge}</span>
                  {/if}
                </div>
                <span class="icon-[lucide--chevron-right] mt-1 size-4 shrink-0 text-[var(--wire-color-text-muted)] transition group-hover:translate-x-0.5 group-hover:text-[var(--wire-color-primary)]" aria-hidden="true"></span>
              </a>
            {:else}
              <div class="flex min-w-0 items-start gap-3 px-4 py-3">
                {#if item.icon}
                  <span class="flex size-10 shrink-0 items-center justify-center rounded-xl bg-[var(--wire-color-primary-soft)] text-[var(--wire-color-primary)]">
                    <span class='{item.icon + " size-5"}' aria-hidden="true"></span>
                  </span>
                {/if}
                <div class="min-w-0 flex-1">
                  <p class="font-semibold text-[var(--wire-color-text)]">{item.title || item.label}</p>
                  {#if item.description}
                    <p class="mt-1 text-sm leading-5 text-[var(--wire-color-text-muted)]">{item.description}</p>
                  {/if}
                </div>
              </div>
            {/if}
          </li>
        {:empty}
          <li class="rounded-xl border border-dashed border-[var(--wire-color-border)] p-6 text-center text-sm text-[var(--wire-color-text-muted)]">
            No items available.
          </li>
        {/each}
      </ul>

      <slot></slot>
    </section>
  }
}
```

---

## ListGroup

Showcase: https://component.wrnexusjs.dev/
Mount: <ListGroup /> (legacy: data-component="ListGroup")
Category: base
Purpose: Theme-aware, responsive list group component.
Props: size: string = "default", color: string = "primary", title: string = "List Group", description: string = "", items: string = [], variant: string = "default", class: string = ""
Slots: default
Events: select, change

### Complete .wrn source contract

```wrn
component ListGroup {
  props {
    @event select = function
    @event change = function
    size = "default"
    color = "primary"
    title = "List Group"
    description = ""
    items = []
    variant = "default"
    class = ""
  }
  view {
    <section class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--list-group wire-next--variant-{variant} {class}">
      {#if title}<strong>{title}</strong>{/if}
      {#if description}<p>{description}</p>{/if}
      {#if items}<div class="wire-next__items">{#each items as item}<span>{item.label}</span>{/each}</div>{/if}
      <slot />
    </section>
  }
}
```

---

## Map

Showcase: https://component.wrnexusjs.dev/
Mount: <Map /> (legacy: data-component="Map")
Category: integrations
Purpose: Theme-aware, responsive map component.
Props: size: string = "default", color: string = "primary", title: string = "Map", description: string = "", items: string = [], variant: string = "default", class: string = ""
Slots: default
Events: none

### Complete .wrn source contract

```wrn
component Map {
  props {
    size = "default"
    color = "primary"
    title = "Map"
    description = ""
    items = []
    variant = "default"
    class = ""
  }

  view {
    <section
      data-ui-component="Map"
      aria-label='{title}'
      class='overflow-hidden rounded-2xl border border-[var(--wire-color-border)] bg-[var(--wire-color-surface-raised)] shadow-sm {class}'
    >
      {#if title || description}
        <header class="flex items-start justify-between gap-4 border-b border-[var(--wire-color-border)] p-5">
          <div>
            {#if title}
              <h3 class="text-lg font-bold text-[var(--wire-color-text)]">{title}</h3>
            {/if}
            {#if description}
              <p class="mt-1 text-sm leading-6 text-[var(--wire-color-text-muted)]">{description}</p>
            {/if}
          </div>
          <span class="flex size-10 shrink-0 items-center justify-center rounded-xl bg-[var(--wire-color-primary-soft)] text-[var(--wire-color-primary)]">
            <span class="icon-[lucide--map] size-5" aria-hidden="true"></span>
          </span>
        </header>
      {/if}

      <div
        class="relative isolate overflow-hidden bg-[var(--wire-color-surface-soft)]"
        class:h-64='size === "sm"'
        class:h-80='size === "default" || size === "md"'
        class:h-[28rem]='size === "lg"'
      >
        <div
          class="pointer-events-none absolute inset-0 opacity-50"
          style="background-image: linear-gradient(var(--wire-color-border) 1px, transparent 1px), linear-gradient(90deg, var(--wire-color-border) 1px, transparent 1px); background-size: 32px 32px;"
          aria-hidden="true"
        ></div>

        <div class="absolute inset-0 flex items-center justify-center p-6">
          <slot></slot>
        </div>

        {#if items.length > 0}
          {#each items as item, index}
            <button
              type="button"
              aria-label='{item.label || item.title || "Map marker"}'
              class="absolute inline-flex size-10 items-center justify-center rounded-full border-4 border-[var(--wire-color-surface-raised)] bg-[var(--wire-color-primary)] text-[var(--wire-color-on-primary)] shadow-lg transition hover:scale-110 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--wire-color-focus)]"
              style='left: {item.x || (20 + index * 12)}%; top: {item.y || (30 + (index % 3) * 18)}%;'
              @click='event.currentTarget.dispatchEvent(new CustomEvent("markerClick", { bubbles: true, detail: item })); event.currentTarget.dispatchEvent(new CustomEvent("select", { bubbles: true, detail: item }))'
            >
              <span class='{item.icon || "icon-[lucide--map-pin]"}' aria-hidden="true"></span>
            </button>
          {/each}
        {/if}

        <div class="absolute bottom-4 right-4 flex flex-col gap-2">
          <button
            type="button"
            aria-label="Zoom in"
            class="inline-flex size-10 items-center justify-center rounded-xl border border-[var(--wire-color-border)] bg-[var(--wire-color-surface-raised)] text-[var(--wire-color-text)] shadow-sm transition hover:bg-[var(--wire-color-surface-soft)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--wire-color-focus)]"
            @click='event.currentTarget.dispatchEvent(new CustomEvent("zoom", { bubbles: true, detail: { direction: "in" } }))'
          >
            <span class="icon-[lucide--plus] size-4" aria-hidden="true"></span>
          </button>
          <button
            type="button"
            aria-label="Zoom out"
            class="inline-flex size-10 items-center justify-center rounded-xl border border-[var(--wire-color-border)] bg-[var(--wire-color-surface-raised)] text-[var(--wire-color-text)] shadow-sm transition hover:bg-[var(--wire-color-surface-soft)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--wire-color-focus)]"
            @click='event.currentTarget.dispatchEvent(new CustomEvent("zoom", { bubbles: true, detail: { direction: "out" } }))'
          >
            <span class="icon-[lucide--minus] size-4" aria-hidden="true"></span>
          </button>
        </div>
      </div>
    </section>
  }
}
```

---

## MarketingSectionHeader

Showcase: https://component.wrnexusjs.dev/
Mount: <MarketingSectionHeader /> (legacy: data-component="MarketingSectionHeader")
Category: blocks
Purpose: Marketing section heading with an optional linked action.
Props: id: string = "", eyebrow: string = "", title: string = "", description: string = "", align: string = "split", size: string = "default", color: string = "primary", actionLabel: string = "", actionHref: string = "", actionIcon: string = "", actionExternal: boolean = false, class: string = ""
Slots: icon, actions, default
Events: none

### Complete .wrn source contract

```wrn
component MarketingSectionHeader {
  props {
    id = ""
    eyebrow = ""
    title = ""
    description = ""
    align = "split"
    size = "default"
    color = "primary"
    actionLabel = ""
    actionHref = ""
    actionIcon = ""
    actionExternal = false
    class = ""
  }

  view {
    <div
      {...attrs}
      data-ui-component="MarketingSectionHeader"
      data-size='{size}'
      data-color='{color}'
      class='{class}'
    >
      <SectionHeader
        id='{id}'
        eyebrow='{eyebrow}'
        title='{title}'
        description='{description}'
        align='{align}'
        size='{size}'
        color='{color}'
        headingLevel="2"
        maxWidth="3xl"
      >
        <div data-slot="icon">
          <slot name="icon"></slot>
        </div>

        <div data-slot="actions">
          {#if actionLabel}
            <TextLink
              label='{actionLabel}'
              href='{actionHref}'
              external='{actionExternal}'
              icon='{actionIcon}'
              iconPosition="start"
              showArrow="true"
              color='{color}'
            />
          {/if}
          <slot name="actions"></slot>
        </div>

        <slot></slot>
      </SectionHeader>
    </div>
  }
}
```

---

## Marquee

Showcase: https://component.wrnexusjs.dev/
Mount: <Marquee /> (legacy: data-component="Marquee")
Category: base
Purpose: Theme-aware, responsive marquee component.
Props: size: string = "default", color: string = "primary", title: string = "Marquee", description: string = "", items: string = [], variant: string = "default", class: string = ""
Slots: default
Events: none

### Complete .wrn source contract

```wrn
component Marquee {
  props {
    size = "default"
    color = "primary"
    title = "Marquee"
    description = ""
    items = []
    variant = "default"
    class = ""
  }

  state paused = false

  view {
    <section
      data-ui-component="Marquee"
      aria-label='{title}'
      class='overflow-hidden border-y border-[var(--wire-color-border)] bg-[var(--wire-color-surface-raised)] {class}'
    >
      <div class="flex items-stretch">
        {#if title}
          <div class="relative z-10 flex shrink-0 items-center gap-2 border-r border-[var(--wire-color-border)] bg-[var(--wire-color-primary)] px-4 py-3 text-[var(--wire-color-on-primary)] sm:px-5">
            <span class="icon-[lucide--megaphone] size-4" aria-hidden="true"></span>
            <span class="text-sm font-bold">{title}</span>
          </div>
        {/if}

        <div
          class="group relative min-w-0 flex-1 overflow-hidden"
          @mouseenter='paused = true; event.currentTarget.dispatchEvent(new CustomEvent("pause", { bubbles: true }))'
          @mouseleave='paused = false; event.currentTarget.dispatchEvent(new CustomEvent("resume", { bubbles: true }))'
          @focusin='paused = true'
          @focusout='paused = false'
        >
          <div
            class="wire-marquee-track flex w-max min-w-full items-center"
            class:wire-marquee-paused='paused'
          >
            {#each items as item}
              <a
                href='{item.href || "#"}'
                class="flex shrink-0 items-center gap-3 px-5 py-3 text-sm font-medium text-[var(--wire-color-text)] transition hover:bg-[var(--wire-color-primary-soft)] hover:text-[var(--wire-color-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--wire-color-focus)]"
              >
                <span
                  class="size-2 shrink-0 rounded-full bg-[var(--wire-color-primary)]"
                  class:bg-[var(--wire-color-danger)]='item.color === "danger"'
                  class:bg-[var(--wire-color-warning)]='item.color === "warning"'
                  class:bg-[var(--wire-color-success)]='item.color === "success"'
                  aria-hidden="true"
                ></span>
                <span>{item.label || item.title}</span>
                {#if item.meta}
                  <span class="text-xs text-[var(--wire-color-text-muted)]">{item.meta}</span>
                {/if}
              </a>
            {:empty}
              <p class="px-5 py-3 text-sm text-[var(--wire-color-text-muted)]">{description || "No announcements available."}</p>
            {/each}

            {#if items.length > 0}
              {#each items as item}
                <a
                  href='{item.href || "#"}'
                  aria-hidden="true"
                  tabindex="-1"
                  class="flex shrink-0 items-center gap-3 px-5 py-3 text-sm font-medium text-[var(--wire-color-text)]"
                >
                  <span class="size-2 shrink-0 rounded-full bg-[var(--wire-color-primary)]" aria-hidden="true"></span>
                  <span>{item.label || item.title}</span>
                </a>
              {/each}
            {/if}
          </div>
        </div>

        <button
          type="button"
          aria-label='{paused ? "Resume announcements" : "Pause announcements"}'
          class="flex shrink-0 items-center justify-center border-l border-[var(--wire-color-border)] px-4 text-[var(--wire-color-text-muted)] transition hover:bg-[var(--wire-color-surface-soft)] hover:text-[var(--wire-color-text)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--wire-color-focus)]"
          @click='paused = !paused; event.currentTarget.dispatchEvent(new CustomEvent(paused ? "pause" : "resume", { bubbles: true }))'
        >
          <span class="icon-[lucide--pause] size-4" data-show='!paused' aria-hidden="true"></span>
          <span class="icon-[lucide--play] size-4" data-show='paused' aria-hidden="true"></span>
        </button>
      </div>

      <slot></slot>
    </section>
  }

  style {
    .wire-marquee-track {
      animation: wire-marquee 32s linear infinite;
    }

    .wire-marquee-paused {
      animation-play-state: paused;
    }

    @keyframes wire-marquee {
      from { transform: translateX(0); }
      to { transform: translateX(-50%); }
    }

    @media (prefers-reduced-motion: reduce) {
      .wire-marquee-track {
        animation: none;
      }
    }
  }
}
```

---

## MegaMenu

Showcase: https://component.wrnexusjs.dev/
Mount: <MegaMenu /> (legacy: data-component="MegaMenu")
Category: navigation
Purpose: Theme-aware, responsive mega menu component.
Props: size: string = "default", color: string = "primary", label: string = "Mega Menu", items: string = [], active: string = "", orientation: string = "horizontal", class: string = ""
Slots: default
Events: open, close, select

### Complete .wrn source contract

```wrn
component MegaMenu {
  props {
    @event open = function
    @event close = function
    @event select = function
    size = "default"
    color = "primary"
    label = "Mega Menu"
    items = []
    active = ""
    orientation = "horizontal"
    class = ""
  }
  view {
    <nav class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--mega-menu wire-next--{orientation} {class}" aria-label="{label}">
      {#each items as item}<a href="{item.href}" aria-current="{item.value === active ? 'page' : ''}">{item.label}</a>{/each}
      <slot />
    </nav>
  }
}
```

---

## MetricCard

Showcase: https://component.wrnexusjs.dev/
Mount: <MetricCard /> (legacy: data-component="MetricCard")
Category: blocks
Purpose: Single statistic or operational metric with icon, trend, and optional action.
Props: label: string = "Metric", value: string = "0", description: string = "", icon: string = "", prefix: string = "", suffix: string = "", trend: string = "", trendLabel: string = "", trendDirection: string = "neutral", href: string = "", actionLabel: string = "", size: string = "default", color: string = "primary", variant: string = "default", align: string = "left", class: string = ""
Slots: none
Events: none

### Complete .wrn source contract

```wrn
component MetricCard {
  props {
    label = "Metric"
    value = "0"
    description = ""
    icon = ""
    prefix = ""
    suffix = ""
    trend = ""
    trendLabel = ""
    trendDirection = "neutral"
    href = ""
    actionLabel = ""
    size = "default"
    color = "primary"
    variant = "default"
    align = "left"
    class = ""
  }

  view {
    <article
      data-ui-component="MetricCard"
      class='group relative flex h-full flex-col rounded-2xl border border-[var(--wire-color-border)] bg-[var(--wire-color-surface-raised)] p-5 shadow-sm transition {class}'
      class:p-4='size === "sm"'
      class:p-6='size === "lg"'
      class:bg-[var(--wire-color-primary-soft)]='variant === "soft" && color === "primary"'
      class:bg-[var(--wire-color-success-soft)]='variant === "soft" && color === "success"'
      class:bg-[var(--wire-color-warning-soft)]='variant === "soft" && color === "warning"'
      class:bg-[var(--wire-color-danger-soft)]='variant === "soft" && color === "danger"'
      class:bg-transparent='variant === "minimal"'
      class:border-transparent='variant === "minimal"'
      class:shadow-none='variant === "minimal"'
      class:text-center='align === "center"'
      class:items-center='align === "center"'
      class:text-right='align === "right"'
      class:items-end='align === "right"'
      class:hover:border-[var(--wire-color-primary)]='href !== ""'
      class:hover:shadow-lg='href !== ""'
    >
      <div class="flex w-full items-start justify-between gap-4">
        <div>
          <p class="text-sm font-semibold text-[var(--wire-color-text-muted)]">{label}</p>
          <p class="mt-2 text-3xl font-bold tracking-tight text-[var(--wire-color-text)]" class:text-4xl='size === "lg"'>
            <span>{prefix}</span><span>{value}</span><span>{suffix}</span>
          </p>
        </div>

        {#if icon}
          <span
            class="flex size-11 shrink-0 items-center justify-center rounded-2xl bg-[var(--wire-color-primary-soft)] text-[var(--wire-color-primary)]"
            class:bg-[var(--wire-color-success-soft)]='color === "success"'
            class:text-[var(--wire-color-success)]='color === "success"'
            class:bg-[var(--wire-color-warning-soft)]='color === "warning"'
            class:text-[var(--wire-color-warning-text)]='color === "warning"'
            class:bg-[var(--wire-color-danger-soft)]='color === "danger"'
            class:text-[var(--wire-color-danger)]='color === "danger"'
            class:bg-[var(--wire-color-info-soft)]='color === "info"'
            class:text-[var(--wire-color-info)]='color === "info"'
          >
            <span class='{icon + " size-5"}' aria-hidden="true"></span>
          </span>
        {/if}
      </div>

      {#if description}
        <p class="mt-3 text-sm leading-6 text-[var(--wire-color-text-muted)]">{description}</p>
      {/if}

      {#if trend || trendLabel}
        <div class="mt-4 inline-flex items-center gap-2 text-sm font-semibold">
          <span
            class="inline-flex items-center gap-1 rounded-full px-2.5 py-1"
            class:bg-[var(--wire-color-success-soft)]='trendDirection === "up" || trendDirection === "positive"'
            class:text-[var(--wire-color-success)]='trendDirection === "up" || trendDirection === "positive"'
            class:bg-[var(--wire-color-danger-soft)]='trendDirection === "down" || trendDirection === "negative"'
            class:text-[var(--wire-color-danger)]='trendDirection === "down" || trendDirection === "negative"'
            class:bg-[var(--wire-color-surface-soft)]='trendDirection === "neutral"'
            class:text-[var(--wire-color-text-muted)]='trendDirection === "neutral"'
          >
            {#if trendDirection === "up" || trendDirection === "positive"}
              <span class="icon-[lucide--trending-up] size-4" aria-hidden="true"></span>
            {:else if trendDirection === "down" || trendDirection === "negative"}
              <span class="icon-[lucide--trending-down] size-4" aria-hidden="true"></span>
            {:else}
              <span class="icon-[lucide--minus] size-4" aria-hidden="true"></span>
            {/if}
            <span>{trend}</span>
          </span>
          {#if trendLabel}
            <span class="text-[var(--wire-color-text-muted)]">{trendLabel}</span>
          {/if}
        </div>
      {/if}

      {#if href}
        <TextLink
          label='{actionLabel || "View details"}'
          href='{href}'
          color='{color}'
          size="sm"
          class="mt-5"
        />
      {/if}
    </article>
  }
}
```

---

## MetricGrid

Showcase: https://component.wrnexusjs.dev/
Mount: <MetricGrid /> (legacy: data-component="MetricGrid")
Category: layout
Purpose: Responsive collection of metric cards.
Props: items: string = [], columns: number = 4, tabletColumns: number = 2, mobileColumns: number = 1, gap: string = "md", equalHeight: boolean = true, dividers: boolean = false, size: string = "default", color: string = "primary", variant: string = "default", class: string = ""
Slots: default
Events: none

### Complete .wrn source contract

```wrn
component MetricGrid {
  props {
    items = []
    columns = 4
    tabletColumns = 2
    mobileColumns = 1
    gap = "md"
    equalHeight = true
    dividers = false
    size = "default"
    color = "primary"
    variant = "default"
    class = ""
  }

  view {
    <div
      data-ui-component="MetricGrid"
      class='grid w-full grid-cols-1 {class}'
      class:grid-cols-2='mobileColumns === 2'
      class:sm:grid-cols-2='tabletColumns === 2'
      class:sm:grid-cols-3='tabletColumns === 3'
      class:lg:grid-cols-2='columns === 2'
      class:lg:grid-cols-3='columns === 3'
      class:lg:grid-cols-4='columns === 4'
      class:lg:grid-cols-5='columns === 5'
      class:lg:grid-cols-6='columns === 6'
      class:gap-3='gap === "sm"'
      class:gap-5='gap === "md"'
      class:gap-8='gap === "lg"'
      class:divide-y='dividers'
      class:sm:divide-y-0='dividers'
      class:sm:divide-x='dividers'
      class:divide-[var(--wire-color-border)]='dividers'
    >
      {#each items as item}
        <MetricCard
          label='{item.label || item.title}'
          value='{item.value}'
          description='{item.description || ""}'
          icon='{item.icon || ""}'
          prefix='{item.prefix || ""}'
          suffix='{item.suffix || ""}'
          trend='{item.trend || ""}'
          trendLabel='{item.trendLabel || ""}'
          trendDirection='{item.trendDirection || "neutral"}'
          href='{item.href || ""}'
          actionLabel='{item.actionLabel || ""}'
          size='{item.size || size}'
          color='{item.color || color}'
          variant='{dividers ? "minimal" : (item.variant || variant)}'
          align='{item.align || "left"}'
          class="h-full"
        />
      {:empty}
        <slot></slot>
      {/each}
    </div>
  }
}
```

---

## Modal

Showcase: https://component.wrnexusjs.dev/
Mount: <Modal /> (legacy: data-component="Modal")
Category: overlays
Purpose: Theme-aware, responsive modal component.
Props: size: string = "default", color: string = "primary", title: string = "Modal", description: string = "", open: boolean = false, placement: string = "bottom", closeLabel: string = "Close", class: string = ""
Slots: default
Events: open, close, cancel, confirm

### Complete .wrn source contract

```wrn
component Modal {
  props {
    @event open = function
    @event close = function
    @event cancel = function
    @event confirm = function
    size = "default"
    color = "primary"
    title = "Modal"
    description = ""
    open = false
    placement = "bottom"
    closeLabel = "Close"
    class = ""
  }
  view {
    <div data-show="{open}" class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--modal wire-next--placement-{placement} {class}" role="dialog" aria-modal="true" aria-label="{title}">
      <header><strong>{title}</strong><button type="button" aria-label="{closeLabel}">×</button></header>
      {#if description}<p>{description}</p>{/if}
      <slot />
    </div>
  }
}
```

---

## Nav

Showcase: https://component.wrnexusjs.dev/
Mount: <Nav /> (legacy: data-component="Nav")
Category: navigation
Purpose: Theme-aware, responsive nav component.
Props: size: string = "default", color: string = "primary", label: string = "Nav", items: string = [], active: string = "", orientation: string = "horizontal", class: string = ""
Slots: default
Events: select, change

### Complete .wrn source contract

```wrn
component Nav {
  props {
    @event select = function
    @event change = function
    size = "default"
    color = "primary"
    label = "Nav"
    items = []
    active = ""
    orientation = "horizontal"
    class = ""
  }
  view {
    <nav class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--nav wire-next--{orientation} {class}" aria-label="{label}">
      {#each items as item}<a href="{item.href}" aria-current="{item.value === active ? 'page' : ''}">{item.label}</a>{/each}
      <slot />
    </nav>
  }
}
```

---

## Navbar

Showcase: https://component.wrnexusjs.dev/
Mount: <Navbar /> (legacy: data-component="Navbar")
Category: navigation
Purpose: Theme-aware, responsive navbar component.
Props: size: string = "default", color: string = "primary", label: string = "Primary navigation", topbarLabel: string = "Utility navigation", brand: string = {}, items: string = [], actions: string = [], active: string = "", sticky: boolean = false, openOnHover: boolean = false, maxWidth: string = "full", mobileLabel: string = "Toggle navigation", class: string = ""
Slots: topbar, actions
Events: toggle, open, close, select, action

### Complete .wrn source contract

```wrn
component Navbar {
  props {
    @event toggle = function
    @event open = function
    @event close = function
    @event select = function
    @event action = function
    size = "default"
    color = "primary"
    label = "Primary navigation"
    topbarLabel = "Utility navigation"
    brand = {}
    items = []
    actions = []
    active = ""
    sticky = false
    openOnHover = false
    maxWidth = "full"
    mobileLabel = "Toggle navigation"
    class = ""
  }

  state mobileOpen = false

  functions {
    function toggleNavigation() {
      mobileOpen = !mobileOpen
      $emit("toggle", { open: mobileOpen })
      $emit(mobileOpen ? "open" : "close", { source: "mobile" })
    }

    function selectItem(item, level) {
      mobileOpen = false
      $emit("select", { item: item, value: item.value || "", level: level })
    }

    function selectAction(item) {
      mobileOpen = false
      $emit("action", { item: item, value: item.value || "" })
    }

    function isItemActive(item) {
      if (!item) return false
      if (item.value && item.value === active) return true
      if (!item.children || !item.children.length) return false
      return item.children.some(function (child) {
        return isItemActive(child)
      })
    }

    function toggleDropdown(event, item) {
      $emit(event.currentTarget.open ? "open" : "close", {
        source: "menu",
        item: item
      })
    }
  }

  view {
    <header class="wire-navbar wire-navbar--width-{maxWidth} wire-next--color-{color} wire-next--size-{size} {sticky ? 'wire-navbar--sticky' : ''} {class}" data-wrn-navbar data-open-on-hover="{openOnHover}">
      <div class="wire-navbar__topbar" aria-label="{topbarLabel}">
        <slot name="topbar" />
      </div>

      <div class="wire-navbar__main">
        <a class="wire-navbar__brand" href="{brand.href || '/'}" aria-label="{brand.ariaLabel || brand.label || label}">
          {#if brand.logo}
            <img class="wire-navbar__brand-logo" src="{brand.logo}" alt="{brand.logoAlt || brand.label || ''}" width="{brand.logoWidth || ''}" height="{brand.logoHeight || ''}" />
          {/if}
          {#if brand.icon}
            <span class="wire-navbar__brand-icon {brand.icon}" aria-hidden="true"></span>
          {/if}
          {#if brand.label || brand.description}
            <span class="wire-navbar__brand-copy">
              {#if brand.label}<strong>{brand.label}</strong>{/if}
              {#if brand.description}<small>{brand.description}</small>{/if}
            </span>
          {/if}
        </a>

        <button type="button" class="wire-navbar__toggle" aria-label="{mobileLabel}" aria-expanded="{mobileOpen}" @click="toggleNavigation()">
          <span aria-hidden="true"></span><span aria-hidden="true"></span><span aria-hidden="true"></span>
        </button>

        <div class="wire-navbar__collapse {mobileOpen ? 'is-open' : ''}">
          <nav class="wire-navbar__menus" aria-label="{label}">
            {#each items as item}
              {#if item.children && item.children.length}
                <details class="wire-navbar__dropdown wire-navbar__dropdown--{item.type || 'dropdown'}" name="wire-navbar-menu" @toggle="toggleDropdown($event, item)">
                  <summary aria-current="{isItemActive(item) ? 'page' : ''}">
                    {#if item.icon}<span class="{item.icon}" aria-hidden="true"></span>{/if}
                    <span>{item.label}</span>
                    <span class="wire-navbar__chevron" aria-hidden="true"></span>
                  </summary>
                  <div class="wire-navbar__panel wire-navbar__panel--columns-{item.columns || 1}">
                    {#if item.description}<p class="wire-navbar__panel-intro">{item.description}</p>{/if}
                    {#each item.children as child}
                      <div class="wire-navbar__group">
                        {#if child.children && child.children.length}
                          {#if child.label}<strong class="wire-navbar__group-title">{child.label}</strong>{/if}
                          {#if child.description}<small>{child.description}</small>{/if}
                          {#each child.children as nested}
                            <a href="{nested.href || '#'}" target="{nested.target || ''}" rel="{nested.rel || ''}" aria-current="{nested.value === active ? 'page' : ''}" @click="selectItem(nested, 3)">
                              {#if nested.icon}<span class="{nested.icon}" aria-hidden="true"></span>{/if}
                              <span><strong>{nested.label}</strong>{#if nested.description}<small>{nested.description}</small>{/if}</span>
                            </a>
                          {/each}
                        {:else}
                          <a href="{child.href || '#'}" target="{child.target || ''}" rel="{child.rel || ''}" aria-current="{child.value === active ? 'page' : ''}" @click="selectItem(child, 2)">
                            {#if child.icon}<span class="{child.icon}" aria-hidden="true"></span>{/if}
                            <span><strong>{child.label}</strong>{#if child.description}<small>{child.description}</small>{/if}</span>
                          </a>
                        {/if}
                      </div>
                    {/each}
                  </div>
                </details>
              {:else}
                <a class="wire-navbar__menu-link" href="{item.href || '#'}" target="{item.target || ''}" rel="{item.rel || ''}" aria-current="{item.value === active ? 'page' : ''}" @click="selectItem(item, 1)">
                  {#if item.icon}<span class="{item.icon}" aria-hidden="true"></span>{/if}
                  <span>{item.label}</span>
                </a>
              {/if}
            {/each}
          </nav>

          <div class="wire-navbar__actions">
            {#each actions as item}
              <a class="wire-navbar__action wire-navbar__action--{item.variant || 'link'}" href="{item.href || '#'}" target="{item.target || ''}" rel="{item.rel || ''}" @click="selectAction(item)">
                {#if item.icon}<span class="{item.icon}" aria-hidden="true"></span>{/if}
                <span>{item.label}</span>
              </a>
            {/each}
            <slot name="actions" />
          </div>
        </div>
      </div>
    </header>
  }
}
```

---

## PageHeader

Showcase: https://component.wrnexusjs.dev/
Mount: <PageHeader /> (legacy: data-component="PageHeader")
Category: blocks
Purpose: Public and application page header with breadcrumbs, metadata, and actions.
Props: eyebrow: string = "", title: string = "", description: string = "", icon: string = "", align: string = "left", size: string = "default", compact: boolean = false, showBreadcrumbs: boolean = false, breadcrumbs: string = [], primaryLabel: string = "", primaryHref: string = "", primaryIcon: string = "", secondaryLabel: string = "", secondaryHref: string = "", secondaryIcon: string = "", color: string = "primary", variant: string = "default", class: string = ""
Slots: meta, actions, default
Events: none

### Complete .wrn source contract

```wrn
component PageHeader {
  props {
    eyebrow = ""
    title = ""
    description = ""
    icon = ""
    align = "left"
    size = "default"
    compact = false
    showBreadcrumbs = false
    breadcrumbs = []
    primaryLabel = ""
    primaryHref = ""
    primaryIcon = ""
    secondaryLabel = ""
    secondaryHref = ""
    secondaryIcon = ""
    color = "primary"
    variant = "default"
    class = ""
  }

  view {
    <div
      {...attrs}
      data-ui-component="PageHeader"
      data-size='{size}'
      data-color='{color}'
      class='{class}'
    >
      <Section
        spacing='{compact || size === "compact" ? "md" : "lg"}'
        variant='{variant}'
        color='{color}'
        borderBottom="true"
      >
        {#if showBreadcrumbs && breadcrumbs.length > 0}
          <Breadcrumb
            label="Breadcrumb"
            items='{breadcrumbs}'
            active='{breadcrumbs[breadcrumbs.length - 1]?.value || breadcrumbs[breadcrumbs.length - 1]?.label || ""}'
            color='{color}'
            class="mb-6"
          />
        {/if}

        <div
          class="flex flex-col gap-6"
          class:items-center='align === "center"'
          class:text-center='align === "center"'
          class:lg:flex-row='align !== "center"'
          class:lg:items-end='align !== "center"'
          class:lg:justify-between='align !== "center"'
        >
          <div class="max-w-4xl">
            {#if icon}
              <span class="mb-5 inline-flex size-12 items-center justify-center rounded-2xl bg-[var(--wire-color-primary-soft)] text-[var(--wire-color-primary)]">
                <span class='{icon + " size-6"}' aria-hidden="true"></span>
              </span>
            {/if}

            <SectionHeader
              eyebrow='{eyebrow}'
              title='{title}'
              description='{description}'
              align='{align === "center" ? "center" : "left"}'
              size='{compact || size === "compact" ? "sm" : "lg"}'
              color='{color}'
              headingLevel="1"
              maxWidth="4xl"
            >
              <slot name="meta"></slot>
            </SectionHeader>
          </div>

          <div class="flex flex-wrap items-center gap-3" class:justify-center='align === "center"'>
            {#if secondaryLabel}
              <Button
                label='{secondaryLabel}'
                href='{secondaryHref}'
                icon='{secondaryIcon}'
                variant="outline"
                color='{color}'
              />
            {/if}

            {#if primaryLabel}
              <Button
                label='{primaryLabel}'
                href='{primaryHref}'
                icon='{primaryIcon}'
                variant="default"
                color='{color}'
              />
            {/if}

            <slot name="actions"></slot>
          </div>
        </div>

        <slot></slot>
      </Section>
    </div>
  }
}
```

---

## Pagination

Showcase: https://component.wrnexusjs.dev/
Mount: <Pagination /> (legacy: data-component="Pagination")
Category: navigation
Purpose: Theme-aware, responsive pagination component.
Props: size: string = "default", color: string = "primary", label: string = "Pagination", items: string = [], active: string = "", orientation: string = "horizontal", class: string = ""
Slots: default
Events: change, previous, next

### Complete .wrn source contract

```wrn
component Pagination {
  props {
    @event change = function
    @event previous = function
    @event next = function
    size = "default"
    color = "primary"
    label = "Pagination"
    items = []
    active = ""
    orientation = "horizontal"
    class = ""
  }
  view {
    <nav class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--pagination wire-next--{orientation} {class}" aria-label="{label}">
      {#each items as item}<a href="{item.href}" aria-current="{item.value === active ? 'page' : ''}">{item.label}</a>{/each}
      <slot />
    </nav>
  }
}
```

---

## PinInput

Showcase: https://component.wrnexusjs.dev/
Mount: <PinInput /> (legacy: data-component="PinInput")
Category: advanced-forms
Purpose: Secure multi-cell PIN and verification-code input with regex and paste support.
Props: size: string = "default", color: string = "primary", label: string = "Verification code", name: string = "pin", value: string = "", length: number = 4, pattern: string = "[0-9]", type: string = "text", inputMode: string = "numeric", placeholder: string = "○", autocomplete: string = "one-time-code", masked: boolean = false, disabled: boolean = false, readonly: boolean = false, required: boolean = false, autoFocus: boolean = false, autoSubmit: boolean = false, allowPaste: boolean = true, clearable: boolean = true, clearLabel: string = "Clear code", separator: string = "", groupSize: number = 0, helpText: string = "", invalid: boolean = false, validationMessage: string = "", class: string = ""
Slots: none
Events: input, change, complete, paste, clear, error

### Complete .wrn source contract

```wrn
component PinInput {
  props {
    size = "default"
    color = "primary"
    label = "Verification code"
    name = "pin"
    value = ""
    length = 4
    pattern = "[0-9]"
    type = "text"
    inputMode = "numeric"
    placeholder = "○"
    autocomplete = "one-time-code"
    masked = false
    disabled = false
    readonly = false
    required = false
    autoFocus = false
    autoSubmit = false
    allowPaste = true
    clearable = true
    clearLabel = "Clear code"
    separator = ""
    groupSize = 0
    helpText = ""
    invalid = false
    validationMessage = ""
    class = ""
    @event input = function
    @event change = function
    @event complete = function
    @event paste = function
    @event clear = function
    @event error = function
  }

  functions {
    function inputIndexes() {
      return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].slice(
        0,
        Math.max(1, Math.min(12, Number(length)))
      )
    }
  }

  view {
    <fieldset
      {...attrs}
      class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--pin-input {invalid ? 'wire-next--invalid' : ''} {disabled ? 'wire-next--disabled' : ''} {class}"
      data-wrn-pin-input
      data-length="{length}"
      data-pattern="{pattern}"
      data-allow-paste="{allowPaste ? 'true' : 'false'}"
      data-auto-submit="{autoSubmit ? 'true' : 'false'}"
      data-value="{value}"
      disabled="{disabled}"
      aria-describedby="{validationMessage ? `${name}-validation` : helpText ? `${name}-help` : ''}"
    >
      <div class="wire-next__pin-heading">
        <legend>{label}</legend>
        <button
          type="button"
          class="wire-next__pin-clear"
          data-pin-clear
          aria-label="{clearLabel}"
          title="{clearLabel}"
          style="{clearable && value ? '' : 'display: none'}"
        >
          <span class="icon-[lucide--rotate-ccw]" aria-hidden="true"></span>
          <span>{clearLabel}</span>
        </button>
      </div>

      <div class="wire-next__pin-cells" role="group" aria-label="{label}">
        {#each inputIndexes() as index}
          <input
            data-pin-cell
            data-pin-index="{index}"
            id="{name}-{index}"
            type="{masked ? 'password' : type}"
            inputmode="{inputMode}"
            maxlength="1"
            value="{value[index] || ''}"
            placeholder="{placeholder}"
            autocomplete="{index === 0 ? autocomplete : 'off'}"
            aria-label="{label} digit {index + 1} of {length}"
            aria-required="{required ? 'true' : 'false'}"
            readonly="{readonly}"
            disabled="{disabled}"
            autofocus="{autoFocus && index === 0}"
          />
          {#if separator && groupSize !== 0 && (index + 1) % groupSize === 0 && index + 1 !== length}
            <span class="wire-next__pin-separator" aria-hidden="true">{separator}</span>
          {/if}
        {/each}
      </div>

      <input
        type="hidden"
        name="{name}"
        value="{value}"
        required="{required}"
        data-pin-value
      />

      {#if helpText && !validationMessage}<small id="{name}-help">{helpText}</small>{/if}
      <small
        id="{name}-validation"
        class="wire-next__validation"
        data-error="{name}"
      >{validationMessage}</small>
    </fieldset>
  }
}
```

---

## Popover

Showcase: https://component.wrnexusjs.dev/
Mount: <Popover /> (legacy: data-component="Popover")
Category: overlays
Purpose: Theme-aware, responsive popover component.
Props: size: string = "default", color: string = "primary", title: string = "Popover", description: string = "", open: boolean = false, placement: string = "bottom", closeLabel: string = "Close", class: string = ""
Slots: default
Events: open, close

### Complete .wrn source contract

```wrn
component Popover {
  props {
    @event open = function
    @event close = function
    size = "default"
    color = "primary"
    title = "Popover"
    description = ""
    open = false
    placement = "bottom"
    closeLabel = "Close"
    class = ""
  }
  view {
    <div data-show="{open}" class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--popover wire-next--placement-{placement} {class}" role="region" aria-modal="false" aria-label="{title}">
      <header><strong>{title}</strong><button type="button" aria-label="{closeLabel}">×</button></header>
      {#if description}<p>{description}</p>{/if}
      <slot />
    </div>
  }
}
```

---

## PortalDashboard

Showcase: https://component.wrnexusjs.dev/
Mount: <PortalDashboard /> (legacy: data-component="PortalDashboard")
Category: blocks
Purpose: Responsive portal dashboard with metrics, actions, tasks, and updates.
Props: size: string = "default", color: string = "primary", eyebrow: string = "Overview", eyebrowKey: string = "", title: string = "Dashboard", titleKey: string = "", description: string = "", descriptionKey: string = "", userName: string = "", metrics: string = [], actions: string = [], updates: string = [], tasks: string = [], class: string = ""
Slots: hero-action
Events: action, navigate

### Complete .wrn source contract

```wrn
component PortalDashboard {
  props {
    @event action = function
    @event navigate = function
    size = "default"
    color = "primary"
    eyebrow = "Overview"
    eyebrowKey = ""
    title = "Dashboard"
    titleKey = ""
    description = ""
    descriptionKey = ""
    userName = ""
    metrics = []
    actions = []
    updates = []
    tasks = []
    class = ""
  }

  functions {
    function chooseAction(item, index) {
      $emit("action", { item: item, value: item.value || "", index: index })
    }

    function chooseNavigation(item, index) {
      $emit("navigate", { item: item, value: item.value || "", index: index })
    }
  }

  view {
    <main class="wire-portal-dashboard wire-next--color-{color} wire-next--size-{size} {class}">
      <header class="wire-portal-dashboard__hero">
        <div>
          {#if eyebrowKey}<span class="wire-portal-dashboard__eyebrow" data-t="{eyebrowKey}">{eyebrow}</span>{/if}
          {#if !eyebrowKey}<span class="wire-portal-dashboard__eyebrow">{eyebrow}</span>{/if}
          <h1>
            {#if titleKey}<span data-t="{titleKey}">{title}</span>{/if}
            {#if !titleKey}<span>{title}</span>{/if}
            {#if userName}, {userName}{/if}
          </h1>
          {#if descriptionKey}<p data-t="{descriptionKey}">{description}</p>{/if}
          {#if !descriptionKey && description}<p>{description}</p>{/if}
        </div>
        <div class="wire-portal-dashboard__hero-slot"><slot name="hero-action" /></div>
      </header>

      <section class="wire-portal-dashboard__metrics" aria-label="Summary">
        {#each metrics as item}
          <article class="wire-portal-dashboard__metric">
            <span class="wire-portal-dashboard__metric-icon {item.icon || 'icon-[lucide--activity]'}" aria-hidden="true"></span>
            <div><small>{item.label}</small><strong>{item.value}</strong>{#if item.detail}<span>{item.detail}</span>{/if}</div>
          </article>
        {/each}
      </section>

      <div class="wire-portal-dashboard__grid">
        <section class="wire-portal-dashboard__panel wire-portal-dashboard__panel--actions">
          <div class="wire-portal-dashboard__panel-heading"><div><small>Shortcuts</small><h2>Quick actions</h2></div></div>
          <div class="wire-portal-dashboard__actions">
            {#each actions as item, index}
              <a href="{item.href || '#'}" @click="chooseAction(item, index)">
                <span class="{item.icon || 'icon-[lucide--arrow-up-right]'}" aria-hidden="true"></span>
                <span><strong>{item.label}</strong>{#if item.description}<small>{item.description}</small>{/if}</span>
                <span class="icon-[lucide--chevron-right]" aria-hidden="true"></span>
              </a>
            {/each}
          </div>
        </section>

        <section class="wire-portal-dashboard__panel">
          <div class="wire-portal-dashboard__panel-heading"><div><small>Priority</small><h2>Tasks requiring attention</h2></div></div>
          <div class="wire-portal-dashboard__list">
            {#each tasks as item, index}
              <a href="{item.href || '#'}" @click="chooseNavigation(item, index)">
                <span class="wire-portal-dashboard__status wire-portal-dashboard__status--{item.status || 'default'}"></span>
                <span><strong>{item.label}</strong>{#if item.detail}<small>{item.detail}</small>{/if}</span>
                {#if item.meta}<em>{item.meta}</em>{/if}
              </a>
            {/each}
          </div>
        </section>

        <section class="wire-portal-dashboard__panel wire-portal-dashboard__panel--updates">
          <div class="wire-portal-dashboard__panel-heading"><div><small>Latest</small><h2>Recent updates</h2></div></div>
          <div class="wire-portal-dashboard__timeline">
            {#each updates as item}
              <article>
                <span class="{item.icon || 'icon-[lucide--bell]'}" aria-hidden="true"></span>
                <div><strong>{item.label}</strong>{#if item.detail}<p>{item.detail}</p>{/if}<small>{item.time || ''}</small></div>
              </article>
            {/each}
          </div>
        </section>
      </div>
    </main>
  }
}
```

---

## PreferenceSwitcher

Showcase: https://component.wrnexusjs.dev/
Mount: <PreferenceSwitcher /> (legacy: data-component="PreferenceSwitcher")
Category: navigation
Purpose: Accessible theme, accent color, and language preference controls.
Props: size: string = "default", color: string = "primary", themeLabel: string = "Theme", colorLabel: string = "Accent color", languageLabel: string = "Language", languages: string = [, colors: string = [, compact: boolean = true, class: string = ""
Slots: none
Events: theme, color, language

### Complete .wrn source contract

```wrn
component PreferenceSwitcher {
  props {
    @event theme = function
    @event color = function
    @event language = function
    size = "default"
    color = "primary"
    themeLabel = "Theme"
    colorLabel = "Accent color"
    languageLabel = "Language"
    languages = [
      {"label": "English", "shortLabel": "EN", "value": "en"},
      {"label": "हिन्दी", "shortLabel": "हि", "value": "hi"},
      {"label": "मराठी", "shortLabel": "म", "value": "mr"}
    ]
    colors = [
      {"label": "Blue", "value": "blue", "hex": "#2563eb"},
      {"label": "Cyan", "value": "cyan", "hex": "#0891b2"},
      {"label": "Emerald", "value": "emerald", "hex": "#059669"},
      {"label": "Violet", "value": "violet", "hex": "#7c3aed"},
      {"label": "Rose", "value": "rose", "hex": "#e11d48"},
      {"label": "Amber", "value": "amber", "hex": "#d97706"}
    ]
    compact = true
    class = ""
  }

  functions {
    function choose(type, value) {
      $emit(type, { value: value })
    }
  }

  view {
    <div class="wire-preferences wire-next--color-{color} wire-next--size-{size} {compact ? 'wire-preferences--compact' : ''} {class}" data-wrn-preferences aria-label="Display and language preferences">
      <details class="wire-preferences__menu" name="wire-preference-menu">
        <summary aria-label="{themeLabel}" title="{themeLabel}">
          <span class="icon-[lucide--sun-moon]" aria-hidden="true"></span>
          {#if !compact}<span>{themeLabel}</span>{/if}
        </summary>
        <div class="wire-preferences__panel">
          <strong>{themeLabel}</strong>
          <div class="wire-preferences__options">
            <button type="button" data-wire-theme-set="light" @click="choose('theme', 'light')"><span class="icon-[lucide--sun]" aria-hidden="true"></span>Light</button>
            <button type="button" data-wire-theme-set="dark" @click="choose('theme', 'dark')"><span class="icon-[lucide--moon]" aria-hidden="true"></span>Dark</button>
          </div>
        </div>
      </details>

      <details class="wire-preferences__menu" name="wire-preference-menu">
        <summary aria-label="{colorLabel}" title="{colorLabel}">
          <span class="icon-[lucide--palette]" aria-hidden="true"></span>
          {#if !compact}<span>{colorLabel}</span>{/if}
        </summary>
        <div class="wire-preferences__panel wire-preferences__panel--colors">
          <strong>{colorLabel}</strong>
          <div class="wire-preferences__swatches">
            {#each colors as item}
              <button type="button" data-wire-accent-set="{item.value}" aria-label="{item.label}" title="{item.label}" style="--wire-preference-swatch: {item.hex}" @click="choose('color', item.value)"></button>
            {/each}
          </div>
        </div>
      </details>

      <details class="wire-preferences__menu wire-preferences__menu--language" name="wire-preference-menu">
        <summary aria-label="{languageLabel}" title="{languageLabel}">
          <span class="icon-[lucide--languages]" aria-hidden="true"></span>
          <span class="wire-preferences__current-language" aria-hidden="true">EN</span>
          {#if !compact}<span>{languageLabel}</span>{/if}
        </summary>
        <div class="wire-preferences__panel wire-preferences__panel--language">
          <strong>{languageLabel}</strong>
          {#each languages as item}
            <button type="button" data-wire-lang-set="{item.value}" lang="{item.value}" @click="choose('language', item.value)">
              <span>{item.shortLabel}</span>{item.label}
            </button>
          {/each}
        </div>
      </details>
    </div>
  }
}
```

---

## Progress

Showcase: https://component.wrnexusjs.dev/
Mount: <Progress /> (legacy: data-component="Progress")
Category: base
Purpose: Theme-aware, responsive progress component.
Props: size: string = "default", color: string = "primary", label: string = "Progress", value: number = 50, max: number = 100, showValue: boolean = true, class: string = ""
Slots: none
Events: none

### Complete .wrn source contract

```wrn
component Progress {
  props {
    size = "default"
    color = "primary"
    label = "Progress"
    value = 50
    max = 100
    showValue = true
    class = ""
  }
  view {
    <div class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--progress {class}">
      <div class="wire-next__row"><span>{label}</span>{#if showValue}<strong>{value}%</strong>{/if}</div>
      <progress value="{value}" max="{max}"></progress>
    </div>
  }
}
```

---

## PublicPageShell

Showcase: https://component.wrnexusjs.dev/
Mount: <PublicPageShell /> (legacy: data-component="PublicPageShell")
Category: layout
Purpose: Consistent structural wrapper for public-facing pages.
Props: maxWidth: string = "full", fullWidth: boolean = true, headerOffset: string = "none", background: string = "default", overflow: string = "clip", minHeight: string = "screen", size: string = "default", color: string = "primary", variant: string = "default", class: string = ""
Slots: before, default, after
Events: none

### Complete .wrn source contract

```wrn
component PublicPageShell {
  props {
    maxWidth = "full"
    fullWidth = true
    headerOffset = "none"
    background = "default"
    overflow = "clip"
    minHeight = "screen"
    size = "default"
    color = "primary"
    variant = "default"
    class = ""
  }

  view {
    <div
      data-ui-component="PublicPageShell"
      data-size='{size}'
      data-color='{color}'
      data-variant='{variant}'
      class='relative isolate w-full text-[var(--wire-color-text)] {class}'
      class:min-h-screen='minHeight === "screen"'
      class:min-h-dvh='minHeight === "dvh"'
      class:overflow-x-clip='overflow === "clip"'
      class:overflow-x-hidden='overflow === "hidden"'
      class:bg-[var(--wire-color-background)]='background === "default"'
      class:bg-[var(--wire-color-surface-soft)]='background === "soft"'
      class:bg-[var(--wire-color-surface-raised)]='background === "raised"'
      class:pt-16='headerOffset === "sm"'
      class:pt-20='headerOffset === "md"'
      class:pt-24='headerOffset === "lg"'
    >
      <slot name="before"></slot>

      {#if fullWidth}
        <main class="w-full">
          <slot></slot>
        </main>
      {:else}
        <main
          class="mx-auto w-full px-4 sm:px-6 lg:px-8"
          class:max-w-5xl='maxWidth === "lg"'
          class:max-w-7xl='maxWidth === "xl"'
          class:max-w-screen-2xl='maxWidth === "2xl"'
        >
          <slot></slot>
        </main>
      {/if}

      <slot name="after"></slot>
    </div>
  }
}
```

---

## Radio

Showcase: https://component.wrnexusjs.dev/
Mount: <Radio /> (legacy: data-component="Radio")
Category: forms
Purpose: Theme-aware, responsive radio component.
Props: size: string = "default", color: string = "primary", id: string = "", name: string = "", label: string = "Radio", hiddenLabel: boolean = false, placeholder: string = "", variant: string = "normal", icon: string = "", iconPosition: string = "start", value: string = "on", options: string = [], checked: boolean = false, orientation: string = "vertical", card: boolean = false, rightAligned: boolean = false, list: boolean = false, helperText: string = "", cornerHint: string = "", error: string = "", inline: boolean = false, readonly: boolean = false, disabled: boolean = false, required: boolean = false, class: string = ""
Slots: none
Events: input, change, focus, blur, invalid

### Complete .wrn source contract

```wrn
component Radio {
  props {
    @event input = function
    @event change = function
    @event focus = function
    @event blur = function
    @event invalid = function
    size = "default"
    color = "primary"
    id = ""
    name = ""
    label = "Radio"
    hiddenLabel = false
    placeholder = ""
    variant = "normal"
    icon = ""
    iconPosition = "start"
    value = "on"
    options = []
    checked = false
    orientation = "vertical"
    card = false
    rightAligned = false
    list = false
    helperText = ""
    cornerHint = ""
    error = ""
    inline = false
    readonly = false
    disabled = false
    required = false
    class = ""
  }
  functions {
    function emitField(nameEvent, sourceEvent) { sourceEvent.stopPropagation(); $emit(nameEvent, { checked: sourceEvent.currentTarget.checked, value: sourceEvent.currentTarget.value, name: name, sourceEvent: sourceEvent }) }
    function preventReadonly(sourceEvent) { if (readonly) sourceEvent.preventDefault() }
  }
  view {
    <div {...attrs} class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--choice-field wire-next--radio-field {class}" data-inline="{inline}" data-invalid="{error ? 'true' : 'false'}" data-orientation="{orientation}" data-card="{card}" data-list="{list}" data-right-aligned="{rightAligned}">
      <div class="wire-next__field-heading">{#if options.length || cornerHint}<span class="{hiddenLabel ? 'wire-next__sr-only' : ''}">{label}</span>{#if cornerHint}<span class="wire-next__field-hint">{cornerHint}</span>{/if}{/if}</div>
      {#if options.length}
        <div class="wire-next__radio-group" role="radiogroup" aria-label="{hiddenLabel ? label : ''}" aria-invalid="{error ? 'true' : 'false'}">
          {#each options as option}
            <label class="wire-next__choice wire-next--radio" for="{id || name}-{option.value}" data-variant="{variant}" data-disabled="{disabled || option.disabled}">
              <input id="{id || name}-{option.value}" type="radio" name="{name}" value="{option.value}" checked="{option.value === value || option.checked}" disabled="{disabled || option.disabled}" required="{required}" readonly="{readonly}" @click="preventReadonly(event)" @input="emitField('input', event)" @change="emitField('change', event)" @focus="emitField('focus', event)" @blur="emitField('blur', event)" @invalid="emitField('invalid', event)" />
              <span class="wire-next__choice-copy"><strong>{option.label}</strong>{#if option.description}<small>{option.description}</small>{/if}</span>
            </label>
          {/each}
        </div>
      {:else}
        <label class="wire-next__choice wire-next--radio" for="{id || name}" data-variant="{variant}" data-icon-position="{iconPosition}"><input id="{id || name}" type="radio" name="{name}" value="{value}" checked="{checked}" disabled="{disabled}" required="{required}" readonly="{readonly}" aria-invalid="{error ? 'true' : 'false'}" @click="preventReadonly(event)" @input="emitField('input', event)" @change="emitField('change', event)" @focus="emitField('focus', event)" @blur="emitField('blur', event)" @invalid="emitField('invalid', event)" />{#if icon}<span class="{icon}" aria-hidden="true"></span>{/if}<span class="{hiddenLabel || cornerHint ? 'wire-next__sr-only' : ''}">{label}</span></label>
      {/if}
      {#if helperText}<small class="wire-next__field-help">{helperText}</small>{/if}<small class="wire-next__field-error" data-error="{name}">{error}</small>
    </div>
  }
}
```

---

## RangeSlider

Showcase: https://component.wrnexusjs.dev/
Mount: <RangeSlider /> (legacy: data-component="RangeSlider")
Category: forms
Purpose: Theme-aware, responsive range slider component.
Props: size: string = "default", color: string = "primary", id: string = "", name: string = "", label: string = "Range", hiddenLabel: boolean = false, placeholder: string = "", variant: string = "normal", icon: string = "", iconPosition: string = "start", value: number = 50, min: number = 0, max: number = 100, step: number = 1, showValue: boolean = true, showBounds: boolean = true, showSteps: boolean = false, marks: string = [], helperText: string = "", cornerHint: string = "", error: string = "", inline: boolean = false, readonly: boolean = false, disabled: boolean = false, required: boolean = false, class: string = ""
Slots: none
Events: input, change, focus, blur

### Complete .wrn source contract

```wrn
component RangeSlider {
  props {
    @event input = function
    @event change = function
    @event focus = function
    @event blur = function
    size = "default"
    color = "primary"
    id = ""
    name = ""
    label = "Range"
    hiddenLabel = false
    placeholder = ""
    variant = "normal"
    icon = ""
    iconPosition = "start"
    value = 50
    min = 0
    max = 100
    step = 1
    showValue = true
    showBounds = true
    showSteps = false
    marks = []
    helperText = ""
    cornerHint = ""
    error = ""
    inline = false
    readonly = false
    disabled = false
    required = false
    class = ""
  }
  state currentValue = value
  functions {
    function percent() { if (Number(max) === Number(min)) { return 0 } return (Number(currentValue) - Number(min)) / (Number(max) - Number(min)) * 100 }
    function setValue(nextValue, sourceEvent, commit, detail, root, slider, input, output, progressValue) { if (readonly || disabled) { return } currentValue = Number(nextValue); root = sourceEvent.currentTarget.closest(".wire-next--range-slider"); if (root) { slider = root.querySelector("[role=slider]"); input = root.querySelector("input[name='" + name + "']"); output = root.querySelector("output"); progressValue = (currentValue - Number(min)) / (Number(max) - Number(min)) * 100; if (slider) { slider.setAttribute("aria-valuenow", String(currentValue)); slider.style.setProperty("--wire-range-progress", progressValue + "%") } if (input) { input.value = String(currentValue) } if (output) { output.textContent = String(currentValue) } } detail = { value: currentValue, min: min, max: max, step: step, name: name, sourceEvent: sourceEvent }; $emit("input", detail); if (commit) { $emit("change", detail) } }
    function valueFromPointer(sourceEvent, rect, ratio) { rect = sourceEvent.currentTarget.getBoundingClientRect(); ratio = Math.max(0, Math.min(1, (sourceEvent.clientX - rect.left) / rect.width)); return Number(min) + ratio * (Number(max) - Number(min)) }
    function beginSlide(sourceEvent, rect, ratio, rawValue) { if (readonly || disabled) { return } sourceEvent.currentTarget.setPointerCapture(sourceEvent.pointerId); rect = sourceEvent.currentTarget.getBoundingClientRect(); ratio = Math.max(0, Math.min(1, (sourceEvent.clientX - rect.left) / rect.width)); rawValue = Number(min) + ratio * (Number(max) - Number(min)); currentValue = Number(min) + Math.round((rawValue - Number(min)) / Number(step)) * Number(step); $emit("input", { value: currentValue, name: name, sourceEvent: sourceEvent }) }
    function moveSlide(sourceEvent, rect, ratio, rawValue) { if (!sourceEvent.currentTarget.hasPointerCapture(sourceEvent.pointerId)) { return } rect = sourceEvent.currentTarget.getBoundingClientRect(); ratio = Math.max(0, Math.min(1, (sourceEvent.clientX - rect.left) / rect.width)); rawValue = Number(min) + ratio * (Number(max) - Number(min)); currentValue = Number(min) + Math.round((rawValue - Number(min)) / Number(step)) * Number(step); $emit("input", { value: currentValue, name: name, sourceEvent: sourceEvent }) }
    function endSlide(sourceEvent, rect, ratio, rawValue) { rect = sourceEvent.currentTarget.getBoundingClientRect(); ratio = Math.max(0, Math.min(1, (sourceEvent.clientX - rect.left) / rect.width)); rawValue = Number(min) + ratio * (Number(max) - Number(min)); currentValue = Number(min) + Math.round((rawValue - Number(min)) / Number(step)) * Number(step); if (sourceEvent.currentTarget.hasPointerCapture(sourceEvent.pointerId)) { sourceEvent.currentTarget.releasePointerCapture(sourceEvent.pointerId) } $emit("change", { value: currentValue, name: name, sourceEvent: sourceEvent }) }
    function selectMark(sourceEvent, root, slider, input, output, nextValue, progressValue, detail) { if (readonly || disabled) { return } root = sourceEvent.currentTarget.closest(".wire-next--range-slider"); slider = root.querySelector(".wire-next__custom-slider"); input = root.querySelector(".wire-next__range-value"); output = root.querySelector("output"); nextValue = Number(sourceEvent.currentTarget.dataset.value); currentValue = nextValue; progressValue = (nextValue - Number(min)) / (Number(max) - Number(min)) * 100; slider.setAttribute("aria-valuenow", String(nextValue)); slider.style.setProperty("--wire-range-progress", progressValue + "%"); input.setAttribute("value", String(nextValue)); output.replaceChildren(String(nextValue)); detail = { value: nextValue, min: min, max: max, step: step, name: name, sourceEvent: sourceEvent }; $emit("input", detail); $emit("change", detail) }
    function handleKey(sourceEvent) { if (sourceEvent.key === "ArrowRight") { sourceEvent.preventDefault(); currentValue = Math.min(Number(max), Number(currentValue) + Number(step)); $emit("input", { value: currentValue, name: name, sourceEvent: sourceEvent }); $emit("change", { value: currentValue, name: name, sourceEvent: sourceEvent }) } if (sourceEvent.key === "ArrowLeft") { sourceEvent.preventDefault(); currentValue = Math.max(Number(min), Number(currentValue) - Number(step)); $emit("input", { value: currentValue, name: name, sourceEvent: sourceEvent }); $emit("change", { value: currentValue, name: name, sourceEvent: sourceEvent }) } if (sourceEvent.key === "Home") { sourceEvent.preventDefault(); currentValue = Number(min); $emit("change", { value: currentValue, name: name, sourceEvent: sourceEvent }) } if (sourceEvent.key === "End") { sourceEvent.preventDefault(); currentValue = Number(max); $emit("change", { value: currentValue, name: name, sourceEvent: sourceEvent }) } }
    function emitFocus(nameEvent, sourceEvent) { $emit(nameEvent, { value: currentValue, name: name, sourceEvent: sourceEvent }) }
    function decreaseValue(sourceEvent) { currentValue = Math.max(Number(min), Number(currentValue) - Number(step)); $emit("input", { value: currentValue, name: name, sourceEvent: sourceEvent }); $emit("change", { value: currentValue, name: name, sourceEvent: sourceEvent }) }
    function increaseValue(sourceEvent) { currentValue = Math.min(Number(max), Number(currentValue) + Number(step)); $emit("input", { value: currentValue, name: name, sourceEvent: sourceEvent }); $emit("change", { value: currentValue, name: name, sourceEvent: sourceEvent }) }
  }
  view {
    <div {...attrs} class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--field wire-next--range-slider {class}" data-variant="{variant}" data-inline="{inline}" data-invalid="{error ? 'true' : 'false'}">
      <div class="wire-next__field-heading"><label class="{hiddenLabel ? 'wire-next__sr-only' : ''}" for="{id || name}">{label}</label>{#if cornerHint}<span class="wire-next__field-hint">{cornerHint}</span>{/if}</div>
      <div class="wire-next__range-control" data-variant="{variant}" data-icon-position="{iconPosition}" data-show-steps="{showSteps}">
        {#if icon}<span class="{icon}" aria-hidden="true"></span>{/if}
        <button type="button" class="wire-next__range-stepper" aria-label="Decrease {label}" disabled="{disabled || readonly}" @click="decreaseValue(event)">−</button>
        <div class="wire-next__range-track">
          <input id="{id || name}" class="wire-next__sr-only wire-next__range-value" type="number" name="{name}" value="{currentValue}" min="{min}" max="{max}" step="{step}" required="{required}" readonly />
          <div class="wire-next__custom-slider" role="slider" tabindex="{disabled ? '-1' : '0'}" aria-label="{hiddenLabel ? label : ''}" aria-valuemin="{min}" aria-valuemax="{max}" aria-valuenow="{currentValue}" aria-disabled="{disabled}" aria-readonly="{readonly}" aria-invalid="{error ? 'true' : 'false'}" style="--wire-range-progress: {percent()}%" @pointerdown="beginSlide(event)" @pointermove="moveSlide(event)" @pointerup="endSlide(event)" @pointercancel="endSlide(event)" @keydown="handleKey(event)" @focus="emitFocus('focus', event)" @blur="emitFocus('blur', event)">
            <span class="wire-next__slider-fill"></span><span class="wire-next__slider-thumb"></span>
            {#if marks.length}<span class="wire-next__slider-marks">{#each marks as mark}<button type="button" data-value="{mark.value}" style="left: {(Number(mark.value) - Number(min)) / (Number(max) - Number(min)) * 100}%" aria-label="{mark.label}" @click="selectMark(event)"></button>{/each}</span>{/if}
          </div>
          {#if showBounds}<div class="wire-next__range-bounds"><span>{min}</span><span>Step {step}</span><span>{max}</span></div>{/if}
        </div>
        {#if showValue}<output for="{id || name}">{currentValue}</output>{/if}
        <button type="button" class="wire-next__range-stepper" aria-label="Increase {label}" disabled="{disabled || readonly}" @click="increaseValue(event)">+</button>
      </div>
      {#if helperText}<small class="wire-next__field-help">{helperText}</small>{/if}<small class="wire-next__field-error" data-error="{name}">{error}</small>
    </div>
  }
}
```

---

## Rating

Showcase: https://component.wrnexusjs.dev/
Mount: <Rating /> (legacy: data-component="Rating")
Category: base
Purpose: Theme-aware, responsive rating component.
Props: size: string = "default", color: string = "primary", title: string = "Rating", description: string = "", items: string = [], variant: string = "default", class: string = ""
Slots: default
Events: input, change

### Complete .wrn source contract

```wrn
component Rating {
  props {
    @event input = function
    @event change = function
    size = "default"
    color = "primary"
    title = "Rating"
    description = ""
    items = []
    variant = "default"
    class = ""
  }
  view {
    <section class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--rating wire-next--variant-{variant} {class}">
      {#if title}<strong>{title}</strong>{/if}
      {#if description}<p>{description}</p>{/if}
      {#if items}<div class="wire-next__items">{#each items as item}<span>{item.label}</span>{/each}</div>{/if}
      <slot />
    </section>
  }
}
```

---

## Scrollspy

Showcase: https://component.wrnexusjs.dev/
Mount: <Scrollspy /> (legacy: data-component="Scrollspy")
Category: navigation
Purpose: Theme-aware, responsive scrollspy component.
Props: size: string = "default", color: string = "primary", label: string = "Scrollspy", items: string = [], active: string = "", orientation: string = "horizontal", class: string = ""
Slots: default
Events: change

### Complete .wrn source contract

```wrn
component Scrollspy {
  props {
    @event change = function
    size = "default"
    color = "primary"
    label = "Scrollspy"
    items = []
    active = ""
    orientation = "horizontal"
    class = ""
  }
  view {
    <nav class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--scrollspy wire-next--{orientation} {class}" aria-label="{label}">
      {#each items as item}<a href="{item.href}" aria-current="{item.value === active ? 'page' : ''}">{item.label}</a>{/each}
      <slot />
    </nav>
  }
}
```

---

## SearchBox

Showcase: https://component.wrnexusjs.dev/
Mount: <SearchBox /> (legacy: data-component="SearchBox")
Category: advanced-forms
Purpose: Theme-aware, responsive search box component.
Props: size: string = "default", color: string = "primary", label: string = "Search Box", name: string = "", value: string = "", placeholder: string = "", type: string = "search", min: string = "", max: string = "", step: string = "", disabled: boolean = false, required: boolean = false, class: string = ""
Slots: none
Events: none

### Complete .wrn source contract

```wrn
component SearchBox {
  props {
    size = "default"
    color = "primary"
    label = "Search Box"
    name = ""
    value = ""
    placeholder = ""
    type = "search"
    min = ""
    max = ""
    step = ""
    disabled = false
    required = false
    class = ""
  }

  state query = value

  view {
    <form
      data-ui-component="SearchBox"
      role="search"
      class='w-full {class}'
      @submit='event.preventDefault(); event.currentTarget.dispatchEvent(new CustomEvent("search", { bubbles: true, detail: { value: query, name: name } }))'
    >
      <label
        class="mb-2 block text-sm font-semibold text-[var(--wire-color-text)]"
        class:sr-only='label === ""'
      >
        {label}
      </label>

      <div class="relative flex items-center">
        <span
          class="icon-[lucide--search] pointer-events-none absolute left-4 size-5 text-[var(--wire-color-input-placeholder)]"
          aria-hidden="true"
        ></span>

        <input
          name='{name}'
          type='{type}'
          value='{query}'
          placeholder='{placeholder}'
          min='{min}'
          max='{max}'
          step='{step}'
          disabled='{disabled}'
          required='{required}'
          autocomplete="off"
          class="w-full rounded-xl border border-[var(--wire-color-input-border)] bg-[var(--wire-color-input-background)] pl-12 pr-24 text-[var(--wire-color-input-text)] outline-none transition placeholder:text-[var(--wire-color-input-placeholder)] hover:border-[var(--wire-color-input-border-hover)] focus:border-[var(--wire-color-input-border-focus)] focus:ring-2 focus:ring-[var(--wire-color-focus)] disabled:cursor-not-allowed disabled:opacity-60"
          class:h-10='size === "sm"'
          class:h-12='size === "default" || size === "md"'
          class:h-14='size === "lg"'
          @input='query = event.target.value'
          @change='query = event.target.value'
        />

        <button
          type="button"
          aria-label="Clear search"
          data-show='query.length > 0 && !disabled'
          class="absolute right-12 inline-flex size-8 items-center justify-center rounded-lg text-[var(--wire-color-text-muted)] transition hover:bg-[var(--wire-color-surface-soft)] hover:text-[var(--wire-color-text)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--wire-color-focus)]"
          @click='query = ""; event.currentTarget.parentElement.querySelector("input")?.focus(); event.currentTarget.dispatchEvent(new CustomEvent("clear", { bubbles: true, detail: { value: "", name: name } }))'
        >
          <span class="icon-[lucide--x] size-4" aria-hidden="true"></span>
        </button>

        <button
          type="submit"
          aria-label='{label || "Search"}'
          disabled='{disabled}'
          class="absolute right-2 inline-flex size-9 items-center justify-center rounded-lg bg-[var(--wire-color-primary)] text-[var(--wire-color-on-primary)] transition hover:bg-[var(--wire-color-primary-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--wire-color-focus)] disabled:cursor-not-allowed disabled:opacity-60"
        >
          <span class="icon-[lucide--arrow-right] size-4" aria-hidden="true"></span>
        </button>
      </div>
    </form>
  }
}
```

---

## Section

Showcase: https://component.wrnexusjs.dev/
Mount: <Section /> (legacy: data-component="Section")
Category: layout
Purpose: Theme-aware page section with consistent spacing, width, background, and border controls.
Props: id: string = "", size: string = "default", color: string = "primary", variant: string = "default", spacing: string = "lg", maxWidth: string = "xl", fullWidth: boolean = false, borderTop: boolean = false, borderBottom: boolean = false, class: string = ""
Slots: default
Events: none

### Complete .wrn source contract

```wrn
component Section {
  props {
    id = ""
    size = "default"
    color = "primary"
    variant = "default"
    spacing = "lg"
    maxWidth = "xl"
    fullWidth = false
    borderTop = false
    borderBottom = false
    class = ""
  }

  view {
    <section
      data-ui-component="Section"
      id='{id}'
      data-size='{size}'
      data-color='{color}'
      data-variant='{variant}'
      class='relative isolate w-full {class}'
      class:py-8='spacing === "sm"'
      class:py-12='spacing === "md"'
      class:py-16='spacing === "lg"'
      class:sm:py-20='spacing === "lg"'
      class:py-20='spacing === "xl"'
      class:sm:py-24='spacing === "xl"'
      class:bg-[var(--wire-color-background)]='variant === "default"'
      class:bg-[var(--wire-color-surface-soft)]='variant === "soft"'
      class:bg-[var(--wire-color-surface-raised)]='variant === "raised"'
      class:bg-[var(--wire-color-primary-soft)]='variant === "tinted" && color === "primary"'
      class:bg-[var(--wire-color-success-soft)]='variant === "tinted" && color === "success"'
      class:bg-[var(--wire-color-warning-soft)]='variant === "tinted" && color === "warning"'
      class:bg-[var(--wire-color-danger-soft)]='variant === "tinted" && color === "danger"'
      class:bg-[var(--wire-color-info-soft)]='variant === "tinted" && color === "info"'
      class:bg-[var(--wire-color-primary)]='variant === "solid" && color === "primary"'
      class:text-[var(--wire-color-on-primary)]='variant === "solid" && color === "primary"'
      class:bg-[var(--wire-color-danger)]='variant === "solid" && color === "danger"'
      class:text-[var(--wire-color-on-danger)]='variant === "solid" && color === "danger"'
      class:border-t='borderTop'
      class:border-b='borderBottom'
      class:border-[var(--wire-color-border)]='borderTop || borderBottom'
    >
      {#if fullWidth}
        <slot></slot>
      {:else}
        <Container
          columns="1"
          gap="md"
          maxWidth='{maxWidth}'
          size='{size}'
          color='{color}'
        >
          <slot></slot>
        </Container>
      {/if}
    </section>
  }
}
```

---

## SectionHeader

Showcase: https://component.wrnexusjs.dev/
Mount: <SectionHeader /> (legacy: data-component="SectionHeader")
Category: layout
Purpose: Reusable accessible section heading with eyebrow, title, description, icon, and actions.
Props: id: string = "", eyebrow: string = "", title: string = "", description: string = "", align: string = "left", size: string = "default", color: string = "primary", headingLevel: number = 2, maxWidth: string = "3xl", class: string = ""
Slots: icon, default, actions
Events: none

### Complete .wrn source contract

```wrn
component SectionHeader {
  props {
    id = ""
    eyebrow = ""
    title = ""
    description = ""
    align = "left"
    size = "default"
    color = "primary"
    headingLevel = 2
    maxWidth = "3xl"
    class = ""
  }

  view {
    <header
      data-ui-component="SectionHeader"
      class='flex min-w-0 flex-col gap-5 {class}'
      class:items-center='align === "center"'
      class:text-center='align === "center"'
      class:items-end='align === "right"'
      class:text-right='align === "right"'
      class:lg:flex-row='align === "split"'
      class:lg:items-end='align === "split"'
      class:lg:justify-between='align === "split"'
    >
      <div
        class="min-w-0"
        class:max-w-xl='maxWidth === "xl"'
        class:max-w-2xl='maxWidth === "2xl"'
        class:max-w-3xl='maxWidth === "3xl"'
        class:max-w-4xl='maxWidth === "4xl"'
        class:mx-auto='align === "center"'
      >
        <div class="mb-3 flex items-center gap-3" class:justify-center='align === "center"' class:justify-end='align === "right"'>
          <slot name="icon"></slot>

          {#if eyebrow}
            <p
              class="text-xs font-bold uppercase tracking-[0.18em]"
              class:text-sm='size === "lg"'
              class:text-[var(--wire-color-primary)]='color === "primary"'
              class:text-[var(--wire-color-secondary)]='color === "secondary"'
              class:text-[var(--wire-color-success)]='color === "success"'
              class:text-[var(--wire-color-warning-text)]='color === "warning"'
              class:text-[var(--wire-color-danger)]='color === "danger"'
              class:text-[var(--wire-color-info)]='color === "info"'
            >
              {eyebrow}
            </p>
          {/if}
        </div>

        {#if headingLevel === 1}
          <h1
            id='{id}'
            class="font-bold leading-tight tracking-tight text-[var(--wire-color-text)]"
            class:text-3xl='size === "sm"'
            class:text-4xl='size === "default" || size === "md"'
            class:sm:text-5xl='size === "default" || size === "md"'
            class:text-5xl='size === "lg"'
            class:sm:text-6xl='size === "lg"'
          >
            {title}
          </h1>
        {:else if headingLevel === 3}
          <h3
            id='{id}'
            class="font-bold leading-tight tracking-tight text-[var(--wire-color-text)]"
            class:text-xl='size === "sm"'
            class:text-2xl='size === "default" || size === "md"'
            class:text-3xl='size === "lg"'
          >
            {title}
          </h3>
        {:else}
          <h2
            id='{id}'
            class="font-bold leading-tight tracking-tight text-[var(--wire-color-text)]"
            class:text-2xl='size === "sm"'
            class:text-3xl='size === "default" || size === "md"'
            class:sm:text-4xl='size === "default" || size === "md"'
            class:text-4xl='size === "lg"'
            class:sm:text-5xl='size === "lg"'
          >
            {title}
          </h2>
        {/if}

        {#if description}
          <p
            class="mt-4 leading-7 text-[var(--wire-color-text-muted)]"
            class:text-sm='size === "sm"'
            class:text-base='size === "default" || size === "md"'
            class:text-lg='size === "lg"'
          >
            {description}
          </p>
        {/if}

        <slot></slot>
      </div>

      <div
        class="flex shrink-0 flex-wrap items-center gap-3"
        class:justify-center='align === "center"'
        class:justify-end='align === "right" || align === "split"'
      >
        <slot name="actions"></slot>
      </div>
    </header>
  }
}
```

---

## Select

Showcase: https://component.wrnexusjs.dev/
Mount: <Select /> (legacy: data-component="Select")
Category: forms
Purpose: Theme-aware, responsive select component.
Props: size: string = "default", color: string = "primary", id: string = "", name: string = "", label: string = "Select", hiddenLabel: boolean = false, value: string = "", values: string = [], options: string = [], placeholder: string = "Select an option", variant: string = "normal", icon: string = "", iconPosition: string = "start", helperText: string = "", cornerHint: string = "", error: string = "", inline: boolean = false, multiple: boolean = false, readonly: boolean = false, disabled: boolean = false, required: boolean = false, class: string = ""
Slots: none
Events: input, change, focus, blur, open, close, invalid

### Complete .wrn source contract

```wrn
component Select {
  props {
    @event input = function
    @event change = function
    @event focus = function
    @event blur = function
    @event open = function
    @event close = function
    @event invalid = function
    size = "default"
    color = "primary"
    id = ""
    name = ""
    label = "Select"
    hiddenLabel = false
    value = ""
    values = []
    options = []
    placeholder = "Select an option"
    variant = "normal"
    icon = ""
    iconPosition = "start"
    helperText = ""
    cornerHint = ""
    error = ""
    inline = false
    multiple = false
    readonly = false
    disabled = false
    required = false
    class = ""
  }
  functions {
    function selected(option) {
      if (multiple) return values.includes(option.value)
      return option.value === value
    }
    function emitField(nameEvent, sourceEvent) {
      sourceEvent.stopPropagation()
      $emit(nameEvent, { value: sourceEvent.currentTarget.value, name: name, sourceEvent: sourceEvent })
    }
    function handleFocus(sourceEvent) { emitField("focus", sourceEvent); $emit("open", { name: name, sourceEvent: sourceEvent }) }
    function handleBlur(sourceEvent) { emitField("blur", sourceEvent); $emit("close", { name: name, sourceEvent: sourceEvent }) }
    function handleInvalid(sourceEvent) { $emit("invalid", { name: name, message: sourceEvent.currentTarget.validationMessage, sourceEvent: sourceEvent }) }
  }
  view {
    <div {...attrs} class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--field wire-next--select {class}" data-variant="{variant}" data-inline="{inline}" data-floating="{variant === 'floating'}" data-invalid="{error ? 'true' : 'false'}" data-readonly="{readonly}">
      <div class="wire-next__field-heading"><label class="{hiddenLabel ? 'wire-next__sr-only' : ''}" for="{id || name}">{label}</label>{#if cornerHint}<span class="wire-next__field-hint">{cornerHint}</span>{/if}</div>
      <div class="wire-next__field-control" data-icon-position="{iconPosition}">
        {#if icon}<span class="{icon} wire-next__field-icon" aria-hidden="true"></span>{/if}
        <select id="{id || name}" name="{name}" multiple="{multiple}" disabled="{disabled || readonly}" required="{required}" aria-readonly="{readonly}" aria-invalid="{error ? 'true' : 'false'}" @input="emitField('input', event)" @change="emitField('change', event)" @focus="handleFocus(event)" @blur="handleBlur(event)" @invalid="handleInvalid(event)">
          {#if !multiple}<option value="" selected="{value === ''}" disabled="{required}">{placeholder}</option>{/if}
          {#each options as option}<option value="{option.value}" selected="{selected(option)}" disabled="{option.disabled}">{option.label}</option>{/each}
        </select>
        {#if variant === "floating"}<span class="wire-next__field-floating-label">{label}</span>{/if}
      </div>
      {#if helperText}<small class="wire-next__field-help">{helperText}</small>{/if}
      <small class="wire-next__field-error" data-error="{name}">{error}</small>
    </div>
  }
}
```

---

## Sidebar

Showcase: https://component.wrnexusjs.dev/
Mount: <Sidebar /> (legacy: data-component="Sidebar")
Category: navigation
Purpose: Theme-aware, responsive sidebar component.
Props: size: string = "default", color: string = "primary", label: string = "Sidebar", items: string = [], active: string = "", orientation: string = "horizontal", mobileLabel: string = "Open navigation", class: string = ""
Slots: default
Events: toggle, open, close, select

### Complete .wrn source contract

```wrn
component Sidebar {
  props {
    @event toggle = function
    @event open = function
    @event close = function
    @event select = function
    size = "default"
    color = "primary"
    label = "Sidebar"
    items = []
    active = ""
    orientation = "horizontal"
    mobileLabel = "Open navigation"
    class = ""
  }

  state mobileOpen = false

  functions {
    function toggleSidebar() {
      mobileOpen = !mobileOpen
      $emit("toggle", { open: mobileOpen })
      $emit(mobileOpen ? "open" : "close", { source: "mobile" })
    }

    function closeSidebar() {
      mobileOpen = false
      $emit("close", { source: "mobile" })
    }

    function selectItem(item, level) {
      mobileOpen = false
      $emit("select", { item: item, value: item.value || "", level: level })
    }
  }

  view {
    <div class="wire-sidebar-shell wire-next--color-{color} wire-next--size-{size} {mobileOpen ? 'is-open' : ''} {class}">
      <button type="button" class="wire-sidebar-toggle" aria-label="{mobileLabel}" aria-expanded="{mobileOpen}" @click="toggleSidebar()">
        <span class="icon-[lucide--panel-left-open]" aria-hidden="true"></span>
        <span>{label}</span>
      </button>
      <button type="button" class="wire-sidebar-backdrop" aria-label="Close navigation" @click="closeSidebar()"></button>
      <nav class="wire-next wire-next--sidebar wire-next--{orientation} wire-sidebar-panel" aria-label="{label}">
        <div class="wire-sidebar-panel__head">
          <strong>{label}</strong>
          <button type="button" aria-label="Close navigation" @click="closeSidebar()"><span class="icon-[lucide--x]" aria-hidden="true"></span></button>
        </div>
        <div class="wire-sidebar-items">
          {#each items as item}
            {#if item.children && item.children.length}
              <details class="wire-sidebar-group" name="wire-sidebar-group">
                <summary>
                  {#if item.icon}<span class="{item.icon}" aria-hidden="true"></span>{/if}
                  <span>{item.label}</span>
                  <span class="icon-[lucide--chevron-down]" aria-hidden="true"></span>
                </summary>
                <div class="wire-sidebar-group__children">
                  {#each item.children as child}
                    <a href="{child.href || '#'}" aria-current="{child.value === active ? 'page' : ''}" @click="selectItem(child, 2)">
                      {#if child.icon}<span class="{child.icon}" aria-hidden="true"></span>{/if}
                      <span>{child.label}</span>
                    </a>
                  {/each}
                </div>
              </details>
            {:else}
              <a href="{item.href || '#'}" aria-current="{item.value === active ? 'page' : ''}" @click="selectItem(item, 1)">
                {#if item.icon}<span class="{item.icon}" aria-hidden="true"></span>{/if}
                <span>{item.label}</span>
              </a>
            {/if}
          {/each}
        </div>
        <slot />
      </nav>
    </div>
  }
}
```

---

## Skeleton

Showcase: https://component.wrnexusjs.dev/
Mount: <Skeleton /> (legacy: data-component="Skeleton")
Category: base
Purpose: Theme-aware, responsive skeleton component.
Props: color: string = "primary", label: string = "Loading", size: string = "md", lines: number = 3, class: string = ""
Slots: none
Events: none

### Complete .wrn source contract

```wrn
component Skeleton {
  props {
    color = "primary"
    label = "Loading"
    size = "md"
    lines = 3
    class = ""
  }
  view {
    <div class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--skeleton wire-next--size-{size} {class}" role="status" aria-label="{label}">
      {#if "Skeleton" === "Skeleton"}{#each Array(lines).fill(0) as line}<span></span>{/each}{:else}<i aria-hidden="true"></i>{/if}
    </div>
  }
}
```

---

## Spinner

Showcase: https://component.wrnexusjs.dev/
Mount: <Spinner /> (legacy: data-component="Spinner")
Category: base
Purpose: Theme-aware, responsive spinner component.
Props: color: string = "primary", label: string = "Loading", size: string = "md", lines: number = 3, class: string = ""
Slots: none
Events: none

### Complete .wrn source contract

```wrn
component Spinner {
  props {
    color = "primary"
    label = "Loading"
    size = "md"
    lines = 3
    class = ""
  }
  view {
    <div class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--spinner wire-next--size-{size} {class}" role="status" aria-label="{label}">
      {#if "Spinner" === "Skeleton"}{#each Array(lines).fill(0) as line}<span></span>{/each}{:else}<i aria-hidden="true"></i>{/if}
    </div>
  }
}
```

---

## SplitHero

Showcase: https://component.wrnexusjs.dev/
Mount: <SplitHero /> (legacy: data-component="SplitHero")
Category: blocks
Purpose: Two-column hero with configurable content and visual placement.
Props: eyebrow: string = "", title: string = "A better digital experience", highlight: string = "", description: string = "", primaryLabel: string = "", primaryHref: string = "", primaryIcon: string = "", secondaryLabel: string = "", secondaryHref: string = "", secondaryIcon: string = "", visualPosition: string = "right", reverse: boolean = false, ratio: string = "balanced", size: string = "default", color: string = "primary", variant: string = "default", trustItems: string = [], class: string = ""
Slots: actions, trust, default, visual
Events: none

### Complete .wrn source contract

```wrn
component SplitHero {
  props {
    eyebrow = ""
    title = "A better digital experience"
    highlight = ""
    description = ""
    primaryLabel = ""
    primaryHref = ""
    primaryIcon = ""
    secondaryLabel = ""
    secondaryHref = ""
    secondaryIcon = ""
    visualPosition = "right"
    reverse = false
    ratio = "balanced"
    size = "default"
    color = "primary"
    variant = "default"
    trustItems = []
    class = ""
  }

  view {
    <Section
      spacing='{size === "compact" ? "md" : "xl"}'
      variant='{variant === "soft" ? "soft" : "default"}'
      color='{color}'
      class='overflow-hidden {class}'
    >
      <div
        data-ui-component="SplitHero"
        class="grid items-center gap-10 lg:grid-cols-2 lg:gap-16"
        class:lg:grid-cols-[1.15fr_0.85fr]='ratio === "content"'
        class:lg:grid-cols-[0.85fr_1.15fr]='ratio === "visual"'
      >
        <div
          class="max-w-3xl"
          class:lg:order-2='reverse || visualPosition === "left"'
        >
          {#if eyebrow}
            <div class="mb-6 inline-flex items-center gap-2 rounded-full border border-[var(--wire-color-primary-muted)] bg-[var(--wire-color-primary-soft)] px-4 py-2 text-sm font-semibold text-[var(--wire-color-primary)]">
              <span class="icon-[lucide--sparkles] size-4" aria-hidden="true"></span>
              <span>{eyebrow}</span>
            </div>
          {/if}

          <h1 class="text-4xl font-bold leading-[1.08] tracking-[-0.035em] text-[var(--wire-color-text)] sm:text-5xl lg:text-6xl">
            <span>{title}</span>
            {#if highlight}
              <span class="block text-[var(--wire-color-primary)]">{highlight}</span>
            {/if}
          </h1>

          {#if description}
            <p class="mt-6 text-base leading-8 text-[var(--wire-color-text-muted)] sm:text-lg">{description}</p>
          {/if}

          <HeroActions
            actions='{[
              { label: primaryLabel, href: primaryHref, icon: primaryIcon, variant: "default", color: color },
              { label: secondaryLabel, href: secondaryHref, icon: secondaryIcon, variant: "outline", color: color }
            ]}'
            align="left"
            stackOnMobile="true"
            fullWidthMobile="true"
            size="lg"
            color='{color}'
            class="mt-8"
          >
            <slot name="actions"></slot>
          </HeroActions>

          {#if trustItems.length > 0}
            <div class="mt-8 flex flex-wrap gap-x-6 gap-y-3 text-sm text-[var(--wire-color-text-muted)]">
              {#each trustItems as item}
                <span class="inline-flex items-center gap-2">
                  <span class='{(item.icon || "icon-[lucide--check-circle-2]") + " size-4 text-[var(--wire-color-primary)]"}' aria-hidden="true"></span>
                  <span>{item.label || item.title || item}</span>
                </span>
              {/each}
            </div>
          {/if}

          <slot name="trust"></slot>
          <slot></slot>
        </div>

        <div
          class="relative min-w-0"
          class:lg:order-1='reverse || visualPosition === "left"'
        >
          <div class="absolute -inset-8 -z-10 rounded-[2.5rem] bg-[var(--wire-color-primary-soft)] blur-2xl" aria-hidden="true"></div>
          <slot name="visual"></slot>
        </div>
      </div>
    </Section>
  }
}
```

---

## StatsBar

Showcase: https://component.wrnexusjs.dev/
Mount: <StatsBar /> (legacy: data-component="StatsBar")
Category: blocks
Purpose: Compact responsive statistics strip.
Props: items: string = [], columns: number = 4, compact: boolean = true, dividers: boolean = true, icons: boolean = true, size: string = "default", color: string = "primary", variant: string = "raised", maxWidth: string = "xl", class: string = ""
Slots: none
Events: none

### Complete .wrn source contract

```wrn
component StatsBar {
  props {
    items = []
    columns = 4
    compact = true
    dividers = true
    icons = true
    size = "default"
    color = "primary"
    variant = "raised"
    maxWidth = "xl"
    class = ""
  }

  view {
    <Section
      spacing='{compact ? "sm" : "md"}'
      variant='{variant}'
      color='{color}'
      maxWidth='{maxWidth}'
      borderTop="true"
      borderBottom="true"
      class='{class}'
    >
      <div data-ui-component="StatsBar">
        <MetricGrid
          items='{items.map((item) => ({ ...item, icon: icons ? item.icon : "", variant: "minimal", size: compact ? "sm" : size }))}'
          columns='{columns}'
          tabletColumns="2"
          mobileColumns="1"
          gap='{compact ? "sm" : "md"}'
          dividers='{dividers}'
          size='{compact ? "sm" : size}'
          color='{color}'
          variant="minimal"
        />
      </div>
    </Section>
  }
}
```

---

## Stepper

Showcase: https://component.wrnexusjs.dev/
Mount: <Stepper /> (legacy: data-component="Stepper")
Category: navigation
Purpose: Theme-aware, responsive stepper component.
Props: size: string = "default", color: string = "primary", label: string = "Stepper", items: string = [], active: string = "", orientation: string = "horizontal", class: string = ""
Slots: default
Events: change, previous, next, complete

### Complete .wrn source contract

```wrn
component Stepper {
  props {
    @event change = function
    @event previous = function
    @event next = function
    @event complete = function
    size = "default"
    color = "primary"
    label = "Stepper"
    items = []
    active = ""
    orientation = "horizontal"
    class = ""
  }
  view {
    <nav class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--stepper wire-next--{orientation} {class}" aria-label="{label}">
      {#each items as item}<a href="{item.href}" aria-current="{item.value === active ? 'page' : ''}">{item.label}</a>{/each}
      <slot />
    </nav>
  }
}
```

---

## StrongPassword

Showcase: https://component.wrnexusjs.dev/
Mount: <StrongPassword /> (legacy: data-component="StrongPassword")
Category: advanced-forms
Purpose: Theme-aware, responsive strong password component.
Props: size: string = "default", color: string = "primary", label: string = "Password", name: string = "password", value: string = "", placeholder: string = "Create a strong password", autocomplete: string = "new-password", minLength: number = 8, specialCharactersSet: string = "!@#$%^&*()_+-=[]{}|;:,.<>?", requireLowercase: boolean = true, requireUppercase: boolean = true, requireNumber: boolean = true, requireSpecialCharacter: boolean = true, showRequirements: boolean = true, presentation: string = "inline", hintText: string = "Use a unique password you do not use elsewhere.", emptyLabel: string = "Enter a password", weakLabel: string = "Weak", fairLabel: string = "Fair", goodLabel: string = "Good", strongLabel: string = "Strong", disabled: boolean = false, readonly: boolean = false, required: boolean = false, invalid: boolean = false, validationMessage: string = "", class: string = ""
Slots: none
Events: input, change, strength

### Complete .wrn source contract

```wrn
component StrongPassword {
  props {
    size = "default"
    color = "primary"
    label = "Password"
    name = "password"
    value = ""
    placeholder = "Create a strong password"
    autocomplete = "new-password"
    minLength = 8
    specialCharactersSet = "!@#$%^&*()_+-=[]{}|;:,.<>?"
    requireLowercase = true
    requireUppercase = true
    requireNumber = true
    requireSpecialCharacter = true
    showRequirements = true
    presentation = "inline"
    hintText = "Use a unique password you do not use elsewhere."
    emptyLabel = "Enter a password"
    weakLabel = "Weak"
    fairLabel = "Fair"
    goodLabel = "Good"
    strongLabel = "Strong"
    disabled = false
    readonly = false
    required = false
    invalid = false
    validationMessage = ""
    class = ""
    @event input = function
    @event change = function
    @event strength = function
  }

  state password = value
  state detailsOpen = false

  functions {
    function hasMinimumLength() {
      return password.length >= Number(minLength)
    }

    function hasLowercase() {
      return password !== password.toUpperCase()
    }

    function hasUppercase() {
      return password !== password.toLowerCase()
    }

    function hasNumber() {
      return containsCharacterAt("0123456789", 0)
    }

    function hasSpecialCharacter() {
      return containsCharacterAt(specialCharactersSet, 0)
    }

    function containsCharacterAt(characters, index) {
      if (index >= characters.length) {
        return false
      }
      if (password.includes(characters[index])) {
        return true
      }
      return containsCharacterAt(characters, index + 1)
    }

    function score() {
      return (hasMinimumLength() ? 1 : 0) + (requireLowercase && hasLowercase() ? 1 : 0) + (requireUppercase && hasUppercase() ? 1 : 0) + (requireNumber && hasNumber() ? 1 : 0) + (requireSpecialCharacter && hasSpecialCharacter() ? 1 : 0)
    }

    function maximumScore() {
      return 1 + (requireLowercase ? 1 : 0) + (requireUppercase ? 1 : 0) + (requireNumber ? 1 : 0) + (requireSpecialCharacter ? 1 : 0)
    }

    function strengthPercent() {
      return Math.round(score() / maximumScore() * 100)
    }

    function strengthLevel() {
      if (!password) {
        return "empty"
      }
      if (strengthPercent() <= 25) {
        return "weak"
      }
      if (strengthPercent() <= 50) {
        return "fair"
      }
      if (strengthPercent() < 100) {
        return "good"
      }
      return "strong"
    }

    function strengthLabel() {
      if (strengthLevel() === "weak") {
        return weakLabel
      }
      if (strengthLevel() === "fair") {
        return fairLabel
      }
      if (strengthLevel() === "good") {
        return goodLabel
      }
      if (strengthLevel() === "strong") {
        return strongLabel
      }
      return emptyLabel
    }

  }

  view {
    <div
      class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--strong-password wire-next--strong-password-{presentation} {invalid ? 'wire-next--invalid' : ''} {disabled ? 'wire-next--disabled' : ''} {class}"
      data-wrn-strong-password
      data-strength="{password ? strengthLevel() : 'empty'}"
      data-score="{password ? score() : 0}"
    >
      <label for="{name}-strong-password">{label}</label>
      <div class="wire-next__strong-password-anchor">
        <input
          {...attrs}
          id="{name}-strong-password"
          type="password"
          name="{name}"
          value="{password}"
          placeholder="{placeholder}"
          autocomplete="{autocomplete}"
          minlength="{minLength}"
          disabled="{disabled}"
          readonly="{readonly}"
          required="{required}"
          aria-invalid="{invalid ? 'true' : 'false'}"
          aria-describedby="{validationMessage ? name + '-validation' : hintText ? name + '-hint' : ''}"
          @focus="detailsOpen = true"
          @blur="detailsOpen = false"
          @input="password = event.target.value; $emit('input', { value: password, score: score(), maximumScore: maximumScore(), percent: strengthPercent(), level: strengthLevel() }); $emit('strength', { value: password, score: score(), maximumScore: maximumScore(), percent: strengthPercent(), level: strengthLevel() })"
          @change="$emit('change', { value: password, score: score(), maximumScore: maximumScore(), percent: strengthPercent(), level: strengthLevel() })"
        />

        {#if presentation === "popover"}
          <div
            class="wire-next__strong-password-popover"
            data-open="{detailsOpen ? 'true' : 'false'}"
            role="status"
          >
            <div class="wire-next__strong-password-popover-arrow" aria-hidden="true"></div>
            <div class="wire-next__strong-password-details">
              <div class="wire-next__strong-password-summary">
                <span>Password strength</span>
                <strong>{password ? strengthLabel() : emptyLabel}</strong>
              </div>
              <div
                class="wire-next__strong-password-meter"
                role="progressbar"
                aria-label="Password strength"
                aria-valuemin="0"
                aria-valuemax="100"
                aria-valuenow="{password ? strengthPercent() : 0}"
              >
                <span style="width: {password ? strengthPercent() : 0}%"></span>
              </div>
              {#if showRequirements}
                <ul class="wire-next__strong-password-requirements">
                  <li data-met="{password && hasMinimumLength() ? 'true' : 'false'}">
                    <span aria-hidden="true"></span>At least {minLength} characters
                  </li>
                  {#if requireLowercase}<li data-met="{password && hasLowercase() ? 'true' : 'false'}"><span aria-hidden="true"></span>One lowercase letter</li>{/if}
                  {#if requireUppercase}<li data-met="{password && hasUppercase() ? 'true' : 'false'}"><span aria-hidden="true"></span>One uppercase letter</li>{/if}
                  {#if requireNumber}<li data-met="{password && hasNumber() ? 'true' : 'false'}"><span aria-hidden="true"></span>One number</li>{/if}
                  {#if requireSpecialCharacter}<li data-met="{password && hasSpecialCharacter() ? 'true' : 'false'}"><span aria-hidden="true"></span>One special character: {specialCharactersSet}</li>{/if}
                </ul>
              {/if}
              {#if hintText}<small id="{name}-hint">{hintText}</small>{/if}
            </div>
          </div>
        {/if}
      </div>

      {#if presentation !== "popover"}
        <div class="wire-next__strong-password-details">
          <div class="wire-next__strong-password-summary">
            <span>Password strength</span>
            <strong>{password ? strengthLabel() : emptyLabel}</strong>
          </div>
          <div
            class="wire-next__strong-password-meter"
            role="progressbar"
            aria-label="Password strength"
            aria-valuemin="0"
            aria-valuemax="100"
            aria-valuenow="{password ? strengthPercent() : 0}"
          >
            <span style="width: {password ? strengthPercent() : 0}%"></span>
          </div>
          {#if showRequirements}
            <ul class="wire-next__strong-password-requirements">
              <li data-met="{password && hasMinimumLength() ? 'true' : 'false'}"><span aria-hidden="true"></span>At least {minLength} characters</li>
              {#if requireLowercase}<li data-met="{password && hasLowercase() ? 'true' : 'false'}"><span aria-hidden="true"></span>One lowercase letter</li>{/if}
              {#if requireUppercase}<li data-met="{password && hasUppercase() ? 'true' : 'false'}"><span aria-hidden="true"></span>One uppercase letter</li>{/if}
              {#if requireNumber}<li data-met="{password && hasNumber() ? 'true' : 'false'}"><span aria-hidden="true"></span>One number</li>{/if}
              {#if requireSpecialCharacter}<li data-met="{password && hasSpecialCharacter() ? 'true' : 'false'}"><span aria-hidden="true"></span>One special character: {specialCharactersSet}</li>{/if}
            </ul>
          {/if}
          {#if hintText}<small id="{name}-hint">{hintText}</small>{/if}
        </div>
      {/if}

      <small id="{name}-validation" class="wire-next__validation" data-error="{name}">{validationMessage}</small>
    </div>
  }
}
```

---

## StyledIcon

Showcase: https://component.wrnexusjs.dev/
Mount: <StyledIcon /> (legacy: data-component="StyledIcon")
Category: base
Purpose: Theme-aware, responsive styled icon component.
Props: size: string = "default", color: string = "primary", title: string = "Styled Icon", description: string = "", items: string = [], variant: string = "default", class: string = ""
Slots: default
Events: none

### Complete .wrn source contract

```wrn
component StyledIcon {
  props {
    size = "default"
    color = "primary"
    title = "Styled Icon"
    description = ""
    items = []
    variant = "default"
    class = ""
  }
  view {
    <section class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--styled-icon wire-next--variant-{variant} {class}">
      {#if title}<strong>{title}</strong>{/if}
      {#if description}<p>{description}</p>{/if}
      {#if items}<div class="wire-next__items">{#each items as item}<span>{item.label}</span>{/each}</div>{/if}
      <slot />
    </section>
  }
}
```

---

## Switch

Showcase: https://component.wrnexusjs.dev/
Mount: <Switch /> (legacy: data-component="Switch")
Category: forms
Purpose: Theme-aware, responsive switch component.
Props: size: string = "default", color: string = "primary", id: string = "", name: string = "", label: string = "Switch", hiddenLabel: boolean = false, placeholder: string = "", variant: string = "normal", icon: string = "", iconPosition: string = "start", value: string = "on", checked: boolean = false, helperText: string = "", cornerHint: string = "", error: string = "", inline: boolean = false, readonly: boolean = false, disabled: boolean = false, required: boolean = false, class: string = ""
Slots: none
Events: input, change, focus, blur

### Complete .wrn source contract

```wrn
component Switch {
  props {
    @event input = function
    @event change = function
    @event focus = function
    @event blur = function
    size = "default"
    color = "primary"
    id = ""
    name = ""
    label = "Switch"
    hiddenLabel = false
    placeholder = ""
    variant = "normal"
    icon = ""
    iconPosition = "start"
    value = "on"
    checked = false
    helperText = ""
    cornerHint = ""
    error = ""
    inline = false
    readonly = false
    disabled = false
    required = false
    class = ""
  }
  functions {
    function emitField(nameEvent, sourceEvent) { sourceEvent.stopPropagation(); $emit(nameEvent, { checked: sourceEvent.currentTarget.checked, value: value, name: name, sourceEvent: sourceEvent }) }
    function preventReadonly(sourceEvent) { if (readonly) sourceEvent.preventDefault() }
  }
  view {
    <div {...attrs} class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--choice-field {class}" data-inline="{inline}" data-invalid="{error ? 'true' : 'false'}">
      <div class="wire-next__field-heading">{#if cornerHint}<span class="{hiddenLabel ? 'wire-next__sr-only' : ''}">{label}</span><span class="wire-next__field-hint">{cornerHint}</span>{/if}</div>
      <label class="wire-next__choice wire-next--switch" for="{id || name}" data-variant="{variant}" data-icon-position="{iconPosition}"><input id="{id || name}" type="checkbox" role="switch" name="{name}" value="{value}" checked="{checked}" disabled="{disabled}" required="{required}" readonly="{readonly}" aria-checked="{checked ? 'true' : 'false'}" aria-invalid="{error ? 'true' : 'false'}" @click="preventReadonly(event)" @input="emitField('input', event)" @change="emitField('change', event)" @focus="emitField('focus', event)" @blur="emitField('blur', event)" />{#if icon}<span class="{icon}" aria-hidden="true"></span>{/if}<span class="{hiddenLabel || cornerHint ? 'wire-next__sr-only' : ''}">{label}</span></label>
      {#if helperText}<small class="wire-next__field-help">{helperText}</small>{/if}<small class="wire-next__field-error" data-error="{name}">{error}</small>
    </div>
  }
}
```

---

## Table

Showcase: https://component.wrnexusjs.dev/
Mount: <Table /> (legacy: data-component="Table")
Category: tables
Purpose: Theme-aware, responsive table component.
Props: size: string = "default", color: string = "primary", caption: string = "Table", columns: string = [], rows: string = [], striped: boolean = true, class: string = ""
Slots: default
Events: sort, select, rowClick

### Complete .wrn source contract

```wrn
component Table {
  props {
    @event sort = function
    @event select = function
    @event rowClick = function
    size = "default"
    color = "primary"
    caption = "Table"
    columns = []
    rows = []
    striped = true
    class = ""
  }
  view {
    <div class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--table {class}"><table><caption>{caption}</caption><thead><tr>{#each columns as column}<th>{column.label}</th>{/each}</tr></thead><tbody>{#each rows as row}<tr>{#each columns as column}<td>{row[column.key]}</td>{/each}</tr>{/each}</tbody></table><slot /></div>
  }
}
```

---

## Tabs

Showcase: https://component.wrnexusjs.dev/
Mount: <Tabs /> (legacy: data-component="Tabs")
Category: navigation
Purpose: Theme-aware, responsive tabs component.
Props: size: string = "default", color: string = "primary", label: string = "Tabs", items: string = [], active: string = "", orientation: string = "horizontal", class: string = ""
Slots: default
Events: none

### Complete .wrn source contract

```wrn
component Tabs {
  props {
    size = "default"
    color = "primary"
    label = "Tabs"
    items = []
    active = ""
    orientation = "horizontal"
    class = ""
  }

  state activeValue = active || (items[0] ? (items[0].value || items[0].id || "0") : "")

  view {
    <section
      data-ui-component="Tabs"
      class='w-full {class}'
      class:flex='orientation === "vertical"'
      class:items-start='orientation === "vertical"'
      class:gap-6='orientation === "vertical"'
    >
      <div
        role="tablist"
        aria-label='{label}'
        aria-orientation='{orientation}'
        class="flex min-w-0 gap-1 overflow-x-auto rounded-xl border border-[var(--wire-color-border)] bg-[var(--wire-color-surface-soft)] p-1"
        class:flex-col='orientation === "vertical"'
        class:w-56='orientation === "vertical"'
        class:shrink-0='orientation === "vertical"'
      >
        {#each items as item, index}
          <button
            type="button"
            role="tab"
            id='tab-{item.value || item.id || index}'
            aria-selected='{activeValue === (item.value || item.id || String(index))}'
            aria-controls='panel-{item.value || item.id || index}'
            tabindex='{activeValue === (item.value || item.id || String(index)) ? "0" : "-1"}'
            disabled='{item.disabled || false}'
            class="inline-flex min-w-max flex-1 items-center justify-center gap-2 rounded-lg px-4 py-2.5 text-sm font-semibold outline-none transition disabled:cursor-not-allowed disabled:opacity-50"
            class:bg-[var(--wire-color-surface-raised)]='activeValue === (item.value || item.id || String(index))'
            class:text-[var(--wire-color-primary)]='activeValue === (item.value || item.id || String(index))'
            class:shadow-sm='activeValue === (item.value || item.id || String(index))'
            class:text-[var(--wire-color-text-muted)]='activeValue !== (item.value || item.id || String(index))'
            class:hover:text-[var(--wire-color-text)]='activeValue !== (item.value || item.id || String(index))'
            class:justify-start='orientation === "vertical"'
            class:px-3='size === "sm"'
            class:py-2='size === "sm"'
            class:px-5='size === "lg"'
            class:py-3='size === "lg"'
            @click='activeValue = item.value || item.id || String(index); event.currentTarget.dispatchEvent(new CustomEvent("change", { bubbles: true, detail: { item: item, index: index, value: activeValue } })); event.currentTarget.dispatchEvent(new CustomEvent("select", { bubbles: true, detail: { item: item, index: index, value: activeValue } }))'
          >
            {#if item.icon}
              <span class='{item.icon + " size-4"}' aria-hidden="true"></span>
            {/if}
            <span>{item.label || item.title}</span>
            {#if item.badge}
              <span class="rounded-full bg-[var(--wire-color-primary-soft)] px-2 py-0.5 text-xs text-[var(--wire-color-primary)]">{item.badge}</span>
            {/if}
          </button>
        {/each}
      </div>

      <div class="min-w-0 flex-1 pt-4" class:pt-0='orientation === "vertical"'>
        {#each items as item, index}
          <div
            role="tabpanel"
            id='panel-{item.value || item.id || index}'
            aria-labelledby='tab-{item.value || item.id || index}'
            tabindex="0"
            data-show='activeValue === (item.value || item.id || String(index))'
            class="rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-[var(--wire-color-focus)]"
          >
            {#if item.title && item.title !== item.label}
              <h3 class="text-lg font-bold text-[var(--wire-color-text)]">{item.title}</h3>
            {/if}
            {#if item.description}
              <p class="mt-2 leading-7 text-[var(--wire-color-text-muted)]">{item.description}</p>
            {/if}
            {#if item.content}
              <div class="mt-4 text-[var(--wire-color-text)]">{item.content}</div>
            {/if}
          </div>
        {/each}

        <slot></slot>
      </div>
    </section>
  }
}
```

---

## Textarea

Showcase: https://component.wrnexusjs.dev/
Mount: <Textarea /> (legacy: data-component="Textarea")
Category: forms
Purpose: Theme-aware, responsive textarea component.
Props: size: string = "default", color: string = "primary", id: string = "", name: string = "", label: string = "Textarea", hiddenLabel: boolean = false, placeholder: string = "", value: string = "", variant: string = "normal", icon: string = "", iconPosition: string = "start", helperText: string = "", cornerHint: string = "", error: string = "", inline: boolean = false, rows: number = 5, resize: string = "vertical", readonly: boolean = false, disabled: boolean = false, required: boolean = false, minlength: string = "", maxlength: string = "", class: string = ""
Slots: none
Events: input, change, focus, blur, invalid

### Complete .wrn source contract

```wrn
component Textarea {
  props {
    @event input = function
    @event change = function
    @event focus = function
    @event blur = function
    @event invalid = function
    size = "default"
    color = "primary"
    id = ""
    name = ""
    label = "Textarea"
    hiddenLabel = false
    placeholder = ""
    value = ""
    variant = "normal"
    icon = ""
    iconPosition = "start"
    helperText = ""
    cornerHint = ""
    error = ""
    inline = false
    rows = 5
    resize = "vertical"
    readonly = false
    disabled = false
    required = false
    minlength = ""
    maxlength = ""
    class = ""
  }
  functions {
    function emitField(nameEvent, sourceEvent) {
      sourceEvent.stopPropagation()
      $emit(nameEvent, { value: sourceEvent.currentTarget.value, name: name, sourceEvent: sourceEvent })
    }
    function handleInvalid(sourceEvent) {
      $emit("invalid", { value: sourceEvent.currentTarget.value, name: name, message: sourceEvent.currentTarget.validationMessage, sourceEvent: sourceEvent })
    }
  }
  view {
    <div {...attrs} class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--field wire-next--textarea {class}" data-variant="{variant}" data-inline="{inline}" data-floating="{variant === 'floating'}" data-invalid="{error ? 'true' : 'false'}">
      <div class="wire-next__field-heading"><label class="{hiddenLabel ? 'wire-next__sr-only' : ''}" for="{id || name}">{label}</label>{#if cornerHint}<span class="wire-next__field-hint">{cornerHint}</span>{/if}</div>
      <div class="wire-next__field-control" data-icon-position="{iconPosition}">
        {#if icon}<span class="{icon} wire-next__field-icon" aria-hidden="true"></span>{/if}
        <textarea id="{id || name}" name="{name}" placeholder="{variant === 'floating' ? ' ' : placeholder}" rows="{rows}" style="resize: {resize}" readonly="{readonly}" disabled="{disabled}" required="{required}" minlength="{minlength}" maxlength="{maxlength}" aria-invalid="{error ? 'true' : 'false'}" aria-describedby="{error ? (id || name) + '-error' : (helperText ? (id || name) + '-help' : '')}" @input="emitField('input', event)" @change="emitField('change', event)" @focus="emitField('focus', event)" @blur="emitField('blur', event)" @invalid="handleInvalid(event)">{value}</textarea>
        {#if variant === "floating"}<span class="wire-next__field-floating-label">{label}</span>{/if}
      </div>
      {#if helperText}<small id="{(id || name) + '-help'}" class="wire-next__field-help">{helperText}</small>{/if}
      <small id="{(id || name) + '-error'}" class="wire-next__field-error" data-error="{name}">{error}</small>
    </div>
  }
}
```

---

## TextLink

Showcase: https://component.wrnexusjs.dev/
Mount: <TextLink /> (legacy: data-component="TextLink")
Category: layout
Purpose: Styled inline action link with icons, arrows, external state, and disabled handling.
Props: label: string = "Learn more", href: string = "#", target: string = "", rel: string = "", external: boolean = false, icon: string = "", iconPosition: string = "start", showArrow: boolean = true, underline: boolean = false, size: string = "default", color: string = "primary", variant: string = "default", disabled: boolean = false, class: string = ""
Slots: none
Events: click, focus, blur

### Complete .wrn source contract

```wrn
component TextLink {
  props {
    @event click = function
    @event focus = function
    @event blur = function
    label = "Learn more"
    href = "#"
    target = ""
    rel = ""
    external = false
    icon = ""
    iconPosition = "start"
    showArrow = true
    underline = false
    size = "default"
    color = "primary"
    variant = "default"
    disabled = false
    class = ""
  }

  view {
    <span
      {...attrs}
      data-ui-component="TextLink"
      data-size='{size}'
      data-color='{color}'
      data-variant='{variant}'
      class='inline-flex min-w-0 {class}'
    >
      {#if disabled}
        <span
          aria-disabled="true"
          class="inline-flex cursor-not-allowed items-center gap-2 font-semibold opacity-50"
          class:text-sm='size === "sm" || size === "default"'
          class:text-base='size === "md"'
          class:text-lg='size === "lg"'
        >
          {#if icon && iconPosition === "start"}
            <span class='{icon + " size-4 shrink-0"}' aria-hidden="true"></span>
          {/if}
          <span>{label}</span>
        </span>
      {:else}
        <a
          href='{href}'
          target='{target}'
          rel='{external ? (rel || "noopener noreferrer") : rel}'
          class="group inline-flex items-center gap-2 rounded-md font-semibold outline-none transition focus-visible:ring-2 focus-visible:ring-[var(--wire-color-focus)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--wire-color-background)]"
          class:text-sm='size === "sm" || size === "default"'
          class:text-base='size === "md"'
          class:text-lg='size === "lg"'
          class:text-[var(--wire-color-primary)]='color === "primary"'
          class:hover:text-[var(--wire-color-primary-hover)]='color === "primary"'
          class:text-[var(--wire-color-secondary)]='color === "secondary"'
          class:text-[var(--wire-color-success)]='color === "success"'
          class:text-[var(--wire-color-warning-text)]='color === "warning"'
          class:text-[var(--wire-color-danger)]='color === "danger"'
          class:text-[var(--wire-color-info)]='color === "info"'
          class:text-[var(--wire-color-text)]='color === "neutral"'
          class:underline='underline'
          class:underline-offset-4='underline'
          class:rounded-lg='variant === "button"'
          class:bg-[var(--wire-color-primary-soft)]='variant === "button" && color === "primary"'
          class:px-3='variant === "button"'
          class:py-2='variant === "button"'
        >
          {#if icon && iconPosition === "start"}
            <span class='{icon + " size-4 shrink-0"}' aria-hidden="true"></span>
          {/if}

          <span>{label}</span>

          {#if icon && iconPosition === "end"}
            <span class='{icon + " size-4 shrink-0"}' aria-hidden="true"></span>
          {/if}

          {#if external}
            <span class="icon-[lucide--external-link] size-4 shrink-0" aria-hidden="true"></span>
          {:else if showArrow}
            <span class="icon-[lucide--arrow-right] size-4 shrink-0 transition-transform group-hover:translate-x-1" aria-hidden="true"></span>
          {/if}
        </a>
      {/if}
    </span>
  }
}
```

---

## Timeline

Showcase: https://component.wrnexusjs.dev/
Mount: <Timeline /> (legacy: data-component="Timeline")
Category: base
Purpose: Theme-aware, responsive timeline component.
Props: size: string = "default", color: string = "primary", title: string = "Timeline", description: string = "", items: string = [], variant: string = "default", class: string = ""
Slots: default
Events: none

### Complete .wrn source contract

```wrn
component Timeline {
  props {
    size = "default"
    color = "primary"
    title = "Timeline"
    description = ""
    items = []
    variant = "default"
    class = ""
  }

  view {
    <section
      data-ui-component="Timeline"
      aria-label='{title}'
      class='w-full {class}'
    >
      {#if title || description}
        <header class="mb-6">
          {#if title}
            <h3 class="text-xl font-bold text-[var(--wire-color-text)]">{title}</h3>
          {/if}
          {#if description}
            <p class="mt-2 max-w-2xl leading-7 text-[var(--wire-color-text-muted)]">{description}</p>
          {/if}
        </header>
      {/if}

      <ol class="relative ml-4 border-l border-[var(--wire-color-border)]">
        {#each items as item, index}
          <li
            class="relative pb-8 pl-8 last:pb-0"
            @click='event.currentTarget.dispatchEvent(new CustomEvent("select", { bubbles: true, detail: { item: item, index: index } }))'
          >
            <span
              class="absolute -left-[1.05rem] top-0 flex size-8 items-center justify-center rounded-full border-4 border-[var(--wire-color-background)] bg-[var(--wire-color-primary)] text-[var(--wire-color-on-primary)] shadow-sm"
              class:bg-[var(--wire-color-success)]='item.status === "complete" || item.status === "success"'
              class:bg-[var(--wire-color-warning)]='item.status === "warning" || item.status === "pending"'
              class:bg-[var(--wire-color-danger)]='item.status === "danger" || item.status === "failed"'
            >
              <span class='{item.icon || "icon-[lucide--circle]"}' aria-hidden="true"></span>
            </span>

            <article
              class="rounded-2xl border border-[var(--wire-color-border)] bg-[var(--wire-color-surface-raised)] p-5 shadow-sm"
              class:border-transparent='variant === "minimal"'
              class:bg-transparent='variant === "minimal"'
              class:p-0='variant === "minimal"'
              class:shadow-none='variant === "minimal"'
            >
              <div class="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
                <div>
                  <h4 class="font-bold text-[var(--wire-color-text)]">{item.title || item.label}</h4>
                  {#if item.subtitle}
                    <p class="mt-1 text-sm font-medium text-[var(--wire-color-primary)]">{item.subtitle}</p>
                  {/if}
                </div>
                {#if item.date || item.meta}
                  <time class="shrink-0 text-sm text-[var(--wire-color-text-muted)]">{item.date || item.meta}</time>
                {/if}
              </div>

              {#if item.description}
                <p class="mt-3 text-sm leading-6 text-[var(--wire-color-text-muted)]">{item.description}</p>
              {/if}

              {#if item.href}
                <a href='{item.href}' class="mt-4 inline-flex items-center gap-2 text-sm font-semibold text-[var(--wire-color-primary)] hover:text-[var(--wire-color-primary-hover)]">
                  <span>{item.actionLabel || "View details"}</span>
                  <span class="icon-[lucide--arrow-right] size-4" aria-hidden="true"></span>
                </a>
              {/if}
            </article>
          </li>
        {:empty}
          <li class="pl-8 text-sm text-[var(--wire-color-text-muted)]">No timeline items available.</li>
        {/each}
      </ol>

      <slot></slot>
    </section>
  }
}
```

---

## TimePicker

Showcase: https://component.wrnexusjs.dev/
Mount: <TimePicker /> (legacy: data-component="TimePicker")
Category: forms
Purpose: Theme-aware, responsive time picker component.
Props: size: string = "default", color: string = "primary", id: string = "", name: string = "", label: string = "Time", hiddenLabel: boolean = false, value: string = "", placeholder: string = "", variant: string = "normal", icon: string = "icon-[lucide--clock-3]", iconPosition: string = "end", helperText: string = "", cornerHint: string = "", error: string = "", inline: boolean = false, min: string = "", max: string = "", step: string = "", format: string = "24", minuteStep: number = 5, hours: string = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"], minutes: string = ["00", "05", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55"], readonly: boolean = false, disabled: boolean = false, required: boolean = false, class: string = ""
Slots: none
Events: input, change, focus, blur, open, close, invalid

### Complete .wrn source contract

```wrn
component TimePicker {
  props {
    @event input = function
    @event change = function
    @event focus = function
    @event blur = function
    @event open = function
    @event close = function
    @event invalid = function
    size = "default"
    color = "primary"
    id = ""
    name = ""
    label = "Time"
    hiddenLabel = false
    value = ""
    placeholder = ""
    variant = "normal"
    icon = "icon-[lucide--clock-3]"
    iconPosition = "end"
    helperText = ""
    cornerHint = ""
    error = ""
    inline = false
    min = ""
    max = ""
    step = ""
    format = "24"
    minuteStep = 5
    hours = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"]
    minutes = ["00", "05", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55"]
    readonly = false
    disabled = false
    required = false
    class = ""
  }
  state currentValue = value
  state selectedHour = value ? value.split(":")[0] : "00"
  state selectedMinute = value ? value.split(":")[1] : "00"
  state expanded = false
  functions {
    function commit(part, nextValue, sourceEvent, next, detail) { if (part === "hour") { selectedHour = String(nextValue).padStart(2, "0") } if (part === "minute") { selectedMinute = String(nextValue).padStart(2, "0") } next = selectedHour + ":" + selectedMinute; if ((min && next < min) || (max && next > max)) { return } currentValue = next; detail = { value: currentValue, hour: selectedHour, minute: selectedMinute, name: name, sourceEvent: sourceEvent }; $emit("input", detail); $emit("change", detail) }
    function selectTimePart(sourceEvent, root, input, parts, hourValue, minuteValue, next, trigger, detail) { root = sourceEvent.currentTarget.closest(".wire-next--time-picker"); input = root.querySelector(".wire-next__time-value"); parts = String(input.value || value || "00:00").split(":"); hourValue = sourceEvent.currentTarget.dataset.part === "hour" ? sourceEvent.currentTarget.dataset.value : parts[0]; minuteValue = sourceEvent.currentTarget.dataset.part === "minute" ? sourceEvent.currentTarget.dataset.value : parts[1]; next = hourValue + ":" + minuteValue; if ((min && next < min) || (max && next > max)) { return } currentValue = next; input.setAttribute("value", next); trigger = root.querySelector(".wire-next__time-trigger span"); if (trigger) { trigger.replaceChildren(next) } sourceEvent.currentTarget.setAttribute("aria-pressed", "true"); detail = { value: next, hour: hourValue, minute: minuteValue, name: name, sourceEvent: sourceEvent }; $emit("input", detail); $emit("change", detail) }
    function openPicker(sourceEvent) { expanded = true; $emit("open", { value: currentValue, name: name, sourceEvent: sourceEvent }) }
    function closePicker(sourceEvent) { expanded = false; $emit("close", { value: currentValue, name: name, sourceEvent: sourceEvent }) }
    function handleFocus(sourceEvent) { $emit("focus", { value: currentValue, name: name, sourceEvent: sourceEvent }) }
    function handleBlur(sourceEvent) { $emit("blur", { value: currentValue, name: name, sourceEvent: sourceEvent }) }
    function handleInvalid(sourceEvent) { $emit("invalid", { name: name, message: sourceEvent.currentTarget.validationMessage, sourceEvent: sourceEvent }) }
  }
  view {
    <div {...attrs} class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--field wire-next--time-picker {class}" data-variant="{variant}" data-inline="{inline}" data-floating="{variant === 'floating'}" data-invalid="{error ? 'true' : 'false'}" data-expanded="{expanded}">
      <div class="wire-next__field-heading"><label class="{hiddenLabel ? 'wire-next__sr-only' : ''}" for="{id || name}">{label}</label>{#if cornerHint}<span class="wire-next__field-hint">{cornerHint}</span>{/if}</div>
      <div class="wire-next__field-control" data-icon-position="{iconPosition}">
        {#if icon}<span class="{icon} wire-next__field-icon" aria-hidden="true"></span>{/if}
        <input id="{id || name}" class="wire-next__sr-only wire-next__time-value" type="text" name="{name}" value="{currentValue}" required="{required}" readonly aria-hidden="true" tabindex="-1" @invalid="handleInvalid(event)" />
        <button type="button" class="wire-next__time-trigger" disabled="{disabled || readonly}" aria-haspopup="dialog" aria-expanded="{expanded}" @click="openPicker(event)" @focus="handleFocus(event)" @blur="handleBlur(event)"><span>{currentValue || placeholder || "Select time"}</span><i class="{icon}" aria-hidden="true"></i></button>
      </div>
      <div class="wire-next__time-panel" role="dialog" aria-label="{label}"><div><strong>Hour</strong><div class="wire-next__time-options">{#each hours as hour}<button type="button" data-part="hour" data-value="{hour}" aria-pressed="{String(hour) === selectedHour}" @click="selectTimePart(event)">{hour}</button>{/each}</div></div><div><strong>Minute</strong><div class="wire-next__time-options">{#each minutes as minute}<button type="button" data-part="minute" data-value="{minute}" aria-pressed="{String(minute) === selectedMinute}" @click="selectTimePart(event)">{minute}</button>{/each}</div></div><button type="button" class="wire-next__time-done" @click="closePicker(event)">Done</button></div>
      {#if helperText}<small class="wire-next__field-help">{helperText}</small>{/if}
      <small class="wire-next__field-error" data-error="{name}">{error}</small>
    </div>
  }
}
```

---

## Toast

Showcase: https://component.wrnexusjs.dev/
Mount: <Toast /> (legacy: data-component="Toast")
Category: base
Purpose: Theme-aware, responsive toast component.
Props: size: string = "default", color: string = "primary", title: string = "Toast", description: string = "", items: string = [], variant: string = "default", class: string = ""
Slots: default
Events: dismiss, action

### Complete .wrn source contract

```wrn
component Toast {
  props {
    @event dismiss = function
    @event action = function
    size = "default"
    color = "primary"
    title = "Toast"
    description = ""
    items = []
    variant = "default"
    class = ""
  }
  view {
    <section class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--toast wire-next--variant-{variant} {class}">
      {#if title}<strong>{title}</strong>{/if}
      {#if description}<p>{description}</p>{/if}
      {#if items}<div class="wire-next__items">{#each items as item}<span>{item.label}</span>{/each}</div>{/if}
      <slot />
    </section>
  }
}
```

---

## ToastNotifications

Showcase: https://component.wrnexusjs.dev/
Mount: <ToastNotifications /> (legacy: data-component="ToastNotifications")
Category: integrations
Purpose: Theme-aware, responsive toast notifications component.
Props: size: string = "default", color: string = "primary", title: string = "Toast Notifications", description: string = "", items: string = [], variant: string = "default", class: string = ""
Slots: default
Events: add, dismiss, clear, action

### Complete .wrn source contract

```wrn
component ToastNotifications {
  props {
    @event add = function
    @event dismiss = function
    @event clear = function
    @event action = function
    size = "default"
    color = "primary"
    title = "Toast Notifications"
    description = ""
    items = []
    variant = "default"
    class = ""
  }
  view {
    <section class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--toast-notifications wire-next--variant-{variant} {class}">
      {#if title}<strong>{title}</strong>{/if}
      {#if description}<p>{description}</p>{/if}
      {#if items}<div class="wire-next__items">{#each items as item}<span>{item.label}</span>{/each}</div>{/if}
      <slot />
    </section>
  }
}
```

---

## ToggleCount

Showcase: https://component.wrnexusjs.dev/
Mount: <ToggleCount /> (legacy: data-component="ToggleCount")
Category: advanced-forms
Purpose: Theme-aware, responsive toggle count component.
Props: size: string = "default", color: string = "primary", variant: string = "segmented", class: string = "", name: string = "billing-cycle", value: string = "monthly", firstValue: string = "monthly", firstLabel: string = "Monthly", secondValue: string = "annual", secondLabel: string = "Annual", ariaLabel: string = "Billing frequency", items: string = [], currency: string = "$", suffix: string = "", firstValueKey: string = "monthly", secondValueKey: string = "annual", emptyValue: string = "—", align: string = "end", fullWidth: boolean = true, disabled: boolean = false, animate: boolean = true, animationDuration: number = 450, animationSteps: number = 18
Slots: none
Events: change, toggle

### Complete .wrn source contract

```wrn
component ToggleCount {
  props {
    size = "default"
    color = "primary"
    variant = "segmented"
    class = ""

    name = "billing-cycle"
    value = "monthly"
    firstValue = "monthly"
    firstLabel = "Monthly"
    secondValue = "annual"
    secondLabel = "Annual"
    ariaLabel = "Billing frequency"

    items = []
    currency = "$"
    suffix = ""
    firstValueKey = "monthly"
    secondValueKey = "annual"
    emptyValue = "—"

    align = "end"
    fullWidth = true
    disabled = false
    animate = true
    animationDuration = 450
    animationSteps = 18

    @event change = function
    @event toggle = function
  }

  state selectedValue = value

  functions {
    function isFirstSelected() {
      return selectedValue === firstValue
    }

    function isSecondSelected() {
      return selectedValue === secondValue
    }

    function displayValue(item) {
      if (isSecondSelected()) {
        return item[secondValueKey] !== undefined
          ? item[secondValueKey]
          : emptyValue
      }

      return item[firstValueKey] !== undefined
        ? item[firstValueKey]
        : emptyValue
    }

    function dispatchToggleEvent(sourceEvent, previousValue, root, customEvent) {
      root = sourceEvent.currentTarget.closest("[data-wrn-toggle-count]")

      if (!root) {
        return
      }

      customEvent = document.createEvent("CustomEvent")
      customEvent.initCustomEvent("change", true, false, {
        component: "ToggleCount",
        name: name,
        value: selectedValue,
        previousValue: previousValue,
        firstValue: firstValue,
        secondValue: secondValue
      })
      root.dispatchEvent(customEvent)

      customEvent = document.createEvent("CustomEvent")
      customEvent.initCustomEvent("toggle", true, false, {
        component: "ToggleCount",
        name: name,
        value: selectedValue,
        previousValue: previousValue,
        firstValue: firstValue,
        secondValue: secondValue
      })
      root.dispatchEvent(customEvent)
    }

    function selectValue(sourceEvent, nextValue, previousValue) {
      if (disabled || selectedValue === nextValue) {
        return
      }

      previousValue = selectedValue
      selectedValue = nextValue

      if (
        animate &&
        !window.matchMedia("(prefers-reduced-motion: reduce)").matches
      ) {
        animateDisplayedValues(sourceEvent, previousValue)
      }

      dispatchToggleEvent(sourceEvent, previousValue)
    }

    function animateDisplayedValues(sourceEvent, previousValue, root, nodes) {
      root = sourceEvent.currentTarget.closest("[data-wrn-toggle-count]")

      if (!root) {
        return
      }

      nodes = root.querySelectorAll("[data-toggle-count-value]")
      animateValueAt(nodes, 0, previousValue)
    }

    function animateValueAt(nodes, index, previousValue, node, fromValue, toValue) {
      if (index >= nodes.length) {
        return
      }

      node = nodes[index]
      fromValue = Number(
        previousValue === secondValue
          ? node.getAttribute("data-second-value")
          : node.getAttribute("data-first-value")
      )
      toValue = Number(
        selectedValue === secondValue
          ? node.getAttribute("data-second-value")
          : node.getAttribute("data-first-value")
      )

      if (!Number.isNaN(fromValue) && !Number.isNaN(toValue)) {
        animateValueFrame(node, fromValue, toValue, 0)
      }

      animateValueAt(nodes, index + 1, previousValue)
    }

    function animateValueFrame(node, fromValue, toValue, frame, totalFrames, nextValue) {
      totalFrames = Math.max(1, Number(animationSteps) || 1)

      if (frame >= totalFrames) {
        node.replaceChildren(String(toValue))
        return
      }

      nextValue = Math.round(
        fromValue +
        (toValue - fromValue) * (frame / totalFrames)
      )
      node.replaceChildren(String(nextValue))

      setTimeout(
        animateValueFrame,
        Math.max(1, Number(animationDuration) / totalFrames),
        node,
        fromValue,
        toValue,
        frame + 1
      )
    }

    function toggleValue(sourceEvent) {
      selectValue(
        sourceEvent,
        isFirstSelected() ? secondValue : firstValue
      )
    }
  }

  view {
    <section
      {...attrs}
      data-wrn-toggle-count
      data-variant="{variant}"
      data-value="{selectedValue}"
      data-disabled="{disabled ? 'true' : 'false'}"
      class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--toggle-count wire-next--toggle-count-{variant} {fullWidth ? 'wire-next--toggle-count-full' : ''} {disabled ? 'wire-next--disabled' : ''} {class}"
    >
      <input type="hidden" name="{name}" value="{selectedValue}" />

      <div class="wire-next__toggle-count-control wire-next__toggle-count-control--{align}">
        {#if variant === "switch"}
          <span data-selected="{isFirstSelected() ? 'true' : 'false'}">{firstLabel}</span>
          <button
            type="button"
            role="switch"
            aria-label="{ariaLabel}"
            aria-checked="{isSecondSelected() ? 'true' : 'false'}"
            disabled="{disabled}"
            @click="toggleValue(event)"
            class="wire-next__toggle-count-switch"
          >
            <span aria-hidden="true"></span>
          </button>
          <span data-selected="{isSecondSelected() ? 'true' : 'false'}">{secondLabel}</span>
        {:else}
          <div class="wire-next__toggle-count-segmented" role="group" aria-label="{ariaLabel}">
            <button
              type="button"
              aria-pressed="{isFirstSelected() ? 'true' : 'false'}"
              disabled="{disabled}"
              @click="selectValue(event, firstValue)"
            >{firstLabel}</button>
            <button
              type="button"
              aria-pressed="{isSecondSelected() ? 'true' : 'false'}"
              disabled="{disabled}"
              @click="selectValue(event, secondValue)"
            >{secondLabel}</button>
          </div>
        {/if}
      </div>

      {#if items.length > 0}
        <div class="wire-next__toggle-count-items">
          {#each items as item}
            <article>
              <span>{item.label || item.name}</span>
              <strong>
                {#if currency}<small>{currency}</small>{/if}
                <span
                  data-toggle-count-value
                  data-first-value="{item[firstValueKey]}"
                  data-second-value="{item[secondValueKey]}"
                >{displayValue(item)}</span>
                {#if suffix}<small>{suffix}</small>{/if}
              </strong>
              {#if item.description}<small>{item.description}</small>{/if}
            </article>
          {/each}
        </div>
      {/if}
    </section>
  }
}
```

---

## TogglePassword

Showcase: https://component.wrnexusjs.dev/
Mount: <TogglePassword /> (legacy: data-component="TogglePassword")
Category: advanced-forms
Purpose: Accessible password field with optional show and hide controls.
Props: size: string = "default", color: string = "primary", label: string = "Password", name: string = "password", value: string = "", placeholder: string = "Enter your password", autocomplete: string = "current-password", minlength: string = "", maxlength: string = "", pattern: string = "(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^A-Za-z0-9]).{8,}", fields: string = [], visible: boolean = false, toggleable: boolean = true, toggleMode: string = "button", checkboxLabel: string = "Show password", showLabel: string = "Show password", hideLabel: string = "Hide password", disabled: boolean = false, readonly: boolean = false, required: boolean = false, invalid: boolean = false, helpText: string = "", validationMessage: string = "", class: string = ""
Slots: none
Events: input, change, toggle

### Complete .wrn source contract

```wrn
component TogglePassword {
  props {
    size = "default"
    color = "primary"
    label = "Password"
    name = "password"
    value = ""
    placeholder = "Enter your password"
    autocomplete = "current-password"
    minlength = ""
    maxlength = ""
    pattern = "(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^A-Za-z0-9]).{8,}"
    fields = []
    visible = false
    toggleable = true
    toggleMode = "button"
    checkboxLabel = "Show password"
    showLabel = "Show password"
    hideLabel = "Hide password"
    disabled = false
    readonly = false
    required = false
    invalid = false
    helpText = ""
    validationMessage = ""
    class = ""
    @event input = function
    @event change = function
    @event toggle = function
  }

  state revealed = visible

  functions {
    function toggleVisibility() {
      if (disabled || readonly || !toggleable) {
        return
      }
      revealed = !revealed
    }

    function fieldId(field, index) {
      return field.id || field.name || name + "-" + index
    }

    function fieldName(field, index) {
      return field.name || name + "-" + index
    }
  }

  view {
    <fieldset
      class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--toggle-password {invalid ? 'wire-next--invalid' : ''} {disabled ? 'wire-next--disabled' : ''} {class}"
      data-wrn-toggle-password
      data-visible="{revealed ? 'true' : 'false'}"
    >
      {#if fields.length}
        <div class="wire-next__password-fields">
          {#each fields as field, index}
            <div class="wire-next__password-field">
              <label for="{fieldId(field, index)}">{field.label || label}</label>
              <div class="wire-next__password-control">
                <input
                  id="{fieldId(field, index)}"
                  type="{revealed ? 'text' : 'password'}"
                  name="{fieldName(field, index)}"
                  value="{field.value || ''}"
                  placeholder="{field.placeholder || placeholder}"
                  autocomplete="{field.autocomplete || autocomplete}"
                  minlength="{field.minlength || minlength}"
                  maxlength="{field.maxlength || maxlength}"
                  pattern="{field.pattern || pattern}"
                  disabled="{disabled || field.disabled}"
                  readonly="{readonly || field.readonly}"
                  required="{required || field.required}"
                  aria-invalid="{invalid ? 'true' : 'false'}"
                  @input="$emit('input', { name: event.target.name, value: event.target.value, visible: revealed })"
                  @change="$emit('change', { name: event.target.name, value: event.target.value, visible: revealed })"
                />
                {#if toggleable && toggleMode === "button"}
                  <button
                    type="button"
                    class="wire-next__password-toggle"
                    aria-label="{revealed ? hideLabel : showLabel}"
                    title="{revealed ? hideLabel : showLabel}"
                    aria-pressed="{revealed ? 'true' : 'false'}"
                    disabled="{disabled || readonly}"
                    @click="toggleVisibility(); $emit('toggle', { visible: revealed })"
                  >
                    <span class="wire-next__password-icon wire-next__password-icon--show" aria-hidden="true"></span>
                  </button>
                {/if}
              </div>
            </div>
          {/each}
        </div>
      {:else}
        <label for="{name}-password">{label}</label>
        <div class="wire-next__password-control">
          <input
            {...attrs}
            id="{name}-password"
            type="{revealed ? 'text' : 'password'}"
            name="{name}"
            value="{value}"
            placeholder="{placeholder}"
            autocomplete="{autocomplete}"
            minlength="{minlength}"
            maxlength="{maxlength}"
            pattern="{pattern}"
            disabled="{disabled}"
            readonly="{readonly}"
            required="{required}"
            aria-invalid="{invalid ? 'true' : 'false'}"
            aria-describedby="{validationMessage ? name + '-validation' : helpText ? name + '-help' : ''}"
            @input="$emit('input', { value: event.target.value, visible: revealed })"
            @change="$emit('change', { value: event.target.value, visible: revealed })"
          />
          {#if toggleable && toggleMode === "button"}
            <button
              type="button"
              class="wire-next__password-toggle"
              aria-label="{revealed ? hideLabel : showLabel}"
              title="{revealed ? hideLabel : showLabel}"
              aria-pressed="{revealed ? 'true' : 'false'}"
              disabled="{disabled || readonly}"
              @click="toggleVisibility(); $emit('toggle', { visible: revealed })"
            >
              <span class="wire-next__password-icon wire-next__password-icon--show" aria-hidden="true"></span>
            </button>
          {/if}
        </div>
      {/if}
      {#if toggleable && toggleMode === "checkbox"}
        <label class="wire-next__password-checkbox">
          <input
            type="checkbox"
            checked="{revealed}"
            disabled="{disabled || readonly}"
            @change="revealed = event.target.checked; $emit('toggle', { visible: revealed })"
          />
          <span>{checkboxLabel}</span>
        </label>
      {/if}
      {#if helpText && !validationMessage}<small id="{name}-help">{helpText}</small>{/if}
      <small
        id="{name}-validation"
        class="wire-next__validation"
        data-error="{name}"
      >{validationMessage}</small>
    </fieldset>
  }
}
```

---

## Tooltip

Showcase: https://component.wrnexusjs.dev/
Mount: <Tooltip /> (legacy: data-component="Tooltip")
Category: overlays
Purpose: Theme-aware, responsive tooltip component.
Props: size: string = "default", color: string = "primary", title: string = "Tooltip", description: string = "", open: boolean = false, placement: string = "bottom", closeLabel: string = "Close", class: string = ""
Slots: default
Events: open, close

### Complete .wrn source contract

```wrn
component Tooltip {
  props {
    @event open = function
    @event close = function
    size = "default"
    color = "primary"
    title = "Tooltip"
    description = ""
    open = false
    placement = "bottom"
    closeLabel = "Close"
    class = ""
  }
  view {
    <div data-show="{open}" class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--tooltip wire-next--placement-{placement} {class}" role="region" aria-modal="false" aria-label="{title}">
      <header><strong>{title}</strong><button type="button" aria-label="{closeLabel}">×</button></header>
      {#if description}<p>{description}</p>{/if}
      <slot />
    </div>
  }
}
```

---

## TreeView

Showcase: https://component.wrnexusjs.dev/
Mount: <TreeView /> (legacy: data-component="TreeView")
Category: base
Purpose: Theme-aware, responsive tree view component.
Props: size: string = "default", color: string = "primary", title: string = "Tree View", description: string = "", items: string = [], variant: string = "default", class: string = ""
Slots: default
Events: select, toggle, expand, collapse

### Complete .wrn source contract

```wrn
component TreeView {
  props {
    @event select = function
    @event toggle = function
    @event expand = function
    @event collapse = function
    size = "default"
    color = "primary"
    title = "Tree View"
    description = ""
    items = []
    variant = "default"
    class = ""
  }
  view {
    <section class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--tree-view wire-next--variant-{variant} {class}">
      {#if title}<strong>{title}</strong>{/if}
      {#if description}<p>{description}</p>{/if}
      {#if items}<div class="wire-next__items">{#each items as item}<span>{item.label}</span>{/each}</div>{/if}
      <slot />
    </section>
  }
}
```

---

## Typography

Showcase: https://component.wrnexusjs.dev/
Mount: <Typography /> (legacy: data-component="Typography")
Category: layout
Purpose: Theme-aware, responsive typography component.
Props: size: string = "default", color: string = "primary", columns: number = 2, gap: string = "md", maxWidth: string = "xl", class: string = ""
Slots: default
Events: none

### Complete .wrn source contract

```wrn
component Typography {
  props {
    size = "default"
    color = "primary"
    columns = 2
    gap = "md"
    maxWidth = "xl"
    class = ""
  }

  view {
    <div
      data-ui-component="Typography"
      class='wire-typography text-[var(--wire-color-text)] {class}'
      class:max-w-3xl='maxWidth === "md"'
      class:max-w-5xl='maxWidth === "lg"'
      class:max-w-7xl='maxWidth === "xl"'
      class:max-w-none='maxWidth === "full"'
      class:text-sm='size === "sm"'
      class:text-base='size === "default" || size === "md"'
      class:text-lg='size === "lg"'
      class:columns-1='columns === 1'
      class:md:columns-2='columns === 2'
      class:lg:columns-3='columns === 3'
      class:gap-4='gap === "sm"'
      class:gap-8='gap === "md"'
      class:gap-12='gap === "lg"'
    >
      <slot></slot>
    </div>
  }

  style {
    .wire-typography :where(h1, h2, h3, h4) {
      color: var(--wire-color-text);
      font-weight: 700;
      letter-spacing: -0.02em;
      line-height: 1.2;
      break-after: avoid;
    }

    .wire-typography :where(h1) { font-size: clamp(2rem, 4vw, 3.5rem); margin: 0 0 1.5rem; }
    .wire-typography :where(h2) { font-size: clamp(1.5rem, 3vw, 2.25rem); margin: 2.5rem 0 1rem; }
    .wire-typography :where(h3) { font-size: 1.35rem; margin: 2rem 0 0.75rem; }
    .wire-typography :where(p, ul, ol, blockquote, pre, table) { margin: 1rem 0; }
    .wire-typography :where(p, li) { color: var(--wire-color-text-muted); line-height: 1.8; }
    .wire-typography :where(a) { color: var(--wire-color-primary); font-weight: 600; text-underline-offset: 0.2em; }
    .wire-typography :where(a:hover) { color: var(--wire-color-primary-hover); text-decoration: underline; }
    .wire-typography :where(ul, ol) { padding-left: 1.4rem; }
    .wire-typography :where(ul) { list-style: disc; }
    .wire-typography :where(ol) { list-style: decimal; }
    .wire-typography :where(blockquote) {
      border-left: 4px solid var(--wire-color-primary);
      background: var(--wire-color-primary-soft);
      border-radius: 0 0.75rem 0.75rem 0;
      padding: 1rem 1.25rem;
      color: var(--wire-color-text);
    }
    .wire-typography :where(code) {
      border-radius: 0.35rem;
      background: var(--wire-color-surface-soft);
      padding: 0.15rem 0.35rem;
      font-size: 0.9em;
    }
    .wire-typography :where(pre) {
      overflow-x: auto;
      border: 1px solid var(--wire-color-border);
      border-radius: 1rem;
      background: var(--wire-color-surface-raised);
      padding: 1rem;
    }
    .wire-typography :where(img) { border-radius: 1rem; }
    .wire-typography :where(hr) { border-color: var(--wire-color-border); margin: 2rem 0; }
  }
}
```

---

## WysiwygEditor

Showcase: https://component.wrnexusjs.dev/
Mount: <WysiwygEditor /> (legacy: data-component="WysiwygEditor")
Category: integrations
Purpose: Theme-aware, responsive wysiwyg editor component.
Props: size: string = "default", color: string = "primary", title: string = "Wysiwyg Editor", description: string = "", items: string = [], variant: string = "default", class: string = ""
Slots: default
Events: input, change, focus, blur

### Complete .wrn source contract

```wrn
component WysiwygEditor {
  props {
    @event input = function
    @event change = function
    @event focus = function
    @event blur = function
    size = "default"
    color = "primary"
    title = "Wysiwyg Editor"
    description = ""
    items = []
    variant = "default"
    class = ""
  }
  view {
    <section class="wire-next wire-next--color-{color} wire-next--size-{size} wire-next--wysiwyg-editor wire-next--variant-{variant} {class}">
      {#if title}<strong>{title}</strong>{/if}
      {#if description}<p>{description}</p>{/if}
      {#if items}<div class="wire-next__items">{#each items as item}<span>{item.label}</span>{/each}</div>{/if}
      <slot />
    </section>
  }
}
```
