@umituz/web-seo 2.0.21 → 2.1.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.
Files changed (106) hide show
  1. package/dist/domains/seo/components/JsonLd.d.ts +1 -9
  2. package/dist/domains/seo/components/JsonLd.js +22 -80
  3. package/dist/domains/seo/components/SEO.js +5 -35
  4. package/dist/domains/seo/components/index.d.ts +0 -5
  5. package/dist/domains/seo/components/index.js +0 -5
  6. package/dist/domains/seo/core/constants.d.ts +9 -0
  7. package/dist/domains/seo/core/constants.js +9 -0
  8. package/dist/domains/seo/core/deep-equal.d.ts +1 -0
  9. package/dist/domains/seo/core/deep-equal.js +21 -0
  10. package/dist/domains/seo/core/dom-queue.d.ts +3 -0
  11. package/dist/domains/seo/core/dom-queue.js +27 -0
  12. package/dist/domains/seo/core/escape.d.ts +2 -0
  13. package/dist/domains/seo/core/escape.js +31 -0
  14. package/dist/domains/seo/core/hash.d.ts +1 -0
  15. package/dist/domains/seo/core/hash.js +21 -0
  16. package/dist/domains/seo/core/init.d.ts +4 -2
  17. package/dist/domains/seo/core/init.js +27 -18
  18. package/dist/domains/seo/core/seo-strategies.d.ts +19 -0
  19. package/dist/domains/seo/core/seo-strategies.js +620 -0
  20. package/dist/domains/seo/core/seo-strategy.d.ts +16 -0
  21. package/dist/domains/seo/core/seo-strategy.js +1 -0
  22. package/dist/domains/seo/hooks/index.d.ts +0 -5
  23. package/dist/domains/seo/hooks/index.js +0 -5
  24. package/dist/domains/seo/hooks/useJsonLd.d.ts +2 -10
  25. package/dist/domains/seo/hooks/useJsonLd.js +23 -64
  26. package/dist/domains/seo/hooks/useSEO.js +2 -30
  27. package/dist/domains/seo/ssr/helmet.d.ts +18 -0
  28. package/dist/domains/seo/ssr/helmet.js +16 -0
  29. package/dist/domains/seo/ssr/index.d.ts +5 -0
  30. package/dist/domains/seo/ssr/index.js +3 -0
  31. package/dist/domains/seo/ssr/renderer.d.ts +1 -47
  32. package/dist/domains/seo/ssr/renderer.js +41 -296
  33. package/dist/domains/seo/ssr/serializer.d.ts +0 -66
  34. package/dist/domains/seo/ssr/serializer.js +21 -172
  35. package/dist/domains/seo/types/index.d.ts +0 -4
  36. package/dist/domains/seo/types/schema.d.ts +22 -3
  37. package/dist/domains/seo/types/schema.js +0 -3
  38. package/dist/domains/seo/utils/dom/dom-context.d.ts +2 -0
  39. package/dist/domains/seo/utils/dom/dom-context.js +48 -0
  40. package/dist/domains/seo/utils/dom/dom-mutator.d.ts +9 -0
  41. package/dist/domains/seo/utils/dom/dom-mutator.js +64 -0
  42. package/dist/domains/seo/utils/dom/index.d.ts +1 -0
  43. package/dist/domains/seo/utils/dom/index.js +1 -0
  44. package/dist/domains/seo/utils/index.d.ts +2 -8
  45. package/dist/domains/seo/utils/index.js +2 -12
  46. package/dist/domains/seo/utils/schema-generators/base.d.ts +14 -0
  47. package/dist/domains/seo/utils/schema-generators/base.js +39 -0
  48. package/dist/domains/seo/utils/schema-generators/factory.d.ts +20 -0
  49. package/dist/domains/seo/utils/schema-generators/factory.js +42 -0
  50. package/dist/domains/seo/utils/schema-generators/generators/article.d.ts +4 -0
  51. package/dist/domains/seo/utils/schema-generators/generators/article.js +39 -0
  52. package/dist/domains/seo/utils/schema-generators/generators/breadcrumb.d.ts +6 -0
  53. package/dist/domains/seo/utils/schema-generators/generators/breadcrumb.js +18 -0
  54. package/dist/domains/seo/utils/schema-generators/generators/course.d.ts +3 -0
  55. package/dist/domains/seo/utils/schema-generators/generators/course.js +70 -0
  56. package/dist/domains/seo/utils/schema-generators/generators/faq.d.ts +3 -0
  57. package/dist/domains/seo/utils/schema-generators/generators/faq.js +21 -0
  58. package/dist/domains/seo/utils/schema-generators/generators/local-business.d.ts +3 -0
  59. package/dist/domains/seo/utils/schema-generators/generators/local-business.js +45 -0
  60. package/dist/domains/seo/utils/schema-generators/generators/organization.d.ts +3 -0
  61. package/dist/domains/seo/utils/schema-generators/generators/organization.js +25 -0
  62. package/dist/domains/seo/utils/schema-generators/generators/person.d.ts +3 -0
  63. package/dist/domains/seo/utils/schema-generators/generators/person.js +27 -0
  64. package/dist/domains/seo/utils/schema-generators/generators/product.d.ts +3 -0
  65. package/dist/domains/seo/utils/schema-generators/generators/product.js +40 -0
  66. package/dist/domains/seo/utils/schema-generators/generators/video.d.ts +3 -0
  67. package/dist/domains/seo/utils/schema-generators/generators/video.js +23 -0
  68. package/dist/domains/seo/utils/schema-generators/generators/website.d.ts +3 -0
  69. package/dist/domains/seo/utils/schema-generators/generators/website.js +30 -0
  70. package/dist/domains/seo/utils/schema-generators/index.d.ts +13 -6
  71. package/dist/domains/seo/utils/schema-generators/index.js +11 -6
  72. package/dist/domains/seo/utils/schema-generators/types.d.ts +138 -0
  73. package/dist/domains/seo/utils/schema-generators/types.js +1 -0
  74. package/dist/domains/seo/utils/validation/hreflang-validator.d.ts +4 -0
  75. package/dist/domains/seo/utils/validation/hreflang-validator.js +10 -0
  76. package/dist/domains/seo/utils/validation/image-validator.d.ts +1 -0
  77. package/dist/domains/seo/utils/validation/image-validator.js +18 -0
  78. package/dist/domains/seo/utils/validation/index.d.ts +8 -6
  79. package/dist/domains/seo/utils/validation/index.js +8 -6
  80. package/dist/domains/seo/utils/validation/jsonld-validator.d.ts +2 -0
  81. package/dist/domains/seo/utils/validation/jsonld-validator.js +67 -0
  82. package/dist/domains/seo/utils/validation/language-code.d.ts +1 -0
  83. package/dist/domains/seo/utils/validation/language-code.js +2 -0
  84. package/dist/domains/seo/utils/validation/length-validator.d.ts +4 -0
  85. package/dist/domains/seo/utils/validation/length-validator.js +34 -0
  86. package/dist/domains/seo/utils/validation/seo-auditor.d.ts +3 -0
  87. package/dist/domains/seo/utils/validation/seo-auditor.js +120 -0
  88. package/dist/domains/seo/utils/validation/text-helpers.d.ts +1 -0
  89. package/dist/domains/seo/utils/validation/text-helpers.js +6 -0
  90. package/dist/domains/seo/utils/validation/url-validator.d.ts +2 -0
  91. package/dist/domains/seo/utils/validation/url-validator.js +20 -0
  92. package/dist/domains/seo/vite/index.d.ts +3 -7
  93. package/dist/domains/seo/vite/index.js +2 -6
  94. package/dist/domains/seo/vite/plugin.d.ts +1 -59
  95. package/dist/domains/seo/vite/plugin.js +26 -190
  96. package/dist/domains/seo/vite/presets.d.ts +8 -0
  97. package/dist/domains/seo/vite/presets.js +28 -0
  98. package/dist/domains/seo/vite/robots-generator.d.ts +6 -0
  99. package/dist/domains/seo/vite/robots-generator.js +33 -0
  100. package/dist/domains/seo/vite/sitemap-generator.d.ts +8 -0
  101. package/dist/domains/seo/vite/sitemap-generator.js +49 -0
  102. package/dist/domains/seo/vite/types.d.ts +20 -0
  103. package/dist/domains/seo/vite/types.js +1 -0
  104. package/dist/index.d.ts +8 -7
  105. package/dist/index.js +4 -12
  106. package/package.json +1 -1
