clovie 0.1.45 → 0.1.47

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.
@@ -0,0 +1,77 @@
1
+ ---
2
+ description: Build and extend Clovie (static/server) projects — config, factories, APIs, routes, hooks, middleware.
3
+ globs: clovie.config.js,**/clovie.config.*,lib/**/*.js,templates/**/*
4
+ ---
5
+
6
+ # Working with Clovie
7
+
8
+ Clovie is a Node.js static site generator and server framework driven by `clovie.config.js` and `@jucie.io/engine` services.
9
+
10
+ ## Mental model
11
+
12
+ - **`type: 'static'`** — build outputs HTML under `outputDir`; dev server is for preview and live reload.
13
+ - **`type: 'server'`** — HTTP server registers **factories** in order: `hooks` → `middleware` → `api` → generated routes from `views` + `routes`.
14
+ - **Factories** — `api`, `routes` (SSR), `middleware`, and `hooks` accept plain objects/arrays **or** `define*` factory functions from `clovie` (re-exported from `@jucie.io/engine-server`). Factories receive `(useContext, opts)` so handlers can depend on engine context when needed.
15
+
16
+ ## Imports
17
+
18
+ ```javascript
19
+ import {
20
+ defineApi, // alias for defineRoutes; use for semantic clarity on api: []
21
+ defineRoutes,
22
+ defineMiddleware,
23
+ defineHooks,
24
+ } from 'clovie';
25
+ ```
26
+
27
+ `defineApi` and `defineRoutes` are the same function — use whichever reads clearer in your config.
28
+
29
+ ## API routes (`opts.api`)
30
+
31
+ - Items are **engine-server route definitions**: at minimum `method`, `path`, and **`handler`** `(ctx) => ...` using `ctx.respond.json()` / `.html()` / `.text()` / `.file()`.
32
+ - **Prefer factories** when routes need `useContext` (logging, DB, services) or you want to split APIs across modules.
33
+
34
+ ```javascript
35
+ import { defineRoutes } from 'clovie';
36
+
37
+ const adminApi = defineRoutes('admin', (useContext, opts) => {
38
+ const [log] = useContext('log');
39
+ return [
40
+ {
41
+ method: 'GET',
42
+ path: '/ping',
43
+ handler: (ctx) => ctx.respond.json({ ok: true }),
44
+ },
45
+ ];
46
+ });
47
+
48
+ export default {
49
+ type: 'server',
50
+ api: [
51
+ { method: 'GET', path: '/api/health', handler: (ctx) => ctx.respond.json({ status: 'up' }) },
52
+ adminApi,
53
+ ],
54
+ };
55
+ ```
56
+
57
+ You can mix **raw route objects** and **factories** in the same `api` array; Clovie normalizes them before `server.use(...)`.
58
+
59
+ ## SSR routes (`opts.routes`)
60
+
61
+ Same factory pattern applies to `routes` merged with auto-generated view routes: use `defineRoutes` when data or handlers need context.
62
+
63
+ ## Middleware and hooks
64
+
65
+ - **`middleware`**: `defineMiddleware(name, (useContext, opts) => [fn, ...])` or raw Express-style functions when using the Express adapter.
66
+ - **`hooks`**: `defineHooks(name, (useContext, opts) => ({ onRequest, preHandler, ... }))`.
67
+
68
+ ## Docs and CLI
69
+
70
+ - Full options: repository `docs/CONFIGURATION.md`.
71
+ - Bundled agent skill path: run `clovie skills path` from an install that includes the `clovie` package.
72
+
73
+ ## Common mistakes
74
+
75
+ - Using a nonexistent **`action`** field on API routes — use **`handler`** and `ctx.respond.*`.
76
+ - Forgetting **`type: 'server'`** when using `api` / server routes.
77
+ - Assuming factories run at import time — they are invoked with `(useContext, opts)` when the server registers routes.
package/AGENTS.md ADDED
@@ -0,0 +1,239 @@
1
+ # AGENTS — Clovie
2
+
3
+ Instructions for AI agents working with or on Clovie.
4
+
5
+ ## Part A: Using Clovie in your project
6
+
7
+ Clovie is a Node.js static site generator and server framework driven by a single `clovie.config.js` file, built on the `@jucie.io/engine` service architecture.
8
+
9
+ ### Two modes
10
+
11
+ - **`type: 'static'`** — generates static HTML under `outputDir`; dev server is for preview and live reload.
12
+ - **`type: 'server'`** — HTTP server registers factories in order: `hooks` -> `middleware` -> `api` -> view routes + `routes`.
13
+
14
+ ### Imports
15
+
16
+ ```javascript
17
+ import {
18
+ createClovie,
19
+ defineApi, // alias for defineRoutes; use for semantic clarity on api: []
20
+ defineRoutes,
21
+ defineMiddleware,
22
+ defineHooks,
23
+ } from 'clovie';
24
+ ```
25
+
26
+ `defineApi` and `defineRoutes` are the same function.
27
+
28
+ ### API route shape
29
+
30
+ Routes in the `api` array must use `method`, `path`, and `handler`:
31
+
32
+ ```javascript
33
+ {
34
+ method: 'GET',
35
+ path: '/api/status',
36
+ handler: (ctx) => ctx.respond.json({ status: 'ok' })
37
+ }
38
+ ```
39
+
40
+ Response methods on `ctx.respond`: `.json(data, status)`, `.html(html, status)`, `.text(text, status)`, `.file(path, status)`.
41
+
42
+ Request data: `ctx.body` (parsed body), `ctx.query` (query params), `ctx.params` (route params), `ctx.req` (raw request).
43
+
44
+ ### Factories
45
+
46
+ `api`, `routes`, `middleware`, and `hooks` accept plain objects/arrays **or** `define*` factory functions. Factories receive `(useContext, opts)` and are invoked lazily when the server registers routes, not at import time.
47
+
48
+ ```javascript
49
+ import { defineRoutes } from 'clovie';
50
+
51
+ const adminApi = defineRoutes('admin', (useContext, opts) => {
52
+ const [log] = useContext('log');
53
+ return [
54
+ { method: 'GET', path: '/ping', handler: (ctx) => ctx.respond.json({ ok: true }) },
55
+ ];
56
+ });
57
+
58
+ export default {
59
+ type: 'server',
60
+ api: [adminApi],
61
+ };
62
+ ```
63
+
64
+ You can mix raw route objects and factories in the same array.
65
+
66
+ ### CLI commands
67
+
68
+ ```
69
+ clovie create <name> [--template static|server]
70
+ clovie dev # development server with live reload
71
+ clovie build # production build
72
+ clovie serve # production server
73
+ clovie kill --port 3000
74
+ clovie skills show # dump bundled Cursor skill for pasting
75
+ ```
76
+
77
+ ### Common mistakes
78
+
79
+ - Using `action` instead of **`handler`** on API routes.
80
+ - Omitting **`type: 'server'`** when using `api` or server routes.
81
+ - Assuming factories run at import time — they run when the server starts.
82
+
83
+ ### Cursor skill
84
+
85
+ Clovie ships a Cursor skill at `.cursor/skills/clovie.mdc`. Run `clovie skills show` to print it, or copy it into your project's `.cursor/skills/`.
86
+
87
+ ---
88
+
89
+ ## Part B: Contributing to the Clovie source
90
+
91
+ ### Repository layout
92
+
93
+ ```
94
+ clovie/
95
+ ├── lib/ # Core source code
96
+ │ ├── services/ # ServiceProvider implementations
97
+ │ ├── factories/ # defineApi, defineRoutes, defineMiddleware, defineHooks
98
+ │ ├── utils/ # Shared utilities
99
+ │ ├── cli/ # CLI subcommands (e.g. skillsCommand.js)
100
+ │ ├── createClovie.js # Engine factory — wires all services
101
+ │ └── main.js # Package exports
102
+ ├── bin/ # CLI entry point
103
+ │ └── cli.js
104
+ ├── __tests__/ # Vitest test suite
105
+ ├── config/ # Default clovie.config.js fallback
106
+ ├── templates/ # Project templates (static, server)
107
+ ├── scripts/ # Build and publish scripts
108
+ ├── packages/ # Workspaces
109
+ │ ├── docs/ # @clovie/docs — Docusaurus documentation site
110
+ │ └── public/ # @clovie/public — Clovie-built static site
111
+ ├── __dev__/ # Development playground (server mode)
112
+ └── .cursor/skills/ # Bundled Cursor skill (ships with npm)
113
+ ```
114
+
115
+ ### Module format
116
+
117
+ ESM only (`"type": "module"` in package.json). Use `import`/`export` everywhere. Use `import.meta.url` instead of `__dirname`.
118
+
119
+ ### Service architecture
120
+
121
+ All services extend `ServiceProvider` from `@jucie.io/engine`. Each service declares:
122
+
123
+ ```javascript
124
+ import { ServiceProvider } from '@jucie.io/engine';
125
+
126
+ export class MyService extends ServiceProvider {
127
+ static manifest = {
128
+ name: 'Human Readable Name',
129
+ namespace: 'camelCaseKey', // becomes the engine accessor (clovie.camelCaseKey)
130
+ version: '1.0.0',
131
+ dependencies: [OtherService], // installed before this service
132
+ };
133
+
134
+ // Optional — runs once during install
135
+ async initialize(_, config) { }
136
+
137
+ // Optional — reactive read-only properties
138
+ getters() {
139
+ return { prop: () => this.#value };
140
+ }
141
+
142
+ // Required — public API exposed on the engine
143
+ actions(useContext) {
144
+ const [file, log] = useContext('file', 'log');
145
+ return {
146
+ doSomething: async (opts) => { /* ... */ },
147
+ };
148
+ }
149
+ }
150
+ ```
151
+
152
+ **`useContext` idioms:**
153
+ - Positional: `const [file, log] = useContext('file', 'log');` — resolves at action-construction time.
154
+ - Whole context: `const { cache } = useContext();` — returns the full context object.
155
+ - Late-bound: `this.useContext('server')` inside async methods for services that may not be installed yet.
156
+
157
+ Use `#private` fields for internal state.
158
+
159
+ ### Engine wiring (`createClovie`)
160
+
161
+ `createClovie({ optsPath, mode })` builds the engine in this order:
162
+
163
+ 1. `Configurator` — loads and watches `clovie.config.js`
164
+ 2. On `configurator.onReady(opts)`:
165
+ - `Compile` and `Run` (always)
166
+ - `EsBuild` (if `opts.scripts` exists)
167
+ - User `opts.setup(clovie)` hook
168
+ - `Server` (if `type: 'server'` or development mode)
169
+ - `LiveReload` (if development mode)
170
+ - User `opts.services` array
171
+
172
+ The resolved value is the engine instance, not a running server. The CLI calls `clovie.run.build()`, `.serve()`, or `.dev()` to execute.
173
+
174
+ ### Testing
175
+
176
+ - **Framework:** Vitest with `globals: true`.
177
+ - **Test files:** `__tests__/*.test.js`
178
+ - **Fixture configs:** `__tests__/clovie.<area>.config.js` (e.g. `clovie.middleware.config.js`)
179
+ - **Integration pattern:**
180
+
181
+ ```javascript
182
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
183
+ import { createClovie } from '../lib/createClovie.js';
184
+ import path from 'path';
185
+
186
+ const pause = async (ms = 10) => new Promise(resolve => setTimeout(resolve, ms));
187
+
188
+ describe('Feature', () => {
189
+ let clovie = null;
190
+
191
+ beforeEach(async () => {
192
+ clovie = await createClovie({
193
+ optsPath: path.resolve(process.cwd(), '__tests__', 'clovie.config.js'),
194
+ mode: 'production',
195
+ open: false,
196
+ });
197
+ await pause(50);
198
+ });
199
+
200
+ afterEach(async () => {
201
+ if (clovie?.server?.isRunning()) {
202
+ await clovie.server.stop();
203
+ }
204
+ clovie = null;
205
+ });
206
+
207
+ it('should work', async () => {
208
+ expect(clovie.configurator.opts.type).toBe('static');
209
+ });
210
+ });
211
+ ```
212
+
213
+ - Use `port: 0` for dynamic port allocation in HTTP tests.
214
+ - CLI tests use `child_process.spawn` with a `runCli` helper.
215
+
216
+ ### CLI structure (`bin/cli.js`)
217
+
218
+ Command branching order: `skills` -> `kill` -> `create` -> `command-line-args` main flow.
219
+
220
+ Main commands: `build` (production, exits after), `serve` (production, stays alive), `dev`/`watch` (development, stays alive).
221
+
222
+ Legacy aliases: `watch` -> `dev`, `server` -> `serve`.
223
+
224
+ Config resolution: dynamic `import(optsPath)`, fallback to `config/clovie.config.js`.
225
+
226
+ ### Templates
227
+
228
+ `templates/static/` and `templates/server/` are copied verbatim by `clovie create`. The placeholders `{{projectName}}` and `{{clovieVersion}}` are substituted at copy time. Keep these placeholders intact when editing template files.
229
+
230
+ ### Workspaces
231
+
232
+ - **`@clovie/docs`** — Docusaurus 3 site, content in `packages/docs/docs/`
233
+ - **`@clovie/public`** — Clovie static site (marketing/legacy docs surface)
234
+
235
+ Root scripts: `npm run docs:dev`, `npm run docs:build`, `npm run public:dev`, `npm run public:build`.
236
+
237
+ ### Publishing
238
+
239
+ `prepublishOnly` runs `npm test` — regressions block publish. Use `scripts/publish.js` for version bumps and releases. The package ships raw source (no build step for the library itself).
package/README.md CHANGED
@@ -4,6 +4,17 @@
4
4
 
