create-acrylblends 0.2.1 → 0.2.3
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.
- package/README.md +15 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +50 -6
- package/dist/index.js.map +1 -1
- package/docs/framework/README.md +2 -1
- package/docs/framework/UPSTREAM.md +1 -1
- package/docs/framework/api/summary.md +6 -3
- package/docs/framework/cordis/node-server.md +3 -0
- package/docs/framework/getting-started/deploy.md +133 -0
- package/docs/framework/getting-started/nodejs.md +37 -16
- package/docs/framework/guides/client-modules.md +209 -0
- package/docs/framework/guides/forms-and-sessions.md +1 -1
- package/docs/framework/guides/jsx-dom.md +6 -1
- package/docs/framework/guides/validation.md +87 -0
- package/docs/framework/helpers/streaming.md +119 -0
- package/docs/framework/helpers/testing.md +17 -0
- package/docs/framework/upstream.json +3 -3
- package/package.json +2 -2
- package/templates/chat/gitignore +5 -0
- package/templates/chat/package.json +23 -0
- package/templates/chat/src/app.ts +6 -0
- package/templates/chat/src/chat-app.ts +96 -0
- package/templates/chat/src/client/chat.tsx +115 -0
- package/templates/chat/src/client/tsconfig.json +15 -0
- package/templates/chat/src/db.ts +59 -0
- package/templates/chat/src/index.ts +22 -0
- package/templates/chat/src/llm.ts +42 -0
- package/templates/chat/src/page.tsx +38 -0
- package/templates/chat/test/chat.test.ts +153 -0
- package/templates/chat/test/server.test.ts +59 -0
- package/templates/chat/tsconfig.json +19 -0
- package/templates/nodejs/gitignore +1 -0
- package/templates/nodejs/package.json +5 -4
- package/templates/nodejs/src/app.ts +5 -5
- package/templates/nodejs/src/client/counter.tsx +12 -0
- package/templates/nodejs/src/client/tsconfig.json +15 -0
- package/templates/nodejs/src/index.ts +16 -4
- package/templates/nodejs/src/page.tsx +12 -0
- package/templates/nodejs/src/routes.ts +10 -0
- package/templates/nodejs/test/app.test.ts +10 -0
- package/templates/nodejs/test/server.test.ts +48 -0
- package/templates/nodejs/tsconfig.json +2 -1
- package/templates/notes/gitignore +5 -0
- package/templates/notes/package.json +23 -0
- package/templates/notes/src/app.ts +7 -0
- package/templates/notes/src/auth.ts +55 -0
- package/templates/notes/src/client/counter.tsx +21 -0
- package/templates/notes/src/client/tsconfig.json +15 -0
- package/templates/notes/src/db.ts +70 -0
- package/templates/notes/src/index.ts +22 -0
- package/templates/notes/src/notes-app.ts +199 -0
- package/templates/notes/src/schema.ts +38 -0
- package/templates/notes/src/views.tsx +134 -0
- package/templates/notes/test/notes.test.ts +245 -0
- package/templates/notes/test/server.test.ts +59 -0
- package/templates/notes/tsconfig.json +19 -0
package/README.md
CHANGED
|
@@ -14,6 +14,8 @@ It asks which template you want, creates `my-app`, and prints what to run next.
|
|
|
14
14
|
| --- | --- |
|
|
15
15
|
| `nodejs` | an Acryl app served with `serve()` from `acrylblends/node-server`, with a test; run with Node.js 22.19 or newer |
|
|
16
16
|
| `bun` (experimental) | the same app for Bun, with `export default app` |
|
|
17
|
+
| `notes` | a full-stack starter: accounts (scrypt, cookie session), notes in SQLite (`node:sqlite`), validated forms, search, a JSON API with a typed test client, csrf on, a test for every route |
|
|
18
|
+
| `chat` | an AI chat starter: the answer streams token by token (Server-Sent Events) from an OpenAI-compatible API (DeepSeek by default, key only from `DEEPSEEK_API_KEY`), a client component with a Stop button that also stops the request to the model, history in SQLite, tests with a mock model |
|
|
17
19
|
| `acryl-app` | a Cordis app built from plugins, with an agent that can extend it while it runs (the same app `npx acrylblends init --template agent` creates) |
|
|
18
20
|
|
|
19
21
|
Every template includes `AGENTS.md`, `CLAUDE.md` and a copy of the framework documentation in `docs/framework/`, so a coding agent working in the folder reads the API from the folder.
|
|
@@ -28,7 +30,7 @@ npm create acrylblends@latest my-app -- --template nodejs --install --pm npm
|
|
|
28
30
|
|
|
29
31
|
| Option | |
|
|
30
32
|
| --- | --- |
|
|
31
|
-
| `--template <name>` | `nodejs`, `bun` or `acryl-app` |
|
|
33
|
+
| `--template <name>` | `nodejs`, `notes`, `chat`, `bun` or `acryl-app` |
|
|
32
34
|
| `--install` | install the dependencies after creating the app |
|
|
33
35
|
| `--pm <manager>` | `npm`, `pnpm`, `yarn` or `bun` (default: the one that ran the command) |
|
|
34
36
|
| `-y`, `--yes` | ask nothing: template `nodejs`, directory `acrylblends-app` unless given |
|
|
@@ -60,3 +62,15 @@ export default app
|
|
|
60
62
|
- ACRYL: https://acryl.dev
|
|
61
63
|
|
|
62
64
|
MIT license.
|
|
65
|
+
|
|
66
|
+
## The `notes` template
|
|
67
|
+
|
|
68
|
+
`npm create acrylblends@latest my-notes -- --template notes` makes a small full-stack app, written to be read and copied:
|
|
69
|
+
|
|
70
|
+
- sign up and log in (scrypt password hashes from `node:crypto`, a random token in an `httpOnly` cookie, sessions in the database);
|
|
71
|
+
- notes in SQLite through the built-in `node:sqlite` (Node.js 22.19 or later, nothing native to install), with create, edit, delete and search forms, server-side validation with messages on the page, and a redirect (303) after each POST;
|
|
72
|
+
- a JSON API under `/api/notes` that shares the validation rules, with a test that uses the typed `testClient`;
|
|
73
|
+
- csrf protection on, a test for every route, and an `AGENTS.md` that describes the files so a coding agent can extend it;
|
|
74
|
+
- a live character counter and an instant filter written as a small script in the page. When the client components of `acrylblends/jsx/dom` can be served without a bundler (planned for 0.7.2), they will replace that script here.
|
|
75
|
+
|
|
76
|
+
`npx acrylblends add desktop` followed by `npm install` and `npm run desktop` runs it as a desktop window (see `docs/framework/getting-started/desktop.md`).
|
package/dist/index.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ export declare const CLASS = "Acryl";
|
|
|
8
8
|
export declare const CREATE = "create-acrylblends";
|
|
9
9
|
//#endregion
|
|
10
10
|
//#region src/index.d.ts
|
|
11
|
-
export declare const TEMPLATES: readonly ["nodejs", "bun", "acryl-app"];
|
|
11
|
+
export declare const TEMPLATES: readonly ["nodejs", "notes", "chat", "bun", "acryl-app"];
|
|
12
12
|
export type Template = (typeof TEMPLATES)[number];
|
|
13
13
|
export declare const PACKAGE_MANAGERS: readonly ["npm", "pnpm", "yarn", "bun"];
|
|
14
14
|
export type PackageManager = (typeof PACKAGE_MANAGERS)[number];
|
package/dist/index.js
CHANGED
|
@@ -48,6 +48,8 @@ function packageManagerInvocation(command, args, platform = process.platform, en
|
|
|
48
48
|
//#region src/index.ts
|
|
49
49
|
const TEMPLATES = [
|
|
50
50
|
"nodejs",
|
|
51
|
+
"notes",
|
|
52
|
+
"chat",
|
|
51
53
|
"bun",
|
|
52
54
|
"acryl-app"
|
|
53
55
|
];
|
|
@@ -65,7 +67,7 @@ Usage:
|
|
|
65
67
|
npm create ${PACKAGE}@latest [directory] [-- options]
|
|
66
68
|
|
|
67
69
|
Options:
|
|
68
|
-
--template <name> nodejs, bun (experimental), acryl-app (asked when not given)
|
|
70
|
+
--template <name> nodejs, notes, chat, bun (experimental), acryl-app (asked when not given)
|
|
69
71
|
--install install the dependencies after creating the app
|
|
70
72
|
--pm <manager> ${PACKAGE_MANAGERS.join(", ")} (default: the one that ran this command, else npm)
|
|
71
73
|
-y, --yes ask nothing: template nodejs unless --template is given, directory ${PACKAGE}-app
|
|
@@ -175,11 +177,15 @@ function replacePlaceholders(text, name) {
|
|
|
175
177
|
function agentsText(template, name) {
|
|
176
178
|
const run = {
|
|
177
179
|
nodejs: "npm run dev",
|
|
180
|
+
notes: "npm run dev",
|
|
181
|
+
chat: "npm run dev",
|
|
178
182
|
bun: "bun run dev"
|
|
179
183
|
}[template];
|
|
180
|
-
const desktopNote = template === "nodejs" ? `\nTo run it as a desktop window: \`npx ${PACKAGE} add desktop\`, \`npm install\`, then \`npm run desktop\` (see \`docs/framework/getting-started/desktop.md\`).` : "";
|
|
184
|
+
const desktopNote = template === "nodejs" || template === "notes" || template === "chat" ? `\nTo run it as a desktop window: \`npx ${PACKAGE} add desktop\`, \`npm install\`, then \`npm run desktop\` (see \`docs/framework/getting-started/desktop.md\`).` : "";
|
|
181
185
|
const test = {
|
|
182
186
|
nodejs: "npm test` and `npm run check",
|
|
187
|
+
notes: "npm test` and `npm run check",
|
|
188
|
+
chat: "npm test` and `npm run check",
|
|
183
189
|
bun: "bun test` and `bun run check"
|
|
184
190
|
}[template];
|
|
185
191
|
return `# ${name}
|
|
@@ -193,17 +199,53 @@ subpath (\`'${PACKAGE}/cors'\`, \`'${PACKAGE}/validator'\`, ...). Parts marked "
|
|
|
193
199
|
|
|
194
200
|
## This app
|
|
195
201
|
|
|
196
|
-
Run it with \`${run}\`. The routes are in \`${template === "bun" ? "src/index.ts" : "src/app.ts"}\`; an app is a function from \`Request\` to \`Response\`,
|
|
202
|
+
Run it with \`${run}\`. The routes are in \`${template === "bun" ? "src/index.ts" : template === "notes" ? "src/notes-app.ts" : template === "chat" ? "src/chat-app.ts" : "src/app.ts"}\`; an app is a function from \`Request\` to \`Response\`,
|
|
197
203
|
so test a route with \`await app.request('/path')\` and no server.${desktopNote}
|
|
198
204
|
|
|
205
|
+
${template === "notes" ? `
|
|
206
|
+
## Structure (a notes app: accounts, sessions, a database)
|
|
207
|
+
|
|
208
|
+
- \`src/db.ts\`: \`openDb()\` (SQLite through the built-in \`node:sqlite\`; the file is \`notes.db\` or \`$NOTES_DB\`) and \`notesStore(db)\`, the queries for notes.
|
|
209
|
+
- \`src/auth.ts\`: scrypt password hashes (\`node:crypto\`) and the \`sessions\` table; the cookie \`sid\` holds a random token.
|
|
210
|
+
- \`src/schema.ts\`: the rules for a note and for credentials. The HTML forms and the JSON API both use \`checkNote\`.
|
|
211
|
+
- \`src/views.tsx\`: the pages, as JSX components rendered to strings, and the small script for the instant filter.
|
|
212
|
+
- \`src/client/\`: client components, with their own \`tsconfig.json\` (browser types). \`counter.tsx\` is the live character counter. \`clientModules\` in \`notes-app.ts\` compiles them when the browser asks; \`npm run build\` compiles them once into \`dist/client\` for production. See \`docs/framework/guides/client-modules.md\`.
|
|
213
|
+
- \`src/notes-app.ts\`: \`createApp(db)\` (pages and forms, csrf on) and \`createApi(db)\` (the JSON API under \`/api/notes\`, chained so \`testClient\` is typed). \`src/app.ts\` is \`export default createApp()\`; tests call \`createApp(openDb(':memory:'))\`.
|
|
214
|
+
- \`test/notes.test.ts\`: a test for every route. A form POST in a test needs \`origin: 'http://localhost'\` (csrf) and the \`sid\` cookie from sign up.
|
|
215
|
+
- Forms answer an invalid input with status 400 and the same page with the messages; a successful POST redirects with 303.
|
|
216
|
+
- To add a column: change the \`CREATE TABLE\` in \`openDb\`, \`notesStore\`, \`checkNote\`, the form and the list in \`views.tsx\`, and the tests.
|
|
217
|
+
|
|
218
|
+
## Before you ship
|
|
219
|
+
|
|
220
|
+
Read \`docs/framework/getting-started/deploy.md\`. In short:
|
|
221
|
+
|
|
222
|
+
- Install with \`npm ci --omit=dev\`, run \`npm run build\` (it compiles \`src/client\` once; with \`NODE_ENV=production\` only \`dist/client\` is served), and start with \`NODE_ENV=production npm start\` (\`typescript\` stays a runtime dependency: it compiles the \`.tsx\` pages at start).
|
|
223
|
+
- The app listens on \`127.0.0.1\`; set \`HOST=0.0.0.0\` only in a container. \`PORT\` chooses the port.
|
|
224
|
+
- Put the SQLite file outside the code folder (\`NOTES_DB=/var/lib/notes/notes.db\`) and back it up.
|
|
225
|
+
- Behind an HTTPS reverse proxy set \`TRUST_PROXY=1\` and \`PUBLIC_ORIGIN=https://your.site\`, or the cookie is not \`Secure\` and csrf refuses form posts.
|
|
226
|
+
- \`npm test\` includes a test that starts the server and stops it with SIGTERM; keep it passing if you change \`src/index.ts\`.
|
|
227
|
+
` : ""}${template === "chat" ? `
|
|
228
|
+
## Structure (a chat app: a streamed answer, history in a database)
|
|
229
|
+
|
|
230
|
+
- \`src/llm.ts\`: \`Llm\`, what the app needs from a model (messages in, pieces out, an aborted signal stops the work), and \`openAiCompatible\`, which calls an OpenAI-compatible chat completions API with \`stream: true\`. The base URL is \`DEEPSEEK_BASE_URL\` (default \`https://api.deepseek.com\`), the model \`DEEPSEEK_MODEL\` (default \`deepseek-chat\`), the key **only** the environment variable \`DEEPSEEK_API_KEY\`, read at the moment of the call: never write it to a file, a response or a log.
|
|
231
|
+
- \`src/db.ts\`: \`openDb()\` (SQLite through \`node:sqlite\`; the file is \`chat.db\` or \`$CHAT_DB\`) and \`chatStore(db)\`. The routes only call \`chatStore\`; keep SQL out of them.
|
|
232
|
+
- \`src/chat-app.ts\`: \`createApp(db, llm)\`. \`POST /api/chat\` answers Server-Sent Events: \`meta\` (the conversation id), a \`token\` per piece, then \`done\` or \`error\`. The request's signal (\`c.req.raw.signal\`) goes to the model call, so a closed tab or the Stop button stops the request to the model; what had arrived is kept.
|
|
233
|
+
- \`src/client/chat.tsx\`: the client component (own \`tsconfig.json\`, browser types): sends the message with \`fetch\`, reads the events as they arrive, shows the answer growing, and aborts on Stop. \`clientModules\` compiles it when the browser asks; \`npm run build\` compiles it once into \`dist/client\`. See \`docs/framework/guides/client-modules.md\`.
|
|
234
|
+
- \`test/chat.test.ts\` tests every route with a mock \`Llm\` (never the network); keep it that way. \`test/server.test.ts\` starts the real server and stops it with a signal.
|
|
235
|
+
- To try it with a real model: \`DEEPSEEK_API_KEY=... npm run dev\`.
|
|
236
|
+
|
|
237
|
+
## Before you ship
|
|
238
|
+
|
|
239
|
+
Read \`docs/framework/getting-started/deploy.md\`. In short: \`npm ci --omit=dev\`, \`npm run build\`, \`NODE_ENV=production npm start\`; the app listens on \`127.0.0.1\` (\`HOST=0.0.0.0\` only in a container); the SQLite file goes outside the code folder (\`CHAT_DB=/var/lib/chat/chat.db\`) and is backed up; the model key is an environment variable of the service (a root-only environment file for systemd), never a file in the repository. Anyone who can reach the app can spend your key: put it behind a login or on a private network before it is public.
|
|
240
|
+
` : ""}
|
|
199
241
|
## Things that surprise people
|
|
200
242
|
|
|
201
243
|
- A page mounted at \`/x\` answers \`/x\`, not \`/x/\` (trailing slashes are strict); \`trimTrailingSlash()\` redirects.
|
|
202
244
|
- A \`json\` validator target reads the body only with a JSON \`Content-Type\`; a failure answers 400 with \`{ error, issues: [{ message, path }] }\`.
|
|
203
245
|
- \`throw new HTTPException(404, { message })\` answers an error response (plain text).
|
|
204
246
|
- \`testClient(app)\` from \`'${PACKAGE}/testing'\` types only routes chained on the \`new ${CLASS}()\` expression (\`new ${CLASS}().get(...).post(...)\`); headers such as a cookie go in the second argument of each call.
|
|
205
|
-
- **JSX:** ${template === "nodejs" ? "Write pages in `.tsx` (see `src/page.tsx`): the scripts in `package.json` run Node.js with `--import acrylblends/node-server/register`, which compiles `.tsx` with this app's own `typescript`, and `tsconfig.json` sets `jsx: react-jsx` with `jsxImportSource: acrylblends/jsx`. Render a component with `.toString()` and return it with `c.html(...)`. A command that starts the app without those scripts (a bare `node src/index.ts`) cannot load a `.tsx` file. Without a build step you can write the call JSX compiles to instead: `jsx('h1', { class: 'title' }, 'Hello')` from `'acrylblends/jsx'`, children after the props. See `docs/framework/guides/jsx.md`." : "Bun compiles `.tsx` itself: write pages in `.tsx`, render a component with `.toString()` and return it with `c.html(...)`. `jsx('h1', { class: 'title' }, 'Hello')` from `'acrylblends/jsx'` (children after the props) is the same thing without JSX syntax. See `docs/framework/guides/jsx.md`."}
|
|
206
|
-
|
|
247
|
+
- **JSX:** ${template === "nodejs" || template === "notes" || template === "chat" ? "Write pages in `.tsx` (see `src/" + (template === "notes" ? "views.tsx" : "page.tsx") + "`): the scripts in `package.json` run Node.js with `--import acrylblends/node-server/register`, which compiles `.tsx` with this app's own `typescript`, and `tsconfig.json` sets `jsx: react-jsx` with `jsxImportSource: acrylblends/jsx`. Render a component with `.toString()` and return it with `c.html(...)`. A command that starts the app without those scripts (a bare `node src/index.ts`) cannot load a `.tsx` file. Without a build step you can write the call JSX compiles to instead: `jsx('h1', { class: 'title' }, 'Hello')` from `'acrylblends/jsx'`, children after the props. See `docs/framework/guides/jsx.md`." : "Bun compiles `.tsx` itself: write pages in `.tsx`, render a component with `.toString()` and return it with `c.html(...)`. `jsx('h1', { class: 'title' }, 'Hello')` from `'acrylblends/jsx'` (children after the props) is the same thing without JSX syntax. See `docs/framework/guides/jsx.md`."}
|
|
248
|
+
${template === "nodejs" ? `- **Client components** (run in the browser) live in \`src/client/\`, which has its own \`tsconfig.json\` (DOM types, no Node types); \`clientModules\` in \`src/app.ts\` compiles them when the browser asks, and \`npm run build\` compiles them once for production. See \`src/client/counter.tsx\` and \`docs/framework/guides/client-modules.md\`.\n` : ""}
|
|
207
249
|
## Before you say you are done
|
|
208
250
|
|
|
209
251
|
\`${test}\` pass.
|
|
@@ -261,7 +303,7 @@ async function runCreate(argv, io = processIo()) {
|
|
|
261
303
|
const directory = options.directory ?? (ask ? (await ask(`Project directory (acrylblends-app): `)).trim() || `acrylblends-app` : `acrylblends-app`);
|
|
262
304
|
const target = resolve(io.cwd, directory);
|
|
263
305
|
const template = options.template ?? (ask ? await (async () => {
|
|
264
|
-
const answer = (await ask(`Which template do you want to use? (nodejs, bun (experimental), acryl-app) [nodejs]: `)).trim() || "nodejs";
|
|
306
|
+
const answer = (await ask(`Which template do you want to use? (nodejs, notes, chat, bun (experimental), acryl-app) [nodejs]: `)).trim() || "nodejs";
|
|
265
307
|
if (!isTemplate(answer)) throw new UsageError(`unknown template "${answer}" (${TEMPLATES.join(", ")})`);
|
|
266
308
|
return answer;
|
|
267
309
|
})() : "nodejs");
|
|
@@ -294,6 +336,8 @@ async function runCreate(argv, io = processIo()) {
|
|
|
294
336
|
}
|
|
295
337
|
const start = {
|
|
296
338
|
nodejs: `${pm} run dev`,
|
|
339
|
+
notes: `${pm} run dev`,
|
|
340
|
+
chat: `${pm} run dev`,
|
|
297
341
|
bun: "bun run dev",
|
|
298
342
|
"acryl-app": `${pm} run dev`
|
|
299
343
|
}[template];
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/names.ts","../src/spawn.ts","../src/index.ts"],"sourcesContent":["/**\n * The one place this package names the framework. The templates are written with `__PACKAGE__` and `__RANGE__` (the range is stamped at create time from the framework version this package carries, see `frameworkRange`), and the text of `AGENTS.md` with\n * `__PACKAGE__`, so a rename (for example to `acryl`) is a change here and in `scripts/lib/names.mjs`, which a test keeps equal.\n */\nexport const PACKAGE = 'acrylblends'\nexport const CLASS = 'Acryl'\nexport const CREATE = 'create-acrylblends'\n","import { existsSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nexport interface Invocation {\n file: string\n args: string[]\n}\n\n/**\n * How to start a package manager without the shell option (Node warns about passing args to a shell, DEP0190, and a `.cmd` shim cannot be spawned directly).\n * Off Windows the command runs as it is. On Windows npm runs as `node npm-cli.js` (the one npm is running from, else the one beside `node`); any other\n * manager goes through `cmd.exe /d /s /c <name>.cmd`, whose arguments stay an array.\n */\nexport function packageManagerInvocation(\n command: string,\n args: readonly string[],\n platform: NodeJS.Platform = process.platform,\n env: NodeJS.ProcessEnv = process.env,\n exists: (path: string) => boolean = existsSync,\n execPath: string = process.execPath,\n): Invocation {\n if (platform !== 'win32') return { file: command, args: [...args] }\n if (command === 'npm') {\n const running = env.npm_execpath\n const cli =\n running !== undefined && /npm-cli\\.c?js$/.test(running)\n ? running\n : join(dirname(execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js')\n if (exists(cli)) return { file: execPath, args: [cli, ...args] }\n }\n return { file: env.ComSpec ?? 'cmd.exe', args: ['/d', '/s', '/c', `${command}.cmd`, ...args] }\n}\n","import { spawn } from 'node:child_process'\nimport { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { basename, dirname, join, resolve } from 'node:path'\nimport { createInterface } from 'node:readline/promises'\nimport { fileURLToPath } from 'node:url'\nimport { parseArgs } from 'node:util'\nimport { CLASS, CREATE, PACKAGE } from './names'\nimport { packageManagerInvocation } from './spawn'\n\nexport { CLASS, CREATE, PACKAGE }\n\nexport const TEMPLATES = ['nodejs', 'bun', 'acryl-app'] as const\nexport type Template = (typeof TEMPLATES)[number]\nexport const PACKAGE_MANAGERS = ['npm', 'pnpm', 'yarn', 'bun'] as const\nexport type PackageManager = (typeof PACKAGE_MANAGERS)[number]\n\n/** The version of this package. */\nexport const VERSION: string = (\n createRequire(import.meta.url)('../package.json') as { version: string }\n).version\n\nexport const HELP = `${CREATE} ${VERSION} - create an ${CLASS} app\n\nUsage:\n npm create ${PACKAGE}@latest [directory] [-- options]\n\nOptions:\n --template <name> nodejs, bun (experimental), acryl-app (asked when not given)\n --install install the dependencies after creating the app\n --pm <manager> ${PACKAGE_MANAGERS.join(', ')} (default: the one that ran this command, else npm)\n -y, --yes ask nothing: template nodejs unless --template is given, directory ${PACKAGE}-app\n -h, --help show this help\n -v, --version show the version\n`\n\n/** A command line mistake. The command prints it with the help text and exits 2. */\nexport class UsageError extends Error {\n override name = 'UsageError'\n}\n\nexport interface Io {\n stdout: { write(text: string): unknown }\n stderr: { write(text: string): unknown }\n cwd: string\n env: Record<string, string | undefined>\n /** Ask one question; `undefined` when there is no terminal to ask on. */\n ask: ((question: string) => Promise<string>) | undefined\n /** Run a program, showing its output; resolves to the exit code. */\n run(command: string, args: string[], cwd: string): Promise<number>\n}\n\nexport function processIo(): Io {\n const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY)\n return {\n stdout: process.stdout,\n stderr: process.stderr,\n cwd: process.cwd(),\n env: process.env,\n ask: interactive\n ? async (question) => {\n const rl = createInterface({ input: process.stdin, output: process.stdout })\n try {\n return await rl.question(question)\n } finally {\n rl.close()\n }\n }\n : undefined,\n run: (command, args, cwd) =>\n new Promise((done) => {\n const invocation = packageManagerInvocation(command, args)\n const child = spawn(invocation.file, invocation.args, { cwd, stdio: 'inherit' })\n child.on('error', () => done(1))\n child.on('exit', (code) => done(code ?? 1))\n }),\n }\n}\n\nexport interface CreateOptions {\n directory: string | undefined\n template: Template | undefined\n install: boolean\n pm: PackageManager | undefined\n yes: boolean\n}\n\nexport function isTemplate(value: string): value is Template {\n return (TEMPLATES as readonly string[]).includes(value)\n}\n\nexport function parseCreateOptions(argv: readonly string[]): CreateOptions {\n let parsed: ReturnType<typeof parse>\n try {\n parsed = parse(argv)\n } catch (error) {\n throw new UsageError((error as Error).message)\n }\n const { values, positionals } = parsed\n if (positionals.length > 1) throw new UsageError('takes at most one directory')\n if (values.template !== undefined && !isTemplate(values.template))\n throw new UsageError(`unknown template \"${values.template}\" (${TEMPLATES.join(', ')})`)\n if (values.pm !== undefined && !(PACKAGE_MANAGERS as readonly string[]).includes(values.pm))\n throw new UsageError(`unknown package manager \"${values.pm}\" (${PACKAGE_MANAGERS.join(', ')})`)\n return {\n directory: positionals[0],\n template: values.template as Template | undefined,\n install: values.install === true,\n pm: values.pm as PackageManager | undefined,\n yes: values.yes === true,\n }\n}\n\nconst parse = (argv: readonly string[]) =>\n parseArgs({\n args: [...argv],\n allowPositionals: true,\n strict: true,\n options: {\n template: { type: 'string' },\n install: { type: 'boolean' },\n pm: { type: 'string' },\n yes: { type: 'boolean', short: 'y' },\n },\n })\n\n/** A valid package name from a directory name: lower case letters, digits and dashes. */\nexport function nameFrom(directory: string): string {\n const name = basename(resolve(directory))\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, '-')\n .replace(/^[^a-z]+/, '')\n .replace(/-+$/g, '')\n return name === '' ? 'acryl-app' : name\n}\n\nfunction walkUp(from: string, test: (dir: string) => string | undefined): string {\n let dir = from\n for (;;) {\n const found = test(dir)\n if (found) return found\n const parent = dirname(dir)\n if (parent === dir) throw new Error(`${CREATE} cannot find its files`)\n dir = parent\n }\n}\nconst here = dirname(fileURLToPath(import.meta.url))\nconst templatesRoot = () =>\n walkUp(here, (d) =>\n existsSync(join(d, 'templates', 'nodejs')) ? join(d, 'templates') : undefined,\n )\n/** The framework docs: the copy `prepack` puts in the package, or `docs/framework` of the repository. */\nconst docsRoot = () =>\n walkUp(here, (d) =>\n existsSync(join(d, 'docs', 'framework', 'README.md'))\n ? join(d, 'docs', 'framework')\n : undefined,\n )\n\n/**\n * The range a created app asks for: the framework version this package was released with, so a new app depends on the release that made it (and gets what that release's\n * commands can do), never an older one. A caret range, so it also takes the newer patch releases.\n */\nexport function frameworkRange(): string {\n const file = createRequire(import.meta.url).resolve(`${PACKAGE}/package.json`)\n return `^${(JSON.parse(readFileSync(file, 'utf8')) as { version: string }).version}`\n}\n\nexport function replacePlaceholders(text: string, name: string): string {\n return text\n .replaceAll('__APP_NAME__', name)\n .replaceAll('__PACKAGE__', PACKAGE)\n .replaceAll('__CLASS__', CLASS)\n .replaceAll('__RANGE__', frameworkRange())\n}\n\n/** The guide for a coding agent in a created app: where the API is, how to run it, what must pass. */\nexport function agentsText(template: Exclude<Template, 'acryl-app'>, name: string): string {\n const run = { nodejs: 'npm run dev', bun: 'bun run dev' }[template]\n const desktopNote =\n template === 'nodejs'\n ? `\\nTo run it as a desktop window: \\`npx ${PACKAGE} add desktop\\`, \\`npm install\\`, then \\`npm run desktop\\` (see \\`docs/framework/getting-started/desktop.md\\`).`\n : ''\n const test = {\n nodejs: 'npm test` and `npm run check',\n bun: 'bun test` and `bun run check',\n }[template]\n const jsxNote =\n template === 'nodejs'\n ? \"Write pages in `.tsx` (see `src/page.tsx`): the scripts in `package.json` run Node.js with `--import acrylblends/node-server/register`, which compiles `.tsx` with this app's own `typescript`, and `tsconfig.json` sets `jsx: react-jsx` with `jsxImportSource: acrylblends/jsx`. Render a component with `.toString()` and return it with `c.html(...)`. A command that starts the app without those scripts (a bare `node src/index.ts`) cannot load a `.tsx` file. Without a build step you can write the call JSX compiles to instead: `jsx('h1', { class: 'title' }, 'Hello')` from `'acrylblends/jsx'`, children after the props. See `docs/framework/guides/jsx.md`.\"\n : \"Bun compiles `.tsx` itself: write pages in `.tsx`, render a component with `.toString()` and return it with `c.html(...)`. `jsx('h1', { class: 'title' }, 'Hello')` from `'acrylblends/jsx'` (children after the props) is the same thing without JSX syntax. See `docs/framework/guides/jsx.md`.\"\n return `# ${name}\n\nAn ${CLASS} app (${template}${template === 'bun' ? ', experimental' : ''}): handlers over the Web Standard \\`Request\\` and \\`Response\\`, from the \\`${PACKAGE}\\` package.\n\n## The framework's API is in \\`docs/framework/\\`\n\nStart at \\`docs/framework/README.md\\`; \\`api/summary.md\\` is the one-page summary. Import the class from \\`'${PACKAGE}'\\` and each middleware or helper from its own\nsubpath (\\`'${PACKAGE}/cors'\\`, \\`'${PACKAGE}/validator'\\`, ...). Parts marked \"not yet available\" in the docs are not in the package yet.\n\n## This app\n\nRun it with \\`${run}\\`. The routes are in \\`${template === 'bun' ? 'src/index.ts' : 'src/app.ts'}\\`; an app is a function from \\`Request\\` to \\`Response\\`,\nso test a route with \\`await app.request('/path')\\` and no server.${desktopNote}\n\n## Things that surprise people\n\n- A page mounted at \\`/x\\` answers \\`/x\\`, not \\`/x/\\` (trailing slashes are strict); \\`trimTrailingSlash()\\` redirects.\n- A \\`json\\` validator target reads the body only with a JSON \\`Content-Type\\`; a failure answers 400 with \\`{ error, issues: [{ message, path }] }\\`.\n- \\`throw new HTTPException(404, { message })\\` answers an error response (plain text).\n- \\`testClient(app)\\` from \\`'${PACKAGE}/testing'\\` types only routes chained on the \\`new ${CLASS}()\\` expression (\\`new ${CLASS}().get(...).post(...)\\`); headers such as a cookie go in the second argument of each call.\n- **JSX:** ${jsxNote}\n\n## Before you say you are done\n\n\\`${test}\\` pass.\n`\n}\n\nfunction copyDocs(target: string): void {\n const filter = (path: string) => !/(upstream\\.json|UPSTREAM\\.md)$/.test(path)\n mkdirSync(join(target, 'docs'), { recursive: true })\n cpSync(docsRoot(), join(target, 'docs', 'framework'), { recursive: true, filter })\n}\n\nfunction copyTemplate(\n template: Exclude<Template, 'acryl-app'>,\n target: string,\n name: string,\n): string[] {\n const written: string[] = []\n const walk = (from: string, to: string, prefix: string) => {\n mkdirSync(to, { recursive: true })\n for (const entry of readdirSync(from, { withFileTypes: true })) {\n const targetName = prefix === '' && entry.name === 'gitignore' ? '.gitignore' : entry.name\n if (entry.isDirectory())\n walk(join(from, entry.name), join(to, targetName), `${prefix}${entry.name}/`)\n else {\n writeFileSync(\n join(to, targetName),\n replacePlaceholders(readFileSync(join(from, entry.name), 'utf8'), name),\n )\n written.push(`${prefix}${targetName}`)\n }\n }\n }\n walk(join(templatesRoot(), template), target, '')\n writeFileSync(join(target, 'AGENTS.md'), agentsText(template, name))\n writeFileSync(join(target, 'CLAUDE.md'), '@AGENTS.md\\n')\n copyDocs(target)\n return written\n}\n\nconst isEmpty = (directory: string) => !existsSync(directory) || readdirSync(directory).length === 0\n\n/** The `acrylblends` command of the installed framework package, which creates the `acryl-app` template. */\nfunction acrylblendsBin(): string {\n const pkgFile = createRequire(import.meta.url).resolve(`${PACKAGE}/package.json`)\n const pkg = JSON.parse(readFileSync(pkgFile, 'utf8')) as { bin?: string | Record<string, string> }\n const bin = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.[PACKAGE]\n if (!bin) throw new Error(`${PACKAGE} has no command to create an app with`)\n return join(dirname(pkgFile), bin)\n}\n\n/** Create the app. Returns the exit code: 0 done, 1 refused or failed, 2 a usage error. Never calls `process.exit`. */\nexport async function runCreate(argv: readonly string[], io: Io = processIo()): Promise<number> {\n try {\n if (argv.includes('-h') || argv.includes('--help')) {\n io.stdout.write(HELP)\n return 0\n }\n if (argv.includes('-v') || argv.includes('--version')) {\n io.stdout.write(`${VERSION}\\n`)\n return 0\n }\n const options = parseCreateOptions(argv)\n const ask = options.yes ? undefined : io.ask\n const directory =\n options.directory ??\n (ask\n ? (await ask(`Project directory (${PACKAGE}-app): `)).trim() || `${PACKAGE}-app`\n : `${PACKAGE}-app`)\n const target = resolve(io.cwd, directory)\n const template: Template =\n options.template ??\n (ask\n ? await (async () => {\n const answer =\n (\n await ask(\n `Which template do you want to use? (nodejs, bun (experimental), acryl-app) [nodejs]: `,\n )\n ).trim() || 'nodejs'\n if (!isTemplate(answer))\n throw new UsageError(`unknown template \"${answer}\" (${TEMPLATES.join(', ')})`)\n return answer\n })()\n : 'nodejs')\n if (!isEmpty(target)) {\n io.stderr.write(`error: ${target} is not empty; nothing was changed\\n`)\n return 1\n }\n const name = nameFrom(target)\n if (template === 'acryl-app') {\n const code = await io.run(\n process.execPath,\n [acrylblendsBin(), 'init', target, '--template', 'agent', '--name', name, '--yes'],\n io.cwd,\n )\n if (code !== 0) return 1\n } else {\n const files = copyTemplate(template, target, name)\n io.stdout.write(\n `created ${name} (${template}) in ${target}: ${files.length} files, ${CLASS} docs in docs/framework\\n`,\n )\n }\n const pm: PackageManager =\n options.pm ??\n ((PACKAGE_MANAGERS as readonly string[]).find((m) =>\n (io.env.npm_config_user_agent ?? '').startsWith(`${m}/`),\n ) as PackageManager | undefined) ??\n 'npm'\n if (options.install) {\n if ((await io.run(pm, ['install'], target)) !== 0) {\n io.stderr.write(`error: ${pm} install failed; run it yourself in ${directory}\\n`)\n return 1\n }\n }\n const start = {\n nodejs: `${pm} run dev`,\n bun: 'bun run dev',\n 'acryl-app': `${pm} run dev`,\n }[template]\n io.stdout.write(\n `\\nNext:\\n cd ${directory}\\n${options.install ? '' : ` ${pm} install\\n`} ${start}\\n`,\n )\n return 0\n } catch (error) {\n if (error instanceof UsageError) {\n io.stderr.write(`error: ${error.message}\\n\\n${HELP}`)\n return 2\n }\n io.stderr.write(`error: ${(error as Error).message}\\n`)\n return 1\n }\n}\n"],"mappings":";;;;;;;;;;;;AAIA,MAAa,UAAU;AACvB,MAAa,QAAQ;AACrB,MAAa,SAAS;;;;;;;;ACOtB,SAAgB,yBACd,SACA,MACA,WAA4B,QAAQ,UACpC,MAAyB,QAAQ,KACjC,SAAoC,YACpC,WAAmB,QAAQ,UACf;CACZ,IAAI,aAAa,SAAS,OAAO;EAAE,MAAM;EAAS,MAAM,CAAC,GAAG,IAAI;CAAE;CAClE,IAAI,YAAY,OAAO;EACrB,MAAM,UAAU,IAAI;EACpB,MAAM,MACJ,YAAY,KAAA,KAAa,iBAAiB,KAAK,OAAO,IAClD,UACA,KAAK,QAAQ,QAAQ,GAAG,gBAAgB,OAAO,OAAO,YAAY;EACxE,IAAI,OAAO,GAAG,GAAG,OAAO;GAAE,MAAM;GAAU,MAAM,CAAC,KAAK,GAAG,IAAI;EAAE;CACjE;CACA,OAAO;EAAE,MA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AI;GACjD,GAAG,OAAO,MACR,WAAW,KAAK,IAAI,SAAS,OAAO,OAAO,IAAI,MAAM,OAAO,UAAU,MAAM,0BAC9E;EACF;EACA,MAAM,KACJ,QAAQ,MACN,iBAAuC,MAAM,OAC5C,GAAG,IAAI,yBAAyB,GAAA,CAAI,WAAW,GAAG,EAAE,EAAE,CACzD,KACA;EACF,IAAI,QAAQ,SACL;OAAA,MAAM,GAAG,IAAI,IAAI,CAAC,SAAS,GAAG,MAAM,MAAO,GAAG;IACjD,GAAG,OAAO,MAAM,UAAU,GAAG,sCAAsC,UAAU,GAAG;IAChF,OAAO;GACT;;EAEF,MAAM,QAAQ;GACZ,QAAQ,GAAG,GAAG;GACd,KAAK;GACL,aAAa,GAAG,GAAG;EACrB,EAAE;EACF,GAAG,OAAO,MACR,iBAAiB,UAAU,IAAI,QAAQ,UAAU,KAAK,KAAK,GAAG,YAAY,IAAI,MAAM,GACtF;EACA,OAAO;CACT,SAAS,OAAO;EACd,IAAI,iBAAiB,YAAY;GAC/B,GAAG,OAAO,MAAM,UAAU,MAAM,QAAQ,MAAM,MAAM;GACpD,OAAO;EACT;EACA,GAAG,OAAO,MAAM,UAAW,MAAgB,QAAQ,GAAG;EACtD,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/names.ts","../src/spawn.ts","../src/index.ts"],"sourcesContent":["/**\n * The one place this package names the framework. The templates are written with `__PACKAGE__` and `__RANGE__` (the range is stamped at create time from the framework version this package carries, see `frameworkRange`), and the text of `AGENTS.md` with\n * `__PACKAGE__`, so a rename (for example to `acryl`) is a change here and in `scripts/lib/names.mjs`, which a test keeps equal.\n */\nexport const PACKAGE = 'acrylblends'\nexport const CLASS = 'Acryl'\nexport const CREATE = 'create-acrylblends'\n","import { existsSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nexport interface Invocation {\n file: string\n args: string[]\n}\n\n/**\n * How to start a package manager without the shell option (Node warns about passing args to a shell, DEP0190, and a `.cmd` shim cannot be spawned directly).\n * Off Windows the command runs as it is. On Windows npm runs as `node npm-cli.js` (the one npm is running from, else the one beside `node`); any other\n * manager goes through `cmd.exe /d /s /c <name>.cmd`, whose arguments stay an array.\n */\nexport function packageManagerInvocation(\n command: string,\n args: readonly string[],\n platform: NodeJS.Platform = process.platform,\n env: NodeJS.ProcessEnv = process.env,\n exists: (path: string) => boolean = existsSync,\n execPath: string = process.execPath,\n): Invocation {\n if (platform !== 'win32') return { file: command, args: [...args] }\n if (command === 'npm') {\n const running = env.npm_execpath\n const cli =\n running !== undefined && /npm-cli\\.c?js$/.test(running)\n ? running\n : join(dirname(execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js')\n if (exists(cli)) return { file: execPath, args: [cli, ...args] }\n }\n return { file: env.ComSpec ?? 'cmd.exe', args: ['/d', '/s', '/c', `${command}.cmd`, ...args] }\n}\n","import { spawn } from 'node:child_process'\nimport { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { basename, dirname, join, resolve } from 'node:path'\nimport { createInterface } from 'node:readline/promises'\nimport { fileURLToPath } from 'node:url'\nimport { parseArgs } from 'node:util'\nimport { CLASS, CREATE, PACKAGE } from './names'\nimport { packageManagerInvocation } from './spawn'\n\nexport { CLASS, CREATE, PACKAGE }\n\nexport const TEMPLATES = ['nodejs', 'notes', 'chat', 'bun', 'acryl-app'] as const\nexport type Template = (typeof TEMPLATES)[number]\nexport const PACKAGE_MANAGERS = ['npm', 'pnpm', 'yarn', 'bun'] as const\nexport type PackageManager = (typeof PACKAGE_MANAGERS)[number]\n\n/** The version of this package. */\nexport const VERSION: string = (\n createRequire(import.meta.url)('../package.json') as { version: string }\n).version\n\nexport const HELP = `${CREATE} ${VERSION} - create an ${CLASS} app\n\nUsage:\n npm create ${PACKAGE}@latest [directory] [-- options]\n\nOptions:\n --template <name> nodejs, notes, chat, bun (experimental), acryl-app (asked when not given)\n --install install the dependencies after creating the app\n --pm <manager> ${PACKAGE_MANAGERS.join(', ')} (default: the one that ran this command, else npm)\n -y, --yes ask nothing: template nodejs unless --template is given, directory ${PACKAGE}-app\n -h, --help show this help\n -v, --version show the version\n`\n\n/** A command line mistake. The command prints it with the help text and exits 2. */\nexport class UsageError extends Error {\n override name = 'UsageError'\n}\n\nexport interface Io {\n stdout: { write(text: string): unknown }\n stderr: { write(text: string): unknown }\n cwd: string\n env: Record<string, string | undefined>\n /** Ask one question; `undefined` when there is no terminal to ask on. */\n ask: ((question: string) => Promise<string>) | undefined\n /** Run a program, showing its output; resolves to the exit code. */\n run(command: string, args: string[], cwd: string): Promise<number>\n}\n\nexport function processIo(): Io {\n const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY)\n return {\n stdout: process.stdout,\n stderr: process.stderr,\n cwd: process.cwd(),\n env: process.env,\n ask: interactive\n ? async (question) => {\n const rl = createInterface({ input: process.stdin, output: process.stdout })\n try {\n return await rl.question(question)\n } finally {\n rl.close()\n }\n }\n : undefined,\n run: (command, args, cwd) =>\n new Promise((done) => {\n const invocation = packageManagerInvocation(command, args)\n const child = spawn(invocation.file, invocation.args, { cwd, stdio: 'inherit' })\n child.on('error', () => done(1))\n child.on('exit', (code) => done(code ?? 1))\n }),\n }\n}\n\nexport interface CreateOptions {\n directory: string | undefined\n template: Template | undefined\n install: boolean\n pm: PackageManager | undefined\n yes: boolean\n}\n\nexport function isTemplate(value: string): value is Template {\n return (TEMPLATES as readonly string[]).includes(value)\n}\n\nexport function parseCreateOptions(argv: readonly string[]): CreateOptions {\n let parsed: ReturnType<typeof parse>\n try {\n parsed = parse(argv)\n } catch (error) {\n throw new UsageError((error as Error).message)\n }\n const { values, positionals } = parsed\n if (positionals.length > 1) throw new UsageError('takes at most one directory')\n if (values.template !== undefined && !isTemplate(values.template))\n throw new UsageError(`unknown template \"${values.template}\" (${TEMPLATES.join(', ')})`)\n if (values.pm !== undefined && !(PACKAGE_MANAGERS as readonly string[]).includes(values.pm))\n throw new UsageError(`unknown package manager \"${values.pm}\" (${PACKAGE_MANAGERS.join(', ')})`)\n return {\n directory: positionals[0],\n template: values.template as Template | undefined,\n install: values.install === true,\n pm: values.pm as PackageManager | undefined,\n yes: values.yes === true,\n }\n}\n\nconst parse = (argv: readonly string[]) =>\n parseArgs({\n args: [...argv],\n allowPositionals: true,\n strict: true,\n options: {\n template: { type: 'string' },\n install: { type: 'boolean' },\n pm: { type: 'string' },\n yes: { type: 'boolean', short: 'y' },\n },\n })\n\n/** A valid package name from a directory name: lower case letters, digits and dashes. */\nexport function nameFrom(directory: string): string {\n const name = basename(resolve(directory))\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, '-')\n .replace(/^[^a-z]+/, '')\n .replace(/-+$/g, '')\n return name === '' ? 'acryl-app' : name\n}\n\nfunction walkUp(from: string, test: (dir: string) => string | undefined): string {\n let dir = from\n for (;;) {\n const found = test(dir)\n if (found) return found\n const parent = dirname(dir)\n if (parent === dir) throw new Error(`${CREATE} cannot find its files`)\n dir = parent\n }\n}\nconst here = dirname(fileURLToPath(import.meta.url))\nconst templatesRoot = () =>\n walkUp(here, (d) =>\n existsSync(join(d, 'templates', 'nodejs')) ? join(d, 'templates') : undefined,\n )\n/** The framework docs: the copy `prepack` puts in the package, or `docs/framework` of the repository. */\nconst docsRoot = () =>\n walkUp(here, (d) =>\n existsSync(join(d, 'docs', 'framework', 'README.md'))\n ? join(d, 'docs', 'framework')\n : undefined,\n )\n\n/**\n * The range a created app asks for: the framework version this package was released with, so a new app depends on the release that made it (and gets what that release's\n * commands can do), never an older one. A caret range, so it also takes the newer patch releases.\n */\nexport function frameworkRange(): string {\n const file = createRequire(import.meta.url).resolve(`${PACKAGE}/package.json`)\n return `^${(JSON.parse(readFileSync(file, 'utf8')) as { version: string }).version}`\n}\n\nexport function replacePlaceholders(text: string, name: string): string {\n return text\n .replaceAll('__APP_NAME__', name)\n .replaceAll('__PACKAGE__', PACKAGE)\n .replaceAll('__CLASS__', CLASS)\n .replaceAll('__RANGE__', frameworkRange())\n}\n\n/** The guide for a coding agent in a created app: where the API is, how to run it, what must pass. */\nexport function agentsText(template: Exclude<Template, 'acryl-app'>, name: string): string {\n const run = {\n nodejs: 'npm run dev',\n notes: 'npm run dev',\n chat: 'npm run dev',\n bun: 'bun run dev',\n }[template]\n const desktopNote =\n template === 'nodejs' || template === 'notes' || template === 'chat'\n ? `\\nTo run it as a desktop window: \\`npx ${PACKAGE} add desktop\\`, \\`npm install\\`, then \\`npm run desktop\\` (see \\`docs/framework/getting-started/desktop.md\\`).`\n : ''\n const test = {\n nodejs: 'npm test` and `npm run check',\n notes: 'npm test` and `npm run check',\n chat: 'npm test` and `npm run check',\n bun: 'bun test` and `bun run check',\n }[template]\n const jsxNote =\n template === 'nodejs' || template === 'notes' || template === 'chat'\n ? 'Write pages in `.tsx` (see `src/' +\n (template === 'notes' ? 'views.tsx' : 'page.tsx') +\n \"`): the scripts in `package.json` run Node.js with `--import acrylblends/node-server/register`, which compiles `.tsx` with this app's own `typescript`, and `tsconfig.json` sets `jsx: react-jsx` with `jsxImportSource: acrylblends/jsx`. Render a component with `.toString()` and return it with `c.html(...)`. A command that starts the app without those scripts (a bare `node src/index.ts`) cannot load a `.tsx` file. Without a build step you can write the call JSX compiles to instead: `jsx('h1', { class: 'title' }, 'Hello')` from `'acrylblends/jsx'`, children after the props. See `docs/framework/guides/jsx.md`.\"\n : \"Bun compiles `.tsx` itself: write pages in `.tsx`, render a component with `.toString()` and return it with `c.html(...)`. `jsx('h1', { class: 'title' }, 'Hello')` from `'acrylblends/jsx'` (children after the props) is the same thing without JSX syntax. See `docs/framework/guides/jsx.md`.\"\n const clientNote =\n template === 'nodejs'\n ? `- **Client components** (run in the browser) live in \\`src/client/\\`, which has its own \\`tsconfig.json\\` (DOM types, no Node types); \\`clientModules\\` in \\`src/app.ts\\` compiles them when the browser asks, and \\`npm run build\\` compiles them once for production. See \\`src/client/counter.tsx\\` and \\`docs/framework/guides/client-modules.md\\`.\\n`\n : ''\n const chatStructure =\n template === 'chat'\n ? `\n## Structure (a chat app: a streamed answer, history in a database)\n\n- \\`src/llm.ts\\`: \\`Llm\\`, what the app needs from a model (messages in, pieces out, an aborted signal stops the work), and \\`openAiCompatible\\`, which calls an OpenAI-compatible chat completions API with \\`stream: true\\`. The base URL is \\`DEEPSEEK_BASE_URL\\` (default \\`https://api.deepseek.com\\`), the model \\`DEEPSEEK_MODEL\\` (default \\`deepseek-chat\\`), the key **only** the environment variable \\`DEEPSEEK_API_KEY\\`, read at the moment of the call: never write it to a file, a response or a log.\n- \\`src/db.ts\\`: \\`openDb()\\` (SQLite through \\`node:sqlite\\`; the file is \\`chat.db\\` or \\`$CHAT_DB\\`) and \\`chatStore(db)\\`. The routes only call \\`chatStore\\`; keep SQL out of them.\n- \\`src/chat-app.ts\\`: \\`createApp(db, llm)\\`. \\`POST /api/chat\\` answers Server-Sent Events: \\`meta\\` (the conversation id), a \\`token\\` per piece, then \\`done\\` or \\`error\\`. The request's signal (\\`c.req.raw.signal\\`) goes to the model call, so a closed tab or the Stop button stops the request to the model; what had arrived is kept.\n- \\`src/client/chat.tsx\\`: the client component (own \\`tsconfig.json\\`, browser types): sends the message with \\`fetch\\`, reads the events as they arrive, shows the answer growing, and aborts on Stop. \\`clientModules\\` compiles it when the browser asks; \\`npm run build\\` compiles it once into \\`dist/client\\`. See \\`docs/framework/guides/client-modules.md\\`.\n- \\`test/chat.test.ts\\` tests every route with a mock \\`Llm\\` (never the network); keep it that way. \\`test/server.test.ts\\` starts the real server and stops it with a signal.\n- To try it with a real model: \\`DEEPSEEK_API_KEY=... npm run dev\\`.\n\n## Before you ship\n\nRead \\`docs/framework/getting-started/deploy.md\\`. In short: \\`npm ci --omit=dev\\`, \\`npm run build\\`, \\`NODE_ENV=production npm start\\`; the app listens on \\`127.0.0.1\\` (\\`HOST=0.0.0.0\\` only in a container); the SQLite file goes outside the code folder (\\`CHAT_DB=/var/lib/chat/chat.db\\`) and is backed up; the model key is an environment variable of the service (a root-only environment file for systemd), never a file in the repository. Anyone who can reach the app can spend your key: put it behind a login or on a private network before it is public.\n`\n : ''\n const notesStructure =\n template === 'notes'\n ? `\n## Structure (a notes app: accounts, sessions, a database)\n\n- \\`src/db.ts\\`: \\`openDb()\\` (SQLite through the built-in \\`node:sqlite\\`; the file is \\`notes.db\\` or \\`$NOTES_DB\\`) and \\`notesStore(db)\\`, the queries for notes.\n- \\`src/auth.ts\\`: scrypt password hashes (\\`node:crypto\\`) and the \\`sessions\\` table; the cookie \\`sid\\` holds a random token.\n- \\`src/schema.ts\\`: the rules for a note and for credentials. The HTML forms and the JSON API both use \\`checkNote\\`.\n- \\`src/views.tsx\\`: the pages, as JSX components rendered to strings, and the small script for the instant filter.\n- \\`src/client/\\`: client components, with their own \\`tsconfig.json\\` (browser types). \\`counter.tsx\\` is the live character counter. \\`clientModules\\` in \\`notes-app.ts\\` compiles them when the browser asks; \\`npm run build\\` compiles them once into \\`dist/client\\` for production. See \\`docs/framework/guides/client-modules.md\\`.\n- \\`src/notes-app.ts\\`: \\`createApp(db)\\` (pages and forms, csrf on) and \\`createApi(db)\\` (the JSON API under \\`/api/notes\\`, chained so \\`testClient\\` is typed). \\`src/app.ts\\` is \\`export default createApp()\\`; tests call \\`createApp(openDb(':memory:'))\\`.\n- \\`test/notes.test.ts\\`: a test for every route. A form POST in a test needs \\`origin: 'http://localhost'\\` (csrf) and the \\`sid\\` cookie from sign up.\n- Forms answer an invalid input with status 400 and the same page with the messages; a successful POST redirects with 303.\n- To add a column: change the \\`CREATE TABLE\\` in \\`openDb\\`, \\`notesStore\\`, \\`checkNote\\`, the form and the list in \\`views.tsx\\`, and the tests.\n\n## Before you ship\n\nRead \\`docs/framework/getting-started/deploy.md\\`. In short:\n\n- Install with \\`npm ci --omit=dev\\`, run \\`npm run build\\` (it compiles \\`src/client\\` once; with \\`NODE_ENV=production\\` only \\`dist/client\\` is served), and start with \\`NODE_ENV=production npm start\\` (\\`typescript\\` stays a runtime dependency: it compiles the \\`.tsx\\` pages at start).\n- The app listens on \\`127.0.0.1\\`; set \\`HOST=0.0.0.0\\` only in a container. \\`PORT\\` chooses the port.\n- Put the SQLite file outside the code folder (\\`NOTES_DB=/var/lib/notes/notes.db\\`) and back it up.\n- Behind an HTTPS reverse proxy set \\`TRUST_PROXY=1\\` and \\`PUBLIC_ORIGIN=https://your.site\\`, or the cookie is not \\`Secure\\` and csrf refuses form posts.\n- \\`npm test\\` includes a test that starts the server and stops it with SIGTERM; keep it passing if you change \\`src/index.ts\\`.\n`\n : ''\n return `# ${name}\n\nAn ${CLASS} app (${template}${template === 'bun' ? ', experimental' : ''}): handlers over the Web Standard \\`Request\\` and \\`Response\\`, from the \\`${PACKAGE}\\` package.\n\n## The framework's API is in \\`docs/framework/\\`\n\nStart at \\`docs/framework/README.md\\`; \\`api/summary.md\\` is the one-page summary. Import the class from \\`'${PACKAGE}'\\` and each middleware or helper from its own\nsubpath (\\`'${PACKAGE}/cors'\\`, \\`'${PACKAGE}/validator'\\`, ...). Parts marked \"not yet available\" in the docs are not in the package yet.\n\n## This app\n\nRun it with \\`${run}\\`. The routes are in \\`${template === 'bun' ? 'src/index.ts' : template === 'notes' ? 'src/notes-app.ts' : template === 'chat' ? 'src/chat-app.ts' : 'src/app.ts'}\\`; an app is a function from \\`Request\\` to \\`Response\\`,\nso test a route with \\`await app.request('/path')\\` and no server.${desktopNote}\n\n${notesStructure}${chatStructure}\n## Things that surprise people\n\n- A page mounted at \\`/x\\` answers \\`/x\\`, not \\`/x/\\` (trailing slashes are strict); \\`trimTrailingSlash()\\` redirects.\n- A \\`json\\` validator target reads the body only with a JSON \\`Content-Type\\`; a failure answers 400 with \\`{ error, issues: [{ message, path }] }\\`.\n- \\`throw new HTTPException(404, { message })\\` answers an error response (plain text).\n- \\`testClient(app)\\` from \\`'${PACKAGE}/testing'\\` types only routes chained on the \\`new ${CLASS}()\\` expression (\\`new ${CLASS}().get(...).post(...)\\`); headers such as a cookie go in the second argument of each call.\n- **JSX:** ${jsxNote}\n${clientNote}\n## Before you say you are done\n\n\\`${test}\\` pass.\n`\n}\n\nfunction copyDocs(target: string): void {\n const filter = (path: string) => !/(upstream\\.json|UPSTREAM\\.md)$/.test(path)\n mkdirSync(join(target, 'docs'), { recursive: true })\n cpSync(docsRoot(), join(target, 'docs', 'framework'), { recursive: true, filter })\n}\n\nfunction copyTemplate(\n template: Exclude<Template, 'acryl-app'>,\n target: string,\n name: string,\n): string[] {\n const written: string[] = []\n const walk = (from: string, to: string, prefix: string) => {\n mkdirSync(to, { recursive: true })\n for (const entry of readdirSync(from, { withFileTypes: true })) {\n const targetName = prefix === '' && entry.name === 'gitignore' ? '.gitignore' : entry.name\n if (entry.isDirectory())\n walk(join(from, entry.name), join(to, targetName), `${prefix}${entry.name}/`)\n else {\n writeFileSync(\n join(to, targetName),\n replacePlaceholders(readFileSync(join(from, entry.name), 'utf8'), name),\n )\n written.push(`${prefix}${targetName}`)\n }\n }\n }\n walk(join(templatesRoot(), template), target, '')\n writeFileSync(join(target, 'AGENTS.md'), agentsText(template, name))\n writeFileSync(join(target, 'CLAUDE.md'), '@AGENTS.md\\n')\n copyDocs(target)\n return written\n}\n\nconst isEmpty = (directory: string) => !existsSync(directory) || readdirSync(directory).length === 0\n\n/** The `acrylblends` command of the installed framework package, which creates the `acryl-app` template. */\nfunction acrylblendsBin(): string {\n const pkgFile = createRequire(import.meta.url).resolve(`${PACKAGE}/package.json`)\n const pkg = JSON.parse(readFileSync(pkgFile, 'utf8')) as { bin?: string | Record<string, string> }\n const bin = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.[PACKAGE]\n if (!bin) throw new Error(`${PACKAGE} has no command to create an app with`)\n return join(dirname(pkgFile), bin)\n}\n\n/** Create the app. Returns the exit code: 0 done, 1 refused or failed, 2 a usage error. Never calls `process.exit`. */\nexport async function runCreate(argv: readonly string[], io: Io = processIo()): Promise<number> {\n try {\n if (argv.includes('-h') || argv.includes('--help')) {\n io.stdout.write(HELP)\n return 0\n }\n if (argv.includes('-v') || argv.includes('--version')) {\n io.stdout.write(`${VERSION}\\n`)\n return 0\n }\n const options = parseCreateOptions(argv)\n const ask = options.yes ? undefined : io.ask\n const directory =\n options.directory ??\n (ask\n ? (await ask(`Project directory (${PACKAGE}-app): `)).trim() || `${PACKAGE}-app`\n : `${PACKAGE}-app`)\n const target = resolve(io.cwd, directory)\n const template: Template =\n options.template ??\n (ask\n ? await (async () => {\n const answer =\n (\n await ask(\n `Which template do you want to use? (nodejs, notes, chat, bun (experimental), acryl-app) [nodejs]: `,\n )\n ).trim() || 'nodejs'\n if (!isTemplate(answer))\n throw new UsageError(`unknown template \"${answer}\" (${TEMPLATES.join(', ')})`)\n return answer\n })()\n : 'nodejs')\n if (!isEmpty(target)) {\n io.stderr.write(`error: ${target} is not empty; nothing was changed\\n`)\n return 1\n }\n const name = nameFrom(target)\n if (template === 'acryl-app') {\n const code = await io.run(\n process.execPath,\n [acrylblendsBin(), 'init', target, '--template', 'agent', '--name', name, '--yes'],\n io.cwd,\n )\n if (code !== 0) return 1\n } else {\n const files = copyTemplate(template, target, name)\n io.stdout.write(\n `created ${name} (${template}) in ${target}: ${files.length} files, ${CLASS} docs in docs/framework\\n`,\n )\n }\n const pm: PackageManager =\n options.pm ??\n ((PACKAGE_MANAGERS as readonly string[]).find((m) =>\n (io.env.npm_config_user_agent ?? '').startsWith(`${m}/`),\n ) as PackageManager | undefined) ??\n 'npm'\n if (options.install) {\n if ((await io.run(pm, ['install'], target)) !== 0) {\n io.stderr.write(`error: ${pm} install failed; run it yourself in ${directory}\\n`)\n return 1\n }\n }\n const start = {\n nodejs: `${pm} run dev`,\n notes: `${pm} run dev`,\n chat: `${pm} run dev`,\n bun: 'bun run dev',\n 'acryl-app': `${pm} run dev`,\n }[template]\n io.stdout.write(\n `\\nNext:\\n cd ${directory}\\n${options.install ? '' : ` ${pm} install\\n`} ${start}\\n`,\n )\n return 0\n } catch (error) {\n if (error instanceof UsageError) {\n io.stderr.write(`error: ${error.message}\\n\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AAG;IACjD,GAAG,OAAO,MAAM,UAAU,GAAG,sCAAsC,UAAU,GAAG;IAChF,OAAO;GACT;;EAEF,MAAM,QAAQ;GACZ,QAAQ,GAAG,GAAG;GACd,OAAO,GAAG,GAAG;GACb,MAAM,GAAG,GAAG;GACZ,KAAK;GACL,aAAa,GAAG,GAAG;EACrB,EAAE;EACF,GAAG,OAAO,MACR,iBAAiB,UAAU,IAAI,QAAQ,UAAU,KAAK,KAAK,GAAG,YAAY,IAAI,MAAM,GACtF;EACA,OAAO;CACT,SAAS,OAAO;EACd,IAAI,iBAAiB,YAAY;GAC/B,GAAG,OAAO,MAAM,UAAU,MAAM,QAAQ,MAAM,MAAM;GACpD,OAAO;EACT;EACA,GAAG,OAAO,MAAM,UAAW,MAAgB,QAAQ,GAAG;EACtD,OAAO;CACT;AACF"}
|
package/docs/framework/README.md
CHANGED
|
@@ -48,9 +48,10 @@ They are enabled as they are ported.
|
|
|
48
48
|
| --- | --- |
|
|
49
49
|
| Run something in five minutes | [Getting started](getting-started/basic.md) |
|
|
50
50
|
| Run the app as a desktop app | [Desktop](getting-started/desktop.md) |
|
|
51
|
+
| Run it on a server | [Deploy](getting-started/deploy.md) |
|
|
51
52
|
| Look up a call | [API](api/index.md), [Routing](api/routing.md), [Context](api/context.md), [Request](api/request.md), [API summary](api/summary.md) |
|
|
52
53
|
| Understand the design | [Concepts](concepts/motivation.md) |
|
|
53
|
-
| Copy a pattern | [Guides](guides/best-practices.md), [Validation](guides/validation.md), [Testing](guides/testing.md), [Forms, sessions and a database](guides/forms-and-sessions.md) |
|
|
54
|
+
| Copy a pattern | [Guides](guides/best-practices.md), [Validation](guides/validation.md), [Testing](guides/testing.md), [Forms, sessions and a database](guides/forms-and-sessions.md), [Client components without a bundler](guides/client-modules.md) |
|
|
54
55
|
| Use Acryl inside a Cordis app | [Acryl in a Cordis app](cordis/acryl-in-a-cordis-app.md), [Plugin lifecycle](cordis/plugin-lifecycle.md), [Mounting](cordis/mounting.md) |
|
|
55
56
|
| Move from the 0.3 router calls | [Migration from 0.3](cordis/migration-from-0-3.md) |
|
|
56
57
|
| Move from the 0.4 names (`App`) | [Migration from 0.4](cordis/migration-from-0-4.md) |
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
# Generated copy
|
|
2
2
|
|
|
3
|
-
This folder is a copy of `docs/framework` of acryldev/acryl at commit `
|
|
3
|
+
This folder is a copy of `docs/framework` of acryldev/acryl at commit `e79bf3de59c700667ae617f5d367cc1fd2f8e037`, made by `scripts/sync-framework.mjs`. Do not edit it here: change the text in ACRYL and sync again. `pnpm run verify:framework` fails when a page differs from the recorded digest.
|
|
@@ -16,8 +16,10 @@ export const name = 'orders' // the package name and the Loader
|
|
|
16
16
|
export const inject = ['router', 'state'] // the plugin waits (PENDING) until both exist
|
|
17
17
|
|
|
18
18
|
interface Order { id: string, item: string }
|
|
19
|
-
const NewOrder: StandardSchema<{ item: string }> = {
|
|
19
|
+
const NewOrder: StandardSchema<unknown, { item: string }> = {
|
|
20
20
|
'~standard': {
|
|
21
|
+
version: 1,
|
|
22
|
+
vendor: 'orders',
|
|
21
23
|
validate: value => {
|
|
22
24
|
const item = (value as { item?: unknown } | null)?.item
|
|
23
25
|
return typeof item === 'string' && item !== '' ? { value: { item } } : { issues: [{ message: 'item is required', path: ['item'] }] }
|
|
@@ -98,8 +100,9 @@ import { validator } from 'acrylblends/validator'
|
|
|
98
100
|
app.post('/', schemaValidator('json', Schema), c => c.json(c.req.valid('json')))
|
|
99
101
|
```
|
|
100
102
|
|
|
101
|
-
- Targets: `json`, `form`, `query`, `param`, `header`, `cookie`. `Schema` is any Standard Schema (Schemastery, Zod, Valibot, or an
|
|
102
|
-
object with `'~standard': { validate }`).
|
|
103
|
+
- Targets: `json`, `form`, `query`, `param`, `header`, `cookie`. `Schema` is any Standard Schema v1 (Schemastery, Zod, Valibot, or an
|
|
104
|
+
object with `'~standard': { version: 1, vendor, validate }`; `version` and `vendor` may be left out, as only `validate` is called).
|
|
105
|
+
`StandardSchema<Input, Output>` is the type of such an object.
|
|
103
106
|
- A failure is 400 `{ error: 'invalid <target>', issues: [{ message, path }] }`; `path` is dotted, and `""` when the issue has none.
|
|
104
107
|
- The `json` target reads the body only with a JSON `Content-Type`; otherwise the schema sees `{}`.
|
|
105
108
|
- `validator(target, (value, c) => valueOrResponse)` is the same middleware with a function instead of a schema.
|
|
@@ -29,6 +29,9 @@ root.inject(['nodeServer'], ctx => {
|
|
|
29
29
|
| `port` | `0` | port to listen on; 0 lets the system choose |
|
|
30
30
|
| `scan` | `20` | how many further ports to try when the configured one is taken |
|
|
31
31
|
|
|
32
|
+
Without Cordis, `serve()` from `acrylblends/node-server` binds the same default, `127.0.0.1`; pass `hostname: '0.0.0.0'` to accept other
|
|
33
|
+
machines (see [Node.js](../getting-started/nodejs.md#listen-on-another-interface)).
|
|
34
|
+
|
|
32
35
|
The plugin becomes active once the server listens, so a plugin that injects `nodeServer` can rely on `ctx.nodeServer.url` and
|
|
33
36
|
`ctx.nodeServer.port`. A failure to bind fails the plugin.
|
|
34
37
|
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# Deploy
|
|
2
|
+
|
|
3
|
+
This page runs an app made by `npm create acrylblends@latest` (the `nodejs` and `notes` templates) on a Linux server with Node.js 22.19 or later: install, start, keep it running, put HTTPS in front, and look after the SQLite file.
|
|
4
|
+
The snippets are examples to adapt: check them against your own server before relying on them.
|
|
5
|
+
|
|
6
|
+
## What the template already does
|
|
7
|
+
|
|
8
|
+
- **Port and address.** `src/index.ts` reads `PORT` (default 3000) and `HOST` (default `127.0.0.1`). The default is local on purpose, and `serve()` without a `hostname` binds `127.0.0.1` too (from acrylblends 0.7.2; earlier versions listened on every interface). In a container, set `HOST=0.0.0.0`.
|
|
9
|
+
- **Graceful stop.** On `SIGTERM` and `SIGINT` the server stops taking requests, closes idle connections, lets the requests in flight finish, closes the database (the `notes` template) and exits with 0. A connection that never ends cannot keep it alive past 10 seconds (it then exits with 1).
|
|
10
|
+
- **Errors.** An error answers `500 Internal Server Error` with no stack and no detail; the stack goes to the log (standard error).
|
|
11
|
+
- **Cookies.** The `notes` template marks its session cookie `Secure` when the request is HTTPS, or when `TRUST_PROXY=1` and the proxy sends `X-Forwarded-Proto: https`.
|
|
12
|
+
|
|
13
|
+
## Environment variables
|
|
14
|
+
|
|
15
|
+
| Variable | Default | Meaning |
|
|
16
|
+
| --- | --- | --- |
|
|
17
|
+
| `NODE_ENV` | unset | set it to `production` on the server |
|
|
18
|
+
| `PORT` | `3000` | the port to listen on |
|
|
19
|
+
| `HOST` | `127.0.0.1` | the address to bind. `0.0.0.0` exposes the app to the network: do it in a container or when nothing else is in front |
|
|
20
|
+
| `NOTES_DB` | `notes.db` in the working directory | the SQLite file (`notes` template) |
|
|
21
|
+
| `TRUST_PROXY` | unset | `1` when a reverse proxy you run terminates HTTPS in front of the app (`notes` template) |
|
|
22
|
+
| `PUBLIC_ORIGIN` | unset | the address in the browser, for example `https://notes.example.com`. Behind a proxy the app sees `http://127.0.0.1:3000`, so csrf needs to be told which origin is the site (`notes` template) |
|
|
23
|
+
|
|
24
|
+
Keep secrets out of the repository: put them in an environment file the service reads (below), readable only by the service user.
|
|
25
|
+
|
|
26
|
+
## Install and start
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
git clone <your repository> /srv/notes && cd /srv/notes
|
|
30
|
+
npm ci --omit=dev
|
|
31
|
+
NODE_ENV=production PORT=3000 npm start
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
`npm ci --omit=dev` installs `acrylblends` and `typescript`. `typescript` is a normal dependency on purpose (it is why a production install is bigger than the framework alone, about 20 MB more): `.tsx` pages are compiled when the app starts, by `acrylblends/node-server/register`, with the app's own `typescript`.
|
|
35
|
+
There is no build step today. When a build step appears (compiling client code, for instance) it belongs in `npm run build` before `npm start`, not in the start command.
|
|
36
|
+
|
|
37
|
+
## Keep it running with systemd
|
|
38
|
+
|
|
39
|
+
`/etc/systemd/system/notes.service`:
|
|
40
|
+
|
|
41
|
+
```ini
|
|
42
|
+
[Unit]
|
|
43
|
+
Description=Notes
|
|
44
|
+
After=network.target
|
|
45
|
+
|
|
46
|
+
[Service]
|
|
47
|
+
User=notes
|
|
48
|
+
WorkingDirectory=/srv/notes
|
|
49
|
+
EnvironmentFile=/etc/notes.env
|
|
50
|
+
ExecStart=/usr/bin/node --import acrylblends/node-server/register src/index.ts
|
|
51
|
+
Restart=on-failure
|
|
52
|
+
TimeoutStopSec=15
|
|
53
|
+
NoNewPrivileges=true
|
|
54
|
+
ProtectSystem=strict
|
|
55
|
+
ReadWritePaths=/var/lib/notes
|
|
56
|
+
|
|
57
|
+
[Install]
|
|
58
|
+
WantedBy=multi-user.target
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`/etc/notes.env` (mode `0640`, owned by root, group `notes`):
|
|
62
|
+
|
|
63
|
+
```sh
|
|
64
|
+
NODE_ENV=production
|
|
65
|
+
PORT=3000
|
|
66
|
+
HOST=127.0.0.1
|
|
67
|
+
NOTES_DB=/var/lib/notes/notes.db
|
|
68
|
+
TRUST_PROXY=1
|
|
69
|
+
PUBLIC_ORIGIN=https://notes.example.com
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
```sh
|
|
73
|
+
sudo useradd --system --home /srv/notes notes
|
|
74
|
+
sudo install -d -o notes -g notes /var/lib/notes
|
|
75
|
+
sudo systemctl daemon-reload && sudo systemctl enable --now notes
|
|
76
|
+
sudo systemctl stop notes # sends SIGTERM; the app exits within seconds
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
`ExecStart` runs `node` directly (not `npm start`) so the signal reaches the app and not an `npm` wrapper.
|
|
80
|
+
|
|
81
|
+
## Behind a reverse proxy
|
|
82
|
+
|
|
83
|
+
Let the proxy handle HTTPS and keep the app on `127.0.0.1`.
|
|
84
|
+
|
|
85
|
+
Caddy (`Caddyfile`), which also obtains the certificate:
|
|
86
|
+
|
|
87
|
+
```text
|
|
88
|
+
notes.example.com {
|
|
89
|
+
reverse_proxy 127.0.0.1:3000
|
|
90
|
+
}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
nginx (certificates from your own tool, for example certbot):
|
|
94
|
+
|
|
95
|
+
```nginx
|
|
96
|
+
server {
|
|
97
|
+
listen 443 ssl;
|
|
98
|
+
server_name notes.example.com;
|
|
99
|
+
# ssl_certificate and ssl_certificate_key here
|
|
100
|
+
|
|
101
|
+
location / {
|
|
102
|
+
proxy_pass http://127.0.0.1:3000;
|
|
103
|
+
proxy_set_header Host $host;
|
|
104
|
+
proxy_set_header X-Forwarded-Proto $scheme;
|
|
105
|
+
proxy_set_header X-Forwarded-For $remote_addr;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Both pass `X-Forwarded-Proto`. Set `TRUST_PROXY=1` only when the app is reachable **only** through that proxy (it listens on `127.0.0.1`): the header is otherwise something any client can send.
|
|
111
|
+
|
|
112
|
+
## The SQLite file and backups
|
|
113
|
+
|
|
114
|
+
The database is one file (plus `-wal` and `-shm` files while it is open). Keep it outside the code folder (`NOTES_DB=/var/lib/notes/notes.db`), owned by the service user, on a disk you back up.
|
|
115
|
+
Do not copy the file while the app writes to it. Take a consistent copy with SQLite's backup, which is safe on a running database:
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
import { DatabaseSync, backup } from 'node:sqlite'
|
|
119
|
+
|
|
120
|
+
const db = new DatabaseSync(process.env.NOTES_DB ?? 'notes.db')
|
|
121
|
+
await backup(db, `/var/backups/notes-${new Date().toISOString().slice(0, 10)}.db`)
|
|
122
|
+
db.close()
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
or, with the `sqlite3` command line tool installed: `sqlite3 /var/lib/notes/notes.db ".backup '/var/backups/notes.db'"`. Run it from cron or a systemd timer and copy the result off the machine. To restore, stop the service and put the backup file in place of `notes.db`.
|
|
126
|
+
|
|
127
|
+
## Check it
|
|
128
|
+
|
|
129
|
+
```sh
|
|
130
|
+
curl -I http://127.0.0.1:3000/ # the app, directly
|
|
131
|
+
curl -I https://notes.example.com/ # through the proxy
|
|
132
|
+
journalctl -u notes -n 50 # the log, including error stacks
|
|
133
|
+
```
|
|
@@ -80,27 +80,29 @@ app.get('/', (c) => c.text('Hello Node.js!'))
|
|
|
80
80
|
serve(app)
|
|
81
81
|
```
|
|
82
82
|
|
|
83
|
-
|
|
83
|
+
`serve()` listens on `127.0.0.1` unless you pass `hostname`, so a development server is reachable from this machine only, not from the rest
|
|
84
|
+
of the network. See [Listen on another interface](#listen-on-another-interface).
|
|
85
|
+
|
|
86
|
+
To shut the server down gracefully, stop taking requests, let the ones in flight finish, and exit after a bounded time, so a connection
|
|
87
|
+
that never ends cannot keep the process alive:
|
|
84
88
|
|
|
85
89
|
```ts
|
|
86
90
|
const server = serve(app)
|
|
87
91
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
console.error(err)
|
|
97
|
-
process.exit(1)
|
|
98
|
-
}
|
|
99
|
-
process.exit(0)
|
|
100
|
-
})
|
|
101
|
-
})
|
|
92
|
+
function shutdown(): void {
|
|
93
|
+
server.close(() => process.exit(0))
|
|
94
|
+
// Keep-alive connections with no request in flight would otherwise hold close() open until they time out.
|
|
95
|
+
server.closeIdleConnections()
|
|
96
|
+
setTimeout(() => process.exit(1), 10_000).unref()
|
|
97
|
+
}
|
|
98
|
+
process.once('SIGINT', shutdown)
|
|
99
|
+
process.once('SIGTERM', shutdown)
|
|
102
100
|
```
|
|
103
101
|
|
|
102
|
+
`serve(app)` and `serve({ fetch, ... })` return an `http.Server`, which has `closeIdleConnections()`. With `createServer` from
|
|
103
|
+
`node:https` the result is an `https.Server`, and with `node:http2` an `Http2Server` or `Http2SecureServer`, which has no such method;
|
|
104
|
+
there, `server.close()` waits for the open sessions.
|
|
105
|
+
|
|
104
106
|
> **Note.** On Node.js, `serve()` wraps the `node:http` module and returns the underlying server instance, so closing it is up to you. Bun serves Fetch handlers natively and manages the server itself, which is why its guide doesn't include this step.
|
|
105
107
|
|
|
106
108
|
## 3. Run
|
|
@@ -136,6 +138,22 @@ serve({
|
|
|
136
138
|
})
|
|
137
139
|
```
|
|
138
140
|
|
|
141
|
+
## Listen on another interface
|
|
142
|
+
|
|
143
|
+
`serve()` binds `127.0.0.1` when `hostname` is not given. That is right on a developer machine and behind a reverse proxy on the same
|
|
144
|
+
host. Inside a container, or when other machines should reach the app directly, bind every interface on purpose:
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
serve({
|
|
148
|
+
fetch: app.fetch,
|
|
149
|
+
port: 3000,
|
|
150
|
+
hostname: '0.0.0.0', // or '::' for IPv6 and IPv4
|
|
151
|
+
})
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
> **Note.** Many Node servers listen on every interface by default. `serve()` does not, so starting a development server never exposes
|
|
155
|
+
> the app to the local network by accident.
|
|
156
|
+
|
|
139
157
|
## WebSocket
|
|
140
158
|
|
|
141
159
|
WebSocket support is built into `acrylblends/node-server`. Install `ws` and, if you use TypeScript, `@types/ws`. Then create a `WebSocketServer` with `{ noServer: true }` and pass it to `serve()` with the `websocket` option.
|
|
@@ -311,7 +329,9 @@ bun run build
|
|
|
311
329
|
|
|
312
330
|
### Dockerfile
|
|
313
331
|
|
|
314
|
-
Here is an example of a Node.js Dockerfile.
|
|
332
|
+
Here is an example of a Node.js Dockerfile. A container's published port reaches the app only when it listens on every interface, so
|
|
333
|
+
the app reads its hostname from the environment, as the templates do (`hostname: process.env.HOST || '127.0.0.1'`), and the image
|
|
334
|
+
sets `HOST=0.0.0.0`.
|
|
315
335
|
|
|
316
336
|
```Dockerfile
|
|
317
337
|
FROM node:22-alpine AS base
|
|
@@ -338,6 +358,7 @@ COPY --from=builder --chown=acrylblends:nodejs /app/dist /app/dist
|
|
|
338
358
|
COPY --from=builder --chown=acrylblends:nodejs /app/package.json /app/package.json
|
|
339
359
|
|
|
340
360
|
USER acrylblends
|
|
361
|
+
ENV HOST=0.0.0.0
|
|
341
362
|
EXPOSE 3000
|
|
342
363
|
|
|
343
364
|
CMD ["node", "/app/dist/index.js"]
|