|
| 1 | +import type { Middleware } from "../core/server.ts"; |
| 2 | + |
| 3 | +export interface Data { |
| 4 | + /** |
| 5 | + * User domain. |
| 6 | + * @default |
| 7 | + * ```ts |
| 8 | + * new URL(req.url).host |
| 9 | + * ``` |
| 10 | + * @example |
| 11 | + * ```ts |
| 12 | + * site.options.location.host |
| 13 | + * ``` |
| 14 | + */ |
| 15 | + host?: URL["host"]; |
| 16 | +} |
| 17 | +export interface Options extends Data { |
| 18 | + /** |
| 19 | + * Rewrite URL function. |
| 20 | + * @param url req.url |
| 21 | + * @returns Rewritten URLs or empty |
| 22 | + */ |
| 23 | + rewriteUrl: (url: URL, data: Data) => Promise<URL> | URL | undefined | void; |
| 24 | + /** |
| 25 | + * User domain. |
| 26 | + * @default |
| 27 | + * ```ts |
| 28 | + * new URL(req.url).host |
| 29 | + * ``` |
| 30 | + * @example |
| 31 | + * ```ts |
| 32 | + * site.options.location.host |
| 33 | + * ``` |
| 34 | + */ |
| 35 | + host?: URL["host"]; |
| 36 | +} |
| 37 | + |
| 38 | +export const hatsu = |
| 39 | + (instance: URL["host"]): Options["rewriteUrl"] => (url, data) => { |
| 40 | + const { pathname } = url; |
| 41 | + const host = data.host ?? url.host; |
| 42 | + if (url.pathname === "/") { |
| 43 | + return new URL(`https://${instance}/users/${host}`); |
| 44 | + } else { |
| 45 | + return new URL( |
| 46 | + `https://${host}${pathname}`, |
| 47 | + `https://${instance}/posts/`, |
| 48 | + ); |
| 49 | + } |
| 50 | + }; |
| 51 | + |
| 52 | +export const bridgyFed = |
| 53 | + (instance: URL["host"] = "fed.brid.gy"): Options["rewriteUrl"] => |
| 54 | + (url, data) => { |
| 55 | + const { pathname } = url; |
| 56 | + const host = data.host ?? url.host; |
| 57 | + if (pathname === "/") return new URL(`https://${instance}/${host}`); |
| 58 | + else return new URL(`https://${host}${pathname}`, `https://${instance}/r/`); |
| 59 | + }; |
| 60 | + |
| 61 | +export default (options: Options): Middleware => async (req, next) => { |
| 62 | + const accept = req.headers.get("accept"); |
| 63 | + if ( |
| 64 | + accept && [ |
| 65 | + "application/activity+json", |
| 66 | + 'application/ld+json;profile="http://www.w3.org/ns/activitystreams"', |
| 67 | + 'application/ld+json; profile="http://www.w3.org/ns/activitystreams"', |
| 68 | + ].some((type) => (accept.includes(type))) |
| 69 | + ) { |
| 70 | + const dest = await options.rewriteUrl(new URL(req.url), { |
| 71 | + host: options.host, |
| 72 | + }); |
| 73 | + if (dest) return Response.redirect(dest); |
| 74 | + } |
| 75 | + |
| 76 | + return await next(req); |
| 77 | +}; |
0 commit comments