@acryldev/create-blends 1.7.0 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/{docs/framework/LICENSE → LICENSE} +1 -3
  2. package/package.json +2 -2
  3. package/docs/framework/README.md +0 -70
  4. package/docs/framework/agents/index.md +0 -59
  5. package/docs/framework/api/acryl.md +0 -247
  6. package/docs/framework/api/context.md +0 -478
  7. package/docs/framework/api/exception.md +0 -80
  8. package/docs/framework/api/index.md +0 -12
  9. package/docs/framework/api/presets.md +0 -62
  10. package/docs/framework/api/request.md +0 -396
  11. package/docs/framework/api/routing.md +0 -303
  12. package/docs/framework/api/summary.md +0 -143
  13. package/docs/framework/concepts/benchmarks.md +0 -26
  14. package/docs/framework/concepts/developer-experience.md +0 -5
  15. package/docs/framework/concepts/middleware.md +0 -21
  16. package/docs/framework/concepts/motivation.md +0 -14
  17. package/docs/framework/concepts/routers.md +0 -63
  18. package/docs/framework/concepts/stacks.md +0 -235
  19. package/docs/framework/concepts/web-standard.md +0 -27
  20. package/docs/framework/cordis/acryl-in-a-cordis-app.md +0 -160
  21. package/docs/framework/cordis/concepts.md +0 -105
  22. package/docs/framework/cordis/middleware.md +0 -8
  23. package/docs/framework/cordis/migration-from-0-3.md +0 -111
  24. package/docs/framework/cordis/migration-from-0-4.md +0 -14
  25. package/docs/framework/cordis/migration-from-dsh-webserver.md +0 -109
  26. package/docs/framework/cordis/migration-to-1-0.md +0 -46
  27. package/docs/framework/cordis/mounting.md +0 -85
  28. package/docs/framework/cordis/node-server.md +0 -100
  29. package/docs/framework/cordis/plugin-lifecycle.md +0 -111
  30. package/docs/framework/cordis/surfaces.md +0 -71
  31. package/docs/framework/cordis/transport-and-cancellation.md +0 -57
  32. package/docs/framework/cordis/validation.md +0 -135
  33. package/docs/framework/getting-started/basic.md +0 -201
  34. package/docs/framework/getting-started/bun.md +0 -219
  35. package/docs/framework/getting-started/deploy.md +0 -133
  36. package/docs/framework/getting-started/desktop.md +0 -80
  37. package/docs/framework/getting-started/nodejs.md +0 -365
  38. package/docs/framework/getting-started/other-runtimes.md +0 -30
  39. package/docs/framework/guides/best-practices.md +0 -231
  40. package/docs/framework/guides/bring-your-own-tool.md +0 -218
  41. package/docs/framework/guides/client-modules.md +0 -210
  42. package/docs/framework/guides/create-acrylblends.md +0 -143
  43. package/docs/framework/guides/data.md +0 -314
  44. package/docs/framework/guides/examples.md +0 -3
  45. package/docs/framework/guides/faq.md +0 -19
  46. package/docs/framework/guides/forms-and-sessions.md +0 -235
  47. package/docs/framework/guides/helpers.md +0 -33
  48. package/docs/framework/guides/jsx-dom.md +0 -301
  49. package/docs/framework/guides/jsx.md +0 -487
  50. package/docs/framework/guides/middleware.md +0 -253
  51. package/docs/framework/guides/production.md +0 -80
  52. package/docs/framework/guides/rpc.md +0 -878
  53. package/docs/framework/guides/testing.md +0 -133
  54. package/docs/framework/guides/validation.md +0 -470
  55. package/docs/framework/helpers/accepts.md +0 -60
  56. package/docs/framework/helpers/adapter.md +0 -57
  57. package/docs/framework/helpers/conninfo.md +0 -77
  58. package/docs/framework/helpers/cookie.md +0 -232
  59. package/docs/framework/helpers/css.md +0 -282
  60. package/docs/framework/helpers/dev.md +0 -64
  61. package/docs/framework/helpers/factory.md +0 -180
  62. package/docs/framework/helpers/html.md +0 -123
  63. package/docs/framework/helpers/jwt.md +0 -184
  64. package/docs/framework/helpers/proxy.md +0 -115
  65. package/docs/framework/helpers/route.md +0 -143
  66. package/docs/framework/helpers/ssg.md +0 -390
  67. package/docs/framework/helpers/streaming.md +0 -224
  68. package/docs/framework/helpers/testing.md +0 -118
  69. package/docs/framework/helpers/websocket.md +0 -208
  70. package/docs/framework/middleware/builtin/basic-auth.md +0 -165
  71. package/docs/framework/middleware/builtin/bearer-auth.md +0 -138
  72. package/docs/framework/middleware/builtin/body-limit.md +0 -71
  73. package/docs/framework/middleware/builtin/cache.md +0 -99
  74. package/docs/framework/middleware/builtin/combine.md +0 -94
  75. package/docs/framework/middleware/builtin/compress.md +0 -59
  76. package/docs/framework/middleware/builtin/context-storage.md +0 -74
  77. package/docs/framework/middleware/builtin/cors.md +0 -134
  78. package/docs/framework/middleware/builtin/csrf.md +0 -105
  79. package/docs/framework/middleware/builtin/etag.md +0 -54
  80. package/docs/framework/middleware/builtin/ip-restriction.md +0 -69
  81. package/docs/framework/middleware/builtin/jsx-renderer.md +0 -283
  82. package/docs/framework/middleware/builtin/jwk.md +0 -192
  83. package/docs/framework/middleware/builtin/jwt.md +0 -145
  84. package/docs/framework/middleware/builtin/language.md +0 -232
  85. package/docs/framework/middleware/builtin/logger.md +0 -74
  86. package/docs/framework/middleware/builtin/loopback-only.md +0 -31
  87. package/docs/framework/middleware/builtin/method-not-allowed.md +0 -48
  88. package/docs/framework/middleware/builtin/method-override.md +0 -80
  89. package/docs/framework/middleware/builtin/mount.md +0 -103
  90. package/docs/framework/middleware/builtin/pretty-json.md +0 -53
  91. package/docs/framework/middleware/builtin/request-id.md +0 -87
  92. package/docs/framework/middleware/builtin/secure-headers.md +0 -247
  93. package/docs/framework/middleware/builtin/timeout.md +0 -98
  94. package/docs/framework/middleware/builtin/timing.md +0 -100
  95. package/docs/framework/middleware/builtin/trailing-slash.md +0 -74
  96. package/docs/framework/middleware/third-party.md +0 -4
  97. package/docs/framework/workshop/README.md +0 -294
  98. package/docs/framework/workshop/facilitator.md +0 -101
