APIルート

このページ

プラグインは、管理UIと外部統合のためにAPIルートを公開できます。ルートは /_emdash/api/plugins/<slug>/<route-name> の下にマウントされ(<slug>emdash-plugin.jsoncslug フィールドで、ランタイムでは 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 SandboxedPluginrouteCtxctx を推論します — パラメータの注釈は不要です。サンドボックス化されたルートハンドラーは 2つの引数 を取ります:(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 スコープを持つトークン)を要求します:

  • 読み取りメソッド(GETHEADOPTIONS)には plugins:read パーミッションが必要です。
  • 書き込みメソッド(POSTPUTPATCHDELETE)には plugins:manage が必要です。
  • プライベートルート上の状態変更メソッドには、X-EmDash-Request: 1 CSRFヘッダーも必要です(管理UIの usePluginAPI() フックは自動的に送信します。Cookie認証された外部呼び出し元は自分で設定する必要があります。トークン認証されたリクエストは免除されます)。

ルートを認証と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 };
		},
	},
},

入力検証

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: <your value> })でラップし、application/json として提供します。

return { id: "abc", count: 42 };  // wrapped to { success: true, data: { id, count } }
return [1, 2, 3];                 // wrapped to { 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"]; // lowercased key, no .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経由の設定

サンドボックス化されたプラグインは、慣例的に settings: プレフィックスの下で、KVストア経由で設定を読み書きします。自動生成される 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からルートを呼び出す

管理パッケージから 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");
	};
}

外部からルートを呼び出す

パブリックルートは直接呼び出し可能です:

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"}'

ルートコンテキストリファレンス

// サンドボックス化されたルートハンドラーが2つの引数として受け取るもの

interface SandboxedRequest {
	url: string;
	method: string;
	headers: Record<string, string>; // lowercased keys
}

interface SandboxedRouteContext {
	input: unknown; // narrow with the `input` Zod schema at the route level
	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;       // when content:read or content:write declared
	media?: MediaAccess;           // when media:read or media:write declared
	http?: HttpAccess;             // when network:request declared
	users?: UserAccess;            // when users:read declared
	email?: EmailAccess;           // when email:send declared and provider configured
}

ネイティブプラグインは、2つを組み合わせた単一の RouteContext 引数を受け取ります — その方向に進む場合は ネイティブプラグインの作成 を参照してください。