All files / routes/marketplace sitemap.ts

99.1% Statements 111/112
89.18% Branches 33/37
100% Functions 29/29
100% Lines 99/99

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 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457                                              2x             104x                                             6x   188x 188x 188x   1x   188x                   2x                                     30x     1x                 8x 6x 1x 6x   1x       1x 6x   94x 92x             92x   1x     2x           2x                             31x 31x 31x       30x 30x 30x     30x               30x 180x                 30x 2760x                 30x 90x                 30x 120x                 30x               30x             30x     2x   2x 30x     30x                           30x                       30x                             30x 30x                   30x   2x 1x   30x 9x           30x 30x 30x 30x 1x 108x     30x 30x 4x 3x 2x                 30x 13x 13x                     30x 9x   30x 6x 6x                               30x 30x                     30x   7x     30x   8x                 30x 30x 507x 5x                     30x 4x                         30x     8x 8x     30x                   30x 1x                 30x 30x 8x 8x 8x               30x         30x            
// 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 {
	getRoomCategorySlug,
	ROOM_CATEGORY_SLUGS,
} from "@interioring/utils/constants/room-categories";
import { and, eq, inArray, isNotNull } from "drizzle-orm";
import { Hono } from "hono";
import { hasShowableCover } from "../../dal/projects-helpers";
import { getDb } from "../../db";
import { listMarketplaceCities } from "../../lib/cities/marketplace-cities";
import {
	blogCategories,
	blogPros,
	blogs,
	media,
	projects,
	pros,
	rooms,
} 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). Only
	// projects with something to show: the project page drops one with no
	// cover and no photo, so its URL would 404 (#1141).
	const publishedProjects = await db
		.select({
			id: projects.id,
			slug: projects.slug,
			proId: projects.proId,
			dateUpdated: projects.dateUpdated,
		})
		.from(projects)
		.where(and(eq(projects.status, "published"), hasShowableCover))
		.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),
	);
 
	// Hyderabad's 106 seed URLs stay when the cities table is empty (unit-test
	// mocks) or when Hyderabad is live. Other live cities are added by slug,
	// hub only — we do not invent zone URLs, and we never emit /interiors/bangalore.
	const directory = await listMarketplaceCities(db);
	const live = directory.filter((city) => city.marketplaceStatus === "live");
	let entities: SitemapEntity[] = [...(await buildStaticEntities())];
	if (directory.length > 0 && !live.some((city) => city.id === "hyderabad")) {
		entities = entities.filter(
			(entity) => !entity.url.includes("/interiors/hyderabad"),
		);
	}
	const today = new Date().toISOString().split("T")[0];
	for (const city of live) {
		if (city.id === "hyderabad") continue;
		if (city.slug === "bangalore" || city.slug === "hyderabad") continue;
		entities.push({
			url: `${SITE_URL}/interiors/${city.slug}`,
			lastmod: today,
			changefreq: "daily",
			priority: 1.0,
		});
	}
 
	// 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.
	// The project page 404s unless its pro is published too (projects.routes),
	// so a published project under a draft or archived pro is left out (#1141).
	const listedProjects = publishedProjects.filter((p) =>
		publishedProIds.has(p.proId),
	);
	for (const project of listedProjects) {
		const identifier = project.slug ?? project.id;
		entities.push({
			url: `${SITE_URL}/projects/${identifier}`,
			lastmod: toDateString(project.dateUpdated),
			changefreq: "weekly",
			priority: 0.8,
		});
	}
 
	// Rooms. /rooms/:category and /rooms/:category/:slug were in neither
	// sitemap, so Google only found them by crawling (Search Console audit
	// 2026-09-25). Same visibility rule as the /rooms listing
	// (rooms.dal findPublishedRooms + the no-media filter in rooms.routes):
	// a room shows only when its project and that project's pro are both
	// published and it has at least one photo. Filtered in JS rather than with
	// inArray() — the published-project id list would blow D1's 100-param
	// bind limit once the catalog grows.
	const listedProjectIds = new Set(listedProjects.map((p) => p.id));
	const sluggedRooms = await db
		.select({
			id: rooms.id,
			slug: rooms.slug,
			roomType: rooms.roomType,
			projectId: rooms.projectId,
			dateUpdated: rooms.dateUpdated,
		})
		.from(rooms)
		.where(isNotNull(rooms.slug))
		.all();
	const roomIdsWithMedia = new Set(
		(await db.selectDistinct({ roomId: media.roomId }).from(media).all()).map(
			(m) => m.roomId,
		),
	);
	const listedRooms = sluggedRooms.filter(
		(r): r is typeof r & { slug: string } =>
			Boolean(r.slug) &&
			listedProjectIds.has(r.projectId) &&
			roomIdsWithMedia.has(r.id),
	);
 
	// A category page is emitted only when it lists at least one room — an
	// empty category is a thin 200, the soft-404 pattern. Categories overlap
	// (kids_bedroom is in both bedroom and kids_room), so test membership per
	// category rather than bucketing through getRoomCategorySlug.
	const listedRoomTypes = new Set(listedRooms.map((r) => r.roomType));
	for (const category of ROOM_CATEGORY_SLUGS) {
		if (category.roomTypeCodes.some((code) => listedRoomTypes.has(code))) {
			entities.push({
				url: `${SITE_URL}/rooms/${category.value}`,
				lastmod: new Date().toISOString().split("T")[0],
				changefreq: "weekly",
				priority: 0.8,
			});
		}
	}
 
	// Detail URLs use the same room_type → category mapping as the page's own
	// canonical and the search index, so no URL here 301s.
	for (const room of listedRooms) {
		entities.push({
			url: `${SITE_URL}/rooms/${getRoomCategorySlug(room.roomType)}/${room.slug}`,
			lastmod: toDateString(room.dateUpdated),
			changefreq: "monthly",
			priority: 0.6,
		});
	}
 
	// 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;