The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
rename: tests → testVariants, testsStartedAt → testStartedAt, testsCompleteAt → testCompletedAt
Steven Tey689b987f9888
diff --git a/apps/web/app/api/cron/links/[linkId]/complete-tests/route.ts b/apps/web/app/api/cron/links/[linkId]/complete-tests/route.tsindex 8b4191e267..d4f8e7c89f 100644--- a/apps/web/app/api/cron/links/[linkId]/complete-tests/route.ts+++ b/apps/web/app/api/cron/links/[linkId]/complete-tests/route.ts@@ -31,10 +31,10 @@ export async function POST(return new Response("Link not found. Skipping...", { status: 200 });if (- link.tests &&- link.testsCompleteAt &&- link.testsCompleteAt < new Date() &&- Date.now() - link.testsCompleteAt.getTime() < 2 * 60 * 60 * 1000 // Limit to two hour window+ link.testVariants &&+ link.testCompletedAt &&+ link.testCompletedAt < new Date() &&+ Date.now() - link.testCompletedAt.getTime() < 2 * 60 * 60 * 1000 // Limit to two hour window) {await completeTests(link as any);return new Response("Tests completed.", { status: 200 });diff --git a/apps/web/app/api/links/bulk/route.ts b/apps/web/app/api/links/bulk/route.tsindex 0aadfde2d2..60202360ed 100644--- a/apps/web/app/api/links/bulk/route.ts+++ b/apps/web/app/api/links/bulk/route.ts@@ -389,15 +389,15 @@ export const PATCH = withWorkspace(? link.expiresAt.toISOString(): link.expiresAt,geo: link.geo as NewLinkProps["geo"],- tests: link.tests as NewLinkProps["tests"],- testsCompleteAt:- link.testsCompleteAt instanceof Date- ? link.testsCompleteAt.toISOString()- : link.testsCompleteAt,- testsStartedAt:- link.testsStartedAt instanceof Date- ? link.testsStartedAt.toISOString()- : link.testsStartedAt,+ testVariants: link.testVariants as NewLinkProps["testVariants"],+ testCompletedAt:+ link.testCompletedAt instanceof Date+ ? link.testCompletedAt.toISOString()+ : link.testCompletedAt,+ testStartedAt:+ link.testStartedAt instanceof Date+ ? link.testStartedAt.toISOString()+ : link.testStartedAt,...data,},workspace,diff --git a/apps/web/app/api/links/upsert/route.ts b/apps/web/app/api/links/upsert/route.tsindex 098693d9d5..983727694c 100644--- a/apps/web/app/api/links/upsert/route.ts+++ b/apps/web/app/api/links/upsert/route.ts@@ -62,15 +62,15 @@ export const PUT = withWorkspace(? link.expiresAt.toISOString(): link.expiresAt,geo: link.geo as NewLinkProps["geo"],- tests: link.tests as NewLinkProps["tests"],- testsCompleteAt:- link.testsCompleteAt instanceof Date- ? link.testsCompleteAt.toISOString()- : link.testsCompleteAt,- testsStartedAt:- link.testsStartedAt instanceof Date- ? link.testsStartedAt.toISOString()- : link.testsStartedAt,+ testVariants: link.testVariants as NewLinkProps["testVariants"],+ testCompletedAt:+ link.testCompletedAt instanceof Date+ ? link.testCompletedAt.toISOString()+ : link.testCompletedAt,+ testStartedAt:+ link.testStartedAt instanceof Date+ ? link.testStartedAt.toISOString()+ : link.testStartedAt,...body,};diff --git a/apps/web/app/api/partner-profile/programs/[programId]/links/[linkId]/route.ts b/apps/web/app/api/partner-profile/programs/[programId]/links/[linkId]/route.tsindex 4d9375ef7d..1bacf23a7a 100644--- a/apps/web/app/api/partner-profile/programs/[programId]/links/[linkId]/route.ts+++ b/apps/web/app/api/partner-profile/programs/[programId]/links/[linkId]/route.ts@@ -69,15 +69,15 @@ export const PATCH = withPartnerProfile(? link.expiresAt.toISOString(): link.expiresAt,geo: link.geo as NewLinkProps["geo"],- tests: link.tests as NewLinkProps["tests"],- testsCompleteAt:- link.testsCompleteAt instanceof Date- ? link.testsCompleteAt.toISOString()- : link.testsCompleteAt,- testsStartedAt:- link.testsStartedAt instanceof Date- ? link.testsStartedAt.toISOString()- : link.testsStartedAt,+ testVariants: link.testVariants as NewLinkProps["testVariants"],+ testCompletedAt:+ link.testCompletedAt instanceof Date+ ? link.testCompletedAt.toISOString()+ : link.testCompletedAt,+ testStartedAt:+ link.testStartedAt instanceof Date+ ? link.testStartedAt.toISOString()+ : link.testStartedAt,// merge in new propskey: key || undefined,diff --git a/apps/web/app/api/partners/links/upsert/route.ts b/apps/web/app/api/partners/links/upsert/route.tsindex 9c5facbfac..c3f8a0e88d 100644--- a/apps/web/app/api/partners/links/upsert/route.ts+++ b/apps/web/app/api/partners/links/upsert/route.ts@@ -85,15 +85,15 @@ export const PUT = withWorkspace(? link.expiresAt.toISOString(): link.expiresAt,geo: link.geo as NewLinkProps["geo"],- tests: link.tests as NewLinkProps["tests"],- testsCompleteAt:- link.testsCompleteAt instanceof Date- ? link.testsCompleteAt.toISOString()- : link.testsCompleteAt,- testsStartedAt:- link.testsStartedAt instanceof Date- ? link.testsStartedAt.toISOString()- : link.testsStartedAt,+ testVariants: link.testVariants as NewLinkProps["testVariants"],+ testCompletedAt:+ link.testCompletedAt instanceof Date+ ? link.testCompletedAt.toISOString()+ : link.testCompletedAt,+ testStartedAt:+ link.testStartedAt instanceof Date+ ? link.testStartedAt.toISOString()+ : link.testStartedAt,// merge in new props...linkProps,// set default fieldsdiff --git a/apps/web/lib/api/links/bulk-create-links.ts b/apps/web/lib/api/links/bulk-create-links.tsindex 32764a36c9..9ca4fd6bff 100644--- a/apps/web/lib/api/links/bulk-create-links.ts+++ b/apps/web/lib/api/links/bulk-create-links.ts@@ -72,7 +72,7 @@ export async function bulkCreateLinks({utm_content,expiresAt: link.expiresAt ? new Date(link.expiresAt) : null,geo: link.geo || undefined,- tests: link.tests || Prisma.JsonNull,+ testVariants: link.testVariants || Prisma.JsonNull,};}),skipDuplicates: true,diff --git a/apps/web/lib/api/links/bulk-update-links.ts b/apps/web/lib/api/links/bulk-update-links.tsindex 6512070c78..460a2a1f9e 100644--- a/apps/web/lib/api/links/bulk-update-links.ts+++ b/apps/web/lib/api/links/bulk-update-links.ts@@ -25,7 +25,7 @@ export async function bulkUpdateLinks(proxy,expiresAt,geo,- tests,+ testVariants,tagId,tagIds,tagNames,@@ -55,7 +55,7 @@ export async function bulkUpdateLinks(: image,expiresAt: expiresAt ? new Date(expiresAt) : null,geo: geo || Prisma.JsonNull,- tests: tests || Prisma.JsonNull,+ testVariants: testVariants || Prisma.JsonNull,...(url && getParamsFromURL(url)),// Associate tags by tagNamesdiff --git a/apps/web/lib/api/links/complete-tests.ts b/apps/web/lib/api/links/complete-tests.tsindex 7b34d2afd5..cc66112aff 100644--- a/apps/web/lib/api/links/complete-tests.ts+++ b/apps/web/lib/api/links/complete-tests.ts@@ -9,9 +9,9 @@ import { processLink } from "./process-link";import { updateLink } from "./update-link";export async function completeTests(link: Link & { project: Project }) {- if (!link.tests || !link.testsCompleteAt || !link.projectId) return;+ if (!link.testVariants || !link.testCompletedAt || !link.projectId) return;- const tests = LinkTestsSchema.parse(link.tests);+ const testVariants = LinkTestsSchema.parse(link.testVariants);const analytics = (await getAnalytics({event: "leads",@@ -19,12 +19,12 @@ export async function completeTests(link: Link & { project: Project }) {linkId: link.id,workspaceId: link.projectId,dataAvailableFrom: link.project.createdAt,- start: link.testsStartedAt ? new Date(link.testsStartedAt) : undefined,- end: link.testsCompleteAt,+ start: link.testStartedAt ? new Date(link.testStartedAt) : undefined,+ end: link.testCompletedAt,})) as { url: string; leads: number }[];const max = Math.max(- ...tests.map(+ ...testVariants.map((test) => analytics.find(({ url }) => url === test.url)?.leads || 0,),);@@ -37,7 +37,7 @@ export async function completeTests(link: Link & { project: Project }) {return;}- const winners = tests.filter(+ const winners = testVariants.filter((test) =>(analytics.find(({ url }) => url === test.url)?.leads || 0) === max,);@@ -49,7 +49,7 @@ export async function completeTests(link: Link & { project: Project }) {const winner = winners[Math.floor(Math.random() * winners.length)];console.log(- `completeTests: Determined A/B tests winner for ${link.id}: ${winner.url}${winners.length > 1 ? ` (${winners.length} tied)` : ""}`,+ `completeTests: Determined A/B testVariants winner for ${link.id}: ${winner.url}${winners.length > 1 ? ` (${winners.length} tied)` : ""}`,);if (winner.url === link.url) return;@@ -67,15 +67,15 @@ export async function completeTests(link: Link & { project: Project }) {: link.expiresAt,geo: link.geo as NewLinkProps["geo"],- tests: link.tests as NewLinkProps["tests"],- testsCompleteAt:- link.testsCompleteAt instanceof Date- ? link.testsCompleteAt.toISOString()- : link.testsCompleteAt,- testsStartedAt:- link.testsStartedAt instanceof Date- ? link.testsStartedAt.toISOString()- : link.testsStartedAt,+ testVariants: link.testVariants as NewLinkProps["testVariants"],+ testCompletedAt:+ link.testCompletedAt instanceof Date+ ? link.testCompletedAt.toISOString()+ : link.testCompletedAt,+ testStartedAt:+ link.testStartedAt instanceof Date+ ? link.testStartedAt.toISOString()+ : link.testStartedAt,// Update URLurl: winner.url,diff --git a/apps/web/lib/api/links/create-link.ts b/apps/web/lib/api/links/create-link.tsindex 990ac51b1c..b8af03afb4 100644--- a/apps/web/lib/api/links/create-link.ts+++ b/apps/web/lib/api/links/create-link.ts@@ -33,8 +33,8 @@ export async function createLink(link: ProcessedLinkProps) {proxy,geo,publicStats,- tests,- testsCompleteAt,+ testVariants,+ testCompletedAt,} = link;const combinedTagIds = combineTagIds(link);@@ -67,9 +67,9 @@ export async function createLink(link: ProcessedLinkProps) {expiresAt: expiresAt ? new Date(expiresAt) : null,geo: geo || Prisma.JsonNull,- tests: tests || Prisma.JsonNull,- testsCompleteAt: testsCompleteAt ? new Date(testsCompleteAt) : null,- testsStartedAt: tests && testsCompleteAt ? new Date() : null,+ testVariants: testVariants || Prisma.JsonNull,+ testCompletedAt: testCompletedAt ? new Date(testCompletedAt) : null,+ testStartedAt: testVariants && testCompletedAt ? new Date() : null,// Associate tags by tagNames...(tagNames?.length &&@@ -181,7 +181,7 @@ export async function createLink(link: ProcessedLinkProps) {webhookIds,}),- tests && testsCompleteAt && scheduleTestCompletion(response),+ testVariants && testCompletedAt && scheduleTestCompletion(response),]),);diff --git a/apps/web/lib/api/links/process-link.ts b/apps/web/lib/api/links/process-link.tsindex 2e7a90440b..4c33d76f24 100644--- a/apps/web/lib/api/links/process-link.ts+++ b/apps/web/lib/api/links/process-link.ts@@ -76,12 +76,12 @@ export async function processLink<T extends Record<string, any>>({partnerId,programId,webhookIds,- tests,+ testVariants,} = payload;let expiresAt: string | Date | null | undefined = payload.expiresAt;- let testsCompleteAt: string | Date | null | undefined =- payload.testsCompleteAt;+ let testCompletedAt: string | Date | null | undefined =+ payload.testCompletedAt;let defaultProgramFolderId: string | null = null;const tagIds = combineTagIds(payload);@@ -299,7 +299,7 @@ export async function processLink<T extends Record<string, any>>({};}- if (tests) {+ if (testVariants) {return {link: payload,error:@@ -309,7 +309,7 @@ export async function processLink<T extends Record<string, any>>({}}- if (!trackConversion && tests) {+ if (!trackConversion && testVariants) {return {link: payload,error: "Conversion tracking must be enabled to use A/B testing.",@@ -553,8 +553,8 @@ export async function processLink<T extends Record<string, any>>({}// A/B testing checks- if (tests && testsCompleteAt) {- const datetime = parseDateTime(testsCompleteAt);+ if (testVariants && testCompletedAt) {+ const datetime = parseDateTime(testCompletedAt);if (!datetime) {return {link: payload,@@ -562,17 +562,17 @@ export async function processLink<T extends Record<string, any>>({code: "unprocessable_entity",};}- testsCompleteAt = datetime;+ testCompletedAt = datetime;- const parsedTests = LinkTestsSchema.safeParse(tests);+ const parsedTests = LinkTestsSchema.safeParse(testVariants);if (!parsedTests.success) {return {link: payload,- error: "Invalid tests.",+ error: "Invalid testVariants.",code: "unprocessable_entity",};}- tests = parsedTests.data;+ testVariants = parsedTests.data;}// remove polyfill attributes from payload@@ -592,8 +592,8 @@ export async function processLink<T extends Record<string, any>>({url,expiresAt,expiredUrl,- tests,- testsCompleteAt,+ testVariants,+ testCompletedAt,// partnerId derived from payload or program enrollmentpartnerId: partnerId || null,// make sure projectId is set to the current workspacediff --git a/apps/web/lib/api/links/schedule-test-completion.ts b/apps/web/lib/api/links/schedule-test-completion.tsindex c6dc726984..d224d8c465 100644--- a/apps/web/lib/api/links/schedule-test-completion.ts+++ b/apps/web/lib/api/links/schedule-test-completion.ts@@ -30,19 +30,19 @@ export async function scheduleTestCompletion(link: ExpandedLink) {);}- if (!link.tests) return;+ if (!link.testVariants) return;- const testsCompleteAt = link.testsCompleteAt- ? new Date(link.testsCompleteAt)+ const testCompletedAt = link.testCompletedAt+ ? new Date(link.testCompletedAt): null;- if (!testsCompleteAt) return;+ if (!testCompletedAt) return;- if (testsCompleteAt > new Date()) {+ if (testCompletedAt > new Date()) {// Tests are not complete yet, schedule a job for completionawait qstash.publishJSON({url: completionUrl,- delay: (testsCompleteAt.getTime() - new Date().getTime()) / 1000,+ delay: (testCompletedAt.getTime() - new Date().getTime()) / 1000,});}}diff --git a/apps/web/lib/api/links/update-link.ts b/apps/web/lib/api/links/update-link.tsindex f9538a5f9b..ca4ab92f19 100644--- a/apps/web/lib/api/links/update-link.ts+++ b/apps/web/lib/api/links/update-link.ts@@ -61,9 +61,9 @@ export async function updateLink({tagIds,tagNames,webhookIds,- tests,- testsStartedAt,- testsCompleteAt,+ testVariants,+ testStartedAt,+ testCompletedAt,...rest} = updatedLink;@@ -101,9 +101,9 @@ export async function updateLink({expiresAt: expiresAt ? new Date(expiresAt) : null,geo: geo || Prisma.JsonNull,- tests: tests || Prisma.JsonNull,- testsCompleteAt: testsCompleteAt ? new Date(testsCompleteAt) : null,- testsStartedAt: testsStartedAt ? new Date(testsStartedAt) : null,+ testVariants: testVariants || Prisma.JsonNull,+ testCompletedAt: testCompletedAt ? new Date(testCompletedAt) : null,+ testStartedAt: testStartedAt ? new Date(testStartedAt) : null,// Associate tags by tagNames...(tagNames &&@@ -194,7 +194,7 @@ export async function updateLink({webhookIds,}),- tests && testsCompleteAt && scheduleTestCompletion(response),+ testVariants && testCompletedAt && scheduleTestCompletion(response),]),);diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.tsindex 47a4ff3433..626e395478 100644--- a/apps/web/lib/middleware/link.ts+++ b/apps/web/lib/middleware/link.ts@@ -147,14 +147,14 @@ export default async function LinkMiddleware(expiredUrl,doIndex,webhookIds,- tests,- testsCompleteAt,+ testVariants,+ testCompletedAt,projectId: workspaceId,} = cachedLink;const testUrl = getTestDestinationURL({- tests,- testsCompleteAt,+ testVariants,+ testCompletedAt,});const url = testUrl || cachedLink.url;diff --git a/apps/web/lib/middleware/utils/get-test-destination-url.ts b/apps/web/lib/middleware/utils/get-test-destination-url.tsindex bd89a74a87..fe61438c45 100644--- a/apps/web/lib/middleware/utils/get-test-destination-url.ts+++ b/apps/web/lib/middleware/utils/get-test-destination-url.ts@@ -3,33 +3,37 @@ import { cookies } from "next/headers";import { z } from "zod";/**- * Determines the destination URL for a link with A/B tests using weighted random selection+ * Determines the destination URL for a link with A/B testVariants using weighted random selection*/export const getTestDestinationURL = ({- tests,- testsCompleteAt,+ testVariants,+ testCompletedAt,}: {- tests?: z.infer<typeof LinkTestsSchema>;- testsCompleteAt?: Date;+ testVariants?: z.infer<typeof LinkTestsSchema>;+ testCompletedAt?: Date;}) => {try {- if (!tests || !testsCompleteAt || !(new Date(testsCompleteAt) > new Date()))+ if (+ !testVariants ||+ !testCompletedAt ||+ !(new Date(testCompletedAt) > new Date())+ )return null;- if (tests.length < 2 || tests.length > MAX_TEST_COUNT)- throw new Error("Invalid test count: " + tests.length);+ if (testVariants.length < 2 || testVariants.length > MAX_TEST_COUNT)+ throw new Error("Invalid test count: " + testVariants.length);const cookieStore = cookies();const cookieUrl = cookieStore.get("dub_test_url")?.value;- if (cookieUrl && tests.map((t) => t.url).includes(cookieUrl))+ if (cookieUrl && testVariants.map((t) => t.url).includes(cookieUrl))return cookieUrl;let i = 0;- const weights = [tests[0].percentage];+ const weights = [testVariants[0].percentage];// Calculate cumulative weights- for (i = 1; i < tests.length; ++i)- weights[i] = tests[i].percentage + weights[i - 1];+ for (i = 1; i < testVariants.length; ++i)+ weights[i] = testVariants[i].percentage + weights[i - 1];// Generate a random number between 0 and the total cumulative weightconst random = Math.random() * weights[weights.length - 1];@@ -38,7 +42,7 @@ export const getTestDestinationURL = ({for (i = 0; i < weights.length; ++i) if (weights[i] > random) break;// Return the corresponding test URL- return tests[i].url;+ return testVariants[i].url;} catch (e) {console.error("Error getting test destination URL", e);}diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex cf7c44d4a1..035b8c92f1 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -113,8 +113,8 @@ export interface RedisLinkProps {doIndex?: boolean;projectId?: string;webhookIds?: string[];- tests?: z.infer<typeof LinkTestsSchema>;- testsCompleteAt?: Date;+ testVariants?: z.infer<typeof LinkTestsSchema>;+ testCompletedAt?: Date;}export interface TagProps {diff --git a/apps/web/lib/upstash/format-redis-link.ts b/apps/web/lib/upstash/format-redis-link.tsindex d78defcca5..bdd5e5d06c 100644--- a/apps/web/lib/upstash/format-redis-link.ts+++ b/apps/web/lib/upstash/format-redis-link.ts@@ -19,8 +19,8 @@ export function formatRedisLink(link: ExpandedLink): RedisLinkProps {doIndex,projectId,webhooks,- tests,- testsCompleteAt,+ testVariants,+ testCompletedAt,} = link;const webhookIds = webhooks?.map(({ webhookId }) => webhookId) ?? [];@@ -44,10 +44,10 @@ export function formatRedisLink(link: ExpandedLink): RedisLinkProps {...(doIndex && { doIndex: true }),...(webhookIds.length > 0 && { webhookIds }),...(Boolean(- tests && testsCompleteAt && new Date(testsCompleteAt) > new Date(),+ testVariants && testCompletedAt && new Date(testCompletedAt) > new Date(),) && {- tests: tests as z.infer<typeof LinkTestsSchema>,- testsCompleteAt: new Date(testsCompleteAt!),+ testVariants: testVariants as z.infer<typeof LinkTestsSchema>,+ testCompletedAt: new Date(testCompletedAt!),}),};}diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.tsindex 2c66a0187b..b8213f33fa 100644--- a/apps/web/lib/zod/schemas/links.ts+++ b/apps/web/lib/zod/schemas/links.ts@@ -401,12 +401,12 @@ export const createLinkBodySchema = z.object({.describe("An array of webhook IDs to trigger when the link is clicked. These webhooks will receive click event data.",),- tests: LinkTestsSchema.nullish(),- testsStartedAt: z+ testVariants: LinkTestsSchema.nullish(),+ testStartedAt: z.string().nullish().describe("The date and time when the tests started."),- testsCompleteAt: z+ testCompletedAt: z.string().nullish().describe("The date and time when the tests were or will be completed."),@@ -626,12 +626,12 @@ export const LinkSchema = z.string().nullable().describe("The UTM content of the short link."),- tests: LinkTestsSchema.nullish(),- testsStartedAt: z+ testVariants: LinkTestsSchema.nullish(),+ testStartedAt: z.string().nullish().describe("The date and time when the tests started."),- testsCompleteAt: z+ testCompletedAt: z.string().nullish().describe("The date and time when the tests were or will be completed."),@@ -734,8 +734,8 @@ export const linkEventSchema = LinkSchema.extend({updatedAt: z.coerce.date(),lastClicked: z.coerce.date(),expiresAt: z.coerce.date(),- testsCompleteAt: z.coerce.date().nullable(),- testsStartedAt: z.coerce.date().nullable(),+ testCompletedAt: z.coerce.date().nullable(),+ testStartedAt: z.coerce.date().nullable(),// userId can be nulluserId: z.string().nullable(),});diff --git a/apps/web/ui/links/link-tests.tsx b/apps/web/ui/links/link-tests.tsxindex 5922f1d14e..d08261cf99 100644--- a/apps/web/ui/links/link-tests.tsx+++ b/apps/web/ui/links/link-tests.tsx@@ -12,21 +12,21 @@ export const LinkTests = memo(({ link }: { link: ResponseLink }) => {const { id: workspaceId } = useWorkspace();const { showTests } = useLinkCardContext();- const tests = useMemo(() => {+ const testVariants = useMemo(() => {if (- !link.tests ||- !link.testsCompleteAt ||- !(new Date() < new Date(link.testsCompleteAt))+ !link.testVariants ||+ !link.testCompletedAt ||+ !(new Date() < new Date(link.testCompletedAt)))return null;try {- return LinkTestsSchema.parse(link.tests);+ return LinkTestsSchema.parse(link.testVariants);} catch (e) {- console.error(`Failed to parse link tests for link ${link.id}`, e);+ console.error(`Failed to parse link testVariants for link ${link.id}`, e);}return null;- }, [link.tests, link.testsCompleteAt, link.id]);+ }, [link.testVariants, link.testCompletedAt, link.id]);const { data, isLoading, error } = useSWR<{@@ -37,14 +37,14 @@ export const LinkTests = memo(({ link }: { link: ResponseLink }) => {sales: number;}[]>(- Boolean(tests && tests.length) &&+ Boolean(testVariants && testVariants.length) &&`/api/analytics?${new URLSearchParams({event: "composite",groupBy: "top_urls",linkId: link.id,workspaceId: workspaceId!,- ...(link.testsStartedAt && {- start: new Date(link.testsStartedAt).toISOString(),+ ...(link.testStartedAt && {+ start: new Date(link.testStartedAt).toISOString(),}),}).toString()}`,fetcher,@@ -54,7 +54,7 @@ export const LinkTests = memo(({ link }: { link: ResponseLink }) => {);console.log(data);- if (!tests || !tests.length) return null;+ if (!testVariants || !testVariants.length) return null;return (<motion.div@@ -64,7 +64,7 @@ export const LinkTests = memo(({ link }: { link: ResponseLink }) => {className="overflow-hidden"><ul className="flex flex-col gap-2.5 border-t border-neutral-200 bg-neutral-100 p-3">- {tests.map((test, idx) => {+ {testVariants.map((test, idx) => {const analytics = data?.find(({ url }) => url === test.url);return (diff --git a/apps/web/ui/links/link-title-column.tsx b/apps/web/ui/links/link-title-column.tsxindex c06cb1e0c5..b84d4c8baf 100644--- a/apps/web/ui/links/link-title-column.tsx+++ b/apps/web/ui/links/link-title-column.tsx@@ -139,9 +139,9 @@ export function LinkTitleColumn({ link }: { link: ResponseLink }) {/>{hasQuickViewSettings && <SettingsBadge link={link} />}{link.comments && <CommentsBadge comments={link.comments} />}- {link.tests &&- link.testsCompleteAt &&- new Date(link.testsCompleteAt) > new Date() && (+ {link.testVariants &&+ link.testCompletedAt &&+ new Date(link.testCompletedAt) > new Date() && (<TestsBadge link={link} />)}</div>diff --git a/apps/web/ui/links/tests-badge.tsx b/apps/web/ui/links/tests-badge.tsxindex e07992fb81..5c09951493 100644--- a/apps/web/ui/links/tests-badge.tsx+++ b/apps/web/ui/links/tests-badge.tsx@@ -9,7 +9,7 @@ import { ResponseLink } from "./links-container";export function TestsBadge({link,}: {- link: Pick<ResponseLink, "tests" | "testsCompleteAt">;+ link: Pick<ResponseLink, "testVariants" | "testCompletedAt">;}) {const { showTests, setShowTests } = useLinkCardContext();diff --git a/apps/web/ui/modals/link-builder/ab-testing-modal.tsx b/apps/web/ui/modals/link-builder/ab-testing-modal.tsxindex f818ef0e01..5d5ad2171b 100644--- a/apps/web/ui/modals/link-builder/ab-testing-modal.tsx+++ b/apps/web/ui/modals/link-builder/ab-testing-modal.tsx@@ -41,8 +41,8 @@ import { toast } from "sonner";import { z } from "zod";import { LinkFormData } from ".";-const parseTests = (tests: LinkFormData["tests"]) =>- Array.isArray(tests) ? LinkTestsSchema.parse(tests) : null;+const parseTests = (testVariants: LinkFormData["testVariants"]) =>+ Array.isArray(testVariants) ? LinkTestsSchema.parse(testVariants) : null;const inTwoWeeks = new Date(Date.now() + 2 * 7 * 24 * 60 * 60 * 1000);@@ -79,56 +79,57 @@ function ABTestingModal({formState: { isDirty, isValid },handleSubmit,} = useForm<- { tests: z.infer<typeof LinkTestsSchema> } & Pick<+ { testVariants: z.infer<typeof LinkTestsSchema> } & Pick<LinkFormData,- "testsCompleteAt"+ "testCompletedAt">>({mode: "onChange",values: {- tests: parseTests(getValuesParent("tests")) ?? [+ testVariants: parseTests(getValuesParent("testVariants")) ?? [{ url: getValuesParent("url") || "", percentage: 100 },],- testsCompleteAt:- (getValuesParent("testsCompleteAt") as Date | null) ?? inTwoWeeks,+ testCompletedAt:+ (getValuesParent("testCompletedAt") as Date | null) ?? inTwoWeeks,},});- const tests = watch("tests") || [];- const testsCompleteAt = watch("testsCompleteAt");- const [idParent, testsParent] = watchParent(["id", "tests"]);+ const testVariants = watch("testVariants") || [];+ const testCompletedAt = watch("testCompletedAt");+ const [idParent, testVariantsParent] = watchParent(["id", "testVariants"]);const addTestUrl = () => {- if (!tests.length || tests.length >= MAX_TEST_COUNT) return;+ if (!testVariants.length || testVariants.length >= MAX_TEST_COUNT) return;- const allEqual = tests.every(- ({ percentage }) => Math.abs(percentage - tests[0].percentage) <= 1,+ const allEqual = testVariants.every(+ ({ percentage }) =>+ Math.abs(percentage - testVariants[0].percentage) <= 1,);if (allEqual) {// All percentages are equal so let's keep it that way- const each = Math.floor(100 / (tests.length + 1));+ const each = Math.floor(100 / (testVariants.length + 1));setValue(- "tests",+ "testVariants",[- ...tests.map((t) => ({ ...t, percentage: each })),- { url: "", percentage: 100 - each * tests.length },+ ...testVariants.map((t) => ({ ...t, percentage: each })),+ { url: "", percentage: 100 - each * testVariants.length },],{ shouldDirty: true },);} else {// Not all percentages are equal so let's split the latest one we can- const toSplitIndex = tests.findLastIndex(+ const toSplitIndex = testVariants.findLastIndex(({ percentage }) => percentage >= MIN_TEST_PERCENTAGE * 2,);- const toSplit = tests[toSplitIndex];+ const toSplit = testVariants[toSplitIndex];const toSplitPercentage = Math.floor(toSplit.percentage / 2);const remainingPercentage = toSplit.percentage - toSplitPercentage;setValue(- "tests",+ "testVariants",[- ...tests.map((test, idx) => ({+ ...testVariants.map((test, idx) => ({...test,percentage:idx === toSplitIndex ? toSplitPercentage : test.percentage,@@ -143,20 +144,21 @@ function ABTestingModal({};const removeTestUrl = (index: number) => {- if (tests.length < 2) return;+ if (testVariants.length < 2) return;- const allEqual = tests.every(- ({ percentage }) => Math.abs(percentage - tests[0].percentage) <= 1,+ const allEqual = testVariants.every(+ ({ percentage }) =>+ Math.abs(percentage - testVariants[0].percentage) <= 1,);if (allEqual) {// All percentages are equal so let's keep it that way- const each = Math.floor(100 / (tests.length - 1));- const remainder = 100 - each * (tests.length - 2);+ const each = Math.floor(100 / (testVariants.length - 1));+ const remainder = 100 - each * (testVariants.length - 2);setValue(- "tests",- tests+ "testVariants",+ testVariants?.filter((_, i) => i !== index).map((test, idx, arr) => ({...test,@@ -168,11 +170,11 @@ function ABTestingModal({);} else {// Not all percentages are equal so let's give the last one the remainder- const remainder = tests[index].percentage;+ const remainder = testVariants[index].percentage;setValue(- "tests",- tests+ "testVariants",+ testVariants?.filter((_, i) => i !== index).map((test, idx, arr) => ({...test,@@ -200,11 +202,11 @@ function ABTestingModal({onSubmit={(e) => {e.stopPropagation();handleSubmit((data) => {- const currentTests = data.tests;+ const currentTests = data.testVariants;if (!currentTests || currentTests.length <= 1) {- setValueParent("tests", null, { shouldDirty: true });- setValueParent("testsCompleteAt", null, {+ setValueParent("testVariants", null, { shouldDirty: true });+ setValueParent("testCompletedAt", null, {shouldDirty: true,});@@ -230,8 +232,8 @@ function ABTestingModal({setValueParent("url", currentTests[0].url, { shouldDirty: true });setValueParent("trackConversion", true);- setValueParent("tests", currentTests, { shouldDirty: true });- setValueParent("testsCompleteAt", data.testsCompleteAt, {+ setValueParent("testVariants", currentTests, { shouldDirty: true });+ setValueParent("testCompletedAt", data.testCompletedAt, {shouldDirty: true,});setShowABTestingModal(false);@@ -292,7 +294,7 @@ function ABTestingModal({className="-m-1"><div className="flex flex-col gap-2 p-1">- {tests.map((_, index) => (+ {testVariants.map((_, index) => (<div key={index} className="flex items-center gap-2"><label className="relative block flex grow items-center overflow-hidden rounded-md border border-neutral-300 focus-within:border-neutral-500 focus-within:ring-1 focus-within:ring-neutral-500"><span className="flex h-9 w-8 items-center justify-center border-r border-neutral-300 text-center text-sm font-medium text-neutral-800">@@ -306,14 +308,15 @@ function ABTestingModal({"https://dub.co/help/article/what-is-dub"}className="block h-9 grow border-none px-2 text-neutral-900 placeholder-neutral-400 focus:ring-0 sm:text-sm"- {...register(`tests.${index}.url`, {- validate: (value, { tests }) => {+ {...register(`testVariants.${index}.url`, {+ validate: (value, { testVariants }) => {if (!value) return "URL is required";if (!isValidUrl(value)) return "Invalid URL";return (- tests.length > 1 && tests.length <= MAX_TEST_COUNT+ testVariants.length > 1 &&+ testVariants.length <= MAX_TEST_COUNT);},})}@@ -343,7 +346,7 @@ function ABTestingModal({className="mt-2 h-8"onClick={addTestUrl}disabledTooltip={- tests.length >= MAX_TEST_COUNT+ testVariants.length >= MAX_TEST_COUNT? `You may only add ${MAX_TEST_COUNT} URLs`: undefined}@@ -364,10 +367,10 @@ function ABTestingModal({</div><div className="mt-4"><TrafficSplitSlider- tests={tests}+ testVariants={testVariants}onChange={(percentages) => {percentages.forEach((percentage, index) => {- setValue(`tests.${index}.percentage`, percentage, {+ setValue(`testVariants.${index}.percentage`, percentage, {shouldDirty: true,});});@@ -380,7 +383,7 @@ function ABTestingModal({<div className="mt-6"><div className="flex items-center gap-2"><label- htmlFor={`${id}-testsCompleteAt`}+ htmlFor={`${id}-testCompletedAt`}className="block text-sm font-medium text-neutral-700">Completion Date@@ -397,19 +400,19 @@ function ABTestingModal({</div><div className="mt-2 flex w-full items-center justify-between rounded-md border border-neutral-300 bg-white shadow-sm transition-all focus-within:border-neutral-800 focus-within:outline-none focus-within:ring-1 focus-within:ring-neutral-500"><input- id={`${id}-testsCompleteAt`}+ id={`${id}-testCompletedAt`}type="text"placeholder='E.g. "in 2 weeks" or "next month"'defaultValue={- getValues("testsCompleteAt")- ? formatDateTime(getValues("testsCompleteAt") as Date)+ getValues("testCompletedAt")+ ? formatDateTime(getValues("testCompletedAt") as Date): ""}onBlur={(e) => {if (e.target.value.length > 0) {const parsedDateTime = parseDateTime(e.target.value);if (parsedDateTime) {- setValue("testsCompleteAt", parsedDateTime, {+ setValue("testCompletedAt", parsedDateTime, {shouldDirty: true,});e.target.value = formatDateTime(parsedDateTime);@@ -421,13 +424,13 @@ function ABTestingModal({<inputtype="datetime-local"value={- getValues("testsCompleteAt")- ? getDateTimeLocal(getValues("testsCompleteAt") as Date)+ getValues("testCompletedAt")+ ? getDateTimeLocal(getValues("testCompletedAt") as Date): ""}onChange={(e) => {const completeDate = new Date(e.target.value);- setValue("testsCompleteAt", completeDate, {+ setValue("testCompletedAt", completeDate, {shouldDirty: true,});}}@@ -437,7 +440,7 @@ function ABTestingModal({<p className="mt-1 text-xs text-neutral-500">6 weeks maximum</p></div>- {testsParent && (+ {testVariantsParent && (<div className="mt-6 flex items-start gap-2 rounded-lg border border-amber-200 bg-amber-50 p-4"><TriangleWarning className="mt-0.5 size-4 shrink-0 text-amber-500" /><p className="text-sm font-medium text-amber-900">@@ -449,7 +452,7 @@ function ABTestingModal({<div className="mt-4 flex items-center justify-between"><div>- {Boolean(testsParent) && (+ {Boolean(testVariantsParent) && (<buttontype="button"className="text-xs font-medium text-neutral-700 transition-colors hover:text-neutral-950"@@ -457,8 +460,8 @@ function ABTestingModal({if (idParent) {setShowEndABTestingModal(true);} else {- (["tests", "testsCompleteAt"] as const).forEach((key) =>- setValueParent(key, null, { shouldDirty: true }),+ (["testVariants", "testCompletedAt"] as const).forEach(+ (key) => setValueParent(key, null, { shouldDirty: true }),);setShowABTestingModal(false);}@@ -483,7 +486,8 @@ function ABTestingModal({type="submit"variant="primary"text={- Array.isArray(testsParent) && testsParent.length > 1+ Array.isArray(testVariantsParent) &&+ testVariantsParent.length > 1? "Save changes": "Start testing"}@@ -492,10 +496,10 @@ function ABTestingModal({!isDirty ||!isValid ||Boolean(- testsCompleteAt &&+ testCompletedAt &&// Restrict competion date from -1 days to 6 weeks- (differenceInDays(testsCompleteAt, new Date()) > 6 * 7 ||- differenceInDays(testsCompleteAt, new Date()) < -1),+ (differenceInDays(testCompletedAt, new Date()) > 6 * 7 ||+ differenceInDays(testCompletedAt, new Date()) < -1),)}/>@@ -507,15 +511,17 @@ function ABTestingModal({}export function getABTestingLabel({- tests,- testsCompleteAt,-}: Pick<LinkFormData, "tests" | "testsCompleteAt">) {- const enabled = Boolean(tests && testsCompleteAt);+ testVariants,+ testCompletedAt,+}: Pick<LinkFormData, "testVariants" | "testCompletedAt">) {+ const enabled = Boolean(testVariants && testCompletedAt);- if (testsCompleteAt && new Date(testsCompleteAt) < new Date())+ if (testCompletedAt && new Date(testCompletedAt) < new Date())return "Test Complete";- return enabled && Array.isArray(tests) ? `${tests?.length} URLs` : "A/B Test";+ return enabled && Array.isArray(testVariants)+ ? `${testVariants?.length} URLs`+ : "A/B Test";}function ABTestingButton({@@ -524,17 +530,20 @@ function ABTestingButton({setShowABTestingModal: Dispatch<SetStateAction<boolean>>;}) {const { watch } = useFormContext<LinkFormData>();- const [tests, testsCompleteAt] = watch(["tests", "testsCompleteAt"]);+ const [testVariants, testCompletedAt] = watch([+ "testVariants",+ "testCompletedAt",+ ]);useKeyboardShortcut("a", () => setShowABTestingModal(true), {modal: true,});- const enabled = Boolean(tests && testsCompleteAt);+ const enabled = Boolean(testVariants && testCompletedAt);const label = useMemo(- () => getABTestingLabel({ tests, testsCompleteAt }),- [tests, testsCompleteAt],+ () => getABTestingLabel({ testVariants, testCompletedAt }),+ [testVariants, testCompletedAt],);return (@@ -577,10 +586,10 @@ export function useABTestingModal() {}function TrafficSplitSlider({- tests,+ testVariants,onChange,}: {- tests: { url: string; percentage: number }[];+ testVariants: { url: string; percentage: number }[];onChange: (percentages: number[]) => void;}) {const [isDragging, setIsDragging] = useState<number | null>(null);@@ -601,14 +610,14 @@ function TrafficSplitSlider({const mousePercentage = Math.round((mouseX / containerWidth) * 100);// Get sum of percentages to the left and right of the two being affected- const leftPercentage = tests+ const leftPercentage = testVariants.slice(0, Math.max(0, isDragging)).reduce((sum, { percentage }) => sum + percentage, 0);- const rightPercentage = tests+ const rightPercentage = testVariants.slice(isDragging + 2).reduce((sum, { percentage }) => sum + percentage, 0);- let newPercentages = tests.map(({ percentage }) => percentage);+ let newPercentages = testVariants.map(({ percentage }) => percentage);newPercentages[isDragging] = mousePercentage - leftPercentage;newPercentages[isDragging + 1] = 100 - rightPercentage - mousePercentage;@@ -618,7 +627,7 @@ function TrafficSplitSlider({onChange(newPercentages);}},- [isDragging, tests, onChange],+ [isDragging, testVariants, onChange],);const handleMouseUp = useCallback(() => {@@ -645,7 +654,7 @@ function TrafficSplitSlider({)}><div className="absolute inset-0 flex h-full">- {tests.map((test, i) => (+ {testVariants.map((test, i) => (<divkey={i}className="@container pointer-events-none relative flex h-full"@@ -660,7 +669,7 @@ function TrafficSplitSlider({{test.percentage}%</span></div>- {i < tests.length - 1 && (+ {i < testVariants.length - 1 && (<><div className="w-1.5" /><divdiff --git a/apps/web/ui/modals/link-builder/ab-testing/ab-testing-modal.tsx b/apps/web/ui/modals/link-builder/ab-testing/ab-testing-modal.tsxindex b092679506..621e96e2a5 100644--- a/apps/web/ui/modals/link-builder/ab-testing/ab-testing-modal.tsx+++ b/apps/web/ui/modals/link-builder/ab-testing/ab-testing-modal.tsx@@ -41,8 +41,8 @@ import { z } from "zod";import { LinkFormData } from "..";import { TrafficSplitSlider } from "./traffic-split-slider";-const parseTests = (tests: LinkFormData["tests"]) =>- Array.isArray(tests) ? LinkTestsSchema.parse(tests) : null;+const parseTests = (testVariants: LinkFormData["testVariants"]) =>+ Array.isArray(testVariants) ? LinkTestsSchema.parse(testVariants) : null;const inTwoWeeks = new Date(Date.now() + 2 * 7 * 24 * 60 * 60 * 1000);@@ -71,9 +71,14 @@ function ABTestingModalInner({}) {const { watch: watchParent } = useFormContext<LinkFormData>();- const [tests, testsCompleteAt] = watchParent(["tests", "testsCompleteAt"]);+ const [testVariants, testCompletedAt] = watchParent([+ "testVariants",+ "testCompletedAt",+ ]);- return tests && testsCompleteAt && new Date(testsCompleteAt) < new Date() ? (+ return testVariants &&+ testCompletedAt &&+ new Date(testCompletedAt) < new Date() ? (<ABTestingComplete setShowABTestingModal={setShowABTestingModal} />) : (<ABTestingEdit setShowABTestingModal={setShowABTestingModal} />@@ -111,60 +116,61 @@ function ABTestingEdit({formState: { isDirty, isValid },handleSubmit,} = useForm<- { tests: z.infer<typeof LinkTestsSchema> } & Pick<+ { testVariants: z.infer<typeof LinkTestsSchema> } & Pick<LinkFormData,- "testsCompleteAt"+ "testCompletedAt">>({mode: "onChange",values: {- tests: parseTests(getValuesParent("tests")) ?? [+ testVariants: parseTests(getValuesParent("testVariants")) ?? [{ url: getValuesParent("url") || "", percentage: 100 },],- testsCompleteAt:- (getValuesParent("testsCompleteAt") as Date | null) ?? inTwoWeeks,+ testCompletedAt:+ (getValuesParent("testCompletedAt") as Date | null) ?? inTwoWeeks,},});- const tests = watch("tests") || [];- const testsCompleteAt = watch("testsCompleteAt");- const [idParent, testsParent, testsStartedAtParent] = watchParent([+ const testVariants = watch("testVariants") || [];+ const testCompletedAt = watch("testCompletedAt");+ const [idParent, testVariantsParent, testStartedAtParent] = watchParent(["id",- "tests",- "testsStartedAt",+ "testVariants",+ "testStartedAt",]);const addTestUrl = () => {- if (!tests.length || tests.length >= MAX_TEST_COUNT) return;+ if (!testVariants.length || testVariants.length >= MAX_TEST_COUNT) return;- const allEqual = tests.every(- ({ percentage }) => Math.abs(percentage - tests[0].percentage) <= 1,+ const allEqual = testVariants.every(+ ({ percentage }) =>+ Math.abs(percentage - testVariants[0].percentage) <= 1,);if (allEqual) {// All percentages are equal so let's keep it that way- const each = Math.floor(100 / (tests.length + 1));+ const each = Math.floor(100 / (testVariants.length + 1));setValue(- "tests",+ "testVariants",[- ...tests.map((t) => ({ ...t, percentage: each })),- { url: "", percentage: 100 - each * tests.length },+ ...testVariants.map((t) => ({ ...t, percentage: each })),+ { url: "", percentage: 100 - each * testVariants.length },],{ shouldDirty: true },);} else {// Not all percentages are equal so let's split the latest one we can- const toSplitIndex = tests.findLastIndex(+ const toSplitIndex = testVariants.findLastIndex(({ percentage }) => percentage >= MIN_TEST_PERCENTAGE * 2,);- const toSplit = tests[toSplitIndex];+ const toSplit = testVariants[toSplitIndex];const toSplitPercentage = Math.floor(toSplit.percentage / 2);const remainingPercentage = toSplit.percentage - toSplitPercentage;setValue(- "tests",+ "testVariants",[- ...tests.map((test, idx) => ({+ ...testVariants.map((test, idx) => ({...test,percentage:idx === toSplitIndex ? toSplitPercentage : test.percentage,@@ -179,20 +185,21 @@ function ABTestingEdit({};const removeTestUrl = (index: number) => {- if (tests.length < 2) return;+ if (testVariants.length < 2) return;- const allEqual = tests.every(- ({ percentage }) => Math.abs(percentage - tests[0].percentage) <= 1,+ const allEqual = testVariants.every(+ ({ percentage }) =>+ Math.abs(percentage - testVariants[0].percentage) <= 1,);if (allEqual) {// All percentages are equal so let's keep it that way- const each = Math.floor(100 / (tests.length - 1));- const remainder = 100 - each * (tests.length - 2);+ const each = Math.floor(100 / (testVariants.length - 1));+ const remainder = 100 - each * (testVariants.length - 2);setValue(- "tests",- tests+ "testVariants",+ testVariants?.filter((_, i) => i !== index).map((test, idx, arr) => ({...test,@@ -204,11 +211,11 @@ function ABTestingEdit({);} else {// Not all percentages are equal so let's give the last one the remainder- const remainder = tests[index].percentage;+ const remainder = testVariants[index].percentage;setValue(- "tests",- tests+ "testVariants",+ testVariants?.filter((_, i) => i !== index).map((test, idx, arr) => ({...test,@@ -232,11 +239,11 @@ function ABTestingEdit({onSubmit={(e) => {e.stopPropagation();handleSubmit((data) => {- const currentTests = data.tests;+ const currentTests = data.testVariants;if (!currentTests || currentTests.length <= 1) {- setValueParent("tests", null, { shouldDirty: true });- setValueParent("testsCompleteAt", null, {+ setValueParent("testVariants", null, { shouldDirty: true });+ setValueParent("testCompletedAt", null, {shouldDirty: true,});@@ -262,12 +269,12 @@ function ABTestingEdit({setValueParent("url", currentTests[0].url, { shouldDirty: true });setValueParent("trackConversion", true);- setValueParent("tests", currentTests, { shouldDirty: true });- setValueParent("testsCompleteAt", data.testsCompleteAt, {+ setValueParent("testVariants", currentTests, { shouldDirty: true });+ setValueParent("testCompletedAt", data.testCompletedAt, {shouldDirty: true,});- if (!testsStartedAtParent)- setValueParent("testsStartedAt", new Date(), {+ if (!testStartedAtParent)+ setValueParent("testStartedAt", new Date(), {shouldDirty: true,});@@ -329,7 +336,7 @@ function ABTestingEdit({className="-m-1"><div className="flex flex-col gap-2 p-1">- {tests.map((_, index) => (+ {testVariants.map((_, index) => (<div key={index} className="flex items-center gap-2"><label className="relative block flex grow items-center overflow-hidden rounded-md border border-neutral-300 focus-within:border-neutral-500 focus-within:ring-1 focus-within:ring-neutral-500"><span className="flex h-9 w-8 items-center justify-center border-r border-neutral-300 text-center text-sm font-medium text-neutral-800">@@ -343,14 +350,15 @@ function ABTestingEdit({"https://dub.co/help/article/what-is-dub"}className="block h-9 grow border-none px-2 text-neutral-900 placeholder-neutral-400 focus:ring-0 sm:text-sm"- {...register(`tests.${index}.url`, {- validate: (value, { tests }) => {+ {...register(`testVariants.${index}.url`, {+ validate: (value, { testVariants }) => {if (!value) return "URL is required";if (!isValidUrl(value)) return "Invalid URL";return (- tests.length > 1 && tests.length <= MAX_TEST_COUNT+ testVariants.length > 1 &&+ testVariants.length <= MAX_TEST_COUNT);},})}@@ -380,7 +388,7 @@ function ABTestingEdit({className="mt-2 h-8"onClick={addTestUrl}disabledTooltip={- tests.length >= MAX_TEST_COUNT+ testVariants.length >= MAX_TEST_COUNT? `You may only add ${MAX_TEST_COUNT} URLs`: undefined}@@ -401,10 +409,10 @@ function ABTestingEdit({</div><div className="mt-4"><TrafficSplitSlider- tests={tests}+ testVariants={testVariants}onChange={(percentages) => {percentages.forEach((percentage, index) => {- setValue(`tests.${index}.percentage`, percentage, {+ setValue(`testVariants.${index}.percentage`, percentage, {shouldDirty: true,});});@@ -417,7 +425,7 @@ function ABTestingEdit({<div className="mt-6"><div className="flex items-center gap-2"><label- htmlFor={`${id}-testsCompleteAt`}+ htmlFor={`${id}-testCompletedAt`}className="block text-sm font-medium text-neutral-700">Completion Date@@ -434,19 +442,19 @@ function ABTestingEdit({</div><div className="mt-2 flex w-full items-center justify-between rounded-md border border-neutral-300 bg-white shadow-sm transition-all focus-within:border-neutral-800 focus-within:outline-none focus-within:ring-1 focus-within:ring-neutral-500"><input- id={`${id}-testsCompleteAt`}+ id={`${id}-testCompletedAt`}type="text"placeholder='E.g. "in 2 weeks" or "next month"'defaultValue={- getValues("testsCompleteAt")- ? formatDateTime(getValues("testsCompleteAt") as Date)+ getValues("testCompletedAt")+ ? formatDateTime(getValues("testCompletedAt") as Date): ""}onBlur={(e) => {if (e.target.value.length > 0) {const parsedDateTime = parseDateTime(e.target.value);if (parsedDateTime) {- setValue("testsCompleteAt", parsedDateTime, {+ setValue("testCompletedAt", parsedDateTime, {shouldDirty: true,});e.target.value = formatDateTime(parsedDateTime);@@ -458,13 +466,13 @@ function ABTestingEdit({<inputtype="datetime-local"value={- getValues("testsCompleteAt")- ? getDateTimeLocal(getValues("testsCompleteAt") as Date)+ getValues("testCompletedAt")+ ? getDateTimeLocal(getValues("testCompletedAt") as Date): ""}onChange={(e) => {const completeDate = new Date(e.target.value);- setValue("testsCompleteAt", completeDate, {+ setValue("testCompletedAt", completeDate, {shouldDirty: true,});}}@@ -474,7 +482,7 @@ function ABTestingEdit({<p className="mt-1 text-xs text-neutral-500">6 weeks maximum</p></div>- {testsParent && (+ {testVariantsParent && (<div className="mt-6 flex items-start gap-2 rounded-lg border border-amber-200 bg-amber-50 p-4"><TriangleWarning className="mt-0.5 size-4 shrink-0 text-amber-500" /><p className="text-sm font-medium text-amber-900">@@ -486,7 +494,7 @@ function ABTestingEdit({<div className="mt-4 flex items-center justify-between"><div>- {Boolean(testsParent) && (+ {Boolean(testVariantsParent) && (<buttontype="button"className="text-xs font-medium text-neutral-700 transition-colors hover:text-neutral-950"@@ -494,8 +502,8 @@ function ABTestingEdit({if (idParent) {setShowEndABTestingModal(true);} else {- (["tests", "testsCompleteAt"] as const).forEach((key) =>- setValueParent(key, null, { shouldDirty: true }),+ (["testVariants", "testCompletedAt"] as const).forEach(+ (key) => setValueParent(key, null, { shouldDirty: true }),);setShowABTestingModal(false);}@@ -520,7 +528,8 @@ function ABTestingEdit({type="submit"variant="primary"text={- Array.isArray(testsParent) && testsParent.length > 1+ Array.isArray(testVariantsParent) &&+ testVariantsParent.length > 1? "Save changes": "Start testing"}@@ -529,10 +538,10 @@ function ABTestingEdit({!isDirty ||!isValid ||Boolean(- testsCompleteAt &&+ testCompletedAt &&// Restrict competion date from -1 days to 6 weeks- (differenceInDays(testsCompleteAt, new Date()) > 6 * 7 ||- differenceInDays(testsCompleteAt, new Date()) < -1),+ (differenceInDays(testCompletedAt, new Date()) > 6 * 7 ||+ differenceInDays(testCompletedAt, new Date()) < -1),)}/>@@ -550,8 +559,11 @@ function ABTestingComplete({}) {const { watch } = useFormContext<LinkFormData>();- const [testsRaw, winnerUrl] = watch(["tests", "url"]);- const tests = useMemo(() => parseTests(testsRaw), [testsRaw]);+ const [testVariantsRaw, winnerUrl] = watch(["testVariants", "url"]);+ const testVariants = useMemo(+ () => parseTests(testVariantsRaw),+ [testVariantsRaw],+ );return (<div className="px-5 py-4">@@ -560,7 +572,7 @@ function ABTestingComplete({{/* Testing URLs */}<div className="mt-6"><div className="flex flex-col gap-2">- {tests?.map((test, index) => (+ {testVariants?.map((test, index) => (<divkey={index}className="relative block flex grow items-center overflow-hidden rounded-md border border-neutral-300 focus-within:border-neutral-500 focus-within:ring-1 focus-within:ring-neutral-500"@@ -597,15 +609,17 @@ function ABTestingComplete({}export function getABTestingLabel({- tests,- testsCompleteAt,-}: Pick<LinkFormData, "tests" | "testsCompleteAt">) {- const enabled = Boolean(tests && testsCompleteAt);+ testVariants,+ testCompletedAt,+}: Pick<LinkFormData, "testVariants" | "testCompletedAt">) {+ const enabled = Boolean(testVariants && testCompletedAt);- if (testsCompleteAt && new Date() > new Date(testsCompleteAt))+ if (testCompletedAt && new Date() > new Date(testCompletedAt))return "Test Complete";- return enabled && Array.isArray(tests) ? `${tests?.length} URLs` : "A/B Test";+ return enabled && Array.isArray(testVariants)+ ? `${testVariants?.length} URLs`+ : "A/B Test";}function ABTestingButton({@@ -614,18 +628,21 @@ function ABTestingButton({setShowABTestingModal: Dispatch<SetStateAction<boolean>>;}) {const { watch } = useFormContext<LinkFormData>();- const [tests, testsCompleteAt] = watch(["tests", "testsCompleteAt"]);+ const [testVariants, testCompletedAt] = watch([+ "testVariants",+ "testCompletedAt",+ ]);useKeyboardShortcut("a", () => setShowABTestingModal(true), {modal: true,});- const enabled = Boolean(tests && testsCompleteAt);- const complete = enabled && new Date() > new Date(testsCompleteAt!);+ const enabled = Boolean(testVariants && testCompletedAt);+ const complete = enabled && new Date() > new Date(testCompletedAt!);const label = useMemo(- () => getABTestingLabel({ tests, testsCompleteAt }),- [tests, testsCompleteAt],+ () => getABTestingLabel({ testVariants, testCompletedAt }),+ [testVariants, testCompletedAt],);const Icon = complete ? CircleCheck : Flask;diff --git a/apps/web/ui/modals/link-builder/ab-testing/end-ab-testing-modal.tsx b/apps/web/ui/modals/link-builder/ab-testing/end-ab-testing-modal.tsxindex 36e51c7e55..675abf8e65 100644--- a/apps/web/ui/modals/link-builder/ab-testing/end-ab-testing-modal.tsx+++ b/apps/web/ui/modals/link-builder/ab-testing/end-ab-testing-modal.tsx@@ -21,7 +21,7 @@ function EndABTestingModal({const { watch: watchParent, setValue: setValueParent } =useFormContext<LinkFormData>();- const tests = watchParent("tests") as Array<{+ const testVariants = watchParent("testVariants") as Array<{url: string;percentage: number;}> | null;@@ -44,7 +44,7 @@ function EndABTestingModal({the change.</p><div className="mt-4 flex flex-col gap-2">- {tests?.map((test, index) => (+ {testVariants?.map((test, index) => (<buttonkey={index}onClick={() => setSelectedUrl(test.url)}@@ -94,7 +94,7 @@ function EndABTestingModal({onClick={() => {if (selectedUrl) {setValueParent("url", selectedUrl, { shouldDirty: true });- setValueParent("testsCompleteAt", new Date(), {+ setValueParent("testCompletedAt", new Date(), {shouldDirty: true,});setShowEndABTestingModal(false);diff --git a/apps/web/ui/modals/link-builder/ab-testing/traffic-split-slider.tsx b/apps/web/ui/modals/link-builder/ab-testing/traffic-split-slider.tsxindex fe9b10905e..948644ce79 100644--- a/apps/web/ui/modals/link-builder/ab-testing/traffic-split-slider.tsx+++ b/apps/web/ui/modals/link-builder/ab-testing/traffic-split-slider.tsx@@ -3,10 +3,10 @@ import { cn } from "@dub/utils";import { useCallback, useEffect, useRef, useState } from "react";export function TrafficSplitSlider({- tests,+ testVariants,onChange,}: {- tests: { url: string; percentage: number }[];+ testVariants: { url: string; percentage: number }[];onChange: (percentages: number[]) => void;}) {const [isDragging, setIsDragging] = useState<number | null>(null);@@ -27,14 +27,14 @@ export function TrafficSplitSlider({const mousePercentage = Math.round((mouseX / containerWidth) * 100);// Get sum of percentages to the left and right of the two being affected- const leftPercentage = tests+ const leftPercentage = testVariants.slice(0, Math.max(0, isDragging)).reduce((sum, { percentage }) => sum + percentage, 0);- const rightPercentage = tests+ const rightPercentage = testVariants.slice(isDragging + 2).reduce((sum, { percentage }) => sum + percentage, 0);- let newPercentages = tests.map(({ percentage }) => percentage);+ let newPercentages = testVariants.map(({ percentage }) => percentage);newPercentages[isDragging] = mousePercentage - leftPercentage;newPercentages[isDragging + 1] = 100 - rightPercentage - mousePercentage;@@ -44,7 +44,7 @@ export function TrafficSplitSlider({onChange(newPercentages);}},- [isDragging, tests, onChange],+ [isDragging, testVariants, onChange],);const handleMouseUp = useCallback(() => {@@ -71,7 +71,7 @@ export function TrafficSplitSlider({)}><div className="absolute inset-0 flex h-full">- {tests.map((test, i) => (+ {testVariants.map((test, i) => (<divkey={i}className="@container pointer-events-none relative flex h-full"@@ -86,7 +86,7 @@ export function TrafficSplitSlider({{test.percentage}%</span></div>- {i < tests.length - 1 && (+ {i < testVariants.length - 1 && (<><div className="w-1.5" /><divdiff --git a/apps/web/ui/modals/link-builder/constants.ts b/apps/web/ui/modals/link-builder/constants.tsindex cf4b88bcc4..11a0c8511e 100644--- a/apps/web/ui/modals/link-builder/constants.ts+++ b/apps/web/ui/modals/link-builder/constants.ts@@ -98,12 +98,12 @@ export const MOBILE_MORE_ITEMS: MoreItem[] = [type: "modal",},{- key: "tests",+ key: "testVariants",icon: Flask,label: "A/B Testing",badgeLabel: getABTestingLabel,shortcutKey: "b",- enabled: (data) => Boolean(data.tests && data.testsCompleteAt),+ enabled: (data) => Boolean(data.testVariants && data.testCompletedAt),type: "modal",},{diff --git a/apps/web/ui/modals/link-builder/conversion-tracking-toggle.tsx b/apps/web/ui/modals/link-builder/conversion-tracking-toggle.tsxindex ea8a672e19..5caaeb1c1e 100644--- a/apps/web/ui/modals/link-builder/conversion-tracking-toggle.tsx+++ b/apps/web/ui/modals/link-builder/conversion-tracking-toggle.tsx@@ -21,7 +21,10 @@ export function ConversionTrackingToggle() {const conversionsEnabled = !!plan && plan !== "free" && plan !== "pro";- const [trackConversion, tests] = watch(["trackConversion", "tests"]);+ const [trackConversion, testVariants] = watch([+ "trackConversion",+ "testVariants",+ ]);useKeyboardShortcut("c",@@ -58,7 +61,7 @@ export function ConversionTrackingToggle() {})}disabledTooltip={- trackConversion && tests ? (+ trackConversion && testVariants ? (<TooltipContent title="Conversion tracking must be enabled to use A/B testing." />) : conversionsEnabled ? undefined : (<TooltipContent@@ -72,7 +75,7 @@ export function ConversionTrackingToggle() {)}thumbIcon={- trackConversion && tests ? (+ trackConversion && testVariants ? (<span className="flex size-full items-center justify-center"><FlaskSmall className="size-2 text-blue-500" /></span>diff --git a/apps/web/ui/modals/link-builder/more-dropdown.tsx b/apps/web/ui/modals/link-builder/more-dropdown.tsxindex 9503c228a5..4c4db8bd88 100644--- a/apps/web/ui/modals/link-builder/more-dropdown.tsx+++ b/apps/web/ui/modals/link-builder/more-dropdown.tsx@@ -39,7 +39,7 @@ export function MoreDropdown() {const { AdvancedModal, setShowAdvancedModal } = useAdvancedModal();const modalCallbacks = {- tests: setShowABTestingModal,+ testVariants: setShowABTestingModal,password: setShowPasswordModal,targeting: setShowTargetingModal,expiresAt: setShowExpirationModal,diff --git a/packages/prisma/schema/link.prisma b/packages/prisma/schema/link.prismaindex dabb6c6202..ababe27612 100644--- a/packages/prisma/schema/link.prisma+++ b/packages/prisma/schema/link.prisma@@ -34,9 +34,9 @@ model Link {geo Json? @db.Json // custom link for specific countries// A/B Testing- tests Json? @db.Json // A/B testing data- testsStartedAt DateTime? // When tests were started- testsCompleteAt DateTime? // When tests were or will be completed+ testVariants Json? @db.Json // A/B testing data+ testStartedAt DateTime? // When tests were started+ testCompletedAt DateTime? // When tests were or will be completed// User who created the linkuser User? @relation(fields: [userId], references: [id])