Hook 參考

本頁內容

Hook 允許外掛在內容、媒體、郵件、留言與頁面生命週期的特定節點攔截並修改 EmDash 行為。

Hook 概覽

下表列出每個 Hook、觸發條件、可修改內容,以及是否為獨占:

Hook觸發可修改獨占
content:beforeSave內容儲存前內容資料否
content:afterSave內容儲存後無否
content:beforeDelete內容刪除前可取消否
content:afterDelete內容刪除後無否
content:beforePublish內容發布前可取消否
content:beforeSchedule內容排程前可取消否
content:beforeUnpublish內容取消發布前可取消否
content:afterPublish內容發布後無否
content:afterUnpublish內容取消發布後無否
content:afterRestore內容還原後無否
content:afterSchedule內容排程後無否
content:afterUnschedule內容取消排程後無否
media:beforeUpload檔案上傳前檔案中繼資料否
media:afterUpload檔案上傳後無否
cron排程任務觸發無否
email:beforeSend郵件寄送前訊息,可取消否
email:deliver透過傳輸層寄送郵件無是
email:afterSend郵件成功寄送後無否
comment:beforeCreate留言寫入前留言,可取消否
comment:moderate決定留言審核狀態狀態是
comment:afterCreate留言寫入後無否
comment:afterModerate管理員變更留言狀態後無否
page:metadata渲染公開頁面 <head>貢獻標籤否
page:fragments渲染公開頁面 <body>注入腳本否
plugin:install外掛首次安裝時無否
plugin:activate外掛啟用時無否
plugin:deactivate外掛停用時無否
plugin:uninstall外掛移除時無否

內容 Hook

content:beforeSave

Capability: content:write

在內容寫入資料庫之前執行。可用於驗證、轉換或豐富內容。沙箱 Hook 可透過回傳 version 1 的 Hook 結果(含 SAVE_REJECTED 錯誤與 1–500 字元的純文字 reason)拒絕儲存。API 會回應 SAVE_REJECTED,管理後台會標示外掛並以文字顯示原因。空白、過長、格式錯誤或未知的錯誤結果會導致儲存失敗,並回傳通用的 CONTENT_HOOK_ERROR 回應。

在主機程序中,可拋出 emdash 匯出的 ContentSaveRejectedError 以拒絕儲存。任一執行模式下的其他例外也會導致儲存失敗,並回傳不暴露例外訊息的通用回應。

import { definePlugin } from "emdash";

export default definePlugin({
	id: "my-plugin",
	version: "1.0.0",
	hooks: {
		"content:beforeSave": async (event, ctx) => {
			const { content, collection, isNew } = event;

			// 加入時間戳記
			if (isNew) {
				content.createdBy = "system";
			}
			content.modifiedAt = new Date().toISOString();

			// 回傳修改後的內容
			return content;
		},
	},
});

事件

interface ActorInfo {
	readonly id: string;
	readonly role: number;
}

interface ContentHookEvent {
	content: Record<string, unknown>; // 內容資料
	collection: string; // 集合 slug
	isNew: boolean; // 建立為 true,更新為 false
	id?: string; // 更新時既有項目的 ID;建立時省略
	actor?: ActorInfo; // 發起儲存的已驗證使用者
}

更新時,content 僅包含已提交的欄位值。若 Hook 需要與既有資料比對,請以 ctx.content.get(event.collection, event.id) 載入已儲存項目。經驗證的 REST、視覺化編輯與 MCP 儲存會包含 actor;沒有已驗證使用者的內部寫入則省略。

回傳值

  • 回傳修改後的內容物件以套用變更
  • 回傳沙箱 Hook 錯誤封套,以有上限的純文字原因拒絕儲存
  • 回傳 void 表示不變更直接通過

沙箱 Hook 可回傳下列完整封套以拒絕儲存:

return {
	__emdashSandboxHookResult: true,
	version: 1,
	error: {
		code: "SAVE_REJECTED",
		reason: "儲存前請先加入摘要。",
	},
};

主機會修剪 reason,並接受 1 至 500 字元。

content:afterSave

Capability: content:read

在內容儲存後執行。可用於通知、快取失效或外部同步等副作用。

