create-acrylblends 0.2.1 → 0.2.2

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 (42) hide show
  1. package/README.md +14 -1
  2. package/dist/index.d.ts +1 -1
  3. package/dist/index.js +33 -6
  4. package/dist/index.js.map +1 -1
  5. package/docs/framework/README.md +2 -1
  6. package/docs/framework/UPSTREAM.md +1 -1
  7. package/docs/framework/api/summary.md +6 -3
  8. package/docs/framework/cordis/node-server.md +3 -0
  9. package/docs/framework/getting-started/deploy.md +133 -0
  10. package/docs/framework/getting-started/nodejs.md +37 -16
  11. package/docs/framework/guides/client-modules.md +175 -0
  12. package/docs/framework/guides/forms-and-sessions.md +1 -1
  13. package/docs/framework/guides/jsx-dom.md +6 -1
  14. package/docs/framework/guides/validation.md +87 -0
  15. package/docs/framework/helpers/testing.md +17 -0
  16. package/docs/framework/upstream.json +3 -3
  17. package/package.json +2 -2
  18. package/templates/nodejs/gitignore +1 -0
  19. package/templates/nodejs/package.json +5 -4
  20. package/templates/nodejs/src/app.ts +5 -5
  21. package/templates/nodejs/src/client/counter.tsx +12 -0
  22. package/templates/nodejs/src/client/tsconfig.json +15 -0
  23. package/templates/nodejs/src/index.ts +16 -4
  24. package/templates/nodejs/src/page.tsx +12 -0
  25. package/templates/nodejs/src/routes.ts +10 -0
  26. package/templates/nodejs/test/app.test.ts +10 -0
  27. package/templates/nodejs/test/server.test.ts +48 -0
  28. package/templates/nodejs/tsconfig.json +2 -1
  29. package/templates/notes/gitignore +5 -0
  30. package/templates/notes/package.json +23 -0
  31. package/templates/notes/src/app.ts +7 -0
  32. package/templates/notes/src/auth.ts +55 -0
  33. package/templates/notes/src/client/counter.tsx +21 -0
  34. package/templates/notes/src/client/tsconfig.json +15 -0
  35. package/templates/notes/src/db.ts +70 -0
  36. package/templates/notes/src/index.ts +22 -0
  37. package/templates/notes/src/notes-app.ts +199 -0
  38. package/templates/notes/src/schema.ts +38 -0
  39. package/templates/notes/src/views.tsx +134 -0
  40. package/templates/notes/test/notes.test.ts +245 -0
  41. package/templates/notes/test/server.test.ts +59 -0
  42. package/templates/notes/tsconfig.json +19 -0
