@fedify/fastify 1.9.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.
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright 2024–2025 Hong Minhee
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,36 @@
1
+ <!-- deno-fmt-ignore-file -->
2
+
3
+ @fedify/fastify: Integrate Fedify with Fastify
4
+ ==============================================
5
+
6
+ [![npm][npm badge]][npm]
7
+ [![Matrix][Matrix badge]][Matrix]
8
+ [![Follow @fedify@hollo.social][@fedify@hollo.social badge]][@fedify@hollo.social]
9
+
10
+ This package provides a simple way to integrate [Fedify] with [Fastify].
11
+
12
+ The integration code looks like this:
13
+
14
+ ~~~~ typescript
15
+ import Fastify from "fastify";
16
+ import { fedifyPlugin } from "@fedify/fastify";
17
+ import { federation } from "./federation.ts"; // Your `Federation` instance
18
+
19
+ const fastify = Fastify({ logger: true });
20
+
21
+ await fastify.register(fedifyPlugin, {
22
+ federation,
23
+ contextDataFactory: () => undefined,
24
+ });
25
+
26
+ fastify.listen({ port: 3000 });
27
+ ~~~~
28
+
29
+ [npm]: https://www.npmjs.com/package/@fedify/fastify
30
+ [npm badge]: https://img.shields.io/npm/v/@fedify/fastify?logo=npm
31
+ [Matrix]: https://matrix.to/#/#fedify:matrix.org
32
+ [Matrix badge]: https://img.shields.io/matrix/fedify%3Amatrix.org
33
+ [@fedify@hollo.social badge]: https://fedi-badge.deno.dev/@fedify@hollo.social/followers.svg
34
+ [@fedify@hollo.social]: https://hollo.social/@fedify
35
+ [Fedify]: https://fedify.dev/
36
+ [Fastify]: https://fastify.dev/
package/dist/index.cjs ADDED
@@ -0,0 +1,107 @@
1
+ Object.defineProperty(exports, '__esModule', { value: true });
2
+ //#region rolldown:runtime
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+
24
+ //#endregion
25
+ const fastify_plugin = __toESM(require("fastify-plugin"));
26
+ const node_stream = __toESM(require("node:stream"));
27
+
28
+ //#region src/index.ts
29
+ /**
30
+ * Fastify plugin that integrates with a Federation instance.
31
+ *
32
+ * @example
33
+ * ```typescript
34
+ * import { createFederation, MemoryKvStore, Person } from "@fedify/fedify";
35
+ * import fedifyPlugin from "@fedify/fastify";
36
+ * import Fastify from "fastify";
37
+ *
38
+ * const fastify = Fastify();
39
+ *
40
+ * const federation = createFederation({ kv: new MemoryKvStore() });
41
+ *
42
+ * // Add federation routes
43
+ * federation.setActorDispatcher("/users/{identifier}", async (ctx, identifier) => {
44
+ * return new Person({
45
+ * id: ctx.getActorUri(identifier),
46
+ * preferredUsername: identifier,
47
+ * });
48
+ * });
49
+ *
50
+ * // Register the plugin
51
+ * await fastify.register(fedifyPlugin, {
52
+ * federation,
53
+ * contextDataFactory: () => undefined,
54
+ * errorHandlers: { onNotFound: () => new Response("Not Found", { status: 404 }) },
55
+ * });
56
+ * ```
57
+ */
58
+ const fedifyPluginCore = (fastify, options) => {
59
+ const { federation, contextDataFactory = () => void 0, errorHandlers } = options;
60
+ fastify.addHook("onRequest", async (request, reply) => {
61
+ const webRequest = toWebRequest(request);
62
+ const contextData = await contextDataFactory(request);
63
+ const response = await federation.fetch(webRequest, {
64
+ contextData,
65
+ onNotAcceptable: () => defaultNotAcceptableResponse,
66
+ onNotFound: () => dummyNotFoundResponse,
67
+ ...errorHandlers
68
+ });
69
+ if (response === dummyNotFoundResponse) return;
70
+ await reply.send(response);
71
+ });
72
+ return Promise.resolve();
73
+ };
74
+ const fedifyPlugin = (0, fastify_plugin.default)(fedifyPluginCore, {
75
+ name: "fedify-plugin",
76
+ fastify: "5.x"
77
+ });
78
+ const dummyNotFoundResponse = new Response("", { status: 404 });
79
+ const defaultNotAcceptableResponse = new Response("Not Acceptable", {
80
+ status: 406,
81
+ headers: {
82
+ "Content-Type": "text/plain",
83
+ Vary: "Accept"
84
+ }
85
+ });
86
+ /**
87
+ * Convert Fastify request to Web API Request.
88
+ */
89
+ function toWebRequest(fastifyReq) {
90
+ const protocol = fastifyReq.protocol;
91
+ const host = fastifyReq.headers.host ?? fastifyReq.hostname;
92
+ const url = `${protocol}://${host}${fastifyReq.url}`;
93
+ const headers = new Headers();
94
+ for (const [key, value] of Object.entries(fastifyReq.raw.headers)) if (Array.isArray(value)) for (const v of value) headers.append(key, v);
95
+ else if (value !== void 0) headers.set(key, String(value));
96
+ const body = fastifyReq.method === "GET" || fastifyReq.method === "HEAD" ? void 0 : fastifyReq.body !== void 0 ? typeof fastifyReq.body === "string" ? fastifyReq.body : JSON.stringify(fastifyReq.body) : node_stream.Readable.toWeb(fastifyReq.raw);
97
+ return new Request(url, {
98
+ method: fastifyReq.method,
99
+ headers,
100
+ body
101
+ });
102
+ }
103
+ var src_default = fedifyPlugin;
104
+
105
+ //#endregion
106
+ exports.default = src_default;
107
+ exports.fedifyPlugin = fedifyPlugin;
@@ -0,0 +1,21 @@
1
+ import { Federation, FederationFetchOptions } from "@fedify/fedify";
2
+ import { FastifyPluginAsync, FastifyPluginOptions, FastifyRequest } from "fastify";
3
+
4
+ //#region src/index.d.ts
5
+
6
+ type ErrorHandlers = Omit<FederationFetchOptions<unknown>, "contextData">;
7
+ /**
8
+ * A factory function that creates context data for the Federation instance.
9
+ */
10
+ type ContextDataFactory<TContextData> = (request: FastifyRequest) => TContextData | Promise<TContextData>;
11
+ /**
12
+ * Plugin options for Fedify integration.
13
+ */
14
+ interface FedifyPluginOptions<TContextData> extends FastifyPluginOptions {
15
+ federation: Federation<TContextData>;
16
+ contextDataFactory?: ContextDataFactory<TContextData>;
17
+ errorHandlers?: Partial<ErrorHandlers>;
18
+ }
19
+ declare const fedifyPlugin: FastifyPluginAsync<FedifyPluginOptions<unknown>>;
20
+ //#endregion
21
+ export { ContextDataFactory, FedifyPluginOptions, fedifyPlugin as default, fedifyPlugin };
@@ -0,0 +1,21 @@
1
+ import { Federation, FederationFetchOptions } from "@fedify/fedify";
2
+ import { FastifyPluginAsync, FastifyPluginOptions, FastifyRequest } from "fastify";
3
+
4
+ //#region src/index.d.ts
5
+
6
+ type ErrorHandlers = Omit<FederationFetchOptions<unknown>, "contextData">;
7
+ /**
8
+ * A factory function that creates context data for the Federation instance.
9
+ */
10
+ type ContextDataFactory<TContextData> = (request: FastifyRequest) => TContextData | Promise<TContextData>;
11
+ /**
12
+ * Plugin options for Fedify integration.
13
+ */
14
+ interface FedifyPluginOptions<TContextData> extends FastifyPluginOptions {
15
+ federation: Federation<TContextData>;
16
+ contextDataFactory?: ContextDataFactory<TContextData>;
17
+ errorHandlers?: Partial<ErrorHandlers>;
18
+ }
19
+ declare const fedifyPlugin: FastifyPluginAsync<FedifyPluginOptions<unknown>>;
20
+ //#endregion
21
+ export { ContextDataFactory, FedifyPluginOptions, fedifyPlugin as default, fedifyPlugin };
package/dist/index.js ADDED
@@ -0,0 +1,82 @@
1
+ import fp from "fastify-plugin";
2
+ import { Readable } from "node:stream";
3
+
4
+ //#region src/index.ts
5
+ /**
6
+ * Fastify plugin that integrates with a Federation instance.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { createFederation, MemoryKvStore, Person } from "@fedify/fedify";
11
+ * import fedifyPlugin from "@fedify/fastify";
12
+ * import Fastify from "fastify";
13
+ *
14
+ * const fastify = Fastify();
15
+ *
16
+ * const federation = createFederation({ kv: new MemoryKvStore() });
17
+ *
18
+ * // Add federation routes
19
+ * federation.setActorDispatcher("/users/{identifier}", async (ctx, identifier) => {
20
+ * return new Person({
21
+ * id: ctx.getActorUri(identifier),
22
+ * preferredUsername: identifier,
23
+ * });
24
+ * });
25
+ *
26
+ * // Register the plugin
27
+ * await fastify.register(fedifyPlugin, {
28
+ * federation,
29
+ * contextDataFactory: () => undefined,
30
+ * errorHandlers: { onNotFound: () => new Response("Not Found", { status: 404 }) },
31
+ * });
32
+ * ```
33
+ */
34
+ const fedifyPluginCore = (fastify, options) => {
35
+ const { federation, contextDataFactory = () => void 0, errorHandlers } = options;
36
+ fastify.addHook("onRequest", async (request, reply) => {
37
+ const webRequest = toWebRequest(request);
38
+ const contextData = await contextDataFactory(request);
39
+ const response = await federation.fetch(webRequest, {
40
+ contextData,
41
+ onNotAcceptable: () => defaultNotAcceptableResponse,
42
+ onNotFound: () => dummyNotFoundResponse,
43
+ ...errorHandlers
44
+ });
45
+ if (response === dummyNotFoundResponse) return;
46
+ await reply.send(response);
47
+ });
48
+ return Promise.resolve();
49
+ };
50
+ const fedifyPlugin = fp(fedifyPluginCore, {
51
+ name: "fedify-plugin",
52
+ fastify: "5.x"
53
+ });
54
+ const dummyNotFoundResponse = new Response("", { status: 404 });
55
+ const defaultNotAcceptableResponse = new Response("Not Acceptable", {
56
+ status: 406,
57
+ headers: {
58
+ "Content-Type": "text/plain",
59
+ Vary: "Accept"
60
+ }
61
+ });
62
+ /**
63
+ * Convert Fastify request to Web API Request.
64
+ */
65
+ function toWebRequest(fastifyReq) {
66
+ const protocol = fastifyReq.protocol;
67
+ const host = fastifyReq.headers.host ?? fastifyReq.hostname;
68
+ const url = `${protocol}://${host}${fastifyReq.url}`;
69
+ const headers = new Headers();
70
+ for (const [key, value] of Object.entries(fastifyReq.raw.headers)) if (Array.isArray(value)) for (const v of value) headers.append(key, v);
71
+ else if (value !== void 0) headers.set(key, String(value));
72
+ const body = fastifyReq.method === "GET" || fastifyReq.method === "HEAD" ? void 0 : fastifyReq.body !== void 0 ? typeof fastifyReq.body === "string" ? fastifyReq.body : JSON.stringify(fastifyReq.body) : Readable.toWeb(fastifyReq.raw);
73
+ return new Request(url, {
74
+ method: fastifyReq.method,
75
+ headers,
76
+ body
77
+ });
78
+ }
79
+ var src_default = fedifyPlugin;
80
+
81
+ //#endregion
82
+ export { src_default as default, fedifyPlugin };
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "@fedify/fastify",
3
+ "version": "1.9.0",
4
+ "description": "Integrate Fedify with Fastify",
5
+ "keywords": [
6
+ "Fedify",
7
+ "Fastify"
8
+ ],
9
+ "license": "MIT",
10
+ "author": "An Nyeong <me@annyeong.me>",
11
+ "homepage": "https://fedify.dev/",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/fedify-dev/fedify.git",
15
+ "directory": "packages/fastify"
16
+ },
17
+ "bugs": {
18
+ "url": "https://github.com/fedify-dev/fedify/issues"
19
+ },
20
+ "funding": [
21
+ "https://opencollective.com/fedify",
22
+ "https://github.com/sponsors/dahlia"
23
+ ],
24
+ "type": "module",
25
+ "module": "./dist/index.js",
26
+ "types": "./dist/index.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "import": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.js",
32
+ "default": "./dist/index.js"
33
+ },
34
+ "require": {
35
+ "types": "./dist/index.d.cts",
36
+ "import": "./dist/index.cjs",
37
+ "default": "./dist/index.cjs"
38
+ }
39
+ },
40
+ "./package.json": "./package.json"
41
+ },
42
+ "files": [
43
+ "dist/",
44
+ "package.json"
45
+ ],
46
+ "dependencies": {
47
+ "fastify-plugin": "^5.0.1"
48
+ },
49
+ "peerDependencies": {
50
+ "fastify": "^5.2.0",
51
+ "@fedify/fedify": "1.9.0"
52
+ },
53
+ "devDependencies": {
54
+ "@types/node": "^22.16.0",
55
+ "tsdown": "^0.12.9",
56
+ "typescript": "^5.9.2"
57
+ },
58
+ "scripts": {
59
+ "build": "tsdown",
60
+ "prepublish": "tsdown",
61
+ "test": "tsdown && node --experimental-transform-types --test"
62
+ }
63
+ }