플러그인은 관리 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은 routeCtx와 ctx를 추론합니다 — 매개변수 어노테이션이 필요 없습니다. 샌드박스 라우트 핸들러는 두 개의 인수를 받습니다: (routeCtx, ctx).
routeCtx는 요청 관련 데이터를 담습니다:{ input, request, requestMeta }.ctx는 훅에서 받는 것과 동일한PluginContext입니다 —ctx.storage,ctx.kv,ctx.content,ctx.http,ctx.log등.
라우트 URL
라우트는 /_emdash/api/plugins/<slug>/<route-name>에 마운트됩니다. 라우트 이름에는 중첩 경로를 위한 슬래시를 포함할 수 있습니다.
| 플러그인 ID | 라우트 이름 | URL |
|---|---|---|
forms | status | /_emdash/api/plugins/forms/status |
forms | submissions | /_emdash/api/plugins/forms/submissions |
seo | settings/save | /_emdash/api/plugins/seo/settings/save |
analytics | events/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) => {
// ...
},
},
},
프라이빗 라우트는 쿠키 인증 요청에 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] }로 래핑
오류
오류 응답을 반환하려면 throw합니다. 알려진 플러그인 오류가 아닌 모든 것은 일반 메시지를 반환합니다 — 내부 예외는 스택 트레이스나 데이터베이스 오류를 노출하는 대신 마스킹됩니다:
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를 throw합니다:
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.request는 **SandboxedRequest**입니다: 프로세스 내와 아이솔레이트 내에서 동일하게 동작하는 포터블 { 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/middleware의 withEmDashRuntime()을 사용하여 런타임을 직접 가져오고 요청 없이 플러그인 라우트를 호출합니다:
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 인수를 받습니다 — 그 경로를 선택한다면 네이티브 플러그인 만들기를 참조하세요.