@@ -0,0 +1,67 @@
1
+ const has = (obj, key) => {
2
+ const value = obj[key];
3
+ if (Array.isArray(value))
4
+ return value.length > 0;
5
+ return Boolean(value);
6
+ };
7
+ const articleRules = (jsonLd, errors) => {
8
+ if (!has(jsonLd, "headline"))
9
+ errors.push("Article must have a headline");
10
+ if (!has(jsonLd, "image"))
11
+ errors.push("Article must have an image");
12
+ if (!has(jsonLd, "datePublished"))
13
+ errors.push("Article must have datePublished");
14
+ if (!has(jsonLd, "author"))
15
+ errors.push("Article must have an author");
16
+ if (!has(jsonLd, "publisher"))
17
+ errors.push("Article must have a publisher");
18
+ };
19
+ const productRules = (jsonLd, errors) => {
20
+ if (!has(jsonLd, "name"))
21
+ errors.push("Product must have a name");
22
+ if (!has(jsonLd, "offers"))
23
+ errors.push("Product must have offers");
24
+ };
25
+ const organizationRules = (jsonLd, errors) => {
26
+ if (!has(jsonLd, "name"))
27
+ errors.push("Organization must have a name");
28
+ };
29
+ const breadcrumbRules = (jsonLd, errors) => {
30
+ if (!has(jsonLd, "itemListElement"))
31
+ errors.push("BreadcrumbList must have itemListElement");
32
+ };
33
+ const faqRules = (jsonLd, errors) => {
34
+ if (!has(jsonLd, "mainEntity"))
35
+ errors.push("FAQPage must have mainEntity");
36
+ };
37
+ const videoRules = (jsonLd, errors) => {
38
+ if (!has(jsonLd, "name"))
39
+ errors.push("Video must have a name");
40
+ if (!has(jsonLd, "thumbnailUrl"))
41
+ errors.push("Video must have thumbnailUrl");
42
+ if (!has(jsonLd, "uploadDate"))
43
+ errors.push("Video must have uploadDate");
44
+ };
45
+ const TYPE_RULES = {
46
+ Article: articleRules,
47
+ NewsArticle: articleRules,
48
+ BlogPosting: articleRules,
49
+ Product: productRules,
50
+ Organization: organizationRules,
51
+ BreadcrumbList: breadcrumbRules,
52
+ FAQPage: faqRules,
53
+ VideoObject: videoRules,
54
+ };
55
+ export const validateJsonLd = (jsonLd) => {
56
+ const errors = [];
57
+ const record = jsonLd;
58
+ if (!record["@context"])
59
+ errors.push('JSON-LD must have a "@context" property');
60
+ if (!record["@type"])
61
+ errors.push('JSON-LD must have a "@type" property');
62
+ const type = record["@type"];
63
+ if (typeof type === "string") {
64
+ TYPE_RULES[type]?.(record, errors);
65
+ }
66
+ return errors;
67
+ };
@@ -0,0 +1 @@
1
+ export declare const isValidLanguageCode: (code: string) => boolean;
@@ -0,0 +1,2 @@
1
+ const LANG_CODE_REGEX = /^(?:[a-z]{2,3}(?:-[A-Z]{2})?|x-default)$/;
2
+ export const isValidLanguageCode = (code) => LANG_CODE_REGEX.test(code);
@@ -0,0 +1,4 @@
1
+ export declare const validateTitleLength: (title: string) => string | null;
2
+ export declare const validateDescriptionLength: (description: string) => string | null;
3
+ export declare const truncateToTitle: (text: string) => string;
4
+ export declare const truncateToDescription: (text: string) => string;
@@ -0,0 +1,34 @@
1
+ import { DESCRIPTION_MAX_LENGTH, DESCRIPTION_MIN_LENGTH, TITLE_MAX_LENGTH, TITLE_MIN_LENGTH, } from "../../core/constants.js";
2
+ const ELLIPSIS = "...";
3
+ export const validateTitleLength = (title) => {
4
+ if (!title)
5
+ return "Title is required";
6
+ if (title.length < TITLE_MIN_LENGTH) {
7
+ return `Title is too short (${title.length} chars). Recommended: ${TITLE_MIN_LENGTH}-${TITLE_MAX_LENGTH} chars`;
8
+ }
9
+ if (title.length > TITLE_MAX_LENGTH) {
10
+ return `Title is too long (${title.length} chars). Recommended: ${TITLE_MIN_LENGTH}-${TITLE_MAX_LENGTH} chars`;
11
+ }
12
+ return null;
13
+ };
14
+ export const validateDescriptionLength = (description) => {
15
+ if (!description)
16
+ return "Description is required";
17
+ if (description.length < DESCRIPTION_MIN_LENGTH) {
18
+ return `Description is too short (${description.length} chars). Recommended: ${DESCRIPTION_MIN_LENGTH}-${DESCRIPTION_MAX_LENGTH} chars`;
19
+ }
20
+ if (description.length > DESCRIPTION_MAX_LENGTH) {
21
+ return `Description is too long (${description.length} chars). Recommended: ${DESCRIPTION_MIN_LENGTH}-${DESCRIPTION_MAX_LENGTH} chars`;
22
+ }
23
+ return null;
24
+ };
25
+ export const truncateToTitle = (text) => {
26
+ if (text.length <= TITLE_MAX_LENGTH)
27
+ return text;
28
+ return text.substring(0, TITLE_MAX_LENGTH - ELLIPSIS.length) + ELLIPSIS;
29
+ };
30
+ export const truncateToDescription = (text) => {
31
+ if (text.length <= DESCRIPTION_MAX_LENGTH)
32
+ return text;
33
+ return text.substring(0, DESCRIPTION_MAX_LENGTH - ELLIPSIS.length) + ELLIPSIS;
34
+ };
@@ -0,0 +1,3 @@
1
+ import type { SEOValidationResult, SEOptions } from "../../types/index.js";
2
+ export declare const validateSEO: (options: SEOptions) => SEOValidationResult;
3
+ export declare const auditSEO: (options: SEOptions, enableConsole?: boolean) => SEOValidationResult;
@@ -0,0 +1,120 @@
1
+ import { validateHreflangEntry } from "./hreflang-validator.js";
2
+ import { validateOpenGraphImage } from "./image-validator.js";
3
+ import { validateDescriptionLength, validateTitleLength } from "./length-validator.js";
4
+ import { validateJsonLd } from "./jsonld-validator.js";
5
+ import { validateUrl } from "./url-validator.js";
6
+ export const validateSEO = (options) => {
7
+ const errors = [];
8
+ const warnings = [];
9
+ const suggestions = [];
10
+ if (options.title) {
11
+ const error = validateTitleLength(options.title);
12
+ if (error)
13
+ warnings.push(error);
14
+ }
15
+ else {
16
+ errors.push("Title is missing");
17
+ }
18
+ if (options.description) {
19
+ const error = validateDescriptionLength(options.description);
20
+ if (error)
21
+ warnings.push(error);
22
+ }
23
+ else {
24
+ warnings.push("Description is missing");
25
+ }
26
+ if (options.canonical) {
27
+ const error = validateUrl(options.canonical, "Canonical URL");
28
+ if (error)
29
+ errors.push(error);
30
+ }
31
+ else {
32
+ suggestions.push("Add a canonical URL to prevent duplicate content issues");
33
+ }
34
+ if (!options.lang) {
35
+ warnings.push("Language attribute is missing");
36
+ suggestions.push('Add lang attribute (e.g., <html lang="en">)');
37
+ }
38
+ if (!options.openGraph) {
39
+ suggestions.push("Add Open Graph tags for better social media sharing");
40
+ }
41
+ else if (!options.openGraph.image) {
42
+ suggestions.push("Add Open Graph image for better social media previews");
43
+ }
44
+ else {
45
+ const imageUrl = typeof options.openGraph.image === "string"
46
+ ? options.openGraph.image
47
+ : options.openGraph.image[0]?.url ?? "";
48
+ const imageError = validateOpenGraphImage(imageUrl);
49
+ if (imageError)
50
+ warnings.push(imageError);
51
+ }
52
+ if (!options.twitter) {
53
+ suggestions.push("Add Twitter Card tags for better Twitter sharing");
54
+ }
55
+ if (options.hreflang && options.hreflang.length > 0) {
56
+ options.hreflang.forEach((entry, index) => {
57
+ const error = validateHreflangEntry(entry);
58
+ if (error)
59
+ errors.push(`Hreflang entry ${index + 1}: ${error}`);
60
+ });
61
+ if (!options.hreflang.some((entry) => entry.lang === "x-default")) {
62
+ suggestions.push('Add hreflang="x-default" for language fallback');
63
+ }
64
+ }
65
+ if (options.jsonLd && options.jsonLd.length > 0) {
66
+ options.jsonLd.forEach((data, index) => {
67
+ validateJsonLd(data).forEach((error) => {
68
+ errors.push(`JSON-LD entry ${index + 1}: ${error}`);
69
+ });
70
+ });
71
+ }
72
+ else {
73
+ suggestions.push("Add JSON-LD structured data for rich snippets in search results");
74
+ }
75
+ if (!options.favicon) {
76
+ suggestions.push("Add a favicon for better brand recognition in browser tabs");
77
+ }
78
+ if (!options.themeColor) {
79
+ suggestions.push("Add a theme color for better mobile browser integration");
80
+ }
81
+ if (!options.preconnect || options.preconnect.length === 0) {
82
+ suggestions.push("Add preconnect hints for external resources to improve performance");
83
+ }
84
+ return { valid: errors.length === 0, errors, warnings, suggestions };
85
+ };
86
+ const STYLE = {
87
+ error: "color: #d32f2f; font-weight: bold;",
88
+ warning: "color: #f57c00; font-weight: bold;",
89
+ success: "color: #388e3c; font-weight: bold;",
90
+ info: "color: #1976d2; font-weight: bold;",
91
+ };
92
+ export const auditSEO = (options, enableConsole = true) => {
93
+ const result = validateSEO(options);
94
+ if (!enableConsole || typeof console === "undefined")
95
+ return result;
96
+ console.group("%cSEO Audit Results", STYLE.info);
97
+ if (result.valid) {
98
+ console.log("%cAll required SEO elements are present.", STYLE.success);
99
+ }
100
+ else {
101
+ console.log("%cSEO validation failed", STYLE.error);
102
+ }
103
+ if (result.errors.length > 0) {
104
+ console.group("%cErrors (must fix)", STYLE.error);
105
+ result.errors.forEach((error) => console.error(error));
106
+ console.groupEnd();
107
+ }
108
+ if (result.warnings.length > 0) {
109
+ console.group("%cWarnings (should fix)", STYLE.warning);
110
+ result.warnings.forEach((warning) => console.warn(warning));
111
+ console.groupEnd();
112
+ }
113
+ if (result.suggestions.length > 0) {
114
+ console.group("%cSuggestions (nice to have)", STYLE.info);
115
+ result.suggestions.forEach((suggestion) => console.log(suggestion));
116
+ console.groupEnd();
117
+ }
118
+ console.groupEnd();
119
+ return result;
120
+ };
@@ -0,0 +1 @@
1
+ export declare const generateSlug: (text: string) => string;
@@ -0,0 +1,6 @@
1
+ export const generateSlug = (text) => text
2
+ .toLowerCase()
3
+ .trim()
4
+ .replace(/[^\w\s-]/g, "")
5
+ .replace(/[\s_-]+/g, "-")
6
+ .replace(/^-+|-+$/g, "");
@@ -0,0 +1,2 @@
1
+ export declare const isValidUrl: (url: string) => boolean;
2
+ export declare const validateUrl: (url: string, fieldName?: string) => string | null;
@@ -0,0 +1,20 @@
1
+ export const isValidUrl = (url) => {
2
+ if (!url)
3
+ return false;
4
+ try {
5
+ const parsed = new URL(url);
6
+ return parsed.protocol === "http:" || parsed.protocol === "https:";
7
+ }
8
+ catch {
9
+ return false;
10
+ }
11
+ };
12
+ export const validateUrl = (url, fieldName = "URL") => {
13
+ if (!url) {
14
+ return `${fieldName} is required`;
15
+ }
16
+ if (!isValidUrl(url)) {
17
+ return `${fieldName} must be a valid HTTP/HTTPS URL`;
18
+ }
19
+ return null;
20
+ };
@@ -1,7 +1,3 @@
1
- /**
2
- * SEO Vite Plugin
3
- *
4
- * Vite plugin for build-time SEO optimization
5
- */
6
- export { viteSEOPlugin, quickSEOSetup } from "./plugin.js";
7
- export type { ViteSEOPluginOptions } from "./plugin.js";
1
+ export { viteSEOPlugin } from "./plugin.js";
2
+ export { quickSEOSetup } from "./presets.js";
3
+ export type { ViteSEOPluginOptions } from "./types.js";
@@ -1,6 +1,2 @@
1
- /**
2
- * SEO Vite Plugin
3
- *
4
- * Vite plugin for build-time SEO optimization
5
- */
6
- export { viteSEOPlugin, quickSEOSetup } from "./plugin.js";
1
+ export { viteSEOPlugin } from "./plugin.js";
2
+ export { quickSEOSetup } from "./presets.js";
@@ -1,62 +1,4 @@
1
- /**
2
- * Vite SEO Plugin
3
- *
4
- * Build-time SEO optimization plugin for Vite applications.
5
- * Generates sitemap.xml, robots.txt, and other SEO assets.
6
- */
7
1
  import type { Plugin } from "vite";