@@ -0,0 +1,175 @@
1
+ # Client components without a bundler
2
+
3
+ A page can run [client components](jsx-dom.md) written in TypeScript and JSX with no bundler and no build configuration. `clientModules` from
4
+ `acrylblends/node-server` serves a folder of client modules to the browser: each `.tsx`, `.ts` or `.jsx` file is compiled when the browser asks
5
+ for it, with your app's own `typescript`, and the framework's browser imports are pointed at the browser builds the package ships. The page
6
+ needs one script tag.
7
+
8
+ It runs on Node, the runtime the framework targets. For a large client app with many npm packages, a bundler (Vite, esbuild) remains the
9
+ better tool; see [The `acrylblends/jsx/dom` runtime](jsx-dom.md#the-acrylblendsjsxdom-runtime).
10
+
11
+ ## Set up
12
+
13
+ The routes, with the type the browser's typed client uses, in a file of their own (`app.ts`):
14
+
15
+ ```ts
16
+ import { Acryl } from 'acrylblends'
17
+
18
+ export const app = new Acryl()
19
+ .get('/', (c) =>
20
+ c.html(
21
+ '<!doctype html><div id="counter"></div><p id="greeting"></p>' +
22
+ '<script type="module" src="/client/counter.tsx"></script>'
23
+ )
24
+ )
25
+ .get('/api/hello', (c) => c.json({ hello: 'browser' }))
26
+
27
+ export type AppType = typeof app
28
+ ```
29
+
30
+ The Node entry routes the client modules next to them (`site.ts`):
31
+
32
+ ```ts
33
+ import { Acryl } from 'acrylblends'
34
+ import { clientModules, serve } from 'acrylblends/node-server'
35
+ import { app } from './app.ts'
36
+
37
+ const site = new Acryl()
38
+ .route('/', app)
39
+ .route('/client', clientModules({ root: 'src/client', compiled: 'dist/client' }))
40
+
41
+ serve({ fetch: site.fetch, port: 3000 })
42
+ ```
43
+
44
+ A client component (`src/client/counter.tsx`), with a helper module beside it (`src/client/parts/label.ts`):
45
+
46
+ ```tsx
47
+ import { render, useState } from 'acrylblends/jsx/dom'
48
+ import { hc } from 'acrylblends/client'
49
+ import type { AppType } from '../../app.ts'
50
+ import { label } from './parts/label.ts'
51
+
52
+ const Counter = () => {
53
+ const [count, setCount] = useState(0)
54
+ return <button onClick={() => setCount(count + 1)}>{label(count)}</button>
55
+ }
56
+
57
+ render(<Counter />, document.getElementById('counter')!)
58
+
59
+ const client = hc<AppType>(location.origin)
60
+ const { hello } = await (await client.api.hello.$get()).json()
61
+ document.getElementById('greeting')!.textContent = `hello ${hello}`
62
+ ```
63
+
64
+ ```ts
65
+ export const label = (count: number): string => `Count ${count}`
66
+ ```
67
+
68
+ Start the site with `node site.ts` and open `http://localhost:3000`. Edit `counter.tsx` and reload: the module is compiled again.
69
+
70
+ Your editor checks the client folder as browser code with its own `src/client/tsconfig.json`: the DOM library, the DOM renderer, no Node
71
+ types. This is why `AppType` comes from `app.ts`, which does not import the Node adapter.
72
+
73
+ ```json
74
+ {
75
+ "compilerOptions": {
76
+ "target": "ES2024",
77
+ "lib": ["ES2024", "DOM", "DOM.Iterable"],
78
+ "module": "NodeNext",
79
+ "moduleResolution": "NodeNext",
80
+ "strict": true,
81
+ "noEmit": true,
82
+ "allowImportingTsExtensions": true,
83
+ "jsx": "react-jsx",
84
+ "jsxImportSource": "acrylblends/jsx/dom",
85
+ "types": []
86
+ },
87
+ "include": ["**/*.ts", "**/*.tsx"]
88
+ }
89
+ ```
90
+
91
+ ## Server markup and `hydrateRoot`
92
+
93
+ A page can carry server-rendered markup for an island and take it over in the browser with `hydrateRoot` from `acrylblends/jsx/dom/client`:
94
+
95
+ ```tsx
96
+ import { useState } from 'acrylblends/jsx/dom'
97
+ import { hydrateRoot } from 'acrylblends/jsx/dom/client'
98
+
99
+ const Counter = () => {
100
+ const [count, setCount] = useState(0)
101
+ return <button onClick={() => setCount(count + 1)}>Count {count}</button>
102
+ }
103
+
104
+ hydrateRoot(document.getElementById('island')!, <Counter />)
105
+ ```
106
+
107
+ The DOM renderer does not reuse server markup: `hydrateRoot` renders the component and replaces the element's children with its output
108
+ in one step, so the page shows the server markup until the module runs and the component from then on, with no empty frame between. The
109
+ server's nodes are gone afterwards, together with anything the visitor did to them before the module ran: focus, a selection, text typed
110
+ into an input. Keep the server markup the same as the component's first render, so the swap does not show, and keep inputs out of the
111
+ server markup of an island, or render them only in the browser.
112
+
113
+ ## How the imports reach the browser
114
+
115
+ - JSX in a client module always compiles for the DOM renderer (`acrylblends/jsx/dom`), whatever the server's `tsconfig.json` says. A file's
116
+ own `/** @jsxImportSource ... */` comment still wins.
117
+ - `acrylblends/jsx/dom`, its `jsx-runtime`, `jsx-dev-runtime` and `client` are one browser module (`@acrylblends/jsx-dom.js`), and
118
+ `acrylblends/client` is another (`@acrylblends/client.js`). Neither imports anything. The same app serves them, and each import is
119
+ rewritten to a URL relative to the module, so the setup works under whatever path you route `clientModules` at.
120
+ - Import your own modules with their file names, as the browser fetches them: `import { label } from './parts/label.ts'`.
121
+ - Another package (`import confetti from 'canvas-confetti'`) is left as it is: add an
122
+ [import map](https://developer.mozilla.org/docs/Web/HTML/Element/script/type/importmap) to the page for it, or use a bundler.
123
+ - `.js` and `.mjs` files are served unchanged.
124
+
125
+ A module is compiled once and kept in memory until its file changes, up to 16 MiB of compiled code (the least recently served goes first;
126
+ set `cacheBytes` to change the bound). Responses carry an `ETag` and `Cache-Control: no-cache`, so the browser revalidates and an edit shows
127
+ on the next reload. Only files inside the folder are served: a path with `..` or a dot segment, a `.d.ts` file, a symbolic link out of the
128
+ folder and other file types answer 404.
129
+
130
+ ## In production
131
+
132
+ Templates install `typescript` as a development dependency, and a deploy that leaves those out (`npm ci --omit=dev`) has no compiler.
133
+ Compile the client folder once when you build, as the `build` script of your `package.json`:
134
+
135
+ ```json
136
+ {
137
+ "scripts": {
138
+ "build": "acrylblends build-client"
139
+ }
140
+ }
141
+ ```
142
+
143
+ `acrylblends build-client [root] [outDir]` (from acrylblends 0.7.2; `src/client` and `dist/client` when not given) calls
144
+ `buildClientModules`. With an earlier version, or without the command line tool, call the function itself:
145
+
146
+ ```json
147
+ {
148
+ "scripts": {
149
+ "build": "node --input-type=module -e \"import { buildClientModules } from 'acrylblends/node-server'; buildClientModules({ root: 'src/client', outDir: 'dist/client' })\""
150
+ }
151
+ }
152
+ ```
153
+
154
+ It writes each module compiled to `dist/client` at the same path and file name, so the page's URLs stay the same, and copies the two
155
+ browser modules to `dist/client/@acrylblends/`. Run it where `typescript` is installed, before the development dependencies are removed.
156
+
157
+ With `NODE_ENV=production` and the `compiled` option set, `clientModules` serves only that folder and compiles nothing. A module that is in
158
+ `src/client` but missing from `dist/client` answers 500 with a message to build again, and a `compiled` folder that does not exist stops the
159
+ server at startup. Outside production, modules are always compiled on request, so a stale `dist/client` never hides an edit.
160
+
161
+ When `typescript` is missing where a module has to be compiled, the module answers 500 with the message
162
+ `... is a client module, and compiling it needs the typescript package in this app: npm install --save-dev typescript`.
163
+
164
+ ## Reference
165
+
166
+ `clientModules(options)` returns an app; route it where the page's script tags point.
167
+
168
+ | Option | Meaning |
169
+ | --- | --- |
170
+ | `root` | The folder of client modules, absolute or relative to the working directory. |
171
+ | `compiled` | The folder `buildClientModules` wrote. Served instead of compiling when `NODE_ENV` is `production`. |
172
+ | `cacheBytes` | The bound of the in-memory cache of compiled modules, in bytes. 16 MiB when not given. |
173
+
174
+ `buildClientModules({ root, outDir })` compiles every module below `root` (dot files, `node_modules` and `.d.ts` files skipped) into `outDir`,
175
+ which must not lie inside `root`, and returns the paths it wrote. Files already in `outDir` that no source produces are left there.
@@ -228,4 +228,4 @@ export const Field = () => (
228
228
  )
229
229
  ```
230
230
 
231
- [Client Components](jsx-dom.md) (`acrylblends/jsx/dom`) are for pages that need components and state in the browser; they have to be bundled for the browser first (with Vite or esbuild).
231
+ [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.
@@ -2,7 +2,9 @@
2
2
 
3
3
  `acrylblends/jsx` supports not only server side but also client side. This means that it is possible to create an interactive UI that runs in the browser. We call it Client Components or `acrylblends/jsx/dom`.
4
4
 
5
- It is fast and very small. The counter program in `acrylblends/jsx/dom` is only 2.8KB with Brotli compression, but 47.8KB for React.
5
+ It is small and imports nothing. Measured with Node's `zlib.brotliCompressSync` at the highest quality: the whole runtime as
6
+ [`clientModules`](client-modules.md) serves it (`jsx-dom.js`, not minified) is 11,209 bytes with Brotli compression, and the counter
7
+ below, bundled and minified with tsdown so only the parts it uses are kept, is 5,804 bytes.
6
8
 
7
9
  This section introduces Client Components-specific features.
8
10
 
@@ -272,6 +274,9 @@ export default function App() {
272
274
 
273
275
  ## The `acrylblends/jsx/dom` runtime
274
276
 
277
+ On Node you can skip the bundler: [Client components without a bundler](client-modules.md) serves `.tsx` client modules to the browser with
278
+ this runtime and one script tag, in development and in production.
279
+
275
280
  There is a small JSX Runtime for Client Components. Using this will result in smaller bundled results than using `acrylblends/jsx`. Specify `acrylblends/jsx/dom` in `tsconfig.json`. For Deno, modify the deno.json.
276
281
 
277
282
  ```json
@@ -144,6 +144,93 @@ app.post(
144
144
  )
145
145
  ```
146
146
 
147
+ ## Validating an HTML form
148
+
149
+ A browser posts a `<form>` as `application/x-www-form-urlencoded`, or as `multipart/form-data` when it has `enctype="multipart/form-data"` (needed
150
+ for file inputs). `validator('form', ...)` parses both. Each field arrives as a `string`, a file input as a `File`, and a name that appears more
151
+ than once (several checkboxes, or a name ending in `[]`) as an array, so the value has the type `Record<string, string | File | (string | File)[]>`.
152
+
153
+ This page shows a form and re-renders it with a message when a field is wrong:
154
+
155
+ ```ts
156
+ import { Acryl } from 'acrylblends'
157
+ import { html } from 'acrylblends/html'
158
+ import { validator } from 'acrylblends/validator'
159
+
160
+ const page = (error?: string) => html`<!doctype html>
161
+ <form method="post" action="/notes" enctype="multipart/form-data">
162
+ <input name="title" required>
163
+ <textarea name="body"></textarea>
164
+ <input type="file" name="attachment">
165
+ <button>Save</button>
166
+ ${error === undefined ? '' : html`<p role="alert">${error}</p>`}
167
+ </form>`
168
+
169
+ const app = new Acryl()
170
+ .get('/notes/new', (c) => c.html(page()))
171
+ .post(
172
+ '/notes',
173
+ validator('form', (form, c) => {
174
+ const { title, body, attachment } = form
175
+ if (typeof title !== 'string' || title.trim() === '') return c.html(page('Title is required'), 400)
176
+ if (body !== undefined && typeof body !== 'string') return c.html(page('Body must be text'), 400)
177
+ if (attachment !== undefined && !(attachment instanceof File)) return c.html(page('Attachment must be one file'), 400)
178
+ return {
179
+ title: title.trim(),
180
+ body: body ?? '',
181
+ // A file input left empty still sends a part: a File with no name and no bytes.
182
+ attachment: attachment !== undefined && attachment.size > 0 ? attachment : undefined,
183
+ }
184
+ }),
185
+ (c) => {
186
+ const { title, attachment } = c.req.valid('form') // { title: string, body: string, attachment: File | undefined }
187
+ return c.text(`Saved ${title}${attachment === undefined ? '' : ` with ${attachment.name}`}`, 201)
188
+ }
189
+ )
190
+ ```
191
+
192
+ The messages are escaped by `html`, so a field value shown back in the page cannot inject markup.
193
+
194
+ ### With a schema
195
+
196
+ `schemaValidator('form', schema)` takes the same value. It answers a failure with 400 and JSON issues, which suits a form your own script submits
197
+ with `fetch()`:
198
+
199
+ ```ts
200
+ import * as z from 'zod'
201
+ import { schemaValidator } from 'acrylblends/schema-validator'
202
+
203
+ const NoteForm = z.object({
204
+ title: z.string().trim().min(1, 'Title is required'),
205
+ body: z.string().default(''),
206
+ attachment: z.instanceof(File).optional(),
207
+ })
208
+
209
+ app.post('/api/notes', schemaValidator('form', NoteForm), (c) => {
210
+ const { title } = c.req.valid('form') // typed by the schema's output
211
+ return c.json({ title }, 201)
212
+ })
213
+ ```
214
+
215
+ For a plain HTML form, call the schema inside `validator('form', ...)` to re-render the page with the first message instead:
216
+
217
+ ```ts
218
+ validator('form', (form, c) => {
219
+ const result = NoteForm.safeParse(form)
220
+ return result.success ? result.data : c.html(page(result.error.issues[0]?.message), 400)
221
+ })
222
+ ```
223
+
224
+ To test a form route, send a `FormData`: `app.request` sets the `multipart/form-data` content type with its boundary itself.
225
+
226
+ ```ts
227
+ const form = new FormData()
228
+ form.set('title', 'Groceries')
229
+ form.set('attachment', new File(['milk'], 'list.txt', { type: 'text/plain' }))
230
+ const res = await app.request('/notes', { method: 'POST', body: form })
231
+ // res.status === 201, await res.text() === 'Saved Groceries with list.txt'
232
+ ```
233
+
147
234
  ## Multiple validators
148
235
 
149
236
  You can also include multiple validators to validate different parts of request:
@@ -99,3 +99,20 @@ describe('Search Endpoint', () => {
99
99
  })
100
100
  })
101
101
  ```
102
+
103
+ ### Default request options
104
+
105
+ `testClient(app, env?, executionCtx?, options?)` takes the client's request options as its fourth argument, so headers every request of a test
106
+ needs, such as a session cookie, are set once. Headers given to a single call are merged over them.
107
+
108
+ ```ts
109
+ import { Acryl } from 'acrylblends'
110
+ import { getCookie } from 'acrylblends/cookie'
111
+ import { testClient } from 'acrylblends/testing'
112
+
113
+ const app = new Acryl().get('/me', (c) => c.json({ session: getCookie(c, 'session') ?? null }))
114
+
115
+ const client = testClient(app, undefined, undefined, { headers: { cookie: 'session=abc' } })
116
+ await (await client.me.$get()).json() // { session: 'abc' }
117
+ await (await client.me.$get(undefined, { headers: { cookie: 'session=xyz' } })).json() // { session: 'xyz' }
118
+ ```
@@ -2,8 +2,8 @@
2
2
  "source": {
3
3
  "repo": "acryldev/acryl",
4
4
  "path": "docs/framework",
5
- "commit": "524406d2033cdc5ca5e01207f9ce29543bbf221b"
5
+ "commit": "cdc083e1bbaedaeafa7494fe646bdb202ce86d09"
6
6
  },
7
- "files": 89,
8
- "digest": "sha256:fe2da945c3286e316a0412b2d3cfccc4dbf8d1c082e283b77606b45e27b778aa"
7
+ "files": 91,
8
+ "digest": "sha256:964e5ff58d487ce53394469d359a251265a3ef093354f55b6b4c47c55051774b"
9
9
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-acrylblends",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "Create an Acryl app: npm create acrylblends@latest",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -37,7 +37,7 @@
37
37
  "scaffold"
38
38
  ],
39
39
  "dependencies": {
40
- "acrylblends": "^0.7.1"
40
+ "acrylblends": "^0.7.2"
41
41
  },
42
42
  "publishConfig": {
43
43
  "access": "public"
@@ -1 +1,2 @@
1
1
  node_modules/
2
+ dist/
@@ -10,13 +10,14 @@
10
10
  "dev": "node --watch --import acrylblends/node-server/register src/index.ts",
11
11
  "start": "node --import acrylblends/node-server/register src/index.ts",
12
12
  "test": "node --import acrylblends/node-server/register --test \"test/**/*.test.{ts,tsx}\"",
13
- "check": "tsc --noEmit"
13
+ "check": "tsc --noEmit && tsc --noEmit -p src/client",
14
+ "build": "acrylblends build-client"
14
15
  },
15
16
  "dependencies": {
16
- "__PACKAGE__": "__RANGE__"
17
+ "__PACKAGE__": "__RANGE__",
18
+ "typescript": "6.0.3"
17
19
  },
18
20
  "devDependencies": {
19
- "@types/node": "^24.0.0",
20
- "typescript": "6.0.3"
21
+ "@types/node": "^24.0.0"
21
22
  }
22
23
  }
