import type { Plugin } from "payload"; import { AIChatPermissionsCollection } from "./collections/AIChatPermissions.js"; import type { PayloadChatPluginConfig } from "./types.js"; import { optimizePostEndpoint } from "./endpoints/optimizeEndpoint.js"; import { generateSlugEndpoint, generateThumbnailEndpoint, generateSingleFieldEndpoint, } from "./endpoints/generateEndpoints.js"; export const payloadChatPlugin = (pluginOptions: PayloadChatPluginConfig): Plugin => (incomingConfig) => { const config = { ...incomingConfig }; // If disabled, return config untouched if (pluginOptions.enabled === false) { return config; } // 1. Inject the Permissions Collection into the Schema const existingCollections = config.collections || []; const mcpServers = pluginOptions.mcpServers || []; // Dynamically populate the select options for Collections and MCP Servers const permissionCollection = { ...AIChatPermissionsCollection }; const collectionField = permissionCollection.fields.find( (f) => "name" in f && f.name === "allowedCollections", ) as any; if (collectionField) { collectionField.options = existingCollections.map((c) => ({ label: c.labels?.singular || c.slug, value: c.slug, })); } const mcpField = permissionCollection.fields.find( (f) => "name" in f && f.name === "allowedMcpServers", ) as any; if (mcpField) { mcpField.options = mcpServers.map((s) => ({ label: s.name, value: s.name, })); } config.collections = [...existingCollections, permissionCollection]; // 2. Register Custom API Endpoint for the AI Chat config.endpoints = [ ...(config.endpoints || []), { path: "/api/mcp-chat", method: "post", handler: async (_req) => { // Fallback simple handler while developing endpoint logic return Response.json({ message: "Chat endpoint active" }); }, }, { path: "/api/mintel-ai/optimize", method: "post", handler: optimizePostEndpoint, }, { path: "/api/mintel-ai/generate-slug", method: "post", handler: generateSlugEndpoint, }, { path: "/api/mintel-ai/generate-thumbnail", method: "post", handler: generateThumbnailEndpoint, }, { path: "/api/mintel-ai/generate-single-field", method: "post", handler: generateSingleFieldEndpoint, }, ]; // 3. Inject Chat React Component into Admin UI if (pluginOptions.renderChatBubble !== false) { config.admin = { ...(config.admin || {}), components: { ...(config.admin?.components || {}), providers: [ ...(config.admin?.components?.providers || []), "@mintel/payload-ai/components/ChatWindow/index#ChatWindowProvider", ], }, }; } return config; };