5
5
  A powerful Node.js-based **static site generator** and **full-stack web framework** that bridges the gap between simple static sites and complex web applications. Built on the **@jucie.io/engine** service architecture for maximum flexibility and maintainability.
6
6
 
7
+ ## 📚 Documentation site
8
+
9
+ The docs website uses **Docusaurus** in [`website/`](website/). From the repo root:
10
+
11
+ ```bash
12
+ npm run website:dev # http://localhost:3000
13
+ npm run website:build # output in website/build/
14
+ ```
15
+
16
+ Authoritative markdown for the long-form guide remains [`docs/CONFIGURATION.md`](docs/CONFIGURATION.md); keep [`website/docs/configuration.md`](website/docs/configuration.md) in sync (or add a copy script). The older Clovie-built docs under [`docs/`](docs/) (`clovie.config.js`, `views/`) are optional legacy.
17
+
7
18
  ## 🚀 Quick Start
8
19
 
9
20
  ```bash
@@ -32,6 +43,14 @@ npm run dev
32
43
 
33
44
  Clovie uses a **service-oriented architecture** built on `@jucie.io/engine`. All functionality is provided by services that extend `ServiceProvider`, orchestrated through dependency injection with reactive state management.
34
45
 
46
+ ### Route factories (`api`, `routes`, `middleware`, `hooks`)
47
+
48
+ In **server** mode, HTTP behavior is registered through **factory definitions** from `@jucie.io/engine-server` (import `defineRoutes`, `defineApi`, `defineMiddleware`, and `defineHooks` from `clovie`). You can pass plain route objects or factories; factories receive `(useContext, opts)` so APIs and SSR routes can resolve engine services when the server starts. Registration order is **hooks → middleware → `api` → view and config routes**. See [docs/CONFIGURATION.md](docs/CONFIGURATION.md#factories-for-api-routes-middleware-and-hooks).
49
+
50
+ ### Cursor / AI agents
51
+
52
+ The npm package ships a Cursor skill at `.cursor/skills/clovie.mdc`. After installing Clovie, run **`clovie skills path`** to print its absolute path, **`clovie skills show`** to dump the file for pasting into a project, or copy that file into your repo’s `.cursor/skills/` so assistants load it automatically.
53
+
35
54
  ### Core Services
36
55
 
37
56
  - **🗂️ File** - File system operations with intelligent watching
package/bin/cli.js CHANGED
@@ -15,6 +15,13 @@ const CLOVIE_VERSION = packageJson.version;
15
15
  // Local - import from compiled dist for published package
16
16
  import { createClovie } from "../lib/createClovie.js";
17
17
  import { killPort, checkPorts, killCommonPorts } from "../scripts/killPort.js";
18
+ import { runSkillsCommand } from "../lib/cli/skillsCommand.js";
19
+
20
+ // Bundled Cursor skill / agent docs (`clovie skills`, `clovie skills path`, …)
21
+ if (process.argv[2] === 'skills') {
22
+ await runSkillsCommand(process.argv.slice(3));
23
+ process.exit(typeof process.exitCode === 'number' && process.exitCode !== 0 ? process.exitCode : 0);
24
+ }
18
25
 
19
26
  // Check for kill command first (before any argument parsing)
20
27
  if (process.argv.includes('kill')) {
@@ -335,7 +342,7 @@ async function executeCommand(clovie, command, options) {
335
342
 
336
343
  default:
337
344
  console.error(`❌ Unknown command: ${command}`);
338
- console.error('Available commands: build, serve, dev, watch');
345
+ console.error('Available commands: build, serve, dev, watch, skills');
339
346
  process.exit(1);
340
347
  }
341
348
  }
@@ -0,0 +1,59 @@
1
+ import path from 'path';
2
+ import { fileURLToPath } from 'url';
3
+ import { readFileSync, existsSync } from 'fs';
4
+
5
+ const __filename = fileURLToPath(import.meta.url);
6
+ const __dirname = path.dirname(__filename);
7
+
8
+ /** Root of the published clovie package (parent of lib/). */
9
+ export function getCloviePackageRoot() {
10
+ return path.resolve(__dirname, '..', '..');
11
+ }
12
+
13
+ export function getBundledSkillPath() {
14
+ return path.join(getCloviePackageRoot(), '.cursor', 'skills', 'clovie.mdc');
15
+ }
16
+
17
+ /**
18
+ * @param {string[]} args Arguments after `clovie skills`
19
+ */
20
+ export async function runSkillsCommand(args) {
21
+ const skillPath = getBundledSkillPath();
22
+
23
+ if (args.includes('--help') || args.includes('-h')) {
24
+ printSkillsUsage(skillPath);
25
+ return;
26
+ }
27
+
28
+ if (args[0] === 'path' || args.includes('--path')) {
29
+ console.log(skillPath);
30
+ return;
31
+ }
32
+
33
+ if (args[0] === 'show' || args.includes('--show')) {
34
+ if (!existsSync(skillPath)) {
35
+ console.error(`Bundled skill file not found at:\n ${skillPath}`);
36
+ process.exitCode = 1;
37
+ return;
38
+ }
39
+ process.stdout.write(readFileSync(skillPath, 'utf8'));
40
+ return;
41
+ }
42
+
43
+ printSkillsUsage(skillPath);
44
+ }
45
+
46
+ function printSkillsUsage(skillPath) {
47
+ console.log('Clovie — bundled Cursor skill for AI agents');
48
+ console.log('');
49
+ console.log('Bundled skill file:');
50
+ console.log(` ${skillPath}`);
51
+ console.log('');
52
+ console.log('Commands:');
53
+ console.log(' clovie skills Show this help and the skill path');
54
+ console.log(' clovie skills path Print only the absolute path (for scripts)');
55
+ console.log(' clovie skills show Print the full skill file to stdout');
56
+ console.log('');
57
+ console.log('Best practice for agents: copy or symlink the file into your project under');
58
+ console.log(' .cursor/skills/ so Cursor loads it automatically, or paste `clovie skills show`.');
59
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clovie",
3
- "version": "0.1.45",
3
+ "version": "0.1.47",
4
4
  "description": "Vintage web dev tooling with modern quality of life",
5
5
  "keywords": [
6
6
  "static-site-generator",
@@ -50,6 +50,8 @@
50
50
  "scripts/**/*",
51
51
  "config/**/*",
52
52
  "templates/**/*",
53
+ ".cursor/skills/**/*",
54
+ "AGENTS.md",
53
55
  "README.md",
54
56
  "LICENSE"
55
57
  ],
@@ -62,9 +64,13 @@
62
64
  "kill:3000": "node ./bin/kill-port.js 3000",
63
65
  "kill:common": "node ./bin/kill-port.js --common",
64
66
  "kill:check": "node ./bin/kill-port.js --check",
65
- "docs:build": "cd docs && npm install && npm run build",
66
- "docs:dev": "cd docs && npm install && npm run dev",
67
- "docs:serve": "cd docs && npm install && npm run serve",
67
+ "public:build": " npm run -w @clovie/public build",
68
+ "public:dev": "npm run -w @clovie/public dev",
69
+ "public:serve": "npm run -w @clovie/public serve",
70
+ "docs:dev": "npm run -w @clovie/docs dev",
71
+ "docs:build": "npm run -w @clovie/docs build",
72
+ "docs:serve": "npm run -w @clovie/docs serve",
73
+ "docs:start": "npm run -w @clovie/docs start",
68
74
  "prepublishOnly": "npm test",
69
75
  "publish:test": "node scripts/publish.js test",
70
76
  "publish:docs": "node scripts/publish.js docs",
@@ -110,6 +116,9 @@
110
116
  "type-detect": "^4.0.8",
111
117
  "vitest": "^1.0.4"
112
118
  },
119
+ "workspaces": [
120
+ "packages/*"
121
+ ],
113
122
  "engines": {
114
123
  "node": ">=18.0.0"
115
124
  }
@@ -72,8 +72,8 @@ function showPublishInfo() {
72
72
  }
73
73
 
74
74
  function buildDocs() {
75
- console.log('\n📚 Building documentation...');
76
- run('npm run docs:build');
75
+ console.log('\n📚 Building documentation (Docusaurus)...');
76
+ run('npm run website:build');
77
77
  }
78
78
 
79
79
  function main() {
@@ -0,0 +1,37 @@
1
+ # AGENTS — Clovie Server Project
2
+
3
+ This is a Clovie server application (`type: 'server'`). Clovie runs an HTTP server with API endpoints, server-rendered pages, and optional middleware, all defined in `clovie.config.js`.
4
+
5
+ ## Project structure
6
+
7
+ ```
8
+ project/
9
+ ├── clovie.config.js # All app behavior: api, routes, hooks, middleware
10
+ ├── package.json
11
+ ├── views/ # Server-rendered HTML templates (Nunjucks by default)
12
+ ├── partials/ # Reusable template components
13
+ ├── scripts/ # Client-side JavaScript (bundled with esbuild)
14
+ ├── styles/ # SCSS/CSS stylesheets
15
+ ├── assets/ # Static files (images, fonts, etc.)
16
+ └── dist/ # Built assets (generated)
17
+ ```
18
+
19
+ ## Key concepts
20
+
21
+ - **`clovie.config.js`** drives everything: `api` for JSON endpoints, `routes` for SSR pages, `hooks` and `middleware` for request lifecycle.
22
+ - **API routes** use `{ method, path, handler }` where `handler` receives `ctx` and returns via `ctx.respond.json()`, `.html()`, `.text()`, or `.file()`.
23
+ - **SSR routes** pair a `path` with a `template` and an async `data` function that returns template variables.
24
+ - **Factories** (`defineApi`, `defineRoutes`, `defineMiddleware`, `defineHooks` from `'clovie'`) let handlers access engine services via `useContext`. You can mix raw objects and factories in the same config array.
25
+ - Registration order: **hooks -> middleware -> api -> view routes + routes**.
26
+
27
+ ## Commands
28
+
29
+ ```bash
30
+ npm run dev # development server with live reload
31
+ npm run build # build assets
32
+ npm start # production server
33
+ ```
34
+
35
+ ## Full Clovie reference
36
+
37
+ For the complete API (ctx object, factories, hooks, middleware, CLI), see `node_modules/clovie/AGENTS.md` or run `clovie skills show` to get the bundled Cursor skill.
@@ -0,0 +1,35 @@
1
+ # AGENTS — Clovie Static Site Project
2
+
3
+ This is a Clovie static site (`type: 'static'`). Clovie generates static HTML files from templates and data defined in `clovie.config.js`.
4
+
5
+ ## Project structure
6
+
7
+ ```
8
+ project/
9
+ ├── clovie.config.js # All site behavior: data, routes, render engine
10
+ ├── package.json
11
+ ├── views/ # HTML templates (Nunjucks by default)
12
+ ├── partials/ # Reusable template components
13
+ ├── scripts/ # Client-side JavaScript (bundled with esbuild)
14
+ ├── styles/ # SCSS/CSS stylesheets
15
+ ├── assets/ # Static files (images, fonts, etc.)
16
+ └── dist/ # Built output (generated)
17
+ ```
18
+
19
+ ## Key concepts
20
+
21
+ - **`clovie.config.js`** drives everything: `data` for global template variables, `routes` for dynamic page generation, `renderEngine` for the template engine.
22
+ - **Views** in `views/` are compiled to HTML with the template data. Each `.html` file becomes a page.
23
+ - **Routes** with `repeat` generate multiple pages from data (e.g. one page per blog post).
24
+ - **Partials** are registered by filename (e.g. `partials/header.html` becomes `header`).
25
+
26
+ ## Commands
27
+
28
+ ```bash
29
+ npm run dev # development server with live reload
30
+ npm run build # production build to dist/
31
+ ```
32
+
33
+ ## Full Clovie reference
34
+
35
+ For the complete API (ctx object, factories, hooks, middleware, CLI), see `node_modules/clovie/AGENTS.md` or run `clovie skills show` to get the bundled Cursor skill.
@@ -1,291 +0,0 @@
1
- # AI Development Guide for Clovie Server Projects
2
-
3
- > **For AI Assistants**: This document explains how to work with Clovie server applications. Read this to understand the project structure, configuration, and development patterns.
4
-
5
- ## What is Clovie Server Mode?
6
-
7
- Clovie Server Mode creates full-stack web applications with Express-like functionality, API endpoints, and server-side rendering. It's built on a service-oriented architecture using `@jucie.io/engine`.
8
-
9
- ## Project Structure
10
-
11
- ```
12
- project/
13
- ├── clovie.config.js # Main configuration with API routes
14
- ├── package.json # Dependencies and scripts
15
- ├── views/ # Server-rendered HTML templates
16
- ├── partials/ # Reusable template components
17
- ├── scripts/ # Client-side JavaScript
18
- ├── styles/ # SCSS/CSS stylesheets
19
- ├── assets/ # Static files (images, fonts, etc.)
20
- └── dist/ # Built assets (generated)
21
- ```
22
-
23
- ## Configuration (`clovie.config.js`)
24
-
25
- The configuration file defines API endpoints, server routes, and application behavior.
26
-
27
- ### Basic Server Configuration
28
-
29
- ```javascript
30
- export default {
31
- type: 'server', // Server application mode
32
- port: 3000, // Server port
33
-
34
- renderEngine: 'nunjucks', // Template engine
35
-
36
- data: { // Global application data
37
- app: {
38
- name: 'My App',
39
- version: '1.0.0'
40
- },
41
- nav: [
42
- { title: 'Home', url: '/' },
43
- { title: 'About', url: '/about' }
44
- ]
45
- },
46
-
47
- // API endpoints (RESTful JSON APIs)
48
- api: [
49
- {
50
- path: '/api/status',
51
- method: 'GET',
52
- handler: async (ctx) => {
53
- return ctx.respond.json({
54
- status: 'ok',
55
- timestamp: new Date().toISOString(),
56
- uptime: process.uptime()
57
- });
58
- }
59
- }
60
- ],
61
-
62
- // Server-rendered routes (SSR pages)
63
- routes: [
64
- {
65
- name: 'Homepage',
66
- path: '/',
67
- template: 'index.html',
68
- data: async ({ context }) => {
69
- return {
70
- title: 'Welcome to My App'
71
- };
72
- }
73
- }
74
- ]
75
- };
76
- ```
77
-
78
- ## API Endpoints
79
-
80
- API endpoints are defined in the `api` array and handle HTTP requests:
81
-
82
- ### Basic API Structure
83
-
84
- ```javascript
85
- {
86
- path: '/api/items',
87
- method: 'GET',
88
- handler: async (ctx) => {
89
- return ctx.respond.json({ items: [] });
90
- }
91
- }
92
- ```
93
-
94
- ### Context Object (`ctx`)
95
-
96
- The context object provides access to request data:
97
-
98
- ```javascript
99
- // Request information
100
- ctx.req.method // HTTP method (GET, POST, etc.)
101
- ctx.req.url // Full URL
102
- ctx.req.headers // Request headers
103
-
104
- // Parsed data
105
- ctx.body // Request body (JSON/form data)
106
- ctx.query // URL query parameters (?name=value)
107
- ctx.params // Route parameters (:id)
108
-
109
- // Response methods
110
- ctx.respond.json(data, status) // Send JSON response
111
- ctx.respond.text(text, status) // Send text response
112
- ctx.respond.html(html, status) // Send HTML response
113
- ctx.respond.file(path, status) // Send file response
114
- ```
115
-
116
- ### API Examples
117
-
118
- ```javascript
119
- // GET /api/items - List items
120
- {
121
- path: '/api/items',
122
- method: 'GET',
123
- handler: async (ctx) => {
124
- return ctx.respond.json({ items: [] });
125
- }
126
- }
127
-
128
- // POST /api/items - Create item
129
- {
130
- path: '/api/items',
131
- method: 'POST',
132
- handler: async (ctx) => {
133
- const { name } = ctx.body;
134
- if (!name) {
135
- return ctx.respond.json({ error: 'Name is required' }, 400);
136
- }
137
- return ctx.respond.json({ success: true, name }, 201);
138
- }
139
- }
140
-
141
- // GET /api/items/:id - Get item by ID
142
- {
143
- path: '/api/items/:id',
144
- method: 'GET',
145
- handler: async (ctx) => {
146
- const { id } = ctx.params;
147
- return ctx.respond.json({ id });
148
- }
149
- }
150
- ```
151
-
152
- ## Server-Rendered Routes
153
-
154
- Server routes generate HTML pages with server-side rendering:
155
-
156
- ### Route Structure
157
-
158
- ```javascript
159
- {
160
- name: 'Route Name',
161
- path: '/dashboard',
162
- template: 'dashboard.html',
163
- data: async ({ context }) => {
164
- return {
165
- title: 'Dashboard',
166
- user: context.req.user
167
- };
168
- }
169
- }
170
- ```
171
-
172
- The `setup` function receives `{ context, rerender }` and returns the template data. It can be async for data fetching:
173
-
174
- ```javascript
175
- {
176
- path: '/news',
177
- template: 'news.html',
178
- data: async ({ context }) => {
179
- const response = await fetch('https://api.example.com/news');
180
- const articles = await response.json();
181
- return { articles, title: 'Latest News' };
182
- }
183
- }
184
- ```
185
-
186
- ## Template Integration
187
-
188
- Templates receive data from `setup` and can use any supported template engine:
189
-
190
- ### Nunjucks Example
191
-
192
- ```html
193
- <!-- views/dashboard.html -->
194
- <h1>{{ title }}</h1>
195
-
196
- {% if items.length > 0 %}
197
- {% for item in items %}
198
- <article>
199
- <h3>{{ item.title }}</h3>
200
- <p>{{ item.excerpt }}</p>
201
- </article>
202
- {% endfor %}
203
- {% else %}
204
- <p>No items found.</p>
205
- {% endif %}
206
- ```
207
-
208
- ## Advanced Features
209
-
210
- ### Middleware Support
211
-
212
- ```javascript
213
- import express from 'express';
214
- import cors from 'cors';
215
-
216
- export default {
217
- type: 'server',
218
-
219
- middleware: [
220
- express.json(),
221
- express.urlencoded({ extended: true }),
222
- cors({ origin: 'http://localhost:3000' }),
223
-
224
- (req, res, next) => {
225
- console.log(`${new Date().toISOString()} ${req.method} ${req.url}`);
226
- next();
227
- }
228
- ],
229
-
230
- api: [...]
231
- };
232
- ```
233
-
234
- ### Server Hooks
235
-
236
- ```javascript
237
- export default {
238
- hooks: {
239
- onRequest: async (ctx) => {
240
- console.log(`${ctx.req.method} ${ctx.req.url}`);
241
- },
242
- preHandler: async (ctx) => {
243
- if (ctx.req.url.startsWith('/api/') && !ctx.req.headers.authorization) {
244
- return ctx.respond.json({ error: 'Unauthorized' }, 401);
245
- }
246
- },
247
- onError: async (ctx, error) => {
248
- console.error('Server error:', error);
249
- return ctx.respond.json({ error: 'Internal server error' }, 500);
250
- }
251
- }
252
- };
253
- ```
254
-
255
- ## Development Workflow
256
-
257
- ### Commands
258
-
259
- ```bash
260
- # Development server with live reload
261
- npm run dev
262
-
263
- # Build assets
264
- npm run build
265
-
266
- # Production server
267
- npm start
268
- ```
269
-
270
- ### File Watching
271
-
272
- Clovie automatically watches and rebuilds:
273
- - Template changes → Re-render pages
274
- - Script/style changes → Rebuild assets
275
- - Config changes → Restart server
276
-
277
- ## Best Practices
278
-
279
- ### API Design
280
- 1. **Use proper HTTP status codes** (200, 201, 400, 404, 500)
281
- 2. **Validate input data** before processing
282
- 3. **Handle errors gracefully** with meaningful messages
283
- 4. **Use consistent response formats**
284
-
285
- ### Templates
286
- 1. **Use semantic HTML**
287
- 2. **Handle missing data** with fallbacks
288
- 3. **Keep templates simple** and focused
289
- 4. **Use partials** for reusable components
290
-
291
- This guide should help you understand and work with any Clovie server project effectively.
@@ -1,301 +0,0 @@
1
- # AI Development Guide for Clovie Projects
2
-
3
- > **For AI Assistants**: This document explains how to work with Clovie projects. Read this to understand the project structure, configuration, and development patterns.
4
-
5
- ## What is Clovie?
6
-
7
- Clovie is a Node.js-based static site generator and full-stack web framework that bridges static sites and web applications. It uses a service-oriented architecture built on `@jucie.io/engine`.
8
-
9
- ## Project Structure
10
-
11
- ```
12
- project/
13
- ├── clovie.config.js # Main configuration file
14
- ├── package.json # Dependencies and scripts
15
- ├── views/ # HTML templates (server-rendered)
16
- ├── partials/ # Reusable template components
17
- ├── scripts/ # Client-side JavaScript
18
- ├── styles/ # SCSS/CSS stylesheets
19
- ├── assets/ # Static files (images, fonts, etc.)
20
- ├── data/ # Database files (server mode only)
21
- └── dist/ # Built output (generated)
22
- ```
23
-
24
- ## Configuration (`clovie.config.js`)
25
-
26
- The configuration file is the heart of any Clovie project. It defines how the project behaves.
27
-
28
- ### Static Mode Configuration
29
-
30
- ```javascript
31
- export default {
32
- type: 'static', // Generate static HTML files
33
- renderEngine: 'nunjucks', // Template engine
34
-
35
- data: { // Global data available in templates
36
- site: { title: 'My Site' },
37
- nav: [{ title: 'Home', url: '/' }]
38
- },
39
-
40
- routes: [ // Dynamic page generation
41
- {
42
- name: 'Blog Posts',
43
- path: '/posts/:slug',
44
- template: 'post.html',
45
- repeat: (data) => data.posts, // Generate page for each post
46
- data: (globalData, post) => ({ // Data for each page
47
- ...globalData,
48
- post,
49
- title: `${post.title} - ${globalData.site.title}`
50
- })
51
- }
52
- ]
53
- };
54
- ```
55
-
56
- ### Server Mode Configuration
57
-
58
- ```javascript
59
- export default {
60
- type: 'server', // Express-like web application
61
- port: 3000,
62
-
63
- data: { // Global application data
64
- app: { name: 'My App' }
65
- },
66
-
67
- api: [ // REST API endpoints
68
- {
69
- path: '/api/users',
70
- method: 'GET',
71
- handler: async (ctx, database) => {
72
- const users = database.collection('users');
73
- return ctx.respond.json({ users: users.all() });
74
- }
75
- }
76
- ],
77
-
78
- routes: [ // Server-rendered pages
79
- {
80
- name: 'User Profile',
81
- path: '/user/:id',
82
- template: 'profile.html',
83
- data: async (ctx, database) => {
84
- const user = database.collection('users').get([ctx.params.id]);
85
- return { user, title: `${user.name}'s Profile` };
86
- }
87
- }
88
- ]
89
- };
90
- ```
91
-
92
- ## Template Engines
93
-
94
- Clovie supports multiple template engines:
95
-
96
- ### Nunjucks (Default - Jinja2-like)
97
- ```html
98
- {% extends "layout.html" %}
99
- {% block content %}
100
- <h1>{{ site.title }}</h1>
101
- {% for post in posts %}
102
- <article>{{ post.title }}</article>
103
- {% endfor %}
104
- {% endblock %}
105
- ```
106
-
107
- ### Handlebars
108
- ```html
109
- {{> header}}
110
- <h1>{{site.title}}</h1>
111
- {{#each posts}}
112
- <article>{{title}}</article>
113
- {{/each}}
114
- {{> footer}}
115
- ```
116
-
117
- ### Pug
118
- ```pug
119
- extends layout
120
- block content
121
- h1= site.title
122
- each post in posts
123
- article= post.title
124
- ```
125
-
126
- ## API Endpoints (Server Mode)
127
-
128
- API endpoints receive a `ctx` (context) parameter:
129
-
130
- ```javascript
131
- {
132
- path: '/api/posts/:id',
133
- method: 'GET',
134
- handler: async (ctx) => {
135
- const { id } = ctx.params;
136
- return ctx.respond.json({ id });
137
- }
138
- }
139
- ```
140
-
141
- ### Context Object (`ctx`)
142
- - `ctx.req` - HTTP request object
143
- - `ctx.body` - Request body (parsed JSON/form data)
144
- - `ctx.query` - URL query parameters
145
- - `ctx.params` - Route parameters
146
- - `ctx.respond.json(data, status)` - Send JSON response
147
- - `ctx.respond.text(text, status)` - Send text response
148
- - `ctx.respond.html(html, status)` - Send HTML response
149
-
150
- ## Development Commands
151
-
152
- ```bash
153
- # Development server with live reload
154
- npm run dev
155
- # or
156
- clovie dev
157
-
158
- # Build for production
159
- npm run build
160
- # or
161
- clovie build
162
-
163
- # Start production server (server mode)
164
- npm start
165
- # or
166
- clovie serve
167
- ```
168
-
169
- ## Common Development Patterns
170
-
171
- ### 1. Loading External Data
172
- ```javascript
173
- export default {
174
- data: async () => {
175
- const posts = await fetch('https://api.example.com/posts')
176
- .then(r => r.json());
177
-
178
- return {
179
- site: { title: 'My Blog' },
180
- posts,
181
- categories: [...new Set(posts.map(p => p.category))]
182
- };
183
- }
184
- };
185
- ```
186
-
187
- ### 2. Dynamic Route Generation
188
- ```javascript
189
- routes: [
190
- {
191
- name: 'Blog Posts',
192
- path: '/posts/:slug',
193
- template: 'post.html',
194
- repeat: (data) => data.posts,
195
- data: (globalData, post) => ({
196
- ...globalData,
197
- post,
198
- title: `${post.title} - ${globalData.site.title}`
199
- })
200
- }
201
- ]
202
- ```
203
-
204
- ### 3. API with Validation
205
- ```javascript
206
- {
207
- path: '/api/posts',
208
- method: 'POST',
209
- handler: async (ctx) => {
210
- const { title, content } = ctx.body;
211
-
212
- if (!title || title.trim().length < 3) {
213
- return ctx.respond.json(
214
- { error: 'Title must be at least 3 characters' },
215
- 400
216
- );
217
- }
218
-
219
- return ctx.respond.json({ success: true, title: title.trim(), content }, 201);
220
- }
221
- }
222
- ```
223
-
224
- ### 4. Server-Side Rendering with Data
225
- ```javascript
226
- {
227
- name: 'News Feed',
228
- path: '/news',
229
- template: 'news.html',
230
- data: async ({ context }) => {
231
- const response = await fetch('https://api.example.com/news');
232
- const articles = await response.json();
233
- return { articles, title: 'Latest News' };
234
- }
235
- }
236
- ```
237
-
238
- ## File Watching & Live Reload
239
-
240
- Clovie automatically watches for changes in:
241
- - `views/` - Template files
242
- - `partials/` - Partial components
243
- - `scripts/` - JavaScript files
244
- - `styles/` - SCSS/CSS files
245
- - `assets/` - Static assets
246
-
247
- Changes trigger automatic rebuilds and browser refresh.
248
-
249
- ## Asset Pipeline
250
-
251
- - **Scripts**: Compiled with esbuild (or custom compiler)
252
- - **Styles**: SCSS compilation with Sass
253
- - **Assets**: Copied as-is to output directory
254
- - **Templates**: Rendered with chosen template engine
255
-
256
- ## Error Handling
257
-
258
- ### API Errors
259
- ```javascript
260
- // Return proper HTTP status codes
261
- return ctx.respond.json({ error: 'Not found' }, 404);
262
- return ctx.respond.json({ error: 'Invalid input' }, 400);
263
- ```
264
-
265
- ### Template Errors
266
- ```javascript
267
- // Handle missing data gracefully in templates
268
- {% if user %}
269
- <h1>{{ user.name }}</h1>
270
- {% else %}
271
- <h1>Unknown User</h1>
272
- {% endif %}
273
- ```
274
-
275
- ## Best Practices
276
-
277
- 1. **Use async data loading** for external APIs
278
- 2. **Validate input** in API endpoints
279
- 3. **Handle errors gracefully** with proper HTTP status codes
280
- 4. **Use semantic HTML** in templates
281
- 5. **Organize data logically** in the config file
282
- 6. **Test builds regularly** with `npm run build`
283
-
284
- ## Troubleshooting
285
-
286
- ### Common Issues
287
- - **Port already in use**: `clovie kill --port 3000`
288
- - **Template not found**: Check file paths in config
289
- - **Build failures**: Check console output for detailed errors
290
-
291
- ### Debug Mode
292
- Add `console.log()` statements in handlers and data functions to debug issues.
293
-
294
- ## Key Differences from Other Frameworks
295
-
296
- - **No client-side routing** - Uses traditional server-side rendering
297
- - **No build-time JavaScript** - Server handles all dynamic content
298
- - **Template agnostic** - Choose your preferred template engine
299
- - **Dual mode** - Same codebase can be static or server-rendered
300
-
301
- This guide should help you understand and work with any Clovie project effectively.