API 路由

本页内容

插件可以为管理 UI 和外部集成暴露 API 路由。路由挂载在 /_emdash/api/plugins/<slug>/<route-name> 下(<slug>emdash-plugin.jsonc 中插件的 slug 字段 — 运行时通过 ctx.plugin.id 暴露),并在与钩子接收到的相同 PluginContext 的沙盒运行时内执行。

本页面涵盖沙盒插件。原生插件的 API 表面相同;唯一的区别是处理器签名 — 详见原生插件中的说明。

定义路由

src/plugin.ts 的默认导出中声明路由:

import type { SandboxedPlugin } from "emdash/plugin";
import { z } from "astro/zod";

export default {
	routes: {
		status: {
			handler: async (_routeCtx, ctx) => {
				return { ok: true, plugin: ctx.plugin.id };
			},
		},

		submissions: {
			input: z.object({
				formId: z.string().optional(),
				limit: z.number().default(50),
				cursor: z.string().optional(),
			}),
			handler: async (routeCtx, ctx) => {
				const { formId, limit, cursor } = routeCtx.input;

				const result = await ctx.storage.submissions.query({
					where: formId ? { formId } : undefined,
					orderBy: { createdAt: "desc" },
					limit,
					cursor,
				});

				return result;
			},
		},
	},
} satisfies SandboxedPlugin;

satisfies SandboxedPlugin 推断 routeCtxctx — 无需参数注解。沙盒路由处理器接受两个参数(routeCtx, ctx)

  • routeCtx 携带请求相关数据:{ input, request, requestMeta }
  • ctx 与钩子中获取的 PluginContext 相同 — ctx.storagectx.kvctx.contentctx.httpctx.log 等。

路由 URL

路由挂载在 /_emdash/api/plugins/<slug>/<route-name>。路由名称可以包含斜杠用于嵌套路径。

插件 ID路由名称URL
formsstatus/_emdash/api/plugins/forms/status
formssubmissions/_emdash/api/plugins/forms/submissions
seosettings/save/_emdash/api/plugins/seo/settings/save
analyticsevents/recent/_emdash/api/plugins/analytics/events/recent

认证和 CSRF

插件路由默认需要认证。 调度器在调用你的处理器之前需要一个会话(或具有 admin 作用域的令牌)。私有路由默认使用 plugins:manage 权限以实现向后兼容。当操作属于现有的内容、媒体、模式或设置功能时,将 permission 设置为更窄的 EmDash RBAC 权限:

routes: {
	create: {
		permission: "content:create",
		input: z.object({ title: z.string() }),
		handler: async (routeCtx, ctx) => {
			// ...
		},
	},
},

私有路由要求 Cookie 认证请求携带 X-EmDash-Request: 1 CSRF 标头。管理 UI 会自动发送它;令牌认证请求不受此限制。

要将路由排除在认证和 CSRF 之外,标记为 public: true

routes: {
	track: {
		public: true,
		input: z.object({ event: z.string() }),
		handler: async (routeCtx, ctx) => {
			ctx.log.info("Tracked", { event: routeCtx.input.event });
			return { ok: true };
		},
	},
},

缓存公共响应

API 响应默认使用 Cache-Control: private, no-store。对于向所有人提供相同数据的公共路由 — 产品目录、公共搜索索引 — 这意味着每个页面访问都要支付到源站的完整往返。公共路由可以通过 cacheControl 选择 CDN/浏览器缓存:

routes: {
	catalog: {
		public: true,
		cacheControl: "public, max-age=60, stale-while-revalidate=300",
		handler: async (ctx) => listProducts(ctx),
	},
},

标头仅应用于公共路由的成功 GET 响应。错误永远不会被缓存,其他方法保持默认值,在私有路由上设置 cacheControl 没有效果 — 认证响应始终保持 private, no-store

将路由作为 MCP 工具暴露

插件可以通过 EmDash 的 MCP 服务器显式暴露选定的私有路由。MCP 暴露永远不会从路由列表推断:

const createEventInput = z.object({
	title: z.string().min(1),
	startsAt: z.string().datetime(),
});

export default {
	routes: {
		"events/create": {
			permission: "content:create",
			input: createEventInput,
			handler: async (routeCtx, ctx) => {
				return { id: await createEvent(routeCtx.input, ctx) };
			},
		},
	},
	mcp: {
		tools: {
			createEvent: {
				description: "Create a calendar event when the user asks to add one.",
				route: "events/create",
				input: createEventInput,
				output: z.object({ id: z.string() }),
				destructive: false,
			},
		},
	},
} satisfies SandboxedPlugin;

