Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Sitemap cron importer (#3637)

Pedro Ladeira5aa8f1f37f5c
diff --git a/apps/web/app/(ee)/api/cron/sitemaps/import/route.ts b/apps/web/app/(ee)/api/cron/sitemaps/import/route.ts
new file mode 100644
index 0000000000..f1af6f2a59
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/sitemaps/import/route.ts
@@ -0,0 +1,109 @@
+import { withCron } from "@/lib/cron/with-cron";
+import { importTrackedSitemaps } from "@/lib/sitemaps/import-tracked-sitemaps";
+import {
+ getOrCreateSiteLinksFolder,
+ getSiteLinksDomain,
+ parseTrackedSitemaps,
+ replaceTrackedSitemapsInColumn,
+} from "@/lib/sitemaps/site-visit-tracking";
+import { prisma } from "@dub/prisma";
+import * as z from "zod/v4";
+import { logAndRespond } from "../../utils";
+
+export const dynamic = "force-dynamic";
+
+const bodySchema = z.object({
+ workspaceId: z.string(),
+});
+
+// POST /api/cron/sitemaps/import - crawl tracked sitemaps and create missing links
+export const POST = withCron(async ({ rawBody }) => {
+ const { workspaceId } = bodySchema.parse(JSON.parse(rawBody));
+
+ const workspace = await prisma.project.findUnique({
+ where: {
+ id: workspaceId,
+ },
+ select: {
+ id: true,
+ slug: true,
+ siteVisitTrackingSettings: true,
+ },
+ });
+
+ if (!workspace) {
+ return logAndRespond(`Workspace ${workspaceId} not found. Skipping...`);
+ }
+
+ const trackedSitemaps = parseTrackedSitemaps(
+ workspace.siteVisitTrackingSettings,
+ );
+
+ if (trackedSitemaps.length === 0) {
+ return logAndRespond(
+ `Workspace ${workspace.slug} has no tracked sitemaps configured. Skipping...`,
+ );
+ }
+
+ const selectedDomain = await getSiteLinksDomain(
+ workspace.id,
+ workspace.siteVisitTrackingSettings,
+ );
+
+ if (!selectedDomain?.slug) {
+ return logAndRespond(
+ `Workspace ${workspace.slug} has no verified site links domain configured. Skipping...`,
+ );
+ }
+
+ const owner = await prisma.projectUsers.findFirst({
+ where: {
+ projectId: workspace.id,
+ role: "owner",
+ },
+ select: {
+ userId: true,
+ },
+ });
+
+ if (!owner) {
+ console.info("[sitemaps.cron.import] no workspace owner", {
+ workspaceId: workspace.id,
+ workspaceSlug: workspace.slug,
+ });
+
+ return logAndRespond(
+ `Workspace ${workspace.slug} has no owner user. Skipping...`,
+ );
+ }
+
+ const siteLinksFolderId = await getOrCreateSiteLinksFolder({
+ projectId: workspace.id,
+ userId: owner.userId,
+ });
+
+ const { linksToCreate, createdLinks, updatedTrackedSitemaps } =
+ await importTrackedSitemaps({
+ trackedSitemaps,
+ domain: selectedDomain.slug,
+ projectId: workspace.id,
+ userId: owner.userId,
+ folderId: siteLinksFolderId,
+ });
+
+ await prisma.project.update({
+ where: {
+ id: workspace.id,
+ },
+ data: {
+ siteVisitTrackingSettings: replaceTrackedSitemapsInColumn(
+ workspace.siteVisitTrackingSettings,
+ updatedTrackedSitemaps,
+ ),
+ },
+ });
+
+ return logAndRespond(
+ `Workspace ${workspace.slug}: found ${linksToCreate.length} new link(s), created ${createdLinks.length}.`,
+ );
+});
diff --git a/apps/web/app/(ee)/api/cron/sitemaps/queue/route.ts b/apps/web/app/(ee)/api/cron/sitemaps/queue/route.ts
new file mode 100644
index 0000000000..f810471fe8
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/sitemaps/queue/route.ts
@@ -0,0 +1,103 @@
+import { qstash } from "@/lib/cron";
+import { withCron } from "@/lib/cron/with-cron";
+import { prisma } from "@dub/prisma";
+import { Prisma } from "@dub/prisma/client";
+import { APP_DOMAIN_WITH_NGROK, log } from "@dub/utils";
+import * as z from "zod/v4";
+import { logAndRespond } from "../../utils";
+
+export const dynamic = "force-dynamic";
+
+const SITEMAP_QUEUE_BATCH_SIZE = 50;
+
+const bodySchema = z.object({
+ startingAfter: z.string().optional(),
+});
+
+async function runSitemapQueueBatch(startingAfter?: string) {
+ const cursorFragment = startingAfter
+ ? Prisma.sql`AND p.id > ${startingAfter}`
+ : Prisma.sql``;
+
+ const rows = await prisma.$queryRaw<Array<{ id: string }>>(
+ Prisma.sql`
+ SELECT p.id
+ FROM Project p
+ INNER JOIN Domain d ON d.projectId = p.id
+ AND d.slug = JSON_UNQUOTE(JSON_EXTRACT(p.siteVisitTrackingSettings, '$.siteDomainSlug'))
+ WHERE p.siteVisitTrackingSettings IS NOT NULL
+ AND JSON_LENGTH(JSON_EXTRACT(p.siteVisitTrackingSettings, '$.trackedSitemaps')) > 0
+ AND CHAR_LENGTH(TRIM(IFNULL(JSON_UNQUOTE(JSON_EXTRACT(p.siteVisitTrackingSettings, '$.siteDomainSlug')), ''))) > 0
+ ${cursorFragment}
+ ORDER BY p.id ASC
+ LIMIT ${SITEMAP_QUEUE_BATCH_SIZE}
+ `,
+ );
+
+ if (rows.length === 0) {
+ return {
+ queued: 0,
+ hasMore: false,
+ lastId: undefined as string | undefined,
+ };
+ }
+
+ const dayKey = new Date().toISOString().slice(0, 10);
+
+ await Promise.all(
+ rows.map(({ id }) =>
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/sitemaps/import`,
+ method: "POST",
+ body: {
+ workspaceId: id,
+ },
+ deduplicationId: `sitemap-import-${dayKey}-${id}`,
+ }),
+ ),
+ );
+
+ return {
+ queued: rows.length,
+ hasMore: rows.length === SITEMAP_QUEUE_BATCH_SIZE,
+ lastId: rows[rows.length - 1]?.id,
+ };
+}
+
+const handler = withCron(async ({ rawBody }) => {
+ const { startingAfter } = bodySchema.parse(
+ JSON.parse(rawBody?.trim() ? rawBody : "{}"),
+ );
+
+ const { queued, hasMore, lastId } = await runSitemapQueueBatch(startingAfter);
+
+ if (hasMore && lastId) {
+ const qstashResponse = await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/sitemaps/queue`,
+ method: "POST",
+ body: {
+ startingAfter: lastId,
+ },
+ });
+
+ if (!qstashResponse.messageId) {
+ await log({
+ message: `Error scheduling next sitemap queue batch: ${JSON.stringify(qstashResponse)}`,
+ type: "errors",
+ mention: true,
+ });
+ }
+
+ return logAndRespond(
+ `Queued ${queued} sitemap import job(s) for this batch. Scheduling next batch (startingAfter: ${lastId}).`,
+ );
+ }
+
+ return logAndRespond(
+ queued === 0 && !startingAfter
+ ? "No eligible workspaces for sitemap import."
+ : `Queued ${queued} sitemap import job(s) for this batch. No further batches.`,
+ );
+});
+
+export { handler as GET, handler as POST };
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/route.ts
index 7a28e26ca4..0261dee525 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/route.ts
@@ -7,14 +7,17 @@ import { prefixWorkspaceId } from "@/lib/api/workspaces/workspace-id";
import { withWorkspace } from "@/lib/auth";
import { getFeatureFlags } from "@/lib/edge-config";
import { jackson } from "@/lib/jackson";
+import { mergeSiteVisitTrackingSettings } from "@/lib/sitemaps/site-visit-tracking";
import { storage } from "@/lib/storage";
import { redis } from "@/lib/upstash";
import {
createWorkspaceSchema,
+ siteVisitTrackingSettingsPatchSchema,
WorkspaceSchema,
WorkspaceSchemaExtended,
} from "@/lib/zod/schemas/workspaces";
import { prisma } from "@dub/prisma";
+import { Prisma } from "@dub/prisma/client";
import { nanoid, R2_URL } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
@@ -35,6 +38,9 @@ const updateWorkspaceSchema = createWorkspaceSchema
])
.optional(),
enforceSAML: z.boolean().nullish(),
+ siteVisitTrackingSettings: siteVisitTrackingSettingsPatchSchema
+ .nullable()
+ .optional(),
})
.partial();
@@ -87,6 +93,7 @@ export const PATCH = withWorkspace(
allowedHostnames,
publishableKey,
enforceSAML,
+ siteVisitTrackingSettings,
} = await updateWorkspaceSchema.parseAsync(await parseRequestBody(req));
if (["free", "pro"].includes(workspace.plan) && conversionEnabled) {
@@ -130,6 +137,48 @@ export const PATCH = withWorkspace(
}
}
+ const flags = await getFeatureFlags({
+ workspaceId: workspace.id,
+ });
+
+ const mergedSiteVisitTrackingSettings =
+ siteVisitTrackingSettings !== undefined
+ ? mergeSiteVisitTrackingSettings(
+ workspace.siteVisitTrackingSettings,
+ siteVisitTrackingSettings,
+ )
+ : undefined;
+
+ if (
+ mergedSiteVisitTrackingSettings !== undefined &&
+ mergedSiteVisitTrackingSettings !== null &&
+ mergedSiteVisitTrackingSettings.siteDomainSlug
+ ) {
+ if (!flags.analyticsSettingsSiteVisitTracking) {
+ throw new DubApiError({
+ code: "forbidden",
+ message:
+ "Site visit tracking is not enabled for this workspace. Please contact support to enable it.",
+ });
+ }
+
+ const domain = await prisma.domain.findFirst({
+ where: {
+ projectId: workspace.id,
+ slug: mergedSiteVisitTrackingSettings.siteDomainSlug,
+ archived: false,
+ },
+ });
+
+ if (!domain) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "The selected site links domain was not found for this workspace.",
+ });
+ }
+ }
+
try {
const updatedWorkspace = await prisma.project.update({
where: {
@@ -147,6 +196,12 @@ export const PATCH = withWorkspace(
...(enforceSAML !== undefined && {
ssoEnforcedAt: enforceSAML ? new Date() : null,
}),
+ ...(mergedSiteVisitTrackingSettings !== undefined && {
+ siteVisitTrackingSettings:
+ mergedSiteVisitTrackingSettings === null
+ ? Prisma.JsonNull
+ : (mergedSiteVisitTrackingSettings as Prisma.InputJsonValue),
+ }),
},
include: {
domains: {
@@ -214,9 +269,6 @@ export const PATCH = withWorkspace(
WorkspaceSchema.parse({
...updatedWorkspace,
id: prefixWorkspaceId(updatedWorkspace.id),
- flags: await getFeatureFlags({
- workspaceId: updatedWorkspace.id,
- }),
}),
);
} catch (error) {
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/sitemaps/import/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/sitemaps/import/route.ts
new file mode 100644
index 0000000000..7832479226
--- /dev/null
+++ b/apps/web/app/api/workspaces/[idOrSlug]/sitemaps/import/route.ts
@@ -0,0 +1,123 @@
+import { DubApiError } from "@/lib/api/errors";
+import { withWorkspace } from "@/lib/auth";
+import { importTrackedSitemaps } from "@/lib/sitemaps/import-tracked-sitemaps";
+import {
+ getOrCreateSiteLinksFolder,
+ getSiteLinksDomain,
+ parseTrackedSitemaps,
+ replaceTrackedSitemapsInColumn,
+} from "@/lib/sitemaps/site-visit-tracking";
+import { ratelimit } from "@/lib/upstash";
+import { prisma } from "@dub/prisma";
+import { NextResponse } from "next/server";
+import * as z from "zod/v4";
+
+const bodySchema = z.object({
+ sitemapUrl: z.string().url().optional(),
+});
+
+// POST /api/workspaces/[idOrSlug]/sitemaps/import - import tracked sitemap(s) immediately
+export const POST = withWorkspace(
+ async ({ req, workspace, session }) => {
+ const { sitemapUrl } = bodySchema.parse(await req.json());
+
+ const trackedSitemaps = parseTrackedSitemaps(
+ workspace.siteVisitTrackingSettings,
+ );
+
+ if (trackedSitemaps.length === 0) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "No tracked sitemaps configured.",
+ });
+ }
+
+ const targetTrackedSitemaps = sitemapUrl
+ ? trackedSitemaps.filter((sitemap) => sitemap.url === sitemapUrl)
+ : trackedSitemaps;
+
+ if (targetTrackedSitemaps.length === 0) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Sitemap not found in tracked sitemaps.",
+ });
+ }
+
+ const rateLimitKey = `sitemap-import:${workspace.id}:${sitemapUrl ?? "all"}`;
+ const { success } = await ratelimit(5, "1 m").limit(rateLimitKey);
+ if (!success) {
+ throw new DubApiError({
+ code: "rate_limit_exceeded",
+ message:
+ "Sitemap import was requested too recently. Please wait a minute and try again.",
+ });
+ }
+
+ const selectedDomain = await getSiteLinksDomain(
+ workspace.id,
+ workspace.siteVisitTrackingSettings,
+ );
+
+ if (!selectedDomain?.slug) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "Configure a verified site links domain in site visit tracking settings.",
+ });
+ }
+
+ const siteLinksFolderId = await getOrCreateSiteLinksFolder({
+ projectId: workspace.id,
+ userId: session.user.id,
+ });
+
+ const { linksToCreate, createdLinks, updatedTrackedSitemaps } =
+ await importTrackedSitemaps({
+ trackedSitemaps: targetTrackedSitemaps,
+ domain: selectedDomain.slug,
+ projectId: workspace.id,
+ userId: session.user.id,
+ folderId: siteLinksFolderId,
+ });
+
+ const updatedByUrl = new Map(
+ updatedTrackedSitemaps.map((sitemap) => [sitemap.url, sitemap]),
+ );
+
+ // Re-read trackedSitemaps right before writing to avoid overwriting
+ // concurrent structural edits (add/delete) that happened during the import.
+ const freshWorkspace = await prisma.project.findUnique({
+ where: { id: workspace.id },
+ select: { siteVisitTrackingSettings: true },
+ });
+ const freshTrackedSitemaps = parseTrackedSitemaps(
+ freshWorkspace?.siteVisitTrackingSettings,
+ );
+
+ const mergedTrackedSitemaps = freshTrackedSitemaps.map((sitemap) => {
+ return updatedByUrl.get(sitemap.url) || sitemap;
+ });
+
+ await prisma.project.update({
+ where: {
+ id: workspace.id,
+ },
+ data: {
+ siteVisitTrackingSettings: replaceTrackedSitemapsInColumn(
+ freshWorkspace?.siteVisitTrackingSettings,
+ mergedTrackedSitemaps,
+ ),
+ },
+ });
+
+ return NextResponse.json({
+ processed: targetTrackedSitemaps.length,
+ found: linksToCreate.length,
+ created: createdLinks.length,
+ });
+ },
+ {
+ requiredPermissions: ["workspaces.write"],
+ featureFlag: "analyticsSettingsSiteVisitTracking",
+ },
+);
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/site-visit-tracking-section.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/site-visit-tracking-section.tsx
index 868f99ca77..f3197f3467 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/site-visit-tracking-section.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/site-visit-tracking-section.tsx
@@ -1,17 +1,42 @@
"use client";
import { clientAccessCheck } from "@/lib/client-access-check";
+import { MAX_TRACKED_SITEMAPS_PER_WORKSPACE } from "@/lib/zod/schemas/site-visit-tracking";
import useWorkspace from "@/lib/swr/use-workspace";
import { useWorkspaceStore } from "@/lib/swr/use-workspace-store";
-import { Button, InfoTooltip, LockSmall, Sitemap, Switch } from "@dub/ui";
-import { formatDate } from "@dub/utils";
+import { DomainSelector } from "@/ui/domains/domain-selector";
+import { ThreeDots } from "@/ui/shared/icons";
+import {
+ Button,
+ InfoTooltip,
+ LoadingSpinner,
+ LockSmall,
+ Popover,
+ Sitemap,
+ Switch,
+} from "@dub/ui";
+import { Trash } from "@dub/ui/icons";
+import { cn, formatDate } from "@dub/utils";
+import { RefreshCw } from "lucide-react";
import { motion } from "motion/react";
-import { useId } from "react";
+import { useId, useState } from "react";
import { toast } from "sonner";
export function SiteVisitTrackingSection() {
- const id = useId();
- const { role } = useWorkspace();
+ const switchId = useId();
+ const workspace = useWorkspace();
+ const { role, id, mutate } = workspace;
+ const siteVisitTrackingSettings = workspace.siteVisitTrackingSettings;
+ const trackedSitemaps = siteVisitTrackingSettings?.trackedSitemaps;
+ const siteDomainSlug = siteVisitTrackingSettings?.siteDomainSlug ?? "";
+ const [newSitemapUrl, setNewSitemapUrl] = useState("");
+ const [addingSitemap, setAddingSitemap] = useState(false);
+ const [refreshingSitemapUrl, setRefreshingSitemapUrl] = useState<
+ string | null
+ >(null);
+ const [deletingSitemapUrl, setDeletingSitemapUrl] = useState<string | null>(
+ null,
+ );
const [enabled, setEnabled, { loading }] = useWorkspaceStore<boolean>(
"analyticsSettingsSiteVisitTrackingEnabled",
@@ -19,6 +44,7 @@ export function SiteVisitTrackingSection() {
mutateOnSet: true,
},
);
+ const siteVisitTrackingEnabled = Boolean(enabled);
const permissionsError = clientAccessCheck({
action: "workspaces.write",
@@ -26,12 +52,286 @@ export function SiteVisitTrackingSection() {
customPermissionDescription: "manage site visit tracking",
}).error;
- const sitemaps = [
- {
- url: "dub.co/sitemap.xml",
- lastUpdated: new Date(),
- },
- ];
+ const trackedSitemapRows = Array.isArray(trackedSitemaps)
+ ? trackedSitemaps
+ .map((sitemap) => {
+ if (!sitemap?.url) {
+ return null;
+ }
+
+ return {
+ url: sitemap.url,
+ lastCrawledAt: sitemap.lastCrawledAt
+ ? new Date(sitemap.lastCrawledAt)
+ : null,
+ lastUrlCount:
+ typeof sitemap.lastUrlCount === "number"
+ ? sitemap.lastUrlCount
+ : null,
+ };
+ })
+ .filter(
+ (
+ sitemap,
+ ): sitemap is {
+ url: string;
+ lastCrawledAt: Date | null;
+ lastUrlCount: number | null;
+ } => Boolean(sitemap),
+ )
+ : [];
+
+ const sitemaps = siteVisitTrackingEnabled
+ ? trackedSitemapRows
+ : [
+ {
+ url: "dub.co/sitemap.xml",
+ lastCrawledAt: new Date(),
+ lastUrlCount: null,
+ },
+ ];
+
+ const serializeSitemaps = (
+ input: {
+ url: string;
+ lastCrawledAt: Date | null;
+ lastUrlCount: number | null;
+ }[],
+ ) =>
+ input.map((sitemap) => ({
+ url: sitemap.url,
+ ...(sitemap.lastCrawledAt
+ ? { lastCrawledAt: sitemap.lastCrawledAt.toISOString() }
+ : {}),
+ ...(typeof sitemap.lastUrlCount === "number"
+ ? { lastUrlCount: sitemap.lastUrlCount }
+ : {}),
+ }));
+
+ const normalizeSitemapUrl = (value: string) => {
+ const trimmed = value.trim();
+ if (!trimmed) {
+ return null;
+ }
+
+ const withProtocol =
+ trimmed.startsWith("http://") || trimmed.startsWith("https://")
+ ? trimmed
+ : `https://${trimmed}`;
+
+ try {
+ return new URL(withProtocol).toString();
+ } catch {
+ return null;
+ }
+ };
+
+ const persistSiteVisitTrackingSettings = async (payload: {
+ trackedSitemaps: {
+ url: string;
+ lastCrawledAt?: string;
+ lastUrlCount?: number;
+ }[];
+ siteDomainSlug?: string | null;
+ }) => {
+ if (!id) {
+ toast.error("Workspace is still loading. Please try again.");
+ return false;
+ }
+
+ const response = await fetch(`/api/workspaces/${id}`, {
+ method: "PATCH",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ siteVisitTrackingSettings: payload,
+ }),
+ });
+
+ if (!response.ok) {
+ const { error } = await response.json();
+ toast.error(error?.message || "Failed to save settings.");
+ return false;
+ }
+
+ await mutate();
+ return true;
+ };
+
+ const setSiteDomainSlug = async (slug: string) => {
+ if (permissionsError) {
+ toast.error(permissionsError);
+ return;
+ }
+
+ const ok = await persistSiteVisitTrackingSettings({
+ trackedSitemaps: serializeSitemaps(trackedSitemapRows),
+ siteDomainSlug: slug ? slug : null,
+ });
+
+ if (ok) {
+ toast.success(slug ? "Domain saved." : "Domain cleared.");
+ }
+ };
+
+ const addSitemap = async () => {
+ if (permissionsError) {
+ toast.error(permissionsError);
+ return;
+ }
+
+ if (!id) {
+ toast.error("Workspace is still loading. Please try again.");
+ return;
+ }
+
+ if (!siteDomainSlug) {
+ toast.error("Choose a domain for sitemap imports before adding sources.");
+ return;
+ }
+
+ const normalizedSitemapUrl = normalizeSitemapUrl(newSitemapUrl);
+
+ if (!normalizedSitemapUrl) {
+ toast.error("Enter a valid sitemap URL.");
+ return;
+ }
+
+ const sitemapAlreadyExists = sitemaps.some(
+ (sitemap) => sitemap.url === normalizedSitemapUrl,
+ );
+
+ if (sitemapAlreadyExists) {
+ toast.error("Sitemap already exists.");
+ return;
+ }
+
+ if (sitemaps.length >= MAX_TRACKED_SITEMAPS_PER_WORKSPACE) {
+ toast.error(
+ `You can track up to ${MAX_TRACKED_SITEMAPS_PER_WORKSPACE} sitemaps per workspace.`,
+ );
+ return;
+ }
+
+ setAddingSitemap(true);
+
+ try {
+ const ok = await persistSiteVisitTrackingSettings({
+ trackedSitemaps: [
+ ...serializeSitemaps(sitemaps),
+ {
+ url: normalizedSitemapUrl,
+ },
+ ],
+ siteDomainSlug,
+ });
+
+ if (ok) {
+ const importResponse = await fetch(
+ `/api/workspaces/${id}/sitemaps/import`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ sitemapUrl: normalizedSitemapUrl,
+ }),
+ },
+ );
+
+ if (importResponse.ok) {
+ toast.success("Sitemap added and crawled.");
+ } else {
+ try {
+ const { error } = await importResponse.json();
+ toast.error(error?.message || "Sitemap added, but crawl failed.");
+ } catch {
+ toast.error("Sitemap added, but crawl failed.");
+ }
+ }
+
+ setNewSitemapUrl("");
+ // Import updates crawl metadata on the server; revalidate so the row shows last crawled / URL count.
+ await mutate();
+ }
+ } catch {
+ toast.error("Network error, please try again or contact support.");
+ } finally {
+ setAddingSitemap(false);
+ }
+ };
+
+ const refreshSitemap = async (sitemapUrl: string) => {
+ if (permissionsError) {
+ toast.error(permissionsError);
+ return;
+ }
+
+ if (!id) {
+ toast.error("Workspace is still loading. Please try again.");
+ return;
+ }
+
+ setRefreshingSitemapUrl(sitemapUrl);
+
+ try {
+ const response = await fetch(`/api/workspaces/${id}/sitemaps/import`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ sitemapUrl,
+ }),
+ });
+
+ if (response.ok) {
+ toast.success("Sitemap refreshed.");
+ mutate();
+ } else {
+ const { error } = await response.json();
+ toast.error(error?.message || "Failed to refresh sitemap.");
+ }
+ } catch {
+ toast.error("Network error, please try again.");
+ } finally {
+ setRefreshingSitemapUrl(null);
+ }
+ };
+
+ const deleteSitemap = async (sitemapUrl: string) => {
+ if (permissionsError) {
+ toast.error(permissionsError);
+ return;
+ }
+
+ if (!id) {
+ toast.error("Workspace is still loading. Please try again.");
+ return;
+ }
+
+ setDeletingSitemapUrl(sitemapUrl);
+
+ const remainingSitemaps = sitemaps.filter(
+ (sitemap) => sitemap.url !== sitemapUrl,
+ );
+
+ try {
+ const ok = await persistSiteVisitTrackingSettings({
+ trackedSitemaps: serializeSitemaps(remainingSitemaps),
+ });
+
+ if (ok) {
+ toast.success("Sitemap deleted.");
+ }
+ } catch {
+ toast.error("Network error, please try again.");
+ } finally {
+ setDeletingSitemapUrl(null);
+ }
+ };
return (
<div className="flex flex-1 flex-col rounded-lg border border-neutral-200 bg-neutral-50">
@@ -39,7 +339,7 @@ export function SiteVisitTrackingSection() {
<div className="flex min-w-0 items-center gap-4">
<div className="overflow-hidden">
<label
- htmlFor={`${id}-switch`}
+ htmlFor={`${switchId}-switch`}
className="text-content-emphasis block text-sm font-semibold"
>
Site visit tracking
@@ -51,6 +351,7 @@ export function SiteVisitTrackingSection() {
</div>
<Switch
+ id={`${switchId}-switch`}
disabled={loading}
{...(permissionsError
? {
@@ -80,47 +381,185 @@ export function SiteVisitTrackingSection() {
}}
initial={false}
>
- <div className="flex flex-col gap-2 border-t border-neutral-200 p-3">
- <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
- <div className="flex items-center gap-1">
- <h2 className="text-content-emphasis text-sm font-semibold">
- Sitemaps
- </h2>
- <InfoTooltip content="Required for conversion tracking." />
+ <div className="flex flex-col gap-4 border-t border-neutral-200 p-3">
+ <div className="flex flex-col gap-2">
+ <div className="flex flex-col">
+ <label className="text-content-emphasis text-sm font-semibold">
+ Domain for sitemap imports
+ </label>
+ <p className="text-content-subtle text-xs font-medium">
+ This domain will be used for links we create when importing
+ pages from the sitemaps you add.
+ </p>
</div>
- <Button
- text="Add sitemap"
- className="h-7 w-fit rounded-lg px-2.5 py-1 text-sm font-medium"
- onClick={() => toast.info("Coming soon")}
+
+ <DomainSelector
+ selectedDomain={siteDomainSlug}
+ setSelectedDomain={(slug) => void setSiteDomainSlug(slug)}
+ disabled={Boolean(permissionsError)}
+ disabledTooltip={permissionsError || undefined}
/>
</div>
<div className="flex flex-col gap-2">
- {sitemaps.map((sitemap) => (
- <div
- key={sitemap.url}
- className="border-border-subtle flex items-center justify-between gap-4 rounded-xl border bg-white p-3"
- >
- <div className="flex min-w-0 items-center gap-2">
- <div className="flex size-[28px] items-center justify-center rounded-md bg-neutral-100">
- <Sitemap className="size-4 text-neutral-800" />
- </div>
- <span className="text-content-emphasis min-w-0 truncate text-sm font-semibold">
- {sitemap.url}
- </span>
- </div>
- <div className="flex items-center gap-2">
- {sitemap.lastUpdated && (
- <span className="text-content-subtle text-xs font-medium">
- Updated {formatDate(sitemap.lastUpdated)}
- </span>
- )}
- </div>
+ <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
+ <div className="flex items-center gap-1">
+ <h2 className="text-content-emphasis text-sm font-semibold">
+ Sitemaps
+ </h2>
+ <InfoTooltip content="Required for conversion tracking." />
</div>
- ))}
+ <div className="flex w-full items-center gap-2 sm:w-auto">
+ {siteVisitTrackingEnabled && (
+ <input
+ type="text"
+ value={newSitemapUrl}
+ onChange={(e) => setNewSitemapUrl(e.target.value)}
+ placeholder="e.g. www.acme.com/sitemap.xml"
+ className="h-7 w-full rounded-lg border border-neutral-300 px-2.5 text-sm focus:border-neutral-500 focus:outline-none focus:ring-0 sm:w-[260px]"
+ />
+ )}
+ <Button
+ text="Add sitemap"
+ className="h-7 w-fit rounded-lg px-2.5 py-1 text-sm font-medium"
+ onClick={() =>
+ siteVisitTrackingEnabled
+ ? addSitemap()
+ : toast.info("Coming soon")
+ }
+ loading={addingSitemap}
+ disabled={
+ Boolean(permissionsError) ||
+ (siteVisitTrackingEnabled && !siteDomainSlug) ||
+ (siteVisitTrackingEnabled &&
+ trackedSitemapRows.length >=
+ MAX_TRACKED_SITEMAPS_PER_WORKSPACE)
+ }
+ disabledTooltip={
+ permissionsError ||
+ (siteVisitTrackingEnabled && !siteDomainSlug
+ ? "Choose a domain for imports first"
+ : undefined) ||
+ (siteVisitTrackingEnabled &&
+ trackedSitemapRows.length >= MAX_TRACKED_SITEMAPS_PER_WORKSPACE
+ ? `Maximum ${MAX_TRACKED_SITEMAPS_PER_WORKSPACE} sitemaps per workspace`
+ : undefined)
+ }
+ />
+ </div>
+ </div>
+
+ <div className="flex flex-col gap-2">
+ {siteVisitTrackingEnabled && sitemaps.length === 0 ? (
+ <div className="text-content-subtle rounded-xl border border-dashed border-neutral-300 bg-white p-3 text-sm">
+ No tracked sitemaps configured yet.
+ </div>
+ ) : (
+ sitemaps.map((sitemap) => (
+ <div
+ key={sitemap.url}
+ className="border-border-subtle flex items-center justify-between gap-4 rounded-xl border bg-white p-3"
+ >
+ <div className="flex min-w-0 items-center gap-2">
+ <div className="flex size-[28px] items-center justify-center rounded-md bg-neutral-100">
+ <Sitemap className="size-4 text-neutral-800" />
+ </div>
+ <div className="flex min-w-0 flex-col">
+ <span className="text-content-emphasis min-w-0 truncate text-sm font-semibold">
+ {sitemap.url}
+ </span>
+ <span className="text-content-subtle text-xs font-medium">
+ {sitemap.lastCrawledAt
+ ? `Last crawled ${formatDate(sitemap.lastCrawledAt)}`
+ : "Not crawled yet"}
+ {sitemap.lastUrlCount !== null
+ ? ` · ${sitemap.lastUrlCount} URLs found`
+ : ""}
+ </span>
+ </div>
+ </div>
+ {siteVisitTrackingEnabled && (
+ <SitemapRowMenu
+ onRefresh={() => refreshSitemap(sitemap.url)}
+ onDelete={() => deleteSitemap(sitemap.url)}
+ loading={
+ refreshingSitemapUrl === sitemap.url ||
+ deletingSitemapUrl === sitemap.url
+ }
+ />
+ )}
+ </div>
+ ))
+ )}
+ </div>
</div>
</div>
</motion.div>
</div>
);
}
+
+function SitemapRowMenu({
+ onRefresh,
+ onDelete,
+ loading,
+}: {
+ onRefresh: () => void;
+ onDelete: () => void;
+ loading: boolean;
+}) {
+ const [openPopover, setOpenPopover] = useState(false);
+
+ return (
+ <Popover
+ content={
+ <div className="w-full sm:w-48">
+ <div className="grid gap-px p-2">
+ <Button
+ text="Refresh source"
+ variant="outline"
+ onClick={() => {
+ setOpenPopover(false);
+ onRefresh();
+ }}
+ icon={<RefreshCw className="h-4 w-4" />}
+ className="h-9 justify-start px-2 font-medium"
+ />
+ </div>
+ <div className="border-t border-neutral-200" />
+ <div className="grid gap-px p-2">
+ <Button
+ text="Delete source"
+ variant="danger-outline"
+ onClick={() => {
+ setOpenPopover(false);
+ onDelete();
+ }}
+ icon={<Trash className="size-4" />}
+ className="h-9 justify-start px-2 font-medium"
+ />
+ </div>
+ </div>
+ }
+ align="end"
+ openPopover={openPopover}
+ setOpenPopover={setOpenPopover}
+ >
+ <Button
+ variant="outline"
+ className={cn(
+ "h-8 w-fit px-1.5 outline-none transition-all duration-200",
+ "border-transparent data-[state=open]:border-neutral-500 sm:group-hover/card:data-[state=closed]:border-neutral-200",
+ )}
+ icon={
+ loading ? (
+ <LoadingSpinner className="size-4 shrink-0" />
+ ) : (
+ <ThreeDots className="size-5 shrink-0" />
+ )
+ }
+ onClick={() => setOpenPopover(!openPopover)}
+ />
+ </Popover>
+ );
+}
diff --git a/apps/web/lib/sitemaps/import-tracked-sitemaps.ts b/apps/web/lib/sitemaps/import-tracked-sitemaps.ts
new file mode 100644
index 0000000000..15256e684c
--- /dev/null
+++ b/apps/web/lib/sitemaps/import-tracked-sitemaps.ts
@@ -0,0 +1,234 @@
+import { bulkCreateLinks } from "@/lib/api/links/bulk-create-links";
+import type { TrackedSitemap } from "@/lib/sitemaps/site-visit-tracking";
+import { ProcessedLinkProps } from "@/lib/types";
+import { prisma } from "@dub/prisma";
+import { fetchWithTimeout } from "@dub/utils/src";
+import { XMLParser } from "fast-xml-parser";
+
+type SitemapXmlUrlEntry = {
+ loc?: string;
+};
+
+type SitemapXmlResult = {
+ urlset?: {
+ url?: SitemapXmlUrlEntry | SitemapXmlUrlEntry[];
+ };
+ sitemapindex?: {
+ sitemap?: SitemapXmlUrlEntry | SitemapXmlUrlEntry[];
+ };
+};
+
+const parser = new XMLParser();
+
+function toArray<T>(value: T | T[] | undefined): T[] {
+ if (!value) {
+ return [];
+ }
+ return Array.isArray(value) ? value : [value];
+}
+
+function extractKeyFromUrl(url: string) {
+ const urlObj = new URL(url);
+ const key = urlObj.pathname.slice(1);
+ return key === "" ? "_root" : key;
+}
+
+/** Max page URLs collected from a single registered sitemap file (no nested fetches). */
+export const MAX_URLS_PER_SITEMAP = 2000;
+
+async function decompressIfGzip(buffer: ArrayBuffer): Promise<string> {
+ const bytes = new Uint8Array(buffer);
+
+ // Gzip magic bytes: 0x1f 0x8b
+ if (bytes[0] === 0x1f && bytes[1] === 0x8b) {
+ const ds = new DecompressionStream("gzip");
+ const writer = ds.writable.getWriter();
+ const reader = ds.readable.getReader();
+
+ writer.write(bytes);
+ writer.close();
+
+ const chunks: Uint8Array[] = [];
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ chunks.push(value);
+ }
+
+ const total = chunks.reduce((acc, c) => acc + c.length, 0);
+ const decompressed = new Uint8Array(total);
+ let offset = 0;
+ for (const chunk of chunks) {
+ decompressed.set(chunk, offset);
+ offset += chunk.length;
+ }
+
+ return new TextDecoder().decode(decompressed);
+ }
+
+ return new TextDecoder().decode(bytes);
+}
+
+async function fetchAndParseSitemap(
+ sitemapUrl: string,
+): Promise<SitemapXmlResult> {
+ const response = await fetchWithTimeout(sitemapUrl, { redirect: "error" }); // don't follow redirects
+ const MAX_SITEMAP_BYTES = 10 * 1024 * 1024; // 10 MB
+ const contentLength = response.headers.get("content-length");
+ if (contentLength && parseInt(contentLength, 10) > MAX_SITEMAP_BYTES) {
+ throw new Error(`Sitemap too large (Content-Length: ${contentLength})`);
+ }
+ const buffer = await response.arrayBuffer();
+ if (buffer.byteLength > MAX_SITEMAP_BYTES) {
+ throw new Error(`Sitemap response too large: ${buffer.byteLength} bytes`);
+ }
+ const xml = await decompressIfGzip(buffer);
+ return parser.parse(xml) as SitemapXmlResult;
+}
+
+export async function crawlSitemapUrls(sitemapUrl: string) {
+ let hadErrors = false;
+
+ let parsed: SitemapXmlResult;
+ try {
+ parsed = await fetchAndParseSitemap(sitemapUrl);
+ } catch (error) {
+ console.error(`Failed to fetch sitemap ${sitemapUrl}:`, error);
+ return { urls: [] as string[], hadErrors: true };
+ }
+
+ const urlsetLocs = toArray(parsed.urlset?.url)
+ .map((entry) => entry?.loc?.trim())
+ .filter((url): url is string => Boolean(url));
+
+ const urls = Array.from(
+ new Set(urlsetLocs.filter((url) => !url.endsWith(".xml"))),
+ );
+
+ if (urls.length > MAX_URLS_PER_SITEMAP) {
+ throw new Error(
+ `Sitemap contains too many unique URLs: ${urls.length} (max ${MAX_URLS_PER_SITEMAP})`,
+ );
+ }
+
+ return { urls, hadErrors };
+}
+
+export async function importTrackedSitemaps({
+ trackedSitemaps,
+ domain,
+ projectId,
+ userId,
+ folderId,
+}: {
+ trackedSitemaps: TrackedSitemap[];
+ domain: string;
+ projectId: string;
+ userId?: string;
+ folderId?: string;
+}) {
+ const nowIso = new Date().toISOString();
+
+ const results = await Promise.all(
+ trackedSitemaps.map(async (sitemap) => {
+ const sitemapLinks = new Map<string, ProcessedLinkProps>();
+
+ try {
+ const { urls: crawledUrls, hadErrors } = await crawlSitemapUrls(
+ sitemap.url,
+ );
+
+ for (const url of crawledUrls) {
+ let key: string;
+ try {
+ key = extractKeyFromUrl(url);
+ } catch {
+ continue;
+ }
+
+ if (!sitemapLinks.has(key)) {
+ sitemapLinks.set(key, {
+ domain,
+ key,
+ url,
+ trackConversion: true,
+ projectId,
+ ...(userId ? { userId } : {}),
+ ...(folderId ? { folderId } : {}),
+ });
+ }
+ }
+
+ if (hadErrors) {
+ return { sitemap: { ...sitemap }, sitemapLinks };
+ }
+
+ return {
+ sitemap: {
+ ...sitemap,
+ lastCrawledAt: nowIso,
+ lastUrlCount: crawledUrls.length,
+ },
+ sitemapLinks,
+ };
+ } catch (error) {
+ console.error(`Failed to crawl sitemap ${sitemap.url}:`, error);
+
+ return { sitemap: { ...sitemap }, sitemapLinks };
+ }
+ }),
+ );
+
+ const linksByKey = new Map<string, ProcessedLinkProps>();
+ for (const { sitemapLinks } of results) {
+ for (const [key, link] of sitemapLinks) {
+ if (!linksByKey.has(key)) {
+ linksByKey.set(key, link);
+ }
+ }
+ }
+
+ const updatedTrackedSitemaps = results.map((r) => r.sitemap);
+
+ const candidateLinks = Array.from(linksByKey.values());
+ const candidateKeys = candidateLinks.map((link) => link.key);
+
+ const existingLinks = await prisma.link.findMany({
+ where: {
+ domain,
+ key: {
+ in: candidateKeys,
+ },
+ },
+ select: {
+ key: true,
+ },
+ });
+
+ const existingKeys = new Set(existingLinks.map((link) => link.key));
+
+ const linksToCreate = candidateLinks.filter(
+ (link) => !existingKeys.has(link.key),
+ );
+
+ console.log(
+ `[importTrackedSitemaps] Found ${linksToCreate.length} links to create, running bulkCreateLinks...`,
+ );
+
+ const createdLinks = await bulkCreateLinks({
+ links: linksToCreate,
+ skipRedisCache: true,
+ });
+
+ console.log({
+ linksToCreate,
+ createdLinks,
+ updatedTrackedSitemaps,
+ });
+
+ return {
+ linksToCreate,
+ createdLinks,
+ updatedTrackedSitemaps,
+ };
+}
diff --git a/apps/web/lib/sitemaps/site-visit-tracking.ts b/apps/web/lib/sitemaps/site-visit-tracking.ts
new file mode 100644
index 0000000000..1ff7b467a1
--- /dev/null
+++ b/apps/web/lib/sitemaps/site-visit-tracking.ts
@@ -0,0 +1,279 @@
+import { createId } from "@/lib/api/create-id";
+import {
+ MAX_TRACKED_SITEMAPS_PER_WORKSPACE,
+ siteVisitTrackingSettingsValueSchema,
+ trackedSitemapSchema,
+} from "@/lib/zod/schemas/site-visit-tracking";
+import { prisma } from "@dub/prisma";
+import { Prisma } from "@dub/prisma/client";
+import type { z } from "zod/v4";
+import * as zod from "zod/v4";
+
+// -----------------------------------------------------------------------------
+// Site visit tracking settings (`Project.siteVisitTrackingSettings` JSON)
+// -----------------------------------------------------------------------------
+
+export type TrackedSitemap = z.infer<typeof trackedSitemapSchema>;
+
+export type SiteVisitTrackingSettingsValue = z.infer<
+ typeof siteVisitTrackingSettingsValueSchema
+>;
+
+function isPlainRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+/**
+ * Parses `trackedSitemaps` JSON with array-level rules: must be an array, each
+ * entry must be a plain object, at most MAX_TRACKED_SITEMAPS_PER_WORKSPACE
+ * entries are considered (excess is truncated). Returns [] if array-level
+ * checks fail. Invalid URLs or shape per row are skipped without failing the list.
+ */
+function parseTrackedSitemapsArrayLoose(arr: unknown): TrackedSitemap[] {
+ if (!Array.isArray(arr)) {
+ return [];
+ }
+
+ const capped = arr.slice(0, MAX_TRACKED_SITEMAPS_PER_WORKSPACE);
+
+ for (const item of capped) {
+ if (!isPlainRecord(item)) {
+ return [];
+ }
+ }
+
+ const result: TrackedSitemap[] = [];
+
+ for (const raw of capped) {
+ const url = typeof raw.url === "string" ? raw.url.trim() : "";
+ if (!url) {
+ continue;
+ }
+
+ const candidate: {
+ url: string;
+ lastCrawledAt?: string;
+ lastUrlCount?: number;
+ } = { url };
+
+ if (typeof raw.lastCrawledAt === "string") {
+ candidate.lastCrawledAt = raw.lastCrawledAt;
+ }
+ if (typeof raw.lastUrlCount === "number") {
+ candidate.lastUrlCount = raw.lastUrlCount;
+ }
+
+ const parsed = trackedSitemapSchema.safeParse(candidate);
+ if (parsed.success) {
+ result.push(parsed.data);
+ }
+ }
+
+ return result;
+}
+
+export function parseSiteVisitTrackingSettings(
+ value: unknown,
+): SiteVisitTrackingSettingsValue {
+ if (value === null || value === undefined) {
+ return { trackedSitemaps: [] };
+ }
+ if (typeof value !== "object" || Array.isArray(value)) {
+ return { trackedSitemaps: [] };
+ }
+
+ const o = value as Record<string, unknown>;
+ const trackedSitemaps = parseTrackedSitemapsArrayLoose(o.trackedSitemaps);
+
+ const merged = {
+ trackedSitemaps,
+ ...(typeof o.siteDomainSlug === "string"
+ ? { siteDomainSlug: o.siteDomainSlug }
+ : {}),
+ ...(typeof o.siteLinksFolderId === "string"
+ ? { siteLinksFolderId: o.siteLinksFolderId }
+ : {}),
+ };
+
+ const parsed = siteVisitTrackingSettingsValueSchema.safeParse(merged);
+ if (parsed.success) {
+ return parsed.data;
+ }
+
+ return {
+ trackedSitemaps: [],
+ ...(typeof o.siteDomainSlug === "string"
+ ? { siteDomainSlug: o.siteDomainSlug }
+ : {}),
+ ...(typeof o.siteLinksFolderId === "string"
+ ? { siteLinksFolderId: o.siteLinksFolderId }
+ : {}),
+ };
+}
+
+export function parseTrackedSitemaps(value: unknown): TrackedSitemap[] {
+ return parseSiteVisitTrackingSettings(value).trackedSitemaps;
+}
+
+export function mergeSiteVisitTrackingSettings(
+ existing: unknown,
+ patch: {
+ trackedSitemaps?: TrackedSitemap[] | null;
+ siteDomainSlug?: string | null;
+ siteLinksFolderId?: string | null;
+ } | null,
+): SiteVisitTrackingSettingsValue | null {
+ if (patch === null) {
+ return null;
+ }
+
+ const base = parseSiteVisitTrackingSettings(existing);
+
+ const trackedSitemaps =
+ patch.trackedSitemaps !== undefined && patch.trackedSitemaps !== null
+ ? patch.trackedSitemaps
+ : base.trackedSitemaps;
+
+ const siteDomainSlug =
+ patch.siteDomainSlug !== undefined
+ ? patch.siteDomainSlug ?? undefined
+ : base.siteDomainSlug;
+
+ const siteLinksFolderId =
+ patch.siteLinksFolderId !== undefined
+ ? patch.siteLinksFolderId ?? undefined
+ : base.siteLinksFolderId;
+
+ const out: SiteVisitTrackingSettingsValue = { trackedSitemaps };
+ if (siteDomainSlug) {
+ out.siteDomainSlug = siteDomainSlug;
+ }
+ if (siteLinksFolderId) {
+ out.siteLinksFolderId = siteLinksFolderId;
+ }
+ return out;
+}
+
+export function replaceTrackedSitemapsInColumn(
+ existing: unknown,
+ trackedSitemaps: TrackedSitemap[],
+): SiteVisitTrackingSettingsValue {
+ const base = parseSiteVisitTrackingSettings(existing);
+ return {
+ ...base,
+ trackedSitemaps,
+ };
+}
+
+export const workspaceSiteVisitTrackingSettingsFieldSchema = zod.preprocess(
+ (v) =>
+ v === null || v === undefined ? null : parseSiteVisitTrackingSettings(v),
+ zod.union([siteVisitTrackingSettingsValueSchema, zod.null()]),
+);
+
+// -----------------------------------------------------------------------------
+// Verified domain for sitemap-import short links
+// -----------------------------------------------------------------------------
+
+export async function getSiteLinksDomain(
+ projectId: string,
+ siteVisitTrackingSettings: unknown,
+) {
+ const { siteDomainSlug } = parseSiteVisitTrackingSettings(
+ siteVisitTrackingSettings,
+ );
+
+ if (!siteDomainSlug) {
+ return null;
+ }
+
+ return prisma.domain.findFirst({
+ where: {
+ projectId,
+ slug: siteDomainSlug,
+ },
+ select: {
+ slug: true,
+ },
+ });
+}
+
+// -----------------------------------------------------------------------------
+// "Site Links" folder for imported links
+// -----------------------------------------------------------------------------
+
+export const SITE_LINKS_FOLDER_NAME = "Site Links";
+
+export async function getOrCreateSiteLinksFolder({
+ projectId,
+ userId,
+}: {
+ projectId: string;
+ userId: string;
+}): Promise<string> {
+ const project = await prisma.project.findUnique({
+ where: { id: projectId },
+ select: { siteVisitTrackingSettings: true },
+ });
+
+ const columnSettings = parseSiteVisitTrackingSettings(
+ project?.siteVisitTrackingSettings,
+ );
+ const storedFolderId = columnSettings.siteLinksFolderId;
+
+ if (storedFolderId) {
+ const existingById = await prisma.folder.findFirst({
+ where: {
+ id: storedFolderId,
+ projectId,
+ },
+ select: { id: true },
+ });
+
+ if (existingById) {
+ return existingById.id;
+ }
+ }
+
+ const newFolderId = createId({ prefix: "fold_" });
+
+ const folder = await prisma.folder.upsert({
+ where: {
+ name_projectId: {
+ name: SITE_LINKS_FOLDER_NAME,
+ projectId,
+ },
+ },
+ update: {},
+ create: {
+ id: newFolderId,
+ name: SITE_LINKS_FOLDER_NAME,
+ projectId,
+ accessLevel: "write",
+ users: {
+ create: {
+ userId,
+ role: "owner",
+ },
+ },
+ },
+ });
+
+ const merged = mergeSiteVisitTrackingSettings(
+ project?.siteVisitTrackingSettings,
+ { siteLinksFolderId: folder.id },
+ );
+
+ if (!merged) {
+ return folder.id;
+ }
+
+ await prisma.project.update({
+ where: { id: projectId },
+ data: {
+ siteVisitTrackingSettings: merged as Prisma.InputJsonValue,
+ },
+ });
+
+ return folder.id;
+}
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 216215143c..ef5d375ca9 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -1,3 +1,4 @@
+import type { SiteVisitTrackingSettingsValue } from "@/lib/sitemaps/site-visit-tracking";
import {
PartnerBountySchema,
partnerBountySubmissionSchema,
@@ -263,9 +264,11 @@ export type BetaFeatures = "noDubLink" | "analyticsSettingsSiteVisitTracking";
export type PartnerBetaFeatures = "postbacks";
-export interface WorkspaceProps extends Project {
+export interface WorkspaceProps
+ extends Omit<Project, "siteVisitTrackingSettings"> {
logo: string | null;
plan: PlanProps;
+ siteVisitTrackingSettings: SiteVisitTrackingSettingsValue | null;
domains: {
slug: string;
primary: boolean;
diff --git a/apps/web/lib/zod/schemas/site-visit-tracking.ts b/apps/web/lib/zod/schemas/site-visit-tracking.ts
new file mode 100644
index 0000000000..5284e5f91d
--- /dev/null
+++ b/apps/web/lib/zod/schemas/site-visit-tracking.ts
@@ -0,0 +1,33 @@
+import * as z from "zod/v4";
+
+export const trackedSitemapSchema = z.object({
+ url: z.url().refine((v) => v.startsWith("https://"), {
+ message: "Only HTTPS sitemap URLs are allowed.",
+ }),
+ lastCrawledAt: z.string().optional(),
+ lastUrlCount: z.number().int().nonnegative().optional(),
+});
+
+/** Max tracked sitemap sources per workspace (enforced on PATCH). */
+export const MAX_TRACKED_SITEMAPS_PER_WORKSPACE = 10;
+
+export const siteVisitTrackingSettingsValueSchema = z.object({
+ trackedSitemaps: z
+ .array(trackedSitemapSchema)
+ .max(MAX_TRACKED_SITEMAPS_PER_WORKSPACE)
+ .default([]),
+ siteDomainSlug: z.string().optional(),
+ siteLinksFolderId: z.string().optional(),
+});
+
+export const siteVisitTrackingSettingsPatchSchema = z
+ .object({
+ trackedSitemaps: z
+ .array(trackedSitemapSchema)
+ .max(MAX_TRACKED_SITEMAPS_PER_WORKSPACE)
+ .nullable()
+ .optional(),
+ siteDomainSlug: z.string().nullable().optional(),
+ siteLinksFolderId: z.string().nullable().optional(),
+ })
+ .partial();
diff --git a/apps/web/lib/zod/schemas/workspaces.ts b/apps/web/lib/zod/schemas/workspaces.ts
index 44747f7f63..b4f8250b95 100644
--- a/apps/web/lib/zod/schemas/workspaces.ts
+++ b/apps/web/lib/zod/schemas/workspaces.ts
@@ -1,3 +1,4 @@
+import { workspaceSiteVisitTrackingSettingsFieldSchema } from "@/lib/sitemaps/site-visit-tracking";
import { WorkspaceRole } from "@dub/prisma/client";
import { DEFAULT_REDIRECTS, RESERVED_SLUGS, validSlugRegex } from "@dub/utils";
import slugify from "@sindresorhus/slugify";
@@ -5,6 +6,11 @@ import * as z from "zod/v4";
import { DomainSchema } from "./domains";
import { googleUserContentUrlSchema, uploadedImageSchema } from "./images";
import { planSchema, roleSchema } from "./misc";
+export {
+ MAX_TRACKED_SITEMAPS_PER_WORKSPACE,
+ siteVisitTrackingSettingsPatchSchema,
+ trackedSitemapSchema,
+} from "./site-visit-tracking";
export const workspaceIdSchema = z.object({
workspaceId: z
@@ -134,6 +140,12 @@ export const WorkspaceSchema = z
.record(z.string(), z.any())
.nullable()
.describe("The miscellaneous key-value store of the workspace."),
+ siteVisitTrackingSettings: workspaceSiteVisitTrackingSettingsFieldSchema
+ .nullable()
+ .optional()
+ .describe(
+ "Site visit tracking: sitemaps, short-link domain slug, and Site Links folder id.",
+ ),
allowedHostnames: z
.array(z.string())
.nullable()
diff --git a/apps/web/scripts/send-batch-emails.ts b/apps/web/scripts/send-batch-emails.ts
index 7b4cb08b5d..edb2f37171 100644
--- a/apps/web/scripts/send-batch-emails.ts
+++ b/apps/web/scripts/send-batch-emails.ts
@@ -12,6 +12,7 @@ async function main() {
partners: {
some: {
partner: {
+ identityVerifiedAt: null,
payouts: {
some: {
status: "completed",
diff --git a/apps/web/scripts/sitemap-importer.ts b/apps/web/scripts/sitemap-importer.ts
index 5babd36665..a7fe17cbc8 100644
--- a/apps/web/scripts/sitemap-importer.ts
+++ b/apps/web/scripts/sitemap-importer.ts
@@ -1,71 +1,20 @@
-import { createId } from "@/lib/api/create-id";
-import { prisma } from "@dub/prisma";
import "dotenv-flow/config";
-import { XMLParser } from "fast-xml-parser";
-import { bulkCreateLinks } from "../lib/api/links/bulk-create-links";
-
-async function fetchSitemap(url: string) {
- const response = await fetch(url);
- const xml = await response.text();
- const parser = new XMLParser();
- const result = parser.parse(xml);
- return result.urlset.url.map((entry: { loc: string }) => entry.loc);
-}
+import { importTrackedSitemaps } from "../lib/sitemaps/import-tracked-sitemaps";
const sitemapUrl = "https://dub.co/sitemap.xml";
const domain = "site.dub.co";
const projectId = "ws_xxx";
-const userId = "user_xxx";
-const folderId = "fold_xxx";
async function main() {
- // Fetch and parse sitemap
- const sitemapUrls = await fetchSitemap(sitemapUrl);
-
- const validUrls = sitemapUrls
- // filter out other sitemaps
- .filter((url: string) => !url.endsWith("sitemap.xml"))
- .map((url: string) => {
- const urlObj = new URL(url);
- let key = urlObj.pathname.slice(1);
- // convert homepage to _root
- if (key === "") {
- key = "_root";
- }
- return {
- id: createId({ prefix: "link_" }),
- domain,
- key,
- url,
- trackConversion: true,
- projectId,
- userId,
- folderId,
- };
- })
- .slice(0, 1000);
-
- const existingLinks = await prisma.link.findMany({
- where: {
- domain,
- key: {
- in: validUrls.map((link) => link.key),
- },
- },
+ const { linksToCreate, createdLinks } = await importTrackedSitemaps({
+ trackedSitemaps: [{ url: sitemapUrl }],
+ domain,
+ projectId,
});
- const linksToCreate = validUrls.filter(
- (link) => !existingLinks.some((l) => l.key === link.key),
- );
-
console.table(linksToCreate);
console.log(`Found ${linksToCreate.length} links to create`);
-
- const res = await bulkCreateLinks({
- links: linksToCreate,
- skipRedisCache: true,
- });
- console.log(`Created ${res.length} links`);
+ console.log(`Created ${createdLinks.length} links`);
}
main().catch(console.error);
diff --git a/apps/web/tests/misc/import-tracked-sitemaps.test.ts b/apps/web/tests/misc/import-tracked-sitemaps.test.ts
new file mode 100644
index 0000000000..492e7e937d
--- /dev/null
+++ b/apps/web/tests/misc/import-tracked-sitemaps.test.ts
@@ -0,0 +1,287 @@
+import {
+ crawlSitemapUrls,
+ MAX_URLS_PER_SITEMAP,
+} from "@/lib/sitemaps/import-tracked-sitemaps";
+import { parseTrackedSitemaps } from "@/lib/sitemaps/site-visit-tracking";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { gzipSync } from "zlib";
+
+function toArrayBuffer(buf: Buffer): ArrayBuffer {
+ const ab = new ArrayBuffer(buf.length);
+ new Uint8Array(ab).set(buf);
+ return ab;
+}
+
+function makeFetchResponse(
+ body: Buffer,
+ status = 200,
+ headers?: Record<string, string>,
+): Response {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ headers: new Headers(headers),
+ arrayBuffer: () => Promise.resolve(toArrayBuffer(body)),
+ } as unknown as Response;
+}
+
+function redirectResponse(location: string, status = 302): Response {
+ return makeFetchResponse(Buffer.alloc(0), status, { Location: location });
+}
+
+const urlsetXml = (urls: string[]) =>
+ `<?xml version="1.0" encoding="UTF-8"?>
+<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
+ ${urls.map((u) => `<url><loc>${u}</loc></url>`).join("\n ")}
+</urlset>`;
+
+const sitemapindexXml = (sitemaps: string[]) =>
+ `<?xml version="1.0" encoding="UTF-8"?>
+<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
+ ${sitemaps.map((u) => `<sitemap><loc>${u}</loc></sitemap>`).join("\n ")}
+</sitemapindex>`;
+
+describe("parseTrackedSitemaps", () => {
+ it("returns empty array for invalid top-level input", () => {
+ expect(parseTrackedSitemaps(null)).toEqual([]);
+ expect(parseTrackedSitemaps(undefined)).toEqual([]);
+ expect(parseTrackedSitemaps("string")).toEqual([]);
+ expect(parseTrackedSitemaps(42)).toEqual([]);
+ expect(parseTrackedSitemaps([])).toEqual([]);
+ expect(parseTrackedSitemaps({})).toEqual([]);
+ });
+
+ it("filters out invalid items (null, primitives, objects without url)", () => {
+ expect(
+ parseTrackedSitemaps({
+ trackedSitemaps: [null, undefined, 42, "string", {}],
+ }),
+ ).toEqual([]);
+ });
+
+ it("filters out items with empty or whitespace-only URL", () => {
+ expect(
+ parseTrackedSitemaps({
+ trackedSitemaps: [{ url: "" }, { url: " " }],
+ }),
+ ).toEqual([]);
+ });
+
+ it("trims URL whitespace", () => {
+ const result = parseTrackedSitemaps({
+ trackedSitemaps: [{ url: " https://example.com/sitemap.xml " }],
+ });
+ expect(result).toEqual([{ url: "https://example.com/sitemap.xml" }]);
+ });
+
+ it("preserves optional metadata fields when valid", () => {
+ const trackedSitemaps = [
+ {
+ url: "https://example.com/sitemap.xml",
+ lastCrawledAt: "2026-03-23T00:00:00.000Z",
+ lastUrlCount: 42,
+ },
+ ];
+ expect(parseTrackedSitemaps({ trackedSitemaps })).toEqual(trackedSitemaps);
+ });
+
+ it("omits lastCrawledAt when not a string", () => {
+ expect(
+ parseTrackedSitemaps({
+ trackedSitemaps: [
+ { url: "https://example.com/sitemap.xml", lastCrawledAt: 12345 },
+ ],
+ }),
+ ).toEqual([{ url: "https://example.com/sitemap.xml" }]);
+ });
+
+ it("omits lastUrlCount when not a number", () => {
+ expect(
+ parseTrackedSitemaps({
+ trackedSitemaps: [
+ {
+ url: "https://example.com/sitemap.xml",
+ lastUrlCount: "not-a-number",
+ },
+ ],
+ }),
+ ).toEqual([{ url: "https://example.com/sitemap.xml" }]);
+ });
+
+ it("returns no sitemaps when the array contains a non-object entry (array-level guard)", () => {
+ expect(
+ parseTrackedSitemaps({
+ trackedSitemaps: [null, { url: "https://a.com/sitemap.xml" }],
+ }),
+ ).toEqual([]);
+ });
+
+ it("skips invalid URL rows when every entry is a plain object", () => {
+ expect(
+ parseTrackedSitemaps({
+ trackedSitemaps: [
+ { url: "" },
+ { url: "https://a.com/sitemap.xml" },
+ { url: "not-a-url" },
+ { url: "https://b.com/sitemap.xml", lastUrlCount: 10 },
+ ],
+ }),
+ ).toEqual([
+ { url: "https://a.com/sitemap.xml" },
+ { url: "https://b.com/sitemap.xml", lastUrlCount: 10 },
+ ]);
+ });
+});
+
+describe("crawlSitemapUrls", () => {
+ const mockFetch = vi.fn();
+
+ beforeEach(() => {
+ vi.stubGlobal("fetch", mockFetch);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.clearAllMocks();
+ });
+
+ describe("flat urlset", () => {
+ it("returns all page URLs from a simple urlset", async () => {
+ const pageUrls = [
+ "https://example.com/page-1",
+ "https://example.com/page-2",
+ ];
+ mockFetch.mockResolvedValue(
+ makeFetchResponse(Buffer.from(urlsetXml(pageUrls))),
+ );
+
+ const { urls, hadErrors } = await crawlSitemapUrls(
+ "https://example.com/sitemap.xml",
+ );
+
+ expect(urls).toEqual(expect.arrayContaining(pageUrls));
+ expect(urls).toHaveLength(pageUrls.length);
+ expect(hadErrors).toBe(false);
+ });
+
+ it("deduplicates URLs across multiple entries", async () => {
+ mockFetch.mockResolvedValue(
+ makeFetchResponse(
+ Buffer.from(
+ urlsetXml([
+ "https://example.com/page-1",
+ "https://example.com/page-1",
+ ]),
+ ),
+ ),
+ );
+
+ const { urls } = await crawlSitemapUrls(
+ "https://example.com/sitemap.xml",
+ );
+
+ expect(urls).toHaveLength(1);
+ });
+ });
+
+ describe("sitemapindex", () => {
+ it("does not fetch nested sitemaps from a sitemap index", async () => {
+ mockFetch.mockResolvedValueOnce(
+ makeFetchResponse(
+ Buffer.from(
+ sitemapindexXml([
+ "https://example.com/sitemap-posts.xml",
+ "https://example.com/sitemap-pages.xml",
+ ]),
+ ),
+ ),
+ );
+
+ const { urls, hadErrors } = await crawlSitemapUrls(
+ "https://example.com/sitemap.xml",
+ );
+
+ expect(urls).toEqual([]);
+ expect(hadErrors).toBe(false);
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ });
+
+ it("returns no page URLs when the index only references itself", async () => {
+ mockFetch.mockResolvedValue(
+ makeFetchResponse(
+ Buffer.from(sitemapindexXml(["https://example.com/sitemap.xml"])),
+ ),
+ );
+
+ const { urls } = await crawlSitemapUrls(
+ "https://example.com/sitemap.xml",
+ );
+
+ expect(urls).toEqual([]);
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe("nested xml in urlset", () => {
+ it("skips .xml loc entries instead of treating them as pages", async () => {
+ mockFetch.mockResolvedValue(
+ makeFetchResponse(
+ Buffer.from(
+ urlsetXml([
+ "https://example.com/page-1",
+ "https://example.com/nested.xml",
+ ]),
+ ),
+ ),
+ );
+
+ const { urls } = await crawlSitemapUrls(
+ "https://example.com/sitemap.xml",
+ );
+
+ expect(urls).toEqual(["https://example.com/page-1"]);
+ });
+ });
+
+ describe("URL volume limits", () => {
+ it(`throws when one sitemap has more than ${MAX_URLS_PER_SITEMAP} unique page URLs`, async () => {
+ const many = Array.from({ length: MAX_URLS_PER_SITEMAP + 50 }, (_, i) =>
+ i === 0 ? "https://example.com/first" : `https://example.com/p/${i}`,
+ );
+ mockFetch.mockResolvedValue(
+ makeFetchResponse(Buffer.from(urlsetXml(many))),
+ );
+
+ await expect(
+ crawlSitemapUrls("https://example.com/sitemap.xml"),
+ ).rejects.toThrow(
+ `Sitemap contains too many unique URLs: ${MAX_URLS_PER_SITEMAP + 50} (max ${MAX_URLS_PER_SITEMAP})`,
+ );
+ });
+ });
+
+ describe("gzip support", () => {
+ it("decompresses a gzip-compressed sitemap response", async () => {
+ const xml = urlsetXml(["https://example.com/page-1"]);
+ const compressed = gzipSync(xml);
+ mockFetch.mockResolvedValue(makeFetchResponse(compressed));
+
+ const { urls } = await crawlSitemapUrls(
+ "https://example.com/sitemap.xml.gz",
+ );
+
+ expect(urls).toContain("https://example.com/page-1");
+ });
+
+ it("handles a plain XML response without attempting decompression", async () => {
+ const xml = urlsetXml(["https://example.com/page-1"]);
+ mockFetch.mockResolvedValue(makeFetchResponse(Buffer.from(xml)));
+
+ const { urls } = await crawlSitemapUrls(
+ "https://example.com/sitemap.xml",
+ );
+
+ expect(urls).toContain("https://example.com/page-1");
+ });
+ });
+});
diff --git a/apps/web/tests/misc/site-visit-tracking-settings.test.ts b/apps/web/tests/misc/site-visit-tracking-settings.test.ts
new file mode 100644
index 0000000000..4b77be50a7
--- /dev/null
+++ b/apps/web/tests/misc/site-visit-tracking-settings.test.ts
@@ -0,0 +1,90 @@
+import {
+ mergeSiteVisitTrackingSettings,
+ parseSiteVisitTrackingSettings,
+ replaceTrackedSitemapsInColumn,
+} from "@/lib/sitemaps/site-visit-tracking";
+import { MAX_TRACKED_SITEMAPS_PER_WORKSPACE } from "@/lib/zod/schemas/site-visit-tracking";
+import { describe, expect, it } from "vitest";
+
+describe("parseSiteVisitTrackingSettings", () => {
+ it("parses object shape with optional fields", () => {
+ const parsed = parseSiteVisitTrackingSettings({
+ trackedSitemaps: [{ url: "https://b.com/sitemap.xml" }],
+ siteDomainSlug: "dub.sh",
+ siteLinksFolderId: "fold_1",
+ });
+ expect(parsed.trackedSitemaps).toHaveLength(1);
+ expect(parsed.siteDomainSlug).toBe("dub.sh");
+ expect(parsed.siteLinksFolderId).toBe("fold_1");
+ });
+
+ it("returns empty defaults for null, non-object, or array input", () => {
+ expect(parseSiteVisitTrackingSettings(null).trackedSitemaps).toEqual([]);
+ expect(parseSiteVisitTrackingSettings("x").trackedSitemaps).toEqual([]);
+ expect(parseSiteVisitTrackingSettings([]).trackedSitemaps).toEqual([]);
+ });
+
+ it("keeps at most MAX_TRACKED_SITEMAPS_PER_WORKSPACE entries (deterministic slice)", () => {
+ const many = Array.from({ length: MAX_TRACKED_SITEMAPS_PER_WORKSPACE + 5 }, (_, i) => ({
+ url: `https://example.com/s${i}.xml`,
+ }));
+ const parsed = parseSiteVisitTrackingSettings({ trackedSitemaps: many });
+ expect(parsed.trackedSitemaps).toHaveLength(MAX_TRACKED_SITEMAPS_PER_WORKSPACE);
+ expect(parsed.trackedSitemaps[0]?.url).toBe("https://example.com/s0.xml");
+ expect(parsed.trackedSitemaps.at(-1)?.url).toBe(
+ `https://example.com/s${MAX_TRACKED_SITEMAPS_PER_WORKSPACE - 1}.xml`,
+ );
+ });
+
+ it("returns no sitemaps when the array contains a non-object entry among the capped prefix", () => {
+ expect(
+ parseSiteVisitTrackingSettings({
+ trackedSitemaps: [{ url: "https://a.com/s.xml" }, null],
+ }).trackedSitemaps,
+ ).toEqual([]);
+ expect(
+ parseSiteVisitTrackingSettings({
+ trackedSitemaps: ["not-an-object"],
+ }).trackedSitemaps,
+ ).toEqual([]);
+ });
+});
+
+describe("mergeSiteVisitTrackingSettings", () => {
+ it("merges partial patch without wiping other keys", () => {
+ const merged = mergeSiteVisitTrackingSettings(
+ {
+ trackedSitemaps: [{ url: "https://a.com/sitemap.xml" }],
+ siteDomainSlug: "dub.sh",
+ siteLinksFolderId: "fold_x",
+ },
+ { trackedSitemaps: [{ url: "https://b.com/sitemap.xml" }] },
+ );
+ expect(merged?.siteDomainSlug).toBe("dub.sh");
+ expect(merged?.siteLinksFolderId).toBe("fold_x");
+ expect(merged?.trackedSitemaps).toHaveLength(1);
+ expect(merged?.trackedSitemaps[0]?.url).toBe("https://b.com/sitemap.xml");
+ });
+
+ it("returns null when patch is null", () => {
+ expect(
+ mergeSiteVisitTrackingSettings({ trackedSitemaps: [] }, null),
+ ).toBeNull();
+ });
+});
+
+describe("replaceTrackedSitemapsInColumn", () => {
+ it("preserves siteDomainSlug and siteLinksFolderId", () => {
+ const next = replaceTrackedSitemapsInColumn(
+ {
+ trackedSitemaps: [{ url: "https://old.com/sitemap.xml" }],
+ siteDomainSlug: "dub.sh",
+ siteLinksFolderId: "fold_1",
+ },
+ [{ url: "https://new.com/sitemap.xml" }],
+ );
+ expect(next.siteDomainSlug).toBe("dub.sh");
+ expect(next.siteLinksFolderId).toBe("fold_1");
+ expect(next.trackedSitemaps[0]?.url).toBe("https://new.com/sitemap.xml");
+ });
+});
diff --git a/apps/web/vercel.json b/apps/web/vercel.json
index ccd1f32643..788ef62275 100644
--- a/apps/web/vercel.json
+++ b/apps/web/vercel.json
@@ -59,6 +59,10 @@
{
"path": "/api/cron/bounties/queue-sync-social-metrics",
"schedule": "0 * * * *"
+ },
+ {
+ "path": "/api/cron/sitemaps/queue",
+ "schedule": "0 2 * * *"
}
],
"functions": {
diff --git a/packages/prisma/schema/workspace.prisma b/packages/prisma/schema/workspace.prisma
index 97b347357c..5bf84809a3 100644
--- a/packages/prisma/schema/workspace.prisma
+++ b/packages/prisma/schema/workspace.prisma
@@ -43,6 +43,7 @@ model Project {
referredSignups Int @default(0)
store Json? // General key-value store for things like persisting toggles, dismissing popups, etc.
+ siteVisitTrackingSettings Json? // Site visit tracking: sitemaps, short-link domain, Site Links folder id
allowedHostnames Json?
publishableKey String? @unique // for the client-side publishable key