@@ -1,10 +1,10 @@
1
1
  import { __CLASS__ } from '__PACKAGE__'
2
- import { aboutPage } from './page.tsx'
2
+ import { clientModules } from '__PACKAGE__/node-server'
3
+ import { routes } from './routes.ts'
3
4
 
5
+ // Client components without a bundler: src/client is compiled when the browser asks; `npm run build` compiles it once for production (NODE_ENV=production serves only dist/client).
4
6
  const app = new __CLASS__()
5
-
6
- app.get('/', (c) => c.text('__CLASS__!'))
7
-
8
- app.get('/about', (c) => c.html(aboutPage()))
7
+ .route('/', routes)
8
+ .route('/client', clientModules({ root: 'src/client', compiled: 'dist/client' }))
9
9
 
10
10
  export default app
@@ -0,0 +1,12 @@
1
+ import { render, useState } from '__PACKAGE__/jsx/dom'
2
+
3
+ const Counter = () => {
4
+ const [count, setCount] = useState(0)
5
+ return (
6
+ <button type="button" onClick={() => setCount(count + 1)}>
7
+ Count {count}
8
+ </button>
9
+ )
10
+ }
11
+
12
+ render(<Counter />, document.getElementById('counter')!)
@@ -0,0 +1,15 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2024",
4
+ "lib": ["ES2024", "DOM", "DOM.Iterable"],
5
+ "module": "NodeNext",
6
+ "moduleResolution": "NodeNext",
7
+ "strict": true,
8
+ "noEmit": true,
9
+ "allowImportingTsExtensions": true,
10
+ "jsx": "react-jsx",
11
+ "jsxImportSource": "__PACKAGE__/jsx/dom",
12
+ "types": []
13
+ },
14
+ "include": ["**/*.ts", "**/*.tsx"]
15
+ }
@@ -1,9 +1,21 @@
1
1
  import { serve } from '__PACKAGE__/node-server'
