@tcds-io/fastify-server 0.1.0 → 0.1.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.
package/README.md CHANGED
@@ -23,6 +23,32 @@ await http.listen({ host: '0.0.0.0', port: 3000 });
23
23
  - **`pinoLogger(fastify)`** implements `debug`, `info`, `warn`, `error` and `fatal`, fields first as pino expects.
24
24
  - **`logStream`** sends log lines elsewhere than stdout (a test collects them).
25
25
 
26
+ ## Taking over a piece
27
+
28
+ Each option below is optional; a server that sets none of them behaves as above. Conflicting options throw at construction.
29
+
30
+ | Option | Instead of | Use when |
31
+ | --- | --- | --- |
32
+ | `logger` | `logLevel` + `logStream` (throws if either is also set) | You bring your own pino options (serializers, redaction, transport), or `false` for no logging. |
33
+ | `requestLogging: false` | Fastify's `incoming request` / `request completed` lines | You write your own access log line. `requestId` stays bound to every line. |
34
+ | `requestId: (raw) => string` | `ids` + trusting the caller's `x-request-id` | The id comes from elsewhere (a `traceparent`, a gateway header). The caller's `x-request-id` is then ignored; the id is still echoed on the response. |
35
+ | `cors: (request) => CorsAnswer` | `corsOrigins` (throws if both are set) | The policy differs per route family. The answer is the `@fastify/cors` options for that request (readonly arrays accepted); `x-request-id` is always added to its `exposedHeaders`. |
36
+ | `installErrorHandler: false` | the error and not-found handlers | You install your own `setErrorHandler` (no `FSTWRN004`) and want Fastify's default 404, or your own `setNotFoundHandler`. |
37
+ | `frameworkErrors` | the router-phase answer (malformed URL, bad content type, ...) | Your error body differs from `fastify-errors`, e.g. with `installErrorHandler: false`. `x-request-id` is written before it runs. |
38
+
39
+ ```ts
40
+ const http = createHttpServer({
41
+ logger: { level: 'info', redact: ['req.headers.authorization'] },
42
+ requestLogging: false,
43
+ requestId: (raw) => traceIdFrom(raw.headers.traceparent) ?? randomUUID(),
44
+ cors: (request) => (request.url.startsWith('/public/') ? { origin: true } : { origin: ['https://app.example.com'], credentials: true }),
45
+ });
46
+ ```
47
+
48
+ ## Known gap
49
+
50
+ Errors Fastify raises before the request hooks run (`frameworkErrors`) skip the CORS hook, so with `corsOrigins` (or `cors`) and the default `frameworkErrors` those replies carry no CORS headers: a browser sees a CORS failure instead of the 400. Set `frameworkErrors` and add the headers there if your clients need to read those errors.
51
+
26
52
  ## Peers
27
53
 
28
- `fastify`, `@tcds-io/errors` and `@tcds-io/runtime` are peer dependencies (ADR-0070).
54
+ `fastify`, `@tcds-io/domain` and `@tcds-io/runtime` are peer dependencies (ADR-0070).
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  export { createHttpServer, pinoLogger, REQUEST_ID_HEADER } from './server.js';
2
- export type { HttpServerOptions } from './server.js';
2
+ export type { CorsAnswer, HttpServerOptions } from './server.js';
package/dist/server.d.ts CHANGED
@@ -1,23 +1,47 @@
1
+ import { type FastifyCorsOptions } from '@fastify/cors';
1
2
  import { type ErrorHandlerOptions } from '@tcds-io/fastify-errors';
2
3
  import type { IdGenerator, Logger } from '@tcds-io/runtime';
3
- import { type FastifyInstance } from 'fastify';
4
+ import { type FastifyError, type FastifyInstance, type FastifyReply, type FastifyRequest, type FastifyServerOptions, type RawRequestDefaultExpression } from 'fastify';
4
5
  export declare const REQUEST_ID_HEADER = "x-request-id";