hooks: {
  "content:afterSave": async (event, ctx) => {
    const { content, collection, isNew } = event;

    if (collection === "posts" && content.status === "published") {
      // 通知外部服務
      await ctx.http?.fetch("https://api.example.com/notify", {
        method: "POST",
        body: JSON.stringify({ postId: content.id }),
      });
    }
  },
}

事件

content:afterSave 接收 content、collection、isNew,以及可選的已驗證 actor。content 為完整已儲存條目,資料庫 ID 在 content.id,集合欄位在 content.data。content:beforeSave 更新時使用的可選 id 在儲存後不再出現。

回傳值

不需要回傳值。

content:beforeDelete

Capability: content:read

在內容刪除前執行。可用於驗證刪除或阻止刪除。

hooks: {
  "content:beforeDelete": async (event, ctx) => {
    const { id, collection } = event;

    // 阻止刪除受保護的內容
    const item = await ctx.content?.get(collection, id);
    if (item?.data.protected) {
      return false; // 取消刪除
    }

    // 允許刪除
    return true;
  },
}

事件

interface ContentDeleteEvent {
	id: string; // 條目 ID
	collection: string; // 集合 slug
	permanent?: false; // 原生外掛會收到;沙箱執行環境省略
}

content:beforeDelete 僅在條目移入垃圾桶時執行。原生外掛會收到 permanent: false;沙箱執行環境只傳 id 與 collection。請勿在沙箱 Hook 內依此欄位分支。永久刪除會略過 content:beforeDelete,因此 Hook 無法阻止管理員永久刪除已在垃圾桶中的條目。

回傳值

  • 回傳 false 取消刪除
  • 回傳 true 或 void 允許刪除

content:afterDelete

Capability: content:read

在內容刪除後執行。可用於清理工作。

hooks: {
  "content:afterDelete": async (event, ctx) => {
    const { id, collection, permanent } = event;

    if (permanent) {
      await ctx.storage.relatedItems.delete(`${collection}:${id}`);
    }
  },
}

事件包含 id、collection 與 permanent。條目移入垃圾桶時 permanent 為 false,永久刪除時為 true。移除資料前請先檢查,以免還原垃圾桶條目時仍需要的資料被刪除。此 Hook 沒有回傳值。

content:beforePublish

Capability: hooks.content-policy:register

在內容發布前執行。回傳 void 允許發布,或回傳 { cancel: true, reason } 拒絕。EmDash 接受 reason 中 1–500 字元的純文字;明確取消時回傳 PUBLISH_REJECTED。

事件包含目前的 content、collection 與 origin。經驗證的 API、MCP 與視覺化編輯操作也包含 actor 及對應的 source。visual-editor 來源需要來自已驗證工具列渲染的簽名、短效動作權杖。排程條目到期時會再次執行此 Hook。排程器拒絕會取消排程,並在儀表板列出受影響條目與原因。成功排程、發布或刪除會清除紀錄;管理員可關閉過期紀錄。

content:beforeSchedule

Capability: hooks.content-policy:register

在條目設定發布時間前執行。決策封套與 origin 欄位與 content:beforePublish 相同,事件額外包含 scheduledAt;明確取消時回傳 SCHEDULE_REJECTED。

沒有 content:beforeUnschedule Hook。管理員隨時可取消未來的發布。

content:beforeUnpublish

Capability: hooks.content-policy:register

在已上線內容下架前執行。決策封套與 origin 欄位與 content:beforePublish 相同;明確取消時回傳 UNPUBLISH_REJECTED。

hooks.content-policy:register 不隱含 content:read、content:write 或發布相關操作。無效決策與非預期的 errorPolicy: "abort" 錯誤會失敗即關閉,且不暴露例外訊息。

content:afterPublish

在條目成功發布後執行,包含 EmDash 依排程時間自動發布的條目。可用於依賴已發布條目的工作,例如通知其他服務或更新外部搜尋索引。

hooks: {
  "content:afterPublish": async (event, ctx) => {
    ctx.log.info(`Published ${event.collection}/${event.content.id}`);
  },
}

此 Hook 需要 content:read 能力。EmDash 在發布回應之後執行,因此回傳值無法變更條目或撤銷發布。錯誤會記錄;若 errorPolicy 為 "abort",後續發布 Hook 不會執行。

content:afterUnpublish

在條目成功取消發布後執行。可用於移除或更新外部系統中的內容副本。取消發布也會取消待處理排程,且不會執行 content:afterUnschedule。

