The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
code improvements
Pedro Ladeira628808004844
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/configure-tracking-section.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/configure-tracking-section.tsxindex 3f4b3573d7..318374f293 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/configure-tracking-section.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/configure-tracking-section.tsx@@ -3,7 +3,7 @@import { clientAccessCheck } from "@/lib/client-access-check";import useWorkspace from "@/lib/swr/use-workspace";import { useWorkspaceStore } from "@/lib/swr/use-workspace-store";-import { guides, stackItems } from "@/ui/guides/integrations";+import { stackItems } from "@/ui/guides/integrations";import { Button, Switch } from "@dub/ui";import { useEffect, useMemo } from "react";import { Controller, useForm } from "react-hook-form";@@ -84,12 +84,6 @@ export function ConfigureTrackingSection() {const [, setConnectionComplete] = useWorkspaceStore<boolean>("analyticsSettingsConnectionSetupComplete",);- const [, setLeadComplete] = useWorkspaceStore<boolean>(- "analyticsSettingsLeadTrackingSetupComplete",- );- const [, setSaleComplete] = useWorkspaceStore<boolean>(- "analyticsSettingsSaleTrackingSetupComplete",- );const persistedSitemaps = useMemo(() =>@@ -195,24 +189,6 @@ export function ConfigureTrackingSection() {if (data.allowedHostnames.length > 0 && data.stack.length > 0) {await setConnectionComplete(true);-- const selectedGuideTypes = new Set(- data.stack- .flatMap(- (stackId) =>- stackItems.find((item) => item.id === stackId)?.guideKeys ?? [],- )- .map((key) => guides.find((guide) => guide.key === key)?.type)- .filter(Boolean),- );-- if (selectedGuideTypes.has("track-lead")) {- await setLeadComplete(true);- }-- if (selectedGuideTypes.has("track-sale")) {- await setSaleComplete(true);- }}const existingUrls = new Set(persistedSitemapUrls);diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/verify-install.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/verify-install.tsxindex 5ebd406654..2b4e076890 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/verify-install.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/verify-install.tsx@@ -2,12 +2,10 @@import { verifyWorkspaceSetup } from "@/lib/actions/verify-workspace-setup";import {- getVerifyErrorHeadline,toVerifySiteUrl,- VERIFY_DOCS_HREF,- VERIFY_SUPPORT_HREF,type VerifyInstallationResult,} from "@/lib/analytics/verify-installation";+import { clientAccessCheck } from "@/lib/client-access-check";import useWorkspace from "@/lib/swr/use-workspace";import { UserAvatar } from "@/ui/users/user-avatar";import { Button, Combobox, Globe } from "@dub/ui";@@ -19,6 +17,18 @@ import { toast } from "sonner";const HOSTNAME_REQUIRED_MESSAGE ="A hostname is required in order to verify installation.";+const VERIFY_DOCS_HREF = "https://dub.co/docs/sdks/client-side";+const VERIFY_SUPPORT_HREF = "https://dub.co/support";++const ERROR_HEADLINE = {+ not_installed: "Script is not installed.",+ missing_attributes: "Script missing attributes.",+ duplicate: "Duplicate script.",+ malformed: "Malformed script.",+ unreachable: "We couldn’t reach this hostname.",+ unsupported: "Wildcard hostnames can’t be verified.",+};+type LastVerified = {hostname: string;verifiedAt: string;@@ -32,10 +42,22 @@ type LastVerified = {type HelperTone = "success" | "error" | "neutral";export function VerifyInstall({ hostnames }: { hostnames: string[] }) {- const { id: workspaceId, store, mutate } = useWorkspace();+ const { id: workspaceId, role, store, mutate } = useWorkspace();const [selectedHostname, setSelectedHostname] = useState<string | null>(null);const [result, setResult] = useState<VerifyInstallationResult | null>(null);+ const permissionsError = clientAccessCheck({+ action: "workspaces.write",+ role,+ customPermissionDescription: "verify tracking installation",+ }).error;+ const disabledTooltip =+ typeof permissionsError === "string"+ ? permissionsError+ : !selectedHostname+ ? HOSTNAME_REQUIRED_MESSAGE+ : undefined;+const lastVerified = store?.analyticsSettingsInstallationVerified as| LastVerified| undefined;@@ -61,7 +83,7 @@ export function VerifyInstall({ hostnames }: { hostnames: string[] }) {const showSuccess = result?.status === "success";const showError = result?.status === "error";const showLastVerified = !result && Boolean(persistedForHostname);- const showButton = !showSuccess && !showLastVerified;+ const canReverify = showSuccess || showLastVerified;const helperTone: HelperTone | null = showSuccess? "success"@@ -131,8 +153,8 @@ export function VerifyInstall({ hostnames }: { hostnames: string[] }) {{showError && result.status === "error" && (<HelperText tone="error">- {getVerifyErrorHeadline(result.error)} After correcting, try- verifying again and if the issue still persists, check out our{" "}+ {ERROR_HEADLINE[result.error]} After correcting, try verifying again+ and if the issue still persists, check out our{" "}<ahref={VERIFY_DOCS_HREF}target="_blank"@@ -177,26 +199,20 @@ export function VerifyInstall({ hostnames }: { hostnames: string[] }) {)}</div>- {showButton && (- <Button- text="Verify installation"- className="bg-bg-inverted h-7 w-fit px-2.5 text-sm font-medium tracking-[-0.02em] active:scale-[0.97]"- loading={isPending}- disabled={!workspaceId}- onClick={() => {- if (!workspaceId) {- return;- }-- if (!selectedHostname) {- toast.error(HOSTNAME_REQUIRED_MESSAGE);- return;- }-- void executeAsync({ workspaceId, hostname: selectedHostname });- }}- />- )}+ <Button+ text={canReverify ? "Verify again" : "Verify installation"}+ className="bg-bg-inverted h-7 w-fit px-2.5 text-sm font-medium tracking-[-0.02em] active:scale-[0.97]"+ loading={isPending}+ disabled={!workspaceId || Boolean(disabledTooltip)}+ disabledTooltip={disabledTooltip}+ onClick={() => {+ if (!workspaceId || !selectedHostname) {+ return;+ }++ void executeAsync({ workspaceId, hostname: selectedHostname });+ }}+ /></div>);}diff --git a/apps/web/lib/actions/verify-workspace-setup.ts b/apps/web/lib/actions/verify-workspace-setup.tsindex d898b751df..5cc61ad5c6 100644--- a/apps/web/lib/actions/verify-workspace-setup.ts+++ b/apps/web/lib/actions/verify-workspace-setup.ts@@ -6,6 +6,7 @@ import {type VerifyInstallationResult,} from "@/lib/analytics/verify-installation";import { prisma } from "@/lib/prisma";+import { ratelimit } from "@/lib/upstash";import FirecrawlApp from "@mendable/firecrawl-js";import * as z from "zod/v4";import { authActionClient } from "./safe-action";@@ -24,9 +25,19 @@ export const verifyWorkspaceSetup = authActionClientthrowIfNoPermission({role: workspace.role,- requiredPermissions: ["workspaces.read"],+ requiredPermissions: ["workspaces.write"],});+ const { success } = await ratelimit(5, "1 m").limit(+ `verify-workspace-setup:${workspace.id}`,+ );++ if (!success) {+ throw new Error(+ "Too many verification attempts. Please try again in a minute.",+ );+ }+const hostnames = (workspace.allowedHostnames as string[]) || [];if (!hostnames.includes(hostname)) {@@ -37,7 +48,7 @@ export const verifyWorkspaceSetup = authActionClientreturn {status: "error",hostname,- error: "unreachable",+ error: "unsupported",};}@@ -49,8 +60,7 @@ export const verifyWorkspaceSetup = authActionClientformats: ["rawHtml"],onlyMainContent: false,parsePDF: false,- includeTags: ["head"],- maxAge: 14400000,+ maxAge: 0,waitFor: 5000,});diff --git a/apps/web/lib/analytics/verify-installation.ts b/apps/web/lib/analytics/verify-installation.tsindex efe7352ecd..b5fe3658e4 100644--- a/apps/web/lib/analytics/verify-installation.ts+++ b/apps/web/lib/analytics/verify-installation.ts@@ -1,11 +1,10 @@-const VERIFY_ERROR_CODES = [- "not_installed",- "missing_attributes",- "duplicate",- "malformed",-] as const;+type VerifyErrorCode =+ | "not_installed"+ | "missing_attributes"+ | "duplicate"+ | "malformed";-export type VerifyErrorCode = (typeof VERIFY_ERROR_CODES)[number];+type VerifyError = VerifyErrorCode | "unreachable" | "unsupported";export type VerifyInstallationResult =| {@@ -21,29 +20,17 @@ export type VerifyInstallationResult =| {status: "error";hostname: string;- error: VerifyErrorCode | "unreachable";+ error: VerifyError;};-const ERROR_HEADLINE: Record<VerifyErrorCode | "unreachable", string> = {- not_installed: "Script is not installed.",- missing_attributes: "Script missing attributes.",- duplicate: "Duplicate script.",- malformed: "Malformed script.",- unreachable: "We couldn’t reach this hostname.",-};--export const VERIFY_DOCS_HREF = "https://dub.co/docs/sdks/client-side";-export const VERIFY_SUPPORT_HREF = "https://dub.co/support";--export function getVerifyErrorHeadline(error: VerifyErrorCode | "unreachable") {- return ERROR_HEADLINE[error];-}-const SCRIPT_TAG_RE = /<script\b[^>]*>/gi;const DUB_SCRIPT_RE =/dubcdn\.com\/analytics|data-sdkn=["']@dub\/analytics["']|@dub\/analytics/i;const DUB_SRC_RE = /src=["'][^"']*dubcdn\.com\/analytics[^"']*["']/i;+const CONVERSION_SRC_RE =+ /src=["'][^"']*dubcdn\.com\/analytics[^"']*conversion-tracking[^"']*["']/i;const SDK_NAME_RE = /data-sdkn=["']@dub\/analytics["']/i;+const PUBLISHABLE_KEY_RE = /data-publishable-key=/i;export function analyzeDubAnalyticsScript(html: string,@@ -71,7 +58,11 @@ export function analyzeDubAnalyticsScript(return "malformed";}- if (!hasSdkName) {+ if (+ CONVERSION_SRC_RE.test(tag) &&+ !hasSdkName &&+ !PUBLISHABLE_KEY_RE.test(tag)+ ) {return "missing_attributes";}@@ -83,5 +74,9 @@ export function toVerifySiteUrl(hostname: string) {return hostname;}+ if (hostname === "localhost" || hostname.startsWith("localhost:")) {+ return `http://${hostname}`;+ }+return `https://${hostname}`;}diff --git a/apps/web/lib/tracking/build-tracking-setup.ts b/apps/web/lib/tracking/build-tracking-setup.tsindex a5fe62574f..7f352024f3 100644--- a/apps/web/lib/tracking/build-tracking-setup.ts+++ b/apps/web/lib/tracking/build-tracking-setup.ts@@ -59,12 +59,6 @@ export type TrackingSetup = {prompt: string;};-function getSelectedStackItems(stack: string[]) {- return stack- .map((id) => stackItems.find((item) => item.id === id))- .filter((item): item is StackItem => Boolean(item));-}-function getGuideForType(item: StackItem, type: IntegrationType) {return item.guideKeys.map((key) => guides.find((guide) => guide.key === key))@@ -91,7 +85,9 @@ function toStep(}function resolveTrackingSetupSteps(stack: string[]): TrackingSetupStep[] {- const selected = getSelectedStackItems(stack);+ const selected = stack+ .map((id) => stackItems.find((item) => item.id === id))+ .filter((item): item is StackItem => Boolean(item));const steps: TrackingSetupStep[] = [];for (const type of STEP_TYPES) {@@ -128,33 +124,6 @@ function resolveTrackingSetupSteps(stack: string[]): TrackingSetupStep[] {return steps;}-function isReactOnlyClientStep(steps: TrackingSetupStep[]) {- const clientSteps = steps.filter((step) => step.type === "client-sdk");-- return clientSteps.length === 1 && clientSteps[0]?.guideKey === "react";-}--function getAnalyticsScriptUrl({- siteVisitEnabled,- outboundEnabled,- publishableKey,-}: Pick<- BuildTrackingSetupInput,- "siteVisitEnabled" | "outboundEnabled" | "publishableKey"->) {- const segments = [- siteVisitEnabled ? "site-visit" : null,- outboundEnabled ? "outbound-domains" : null,- publishableKey ? "conversion-tracking" : null,- ].filter(Boolean);-- if (segments.length === 0) {- return ANALYTICS_SCRIPT_BASE;- }-- return `https://www.dubcdn.com/analytics/script.${segments.join(".")}.js`;-}-function composeTrackingSetupPrompt({steps,hostnames,@@ -164,19 +133,24 @@ function composeTrackingSetupPrompt({}: {steps: TrackingSetupStep[];} & Omit<BuildTrackingSetupInput, "stack">) {- const reactOnlyClient = isReactOnlyClientStep(steps);+ const clientSteps = steps.filter((step) => step.type === "client-sdk");+ const reactOnlyClient =+ clientSteps.length === 1 && clientSteps[0]?.guideKey === "react";+ const scriptSegments = [+ siteVisitEnabled ? "site-visit" : null,+ outboundEnabled ? "outbound-domains" : null,+ publishableKey ? "conversion-tracking" : null,+ ].filter(Boolean);+ const analyticsScriptUrl =+ scriptSegments.length === 0+ ? ANALYTICS_SCRIPT_BASE+ : `https://www.dubcdn.com/analytics/script.${scriptSegments.join(".")}.js`;const workspaceLines = [hostnames.length > 0 ? `- Hostnames: ${hostnames.join(", ")}` : null,publishableKey? `- Publishable key (client-side): ${publishableKey}`: null,- reactOnlyClient- ? null- : `- Analytics script: ${getAnalyticsScriptUrl({- siteVisitEnabled,- outboundEnabled,- publishableKey,- })}`,+ reactOnlyClient ? null : `- Analytics script: ${analyticsScriptUrl}`,].filter(Boolean);const hasDuplicateTypes = STEP_TYPES.some(