Créer un premier plugin
Construisez votre premier plugin complet étape par étape.
Objectif
Créer un plugin qui analyse du texte et retourne des statistiques.
Étape 1 : Définir le schéma
Fichier : schemas/text-analyzer.ts
import { z } from "zod";
export const TextAnalyzerInputSchema = z.object({
text: z.string().describe("Texte à analyser"),
countWords: z.boolean().default(true).describe("Compter les mots"),
countSentences: z.boolean().default(true).describe("Compter les phrases"),
});
export type TextAnalyzerInput = z.infer<typeof TextAnalyzerInputSchema>;
Étape 2 : Implémenter le handler
Fichier : plugins/text-analyzer.ts
import { TextAnalyzerInputSchema } from "../schemas/text-analyzer";
export async function analyzeText(input: unknown): Promise<string> {
const { text, countWords, countSentences } = TextAnalyzerInputSchema.parse(input);
const stats: Record<string, any> = {};
if (countWords) {
stats.wordCount = text.split(/\s+/).length;
}
if (countSentences) {
stats.sentenceCount = text.split(/[.!?]+/).length - 1;
}
stats.charCount = text.length;
return JSON.stringify(stats, null, 2);
}
Étape 3 : Tester
Fichier : __tests__/text-analyzer.test.ts
import { describe, it, expect } from "bun:test";
import { analyzeText } from "../plugins/text-analyzer";
describe("text-analyzer", () => {
it("doit analyser le texte", async () => {
const result = await analyzeText({
text: "Hello world. This is a test.",
countWords: true,
countSentences: true,
});
const stats = JSON.parse(result);
expect(stats.wordCount).toBe(6);
expect(stats.sentenceCount).toBe(2);
});
it("doit gérer les options", async () => {
const result = await analyzeText({
text: "Hello world",
countWords: false,
countSentences: false,
});
const stats = JSON.parse(result);
expect(stats.wordCount).toBeUndefined();
expect(stats.sentenceCount).toBeUndefined();
expect(stats.charCount).toBe(11);
});
});
Exécutez :
bun test
Félicitations !
Vous avez créé un plugin complet avec :
- ✅ Schéma Zod validé
- ✅ Handler fonctionnel
- ✅ Tests passants
Prochaines étapes :