@umituz/web-seo 2.3.1 → 2.5.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.
@@ -0,0 +1,7 @@
1
+ import type { RouteMeta } from "../vite/types.js";
2
+ export interface RouteSEOProps {
3
+ routes: Record<string, RouteMeta>;
4
+ siteUrl?: string;
5
+ fallback?: RouteMeta;
6
+ }
7
+ export declare const RouteSEO: import("react").MemoExoticComponent<({ routes, siteUrl, fallback }: RouteSEOProps) => null>;
@@ -0,0 +1,57 @@
1
+ import { memo, useMemo } from "react";
2
+ import { useSEO } from "../hooks/index.js";
3
+ const normalizePath = (path) => {
4
+ const stripped = path.replace(/\/+$/, "");
5
+ return stripped === "" ? "/" : stripped;
6
+ };
7
+ const toOpenGraph = (meta, path, siteUrl) => {
8
+ const og = meta.og;
9
+ if (!og)
10
+ return undefined;
11
+ return {
12
+ title: og.title ?? meta.title,
13
+ description: og.description ?? meta.description,
14
+ image: og.image,
15
+ url: og.url ?? (siteUrl ? `${siteUrl}${path}` : undefined),
16
+ siteName: og.siteName,
17
+ ...(og.type ? { type: og.type } : {}),
18
+ };
19
+ };
20
+ const toTwitter = (meta) => {
21
+ const twitter = meta.twitter;
22
+ if (!twitter)
23
+ return undefined;
24
+ return {
25
+ ...(twitter.card ? { cardType: twitter.card } : {}),
26
+ site: twitter.site,
27
+ handle: twitter.creator,
28
+ title: twitter.title ?? meta.title,
29
+ description: twitter.description ?? meta.description,
30
+ image: twitter.image,
31
+ };
32
+ };
33
+ const RouteSEOComponent = ({ routes, siteUrl, fallback }) => {
34
+ const path = typeof window === "undefined" ? "/" : normalizePath(window.location.pathname);
35
+ const meta = routes[path];
36
+ const options = useMemo(() => {
37
+ if (meta) {
38
+ return {
39
+ title: meta.title,
40
+ description: meta.description,
41
+ lang: meta.lang,
42
+ canonical: meta.canonical ?? (siteUrl ? `${siteUrl}${path}` : undefined),
43
+ robots: { index: true, follow: true },
44
+ openGraph: toOpenGraph(meta, path, siteUrl),
45
+ twitter: toTwitter(meta),
46
+ };
47
+ }
48
+ return {
49
+ title: fallback?.title,
50
+ description: fallback?.description,
51
+ robots: { index: false, follow: false },
52
+ };
53
+ }, [meta, siteUrl, path, fallback]);
54
+ useSEO(options);
55
+ return null;
56
+ };
57
+ export const RouteSEO = memo(RouteSEOComponent);
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,60 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { act } from 'react';
3
+ import { createRoot } from 'react-dom/client';
4
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
5
+ import { RouteSEO } from './RouteSEO.js';
6
+ const ROUTES = {
7
+ '/': { title: 'Demo — vertical SaaS', description: 'Run your studio end to end.' },
8
+ '/pricing': { title: 'Pricing — Demo' },
9
+ };
10
+ let container = null;
11
+ let root = null;
12
+ const nextFrame = async () => {
13
+ await new Promise((resolve) => {
14
+ requestAnimationFrame(() => resolve());
15
+ });
16
+ };
17
+ const render = async (ui) => {
18
+ act(() => {
19
+ root?.render(ui);
20
+ });
21
+ await nextFrame();
22
+ await nextFrame();
23
+ };
24
+ beforeEach(() => {
25
+ container = document.createElement('div');
26
+ document.body.appendChild(container);
27
+ root = createRoot(container);
28
+ });
29
+ afterEach(() => {
30
+ act(() => {
31
+ root?.unmount();
32
+ });
33
+ container?.remove();
34
+ container = null;
35
+ root = null;
36
+ document.title = '';
37
+ document.querySelectorAll('meta[name="robots"]').forEach((el) => el.remove());
38
+ });
39
+ const robotsContent = () => document.querySelector('meta[name="robots"]')?.getAttribute('content') ?? '';
40
+ describe('RouteSEO', () => {
41
+ it('indexes a public route and applies its title and canonical', async () => {
42
+ window.history.replaceState({}, '', '/');
43
+ await render(_jsx(RouteSEO, { routes: ROUTES, siteUrl: "https://demo.test.dev" }));
44
+ expect(document.title).toBe('Demo — vertical SaaS');
45
+ expect(robotsContent()).not.toMatch(/noindex/);
46
+ expect(document.querySelector('link[rel="canonical"]')?.getAttribute('href')).toBe('https://demo.test.dev/');
47
+ });
48
+ it('noindexes any path outside the public map', async () => {
49
+ window.history.replaceState({}, '', '/dashboard/cases');
50
+ await render(_jsx(RouteSEO, { routes: ROUTES, siteUrl: "https://demo.test.dev", fallback: { title: 'Demo app' } }));
51
+ expect(document.title).toBe('Demo app');
52
+ expect(robotsContent()).toMatch(/noindex/);
53
+ });
54
+ it('normalizes trailing slashes when matching routes', async () => {
55
+ window.history.replaceState({}, '', '/pricing/');
56
+ await render(_jsx(RouteSEO, { routes: ROUTES, siteUrl: "https://demo.test.dev" }));
57
+ expect(document.title).toBe('Pricing — Demo');
58
+ expect(robotsContent()).not.toMatch(/noindex/);
59
+ });
60
+ });
@@ -1,2 +1,4 @@
1
1
  export { SEO } from "./SEO.js";
