webspresso 0.0.98 → 0.0.100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/.agents/ADMIN.md +11 -1
  2. package/.agents/AGENTS.md +2 -2
  3. package/.agents/AUTH.md +415 -0
  4. package/.agents/CLI.md +47 -0
  5. package/.agents/ERRORS.md +59 -0
  6. package/.agents/ORM.md +178 -4
  7. package/.agents/PLUGINS.md +113 -8
  8. package/.agents/QUEUE.md +92 -0
  9. package/.agents/ROUTING.md +160 -7
  10. package/.agents/STREAMING.md +35 -0
  11. package/AGENTS.md +2 -0
  12. package/README.md +145 -93
  13. package/bin/commands/add-docker.js +467 -0
  14. package/bin/commands/deploy-check.js +339 -0
  15. package/bin/webspresso.js +4 -0
  16. package/core/auth/index.js +123 -1
  17. package/core/auth/magic-link.js +170 -0
  18. package/core/auth/manager.js +477 -3
  19. package/core/auth/middleware.js +118 -5
  20. package/core/auth/oauth.js +517 -0
  21. package/core/auth/qrcode.js +499 -0
  22. package/core/auth/session-manager.js +255 -0
  23. package/core/auth/sessions.js +351 -0
  24. package/core/auth/tokens.js +1 -0
  25. package/core/auth/totp.js +507 -0
  26. package/core/auth/user-agent.js +161 -0
  27. package/core/orm/eager-loader.js +144 -10
  28. package/core/orm/index.js +10 -1
  29. package/core/orm/model.js +55 -1
  30. package/core/orm/query-builder.js +90 -4
  31. package/core/orm/repository.js +327 -16
  32. package/core/orm/scopes.js +3 -2
  33. package/core/orm/search.js +213 -0
  34. package/core/orm/types.js +6 -1
  35. package/core/queue/cron.js +544 -0
  36. package/core/queue/index.js +8 -1
  37. package/core/queue/manager.js +100 -1
  38. package/core/queue/scheduler.js +415 -0
  39. package/core/sse/index.js +19 -0
  40. package/core/sse/stream.js +430 -0
  41. package/core/ssr/stream.js +62 -2
  42. package/index.d.ts +794 -6
  43. package/index.js +48 -0
  44. package/package.json +7 -5
  45. package/plugins/admin-panel/client/parts/05-rich-text-file-helpers.js +323 -31
  46. package/plugins/admin-panel/client/parts/08-record-list.js +5 -0
  47. package/plugins/admin-panel/client/verify-spa-parts.js +2 -0
  48. package/plugins/admin-panel/field-renderers/file-upload.js +187 -104
  49. package/plugins/admin-panel/field-renderers/index.js +2 -0
  50. package/plugins/admin-panel/modules/admin-users.js +1 -1
  51. package/plugins/api-key/crypto.js +101 -0
  52. package/plugins/api-key/index.js +288 -0
  53. package/plugins/api-key/middleware.js +461 -0
  54. package/plugins/api-key/migration-template.js +48 -0
  55. package/plugins/api-key/model.js +50 -0
  56. package/plugins/api-key/scopes.js +125 -0
  57. package/plugins/audit-log/admin-component.js +487 -70
  58. package/plugins/audit-log/api-handlers.js +114 -0
  59. package/plugins/audit-log/index.js +24 -0
  60. package/plugins/content/client/inline-edit.js +2 -46
  61. package/plugins/cors.js +13 -2
  62. package/plugins/email/auth-bridge.js +66 -0
  63. package/plugins/email/bundled-templates.js +15 -0
  64. package/plugins/email/templates/auth-magic-link.mjml +13 -0
  65. package/plugins/file-manager/admin-component.js +69 -53
  66. package/plugins/file-manager/index.js +25 -8
  67. package/plugins/index.js +8 -0
  68. package/plugins/oauth/index.js +338 -0
  69. package/plugins/queue/index.js +4 -0
  70. package/plugins/webhooks/admin-component.js +608 -0
  71. package/plugins/webhooks/api-handlers.js +237 -0
  72. package/plugins/webhooks/crypto.js +144 -0
  73. package/plugins/webhooks/dispatcher.js +708 -0
  74. package/plugins/webhooks/index.js +263 -0
  75. package/plugins/webhooks/matcher.js +113 -0
  76. package/plugins/webhooks/migration-template.js +75 -0
  77. package/plugins/webhooks/models.js +98 -0
  78. package/plugins/webhooks/sender.js +176 -0
  79. package/src/api/api-loader.js +1 -0
  80. package/src/bundle/index.js +2 -1
  81. package/src/discovery/file-route-parser.js +44 -1
  82. package/src/discovery/scan-routes.js +2 -2
  83. package/src/file-router.js +310 -104
  84. package/src/helpers.js +16 -1
  85. package/src/njk-frontmatter.js +3 -0
  86. package/src/routing/cascading.js +490 -0
  87. package/src/routing/middleware-resolver.js +92 -0
  88. package/src/server.js +6 -0