@@ -1,314 +0,0 @@
1
- # Data: the `db` port, migrations and choosing a store
2
-
3
- An app that keeps records (users, notes, orders) keeps them in a SQL database, and reaches it through one small interface, `db`. Handlers and
4
- stores take a `Db` as an argument and never import a driver, so the file or server behind it can change without touching them. SQLite is the
5
- provider in `acrylblends`. Postgres (or Supabase, through `DATABASE_URL`) is an optional plugin, `@acryldev/db-postgres`, that serves the same
6
- interface; it is not part of `acrylblends` or the templates, and an app adds it only when it must use Postgres.
7
-
8
- ## Choosing
9
-
10
- | The app | Use | State |
11
- | --- | --- | --- |
12
- | Normal web or desktop app, users, lists, orders | `db` with SQLite (the `notes` and `chat` templates) | available |
13
- | SQLite is not enough, but no server | `db` with the optional `@acryldev/db-pglite` plugin: Postgres in the app's process, one folder in the app home | optional, not in `acrylblends` |
14
- | Must use Postgres or Supabase | `db` with the optional `@acryldev/db-postgres` plugin | optional, not in `acrylblends` |
15
- | Tiny, one person, a few screens | [`kv`](#a-tiny-app-kv), named JSON documents with no SQL | available |
16
-
17
- Start with `db` when the data has users, lists or relations: SQL is what people and coding agents already know. Start with `kv` when the whole
18
- data is a handful of settings or a small list that one process reads and writes.
19
-
20
- ## A tiny app: `kv`
21
-
22
- `kv` keeps named JSON documents in one file, with no SQL and no migrations. It suits a settings page, a demo, a one-person tool.
23
-
24
- ```ts
25
- import { openKv } from '@acryldev/blends/kv/json'
26
-
27
- const { kv, close } = await openKv({ path: 'data/kv.json' })
28
-
29
- await kv.set('theme', 'dark')
30
- const theme = await kv.get<string>('theme') // 'dark'; undefined for a key that was never set
31
-
32
- // Change a value from the value it has now, without losing a concurrent change.
33
- const visits = await kv.update<number>('visits', (current) => (current ?? 0) + 1)
34
-
35
- await kv.set('todos/1', { title: 'Buy milk', done: false })
36
- await kv.set('todos/2', { title: 'Write docs', done: true })
37
- const keys = await kv.list('todos/') // ['todos/1', 'todos/2'], sorted by code point
38
-
39
- await kv.delete('todos/1') // a key that is not there is not an error
40
- await close()
41
- ```
42
-
43
- - A key is a non-empty string; a prefix such as `todos/` groups related documents. A value is JSON (`null`, booleans, numbers, strings, arrays,
44
- objects). `undefined`, functions, bigints and `NaN` are refused with a `TypeError` before anything is written, and a value read back is a copy.
45
- - `update` runs your function with the current value (`undefined` when the key is missing) and stores what it returns. The function is
46
- **synchronous**: an `async` function is a type error. Read what you need first with `await kv.get(...)`, then update with a plain function.
47
- If it throws, the value stays as it was.
48
- - Every write reaches the disk before its promise resolves, and the file is replaced as a whole (a temporary file, then a rename), so a crash
49
- or a power cut leaves the old file or the new one, never half of one. A file that exists but does not parse stops the app with a message that
50
- names it; it is never started over.
51
- - Like `db`, the store is passed to the code that needs it (`createApp(kv)`), opened in one place, and closed when the process stops.
52
- A test opens a file in a temporary folder.
53
-
54
- ### When to move to SQL
55
-
56
- The whole file is kept in memory and rewritten on every write, and one process owns it. Move to `db` when:
57
-
58
- - more than one process must write (two writers would overwrite each other);
59
- - the file grows past a few megabytes, or you need to search, sort or join the data;
60
- - the data gets relations (users who own notes).
61
-
62
- The same `kv` interface runs on SQL, so the code does not change, only the line that opens it. `kvOnDb` keeps the documents in a `kv` table of the
63
- database from `openDb`, and `copyKv` moves what the file holds:
64
-
65
- ```ts
66
- import { copyKv } from '@acryldev/blends/kv'
67
- import { openKv } from '@acryldev/blends/kv/json'
68
- import { kvOnDb } from '@acryldev/blends/kv/db'
69
- import { openDb } from '@acryldev/blends/db/sqlite'
70
-
71
- const file = await openKv({ path: 'data/kv.json' })
72
- const sql = await openDb({ path: 'data/app.sqlite', migrations: 'migrations' })
73
-
74
- const { copied } = await copyKv(file.kv, kvOnDb(sql.db)) // refuses to overwrite a key the table already has, unless you pass { overwrite: true }
75
-
76
- await file.close()
77
- await sql.close()
78
- ```
79
-
80
- On the command line, `npx acrylblends kv import data/kv.json data/app.sqlite` does the same (add `--overwrite` to replace keys the table has).
81
- The table is created on first use, beside the app's own tables; nothing else changes.
82
-
83
- ## Open the database
84
-
85
- `openDb` from `acrylblends/db/sqlite` opens one SQLite file, applies your migrations, and returns the database next to the function that closes it:
86
-
87
- ```ts
88
- import { openDb } from '@acryldev/blends/db/sqlite'
89
-
90
- const { db, close } = await openDb({ path: 'data/app.sqlite', migrations: 'migrations' })
91
- ```
92
-
93
- - `path` is the file, created with its folder when it does not exist. `':memory:'` opens a database that lives and dies with the process, which
94
- is what tests use.
95
- - `migrations` is a folder of numbered SQL files, relative to the working directory (see below).
96
- - `db` is the port: `exec`, `run`, `get`, `all` and `transaction`, every one returning a promise. It has no `close`, so no part of the app can
97
- close the database another part is using. `close` is the opener's: call it once, when the process stops.
98
-
99
- Pass `db` to the code that needs it. Nothing opens the database at import time, so importing a module never creates a file:
100
-
101
- ```ts
102
- import type { Db } from '@acryldev/blends/db'
103
-
104
- export function notesStore(db: Db) {
105
- return {
106
- async titles(userId: number): Promise<string[]> {
107
- const rows = await db.all<{ title: string }>(
108
- 'SELECT title FROM notes WHERE user_id = ? ORDER BY updated_at DESC',
109
- userId,
110
- )
111
- return rows.map((row) => row.title)
112
- },
113
- }
114
- }
115
- ```
116
-
117
- ## Migrations
118
-
119
- The shape of the database lives in `migrations/`, one numbered file per change:
120
-
121
- ```
122
- migrations/
123
- 001-notes.sql
124
- 002-tags.sql
125
- ```
126
-
127
- ```sql
128
- -- migrations/002-tags.sql
129
- CREATE TABLE tags (
130
- note_id INTEGER NOT NULL REFERENCES notes(id) ON DELETE CASCADE,
131
- name TEXT NOT NULL,
132
- PRIMARY KEY (note_id, name)
133
- );
134
- ```
135
-
136
- - Files are named `NNN-name.sql` and numbered from 1 with no gaps. A gap, a repeated number or a file named otherwise stops the app at start
137
- with a message that names it.
138
- - On start, `openDb` applies the files that have not run yet, in order, **in one transaction**: a failing file leaves the database as it was.
139
- - The version is recorded in the `_migrations` table. Do not touch that table.
140
- - **Never edit a file that has been applied.** A database that already ran `001` does not run it again, so an edit changes only new databases.
141
- To change a table, add the next file (`ALTER TABLE notes ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0`).
142
- - A database whose version is newer than your files (an older build started on newer data) is refused. The app does not start.
143
- - A migration is plain SQL. Put the data change next to the shape change in the same file when they belong together.
144
-
145
- **In an app made by `acrylblends init`** (a Cordis app) the provider is a row of `blend.yaml` (and an entry in the `registry` of `src/app.ts`, which `acrylblends add db` prints how to write):
146
-
147
- ```yaml
148
- - id: db
149
- name: '@acryldev/db-sqlite'
150
- config:
151
- path: data/app.sqlite
152
- migrations: migrations
153
- ```
154
-
155
- A relative `path` or `migrations` in a row is read from the app's folder (the one that holds `blend.yaml`), not from where the command was started. (Since 1.0.3; before it a relative path stopped the app with "no file base URL", and an absolute path, or the `db: { migrations: join(projectRoot, 'migrations') }` option of `compose` in `src/app.ts` as the notes template does, was the way.)
156
-
157
- To add a feature that needs a column or a table, the work is always the same three steps: write the next migration, change the store that
158
- reads and writes it, and change the handlers and views that use the store.
159
-
160
- ## Reading and writing
161
-
162
- ```ts
163
- // One row, or undefined.
164
- const note = await db.get<Note>('SELECT * FROM notes WHERE id = ? AND user_id = ?', id, userId)
165
-
166
- // Many rows.
167
- const notes = await db.all<Note>('SELECT * FROM notes WHERE user_id = ? ORDER BY id', userId)
168
-
169
- // A write: how many rows it changed.
170
- const { changes } = await db.run('DELETE FROM notes WHERE id = ? AND user_id = ?', id, userId)
171
- if (changes === 0) return c.notFound()
172
-
173
- // A write that gives back the row it made.
174
- const created = await db.get<Note>(
175
- 'INSERT INTO notes (user_id, title, body, updated_at) VALUES (?, ?, ?, ?) RETURNING *',
176
- userId, title, body, new Date().toISOString(),
177
- )
178
- ```
179
-
180
- - Values go in as **bindings** after the SQL (`?`, in order), never inside the SQL text. This is what keeps a title like `'); DROP TABLE notes;--`
181
- a title. A binding is `null`, a number, a bigint, a string or a `Uint8Array`; turn a boolean into `0` or `1` and a date into
182
- `toISOString()` yourself.
183
- - `exec(sql)` runs SQL text with no bindings, and may hold several statements. Use it for setup, not for user input.
184
- - `db.get` has no `lastInsertRowid`. To get the new row or its id, end the insert with `RETURNING *` or `RETURNING id`.
185
- - `changes` is what makes "update only if nothing changed meanwhile" possible: `UPDATE ... WHERE id = ? AND version = ?` and check `changes`.
186
-
187
- ## Transactions
188
-
189
- Changes that must happen together go in `transaction`. Everything inside goes through the handle the callback receives:
190
-
191
- ```ts
192
- await db.transaction(async (tx) => {
193
- const { changes } = await tx.run('UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ?', amount, from, amount)
194
- if (changes === 0) throw new Error('not enough money')
195
- await tx.run('UPDATE accounts SET balance = balance + ? WHERE id = ?', amount, to)
196
- })
197
- ```
198
-
199
- - If the callback throws, the transaction is rolled back and `transaction` rejects with that same error.
200
- - Other calls, and other transactions, wait until the transaction finishes. So **never call `db` itself inside the callback**, only `tx`: that
201
- call would wait for a transaction that waits for it, and never return.
202
- - The handle stops working when the callback settles. Do not keep it.
203
-
204
- ## Writing SQL that moves to Postgres
205
-
206
- The optional Postgres plugins (`@acryldev/db-pglite` embedded, `@acryldev/db-postgres` on a server) serve the same interface. SQL that stays inside this list runs on both:
207
-
208
- - Placeholders are `?` on every provider.
209
- - Use `RETURNING` to get a new row, not a driver-specific "last id".
210
- - Keep dates as ISO 8601 text (`new Date().toISOString()`), and booleans as `0` and `1`.
211
- - Keep identifiers lower case and unquoted.
212
- - `INTEGER PRIMARY KEY` makes an automatically numbered key in SQLite. The identity column of another database is spelled differently, so keep key
213
- definitions in migration files, where a different provider's version of the file can differ.
214
- - SQLite lets a column hold a value of another type than it declares; most other databases do not. Store what you declare.
215
-
216
- ## In tests
217
-
218
- A test opens its own database in memory, with the same migrations as production, and closes it:
219
-
220
- ```ts
221
- import { afterEach, beforeEach, expect, test } from 'vitest'
222
- import { openDb } from '@acryldev/blends/db/sqlite'
223
- import { notesStore } from './db.ts'
224
-
225
- let close: () => Promise<void>
226
- let store: ReturnType<typeof notesStore>
227
-
228
- beforeEach(async () => {
229
- const opened = await openDb({ path: ':memory:', migrations: 'migrations' })
230
- close = opened.close
231
- store = notesStore(opened.db)
232
- })
233
- afterEach(() => close())
234
-
235
- test('a new store has no notes', async () => {
236
- expect(await store.titles(1)).toEqual([])
237
- })
238
- ```
239
-
240
- ## In production
241
-
242
- Open the database once at start, serve, and close it when the process is told to stop, after the server has stopped taking requests:
243
-
244
- ```ts
245
- import { serve } from '@acryldev/blends/node-server'
246
- import { openDb } from '@acryldev/blends/db/sqlite'
247
- import { createApp } from './app.ts'
248
-
249
- const { db, close } = await openDb({ path: process.env.DATABASE_FILE ?? 'data/app.sqlite', migrations: 'migrations' })
250
- const server = serve({ fetch: createApp(db).fetch, port: Number(process.env.PORT ?? 3000) })
251
-
252
- process.once('SIGTERM', async () => {
253
- server.close()
254
- await close()
255
- })
256
- ```
257
-
258
- `close` waits for the calls and the transaction that are running, flushes the write-ahead log into the main file, and releases the file, so a
259
- copy of `data/app.sqlite` made afterwards is complete. Keep the file on a disk that outlives a deploy; on a host with only an ephemeral disk the
260
- data goes with the machine.
261
-
262
- ## Why the database is opened in one place
263
-
264
- Only one file of an app opens the database: the **opener** (`src/db.ts` in the templates). Every other file receives a `Db` as an argument and
265
- imports its type from `acrylblends/db`. Nothing outside the opener imports `node:sqlite`, `pg`, `postgres`, `@electric-sql/pglite` or another
266
- driver, or `acrylblends/db/sqlite` itself.
267
-
268
- Why it matters:
269
-
270
- - **Changing the database is one file.** Moving from SQLite to Postgres changes what the opener calls, and no route, store or test.
271
- - **A test opens its own database.** Code that opens a database by itself cannot be given an in-memory one, and a test that reaches the real file
272
- breaks the next one.
273
- - **There is one place to close it.** The code that opened a database closes it; the port has no `close`, so a route cannot do it by mistake.
274
- - **An agent that adds a feature keeps the shape.** A coding agent asked for "tags" writes a migration and a store function, and has no reason to
275
- reach for a driver when the interface is in front of it.
276
-
277
- The rule is checked, not hoped for. The app names its opener once, in `package.json`:
278
-
279
- ```json
280
- {
281
- "acryl": { "opener": "src/db.ts" }
282
- }
283
- ```
284
-
285
- `acrylblends check-deps` reads every `.ts`, `.tsx` and `.js` file in `src/`, `test/`, `tests/` and `plugins/`, and fails when a file other than
286
- the opener imports a database driver, an opener such as `acrylblends/db/sqlite` or `@acryldev/db-sqlite`, or (outside `plugins/desktop-shell`) `electron`.
287
- It names the file and the line:
288
-
289
- ```
290
- src/routes.ts:3: "node:sqlite" is a database driver; take a Db (import type { Db } from "@acryldev/blends/db") as an argument and let src/db.ts open the database
291
- ```
292
-
293
- The `notes` and `chat` templates run it in `npm test` and `npm run check`. List more than one opener as an array (`"opener": ["src/db.ts", "src/app.ts"]`).
294
- In a Blend app, `acrylblends add db` declares `src/app.ts`, where the provider is mounted, and a plugin that declares `inject: ['db']` must not import
295
- `@acryldev/db-sqlite`: it receives `ctx.db`.
296
-
297
- ## In a Cordis app
298
-
299
- An ACRYL app gets the same interface as a service. The `@acryldev/db-sqlite` plugin row opens the file (by default `data.sqlite` in the app home),
300
- applies the `migrations` folder, and provides `db`; a plugin declares `inject: ['db']` and imports the types only:
301
-
302
- ```ts
303
- import type { Context } from '@deepseek-ai/cordis'
304
- import type {} from '@acryldev/blends/cordis/db'
305
-
306
- export const name = 'notes'
307
- export const inject = ['db']
308
-
309
- export function apply(ctx: Context) {
310
- void ctx.db.run('INSERT INTO notes (title) VALUES (?)', 'first')
311
- }
312
- ```
313
-
314
- The plugin never imports a driver, so replacing the SQLite row by another provider is a change to the configuration.
@@ -1,3 +0,0 @@
1
- # Examples
2
-
3
- See the Examples section.
@@ -1,19 +0,0 @@
1
- # Frequently Asked Questions
2
-
3
- ## Why does `/orders/` return 404 when `/orders` works?
4
-
5
- Trailing slashes are strict by default: `/orders` and `/orders/` are different paths. Add `trimTrailingSlash()` to redirect, or set the router to ignore the slash. See
6
- [Mounting and trailing slashes](../cordis/mounting.md#trailing-slashes).
7
-
8
- ## Why does my validator see `{}` for a JSON body?
9
-
10
- A `json` validation target reads the body only when the request has a JSON `Content-Type`; without it the validator sees `{}`. See
11
- [Validation with Standard Schema](../cordis/validation.md).
12
-
13
- ## Which runtimes are verified?
14
-
15
- Node.js. Bun is experimental. The other hosting platforms have no adapter in 1.0; they are listed on [Other runtimes](../getting-started/other-runtimes.md).
16
-
17
- ## Where are the parts marked "not yet available"?
18
-
19
- Their pages are part of the documentation so that the structure is complete; each starts with a note saying so. They are enabled as they are built.
@@ -1,235 +0,0 @@
1
- # Forms, sessions and a database
2
-
3
- This page shows the parts a small multi-user app needs, in the order an app uses them: a database, passwords, a cookie session, HTML forms with server-side validation, and a JSON API that shares the same rules.
4
- It is the shape of a "Notes" app built from these docs alone (sign up, log in, create, edit, delete and search notes, a typed test client for the API).
5
-
6
- ## A database with the `db` port
7
-
8
- `openDb` from `acrylblends/db/sqlite` opens a SQLite file (Node.js 22.19 and later include SQLite, so there is nothing to install), applies the SQL files in `migrations/`, and returns `{ db, close }`.
9
- Every call on `db` returns a promise, so `await` it. The [data guide](data.md) has the whole story: migrations, transactions, tests and shutdown.
10
-
11
- ```sql
12
- -- migrations/001-notes.sql
13
- CREATE TABLE users (
14
- id INTEGER PRIMARY KEY,
15
- email TEXT NOT NULL UNIQUE,
16
- password_hash TEXT NOT NULL
17
- );
18
-
19
- CREATE TABLE sessions (
20
- token TEXT PRIMARY KEY,
21
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE
22
- );
23
- ```
24
-
25
- ```ts
26
- import { openDb } from '@acryldev/blends/db/sqlite'
27
-
28
- export function openNotesDb(path = process.env.NOTES_DB ?? 'data/notes.sqlite') {
29
- return openDb({ path, migrations: 'migrations' })
30
- }
31
- ```
32
-
33
- Take the database as an argument (`createApp(db)`) instead of opening it at import time. A test then opens `openNotesDb(':memory:')`, and importing the app module does not create a file.
34
-
35
- ## Passwords with `node:crypto`
36
-
37
- Never store a password. Store a salted `scrypt` hash and compare in constant time.
38
-
39
- ```ts
40
- import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
41
- import { promisify } from 'node:util'
42
-
43
- const scryptAsync = promisify(scrypt) as (password: string, salt: Buffer, length: number) => Promise<Buffer>
44
-
45
- export async function hashPassword(password: string): Promise<string> {
46
- const salt = randomBytes(16)
47
- const key = await scryptAsync(password, salt, 64)
48
- return `${salt.toString('hex')}:${key.toString('hex')}`
49
- }
50
-
51
- export async function verifyPassword(password: string, stored: string): Promise<boolean> {
52
- const [salt, key] = stored.split(':')
53
- if (!salt || !key) return false
54
- const expected = Buffer.from(key, 'hex')
55
- return timingSafeEqual(await scryptAsync(password, Buffer.from(salt, 'hex'), expected.length), expected)
56
- }
57
- ```
58
-
59
- ## A cookie session
60
-
61
- The simplest session is a random token in an `httpOnly` cookie and a `sessions` row that maps it to a user. Log out deletes the row, so a stolen cookie stops working.
62
- `getCookie`, `setCookie` and `deleteCookie` are in [the Cookie helper](../helpers/cookie.md).
63
-
64
- ```ts
65
- import { Acryl } from '@acryldev/blends'
66
- import { createMiddleware } from '@acryldev/blends/factory'
67
- import { deleteCookie, getCookie, setCookie } from '@acryldev/blends/cookie'
68
- import { randomBytes } from 'node:crypto'
69
- import type { Db } from '@acryldev/blends/db'
70
-
71
- type Env = { Variables: { user: { id: number; email: string } } }
72
-
73
- export function createApp(db: Db) {
74
- const userFor = (token: string | undefined) =>
75
- token
76
- ? db.get<{ id: number; email: string }>(
77
- 'SELECT users.id AS id, users.email AS email FROM sessions JOIN users ON users.id = sessions.user_id WHERE token = ?',
78
- token
79
- )
80
- : undefined
81
-
82
- const requireUser = createMiddleware<Env>(async (c, next) => {
83
- const user = await userFor(getCookie(c, 'sid'))
84
- if (!user) return c.redirect('/login')
85
- c.set('user', user)
86
- await next()
87
- })
88
-
89
- const app = new Acryl<Env>()
90
- app.use('/notes', requireUser)
91
- app.use('/notes/*', requireUser)
92
- app.get('/notes', (c) => c.text(`Hello ${c.get('user').email}`))
93
-
94
- app.post('/login-example', async (c) => {
95
- const token = randomBytes(32).toString('hex')
96
- await db.run('INSERT INTO sessions (token, user_id) VALUES (?, ?)', token, 1)
97
- setCookie(c, 'sid', token, { path: '/', httpOnly: true, sameSite: 'Lax', maxAge: 60 * 60 * 24 * 30 })
98
- return c.redirect('/notes', 303)
99
- })
100
-
101
- app.post('/logout', async (c) => {
102
- const token = getCookie(c, 'sid')
103
- if (token) await db.run('DELETE FROM sessions WHERE token = ?', token)
104
- deleteCookie(c, 'sid', { path: '/' })
105
- return c.redirect('/login', 303)
106
- })
107
- return app
108
- }
109
- ```
110
-
111
- A middleware registered with `use('/notes', ...)` does not cover `/notes/…`: register both `'/notes'` and `'/notes/*'`.
112
- After a form POST redirect with status **303** so the browser follows with a GET.
113
-
114
- ## Forms and server-side validation
115
-
116
- `await c.req.parseBody()` reads an HTML form (`application/x-www-form-urlencoded` or multipart). Each value is a `string` or a `File`, so convert with `String(...)` or check `typeof`.
117
- Keep the rules in one function that both the form routes and the JSON API call, and answer an invalid form with **status 400 and the same page**, with the messages and the typed values filled in:
118
-
119
- ```ts
120
- export interface NoteInput {
121
- title: string
122
- body: string
123
- }
124
-
125
- export function checkNote(value: unknown): { value: NoteInput } | { issues: { message: string; path: string[] }[] } {
126
- const input = (value ?? {}) as Record<string, unknown>
127
- const title = typeof input.title === 'string' ? input.title.trim() : ''
128
- const body = typeof input.body === 'string' ? input.body : ''
129
- const issues: { message: string; path: string[] }[] = []
130
- if (title === '') issues.push({ message: 'Give the note a title.', path: ['title'] })
131
- if (body.length > 2000) issues.push({ message: 'The note is at most 2000 characters.', path: ['body'] })
132
- return issues.length > 0 ? { issues } : { value: { title, body } }
133
- }
134
- ```
135
-
136
- ```tsx
137
- import { Acryl } from '@acryldev/blends'
138
-
139
- const app = new Acryl()
140
-
141
- app.post('/notes', async (c) => {
142
- const form = await c.req.parseBody()
143
- const checked = checkNote(form)
144
- if ('issues' in checked) {
145
- const messages = checked.issues.map((issue) => issue.message)
146
- return c.html(
147
- <form method="post" action="/notes">
148
- <ul role="alert">
149
- {messages.map((message) => (
150
- <li>{message}</li>
151
- ))}
152
- </ul>
153
- <input name="title" value={String(form.title ?? '')} />
154
- <textarea name="body">{String(form.body ?? '')}</textarea>
155
- <button type="submit">Save</button>
156
- </form>,
157
- 400,
158
- )
159
- }
160
- return c.redirect('/notes', 303)
161
- })
162
- ```
163
-
164
- Escaping is automatic in JSX: `{String(form.title)}` is safe to put in a page. Use `dangerouslySetInnerHTML` only for text you wrote yourself, such as a `<style>` or `<script>` block.
165
-
166
- ## A JSON API that shares the rules
167
-
168
- Wrap `checkNote` as a Standard Schema (an object with a `~standard.validate` function) and give it to `schemaValidator`. A failure answers 400 with `{ error, issues: [{ message, path }] }`.
169
- Build the API app by **chaining** the routes on `new Acryl()`, because the typed client and `testClient` only know chained routes:
170
-
171
- ```ts
172
- import { Acryl } from '@acryldev/blends'
173
- import { schemaValidator, type StandardSchema } from '@acryldev/blends/schema-validator'
174
-
175
- const NoteSchema: StandardSchema<NoteInput> = {
176
- '~standard': { validate: (value) => checkNote(value) },
177
- }
178
-
179
- export const api = new Acryl()
180
- .get('/', (c) => c.json({ notes: [] as NoteInput[] }, 200))
181
- .post('/', schemaValidator('json', NoteSchema), (c) => c.json({ note: c.req.valid('json') }, 201))
182
- .get('/:id', (c) => (c.req.param('id') === '1' ? c.json({ note: { title: 't', body: '' } }, 200) : c.json({ error: 'No such note.' }, 404)))
183
- ```
184
-
185
- Mount it below the pages with `app.route('/api/notes', api)`.
186
-
187
- ## Testing every route
188
-
189
- Call the app with `app.request`. A form POST needs a body and the cookie of a signed-in user, which a test reads from the sign-up response's `set-cookie` header:
190
-
191
- ```ts
192
- const response = await app.request('/signup', {
193
- method: 'POST',
194
- body: new URLSearchParams({ email: 'a@example.com', password: 'correct horse' }),
195
- })
196
- const cookie = (response.headers.get('set-cookie') ?? '').split(';')[0] ?? ''
197
- await app.request('/notes', { headers: { cookie } })
198
- ```
199
-
200
- For the typed API use `testClient` ([Testing helper](../helpers/testing.md)); the cookie goes in the second argument of each call:
201
-
202
- ```ts
203
- import { testClient } from '@acryldev/blends/testing'
204
-
205
- const client = testClient(api)
206
- const created = await client.index.$post({ json: { title: 'First', body: 'hello' } }, { headers: { cookie } })
207
- const { note } = await created.json()
208
- const one = await client[':id'].$get({ param: { id: '1' } }, { headers: { cookie } })
209
- ```
210
-
211
- A route mounted at `'/'` is `client.index` and `'/:id'` is `client[':id']`.
212
-
213
- ## A part of the page that reacts in the browser
214
-
215
- A live character counter or an instant filter needs a little JavaScript in the page. The simplest way, with no build step, is a `<script>` in the server-rendered page:
216
-
217
- ```tsx
218
- const counter = `
219
- const area = document.getElementById('body')
220
- const out = document.getElementById('count')
221
- const show = () => { out.textContent = area.value.length + ' / ' + area.maxLength }
222
- area.addEventListener('input', show)
223
- show()
224
- `
225
-
226
- export const Field = () => (
227
- <>
228
- <textarea id="body" name="body" maxlength={2000} />
229
- <small id="count" aria-live="polite" />
230
- <script dangerouslySetInnerHTML={{ __html: counter }} />
231
- </>
232
- )
233
- ```
234
-
235
- [Client Components](jsx-dom.md) (`acrylblends/jsx/dom`) are for pages that need components and state in the browser; on Node, [Client components without a bundler](client-modules.md) serves them to the browser with one script tag, or bundle them with Vite or esbuild.
@@ -1,33 +0,0 @@
1
- # Helpers
2
-
3
- Helpers are available to assist in developing your application. Unlike middleware, they don't act as handlers, but rather provide useful functions.
4
-
5
- For instance, here's how to use the [Cookie helper](../helpers/cookie.md):
6
-
7
- ```ts
8
- import { getCookie, setCookie } from '@acryldev/blends/cookie'
9
-
10
- const app = new Acryl()
11
-
12
- app.get('/cookie', (c) => {
13
- const yummyCookie = getCookie(c, 'yummy_cookie')
14
- // ...
15
- setCookie(c, 'delicious_cookie', 'macha')
16
- //
17
- })
18
- ```
19
-
20
- ## Available Helpers
21
-
22
- - [Accepts](../helpers/accepts.md)
23
- - [Adapter](../helpers/adapter.md)
24
- - [Cookie](../helpers/cookie.md)
25
- - [css](../helpers/css.md)
26
- - [Dev](../helpers/dev.md)
27
- - [Factory](../helpers/factory.md)
28
- - [html](../helpers/html.md)
29
- - [JWT](../helpers/jwt.md)
30
- - [SSG](../helpers/ssg.md)
31
- - [Streaming](../helpers/streaming.md)
32
- - [Testing](../helpers/testing.md)
33
- - [WebSocket](../helpers/websocket.md)