hooks: {
  "content:afterUnpublish": async (event, ctx) => {
    ctx.log.info(`Unpublished ${event.collection}/${event.content.id}`);
  },
}

此 Hook 與 content:afterPublish 相同:需要 content:read、延後執行、相同事件形狀,且無回傳值。

content:afterRestore

在垃圾桶內容還原後執行。需要 content:read 能力。還原後的條目為草稿且無排程,不論移入垃圾桶前的狀態為何。取消排程不會一併執行 content:afterUnschedule。

hooks: {
  "content:afterRestore": async (event, ctx) => {
    ctx.log.info(`Restored ${event.collection}/${event.content.id}`);
  },
}

content:afterSchedule

在內容排程為未來發布後執行。需要 content:read 能力。

hooks: {
  "content:afterSchedule": async (event, ctx) => {
    ctx.log.info(`Scheduled ${event.collection}/${event.content.id}`);
  },
}

content:afterUnschedule

在已排程內容取消排程後執行。需要 content:read 能力。

hooks: {
  "content:afterUnschedule": async (event, ctx) => {
    ctx.log.info(`Unscheduled ${event.collection}/${event.content.id}`);
  },
}

事件

interface ContentStateChangeEvent {
	content: Record<string, unknown>;
	collection: string;
}

此事件形狀由 content:afterPublish、content:afterUnpublish、content:afterRestore、content:afterSchedule 與 content:afterUnschedule 共用。content 為狀態變更後的完整條目,包含 id、slug 與狀態;集合欄位在 content.data。

回傳值

不需要回傳值。

媒體 Hook

media:beforeUpload

Capability: media:write

在檔案上傳前執行。可用於驗證、重新命名或拒絕檔案。

hooks: {
  "media:beforeUpload": async (event, ctx) => {
    const { file } = event;

    // 拒絕超過 10MB 的檔案
    if (file.size > 10 * 1024 * 1024) {
      throw new Error("File too large");
    }

    // 重新命名檔案
    return {
      name: `${Date.now()}-${file.name}`,
      type: file.type,
      size: file.size,
    };
  },
}

事件

interface MediaUploadEvent {
	file: {
		name: string; // 原始檔名
		type: string; // MIME 類型
		size: number; // 位元組大小
	};
}

回傳值

  • 回傳修改後的檔案中繼資料以套用變更
  • 回傳 void 表示不變更直接通過
  • 拋出例外以拒絕上傳

media:afterUpload

Capability: media:read

在檔案上傳後執行。可用於處理、縮圖或擷取中繼資料。

hooks: {
  "media:afterUpload": async (event, ctx) => {
    const { media } = event;

    if (media.mimeType.startsWith("image/")) {
      // 儲存圖片中繼資料
      await ctx.kv.set(`media:${media.id}:analyzed`, {
        processedAt: new Date().toISOString(),
      });
    }
  },
}

事件

interface MediaAfterUploadEvent {
	media: {
		id: string;
		filename: string;
		mimeType: string;
		size: number | null;
		url: string;
		createdAt: string;
	};
}

回傳值

不需要回傳值。

生命週期 Hook

生命週期 Hook 不需要註冊能力。

plugin:install

在外掛首次安裝時執行。可用於初始設定、建立儲存集合或種子資料。

hooks: {
  "plugin:install": async (event, ctx) => {
    // 初始化預設設定
    await ctx.settings.set("enabled", true);
    await ctx.settings.set("threshold", 100);

    ctx.log.info("外掛已成功安裝");
  },
}

plugin:activate

在外掛啟用時執行(安裝後或重新啟用後)。

hooks: {
  "plugin:activate": async (event, ctx) => {
    ctx.log.info("外掛已啟用");
  },
}

plugin:deactivate

在外掛停用時執行。

hooks: {
  "plugin:deactivate": async (event, ctx) => {
    ctx.log.info("外掛已停用");
  },
}

plugin:install、plugin:activate 與 plugin:deactivate 接收空事件物件,沒有回傳值。

plugin:uninstall

在外掛移除時執行。可用於清理。

hooks: {
  "plugin:uninstall": async (event, ctx) => {
    const { deleteData } = event;

    if (deleteData) {
      // 清理所有外掛資料
      const items = await ctx.settings.list();
      for (const { key } of items) {
        await ctx.kv.delete(key);
      }
    }

    ctx.log.info("外掛已卸載");
  },
}

