您的第一個原生外掛

本頁內容

本指南將引導您從零開始建構原生外掛。原生外掛與您的 Astro 網站在同一個程序中執行,可完全存取執行時期,包括 React 管理頁面、Portable Text 元件和頁面片段。

如果您尚未決定要使用原生外掛還是沙盒外掛,請先閱讀選擇外掛格式

兩個部分,一個或兩個檔案

  1. 描述符工廠 — 回傳一個包含 format: "native"PluginDescriptor
  2. createPlugin(options) 函式 — 執行時期部分。
my-native-plugin/
├── src/
│   ├── index.ts          # 描述符工廠 + createPlugin
│   ├── admin.tsx         # React 管理元件(選用)
│   └── astro/
│       └── index.ts
├── package.json
└── tsconfig.json

設定套件

{
	"name": "@my-org/plugin-analytics",
	"version": "0.1.0",
	"type": "module",
	"main": "dist/index.js",
	"exports": {
		".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
		"./admin": { "types": "./dist/admin.d.ts", "import": "./dist/admin.js" }
	},
	"files": ["dist"],
	"peerDependencies": { "emdash": "*", "react": "^18.0.0" }
}

撰寫描述符和執行時期

import { definePlugin } from "emdash";
import type { PluginDescriptor } from "emdash";

export interface AnalyticsOptions { enabled?: boolean; maxEvents?: number; }

export function analyticsPlugin(options: AnalyticsOptions = {}): PluginDescriptor {
	return {
		id: "analytics", version: "0.1.0", format: "native",
		entrypoint: "@my-org/plugin-analytics", options,
		adminEntry: "@my-org/plugin-analytics/admin",
		adminPages: [{ path: "/dashboard", label: "Dashboard", icon: "chart" }],
		adminWidgets: [{ id: "events-today", title: "Events Today", size: "third" }],
	};
}

export function createPlugin(options: AnalyticsOptions = {}) {
	const maxEvents = options.maxEvents ?? 100;
	return definePlugin({
		id: "analytics", version: "0.1.0",
		capabilities: ["network:request"],
		allowedHosts: ["api.analytics.example.com"],
		storage: { events: { indexes: ["type", "createdAt"] } },
		admin: {
			entry: "@my-org/plugin-analytics/admin",
			settingsSchema: {
				trackingId: { type: "string", label: "Tracking ID" },
				enabled: { type: "boolean", label: "Enabled", default: options.enabled ?? true },
			},
			pages: [{ path: "/dashboard", label: "Dashboard", icon: "chart" }],
			widgets: [{ id: "events-today", title: "Events Today", size: "third" }],
		},
		hooks: {
			"plugin:install": async (_event, ctx) => { ctx.log.info("Analytics plugin installed", { maxEvents }); },
			"content:afterSave": async (event, ctx) => {
				const enabled = await ctx.kv.get<boolean>("settings:enabled");
				if (enabled === false) return;
				await ctx.storage.events.put(`evt_${Date.now()}`, {
					type: "content:save", contentId: event.content.id, createdAt: new Date().toISOString(),
				});
			},
		},
		routes: {
			stats: {
				handler: async (ctx) => {
					const today = new Date().toISOString().split("T")[0];
					const count = await ctx.storage.events.count({ createdAt: { gte: today } });
					return { today: count };
				},
			},
		},
	});
}

export default createPlugin;

外掛 ID 規則

id 欄位必須符合 /^[a-z][a-z0-9_-]*$/

版本格式

使用語意化版本控制。

註冊外掛

import { defineConfig } from "astro/config";
import emdash from "emdash/astro";
import { analyticsPlugin } from "@my-org/plugin-analytics";

export default defineConfig({
	integrations: [
		emdash({ plugins: [analyticsPlugin({ enabled: true, maxEvents: 500 })] }),
	],
});

設定 UI

欄位類型:stringnumberbooleanselectsecreturlemail。設定持久化到同一個外掛專屬 KV 儲存中 — 使用 ctx.kv.get<T>("settings:<key>") 讀取。

完整範例 — 稽核日誌外掛

import { definePlugin } from "emdash";
import type { PluginDescriptor } from "emdash";

interface AuditEntry {
	timestamp: string; action: "create" | "update" | "delete";
	collection: string; resourceId: string;
}

export function auditLogPlugin(): PluginDescriptor {
	return { id: "audit-log", version: "0.1.0", format: "native", entrypoint: "@emdash-cms/plugin-audit-log" };
}

export function createPlugin() {
	return definePlugin({
		id: "audit-log", version: "0.1.0",
		storage: {
			entries: { indexes: ["timestamp", "action", "collection", ["collection", "timestamp"], ["action", "timestamp"]] },
		},
		admin: {
			settingsSchema: { retentionDays: { type: "number", label: "保留天數", description: "保留條目的天數。0 = 永久。", default: 90, min: 0, max: 365 } },
			pages: [{ path: "/history", label: "Audit History", icon: "history" }],
			widgets: [{ id: "recent-activity", title: "Recent Activity", size: "half" }],
		},
		hooks: {
			"content:afterSave": {
				priority: 200,
				handler: async (event, ctx) => {
					await ctx.storage.entries.put(`${Date.now()}-${event.content.id}`, {
						timestamp: new Date().toISOString(), action: event.isNew ? "create" : "update",
						collection: event.collection, resourceId: event.content.id as string,
					});
				},
			},
			"content:afterDelete": {
				priority: 200,
				handler: async (event, ctx) => {
					await ctx.storage.entries.put(`${Date.now()}-${event.id}`, {
						timestamp: new Date().toISOString(), action: "delete",
						collection: event.collection, resourceId: event.id,
					});
				},
			},
		},
		routes: {
			recent: {
				handler: async (ctx) => {
					const result = await ctx.storage.entries.query({ orderBy: { timestamp: "desc" }, limit: 10 });
					return { entries: result.items.map((item) => ({ id: item.id, ...(item.data as AuditEntry) })) };
				},
			},
		},
	});
}

export default createPlugin;

測試

  1. 建立一個安裝了 EmDash 的測試網站。
  2. astro.config.mjs 中註冊您的外掛。
  3. 啟動開發伺服器,透過建立、更新或刪除內容來觸發鉤子。
  4. 檢查主控台中的 ctx.log 輸出,並透過 API 路由驗證儲存。

下一步