The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
finalize AI filtering schema, fix filter.list
Steven Teyad5b746977dc
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/use-program-network-filters.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/use-program-network-filters.tsxindex b8c27c0b1a..62b148b24e 100644--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/use-program-network-filters.tsx+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/use-program-network-filters.tsx@@ -91,6 +91,7 @@ export function useProgramNetworkFilters() {key: "category",icon: Suitcase,label: "Category",+ labelPlural: "categories",getOptionIcon: (value) => {const Icon = PROGRAM_CATEGORIES_MAP[value]?.icon || Suitcase;return <Icon className="size-4" />;diff --git a/apps/web/lib/ai/generate-filters.ts b/apps/web/lib/ai/generate-filters.tsindex 4d5c035e82..a918bc43e8 100644--- a/apps/web/lib/ai/generate-filters.ts+++ b/apps/web/lib/ai/generate-filters.ts@@ -4,40 +4,53 @@ import { VALID_ANALYTICS_FILTERS } from "@/lib/analytics/constants";import { analyticsQuerySchema } from "@/lib/zod/schemas/analytics";import { anthropic } from "@ai-sdk/anthropic";import { createStreamableValue } from "@ai-sdk/rsc";-import { COUNTRY_CODES } from "@dub/utils";-import { streamObject } from "ai";+import { Output, streamText } from "ai";import * as z from "zod/v4";+function getDescription(schema: z.ZodTypeAny): string {+ const s = schema as { description?: string; _def?: { description?: string } };+ return s.description ?? s._def?.description ?? "";+}++/** Schema for AI filter generation: same keys as analytics filters but all string (no parseFilterValue transform). */+function buildAIFilterSchema() {+ const shape = analyticsQuerySchema.shape as Record<string, z.ZodTypeAny>;+ const entries = VALID_ANALYTICS_FILTERS.filter(+ (key) => shape[key] != null,+ ).map((key) => {+ return [+ key,+ z.string().optional().describe(getDescription(shape[key])),+ ] as const;+ });+ return z.object(Object.fromEntries(entries));+}++const AI_FILTER_SCHEMA = buildAIFilterSchema();++const SYSTEM_PROMPT = `You are an analytics filter assistant. Extract or infer filter parameters from the user's request.++Output format: every filter value must use the advanced filtering syntax as a single string:+- Single value: \`dub.co\`+- Multiple values (comma-separated): \`dub.co,google.com\`+- Exclusion (prefix with -): \`-spam.com\`++Only include fields that are clearly requested or implied. Omit optional fields when not relevant. For dates use ISO 8601 (e.g. 2024-01-15).`;+export async function generateFilters(prompt: string) {const stream = createStreamableValue();- const schema = analyticsQuerySchema- .pick({- ...(VALID_ANALYTICS_FILTERS.reduce((acc, filter) => {- acc[filter] = true;- return acc;- }, {}) as any),- })- .extend({- // polyfilling this here cause we're removing it from the main Analytics schema (to save space for our OpenAPI spec)- country: z- .enum(COUNTRY_CODES)- .optional()- .describe(- "The country to retrieve analytics for. Must be passed as a 2-letter ISO 3166-1 country code. See https://d.to/geo for more information.",- ),- });-(async () => {- const { partialObjectStream } = await streamObject({+ const { partialOutputStream } = streamText({model: anthropic("claude-sonnet-4-20250514"),- schema,+ output: Output.object({ schema: AI_FILTER_SCHEMA }),+ system: SYSTEM_PROMPT,prompt,temperature: 0.4,});- for await (const partialObject of partialObjectStream) {- const parsed = schema.safeParse(partialObject);+ for await (const partialObject of partialOutputStream) {+ const parsed = AI_FILTER_SCHEMA.safeParse(partialObject);if (parsed.success) stream.update(parsed.data);}diff --git a/apps/web/lib/analytics/constants.ts b/apps/web/lib/analytics/constants.tsindex 04ac1c8020..da7839428e 100644--- a/apps/web/lib/analytics/constants.ts+++ b/apps/web/lib/analytics/constants.ts@@ -122,9 +122,15 @@ export const VALID_ANALYTICS_FILTERS = ["domain","key","linkId",+ "tagId",+ "folderId",+ "groupId",+ "partnerId",+ "customerId","interval","start","end",+ // more filter facets"country","city","region",@@ -136,20 +142,16 @@ export const VALID_ANALYTICS_FILTERS = ["referer","refererUrl","url",- "partnerId",- "folderId",- "groupId",- "tagId",- "tagIds",- "customerId",- "qr", // deprecated, but keeping for now for backwards compatibility- "root",- "saleType","utm_source","utm_medium","utm_campaign","utm_term","utm_content",+ "root",+ "saleType",+ // deprecated filters, but keeping for now for backwards compatibility+ "tagIds",+ "qr",];// possible analytics filters for a given linkIddiff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.tsindex 325b6a5227..46998ddf5d 100644--- a/apps/web/lib/zod/schemas/analytics.ts+++ b/apps/web/lib/zod/schemas/analytics.ts@@ -94,12 +94,35 @@ export const analyticsQuerySchema = z.object({"The ID of the tenant that created the link inside your system. " +"Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +"Examples: `tenant_123`, `tenant_123,tenant_456`, `-tenant_789`.",- )- .meta({ example: "tenant_123" }),- programId: z+ ),+ tagId: z+ .string()+ .optional()+ .transform(parseFilterValue)+ .describe(+ "The tag ID to retrieve analytics for. " ++ "Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " ++ "Examples: `tag_123`, `tag_123,tag_456`, `-tag_789`.",+ ),+ folderId: z+ .string()+ .optional()+ .transform(parseFilterValue)+ .describe(+ "The folder ID to retrieve analytics for. " ++ "Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " ++ "Examples: `folder_123`, `folder_123,folder_456`, `-folder_789`. " ++ "If not provided, return analytics for all links.",+ ),+ groupId: z.string().optional()- .describe("The ID of the program to retrieve analytics for."),+ .transform(parseFilterValue)+ .describe(+ "The group ID to retrieve analytics for. " ++ "Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " ++ "Examples: `grp_123`, `grp_123,grp_456`, `-grp_789`.",+ ),partnerId: z.string().optional()@@ -108,8 +131,7 @@ export const analyticsQuerySchema = z.object({"The ID of the partner to retrieve analytics for. " +"Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +"Examples: `pn_123`, `pn_123,pn_456`, `-pn_789`.",- )- .meta({ example: "pn_123" }),+ ),customerId: z.string().optional()@@ -140,22 +162,16 @@ export const analyticsQuerySchema = z.object({"The IANA time zone code for aligning timeseries granularity (e.g. America/New_York). Defaults to UTC.",).meta({ example: "America/New_York", default: "UTC" }),+ // more filter facetscountry: z.string().optional().transform(parseFilterValue).describe(- "The country to retrieve analytics for. Must be passed as a 2-letter ISO 3166-1 country code. " +- "Supports advanced filtering: " +- "• Single value: `US` (IS US) " +- "• Multiple values: `US,BR,FR` (IS ONE OF) " +- "• Exclude single: `-US` (IS NOT US) " +- "• Exclude multiple: `-US,BR` (IS NOT ONE OF). " +- "See https://d.to/geo for country codes.",- )- .meta({- example: "US",- }),+ "The country to retrieve analytics for. Must be passed as a 2-letter ISO 3166-1 country code (see https://d.to/geo). " ++ "Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " ++ "Examples: `US`, `US,BR,FR`, `-US`.",+ ),city: z.string().optional()@@ -164,23 +180,24 @@ export const analyticsQuerySchema = z.object({"The city to retrieve analytics for. " +"Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +"Examples: `New York`, `New York,London`, `-New York`.",- )- .meta({ example: "New York" }),+ ),region: z.string().optional()- .describe("The ISO 3166-2 region code to retrieve analytics for."),+ .describe(+ "The ISO 3166-2 region code to retrieve analytics for. " ++ "Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " ++ "Examples: `NY`, `NY,CA`, `-NY`.",+ ),continent: z.string().optional().transform(parseFilterValue).describe(- "The continent to retrieve analytics for. " ++ "The continent to retrieve analytics for. Valid values: AF, AN, AS, EU, NA, OC, SA. " +"Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +- "Valid values: AF, AN, AS, EU, NA, OC, SA. " +"Examples: `NA`, `NA,EU`, `-AS`.",- )- .meta({ example: "NA" }),+ ),device: z.string().optional()@@ -200,8 +217,7 @@ export const analyticsQuerySchema = z.object({"The device to retrieve analytics for. " +"Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +"Examples: `Desktop`, `Mobile,Tablet`, `-Mobile`.",- )- .meta({ example: "Desktop" }),+ ),browser: z.string().optional()@@ -220,8 +236,7 @@ export const analyticsQuerySchema = z.object({"The browser to retrieve analytics for. " +"Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +"Examples: `Chrome`, `Chrome,Firefox,Safari`, `-IE`.",- )- .meta({ example: "Chrome" }),+ ),os: z.string().optional()@@ -240,20 +255,17 @@ export const analyticsQuerySchema = z.object({"The OS to retrieve analytics for. " +"Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +"Examples: `Windows`, `Mac,Windows,Linux`, `-Windows`.",- )- .meta({ example: "Windows" }),+ ),trigger: z.string().optional().transform(parseFilterValue).describe(- "The trigger to retrieve analytics for. " ++ "The trigger to retrieve analytics for. Valid values: qr, link, pageview. " +"Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +- "Valid values: qr, link. " +"Examples: `qr`, `qr,link`, `-qr`. " +"If undefined, returns all trigger types.",- )- .meta({ example: "qr" }),+ ),referer: z.string().optional()@@ -262,17 +274,16 @@ export const analyticsQuerySchema = z.object({"The referer hostname to retrieve analytics for. " +"Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +"Examples: `google.com`, `google.com,twitter.com`, `-facebook.com`.",- )- .meta({ example: "google.com" }),+ ),refererUrl: z.string().optional().transform(parseFilterValue).describe("The full referer URL to retrieve analytics for. " +- "Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`).",- )- .meta({ example: "https://dub.co/blog" }),+ "Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " ++ "Examples: `https://google.com`, `https://google.com,https://twitter.com`, `-https://spam.com`.",+ ),url: z.string().optional()@@ -281,39 +292,7 @@ export const analyticsQuerySchema = z.object({"The destination URL to retrieve analytics for. " +"Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +"Examples: `https://example.com`, `https://example.com,https://other.com`, `-https://spam.com`.",- )- .meta({ example: "https://example.com" }),- tagId: z- .string()- .optional()- .transform(parseFilterValue)- .describe(- "The tag ID to retrieve analytics for. " +- "Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +- "Examples: `tag_123`, `tag_123,tag_456`, `-tag_789`.",- )- .meta({ example: "tag_123" }),- folderId: z- .string()- .optional()- .transform(parseFilterValue)- .describe(- "The folder ID to retrieve analytics for. " +- "Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +- "Examples: `folder_123`, `folder_123,folder_456`, `-folder_789`. " +- "If not provided, return analytics for all links.",- )- .meta({ example: "folder_123" }),- groupId: z- .string()- .optional()- .transform(parseFilterValue)- .describe(- "The group ID to retrieve analytics for. " +- "Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +- "Examples: `grp_123`, `grp_123,grp_456`, `-grp_789`.",- )- .meta({ example: "grp_123" }),+ ),utm_source: z.string().optional()@@ -322,8 +301,7 @@ export const analyticsQuerySchema = z.object({"The UTM source to retrieve analytics for. " +"Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +"Examples: `google`, `google,twitter`, `-spam`.",- )- .meta({ example: "google" }),+ ),utm_medium: z.string().optional()@@ -332,8 +310,7 @@ export const analyticsQuerySchema = z.object({"The UTM medium to retrieve analytics for. " +"Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +"Examples: `cpc`, `cpc,social`, `-email`.",- )- .meta({ example: "cpc" }),+ ),utm_campaign: z.string().optional()@@ -342,8 +319,7 @@ export const analyticsQuerySchema = z.object({"The UTM campaign to retrieve analytics for. " +"Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +"Examples: `summer_sale`, `summer_sale,winter_sale`, `-old_campaign`.",- )- .meta({ example: "summer_sale" }),+ ),utm_term: z.string().optional()@@ -351,8 +327,7 @@ export const analyticsQuerySchema = z.object({.describe("The UTM term to retrieve analytics for. " +"Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`).",- )- .meta({ example: "keyword" }),+ ),utm_content: z.string().optional()@@ -360,8 +335,7 @@ export const analyticsQuerySchema = z.object({.describe("The UTM content to retrieve analytics for. " +"Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`).",- )- .meta({ example: "banner" }),+ ),root: z.string().optional()@@ -385,31 +359,33 @@ export const analyticsQuerySchema = z.object({"Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +"Examples: `true` (root domains only), `false` (regular links only), `true,false` (both). " +"If undefined, return both.",- )- .meta({ example: "true" }),+ ),saleType: z.string().optional().transform(parseFilterValue).describe(- "Filter sales by type. " ++ "Filter sales by type. Valid values: `new` (first-time purchases), `recurring` (repeat purchases). " +"Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +- "Valid values: `new` (first-time purchases), `recurring` (repeat purchases). " +"Examples: `new`, `new,recurring`, `-recurring`. " +"If undefined, returns both.",- )- .meta({ example: "new" }),+ ),query: z.string().max(10000).optional().describe(- "Search the events by a custom metadata value. Only available for lead and sale events.",- )- .meta({- example: "metadata['key']:'value'",- }),+ "Search the events by a custom metadata value. Only available for lead and sale events. " ++ "Examples: `metadata['key']:'value'`",+ ),// deprecated fields+ programId: z+ .string()+ .optional()+ .describe(+ "Deprecated: This is automatically inferred from your workspace's defaultProgramId. The ID of the program to retrieve analytics for.",+ )+ .meta({ deprecated: true }),tagIds: z.string().optional()diff --git a/apps/web/ui/analytics/use-analytics-filters.tsx b/apps/web/ui/analytics/use-analytics-filters.tsxindex a04c585271..e9b40e78a6 100644--- a/apps/web/ui/analytics/use-analytics-filters.tsx+++ b/apps/web/ui/analytics/use-analytics-filters.tsx@@ -410,6 +410,7 @@ export function useAnalyticsFilters({icon: Receipt2,label: "Sale type",separatorAfter: true,+ hideMultipleIcons: true,options: [{value: "new",@@ -543,6 +544,7 @@ export function useAnalyticsFilters({key: "root",icon: Sliders,label: "Link type",+ hideMultipleIcons: true,options: [{value: "true",@@ -562,6 +564,7 @@ export function useAnalyticsFilters({key: "country",icon: FlagWavy,label: "Country",+ labelPlural: "countries",getOptionIcon: (value) => {if (typeof value !== "string") return null;@@ -584,6 +587,7 @@ export function useAnalyticsFilters({key: "city",icon: OfficeBuilding,label: "City",+ labelPlural: "cities",options:cities?.map(({ city, country, ...rest }) => ({value: city,@@ -683,6 +687,7 @@ export function useAnalyticsFilters({key: "os",icon: Cube,label: "OS",+ labelPlural: "OS",hideMultipleIcons: true,getOptionIcon: (value) => {if (typeof value !== "string") return null;@@ -789,6 +794,8 @@ export function useAnalyticsFilters({key: "customerId",icon: User,label: "Customer",+ singleSelect: true,+ hideMultipleIcons: true,hideInFilterDropdown: true,getOptionIcon: () => {return selectedCustomer ? (diff --git a/packages/ui/src/filter/filter-list.tsx b/packages/ui/src/filter/filter-list.tsxindex 2ac66cb778..13ce723ea2 100644--- a/packages/ui/src/filter/filter-list.tsx+++ b/packages/ui/src/filter/filter-list.tsx@@ -1,4 +1,4 @@-import { cn, truncate } from "@dub/utils";+import { cn, pluralize, truncate } from "@dub/utils";import { Command } from "cmdk";import { X } from "lucide-react";import { AnimatePresence, motion } from "motion/react";@@ -47,31 +47,6 @@ function getOperatorLabel(operator: FilterOperator): string {}}-function pluralize(word: string, count: number): string {- if (count === 1) return word.toLowerCase();-- const irregularPlurals: Record<string, string> = {- country: "countries",- city: "cities",- category: "categories",- os: "OS",- };-- const lowerWord = word.toLowerCase();- if (irregularPlurals[lowerWord]) {- return irregularPlurals[lowerWord];- }-- if (- lowerWord.endsWith("y") &&- !["ay", "ey", "iy", "oy", "uy"].some((ending) => lowerWord.endsWith(ending))- ) {- return lowerWord.slice(0, -1) + "ies";- }-- return lowerWord + "s";-}-export function FilterList({filters,activeFilters,@@ -140,7 +115,7 @@ export function FilterList({String(value));})()- : `${values.length} ${pluralize(filter.label, values.length)}`;+ : `${values.length} ${filter.labelPlural ?? pluralize(filter.label, values.length)}`;const OptionDisplay = ({ className }: { className?: string }) => {let iconDisplay;@@ -436,7 +411,9 @@ function OperatorFilterPill({{filter.label}</div>- {(isAdvancedFilter || filter.multiple) && !filter.hideOperator ? (+ {(isAdvancedFilter || filter.multiple) &&+ !filter.singleSelect &&+ !filter.hideOperator ? (<PopoveropenPopover={operatorDropdownOpen}setOpenPopover={setOperatorDropdownOpen}@@ -566,20 +543,21 @@ function OperatorFilterPill({}}value={optionLabel + option.value}>- {(isAdvancedFilter || filter.multiple) && (- <div- className={cn(- "flex h-4 w-4 items-center justify-center rounded border",- isSelected- ? "border-neutral-900 bg-neutral-900"- : "border-neutral-300",- )}- >- {isSelected && (- <Check className="h-3 w-3 text-white" />- )}- </div>- )}+ {(isAdvancedFilter || filter.multiple) &&+ !filter.singleSelect && (+ <div+ className={cn(+ "flex h-4 w-4 items-center justify-center rounded border",+ isSelected+ ? "border-neutral-900 bg-neutral-900"+ : "border-neutral-300",+ )}+ >+ {isSelected && (+ <Check className="h-3 w-3 text-white" />+ )}+ </div>+ )}<span className="shrink-0 text-neutral-600">{isReactNode(OptionIcon) ? (OptionIcon@@ -591,7 +569,8 @@ function OperatorFilterPill({{truncate(optionLabel, 48)}</span><div className="ml-1 flex shrink-0 justify-end text-neutral-500">- {isAdvancedFilter || filter.multiple ? (+ {(isAdvancedFilter || filter.multiple) &&+ !filter.singleSelect ? (option.right) : isSelected ? (<Check className="h-4 w-4" />@@ -608,6 +587,7 @@ function OperatorFilterPill({{selectedOptions.map(renderOption)}{(isAdvancedFilter || filter.multiple) &&+ !filter.singleSelect &&selectedOptions.length > 0 &&unselectedOptions.length > 0 && (<Command.Separator className="-mx-1 my-1 border-b border-neutral-200" />diff --git a/packages/ui/src/filter/types.ts b/packages/ui/src/filter/types.tsindex a29a059fd3..2d09789133 100644--- a/packages/ui/src/filter/types.ts+++ b/packages/ui/src/filter/types.ts@@ -13,10 +13,11 @@ export type Filter = {key: string;icon: FilterIcon;label: string;+ labelPlural?: string; // Plural form of the label (optional, defaults to pluralize(label))options: FilterOption[] | null;- hideInFilterDropdown?: boolean;- shouldFilter?: boolean;- separatorAfter?: boolean;+ hideInFilterDropdown?: boolean; // Hide in Filter.Select dropdown+ shouldFilter?: boolean; // Disable filtering for this filter+ separatorAfter?: boolean; // Add a separator after the filter in Filter.Select dropdownmultiple?: boolean; // Allow multiple selection of valueshideMultipleIcons?: boolean; // Hide multiple "stacked icons" view for the filter (fallback to icon display)singleSelect?: boolean; // Force single-select behavior even if multiSelect is enabled globally