EmDash 将其暴露为 <pluginId>__createEvent。引用的路由必须是私有的并声明 permission。输入模式是必需的;输出模式是可选的。对于删除、覆盖、发布、收费或执行其他难以撤销操作的工具,设置 destructive: true

管理员必须在审查工具的名称、描述、路由、权限和 destructive 标志后,单独启用插件的 MCP 工具。调用工具需要路由权限和 mcp:tools 令牌作用域或 mcp:tools:<pluginId>

输入验证

input 接受 Zod 模式。调度器解析请求体(POST/PUT/PATCH)或查询字符串(GET/DELETE),验证它,并将类型化结果作为 routeCtx.input 传递给你的处理器。无效输入在你的处理器运行之前返回 400。

routes: {
	create: {
		input: z.object({
			title: z.string().min(1).max(200),
			email: z.string().email(),
			priority: z.enum(["low", "medium", "high"]).default("medium"),
			tags: z.array(z.string()).optional(),
		}),
		handler: async (routeCtx, ctx) => {
			const { title, email, priority, tags } = routeCtx.input;

			await ctx.storage.items.put(`item_${Date.now()}`, {
				title,
				email,
				priority,
				tags: tags ?? [],
				createdAt: new Date().toISOString(),
			});

			return { success: true };
		},
	},
},

返回值

返回任何可 JSON 序列化的值。调度器将其包装在 EmDash 的标准信封({ success: true, data: <你的值> })中,并以 application/json 形式提供。

return { id: "abc", count: 42 };  // 包装为 { success: true, data: { id, count } }
return [1, 2, 3];                 // 包装为 { success: true, data: [1, 2, 3] }

错误

抛出异常以返回错误响应。任何不是已知插件错误的内容都返回通用消息 — 内部异常被屏蔽而不是泄露堆栈跟踪或数据库错误:

handler: async (routeCtx, ctx) => {
	const item = await ctx.storage.items.get(routeCtx.input.id);
	if (!item) {
		throw new Error("Item not found");
	}
	return item;
},

对于特定状态码,抛出 Response

handler: async (routeCtx, ctx) => {
	const item = await ctx.storage.items.get(routeCtx.input.id);
	if (!item) {
		throw new Response(JSON.stringify({ error: "Not found" }), {
			status: 404,
			headers: { "Content-Type": "application/json" },
		});
	}
	return item;
},

HTTP 方法

路由响应所有方法。如果需要按方法区分行为,在 routeCtx.request.method 上分支:

routes: {
	item: {
		input: z.object({ id: z.string() }),
		handler: async (routeCtx, ctx) => {
			const { id } = routeCtx.input;

			switch (routeCtx.request.method) {
				case "GET":
					return await ctx.storage.items.get(id);
				case "DELETE":
					await ctx.storage.items.delete(id);
					return { deleted: true };
				default:
					throw new Response("Method not allowed", { status: 405 });
			}
		},
	},
},

访问请求

routeCtx.requestSandboxedRequest:一个可移植的 { url, method, headers } 记录,在进程内和隔离区内行为相同。headers 是小写键的 Record<string, string> — 按小写名称索引或使用 Object.entries 迭代。url 是字符串,所以 new URL(request.url) 解析查询参数。routeCtx.requestMeta 包含可用时跨平台标准化的 IP、用户代理和地理数据。

handler: async (routeCtx, ctx) => {
	const { request, requestMeta } = routeCtx;

	const auth = request.headers["authorization"]; // 小写键,无 .get()
	const url = new URL(request.url);
	const page = url.searchParams.get("page");

	ctx.log.info("Request", { meta: requestMeta });

	if (request.method !== "POST") {
		throw new Response("POST required", { status: 405 });
	}
},

常见模式

通过 KV 的设置

沙盒插件通过 KV 存储读写设置,习惯上使用 settings: 前缀。自动生成的 settingsSchema 表单仅适用于原生插件 — 对于沙盒插件,通过路由暴露读写并在 Block Kit 中渲染表单。

routes: {
	settings: {
		handler: async (_routeCtx, ctx) => {
			const settings = await ctx.kv.list("settings:");
			const result: Record<string, unknown> = {};
			for (const entry of settings) {
				result[entry.key.replace("settings:", "")] = entry.value;
			}
			return result;
		},
	},

	"settings/save": {
		input: z.object({
			enabled: z.boolean().optional(),
			apiKey: z.string().optional(),
			maxItems: z.number().optional(),
		}),
		handler: async (routeCtx, ctx) => {
			for (const [key, value] of Object.entries(routeCtx.input)) {
				if (value !== undefined) {
					await ctx.kv.set(`settings:${key}`, value);
				}
			}
			return { success: true };
		},
	},
},