事件

interface UninstallEvent {
	deleteData: boolean; // 使用者選擇刪除資料
}

卸載 Hook 沒有回傳值。

Cron Hook

cron

Capability: 不需要

排程任務執行時觸發。以 ctx.cron.schedule() 排程任務。Cron 運算式在每台主機上以 UTC 評估。

hooks: {
  "cron": async (event, ctx) => {
    if (event.name === "daily-sync") {
      const data = await ctx.http?.fetch("https://api.example.com/data");
      ctx.log.info("同步完成");
    }
  },
}

事件

interface CronEvent {
	name: string;
	data?: Record<string, unknown>;
	scheduledAt: string;
}

Cron Hook 沒有回傳值。

郵件 Hook

外掛寄出的郵件依序執行:email:beforeSend、接著 email:deliver、再 email:afterSend。系統驗證郵件直接進入 email:deliver,不會經過 email:beforeSend 或 email:afterSend。

email:beforeSend

Capability: hooks.email-events:register

在寄送前的中介 Hook。可轉換訊息或取消寄送。

hooks: {
  "email:beforeSend": async (event, ctx) => {
    // 為所有郵件加入頁尾
    return {
      ...event.message,
      text: event.message.text + "\n\n—由 My Site 寄出",
    };

    // 或回傳 false 取消寄送
  },
}

事件

interface EmailBeforeSendEvent {
	message: {
		to: string;
		cc?: string[];
		replyTo?: string;
		subject: string;
		text: string;
		html?: string;
	};
	source: string;
}

回傳值

  • 回傳修改後的訊息以轉換內容
  • 回傳 false 取消寄送

email:deliver

Capability: hooks.email-transport:register | Exclusive: 是

傳輸提供者。僅一個外掛可負責寄信,需透過郵件服務實際送出訊息。

hooks: {
  "email:deliver": {
    exclusive: true,
    handler: async (event, ctx) => {
      await sendViaSES(event.message);
    },
  },
}

事件與回傳值

interface EmailDeliverEvent {
	message: {
		to: string;
		cc?: string[];
		replyTo?: string;
		subject: string;
		text: string;
		html?: string;
	};
	source: string;
}

Hook 沒有回傳值。EmDash 驗證郵件的 source 為 "system";外掛寄出的郵件為外掛 ID。

外掛可在訊息上設定 cc(額外收件者)與 replyTo。提供者應在存在時一併寄送;若提供者靜默忽略 cc,那些收件者將收不到郵件。

email:afterSend

Capability: hooks.email-events:register

成功寄送後的非同步 Hook(不等待結果)。錯誤會記錄但不向上傳播。

hooks: {
  "email:afterSend": async (event, ctx) => {
    await ctx.kv.set(`email:log:${Date.now()}`, {
      to: event.message.to,
      subject: event.message.subject,
    });
  },
}

事件與回傳值

email:afterSend 接收與 email:deliver 相同的 message 與 source 欄位,沒有回傳值。

留言 Hook

留言 Hook 依序執行:comment:beforeCreate、接著 comment:moderate、再 comment:afterCreate。管理員或具權限的外掛變更留言狀態時,會另外執行 comment:afterModerate。

留言寫入後,Hook 接收下列紀錄形狀:

interface StoredComment {
	id: string;
	collection: string;
	contentId: string;
	parentId: string | null;
	authorName: string;
	authorEmail: string;
	authorUserId: string | null;
	body: string;
	status: string;
	moderationMetadata: Record<string, unknown> | null;
	createdAt: string;
	updatedAt: string;
}

comment:beforeCreate

Capability: users:read

留言寫入前的中介 Hook。可豐富、驗證或拒絕留言。

hooks: {
  "comment:beforeCreate": async (event, ctx) => {
    // 拒絕含連結的留言
    if (event.comment.body.includes("http")) {
      return false;
    }
  },
}

事件

interface CommentBeforeCreateEvent {
	comment: {
		collection: string;
		contentId: string;
		parentId: string | null;
		authorName: string;
		authorEmail: string;
		authorUserId: string | null;
		body: string;
		ipHash: string | null;
		userAgent: string | null;
	};
	metadata: Record<string, unknown>;
}

