@afora/fastify 0.0.0-stage → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,133 @@
1
- # Temporary Holding Version
1
+ # @afora/fastify
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A [Fastify](https://fastify.dev) sink for [`@afora/core`](../../README.md) outputs. It turns the operations of an output into a Fastify instance: the route each use case declares, validated input (from the body, the query, the path, headers and cookies), the access each use case declares, the response with its status (sensitive values masked), RFC 9457 `application/problem+json` errors, and an OpenAPI document of the same routes.
4
+
5
+ ```bash
6
+ bun add @afora/core @afora/fastify fastify typebox
7
+ # or: npm install @afora/core @afora/fastify fastify typebox
8
+ ```
9
+
10
+ `@afora/core`, `fastify` (`^5.12.8`) and TypeBox (`^1`) are peer dependencies. It runs wherever Fastify does: Node >= 22 and Bun.
11
+
12
+ ## Example
13
+
14
+ ```ts
15
+ import {
16
+ blueprintOf,
17
+ commandOf,
18
+ outputOf,
19
+ Route,
20
+ useCaseOf,
21
+ } from "@afora/core";
22
+ import { fastify } from "@afora/fastify";
23
+
24
+ @Route("GET", "/posts/{slug}")
25
+ class GetPost extends useCaseOf({
26
+ name: "GetPost",
27
+ blueprint: blueprintOf((ctx) => ({ slug: ctx.slug })),
28
+ response: blueprintOf(() => ({ post: Post })),
29
+ dependencies: { posts: Posts },
30
+ }) {
31
+ override async execute() {
32
+ return { post: await this.dependencies.posts.findBySlug(this.input.slug) };
33
+ }
34
+ }
35
+
36
+ const Blog = commandOf({ name: "Blog", useCases: { getPost: GetPost } });
37
+
38
+ const Api = outputOf({
39
+ name: "Api",
40
+ commands: [Blog],
41
+ pipe: [
42
+ fastify({
43
+ basePath: "/api",
44
+ docs: {
45
+ path: "/openapi.json",
46
+ info: { title: "Blog", version: "1.0.0" },
47
+ },
48
+ }),
49
+ ],
50
+ });
51
+
52
+ const app = Api.build(); // a FastifyInstance
53
+ await app.listen({ port: 3000 });
54
+ ```
55
+
56
+ ```
57
+ GET /api/posts/hello -> 200 { "post": { "slug": "hello", ... } }
58
+ GET /api/posts/Not%20A%20Slug -> 400 application/problem+json, with "issues"
59
+ GET /openapi.json -> the OpenAPI 3.1 document of the same routes
60
+ ```
61
+
62
+ ## Options
63
+
64
+ All options are JSON, so the stage can live in an `afora.json` (`{ "sink": "fastify", "options": { ... } }`). They are the options of every afora sink that serves HTTP, so moving an output from one server to another changes one import.
65
+
66
+ | Option | Meaning |
67
+ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
68
+ | `basePath` | Prefix of every route, e.g. `"/api"`. |
69
+ | `route` | `{ [operationId]: { method?, path?, status? } }`: overrides the route a use case declares, or the default `POST /{command}/{operation}`. |
70
+ | `responses` | `{ [operationId]: { headers: { name: value } } }`: static headers of the success responses, such as `cache-control`. |
71
+ | `requestId` | `true` (`x-request-id`) or a header name: every response of the sink carries the request's id, or a new one. |
72
+ | `security` | `{ schemes, operations?, default? }`: the security schemes of the OpenAPI document. |
73
+ | `docs` | `{ path, info: { title, version, description? }, servers? }`: serves the OpenAPI document of the same operations at `path` (not under `basePath`). |
74
+ | `debug` | `true` adds the `trace` to problems and the real `detail` to 5xx ones. Off by default. |
75
+ | `context` | `{ headers?: { [contextKey]: headerName }, variables?: { [contextKey]: name } }`: the context of an operation from request headers and from properties a hook set on the request (`request.tenant`, declared with `decorateRequest`). |
76
+ | `auth` | `{ jwt: { secret: { env }, issuer?, audience?, algorithm?, header?, cookie? } }`: authenticates callers from a JSON Web Token. Experimental: see [Tokens and sessions](../../docs/auth.md#tokens-and-sessions). |
77
+
78
+ What JSON cannot hold goes in a second argument, the hooks: `fastify(options, { authenticator, middlewares, app })`. The type `FastifyHooks` is exported.
79
+
80
+ | Hook | Meaning |
81
+ | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
82
+ | `authenticator` | `(request) => Principal \| null`: who calls, from the credentials of the request. `request` has `header(name)`, `cookie(name)`, the `operation` and `native`, the `FastifyRequest`. |
83
+ | `middlewares` | `onRequest` hooks: `(request, reply) => ...`, run in order before the routes of the sink. |
84
+ | `app` | The Fastify instance to add the routes to, instead of a new one. |
85
+
86
+ Invalid options throw `InvalidOutputStage` when the stage is made, and unknown operation ids in `route` or two operations on one method and path when the output is built.
87
+
88
+ ## Behavior
89
+
90
+ The requests are handled by the route table of the core (`compileRoutes` of `@afora/core/adapters`), shared by every afora sink that serves HTTP, so they all answer the same way. This package only routes and sends. The behavior is described once, in [Outputs](../../docs/outputs.md); in short:
91
+
92
+ - **Input.** `post`, `put` and `patch` read a JSON body, `get` and `delete` the query string. Over it come the keys the [route of the use case](../../docs/use-cases.md#routes) places: `{name}` segments of the path, and the query keys, headers and cookies it declares. Text is converted to the numbers and booleans the input takes, and the blueprint of the use case validates it: a 400 problem with `issues`.
93
+ - **Access.** An operation whose use case declares an [`access`](../../docs/auth.md) asks the `authenticator` hook (or `auth`) who calls, and answers a 401 or a 403 problem before the input is validated. With neither, such an operation always answers 401.
94
+ - **Success.** The status of the route (`200` by default) with the response as JSON; records go through `toJSON`, so sensitive values are masked. A `204` has no body. The keys a route sends with `setCookie` leave the body and become `set-cookie` headers.
95
+ - **Errors.** `application/problem+json`, with the status of `statusOf`: the `statuses` of the output first, then 400, 401, 403, 404, 409, 422 for a declared error, else 500, whose detail is `"Internal error."` unless `debug` is on.
96
+ - **Unknown routes** are a 404 problem and anything thrown outside an operation is a problem too, unless you gave the `app`.
97
+ - **The body.** The routes are registered in an encapsulated plugin whose content type parser keeps the body as text, so an invalid JSON body is a problem like the others, not Fastify's own error.
98
+
99
+ ## Middlewares and your own app
100
+
101
+ ```ts
102
+ fastify(
103
+ { context: { variables: { tenant: "tenant" } } },
104
+ {
105
+ middlewares: [
106
+ async (request) => {
107
+ request.tenant = tenantOf(request.headers.host);
108
+ },
109
+ ],
110
+ },
111
+ );
112
+ ```
113
+
114
+ A value a middleware sets reaches the use case through `context.variables`, for the operations whose `context` blueprint declares the key.
115
+
116
+ `app` takes a Fastify instance you made: register `@fastify/cors`, `@fastify/helmet` or a rate limiter on it as usual. The routes of the sink live in a plugin of their own, where the body is read as text (the route table parses it), so the content type parsers of your instance are not touched; your not found and error handlers are kept.
117
+
118
+ ## Catalog
119
+
120
+ `FastifyStages` is `stageCatalogOf(fastify)` (from `@afora/core/adapters`), and `stages` are the entries codegen reads to resolve `{ "sink": "fastify" }` in an `afora.json`:
121
+
122
+ ```ts
123
+ // stages.ts
124
+ export { stages } from "@afora/fastify";
125
+ ```
126
+
127
+ ```bash
128
+ bunx afora-codegen generate --stages ./stages.ts
129
+ ```
130
+
131
+ ## Testing a sink
132
+
133
+ This package passes `httpProviderContract` of `@afora/core/testing`, the cases every afora sink that serves HTTP must pass. A sink for another server is tested the same way; see [Outputs](../../docs/outputs.md).
@@ -0,0 +1,55 @@
1
+ import { type Authenticator, type HttpOptions } from "@afora/core/adapters";
2
+ import { type FastifyInstance, type onRequestHookHandler } from "fastify";
3
+ /**
4
+ * The options of the `fastify` sink: those of every sink that serves HTTP
5
+ * (`basePath`, `route`, `responses`, `requestId`, `security`, `docs`,
6
+ * `debug`, `context`, `auth`). JSON, so the stage can live in an
7
+ * `afora.json`. The `variables` of `context` are properties a hook set on
8
+ * the request (`request.tenant`, after `decorateRequest`).
9
+ */
10
+ export type FastifyOptions = HttpOptions;
11
+ /**
12
+ * What the `fastify` sink takes that JSON cannot hold, as the second
13
+ * argument of `fastify(options, hooks)`.
14
+ */
15
+ export interface FastifyHooks {
16
+ /**
17
+ * Who calls, from the credentials of a request (`request.native` is the
18
+ * `FastifyRequest`). Asked for each operation with an `access` other than
19
+ * `public`; without it (and without `auth`) those operations answer 401.
20
+ */
21
+ readonly authenticator?: Authenticator;
22
+ /** `onRequest` hooks, run in order before every route of the sink. */
23
+ readonly middlewares?: readonly onRequestHookHandler[];
24
+ /**
25
+ * The Fastify instance to add the routes to, instead of a new one: its own
26
+ * plugins, hooks, not found and error handlers are kept.
27
+ */
28
+ readonly app?: FastifyInstance;
29
+ }
30
+ /**
31
+ * A Fastify instance that serves the operations of an output: the route each
32
+ * use case declares (`route` or `@Route`), else
33
+ * `POST {basePath}/{command}/{operation}`. The requests are handled by the
34
+ * route table of the core (`compileRoutes`), as in every sink that serves
35
+ * HTTP: the input from the body, the query, the path, headers and cookies,
36
+ * the context, the access of each use case (401 and 403), statuses,
37
+ * `application/problem+json` errors, the request id and the OpenAPI document
38
+ * at `docs.path`.
39
+ *
40
+ * The routes live in a plugin of their own, where the body is read as text
41
+ * (the table parses it, so an invalid one is a problem like the others), so
42
+ * the content type parsers of the instance are not touched. `hooks` (the
43
+ * second argument) holds what is not JSON: `authenticator`, `middlewares`
44
+ * (`onRequest` hooks) and an `app` to add the routes to.
45
+ */
46
+ export declare const fastify: import("@afora/core/adapters").SinkFactory<FastifyInstance<import("fastify").RawServerDefault, import("node:http").IncomingMessage, import("node:http").ServerResponse<import("node:http").IncomingMessage>, import("fastify").FastifyBaseLogger, import("fastify").FastifyTypeProviderDefault>, HttpOptions, FastifyHooks>;
47
+ /** The runtime catalog of this package: the stage name `fastify` resolves to the sink. */
48
+ export declare const FastifyStages: import("../../../dist/index.js").IStageCatalog<Readonly<Record<string, import("../../../dist/index.js").StageFactory>>>;
49
+ /** The catalog entries codegen reads (`--stages`): `{ name, module, export, kind }`. */
50
+ export declare const stages: readonly [{
51
+ readonly name: "fastify";
52
+ readonly module: "@afora/fastify";
53
+ readonly export: "fastify";
54
+ readonly kind: "sink";
55
+ }];
package/dist/index.js ADDED
@@ -0,0 +1,106 @@
1
+ // src/index.ts
2
+ import {
3
+ compileRoutes,
4
+ HTTP_OPTION_KEYS,
5
+ httpOptionsIssue,
6
+ sinkOf,
7
+ stageCatalogOf
8
+ } from "@afora/core/adapters";
9
+ import Fastify from "fastify";
10
+ function validate(options) {
11
+ for (const key of Object.keys(options)) {
12
+ if (!HTTP_OPTION_KEYS.includes(key)) {
13
+ return `fastify has no option "${key}".`;
14
+ }
15
+ }
16
+ return httpOptionsIssue(options, "fastify");
17
+ }
18
+ function first(value) {
19
+ if (Array.isArray(value))
20
+ return first(value[0]);
21
+ return typeof value === "string" ? value : undefined;
22
+ }
23
+
24
+ class FastifyHttpRequest {
25
+ native;
26
+ constructor(native) {
27
+ this.native = native;
28
+ }
29
+ param(name) {
30
+ return this.native.params[name];
31
+ }
32
+ query() {
33
+ const query = {};
34
+ for (const [name, value] of Object.entries(this.native.query)) {
35
+ query[name] = first(value);
36
+ }
37
+ return query;
38
+ }
39
+ header(name) {
40
+ return first(this.native.headers[name]);
41
+ }
42
+ text() {
43
+ return typeof this.native.body === "string" ? this.native.body : "";
44
+ }
45
+ variable(name) {
46
+ return this.native[name];
47
+ }
48
+ }
49
+ var requestOf = (request) => new FastifyHttpRequest(request);
50
+ function send(reply, result) {
51
+ reply.code(result.status).headers(result.headers);
52
+ if (result.cookies.length > 0)
53
+ reply.header("set-cookie", result.cookies);
54
+ return result.body === null ? reply.send() : reply.send(result.body);
55
+ }
56
+ function fastifyPath(path) {
57
+ return path.replace(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g, ":$1");
58
+ }
59
+ var fastify = sinkOf({
60
+ name: "fastify",
61
+ validate,
62
+ build: (operations, options, context, hooks) => {
63
+ const table = compileRoutes(operations, options, context, {
64
+ source: "fastify",
65
+ ...hooks?.authenticator ? { authenticator: hooks.authenticator } : {}
66
+ });
67
+ const app = hooks?.app ?? Fastify();
68
+ if (!hooks?.app) {
69
+ app.setNotFoundHandler((request, reply) => send(reply, table.notFound(requestOf(request))));
70
+ app.setErrorHandler((error, request, reply) => send(reply, table.failure(error, { request: requestOf(request) })));
71
+ }
72
+ app.register(async (scope) => {
73
+ scope.removeAllContentTypeParsers();
74
+ scope.addContentTypeParser("*", { parseAs: "string" }, (_request, body, done) => done(null, body));
75
+ for (const middleware of hooks?.middlewares ?? []) {
76
+ scope.addHook("onRequest", middleware);
77
+ }
78
+ for (const route of table.routes) {
79
+ scope.route({
80
+ method: route.method.toUpperCase(),
81
+ url: fastifyPath(route.path),
82
+ handler: async (request, reply) => send(reply, await route.handle(requestOf(request)))
83
+ });
84
+ }
85
+ const docs = table.docs;
86
+ if (docs) {
87
+ scope.get(docs.path, (request, reply) => send(reply, docs.handle(requestOf(request))));
88
+ }
89
+ });
90
+ return app;
91
+ }
92
+ });
93
+ var FastifyStages = stageCatalogOf(fastify);
94
+ var stages = [
95
+ {
96
+ name: "fastify",
97
+ module: "@afora/fastify",
98
+ export: "fastify",
99
+ kind: "sink"
100
+ }
101
+ ];
102
+ export {
103
+ FastifyStages,
104
+ fastify,
105
+ stages
106
+ };
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
- "name": "@afora/fastify",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@afora/fastify",
3
+ "version": "0.0.9",
4
+ "description": "A Fastify sink for afora outputs: one route per operation, problem+json errors, sensitive data masked, declared access enforced and an optional OpenAPI document.",
5
+ "keywords": [
6
+ "afora",
7
+ "fastify",
8
+ "openapi",
9
+ "problem-json",
10
+ "http",
11
+ "api"
12
+ ],
13
+ "author": "Alan Reis <alanreisanjo@gmail.com> (https://github.com/Hoyasumii)",
14
+ "license": "MIT",
15
+ "homepage": "https://github.com/afora-framework/core/tree/main/packages/fastify#readme",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/afora-framework/core.git",
19
+ "directory": "packages/fastify"
20
+ },
21
+ "type": "module",
22
+ "main": "./dist/index.js",
23
+ "module": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js",
29
+ "default": "./dist/index.js"
30
+ },
31
+ "./package.json": "./package.json"
32
+ },
33
+ "files": [
34
+ "dist"
35
+ ],
36
+ "engines": {
37
+ "bun": ">=1.4.4",
38
+ "node": ">=22"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public",
42
+ "provenance": true
43
+ },
44
+ "scripts": {
45
+ "typecheck": "bun check",
46
+ "build": "rm -rf dist && bun build ./src/index.ts --outdir ./dist --target node --format esm --packages external --tsconfig-override tsconfig.build.json && tsc -p tsconfig.build.json && bun ../../scripts/add-dts-extensions.ts dist",
47
+ "test": "bun test"
48
+ },
49
+ "devDependencies": {
50
+ "@types/bun": "^1.4.4",
51
+ "fastify": "^5.12.8",
52
+ "typebox": "^1.4.3"
53
+ },
54
+ "peerDependencies": {
55
+ "@afora/core": ">=0.0.9",
56
+ "fastify": "^5.12.8",
57
+ "typebox": "^1"
58
+ }
59
+ }