All files / routes/marketplace sitemap.ts

98.57% Statements 69/70
77.77% Branches 14/18
100% Functions 17/17
100% Lines 63/63

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282                      1x             104x           8x 6x   6x   6x                                   6x   188x 188x 188x   1x   188x         1x   1x 94x 92x           92x   1x           1x                             14x 14x 14x       21x 21x     21x               21x 126x                 21x 1932x                 21x 63x                 21x 84x                 21x                 21x             21x     1x   1x 21x     21x                       21x                     21x                           21x 21x                   21x   2x 1x   21x 7x     21x     21x 5x 5x                 21x 3x 3x                 21x 21x 6x 6x 6x               21x         21x            
// Sitemap data route — public, no auth required.
// Aggregates all published entity URLs so the marketplace can build its
// dynamic sitemap without duplicating the static-URL enumeration logic.
 
import { and, eq } from "drizzle-orm";
import { Hono } from "hono";
import { getDb } from "../../db";
import { blogPros, blogs, projects, pros } from "../../db/schema";
import { localitiesData, zonesData } from "../../../seeds/taxonomy-data";
import { hyderabadLocalitiesSeoData } from "../../../seeds/seo-content-data";
 
const SITE_URL = "https://interioring.com";
 
// ── Static geo/content URLs ──────────────────────────────────────────────────
// Zones and localities are derived from the seed taxonomy — the same source
// that populates the DB — so renames or additions propagate without manual
// duplication. Slug convention: lowercase name with spaces → hyphens.
 
const toSlug = (name: string) => name.toLowerCase().replace(/\s+/g, "-");
 
// Sitemap URLs are hardcoded under `/interiors/hyderabad/`, so only Hyderabad
// zones/localities belong here. Non-Hyderabad zones (sentinel buckets like
// `unlisted`/`overseas` for #626) must be excluded or they leak duplicate
// empty-slug URLs into the sitemap.
const hyderabadZones = zonesData.filter((z) => z.cityId === "hyderabad");
const hyderabadZoneIds = new Set(hyderabadZones.map((z) => z.id));
 
const ZONES = hyderabadZones.map((z) => ({ slug: toSlug(z.name), name: z.name }));
 
const zoneSlugById = new Map(hyderabadZones.map((z) => [z.id, toSlug(z.name)] as const));
 
// A locality landing page is near-duplicate boilerplate (same 25 fallback pros +
// name-swapped copy) unless it carries authored editorial content — a unique
// intro or FAQ overrides. The marketplace locality page noindexes those thin
// variants (see [zone]/[locality].astro `isThinPage`), so emitting them in the
// sitemap would surface "Submitted URL marked 'noindex'" in Search Console. We
// exclude positively-thin localities here using the same content seed that
// populates the DB, keeping page + sitemap in lockstep.
//
// Note: the page's *other* indexing path — >=3 local pros — is a pro↔locality
// m:n junction we intentionally don't aggregate here. Every seeded locality
// carries an authored intro, so the editorial check matches the page in
// practice; a content-less locality is omitted from the sitemap but stays
// reachable/indexable via internal links.
export function buildLocalityEditorialMap(
	seoData: { slug: string; intro: string; faqOverrides: string }[],
): Map<string, boolean> {
	return new Map(
		seoData.map((l) => {
			let faqCount = 0;
			try {
				faqCount = (JSON.parse(l.faqOverrides) as unknown[]).length;
			} catch {
				faqCount = 0;
			}
			return [l.slug, Boolean(l.intro?.trim()) || faqCount > 0] as const;
		}),
	);
}
 
const localityHasEditorial = buildLocalityEditorialMap(hyderabadLocalitiesSeoData);
 
const LOCALITIES: { zoneSlug: string; localitySlug: string }[] = localitiesData
	.filter((l) => hyderabadZoneIds.has(l.zoneId))
	.map((l) => ({
		zoneSlug: zoneSlugById.get(l.zoneId) ?? "",
		localitySlug: toSlug(l.name),
	}))
	// Keep unless the locality is *positively* identified as editorial-thin.
	// An unmatched slug (undefined) is kept — never silently drop a real page.
	.filter((loc) => localityHasEditorial.get(loc.localitySlug) !== false);
 
const SERVICES = [
	"modular-kitchen",
	"full-home-interior",
	"2bhk-turnkey-package",
];
 
const BHK_COUNTS = [1, 2, 3, 4];
 
export type SitemapEntity = {
	url: string;
	lastmod: string;
	changefreq: string;
	priority: number;
};
 
export type SitemapResponse = {
	entities: SitemapEntity[];
	generatedAt: string;
};
 
function toDateString(ts: Date | number | null | undefined): string {
	Iif (!ts) return new Date().toISOString().split("T")[0];
	const d = typeof ts === "number" ? new Date(ts * 1000) : ts;
	return d.toISOString().split("T")[0];
}
 