回傳值

  • 回傳修改後的事件以轉換
  • 回傳 false 拒絕
  • 回傳 void 表示不變更直接通過

comment:moderate

Capability: users:read | Exclusive: 是

決定留言為核准、待審或垃圾。僅一個審核提供者會生效。

hooks: {
  "comment:moderate": {
    exclusive: true,
    handler: async (event, ctx) => {
      const score = await checkSpam(event.comment);
      return {
        status: score > 0.8 ? "spam" : score > 0.5 ? "pending" : "approved",
        reason: `Spam score: ${score}`,
      };
    },
  },
}

事件

interface CommentModerateEvent {
	comment: { /* 與 beforeCreate 相同 */ };
	metadata: Record<string, unknown>;
	collectionSettings: {
		commentsEnabled: boolean;
		commentsModeration: "all" | "first_time" | "none";
		commentsClosedAfterDays: number;
		commentsAutoApproveUsers: boolean;
	};
	priorApprovedCount: number;
}

回傳值

{ status: "approved" | "pending" | "spam"; reason?: string }

活躍審核器

EmDash 內建審核器會套用集合的留言設定。若恰好一個外掛提供 comment:moderate,EmDash 會選用該外掛而非內建審核器並儲存選擇。若多個外掛提供且尚未儲存選擇,EmDash 不選任何一個,新留言待人工審核。已儲存的選擇(含內建審核器)在所選審核器仍啟用時持續有效。

comment:afterCreate

Capability: users:read

留言寫入後的非同步 Hook(不等待結果)。可用於通知。寄信還需要 email:send 能力與已設定的 email:deliver 提供者;兩者缺一時 ctx.email 為 undefined。

hooks: {
  "comment:afterCreate": async (event, ctx) => {
    const recipient = event.contentAuthor?.email;
    if (event.comment.status === "approved" && recipient && ctx.email) {
      await ctx.email.send({
        to: recipient,
        subject: `New comment on "${event.content.title}"`,
        text: `${event.comment.authorName} commented: ${event.comment.body}`,
      });
    }
  },
}

事件與回傳值

interface CommentAfterCreateEvent {
	comment: StoredComment;
	metadata: Record<string, unknown>;
	content: { id: string; collection: string; slug: string; title?: string };
	contentAuthor?: { id: string; name: string | null; email: string };
}

Hook 沒有回傳值。

comment:afterModerate

Capability: users:read

在管理員或外掛變更留言狀態後執行。成功轉換時執行一次。Hook 錯誤會記錄,不會撤銷狀態變更。

事件

interface CommentAfterModerateEvent {
	comment: StoredComment;
	previousStatus: string;
	newStatus: string;
	moderator: { id: string; name: string | null };
	origin?:
		| { source: "admin"; userId: string }
		| { source: "plugin"; pluginId: string };
}

Hook 沒有回傳值。

頁面 Hook

頁面 Hook 在渲染公開頁面時執行,讓外掛可注入中繼資料與腳本。

兩個頁面 Hook 都接收目前的公開頁面上下文:

interface PublicPageContext {
	url: string;
	path: string;
	locale: string | null;
	kind: "content" | "custom";
	pageType: string;
	title: string | null;
	pageTitle?: string | null;
	description: string | null;
	canonical: string | null;
	image: string | null;
	content?: { collection: string; id: string; slug: string | null };
	seo?: {
		ogTitle?: string | null;
		ogDescription?: string | null;
		ogImage?: string | null;
		robots?: string | null;
	};
	articleMeta?: {
		publishedTime?: string | null;
		modifiedTime?: string | null;
		author?: string | null;
	};
	siteName?: string;
	breadcrumbs?: Array<{ name: string; url: string }>;
	siteUrl?: string;
}

interface PageMetadataEvent { page: PublicPageContext }
interface PageFragmentEvent { page: PublicPageContext }

page:metadata

Capability: 不需要

向頁面 <head> 貢獻 meta 標籤、Open Graph 屬性、JSON-LD 結構化資料或 link 標籤。

hooks: {
  "page:metadata": async (event, ctx) => {
    return [
      { kind: "meta", name: "generator", content: "EmDash" },
      { kind: "property", property: "og:site_name", content: event.page.siteName ?? "My Site" },
      { kind: "jsonld", graph: { "@type": "WebSite", name: event.page.siteName } },
    ];
  },
}

