UNPKG

@ai-growth/n8n-nodes-wordpress

Version:

n8n node for WordPress integration with AI GROWTH - SEO WP plugin

310 lines (309 loc) 14.6 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; exports.__esModule = true; exports.SeoService = void 0; var ErrorUtils_1 = require("../utils/ErrorUtils"); /** * Serviço para gerenciamento de metadados SEO */ var SeoService = /** @class */ (function () { /** * Construtor do serviço * @param client Cliente WordPress */ function SeoService(client) { this.pluginEndpoint = 'ai-growth-seo/v1'; this.pluginAvailabilityChecked = false; this.pluginAvailable = false; this.pluginVersion = 'unknown'; this.pluginFeatures = []; this.client = client; } /** * Verifica se o plugin AI GROWTH - SEO WP está disponível * @param force Forçar verificação mesmo se já verificado * @returns Status do plugin */ SeoService.prototype.checkPluginAvailability = function (force) { if (force === void 0) { force = false; } return __awaiter(this, void 0, void 0, function () { var response, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: // Se já verificou e não está forçando, retorna o status atual if (this.pluginAvailabilityChecked && !force) { return [2 /*return*/, { version: this.pluginVersion, features: this.pluginFeatures, status: this.pluginAvailable ? 'active' : 'not_installed' }]; } _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, this.client.get("".concat(this.pluginEndpoint, "/info"))]; case 2: response = _a.sent(); // Atualiza as informações do plugin this.pluginAvailable = true; this.pluginVersion = response.version || 'unknown'; this.pluginFeatures = response.features || []; this.pluginAvailabilityChecked = true; return [2 /*return*/, { version: this.pluginVersion, features: this.pluginFeatures, status: 'active' }]; case 3: error_1 = _a.sent(); // Marca o plugin como indisponível this.pluginAvailable = false; this.pluginAvailabilityChecked = true; this.pluginVersion = 'unknown'; this.pluginFeatures = []; return [2 /*return*/, { version: 'unknown', features: [], status: 'not_installed' }]; case 4: return [2 /*return*/]; } }); }); }; /** * Obtém metadados SEO para um post específico * @param postId ID do post * @param options Opções da consulta * @returns Metadados SEO do post */ SeoService.prototype.getPostSeoMetadata = function (postId, options) { if (options === void 0) { options = {}; } return __awaiter(this, void 0, void 0, function () { var _a, includeFaq, _b, includeCta, _c, requirePlugin, response, metadata, error_2; return __generator(this, function (_d) { switch (_d.label) { case 0: _a = options.includeFaq, includeFaq = _a === void 0 ? true : _a, _b = options.includeCta, includeCta = _b === void 0 ? true : _b, _c = options.requirePlugin, requirePlugin = _c === void 0 ? false : _c; if (!!this.pluginAvailabilityChecked) return [3 /*break*/, 2]; return [4 /*yield*/, this.checkPluginAvailability()]; case 1: _d.sent(); _d.label = 2; case 2: // Se o plugin não está disponível e é requerido, lança erro if (!this.pluginAvailable && requirePlugin) { throw new ErrorUtils_1.WordPressError('AI GROWTH - SEO WP plugin is required but not available on the WordPress site', ErrorUtils_1.WordPressErrorType.NOT_FOUND); } // Se o plugin não está disponível, retorna metadados vazios if (!this.pluginAvailable) { return [2 /*return*/, {}]; } _d.label = 3; case 3: _d.trys.push([3, 5, , 6]); return [4 /*yield*/, this.client.get("".concat(this.pluginEndpoint, "/post/").concat(postId, "/metadata"))]; case 4: response = _d.sent(); metadata = { meta_title: response.meta_title || '', meta_description: response.meta_description || '', meta_keywords: response.meta_keywords || '' }; // Adicionar FAQ se solicitado e disponível if (includeFaq && response.faq) { metadata.faq = this.formatFaq(response.faq); } // Adicionar CTA se solicitado e disponível if (includeCta && response.cta) { metadata.cta = this.formatCta(response.cta); } return [2 /*return*/, metadata]; case 5: error_2 = _d.sent(); // Se o plugin não está disponível mas não é requerido, retorna metadados vazios if (!requirePlugin) { return [2 /*return*/, {}]; } // Caso contrário, relança o erro if (error_2 instanceof ErrorUtils_1.WordPressError) { throw error_2; } throw new ErrorUtils_1.WordPressError("Failed to fetch SEO metadata for post ".concat(postId, ": ").concat(error_2.message), ErrorUtils_1.WordPressErrorType.SERVER, undefined, error_2); case 6: return [2 /*return*/]; } }); }); }; /** * Formata os dados de FAQ do plugin * @param faq Dados de FAQ da API * @returns FAQ formatado */ SeoService.prototype.formatFaq = function (faq) { if (Array.isArray(faq)) { return faq.map(function (item) { return ({ question: item.question || '', answer: item.answer || '' }); }); } if (typeof faq === 'object' && faq !== null) { // Alguns plugins podem retornar um objeto com índices numéricos return Object.values(faq).map(function (item) { return ({ question: item.question || '', answer: item.answer || '' }); }); } return []; }; /** * Formata os dados de CTA do plugin * @param cta Dados de CTA da API * @returns CTA formatado */ SeoService.prototype.formatCta = function (cta) { if (typeof cta === 'object' && cta !== null) { return { text: cta.text || '', url: cta.url || '' }; } return { text: '', url: '' }; }; /** * Verifica se uma feature específica do plugin está disponível * @param featureName Nome da feature * @returns Se a feature está disponível */ SeoService.prototype.hasFeature = function (featureName) { return this.pluginFeatures.includes(featureName); }; /** * Enriquece um post com metadados SEO * @param post Post a ser enriquecido * @param options Opções da consulta * @returns Post com metadados SEO */ SeoService.prototype.enrichPostWithSeo = function (post, options) { if (options === void 0) { options = {}; } return __awaiter(this, void 0, void 0, function () { var seoMetadata, error_3; return __generator(this, function (_a) { switch (_a.label) { case 0: // Se não há post ou não há ID, retorna o post original if (!post || !post.id) { return [2 /*return*/, post]; } _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, this.getPostSeoMetadata(post.id, options)]; case 2: seoMetadata = _a.sent(); // Mesclar os metadados com o post return [2 /*return*/, __assign(__assign({}, post), seoMetadata)]; case 3: error_3 = _a.sent(); // Se falhar e não é obrigatório, retorna o post original if (!options.requirePlugin) { return [2 /*return*/, post]; } // Caso contrário, relança o erro throw error_3; case 4: return [2 /*return*/]; } }); }); }; /** * Enriquece múltiplos posts com metadados SEO * @param posts Array de posts a serem enriquecidos * @param options Opções da consulta * @returns Posts com metadados SEO */ SeoService.prototype.enrichPostsWithSeo = function (posts, options) { if (options === void 0) { options = {}; } return __awaiter(this, void 0, void 0, function () { var error_4; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: // Se não há posts, retorna array vazio if (!posts || !Array.isArray(posts) || posts.length === 0) { return [2 /*return*/, []]; } _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, Promise.all(posts.map(function (post) { return _this.enrichPostWithSeo(post, options); }))]; case 2: // Enriquecer cada post com metadados SEO return [2 /*return*/, _a.sent()]; case 3: error_4 = _a.sent(); // Se falhar e não é obrigatório, retorna os posts originais if (!options.requirePlugin) { return [2 /*return*/, posts]; } // Caso contrário, relança o erro throw error_4; case 4: return [2 /*return*/]; } }); }); }; return SeoService; }()); exports.SeoService = SeoService;