@alxia/create 0.1.6 → 0.2.0

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 (65) hide show
  1. package/README.md +80 -25
  2. package/dist/args.d.ts +3 -1
  3. package/dist/args.d.ts.map +1 -1
  4. package/dist/index.js +19 -9
  5. package/dist/index.js.map +7 -7
  6. package/dist/main.d.ts +1 -1
  7. package/dist/main.d.ts.map +1 -1
  8. package/dist/registry.d.ts +2 -0
  9. package/dist/registry.d.ts.map +1 -1
  10. package/dist/versions.d.ts +5 -2
  11. package/dist/versions.d.ts.map +1 -1
  12. package/docs/README.md +16 -6
  13. package/docs/guide.md +438 -56
  14. package/docs/roadmap.md +24 -0
  15. package/docs/troubleshooting.md +146 -50
  16. package/package.json +16 -6
  17. package/templates/api/.env.example +9 -1
  18. package/templates/api/README.md +40 -12
  19. package/templates/api/openapi.yaml +13 -9
  20. package/templates/api/package.json +6 -4
  21. package/templates/api/src/app.spec.ts +42 -28
  22. package/templates/api/src/app.ts +13 -3
  23. package/templates/api/src/context.ts +3 -4
  24. package/templates/api/src/env.ts +20 -0
  25. package/templates/api/src/generated/alxia.ts +15 -5
  26. package/templates/api/src/generated/operations.ts +4 -4
  27. package/templates/api/src/generated/paths.ts +6 -6
  28. package/templates/api/src/generated/types.ts +14 -10
  29. package/templates/api/src/generated/zod.ts +6 -2
  30. package/templates/api/src/routes/todos.ts +2 -2
  31. package/templates/api/src/server.ts +8 -16
  32. package/templates/graphql/.dockerignore +6 -0
  33. package/templates/graphql/.env.example +3 -0
  34. package/templates/graphql/.vscode/extensions.json +3 -0
  35. package/templates/graphql/.vscode/settings.json +8 -0
  36. package/templates/graphql/Dockerfile +26 -0
  37. package/templates/graphql/README.md +171 -0
  38. package/templates/graphql/_biome.json +32 -0
  39. package/templates/graphql/codegen.ts +22 -0
  40. package/templates/graphql/gitignore +6 -0
  41. package/templates/graphql/package.json +34 -0
  42. package/templates/graphql/schema.graphql +26 -0
  43. package/templates/graphql/src/app.spec.ts +119 -0
  44. package/templates/graphql/src/app.ts +14 -0
  45. package/templates/graphql/src/context.ts +24 -0
  46. package/templates/graphql/src/env.ts +8 -0
  47. package/templates/graphql/src/generated/resolvers.ts +180 -0
  48. package/templates/graphql/src/graphql.d.ts +6 -0
  49. package/templates/graphql/src/resolvers.ts +42 -0
  50. package/templates/graphql/src/schema.ts +6 -0
  51. package/templates/graphql/src/server.ts +10 -0
  52. package/templates/graphql/src/store.ts +25 -0
  53. package/templates/graphql/tsconfig.json +25 -0
  54. package/templates/minimal/.dockerignore +6 -0
  55. package/templates/minimal/.vscode/extensions.json +3 -0
  56. package/templates/minimal/.vscode/settings.json +8 -0
  57. package/templates/minimal/Dockerfile +26 -0
  58. package/templates/minimal/README.md +107 -0
  59. package/templates/minimal/_biome.json +32 -0
  60. package/templates/minimal/gitignore +6 -0
  61. package/templates/minimal/package.json +25 -0
  62. package/templates/minimal/src/index.spec.ts +12 -0
  63. package/templates/minimal/src/index.ts +17 -0
  64. package/templates/minimal/tsconfig.json +25 -0
  65. package/templates/react-router/package.json +2 -2
package/docs/guide.md CHANGED
@@ -1,12 +1,15 @@
1
1
  # Guide
2
2
 
3
3
  How `bun create @alxia` asks, what each template writes, how the `api`
4
- project grows from its OpenAPI document, and how the command chooses the
5
- versions it writes.
4
+ project grows from its OpenAPI document and the `graphql` one from its
5
+ schema, and how the command chooses the versions it writes.
6
6
 