6
+ type CorsOrigin = boolean | string | RegExp;
7
+ /** The CORS options for one request (the `@fastify/cors` delegator answer), with readonly arrays accepted. */
8
+ export type CorsAnswer = Omit<FastifyCorsOptions, 'origin' | 'methods' | 'allowedHeaders' | 'exposedHeaders' | 'delegator' | 'hook' | 'hideOptionsRoute' | 'logLevel'> & {
9
+ readonly origin?: CorsOrigin | readonly CorsOrigin[];
10
+ readonly methods?: string | readonly string[];
11
+ readonly allowedHeaders?: string | readonly string[];
12
+ /** `x-request-id` is always added. */
13
+ readonly exposedHeaders?: string | readonly string[];
14
+ };
5
15
  export type HttpServerOptions = {
6
- readonly logLevel: string;
7
- /** Mints the id of a request that arrives without `x-request-id`. */
8
- readonly ids: IdGenerator;
9
- /** Browser origins allowed to call the API. Empty or omitted: none (same-origin only). */
16
+ /** Required unless `logger` is set. */
17
+ readonly logLevel?: string;
18
+ /** Mints the id of a request that arrives without `x-request-id`. Required unless `requestId` is set. */
19
+ readonly ids?: IdGenerator;
20
+ /** Browser origins allowed to call the API. Empty or omitted: none (same-origin only). Not with `cors`. */
10
21
  readonly corsOrigins?: readonly string[];
11
22
  /** Passed to `installErrorHandler`: status table, wire codes, internal message, `onError`. */
12
23
  readonly errorOptions?: ErrorHandlerOptions;
13
- /** Where log lines go. Default: stdout. */
24
+ /** Where log lines go. Default: stdout. Not with `logger`. */
14
25
  readonly logStream?: NodeJS.WritableStream;
26
+ /** Fastify's `logger` option, used as given (options object or `false`). Not with `logLevel` or `logStream`. */
27
+ readonly logger?: FastifyServerOptions['logger'];
28
+ /** Fastify's "incoming request" / "request completed" log lines. Default true. */
29
+ readonly requestLogging?: boolean;
30
+ /** Derives the request id from the raw request; `x-request-id` from the caller is then not trusted and `ids` is unused. */
31
+ readonly requestId?: (request: RawRequestDefaultExpression) => string;
32
+ /** CORS decided per request; `x-request-id` is always added to the exposed headers. Not with `corsOrigins`. */
33
+ readonly cors?: (request: FastifyRequest) => CorsAnswer;
34
+ /** Default true. false: neither the error handler nor the not-found handler is installed; the caller installs its own. */
35
+ readonly installErrorHandler?: boolean;
36
+ /** Answers errors Fastify raises before the request hooks run. `x-request-id` is written before it is called. */
37
+ readonly frameworkErrors?: (error: FastifyError, request: FastifyRequest, reply: FastifyReply) => void;
15
38
  };
16
39
  /**
17
- * Fastify with pino logging, one request id per request (taken from `x-request-id` when the caller sends one,
18
- * minted by `ids` otherwise), echoed back on the response and bound to every log line as `requestId`, optional
19
- * CORS, and the one error handler (`@tcds-io/fastify-errors`).
40
+ * Fastify with pino logging, one request id per request (taken from `x-request-id` when the caller sends one and
41
+ * minted by `ids` otherwise, or derived by `requestId`), echoed back on the response and bound to every log line as
42
+ * `requestId`, optional CORS, and the one error handler (`@tcds-io/fastify-errors`).
20
43
  */
21
44
  export declare const createHttpServer: (options: HttpServerOptions) => FastifyInstance;
22
45
  /** The `Logger` port (`@tcds-io/runtime`) over Fastify's pino logger. */
23
46
  export declare const pinoLogger: (fastify: Pick<FastifyInstance, "log">) => Logger;
47
+ export {};
package/dist/server.js CHANGED
@@ -1,34 +1,84 @@
1
- import cors from '@fastify/cors';
1
+ import cors, {} from '@fastify/cors';
2
2
  import { createErrorHandler, installErrorHandler } from '@tcds-io/fastify-errors';
3
- import Fastify, { LogController } from 'fastify';
3
+ import Fastify, { LogController, } from 'fastify';
4
4
  export const REQUEST_ID_HEADER = 'x-request-id';
5
+ const validate = (options) => {
6
+ if (options.logger !== undefined && (options.logLevel !== undefined || options.logStream !== undefined)) {
7
+ throw new Error('createHttpServer: `logger` replaces `logLevel` and `logStream`; set one or the other');
8
+ }
9
+ if (options.logger === undefined && options.logLevel === undefined) {
10
+ throw new Error('createHttpServer: set `logLevel` or `logger`');
11
+ }
12
+ if (options.ids === undefined && options.requestId === undefined) {
13
+ throw new Error('createHttpServer: set `ids` or `requestId`');
14
+ }
15
+ if (options.cors !== undefined && options.corsOrigins !== undefined) {
16
+ throw new Error('createHttpServer: set `cors` or `corsOrigins`, not both');
17
+ }
18
+ };
19
+ const list = (value) => value === undefined ? [] : typeof value === 'string' ? value.split(',').map((item) => item.trim()).filter(Boolean) : [...value];
20
+ const withRequestIdExposed = (answer) => {
21
+ const exposed = list(answer.exposedHeaders);
22
+ if (!exposed.some((header) => header.toLowerCase() === REQUEST_ID_HEADER))
23
+ exposed.push(REQUEST_ID_HEADER);
24
+ return {
25
+ ...answer,
26
+ origin: Array.isArray(answer.origin) ? [...answer.origin] : answer.origin,
27
+ methods: answer.methods === undefined ? undefined : list(answer.methods),
28
+ allowedHeaders: answer.allowedHeaders === undefined ? undefined : list(answer.allowedHeaders),
29
+ exposedHeaders: exposed,
30
+ };
31
+ };
5
32
  /**
6
- * Fastify with pino logging, one request id per request (taken from `x-request-id` when the caller sends one,
7
- * minted by `ids` otherwise), echoed back on the response and bound to every log line as `requestId`, optional
8
- * CORS, and the one error handler (`@tcds-io/fastify-errors`).
33
+ * Fastify with pino logging, one request id per request (taken from `x-request-id` when the caller sends one and
34
+ * minted by `ids` otherwise, or derived by `requestId`), echoed back on the response and bound to every log line as
35
+ * `requestId`, optional CORS, and the one error handler (`@tcds-io/fastify-errors`).
9
36
  */
