@mastrojs/mastro 0.0.0-stage → 0.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.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +60 -2
  3. package/dist/cli.d.ts +3 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +92 -0
  6. package/dist/core/fs.d.ts +67 -0
  7. package/dist/core/fs.d.ts.map +1 -0
  8. package/dist/core/fs.js +114 -0
  9. package/dist/core/fsHelpers.d.ts +18 -0
  10. package/dist/core/fsHelpers.d.ts.map +1 -0
  11. package/dist/core/fsHelpers.js +17 -0
  12. package/dist/core/html.d.ts +67 -0
  13. package/dist/core/html.d.ts.map +1 -0
  14. package/dist/core/html.js +201 -0
  15. package/dist/core/responses.d.ts +98 -0
  16. package/dist/core/responses.d.ts.map +1 -0
  17. package/dist/core/responses.js +145 -0
  18. package/dist/core/routeHelpers.d.ts +12 -0
  19. package/dist/core/routeHelpers.d.ts.map +1 -0
  20. package/dist/core/routeHelpers.js +51 -0
  21. package/dist/generator.d.ts +16 -0
  22. package/dist/generator.d.ts.map +1 -0
  23. package/dist/generator.js +124 -0
  24. package/dist/index.d.ts +13 -0
  25. package/dist/index.d.ts.map +1 -0
  26. package/dist/index.js +10 -0
  27. package/dist/mastro.d.ts +58 -0
  28. package/dist/mastro.d.ts.map +1 -0
  29. package/dist/mastro.js +93 -0
  30. package/dist/middleware.d.ts +4 -0
  31. package/dist/middleware.d.ts.map +1 -0
  32. package/dist/middleware.js +21 -0
  33. package/dist/middlewares/fingerprintAssets.d.ts +3 -0
  34. package/dist/middlewares/fingerprintAssets.d.ts.map +1 -0
  35. package/dist/middlewares/fingerprintAssets.js +35 -0
  36. package/dist/middlewares/logger.d.ts +4 -0
  37. package/dist/middlewares/logger.d.ts.map +1 -0
  38. package/dist/middlewares/logger.js +41 -0
  39. package/dist/middlewares/staticFiles/mediaTypes.d.ts +6 -0
  40. package/dist/middlewares/staticFiles/mediaTypes.d.ts.map +1 -0
  41. package/dist/middlewares/staticFiles/mediaTypes.js +26 -0
  42. package/dist/middlewares/staticFiles/mediaTypes.json +910 -0
  43. package/dist/middlewares/staticFiles/staticFiles.d.ts +10 -0
  44. package/dist/middlewares/staticFiles/staticFiles.d.ts.map +1 -0
  45. package/dist/middlewares/staticFiles/staticFiles.js +119 -0
  46. package/dist/middlewares/tsToJs.d.ts +13 -0
  47. package/dist/middlewares/tsToJs.d.ts.map +1 -0
  48. package/dist/middlewares/tsToJs.js +49 -0
  49. package/dist/servers/fileRouter.d.ts +11 -0
  50. package/dist/servers/fileRouter.d.ts.map +1 -0
  51. package/dist/servers/fileRouter.js +74 -0
  52. package/dist/servers/fileRoutes.d.ts +2 -0
  53. package/dist/servers/fileRoutes.d.ts.map +1 -0
  54. package/dist/servers/fileRoutes.js +1 -0
  55. package/dist/servers/server.d.ts +22 -0
  56. package/dist/servers/server.d.ts.map +1 -0
  57. package/dist/servers/server.js +21 -0
  58. package/dist/types/mastro.d.ts +80 -0
  59. package/dist/types/middleware.d.ts +157 -0
  60. package/dist/types/standard-schema.d.ts +76 -0
  61. package/package.json +52 -3
  62. package/src/README.md +29 -0
  63. package/src/cli.ts +89 -0
  64. package/src/core/fs.ts +131 -0
  65. package/src/core/fsHelpers.ts +24 -0
  66. package/src/core/html.ts +226 -0
  67. package/src/core/responses.ts +175 -0
  68. package/src/core/routeHelpers.ts +60 -0
  69. package/src/generator.ts +139 -0
  70. package/src/index.ts +14 -0
  71. package/src/mastro.ts +116 -0
  72. package/src/middleware.ts +28 -0
  73. package/src/middlewares/fingerprintAssets.ts +37 -0
  74. package/src/middlewares/logger.ts +43 -0
  75. package/src/middlewares/staticFiles/mediaTypes.json +910 -0
  76. package/src/middlewares/staticFiles/mediaTypes.ts +28 -0
  77. package/src/middlewares/staticFiles/staticFiles.ts +136 -0
  78. package/src/middlewares/tsToJs.ts +43 -0
  79. package/src/servers/fileRouter.ts +83 -0
  80. package/src/servers/fileRoutes.ts +1 -0
  81. package/src/servers/server.ts +29 -0
  82. package/src/types/mastro.d.ts +80 -0
  83. package/src/types/middleware.d.ts +157 -0
  84. package/src/types/standard-schema.d.ts +76 -0
