aeo.js 0.0.1 → 0.0.3

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.
Files changed (70) hide show
  1. package/README.md +303 -6
  2. package/dist/angular.d.mts +29 -0
  3. package/dist/angular.d.ts +29 -0
  4. package/dist/angular.js +1314 -0
  5. package/dist/angular.js.map +1 -0
  6. package/dist/angular.mjs +1310 -0
  7. package/dist/angular.mjs.map +1 -0
  8. package/dist/astro.d.mts +15 -0
  9. package/dist/astro.d.ts +15 -0
  10. package/dist/astro.js +1421 -0
  11. package/dist/astro.js.map +1 -0
  12. package/dist/astro.mjs +1414 -0
  13. package/dist/astro.mjs.map +1 -0
  14. package/dist/cli.d.mts +1 -0
  15. package/dist/cli.d.ts +1 -0
  16. package/dist/cli.js +1880 -2
  17. package/dist/cli.js.map +1 -0
  18. package/dist/cli.mjs +1878 -0
  19. package/dist/cli.mjs.map +1 -0
  20. package/dist/index.d.mts +191 -0
  21. package/dist/index.d.ts +191 -1
  22. package/dist/index.js +1829 -1
  23. package/dist/index.js.map +1 -0
  24. package/dist/index.mjs +1801 -1
  25. package/dist/index.mjs.map +1 -0
  26. package/dist/next.d.mts +18 -0
  27. package/dist/next.d.ts +18 -0
  28. package/dist/next.js +1302 -0
  29. package/dist/next.js.map +1 -0
  30. package/dist/next.mjs +1295 -0
  31. package/dist/next.mjs.map +1 -0
  32. package/dist/nuxt.d.mts +13 -0
  33. package/dist/nuxt.d.ts +13 -0
  34. package/dist/nuxt.js +1344 -0
  35. package/dist/nuxt.js.map +1 -0
  36. package/dist/nuxt.mjs +1337 -0
  37. package/dist/nuxt.mjs.map +1 -0
  38. package/dist/react.d.mts +10 -0
  39. package/dist/react.d.ts +10 -0
  40. package/dist/react.js +1023 -0
  41. package/dist/react.js.map +1 -0
  42. package/dist/react.mjs +1020 -0
  43. package/dist/react.mjs.map +1 -0
  44. package/dist/types-Cn_Qbkmg.d.mts +166 -0
  45. package/dist/types-Cn_Qbkmg.d.ts +166 -0
  46. package/dist/vite.d.mts +5 -0
  47. package/dist/vite.d.ts +5 -0
  48. package/dist/vite.js +1370 -0
  49. package/dist/vite.js.map +1 -0
  50. package/dist/vite.mjs +1366 -0
  51. package/dist/vite.mjs.map +1 -0
  52. package/dist/vue.d.mts +19 -0
  53. package/dist/vue.d.ts +19 -0
  54. package/dist/vue.js +1078 -0
  55. package/dist/vue.js.map +1 -0
  56. package/dist/vue.mjs +1072 -0
  57. package/dist/vue.mjs.map +1 -0
  58. package/dist/webpack.d.mts +11 -0
  59. package/dist/webpack.d.ts +11 -0
  60. package/dist/webpack.js +1179 -0
  61. package/dist/webpack.js.map +1 -0
  62. package/dist/webpack.mjs +1173 -0
  63. package/dist/webpack.mjs.map +1 -0
  64. package/dist/widget.d.mts +37 -0
  65. package/dist/widget.d.ts +37 -0
  66. package/dist/widget.js +1004 -0
  67. package/dist/widget.js.map +1 -0
  68. package/dist/widget.mjs +1001 -0
  69. package/dist/widget.mjs.map +1 -0
  70. package/package.json +110 -10