@@ -53,7 +53,10 @@ All routes are automatically discovered and registered from the `pages/` directo
53
53
  | `pages/index.njk` | `GET` | `/` | Home page (SSR Nunjucks) |
54
54
  | `pages/about.njk` | `GET` | `/about` | Static SSR page |
55
55
  | `pages/notes/[id].njk` | `GET` | `/notes/:id` | Dynamic SSR route with param |
56
+ | `pages/(marketing)/about.njk` | `GET` | `/about` | Route Group page (omits `(marketing)`) |
57
+ | `pages/(auth)/login.njk` | `GET` | `/login` | Route Group with isolated layout & middleware |
56
58
  | `pages/api/notes.get.js` | `GET` | `/api/notes` | List notes API endpoint |
59
+ | `pages/api/(v1)/notes.get.js` | `GET` | `/api/notes` | API route inside Route Group |
57
60
  | `pages/api/notes.post.js` | `POST` | `/api/notes` | Create note API endpoint |
58
61
  | `pages/api/notes/[id].get.js` | `GET` | `/api/notes/:id` | Get single note API endpoint |
59
62
  | `pages/api/notes/[id].put.js` | `PUT` | `/api/notes/:id` | Update note API endpoint |
@@ -148,7 +151,50 @@ module.exports = {
148
151
 
149
152
  ---
150
153
 
151
- ## 4. SSR Page Routes (`load()` Loader)
154
+ ## 4. Route Groups `(group)` Syntax & Layout Isolation
155
+
156
+ Webspresso supports Next.js / Nuxt-style **Route Groups**. Any directory name wrapped in parentheses `(groupName)` is treated as an organizational group:
157
+ - **Clean Public URLs**: The parenthesized directory name is completely omitted from the generated URL path.
158
+ - **Layout & Middleware Isolation**: The directory hierarchy is preserved for cascading middleware (`_middleware.js`) and nested layouts (`_layout.njk`), allowing distinct shells and security guards without polluting public route URLs.
159
+ - **Nesting & Dynamic Route Support**: Route groups can be nested (e.g. `(shop)/(checkout)/cart.njk` → `/cart`), combined with dynamic segments (e.g. `(app)/users/[id].njk` → `/users/:id`), and applied to API routes (`pages/api/(v1)/items.get.js` → `/api/items` or `pages/(marketing)/api/newsletter.post.js` → `/api/newsletter`).
160
+
161
+ ### 4.1 Route Group Structure Example
162
+
163
+ ```
164
+ pages/
165
+ ├── (marketing)/
166
+ │ ├── _layout.njk # Marketing layout (Hero header, footer)
167
+ │ ├── _middleware.js # Track analytics / marketing headers
168
+ │ ├── index.njk -> GET /
169
+ │ ├── about.njk -> GET /about
170
+ │ └── api/
171
+ │ └── newsletter.post.js -> POST /api/newsletter
172
+ ├── (auth)/
173
+ │ ├── _layout.njk # Centered card layout (no nav/footer)
174
+ │ ├── _middleware.js # Guest-only guard (redirects authenticated users)
175
+ │ ├── login.njk -> GET /login
176
+ │ └── register.njk -> GET /register
177
+ └── (app)/
178
+ ├── _layout.njk # App shell layout with sidebar
179
+ ├── _middleware.js # Strict session auth guard
180
+ └── dashboard.njk -> GET /dashboard
181
+ ```
182
+
183
+ ### 4.2 Programmatic Utilities
184
+ Webspresso exports core helpers to inspect and transform route group paths:
185
+ ```javascript
186
+ const { isRouteGroupSegment, stripRouteGroups } = require('webspresso');
187
+
188
+ isRouteGroupSegment('(marketing)'); // true
189
+ isRouteGroupSegment('about'); // false
190
+
191
+ stripRouteGroups('/(marketing)/about'); // '/about'
192
+ stripRouteGroups('/(shop)/(checkout)/cart'); // '/cart'
193
+ ```
194
+
195
+ ---
196
+
197
+ ## 5. SSR Page Routes (`load()` Loader)
152
198
 
153
199
  For server-rendered Nunjucks HTML pages, use `.njk` templates and companion `.js` loader files (or inline `async function load` in a `.js` file):
154
200
 
@@ -174,7 +220,7 @@ module.exports = {
174
220
 
175
221
  ---
176
222
 
177
- ## 5. Module & File-Based Discovery (`src/pages`, `src/api`, `modules/{name}`)
223
+ ## 6. Module & File-Based Discovery (`src/pages`, `src/api`, `modules/{name}`)
178
224
 
179
225
  Webspresso supports clean, domain-driven module discovery alongside root-level pages and APIs:
180
226
 
@@ -204,7 +250,7 @@ src/
204
250
  auth-guard.js -> module-local named middleware 'authGuard'
205
251
  ```
206
252
 
207
- ### 5.1 `definePage()` Contract
253
+ ### 6.1 `definePage()` Contract
208
254
  ```javascript
209
255
  const { definePage } = require('webspresso');
210
256
 
@@ -230,7 +276,7 @@ module.exports = definePage({
230
276
  });
231
277
  ```
232
278
 
233
- ### 5.2 `defineApi()` Contract
279
+ ### 6.2 `defineApi()` Contract
234
280
  ```javascript
235
281
  const { defineApi, z } = require('webspresso');
236
282
 
@@ -252,7 +298,7 @@ module.exports = defineApi({
252
298
  });
253
299
  ```
254
300
 
255
- ### 5.3 `defineModule()` Contract
301
+ ### 6.3 `defineModule()` Contract
256
302
  ```javascript
257
303
  const { defineModule } = require('webspresso');
258
304
 
@@ -270,7 +316,7 @@ module.exports = defineModule({
270
316
  });
271
317
  ```
272
318
 
273
- ### 5.4 Route Introspection (`app.routes.list()`)
319
+ ### 6.4 Route Introspection (`app.routes.list()`)
274
320
  Compiled routes are accessible at runtime for tooling, CLI inspection, and documentation:
275
321
  ```javascript
276
322
  const routeList = app.routes.list();
@@ -280,9 +326,116 @@ const routeList = app.routes.list();
280
326
  // ]
281
327
  ```
282
328
 
329
+ ### 6.5 Server-Sent Events (SSE) Streaming (`res.sse`)
330
+ For real-time event streaming and LLM token outputs, use the native `res.sse()` helper (or `{ sse }` from `ctx`):
331
+
332
+ ```javascript
333
+ // File: pages/api/ai/chat.post.js
334
+ const { defineApi } = require('webspresso');
335
+
336
+ module.exports = defineApi({
337
+ handler: async (req, res, { sse }) => {
338
+ // 1. Controller mode with automatic keepalive & reconnection directives
339
+ const stream = sse({ heartbeat: 15000, retry: 3000 });
340
+
341
+ await stream.send({ delta: 'Hello ' });
342
+ await stream.send({ event: 'delta', data: { text: 'world!' }, id: '1' });
343
+ stream.close();
344
+
345
+ // 2. OR stream an async generator / LLM stream directly:
346
+ // return res.sse(async function*() {
347
+ // for await (const chunk of llmStream) {
348
+ // yield { token: chunk.text };
349
+ // }
350
+ // });
351
+ },
352
+ });
353
+ ```
354
+
355
+ ### 6.6 Cascading Middleware (`_middleware.js`) & Nested Layouts (`_layout.njk`)
356
+
357
+ Webspresso supports folder-level cascading middleware inheritance and nested layouts across directory trees:
358
+
359
+ #### 1. Cascading Middleware (`_middleware.js`)
360
+ Any directory under `pages/` can declare a `_middleware.js` file:
361
+ - **Execution Order**: Middlewares execute in top-down ancestral order (from root down to route leaf) before route handlers and route-specific middleware.
362
+ - **Early Termination**: If any middleware sends headers (e.g. `res.status(401).json(...)` or `res.redirect('/login')`), execution halts immediately and downstream middlewares/handlers are skipped.
363
+ - **Export Formats**: Standard Express middleware function `(req, res, next)`, async function, named middleware string/array `['auth', 'cors']`, or middleware tuples with options `[['rateLimit', { max: 100 }]]`.
364
+
365
+ ```
366
+ pages/
367
+ ├── _middleware.js # Runs for ALL routes (adds global headers / request ID)
368
+ ├── api/
369
+ │ └── admin/
370
+ │ ├── _middleware.js # Protects all /api/admin/* endpoints
371
+ │ └── metrics.get.js # Inherits root + admin middleware
372
+ └── dashboard/
373
+ ├── _middleware.js # Auth guard for /dashboard/* pages
374
+ └── settings.njk
375
+ ```
376
+
377
+ #### 2. Nested Layouts (`_layout.njk` & `_layout.js`)
378
+ Pages under `pages/` automatically inherit ancestor layouts:
379
+ - **Wrapping Order**: Child template is rendered first, then wrapped by layouts from innermost to outermost using `{{ content | safe }}`.
380
+ - **Layout Loaders (`_layout.js`)**: Companion `_layout.js` files can export `async function load(req, ctx)` to supply shared data (e.g., site title, navigation, breadcrumbs) in top-down order before the page loader runs.
381
+ - **Opt-Out**: A page can opt out of automatic layout wrapping by setting `layout: false` in its companion `.js` config/loader, or by explicitly using `{% extends "..." %}` in its Nunjucks template.
382
+
383
+ ```html
384
+ {# pages/_layout.njk #}
385
+ <!DOCTYPE html>
386
+ <html>
387
+ <head><title>{{ siteTitle }}</title></head>
388
+ <body>
389
+ <header>Global Nav</header>
390
+ {{ content | safe }}
391
+ </body>
392
+ </html>
393
+ ```
394
+
395
+ ```html
396
+ {# pages/dashboard/_layout.njk #}
397
+ <div class="dashboard-shell">
398
+ <aside>Dashboard Sidebar</aside>
399
+ <main>{{ content | safe }}</main>
400
+ </div>
401
+ ```
402
+
403
+ #### 3. Folder-Level Error Boundaries (`_error.njk` & `_error.js`)
404
+ When an exception occurs during SSR lifecycle execution (in `load()`, template rendering, hooks, or nested layout loaders):
405
+ - **Ancestral Discovery**: Webspresso searches up the directory hierarchy from the route's directory up to `pages/` for the nearest `_error.njk`.
406
+ - **Isolated Layout Preservation**: `_error.njk` is automatically wrapped inside the surrounding ancestor `_layout.njk` chain, keeping the UI intact (e.g. an error in `/dashboard/billing/invoices` renders the error card inside the dashboard sidebar and header).
407
+ - **Companion Loader (`_error.js`)**: Can export `load({ error, req, res, ctx, db })` to attach custom error data or report exceptions.
408
+ - **Status Code Propagation**: HTTP status is set to `error.status || error.statusCode || 500` (e.g., throwing `NotFoundError` returns HTTP 404).
409
+ - **Opt-Out**: Disable layout wrapping with `layout: false` in `_error.js` or frontmatter (`--- layout: false ---`).
410
+ - **Fallback**: If no `_error.njk` exists in any ancestor directory, execution falls through to the global Express error boundary (`app.setErrorHandler` / 500 page).
411
+
412
+ ```html
413
+ {# pages/dashboard/_error.njk #}
414
+ <div class="p-6 bg-red-50 dark:bg-red-950/30 rounded-xl border border-red-200">
415
+ <h2 class="text-xl font-bold text-red-700">Error {{ error.status }}</h2>
416
+ <p class="text-red-600 mt-2">{{ error.message }}</p>
417
+ {% if supportEmail %}<p class="mt-4 text-sm">Need help? Email {{ supportEmail }}</p>{% endif %}
418
+ </div>
419
+ ```
420
+
421
+ #### 4. Folder-Level Loading Skeletons (`_loading.njk`)
422
+ In SSR streaming mode (`stream: true` or `renderStream`):
423
+ - **Automatic Discovery**: Discovers the nearest `_loading.njk` up the directory chain.
424
+ - **Auto-Populate Slots**: Any empty `<div data-stream-target="slotName"></div>` in the page template is automatically populated with the `_loading.njk` skeleton HTML in the initial flushed shell chunk!
425
+ - **Context Availability**: Exposed as `{{ loadingSkeleton | safe }}` and `{{ loadingHtml | safe }}` in the template context.
426
+ - **Layout Integration**: Cascading `_layout.njk` templates automatically wrap the streaming shell.
427
+
428
+ ```html
429
+ {# pages/dashboard/_loading.njk #}
430
+ <div class="animate-pulse space-y-4">
431
+ <div class="h-8 bg-slate-200 dark:bg-slate-800 rounded w-1/4"></div>
432
+ <div class="h-32 bg-slate-200 dark:bg-slate-800 rounded"></div>
433
+ </div>
434
+ ```
435
+
283
436
  ---
284
437
 
285
- ## 6. Summary Checklist for Agents
438
+ ## 7. Summary Checklist for Agents
286
439
 
287
440
  When a user asks to add or modify endpoints:
288
441
  1. Identify the URL and method (e.g. `POST /api/auth/register` or `POST /auth/login`).
@@ -71,3 +71,38 @@ export async function load({ req, db }) {
71
71
  };
72
72
  }
73
73
  ```
74
+
75
+ ---
76
+
77
+ ## 4. Folder-Based Loading Skeletons (`_loading.njk`)
78
+
79
+ Directory trees under `pages/` support automatic loading skeleton discovery and injection:
80
+
81
+ ```
82
+ pages/
83
+ ├── _loading.njk # Root fallback skeleton
84
+ └── dashboard/
85
+ ├── _loading.njk # Dashboard-specific skeleton
86
+ ├── _layout.njk # Cascading layout (wraps streaming shell)
87
+ ├── overview.njk
88
+ └── overview.js # Returns { stream: true, defer: { metrics: ... } }
89
+ ```
90
+
91
+ ### Automatic Slot Population
92
+ When `_loading.njk` exists in a folder hierarchy, any empty `<div data-stream-target="slotName"></div>` element is automatically populated with the rendered `_loading.njk` template inside the initial flushed HTML shell:
93
+
94
+ ```html
95
+ <!-- pages/dashboard/overview.njk -->
96
+ <h1>Dashboard Overview</h1>
97
+
98
+ <!-- Automatically receives _loading.njk skeleton on initial flush! -->
99
+ <div data-stream-target="metrics"></div>
100
+ ```
101
+
102
+ ### Template Context Availability
103
+ The skeleton HTML is also directly accessible in the template context:
104
+ - `{{ loadingSkeleton | safe }}`
105
+ - `{{ loadingHtml | safe }}`
106
+
107
+ ### Nested Layouts with Streaming
108
+ Cascading `_layout.njk` layouts automatically wrap the initial streaming shell chunk, preserving headers, navigation, and sidebars without extra configuration.
package/AGENTS.md CHANGED
@@ -142,6 +142,8 @@ Plugins expose `name`, `version`, `dependencies`, and lifecycle hooks (`register
142
142
  - `restResourcePlugin`: Zero-boilerplate RESTful CRUD API generator directly from ORM models with eager loading, sanitization, filtering, pagination, and soft-delete scoping.
143
143
  - `xlsxPlugin`: Excel spreadsheet generation, parsing, ORM streaming export (`res.xlsx`), and built-in services (`xlsx.generate`, `xlsx.parse`, `xlsx.exportModel`).
144
144
  - `csvPlugin`: RFC 4180 CSV generator, parser, Excel UTF-8 BOM compatibility, formula sanitization, streaming writer (`res.csv`), and built-in services (`csv.generate`, `csv.parse`, `csv.exportModel`).
145
+ - `apiKeyPlugin`: Zero-dependency B2B & Developer API Key Management with SHA-256 secure storage, constant-time verification, granular wildcard scopes, named route middleware (`ctx.middlewares.apiKey`), and non-blocking usage tracking.
146
+ - `webhooksPlugin`: Outgoing Webhook Dispatcher with HMAC-SHA256 cryptographic signatures, wildcard event matching (`*`, `order.*`), automatic retries with exponential backoff, background job queue integration (`core/queue`), built-in services (`webhook.dispatch`, `webhook.ping`, `webhook.retry`), and Mithril.js Admin Panel management UI.
145
147
 
146
148
  ---
147
149
 
package/README.md CHANGED
@@ -2,21 +2,22 @@
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/webspresso.svg?style=flat-square)](https://www.npmjs.com/package/webspresso)
4
4
  [![vulnerabilities](https://npmx.dev/api/registry/badge/vulnerabilities/webspresso?style=shieldsio)](https://npmx.dev/package/webspresso)
5
+ [![Node.js >= 20](https://img.shields.io/badge/node-%3E%3D20-brightgreen.svg?style=flat-square)](https://nodejs.org)
5
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=flat-square)](LICENSE)
6
7
 
7
- A lightweight, zero-dependency-sprawl Express SSR framework featuring file-based routing, server-side Nunjucks rendering, an intuitive Knex-based ORM with ambient `AsyncLocalStorage` transactions, dual authentication (Session + JWT), zero-dependency streaming compression, graceful shutdown, and a customizable Mithril.js SPA Admin Panel.
8
+ A batteries-included, full-stack Node.js framework combining Next.js/Nuxt-style file-based routing, server-rendered Nunjucks streaming, a Knex-based ORM with ambient transactions, zero-dependency dual authentication, background queues, and a customizable Mithril.js SPA Admin Panel.
8
9
 
9
10
  ---
10
11
 
11
- ## ⚡ Quick Start (3 Minutes)
12
+ ## ⚡ Quick Start
12
13
 
13
- Scaffold a new project with interactive database and styling setup:
14
+ Create a new Webspresso project in seconds:
14
15
 
15
16
  ```bash
16
- # Create a new project interactively
17
+ # Scaffold a new application interactively
17
18
  npx webspresso new my-app --install
18
19
 
19
- # Navigate and start development server
20
+ # Start development server with live reload
20
21
  cd my-app
21
22
  npm run dev
22
23
  ```
@@ -25,132 +26,183 @@ Open **`http://localhost:3000`** in your browser.
25
26
 
26
27
  ---
27
28
 
28
- ## ✨ Why Webspresso?
29
+ ## 🌟 Core Capabilities
29
30
 
30
- - **Zero-Dependency Sprawl**: Core framework features (Dual Auth, JWT signing, Error handling, Streaming Compression, Graceful Shutdown, Template Helpers) rely strictly on native Node.js standard modules (`crypto`, `path`, `fs`, `events`, `zlib`, `async_hooks`) without bloated dependency trees.
31
- - **File-Based Routing & API Suffixes**: Pages and APIs automatically map to clean URLs with dynamic params (`[id]`), wildcards (`[...slug]`), and method suffixes (`.get.js`, `.post.js`, `.delete.js`, `.patch.js`, `.put.js`).
32
- - **Feature Modules (`defineModule`)**: Domain-driven modular organization for large projects (`modules/{name}/pages`, `api`, `services`, `middleware`).
33
- - **Modern Page & API Helpers (`definePage`, `defineApi`)**: Declarative Zod request schemas, unified execution context, and automatic JSON response serialization.
34
- - **Server Data Prefetching (`load()`)**: Page routes export `async function load({ req, res, db, ctx })` to fetch data server-side before template compilation.
35
- - **Services Layer**: File-based auto-discovery in `services/` with declarative Zod validation, role/predicate authorization guards, and memoization.
36
- - **Ambient Transactions**: Knex database transactions automatically bind to `AsyncLocalStorage` (`core/orm/transaction.js`). Scoped repositories seamlessly participate in active transactions without manual `trx` passing.
37
- - **Mithril.js Admin Panel SPA**: Built-in, isolated single-page admin panel mounted at `/_admin` with auto-layout wrapping for custom pages, widgets, and field renderers.
38
- - **TypeScript First-Class Support**: Shipped with complete [`index.d.ts`](index.d.ts) type definitions for IDE autocompletion and type checking.
31
+ | Layer | Capabilities |
32
+ | :--- | :--- |
33
+ | **Routing & SSR** | 100% file-based routing (`pages/`), method suffixes (`.get.js`, `.post.js`), nested layouts (`_layout.njk`), directory-level error boundaries (`_error.njk`), loading skeletons (`_loading.njk`), and out-of-order chunked response streaming (`res.renderStream`). |
34
+ | **Database & ORM** | Built-in Knex ORM with `defineModel`, `zdb` schema builder, Repository pattern (`db.getRepository('Model')`), relations (`belongsTo`, `hasMany`), cascade soft-delete & restore, and ambient transactions via `AsyncLocalStorage`. |
35
+ | **Dual Auth & Sessions** | Stateful cookies for SSR + stateless HS256 JWT rotation for APIs, magic links, active device management & remote session revocation, CSRF protection, and zero external auth dependencies. |
36
+ | **Services & Queues** | File-based auto-discovery in `services/` with declarative Zod validation, role-based access guards, and ACID transaction propagation. Background worker queues in `jobs/`. |
37
+ | **Admin Panel SPA** | Integrated Mithril.js single-page admin panel mounted at `/_admin` with auto-layout wrapping, CRUD views, custom dashboard widgets, and custom field renderers. |
38
+ | **Plugin Ecosystem** | 20+ official plugins: Polar.sh billing, Webhooks dispatcher with HMAC signatures, Realtime (WebSocket/SSE), Site Analytics, API Keys, File Manager, CSV/Excel generation, and more. |
39
+ | **DevOps & Production** | Built-in streaming zlib compression (`brotli`/`gzip`), socket connection draining & graceful shutdown, `webspresso deploy:check` production readiness auditor, and Docker scaffolding. |
39
40
 
40
41
  ---
41
42
 
42
- ## 🛠️ Minimal Example
43
+ ## 🛠️ Code at a Glance
43
44
 
44
- ### 1. Server Entry Point (`server.js`)
45
- ```javascript
46
- const path = require('path');
47
- require('./config/load-env');
48
- const { createApp, createDatabase } = require('webspresso');
49
-
50
- const db = createDatabase(require('./webspresso.db'));
51
-
52
- const { app } = createApp({
53
- db,
54
- pagesDir: path.join(__dirname, 'pages'),
55
- viewsDir: path.join(__dirname, 'views'),
56
- server: {
57
- shutdown: { enabled: true, timeout: 10000 },
58
- compression: true,
59
- },
60
- });
45
+ ### 1. File-Based Page Route (`pages/notes.njk` + `pages/notes.js`)
61
46
 
62
- const PORT = process.env.PORT || 3000;
63
- app.listen(PORT, () => {
64
- console.log(`Server listening at http://localhost:${PORT}`);
65
- });
66
- ```
47
+ Companion `.js` loaders fetch data server-side before template rendering:
67
48
 
68
- ### 2. Server-Rendered Page (`pages/index.njk` + `pages/index.js`)
69
49
  ```html
70
- <!-- pages/index.njk -->
50
+ <!-- pages/notes.njk -->
71
51
  {% extends "views/layout.njk" %}
72
52
 
73
53
  {% block content %}
74
- <div class="max-w-4xl mx-auto py-12 px-4">
75
- <h1 class="text-3xl font-bold mb-4">{{ title }}</h1>
76
- <p class="text-slate-600">Welcome, {{ user.name or "Guest" }}!</p>
54
+ <div class="max-w-3xl mx-auto py-8">
55
+ <h1 class="text-2xl font-bold mb-4">My Notes</h1>
56
+ <ul class="space-y-2">
57
+ {% for note in notes %}
58
+ <li class="p-4 bg-white rounded border shadow-sm">{{ note.title }}</li>
59
+ {% else %}
60
+ <p class="text-slate-500">No notes yet.</p>
61
+ {% endfor %}
62
+ </ul>
77
63
  </div>
78
64
  {% endblock %}
79
65
  ```
80
66
 
81
67
  ```javascript
82
- // pages/index.js
83
- const { definePage } = require('webspresso');
84
-
85
- module.exports = definePage({
86
- async load({ req, ctx }) {
87
- return {
88
- title: 'Home Page',
89
- user: req.user || null,
90
- };
68
+ // pages/notes.js
69
+ module.exports = {
70
+ async load({ req, db }) {
71
+ const notes = await db.getRepository('Note').find({
72
+ userId: req.user?.id,
73
+ });
74
+ return { notes };
91
75
  },
92
- });
76
+ };
93
77
  ```
94
78
 
95
- ### 3. Validated JSON API Endpoint (`pages/api/greet.post.js`)
79
+ ### 2. Method-Suffixed API Route (`pages/api/notes.post.js`)
80
+
81
+ Export `{ schema, middleware, handler }` or `defineApi()` with declarative Zod validation:
82
+
96
83
  ```javascript
97
- const { defineApi, z } = require('webspresso');
84
+ // pages/api/notes.post.js
85
+ const { defineApi } = require('webspresso');
98
86
 
99
87
  module.exports = defineApi({
100
- schema: {
88
+ schema: ({ z }) => ({
101
89
  body: z.object({
102
- name: z.string().min(2),
90
+ title: z.string().min(1, 'Title is required').max(200),
91
+ content: z.string().min(1),
103
92
  }),
93
+ }),
94
+ middleware: ['auth'], // Built-in session or JWT guard
95
+ async handler(req, res) {
96
+ // req.input.body is validated and typed
97
+ const note = await req.db.getRepository('Note').create({
98
+ ...req.input.body,
99
+ userId: req.user.id,
100
+ });
101
+ return res.status(201).json(note);
102
+ },
103
+ });
104
+ ```
105
+
106
+ ### 3. ORM Model Definition (`models/Note.js`)
107
+
108
+ Define models with `defineModel` and the expressive `zdb` schema builder:
109
+
110
+ ```javascript
111
+ // models/Note.js
112
+ const { defineModel, zdb } = require('webspresso');
113
+
114
+ module.exports = defineModel({
115
+ name: 'Note',
116
+ table: 'notes',
117
+ schema: {
118
+ id: zdb.id(),
119
+ title: zdb.string(200),
120
+ content: zdb.text(),
121
+ userId: zdb.integer(),
122
+ ...zdb.timestamps(),
123
+ ...zdb.softDeletes(),
104
124
  },
125
+ relations: {
126
+ user: { type: 'belongsTo', model: 'User', foreignKey: 'userId' },
127
+ },
128
+ });
129
+ ```
130
+
131
+ ### 4. Application Server (`server.js`)
105
132
 
106
- async handler(req, res, ctx) {
107
- // req.input is typed and validated by Zod
108
- const result = await ctx.service('user.greet', req.input.body);
109
- return result; // Automatically serialized as JSON (HTTP 200)
133
+ ```javascript
134
+ const path = require('path');
135
+ const { createApp, createDatabase } = require('webspresso');
136
+
137
+ const db = createDatabase(require('./webspresso.db'));
138
+
139
+ const { app } = createApp({
140
+ db,
141
+ pagesDir: path.join(__dirname, 'pages'),
142
+ viewsDir: path.join(__dirname, 'views'),
143
+ server: {
144
+ compression: true,
145
+ shutdown: { enabled: true, timeout: 10000 },
110
146
  },
111
147
  });
148
+
149
+ const PORT = process.env.PORT || 3000;
150
+ app.listen(PORT, () => {
151
+ console.log(`Server running at http://localhost:${PORT}`);
152
+ });
153
+ ```
154
+
155
+ ---
156
+
157
+ ## 🧰 Essential CLI Commands
158
+
159
+ ```bash
160
+ # Development & Builds
161
+ npx webspresso dev # Start dev server with watch & live reload
162
+ npx webspresso build # Compile production assets
163
+ npx webspresso start # Run production server
164
+
165
+ # Database & Migrations
166
+ npx webspresso db:migrate # Run pending database migrations
167
+ npx webspresso db:rollback # Roll back latest migration batch
168
+ npx webspresso db:status # Inspect migration status
169
+ npx webspresso seed # Run seed files
170
+
171
+ # Code Generation
172
+ npx webspresso page <path> # Scaffold a new SSR page + loader
173
+ npx webspresso api <path> # Scaffold a new method-suffixed API route
174
+ npx webspresso make:model <name> # Generate a new ORM model
175
+ npx webspresso make:job <name> # Generate a background queue job
176
+
177
+ # DevOps & Production Readiness
178
+ npx webspresso doctor # Run project health & configuration check
179
+ npx webspresso deploy:check # Pre-flight production readiness inspection
180
+ npx webspresso add:docker # Scaffold Dockerfile & docker-compose.yml
181
+ npx webspresso add:tailwind # Configure TailwindCSS integration
112
182
  ```
113
183
 
114
184
  ---
115
185
 
116
186
  ## 📚 Documentation
117
187
 
118
- The complete Webspresso documentation is organized into 5 focused pillars:
119
-
120
- ### 🚀 Getting Started
121
- - **[Installation Guide](docs/getting-started/installation.md)** — Node.js 20 LTS prerequisites, CLI setup, and TypeScript.
122
- - **[Creating Your First App](docs/getting-started/first-app.md)** — Step-by-step walkthrough building an SSR page, API endpoint, and service.
123
- - **[Project Structure](docs/getting-started/project-structure.md)** — Anatomy of `pages/`, `views/`, `services/`, `models/`, and `config/`.
124
- - **[Deployment & Production](docs/getting-started/deployment.md)** — Production configuration, Docker, PM2, and Nginx.
125
-
126
- ### 📖 Task Guides ("How do I...?")
127
- - **[File-Based Routing](docs/guides/routing.md)** — Static routes, dynamic params (`[id]`), and catch-all wildcards.
128
- - **[SSR & Templates](docs/guides/ssr-and-templates.md)** — Nunjucks layouts, `load()` loaders, `fsy` helper catalog, and chunked streaming.
129
- - **[Services Layer](docs/guides/services.md)** — Defining services, Zod validation, auth role guards, and ACID transactions.
130
- - **[Database & ORM](docs/guides/database-and-orm.md)** — Model definitions (`defineModel`), `zdb` schema builder, and Knex migrations.
131
- - **[Dual Authentication](docs/guides/authentication.md)** — Stateful Session cookies for SSR and stateless JWT rotation for REST APIs.
132
- - **[Admin Panel Customization](docs/guides/admin-panel.md)** — Custom Mithril.js SPA pages, KPI widgets, and custom field renderers.
133
-
134
- ### 🧠 Concepts & Architecture ("How does it work and why?")
135
- - **[System Architecture](docs/concepts/architecture.md)** — Layered architecture, subsystem boundaries, and design principles.
136
- - **[Request Lifecycle](docs/concepts/request-lifecycle.md)** — End-to-end trace from TCP socket to template render and response stream.
137
- - **[Service Execution Pipeline](docs/concepts/service-execution-pipeline.md)** — Sanitization, Zod validation, auth guards, ambient transactions, and caching.
138
- - **[Ambient Transaction Propagation](docs/concepts/transaction-propagation.md)** — How `AsyncLocalStorage` manages ACID database transactions across nested services.
139
-
140
- ### 📚 API Reference ("What is the exact contract?")
141
- - **[`createApp()` Configuration](docs/reference/create-app.md)** — Full `CreateAppOptions` parameter reference.
142
- - **[CLI Reference](docs/reference/cli.md)** — Complete `webspresso` CLI command manual.
143
- - **[Service Definition Spec](docs/reference/service-definition.md)** — `defineService` options and `ServiceContext` properties.
144
- - **[Model Definition Spec](docs/reference/model-definition.md)** — `defineModel` options, `zdb` column types, and `Repository` query methods.
145
- - **[Exceptions Catalog](docs/reference/exceptions.md)** — Built-in framework exception classes and HTTP status codes.
188
+ Detailed topic guides are available in the repository:
189
+
190
+ - **[Installation & First App](docs/getting-started/installation.md)** — Node.js requirements, setup, and first steps.
191
+ - **[File-Based Routing & API Routes](.agents/ROUTING.md)** — Routing conventions, parameters, and cascading layouts.
192
+ - **[SSR Streaming & Chunked Transfer](.agents/STREAMING.md)** — Out-of-order slots, `_loading.njk` skeletons, and TTFB optimization.
193
+ - **[Database & ORM Guide](.agents/ORM.md)** — Repositories, relations, soft deletes, and ambient transactions.
194
+ - **[Dual Authentication System](.agents/AUTH.md)** — Sessions, JWT rotation, magic links, and device management.
195
+ - **[Plugin Ecosystem Reference](.agents/PLUGINS.md)** — Polar billing, webhooks, analytics, realtime, and more.
196
+ - **[Admin Panel Customization](.agents/ADMIN.md)** — Extending the Mithril.js SPA admin panel.
197
+ - **[Full TypeScript Reference](index.d.ts)** — Canonical framework types and signatures.
146
198
 
147
199
  ---
148
200
 
149
- ## 🤖 For AI Coding Agents
201
+ ## 🤖 For AI Coding Assistants
150
202
 
151
- If you are an autonomous coding assistant or LLM working on a Webspresso codebase:
152
- - Read **[`AGENTS.md`](AGENTS.md)** for authoritative architectural guidelines, zero-regression policies, and critical signatures.
153
- - Consult **[`llms.txt`](llms.txt)** for a machine-readable sitemap of all documentation resources.
203
+ If you are an autonomous coding agent working in a Webspresso codebase:
204
+ - Read **[`AGENTS.md`](AGENTS.md)** for mandatory architectural rules, zero-regression policies, and code contracts.
205
+ - Check **[`llms.txt`](llms.txt)** for a machine-readable directory map of all documentation.
154
206
 
155
207
  ---
156
208