page wrnexusrouter {
  seo {
    title = "@wrnexus/router"
    description = "Filesystem discovery, route matching, and typed route generation."
  }

  view {
    <div class="docs-shell">
      <a class="skip-link" href="#main">Skip to content</a>
      <header class="topbar">
        <a class="brand" href="/"><span>W</span> WRNexusJS</a>
        <nav aria-label="Primary"><a href="/getting-started">Get started</a><a href="/packages">Packages</a><a href="/language">Language</a><a href="/architecture">Architecture</a></nav>
        <div class="topbar-actions"><a class="preview-pill" href="/access">Private preview · v0.2.31</a><button data-wire-theme-toggle class="theme-button" aria-label="Toggle color theme" title="Toggle color theme">◐</button></div>
      </header>
      <div class="mobile-doc-nav"><details><summary>Browse documentation</summary><nav><a href="/getting-started">Get started</a><a href="/packages">Packages</a><a href="/language">Language</a><a href="/architecture">Architecture</a><a href="/tutorial">Tutorial</a><a href="/guides/project-structure">Guides</a><a href="/examples">Examples</a><a href="/search">Search</a></nav></details></div>
      <main class="page package-page">
      <aside class="sidebar"><a href="/packages">← All packages</a><span class="category">Core</span><h2>@wrnexus/router</h2><p>Filesystem discovery, route matching, and typed route generation.</p><span class="status status-beta">Private preview · 0.2.31</span><nav><a href="#access">Access</a><a href="#guide">Guide</a><a href="#api">Complete API</a></nav></aside>
      <article id="main" class="documentation"><section class="doc-intro"><span class="eyebrow">Core · Preview</span><h1>@wrnexus/router</h1><p>Filesystem discovery, route matching, and typed route generation.</p><section id="access" class="access-callout"><h2>Private registry access required</h2><p>This package is not available from the public npm registry. After WorkRoot approves access and supplies private registry instructions, install the release-aligned package:</p><pre><code>bun add @wrnexus/router@0.2.31</code><button type="button" class="copy-button" aria-label="Copy installation command">Copy</button></pre><p><a href="/access">Request preview access</a>. Never put registry tokens in source control.</p></section></section><section id="guide" class="prose"><blockquote>File-based router that maps an <code>app/</code> directory onto route tables and matches request paths against them.</blockquote>
<p>Part of the <strong>WRNexusJS</strong> framework — an SSR-first, Bun-native full-stack web framework.</p>
<h3 id="overview">Overview</h3>
<p><code>@wrnexus/router</code> scans an application's <code>app/</code> directory once at startup and builds route tables for pages, API endpoints, realtime channels, middleware, server-rendered <code>.wrn</code> components, layouts, and validation schemas. It also compiles URL patterns (<code>/users/[id]</code>) 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 WRNexusJS runtime to resolve incoming requests, plus a codegen helper for compile-time typed links.</p>
<pre data-language="bash"><code>bun add @wrnexus/router</code></pre>
<blockquote>Private package — the machine must be authenticated to the <code>wrnexus</code> npm org</blockquote>
<blockquote>(a read token in <code>~/.npmrc</code>). Requires <strong>Bun</strong> (Node is not supported).</blockquote>
<h3 id="directory-conventions">Directory conventions</h3>
<p>The router maps files under <code>appDir</code> onto routes:</p>
<pre data-language=""><code>app/pages/index.tsx        -&gt; GET /
app/pages/about.tsx        -&gt; GET /about
app/pages/users/[id].tsx   -&gt; GET /users/:id
app/api/hello.ts           -&gt; /api/hello
app/realtime/chat.ts       -&gt; /realtime/chat
app/pages/*.wrn  (api)    -&gt; embedded /api/* routes
app/pages/*.wrn  (rt)     -&gt; embedded /realtime/* routes
app/middleware/*.ts        -&gt; global middleware (alphabetical)
app/components/*.wrn      -&gt; server-rendered components (by basename)
app/layouts/*.wrn         -&gt; named page layouts
app/schemas/*.ts           -&gt; validation schemas</code></pre>
<p>Allowed route extensions are <code>.ts</code>, <code>.tsx</code>, and <code>.wrn</code>. Dotfiles and underscore-prefixed files are ignored. A trailing <code>index</code> segment is dropped from the route. <code>.wrn</code> pages may embed <code>api</code> and <code>realtime</code> blocks, which the router extracts and mounts under <code>/api/*</code> and <code>/realtime/*</code>.</p>
<h3 id="api">API</h3>
<h4 id="buildrouter-appdir-opts-router"><code>buildRouter(appDir, opts?): Router</code></h4>
<p>Scan an app directory and build all route tables.</p>
<pre data-language="ts"><code>function buildRouter(appDir: string, opts?: RouterOptions): Router;

interface RouterOptions &#123;
  /** Extra dirs scanned for `.wrn` components (e.g. `@wrnexus/ui`), before
   *  `app/components`, so an app component of the same name wins. */
  componentDirs?: string[];
&#125;</code></pre>
<p>The returned <code>Router</code> exposes the built tables plus per-kind matchers:</p>
<pre data-language="ts"><code>interface Router &#123;
  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/&lt;name&gt;.wrn`); a page picks one via `layout`. */
  layouts: ComponentRef[];
  /** Validation schemas (`app/schemas/&lt;name&gt;.ts`) shared by API + forms. */
  schemas: ComponentRef[];
  matchPage(pathname: string): RouteMatch | null;
  matchApi(pathname: string): RouteMatch | null;
  matchRealtime(pathname: string): RouteMatch | null;
&#125;

interface ComponentRef &#123;
  /** Validated component name (matches a `data-component` attribute). */
  name: string;
  /** Absolute path to the component's `.wrn` module. */
  file: string;
&#125;</code></pre>
<p>Component, layout, and schema names are validated with <code>isSafeIslandName</code> from <code>@wrnexus/core</code>; unsafe names are skipped with a warning. Realtime channel names are validated the same way.</p>
<h4 id="route-matching">Route matching</h4>
<div class="table-wrap"><table>
<thead><tr><th>Export</th><th>Signature</th><th>Description</th></tr></thead>
<tbody><tr><td><code>compileRoutePattern</code></td><td>`(raw: string) =&gt; Pick&lt;Route, &quot;regex&quot; \</td><td>&quot;paramNames&quot;&gt;`</td><td>Compile a <code>/users/[id]</code> pattern into a RegExp (with optional trailing slash) plus ordered param names.</td></tr><tr><td><code>matchRoute</code></td><td>`(routes: Route[], pathname: string) =&gt; RouteMatch \</td><td>null`</td><td>Return the first route whose regex matches; captured params are <code>decodeURIComponent</code>-decoded.</td></tr><tr><td><code>sortRoutes</code></td><td><code>(routes: Route[]) =&gt; Route[]</code></td><td>Order routes so static routes win over dynamic ones (fewer params first), then longer/more specific patterns first.</td></tr></tbody></table></div>
<pre data-language="ts"><code>interface Route &#123;
  raw: string; // e.g. &quot;/users/[id]&quot;
  file: string; // absolute path to the handling module
  regex: RegExp; // compiled matcher
  paramNames: string[]; // ordered dynamic param names
&#125;

interface RouteMatch &#123;
  route: Route;
  params: Record&lt;string, string&gt;;
&#125;</code></pre>
<h4 id="typed-routes-codegen">Typed-routes codegen</h4>
<pre data-language="ts"><code>function generateRoutesFile(pages: Route[]): string;</code></pre>
<p>Emits the source for <code>app/routes.gen.ts</code>: a <code>Routes</code> map (each page path → its <code>[param]</code> types), a <code>RoutePath</code> union, and an <code>href()</code> builder that fills params and rejects unknown paths at compile time. Entries are de-duplicated and sorted by path.</p>
<h4 id="re-exports">Re-exports</h4>
<p><code>Middleware</code> (the type from <code>@wrnexus/core</code>) is re-exported for callers that load middleware modules themselves.</p>
<h3 id="usage">Usage</h3>
<pre data-language="ts"><code>import &#123; buildRouter &#125; from &quot;@wrnexus/router&quot;;

const router = buildRouter(&quot;./app&quot;, &#123;
  componentDirs: [&quot;./node_modules/@wrnexus/ui/components&quot;],
&#125;);

// Resolve an incoming request.
const match = router.matchPage(&quot;/users/42&quot;);
if (match) &#123;
  console.log(match.route.file); // absolute path to the page module
  console.log(match.params); // &#123; id: &quot;42&quot; &#125;
&#125;

const api = router.matchApi(&quot;/api/hello&quot;);
const rt = router.matchRealtime(&quot;/realtime/chat&quot;);</code></pre>
<p>Generating the typed-routes file (as <code>wrnexus dev</code> does):</p>
<pre data-language="ts"><code>import &#123; generateRoutesFile &#125; from &quot;@wrnexus/router&quot;;
import &#123; writeFileSync &#125; from &quot;node:fs&quot;;

const router = buildRouter(&quot;./app&quot;);
writeFileSync(&quot;./app/routes.gen.ts&quot;, generateRoutesFile(router.pages));</code></pre>
<pre data-language="ts"><code>// Then, in app code, links are checked at compile time:
import &#123; href &#125; from &quot;./routes.gen.ts&quot;;

href(&quot;/users/[id]&quot;, &#123; id: &quot;42&quot; &#125;); // &quot;/users/42&quot;
href(&quot;/about&quot;); // &quot;/about&quot;
href(&quot;/nope&quot;); // type error: unknown path</code></pre>
<p>Lower-level pattern matching, if you need it directly:</p>
<pre data-language="ts"><code>import &#123; compileRoutePattern, matchRoute, sortRoutes, type Route &#125; from &quot;@wrnexus/router&quot;;

const &#123; regex, paramNames &#125; = compileRoutePattern(&quot;/posts/[slug]&quot;);
const routes = sortRoutes([&#123; raw: &quot;/posts/[slug]&quot;, file: &quot;…&quot;, regex, paramNames &#125;]);
const m = matchRoute(routes, &quot;/posts/hello&quot;); // &#123; route, params: &#123; slug: &quot;hello&quot; &#125; &#125;</code></pre>
<h3 id="requirements-notes">Requirements / Notes</h3>
<ul>
<li>Scanning uses <code>node:fs</code> (<code>existsSync</code>, <code>readdirSync</code>, <code>statSync</code>) and <code>node:path</code> — runs under Bun.</li>
<li>Depends on [<code>@wrnexus/compiler</code>](../compiler) to <code>parse</code> <code>.wrn</code> pages and extract embedded <code>api</code> / <code>realtime</code> blocks.</li>
<li>Depends on [<code>@wrnexus/core</code>](../core) for <code>isSafeIslandName</code> (name validation) and the <code>Middleware</code> type.</li>
<li>Missing route directories are tolerated — a route kind you don't use simply yields an empty table.</li>
</ul></section><section id="api" class="prose api"><h2>Complete TypeScript API</h2><p>This declaration comes from the exact installed package and lists its exported functions, classes, interfaces, and types.</p><pre data-language="typescript"><code>export &#123; Middleware &#125; from '@wrnexus/core';

/**
 * Route compilation + matching.
 *
 * A &quot;route&quot; is a URL pattern compiled to a RegExp. We support static segments
 * and dynamic `[param]` segments, e.g. `/users/[id]` -&gt; `&#123; id &#125;`.
 */
interface Route &#123;
    /** 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[];
&#125;
interface RouteMatch &#123;
    route: Route;
    params: Record&lt;string, string&gt;;
&#125;
/** Compile a `/users/[id]` style pattern into a RegExp + param names. */
declare function compileRoutePattern(raw: string): Pick&lt;Route, &quot;regex&quot; | &quot;paramNames&quot;&gt;;
/**
 * Order routes so that static routes win over dynamic ones, and longer/more
 * specific routes win over shorter ones. Sorting once keeps matching simple.
 */
declare function sortRoutes(routes: Route[]): Route[];
/** 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 — so links
 * are checked at compile time (unknown path or missing param = type error).
 */

declare function generateRoutesFile(pages: Route[]): string;

/**
 * @wrnexus/router — file-based router.
 *
 * Maps the `app/` directory onto route tables:
 *   app/pages/index.tsx     -&gt; GET /
 *   app/pages/about.tsx     -&gt; GET /about
 *   app/pages/users/[id].tsx-&gt; GET /users/:id
 *   app/api/hello.ts        -&gt; /api/hello
 *   app/realtime/chat.ts    -&gt; /realtime/chat
 *   app/pages/*.wrn api      -&gt; embedded /api/* routes
 *   app/pages/*.wrn realtime -&gt; embedded /realtime/* routes
 *   app/middleware/*.ts     -&gt; global middleware (alphabetical)
 *   app/components/*.wrn   -&gt; server-rendered components (by basename),
 *                              mounted in a page via data-component=&quot;&lt;name&gt;&quot;
 */

interface ComponentRef &#123;
    /** Validated component name (matches a `data-component` attribute). */
    name: string;
    /** Absolute path to the component's `.wrn` module. */
    file: string;
&#125;
interface Router &#123;
    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/&lt;name&gt;.wrn`); a page picks one via `layout`. */
    layouts: ComponentRef[];
    /** Validation schemas (`app/schemas/&lt;name&gt;.ts`) shared by API + forms. */
    schemas: ComponentRef[];
    matchPage(pathname: string): RouteMatch | null;
    matchApi(pathname: string): RouteMatch | null;
    matchRealtime(pathname: string): RouteMatch | null;
&#125;
interface RouterOptions &#123;
    /**
     * 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[];
&#125;
/** Scan an app directory and build all route tables. */
declare function buildRouter(appDir: string, opts?: RouterOptions): Router;

export &#123; type ComponentRef, type Route, type RouteMatch, type Router, type RouterOptions, buildRouter, compileRoutePattern, generateRoutesFile, matchRoute, sortRoutes &#125;;
</code></pre></section><section id="examples" class="prose examples"><h2>Examples</h2><p>Examples are taken from this package's installed documentation and must be evaluated with its requirements and stability notes.</p><div class="example-grid"><article class="example-card"><h3>Typical usage</h3><pre data-language="ts"><code>import &#123; buildRouter &#125; from &quot;@wrnexus/router&quot;;

const router = buildRouter(&quot;./app&quot;, &#123;
  componentDirs: [&quot;./node_modules/@wrnexus/ui/components&quot;],
&#125;);

// Resolve an incoming request.
const match = router.matchPage(&quot;/users/42&quot;);
if (match) &#123;
  console.log(match.route.file); // absolute path to the page module
  console.log(match.params); // &#123; id: &quot;42&quot; &#125;
&#125;

const api = router.matchApi(&quot;/api/hello&quot;);
const rt = router.matchRealtime(&quot;/realtime/chat&quot;);</code></pre></article><article class="example-card"><h3>Generating the typed-routes file (as wrnexus dev does)</h3><pre data-language="ts"><code>import &#123; generateRoutesFile &#125; from &quot;@wrnexus/router&quot;;
import &#123; writeFileSync &#125; from &quot;node:fs&quot;;

const router = buildRouter(&quot;./app&quot;);
writeFileSync(&quot;./app/routes.gen.ts&quot;, generateRoutesFile(router.pages));</code></pre></article><article class="example-card"><h3>Typical usage</h3><pre data-language="ts"><code>// Then, in app code, links are checked at compile time:
import &#123; href &#125; from &quot;./routes.gen.ts&quot;;

href(&quot;/users/[id]&quot;, &#123; id: &quot;42&quot; &#125;); // &quot;/users/42&quot;
href(&quot;/about&quot;); // &quot;/about&quot;
href(&quot;/nope&quot;); // type error: unknown path</code></pre></article><article class="example-card"><h3>Lower-level pattern matching, if you need it directly</h3><pre data-language="ts"><code>import &#123; compileRoutePattern, matchRoute, sortRoutes, type Route &#125; from &quot;@wrnexus/router&quot;;

const &#123; regex, paramNames &#125; = compileRoutePattern(&quot;/posts/[slug]&quot;);
const routes = sortRoutes([&#123; raw: &quot;/posts/[slug]&quot;, file: &quot;…&quot;, regex, paramNames &#125;]);
const m = matchRoute(routes, &quot;/posts/hello&quot;); // &#123; route, params: &#123; slug: &quot;hello&quot; &#125; &#125;</code></pre></article></div></section></article>
      <aside class="on-this-page"><h2>On this page</h2><nav><a class="toc-level-2" href="#guide">Guide</a><a class="toc-level-3" href="#overview">Overview</a><a class="toc-level-3" href="#directory-conventions">Directory conventions</a><a class="toc-level-3" href="#api">API</a><a class="toc-level-4" href="#buildrouter-appdir-opts-router">buildRouter(appDir, opts?): Router</a><a class="toc-level-4" href="#route-matching">Route matching</a><a class="toc-level-4" href="#typed-routes-codegen">Typed-routes codegen</a><a class="toc-level-4" href="#re-exports">Re-exports</a><a class="toc-level-3" href="#usage">Usage</a><a class="toc-level-3" href="#requirements-notes">Requirements / Notes</a><a class="toc-level-2" href="#api">Complete API</a><a class="toc-level-2" href="#examples">Examples</a></nav></aside>
    </main>
      <footer>WRNexusJS 0.2.31 · Private Developer Preview · Bun-native · Documentation generated from installed package APIs.</footer>
    </div>
  }
}