function buildStaticEntities(): SitemapEntity[] {
	const today = new Date().toISOString().split("T")[0];
	const entities: SitemapEntity[] = [];
 
	// City hub
	entities.push({
		url: `${SITE_URL}/interiors/hyderabad`,
		lastmod: today,
		changefreq: "daily",
		priority: 1.0,
	});
 
	// Zone pages
	for (const zone of ZONES) {
		entities.push({
			url: `${SITE_URL}/interiors/hyderabad/${zone.slug}`,
			lastmod: today,
			changefreq: "weekly",
			priority: 0.9,
		});
	}
 
	// Locality pages
	for (const loc of LOCALITIES) {
		entities.push({
			url: `${SITE_URL}/interiors/hyderabad/${loc.zoneSlug}/${loc.localitySlug}`,
			lastmod: today,
			changefreq: "weekly",
			priority: 0.85,
		});
	}
 
	// City × service pages
	for (const service of SERVICES) {
		entities.push({
			url: `${SITE_URL}/interiors/hyderabad/${service}`,
			lastmod: today,
			changefreq: "weekly",
			priority: 0.9,
		});
	}
 
	// BHK × city pages
	for (const bhk of BHK_COUNTS) {
		entities.push({
			url: `${SITE_URL}/interiors/hyderabad/${bhk}bhk-interior`,
			lastmod: today,
			changefreq: "weekly",
			priority: 0.8,
		});
	}
 
	// Cost calculator tool
	entities.push({
		url: `${SITE_URL}/tools/interior-design-cost-calculator`,
		lastmod: today,
		changefreq: "monthly",
		priority: 0.8,
	});
 
 
	// FAQ hub
	entities.push({
		url: `${SITE_URL}/faq`,
		lastmod: today,
		changefreq: "monthly",
		priority: 0.8,
	});
 
	return entities;
}
 
const sitemap = new Hono<{ Bindings: CloudflareBindings }>();
 
sitemap.get("/", async (c) => {
	const db = getDb(c.env.DB);
 
	// Fetch published pros
	const publishedPros = await db
		.select({
			slug: pros.slug,
			id: pros.id,
			dateUpdated: pros.dateUpdated,
		})
		.from(pros)
		.where(eq(pros.status, "published"))
		.all();
 
	// Fetch published projects — include slug so canonical URLs avoid the
	// /projects/[id] → /projects/[slug] 301 redirect (saves ~1s LCP).
	const publishedProjects = await db
		.select({
			id: projects.id,
			slug: projects.slug,
			dateUpdated: projects.dateUpdated,
		})
		.from(projects)
		.where(eq(projects.status, "published"))
		.all();
 
	// Fetch published blogs
	const publishedBlogs = await db
		.select({
			id: blogs.id,
			slug: blogs.slug,
			publishedAt: blogs.publishedAt,
			dateUpdated: blogs.dateUpdated,
		})
		.from(blogs)
		.where(eq(blogs.status, "published"))
		.all();
 
	// Exclude blogs whose author pro is not published — mirrors blog detail page
	// logic (blogs.routes.ts). Without this, a blog with an unpublished author
	// appears in the sitemap but returns 404, wasting crawl budget.
	const publishedProIds = new Set(publishedPros.map((p) => p.id));
	const authorBlogPros = await db
		.select({ blogId: blogPros.blogId, proId: blogPros.proId })
		.from(blogPros)
		.where(
			and(
				eq(blogPros.attributionType, "author"),
				eq(blogPros.approvalStatus, "approved"),
			),
		)
		.all();
	const blogsWithUnpublishedAuthors = new Set(
		authorBlogPros
			.filter((bp) => !publishedProIds.has(bp.proId))
			.map((bp) => bp.blogId),
	);
	const indexableBlogs = publishedBlogs.filter(
		(b) => !blogsWithUnpublishedAuthors.has(b.id),
	);
 
	const entities: SitemapEntity[] = [...buildStaticEntities()];
 
	// Pros — use slug if available, fall back to id
	for (const pro of publishedPros) {
		const identifier = pro.slug ?? pro.id;
		entities.push({
			url: `${SITE_URL}/pros/${identifier}`,
			lastmod: toDateString(pro.dateUpdated),
			changefreq: "weekly",
			priority: 0.8,
		});
	}
 
	// Projects — prefer slug to avoid the id→slug 301 redirect on canonical URLs.
	for (const project of publishedProjects) {
		const identifier = project.slug ?? project.id;
		entities.push({
			url: `${SITE_URL}/projects/${identifier}`,
			lastmod: toDateString(project.dateUpdated),
			changefreq: "weekly",
			priority: 0.8,
		});
	}
 
	// Blogs — weekly if updated within 30 days, otherwise monthly
	const thirtyDaysAgo = Date.now() / 1000 - 30 * 24 * 60 * 60;
	for (const blog of indexableBlogs) {
		const lastmodTs = blog.publishedAt ?? blog.dateUpdated;
		const isRecent = typeof lastmodTs === "number" && lastmodTs > thirtyDaysAgo;
		entities.push({
			url: `${SITE_URL}/blog/${blog.slug}`,
			lastmod: toDateString(lastmodTs),
			changefreq: isRecent ? "weekly" : "monthly",
			priority: 0.7,
		});
	}
 
	const body: SitemapResponse = {
		entities,
		generatedAt: new Date().toISOString(),
	};
 
	return c.json(body, 200, {
		"Cache-Control": "public, s-maxage=172800, stale-while-revalidate=604800",
	});
});
 
export default sitemap;