7
7
  - [Running it](#running-it)
8
+ - [The `minimal` template](#the-minimal-template)
8
9
  - [The `api` template](#the-api-template)
9
10
  - [Adding an operation](#adding-an-operation)
11
+ - [The `graphql` template](#the-graphql-template)
12
+ - [Adding a field](#adding-a-field)
10
13
  - [The `react-router` template](#the-react-router-template)
11
14
  - [Lint and format](#lint-and-format)
12
15
  - [Docker](#docker)
@@ -24,14 +27,14 @@ answer takes:
24
27
 
25
28
  ```
26
29
  Where should the project go? [alxia-app] my-app
27
- Which template? api or react-router [api]
30
+ Which template? minimal, api, graphql or react-router [minimal]
28
31
  ```
29
32
 
30
33
  then writes the project, runs `bun install` in it, and prints what to run
31
34
  next:
32
35
 
33
36
  ```
34
- Done: my-app holds the api template. Next:
37
+ Done: my-app holds the minimal template. Next:
35
38
 
36
39
  cd my-app
37
40
  bun dev
@@ -40,7 +43,7 @@ Done: my-app holds the api template. Next:
40
43
  | option | default | |
41
44
  | --- | --- | --- |
42
45
  | `[dir]` | asked, `alxia-app` | where to write: empty, or not there yet |
43
- | `--template <name>`, `--template=<name>`, `-t <name>` | asked, `api` | `api` or `react-router` |
46
+ | `--template <name>`, `--template=<name>`, `-t <name>` | asked, `minimal` | `minimal`, `api`, `graphql` or `react-router` |
44
47
  | `--no-install` | install | write the files, skip `bun install` |
45
48
  | `--help`, `-h` | | the usage, and nothing else |
46
49
 
@@ -57,8 +60,8 @@ files, as the README's `docker build -t` and `docker run`: `bun create
57
60
  to the package `@scope/create`, and npm maps `npm create @scope` the same
58
61
  way. Any of the three runs the same bin, on Bun.
59
62
 
60
- Both templates are files shipped in this package, under
61
- `templates/api/` and `templates/react-router/`, and copied as they are:
63
+ The templates are files shipped in this package, under `templates/minimal/`,
64
+ `templates/api/`, `templates/graphql/` and `templates/react-router/`, and copied as they are:
62
65
  nothing is downloaded but the dependencies. `package.json` is written
63
66
  again, with the directory's name, alxia's versions and the newest of the
64
67
  others ([Versions](#versions)); in every other text file, the template's
@@ -69,6 +72,78 @@ publish` leaves those out of a tarball, and `_biome.json` as `biome.json`,
69
72
  since alxia's own Biome refuses a second root configuration inside its
70
73
  repository ([Lint and format](#lint-and-format)).
71
74
 
75
+ ## The `minimal` template
76
+
77
+ The template to try alxia with: one file, one dependency, a test.
78
+
79
+ ```
80
+ my-app/
81
+ ├── src/
82
+ │ ├── index.ts the app, exported; listens only when it is the entry file
83
+ │ └── index.spec.ts bun test: app.request(), no port
84
+ ├── package.json
85
+ ├── tsconfig.json
86
+ ├── biome.json Biome: lint, format, imports sorted
87
+ ├── .vscode/ Biome's extension recommended, format on save
88
+ ├── Dockerfile bun run build, then dist/ alone, on oven/bun:1-alpine
89
+ ├── .dockerignore
90
+ ├── .gitignore
91
+ └── README.md
92
+ ```
93
+
94
+ ```ts
95
+ // src/index.ts
96
+ import { alxia } from "@alxia/core";
97
+
98
+ export const app = alxia().get("/", ({ reply }) =>
99
+ reply(200, { hello: "world" }),
100
+ );
101
+
102
+ // Only when this file is the entry: the test imports `app` and listens on
103
+ // no port.
104
+ if (import.meta.main) {
105
+ // In dev, the URL and the route table; in production, the URL alone. On
106
+ // SIGINT and SIGTERM, listen drains the requests in flight and exits.
107
+ app.listen({
108
+ port: Number(Bun.env["PORT"] ?? 3000),
109
+ onListen: ({ dev, table, url }) =>
110
+ console.log(dev ? table : `listening on ${url}`),
111
+ });
112
+ }
113
+ ```
114
+
115
+ `bun dev` runs `NODE_ENV=development bun --hot src/index.ts`, which
116
+ prints the route table `@alxia/core` writes in dev — on under
117
+ `NODE_ENV=development` alone; `bun start` runs `NODE_ENV=production bun dist/index.js`, what
118
+ `bun run build` wrote, and the image sets `NODE_ENV=production`, under
119
+ which it prints the URL alone. `import.meta.main` is why
120
+ the spec can import `app` without opening a port, and why the one file is
121
+ both the app and its server. `listen` shuts the app down gracefully on
122
+ `SIGINT` and `SIGTERM`, then exits, so as a container's process 1 Bun stops
123
+ at once on `docker stop`: the template installs no handler of its own.
124
+
125
+ The spec:
126
+
127
+ ```ts
128
+ // src/index.spec.ts
129
+ import { expect, test } from "bun:test";
130
+ import { app } from "./index";
131
+
132
+ test("GET / says hello", async () => {
133
+ const response = await app.request("/");
134
+ expect(response.status).toBe(200);
135
+ expect(await response.json()).toEqual({ hello: "world" });
136
+ });
137
+ ```
138
+
139
+ What it leaves out is the point: one dependency, `@alxia/core`; no
140
+ OpenAPI, no code generation, no validator, no `.env` file (`PORT` is read
141
+ as it is). `bun run verify` is `check:ci`, `typecheck`, then `test`. When
142
+ the app outgrows one file, move to the layout of the
143
+ [`api`](#the-api-template) or [`graphql`](#the-graphql-template) template,
144
+ or read
145
+ [`@alxia/core`'s guide](https://github.com/softistx/alxia/tree/develop/packages/core/docs).
146
+
72
147
  ## The `api` template
73
148
 
74
149
  ```
@@ -77,18 +152,19 @@ my-api/
77
152
  ├── openapi-codegen.config.ts how `bun run generate` reads it
78
153
  ├── src/
79
154
  │ ├── generated/ what `bun run generate` writes: committed, never edited
155
+ │ ├── env.ts defineEnv from @alxia/env: PORT, API_KEY and API_DOCS
80
156
  │ ├── context.ts the base: what every route reads, and its Register
81
157
  │ ├── routes/todos.ts defineRoutes(): one route per operation
82
- │ ├── app.ts the app: the base, then the routes, and its type
83
- │ ├── app.spec.ts bun test: app.request(), no port, and matchesSpec
84
- │ └── server.ts app.listen(PORT), stopped on SIGTERM
158
+ │ ├── app.ts the app: the base, health(), apiDocs, the routes, and its type
159
+ │ ├── app.spec.ts bun test: the typed client over app.fetch, and matchesSpec
160
+ │ └── server.ts app.listen on env.PORT, which stops on SIGINT and SIGTERM
85
161
  ├── package.json
86
162
  ├── tsconfig.json
87
163
  ├── biome.json Biome: lint, format, imports sorted
88
164
  ├── .vscode/ Biome's extension recommended, format on save
89
165
  ├── Dockerfile bun run build, then dist/ alone, on oven/bun:1-alpine
90
166
  ├── .dockerignore
91
- ├── .env.example PORT and API_KEY, for a .env Bun loads
167
+ ├── .env.example PORT, API_KEY and API_DOCS, for a .env Bun loads
92
168
  ├── .gitignore
93
169
  └── README.md
94
170
  ```
@@ -232,19 +308,52 @@ bun run generate
232
308
  git diff src/generated
233
309
  ```
234
310
 
235
- What the generator does not write, in 0.6.0, and how the app does it
311
+ What the generator does not write, in 0.7.0, and how the app does it
236
312
  instead:
237
313
 
238
314
  - **`security`**: no middleware is generated from it. Authentication is
239
315
  a middleware the app writes, `requireKey` here, given to the routes
240
316
  that need it.
241
- - **A cookie parameter**: the generator refuses the whole spec
242
- ([troubleshooting](troubleshooting.md#cookie-parameter-session-is-not-supported-unsupported_parameter)).
243
- Read the cookie in a middleware, or validate it with `validate({ cookies })`
244
- by hand.
245
- - **Named server-sent events** (an `itemSchema` with `event` names): the
246
- operation is left out of `alxia.ts` with a warning; declare that route
247
- by hand with `@alxia/core`'s `eventStream`.
317
+ - **A cookie parameter in the client files**: `alxia.ts` validates it as
318
+ the route's `cookies`; `types.ts`, `zod.ts`, `operations.ts` and
319
+ `paths.ts` leave it out with an `ignored` warning, since a client does not
320
+ set cookies.
321
+ - **Server-sent events with text data**: the operation is left out of
322
+ `alxia.ts` with a warning; give each event's data a JSON `contentSchema`,
323
+ or declare that route by hand with `@alxia/core`'s `eventStream`. Named
324
+ events whose data is JSON are generated.
325
+
326
+ ### `src/env.ts`
327
+
328
+ ```ts
329
+ import { defineEnv } from "@alxia/env";
330
+ import { z } from "zod";
331
+
332
+ // `bun dev` and `bun test` run in development and test; anything else,
333
+ // production included, is a deployment.
334
+ const local = ["development", "test"].includes(Bun.env.NODE_ENV ?? "");
335
+
336
+ export const env = defineEnv(
337
+ {
338
+ PORT: z.coerce.number().default(3000),
339
+ API_KEY: local ? z.string().min(1).default("dev-key") : z.string().min(1),
340
+ API_DOCS: z.stringbool().default(Bun.env.NODE_ENV === "development"),
341
+ },
342
+ { secret: ["API_KEY"] },
343
+ );
344
+ ```
345
+
346
+ [`defineEnv`](https://github.com/softistx/alxia/tree/develop/packages/env/docs)
347
+ checks the environment once, when the module is first imported: a missing
348
+ or malformed variable stops the process with every issue, before it listens.
349
+ `API_KEY` is a secret, so it prints as `***`. It defaults to `dev-key`
350
+ under `NODE_ENV=development` and `test` alone: anywhere else — `bun start`,
351
+ the image — it is required, and the app does not start without it.
352
+ `API_DOCS` turns the API reference at `/docs` on: by default in
353
+ development alone. `Bun.env`, not `process.env.NODE_ENV`, which
354
+ `bun build` would replace with the mode of the build. `src/server.ts` listens on `env.PORT` and
355
+ `src/routes/todos.ts` compares the `x-api-key` header with `env.API_KEY`.
356
+ `@alxia/env` and `zod` are dependencies.
248
357
 
249
358
  ### `src/context.ts`
250
359
 
@@ -252,14 +361,13 @@ instead:
252
361
  import { alxia } from "@alxia/core";
253
362
  import type { Todo } from "./generated/types";
254
363
 
255
- /** Set API_KEY in the environment: this default is for development. */
256
- export const apiKey = Bun.env["API_KEY"] ?? "dev-key";
257
-
258
364
  const todos: Todo[] = [];
259
365
 
260
366
  // The base: what every route reads, decorated or derived here. It is
261
367
  // registered below, so a route file reads it with no import of the app.
262
- export const base = alxia().decorate({ todos });
368
+ // alxia's own errors — a 400 the schemas refuse, a 404 no route matches, a
369
+ // 500 — are RFC 9457 problems, as openapi.yaml declares them.
370
+ export const base = alxia({ errors: "problem" }).decorate({ todos });
263
371
 
264
372
  // Register the base, never the app: the app mounts the route files, whose
265
373
  // type reads this, and would then be typed by itself.
@@ -282,13 +390,13 @@ for a `user` from a session goes here too, and every route then reads
282
390
 
283
391
  ```ts
284
392
  import { defineMiddleware, defineRoutes } from "@alxia/core";
285
- import { apiKey } from "../context";
393
+ import { env } from "../env";
286
394
  import { operations } from "../generated/alxia";
287
395
 
288
396
  // A middleware of the routes it is given to: it answers 401 without the key,
289
397
  // before the body is read. openapi.yaml declares that 401.
290
398
  const requireKey = defineMiddleware(({ request, reply }, next) =>
291
- request.headers.get("x-api-key") === apiKey
399
+ request.headers.get("x-api-key") === env.API_KEY
292
400
  ? next()
293
401
  : reply(401, { error: "unauthorized" as const }),
294
402
  );
@@ -322,16 +430,32 @@ error. It takes no prefix here: an operation's path is already whole.
322
430
  ### `src/app.ts`
323
431
 
324
432
  ```ts
433
+ import { health } from "@alxia/core";
434
+ import { apiDocs } from "@alxia/openapi";
435
+ import spec from "../openapi.yaml";
325
436
  import { base } from "./context";
437
+ import { env } from "./env";
326
438
  import { todoRoutes } from "./routes/todos";
327
439
 
328
- // The base, then the route files: each requires the base's context, so
329
- // mounting one before it is a compile error.
330
- export const app = base.plugin(todoRoutes);
440
+ // The base, then the probes (GET /health, GET /ready) before any guard,
441
+ // the API reference at /docs (on in development; API_DOCS=true elsewhere),
442
+ // and the route files: each requires the base's context, so mounting one
443
+ // before it is a compile error. openapi.yaml is imported, so `bun run build`
444
+ // puts it inside dist/server.js: the image needs no copy of it.
445
+ export const app = base
446
+ .plugin(health())
447
+ .plugin(apiDocs({ spec, enabled: env.API_DOCS }))
448
+ .plugin(todoRoutes);
331
449
 
332
450
  export type App = typeof app;
333
451
  ```
334
452
 
453
+ `health()` answers `GET /health` (liveness) and `GET /ready` (readiness),
454
+ and `apiDocs` serves a Scalar page at `/docs` with the document at
455
+ `/docs/openapi.yaml` and `/docs/openapi.json`. `matchesSpec` leaves both
456
+ out: no operation of `openapi.yaml` describes them. The document is public
457
+ wherever `/docs` is on.
458
+
335
459
  ```ts
336
460
  route(operation, ...middlewares, handler)
337
461
  ```
@@ -359,32 +483,47 @@ route(operation, ...middlewares, handler)
359
483
 
360
484
  ### `src/app.spec.ts`
361
485
 
486
+ The spec calls the app through the client the generated `paths.ts`
487
+ describes, [openapi-fetch](https://openapi-ts.dev/openapi-fetch/) (a dev
488
+ dependency), whose `fetch` is `app.fetch`: in process, no server, no port,
489
+ and every path, parameter, body and reply typed by `openapi.yaml`.
490
+
362
491
  ```ts
363
492
  import { expect, test } from "bun:test";
364
493
  import { matchesSpec } from "@alxia/openapi";
494
+ import createClient from "openapi-fetch";
365
495
  import { app } from "./app";
366
- import { apiKey } from "./context";
496
+ import { env } from "./env";
367
497
  import { operations } from "./generated/alxia";
498
+ import type { paths } from "./generated/paths";
499
+
500
+ const api = createClient<paths>({
501
+ baseUrl: "http://alxia.test",
502
+ fetch: (request) => app.fetch(request),
503
+ headers: { "x-api-key": env.API_KEY },
504
+ });
368
505
 
369
506
  test("routes every operation of openapi.yaml, and nothing else", () => {
370
507
  matchesSpec(app, operations);
371
508
  });
372
509
 
373
510
  test("creates a todo from JSON", async () => {
374
- const response = await app.request("/todos", {
375
- method: "POST",
376
- headers: { "content-type": "application/json", "x-api-key": apiKey },
377
- body: JSON.stringify({ title: "Write a route" }),
511
+ const { data, response } = await api.POST("/todos", {
512
+ body: { title: "Write a route" },
378
513
  });
379
514
  expect(response.status).toBe(201);
515
+ expect(data?.title).toBe("Write a route");
380
516
  });
381
517
  ```
382
518
 
383
519
  `matchesSpec(app, operations)`, from
384
520
  [`@alxia/openapi`](https://www.npmjs.com/package/@alxia/openapi), throws
385
521
  when an operation has no route, or a route has no operation, naming each.
386
- The spec also checks the 400, the 401 before the body and the 404, each
387
- with `app.request()`, in process, with no port.
522
+ The spec also checks the 400, the 401 before the body and the 404 through
523
+ the client, and keeps one test on `app.request()`: the client sends only
524
+ what the spec allows, so a request it forbids (`/todos/first`) goes
525
+ through `app.request`. See
526
+ [Testing with the generated client](https://github.com/softistx/alxia/blob/develop/packages/openapi/docs/guide/testing.md).
388
527
 
389
528
  ### Adding an operation
390
529
 
@@ -456,12 +595,12 @@ The scripts:
456
595
 
457
596
  | script | runs |
458
597
  | --- | --- |
459
- | `bun dev` | `bun --watch src/server.ts`: restarted on every change, on `PORT` or 3000 |
598
+ | `bun dev` | `NODE_ENV=development bun --watch src/server.ts`: restarted on every change, on `PORT` or 3000, with alxia's dev helps and `/docs` on |
460
599
  | `bun test` | the spec |
461
600
  | `bun run generate` | `nxgt-openapi generate`: `src/generated/` from `openapi.yaml`. `bun run generate --check` writes nothing and exits 1 when a file is stale |
462
601
  | `bun run typecheck` | `tsc --noEmit` |
463
602
  | `bun run build` | `bun build src/server.ts --target=bun --outdir=dist --minify --sourcemap=linked`: one file, its dependencies bundled |
464
- | `bun start` | `bun dist/server.js`: the build, after `bun run build` |
603
+ | `bun start` | `NODE_ENV=production bun dist/server.js`: the build, after `bun run build` |
465
604
  | `bun run check` | `biome check --write`: lint, format, sort imports, fixing what it can |
466
605
  | `bun run lint`, `bun run format` | `biome lint`, `biome format --write` |
467
606
  | `bun run check:ci` | `biome ci`: read-only, for CI |
@@ -479,20 +618,230 @@ is linked from it: Bun reads the map, so a stack trace names the lines of
479
618
  `src/`. `bun dev` and `bun test` run the TypeScript as it is, with no
480
619
  build.
481
620
 
482
- Bun loads `.env` on every command. `.env.example` names the two variables
483
- the app reads, `PORT` (3000 by default) and `API_KEY` (`dev-key` by
484
- default, for development only): copy it to `.env`, which `.gitignore`
485
- keeps out of git and `.dockerignore` out of the image.
621
+ Bun loads `.env` on every command. `.env.example` names the variables
622
+ `src/env.ts` reads, `PORT` (3000 by default), `API_KEY` (`dev-key` by
623
+ default in development and test alone, required elsewhere) and `API_DOCS`:
624
+ copy it to `.env`, which `.gitignore` keeps out of git and `.dockerignore`
625
+ out of the image. Its `API_KEY` and `API_DOCS` are commented out: Bun
626
+ loads `.env` on `bun start` too, where a development key or a public
627
+ `/docs` would defeat the defaults; set them for a deployment in its own
628
+ environment.
486
629
 
487
630
  `tsconfig.json` holds the settings alxia's own packages are checked under:
488
631
  `strict`, and past it `exactOptionalPropertyTypes`,
489
632
  `noUncheckedIndexedAccess`, `noPropertyAccessFromIndexSignature`,
490
- `noUnusedLocals` and the rest. Hence `Bun.env["API_KEY"]` and not
491
- `Bun.env.API_KEY`, and Biome's `useLiteralKeys`, which would ask for the
633
+ `noUnusedLocals` and the rest. Hence `Bun.env["PORT"]` and not
634
+ `Bun.env.PORT` (in the `minimal` project), and Biome's `useLiteralKeys`, which would ask for the
492
635
  second, is off in `biome.json`. Loosen what you would rather not keep:
493
636
  alxia's types, and the generated files, compile under each one, and under
494
637
  none.
495
638
 
639
+ ## The `graphql` template
640
+
641
+ A GraphQL API with [GraphQL Yoga](https://the-guild.dev/graphql/yoga-server),
642
+ served by `@alxia/graphql` as a route of the app, behind its middlewares.
643
+ It is schema first, as the `api` project is spec first: `schema.graphql` is
644
+ written first, the resolvers are typed from it.
645
+
646
+ ```
647
+ my-graphql-api/
648
+ ├── schema.graphql the contract: Query, Mutation, Subscription and their types
649
+ ├── codegen.ts how `bun run generate` reads it
650
+ ├── src/
651
+ │ ├── generated/resolvers.ts what `bun run generate` writes: committed, never edited
652
+ │ ├── env.ts defineEnv: PORT
653
+ │ ├── store.ts in-memory users, tokens and notes, and the pub/sub
654
+ │ ├── context.ts the base, the viewerOf middleware, and Context
655
+ │ ├── resolvers.ts const resolvers: Resolvers
656
+ │ ├── schema.ts createSchema from schema.graphql and the resolvers
657
+ │ ├── app.ts health() and graphql(app, { schema }) mounted on the base
658
+ │ ├── graphql.d.ts declares the *.graphql module
659
+ │ ├── app.spec.ts bun test: POST /graphql through app.request()
660
+ │ └── server.ts app.listen on env.PORT, which stops on SIGINT and SIGTERM
661
+ ├── package.json
662
+ ├── tsconfig.json
663
+ ├── biome.json Biome; skips dist/ and src/generated/
664
+ ├── .vscode/
665
+ ├── Dockerfile bun run build, then dist/ alone, on oven/bun:1-alpine
666
+ ├── .dockerignore
667
+ ├── .env.example PORT, for a .env Bun loads
668
+ ├── .gitignore
669
+ └── README.md
670
+ ```
671
+
672
+ `bun dev` serves `http://localhost:3000/graphql`; a browser's GET opens
673
+ GraphiQL, and a POST answers queries:
674
+
675
+ ```sh
676
+ curl localhost:3000/graphql -H 'content-type: application/json' \
677
+ -H 'authorization: Bearer ada-token' \
678
+ -d '{"query":"mutation { addNote(text: \"Hello\") { id author { name } } }"}'
679
+ ```
680
+
681
+ ### `schema.graphql` and `codegen.ts`
682
+
683
+ The schema declares `Query` (`me`, `notes`), `Mutation` (`addNote(text:
684
+ String!): Note!`), `Subscription` (`noteAdded: Note!`) and the `User` and
685
+ `Note` types. `bun run generate` is `graphql-codegen --config codegen.ts`:
686
+
687
+ ```ts
688
+ // codegen.ts
689
+ const config: CodegenConfig = {
690
+ schema: "schema.graphql",
691
+ generates: {
692
+ "src/generated/resolvers.ts": {
693
+ plugins: ["typescript", "typescript-resolvers"],
694
+ config: {
695
+ contextType: "../context#Context",
696
+ mappers: { Note: "../store#NoteRecord" },
697
+ useTypeImports: true,
698
+ useIndexSignature: true,
699
+ },
700
+ },
701
+ },
702
+ };
703
+ ```
704
+
705
+ It writes the schema's types and `Resolvers`, whose context is the app's own
706
+ `Context` and whose `Note` is the `NoteRecord` the store holds, so a resolver
707
+ returns the record and `Note.author` reads it. `src/generated/` is
708
+ committed, so nothing is generated at install or build, in Docker too, and
709
+ Biome skips it. Never edit it.
710
+
711
+ Why GraphQL Code Generator: it is the de facto standard for typed
712
+ resolvers from a `schema.graphql`, and the generator that types `Resolvers`
713
+ with a custom context type and mappers. It is a devDependency, so the image
714
+ stays bundle-only. Lighter tools were not chosen: gql.tada types documents,
715
+ not resolvers, and Pothos is code first.
716
+
717
+ ### `src/context.ts`, `src/resolvers.ts`
718
+
719
+ ```ts
720
+ // src/context.ts
721
+ import { alxia, defineMiddleware } from "@alxia/core";
722
+ import type { GraphQLContext } from "@alxia/graphql";
723
+ import { env } from "./env";
724
+ import { db } from "./store";
725
+
726
+ const viewerOf = defineMiddleware(({ request }, next) => {
727
+ const token = request.headers
728
+ .get("authorization")
729
+ ?.match(/^Bearer (.+)$/i)?.[1];
730
+ const id = token === undefined ? undefined : db.tokens.get(token);
731
+ return next({
732
+ viewer: (id === undefined ? undefined : db.users.get(id)) ?? null,
733
+ });
734
+ });
735
+
736
+ export const base = alxia().decorate({ env, db }).use(viewerOf);
737
+ export type Context = GraphQLContext<typeof base>;
738
+ ```
739
+
740
+ `viewerOf` is a middleware given to `use`: it reads
741
+ `Authorization: Bearer <token>` and passes `next({ viewer })`, the user or
742
+ `null`. It never refuses, so a query may be anonymous (`me` is `null`), and
743
+ `viewer` is typed in every resolver through `GraphQLContext<typeof base>`.
744
+ The tokens in `src/store.ts` are for development (`ada-token`): look a
745
+ session up, or verify a JWT, in the same place.
746
+
747
+ ```ts
748
+ // src/resolvers.ts, in part
749
+ export const resolvers: Resolvers = {
750
+ Query: {
751
+ me: (_, __, { viewer }) => viewer,
752
+ notes: (_, __, { db }) => db.notes,
753
+ },
754
+ Mutation: {
755
+ addNote: (_, { text }, { viewer, db }) => {
756
+ if (viewer === null) {
757
+ throw new GraphQLError("Sign in to add a note", {
758
+ extensions: { code: "UNAUTHENTICATED" },
759
+ });
760
+ }
761
+ // …
762
+ },
763
+ },
764
+ };
765
+ ```
766
+
767
+ A field the schema lacks, or a value its type refuses, is a compile error.
768
+ `addNote` throws a `GraphQLError` with the code `UNAUTHENTICATED` when
769
+ `viewer` is `null` ([troubleshooting](troubleshooting.md#sign-in-to-add-a-note)).
770
+
771
+ ### `src/app.ts` and the subscription
772
+
773
+ ```ts
774
+ export const app = base
775
+ .plugin(health())
776
+ .plugin((app) => graphql(app, { schema }));
777
+ ```
778
+
779
+ `health()` answers `GET /health` and `GET /ready`. GraphiQL follows the
780
+ app's dev switch, `graphql()`'s default: on under `bun dev`, which sets
781
+ `NODE_ENV=development`, off under `bun start` and in the image. `noteAdded` is served over server-sent events, Yoga's default,
782
+ so no WebSockets: a request with `Accept: text/event-stream` gets a result
783
+ each time `addNote` publishes to the `createPubSub` of `src/store.ts`:
784
+
785
+ ```sh
786
+ curl -N localhost:3000/graphql -H 'content-type: application/json' \
787
+ -H 'accept: text/event-stream' \
788
+ -d '{"query":"subscription { noteAdded { text author { name } } }"}'
789
+ ```
790
+
791
+ That pub/sub lives in one process: across several, back it with a broker.
792
+
793
+ ### `src/env.ts`
794
+
795
+ `defineEnv` from `@alxia/env` reads `PORT` (3000 by default), checked once,
796
+ when the module is first imported: a malformed one stops the process with
797
+ every issue, before it listens. Bun loads `.env`; copy `.env.example` to
798
+ `.env` to set it.
799
+
800
+ ### Adding a field
801
+
802
+ 1. Add it to `schema.graphql`: `notesBy(userId: ID!): [Note!]!` on `Query`.
803
+ 2. `bun run generate`: `Resolvers` has `notesBy`, its arguments typed.
804
+ 3. Write the resolver in `src/resolvers.ts`:
805
+ `notesBy: (_, { userId }, { db }) => db.notes.filter(…)`.
806
+ 4. Add a query to `src/app.spec.ts`, which POSTs to `/graphql` through
807
+ `app.request()`, with no port, and `bun test`.
808
+
809
+ `bun run verify` is `generate --check`, `check:ci`, `typecheck`, then
810
+ `test`: it fails when `src/generated/` is not what `schema.graphql` gives.
811
+
812
+ The spec's `query` helper types its result by hand (`Result`). To type each
813
+ operation's variables and data from `schema.graphql`, add
814
+ `@graphql-codegen/client-preset` and write the operations with its `graphql()`
815
+ tag; the template does not ship it, to keep `src/generated/` to the
816
+ resolvers.
817
+
818
+ ### The build bundles the schema
819
+
820
+ `src/schema.ts` imports the schema as text:
821
+
822
+ ```ts
823
+ import typeDefs from "../schema.graphql" with { type: "text" };
824
+ ```
825
+
826
+ `src/graphql.d.ts` declares the `*.graphql` module for TypeScript, and
827
+ `bun run build` puts the file's content in `dist/server.js`, so the image
828
+ holds `dist/` alone and no `.graphql` file beside it.
829
+
830
+ ### Pinned versions
831
+
832
+ `@graphql-codegen/cli` (7.4.3), `typescript` and `typescript-resolvers`
833
+ (6.1.0 each) are pinned exactly, and `@alxia/create` keeps them at those
834
+ versions ([Versions](#versions)): a generator patch may write
835
+ `src/generated/` differently, which `generate --check` would then fail in a
836
+ fresh project. To move them, run `bun run generate`, read `git diff
837
+ src/generated`, then `bun run verify`
838
+ ([troubleshooting](troubleshooting.md#srcgenerated-changes-after-moving-graphql-codegen)).
839
+
840
+ The scripts are those of the [`api`](#the-rest) project, with `generate` as
841
+ `graphql-codegen --config codegen.ts` and `start` as `NODE_ENV=production bun dist/server.js`.
842
+ For Yoga's plugins, the IDE and the typed context, see
843
+ [`@alxia/graphql`'s guide](https://github.com/softistx/alxia/tree/develop/packages/graphql/docs).
844
+
496
845
  ## The `react-router` template
497
846
 
498
847
  It is React Router's official template, shipped inside this package and
@@ -506,7 +855,7 @@ before `bun install`. The change, against React Router's files:
506
855
  // package.json
507
856
  "scripts": {
508
857
  - "start": "react-router-serve ./build/server/index.js",
509
- + "start": "bun build/server/index.js",
858
+ + "start": "NODE_ENV=production bun build/server/index.js",
510
859
  },
511
860
  "dependencies": {
512
861
  + "@alxia/core": "^0.3.1",
@@ -575,8 +924,8 @@ goes from there.
575
924
 
576
925
  ## Lint and format
577
926
 
578
- Both projects lint and format with [Biome](https://biomejs.dev), in one
579
- style whichever template wrote them. Their `biome.json` is a root
927
+ Every project lints and formats with [Biome](https://biomejs.dev), in one
928
+ style whichever template wrote it. Its `biome.json` is a root
580
929
  configuration of its own, extending nothing:
581
930
 
582
931
  ```json
@@ -607,8 +956,8 @@ configuration of its own, extending nothing:
607
956
  ```
608
957
 
609
958
  That is the `react-router` project's, written here compact. The `api`
610
- project's skips `dist/` and `src/generated/` instead of `build/` and
611
- `.react-router/`, has no
959
+ and `graphql` projects' skip `dist/` and `src/generated/` instead of
960
+ `build/` and `.react-router/`, and the `minimal` one `dist/` alone; they have no
612
961
  CSS settings and no overrides, and turns `complexity.useLiteralKeys` off
613
962
  in place of `noEmptyPattern` ([the `api` template](#the-api-template)).
614
963
 
@@ -616,7 +965,7 @@ in place of `noEmptyPattern` ([the `api` template](#the-api-template)).
616
965
  quotes, 80 columns. React Router's scaffold is written so, and so is
617
966
  the `package.json` the command writes: formatting the scaffold once
618
967
  changed three of its files, where tabs would change every line. The
619
- `api` project takes the same style, so the two read alike.
968
+ other projects take the same style, so they read alike.
620
969
  - **`$schema` is the installed Biome's own schema**, so an editor checks
621
970
  the file against the version `bun install` put in `node_modules`,
622
971
  whichever the command wrote.
@@ -650,7 +999,7 @@ bunx biome migrate --write
650
999
  | `bun run lint` | `biome lint` |
651
1000
  | `bun run format` | `biome format --write` |
652
1001
  | `bun run check:ci` | `biome ci`: changes nothing, and fails on any error |
653
- | `bun run verify` | `api`: `generate --check`, `check:ci`, `typecheck`, then `test`; `react-router`: `check:ci`, `typecheck`, then `build` |
1002
+ | `bun run verify` | `minimal`: `check:ci`, `typecheck`, then `test`; `api` and `graphql`: `generate --check`, then those; `react-router`: `check:ci`, `typecheck`, then `build` |
654
1003
 
655
1004
  The read-only one is `check:ci`, not `ci`: `bun ci` is Bun's
656
1005
  `bun install --frozen-lockfile`, and a script named `ci` would only run
@@ -690,6 +1039,19 @@ final stage goes back to `oven/bun:1`
690
1039
  copied in: see
691
1040
  [troubleshooting](troubleshooting.md#error-cannot-find-package--from-appdistserverjs).
692
1041
 
1042
+ ### `minimal`
1043
+
1044
+ Two stages, as `api`'s below: every dependency and `bun run build`, which
1045
+ writes `dist/index.js`, then an image with `dist/` alone, running
1046
+ `bun --no-install dist/index.js`. `listen`, called only when
1047
+ `src/index.ts` is the entry file, stops the app on `SIGTERM` and exits.
1048
+
1049
+ ```sh
1050
+ cd my-app
1051
+ docker build -t my-app .
1052
+ docker run -p 3000:3000 my-app
1053
+ ```
1054
+
693
1055
  ### `api`
694
1056
 
695
1057
  Two stages: every dependency, installed with
@@ -698,8 +1060,9 @@ Two stages: every dependency, installed with
698
1060
  running `bun --no-install dist/server.js`, `start`'s command with
699
1061
  Bun's `--no-install` (not create-alxia's option of the same name), so that a package missing from the bundle fails at
700
1062
  startup rather than being fetched from npm, written out so that Bun
701
- is the container's process. `src/server.ts` stops the app on `SIGTERM`:
702
- as process 1, Bun would otherwise ignore it, and `docker stop` would wait.
1063
+ is the container's process. `listen` stops the app on `SIGINT` and `SIGTERM`,
1064
+ then exits: as process 1, Bun would otherwise ignore them, and `docker stop`
1065
+ would wait.
703
1066
  Nothing is generated in the image: `src/generated/` is committed, and
704
1067
  `COPY . .` brings it with the rest, so the build stage runs no
705
1068
  `bun run generate` and needs no `openapi.yaml`.
@@ -730,8 +1093,24 @@ docker build -t my-api .
730
1093
  docker run -p 3000:3000 -e API_KEY=change-me my-api
731
1094
  ```
732
1095
 
733
- The server listens on `PORT`, 3000 in the image; set `API_KEY`, whose
734
- default is for development.
1096
+ The server listens on `PORT`, 3000 in the image; `API_KEY` is required
1097
+ there, and the container exits at once without it. `-e API_DOCS=true`
1098
+ serves `/docs` from the image: `openapi.yaml` is inside the bundle.
1099
+
1100
+ ### `graphql`
1101
+
1102
+ The same two stages as `api`'s, `Dockerfile` and all but the file name:
1103
+ `bun run build` writes `dist/server.js`, with `schema.graphql` bundled in
1104
+ as text, and the image holds `dist/` alone and runs
1105
+ `bun --no-install dist/server.js`. `src/generated/` is committed, so the
1106
+ build generates nothing. The image sets `NODE_ENV=production`, under which
1107
+ GraphiQL is off. `listen` stops the app on `SIGINT` and `SIGTERM`.
1108
+
1109
+ ```sh
1110
+ cd my-graphql-api
1111
+ docker build -t my-graphql-api .
1112
+ docker run -p 3000:3000 my-graphql-api
1113
+ ```
735
1114
 
736
1115
  ### `react-router`
737
1116
 
@@ -765,13 +1144,16 @@ template pins exactly:
765
1144
 
766
1145
  | dependency | moved to the newest within |
767
1146
  | --- | --- |
768
- | `@alxia/core`, `@alxia/openapi`, `@alxia/react-router` | the ranges this `@alxia/create` was published with, such as `^0.3.1`; while the registry does not serve that version yet, the newest of its minor, `~0.3.0` |
1147
+ | `@alxia/core`, `@alxia/env`, `@alxia/graphql`, `@alxia/openapi`, `@alxia/react-router` | the ranges this `@alxia/create` was published with, such as `^0.3.1`; while the registry does not serve that version yet, the newest of its minor, `~0.3.0` |
769
1148
  | `typescript` | `^6.0.3 \|\| ^7.0.0`, every alxia package's peer range |
770
1149
  | `zod` | `^4.2.0`, `@alxia/zod`'s |
771
1150
  | `vite` | `^7.0.0 \|\| ^8.0.0`, `@alxia/react-router`'s |
772
1151
  | `react-router`, `@react-router/*` | `^8.0.0`, `@alxia/react-router`'s; the `@react-router/*` packages take `react-router`'s version, which `@react-router/node` pins exactly |
773
1152
  | `@biomejs/biome` | its own minor, from the exact version the template pins (`~2.5.15`): written exactly, `2.5.16`, never `^`. A minor of Biome may add a recommended rule |
774
- | `@nxgt/openapi-codegen` | none: the template's exact version, `0.6.0`, is kept. Any release may write `src/generated/` differently, and `bun run verify` checks it with `generate --check` |
1153
+ | `graphql` | `^16.11.0 \|\| ^17.0.0`, `@alxia/graphql`'s; so a new project may declare `^17` where the template ships `^16.11.0` |
1154
+ | `graphql-yoga` | `^5.16.0`, `@alxia/graphql`'s |
1155
+ | `@graphql-codegen/cli`, `@graphql-codegen/typescript`, `@graphql-codegen/typescript-resolvers` | none: the template's exact versions, 7.4.3, 6.1.0 and 6.1.0, are kept, for the reason `@nxgt/openapi-codegen`'s are: `generate --check` |
1156
+ | `@nxgt/openapi-codegen` | none: the template's exact version, `0.7.0`, is kept. Any release may write `src/generated/` differently, and `bun run verify` checks it with `generate --check` |
775
1157
  | anything else: `react`, `isbot`, Tailwind, `@types/*` | no alxia range: npm's `latest` |
776
1158
 
777
1159
  The command prints each move, and each newer major it left out: