All files / routes/marketplace sitemap.ts

98.76% Statements 80/81
81.81% Branches 18/22
100% Functions 20/20
100% Lines 75/75

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 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361                              1x             104x                                             6x   188x 188x 188x   1x   188x                   1x                                     23x     1x                 8x 6x 1x 6x   1x       1x 6x   94x 92x             92x   1x     1x           1x                             16x 16x 16x       23x 23x 23x     23x               23x 138x                 23x 2116x                 23x 69x                 23x 92x                 23x               23x             23x     1x   1x 23x     23x                       23x                     23x                             23x 23x                   23x   2x 1x   23x 9x     23x     23x 5x 5x                 23x 3x 3x                         23x     8x 8x     23x                   23x 1x                 23x 23x 8x 8x 8x               23x         23x            
// 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, inArray } from "drizzle-orm";
import { Hono } from "hono";
import { getDb } from "../../db";
import {
	blogCategories,
	blogPros,
	blogs,
	projects,
	pros,
} from "../../db/schema";
 
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.
 
// 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;
		}),
	);
}
 
type Geo = {
	ZONES: { slug: string; name: string }[];
	LOCALITIES: { zoneSlug: string; localitySlug: string }[];
};
 
let geoCache: Geo | null = null;
 
/**
 * Loads the seed taxonomy and derives the zone/locality URL lists.
 *
 * Lazily, and memoised — NOT at module scope, which is where this used to
 * live. The two seed modules pull in ~430 KB of authored locality prose, and
 * a Worker parses AND EVALUATES every statically-imported module during
 * startup, before it can serve anything. This route is one endpoint the
 * marketplace calls when it rebuilds its sitemap; every other request in the
 * API was paying for it on each cold start.
 *
 * That was one of two contributors to `dr-dev-api` exceeding Cloudflare's
 * startup CPU limit (validation error 10021) on the 2026-08-28 develop
 * deploy — the larger being the AWS SDK in `services/upload.service.ts`.
 *
 * The derived lists are small; the cache means a warm isolate does this once.
 */
async function loadGeo(): Promise<Geo> {
	if (geoCache) return geoCache;
 
	const [{ localitiesData, zonesData }, { hyderabadLocalitiesSeoData }] =
		await Promise.all([
			import("../../../seeds/taxonomy-data"),
			import("../../../seeds/seo-content-data"),
		]);
 
	// 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 zoneSlugById = new Map(
		hyderabadZones.map((z) => [z.id, toSlug(z.name)] as const),
	);
	const localityHasEditorial = buildLocalityEditorialMap(
		hyderabadLocalitiesSeoData,
	);
 
	geoCache = {
		ZONES: hyderabadZones.map((z) => ({ slug: toSlug(z.name), name: z.name })),
		LOCALITIES: 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),
	};
	return geoCache;
}
 
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];
}
 
async function buildStaticEntities(): Promise<SitemapEntity[]> {
	const { ZONES, LOCALITIES } = await loadGeo();
	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,
			categoryId: blogs.categoryId,
			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[] = [...(await 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,
		});
	}
 
	// Blog category pages. /blog/category/:slug is the crawlable, indexable
	// home for a category — the ?category= filter form is robots-blocked. Only
	// categories that actually hold an indexable post are emitted: an empty
	// category page is a 200 with no content, which is exactly the soft-404
	// pattern that buried this site's index coverage (indexing-diagnosis.md).
	const usedCategoryIds = [
		...new Set(
			indexableBlogs
				.map((b) => b.categoryId)
				.filter((id): id is string => Boolean(id)),
		),
	];
	const usedCategories = usedCategoryIds.length
		? await db
				.select({ slug: blogCategories.slug })
				.from(blogCategories)
				.where(inArray(blogCategories.id, usedCategoryIds))
				.all()
		: [];
 
	// /blog itself is already in the static @astrojs/sitemap build — don't
	// duplicate it across two sitemaps.
	for (const category of usedCategories) {
		entities.push({
			url: `${SITE_URL}/blog/category/${category.slug}`,
			lastmod: new Date().toISOString().split("T")[0],
			changefreq: "weekly",
			priority: 0.7,
		});
	}
 
	// 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;