10
37
  export const createHttpServer = (options) => {
11
- const frameworkHandler = createErrorHandler(options.errorOptions);
38
+ validate(options);
39
+ const answerFrameworkError = options.frameworkErrors ?? createErrorHandler(options.errorOptions);
40
+ const requestId = options.requestId;
41
+ const ids = options.ids;
12
42
  const fastify = Fastify({
13
- logger: { level: options.logLevel, ...(options.logStream !== undefined ? { stream: options.logStream } : {}) },
14
- logController: new LogController({ requestIdLogLabel: 'requestId' }),
15
- requestIdHeader: REQUEST_ID_HEADER,
16
- genReqId: () => options.ids.next(),
17
- // Errors Fastify raises before the request hooks ran (a malformed URL, say): same body, and the request id the
18
- // `onRequest` hook would have echoed.
43
+ logger: options.logger !== undefined
44
+ ? options.logger
45
+ : { level: options.logLevel, ...(options.logStream !== undefined ? { stream: options.logStream } : {}) },
46
+ logController: new LogController({
47
+ requestIdLogLabel: 'requestId',
48
+ ...(options.requestLogging === false ? { disableRequestLogging: true } : {}),
49
+ }),
50
+ ...(requestId !== undefined
51
+ ? { requestIdHeader: false, genReqId: requestId }
52
+ : { requestIdHeader: REQUEST_ID_HEADER, genReqId: () => ids.next() }),
53
+ // Errors Fastify raises before the request hooks ran (a malformed URL, say): the request id the `onRequest` hook
54
+ // would have echoed, then the same body as every other error (or the caller's own answer).
19
55
  frameworkErrors: (error, request, reply) => {
20
56
  void reply.header(REQUEST_ID_HEADER, request.id);
21
- void frameworkHandler(error, request, reply);
57
+ void answerFrameworkError(error, request, reply);
22
58
  },
23
59
  });
24
60
  fastify.addHook('onRequest', (request, reply, done) => {
25
61
  reply.header(REQUEST_ID_HEADER, request.id);
26
62
  done();
27
63
  });
28
- if (options.corsOrigins !== undefined && options.corsOrigins.length > 0) {
64
+ const corsAnswer = options.cors;
65
+ if (corsAnswer !== undefined) {
66
+ void fastify.register(cors, {
67
+ delegator: (request, callback) => {
68
+ try {
69
+ callback(null, withRequestIdExposed(corsAnswer(request)));
70
+ }
71
+ catch (error) {
72
+ callback(error);
73
+ }
74
+ },
75
+ });
76
+ }
77
+ else if (options.corsOrigins !== undefined && options.corsOrigins.length > 0) {
29
78
  void fastify.register(cors, { origin: [...options.corsOrigins], exposedHeaders: [REQUEST_ID_HEADER] });
30
79
  }
31
- installErrorHandler(fastify, options.errorOptions);
80
+ if (options.installErrorHandler !== false)
81
+ installErrorHandler(fastify, options.errorOptions);
32
82
  return fastify;
33
83
  };
34
84
  /** The `Logger` port (`@tcds-io/runtime`) over Fastify's pino logger. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tcds-io/fastify-server",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Fastify with request ids, pino logging, CORS and the one error handler already wired.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -25,10 +25,10 @@
25
25
  },
26
26
  "dependencies": {
27
27
  "@fastify/cors": "^11.1.0",
28
- "@tcds-io/fastify-errors": "^0.1.0"
28
+ "@tcds-io/fastify-errors": "^0.1.2"
29
29
  },
30
30
  "peerDependencies": {
31
- "@tcds-io/errors": "~0.1.0",
31
+ "@tcds-io/domain": "~0.1.0",
32
32
  "@tcds-io/runtime": "~0.1.0",
33
33
  "fastify": ">=5.12"
34
34
  },
@@ -37,14 +37,14 @@
37
37
  "fastify": "^5.12.8",
38
38
  "typescript": "^5.7.2",
39
39
  "vitest": "^2.1.8",
40
- "@tcds-io/runtime": "^0.1.0",
41
- "@tcds-io/errors": "^0.1.0"
40
+ "@tcds-io/domain": "^0.1.0",
41
+ "@tcds-io/runtime": "^0.1.0"
42
42
  },
43
43
  "engines": {
44
44
  "node": ">=22"
45
45
  },
46
46
  "scripts": {
47
- "build": "tsc -p tsconfig.build.json",
47
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
48
48
  "check:types": "tsc --noEmit -p .",
49
49
  "test": "vitest run"
50
50
  }