@@ -0,0 +1,28 @@
1
+ /*
2
+ Source of mediaTypes.json is https://github.com/denoland/std/blob/9145d20d86f897d21afc3cfda0f0219e79fd02c1/media_types/vendor/db.ts
3
+ Copyright 2018-2026 the Deno authors. MIT license.
4
+
5
+ It was transformed into its current shape with:
6
+
7
+ JSON.stringify(Object.keys(db).reduce((acc, type) => {
8
+ const { extensions, charset, source } = db[type];
9
+ if (extensions && (source === "iana" || !source)) {
10
+ const cs = charset || (type.startsWith("text/") ? "UTF-8" : null);
11
+ for (const ext of extensions) {
12
+ const current = acc[ext];
13
+ if (!current || current === "application/octet-stream" || current === "application/mp4") {
14
+ acc[ext] = type + (cs ? `; charset=${cs}` : "");
15
+ }
16
+ }
17
+ }
18
+ return acc;
19
+ }, {}))
20
+ */
21
+ import types from "./mediaTypes.json" with { type: "json" };
22
+
23
+ /**
24
+ * Returns the `Content-Type` header value for a given file extension. For example:
25
+ * `extensionToContentType("html") === "text/html; charset=UTF-8"`;
26
+ */
27
+ export const contentTypeFromExt = (ext: string): string | undefined =>
28
+ types[ext.toLowerCase() as keyof typeof types];
@@ -0,0 +1,136 @@
1
+ import { Buffer } from "node:buffer";
2
+ import type { Stats } from "node:fs";
3
+ import fs from "node:fs/promises";
4
+ import { extname } from "node:path";
5
+
6
+ import { findFiles } from "../../core/fs.ts";
7
+ import { urlPathToFilePath, type FilePath } from "../../core/fsHelpers.ts";
8
+ import { isDevServer } from "../../core/routeHelpers.ts";
9
+ import type { Context, Middleware } from "../../types/middleware.d.ts";
10
+ import { contentTypeFromExt } from "./mediaTypes.ts";
11
+
12
+ /**
13
+ * Serve static files in routes folder (excluding *.client.ts, *.server.ts and *.server.js files)
14
+ *
15
+ * In production, we also look for files in the `generated` folder, which take precedence.
16
+ */
17
+ export const staticFiles: Middleware = {
18
+ name: "staticFiles",
19
+ getStaticPaths: () =>
20
+ findFiles(["routes/**/*", "routes/**/.*/**/*"]).then((paths) =>
21
+ paths.filter((p) => !reserved(p)).map((p) => p.slice(6)),
22
+ ),
23
+ handler: async (req, ctx) => (await serveStaticFile(req, ctx)) || ctx.fetchNext(req),
24
+ };
25
+
26
+ const serveStaticFile = async (req: Request, ctx: Context): Promise<Response | undefined> => {
27
+ if (req.method === "GET" || req.method === "HEAD") {
28
+ const { pathname } = new URL(req.url);
29
+ const path = pathname.endsWith("/") ? pathname + "index.html" : pathname;
30
+ const tryPregen = generatedExists && ctx.mode === "server" && ctx.environment === "production";
31
+ const pregenerated = tryPregen ? await tryServeFile(req, "generated" + path, reserved) : null;
32
+ return pregenerated || (await tryServeFile(req, "routes" + path, reserved));
33
+ }
34
+ };
35
+
36
+ const generatedExists = (await fs.stat("generated", { throwIfNoEntry: false }))?.isDirectory();
37
+
38
+ export const tryServeFile = async (
39
+ req: Request,
40
+ path: string,
41
+ reserved?: (path: FilePath) => boolean,
42
+ ): Promise<Response | undefined> => {
43
+ let decodedPath: FilePath;
44
+ try {
45
+ decodedPath = urlPathToFilePath(path);
46
+ } catch {
47
+ return newResponse(400);
48
+ }
49
+ if (reserved?.(decodedPath)) return;
50
+
51
+ const res = await serveFile(req, decodedPath);
52
+
53
+ if (res.status === 404 || res.status === 405) return;
54
+ if (isDevServer(new URL(req.url))) res.headers.set("Cache-Control", "max-age=0");
55
+ return res;
56
+ };
57
+
58
+ /**
59
+ * Returns a `Response` from a file on the file system.
60
+ *
61
+ * Previously we did `import { serveFile } from "@std/http/file-server"`,
62
+ * but [@std:http](https://jsr.io/@std/http) doesn't run on Node.js.
63
+ * It also has a bunch of dependencies, so we use this vendored implementation everywhere.
64
+ *
65
+ * lightly adapted from:
66
+ * https://github.com/denoland/std/blob/2258bf2628a97a03dece8d0235d910bfaf1f501d/http/file_server.ts
67
+ * (MIT License)
68
+ */
69
+ const serveFile = async (req: Request, filePath: FilePath): Promise<Response> => {
70
+ if (req.method !== "GET" && req.method !== "HEAD") return newResponse(405);
71
+
72
+ let fileInfo;
73
+ try {
74
+ fileInfo = await fs.stat(filePath);
75
+ } catch (error: any) {
76
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return newResponse(404);
77
+ throw error;
78
+ }
79
+
80
+ if (fileInfo.isDirectory()) return newResponse(404);
81
+
82
+ const headers = new Headers();
83
+ if (fileInfo.mtime) headers.set("Last-Modified", fileInfo.mtime.toUTCString());
84
+
85
+ const etag = fileInfo.mtime ? await eTag(fileInfo) : undefined;
86
+ if (etag) headers.set("ETag", etag);
87
+
88
+ const fileSize = fileInfo.size;
89
+ if (etag || fileInfo.mtime) {
90
+ // If a `if-none-match` header is present and the value matches the tag or
91
+ // if a `if-modified-since` header is present and the value is bigger than
92
+ // the access timestamp value, then return 304
93
+ const ifNoneMatchValue = req.headers.get("If-None-Match");
94
+ const ifModifiedSinceValue = req.headers.get("If-Modified-Since");
95
+ if (
96
+ !ifNoneMatch(ifNoneMatchValue, etag) ||
97
+ (ifNoneMatchValue === null &&
98
+ fileInfo.mtime &&
99
+ ifModifiedSinceValue &&
100
+ fileInfo.mtime.getTime() < new Date(ifModifiedSinceValue).getTime() + 1000)
101
+ ) {
102
+ return new Response(null, { status: 304, headers });
103
+ }
104
+ }
105
+
106
+ const contentTypeValue = contentTypeFromExt(extname(filePath).slice(1));
107
+ if (contentTypeValue) headers.set("Content-Type", contentTypeValue);
108
+
109
+ headers.set("Content-Length", `${fileSize}`);
110
+ if (req.method === "HEAD") return new Response(null, { status: 200, headers });
111
+
112
+ const file = await fs.open(filePath, "r");
113
+ const stream = file.readableWebStream({ autoClose: true }) as ReadableStream;
114
+ return new Response(stream, { status: 200, headers });
115
+ };
116
+
117
+ const reserved = (p: string) => /\.(client\.ts|server\.ts|server\.js)$/i.test(p);
118
+
119
+ const newResponse = (status: number) => new Response(`HTTP ${status}`, { status });
120
+
121
+ const encoder = new TextEncoder();
122
+ const eTag = async (fileInfo: Stats): Promise<string> => {
123
+ const ab = await crypto.subtle.digest("SHA-256", encoder.encode(fileInfo.mtime.toJSON()));
124
+ const hash = Buffer.from(ab).toString("base64").substring(0, 27);
125
+ return `"${fileInfo.size.toString(16)}-${hash}"`;
126
+ };
127
+
128
+ const STAR_REGEXP = /^\s*\*\s*$/;
129
+ const COMMA_REGEXP = /\s*,\s*/;
130
+ const ifNoneMatch = (value: string | null, etag: string | undefined): boolean => {
131
+ if (!value || !etag) return true;
132
+ if (STAR_REGEXP.test(value)) return false;
133
+ etag = etag.startsWith("W/") ? etag.slice(2) : etag;
134
+ const tags = value.split(COMMA_REGEXP).map((tag) => (tag.startsWith("W/") ? tag.slice(2) : tag));
135
+ return !tags.includes(etag);
136
+ };
@@ -0,0 +1,43 @@
1
+ import { findFiles } from "../core/fs.ts";
2
+ import type { Middleware } from "../types/middleware.d.ts";
3
+ import { tryServeFile } from "./staticFiles/staticFiles.ts";
4
+
5
+ /**
6
+ * Middleware that converts `*.client.ts` files to `*.client.js` by running it through
7
+ * `stripTypeScriptTypes` (or `ts-blank-space` on Bun), and then
8
+ * changing imports ending with `.ts` to end in `.js`.
9
+ *
10
+ * Since browsers don't understand TypeScript, we run this function on `.client.ts` files,
11
+ * to convert them to `.client.js` files. Extension needs to change because
12
+ * static file servers don't serve `.ts` files with `content-type: text/javascript`.
13
+ */
14
+ export const tsToJs: Middleware = {
15
+ name: "tsToJs",
16
+ getStaticPaths: () =>
17
+ findFiles("routes/**/*.client.ts").then((ps) => ps.map((p) => p.slice(6, -3) + ".js")),
18
+ handler: async (req, ctx) => {
19
+ if (ctx.mode === "generator" || ctx.environment === "development") {
20
+ const { pathname } = new URL(req.url);
21
+ if (pathname.endsWith(".client.js")) {
22
+ const res = await tryServeFile(req, "routes" + pathname.slice(0, -3) + ".ts");
23
+ if (res) {
24
+ if (!res.ok) return res; // 304 Not Modified, etc. get passed through
25
+ const { headers } = res;
26
+ headers.set("Content-Type", "text/javascript; charset=utf-8");
27
+ headers.set("Accept-Ranges", "none");
28
+ headers.delete("Content-Length");
29
+ if (res.body === null) return res;
30
+ const body = stripTypeScriptTypes(await res.text()).replace(importRegex, "$1.js$2;");
31
+ return new Response(body, { headers });
32
+ }
33
+ }
34
+ }
35
+ return ctx.fetchNext(req);
36
+ },
37
+ };
38
+
39
+ // @ts-expect-error no type definitions for Bun
40
+ const { stripTypeScriptTypes } = typeof Bun === "object"
41
+ ? await import("npm:ts-blank-space" as any).then((m) => ({ stripTypeScriptTypes: m.default }))
42
+ : await import("node:module");
43
+ export const importRegex: RegExp = /^(\s*import\s+[^"'(]*["'][^"']*)\.ts(["']);?$/gm;
@@ -0,0 +1,83 @@
1
+ import { findFiles } from "../core/fs.ts";
2
+ import { urlPathToFilePath, type FilePath } from "../core/fsHelpers.ts";
3
+ import { httpMethods } from "../mastro.ts";
4
+ import type { Route } from "../types/mastro.d.ts";
5
+
6
+ interface FileRoute {
7
+ name: string;
8
+ pathname: string;
9
+ }
10
+ type RouteLoader = (fileName: string) => Promise<Record<string, unknown>>;
11
+
12
+ export const loadFileRoutes = async (): Promise<Route[]> => {
13
+ const { pathToFileURL } = await import("node:url");
14
+ const loader = (name: string) => import(pathToFileURL(process.cwd() + "/" + name).toString());
15
+ return loadRoutes(await findRoutes(), loader);
16
+ };
17
+
18
+ export const findRoutes = async (): Promise<FileRoute[]> => {
19
+ const files = await findFiles(["routes/**/*.server.{ts,js}", "routes/**/.*/**/*.server.{ts,js}"]);
20
+ if (files.length === 0) console.warn(noRt);
21
+ return files.map(urlPathToFilePath).sort(cmp).map((n) => ({ name: n, pathname: toPattern(n) }));
22
+ };
23
+ const noRt = "\n\nWARNING: No route files found!\n see https://mastrojs.github.io/docs/routing/\n";
24
+
25
+ export const loadRoutes = async (routes: FileRoute[], loader: RouteLoader): Promise<Route[]> => {
26
+ const modules = await Promise.all(
27
+ routes.map(async ({ name, pathname }) => ({
28
+ module: await loader(name),
29
+ name,
30
+ pattern: new URLPattern({ pathname }),
31
+ })),
32
+ );
33
+
34
+ return modules.flatMap(({ module, name, pattern }) =>
35
+ (typeof module.ALL === "function" ? (["ALL"] as const) : httpMethods).flatMap((method) => {
36
+ const handler = module[method];
37
+ return typeof handler === "function"
38
+ ? ({
39
+ name,
40
+ handler,
41
+ method: method === "ALL" ? "all" : method,
42
+ pattern,
43
+ getStaticPaths: module.getStaticPaths,
44
+ pregenerate: module.pregenerate,
45
+ } as Route)
46
+ : [];
47
+ }),
48
+ );
49
+ };
50
+
51
+ /**
52
+ * Compare routes according to reverse alphabetical order, with the exception that `[` goes last.
53
+ * This guarantees us at least that:
54
+ * - dynamic segments lose out over fixed segments at every depth
55
+ * - longer paths win over their prefixes.
56
+ */
57
+ const cmp = (a: string, b: string) => (a.replaceAll("[", "\0") < b.replaceAll("[", "\0") ? 1 : -1);
58
+
59
+ const toPattern = (filePath: FilePath) => {
60
+ const pathParts = filePath.split("/").slice(1);
61
+ const parts = pathParts.map((part, i) => {
62
+ const segment = i === pathParts.length - 1 ? part.slice(0, -10) : part; // slice off .server.ts
63
+ const [, param, suffix] = segment.match(paramRegex) || [];
64
+ if (param) {
65
+ const pattern = param.startsWith("...") ? `:${param.slice(3)}(.*)?` : `:${param}`;
66
+ return `${pattern}{${escapePattern(suffix || "")}}`;
67
+ } else if (indexRegex.test(part)) {
68
+ return "";
69
+ }
70
+ const folder = pathParts[i - 1];
71
+ if (folder && (part === `(${folder}).server.ts` || part === `(${folder}).server.js`)) {
72
+ return "";
73
+ }
74
+ return escapePattern(segment);
75
+ });
76
+ return "/" + parts.join("/");
77
+ };
78
+
79
+ const indexRegex = /^index(\.html)?\.server\.(ts|js)$/;
80
+ const paramRegex = /^\[([a-zA-Z0-9\.]+)\](.*)$/;
81
+
82
+ /** Encode literal path text and escape characters with special meaning in URLPattern */
83
+ const escapePattern = (part: string) => encodeURIComponent(part).replace(/[()*]/g, "\\$&");
@@ -0,0 +1 @@
1
+ export { loadRoutes } from "./fileRouter.ts";
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Helpers to create Mastro apps with middleware suited for a Node.js server.
3
+ * @module
4
+ */
5
+
6
+ import { Mastro } from "../mastro.ts";
7
+ import { fingerprintAssets } from "../middlewares/fingerprintAssets.ts";
8
+ import { logger } from "../middlewares/logger.ts";
9
+ import { staticFiles } from "../middlewares/staticFiles/staticFiles.ts";
10
+ import { tsToJs } from "../middlewares/tsToJs.ts";
11
+ import type { Route } from "../types/mastro.js";
12
+ import type { Middleware } from "../types/middleware.d.ts";
13
+ import { loadFileRoutes } from "./fileRouter.ts";
14
+
15
+ export { logger, fingerprintAssets, tsToJs, staticFiles };
16
+ export const middlewares: Middleware[] = [logger, fingerprintAssets, tsToJs, staticFiles];
17
+
18
+ /**
19
+ * Creates an app with the programmatic router and default middleware.
20
+ */
21
+ export const createApp = <E extends unknown[]>(): Mastro<E> =>
22
+ new Mastro<E>().use(logger).use(fingerprintAssets).use(tsToJs).use(staticFiles);
23
+
24
+ /**
25
+ * Creates an app with the file-based router and default middleware.
26
+ */
27
+ export const createFileRouterApp = <E extends unknown[]>(routes?: Promise<Route[]>): Mastro<E> =>
28
+ new Mastro<E>({ routes: routes || loadFileRoutes() })
29
+ .use(logger).use(fingerprintAssets).use(tsToJs).use(staticFiles);
@@ -0,0 +1,80 @@
1
+ import type { HttpMethod } from "../mastro.ts";
2
+ import type { Context, MiddlewareContext } from "./middleware.d.ts";
3
+
4
+ /** A route pathname starts with a slash. */
5
+ export type Pathname = `/${string}`;
6
+
7
+ /**
8
+ * A route or middleware handler. It receives a standard Request
9
+ * (and a {@link Context} or {@link MiddlewareContext} as a second argument).
10
+ *
11
+ * ```ts
12
+ * import { type Handler } from "@mastrojs/mastro";
13
+ *
14
+ * export const GET: Handler = (req, ctx) =>
15
+ * new Response(`Hello ${ctx.params.name ?? "world"}`);
16
+ * ```
17
+ */
18
+ export type Handler<C = Context> = (req: Request, ctx: C) => Promise<Response> | Response;
19
+
20
+ /**
21
+ * A Mastro Route
22
+ */
23
+ export interface Route<C = Context> {
24
+ /**
25
+ * Name of the route for error messages etc.
26
+ * For file-based routes the `filePath`, e.g. `routes/index.server.ts`
27
+ */
28
+ name: string;
29
+ /** Fetch handler */
30
+ handler: Handler<C>;
31
+ /** HTTP method, or "all" if the route should match any HTTP method. */
32
+ method: "all" | HttpMethod;
33
+ /** `URLPattern` with `pathname` set */
34
+ pattern: URLPattern;
35
+ /** Called by the static site generator. */
36
+ getStaticPaths?: () => Promise<string[]> | string[];
37
+ /** Before starting your server, you can run `mastro generate --only-pregenerate` to
38
+ * only pregenerate routes which have this field set. */
39
+ pregenerate?: true;
40
+ }
41
+
42
+ export type RouteHandler<E, L, P extends Pathname> =
43
+ | Handler<Context<E, L, RouteParams<P>>>
44
+ | {
45
+ handler: Handler<Context<E, L, RouteParams<P>>>;
46
+ getStaticPaths?: () => Promise<string[]> | string[];
47
+ pregenerate?: true;
48
+ };
49
+
50
+ /** Expand merged locals into an object shape for editor hovers. */
51
+ export type Simplify<T> = { [Key in keyof T]: T[Key] } & {};
52
+
53
+ type ParamNames<P> = string extends P
54
+ ? string
55
+ : P extends `${string}${"(" | "{" | "\\"}${string}`
56
+ ? string
57
+ : P extends `${infer Segment}/${infer Rest}`
58
+ ? ParamNames<Segment> | ParamNames<Rest>
59
+ : P extends `${string}:${infer Name}`
60
+ ? Name extends `${string}${":" | "-" | "@"}${string}`
61
+ ? string
62
+ : Name extends `${infer Param}.${string}`
63
+ ? Param
64
+ : Name
65
+ : P extends `${string}*${string}`
66
+ ? string
67
+ : never;
68
+
69
+ /** e.g. `RouteParams<"/users/:userId">` is the type `{ userId: string }`.
70
+ * We don't cover full URLPattern syntax, but do support `.suffix`, `?`, `+` and `*` modifiers.
71
+ * `string` signals that we need the Record fallback.
72
+ */
73
+ export type RouteParams<P extends Pathname> =
74
+ string extends ParamNames<P>
75
+ ? Record<string, string | undefined>
76
+ : {
77
+ [
78
+ K in ParamNames<P> as K extends `${infer Name}${"?" | "+" | "*"}` ? Name : K
79
+ ]: K extends `${string}${"?" | "*"}` ? string | undefined : string;
80
+ };
@@ -0,0 +1,157 @@
1
+ import type { Handler } from "./mastro.d.ts";
2
+
3
+ /**
4
+ * Middleware allows you to intercept requests before they hit your routes, and modify responses
5
+ * returned by downstream handlers.
6
+ *
7
+ * Often, calling a shared helper function (like [jsonRoute](https://github.com/mastrojs/api))
8
+ * in your routes is simpler. However, middleware can be useful if you have lots of routes,
9
+ * or want to ensure you don't forget calling the helper function accidentally (e.g. for auth).
10
+ *
11
+ * ## Execution order
12
+ *
13
+ * Multiple middlewares are executed in registration order. When a `Request` comes in, it first
14
+ * hits the first middleware, which calls the next middleware in the chain, and so forth
15
+ * – each middleware forming a layer in an onion, with your route handlers at the center.
16
+ * On the way out, the `Response` is handed back, layer for layer, up the whole chain, with the
17
+ * middlewares continuing their execution, in reverse order than on the way in.
18
+ *
19
+ * This is conceptually similar to middleware in other JS frameworks like Express or Hono.
20
+ * However, Mastro's middleware API is explicitly modelled after a network proxy. Thinking
21
+ * of your middleware as a network proxy may be easier than the onion call chain described above.
22
+ *
23
+ * (If you use the `createApp` or `createFileRouterApp` factory from "@mastrojs/mastro/server",
24
+ * be aware that the middleware they set will run before the ones you add later.
25
+ * If that's a problem, use `new Mastro()` directly, import the default middlewares you need from
26
+ * "@mastrojs/mastro/server", and add them in the desired order.)
27
+ *
28
+ * The simplest middleware, which doesn't do anything, is:
29
+ *
30
+ * ```ts
31
+ * const identityMiddleware: Middleware = (req, ctx) =>
32
+ * ctx.fetchNext(req);
33
+ * ```
34
+ *
35
+ * Or it can return early:
36
+
37
+ * ```ts
38
+ * const redirectMiddleware: Middleware = (req, ctx) => {
39
+ * const url = new URL(req.url);
40
+ * if (url.pathname === "/stories/") {
41
+ * return Response.redirect(new URL("/blog/", url));
42
+ * }
43
+ * return ctx.fetchNext(req);
44
+ * }
45
+ * ```
46
+ *
47
+ * ## Error handling
48
+ *
49
+ * You don't need to wrap `ctx.fetchNext()` in `try...catch` – Mastro already does that for you
50
+ * and returns a 500 Response with an `error` field that contains whatever value was thrown.
51
+ * Be sure to check for `res.ok`, if your middleware should behave differently for 4xx or 5xx.
52
+ *
53
+ * ## Server and static site generation
54
+ *
55
+ * Middlewares are run on every route and on every request.
56
+ * When doing static site generation, they are run when you generate the site. In that case,
57
+ * returning 404 skips a page. Use the `Content-Disposition` HTTP header to override the output
58
+ * filename (don't include the directory).
59
+ *
60
+ * When running a server, a middleware can be just a {@link MiddlewareHandler} function. For
61
+ * static site generation, if you also need to provide `getStaticPaths` or `afterGenerate`,
62
+ * use the object form (see [tsToJs](../middlewares/tsToJs.ts) for an example).
63
+ *
64
+ * ## Locals
65
+ *
66
+ * Middleware can set or update locals, the types of which need to be declared with the `L` generic:
67
+ *
68
+ * ```ts
69
+ * const authMiddleware: Middleware<{ user: User }> = async (req, ctx) => {
70
+ * const user = await loadUser(req.headers);
71
+ * return ctx.fetchNext(req, { user });
72
+ * }
73
+ *
74
+ * const app = new Mastro()
75
+ * .use(authMiddleware)
76
+ * .get("/", (_req, ctx) => new Response(ctx.locals.user.name));
77
+ * ```
78
+ *
79
+ * @template L Locals this middleware sets or updates, defaults to `{}`.
80
+ * @template C Incoming base context, defaults to a Context with no declared locals.
81
+ */
82
+ export type Middleware<L = {}, C extends { extras: unknown } = Context<unknown[], {}>> =
83
+ | MiddlewareHandler<L, C>
84
+ | {
85
+ /** Name by which users can identify the middleware. */
86
+ name: string;
87
+ handler: MiddlewareHandler<L, C>;
88
+ /** Called by the static site generator. */
89
+ getStaticPaths?: (ctx: GeneratorCtxSimple<C>) => Promise<string[]> | string[];
90
+ /** Called by the static site generator before generation starts. */
91
+ beforeGenerate?: (ctx: GeneratorCtxSimple<C>) => void;
92
+ /** Called by the static site generator after generation completes successfully. */
93
+ afterGenerate?: (ctx: GeneratorCtxSimple<C>) => void;
94
+ };
95
+
96
+ export type MiddlewareContext<C = Context, L = {}> = C & { fetchNext: FetchNext<L> };
97
+
98
+ type MiddlewareHandler<L = {}, C = Context> = Handler<MiddlewareContext<C, L>>;
99
+
100
+ interface BaseContext<E, L, P> {
101
+ /** array of extra arguments to the root fetch handler that Mastro receives from the platform */
102
+ readonly extras: Readonly<E>;
103
+ /** ctx.locals is an object collecting variables set by middlewares */
104
+ readonly locals: Readonly<L>;
105
+ /** e.g. on the "/users/:userId" route, ctx.params.userId will be a string */
106
+ readonly params: Readonly<P>;
107
+ }
108
+
109
+ /** Context that both middleware and routes receive as the second argument. */
110
+ export type Context<
111
+ E = unknown[],
112
+ L = Record<string, unknown>,
113
+ P = Record<string, string | undefined>,
114
+ > = GeneratorContext<E, L, P> | ServerContext<E, L, P>;
115
+
116
+ export interface GeneratorContext<E, L, P> extends BaseContext<E, L, P> {
117
+ mode: "generator";
118
+ /** Base URL for synthetic requests. Defaults to http://127.0.0.1. */
119
+ baseUrl?: string;
120
+ /** Only pregenerate marked routes, while still copying static files. */
121
+ onlyPregenerate: boolean;
122
+ /** Output directory. Defaults to generated. */
123
+ outFolder?: string;
124
+ }
125
+
126
+ /** Generator lifecycle context, using the base context's extras without request-specific state. */
127
+ export type GeneratorCtxSimple<C extends { extras: unknown } = Context> = Omit<
128
+ GeneratorContext<C["extras"], {}, {}>,
129
+ "locals" | "params"
130
+ >;
131
+
132
+ export interface ServerContext<E, L, P> extends BaseContext<E, L, P> {
133
+ mode: "server";
134
+ environment: "development" | "production";
135
+ }
136
+
137
+ /**
138
+ * Allow updates to a local only when the output variant preserves the existing type.
139
+ * Without this restriction, it's hard to ensure the correct locals types in a middleware chain.
140
+ */
141
+ export type CompatibleLocals<L, SetL> = (
142
+ SetL extends Pick<L, keyof SetL & keyof L> ? true : false
143
+ ) extends true
144
+ ? unknown
145
+ : never;
146
+
147
+ /**
148
+ * Make sure `ctx.fetchNext(req, locals)` adheres to the generic `L` that the middleware declared.
149
+ */
150
+ type FetchNext<in out L = {}> = <Arg extends L & object>(
151
+ req: Request,
152
+ ...args: {} extends L ? [locals?: NoExtraKeys<L, Arg>] : [locals: NoExtraKeys<L, Arg>]
153
+ ) => Promise<Response> | Response;
154
+
155
+ /* Reject Arg object if it tries to set more keys than the middleware declared in L. */
156
+ type NoExtraKeys<L, Arg> = Arg &
157
+ Record<Exclude<Arg extends unknown ? keyof Arg : never, keyof L>, never>;
@@ -0,0 +1,76 @@
1
+ /** The Standard Schema interface. */
2
+ export interface StandardSchemaV1<Input = unknown, Output = Input> {
3
+ /** The Standard Schema properties. */
4
+ readonly "~standard": StandardSchemaV1.Props<Input, Output>;
5
+ }
6
+
7
+ export declare namespace StandardSchemaV1 {
8
+ /** The Standard Schema properties interface. */
9
+ export interface Props<Input = unknown, Output = Input> {
10
+ /** The version number of the standard. */
11
+ readonly version: 1;
12
+ /** The vendor name of the schema library. */
13
+ readonly vendor: string;
14
+ /** Validates unknown input values. */
15
+ readonly validate: (
16
+ value: unknown,
17
+ options?: StandardSchemaV1.Options | undefined,
18
+ ) => Result<Output> | Promise<Result<Output>>;
19
+ /** Inferred types associated with the schema. */
20
+ readonly types?: Types<Input, Output> | undefined;
21
+ }
22
+
23
+ /** The result interface of the validate function. */
24
+ export type Result<Output> = SuccessResult<Output> | FailureResult;
25
+
26
+ /** The result interface if validation succeeds. */
27
+ export interface SuccessResult<Output> {
28
+ /** The typed output value. */
29
+ readonly value: Output;
30
+ /** A falsy value for `issues` indicates success. */
31
+ readonly issues?: undefined;
32
+ }
33
+
34
+ export interface Options {
35
+ /** Explicit support for additional vendor-specific parameters, if needed. */
36
+ readonly libraryOptions?: Record<string, unknown> | undefined;
37
+ }
38
+
39
+ /** The result interface if validation fails. */
40
+ export interface FailureResult {
41
+ /** The issues of failed validation. */
42
+ readonly issues: ReadonlyArray<Issue>;
43
+ }
44
+
45
+ /** The issue interface of the failure output. */
46
+ export interface Issue {
47
+ /** The error message of the issue. */
48
+ readonly message: string;
49
+ /** The path of the issue, if any. */
50
+ readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
51
+ }
52
+
53
+ /** The path segment interface of the issue. */
54
+ export interface PathSegment {
55
+ /** The key representing a path segment. */
56
+ readonly key: PropertyKey;
57
+ }
58
+
59
+ /** The Standard Schema types interface. */
60
+ export interface Types<Input = unknown, Output = Input> {
61
+ /** The input type of the schema. */
62
+ readonly input: Input;
63
+ /** The output type of the schema. */
64
+ readonly output: Output;
65
+ }
66
+
67
+ /** Infers the input type of a Standard Schema. */
68
+ export type InferInput<Schema extends StandardSchemaV1> = NonNullable<
69
+ Schema["~standard"]["types"]
70
+ >["input"];
71
+
72
+ /** Infers the output type of a Standard Schema. */
73
+ export type InferOutput<Schema extends StandardSchemaV1> = NonNullable<
74
+ Schema["~standard"]["types"]
75
+ >["output"];
76
+ }