8
- export interface ViteSEOPluginOptions {
9
- /** Base URL of your site (e.g., https://example.com) */
10
- siteUrl: string;
11
- /** Array of routes to include in sitemap */
12
- routes?: string[];
13
- /** Automatically discover routes from build output */
14
- discoverRoutes?: boolean;
15
- /** Sitemap options */
16
- sitemap?: {
17
- /** Output filename */
18
- filename?: string;
19
- /** Changefreq for all URLs */
20
- changefreq?: "always" | "hourly" | "daily" | "weekly" | "monthly" | "yearly" | "never";
21
- /** Priority for all URLs (0.0-1.0) */
22
- priority?: number;
23
- /** Last modified date */
24
- lastmod?: string;
25
- };
26
- /** Robots.txt options */
27
- robotsTxt?: {
28
- /** Output filename */
29
- filename?: string;
30
- /** User-agent rules */
31
- userAgent?: string | Record<string, string[]>;
32
- /** Disallow rules */
33
- disallow?: string | string[];
34
- /** Allow rules */
35
- allow?: string | string[];
36
- /** Sitemap location */
37
- sitemap?: string;
38
- /** Crawl delay */
39
- crawlDelay?: number;
40
- };
41
- /** Suppress console output */
42
- silent?: boolean;
43
- }
2
+ import type { ViteSEOPluginOptions } from "./types.js";
44
3
  export declare const viteSEOPlugin: (options: ViteSEOPluginOptions) => Plugin;