貢獻類型

type PageMetadataContribution =
	| { kind: "meta"; name: string; content: string; key?: string }
	| { kind: "property"; property: string; content: string; key?: string }
	| {
			kind: "link";
			rel: "canonical" | "alternate" | "author" | "license" | "nlweb" | "site.standard.document";
			href: string;
			hreflang?: string;
			key?: string;
	  }
	| {
			kind: "jsonld";
			id?: string;
			graph: Record<string, unknown> | Array<Record<string, unknown>>;
	  };

key 欄位用於去重——相同 key 僅保留最後一筆貢獻。

可回傳單一貢獻、貢獻陣列,或在外掛無需新增時回傳 null。

page:fragments

Capability: hooks.page-fragments:register

向頁面注入腳本或 HTML。僅原生外掛可用。

hooks: {
  "page:fragments": async (event, ctx) => {
    return [
      {
        kind: "external-script",
        placement: "body:end",
        src: "https://analytics.example.com/script.js",
        async: true,
      },
      {
        kind: "inline-script",
        placement: "head",
        code: `window.siteId = "abc123";`,
      },
    ];
  },
}

貢獻類型

type PageFragmentContribution =
	| {
			kind: "external-script";
			placement: "head" | "body:start" | "body:end";
			src: string;
			async?: boolean;
			defer?: boolean;
			attributes?: Record<string, string>;
			key?: string;
		}
	| {
			kind: "inline-script";
			placement: "head" | "body:start" | "body:end";
			code: string;
			attributes?: Record<string, string>;
			key?: string;
		}
	| {
			kind: "html";
			placement: "head" | "body:start" | "body:end";
			html: string;
			key?: string;
		};

可回傳單一片段貢獻、貢獻陣列,或在外掛無需新增時回傳 null。

Hook 設定

Hook 可接受處理函式或設定物件:

hooks: {
  // 簡單處理函式
  "content:afterSave": async (event, ctx) => { ... },

  // 含設定
  "content:beforeSave": {
    priority: 50,        // 數值越小越早(預設:100)
    timeout: 10000,      // 最長執行時間(毫秒,預設:5000)
    dependencies: [],    // 在這些外掛之後執行
    errorPolicy: "abort", // "continue" 或 "abort"(預設)
    handler: async (event, ctx) => { ... },
  },
}

設定選項

選項類型預設值說明
prioritynumber100執行順序(數值越小越早)
timeoutnumber5000最長執行時間(毫秒)
dependenciesstring[][]必須先執行的外掛 ID
errorPolicystring"abort""continue" 表示忽略錯誤
exclusivebooleanfalse僅一個外掛可為作用中提供者(如 email:deliver、comment:moderate 等提供者模式 Hook)

外掛上下文

所有 Hook 都接收含外掛 API 的上下文物件:

interface PluginContext {
	plugin: { id: string; version: string };
	storage: PluginStorage;
	kv: KVAccess;
	content?: ContentAccess;
	media?: MediaAccess;
	http?: HttpAccess;
	log: LogAccess;
	site: { name: string; url: string; locale: string };
	url(path: string): string;
	users?: UserAccess;
	cron?: CronAccess;
	email?: EmailAccess;
}

各上下文 API 所需能力請見外掛能力。

錯誤處理

Hook 中的錯誤會依 errorPolicy 記錄並處理:

  • "abort"(預設)— 停止執行,適用時回滾交易
  • "continue" — 記錄錯誤並繼續下一個 Hook
hooks: {
  "content:beforeSave": {
    errorPolicy: "continue", // 失敗時不阻擋儲存
    handler: async (event, ctx) => {
      try {
        await ctx.http?.fetch("https://api.example.com/validate");
      } catch (error) {
        ctx.log.warn("驗證服務不可用", error);
      }
    },
  },
}

執行順序

Hook 依下列規則執行:

  1. 依 priority 升序排序
  2. 設有 dependencies 的外掛在其依賴之後執行
  3. 相同 priority 內順序確定但未指定
// 最先執行(priority 10)
{ priority: 10, handler: ... }

// 其次(priority 50)
{ priority: 50, handler: ... }

// 最後(預設 priority 100)
{ handler: ... }