2
2
  import app from './app.ts'
3
3
 
4
- const server = serve({ fetch: app.fetch, port: Number(process.env.PORT ?? 3000) }, (info) => {
5
- console.log(`listening on http://localhost:${info.port}`)
4
+ const port = Number(process.env.PORT || 3000)
5
+ // Local by default. Behind a reverse proxy on the same machine this is right; in a container set HOST=0.0.0.0.
6
+ const hostname = process.env.HOST || '127.0.0.1'
7
+
8
+ const server = serve({ fetch: app.fetch, port, hostname }, (info) => {
9
+ console.log(`listening on http://${info.address}:${info.port}`)
6
10
  })
7
11
 
8
- process.once('SIGINT', () => server.close(() => process.exit(0)))
9
- process.once('SIGTERM', () => server.close(() => process.exit(0)))
12
+ // Stop taking requests, let the ones in flight finish, then exit. A connection that never ends cannot keep the process alive past 10 seconds.
13
+ function shutdown(): void {
14
+ server.close(() => {
15
+ process.exit(0)
16
+ })
17
+ server.closeIdleConnections()
18
+ setTimeout(() => process.exit(1), 10_000).unref()
19
+ }
20
+ process.once('SIGINT', shutdown)
21
+ process.once('SIGTERM', shutdown)
@@ -12,3 +12,15 @@ export const aboutPage = (): string => (<About />).toString()
12
12
  export const failingPage = (): string => {
13
13
  throw new Error('a page failed')
14
14
  }
15
+
16
+ /** A page with one client component: `src/client/counter.tsx` runs in the browser, compiled on request by `clientModules` (see src/app.ts). */
17
+ export const counterPage = (): string =>
18
+ (
19
+ <html lang="en">
20
+ <body>
21
+ <h1>Counter</h1>
22
+ <div id="counter" />
23
+ <script type="module" src="/client/counter.tsx" />
24
+ </body>
25
+ </html>
26
+ ).toString()
@@ -0,0 +1,10 @@
1
+ import { __CLASS__ } from '__PACKAGE__'
2
+ import { aboutPage, counterPage } from './page.tsx'
3
+
4
+ /** The routes, in a file that does not import the Node adapter, so browser code can import the type: `import type { AppType } from '../routes.ts'`. */
5
+ export const routes = new __CLASS__()
6
+ .get('/', (c) => c.text('__CLASS__!'))
7
+ .get('/about', (c) => c.html(aboutPage()))
8
+ .get('/counter', (c) => c.html(counterPage()))
9
+
10
+ export type AppType = typeof routes
@@ -28,3 +28,13 @@ test('an error thrown in a .tsx file names the .tsx line in its stack', async ()
28
28
  }
29
29
  assert.match(stack, /page\.tsx:\d+/)
30
30
  })
