@edtools/cli 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,850 @@
1
+ import {
2
+ calculateReadTime,
3
+ calculateWordCount,
4
+ extractShortDescription,
5
+ generateTimestamp,
6
+ generateUUID
7
+ } from "./chunk-INVECVSW.js";
8
+
9
+ // src/types/adapter.ts
10
+ var AdapterRegistry = class {
11
+ adapters;
12
+ constructor() {
13
+ this.adapters = /* @__PURE__ */ new Map();
14
+ }
15
+ register(adapter) {
16
+ this.adapters.set(adapter.name, adapter);
17
+ }
18
+ get(name) {
19
+ return this.adapters.get(name);
20
+ }
21
+ async detectAdapter(projectPath) {
22
+ for (const adapter of this.adapters.values()) {
23
+ if (await adapter.detect(projectPath)) {
24
+ return adapter;
25
+ }
26
+ }
27
+ return null;
28
+ }
29
+ list() {
30
+ return Array.from(this.adapters.keys());
31
+ }
32
+ };
33
+
34
+ // src/adapters/html/index.ts
35
+ import fs from "fs-extra";
36
+ import path from "path";
37
+ import { fileURLToPath } from "url";
38
+ import ejs from "ejs";
39
+ import { marked } from "marked";
40
+ var __filename = fileURLToPath(import.meta.url);
41
+ var __dirname = path.dirname(__filename);
42
+ var HTMLAdapter = class {
43
+ name = "html";
44
+ async detect(projectPath) {
45
+ try {
46
+ const files = await fs.readdir(projectPath);
47
+ const hasHtmlInRoot = files.some((f) => f.endsWith(".html"));
48
+ const hasIndexHtml = await fs.pathExists(path.join(projectPath, "index.html"));
49
+ const commonDirs = ["public", "dist", "build", "src"];
50
+ for (const dir of commonDirs) {
51
+ const dirPath = path.join(projectPath, dir);
52
+ if (await fs.pathExists(dirPath)) {
53
+ const dirFiles = await fs.readdir(dirPath);
54
+ const hasHtmlInDir = dirFiles.some((f) => f.endsWith(".html"));
55
+ if (hasHtmlInDir) {
56
+ return true;
57
+ }
58
+ }
59
+ }
60
+ return hasHtmlInRoot || hasIndexHtml;
61
+ } catch (error) {
62
+ return false;
63
+ }
64
+ }
65
+ async render(content, data) {
66
+ const possiblePaths = [
67
+ path.join(__dirname, "templates", "blog-post-enhanced.ejs"),
68
+ path.join(__dirname, "../../../src/adapters/html/templates/blog-post-enhanced.ejs"),
69
+ path.join(path.dirname(fileURLToPath(import.meta.url)), "templates/blog-post-enhanced.ejs"),
70
+ path.join(path.dirname(fileURLToPath(import.meta.url)), "../html/templates/blog-post-enhanced.ejs")
71
+ ];
72
+ let templatePath = null;
73
+ let templateDir = null;
74
+ for (const p of possiblePaths) {
75
+ if (await fs.pathExists(p)) {
76
+ templatePath = p;
77
+ templateDir = path.dirname(p);
78
+ break;
79
+ }
80
+ }
81
+ if (!templatePath || !templateDir) {
82
+ throw new Error(`Template not found. Tried paths:
83
+ ${possiblePaths.join("\n")}`);
84
+ }
85
+ const template = await fs.readFile(templatePath, "utf-8");
86
+ const blogConfig = data?.blogConfig || {
87
+ name: content.metadata.author || "Blog",
88
+ description: "",
89
+ language: "es",
90
+ websiteUrl: "",
91
+ navigation: [],
92
+ primaryColor: "#2563eb",
93
+ textColor: "#1f2937",
94
+ textLight: "#6b7280",
95
+ borderColor: "#e5e7eb",
96
+ bgLight: "#f9fafb",
97
+ allowAICrawlers: true
98
+ };
99
+ const templateData = {
100
+ metadata: content.metadata,
101
+ schemaOrg: JSON.stringify(content.schemaOrg, null, 2),
102
+ intro: await this.markdownToHTML(content.content.intro),
103
+ sections: await Promise.all(
104
+ content.content.sections.map(async (section) => ({
105
+ ...section,
106
+ content: await this.renderSectionContent(section)
107
+ }))
108
+ ),
109
+ conclusion: await this.markdownToHTML(content.content.conclusion),
110
+ cta: content.content.cta,
111
+ relatedPosts: content.relatedPosts || [],
112
+ seoScore: content.seo.score,
113
+ // New data
114
+ blogConfig,
115
+ tableOfContents: data?.tableOfContents || [],
116
+ prevPost: data?.prevPost,
117
+ nextPost: data?.nextPost
118
+ };
119
+ const html = ejs.render(template, templateData, {
120
+ filename: templatePath,
121
+ // Required for includes to resolve correctly
122
+ root: templateDir
123
+ // Root directory for include resolution
124
+ });
125
+ return html;
126
+ }
127
+ async write(output, outputPath) {
128
+ await fs.ensureDir(path.dirname(outputPath));
129
+ await fs.writeFile(outputPath, output, "utf-8");
130
+ }
131
+ getFileExtension() {
132
+ return ".html";
133
+ }
134
+ transformPath(basePath) {
135
+ if (!basePath.endsWith(".html")) {
136
+ return basePath + ".html";
137
+ }
138
+ return basePath;
139
+ }
140
+ /**
141
+ * Convert markdown to HTML
142
+ */
143
+ async markdownToHTML(markdown) {
144
+ return marked(markdown);
145
+ }
146
+ /**
147
+ * Render section content based on type
148
+ */
149
+ async renderSectionContent(section) {
150
+ switch (section.type) {
151
+ case "text":
152
+ return await this.markdownToHTML(section.content);
153
+ case "comparison":
154
+ return this.renderComparisonTable(section.data);
155
+ case "list":
156
+ return this.renderList(section.data);
157
+ case "code":
158
+ return this.renderCode(section.data);
159
+ default:
160
+ return await this.markdownToHTML(section.content);
161
+ }
162
+ }
163
+ /**
164
+ * Render comparison table
165
+ */
166
+ renderComparisonTable(data) {
167
+ if (!data || !data.headers || !data.rows) {
168
+ return "";
169
+ }
170
+ let html = '<table class="comparison-table">\n';
171
+ html += " <thead>\n <tr>\n";
172
+ data.headers.forEach((header) => {
173
+ html += ` <th>${header}</th>
174
+ `;
175
+ });
176
+ html += " </tr>\n </thead>\n";
177
+ html += " <tbody>\n";
178
+ data.rows.forEach((row) => {
179
+ html += " <tr>\n";
180
+ row.forEach((cell) => {
181
+ html += ` <td>${cell}</td>
182
+ `;
183
+ });
184
+ html += " </tr>\n";
185
+ });
186
+ html += " </tbody>\n";
187
+ html += "</table>";
188
+ return html;
189
+ }
190
+ /**
191
+ * Render list
192
+ */
193
+ renderList(data) {
194
+ if (!data || !data.items) {
195
+ return "";
196
+ }
197
+ const tag = data.ordered ? "ol" : "ul";
198
+ let html = `<${tag} class="content-list">
199
+ `;
200
+ data.items.forEach((item) => {
201
+ html += " <li>\n";
202
+ html += ` <strong>${item.title}</strong>
203
+ `;
204
+ if (item.description) {
205
+ html += ` <p>${item.description}</p>
206
+ `;
207
+ }
208
+ html += " </li>\n";
209
+ });
210
+ html += `</${tag}>`;
211
+ return html;
212
+ }
213
+ /**
214
+ * Render code block
215
+ */
216
+ renderCode(data) {
217
+ if (!data || !data.code) {
218
+ return "";
219
+ }
220
+ let html = '<div class="code-block">\n';
221
+ if (data.caption) {
222
+ html += ` <div class="code-caption">${data.caption}</div>
223
+ `;
224
+ }
225
+ html += ` <pre><code class="language-${data.language || "plaintext"}">${this.escapeHtml(data.code)}</code></pre>
226
+ `;
227
+ html += "</div>";
228
+ return html;
229
+ }
230
+ /**
231
+ * Escape HTML entities
232
+ */
233
+ escapeHtml(text) {
234
+ const map = {
235
+ "&": "&amp;",
236
+ "<": "&lt;",
237
+ ">": "&gt;",
238
+ '"': "&quot;",
239
+ "'": "&#039;"
240
+ };
241
+ return text.replace(/[&<>"']/g, (m) => map[m]);
242
+ }
243
+ };
244
+
245
+ // src/core/generator.ts
246
+ import Anthropic from "@anthropic-ai/sdk";
247
+ import OpenAI from "openai";
248
+ import path2 from "path";
249
+ import { fileURLToPath as fileURLToPath2 } from "url";
250
+ import fs2 from "fs-extra";
251
+ import slugify from "slugify";
252
+ var ContentGenerator = class {
253
+ anthropic = null;
254
+ openai = null;
255
+ provider;
256
+ adapters;
257
+ constructor(apiKey, provider = "anthropic") {
258
+ this.provider = provider;
259
+ if (provider === "anthropic") {
260
+ this.anthropic = new Anthropic({
261
+ apiKey: apiKey || process.env.ANTHROPIC_API_KEY || ""
262
+ });
263
+ } else if (provider === "openai") {
264
+ this.openai = new OpenAI({
265
+ apiKey: apiKey || process.env.OPENAI_API_KEY || ""
266
+ });
267
+ }
268
+ this.adapters = new AdapterRegistry();
269
+ this.adapters.register(new HTMLAdapter());
270
+ }
271
+ /**
272
+ * Main generate method
273
+ */
274
+ async generate(config) {
275
+ const results = {
276
+ success: true,
277
+ posts: [],
278
+ warnings: [],
279
+ errors: [],
280
+ dryRun: config.dryRun
281
+ };
282
+ const allPostsContent = [];
283
+ const { calculateAvgReadTime } = await import("./content-helpers-TXVEJMQK.js");
284
+ try {
285
+ const adapter = await this.adapters.detectAdapter(config.projectPath);
286
+ if (!adapter) {
287
+ throw new Error("No suitable adapter found for this project");
288
+ }
289
+ console.log(`\u2713 Using adapter: ${adapter.name}`);
290
+ const topics = config.topics || await this.generateTopics(config.productInfo, config.count || 3);
291
+ const blogConfig = config.blogConfig || {
292
+ name: `${config.productInfo.name} Blog`,
293
+ description: config.productInfo.description,
294
+ language: "en",
295
+ websiteUrl: config.productInfo.websiteUrl,
296
+ navigation: [
297
+ { label: "Home", url: config.productInfo.websiteUrl || "/" },
298
+ { label: "Blog", url: `${config.productInfo.websiteUrl}/blog/`, active: true }
299
+ ],
300
+ primaryColor: "#2563eb",
301
+ textColor: "#1f2937",
302
+ textLight: "#6b7280",
303
+ borderColor: "#e5e7eb",
304
+ bgLight: "#f9fafb",
305
+ allowAICrawlers: true
306
+ };
307
+ for (const topic of topics.slice(0, config.count || 3)) {
308
+ try {
309
+ console.log(`
310
+ \u{1F4DD} Generating: ${topic}`);
311
+ const content = await this.generateContent(config.productInfo, topic);
312
+ const tableOfContents = this.generateTableOfContents(content);
313
+ const relatedPosts = await this.generateRelatedPosts(content, config.outputDir);
314
+ const navigation = await this.generateNavigationData(content, config.outputDir);
315
+ content.relatedPosts = relatedPosts;
316
+ const output = await adapter.render(content, {
317
+ blogConfig,
318
+ tableOfContents,
319
+ prevPost: navigation.prevPost,
320
+ nextPost: navigation.nextPost
321
+ });
322
+ const slug = content.metadata.slug;
323
+ const fileName = adapter.transformPath?.(slug) || `${slug}/index${adapter.getFileExtension()}`;
324
+ const outputPath = path2.join(config.outputDir, fileName);
325
+ if (!config.dryRun) {
326
+ await adapter.write(output, outputPath);
327
+ }
328
+ allPostsContent.push(content);
329
+ results.posts.push({
330
+ id: content.metadata.id,
331
+ title: content.metadata.title,
332
+ slug,
333
+ path: outputPath,
334
+ url: content.metadata.url,
335
+ seoScore: content.seo.score,
336
+ readTime: content.metadata.readTime,
337
+ wordCount: content.metadata.wordCount,
338
+ tags: content.metadata.tags,
339
+ keywords: content.metadata.keywords,
340
+ datePublished: content.metadata.datePublished,
341
+ seoIssues: content.seo.suggestions
342
+ });
343
+ if (!config.dryRun) {
344
+ console.log(`\u2713 Generated: ${outputPath}`);
345
+ } else {
346
+ console.log(`\u2713 Would generate: ${outputPath}`);
347
+ }
348
+ console.log(` SEO Score: ${content.seo.score}/100`);
349
+ } catch (error) {
350
+ results.errors?.push(`Failed to generate "${topic}": ${error.message}`);
351
+ results.success = false;
352
+ }
353
+ }
354
+ if (results.posts.length > 0 && allPostsContent.length > 0) {
355
+ results.manifestPath = path2.join(config.outputDir, "index.json");
356
+ results.sitemapPath = path2.join(config.outputDir, "sitemap.xml");
357
+ if (!config.dryRun) {
358
+ await this.generateManifest(config.outputDir, config.productInfo, allPostsContent);
359
+ await this.generateBlogIndex(config.outputDir, config.productInfo, blogConfig);
360
+ await this.updateSitemap(config.outputDir, config.productInfo, allPostsContent);
361
+ }
362
+ const totalWords = allPostsContent.reduce((sum, post) => sum + post.metadata.wordCount, 0);
363
+ const avgSeoScore = results.posts.reduce((sum, p) => sum + p.seoScore, 0) / results.posts.length;
364
+ const wordCounts = allPostsContent.map((post) => post.metadata.wordCount);
365
+ const avgReadTime = calculateAvgReadTime(wordCounts);
366
+ results.stats = {
367
+ avgSeoScore: Math.round(avgSeoScore * 10) / 10,
368
+ totalWords,
369
+ avgReadTime
370
+ };
371
+ }
372
+ } catch (error) {
373
+ results.success = false;
374
+ results.errors?.push(error.message);
375
+ }
376
+ return results;
377
+ }
378
+ /**
379
+ * Generate blog post content using the selected AI provider
380
+ */
381
+ async generateContent(productInfo, topic) {
382
+ const prompt = this.buildPrompt(productInfo, topic);
383
+ let contentData;
384
+ if (this.provider === "anthropic") {
385
+ contentData = await this.generateWithAnthropic(prompt);
386
+ } else if (this.provider === "openai") {
387
+ contentData = await this.generateWithOpenAI(prompt);
388
+ } else {
389
+ throw new Error(`Unsupported provider: ${this.provider}`);
390
+ }
391
+ const id = generateUUID();
392
+ const slug = slugify(contentData.metadata.title, { lower: true, strict: true });
393
+ const datePublished = generateTimestamp();
394
+ const baseUrl = productInfo.websiteUrl.replace(/\/$/, "");
395
+ const url = `${baseUrl}/blog/${slug}.html`;
396
+ const fullContent = [
397
+ contentData.content.intro,
398
+ ...contentData.content.sections.map((s) => s.content),
399
+ contentData.content.conclusion
400
+ ].join(" ");
401
+ const wordCount = calculateWordCount(fullContent);
402
+ const readTime = calculateReadTime(wordCount);
403
+ const shortDescription = extractShortDescription(contentData.content.intro);
404
+ const tags = contentData.metadata.keywords.slice(0, 5);
405
+ const content = {
406
+ metadata: {
407
+ id,
408
+ ...contentData.metadata,
409
+ slug,
410
+ url,
411
+ datePublished,
412
+ author: productInfo.name,
413
+ readTime,
414
+ wordCount,
415
+ tags,
416
+ shortDescription,
417
+ fullDescription: contentData.content.intro
418
+ },
419
+ schemaOrg: this.generateSchemaOrg({
420
+ id,
421
+ ...contentData.metadata,
422
+ slug,
423
+ url,
424
+ datePublished,
425
+ author: productInfo.name,
426
+ readTime,
427
+ wordCount,
428
+ tags
429
+ }, productInfo),
430
+ content: contentData.content,
431
+ relatedPosts: [],
432
+ seo: await this.calculateSEOScore(contentData)
433
+ };
434
+ return content;
435
+ }
436
+ /**
437
+ * Generate content using Anthropic's Claude API
438
+ */
439
+ async generateWithAnthropic(prompt) {
440
+ if (!this.anthropic) {
441
+ throw new Error("Anthropic client not initialized");
442
+ }
443
+ const response = await this.anthropic.messages.create({
444
+ model: "claude-3-5-sonnet-20241022",
445
+ max_tokens: 4096,
446
+ temperature: 0.7,
447
+ messages: [
448
+ {
449
+ role: "user",
450
+ content: prompt
451
+ }
452
+ ]
453
+ });
454
+ const textContent = response.content[0].type === "text" ? response.content[0].text : "";
455
+ const jsonMatch = textContent.match(/\{[\s\S]*\}/);
456
+ if (!jsonMatch) {
457
+ throw new Error("Failed to extract JSON from Claude response");
458
+ }
459
+ return JSON.parse(jsonMatch[0]);
460
+ }
461
+ /**
462
+ * Generate content using OpenAI's ChatGPT API
463
+ */
464
+ async generateWithOpenAI(prompt) {
465
+ if (!this.openai) {
466
+ throw new Error("OpenAI client not initialized");
467
+ }
468
+ const response = await this.openai.chat.completions.create({
469
+ model: "gpt-4-turbo-preview",
470
+ max_tokens: 4096,
471
+ temperature: 0.7,
472
+ messages: [
473
+ {
474
+ role: "user",
475
+ content: prompt
476
+ }
477
+ ],
478
+ response_format: { type: "json_object" }
479
+ });
480
+ const textContent = response.choices[0]?.message?.content || "";
481
+ if (!textContent) {
482
+ throw new Error("Failed to get response from OpenAI");
483
+ }
484
+ return JSON.parse(textContent);
485
+ }
486
+ /**
487
+ * Build prompt for Claude API
488
+ */
489
+ buildPrompt(productInfo, topic) {
490
+ return `You are an expert SEO content writer. Generate a comprehensive blog post about: "${topic}"
491
+
492
+ Product context:
493
+ - Name: ${productInfo.name}
494
+ - Tagline: ${productInfo.tagline || ""}
495
+ - Category: ${productInfo.category}
496
+ - Features: ${productInfo.features.join(", ")}
497
+ - Pricing: ${productInfo.pricingModel || "Not specified"}
498
+ ${productInfo.useCases ? `- Use cases: ${productInfo.useCases.join(", ")}` : ""}
499
+
500
+ IMPORTANT INSTRUCTIONS:
501
+ 1. Write for users searching on Google and being recommended by AI assistants (Claude, ChatGPT)
502
+ 2. Focus on being helpful, not promotional
503
+ 3. Include comparisons with alternatives when relevant
504
+ 4. Use natural language, avoid keyword stuffing
505
+ 5. Make it comprehensive (1000-1500 words worth of content)
506
+ 6. Structure with clear sections (intro, 3-5 main sections, conclusion)
507
+ 7. Be factual - do NOT invent statistics or make false claims
508
+
509
+ Output ONLY valid JSON in this exact format (no markdown, no code blocks):
510
+ {
511
+ "metadata": {
512
+ "title": "SEO-optimized title (under 60 chars)",
513
+ "description": "Meta description (under 160 chars)",
514
+ "keywords": ["keyword1", "keyword2", "keyword3"],
515
+ "category": "${productInfo.category}"
516
+ },
517
+ "content": {
518
+ "intro": "Engaging introduction paragraph in markdown format",
519
+ "sections": [
520
+ {
521
+ "heading": "Section title",
522
+ "level": 2,
523
+ "content": "Section content in markdown format",
524
+ "type": "text"
525
+ }
526
+ ],
527
+ "conclusion": "Conclusion paragraph in markdown",
528
+ "cta": {
529
+ "text": "Try ${productInfo.name}",
530
+ "url": "${productInfo.websiteUrl || "/signup"}"
531
+ }
532
+ }
533
+ }`;
534
+ }
535
+ /**
536
+ * Generate Schema.org structured data
537
+ */
538
+ generateSchemaOrg(metadata, productInfo) {
539
+ return {
540
+ "@context": "https://schema.org",
541
+ "@type": "BlogPosting",
542
+ headline: metadata.title,
543
+ description: metadata.description,
544
+ author: {
545
+ "@type": "Organization",
546
+ name: productInfo.name,
547
+ url: productInfo.websiteUrl
548
+ },
549
+ datePublished: metadata.datePublished,
550
+ publisher: {
551
+ "@type": "Organization",
552
+ name: productInfo.name
553
+ },
554
+ keywords: metadata.keywords.join(", "),
555
+ articleSection: metadata.category
556
+ };
557
+ }
558
+ /**
559
+ * Calculate SEO score
560
+ */
561
+ async calculateSEOScore(content) {
562
+ let score = 100;
563
+ const suggestions = [];
564
+ if (content.metadata.title.length > 60) {
565
+ score -= 10;
566
+ suggestions.push("Title is too long (should be under 60 chars)");
567
+ }
568
+ if (content.metadata.description.length > 160) {
569
+ score -= 10;
570
+ suggestions.push("Meta description is too long (should be under 160 chars)");
571
+ }
572
+ if (content.metadata.keywords.length < 3) {
573
+ score -= 5;
574
+ suggestions.push("Add more keywords (at least 3)");
575
+ }
576
+ if (content.content.sections.length < 3) {
577
+ score -= 10;
578
+ suggestions.push("Add more sections for better structure (at least 3)");
579
+ }
580
+ return {
581
+ score: Math.max(0, score),
582
+ suggestions
583
+ };
584
+ }
585
+ /**
586
+ * Generate topic suggestions
587
+ */
588
+ async generateTopics(productInfo, count) {
589
+ const prompt = `Generate ${count} SEO-friendly blog post topics for a product called "${productInfo.name}" in the ${productInfo.category} category.
590
+
591
+ Product description: ${productInfo.description}
592
+ Features: ${productInfo.features.join(", ")}
593
+
594
+ Requirements:
595
+ - Topics should be helpful for potential customers
596
+ - Focus on solving problems or answering questions
597
+ - Include comparisons, guides, and use cases
598
+ - Optimize for search engines and AI recommendations
599
+
600
+ Output ONLY a JSON array of topic strings, no markdown:
601
+ ["Topic 1", "Topic 2", "Topic 3"]`;
602
+ try {
603
+ if (this.provider === "anthropic" && this.anthropic) {
604
+ const response = await this.anthropic.messages.create({
605
+ model: "claude-3-5-sonnet-20241022",
606
+ max_tokens: 1024,
607
+ messages: [{ role: "user", content: prompt }]
608
+ });
609
+ const textContent = response.content[0].type === "text" ? response.content[0].text : "";
610
+ const jsonMatch = textContent.match(/\[[\s\S]*\]/);
611
+ if (jsonMatch) {
612
+ return JSON.parse(jsonMatch[0]);
613
+ }
614
+ } else if (this.provider === "openai" && this.openai) {
615
+ const response = await this.openai.chat.completions.create({
616
+ model: "gpt-4-turbo-preview",
617
+ max_tokens: 1024,
618
+ messages: [{ role: "user", content: prompt }],
619
+ response_format: { type: "json_object" }
620
+ });
621
+ const textContent = response.choices[0]?.message?.content || "";
622
+ if (textContent) {
623
+ const data = JSON.parse(textContent);
624
+ const topicsArray = data.topics || data;
625
+ if (Array.isArray(topicsArray)) {
626
+ return topicsArray;
627
+ }
628
+ if (typeof topicsArray === "object") {
629
+ return Object.values(topicsArray).filter((v) => typeof v === "string");
630
+ }
631
+ }
632
+ }
633
+ } catch (error) {
634
+ console.warn("Failed to generate topics with AI, using fallback");
635
+ }
636
+ return [
637
+ `Best ${productInfo.category} software ${(/* @__PURE__ */ new Date()).getFullYear()}`,
638
+ `How to choose ${productInfo.category} solution`,
639
+ `${productInfo.name} vs alternatives: Complete comparison`
640
+ ];
641
+ }
642
+ /**
643
+ * Generate blog manifest (index.json)
644
+ */
645
+ async generateManifest(outputDir, productInfo, posts) {
646
+ const { calculateAvgReadTime } = await import("./content-helpers-TXVEJMQK.js");
647
+ const manifestPosts = posts.map((post) => ({
648
+ id: post.metadata.id,
649
+ slug: post.metadata.slug,
650
+ url: post.metadata.url,
651
+ title: post.metadata.title,
652
+ shortDescription: post.metadata.shortDescription || post.metadata.description,
653
+ fullDescription: post.metadata.fullDescription || post.content.intro,
654
+ publishDate: post.metadata.datePublished,
655
+ readTime: post.metadata.readTime,
656
+ wordCount: post.metadata.wordCount,
657
+ tags: post.metadata.tags,
658
+ category: post.metadata.category,
659
+ seo: {
660
+ metaTitle: post.metadata.title,
661
+ metaDescription: post.metadata.description,
662
+ keywords: post.metadata.keywords,
663
+ seoScore: post.seo.score
664
+ }
665
+ }));
666
+ const totalWords = posts.reduce((sum, post) => sum + post.metadata.wordCount, 0);
667
+ const wordCounts = posts.map((post) => post.metadata.wordCount);
668
+ const avgReadTime = calculateAvgReadTime(wordCounts);
669
+ const manifest = {
670
+ version: "1.0.0",
671
+ generated: generateTimestamp(),
672
+ site: {
673
+ name: `${productInfo.name} Blog`,
674
+ url: productInfo.websiteUrl + "/blog",
675
+ description: productInfo.description || `Insights on ${productInfo.category}`
676
+ },
677
+ posts: manifestPosts,
678
+ stats: {
679
+ totalPosts: posts.length,
680
+ totalWords,
681
+ avgReadTime
682
+ }
683
+ };
684
+ const manifestPath = path2.join(outputDir, "index.json");
685
+ await fs2.writeJson(manifestPath, manifest, { spaces: 2 });
686
+ console.log(`\u2713 Generated blog manifest: ${manifestPath}`);
687
+ }
688
+ /**
689
+ * Generate blog index.html page
690
+ */
691
+ async generateBlogIndex(outputDir, productInfo, blogConfig) {
692
+ const ejs2 = await import("ejs");
693
+ const possiblePaths = [
694
+ path2.join(path2.dirname(fileURLToPath2(import.meta.url)), "../adapters/html/templates/blog-index.html.ejs"),
695
+ path2.join(path2.dirname(fileURLToPath2(import.meta.url)), "../../adapters/html/templates/blog-index.html.ejs"),
696
+ path2.join(path2.dirname(fileURLToPath2(import.meta.url)), "adapters/html/templates/blog-index.html.ejs")
697
+ ];
698
+ let templatePath = null;
699
+ for (const p of possiblePaths) {
700
+ if (await fs2.pathExists(p)) {
701
+ templatePath = p;
702
+ break;
703
+ }
704
+ }
705
+ if (!templatePath) {
706
+ console.warn(`Blog index template not found in any of the expected locations. Skipping blog index generation.`);
707
+ return;
708
+ }
709
+ const templateDir = path2.dirname(templatePath);
710
+ const template = await fs2.readFile(templatePath, "utf-8");
711
+ const html = ejs2.render(template, {
712
+ siteName: `${productInfo.name} Blog`,
713
+ siteDescription: productInfo.description || `Insights on ${productInfo.category}`,
714
+ siteUrl: productInfo.websiteUrl + "/blog",
715
+ blogConfig
716
+ }, {
717
+ filename: templatePath,
718
+ // Required for includes to resolve correctly
719
+ root: templateDir
720
+ // Root directory for include resolution
721
+ });
722
+ const indexPath = path2.join(outputDir, "index.html");
723
+ await fs2.writeFile(indexPath, html, "utf-8");
724
+ console.log(`\u2713 Generated blog index: ${indexPath}`);
725
+ }
726
+ /**
727
+ * Update sitemap.xml
728
+ */
729
+ async updateSitemap(blogDir, productInfo, posts) {
730
+ const sitemapPath = path2.join(blogDir, "sitemap.xml");
731
+ const urls = posts.map((post) => {
732
+ return ` <url>
733
+ <loc>${post.metadata.url}</loc>
734
+ <lastmod>${post.metadata.datePublished.split("T")[0]}</lastmod>
735
+ <changefreq>weekly</changefreq>
736
+ <priority>0.8</priority>
737
+ </url>`;
738
+ }).join("\n");
739
+ const baseUrl = productInfo.websiteUrl.replace(/\/$/, "");
740
+ const blogIndexUrl = ` <url>
741
+ <loc>${baseUrl}/blog/</loc>
742
+ <lastmod>${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}</lastmod>
743
+ <changefreq>daily</changefreq>
744
+ <priority>1.0</priority>
745
+ </url>`;
746
+ const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
747
+ <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
748
+ ${blogIndexUrl}
749
+ ${urls}
750
+ </urlset>`;
751
+ await fs2.writeFile(sitemapPath, sitemap, "utf-8");
752
+ console.log(`\u2713 Generated sitemap: ${sitemapPath}`);
753
+ }
754
+ /**
755
+ * Generate table of contents from post sections
756
+ */
757
+ generateTableOfContents(content) {
758
+ const toc = [];
759
+ content.content.sections.forEach((section) => {
760
+ if (section.level >= 2 && section.level <= 4) {
761
+ const id = section.heading.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
762
+ toc.push({
763
+ id,
764
+ text: section.heading,
765
+ level: section.level
766
+ });
767
+ }
768
+ });
769
+ return toc;
770
+ }
771
+ /**
772
+ * Find related posts based on tags and category similarity
773
+ */
774
+ async generateRelatedPosts(currentPost, outputDir, limit = 3) {
775
+ try {
776
+ const manifestPath = path2.join(outputDir, "index.json");
777
+ if (!await fs2.pathExists(manifestPath)) {
778
+ return [];
779
+ }
780
+ const manifest = await fs2.readJson(manifestPath);
781
+ const scoredPosts = manifest.posts.filter((post) => post.id !== currentPost.metadata.id).map((post) => {
782
+ let score = 0;
783
+ if (post.category === currentPost.metadata.category) {
784
+ score += 3;
785
+ }
786
+ const sharedTags = post.tags.filter(
787
+ (tag) => currentPost.metadata.tags.includes(tag)
788
+ );
789
+ score += sharedTags.length;
790
+ return {
791
+ post,
792
+ score
793
+ };
794
+ }).filter((item) => item.score > 0).sort((a, b) => b.score - a.score).slice(0, limit);
795
+ return scoredPosts.map((item) => ({
796
+ title: item.post.title,
797
+ slug: item.post.slug,
798
+ url: item.post.url,
799
+ excerpt: item.post.shortDescription
800
+ }));
801
+ } catch (error) {
802
+ console.warn("Failed to generate related posts:", error);
803
+ return [];
804
+ }
805
+ }
806
+ /**
807
+ * Get previous and next posts for navigation
808
+ */
809
+ async generateNavigationData(currentPost, outputDir) {
810
+ try {
811
+ const manifestPath = path2.join(outputDir, "index.json");
812
+ if (!await fs2.pathExists(manifestPath)) {
813
+ return {};
814
+ }
815
+ const manifest = await fs2.readJson(manifestPath);
816
+ const sortedPosts = [...manifest.posts].sort(
817
+ (a, b) => new Date(b.publishDate).getTime() - new Date(a.publishDate).getTime()
818
+ );
819
+ const currentIndex = sortedPosts.findIndex(
820
+ (post) => post.id === currentPost.metadata.id
821
+ );
822
+ if (currentIndex === -1) {
823
+ return {};
824
+ }
825
+ const prevPost = sortedPosts[currentIndex + 1];
826
+ const nextPost = sortedPosts[currentIndex - 1];
827
+ return {
828
+ prevPost: prevPost ? {
829
+ title: prevPost.title,
830
+ url: prevPost.url,
831
+ slug: prevPost.slug
832
+ } : void 0,
833
+ nextPost: nextPost ? {
834
+ title: nextPost.title,
835
+ url: nextPost.url,
836
+ slug: nextPost.slug
837
+ } : void 0
838
+ };
839
+ } catch (error) {
840
+ console.warn("Failed to generate navigation data:", error);
841
+ return {};
842
+ }
843
+ }
844
+ };
845
+
846
+ export {
847
+ AdapterRegistry,
848
+ HTMLAdapter,
849
+ ContentGenerator
850
+ };