@edtools/cli 0.1.0 → 0.3.0

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.
package/bin/edtools.js CHANGED
File without changes
@@ -0,0 +1,527 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // src/types/adapter.ts
9
+ var AdapterRegistry = class {
10
+ adapters;
11
+ constructor() {
12
+ this.adapters = /* @__PURE__ */ new Map();
13
+ }
14
+ register(adapter) {
15
+ this.adapters.set(adapter.name, adapter);
16
+ }
17
+ get(name) {
18
+ return this.adapters.get(name);
19
+ }
20
+ async detectAdapter(projectPath) {
21
+ for (const adapter of this.adapters.values()) {
22
+ if (await adapter.detect(projectPath)) {
23
+ return adapter;
24
+ }
25
+ }
26
+ return null;
27
+ }
28
+ list() {
29
+ return Array.from(this.adapters.keys());
30
+ }
31
+ };
32
+
33
+ // src/adapters/html/index.ts
34
+ import fs from "fs-extra";
35
+ import path from "path";
36
+ import ejs from "ejs";
37
+ import { marked } from "marked";
38
+ var HTMLAdapter = class {
39
+ name = "html";
40
+ templatePath;
41
+ constructor() {
42
+ this.templatePath = path.join(__dirname, "templates", "blog-post.html.ejs");
43
+ }
44
+ async detect(projectPath) {
45
+ try {
46
+ const files = await fs.readdir(projectPath);
47
+ const hasHtml = files.some((f) => f.endsWith(".html"));
48
+ const hasIndexHtml = await fs.pathExists(path.join(projectPath, "index.html"));
49
+ return hasHtml || hasIndexHtml;
50
+ } catch (error) {
51
+ return false;
52
+ }
53
+ }
54
+ async render(content) {
55
+ const template = await fs.readFile(this.templatePath, "utf-8");
56
+ const templateData = {
57
+ metadata: content.metadata,
58
+ schemaOrg: JSON.stringify(content.schemaOrg, null, 2),
59
+ intro: await this.markdownToHTML(content.content.intro),
60
+ sections: await Promise.all(
61
+ content.content.sections.map(async (section) => ({
62
+ ...section,
63
+ content: await this.renderSectionContent(section)
64
+ }))
65
+ ),
66
+ conclusion: await this.markdownToHTML(content.content.conclusion),
67
+ cta: content.content.cta,
68
+ relatedPosts: content.relatedPosts || [],
69
+ seoScore: content.seo.score
70
+ };
71
+ const html = ejs.render(template, templateData);
72
+ return html;
73
+ }
74
+ async write(output, outputPath) {
75
+ await fs.ensureDir(path.dirname(outputPath));
76
+ await fs.writeFile(outputPath, output, "utf-8");
77
+ }
78
+ getFileExtension() {
79
+ return ".html";
80
+ }
81
+ transformPath(basePath) {
82
+ if (!basePath.endsWith(".html")) {
83
+ return basePath + "/index.html";
84
+ }
85
+ return basePath;
86
+ }
87
+ /**
88
+ * Convert markdown to HTML
89
+ */
90
+ async markdownToHTML(markdown) {
91
+ return marked(markdown);
92
+ }
93
+ /**
94
+ * Render section content based on type
95
+ */
96
+ async renderSectionContent(section) {
97
+ switch (section.type) {
98
+ case "text":
99
+ return await this.markdownToHTML(section.content);
100
+ case "comparison":
101
+ return this.renderComparisonTable(section.data);
102
+ case "list":
103
+ return this.renderList(section.data);
104
+ case "code":
105
+ return this.renderCode(section.data);
106
+ default:
107
+ return await this.markdownToHTML(section.content);
108
+ }
109
+ }
110
+ /**
111
+ * Render comparison table
112
+ */
113
+ renderComparisonTable(data) {
114
+ if (!data || !data.headers || !data.rows) {
115
+ return "";
116
+ }
117
+ let html = '<table class="comparison-table">\n';
118
+ html += " <thead>\n <tr>\n";
119
+ data.headers.forEach((header) => {
120
+ html += ` <th>${header}</th>
121
+ `;
122
+ });
123
+ html += " </tr>\n </thead>\n";
124
+ html += " <tbody>\n";
125
+ data.rows.forEach((row) => {
126
+ html += " <tr>\n";
127
+ row.forEach((cell) => {
128
+ html += ` <td>${cell}</td>
129
+ `;
130
+ });
131
+ html += " </tr>\n";
132
+ });
133
+ html += " </tbody>\n";
134
+ html += "</table>";
135
+ return html;
136
+ }
137
+ /**
138
+ * Render list
139
+ */
140
+ renderList(data) {
141
+ if (!data || !data.items) {
142
+ return "";
143
+ }
144
+ const tag = data.ordered ? "ol" : "ul";
145
+ let html = `<${tag} class="content-list">
146
+ `;
147
+ data.items.forEach((item) => {
148
+ html += " <li>\n";
149
+ html += ` <strong>${item.title}</strong>
150
+ `;
151
+ if (item.description) {
152
+ html += ` <p>${item.description}</p>
153
+ `;
154
+ }
155
+ html += " </li>\n";
156
+ });
157
+ html += `</${tag}>`;
158
+ return html;
159
+ }
160
+ /**
161
+ * Render code block
162
+ */
163
+ renderCode(data) {
164
+ if (!data || !data.code) {
165
+ return "";
166
+ }
167
+ let html = '<div class="code-block">\n';
168
+ if (data.caption) {
169
+ html += ` <div class="code-caption">${data.caption}</div>
170
+ `;
171
+ }
172
+ html += ` <pre><code class="language-${data.language || "plaintext"}">${this.escapeHtml(data.code)}</code></pre>
173
+ `;
174
+ html += "</div>";
175
+ return html;
176
+ }
177
+ /**
178
+ * Escape HTML entities
179
+ */
180
+ escapeHtml(text) {
181
+ const map = {
182
+ "&": "&amp;",
183
+ "<": "&lt;",
184
+ ">": "&gt;",
185
+ '"': "&quot;",
186
+ "'": "&#039;"
187
+ };
188
+ return text.replace(/[&<>"']/g, (m) => map[m]);
189
+ }
190
+ };
191
+
192
+ // src/core/generator.ts
193
+ import Anthropic from "@anthropic-ai/sdk";
194
+ import OpenAI from "openai";
195
+ import path2 from "path";
196
+ import fs2 from "fs-extra";
197
+ import slugify from "slugify";
198
+ var ContentGenerator = class {
199
+ anthropic = null;
200
+ openai = null;
201
+ provider;
202
+ adapters;
203
+ constructor(apiKey, provider = "anthropic") {
204
+ this.provider = provider;
205
+ if (provider === "anthropic") {
206
+ this.anthropic = new Anthropic({
207
+ apiKey: apiKey || process.env.ANTHROPIC_API_KEY || ""
208
+ });
209
+ } else if (provider === "openai") {
210
+ this.openai = new OpenAI({
211
+ apiKey: apiKey || process.env.OPENAI_API_KEY || ""
212
+ });
213
+ }
214
+ this.adapters = new AdapterRegistry();
215
+ this.adapters.register(new HTMLAdapter());
216
+ }
217
+ /**
218
+ * Main generate method
219
+ */
220
+ async generate(config) {
221
+ const results = {
222
+ success: true,
223
+ posts: [],
224
+ warnings: [],
225
+ errors: []
226
+ };
227
+ try {
228
+ const adapter = await this.adapters.detectAdapter(config.projectPath);
229
+ if (!adapter) {
230
+ throw new Error("No suitable adapter found for this project");
231
+ }
232
+ console.log(`\u2713 Using adapter: ${adapter.name}`);
233
+ const topics = config.topics || await this.generateTopics(config.productInfo, config.count || 3);
234
+ for (const topic of topics.slice(0, config.count || 3)) {
235
+ try {
236
+ console.log(`
237
+ \u{1F4DD} Generating: ${topic}`);
238
+ const content = await this.generateContent(config.productInfo, topic);
239
+ const output = await adapter.render(content);
240
+ const slug = content.metadata.slug;
241
+ const fileName = adapter.transformPath?.(slug) || `${slug}/index${adapter.getFileExtension()}`;
242
+ const outputPath = path2.join(config.outputDir, fileName);
243
+ await adapter.write(output, outputPath);
244
+ results.posts.push({
245
+ title: content.metadata.title,
246
+ slug,
247
+ path: outputPath,
248
+ seoScore: content.seo.score
249
+ });
250
+ console.log(`\u2713 Generated: ${outputPath}`);
251
+ console.log(` SEO Score: ${content.seo.score}/100`);
252
+ } catch (error) {
253
+ results.errors?.push(`Failed to generate "${topic}": ${error.message}`);
254
+ results.success = false;
255
+ }
256
+ }
257
+ if (results.posts.length > 0) {
258
+ await this.updateSitemap(config.projectPath, config.outputDir, results.posts);
259
+ }
260
+ } catch (error) {
261
+ results.success = false;
262
+ results.errors?.push(error.message);
263
+ }
264
+ return results;
265
+ }
266
+ /**
267
+ * Generate blog post content using the selected AI provider
268
+ */
269
+ async generateContent(productInfo, topic) {
270
+ const prompt = this.buildPrompt(productInfo, topic);
271
+ let contentData;
272
+ if (this.provider === "anthropic") {
273
+ contentData = await this.generateWithAnthropic(prompt);
274
+ } else if (this.provider === "openai") {
275
+ contentData = await this.generateWithOpenAI(prompt);
276
+ } else {
277
+ throw new Error(`Unsupported provider: ${this.provider}`);
278
+ }
279
+ const slug = slugify(contentData.metadata.title, { lower: true, strict: true });
280
+ const content = {
281
+ metadata: {
282
+ ...contentData.metadata,
283
+ slug,
284
+ datePublished: (/* @__PURE__ */ new Date()).toISOString(),
285
+ author: productInfo.name
286
+ },
287
+ schemaOrg: this.generateSchemaOrg({
288
+ ...contentData.metadata,
289
+ slug,
290
+ datePublished: (/* @__PURE__ */ new Date()).toISOString(),
291
+ author: productInfo.name
292
+ }, productInfo),
293
+ content: contentData.content,
294
+ relatedPosts: [],
295
+ seo: await this.calculateSEOScore(contentData)
296
+ };
297
+ return content;
298
+ }
299
+ /**
300
+ * Generate content using Anthropic's Claude API
301
+ */
302
+ async generateWithAnthropic(prompt) {
303
+ if (!this.anthropic) {
304
+ throw new Error("Anthropic client not initialized");
305
+ }
306
+ const response = await this.anthropic.messages.create({
307
+ model: "claude-3-5-sonnet-20241022",
308
+ max_tokens: 4096,
309
+ temperature: 0.7,
310
+ messages: [
311
+ {
312
+ role: "user",
313
+ content: prompt
314
+ }
315
+ ]
316
+ });
317
+ const textContent = response.content[0].type === "text" ? response.content[0].text : "";
318
+ const jsonMatch = textContent.match(/\{[\s\S]*\}/);
319
+ if (!jsonMatch) {
320
+ throw new Error("Failed to extract JSON from Claude response");
321
+ }
322
+ return JSON.parse(jsonMatch[0]);
323
+ }
324
+ /**
325
+ * Generate content using OpenAI's ChatGPT API
326
+ */
327
+ async generateWithOpenAI(prompt) {
328
+ if (!this.openai) {
329
+ throw new Error("OpenAI client not initialized");
330
+ }
331
+ const response = await this.openai.chat.completions.create({
332
+ model: "gpt-4-turbo-preview",
333
+ max_tokens: 4096,
334
+ temperature: 0.7,
335
+ messages: [
336
+ {
337
+ role: "user",
338
+ content: prompt
339
+ }
340
+ ],
341
+ response_format: { type: "json_object" }
342
+ });
343
+ const textContent = response.choices[0]?.message?.content || "";
344
+ if (!textContent) {
345
+ throw new Error("Failed to get response from OpenAI");
346
+ }
347
+ return JSON.parse(textContent);
348
+ }
349
+ /**
350
+ * Build prompt for Claude API
351
+ */
352
+ buildPrompt(productInfo, topic) {
353
+ return `You are an expert SEO content writer. Generate a comprehensive blog post about: "${topic}"
354
+
355
+ Product context:
356
+ - Name: ${productInfo.name}
357
+ - Tagline: ${productInfo.tagline || ""}
358
+ - Category: ${productInfo.category}
359
+ - Features: ${productInfo.features.join(", ")}
360
+ - Pricing: ${productInfo.pricingModel || "Not specified"}
361
+ ${productInfo.useCases ? `- Use cases: ${productInfo.useCases.join(", ")}` : ""}
362
+
363
+ IMPORTANT INSTRUCTIONS:
364
+ 1. Write for users searching on Google and being recommended by AI assistants (Claude, ChatGPT)
365
+ 2. Focus on being helpful, not promotional
366
+ 3. Include comparisons with alternatives when relevant
367
+ 4. Use natural language, avoid keyword stuffing
368
+ 5. Make it comprehensive (1000-1500 words worth of content)
369
+ 6. Structure with clear sections (intro, 3-5 main sections, conclusion)
370
+ 7. Be factual - do NOT invent statistics or make false claims
371
+
372
+ Output ONLY valid JSON in this exact format (no markdown, no code blocks):
373
+ {
374
+ "metadata": {
375
+ "title": "SEO-optimized title (under 60 chars)",
376
+ "description": "Meta description (under 160 chars)",
377
+ "keywords": ["keyword1", "keyword2", "keyword3"],
378
+ "category": "${productInfo.category}"
379
+ },
380
+ "content": {
381
+ "intro": "Engaging introduction paragraph in markdown format",
382
+ "sections": [
383
+ {
384
+ "heading": "Section title",
385
+ "level": 2,
386
+ "content": "Section content in markdown format",
387
+ "type": "text"
388
+ }
389
+ ],
390
+ "conclusion": "Conclusion paragraph in markdown",
391
+ "cta": {
392
+ "text": "Try ${productInfo.name}",
393
+ "url": "${productInfo.websiteUrl || "/signup"}"
394
+ }
395
+ }
396
+ }`;
397
+ }
398
+ /**
399
+ * Generate Schema.org structured data
400
+ */
401
+ generateSchemaOrg(metadata, productInfo) {
402
+ return {
403
+ "@context": "https://schema.org",
404
+ "@type": "BlogPosting",
405
+ headline: metadata.title,
406
+ description: metadata.description,
407
+ author: {
408
+ "@type": "Organization",
409
+ name: productInfo.name,
410
+ url: productInfo.websiteUrl
411
+ },
412
+ datePublished: metadata.datePublished,
413
+ publisher: {
414
+ "@type": "Organization",
415
+ name: productInfo.name
416
+ },
417
+ keywords: metadata.keywords.join(", "),
418
+ articleSection: metadata.category
419
+ };
420
+ }
421
+ /**
422
+ * Calculate SEO score
423
+ */
424
+ async calculateSEOScore(content) {
425
+ let score = 100;
426
+ const suggestions = [];
427
+ if (content.metadata.title.length > 60) {
428
+ score -= 10;
429
+ suggestions.push("Title is too long (should be under 60 chars)");
430
+ }
431
+ if (content.metadata.description.length > 160) {
432
+ score -= 10;
433
+ suggestions.push("Meta description is too long (should be under 160 chars)");
434
+ }
435
+ if (content.metadata.keywords.length < 3) {
436
+ score -= 5;
437
+ suggestions.push("Add more keywords (at least 3)");
438
+ }
439
+ if (content.content.sections.length < 3) {
440
+ score -= 10;
441
+ suggestions.push("Add more sections for better structure (at least 3)");
442
+ }
443
+ return {
444
+ score: Math.max(0, score),
445
+ suggestions
446
+ };
447
+ }
448
+ /**
449
+ * Generate topic suggestions
450
+ */
451
+ async generateTopics(productInfo, count) {
452
+ const prompt = `Generate ${count} SEO-friendly blog post topics for a product called "${productInfo.name}" in the ${productInfo.category} category.
453
+
454
+ Product description: ${productInfo.description}
455
+ Features: ${productInfo.features.join(", ")}
456
+
457
+ Requirements:
458
+ - Topics should be helpful for potential customers
459
+ - Focus on solving problems or answering questions
460
+ - Include comparisons, guides, and use cases
461
+ - Optimize for search engines and AI recommendations
462
+
463
+ Output ONLY a JSON array of topic strings, no markdown:
464
+ ["Topic 1", "Topic 2", "Topic 3"]`;
465
+ try {
466
+ if (this.provider === "anthropic" && this.anthropic) {
467
+ const response = await this.anthropic.messages.create({
468
+ model: "claude-3-5-sonnet-20241022",
469
+ max_tokens: 1024,
470
+ messages: [{ role: "user", content: prompt }]
471
+ });
472
+ const textContent = response.content[0].type === "text" ? response.content[0].text : "";
473
+ const jsonMatch = textContent.match(/\[[\s\S]*\]/);
474
+ if (jsonMatch) {
475
+ return JSON.parse(jsonMatch[0]);
476
+ }
477
+ } else if (this.provider === "openai" && this.openai) {
478
+ const response = await this.openai.chat.completions.create({
479
+ model: "gpt-4-turbo-preview",
480
+ max_tokens: 1024,
481
+ messages: [{ role: "user", content: prompt }],
482
+ response_format: { type: "json_object" }
483
+ });
484
+ const textContent = response.choices[0]?.message?.content || "";
485
+ if (textContent) {
486
+ const data = JSON.parse(textContent);
487
+ return data.topics || data;
488
+ }
489
+ }
490
+ } catch (error) {
491
+ console.warn("Failed to generate topics with AI, using fallback");
492
+ }
493
+ return [
494
+ `Best ${productInfo.category} software ${(/* @__PURE__ */ new Date()).getFullYear()}`,
495
+ `How to choose ${productInfo.category} solution`,
496
+ `${productInfo.name} vs alternatives: Complete comparison`
497
+ ];
498
+ }
499
+ /**
500
+ * Update sitemap.xml
501
+ */
502
+ async updateSitemap(projectPath, blogDir, posts) {
503
+ const sitemapPath = path2.join(projectPath, "sitemap.xml");
504
+ const urls = posts.map((post) => {
505
+ return ` <url>
506
+ <loc>${post.slug}/</loc>
507
+ <lastmod>${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}</lastmod>
508
+ <changefreq>weekly</changefreq>
509
+ <priority>0.8</priority>
510
+ </url>`;
511
+ }).join("\n");
512
+ const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
513
+ <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
514
+ ${urls}
515
+ </urlset>`;
516
+ await fs2.writeFile(sitemapPath, sitemap, "utf-8");
517
+ console.log(`
518
+ \u2713 Updated sitemap.xml`);
519
+ }
520
+ };
521
+
522
+ export {
523
+ __require,
524
+ AdapterRegistry,
525
+ HTMLAdapter,
526
+ ContentGenerator
527
+ };