31
+
32
+ test('GET /counter serves a page with a client component, and the component is compiled for the browser', async () => {
33
+ const page = await app.request('/counter')
34
+ assert.equal(page.status, 200)
35
+ assert.match(await page.text(), /<script type="module" src="\/client\/counter\.tsx">/)
36
+ const module = await app.request('/client/counter.tsx')
37
+ assert.equal(module.status, 200)
38
+ assert.match(module.headers.get('content-type') ?? '', /javascript/)
39
+ assert.doesNotMatch(await module.text(), /<Counter|<button/)
40
+ })
@@ -0,0 +1,48 @@
1
+ import assert from 'node:assert/strict'
2
+ import { spawn } from 'node:child_process'
3
+ import { once } from 'node:events'
4
+ import { test } from 'node:test'
5
+
6
+ /** Start `src/index.ts` the way `npm start` does, on a port the system chooses, and read the address it prints. */
7
+ async function start(env: Record<string, string> = {}) {
8
+ const child = spawn(
9
+ process.execPath,
10
+ ['--import', '__PACKAGE__/node-server/register', 'src/index.ts'],
11
+ { env: { ...process.env, PORT: '0', ...env }, stdio: ['ignore', 'pipe', 'inherit'] },
12
+ )
13
+ let out = ''
14
+ const address = await new Promise<string>((resolve, reject) => {
15
+ child.once('exit', (code) =>
16
+ reject(new Error(`the server exited with ${code} before it listened`)),
17
+ )
18
+ child.stdout.on('data', (chunk) => {
19
+ out += chunk
20
+ const match = /listening on (http:\/\/\S+)/.exec(out)
21
+ if (match?.[1]) resolve(match[1])
22
+ })
23
+ })
24
+ return { child, address }
25
+ }
26
+
27
+ test('the server listens on 127.0.0.1 unless HOST says otherwise', async () => {
28
+ const { child, address } = await start()
29
+ try {
30
+ assert.match(address, /^http:\/\/127\.0\.0\.1:\d+$/)
31
+ } finally {
32
+ child.kill('SIGTERM')
33
+ await once(child, 'exit')
34
+ }
35
+ })
36
+
37
+ for (const signal of ['SIGTERM', 'SIGINT'] as const) {
38
+ test(`${signal} stops the server cleanly and frees the port`, async () => {
39
+ const { child, address } = await start()
40
+ assert.equal((await fetch(address)).status, 200)
41
+ const started = Date.now()
42
+ child.kill(signal)
43
+ const [code] = await once(child, 'exit')
44
+ assert.equal(code, 0)
45
+ assert.ok(Date.now() - started < 5000, 'the server took too long to stop')
46
+ await assert.rejects(fetch(address), 'the port should be free')
47
+ })
48
+ }
@@ -14,5 +14,6 @@
14
14
  "jsx": "react-jsx",