2
2
  export { JsonLd } from "./JsonLd.js";
3
+ export { RouteSEO } from "./RouteSEO.js";
4
+ export type { RouteSEOProps } from "./RouteSEO.js";
@@ -1,2 +1,3 @@
1
1
  export { SEO } from "./SEO.js";
2
2
  export { JsonLd } from "./JsonLd.js";
3
+ export { RouteSEO } from "./RouteSEO.js";
@@ -21,6 +21,32 @@ const upsertMetaTag = (html, attributeName, attributeValue, content) => {
21
21
  const newTag = `<meta ${attributeName}="${attributeValue}" content="${escapeHtml(content)}" />`;
22
22
  return upsertTag(html, regex, newTag);
23
23
  };
24
+ const replaceRootContent = (html, newContent) => {
25
+ const rootMatch = html.match(/<div\s+[^>]*?id=["']root["'][^>]*>/i);
26
+ if (!rootMatch || rootMatch.index === undefined)
27
+ return html;
28
+ const startIdx = rootMatch.index + rootMatch[0].length;
29
+ let depth = 1;
30
+ let pos = startIdx;
31
+ while (pos < html.length && depth > 0) {
32
+ const nextOpen = html.indexOf("<div", pos);
33
+ const nextClose = html.indexOf("</div>", pos);
34
+ if (nextClose === -1)
35
+ break;
36
+ if (nextOpen !== -1 && nextOpen < nextClose) {
37
+ depth++;
38
+ pos = nextOpen + 4;
39
+ }
40
+ else {
41
+ depth--;
42
+ if (depth === 0) {
43
+ return `${html.slice(0, startIdx)}\n${newContent}\n ${html.slice(nextClose)}`;
44
+ }
45
+ pos = nextClose + 6;
46
+ }
47
+ }
48
+ return html;
49
+ };
24
50
  export const injectRouteMeta = (htmlTemplate, meta, siteUrl, routePath) => {
25
51
  let html = htmlTemplate;
26
52
  const normalizedSiteUrl = siteUrl.replace(/\/$/, "");
@@ -105,5 +131,8 @@ export const injectRouteMeta = (htmlTemplate, meta, siteUrl, routePath) => {
105
131
  const existingJsonLdRegex = /<script\s+[^>]*?type=["']application\/ld\+json["'][^>]*>[\s\S]*?<\/script>/i;
106
132
  html = upsertTag(html, existingJsonLdRegex, jsonLdTag);
107
133
  }
134
+ if (meta.bodyHtml) {
135
+ html = replaceRootContent(html, meta.bodyHtml);
136
+ }
108
137
  return html;
109
138
  };
@@ -1,4 +1,5 @@
1
1
  export { viteSEOPlugin } from "./plugin.js";
2
2
  export { injectRouteMeta } from "./html-rewriter.js";
3
- export { quickSEOSetup } from "./presets.js";
3
+ export { quickSEOSetup, saasSEOOptions } from "./presets.js";
4
+ export type { SaasSEOOptions } from "./presets.js";
4
5
  export type { ViteSEOPluginOptions, SitemapRouteItem, SitemapChangeFreq, RouteMeta, PrerenderOptions, } from "./types.js";
@@ -1,3 +1,3 @@
1
1
  export { viteSEOPlugin } from "./plugin.js";
2
2
  export { injectRouteMeta } from "./html-rewriter.js";
3
- export { quickSEOSetup } from "./presets.js";
3
+ export { quickSEOSetup, saasSEOOptions } from "./presets.js";
@@ -1,8 +1,17 @@
1
- import type { ViteSEOPluginOptions } from "./types.js";
1
+ import type { RouteMeta, SitemapRouteItem, ViteSEOPluginOptions } from "./types.js";
2
+ export interface SaasSEOOptions {
3
+ landing?: Array<string | SitemapRouteItem>;
4
+ prerender?: Record<string, RouteMeta>;
5
+ brand?: string;
6
+ image?: string;
7
+ disallow?: string[];
8
+ }
9
+ export declare const saasSEOOptions: (siteUrl: string, opts?: SaasSEOOptions) => ViteSEOPluginOptions;
2
10
  export declare const quickSEOSetup: {
3
11
  readonly basic: (siteUrl: string, routes?: string[]) => import("vite").Plugin<any>;
4
12
  readonly blog: (siteUrl: string, routes?: string[]) => import("vite").Plugin<any>;
5
13
  readonly ecommerce: (siteUrl: string, routes?: string[]) => import("vite").Plugin<any>;
14
+ readonly saas: (siteUrl: string, opts?: SaasSEOOptions) => import("vite").Plugin<any>;
6
15
  };
7
16
  export type QuickSetupKey = keyof typeof quickSEOSetup;
8
17
  export type { ViteSEOPluginOptions };
@@ -2,7 +2,33 @@ import { viteSEOPlugin } from "./plugin.js";
2
2
  const baseDisallow = ["/api", "/admin"];
3
3
  const blogDisallow = [...baseDisallow, "/private"];
4
4
  const ecommerceDisallow = [...baseDisallow, "/cart", "/checkout", "/account"];
5
+ const saasDisallow = ["/api/", "/auth/"];
5
6
  const withRoutes = (routes) => ["/", ...(routes ?? [])];
7
+ export const saasSEOOptions = (siteUrl, opts = {}) => ({
8
+ siteUrl,
9
+ routes: ["/", ...(opts.landing ?? [])],
10
+ sitemap: { filename: "sitemap.xml" },
11
+ robotsTxt: {
12
+ filename: "robots.txt",
13
+ allow: "/",
14
+ disallow: opts.disallow ?? saasDisallow,
15
+ sitemap: `${siteUrl}/sitemap.xml`,
16
+ },
17
+ prerender: {
18
+ fallbackMeta: {
19
+ ...(opts.brand || opts.image
20
+ ? {
21
+ og: {
22
+ ...(opts.brand ? { siteName: opts.brand } : {}),
23
+ ...(opts.image ? { image: opts.image } : {}),
24
+ },
25
+ ...(opts.image ? { twitter: { card: "summary_large_image", image: opts.image } } : {}),
26
+ }
27
+ : {}),
28
+ },
29
+ routes: opts.prerender ?? { "/": {} },
30
+ },
31
+ });
6
32
  export const quickSEOSetup = {
7
33
  basic: (siteUrl, routes) => viteSEOPlugin({
8
34
  siteUrl,
@@ -25,4 +51,5 @@ export const quickSEOSetup = {
25
51
  sitemap: { changefreq: "hourly", priority: 1.0 },
26
52
  robotsTxt: { disallow: ecommerceDisallow, crawlDelay: 1 },
27
53
  }),
54
+ saas: (siteUrl, opts = {}) => viteSEOPlugin(saasSEOOptions(siteUrl, opts)),
28
55
  };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,37 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { saasSEOOptions } from './presets.js';
3
+ describe('saasSEOOptions', () => {
4
+ it('builds the fleet sitemap/robots/prerender shape from site url', () => {
5
+ const options = saasSEOOptions('https://demo.test.dev');
6
+ expect(options.siteUrl).toBe('https://demo.test.dev');
7
+ expect(options.routes).toEqual(['/']);
8
+ expect(options.sitemap).toEqual({ filename: 'sitemap.xml' });
9
+ expect(options.robotsTxt).toEqual({
10
+ filename: 'robots.txt',
11
+ allow: '/',
12
+ disallow: ['/api/', '/auth/'],
13
+ sitemap: 'https://demo.test.dev/sitemap.xml',
14
+ });
15
+ expect(options.prerender?.routes).toEqual({ '/': {} });
16
+ });
17
+ it('carries landing routes, brand fallback meta, and custom disallow', () => {
18
+ const options = saasSEOOptions('https://demo.test.dev', {
19
+ landing: [{ url: '/pricing', priority: 0.8 }, '/about'],
20
+ brand: 'Demo',
21
+ image: 'https://demo.test.dev/favicon.svg',
22
+ disallow: ['/api/', '/auth/', '/admin/'],
23
+ prerender: { '/': { title: 'Demo — home' } },
24
+ });
25
+ expect(options.routes).toEqual(['/', { url: '/pricing', priority: 0.8 }, '/about']);
26
+ expect(options.robotsTxt?.disallow).toEqual(['/api/', '/auth/', '/admin/']);
27
+ expect(options.prerender?.fallbackMeta).toEqual({
28
+ og: { siteName: 'Demo', image: 'https://demo.test.dev/favicon.svg' },
29
+ twitter: { card: 'summary_large_image', image: 'https://demo.test.dev/favicon.svg' },
30
+ });
31
+ expect(options.prerender?.routes).toEqual({ '/': { title: 'Demo — home' } });
32
+ });
33
+ it('omits fallback meta entirely when neither brand nor image is given', () => {
34
+ const options = saasSEOOptions('https://demo.test.dev', { prerender: {} });
35
+ expect(options.prerender?.fallbackMeta).toEqual({});
36
+ });
37
+ });
@@ -29,6 +29,7 @@ export interface RouteMeta {
29
29
  creator?: string;
30
30
  };
31
31
  jsonLd?: Record<string, unknown> | Array<Record<string, unknown>>;
32
+ bodyHtml?: string;
32
33
  }
33
34
  export interface PrerenderOptions {
34
35
  routes?: Record<string, RouteMeta>;
package/dist/index.d.ts CHANGED
@@ -1,9 +1,12 @@
1
1
  export { SEO } from "./domains/seo/components/SEO.js";
2
2
  export { JsonLd } from "./domains/seo/components/JsonLd.js";
3
+ export { RouteSEO } from "./domains/seo/components/RouteSEO.js";
4
+ export type { RouteSEOProps } from "./domains/seo/components/RouteSEO.js";
3
5
  export { useSEO } from "./domains/seo/hooks/useSEO.js";
4
6
  export { useJsonLd } from "./domains/seo/hooks/useJsonLd.js";
5
7
  export { initSEO } from "./domains/seo/core/init.js";
6
8
  export { updateSEO, clearSEO, getCurrentSEOState } from "./domains/seo/utils/dom/index.js";
9
+ export type { RouteMeta, SitemapRouteItem } from "./domains/seo/vite/types.js";
7
10
  export { generateArticleSchema, generateProductSchema, generateOrganizationSchema, generateLocalBusinessSchema, generateBreadcrumbSchema, generateFAQSchema, generateWebSiteSchema, generatePersonSchema, generateVideoSchema, generateCourseSchema, schemaFactory, } from "./domains/seo/utils/schema-generators/index.js";
8
11
  export { validateSEO, auditSEO, isValidUrl, validateUrl, validateTitleLength, validateDescriptionLength, validateOpenGraphImage, validateHreflangEntry, truncateToTitle, truncateToDescription, generateSlug, } from "./domains/seo/utils/validation/index.js";
9
12
  export { renderSEO, generateHead, extractSEOData, hydrateSEO, renderAsHelmet, serializeSEO, deserializeSEO, serializeSEOToBase64, deserializeSEOFromBase64, safeDeserializeSEO, } from "./domains/seo/ssr/index.js";
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export { SEO } from "./domains/seo/components/SEO.js";
2
2
  export { JsonLd } from "./domains/seo/components/JsonLd.js";
3
+ export { RouteSEO } from "./domains/seo/components/RouteSEO.js";
3
4
  export { useSEO } from "./domains/seo/hooks/useSEO.js";
4
5
  export { useJsonLd } from "./domains/seo/hooks/useJsonLd.js";
5
6
  export { initSEO } from "./domains/seo/core/init.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umituz/web-seo",
3
- "version": "2.3.1",
3
+ "version": "2.5.0",
4
4
  "description": "Comprehensive SEO solution for React Vite applications with structured data, performance hints, and build-time optimization",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -10,7 +10,8 @@
10
10
  "build": "tsc",
11
11
  "lint": "eslint .",
12
12
  "typecheck": "tsc --noEmit",
13
- "prepublishOnly": "npm run build"
13
+ "prepublishOnly": "npm run build",
14
+ "test": "vitest run"
14
15
  },
15
16
  "exports": {
16
17
  ".": {
@@ -86,9 +87,11 @@
86
87
  "@typescript-eslint/eslint-plugin": "^8.57.1",
87
88
  "@typescript-eslint/parser": "^8.57.1",
88
89
  "eslint": "^8.57.0",
90
+ "jsdom": "^29.1.1",
89
91
  "react": "^19.2.4",
90
92
  "react-dom": "^19.2.4",
91
93
  "typescript": "^5.4.5",
92
- "vite": "^5.4.21"
94
+ "vite": "^5.4.21",
95
+ "vitest": "3.2.4"
93
96
  }
94
97
  }