@decohere/http-fastify 0.0.1-dev.20261120.336 → 0.0.1-dev.5

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/LICENSE DELETED
@@ -1,15 +0,0 @@
1
- ISC License
2
-
3
- Copyright (c) 2025-2026 Typesmiths
4
-
5
- Permission to use, copy, modify, and/or distribute this software for any
6
- purpose with or without fee is hereby granted, provided that the above
7
- copyright notice and this permission notice appear in all copies.
8
-
9
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
@@ -1,394 +0,0 @@
1
- function _ts_decorate(decorators, target, key, desc) {
2
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
- else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
- return c > 3 && r && Object.defineProperty(target, key, r), r;
6
- }
7
- function _ts_metadata(k, v) {
8
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
- }
10
- function _ts_param(paramIndex, decorator) {
11
- return function(target, key) {
12
- decorator(target, key, paramIndex);
13
- };
14
- }
15
- import { randomUUID } from "node:crypto";
16
- import { stat } from "node:fs/promises";
17
- import path from "node:path";
18
- import { Readable } from "node:stream";
19
- import { inject } from "@decohere/crucible/decorators";
20
- import { scribe } from "@decohere/scribe";
21
- import compress from "@fastify/compress";
22
- import cors from "@fastify/cors";
23
- import helmet from "@fastify/helmet";
24
- import rateLimit from "@fastify/rate-limit";
25
- import fastifyStatic from "@fastify/static";
26
- import Fastify from "fastify";
27
- import { DEFAULT_COMPRESSION_ENCODINGS, DEFAULT_COMPRESSION_THRESHOLD, DEFAULT_HTTP_BODY_LIMIT, DEFAULT_HTTP_RATE_LIMIT, DEFAULT_SSE_HEARTBEAT_MS, DefaultHttpExceptionFilter, ExceptionFilterHostToken, HttpOptionsToken, HttpRequest, PROBLEM_CONTENT_TYPE, REQUEST_ID_HEADER, RouteRegistryToken, RouterToken, SseResponse, encodeSse, generateOpenApiDocument, normalizePrefix, problemDetails, resolveOpenApiPath, resolveRequestId, staticFiles } from "@decohere/http";
28
- export class FastifyProvider {
29
- provider;
30
- router;
31
- routeRegistry;
32
- httpOptions;
33
- exceptionFilterHost;
34
- closing;
35
- logger = scribe.logger(FastifyProvider.name);
36
- /** One per live `@Sse()` request, so stopping the app can end the streams. */ openStreams = new Set();
37
- constructor(routeRegistry, router, httpOptions, exceptionFilterHost){
38
- this.routeRegistry = routeRegistry;
39
- this.router = router;
40
- this.httpOptions = httpOptions;
41
- this.exceptionFilterHost = exceptionFilterHost;
42
- this.provider = Fastify({
43
- logger: false,
44
- requestIdHeader: REQUEST_ID_HEADER,
45
- genReqId: ()=>randomUUID(),
46
- bodyLimit: httpOptions?.bodyLimit ?? DEFAULT_HTTP_BODY_LIMIT
47
- });
48
- }
49
- async start(options) {
50
- const statics = await this.resolveStatics();
51
- await this.registerHelmet(this.httpOptions?.helmet);
52
- await this.registerRateLimit(this.httpOptions?.rateLimit, statics);
53
- await this.registerCors(this.httpOptions?.cors);
54
- await this.registerCompression(this.httpOptions?.compression);
55
- this.registerProblemReplies(statics);
56
- this.registerOpenApi(this.httpOptions);
57
- this.registerAllRoutes(this.routeRegistry);
58
- for (const mount of statics){
59
- await this.registerStatic(mount, statics);
60
- }
61
- this.closeConnectionsWhileStopping();
62
- await this.provider.listen(options);
63
- return {
64
- addresses: this.addresses
65
- };
66
- }
67
- async stop() {
68
- // App stops HTTP before disposing the container, which calls this again.
69
- // A stream never finishes on its own, and close() waits for open responses, so end them first.
70
- for (const stream of this.openStreams){
71
- stream.abort(new Error("The app is stopping"));
72
- }
73
- this.closing ??= this.provider.close();
74
- await this.closing;
75
- return {
76
- message: "closed"
77
- };
78
- }
79
- async [Symbol.asyncDispose]() {
80
- await this.stop();
81
- }
82
- /**
83
- * Once stopping, tell clients to drop the connection after their response. Otherwise
84
- * a request that was in flight leaves a kept-alive socket that holds `close()` open
85
- * until Node's keep-alive timeout (5s).
86
- */ closeConnectionsWhileStopping() {
87
- this.provider.addHook("onSend", async (_request, reply, payload)=>{
88
- if (this.closing) reply.header("connection", "close");
89
- return payload;
90
- });
91
- }
92
- get addresses() {
93
- return this.provider.addresses().filter((a)=>typeof a !== "string" && a.family === "IPv4").map((a)=>`http://${a.address}:${a.port}`);
94
- }
95
- async registerHelmet(helmetOptions) {
96
- if (helmetOptions === false) {
97
- return;
98
- }
99
- await this.provider.register(helmet, helmetOptions ?? {});
100
- }
101
- async registerRateLimit(rateLimitOptions, statics) {
102
- if (rateLimitOptions === false) {
103
- return;
104
- }
105
- // Static files are outside the rate limit (ADR 0007). Matched on the route the request
106
- // resolved to, not on its URL, so only requests the static plugin serves are exempt.
107
- const staticRoutes = new Set(statics.map((mount)=>`${mount.prefix}*`));
108
- const userAllowList = rateLimitOptions?.allowList;
109
- await this.provider.register(rateLimit, {
110
- ...DEFAULT_HTTP_RATE_LIMIT,
111
- ...rateLimitOptions,
112
- allowList: (request, key)=>{
113
- if (staticRoutes.has(request.routeOptions.url ?? "")) return true;
114
- if (typeof userAllowList === "function") return userAllowList(request, key);
115
- return Array.isArray(userAllowList) && userAllowList.includes(key);
116
- }
117
- });
118
- }
119
- async resolveStatics() {
120
- return staticFiles.resolve(this.httpOptions?.statics ?? [], {
121
- nodeEnv: process.env.NODE_ENV,
122
- directoryExists: async (directory)=>(await stat(directory).catch(()=>undefined))?.isDirectory() === true,
123
- warn: (message)=>this.logger.warn(message)
124
- });
125
- }
126
- /**
127
- * One encapsulated context per mount: its not-found handler (the SPA fallback) applies to
128
- * paths under the prefix and nowhere else, so an API 404 is never answered with the UI.
129
- */ async registerStatic(mount, mounts) {
130
- const withoutSlash = mount.prefix.slice(0, -1);
131
- const isRoot = mount.prefix === "/";
132
- const excluded = staticFiles.excluder(mount.exclude);
133
- const belongsToApi = this.apiBoundary();
134
- // Requests that already fell back once: a missing index must be a 404, not a loop.
135
- const fellBack = new WeakSet();
136
- await this.provider.register(async (scope)=>{
137
- await scope.register(fastifyStatic, {
138
- root: mount.root,
139
- prefix: "/",
140
- index: mount.index,
141
- dotfiles: "ignore",
142
- list: false,
143
- redirect: false,
144
- etag: true,
145
- lastModified: true,
146
- // The header is set in setHeaders, per file.
147
- cacheControl: false,
148
- setHeaders: (reply, filePath)=>{
149
- reply.header("cache-control", staticFiles.cacheControlFor(mount, path.relative(mount.root, filePath)));
150
- }
151
- });
152
- // Excluded paths are not served at all: not as a file, not as the fallback.
153
- scope.addHook("onRequest", async (request, reply)=>{
154
- if (excluded(staticFiles.normalizePathname(request.url))) {
155
- return reply.callNotFound();
156
- }
157
- });
158
- scope.setNotFoundHandler((request, reply)=>{
159
- const [pathname = "", query] = request.url.split("?");
160
- const readOnly = request.method === "GET" || request.method === "HEAD";
161
- // `/ui` goes to `/ui/`. A request for it reaches the root mount's handler instead
162
- // when there is one, so that handler redirects for the other mounts too.
163
- const redirectTo = mounts.find((other)=>other.prefix !== "/" && other.prefix.slice(0, -1) === pathname && (isRoot || other === mount));
164
- if (readOnly && redirectTo != null) {
165
- return reply.redirect(query == null ? redirectTo.prefix : `${redirectTo.prefix}?${query}`, 301);
166
- }
167
- const normalized = staticFiles.normalizePathname(request.url);
168
- if (mount.spaFallback && !fellBack.has(request) && !excluded(normalized) && staticFiles.shouldFallBack({
169
- method: request.method,
170
- pathname: normalized,
171
- accept: request.headers.accept
172
- }, belongsToApi)) {
173
- fellBack.add(request);
174
- return reply.sendFile(mount.index);
175
- }
176
- return this.sendRouteNotFound(request, reply);
177
- });
178
- }, {
179
- prefix: withoutSlash
180
- });
181
- }
182
- /**
183
- * Fastify's own replies, for an unknown route or a request it rejects before any handler
184
- * (a body that isn't valid JSON, too large, the rate limit), are problems like the API's.
185
- */ registerProblemReplies(statics) {
186
- // A UI served from the root owns the root's not-found handler, and answers the same 404.
187
- if (!statics.some((mount)=>mount.prefix === "/")) {
188
- this.provider.setNotFoundHandler((request, reply)=>this.sendRouteNotFound(request, reply));
189
- }
190
- this.provider.setErrorHandler((error, _request, reply)=>{
191
- const status = this.getErrorStatus(error);
192
- const message = error instanceof Error ? error.message : undefined;
193
- if (status >= 500) {
194
- this.logger.error(message ?? "Request failed", error instanceof Error ? error.stack : undefined);
195
- }
196
- const problem = problemDetails.create(status, {
197
- detail: status >= 500 ? undefined : message
198
- });
199
- return reply.status(status).header("content-type", PROBLEM_CONTENT_TYPE).send(problem);
200
- });
201
- }
202
- getErrorStatus(error) {
203
- const status = error?.statusCode;
204
- return typeof status === "number" && status >= 400 && status < 600 ? status : 500;
205
- }
206
- sendRouteNotFound(request, reply) {
207
- const [pathname = ""] = request.url.split("?");
208
- const problem = problemDetails.create(404, {
209
- detail: `Route ${request.method}:${pathname} not found`
210
- });
211
- return reply.code(404).header("content-type", PROBLEM_CONTENT_TYPE).send(problem);
212
- }
213
- /** What the static fallback leaves to the API: the global prefix, else the registered routes. ADR 0007. */ apiBoundary() {
214
- return staticFiles.apiBoundary({
215
- globalPrefix: normalizePrefix(this.httpOptions?.globalPrefix),
216
- openApiPath: this.httpOptions?.openapi == null ? undefined : resolveOpenApiPath(this.httpOptions.openapi),
217
- routePaths: [
218
- ...this.routeRegistry.routes
219
- ].map((route)=>route.path)
220
- });
221
- }
222
- /**
223
- * `@fastify/compress` with best-practice defaults; the plugin owns the policy. Registered
224
- * before any route so every response goes through it, errors and static files included.
225
- * `providerOptions` is merged last, so a user can override any plugin option.
226
- */ async registerCompression(compressionOptions) {
227
- if (compressionOptions === false) {
228
- return;
229
- }
230
- await this.provider.register(compress, {
231
- global: true,
232
- threshold: compressionOptions?.threshold ?? DEFAULT_COMPRESSION_THRESHOLD,
233
- encodings: [
234
- ...compressionOptions?.encodings ?? DEFAULT_COMPRESSION_ENCODINGS
235
- ],
236
- ...compressionOptions?.types != null && {
237
- customTypes: compressionOptions.types
238
- },
239
- ...compressionOptions?.providerOptions
240
- });
241
- }
242
- async registerCors(corsOptions) {
243
- if (corsOptions == null) {
244
- return;
245
- }
246
- await this.provider.register(cors, {
247
- origin: corsOptions.origin,
248
- methods: corsOptions.methods,
249
- allowedHeaders: corsOptions.allowedHeaders,
250
- exposedHeaders: corsOptions.exposedHeaders,
251
- credentials: corsOptions.credentials,
252
- maxAge: corsOptions.maxAge
253
- });
254
- }
255
- registerOpenApi(httpOptions) {
256
- const openapi = httpOptions?.openapi;
257
- if (openapi == null) {
258
- return;
259
- }
260
- const path = resolveOpenApiPath(openapi);
261
- const document = generateOpenApiDocument(this.routeRegistry, openapi);
262
- this.provider.get(path, async (_request, reply)=>{
263
- reply.header("content-type", "application/json; charset=utf-8");
264
- return document;
265
- });
266
- }
267
- registerAllRoutes(registry) {
268
- for (const route of registry.routes){
269
- const { key, method, path } = route;
270
- this.provider.route({
271
- method,
272
- url: path,
273
- handler: (request, reply)=>this.routeRequest(route, key, request, reply)
274
- });
275
- }
276
- }
277
- async routeRequest(route, key, request, reply) {
278
- const httpRequest = this.fastifyToRequest(request);
279
- const disconnect = this.abortOnDisconnect(reply, httpRequest, route.sse != null);
280
- try {
281
- const response = await this.router.route(key, httpRequest);
282
- if (route.httpCode != null) {
283
- reply.status(route.httpCode);
284
- }
285
- if (route.headers != null) {
286
- for (const [name, value] of Object.entries(route.headers)){
287
- reply.header(name, value);
288
- }
289
- }
290
- this.applyResponseHeaders(reply, httpRequest);
291
- if (response instanceof SseResponse) {
292
- return this.sendEventStream(route, reply, response, disconnect);
293
- }
294
- return response;
295
- } catch (error) {
296
- const result = this.exceptionFilterHost ? await this.exceptionFilterHost.handle(error, {
297
- request: httpRequest
298
- }) : new DefaultHttpExceptionFilter().catch(error, {
299
- request: httpRequest
300
- });
301
- if (result.headers) {
302
- for (const [name, value] of Object.entries(result.headers)){
303
- reply.header(name, value);
304
- }
305
- }
306
- this.applyResponseHeaders(reply, httpRequest);
307
- // Returned so Fastify waits for the async onSend hooks instead of sending an empty reply of its own.
308
- return reply.status(result.status).send(result.body);
309
- }
310
- }
311
- /**
312
- * Gives the handler a signal that aborts when the client goes away before the response
313
- * finished. Streams are also tracked so that stopping the app can abort them.
314
- */ abortOnDisconnect(reply, httpRequest, isStream) {
315
- const controller = new AbortController();
316
- httpRequest.signal = controller.signal;
317
- if (isStream) {
318
- if (this.closing) controller.abort(new Error("The app is stopping"));
319
- this.openStreams.add(controller);
320
- }
321
- reply.raw.once("close", ()=>{
322
- this.openStreams.delete(controller);
323
- if (!reply.raw.writableFinished) {
324
- controller.abort(new Error("The client disconnected"));
325
- }
326
- });
327
- return controller;
328
- }
329
- sendEventStream(route, reply, response, disconnect) {
330
- let started = false;
331
- const release = ()=>{
332
- response.release().catch((error)=>{
333
- this.logger.error("Releasing the request scope of an SSE stream failed", error);
334
- });
335
- };
336
- const frames = encodeSse(response.events, {
337
- signal: disconnect.signal,
338
- heartbeatMs: route.sse?.heartbeatMs ?? DEFAULT_SSE_HEARTBEAT_MS,
339
- onProducerStopped: (stopped)=>void stopped.then(release)
340
- });
341
- const guarded = async function*() {
342
- started = true;
343
- yield* frames;
344
- }();
345
- // Never pulled if the client left first, in which case nothing else would release the scope.
346
- reply.raw.once("close", ()=>{
347
- if (!started) release();
348
- });
349
- return reply.status(route.httpCode ?? 200).header("content-type", "text/event-stream; charset=utf-8").header("cache-control", "no-cache, no-transform").header("x-accel-buffering", "no")// A stream owns its connection; closing it afterwards lets app stop finish at once instead of waiting out keep-alive.
350
- .header("connection", "close").send(Readable.from(guarded));
351
- }
352
- applyResponseHeaders(reply, httpRequest) {
353
- reply.header(REQUEST_ID_HEADER, httpRequest.requestId);
354
- for (const [name, value] of Object.entries(httpRequest.responseHeaders)){
355
- reply.header(name, value);
356
- }
357
- }
358
- fastifyToRequest(fastifyRequest) {
359
- const method = fastifyRequest.method;
360
- const url = fastifyRequest.url;
361
- const params = fastifyRequest.params;
362
- const query = fastifyRequest.query;
363
- const body = fastifyRequest.body ?? {};
364
- const headers = {};
365
- for (const [key, value] of Object.entries(fastifyRequest.headers)){
366
- if (typeof value === "string") {
367
- headers[key.toLowerCase()] = value;
368
- }
369
- }
370
- const requestId = resolveRequestId(headers, String(fastifyRequest.id ?? ""));
371
- return new HttpRequest({
372
- requestId,
373
- url,
374
- method,
375
- params,
376
- query,
377
- body,
378
- headers
379
- });
380
- }
381
- }
382
- FastifyProvider = _ts_decorate([
383
- _ts_param(0, inject(RouteRegistryToken)),
384
- _ts_param(1, inject(RouterToken)),
385
- _ts_param(2, inject(HttpOptionsToken)),
386
- _ts_param(3, inject(ExceptionFilterHostToken)),
387
- _ts_metadata("design:type", Function),
388
- _ts_metadata("design:paramtypes", [
389
- typeof RouteRegistry === "undefined" ? Object : RouteRegistry,
390
- typeof Router === "undefined" ? Object : Router,
391
- typeof HttpOptions === "undefined" ? Object : HttpOptions,
392
- typeof ExceptionFilterHost === "undefined" ? Object : ExceptionFilterHost
393
- ])
394
- ], FastifyProvider);
@@ -1,59 +0,0 @@
1
- import { type FastifyInstance } from "fastify";
2
- import { type ExceptionFilterHost, type HttpOptions, type HttpProvider, type RouteRegistry, type Router, type StartOptions, type StartResponse, type StopResponse } from "@decohere/http";
3
- export declare class FastifyProvider implements HttpProvider {
4
- readonly provider: FastifyInstance;
5
- readonly router: Router;
6
- private readonly routeRegistry;
7
- private readonly httpOptions?;
8
- private readonly exceptionFilterHost?;
9
- private closing;
10
- private readonly logger;
11
- /** One per live `@Sse()` request, so stopping the app can end the streams. */
12
- private readonly openStreams;
13
- constructor(routeRegistry?: RouteRegistry, router?: Router, httpOptions?: HttpOptions, exceptionFilterHost?: ExceptionFilterHost);
14
- start<T extends StartOptions>(options?: T): Promise<StartResponse>;
15
- stop(): Promise<StopResponse>;
16
- [Symbol.asyncDispose](): Promise<void>;
17
- /**
18
- * Once stopping, tell clients to drop the connection after their response. Otherwise
19
- * a request that was in flight leaves a kept-alive socket that holds `close()` open
20
- * until Node's keep-alive timeout (5s).
21
- */
22
- private closeConnectionsWhileStopping;
23
- get addresses(): string[];
24
- private registerHelmet;
25
- private registerRateLimit;
26
- private resolveStatics;
27
- /**
28
- * One encapsulated context per mount: its not-found handler (the SPA fallback) applies to
29
- * paths under the prefix and nowhere else, so an API 404 is never answered with the UI.
30
- */
31
- private registerStatic;
32
- /**
33
- * Fastify's own replies, for an unknown route or a request it rejects before any handler
34
- * (a body that isn't valid JSON, too large, the rate limit), are problems like the API's.
35
- */
36
- private registerProblemReplies;
37
- private getErrorStatus;
38
- private sendRouteNotFound;
39
- /** What the static fallback leaves to the API: the global prefix, else the registered routes. ADR 0007. */
40
- private apiBoundary;
41
- /**
42
- * `@fastify/compress` with best-practice defaults; the plugin owns the policy. Registered
43
- * before any route so every response goes through it, errors and static files included.
44
- * `providerOptions` is merged last, so a user can override any plugin option.
45
- */
46
- private registerCompression;
47
- private registerCors;
48
- private registerOpenApi;
49
- private registerAllRoutes;
50
- private routeRequest;
51
- /**
52
- * Gives the handler a signal that aborts when the client goes away before the response
53
- * finished. Streams are also tracked so that stopping the app can abort them.
54
- */
55
- private abortOnDisconnect;
56
- private sendEventStream;
57
- private applyResponseHeaders;
58
- private fastifyToRequest;
59
- }
@@ -1 +0,0 @@
1
- export { FastifyProvider } from "./fastify.provider.js";
File without changes