Compare commits
332
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4dd7681bf7 | ||
|
|
843db2815f | ||
|
|
17aa3b98eb | ||
|
|
442a3106ed | ||
|
|
3115277e9d | ||
|
|
02fdfa3aee | ||
|
|
5f66c8129c | ||
|
|
01a3b3b4e9 | ||
|
|
a184f1a3be | ||
|
|
06df9d66ae | ||
|
|
d269772a79 | ||
|
|
df2ee036eb | ||
|
|
b405025f37 | ||
|
|
cd07f0f8e2 | ||
|
|
ce67d0d1d2 | ||
|
|
468f63f378 | ||
|
|
a6570d7f68 | ||
|
|
4ef2ef14ff | ||
|
|
d78707be9f | ||
|
|
1d16ef1e82 | ||
|
|
12a1014db2 | ||
|
|
52b3e6d378 | ||
|
|
f88dd47408 | ||
|
|
f0447fddb0 | ||
|
|
5106256401 | ||
|
|
94a6b436f5 | ||
|
|
2425a5146f | ||
|
|
fc2c526d70 | ||
|
|
fcd552969f | ||
|
|
5deac48131 | ||
|
|
2e1b667285 | ||
|
|
8393a953b7 | ||
|
|
2459a0b5a7 | ||
|
|
4e5949aedc | ||
|
|
60e38b983c | ||
|
|
5afb2d1875 | ||
|
|
2e42be7b31 | ||
|
|
b508b49058 | ||
|
|
e638c6be6a | ||
|
|
082da38f67 | ||
|
|
5de792f359 | ||
|
|
a0dab308f0 | ||
|
|
dd9b7a289a | ||
|
|
effed1c3cf | ||
|
|
6133d33b8c | ||
|
|
32187a425c | ||
|
|
531bf7b2da | ||
|
|
afe1c413cc | ||
|
|
f68f79786f | ||
|
|
d47c57a953 | ||
|
|
7a968977f6 | ||
|
|
fe9bb9ede0 | ||
|
|
7ba7c8a73f | ||
|
|
8e6dca0751 | ||
|
|
b76053ae93 | ||
|
|
13b198326f | ||
|
|
2c960fc1dc | ||
|
|
ec23dd4c93 | ||
|
|
f73fbb7aba | ||
|
|
0f201c9767 | ||
|
|
9637a47ec7 | ||
|
|
1719059fa0 | ||
|
|
cf06a60f2b | ||
|
|
8fa3d7ecd1 | ||
|
|
bf0d866793 | ||
|
|
e189b2b62f | ||
|
|
6c49991700 | ||
|
|
4d6db0d887 | ||
|
|
78ca2b85d9 | ||
|
|
d3fe0a71aa | ||
|
|
794a7b3378 | ||
|
|
b1086d14e9 | ||
|
|
743275e6fa | ||
|
|
904127687b | ||
|
|
b72f517fa4 | ||
|
|
52842f149d | ||
|
|
1cea44aaf2 | ||
|
|
c54a69532c | ||
|
|
8d044565e3 | ||
|
|
feff30a2b5 | ||
|
|
816594a58b | ||
|
|
db612df6cd | ||
|
|
bca9549f3a | ||
|
|
232d8e6734 | ||
|
|
8f19a5eb2b | ||
|
|
937ccb9e8e | ||
|
|
6859b5c4ff | ||
|
|
3f5ec8696f | ||
|
|
9fd80b7cef | ||
|
|
7d87200e31 | ||
|
|
51286d0fa3 | ||
|
|
905cbce0c1 | ||
|
|
09ebd44b6c | ||
|
|
2e5c0cc953 | ||
|
|
1660044ed2 | ||
|
|
324928cfca | ||
|
|
5c2c6a0a8f | ||
|
|
ff62918dbb | ||
|
|
54a93c1d14 | ||
|
|
b6bd5cfcb7 | ||
|
|
fdf6282aed | ||
|
|
ca8aabf640 | ||
|
|
a90d3683d3 | ||
|
|
d85be6c456 | ||
|
|
8ef6233ef3 | ||
|
|
91e8b2ab05 | ||
|
|
b2e83bc941 | ||
|
|
3e77a621f5 | ||
|
|
a1f671ed5d | ||
|
|
7c584c1d2e | ||
|
|
709a38feb4 | ||
|
|
35cd28aad4 | ||
|
|
de8d792e37 | ||
|
|
64bb0e366a | ||
|
|
e4502f2437 | ||
|
|
504d065003 | ||
|
|
f09341fcfa | ||
|
|
535ad5af6d | ||
|
|
247f360ae7 | ||
|
|
790b81330a | ||
|
|
69020b2555 | ||
|
|
9ed896d2b9 | ||
|
|
8389d9674e | ||
|
|
5112cc1a62 | ||
|
|
30d1632252 | ||
|
|
7a2b58652a | ||
|
|
5e65627305 | ||
|
|
84dc4e06a2 | ||
|
|
c7ab605e85 | ||
|
|
8aa28205e0 | ||
|
|
b56cb8cba5 | ||
|
|
b3a4d80df3 | ||
|
|
7bd4574b08 | ||
|
|
e32d83933e | ||
|
|
5ce2771718 | ||
|
|
68c7b96a9f | ||
|
|
6a9c48a207 | ||
|
|
9a03b7c8d4 | ||
|
|
361129b6ac | ||
|
|
8069541cd9 | ||
|
|
4a82640c5b | ||
|
|
52660cbb8e | ||
|
|
ca2f9451ab | ||
|
|
b3116de354 | ||
|
|
f6993e6cdb | ||
|
|
f1d1081b67 | ||
|
|
b4d3cb3695 | ||
|
|
124da548b8 | ||
|
|
f4960f2fc5 | ||
|
|
45ef035bae | ||
|
|
b67a5e43eb | ||
|
|
7ac6e08544 | ||
|
|
f94004648d | ||
|
|
e8e1a2623b | ||
|
|
ecb93c7116 | ||
|
|
f01a308287 | ||
|
|
1fb1a8d2d0 | ||
|
|
949cf78636 | ||
|
|
296728d51d | ||
|
|
98205daef6 | ||
|
|
3eec9fd8c6 | ||
|
|
6aaf21aa06 | ||
|
|
ce68803471 | ||
|
|
7c4b484d0a | ||
|
|
fcf4ed3039 | ||
|
|
e01915823a | ||
|
|
9bc0f48514 | ||
|
|
9f599e02e8 | ||
|
|
83c99cc3e5 | ||
|
|
1393a8a3b8 | ||
|
|
2257ee871e | ||
|
|
40625e98ed | ||
|
|
e0bd84247e | ||
|
|
34d5bbc810 | ||
|
|
e16903b286 | ||
|
|
21ea8a84a0 | ||
|
|
dd8354477d | ||
|
|
796b19d923 | ||
|
|
3e1d7db537 | ||
|
|
a4c7d7b298 | ||
|
|
e1fca3eddf | ||
|
|
63e6148cdb | ||
|
|
87d33a2ce1 | ||
|
|
2ab7b1e762 | ||
|
|
2e93124080 | ||
|
|
2c339bee15 | ||
|
|
41b6e2ed2b | ||
|
|
3867e7c183 | ||
|
|
a7255fa1bd | ||
|
|
fd5e2b7128 | ||
|
|
57097c8204 | ||
|
|
226217ecbf | ||
|
|
daea59cf5d | ||
|
|
bc5437063d | ||
|
|
b9098382b3 | ||
|
|
e5d0654d2a | ||
|
|
3ef353de83 | ||
|
|
726b8a7d24 | ||
|
|
91e5c6e0c5 | ||
|
|
2fbf059c00 | ||
|
|
1cc0b97a72 | ||
|
|
134c5fa4bc | ||
|
|
205f4e2d4c | ||
|
|
f19462dff0 | ||
|
|
3fa3fce5df | ||
|
|
218f5e2dd6 | ||
|
|
e136fbc56a | ||
|
|
41fb82b9e9 | ||
|
|
e7743cdbb5 | ||
|
|
703baa1ead | ||
|
|
e05ddc7aa5 | ||
|
|
6f3a53b9ff | ||
|
|
13859ce7dc | ||
|
|
e15422ed8d | ||
|
|
3f1fcd0d2d | ||
|
|
798f56734a | ||
|
|
77b9e49bf2 | ||
|
|
9e3624e584 | ||
|
|
b7f3507b59 | ||
|
|
cc8085bcfa | ||
|
|
984c6236d3 | ||
|
|
cd82bec414 | ||
|
|
d6a2d05407 | ||
|
|
ae37c9b57a | ||
|
|
86b3dc1e6a | ||
|
|
c499f136fd | ||
|
|
6d8b6daba9 | ||
|
|
d7509421c7 | ||
|
|
d609a41222 | ||
|
|
e710756baf | ||
|
|
ba83038d8d | ||
|
|
f033197850 | ||
|
|
dc0771308a | ||
|
|
83f2951035 | ||
|
|
4362d49770 | ||
|
|
a01b7bc99e | ||
|
|
9b6b970cae | ||
|
|
1849213ce4 | ||
|
|
d694dda320 | ||
|
|
212fdaa5b5 | ||
|
|
0ac648bc26 | ||
|
|
10da210b0a | ||
|
|
b209936f86 | ||
|
|
c64434a131 | ||
|
|
72e4d3eceb | ||
|
|
4cebacadfe | ||
|
|
e8f630f12d | ||
|
|
4550a11460 | ||
|
|
3c6b659f36 | ||
|
|
1a1d2e9d08 | ||
|
|
fed1d5d3f4 | ||
|
|
b61020babd | ||
|
|
379f80cbd0 | ||
|
|
649e3d9127 | ||
|
|
b3e9b99e13 | ||
|
|
586a6db8ff | ||
|
|
87507edf59 | ||
|
|
c54144f2e4 | ||
|
|
2b06b00d35 | ||
|
|
28d931dfff | ||
|
|
e2f7bea299 | ||
|
|
d5e834bc78 | ||
|
|
687d345882 | ||
|
|
3e565e8d03 | ||
|
|
358a520bc5 | ||
|
|
9dffe83f32 | ||
|
|
d64e899993 | ||
|
|
f37303b22d | ||
|
|
d1b0c55b53 | ||
|
|
8fc6f15402 | ||
|
|
6afe32f63f | ||
|
|
76c768099d | ||
|
|
30e5721e84 | ||
|
|
8b728a3e5d | ||
|
|
d0aded0392 | ||
|
|
c81dedff17 | ||
|
|
44ba847210 | ||
|
|
798f06d4c0 | ||
|
|
173e230d7f | ||
|
|
bbec4cc7bb | ||
|
|
504bd4358f | ||
|
|
e543fd026d | ||
|
|
d51662826d | ||
|
|
e2d9ea1ece | ||
|
|
58ba2f2046 | ||
|
|
304819dfe9 | ||
|
|
07d8fb59d6 | ||
|
|
13dfa31d19 | ||
|
|
c6fc0f1f63 | ||
|
|
7ff5b3e8c5 | ||
|
|
569365143b | ||
|
|
69b6cd431f | ||
|
|
2ca2d02b22 | ||
|
|
0013c0771d | ||
|
|
0b8856b3b5 | ||
|
|
45e6fd3cb9 | ||
|
|
54f5309fca | ||
|
|
944f83d3f4 | ||
|
|
a75779fa4d | ||
|
|
2b4083c6db | ||
|
|
aa2595ec01 | ||
|
|
b3e5e5b999 | ||
|
|
3888453e0d | ||
|
|
b95bdc6e77 | ||
|
|
1745d8d676 | ||
|
|
f72aec7c8c | ||
|
|
33730c68ab | ||
|
|
5ce45b4973 | ||
|
|
dcdb5e766d | ||
|
|
a3e21163c1 | ||
|
|
c5326f7622 | ||
|
|
eaea2c5f72 | ||
|
|
ca8f746f41 | ||
|
|
94ae40d8bd | ||
|
|
0d3ec79ee4 | ||
|
|
c0c09426ff | ||
|
|
14e2878417 | ||
|
|
180239ef4c | ||
|
|
12beb6f4ba | ||
|
|
6dbc75c370 | ||
|
|
7cee13526e | ||
|
|
3bb096057e | ||
|
|
646d16f83d | ||
|
|
df4c1d3e7d | ||
|
|
17dc7c1a06 | ||
|
|
c72cbbd780 | ||
|
|
1cda2a01b3 | ||
|
|
9ca1cc6b0f | ||
|
|
aa6badbd31 | ||
|
|
4a3ee3baa7 | ||
|
|
95ca1c0625 | ||
|
|
d22824fa62 |
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"version": "0.0.1",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "basic-app",
|
||||
"runtimeExecutable": "bun",
|
||||
"runtimeArgs": [
|
||||
"run",
|
||||
"packages/cli/src/index.ts",
|
||||
"dev",
|
||||
"examples/basic-app",
|
||||
"--port=3520"
|
||||
],
|
||||
"port": 3520
|
||||
},
|
||||
{
|
||||
"name": "component-showcase",
|
||||
"runtimeExecutable": "bun",
|
||||
"runtimeArgs": [
|
||||
"run",
|
||||
"packages/cli/src/index.ts",
|
||||
"dev",
|
||||
"examples/component-showcase",
|
||||
"--port=3400"
|
||||
],
|
||||
"port": 3400
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
# Enforce LF in the working tree regardless of a contributor's core.autocrlf.
|
||||
# Without this, Git on Windows smudges every text file to CRLF on clone, stash
|
||||
# pop, or checkout, which fails `bun run format:check` (prettier endOfLine: lf).
|
||||
* text=auto eol=lf
|
||||
|
||||
# Binary assets Git must not touch.
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
*.gif binary
|
||||
*.webp binary
|
||||
*.ico binary
|
||||
*.pdf binary
|
||||
*.woff binary
|
||||
*.woff2 binary
|
||||
*.db binary
|
||||
@@ -0,0 +1,50 @@
|
||||
name: Quality
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, windows-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.3.14
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
cache-dependency-path: editors/vscode/package-lock.json
|
||||
- name: Install framework dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
- name: Install editor dependencies
|
||||
run: npm ci --prefix editors/vscode
|
||||
- name: Typecheck
|
||||
run: bun run typecheck
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
- name: Formatting
|
||||
run: bun run format:check
|
||||
- name: Package and application tests
|
||||
run: bun run test:all
|
||||
- name: Package contracts
|
||||
run: bun run check:public-api && bun run check:ui-visual && bun run audit:packages && bun run test:package-kits && bun run validate:staging
|
||||
- name: Stage and test publishable packages
|
||||
if: matrix.os == 'ubuntu-latest'
|
||||
run: bun run stage:packages && bun run test:staged-consumers
|
||||
- name: Framework validation
|
||||
run: bun run validate:0.8
|
||||
- name: Dependency audit
|
||||
run: bun audit
|
||||
- name: Editor dependency audit
|
||||
run: npm audit --prefix editors/vscode --audit-level=high
|
||||
+18
@@ -1,9 +1,27 @@
|
||||
node_modules/
|
||||
dist/
|
||||
.wrnexus/
|
||||
.wrnexus-*/
|
||||
*.log
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
.DS_Store
|
||||
bun.lockb
|
||||
|
||||
.publish/
|
||||
|
||||
# Environment files may contain secrets. Commit only templates.
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
!.env.*.example
|
||||
|
||||
# Local focused typecheck helpers must never enter the repository.
|
||||
focus-shims.d.ts
|
||||
tsconfig.focus.json
|
||||
|
||||
# Scratch dirs for tests that must dynamically import scaffolded files using
|
||||
# "@wrnexus/*" bare specifiers (resolved via the root tsconfig.json `paths`,
|
||||
# which requires the scaffold to live inside the repo tree).
|
||||
**/test/.tmp-*/
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
@wrnexus:registry=https://registry.npmjs.org/
|
||||
audit=true
|
||||
fund=false
|
||||
+18
-2
@@ -1,8 +1,10 @@
|
||||
node_modules/
|
||||
dist/
|
||||
**/dist/
|
||||
**/.wrnexus/**
|
||||
**/.wrnexus-*/**
|
||||
.publish/
|
||||
**/.wirefw/
|
||||
**/.wrnfw/
|
||||
coverage/
|
||||
bun.lock
|
||||
bun.lockb
|
||||
@@ -10,8 +12,22 @@ bun.lockb
|
||||
|
||||
# Generated code (queries.gen.ts, routes.gen.ts, etc.)
|
||||
**/*.gen.ts
|
||||
**/*.generated.d.ts
|
||||
|
||||
# Bundled .wire compiler for the VS Code extension (generated)
|
||||
# Bundled .wrn compiler for the VS Code extension (generated)
|
||||
editors/vscode/src/compiler.cjs
|
||||
editors/vscode/src/language-server.cjs
|
||||
editors/vscode/src/extension.bundle.cjs
|
||||
docs/public-api-0.8.json
|
||||
docs/ui-visual-contract-0.8.json
|
||||
*.svg
|
||||
**/.vscodeignore
|
||||
|
||||
# Local focused typecheck helpers (never part of a release)
|
||||
focus-shims.d.ts
|
||||
**/focus-shims.d.ts
|
||||
tsconfig.focus.json
|
||||
**/tsconfig.focus.json
|
||||
|
||||
# SDD scratch workspace (git-ignored controller artifacts)
|
||||
.superpowers/
|
||||
|
||||
@@ -1,165 +0,0 @@
|
||||
# @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).
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/ai",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "Zero-dependency Claude (Anthropic) client for WrNexus apps.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
# @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).
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/authz",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/authz — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,262 +0,0 @@
|
||||
# @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 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
|
||||
```
|
||||
|
||||
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.
|
||||
@@ -1,45 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/cli",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/cli — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
},
|
||||
"./workspace": {
|
||||
"types": "./dist/workspace.d.ts",
|
||||
"import": "./dist/workspace.js"
|
||||
}
|
||||
},
|
||||
"bin": {
|
||||
"wrnexus": "./dist/index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@wrnexus/core": "^0.2.46",
|
||||
"@wrnexus/router": "^0.2.46",
|
||||
"@wrnexus/csr": "^0.2.46",
|
||||
"@wrnexus/compiler": "^0.2.46",
|
||||
"@wrnexus/styles": "^0.2.46",
|
||||
"@wrnexus/dev-server": "^0.2.46",
|
||||
"@wrnexus/ui": "^0.2.46",
|
||||
"@wrnexus/validation": "^0.2.46",
|
||||
"@wrnexus/i18n": "^0.2.46",
|
||||
"@wrnexus/db": "^0.2.46"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
# @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.
|
||||
|
||||
## 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: `kind` (`"page" \| "component"`), `name`, optional `layout`, `props`, `states`, `seo`, `view`, `styles`, `functions`, `dataApis`, `modeFunctions`, `apis`, `realtimes`. |
|
||||
| `ViewNode` | `{ type: "text"; value }` or `{ type: "element"; tag; attrs; children }`. |
|
||||
| `Attr` | `{ name; value; event; boolean? }` — `event` marks `@event` bindings. |
|
||||
| `StateDecl` | `{ name; expr }` — a `state x = <expr>` 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).
|
||||
- `props { name = <default> ... }` — component props; each default's type drives coercion.
|
||||
- `state <ident> = <expr>` — reactive state seeded from a raw JS expression.
|
||||
- `view { <html> }` — plain HTML with `{expr}` interpolation in text and attributes, hyphenated attributes, boolean attributes, `@event="..."` client bindings, and `<!-- comments -->`. Attribute expressions that reference `state` keep an SSR 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 { <raw js> }` — shared server-side helpers (repeatable).
|
||||
- `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.
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/compiler",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/compiler — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,381 +0,0 @@
|
||||
# @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.
|
||||
@@ -1,34 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/core",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/core — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
},
|
||||
"./jsx-runtime": {
|
||||
"types": "./dist/jsx-runtime.d.ts",
|
||||
"import": "./dist/jsx-runtime.js"
|
||||
},
|
||||
"./jsx-dev-runtime": {
|
||||
"types": "./dist/jsx-dev-runtime.d.ts",
|
||||
"import": "./dist/jsx-dev-runtime.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,189 +0,0 @@
|
||||
# @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. `item, i in list`) | Per-item list rendering template |
|
||||
| `{{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.
|
||||
@@ -1,29 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/csr",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/csr — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@wrnexus/core": "^0.2.46"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,228 +0,0 @@
|
||||
# @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.
|
||||
@@ -1,50 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/db",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/db — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
},
|
||||
"./connect": {
|
||||
"types": "./dist/connect.d.ts",
|
||||
"import": "./dist/connect.js"
|
||||
},
|
||||
"./session": {
|
||||
"types": "./dist/session-store.d.ts",
|
||||
"import": "./dist/session-store.js"
|
||||
},
|
||||
"./sqlite": {
|
||||
"types": "./dist/adapters/sqlite.d.ts",
|
||||
"import": "./dist/adapters/sqlite.js"
|
||||
},
|
||||
"./postgres": {
|
||||
"types": "./dist/adapters/postgres.d.ts",
|
||||
"import": "./dist/adapters/postgres.js"
|
||||
},
|
||||
"./mysql": {
|
||||
"types": "./dist/adapters/mysql.d.ts",
|
||||
"import": "./dist/adapters/mysql.js"
|
||||
},
|
||||
"./mongo": {
|
||||
"types": "./dist/adapters/mongo.d.ts",
|
||||
"import": "./dist/adapters/mongo.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,303 +0,0 @@
|
||||
# @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>
|
||||
@@ -1,44 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/dev-server",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/dev-server — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
},
|
||||
"./serve-entry": {
|
||||
"types": "./dist/serve-entry.d.ts",
|
||||
"import": "./dist/serve-entry.js"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@wrnexus/core": "^0.2.46",
|
||||
"@wrnexus/router": "^0.2.46",
|
||||
"@wrnexus/ssr": "^0.2.46",
|
||||
"@wrnexus/csr": "^0.2.46",
|
||||
"@wrnexus/compiler": "^0.2.46",
|
||||
"@wrnexus/styles": "^0.2.46",
|
||||
"@wrnexus/ui": "^0.2.46",
|
||||
"@wrnexus/validation": "^0.2.46",
|
||||
"@wrnexus/i18n": "^0.2.46",
|
||||
"@wrnexus/db": "^0.2.46",
|
||||
"@wrnexus/pubsub": "^0.2.46",
|
||||
"@wrnexus/uploader": "^0.2.46"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
# @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.
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/encryption",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/encryption — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
# @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`.
|
||||
@@ -1,29 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/helpers",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "Safe convenience helpers for WrNexus request contexts and common application flows.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@wrnexus/core": "^0.2.46"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
# @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.
|
||||
@@ -1,29 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/i18n",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/i18n — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@wrnexus/core": "^0.2.46"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
# @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.
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/jwt",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/jwt — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
# @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.
|
||||
@@ -1,29 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/mobile",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/mobile — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@wrnexus/native": "^0.2.46"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
# @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.
|
||||
@@ -1,34 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/native",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/native — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
},
|
||||
"./browser": {
|
||||
"types": "./dist/browser.d.ts",
|
||||
"import": "./dist/browser.js"
|
||||
},
|
||||
"./mobile": {
|
||||
"types": "./dist/mobile.d.ts",
|
||||
"import": "./dist/mobile.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,196 +0,0 @@
|
||||
# @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.
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/oauth",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/oauth — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
# @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.
|
||||
@@ -1,30 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/pubsub",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/pubsub — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
},
|
||||
"./redis": {
|
||||
"types": "./dist/redis.d.ts",
|
||||
"import": "./dist/redis.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
# @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.
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/queue",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/queue — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
# @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.
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/reactive",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/reactive — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
# @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.
|
||||
@@ -1,30 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/router",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/router — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@wrnexus/compiler": "^0.2.46",
|
||||
"@wrnexus/core": "^0.2.46"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
# @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).
|
||||
@@ -1,29 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/ssr",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/ssr — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@wrnexus/core": "^0.2.46"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,227 +0,0 @@
|
||||
# @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 {
|
||||
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 token keys (both `light` and `dark`): `color-scheme`, `color-bg`, `color-surface`, `color-surface-2`, `color-text`, `color-muted`, `color-border`, `color-primary`, `color-primary-hover`, `color-primary-contrast`, `color-danger`, `color-success`, `color-warning`, `radius`, `radius-sm`, `font-sans`, `shadow-1`.
|
||||
|
||||
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: {
|
||||
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.
|
||||
@@ -1,29 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/styles",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/styles — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@wrnexus/uploader": "^0.2.46"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
# @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).
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/test",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/test — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
# @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.
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/tracking",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/tracking — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
# @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.
|
||||
|
||||
## 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 mount name
|
||||
is the **lowercase file basename** (e.g. `button.wrn` → `data-component="button"`).
|
||||
Each 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`, and `table`.
|
||||
|
||||
The authoritative, always-current list is `uiComponentNames()` (below), which reads
|
||||
the component directory at runtime.
|
||||
|
||||
## API
|
||||
|
||||
The JS module (`@wrnexus/ui`) exposes four 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 built-in component names (e.g. for `wrnexus eject` listing). |
|
||||
|
||||
### `./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.
|
||||
|
||||
## 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.
|
||||
@@ -1,16 +0,0 @@
|
||||
// Callout box. variant: info | success | danger | warning.
|
||||
// Optional `title`; body from `message` prop or the slot.
|
||||
component Alert {
|
||||
props {
|
||||
variant = "info"
|
||||
title = ""
|
||||
message = ""
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<div class="wire-alert wire-alert--{variant} {class}" role="alert">
|
||||
<div class="wire-alert__title">{title}</div>
|
||||
<div class="wire-alert__body"><slot>{message}</slot></div>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
// Rounded user image.
|
||||
component Avatar {
|
||||
props {
|
||||
src = ""
|
||||
alt = ""
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<img class="wire-avatar {class}" src="{src}" alt="{alt}">
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
// Small status label. variant: default | primary | success | danger | warning.
|
||||
component Badge {
|
||||
props {
|
||||
label = ""
|
||||
variant = "default"
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<span class="wire-badge wire-badge--{variant} {class}"><slot>{label}</slot></span>
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
// Button. variant: default | primary | danger | ghost — size: sm | md | lg.
|
||||
// Use the `label` prop, or put custom content in the slot.
|
||||
component Button {
|
||||
props {
|
||||
label = "Button"
|
||||
variant = "default"
|
||||
size = "md"
|
||||
type = "button"
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<button type="{type}" class="wire-btn wire-btn--{variant} wire-btn--{size} {class}"><slot>{label}</slot></button>
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
// Surface container with padding, border, and rounded corners.
|
||||
component Card {
|
||||
props {
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<div class="wire-card {class}"><slot></slot></div>
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
// Checkbox with an inline label.
|
||||
component Checkbox {
|
||||
props {
|
||||
name = ""
|
||||
label = ""
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<label class="wire-check {class}">
|
||||
<input type="checkbox" name="{name}" class="wire-check__box">
|
||||
<span class="wire-check__label"><slot>{label}</slot></span>
|
||||
</label>
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
// Centered, max-width page container. Children go in the <slot>.
|
||||
component Container {
|
||||
props {
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<div class="wire-container {class}"><slot></slot></div>
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
// Expand/collapse section using native <details> (no JS).
|
||||
component Disclosure {
|
||||
props {
|
||||
summary = "Details"
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<details class="wire-disclosure {class}">
|
||||
<summary class="wire-disclosure__summary">{summary}</summary>
|
||||
<div class="wire-disclosure__body"><slot></slot></div>
|
||||
</details>
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
// Horizontal rule using theme border color.
|
||||
component Divider {
|
||||
props {
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<hr class="wire-divider {class}">
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
// Drag-and-drop file uploader with per-file progress. Progressive enhancement:
|
||||
// the markup is inert until /__wrnexus/uploader.js loads (auto-injected when a
|
||||
// page contains `data-uploader`). Pairs with `handleUpload` on the server —
|
||||
// files POST to `endpoint`, which returns `{ ok, files:[{ key, url, … }] }`.
|
||||
//
|
||||
// <div data-component="file-upload" store="public" endpoint="/api/upload"
|
||||
// accept="image/*" max="10000000" multiple="true"></div>
|
||||
component FileUpload {
|
||||
props {
|
||||
store = "public"
|
||||
endpoint = "/api/upload"
|
||||
accept = ""
|
||||
multiple = false
|
||||
max = 0
|
||||
label = "Drag files here or click to browse"
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<div class="wire-fileupload {class}" data-uploader="{store}" data-endpoint="{endpoint}" data-accept="{accept}" data-multiple="{multiple}" data-max="{max}" data-label="{label}"></div>
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
// Responsive-ish grid: `cols` columns (1–6) with a gap (scale 0–8).
|
||||
component Grid {
|
||||
props {
|
||||
cols = "2"
|
||||
gap = "4"
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<div class="wire-grid wire-cols-{cols} wire-gap-{gap} {class}"><slot></slot></div>
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
// Horizontal stack: row layout with a gap and cross-axis alignment.
|
||||
// align: start | center | end | stretch
|
||||
component HStack {
|
||||
props {
|
||||
gap = "4"
|
||||
align = "center"
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<div class="wire-hstack wire-gap-{gap} wire-items-{align} {class}"><slot></slot></div>
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
// Text input. Pairs with the validation system (name maps to a field).
|
||||
component Input {
|
||||
props {
|
||||
type = "text"
|
||||
name = ""
|
||||
value = ""
|
||||
placeholder = ""
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<input type="{type}" name="{name}" value="{value}" placeholder="{placeholder}" class="wire-input {class}">
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
// Progress bar (native <progress>, themed).
|
||||
component Progress {
|
||||
props {
|
||||
value = 0
|
||||
max = 100
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<progress class="wire-progress {class}" value="{value}" max="{max}"></progress>
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
// Radio input with an inline label.
|
||||
component Radio {
|
||||
props {
|
||||
name = ""
|
||||
value = ""
|
||||
label = ""
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<label class="wire-check {class}">
|
||||
<input type="radio" name="{name}" value="{value}" class="wire-check__box">
|
||||
<span class="wire-check__label"><slot>{label}</slot></span>
|
||||
</label>
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
// Styled native select. Put <option>s in the slot.
|
||||
component Select {
|
||||
props {
|
||||
name = ""
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<select name="{name}" class="wire-input wire-select {class}"><slot></slot></select>
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
// Loading placeholder (animated shimmer). Size it with width/height props.
|
||||
component Skeleton {
|
||||
props {
|
||||
width = "100%"
|
||||
height = "1rem"
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<span class="wire-skeleton {class}" style="width: {width}; height: {height};" aria-hidden="true"></span>
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
// Flexible spacer: grows to push siblings apart inside a flex row/column.
|
||||
component Spacer {
|
||||
props {
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<div class="wire-spacer {class}"></div>
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
// Loading spinner (pure CSS animation, no JS).
|
||||
component Spinner {
|
||||
props {
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<span class="wire-spinner {class}" role="status" aria-label="Loading"></span>
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
// Vertical stack: lays children out in a column with a gap (scale 0–8).
|
||||
component Stack {
|
||||
props {
|
||||
gap = "4"
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<div class="wire-stack wire-gap-{gap} {class}"><slot></slot></div>
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
// Toggle switch (an accessible checkbox styled as a switch).
|
||||
component Switch {
|
||||
props {
|
||||
name = ""
|
||||
label = ""
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<label class="wire-switch {class}">
|
||||
<input type="checkbox" name="{name}" class="wire-switch__input" role="switch">
|
||||
<span class="wire-switch__track"><span class="wire-switch__thumb"></span></span>
|
||||
<span class="wire-switch__label"><slot>{label}</slot></span>
|
||||
</label>
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
// Themed table wrapper — put a <table>…</table> (or thead/tbody) in the slot.
|
||||
// Scrolls horizontally on small screens.
|
||||
component Table {
|
||||
props {
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<div class="wire-table-wrap {class}">
|
||||
<table class="wire-table"><slot></slot></table>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
// Small tag / chip. variant: default | primary | success | danger | warning.
|
||||
component Tag {
|
||||
props {
|
||||
label = ""
|
||||
variant = "default"
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<span class="wire-tag wire-tag--{variant} {class}"><slot>{label}</slot></span>
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
// Multi-line text input.
|
||||
component Textarea {
|
||||
props {
|
||||
name = ""
|
||||
placeholder = ""
|
||||
rows = "4"
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<textarea name="{name}" placeholder="{placeholder}" rows="{rows}" class="wire-input wire-textarea {class}"><slot></slot></textarea>
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
// Theme switch button. The framework's theme runtime binds the click
|
||||
// (data-wire-theme-toggle), so no component JS is needed.
|
||||
component ThemeToggle {
|
||||
props {
|
||||
label = "Toggle theme"
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<button type="button" class="wire-btn wire-btn--ghost {class}" data-wire-theme-toggle><slot>{label}</slot></button>
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
// CSS-only tooltip shown on hover/focus. Wrap the trigger content in the slot.
|
||||
component Tooltip {
|
||||
props {
|
||||
text = ""
|
||||
class = ""
|
||||
}
|
||||
view {
|
||||
<span class="wire-tooltip {class}" data-tooltip="{text}" tabindex="0"><slot></slot></span>
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/ui",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/ui — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
},
|
||||
"./ui.css": "./ui.css"
|
||||
},
|
||||
"dependencies": {
|
||||
"@wrnexus/core": "^0.2.46"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"components",
|
||||
"ui.css"
|
||||
]
|
||||
}
|
||||
@@ -1,525 +0,0 @@
|
||||
/*
|
||||
* Wire UI stylesheet. Served once at /__wrnexus/ui.css. Every value is a theme
|
||||
* token (var(--wire-*)), so components restyle instantly when the theme changes.
|
||||
* Override any of these classes in your own CSS (it loads after ui.css).
|
||||
*/
|
||||
|
||||
/* --- Layout --------------------------------------------------------------- */
|
||||
.wire-container {
|
||||
width: 100%;
|
||||
max-width: 960px;
|
||||
margin-inline: auto;
|
||||
padding-inline: 1rem;
|
||||
}
|
||||
.wire-stack {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.wire-hstack {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.wire-grid {
|
||||
display: grid;
|
||||
}
|
||||
.wire-spacer {
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
.wire-divider {
|
||||
border: 0;
|
||||
border-top: 1px solid var(--wire-color-border);
|
||||
margin: 1rem 0;
|
||||
}
|
||||
|
||||
/* gap scale (shared by stack / hstack / grid) */
|
||||
.wire-gap-0 {
|
||||
gap: 0;
|
||||
}
|
||||
.wire-gap-1 {
|
||||
gap: 0.25rem;
|
||||
}
|
||||
.wire-gap-2 {
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.wire-gap-3 {
|
||||
gap: 0.75rem;
|
||||
}
|
||||
.wire-gap-4 {
|
||||
gap: 1rem;
|
||||
}
|
||||
.wire-gap-5 {
|
||||
gap: 1.5rem;
|
||||
}
|
||||
.wire-gap-6 {
|
||||
gap: 2rem;
|
||||
}
|
||||
.wire-gap-8 {
|
||||
gap: 3rem;
|
||||
}
|
||||
|
||||
.wire-items-start {
|
||||
align-items: flex-start;
|
||||
}
|
||||
.wire-items-center {
|
||||
align-items: center;
|
||||
}
|
||||
.wire-items-end {
|
||||
align-items: flex-end;
|
||||
}
|
||||
.wire-items-stretch {
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.wire-cols-1 {
|
||||
grid-template-columns: repeat(1, 1fr);
|
||||
}
|
||||
.wire-cols-2 {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
.wire-cols-3 {
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
}
|
||||
.wire-cols-4 {
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
}
|
||||
.wire-cols-5 {
|
||||
grid-template-columns: repeat(5, 1fr);
|
||||
}
|
||||
.wire-cols-6 {
|
||||
grid-template-columns: repeat(6, 1fr);
|
||||
}
|
||||
@media (max-width: 640px) {
|
||||
.wire-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- Button --------------------------------------------------------------- */
|
||||
.wire-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.4rem;
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--wire-radius-sm);
|
||||
padding: 0.55rem 0.9rem;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
transition:
|
||||
filter 0.15s ease,
|
||||
background 0.15s ease,
|
||||
transform 0.04s ease;
|
||||
}
|
||||
.wire-btn:active {
|
||||
transform: translateY(1px);
|
||||
}
|
||||
.wire-btn:focus-visible {
|
||||
outline: 2px solid var(--wire-color-primary);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.wire-btn--default {
|
||||
background: var(--wire-color-surface-2);
|
||||
color: var(--wire-color-text);
|
||||
border-color: var(--wire-color-border);
|
||||
}
|
||||
.wire-btn--primary {
|
||||
background: var(--wire-color-primary);
|
||||
color: var(--wire-color-primary-contrast);
|
||||
}
|
||||
.wire-btn--primary:hover {
|
||||
background: var(--wire-color-primary-hover);
|
||||
}
|
||||
.wire-btn--danger {
|
||||
background: var(--wire-color-danger);
|
||||
color: #fff;
|
||||
}
|
||||
.wire-btn--ghost {
|
||||
background: transparent;
|
||||
color: var(--wire-color-text);
|
||||
border-color: var(--wire-color-border);
|
||||
}
|
||||
.wire-btn--ghost:hover {
|
||||
background: var(--wire-color-surface-2);
|
||||
}
|
||||
|
||||
.wire-btn--sm {
|
||||
padding: 0.35rem 0.6rem;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.wire-btn--md {
|
||||
padding: 0.55rem 0.9rem;
|
||||
}
|
||||
.wire-btn--lg {
|
||||
padding: 0.7rem 1.2rem;
|
||||
font-size: 1.05rem;
|
||||
}
|
||||
|
||||
/* --- Inputs --------------------------------------------------------------- */
|
||||
.wire-input {
|
||||
width: 100%;
|
||||
font: inherit;
|
||||
color: var(--wire-color-text);
|
||||
background: var(--wire-color-bg);
|
||||
border: 1px solid var(--wire-color-border);
|
||||
border-radius: var(--wire-radius-sm);
|
||||
padding: 0.5rem 0.7rem;
|
||||
}
|
||||
.wire-input::placeholder {
|
||||
color: var(--wire-color-muted);
|
||||
}
|
||||
.wire-input:focus-visible {
|
||||
outline: 2px solid var(--wire-color-primary);
|
||||
outline-offset: 1px;
|
||||
border-color: var(--wire-color-primary);
|
||||
}
|
||||
.wire-textarea {
|
||||
resize: vertical;
|
||||
min-height: 4.5rem;
|
||||
}
|
||||
|
||||
/* Validation states (set by /__wrnexus/validate.js). */
|
||||
.wire-invalid {
|
||||
border-color: var(--wire-color-danger) !important;
|
||||
}
|
||||
.wire-field-error {
|
||||
display: block;
|
||||
min-height: 1em;
|
||||
margin-top: 0.25rem;
|
||||
color: var(--wire-color-danger);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.wire-check {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.wire-check__box {
|
||||
width: 1rem;
|
||||
height: 1rem;
|
||||
accent-color: var(--wire-color-primary);
|
||||
}
|
||||
.wire-check__box:focus-visible {
|
||||
outline: 2px solid var(--wire-color-primary);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.wire-check__label {
|
||||
color: var(--wire-color-text);
|
||||
}
|
||||
|
||||
/* --- Badge ---------------------------------------------------------------- */
|
||||
.wire-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: 999px;
|
||||
}
|
||||
.wire-badge--default {
|
||||
background: var(--wire-color-surface-2);
|
||||
color: var(--wire-color-text);
|
||||
}
|
||||
.wire-badge--primary {
|
||||
background: var(--wire-color-primary);
|
||||
color: var(--wire-color-primary-contrast);
|
||||
}
|
||||
.wire-badge--success {
|
||||
background: var(--wire-color-success);
|
||||
color: #05210f;
|
||||
}
|
||||
.wire-badge--danger {
|
||||
background: var(--wire-color-danger);
|
||||
color: #fff;
|
||||
}
|
||||
.wire-badge--warning {
|
||||
background: var(--wire-color-warning);
|
||||
color: #201400;
|
||||
}
|
||||
|
||||
/* --- Alert ---------------------------------------------------------------- */
|
||||
.wire-alert {
|
||||
border: 1px solid var(--wire-color-border);
|
||||
border-left-width: 4px;
|
||||
border-radius: var(--wire-radius-sm);
|
||||
padding: 0.75rem 1rem;
|
||||
background: var(--wire-color-surface);
|
||||
color: var(--wire-color-text);
|
||||
}
|
||||
.wire-alert__title {
|
||||
font-weight: 700;
|
||||
margin-bottom: 0.15rem;
|
||||
}
|
||||
.wire-alert__title:empty {
|
||||
display: none;
|
||||
}
|
||||
.wire-alert__body {
|
||||
color: var(--wire-color-muted);
|
||||
}
|
||||
.wire-alert--info {
|
||||
border-left-color: var(--wire-color-primary);
|
||||
}
|
||||
.wire-alert--success {
|
||||
border-left-color: var(--wire-color-success);
|
||||
}
|
||||
.wire-alert--danger {
|
||||
border-left-color: var(--wire-color-danger);
|
||||
}
|
||||
.wire-alert--warning {
|
||||
border-left-color: var(--wire-color-warning);
|
||||
}
|
||||
|
||||
/* --- Card ----------------------------------------------------------------- */
|
||||
.wire-card {
|
||||
background: var(--wire-color-surface);
|
||||
border: 1px solid var(--wire-color-border);
|
||||
border-radius: var(--wire-radius);
|
||||
padding: 1.25rem;
|
||||
box-shadow: var(--wire-shadow-1);
|
||||
}
|
||||
|
||||
/* --- Avatar --------------------------------------------------------------- */
|
||||
.wire-avatar {
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
border-radius: 999px;
|
||||
object-fit: cover;
|
||||
border: 1px solid var(--wire-color-border);
|
||||
}
|
||||
|
||||
/* --- Spinner -------------------------------------------------------------- */
|
||||
.wire-spinner {
|
||||
display: inline-block;
|
||||
width: 1.15rem;
|
||||
height: 1.15rem;
|
||||
border: 2px solid var(--wire-color-border);
|
||||
border-top-color: var(--wire-color-primary);
|
||||
border-radius: 999px;
|
||||
animation: wire-spin 0.7s linear infinite;
|
||||
}
|
||||
@keyframes wire-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
/* --- Disclosure ----------------------------------------------------------- */
|
||||
.wire-disclosure {
|
||||
border: 1px solid var(--wire-color-border);
|
||||
border-radius: var(--wire-radius-sm);
|
||||
background: var(--wire-color-surface);
|
||||
}
|
||||
.wire-disclosure__summary {
|
||||
cursor: pointer;
|
||||
padding: 0.6rem 0.9rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.wire-disclosure__summary:focus-visible {
|
||||
outline: 2px solid var(--wire-color-primary);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
.wire-disclosure__body {
|
||||
padding: 0 0.9rem 0.75rem;
|
||||
color: var(--wire-color-muted);
|
||||
}
|
||||
|
||||
/* --- Select --------------------------------------------------------------- */
|
||||
.wire-select {
|
||||
appearance: none;
|
||||
background-image:
|
||||
linear-gradient(45deg, transparent 50%, var(--wire-color-muted) 50%),
|
||||
linear-gradient(135deg, var(--wire-color-muted) 50%, transparent 50%);
|
||||
background-position:
|
||||
calc(100% - 18px) 1.05em,
|
||||
calc(100% - 13px) 1.05em;
|
||||
background-size:
|
||||
5px 5px,
|
||||
5px 5px;
|
||||
background-repeat: no-repeat;
|
||||
padding-right: 2rem;
|
||||
}
|
||||
|
||||
/* --- Switch --------------------------------------------------------------- */
|
||||
.wire-switch {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.wire-switch__input {
|
||||
position: absolute;
|
||||
opacity: 0;
|
||||
width: 0;
|
||||
height: 0;
|
||||
}
|
||||
.wire-switch__track {
|
||||
position: relative;
|
||||
width: 2.25rem;
|
||||
height: 1.25rem;
|
||||
border-radius: 999px;
|
||||
background: var(--wire-color-border);
|
||||
transition: background 0.15s ease;
|
||||
flex: none;
|
||||
}
|
||||
.wire-switch__thumb {
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
left: 2px;
|
||||
width: calc(1.25rem - 4px);
|
||||
height: calc(1.25rem - 4px);
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
transition: transform 0.15s ease;
|
||||
}
|
||||
.wire-switch__input:checked + .wire-switch__track {
|
||||
background: var(--wire-color-primary);
|
||||
}
|
||||
.wire-switch__input:checked + .wire-switch__track .wire-switch__thumb {
|
||||
transform: translateX(1rem);
|
||||
}
|
||||
.wire-switch__input:focus-visible + .wire-switch__track {
|
||||
outline: 2px solid var(--wire-color-primary);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.wire-switch__label {
|
||||
color: var(--wire-color-text);
|
||||
}
|
||||
|
||||
/* --- Progress ------------------------------------------------------------- */
|
||||
.wire-progress {
|
||||
appearance: none;
|
||||
width: 100%;
|
||||
height: 0.5rem;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
overflow: hidden;
|
||||
background: var(--wire-color-surface-2);
|
||||
}
|
||||
.wire-progress::-webkit-progress-bar {
|
||||
background: var(--wire-color-surface-2);
|
||||
}
|
||||
.wire-progress::-webkit-progress-value {
|
||||
background: var(--wire-color-primary);
|
||||
border-radius: 999px;
|
||||
}
|
||||
.wire-progress::-moz-progress-bar {
|
||||
background: var(--wire-color-primary);
|
||||
}
|
||||
|
||||
/* --- Tag ------------------------------------------------------------------ */
|
||||
.wire-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
padding: 0.2rem 0.5rem;
|
||||
border-radius: var(--wire-radius-sm);
|
||||
border: 1px solid var(--wire-color-border);
|
||||
background: var(--wire-color-surface-2);
|
||||
color: var(--wire-color-text);
|
||||
}
|
||||
.wire-tag--primary {
|
||||
background: var(--wire-color-primary);
|
||||
color: var(--wire-color-primary-contrast);
|
||||
border-color: transparent;
|
||||
}
|
||||
.wire-tag--success {
|
||||
background: var(--wire-color-success);
|
||||
color: #05210f;
|
||||
border-color: transparent;
|
||||
}
|
||||
.wire-tag--danger {
|
||||
background: var(--wire-color-danger);
|
||||
color: #fff;
|
||||
border-color: transparent;
|
||||
}
|
||||
.wire-tag--warning {
|
||||
background: var(--wire-color-warning);
|
||||
color: #201400;
|
||||
border-color: transparent;
|
||||
}
|
||||
|
||||
/* --- Skeleton ------------------------------------------------------------- */
|
||||
.wire-skeleton {
|
||||
display: inline-block;
|
||||
border-radius: var(--wire-radius-sm);
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
var(--wire-color-surface-2) 25%,
|
||||
var(--wire-color-border) 37%,
|
||||
var(--wire-color-surface-2) 63%
|
||||
);
|
||||
background-size: 400% 100%;
|
||||
animation: wire-shimmer 1.4s ease infinite;
|
||||
}
|
||||
@keyframes wire-shimmer {
|
||||
0% {
|
||||
background-position: 100% 50%;
|
||||
}
|
||||
100% {
|
||||
background-position: 0 50%;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- Tooltip -------------------------------------------------------------- */
|
||||
.wire-tooltip {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
cursor: help;
|
||||
}
|
||||
.wire-tooltip::after {
|
||||
content: attr(data-tooltip);
|
||||
position: absolute;
|
||||
bottom: calc(100% + 6px);
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
white-space: nowrap;
|
||||
background: var(--wire-color-text);
|
||||
color: var(--wire-color-bg);
|
||||
font-size: 0.75rem;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: var(--wire-radius-sm);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.12s ease;
|
||||
z-index: 10;
|
||||
}
|
||||
.wire-tooltip:hover::after,
|
||||
.wire-tooltip:focus-visible::after {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* --- Table ---------------------------------------------------------------- */
|
||||
.wire-table-wrap {
|
||||
overflow-x: auto;
|
||||
}
|
||||
.wire-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
.wire-table th,
|
||||
.wire-table td {
|
||||
text-align: left;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border-bottom: 1px solid var(--wire-color-border);
|
||||
}
|
||||
.wire-table th {
|
||||
font-weight: 700;
|
||||
color: var(--wire-color-muted);
|
||||
font-size: 0.8rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
.wire-table tbody tr:hover {
|
||||
background: var(--wire-color-surface-2);
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
# @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).
|
||||
@@ -1,29 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/uploader",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/uploader — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@wrnexus/core": "^0.2.46"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
# @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`.
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"name": "@wrnexus/validation",
|
||||
"version": "0.2.46",
|
||||
"type": "module",
|
||||
"description": "@wrnexus/validation — part of the WrNexus framework.",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"engines": {
|
||||
"bun": ">=1.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
Vendored
+3
-58
@@ -1,62 +1,7 @@
|
||||
{
|
||||
// Treat .wrn files as the WrNexus language (redundant with the extension, but
|
||||
// makes highlighting work the moment the repo is opened).
|
||||
"editor.formatOnSave": true,
|
||||
"files.associations": {
|
||||
"*.wrn": "wire"
|
||||
"*.wrn": "wrnexus"
|
||||
},
|
||||
|
||||
// Distinct colors for WrNexus's own attributes, so they're easy to spot inside
|
||||
// plain HTML. These mirror the extension's shipped defaults; keeping them here
|
||||
// guarantees the colors apply in this workspace and gives you one place to tweak.
|
||||
"editor.tokenColorCustomizations": {
|
||||
"textMateRules": [
|
||||
{
|
||||
"scope": "entity.other.attribute-name.wrn.directive",
|
||||
"settings": { "foreground": "#5eead4", "fontStyle": "bold" }
|
||||
},
|
||||
{
|
||||
"scope": "entity.other.attribute-name.wrn.event",
|
||||
"settings": { "foreground": "#f472b6", "fontStyle": "bold" }
|
||||
},
|
||||
{
|
||||
"scope": "punctuation.definition.keyword.wrn",
|
||||
"settings": { "foreground": "#f472b6" }
|
||||
},
|
||||
{
|
||||
"scope": "keyword.control.i18n.wrn",
|
||||
"settings": { "foreground": "#f472b6", "fontStyle": "bold" }
|
||||
},
|
||||
{
|
||||
"scope": "string.other.i18n-key.wrn",
|
||||
"settings": { "foreground": "#5eead4" }
|
||||
},
|
||||
{
|
||||
"scope": "constant.language.http-method.wrn",
|
||||
"settings": { "foreground": "#f472b6", "fontStyle": "bold" }
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
// The bundled .wrn compiler is a generated artifact — hide it from search.
|
||||
"search.exclude": {
|
||||
"editors/vscode/src/compiler.cjs": true
|
||||
},
|
||||
|
||||
"wrnexus.diagnostics.enable": true,
|
||||
|
||||
"editor.semanticHighlighting.enabled": true,
|
||||
"editor.semanticTokenColorCustomizations": {
|
||||
"rules": {
|
||||
"variable:wrn": {
|
||||
"foreground": "#8B5CF6"
|
||||
},
|
||||
"variable.declaration:wrn": {
|
||||
"foreground": "#A78BFA",
|
||||
"fontStyle": "bold"
|
||||
},
|
||||
"variable.modification:wrn": {
|
||||
"foreground": "#F59E0B"
|
||||
}
|
||||
}
|
||||
}
|
||||
"typescript.tsdk": "node_modules/typescript/lib"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
# Changelog
|
||||
|
||||
## 0.8.8
|
||||
|
||||
- Added the framework request context to `.wrn` language-server type environments.
|
||||
- Kept workspace type declarations inside runnable apps during updates.
|
||||
- Regenerated lint-safe application declarations before update verification.
|
||||
|
||||
All notable framework changes are recorded here. Every release must also include an idempotent
|
||||
entry in the CLI migration registry.
|
||||
|
||||
## 0.8.3 - 2026-08-03
|
||||
|
||||
- Bundled hydrated browser modules so package aliases and filesystem imports do not leak into
|
||||
browser-native modules.
|
||||
- Fixed SSR computed values, Async branch aliases, typed object props in loops, reactive route
|
||||
state, loader invalidation, realtime identity isolation, and client-function hydration.
|
||||
- Fixed template-literal parsing in the reactive fallback evaluator and removed the unsupported
|
||||
default `unload` Permissions Policy directive.
|
||||
- Made official package components compatible with strict explicit imports and added regression
|
||||
coverage for the TeamSpace application failures.
|
||||
- Fixed Bun 1.3.14 and TypeScript 5.9 release-gate compatibility in client bundling, alias
|
||||
resolution, and Happy DOM event tests.
|
||||
- Fixed ESLint compatibility in Node release scripts by declaring Node globals and using explicit
|
||||
regex space quantifiers.
|
||||
- Fixed package component import validation after workspace installation by excluding generated and
|
||||
dependency directories such as nested `node_modules` from first-party source scans.
|
||||
- Made the VS Code embedded compiler freshness check deterministic across TypeScript patch
|
||||
versions, Windows/Linux line endings, and workspace environments by verifying normalized source
|
||||
and generator fingerprints while retaining exact-output checks for the same TypeScript version.
|
||||
- Fixed the VS Code language-server bundle so it executes under Node instead of exiting after
|
||||
defining an uninvoked Bun CommonJS wrapper, and added request-level crash containment.
|
||||
- Scoped HTML diagnostics to `view` blocks, ignored TypeScript generic syntax and WRN expressions,
|
||||
and preserved JavaScript-looking documentation inside `<pre><code>` examples.
|
||||
- Fixed formatter corruption of preformatted examples, balanced compact sibling markup, long bare
|
||||
tags, and repeated format-on-save indentation drift.
|
||||
- Fixed component prop intelligence for dynamic boolean/union expressions, boolean string literals,
|
||||
literal-union runtime types, and reserved prop names such as `class`.
|
||||
- Prevented bundled editor type checking from publishing TypeScript standard-library path failures or
|
||||
unmapped synthetic virtual-document diagnostics.
|
||||
- Fixed language-server virtual TypeScript inference for untyped dynamic handler parameters and
|
||||
indexed output dispatch, while retaining strict diagnostics for explicitly typed parameters.
|
||||
- Made bundled editor type checking resolve TypeScript standard libraries from the active workspace,
|
||||
and added a regression test that proves semantic diagnostics are actually running.
|
||||
- Fixed final release-gate lint failures by removing the obsolete editor `stripComments` helper and
|
||||
importing Node `Buffer` explicitly in the language-server bundle generator.
|
||||
- Reviewed the UI visual-contract change caused only by corrected `AuthForm.wrn` indentation and
|
||||
regenerated the 0.8 baseline after confirming no rendered component behavior changed.
|
||||
|
||||
## 0.8.0 - 2026-08-02
|
||||
|
||||
- Added package-owned helper and component kits across all 39 framework packages.
|
||||
- Added standalone realtime and package-aware auth, i18n, image, uploader, validation, JWT,
|
||||
encryption, database, and CAPTCHA improvements.
|
||||
- Added whole-application WRN syntax, import, and formatting modernization to the CLI update.
|
||||
- Added Windows/Linux CI, read-only package audits, governance documents, and security gates.
|
||||
@@ -0,0 +1,8 @@
|
||||
# Code of conduct
|
||||
|
||||
Be respectful, constructive, and specific. Harassment, discrimination, threats, personal attacks,
|
||||
and publication of private information are not acceptable. Discuss technical decisions with
|
||||
evidence, assume good intent, and give contributors room to correct mistakes.
|
||||
|
||||
Report conduct concerns privately to the maintainers. Maintainers may remove content, limit
|
||||
participation, or ban contributors when necessary to protect the community.
|
||||
@@ -0,0 +1,17 @@
|
||||
# Contributing
|
||||
|
||||
Install Bun 1.3.14 or newer and Node.js 24, then run:
|
||||
|
||||
```sh
|
||||
bun install --frozen-lockfile
|
||||
npm ci --prefix editors/vscode
|
||||
bun run typecheck
|
||||
bun run lint
|
||||
bun run format:check
|
||||
bun run test:all
|
||||
bun run validate:0.8
|
||||
```
|
||||
|
||||
Keep migrations conservative, backed up, idempotent, and covered by fixtures. Generated files
|
||||
must be produced by their documented `generate:*` command and committed with their source change.
|
||||
Security issues follow `SECURITY.md` and must not be disclosed publicly before a coordinated fix.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 WorkRoot
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
# Security policy
|
||||
|
||||
Security fixes are provided for the latest published WRNexusJS minor release. Keep every
|
||||
`@wrnexus/*` package on the same version and run `wrnexus update` before reporting an issue.
|
||||
|
||||
Do not open a public issue for a suspected vulnerability. Use the repository's private security
|
||||
reporting channel and include the affected package/version, reproduction, impact, and suggested
|
||||
mitigation. Never include production credentials or personal data.
|
||||
|
||||
Deployments must use HTTPS, keep secrets outside source control, configure trusted proxies and
|
||||
origins explicitly, and review the package security notes for auth, CAPTCHA, encryption, uploads,
|
||||
OAuth, JWT, and database adapters.
|
||||
@@ -0,0 +1,64 @@
|
||||
diff --git a/package.json b/package.json
|
||||
index f7c6a5f..6ac4583 100644
|
||||
--- a/package.json
|
||||
+++ b/package.json
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "wrnexus",
|
||||
- "version": "0.8.3",
|
||||
+ "version": "0.8.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "An SSR-first full-stack web framework with server-rendered reactive components. Bun-first, Node-friendly.",
|
||||
diff --git a/packages/language-server/src/server.ts b/packages/language-server/src/server.ts
|
||||
index c27baa7..974d966 100644
|
||||
--- a/packages/language-server/src/server.ts
|
||||
+++ b/packages/language-server/src/server.ts
|
||||
@@ -102,7 +102,7 @@ async function handle(message: JsonRpc): Promise<void> {
|
||||
case "initialize":
|
||||
workspaceRoot = params.rootPath ?? rootFromUri(params.rootUri);
|
||||
result(message.id, {
|
||||
- serverInfo: { name: "WRNexus Language Server", version: "0.8.3" },
|
||||
+ serverInfo: { name: "WRNexus Language Server", version: "0.8.4" },
|
||||
capabilities: {
|
||||
textDocumentSync: 1,
|
||||
documentFormattingProvider: true,
|
||||
diff --git a/update-package-versions.mjs b/update-package-versions.mjs
|
||||
index 318b962..8b70170 100644
|
||||
--- a/update-package-versions.mjs
|
||||
+++ b/update-package-versions.mjs
|
||||
@@ -1,7 +1,17 @@
|
||||
import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
+import process from "node:process";
|
||||
|
||||
-const version = "0.8.3";
|
||||
+const version = process.argv[2] ?? "0.8.4";
|
||||
+
|
||||
+if (!/^0\.8\.\d+$/.test(version)) {
|
||||
+ throw new Error(`Expected a 0.8.x version, received ${JSON.stringify(version)}`);
|
||||
+}
|
||||
+
|
||||
+const rootPackageFile = "package.json";
|
||||
+const rootPackage = JSON.parse(readFileSync(rootPackageFile, "utf8"));
|
||||
+rootPackage.version = version;
|
||||
+writeFileSync(rootPackageFile, `${JSON.stringify(rootPackage, null, 2)}\n`);
|
||||
|
||||
const dependencyGroups = [
|
||||
"dependencies",
|
||||
@@ -62,6 +72,15 @@ for (const entry of readdirSync("packages", {
|
||||
writeFileSync(packageFile, `${JSON.stringify(packageJson, null, 2)}\n`);
|
||||
}
|
||||
|
||||
+const languageServerFile = join("packages", "language-server", "src", "server.ts");
|
||||
+if (existsSync(languageServerFile)) {
|
||||
+ const source = readFileSync(languageServerFile, "utf8").replace(
|
||||
+ /serverInfo: \{ name: "WRNexus Language Server", version: "[^"]+" \}/,
|
||||
+ `serverInfo: { name: "WRNexus Language Server", version: "${version}" }`,
|
||||
+ );
|
||||
+ writeFileSync(languageServerFile, source);
|
||||
+}
|
||||
+
|
||||
const editorPackageFile = join("editors", "vscode", "package.json");
|
||||
if (existsSync(editorPackageFile)) {
|
||||
const editorPackage = JSON.parse(readFileSync(editorPackageFile, "utf8"));
|
||||
+9
-9
@@ -5,13 +5,13 @@ services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
environment:
|
||||
POSTGRES_USER: wire
|
||||
POSTGRES_PASSWORD: wire
|
||||
POSTGRES_DB: wire_test
|
||||
POSTGRES_USER: wrn
|
||||
POSTGRES_PASSWORD: wrn
|
||||
POSTGRES_DB: wrn_test
|
||||
ports:
|
||||
- "5433:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U wire -d wire_test"]
|
||||
test: ["CMD-SHELL", "pg_isready -U wrn -d wrn_test"]
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
retries: 40
|
||||
@@ -19,14 +19,14 @@ services:
|
||||
mysql:
|
||||
image: mysql:8
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: wire
|
||||
MYSQL_DATABASE: wire_test
|
||||
MYSQL_USER: wire
|
||||
MYSQL_PASSWORD: wire
|
||||
MYSQL_ROOT_PASSWORD: wrn
|
||||
MYSQL_DATABASE: wrn_test
|
||||
MYSQL_USER: wrn
|
||||
MYSQL_PASSWORD: wrn
|
||||
ports:
|
||||
- "3307:3306"
|
||||
healthcheck:
|
||||
test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-uwire", "-pwire"]
|
||||
test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-uwrn", "-pwrn"]
|
||||
interval: 3s
|
||||
timeout: 3s
|
||||
retries: 40
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# WRNexusJS 0.3 — 40-Point Implementation Matrix
|
||||
|
||||
Legend:
|
||||
|
||||
- **Existing + hardened**: capability already existed and was preserved or extended
|
||||
- **Implemented**: new usable public API/runtime behavior in 0.3
|
||||
- **Foundation / experimental**: contract and integration seam exist; advanced provider-specific
|
||||
implementations should remain opt-in until they receive production soak testing
|
||||
|
||||
| # | Improvement | 0.3 implementation | Level |
|
||||
| --: | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ------------------------- |
|
||||
| 1 | Formal language specification | Canonical spec constants, stable diagnostics, and `docs/WRN-LANGUAGE-SPEC-1.0.md` | Implemented |
|
||||
| 2 | Shared parser and AST | New `@wrnexus/syntax`; compiler compatibility re-exports | Implemented |
|
||||
| 3 | Compile-time/runtime separation | Runtime metadata, server-only suppression, compile-time diagnostics and transforms | Existing + hardened |
|
||||
| 4 | Fine-grained reactivity | Batched signals, dependency-tracked computed/effects, coalesced renderers | Implemented |
|
||||
| 5 | Deterministic SSR/hydration | Stable hydration IDs, runtime/strategy metadata, mismatch diagnostics, keyed `data-for` reconciliation and keyed `{#each}` syntax | Implemented |
|
||||
| 6 | Partial hydration/islands | load/idle/visible/interaction/media/none strategies | Implemented |
|
||||
| 7 | Server-only execution | `runtime = "server"`, `load server`, browser-interactivity rejection | Implemented |
|
||||
| 8 | Data-loading model | `defineLoader`, `defineAction`, request-local dedupe, WRN loaders/actions | Foundation / experimental |
|
||||
| 9 | Streaming SSR | Promise and `AsyncIterable` document streams and response helper | Implemented |
|
||||
| 10 | Routing | groups, optional and catch-all params, conflict checks, typed builders | Implemented |
|
||||
| 11 | Middleware | Existing ordered middleware plus tracing and tenancy middleware | Existing + hardened |
|
||||
| 12 | Typed API/RPC | validated endpoint definitions, typed RPC client, structured errors | Implemented |
|
||||
| 13 | Security defaults | Existing CSP/CSRF/cookies/CORS/body guards plus WRN security metadata | Existing + hardened |
|
||||
| 14 | DevToolbar | Runtime diagnostic bridge and existing accessibility/performance/SEO/security rules | Existing + hardened |
|
||||
| 15 | Optimization reports | `dist/build-report.json`, CLI analyzer, route/assets/budget measurements | Implemented |
|
||||
| 16 | Error messages | Stable WRN codes, positions, code frames, hints | Implemented |
|
||||
| 17 | Language server/editor | VS Code diagnostics/completion/grammar/snippets aligned to 0.3 syntax | Existing + hardened |
|
||||
| 18 | Schemas/validation | Existing shared form/API validation retained; endpoint schema contract added | Existing + hardened |
|
||||
| 19 | Authentication primitives | Existing auth/session/OAuth/passkey-related packages retained; security metadata seam | Existing + hardened |
|
||||
| 20 | Multi-tenancy | tenant context, resolver/middleware, subdomain/domain/path runtime config | Implemented |
|
||||
| 21 | Jobs/cron/workflows | priority, concurrency, idempotency, cancellation, job/workflow/cron helpers | Implemented |
|
||||
| 22 | Realtime | Existing rooms/pub-sub/Redis bridge retained with shared runtime | Existing + hardened |
|
||||
| 23 | Plugin system | deterministic lifecycle, AST/code transforms, diagnostics, server/build hooks | Implemented |
|
||||
| 24 | Infrastructure adapters | portable fetch handler and existing Bun/Node seams; adapter config/reporting | Foundation / experimental |
|
||||
| 25 | Build caching/monorepo | Existing compile cache and targeted HMR retained; build cache config seam | Existing + hardened |
|
||||
| 26 | Compatibility/migrations | reversible 0.3 migration, source backup/report, `doctor`, unique versions | Implemented |
|
||||
| 27 | Testing | new syntax/core/compiler/router/queue/SSR/update/editor regressions | Implemented |
|
||||
| 28 | Performance budgets | configurable route JS/CSS, HTML, image, hydration, and SSR budgets | Implemented |
|
||||
| 29 | Observability | tracer/span APIs, request middleware, Server-Timing, console exporter | Implemented |
|
||||
| 30 | Component architecture | Existing `@wrnexus/ui` inventory retained; syntax metadata supports typed tooling | Existing + hardened |
|
||||
| 31 | Design tokens | Existing `--wrn-*` system and theme resolution retained | Existing + hardened |
|
||||
| 32 | Accessibility | compile-time missing-alt diagnostic plus existing DevToolbar scanning | Implemented |
|
||||
| 33 | Motion/transitions | Existing CSR/lifecycle foundation retained; strategy can be plugin/runtime extended | Foundation / experimental |
|
||||
| 34 | Documentation | language, architecture, upgrade, implementation, test checklist docs | Implemented |
|
||||
| 35 | AI-friendly framework | machine-readable spec/AST/diagnostics/build report and existing AI package | Implemented |
|
||||
| 36 | Feature flags/experimental APIs | async context-aware feature flags and typed config gates | Implemented |
|
||||
| 37 | Public API boundaries | syntax/compiler separation and explicit package exports | Implemented |
|
||||
| 38 | Configuration | typed validation, source explanation, profile/env visibility | Implemented |
|
||||
| 39 | Gateway | existing host routing/auth/WebSocket/security gateway preserved; internal contracts unchanged | Existing + hardened |
|
||||
| 40 | Focused roadmap/release gates | 0.3 stability levels, verification script, audit and test matrix | Implemented |
|
||||
|
||||
## Important release distinction
|
||||
|
||||
This matrix records code present in the 0.3 source tree. “Foundation / experimental”
|
||||
does not mean absent; it means the API or adapter seam is implemented but should not
|
||||
be advertised as provider-complete until the relevant deployment, animation, cache,
|
||||
or server-component adapters receive real production tests.
|
||||
|
||||
## Backward-compatibility gates
|
||||
|
||||
1. Existing compiler imports continue through re-exports.
|
||||
2. Existing `.wrn` members and directives remain accepted.
|
||||
3. New runtime behavior is disabled unless syntax/config opts in.
|
||||
4. Source migration is conservative, backed up, idempotent, and reported.
|
||||
5. Existing route syntax retains matching precedence.
|
||||
6. Existing dev and production request runtimes remain shared.
|
||||
7. Every bug fix receives a regression test or static verification assertion.
|
||||
@@ -0,0 +1,136 @@
|
||||
# WRNexusJS 0.3 Architecture
|
||||
|
||||
## Design goals
|
||||
|
||||
WRNexusJS 0.3 is an additive architecture release focused on one invariant:
|
||||
|
||||
> A valid `.wrn` file must be parsed, diagnosed, compiled, rendered, hydrated,
|
||||
> formatted, migrated, and edited from one shared language model.
|
||||
|
||||
The release keeps existing application contracts while adding extension seams for
|
||||
full-stack data, plugins, partial hydration, observability, tenancy, advanced
|
||||
routing, build analysis, jobs, and deployment adapters.
|
||||
|
||||
## Package boundaries
|
||||
|
||||
### Language and compilation
|
||||
|
||||
- `@wrnexus/syntax`: canonical tokens, AST, source positions, diagnostics, and spec
|
||||
- `@wrnexus/compiler`: SSR/client code generation and deprecated parser re-exports
|
||||
- `@wrnexus/csr`: browser navigation and fine-grained reactive hydration
|
||||
- `@wrnexus/reactive`: framework-independent signals, computed values, effects, and batching
|
||||
|
||||
### Request and application runtime
|
||||
|
||||
- `@wrnexus/core`: context, middleware, security, typed endpoints, loaders/actions,
|
||||
tenant APIs, tracing, feature flags, and performance budgets
|
||||
- `@wrnexus/router`: route discovery, matching, groups, optional/catch-all params,
|
||||
conflicts, and typed URL generation
|
||||
- `@wrnexus/ssr`: document rendering plus string, promise, and async-iterable streaming
|
||||
- `@wrnexus/dev-server`: shared dev/production request runtime and portable fetch handlers
|
||||
|
||||
### Extension and operations
|
||||
|
||||
- `@wrnexus/plugin`: deterministic plugin ordering and lifecycle hooks
|
||||
- `@wrnexus/dev-toolbar`: source-linked page diagnostics
|
||||
- `@wrnexus/cli`: build, doctor, config explanation, analyzer, migrations, and generators
|
||||
- `@wrnexus/queue`: jobs, priority, concurrency, idempotency, cancellation, cron helpers,
|
||||
and workflows
|
||||
- `@wrnexus/pubsub`: realtime scaling adapters
|
||||
|
||||
## Compatibility layers
|
||||
|
||||
The compiler's former parser, tokenizer, and AST modules re-export the canonical
|
||||
syntax package. No existing public compiler import must be changed immediately.
|
||||
|
||||
The client runtime continues to support legacy hydration scopes, `data-for`, and
|
||||
`{#each}` output. New hydration metadata is additive:
|
||||
|
||||
```html
|
||||
<div data-wrn-hydration="stable-id" data-wrn-hydrate="visible" data-wrn-runtime="universal"></div>
|
||||
```
|
||||
|
||||
The updater creates a full application-source backup before source normalization.
|
||||
Its migration report lists every changed file.
|
||||
|
||||
## Request flow
|
||||
|
||||
```text
|
||||
Request
|
||||
-> security/CORS/body-size boundary
|
||||
-> optional tracing middleware
|
||||
-> optional tenant middleware
|
||||
-> application middleware
|
||||
-> route matcher
|
||||
-> loader/API/page/realtime dispatch
|
||||
-> SSR document assembly
|
||||
-> response cookies/security/compression
|
||||
```
|
||||
|
||||
Development and production use the same `createHandlers` runtime. Production also
|
||||
exposes `createProductionHandlers`, a portable web-standard fetch seam used by Bun,
|
||||
Node, and future edge/serverless adapters.
|
||||
|
||||
## Reactive update flow
|
||||
|
||||
```text
|
||||
signal write
|
||||
-> dependency invalidation
|
||||
-> microtask batch
|
||||
-> computed values refresh on demand
|
||||
-> only subscribed renderers/effects run
|
||||
-> DOM bindings update
|
||||
```
|
||||
|
||||
Renderer scheduling is coalesced so repeated writes in one task do not cause a full
|
||||
component rerender for each write.
|
||||
|
||||
## Plugin lifecycle
|
||||
|
||||
Plugins are ordered deterministically with `enforce`, `before`, and `after`:
|
||||
|
||||
```text
|
||||
configure
|
||||
configResolved
|
||||
buildStart / configureServer
|
||||
transformAst
|
||||
plugin diagnostics
|
||||
transformCode
|
||||
buildEnd
|
||||
```
|
||||
|
||||
Duplicate names and ordering cycles fail with stable plugin errors. Plugin hooks
|
||||
are optional and the absence of plugins has zero behavioral effect.
|
||||
|
||||
## Build outputs
|
||||
|
||||
A production build can emit:
|
||||
|
||||
- compiled route/component modules
|
||||
- source maps when enabled
|
||||
- route and asset measurements
|
||||
- `dist/build-report.json`
|
||||
- performance-budget violations
|
||||
- generated production entry with security, observability, tenancy, storage,
|
||||
databases, realtime, mobile, PWA, and SEO configuration
|
||||
|
||||
Use:
|
||||
|
||||
```bash
|
||||
wrnexus config . --explain
|
||||
wrnexus build .
|
||||
wrnexus analyze .
|
||||
wrnexus doctor .
|
||||
```
|
||||
|
||||
## Stability levels
|
||||
|
||||
- **Stable**: existing behavior, canonical syntax ownership, diagnostics, router
|
||||
compatibility, typed core primitives, build reports, migration safety
|
||||
- **Additive stable API**: plugin contracts, tracing, tenancy, loaders/actions,
|
||||
endpoint definitions, job definitions
|
||||
- **Experimental runtime behavior**: server components, broader streaming boundaries,
|
||||
custom adapter implementations, and plugin transforms can be gated in config
|
||||
|
||||
Experimental flags make feature adoption explicit without forcing existing apps to
|
||||
change their runtime behavior.
|
||||
@@ -0,0 +1,68 @@
|
||||
# WRNexusJS 0.4 architecture
|
||||
|
||||
## Goals
|
||||
|
||||
WRNexusJS 0.4 keeps the existing SSR-first model while making advanced systems installable without application-owned copies or manual wiring. The framework remains conservative: HTML is rendered on the server, the reactive runtime loads only for reactive pages, and package browser code loads only when its component or markup declares a runtime requirement.
|
||||
|
||||
## Request and render path
|
||||
|
||||
1. The CLI or development server loads `wrnexus.config.*`.
|
||||
2. `@wrnexus/plugin` discovers explicit plugins and installed package manifests.
|
||||
3. Contributions are normalized and validated for duplicate IDs, paths, routes, and migrations.
|
||||
4. The router combines application and package components/routes/middleware.
|
||||
5. `.wrn` sources compile through plugin AST/code transforms.
|
||||
6. SSR renders page and component HTML.
|
||||
7. Rendered `data-wrnexus-runtime` markers are matched against registered client runtimes.
|
||||
8. Only referenced runtime scripts are added to the response.
|
||||
9. CSR navigation loads newly required runtime chunks, calls `mount`, and calls `unmount` before replacing old page content.
|
||||
|
||||
## Package contribution model
|
||||
|
||||
A package can contribute:
|
||||
|
||||
- component directories
|
||||
- client runtimes
|
||||
- static or generated assets
|
||||
- stylesheet entries and Tailwind scan sources
|
||||
- page, API, and realtime routes
|
||||
- middleware
|
||||
- database migrations
|
||||
- DevToolbar panels
|
||||
- compiler diagnostics and transforms
|
||||
- build and server lifecycle hooks
|
||||
|
||||
Contributions are declared by a package plugin or by the `wrnexus` field in `package.json`.
|
||||
|
||||
## Client runtime rules
|
||||
|
||||
A runtime has a stable ID, source entry, loading policy, module/classic format, and singleton policy. Development serves it from `/__wrnexus/assets/`; TypeScript runtime entries are browser-bundled on demand. Production builds emit content-hashed immutable runtime chunks and store their paths in the static server manifest.
|
||||
|
||||
Runtime code should register:
|
||||
|
||||
```js
|
||||
window.__wrnexusRuntimes = window.__wrnexusRuntimes || {};
|
||||
window.__wrnexusRuntimes.example = {
|
||||
mount(root) {},
|
||||
unmount(root) {},
|
||||
};
|
||||
```
|
||||
|
||||
Mount and unmount must be idempotent. Event listeners, observers, audio, timers, and provider widgets must be cleaned up during unmount.
|
||||
|
||||
## Package assets and styles
|
||||
|
||||
Package assets use validated framework paths and receive correct MIME and `nosniff` headers. Production stores package assets in content-addressed files while preserving their declared public URLs; immutable caching remains opt-in. Package component directories and style sources are automatically added to application stylesheet processing, so apps do not need manual Tailwind `@source` entries for installed systems.
|
||||
|
||||
Production stylesheet processing fails closed by default. A Tailwind/PostCSS failure cannot silently ship unprocessed CSS unless the application explicitly selects fallback behavior.
|
||||
|
||||
## Package migrations
|
||||
|
||||
Packages can register inline SQL, a SQL file, or an ordered directory. Migration names are namespaced by package migration ID and may target the default or a named database. Development applies application and package migrations through the same migration table. Production copies both into the build output.
|
||||
|
||||
## Development experience
|
||||
|
||||
The development server watches application and workspace package component/runtime/style sources. Package `.wrn` changes invalidate both compiled modules and the stylesheet cache. `wrnexus inspect` exposes packages, plugins, routes, assets, runtimes, styles, migrations, and build reports. DevToolbar receives a platform snapshot and package panels.
|
||||
|
||||
## Compatibility
|
||||
|
||||
The 0.4 migration removes legacy CAPTCHA script tags, archives manually copied runtime files instead of deleting them, and leaves user-authored application code intact. Existing explicit plugins continue to work and take precedence over automatically discovered plugins with the same name.
|
||||
@@ -0,0 +1,45 @@
|
||||
# WRNexusJS 0.3 — Source Audit and Validation Record
|
||||
|
||||
## Audit scope
|
||||
|
||||
The uploaded monorepo was inspected package-by-package before changes. The baseline already contained compiler, SSR/CSR, reactive runtime, routing, gateway/dev-server integration, authentication and authorization packages, validation, database, queue, pub/sub/realtime, upload/storage helpers, UI, DevToolbar, AI tooling, mobile/native support, CLI migrations, and a VS Code extension.
|
||||
|
||||
The 0.3 work therefore extends existing contracts instead of replacing them. The baseline archive was committed locally before edits so every source change remained reviewable and reversible.
|
||||
|
||||
## Compatibility decisions
|
||||
|
||||
- Existing `@wrnexus/compiler` parser/type imports remain available through re-exports from `@wrnexus/syntax`.
|
||||
- Existing `.wrn` roots, directives, route forms, component mounts, SSR output, and gateway configuration remain accepted.
|
||||
- New hydration, plugin, tenancy, observability, feature-flag, performance-budget, and build-analysis behavior is opt-in.
|
||||
- The updater backs up the complete `app/` directory and important project configuration before writing.
|
||||
- Source normalization only rewrites simple unquoted dynamic attributes and safely parseable one-line props blocks. Nested-brace expressions are left unchanged for manual review.
|
||||
- The updater writes a machine-readable changed-file report and is source-idempotent.
|
||||
|
||||
## Validation completed in this sandbox
|
||||
|
||||
- TypeScript static validation across all package source files: passed.
|
||||
- TypeScript emit of all package sources for runtime smoke testing: passed.
|
||||
- Compiled smoke tests for syntax/compiler, batched reactivity, computed/effects, typed endpoints, tracing, optional/catch-all routing, plugin ordering/transforms, queue priority/idempotency/workflows/cron, and streaming SSR: passed.
|
||||
- Generated browser reactive runtime JavaScript syntax check: passed.
|
||||
- All 913 checked-in `.wrn` files compile with the 0.3 compiler: passed.
|
||||
- All 913 checked-in `.wrn` files remain valid and formatter-idempotent after formatting: passed.
|
||||
- VS Code Node regression tests: 15 passed, 0 failed.
|
||||
- VS Code asset/compiler validation: passed; `src/compiler.cjs` was rebuilt from the 0.3 compiler and shared syntax source.
|
||||
- 0.3 structural release verification: 30 named packages and 66 migration entries passed.
|
||||
- Git whitespace/error check: passed.
|
||||
- Synthetic 0.2.70 to 0.3.0 migration: backup, dependency bump, scripts, new packages, conservative source normalization, report, nested-expression preservation, and second-run source idempotency all passed.
|
||||
|
||||
## Environment limitations
|
||||
|
||||
The sandbox did not contain Bun and could not reach the package registry. Therefore these release gates must still be run in the normal WRNexusJS development environment:
|
||||
|
||||
```bash
|
||||
bun install
|
||||
bun run check
|
||||
bun run build
|
||||
cd editors/vscode && bun run check && bun run package
|
||||
```
|
||||
|
||||
Because VSCE dependencies were unavailable, a new 0.3.0 VSIX binary was not packaged here. The compiler bundle, source, grammar, snippets, metadata, Node tests, and extension validation were updated; run `bun run package` before Marketplace publishing.
|
||||
|
||||
The broad provider-specific parts of infrastructure adapters, advanced cache backends, and motion adapters remain deliberately marked as foundation/experimental in the implementation matrix until they receive real deployment and browser soak tests. They are not advertised as provider-complete.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user