Files
WRNexusJSDoc/app/pages/packages/compiler.wrn
T

249 lines
22 KiB
Plaintext

page wrnexuscompiler {
seo {
title = "@wrnexus/compiler"
description = "Parser and code generators for the .wrn language."
}
view {
<div class="docs-shell">
<SkipLink label="Skip to content" href="#main" class="docs-skip-link" />
<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="https://component.wrnexusjs.dev/">Components</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.5.13</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="https://component.wrnexusjs.dev/">Components</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="portal-main docs-layout">
<article id="main" class="documentation prose standalone package-document"><nav class="breadcrumbs" aria-label="Breadcrumb"><a href="/">Home</a><span>/</span><a href="/packages">Packages</a><span>/</span><span aria-current="page">@wrnexus/compiler</span></nav><section class="doc-intro"><span class="eyebrow">Core · Package reference</span><h1>@wrnexus/compiler</h1><p>Parser and code generators for the .wrn language.</p><div class="doc-meta"><span>v0.5.13</span><span>Private registry</span><span>Core</span></div><section id="access" class="access-callout"><h2>Install the package</h2><p>After WorkRoot approves private registry access, install the release-aligned package:</p><pre><code>bun add @wrnexus/compiler@0.5.13</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"><blockquote>Compiler for the <code>.wrn</code> language — tokenizes, parses, and lowers <code>.wrn</code> page and component files to TypeScript.</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/compiler</code> turns <code>.wrn</code> source into TypeScript that targets the framework's runtime primitives. A <code>.wrn</code> file declares either a <code>page</code> (a route) or a <code>component</code> (a reusable, prop-driven fragment) with blocks for <code>state</code>, <code>view</code> (plain HTML), <code>seo</code>, <code>style</code>, <code>functions</code>, <code>api</code>, <code>ssr</code>/<code>client</code> data bindings, and <code>realtime</code> websocket handlers. The pipeline is <code>source → Lexer → parse() → PageAst → generate() → TypeScript</code>. It is a build/server-side library — the WRNexusJS dev loader calls it to compile <code>.wrn</code> files on the fly, surfacing <code>ParseError</code> as a readable error page.</p>
<p>Static ES module imports may appear before the root declaration. Imported values are available to server-rendered expressions, including component props:</p>
<pre data-language="wrn"><code>import &#123; appUrl &#125; from &quot;@wrnexus/helpers&quot;;
layout PublicLayout &#123;
view &#123;
&lt;PublicHeader signInHref=&quot;&#123;appUrl('sso', '/sign-in')&#125;&quot; /&gt;
&#125;
&#125;</code></pre>
<pre data-language="bash"><code>bun add @wrnexus/compiler</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="api">API</h3>
<p>All exports come from the package root (<code>@wrnexus/compiler</code>).</p>
<h4 id="compilewirefile-source-string-string"><code>compileWireFile(source: string): string</code></h4>
<p>Compile <code>.wrn</code> source to a TypeScript module string. Throws <code>ParseError</code> on invalid input. The output is prefixed with a <code>// compiled from .wrn</code> comment.</p>
<h4 id="compile-source-string-compileresult"><code>compile(source: string): CompileResult</code></h4>
<p>Richer entry point that returns the generated code, the AST, and any diagnostics.</p>
<pre data-language="ts"><code>interface CompileResult &#123;
code: string;
ast: PageAst;
diagnostics: string[];
&#125;</code></pre>
<p>On a <code>ParseError</code> it pushes the message into <code>diagnostics</code> and re-throws.</p>
<h4 id="parse-source-string-pageast"><code>parse(source: string): PageAst</code></h4>
<p>Run the lexer + recursive-descent parser and return the AST. Throws <code>ParseError</code> (lexer <code>LexError</code>s are caught and rethrown as <code>ParseError</code>).</p>
<h4 id="generate-ast-pageast-string"><code>generate(ast: PageAst): string</code></h4>
<p>Lower a <code>PageAst</code> to TypeScript. <code>page</code> ASTs become a default-export page component (plus <code>meta</code>, optional <code>layout</code>, <code>__wrnexusApi</code>/method handlers, <code>websocket</code>, and SSR/CSR data bindings); <code>component</code> ASTs become a module exporting <code>render(props)</code> and <code>__wrnexusComponent</code>.</p>
<h4 id="lexer"><code>Lexer</code></h4>
<p>On-demand lexer for <code>.wrn</code>. Yields structural tokens and exposes raw-span readers for the parser.</p>
<pre data-language="ts"><code>class Lexer &#123;
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 &#123; ... &#125; block, string-aware
&#125;</code></pre>
<p><code>Token</code> is <code>&#123; type: TokenType; value: string; pos: number &#125;</code>, where <code>TokenType</code> is one of <code>ident</code>, <code>string</code>, <code>lbrace</code>, <code>rbrace</code>, <code>lparen</code>, <code>rparen</code>, <code>at</code>, <code>eq</code>, <code>comma</code>, <code>eof</code>.</p>
<h4 id="errors">Errors</h4>
<div class="table-wrap"><table>
<thead><tr><th>Class</th><th>Thrown by</th><th>Meaning</th></tr></thead>
<tbody><tr><td><code>ParseError</code></td><td><code>parse</code>, <code>compile</code>, <code>compileWireFile</code>, <code>generate</code></td><td>Invalid <code>.wrn</code> grammar or (rewrapped) lex failure.</td></tr><tr><td><code>LexError</code></td><td><code>Lexer</code></td><td>Unexpected character / unterminated string / unbalanced braces.</td></tr></tbody></table></div>
<h4 id="ast-types">AST types</h4>
<p>Exported type-only symbols describing the parsed tree:</p>
<div class="table-wrap"><table>
<thead><tr><th>Type</th><th>Description</th></tr></thead>
<tbody><tr><td><code>PageAst</code></td><td>Root node including top-level <code>imports</code>, <code>kind</code>, <code>name</code>, <code>types</code>, typed <code>props</code>, typed <code>states</code>, <code>view</code>, styles, functions, data APIs, lifecycle, and routes.</td></tr><tr><td><code>ViewNode</code></td><td><code>&#123; type: &quot;text&quot;; value &#125;</code> or <code>&#123; type: &quot;element&quot;; tag; attrs; children &#125;</code>.</td></tr><tr><td><code>Attr</code></td><td><code>&#123; name; value; event; boolean? &#125;</code> — <code>event</code> marks <code>@event</code> bindings.</td></tr><tr><td><code>StateDecl</code></td><td><code>&#123; name; valueType?; expr &#125;</code> — a typed <code>state x: Type = &lt;expr&gt;</code> declaration.</td></tr><tr><td><code>PropDecl</code></td><td><code>&#123; name; valueType?; required; default &#125;</code> — a typed prop declaration.</td></tr><tr><td><code>SeoBlock</code></td><td><code>Record&lt;string, string&gt;</code> from the <code>seo &#123; ... &#125;</code> block.</td></tr><tr><td><code>ApiBlock</code></td><td><code>&#123; method; path; body &#125;</code> — a top-level <code>api METHOD /path &#123; ... &#125;</code>.</td></tr><tr><td><code>DataApiBlock</code></td><td><code>&#123; mode; name; method; path; body &#125;</code> — an <code>api</code> inside an <code>ssr</code>/<code>client</code> block.</td></tr><tr><td><code>DataMode</code></td><td>`&quot;ssr&quot; \</td><td>&quot;client&quot;`.</td></tr><tr><td><code>ModeFunctionsBlock</code></td><td><code>&#123; mode; body &#125;</code> — a <code>functions &#123; ... &#125;</code> inside an <code>ssr</code>/<code>client</code> block.</td></tr><tr><td><code>RealtimeBlock</code></td><td><code>&#123; name; handlers &#125;</code> — a <code>realtime &lt;name&gt; &#123; on evt(args) &#123; ... &#125; &#125;</code> block.</td></tr></tbody></table></div>
<h3 id="usage">Usage</h3>
<p>Compile a page:</p>
<pre data-language="ts"><code>import &#123; compileWireFile &#125; from &quot;@wrnexus/compiler&quot;;
const ts = compileWireFile(`
page Home &#123;
state count = 0
seo &#123; title = &quot;Home&quot; description = &quot;Welcome&quot; &#125;
view &#123;
&lt;button @click=&quot;count++&quot;&gt;Clicked &#123;count&#125; times&lt;/button&gt;
&#125;
&#125;
`);
// 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.</code></pre>
<p>Inspect the AST and diagnostics:</p>
<pre data-language="ts"><code>import &#123; compile, ParseError &#125; from &quot;@wrnexus/compiler&quot;;
try &#123;
const &#123; code, ast, diagnostics &#125; = compile(source);
console.log(ast.kind, ast.name, ast.states.length);
&#125; catch (err) &#123;
if (err instanceof ParseError) console.error(err.message);
&#125;</code></pre>
<p>Drive the parse/codegen stages directly:</p>
<pre data-language="ts"><code>import &#123; parse, generate &#125; from &quot;@wrnexus/compiler&quot;;
const ast = parse(componentSource); // ast.kind === &quot;component&quot;
const module = generate(ast); // exports render(props) + __wrnexusComponent</code></pre>
<p>Use the lexer standalone:</p>
<pre data-language="ts"><code>import &#123; Lexer &#125; from &quot;@wrnexus/compiler&quot;;
const lx = new Lexer(&quot;page Home &#123;&quot;);
lx.next(); // &#123; type: &quot;ident&quot;, value: &quot;page&quot;, pos: 0 &#125;
lx.next(); // &#123; type: &quot;ident&quot;, value: &quot;Home&quot;, pos: 5 &#125;
lx.next(); // &#123; type: &quot;lbrace&quot;, value: &quot;&#123;&quot;, pos: 10 &#125;</code></pre>
<h3 id="the-wrn-language-as-parsed">The <code>.wrn</code> language (as parsed)</h3>
<p>A file opens with <code>page &lt;Name&gt;</code> or <code>component &lt;Name&gt;</code> followed by a <code>&#123; ... &#125;</code> body containing zero or more members:</p>
<ul>
<li><code>layout = &quot;&lt;name&gt;&quot;</code> — selects <code>app/layouts/&lt;name&gt;.wrn</code> (pages only).</li>
<li><code>types &#123; &lt;TypeScript declarations&gt; &#125;</code> — reusable interfaces and aliases for the current file.</li>
<li><code>props &#123; name: Type = &lt;default&gt; ... &#125;</code> — typed component props. Omit <code>= &lt;default&gt;</code> to make a prop required. Legacy inferred props remain supported.</li>
<li><code>@event name = function</code> inside <code>props</code> — declares a public component event. Emit it from component behavior with <code>name(detail)</code> or <code>$emit(&quot;name&quot;, detail)</code>, and consume it with <code>&lt;Component @name=&quot;handler(event)&quot; /&gt;</code>.</li>
<li><code>state &lt;ident&gt;: Type = &lt;expr&gt;</code> — typed reactive state seeded from a raw JS expression, including native array and object literals. The annotation is optional for backward compatibility.</li>
<li><code>view &#123; &lt;html&gt; &#125;</code> — plain HTML with <code>&#123;expr&#125;</code> interpolation in text and attributes, JSX-style component props such as <code>items=&#123;items&#125;</code>, <code>items=&#123;[...]&#125;</code>, and <code>options=&#123;&#123;...&#125;&#125;</code>, hyphenated attributes, boolean attributes, <code>@event=&quot;...&quot;</code> client bindings, and <code>&lt;!-- comments --&gt;</code>. Structured component props are serialized safely for SSR; expressions that reference <code>state</code> retain their initial value and update reactively in the browser.</li>
<li><code>seo &#123; key = &quot;value&quot; ... &#125;</code> — metadata merged into the generated <code>meta</code>.</li>
<li><code>style &#123; &lt;raw css&gt; &#125;</code> — inlined page/component stylesheet (repeatable).</li>
<li><code>functions &#123; &lt;TypeScript&gt; &#125;</code> — helpers with typed parameters and return values. Types remain in server output and are safely erased from browser behavior code.</li>
<li><code>api &lt;METHOD&gt; &lt;path&gt; &#123; &lt;raw js&gt; &#125;</code> — route handler, lowered to a <code>METHOD</code> export (repeatable).</li>
<li><code>ssr &#123; ... &#125;</code> / <code>client &#123; ... &#125;</code> — data blocks holding <code>api &lt;name&gt; &lt;METHOD&gt; &lt;path&gt; &#123; ... &#125;</code> bindings and their own <code>functions &#123; ... &#125;</code>.</li>
<li><code>realtime &lt;name&gt; &#123; on &lt;evt&gt;(&lt;args&gt;) &#123; &lt;raw js&gt; &#125; ... &#125;</code> — websocket handlers, lowered to a <code>websocket</code> export.</li>
</ul>
<p><code>view</code> markup is parsed by a lenient dedicated HTML parser (<code>parseHtmlView</code>); HTML void elements (<code>&lt;br&gt;</code>, <code>&lt;img&gt;</code>, …) take no closing tag. Line comments (<code>//</code>) are skipped by the lexer.</p>
<h3 id="requirements-notes">Requirements / Notes</h3>
<ul>
<li>Pure TypeScript with no runtime dependencies; runs under <strong>Bun</strong> as part of the WRNexusJS toolchain (Node is not supported).</li>
<li>Generated modules target WRNexusJS runtime primitives (<code>data-scope</code>, <code>data-text</code>, <code>data-on-*</code>, <code>data-for</code>, <code>data-component</code>, <code>__wrnexus*</code>/<code>__wire*</code> helpers) — consume the output within a WRNexusJS app, e.g. via <code>@wrnexus/core</code>'s dev loader.</li>
</ul></section><section id="api" class="api"><h2>Complete TypeScript API</h2><p>Generated from the exact installed package declarations.</p><pre data-language="typescript"><code>import &#123; PageAst as PageAst$1, WrnDiagnostic &#125; from '@wrnexus/syntax';
export &#123; 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 &#125; from '@wrnexus/syntax';
import &#123; PageAst &#125; from '@wrnexus/syntax/parser';
/**
* Code generation: lower a `.wrn` AST to TypeScript that targets the framework's
* existing primitives.
*
* state -&gt; a `data-scope` declaration consumed by the runtime
* view -&gt; an HTML string returned by a page component
* @event=&quot;...&quot; -&gt; data-on-&lt;event&gt;=&quot;...&quot;
* &quot;...&#123;expr&#125;...&quot; -&gt; text kept verbatim (&#123;expr&#125; is mustache for runtime)
* api=&quot;&lt;name&gt;&quot; -&gt; SSR/client data binding declared in a mode block
* ssrGet/ssrText -&gt; legacy server-side API fetch + render
* csrGet/csrText -&gt; legacy browser-side API fetch + render
* style -&gt; an inline page stylesheet
* functions -&gt; server-only helpers for API/realtime code
* api M /p &#123;b&#125; -&gt; export const M = async (ctx) =&gt; &#123; b &#125;
* realtime &#123;..&#125; -&gt; export const websocket = &#123; evt(ws, ...args) &#123; b &#125; &#125;
*/
declare function generate(ast: PageAst): string;
declare class NativeCompileError extends Error &#123;
constructor(message: string);
&#125;
/** Compile a parsed `.wrn` page to an Expo Router React Native screen. */
declare function generateNative(ast: PageAst): string;
interface CompilationCacheEntry extends CompileResult &#123;
key: string;
file: string;
sourceHash: string;
createdAt: number;
&#125;
interface CompilationCacheOptions &#123;
maxEntries?: number;
now?: () =&gt; number;
&#125;
interface CompilationCache &#123;
compile(source: string, file?: string, salt?: string): CompilationCacheEntry;
get(key: string): CompilationCacheEntry | undefined;
invalidate(file?: string): number;
clear(): void;
size(): number;
stats(): &#123;
hits: number;
misses: number;
entries: number;
&#125;;
&#125;
declare function compilationKey(source: string, file?: string, salt?: string): string;
declare function createCompilationCache(options?: CompilationCacheOptions): CompilationCache;
declare class DependencyGraph &#123;
#private;
set(file: string, dependencies: Iterable&lt;string&gt;): void;
remove(file: string): void;
dependencies(file: string): string[];
dependents(file: string): string[];
affected(file: string): string[];
&#125;
/**
* @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 &#123;
code: string;
ast: PageAst$1;
/** Backward-compatible plain diagnostic messages. */
diagnostics: string[];
/** Structured diagnostics for editors, CI, and the DevToolbar. */
richDiagnostics: WrnDiagnostic[];
&#125;
/** 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 &#123; type CompilationCache, type CompilationCacheEntry, type CompilationCacheOptions, type CompileResult, DependencyGraph, NativeCompileError, compilationKey, compile, compileNativeWireFile, compileWireFile, createCompilationCache, generate, generateNative &#125;;
</code></pre></section><section id="examples" class="examples"><h2>Examples</h2><p>Copy-ready examples from the installed package documentation.</p><div class="example-grid"><article class="example-card"><h3>Compile a page</h3><pre data-language="ts"><code>import &#123; compileWireFile &#125; from &quot;@wrnexus/compiler&quot;;
const ts = compileWireFile(`
page Home &#123;
state count = 0
seo &#123; title = &quot;Home&quot; description = &quot;Welcome&quot; &#125;
view &#123;
&lt;button @click=&quot;count++&quot;&gt;Clicked &#123;count&#125; times&lt;/button&gt;
&#125;
&#125;
`);
// 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.</code></pre></article><article class="example-card"><h3>Inspect the AST and diagnostics</h3><pre data-language="ts"><code>import &#123; compile, ParseError &#125; from &quot;@wrnexus/compiler&quot;;
try &#123;
const &#123; code, ast, diagnostics &#125; = compile(source);
console.log(ast.kind, ast.name, ast.states.length);
&#125; catch (err) &#123;
if (err instanceof ParseError) console.error(err.message);
&#125;</code></pre></article><article class="example-card"><h3>Drive the parse/codegen stages directly</h3><pre data-language="ts"><code>import &#123; parse, generate &#125; from &quot;@wrnexus/compiler&quot;;
const ast = parse(componentSource); // ast.kind === &quot;component&quot;
const module = generate(ast); // exports render(props) + __wrnexusComponent</code></pre></article><article class="example-card"><h3>Use the lexer standalone</h3><pre data-language="ts"><code>import &#123; Lexer &#125; from &quot;@wrnexus/compiler&quot;;
const lx = new Lexer(&quot;page Home &#123;&quot;);
lx.next(); // &#123; type: &quot;ident&quot;, value: &quot;page&quot;, pos: 0 &#125;
lx.next(); // &#123; type: &quot;ident&quot;, value: &quot;Home&quot;, pos: 5 &#125;
lx.next(); // &#123; type: &quot;lbrace&quot;, value: &quot;&#123;&quot;, pos: 10 &#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="#api">API</a><a class="toc-level-4" href="#compilewirefile-source-string-string">compileWireFile(source: string): string</a><a class="toc-level-4" href="#compile-source-string-compileresult">compile(source: string): CompileResult</a><a class="toc-level-4" href="#parse-source-string-pageast">parse(source: string): PageAst</a><a class="toc-level-4" href="#generate-ast-pageast-string">generate(ast: PageAst): string</a><a class="toc-level-4" href="#lexer">Lexer</a><a class="toc-level-4" href="#errors">Errors</a><a class="toc-level-4" href="#ast-types">AST types</a><a class="toc-level-3" href="#usage">Usage</a><a class="toc-level-3" href="#the-wrn-language-as-parsed">The .wrn language (as parsed)</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><div class="footer-brand"><span class="footer-mark" aria-hidden="true">W</span><p><strong>WRNexusJS 0.5.13</strong><span>Complete API documentation generated from installed package declarations.</span></p></div><nav aria-label="Footer"><a href="/packages">All packages</a><a href="/getting-started">Get started</a><a href="/security">Security</a><a href="/support">Support</a><a href="/llms.txt">AI guide</a></nav><p class="footer-meta">Private Developer Preview · Bun-native</p></footer>
<BackToTop />
</div>
}
}