15
15
  "jsxImportSource": "__PACKAGE__/jsx"
16
16
  },
17
- "include": ["src", "test"]
17
+ "include": ["src", "test"],
18
+ "exclude": ["src/client"]
18
19
  }
@@ -0,0 +1,5 @@
1
+ node_modules/
2
+ *.db
3
+ *.db-*
4
+ .acrylblends/
5
+ dist/
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "__APP_NAME__",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "engines": {
7
+ "node": ">=22.19.0"
8
+ },
9
+ "scripts": {
10
+ "dev": "node --watch --import acrylblends/node-server/register src/index.ts",
11
+ "start": "node --import acrylblends/node-server/register src/index.ts",
12
+ "test": "node --import acrylblends/node-server/register --test \"test/**/*.test.{ts,tsx}\"",
13
+ "check": "tsc --noEmit && tsc --noEmit -p src/client",
14
+ "build": "acrylblends build-client"
15
+ },
16
+ "dependencies": {
17
+ "__PACKAGE__": "__RANGE__",
18
+ "typescript": "6.0.3"
19
+ },
20
+ "devDependencies": {
21
+ "@types/node": "^24.0.0"
22
+ }
23
+ }
@@ -0,0 +1,7 @@
1
+ import { openDb } from './db.ts'
2
+ import { createApp } from './notes-app.ts'
3
+
4
+ /** The database is opened here, once, so the server can close it when it stops. */
5
+ export const db = openDb()
6
+
7
+ export default createApp(db)
@@ -0,0 +1,55 @@
1
+ import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
2
+ import type { DatabaseSync } from 'node:sqlite'
3
+ import { promisify } from 'node:util'
4
+
5
+ const scryptAsync = promisify(scrypt) as (
6
+ password: string,
7
+ salt: Buffer,
8
+ length: number,
9
+ ) => Promise<Buffer>
10
+
11
+ export async function hashPassword(password: string): Promise<string> {
12
+ const salt = randomBytes(16)
13
+ const key = await scryptAsync(password, salt, 64)
14
+ return `${salt.toString('hex')}:${key.toString('hex')}`
15
+ }
16
+
17
+ export async function verifyPassword(password: string, stored: string): Promise<boolean> {
18
+ const [salt, key] = stored.split(':')
19
+ if (!salt || !key) return false
20
+ const expected = Buffer.from(key, 'hex')
21
+ const actual = await scryptAsync(password, Buffer.from(salt, 'hex'), expected.length)
22
+ return timingSafeEqual(actual, expected)
23
+ }
24
+
25
+ export function authStore(db: DatabaseSync) {
26
+ return {
27
+ findUser(email: string) {
28
+ return db.prepare('SELECT id, email, password_hash FROM users WHERE email = ?').get(email) as
29
+ | { id: number; email: string; password_hash: string }
30
+ | undefined
31
+ },
32
+ async createUser(email: string, password: string): Promise<number> {
33
+ const info = db
34
+ .prepare('INSERT INTO users (email, password_hash) VALUES (?, ?)')
35
+ .run(email, await hashPassword(password))
36
+ return Number(info.lastInsertRowid)
37
+ },
38
+ startSession(userId: number): string {
39
+ const token = randomBytes(32).toString('hex')
40
+ db.prepare('INSERT INTO sessions (token, user_id) VALUES (?, ?)').run(token, userId)
41
+ return token
42
+ },
43
+ userFor(token: string | undefined) {
44
+ if (!token) return undefined
45
+ return db
46
+ .prepare(
47
+ 'SELECT users.id AS id, users.email AS email FROM sessions JOIN users ON users.id = sessions.user_id WHERE token = ?',
48
+ )
49
+ .get(token) as { id: number; email: string } | undefined
50
+ },
51
+ endSession(token: string) {
52
+ db.prepare('DELETE FROM sessions WHERE token = ?').run(token)
53
+ },
54
+ }
55
+ }