45
4
  export default viteSEOPlugin;
46
- /**
47
- * Quick setup for common SEO scenarios
48
- */
49
- export declare const quickSEOSetup: {
50
- /**
51
- * Basic setup for a simple website
52
- */
53
- basic: (siteUrl: string, routes?: string[]) => Plugin<any>;
54
- /**
55
- * Setup for a blog
56
- */
57
- blog: (siteUrl: string, routes?: string[]) => Plugin<any>;
58
- /**
59
- * Setup for an e-commerce site
60
- */
61
- ecommerce: (siteUrl: string, routes?: string[]) => Plugin<any>;
62
- };
@@ -1,222 +1,58 @@
1
- /**
2
- * Vite SEO Plugin
3
- *
4
- * Build-time SEO optimization plugin for Vite applications.
5
- * Generates sitemap.xml, robots.txt, and other SEO assets.
6
- */
7
- import * as fs from "fs";
8
- import * as path from "path";
9
- const generateSitemapXML = (urls) => {
10
- const urlElements = urls
11
- .map((url) => ` <url>
12
- <loc>${escapeXML(url.loc)}</loc>
13
- ${url.lastmod ? `<lastmod>${url.lastmod}</lastmod>` : ""}
14
- ${url.changefreq ? `<changefreq>${url.changefreq}</changefreq>` : ""}
15
- ${url.priority !== undefined ? `<priority>${url.priority}</priority>` : ""}
16
- </url>`)
17
- .join("\n");
18
- return `<?xml version="1.0" encoding="UTF-8"?>
19
- <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
20
- ${urlElements}
21
- </urlset>`;
22
- };
23
- const escapeXML = (str) => {
24
- return str
25
- .replace(/&/g, "&amp;")
26
- .replace(/</g, "&lt;")
27
- .replace(/>/g, "&gt;")
28
- .replace(/"/g, "&quot;")
29
- .replace(/'/g, "&apos;");
30
- };
31
- // ============================================================================
32
- // Robots.txt Generation
33
- // ============================================================================
34
- const generateRobotsTxt = (options) => {
35
- const lines = [];
36
- if (!options)
37
- return "";
38
- // User-agent
39
- if (typeof options.userAgent === "string") {
40
- lines.push(`User-agent: ${options.userAgent}`);
41
- }
42
- else if (typeof options.userAgent === "object") {
43
- Object.entries(options.userAgent).forEach(([agent, rules]) => {
44
- lines.push(`User-agent: ${agent}`);
45
- rules.forEach((rule) => lines.push(rule));
46
- });
47
- }
48
- else {
49
- lines.push("User-agent: *");
50
- }
51
- // Disallow
52
- if (options.disallow) {
53
- const disallowRules = Array.isArray(options.disallow) ? options.disallow : [options.disallow];
54
- disallowRules.forEach((rule) => lines.push(`Disallow: ${rule}`));
55
- }
56
- // Allow
57
- if (options.allow) {
58
- const allowRules = Array.isArray(options.allow) ? options.allow : [options.allow];
59
- allowRules.forEach((rule) => lines.push(`Allow: ${rule}`));
60
- }
61
- // Crawl delay
62
- if (options.crawlDelay) {
63
- lines.push(`Crawl-delay: ${options.crawlDelay}`);
64
- }
65
- // Sitemap
66
- if (options.sitemap) {
67
- lines.push(`Sitemap: ${options.sitemap}`);
68
- }
69
- return lines.join("\n") + "\n";
70
- };
71
- // ============================================================================
72
- // Route Discovery
73
- // ============================================================================
74
- const discoverRoutesFromBuild = (outDir) => {
75
- const routes = new Set("/");
76
- const traverseDirectory = (dir, basePath = "") => {
77
- try {
78
- const files = fs.readdirSync(dir);
79
- files.forEach((file) => {
80
- const fullPath = path.join(dir, file);
81
- const stat = fs.statSync(fullPath);
82
- if (stat.isDirectory()) {
83
- traverseDirectory(fullPath, path.join(basePath, file));
84
- }
85
- else if (file === "index.html") {
86
- routes.add(basePath || "/");
87
- }
88
- });
89
- }
90
- catch (error) {
91
- // Directory doesn't exist or isn't accessible yet - silently skip
92
- if (error.code !== 'ENOENT') {
93
- console.warn(`[vite-plugin-seo] Warning: Could not traverse directory ${dir}:`, error);
94
- }
95
- }
96
- };
97
- traverseDirectory(outDir);
98
- return Array.from(routes);
99
- };
100
- // ============================================================================
101
- // Main Plugin
102
- // ============================================================================
1
+ import { generateRobotsTxt } from "./robots-generator.js";
2
+ import { discoverRoutesFromBuild, generateSitemapXML } from "./sitemap-generator.js";
3
+ const PLUGIN_NAME = "umituz-web-seo";
103
4
  export const viteSEOPlugin = (options) => {
104
5
  const { siteUrl, routes: manualRoutes = [], discoverRoutes = false, sitemap: sitemapOptions = {}, robotsTxt: robotsOptions = {}, silent = false, } = options;
105
- const sitemapFilename = sitemapOptions.filename || "sitemap.xml";
106
- const robotsFilename = robotsOptions.filename || "robots.txt";
107
- // Store plugin state
6
+ const sitemapFilename = sitemapOptions.filename ?? "sitemap.xml";
7
+ const robotsFilename = robotsOptions.filename ?? "robots.txt";
8
+ const normalizedSiteUrl = siteUrl.replace(/\/$/, "");
108
9
  const pluginState = {};
109
10
  return {
110
- name: "vite-plugin-seo",
11
+ name: PLUGIN_NAME,
111
12
  enforce: "post",
112
13
  configResolved(config) {
113
- // Store resolved config for later use
114
14
  pluginState.publicDir = config.publicDir;
115
15
  pluginState.outDir = config.build.outDir;
116
16
  },
117
- generateBundle(_input, _bundle) {
118
- const outDir = pluginState.outDir || "dist";
119
- // Collect routes
17
+ generateBundle() {
18
+ const outDir = pluginState.outDir ?? "dist";
120
19
  let routes = [...manualRoutes];
121
20
  if (discoverRoutes) {
122
- const discoveredRoutes = discoverRoutesFromBuild(outDir);
123
- routes = [...new Set([...routes, ...discoveredRoutes])];
21
+ const discovered = discoverRoutesFromBuild(outDir);
22
+ routes = Array.from(new Set([...routes, ...discovered]));
124
23
  }
125
- // Ensure at least the root route
126
- if (routes.length === 0) {
24
+ if (routes.length === 0)
127
25
  routes.push("/");
128
- }
129
- // Generate sitemap
130
26
  const sitemapUrls = routes.map((route) => ({
131
- loc: `${siteUrl.replace(/\/$/, "")}${route}`,
27
+ loc: `${normalizedSiteUrl}${route}`,
132
28
  lastmod: sitemapOptions.lastmod,
133
29
  changefreq: sitemapOptions.changefreq,
134
30
  priority: sitemapOptions.priority,
135
31
  }));
136
- const sitemapXML = generateSitemapXML(sitemapUrls);
137
- // Add sitemap to bundle
138
32
  this.emitFile({
139
33
  type: "asset",
140
34
  fileName: sitemapFilename,
141
- source: sitemapXML,
142
- });
143
- // Generate robots.txt
144
- const robotsTxtContent = generateRobotsTxt({
145
- siteUrl,
146
- ...robotsOptions,
147
- sitemap: robotsOptions.sitemap || `${siteUrl.replace(/\/$/, "")}/${sitemapFilename}`,
35
+ source: generateSitemapXML(sitemapUrls),
148
36
  });
149
- // Add robots.txt to bundle
150
37
  this.emitFile({
151
38
  type: "asset",
152
39
  fileName: robotsFilename,
153
- source: robotsTxtContent,
40
+ source: generateRobotsTxt({
41
+ siteUrl,
42
+ ...robotsOptions,
43
+ sitemap: robotsOptions.sitemap ?? `${normalizedSiteUrl}/${sitemapFilename}`,
44
+ }),
154
45
  });
155
46
  },
156
47
  closeBundle() {
157
- // Log generated files
158
- if (!silent) {
159
- console.log(`\n${"=".repeat(50)}`);
160
- console.log(`🚀 SEO files generated:`);
161
- console.log(` 📄 ${sitemapFilename}`);
162
- console.log(` 🤖 ${robotsFilename}`);
163
- console.log(`${"=".repeat(50)}\n`);
164
- }
48
+ if (silent)
49
+ return;
50
+ console.log(`\n${"=".repeat(50)}`);
51
+ console.log("SEO files generated:");
52
+ console.log(` ${sitemapFilename}`);
53
+ console.log(` ${robotsFilename}`);
54
+ console.log(`${"=".repeat(50)}\n`);
165
55
  },
166
56
  };
167
57
  };
168
58
  export default viteSEOPlugin;
169
- // ============================================================================
170
- // Convenience Exports
171
- // ============================================================================
172
- /**
173
- * Quick setup for common SEO scenarios
174
- */
175
- export const quickSEOSetup = {
176
- /**
177
- * Basic setup for a simple website
178
- */
179
- basic: (siteUrl, routes) => viteSEOPlugin({
180
- siteUrl,
181
- routes,
182
- discoverRoutes: true,
183
- sitemap: {
184
- changefreq: "weekly",
185
- priority: 0.8,
186
- },
187
- robotsTxt: {
188
- disallow: ["/api", "/admin"],
189
- },
190
- }),
191
- /**
192
- * Setup for a blog
193
- */
194
- blog: (siteUrl, routes) => viteSEOPlugin({
195
- siteUrl,
196
- routes: ["/", routes || []].flat(),
197
- discoverRoutes: true,
198
- sitemap: {
199
- changefreq: "daily",
200
- priority: 0.9,
201
- },
202
- robotsTxt: {
203
- disallow: ["/api", "/admin", "/private"],
204
- },
205
- }),
206
- /**
207
- * Setup for an e-commerce site
208
- */
209
- ecommerce: (siteUrl, routes) => viteSEOPlugin({
210
- siteUrl,
211
- routes: ["/", routes || []].flat(),
212
- discoverRoutes: true,
213
- sitemap: {
214
- changefreq: "hourly",
215
- priority: 1.0,
216
- },
217
- robotsTxt: {
218
- disallow: ["/api", "/admin", "/cart", "/checkout", "/account"],
219
- crawlDelay: 1,
220
- },
221
- }),
222
- };
@@ -0,0 +1,8 @@
1
+ import type { ViteSEOPluginOptions } from "./types.js";
2
+ export declare const quickSEOSetup: {
3
+ readonly basic: (siteUrl: string, routes?: string[]) => import("vite").Plugin<any>;
4
+ readonly blog: (siteUrl: string, routes?: string[]) => import("vite").Plugin<any>;
5
+ readonly ecommerce: (siteUrl: string, routes?: string[]) => import("vite").Plugin<any>;
6
+ };
7
+ export type QuickSetupKey = keyof typeof quickSEOSetup;
8
+ export type { ViteSEOPluginOptions };
@@ -0,0 +1,28 @@
1
+ import { viteSEOPlugin } from "./plugin.js";
2
+ const baseDisallow = ["/api", "/admin"];
3
+ const blogDisallow = [...baseDisallow, "/private"];
4
+ const ecommerceDisallow = [...baseDisallow, "/cart", "/checkout", "/account"];
5
+ const withRoutes = (routes) => ["/", ...(routes ?? [])];
6
+ export const quickSEOSetup = {
7
+ basic: (siteUrl, routes) => viteSEOPlugin({
8
+ siteUrl,
9
+ routes,
10
+ discoverRoutes: true,
11
+ sitemap: { changefreq: "weekly", priority: 0.8 },
12
+ robotsTxt: { disallow: baseDisallow },
13
+ }),
14
+ blog: (siteUrl, routes) => viteSEOPlugin({
15
+ siteUrl,
16
+ routes: withRoutes(routes),
17
+ discoverRoutes: true,
18
+ sitemap: { changefreq: "daily", priority: 0.9 },
19
+ robotsTxt: { disallow: blogDisallow },
20
+ }),
21
+ ecommerce: (siteUrl, routes) => viteSEOPlugin({
22
+ siteUrl,
23
+ routes: withRoutes(routes),
24
+ discoverRoutes: true,
25
+ sitemap: { changefreq: "hourly", priority: 1.0 },
26
+ robotsTxt: { disallow: ecommerceDisallow, crawlDelay: 1 },
27
+ }),
28
+ };
@@ -0,0 +1,6 @@
1
+ import type { ViteSEOPluginOptions } from "./types.js";
2
+ type RobotsOptions = ViteSEOPluginOptions["robotsTxt"] & {
3
+ siteUrl: string;
4
+ };
5
+ export declare const generateRobotsTxt: (options: RobotsOptions) => string;
6
+ export {};