@@ -0,0 +1,1179 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var fs = require('fs');
6
+ var path = require('path');
7
+ require('minimatch');
8
+ var crypto = require('crypto');
9
+
10
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
11
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
12
+ }) : x)(function(x) {
13
+ if (typeof require !== "undefined") return require.apply(this, arguments);
14
+ throw Error('Dynamic require of "' + x + '" is not supported');
15
+ });
16
+
17
+ // src/core/robots.ts
18
+ var AI_CRAWLERS = [
19
+ "GPTBot",
20
+ "OAI-SearchBot",
21
+ "ChatGPT-User",
22
+ "ClaudeBot",
23
+ "Claude-Web",
24
+ "anthropic-ai",
25
+ "PerplexityBot",
26
+ "Google-Extended",
27
+ "Gemini-Deep-Research",
28
+ "Bingbot",
29
+ "FacebookBot",
30
+ "meta-externalagent",
31
+ "Amazonbot",
32
+ "Applebot",
33
+ "DeepSeekBot",
34
+ "Bytespider",
35
+ "cohere-ai",
36
+ "CCBot",
37
+ "DiffBot",
38
+ "YouBot",
39
+ "FirecrawlAgent",
40
+ "Crawl4AI",
41
+ "BraveBot",
42
+ "SemrushBot",
43
+ "AhrefsBot",
44
+ "MJ12bot",
45
+ "DotBot",
46
+ "DataForSeoBot",
47
+ "Screaming Frog SEO Spider",
48
+ "SEOkicks",
49
+ "SEMrushBot",
50
+ "BLEXBot",
51
+ "Yandex",
52
+ "Baiduspider",
53
+ "Sogou",
54
+ "Exabot",
55
+ "facebookexternalhit",
56
+ "LinkedInBot",
57
+ "WhatsApp",
58
+ "Slackbot",
59
+ "TwitterBot",
60
+ "TelegramBot",
61
+ "Discordbot",
62
+ "PinterestBot",
63
+ "TumblrBot",
64
+ "ViberBot",
65
+ "SkypeUriPreview",
66
+ "redditbot",
67
+ "Snapchat",
68
+ "TikTok"
69
+ ];
70
+ function generateRobotsTxt(config) {
71
+ const lines = [
72
+ "# robots.txt generated by aeo.js",
73
+ "# Allow AI crawlers to index this site",
74
+ "",
75
+ "# Traditional search engines",
76
+ "User-agent: Googlebot",
77
+ "Allow: /",
78
+ "",
79
+ "User-agent: Bingbot",
80
+ "Allow: /",
81
+ "",
82
+ "# AI crawlers and answer engines"
83
+ ];
84
+ for (const crawler of AI_CRAWLERS) {
85
+ lines.push(`User-agent: ${crawler}`);
86
+ lines.push("Allow: /");
87
+ lines.push("");
88
+ }
89
+ lines.push("# Default for all other bots");
90
+ lines.push("User-agent: *");
91
+ lines.push("Allow: /");
92
+ lines.push("");
93
+ if (config.url) {
94
+ lines.push(`Sitemap: ${config.url}/sitemap.xml`);
95
+ }
96
+ lines.push("");
97
+ lines.push("# AEO (Answer Engine Optimization) files");
98
+ lines.push("# These help LLMs understand your content better");
99
+ lines.push(`# ${config.url}/llms.txt`);
100
+ lines.push(`# ${config.url}/llms-full.txt`);
101
+ lines.push(`# ${config.url}/docs.json`);
102
+ lines.push(`# ${config.url}/ai-index.json`);
103
+ return lines.join("\n");
104
+ }
105
+
106
+ // src/core/detect.ts
107
+ function detectFramework(projectRoot = process.cwd()) {
108
+ const packageJson = readPackageJson(projectRoot);
109
+ const dependencies = {
110
+ ...packageJson.dependencies,
111
+ ...packageJson.devDependencies
112
+ };
113
+ if (dependencies["next"]) {
114
+ return {
115
+ framework: "next",
116
+ contentDir: "app",
117
+ outDir: "out"
118
+ };
119
+ }
120
+ if (dependencies["nuxt"] || dependencies["@nuxt/kit"]) {
121
+ return {
122
+ framework: "nuxt",
123
+ contentDir: "content",
124
+ outDir: ".output/public"
125
+ };
126
+ }
127
+ if (dependencies["astro"] || dependencies["@astrojs/astro"]) {
128
+ return {
129
+ framework: "astro",
130
+ contentDir: "src/content",
131
+ outDir: "dist"
132
+ };
133
+ }
134
+ if (dependencies["@remix-run/dev"]) {
135
+ return {
136
+ framework: "remix",
137
+ contentDir: "app",
138
+ outDir: "build/client"
139
+ };
140
+ }
141
+ if (dependencies["@sveltejs/kit"]) {
142
+ return {
143
+ framework: "sveltekit",
144
+ contentDir: "src",
145
+ outDir: "build"
146
+ };
147
+ }
148
+ if (dependencies["@angular/core"]) {
149
+ return {
150
+ framework: "angular",
151
+ contentDir: "src",
152
+ outDir: "dist"
153
+ };
154
+ }
155
+ if (dependencies["@docusaurus/core"]) {
156
+ return {
157
+ framework: "docusaurus",
158
+ contentDir: "docs",
159
+ outDir: "build"
160
+ };
161
+ }
162
+ if (dependencies["vite"]) {
163
+ return {
164
+ framework: "vite",
165
+ contentDir: "src",
166
+ outDir: "dist"
167
+ };
168
+ }
169
+ return {
170
+ framework: "unknown",
171
+ contentDir: "src",
172
+ outDir: "dist"
173
+ };
174
+ }
175
+ function resolveConfig(config = {}) {
176
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M;
177
+ const frameworkInfo = detectFramework();
178
+ return {
179
+ title: config.title || "My Site",
180
+ description: config.description || "",
181
+ url: config.url || "https://example.com",
182
+ contentDir: config.contentDir || frameworkInfo.contentDir,
183
+ outDir: config.outDir || frameworkInfo.outDir,
184
+ pages: config.pages || [],
185
+ generators: {
186
+ robotsTxt: ((_a = config.generators) == null ? void 0 : _a.robotsTxt) !== false,
187
+ llmsTxt: ((_b = config.generators) == null ? void 0 : _b.llmsTxt) !== false,
188
+ llmsFullTxt: ((_c = config.generators) == null ? void 0 : _c.llmsFullTxt) !== false,
189
+ rawMarkdown: ((_d = config.generators) == null ? void 0 : _d.rawMarkdown) !== false,
190
+ manifest: ((_e = config.generators) == null ? void 0 : _e.manifest) !== false,
191
+ sitemap: ((_f = config.generators) == null ? void 0 : _f.sitemap) !== false,
192
+ aiIndex: ((_g = config.generators) == null ? void 0 : _g.aiIndex) !== false,
193
+ schema: ((_h = config.generators) == null ? void 0 : _h.schema) !== false
194
+ },
195
+ robots: {
196
+ allow: ((_i = config.robots) == null ? void 0 : _i.allow) || ["/"],
197
+ disallow: ((_j = config.robots) == null ? void 0 : _j.disallow) || [],
198
+ crawlDelay: ((_k = config.robots) == null ? void 0 : _k.crawlDelay) || 0,
199
+ sitemap: ((_l = config.robots) == null ? void 0 : _l.sitemap) || ""
200
+ },
201
+ schema: {
202
+ enabled: ((_m = config.schema) == null ? void 0 : _m.enabled) !== false,
203
+ organization: {
204
+ name: ((_o = (_n = config.schema) == null ? void 0 : _n.organization) == null ? void 0 : _o.name) || config.title || "My Site",
205
+ url: ((_q = (_p = config.schema) == null ? void 0 : _p.organization) == null ? void 0 : _q.url) || config.url || "https://example.com",
206
+ logo: ((_s = (_r = config.schema) == null ? void 0 : _r.organization) == null ? void 0 : _s.logo) || "",
207
+ sameAs: ((_u = (_t = config.schema) == null ? void 0 : _t.organization) == null ? void 0 : _u.sameAs) || []
208
+ },
209
+ defaultType: ((_v = config.schema) == null ? void 0 : _v.defaultType) || "WebPage"
210
+ },
211
+ og: {
212
+ enabled: ((_w = config.og) == null ? void 0 : _w.enabled) !== false,
213
+ image: ((_x = config.og) == null ? void 0 : _x.image) || "",
214
+ twitterHandle: ((_y = config.og) == null ? void 0 : _y.twitterHandle) || "",
215
+ type: ((_z = config.og) == null ? void 0 : _z.type) || "website"
216
+ },
217
+ widget: {
218
+ enabled: ((_A = config.widget) == null ? void 0 : _A.enabled) !== false,
219
+ position: ((_B = config.widget) == null ? void 0 : _B.position) || "bottom-right",
220
+ theme: {
221
+ background: ((_D = (_C = config.widget) == null ? void 0 : _C.theme) == null ? void 0 : _D.background) || "rgba(18, 18, 24, 0.9)",
222
+ text: ((_F = (_E = config.widget) == null ? void 0 : _E.theme) == null ? void 0 : _F.text) || "#C0C0C5",
223
+ accent: ((_H = (_G = config.widget) == null ? void 0 : _G.theme) == null ? void 0 : _H.accent) || "#E8E8EA",
224
+ badge: ((_J = (_I = config.widget) == null ? void 0 : _I.theme) == null ? void 0 : _J.badge) || "#4ADE80"
225
+ },
226
+ humanLabel: ((_K = config.widget) == null ? void 0 : _K.humanLabel) || "Human",
227
+ aiLabel: ((_L = config.widget) == null ? void 0 : _L.aiLabel) || "AI",
228
+ showBadge: ((_M = config.widget) == null ? void 0 : _M.showBadge) !== false
229
+ }
230
+ };
231
+ }
232
+ function parseFrontmatter(content) {
233
+ const frontmatterMatch = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)/);
234
+ if (frontmatterMatch) {
235
+ const frontmatterStr = frontmatterMatch[1];
236
+ const contentWithoutFrontmatter = frontmatterMatch[2];
237
+ const frontmatter = {};
238
+ const lines = frontmatterStr.split("\n");
239
+ for (const line of lines) {
240
+ const [key, ...valueParts] = line.split(":");
241
+ if (key && valueParts.length > 0) {
242
+ const value = valueParts.join(":").trim();
243
+ frontmatter[key.trim()] = value.replace(/^["']|["']$/g, "");
244
+ }
245
+ }
246
+ return { frontmatter, content: contentWithoutFrontmatter };
247
+ }
248
+ return { frontmatter: {}, content };
249
+ }
250
+ function bumpHeadings(content, levels = 1) {
251
+ return content.replace(/^(#{1,6})\s/gm, (match, hashes) => {
252
+ const newLevel = Math.min(hashes.length + levels, 6);
253
+ return "#".repeat(newLevel) + " ";
254
+ });
255
+ }
256
+ function extractTitle(content) {
257
+ const h1Match = content.match(/^#\s+(.+)$/m);
258
+ if (h1Match) return h1Match[1];
259
+ const h2Match = content.match(/^##\s+(.+)$/m);
260
+ if (h2Match) return h2Match[1];
261
+ const firstLine = content.split("\n")[0];
262
+ return firstLine.slice(0, 100);
263
+ }
264
+ function readPackageJson(projectRoot = process.cwd()) {
265
+ const packageJsonPath = path.join(projectRoot, "package.json");
266
+ if (!fs.existsSync(packageJsonPath)) {
267
+ return {};
268
+ }
269
+ try {
270
+ const content = fs.readFileSync(packageJsonPath, "utf-8");
271
+ return JSON.parse(content);
272
+ } catch {
273
+ return {};
274
+ }
275
+ }
276
+
277
+ // src/core/llms-txt.ts
278
+ function collectMarkdownFiles(dir, base = dir) {
279
+ const files = [];
280
+ try {
281
+ const entries = fs.readdirSync(dir);
282
+ for (const entry of entries) {
283
+ const fullPath = path.join(dir, entry);
284
+ const stat = fs.statSync(fullPath);
285
+ if (stat.isDirectory() && !entry.startsWith(".") && entry !== "node_modules") {
286
+ files.push(...collectMarkdownFiles(fullPath, base));
287
+ } else if (stat.isFile() && (path.extname(entry) === ".md" || path.extname(entry) === ".mdx")) {
288
+ const content = fs.readFileSync(fullPath, "utf-8");
289
+ const { frontmatter, content: mainContent } = parseFrontmatter(content);
290
+ const relativePath = path.relative(base, fullPath);
291
+ files.push({
292
+ path: relativePath,
293
+ content: mainContent,
294
+ title: frontmatter.title || extractTitle(mainContent),
295
+ description: frontmatter.description,
296
+ frontmatter
297
+ });
298
+ }
299
+ }
300
+ } catch (error) {
301
+ console.warn(`Warning: Could not read directory ${dir}:`, error);
302
+ }
303
+ return files;
304
+ }
305
+ function generateLlmsTxt(config) {
306
+ const lines = [
307
+ `# ${config.title}`,
308
+ ""
309
+ ];
310
+ if (config.description) {
311
+ lines.push(`> ${config.description}`);
312
+ lines.push("");
313
+ }
314
+ lines.push("## About");
315
+ lines.push("");
316
+ lines.push("This file provides a structured overview of the documentation and content available on this site,");
317
+ lines.push("optimized for consumption by Large Language Models (LLMs) and AI assistants.");
318
+ lines.push("");
319
+ if (config.pages && config.pages.length > 0) {
320
+ lines.push("## Pages");
321
+ lines.push("");
322
+ for (const page of config.pages) {
323
+ const url = `${config.url}${page.pathname === "/" ? "" : page.pathname}`;
324
+ const title = page.title || page.pathname;
325
+ lines.push(`- [${title}](${url})`);
326
+ if (page.description) {
327
+ lines.push(` ${page.description}`);
328
+ }
329
+ }
330
+ lines.push("");
331
+ }
332
+ const markdownFiles = collectMarkdownFiles(config.contentDir);
333
+ if (markdownFiles.length > 0) {
334
+ lines.push("## Documentation");
335
+ lines.push("");
336
+ const grouped = {};
337
+ for (const file of markdownFiles) {
338
+ const dir = file.path.split("/")[0] || "root";
339
+ if (!grouped[dir]) grouped[dir] = [];
340
+ grouped[dir].push(file);
341
+ }
342
+ for (const [dir, files] of Object.entries(grouped)) {
343
+ lines.push(`### ${dir === "root" ? "Main Documentation" : dir}`);
344
+ lines.push("");
345
+ for (const file of files) {
346
+ const url = `${config.url}/${file.path.replace(/\.mdx?$/, "")}`;
347
+ lines.push(`- [${file.title}](${url})`);
348
+ if (file.description) {
349
+ lines.push(` ${file.description}`);
350
+ }
351
+ }
352
+ lines.push("");
353
+ }
354
+ }
355
+ lines.push("## Quick Links");
356
+ lines.push("");
357
+ lines.push(`- Full Documentation: ${config.url}/llms-full.txt`);
358
+ lines.push(`- Documentation Manifest: ${config.url}/docs.json`);
359
+ lines.push(`- AI-Optimized Index: ${config.url}/ai-index.json`);
360
+ lines.push(`- Sitemap: ${config.url}/sitemap.xml`);
361
+ lines.push("");
362
+ lines.push("## For LLMs");
363
+ lines.push("");
364
+ lines.push("To get the complete documentation in a single file, request:");
365
+ lines.push(`${config.url}/llms-full.txt`);
366
+ lines.push("");
367
+ lines.push("For structured access to individual pages with metadata:");
368
+ lines.push(`${config.url}/docs.json`);
369
+ lines.push("");
370
+ lines.push("For RAG (Retrieval Augmented Generation) systems:");
371
+ lines.push(`${config.url}/ai-index.json`);
372
+ lines.push("");
373
+ lines.push("---");
374
+ lines.push("Generated by aeo.js - Answer Engine Optimization for the modern web");
375
+ lines.push("Learn more at https://aeojs.org");
376
+ return lines.join("\n");
377
+ }
378
+ function collectAndConcatenateMarkdown(dir, base = dir) {
379
+ const sections = [];
380
+ try {
381
+ const entries = fs.readdirSync(dir).sort();
382
+ for (const entry of entries) {
383
+ const fullPath = path.join(dir, entry);
384
+ const stat = fs.statSync(fullPath);
385
+ if (stat.isDirectory() && !entry.startsWith(".") && entry !== "node_modules") {
386
+ const subSections = collectAndConcatenateMarkdown(fullPath, base);
387
+ if (subSections.length > 0) {
388
+ sections.push(...subSections);
389
+ }
390
+ } else if (stat.isFile() && (path.extname(entry) === ".md" || path.extname(entry) === ".mdx")) {
391
+ const content = fs.readFileSync(fullPath, "utf-8");
392
+ const { frontmatter, content: mainContent } = parseFrontmatter(content);
393
+ const relativePath = path.relative(base, fullPath);
394
+ const sectionLines = [
395
+ "---",
396
+ "",
397
+ `# ${frontmatter.title || relativePath}`,
398
+ "",
399
+ `Source: ${relativePath}`,
400
+ ""
401
+ ];
402
+ if (frontmatter.description) {
403
+ sectionLines.push(`> ${frontmatter.description}`);
404
+ sectionLines.push("");
405
+ }
406
+ const bumpedContent = bumpHeadings(mainContent, 1);
407
+ sectionLines.push(bumpedContent);
408
+ sectionLines.push("");
409
+ sections.push(sectionLines.join("\n"));
410
+ }
411
+ }
412
+ } catch (error) {
413
+ console.warn(`Warning: Could not read directory ${dir}:`, error);
414
+ }
415
+ return sections;
416
+ }
417
+ function generateLlmsFullTxt(config) {
418
+ const lines = [
419
+ `# ${config.title} - Complete Documentation`,
420
+ "",
421
+ `This file contains all documentation concatenated into a single file for easy consumption by LLMs.`,
422
+ ""
423
+ ];
424
+ if (config.description) {
425
+ lines.push(`> ${config.description}`);
426
+ lines.push("");
427
+ }
428
+ lines.push("## Table of Contents");
429
+ lines.push("");
430
+ lines.push("This document includes all content from this project.");
431
+ lines.push("Each section is separated by a horizontal rule (---) for easy parsing.");
432
+ lines.push("");
433
+ let hasContent = false;
434
+ if (config.pages && config.pages.length > 0) {
435
+ for (const page of config.pages) {
436
+ const url = `${config.url}${page.pathname === "/" ? "" : page.pathname}`;
437
+ const title = page.title || page.pathname;
438
+ const sectionLines = [
439
+ "---",
440
+ "",
441
+ `# ${title}`,
442
+ "",
443
+ `URL: ${url}`,
444
+ ""
445
+ ];
446
+ if (page.description) {
447
+ sectionLines.push(`> ${page.description}`);
448
+ sectionLines.push("");
449
+ }
450
+ if (page.content) {
451
+ sectionLines.push(page.content);
452
+ sectionLines.push("");
453
+ }
454
+ lines.push(sectionLines.join("\n"));
455
+ hasContent = true;
456
+ }
457
+ }
458
+ const sections = collectAndConcatenateMarkdown(config.contentDir);
459
+ if (sections.length > 0) {
460
+ lines.push(...sections);
461
+ hasContent = true;
462
+ }
463
+ if (!hasContent) {
464
+ lines.push("---");
465
+ lines.push("");
466
+ lines.push(`# ${config.title}`);
467
+ lines.push("");
468
+ lines.push(`URL: ${config.url}`);
469
+ lines.push("");
470
+ if (config.description) {
471
+ lines.push(config.description);
472
+ lines.push("");
473
+ }
474
+ }
475
+ lines.push("---");
476
+ lines.push("");
477
+ lines.push("## About This Document");
478
+ lines.push("");
479
+ lines.push("This concatenated documentation file is generated automatically by aeo.js");
480
+ lines.push("to make it easier for AI systems to understand the complete context of this project.");
481
+ lines.push("");
482
+ lines.push(`For a structured index, see: ${config.url}/llms.txt`);
483
+ lines.push(`For individual files, see: ${config.url}/docs.json`);
484
+ lines.push("");
485
+ lines.push("Generated by aeo.js - https://aeojs.org");
486
+ return lines.join("\n");
487
+ }
488
+ function ensureDir(path) {
489
+ fs.mkdirSync(path, { recursive: true });
490
+ }
491
+ function copyMarkdownFiles(config) {
492
+ const copiedFiles = [];
493
+ function copyRecursive(dir, base = config.contentDir) {
494
+ try {
495
+ const entries = fs.readdirSync(dir);
496
+ for (const entry of entries) {
497
+ const fullPath = path.join(dir, entry);
498
+ const stat = fs.statSync(fullPath);
499
+ if (stat.isDirectory() && !entry.startsWith(".") && entry !== "node_modules") {
500
+ copyRecursive(fullPath, base);
501
+ } else if (stat.isFile() && path.extname(entry) === ".md") {
502
+ const relativePath = path.relative(base, fullPath);
503
+ const destPath = path.join(config.outDir, relativePath);
504
+ ensureDir(path.dirname(destPath));
505
+ try {
506
+ fs.copyFileSync(fullPath, destPath);
507
+ copiedFiles.push({
508
+ source: fullPath,
509
+ destination: destPath
510
+ });
511
+ } catch (error) {
512
+ console.warn(`Warning: Could not copy ${fullPath}:`, error);
513
+ }
514
+ }
515
+ }
516
+ } catch (error) {
517
+ console.warn(`Warning: Could not read directory ${dir}:`, error);
518
+ }
519
+ }
520
+ copyRecursive(config.contentDir);
521
+ return copiedFiles;
522
+ }
523
+ function generatePageMarkdownFiles(config) {
524
+ const generated = [];
525
+ const pages = config.pages || [];
526
+ for (const page of pages) {
527
+ if (!page.content) continue;
528
+ const pageTitle = page.title || (page.pathname === "/" ? config.title : void 0);
529
+ let filename;
530
+ if (page.pathname === "/") {
531
+ filename = "index.md";
532
+ } else {
533
+ const clean = page.pathname.replace(/^\//, "").replace(/\/$/, "");
534
+ filename = clean.includes("/") ? `${clean}.md` : `${clean}.md`;
535
+ }
536
+ const destPath = path.join(config.outDir, filename);
537
+ const pageUrl = page.pathname === "/" ? config.url : `${config.url.replace(/\/$/, "")}${page.pathname}`;
538
+ const lines = [];
539
+ lines.push("---");
540
+ if (pageTitle) lines.push(`title: "${pageTitle}"`);
541
+ if (page.description) lines.push(`description: "${page.description}"`);
542
+ lines.push(`url: ${pageUrl}`);
543
+ lines.push(`source: ${pageUrl}`);
544
+ lines.push(`generated_by: aeo.js`);
545
+ lines.push("---", "");
546
+ if (pageTitle) {
547
+ lines.push(`# ${pageTitle}`, "");
548
+ }
549
+ if (page.description) {
550
+ lines.push(`${page.description}`, "");
551
+ }
552
+ if (page.content) {
553
+ lines.push(page.content);
554
+ }
555
+ const content = lines.join("\n");
556
+ ensureDir(path.dirname(destPath));
557
+ try {
558
+ fs.writeFileSync(destPath, content, "utf-8");
559
+ generated.push({ pathname: page.pathname, destination: destPath });
560
+ } catch {
561
+ }
562
+ }
563
+ return generated;
564
+ }
565
+ function collectManifestEntries(dir, config, base = dir) {
566
+ const entries = [];
567
+ try {
568
+ const files = fs.readdirSync(dir);
569
+ for (const file of files) {
570
+ const fullPath = path.join(dir, file);
571
+ const stat = fs.statSync(fullPath);
572
+ if (stat.isDirectory() && !file.startsWith(".") && file !== "node_modules") {
573
+ entries.push(...collectManifestEntries(fullPath, config, base));
574
+ } else if (stat.isFile() && (path.extname(file) === ".md" || path.extname(file) === ".mdx")) {
575
+ const content = fs.readFileSync(fullPath, "utf-8");
576
+ const { frontmatter, content: mainContent } = parseFrontmatter(content);
577
+ const relativePath = path.relative(base, fullPath);
578
+ const urlPath = relativePath.replace(/\.mdx?$/, "");
579
+ entries.push({
580
+ url: `${config.url}/${urlPath}`,
581
+ title: frontmatter.title || extractTitle(mainContent),
582
+ description: frontmatter.description,
583
+ lastModified: stat.mtime.toISOString()
584
+ });
585
+ }
586
+ }
587
+ } catch (error) {
588
+ console.warn(`Warning: Could not read directory ${dir}:`, error);
589
+ }
590
+ return entries;
591
+ }
592
+ function generateManifest(config) {
593
+ const entries = [];
594
+ if (config.pages && config.pages.length > 0) {
595
+ for (const page of config.pages) {
596
+ entries.push({
597
+ url: `${config.url}${page.pathname === "/" ? "" : page.pathname}`,
598
+ title: page.title || page.pathname,
599
+ description: page.description
600
+ });
601
+ }
602
+ }
603
+ entries.push(...collectManifestEntries(config.contentDir, config));
604
+ const manifest = {
605
+ version: "1.0",
606
+ generated: (/* @__PURE__ */ new Date()).toISOString(),
607
+ site: {
608
+ title: config.title,
609
+ description: config.description,
610
+ url: config.url
611
+ },
612
+ documents: entries.sort((a, b) => a.url.localeCompare(b.url)),
613
+ metadata: {
614
+ totalDocuments: entries.length,
615
+ generator: "aeo.js",
616
+ generatorUrl: "https://aeojs.org"
617
+ }
618
+ };
619
+ return JSON.stringify(manifest, null, 2);
620
+ }
621
+ function collectUrls(dir, config, base = dir) {
622
+ const urls = [];
623
+ try {
624
+ const entries = fs.readdirSync(dir);
625
+ for (const entry of entries) {
626
+ const fullPath = path.join(dir, entry);
627
+ const stat = fs.statSync(fullPath);
628
+ if (stat.isDirectory() && !entry.startsWith(".") && entry !== "node_modules") {
629
+ urls.push(...collectUrls(fullPath, config, base));
630
+ } else if (stat.isFile() && (path.extname(entry) === ".md" || path.extname(entry) === ".mdx" || path.extname(entry) === ".html")) {
631
+ const relativePath = path.relative(base, fullPath);
632
+ const urlPath = relativePath.replace(/\.(md|mdx|html)$/, "");
633
+ urls.push(`${config.url}/${urlPath}`);
634
+ }
635
+ }
636
+ } catch (error) {
637
+ console.warn(`Warning: Could not read directory ${dir}:`, error);
638
+ }
639
+ return urls;
640
+ }
641
+ function escapeXml(str) {
642
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
643
+ }
644
+ function generateSitemap(config) {
645
+ const urls = [];
646
+ if (config.pages && config.pages.length > 0) {
647
+ for (const page of config.pages) {
648
+ urls.push(`${config.url}${page.pathname === "/" ? "" : page.pathname}`);
649
+ }
650
+ }
651
+ if (config.contentDir) {
652
+ urls.push(...collectUrls(config.contentDir, config));
653
+ }
654
+ const lines = [
655
+ '<?xml version="1.0" encoding="UTF-8"?>',
656
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
657
+ ];
658
+ urls.push(config.url);
659
+ const uniqueUrls = [...new Set(urls)].sort();
660
+ for (const url of uniqueUrls) {
661
+ lines.push(" <url>");
662
+ lines.push(` <loc>${escapeXml(url)}</loc>`);
663
+ lines.push(` <lastmod>${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}</lastmod>`);
664
+ lines.push(" <changefreq>weekly</changefreq>");
665
+ lines.push(" <priority>0.8</priority>");
666
+ lines.push(" </url>");
667
+ }
668
+ lines.push("</urlset>");
669
+ return lines.join("\n");
670
+ }
671
+ function extractKeywords(content) {
672
+ const words = content.toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter((word) => word.length > 3);
673
+ const wordCount = {};
674
+ for (const word of words) {
675
+ wordCount[word] = (wordCount[word] || 0) + 1;
676
+ }
677
+ return Object.entries(wordCount).sort((a, b) => b[1] - a[1]).slice(0, 10).map(([word]) => word);
678
+ }
679
+ function chunkContent(content, maxLength = 2e3) {
680
+ const chunks = [];
681
+ const paragraphs = content.split("\n\n");
682
+ let currentChunk = "";
683
+ for (const paragraph of paragraphs) {
684
+ if (currentChunk.length + paragraph.length > maxLength && currentChunk.length > 0) {
685
+ chunks.push(currentChunk.trim());
686
+ currentChunk = "";
687
+ }
688
+ currentChunk += paragraph + "\n\n";
689
+ }
690
+ if (currentChunk.trim()) {
691
+ chunks.push(currentChunk.trim());
692
+ }
693
+ return chunks;
694
+ }
695
+ function collectAIIndexEntries(dir, config, base = dir) {
696
+ const entries = [];
697
+ try {
698
+ const files = fs.readdirSync(dir);
699
+ for (const file of files) {
700
+ const fullPath = path.join(dir, file);
701
+ const stat = fs.statSync(fullPath);
702
+ if (stat.isDirectory() && !file.startsWith(".") && file !== "node_modules") {
703
+ entries.push(...collectAIIndexEntries(fullPath, config, base));
704
+ } else if (stat.isFile() && (path.extname(file) === ".md" || path.extname(file) === ".mdx")) {
705
+ const content = fs.readFileSync(fullPath, "utf-8");
706
+ const { frontmatter, content: mainContent } = parseFrontmatter(content);
707
+ const relativePath = path.relative(base, fullPath);
708
+ const urlPath = relativePath.replace(/\.mdx?$/, "");
709
+ const url = `${config.url}/${urlPath}`;
710
+ const chunks = chunkContent(mainContent);
711
+ const title = frontmatter.title || extractTitle(mainContent);
712
+ const keywords = extractKeywords(mainContent);
713
+ chunks.forEach((chunk, index) => {
714
+ const id = crypto.createHash("sha256").update(`${url}-${index}`).digest("hex").slice(0, 16);
715
+ entries.push({
716
+ id,
717
+ url,
718
+ title: chunks.length > 1 ? `${title} (Part ${index + 1})` : title,
719
+ content: chunk,
720
+ description: frontmatter.description,
721
+ keywords,
722
+ metadata: {
723
+ ...frontmatter,
724
+ chunkIndex: index,
725
+ totalChunks: chunks.length,
726
+ sourcePath: relativePath
727
+ }
728
+ });
729
+ });
730
+ }
731
+ }
732
+ } catch (error) {
733
+ console.warn(`Warning: Could not read directory ${dir}:`, error);
734
+ }
735
+ return entries;
736
+ }
737
+ function generateAIIndex(config) {
738
+ const entries = [];
739
+ if (config.pages && config.pages.length > 0) {
740
+ for (const page of config.pages) {
741
+ const url = `${config.url}${page.pathname === "/" ? "" : page.pathname}`;
742
+ const title = page.title || page.pathname;
743
+ const content = page.content || "";
744
+ if (content) {
745
+ const chunks = chunkContent(content);
746
+ const keywords = extractKeywords(content);
747
+ chunks.forEach((chunk, index2) => {
748
+ const id = crypto.createHash("sha256").update(`${url}-${index2}`).digest("hex").slice(0, 16);
749
+ entries.push({
750
+ id,
751
+ url,
752
+ title: chunks.length > 1 ? `${title} (Part ${index2 + 1})` : title,
753
+ content: chunk,
754
+ description: page.description,
755
+ keywords,
756
+ metadata: {
757
+ chunkIndex: index2,
758
+ totalChunks: chunks.length,
759
+ sourcePath: page.pathname
760
+ }
761
+ });
762
+ });
763
+ } else {
764
+ const id = crypto.createHash("sha256").update(url).digest("hex").slice(0, 16);
765
+ entries.push({
766
+ id,
767
+ url,
768
+ title,
769
+ content: page.description || title,
770
+ description: page.description,
771
+ keywords: []
772
+ });
773
+ }
774
+ }
775
+ }
776
+ entries.push(...collectAIIndexEntries(config.contentDir, config));
777
+ const index = {
778
+ version: "1.0",
779
+ generated: (/* @__PURE__ */ new Date()).toISOString(),
780
+ site: {
781
+ title: config.title,
782
+ description: config.description,
783
+ url: config.url
784
+ },
785
+ entries: entries.sort((a, b) => a.id.localeCompare(b.id)),
786
+ metadata: {
787
+ totalEntries: entries.length,
788
+ generator: "aeo.js",
789
+ generatorUrl: "https://aeojs.org",
790
+ embedding: {
791
+ recommended: "text-embedding-ada-002",
792
+ dimensions: 1536
793
+ }
794
+ }
795
+ };
796
+ return JSON.stringify(index, null, 2);
797
+ }
798
+
799
+ // src/core/schema.ts
800
+ function generateSchema(config) {
801
+ const output = generateSchemaObjects(config);
802
+ return JSON.stringify(output, null, 2);
803
+ }
804
+ function generateSchemaObjects(config) {
805
+ const siteSchemas = generateSiteSchemas(config);
806
+ const pageSchemas = {};
807
+ for (const page of config.pages) {
808
+ const schemas = generatePageSchemas(page, config);
809
+ if (schemas.length > 0) {
810
+ pageSchemas[page.pathname] = schemas;
811
+ }
812
+ }
813
+ return { site: siteSchemas, pages: pageSchemas };
814
+ }
815
+ function generateSiteSchemas(config) {
816
+ const schemas = [];
817
+ schemas.push({
818
+ "@context": "https://schema.org",
819
+ "@type": "WebSite",
820
+ name: config.title,
821
+ description: config.description || void 0,
822
+ url: config.url
823
+ });
824
+ const org = config.schema.organization;
825
+ if (org.name || org.sameAs.length > 0) {
826
+ const orgSchema = {
827
+ "@context": "https://schema.org",
828
+ "@type": "Organization",
829
+ name: org.name,
830
+ url: org.url
831
+ };
832
+ if (org.logo) orgSchema.logo = org.logo;
833
+ if (org.sameAs.length > 0) orgSchema.sameAs = org.sameAs;
834
+ schemas.push(orgSchema);
835
+ }
836
+ return schemas;
837
+ }
838
+ function generatePageSchemas(page, config) {
839
+ const schemas = [];
840
+ const pageUrl = page.pathname === "/" ? config.url : `${config.url.replace(/\/$/, "")}${page.pathname}`;
841
+ const faqItems = detectFaqPatterns(page.content || "");
842
+ if (faqItems.length > 0) {
843
+ schemas.push({
844
+ "@context": "https://schema.org",
845
+ "@type": "FAQPage",
846
+ mainEntity: faqItems.map(({ question, answer }) => ({
847
+ "@type": "Question",
848
+ name: question,
849
+ acceptedAnswer: {
850
+ "@type": "Answer",
851
+ text: answer
852
+ }
853
+ }))
854
+ });
855
+ }
856
+ const pageType = config.schema.defaultType;
857
+ const pageSchema = {
858
+ "@context": "https://schema.org",
859
+ "@type": pageType,
860
+ name: page.title || config.title,
861
+ url: pageUrl
862
+ };
863
+ if (page.description) pageSchema.description = page.description;
864
+ if (pageType === "Article") {
865
+ pageSchema.headline = page.title || config.title;
866
+ pageSchema.author = {
867
+ "@type": "Organization",
868
+ name: config.schema.organization.name
869
+ };
870
+ }
871
+ schemas.push(pageSchema);
872
+ if (page.pathname !== "/") {
873
+ const breadcrumbs = generateBreadcrumbs(page.pathname, config);
874
+ if (breadcrumbs.length > 1) {
875
+ schemas.push({
876
+ "@context": "https://schema.org",
877
+ "@type": "BreadcrumbList",
878
+ itemListElement: breadcrumbs.map((crumb, i) => ({
879
+ "@type": "ListItem",
880
+ position: i + 1,
881
+ name: crumb.name,
882
+ item: crumb.url
883
+ }))
884
+ });
885
+ }
886
+ }
887
+ return schemas;
888
+ }
889
+ function generateBreadcrumbs(pathname, config) {
890
+ const baseUrl = config.url.replace(/\/$/, "");
891
+ const parts = pathname.split("/").filter(Boolean);
892
+ const crumbs = [
893
+ { name: "Home", url: baseUrl + "/" }
894
+ ];
895
+ let currentPath = "";
896
+ for (const part of parts) {
897
+ currentPath += "/" + part;
898
+ crumbs.push({
899
+ name: part.charAt(0).toUpperCase() + part.slice(1).replace(/-/g, " "),
900
+ url: baseUrl + currentPath
901
+ });
902
+ }
903
+ return crumbs;
904
+ }
905
+ function detectFaqPatterns(content) {
906
+ const items = [];
907
+ const lines = content.split("\n");
908
+ for (let i = 0; i < lines.length; i++) {
909
+ const line = lines[i].trim();
910
+ const headingMatch = line.match(/^#{1,6}\s+(.+\?)\s*$/);
911
+ if (headingMatch) {
912
+ const answerLines = [];
913
+ for (let j = i + 1; j < lines.length; j++) {
914
+ const nextLine = lines[j].trim();
915
+ if (!nextLine) {
916
+ if (answerLines.length > 0) break;
917
+ continue;
918
+ }
919
+ if (/^#{1,6}\s/.test(nextLine)) break;
920
+ answerLines.push(nextLine);
921
+ }
922
+ if (answerLines.length > 0) {
923
+ items.push({
924
+ question: headingMatch[1],
925
+ answer: answerLines.join(" ").slice(0, 500)
926
+ });
927
+ }
928
+ }
929
+ }
930
+ return items;
931
+ }
932
+ async function generateAEOFiles(configOrRoot, maybeConfig) {
933
+ var _a;
934
+ let config;
935
+ if (typeof configOrRoot === "string") {
936
+ config = resolveConfig({ ...maybeConfig, outDir: configOrRoot });
937
+ } else if (configOrRoot && typeof configOrRoot === "object" && "generators" in configOrRoot && typeof ((_a = configOrRoot.generators) == null ? void 0 : _a.robotsTxt) === "boolean") {
938
+ config = configOrRoot;
939
+ } else {
940
+ config = resolveConfig(configOrRoot);
941
+ }
942
+ const outDir = config.outDir;
943
+ const files = [];
944
+ const errors = [];
945
+ if (!fs.existsSync(outDir)) {
946
+ fs.mkdirSync(outDir, { recursive: true });
947
+ }
948
+ if (config.generators.robotsTxt) {
949
+ try {
950
+ const content = generateRobotsTxt(config);
951
+ fs.writeFileSync(path.join(outDir, "robots.txt"), content, "utf-8");
952
+ files.push("robots.txt");
953
+ } catch (e) {
954
+ errors.push(`robots.txt: ${e.message}`);
955
+ }
956
+ }
957
+ if (config.generators.llmsTxt) {
958
+ try {
959
+ const content = generateLlmsTxt(config);
960
+ fs.writeFileSync(path.join(outDir, "llms.txt"), content, "utf-8");
961
+ files.push("llms.txt");
962
+ } catch (e) {
963
+ errors.push(`llms.txt: ${e.message}`);
964
+ }
965
+ }
966
+ if (config.generators.llmsFullTxt) {
967
+ try {
968
+ const content = generateLlmsFullTxt(config);
969
+ fs.writeFileSync(path.join(outDir, "llms-full.txt"), content, "utf-8");
970
+ files.push("llms-full.txt");
971
+ } catch (e) {
972
+ errors.push(`llms-full.txt: ${e.message}`);
973
+ }
974
+ }
975
+ if (config.generators.rawMarkdown) {
976
+ try {
977
+ const generated = generatePageMarkdownFiles(config);
978
+ for (const f of generated) {
979
+ files.push(f.destination);
980
+ }
981
+ } catch (e) {
982
+ errors.push(`page-markdown: ${e.message}`);
983
+ }
984
+ try {
985
+ const copied = copyMarkdownFiles(config);
986
+ for (const f of copied) {
987
+ files.push(f.destination);
988
+ }
989
+ } catch (e) {
990
+ errors.push(`raw-markdown: ${e.message}`);
991
+ }
992
+ }
993
+ if (config.generators.manifest) {
994
+ try {
995
+ const content = generateManifest(config);
996
+ fs.writeFileSync(path.join(outDir, "docs.json"), content, "utf-8");
997
+ files.push("docs.json");
998
+ } catch (e) {
999
+ errors.push(`docs.json: ${e.message}`);
1000
+ }
1001
+ }
1002
+ if (config.generators.sitemap) {
1003
+ try {
1004
+ const content = generateSitemap(config);
1005
+ fs.writeFileSync(path.join(outDir, "sitemap.xml"), content, "utf-8");
1006
+ files.push("sitemap.xml");
1007
+ } catch (e) {
1008
+ errors.push(`sitemap.xml: ${e.message}`);
1009
+ }
1010
+ }
1011
+ if (config.generators.aiIndex) {
1012
+ try {
1013
+ const content = generateAIIndex(config);
1014
+ fs.writeFileSync(path.join(outDir, "ai-index.json"), content, "utf-8");
1015
+ files.push("ai-index.json");
1016
+ } catch (e) {
1017
+ errors.push(`ai-index.json: ${e.message}`);
1018
+ }
1019
+ }
1020
+ if (config.generators.schema && config.schema.enabled) {
1021
+ try {
1022
+ const content = generateSchema(config);
1023
+ fs.writeFileSync(path.join(outDir, "schema.json"), content, "utf-8");
1024
+ files.push("schema.json");
1025
+ } catch (e) {
1026
+ errors.push(`schema.json: ${e.message}`);
1027
+ }
1028
+ }
1029
+ return { files, errors };
1030
+ }
1031
+ function scanHtmlAssets(compilation) {
1032
+ var _a, _b, _c;
1033
+ const pages = [];
1034
+ try {
1035
+ for (const [name, source] of Object.entries(compilation.assets)) {
1036
+ if (name.endsWith(".html") && name !== "404.html" && name !== "500.html") {
1037
+ const html = ((_a = source.source) == null ? void 0 : _a.call(source).toString()) || "";
1038
+ const titleMatch = html.match(/<title>([^<]*)<\/title>/i);
1039
+ const descMatch = html.match(/<meta\s+name=["']description["']\s+content=["']([^"']*)["']/i);
1040
+ let pathname = "/" + name.replace(/\/?index\.html$/, "").replace(/\.html$/, "");
1041
+ pathname = pathname.replace(/\/+/g, "/") || "/";
1042
+ pages.push({
1043
+ pathname,
1044
+ title: (_c = (_b = titleMatch == null ? void 0 : titleMatch[1]) == null ? void 0 : _b.split("|")[0]) == null ? void 0 : _c.trim(),
1045
+ description: descMatch == null ? void 0 : descMatch[1]
1046
+ });
1047
+ }
1048
+ }
1049
+ } catch {
1050
+ }
1051
+ return pages;
1052
+ }
1053
+ var AeoWebpackPlugin = class {
1054
+ constructor(options = {}) {
1055
+ this.options = options;
1056
+ this.resolvedConfig = resolveConfig(options);
1057
+ }
1058
+ apply(compiler) {
1059
+ const pluginName = "AeoWebpackPlugin";
1060
+ compiler.hooks.beforeCompile.tapAsync(pluginName, async (_params, callback) => {
1061
+ var _a;
1062
+ this.resolvedConfig = resolveConfig({
1063
+ ...this.options,
1064
+ outDir: this.options.outDir || ((_a = compiler.options.output) == null ? void 0 : _a.path) || path.join(process.cwd(), "dist")
1065
+ });
1066
+ console.log("[aeo.js] Generating AEO files...");
1067
+ try {
1068
+ const result = await generateAEOFiles(this.resolvedConfig);
1069
+ if (result.files.length > 0) {
1070
+ console.log(`[aeo.js] Generated ${result.files.length} files:`);
1071
+ result.files.forEach((file) => {
1072
+ console.log(` - ${file}`);
1073
+ });
1074
+ }
1075
+ if (result.errors.length > 0) {
1076
+ console.error("[aeo.js] Errors during generation:");
1077
+ result.errors.forEach((error) => {
1078
+ console.error(` - ${error}`);
1079
+ });
1080
+ }
1081
+ } catch (error) {
1082
+ console.error("[aeo.js] Failed to generate AEO files:", error);
1083
+ }
1084
+ callback();
1085
+ });
1086
+ if (compiler.options.mode === "development" && this.resolvedConfig.contentDir) {
1087
+ const contentPath = path.join(process.cwd(), this.resolvedConfig.contentDir);
1088
+ compiler.hooks.afterCompile.tap(pluginName, (compilation) => {
1089
+ compilation.contextDependencies.add(contentPath);
1090
+ });
1091
+ compiler.hooks.watchRun.tapAsync(pluginName, async (comp, callback) => {
1092
+ const changedFiles = Array.from(comp.modifiedFiles || []);
1093
+ const hasMarkdownChanges = changedFiles.some((file) => file.endsWith(".md"));
1094
+ if (hasMarkdownChanges) {
1095
+ console.log("[aeo.js] Markdown files changed, regenerating...");
1096
+ try {
1097
+ const result = await generateAEOFiles(this.resolvedConfig);
1098
+ if (result.files.length > 0) {
1099
+ console.log(`[aeo.js] Regenerated ${result.files.length} files`);
1100
+ }
1101
+ if (result.errors.length > 0) {
1102
+ console.error("[aeo.js] Errors during regeneration:", result.errors);
1103
+ }
1104
+ } catch (error) {
1105
+ console.error("[aeo.js] Failed to regenerate AEO files:", error);
1106
+ }
1107
+ }
1108
+ callback();
1109
+ });
1110
+ }
1111
+ compiler.hooks.emit.tapAsync(pluginName, async (compilation, callback) => {
1112
+ const discoveredPages = scanHtmlAssets(compilation);
1113
+ if (discoveredPages.length > 0) {
1114
+ console.log(`[aeo.js] Discovered ${discoveredPages.length} pages from build output`);
1115
+ this.resolvedConfig = resolveConfig({
1116
+ ...this.options,
1117
+ outDir: this.resolvedConfig.outDir,
1118
+ pages: [...this.options.pages || [], ...discoveredPages]
1119
+ });
1120
+ try {
1121
+ await generateAEOFiles(this.resolvedConfig);
1122
+ } catch (error) {
1123
+ console.error("[aeo.js] Failed to regenerate with pages:", error);
1124
+ }
1125
+ }
1126
+ const aeoFiles = ["robots.txt", "llms.txt", "llms-full.txt", "sitemap.xml", "docs.json", "ai-index.json"];
1127
+ aeoFiles.forEach((filename) => {
1128
+ const filepath = path.join(this.resolvedConfig.outDir, filename);
1129
+ try {
1130
+ if (fs.existsSync(filepath)) {
1131
+ const content = fs.readFileSync(filepath);
1132
+ compilation.assets[filename] = {
1133
+ source: () => content,
1134
+ size: () => content.length
1135
+ };
1136
+ }
1137
+ } catch (error) {
1138
+ console.warn(`[aeo.js] Could not add ${filename} to assets:`, error);
1139
+ }
1140
+ });
1141
+ callback();
1142
+ });
1143
+ if (this.resolvedConfig.widget.enabled) {
1144
+ compiler.hooks.compilation.tap(pluginName, (compilation) => {
1145
+ try {
1146
+ const HtmlWebpackPlugin = __require("html-webpack-plugin");
1147
+ const hooks = HtmlWebpackPlugin.getHooks(compilation);
1148
+ hooks.beforeEmit.tapAsync(pluginName, (data, callback) => {
1149
+ const widgetScript = `
1150
+ <script type="module">
1151
+ import { AeoWidget } from 'aeo.js/widget';
1152
+ if (document.readyState === 'loading') {
1153
+ document.addEventListener('DOMContentLoaded', () => {
1154
+ new AeoWidget(${JSON.stringify(this.resolvedConfig.widget)});
1155
+ });
1156
+ } else {
1157
+ new AeoWidget(${JSON.stringify(this.resolvedConfig.widget)});
1158
+ }
1159
+ </script>`;
1160
+ data.html = data.html.replace("</body>", `${widgetScript}
1161
+ </body>`);
1162
+ callback(null, data);
1163
+ });
1164
+ } catch (error) {
1165
+ }
1166
+ });
1167
+ }
1168
+ }
1169
+ };
1170
+ function createAeoWebpackPlugin(options) {
1171
+ return new AeoWebpackPlugin(options);
1172
+ }
1173
+ var webpack_default = AeoWebpackPlugin;
1174
+
1175
+ exports.AeoWebpackPlugin = AeoWebpackPlugin;
1176
+ exports.createAeoWebpackPlugin = createAeoWebpackPlugin;
1177
+ exports.default = webpack_default;
1178
+ //# sourceMappingURL=webpack.js.map
1179
+ //# sourceMappingURL=webpack.js.map