分页列表

从存储查询返回基于游标的分页 — 响应形式与 EmDash 其余部分使用的一致:

routes: {
	list: {
		input: z.object({
			limit: z.number().min(1).max(100).default(50),
			cursor: z.string().optional(),
			status: z.string().optional(),
		}),
		handler: async (routeCtx, ctx) => {
			const { limit, cursor, status } = routeCtx.input;

			const result = await ctx.storage.items.query({
				where: status ? { status } : undefined,
				orderBy: { createdAt: "desc" },
				limit,
				cursor,
			});

			return {
				items: result.items.map((item) => ({ id: item.id, ...item.data })),
				cursor: result.cursor,
				hasMore: result.hasMore,
			};
		},
	},
},

外部 API 代理

通过 ctx.http 将请求代理到外部服务(需要 network:request 能力和 allowedHosts 中的条目):

routes: {
	forecast: {
		input: z.object({ city: z.string() }),
		handler: async (routeCtx, ctx) => {
			if (!ctx.http) throw new Error("Network capability not granted");

			const apiKey = await ctx.kv.get<string>("settings:apiKey");
			if (!apiKey) throw new Error("API key not configured");

			const response = await ctx.http.fetch(
				`https://api.weather.example.com/forecast?city=${routeCtx.input.city}`,
				{ headers: { "X-API-Key": apiKey } },
			);

			if (!response.ok) {
				throw new Error(`Weather API error: ${response.status}`);
			}
			return response.json();
		},
	},
},

从管理 UI 调用路由

使用 admin 包中的 usePluginAPI() — 它自动添加 X-EmDash-Request CSRF 标头和插件 ID 前缀:

import { usePluginAPI } from "@emdash-cms/admin";

function SettingsPage() {
	const api = usePluginAPI();

	const handleSave = async (settings) => {
		await api.post("settings/save", settings);
	};

	const loadSettings = async () => {
		return api.get("settings");
	};
}

从队列和定时处理器调用路由

平台事件处理器(Cloudflare Queue 消费者、自定义 scheduled() 处理器)没有 HTTP 请求,因此也没有 locals.emdash。使用 emdash/middlewarewithEmDashRuntime() 直接获取运行时,无需请求即可调用插件路由:

import { withEmDashRuntime } from "emdash/middleware";

export default {
	// ... 来自 @emdash-cms/cloudflare/worker 的 fetch/scheduled

	async queue(batch: MessageBatch) {
		await withEmDashRuntime(async (runtime) => {
			for (const message of batch.messages) {
				const result = await runtime.handlePluginApiRoute(
					"my-plugin",
					"POST",
					"/finishJob",
					new Request("https://internal/", {
						method: "POST",
						body: JSON.stringify(message.body),
					}),
				);
				if (result.success) message.ack();
				else message.retry();
			}
		});
	},
};

这解析了请求处理器使用的相同缓存运行时,因此插件存储、钩子和媒体访问的行为与请求期间完全相同。在基于连接的数据库适配器(例如通过 Hyperdrive 的 Postgres)上,回调在事件范围的连接下运行,返回时提交并关闭。

外部调用路由

公共路由可以直接调用:

curl -X POST https://your-site.com/_emdash/api/plugins/forms/track \
  -H "Content-Type: application/json" \
  -d '{"event": "pageview"}'

私有路由需要会话凭据或具有 admin 作用域的 API 令牌:

curl -X POST https://your-site.com/_emdash/api/plugins/forms/create \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{"title": "Hello", "email": "user@example.com"}'

路由上下文参考

// 沙盒路由处理器作为两个参数接收的内容

interface SandboxedRequest {
	url: string;
	method: string;
	headers: Record<string, string>; // 小写键
}

interface SandboxedRouteContext {
	input: unknown; // 使用路由级别的 `input` Zod 模式缩窄
	request: SandboxedRequest;
	requestMeta?: unknown;
}

interface PluginContext {
	plugin: { id: string; version: string };
	storage: PluginStorage;
	kv: KVAccess;
	log: LogAccess;
	site: SiteInfo;
	url(path: string): string;
	cron?: CronAccess;
	content?: ContentAccess;       // 当声明了 content:read 或 content:write
	taxonomies?: TaxonomyAccess;   // 当声明了 taxonomies:read
	media?: MediaAccess;           // 当声明了 media:read 或 media:write
	http?: HttpAccess;             // 当声明了 network:request
	users?: UserAccess;            // 当声明了 users:read
	email?: EmailAccess;           // 当声明了 email:send 且配置了提供者
}

原生插件接收一个组合了两者的单一 RouteContext 参数 — 如果走那条路,请参见创建原生插件