The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
fix & standardize schemas
Steven Tey3e9680bb99d6
diff --git a/apps/web/lib/analytics/get-events.ts b/apps/web/lib/analytics/get-events.tsindex 450c647f99..98cba78ce6 100644--- a/apps/web/lib/analytics/get-events.ts+++ b/apps/web/lib/analytics/get-events.ts@@ -3,17 +3,20 @@ import { tb } from "@/lib/tinybird";import { Link } from "@prisma/client";import { transformLink } from "../api/links";import { tbDemo } from "../tinybird/demo-client";-import { clickEventSchema } from "../webhook/schemas";-import {- transformClickEventData,- transformLeadEventData,- transformLinkEventData,- transformSaleEventData,-} from "../webhook/transform";import { eventsFilterTB } from "../zod/schemas/analytics";-import { clickEventEnrichedSchema } from "../zod/schemas/clicks";-import { leadEventEnrichedSchema } from "../zod/schemas/leads";-import { saleEventEnrichedSchema } from "../zod/schemas/sales";+import {+ clickEventEnrichedSchema,+ clickEventResponseSchema,+ clickEventSchema,+} from "../zod/schemas/clicks";+import {+ leadEventEnrichedSchema,+ leadEventResponseSchema,+} from "../zod/schemas/leads";+import {+ saleEventEnrichedSchema,+ saleEventResponseSchema,+} from "../zod/schemas/sales";import { INTERVAL_DATA } from "./constants";import { EventsFilters } from "./types";@@ -72,38 +75,39 @@ export const getEvents = async (params: EventsFilters) => {);const events = response.data- .map((event) => {- const link = linksMap[event.link_id];+ .map((evt) => {+ const link = linksMap[evt.link_id];if (!link) {return null;}const eventData = {- ...event,+ ...evt,// timestamp is always in UTC- timestamp: new Date(event.timestamp + "Z"),- link: transformLinkEventData(transformLink(link)),- ...(eventType === "leads" || eventType === "sales"+ timestamp: new Date(evt.timestamp + "Z"),+ click: clickEventSchema.parse({+ ...evt,+ id: evt.click_id,+ }),+ // transformLink -> add shortLink, qrCode, workspaceId, etc.+ link: transformLink(link),+ ...(evt.event === "lead" || evt.event === "sale"? {- click: clickEventSchema.parse({- ...event,- id: event.click_id,- }),+ eventId: evt.event_id,+ eventName: evt.event_name,customer: {- id: event.customer_id,- name: event.customer_name,- email: event.customer_email,+ name: evt.customer_name,+ email: evt.customer_email,avatar:- event.customer_avatar ||- `https://api.dicebear.com/7.x/micah/svg?seed=${event.customer_id}`,+ evt.customer_avatar ||+ `https://api.dicebear.com/7.x/micah/svg?seed=${evt.customer_email}`,},- ...(eventType === "sales"+ ...(evt.event === "sale"? {sale: {- amount: event.saleAmount,- invoiceId: event.invoice_id,- paymentProcessor: event.payment_processor,- metadata: event.metadata,+ amount: evt.saleAmount,+ invoiceId: evt.invoice_id,+ paymentProcessor: evt.payment_processor,},}: {}),@@ -111,12 +115,12 @@ export const getEvents = async (params: EventsFilters) => {: {}),};- if (event === "clicks") {- return transformClickEventData(eventData);- } else if (event === "leads") {- return transformLeadEventData(eventData);- } else if (event === "sales") {- return transformSaleEventData(eventData);+ if (evt.event === "click") {+ return clickEventResponseSchema.parse(eventData);+ } else if (evt.event === "lead") {+ return leadEventResponseSchema.parse(eventData);+ } else if (evt.event === "sale") {+ return saleEventResponseSchema.parse(eventData);}return eventData;diff --git a/apps/web/lib/webhook/schemas.ts b/apps/web/lib/webhook/schemas.tsindex 6db6903e63..768a700fd0 100644--- a/apps/web/lib/webhook/schemas.ts+++ b/apps/web/lib/webhook/schemas.ts@@ -1,10 +1,9 @@import z from "@/lib/zod";-import { LinkSchema } from "../zod/schemas/links";-import { parseUrlSchemaAllowEmpty } from "../zod/schemas/utils";+import { clickEventSchema } from "../zod/schemas/clicks";+import { linkEventSchema } from "../zod/schemas/links";import { WEBHOOK_TRIGGERS } from "./constants";const customerSchema = z.object({- id: z.string(),name: z.string().nullable(),email: z.string().nullable(),avatar: z.string().nullable(),@@ -14,61 +13,25 @@ const saleSchema = z.object({amount: z.number(),paymentProcessor: z.string(),invoiceId: z.string().nullable(),- currency: z.string(),-});--export const linkEventSchema = LinkSchema.omit({- url: true,- tags: true,- tagId: true,- projectId: true,- // boolean fields- archived: true,- doIndex: true,- proxy: true,- publicStats: true,- rewrite: true,- trackConversion: true,-}).merge(- z.object({- url: parseUrlSchemaAllowEmpty,- archived: z.coerce.boolean(),- doIndex: z.coerce.boolean(),- proxy: z.coerce.boolean(),- publicStats: z.coerce.boolean(),- rewrite: z.coerce.boolean(),- trackConversion: z.coerce.boolean(),- }),-);--export const clickEventSchema = z.object({- id: z.string(),- url: z.string(),- ip: z.string(),- continent: z.string(),- country: z.string(),- city: z.string(),- device: z.string(),- browser: z.string(),- os: z.string(),- bot: z.coerce.boolean(),- qr: z.coerce.boolean(),- referer: z.string(),});export const leadEventSchema = z.object({+ eventId: z.string(),eventName: z.string(),+ timestamp: z.date(),customer: customerSchema,click: clickEventSchema,link: linkEventSchema,});export const saleEventSchema = z.object({+ eventId: z.string(),eventName: z.string(),- customer: customerSchema,- sale: saleSchema,+ timestamp: z.date(),click: clickEventSchema,link: linkEventSchema,+ customer: customerSchema,+ sale: saleSchema,});// Schema of the payload sent to the webhook endpoint by Dubdiff --git a/apps/web/lib/webhook/transform.ts b/apps/web/lib/webhook/transform.tsindex ae74d5eee5..7ce8b36975 100644--- a/apps/web/lib/webhook/transform.ts+++ b/apps/web/lib/webhook/transform.ts@@ -1,12 +1,13 @@-import { linkEventSchema, webhookPayloadSchema } from "@/lib/webhook/schemas";+import { webhookPayloadSchema } from "@/lib/webhook/schemas";import { nanoid, toCamelCase } from "@dub/utils";import type { Link, Webhook } from "@prisma/client";import { LinkWithTags, transformLink } from "../api/links/utils/transform-link";import { WebhookTrigger } from "../types";import z from "../zod";-import { clickEventSchemaTB } from "../zod/schemas/clicks";+import { clickEventSchema, clickEventSchemaTB } from "../zod/schemas/clicks";+import { linkEventSchema } from "../zod/schemas/links";import { WEBHOOK_EVENT_ID_PREFIX } from "./constants";-import { clickEventSchema, leadEventSchema, saleEventSchema } from "./schemas";+import { leadEventSchema, saleEventSchema } from "./schemas";interface TransformWebhookPropsextends Pick<Webhook, "id" | "name" | "url" | "secret" | "triggers"> {diff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.tsindex 3e1fbd49d0..1a8e67320f 100644--- a/apps/web/lib/zod/schemas/analytics.ts+++ b/apps/web/lib/zod/schemas/analytics.ts@@ -208,18 +208,22 @@ export const eventsFilterTB = analyticsFilterTB);export const eventsQuerySchema = analyticsQuerySchema- .omit({ groupBy: true, interval: true })- .merge(- z.object({- interval: z- .enum(eventIntervals)- .default("24h")- .describe(- "The interval to retrieve events for. Takes precedence over start and end. If undefined, defaults to 24h.",- ),- page: z.coerce.number().default(0),- limit: z.coerce.number().default(PAGINATION_LIMIT),- order: z.enum(["asc", "desc"]).default("desc"),- sortBy: z.enum(["timestamp"]).default("timestamp"),- }),- );+ .omit({ groupBy: true })+ .extend({+ event: z+ .enum(EVENT_TYPES)+ .default("clicks")+ .describe(+ "The type of event to retrieve analytics for. Defaults to 'clicks'.",+ ),+ interval: z+ .enum(eventIntervals)+ .default("24h")+ .describe(+ "The interval to retrieve events for. Takes precedence over start and end. If undefined, defaults to 24h.",+ ),+ page: z.coerce.number().default(0),+ limit: z.coerce.number().default(PAGINATION_LIMIT),+ order: z.enum(["asc", "desc"]).default("desc"),+ sortBy: z.enum(["timestamp"]).default("timestamp"),+ });diff --git a/apps/web/lib/zod/schemas/clicks.ts b/apps/web/lib/zod/schemas/clicks.tsindex 6b870df9dc..563f945e56 100644--- a/apps/web/lib/zod/schemas/clicks.ts+++ b/apps/web/lib/zod/schemas/clicks.ts@@ -1,5 +1,6 @@import z from "@/lib/zod";-import { LinkSchema } from "./links";+import { commonDeprecatedEventFields } from "./deprecated";+import { linkEventSchema } from "./links";export const clickEventSchemaTB = z.object({timestamp: z.string(),@@ -49,28 +50,26 @@ export const clickEventEnrichedSchema = z.object({qr: z.number().nullable(),});+export const clickEventSchema = z.object({+ id: z.string(),+ url: z.string(),+ continent: z.string(),+ country: z.string(),+ city: z.string(),+ device: z.string(),+ browser: z.string(),+ os: z.string(),+ referer: z.string(),+ qr: z.coerce.boolean(),+ ip: z.string(),+});+export const clickEventResponseSchema = z.object({event: z.literal("click"),- timestamp: z.string(),- click_id: z.string(),- link_id: z- .string()- .describe("Deprecated. Use `link.id` instead.")- .openapi({ deprecated: true }),- domain: z.string(),- key: z.string(),- url: z.string(),- continent: z.string(),- country: z.string(),- city: z.string(),- device: z.string(),- browser: z.string(),- os: z.string(),- referer: z.string(),- ip: z.string(),- bot: z.coerce.boolean(),- qr: z.coerce.boolean(),- link: LinkSchema,+ timestamp: z.coerce.string(),+ click: clickEventSchema,+ link: linkEventSchema,})+ .merge(commonDeprecatedEventFields).openapi({ ref: "ClickEvent" });diff --git a/apps/web/lib/zod/schemas/deprecated.ts b/apps/web/lib/zod/schemas/deprecated.tsnew file mode 100644index 0000000000..da2de84edb--- /dev/null+++ b/apps/web/lib/zod/schemas/deprecated.ts@@ -0,0 +1,21 @@+import z from "@/lib/zod";++export const commonDeprecatedEventFields = z.object({+ click_id: z.string(),+ link_id: z+ .string()+ .describe("Deprecated. Use `link.id` instead.")+ .openapi({ deprecated: true }),+ domain: z.string().describe("Deprecated. Use `link.domain` instead."),+ key: z.string().describe("Deprecated. Use `link.key` instead."),+ url: z.string().describe("Deprecated. Use `click.url` instead."),+ continent: z.string().describe("Deprecated. Use `click.continent` instead."),+ country: z.string().describe("Deprecated. Use `click.country` instead."),+ city: z.string().describe("Deprecated. Use `click.city` instead."),+ device: z.string().describe("Deprecated. Use `click.device` instead."),+ browser: z.string().describe("Deprecated. Use `click.browser` instead."),+ os: z.string().describe("Deprecated. Use `click.os` instead."),+ referer: z.string().describe("Deprecated. Use `click.referer` instead."),+ qr: z.number().describe("Deprecated. Use `click.qr` instead."),+ ip: z.string().describe("Deprecated. Use `click.ip` instead."),+});diff --git a/apps/web/lib/zod/schemas/leads.ts b/apps/web/lib/zod/schemas/leads.tsindex 4b8e421615..f2e42d23a4 100644--- a/apps/web/lib/zod/schemas/leads.ts+++ b/apps/web/lib/zod/schemas/leads.ts@@ -1,8 +1,7 @@-import { clickEventSchema } from "@/lib/webhook/schemas";import z from "@/lib/zod";-import { clickEventSchemaTB } from "./clicks";+import { clickEventSchema, clickEventSchemaTB } from "./clicks";import { customerSchema } from "./customers";-import { LinkSchema } from "./links";+import { linkEventSchema } from "./links";export const trackLeadRequestSchema = z.object({// Required@@ -106,10 +105,12 @@ export const leadEventEnrichedSchema = z.object({export const leadEventResponseSchema = z.object({event: z.literal("lead"),- timestamp: z.string(),- event_id: z.string(),- event_name: z.string(),+ timestamp: z.coerce.string(),+ eventId: z.string(),+ eventName: z.string(),// deprecated fields+ event_id: z.string().describe("Deprecated. Use `eventId` instead."),+ event_name: z.string().describe("Deprecated. Use `eventName` instead."),link_id: z.string().describe("Deprecated. Use `link.id` instead.")@@ -132,19 +133,21 @@ export const leadEventResponseSchema = z.openapi({ deprecated: true }),domain: z.string().describe("Deprecated. Use `link.domain` instead."),key: z.string().describe("Deprecated. Use `link.key` instead."),- url: z.string().describe("Deprecated. Use `link.url` instead."),- continent: z.string().describe("Deprecated. Use `link.continent` instead."),- country: z.string().describe("Deprecated. Use `link.country` instead."),- city: z.string().describe("Deprecated. Use `link.city` instead."),- device: z.string().describe("Deprecated. Use `link.device` instead."),- browser: z.string().describe("Deprecated. Use `link.browser` instead."),- os: z.string().describe("Deprecated. Use `link.os` instead."),- referer: z.string().describe("Deprecated. Use `link.referer` instead."),- qr: z.number().describe("Deprecated. Use `link.qr` instead."),- ip: z.string().describe("Deprecated. Use `link.ip` instead."),+ url: z.string().describe("Deprecated. Use `click.url` instead."),+ continent: z+ .string()+ .describe("Deprecated. Use `click.continent` instead."),+ country: z.string().describe("Deprecated. Use `click.country` instead."),+ city: z.string().describe("Deprecated. Use `click.city` instead."),+ device: z.string().describe("Deprecated. Use `click.device` instead."),+ browser: z.string().describe("Deprecated. Use `click.browser` instead."),+ os: z.string().describe("Deprecated. Use `click.os` instead."),+ referer: z.string().describe("Deprecated. Use `click.referer` instead."),+ qr: z.number().describe("Deprecated. Use `click.qr` instead."),+ ip: z.string().describe("Deprecated. Use `click.ip` instead."),// nested objectsclick: clickEventSchema,- link: LinkSchema,+ link: linkEventSchema,customer: customerSchema,}).openapi({ ref: "LeadEvent" });diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.tsindex 20533423a5..e3022cc998 100644--- a/apps/web/lib/zod/schemas/links.ts+++ b/apps/web/lib/zod/schemas/links.ts@@ -549,3 +549,20 @@ export const getLinksQuerySchemaExtended = getLinksQuerySchema.merge(includeUser: booleanQuerySchema.default("false"),}),);++export const linkEventSchema = LinkSchema.extend({+ // coerce url field+ url: parseUrlSchemaAllowEmpty,+ // coerce boolean fields+ archived: z.coerce.boolean(),+ doIndex: z.coerce.boolean(),+ proxy: z.coerce.boolean(),+ publicStats: z.coerce.boolean(),+ rewrite: z.coerce.boolean(),+ trackConversion: z.coerce.boolean(),+ // coerce date fields+ createdAt: z.coerce.date(),+ updatedAt: z.coerce.date(),+ lastClicked: z.coerce.date(),+ expiresAt: z.coerce.date(),+});diff --git a/apps/web/lib/zod/schemas/sales.ts b/apps/web/lib/zod/schemas/sales.tsindex 59282bcf65..a316fc8e76 100644--- a/apps/web/lib/zod/schemas/sales.ts+++ b/apps/web/lib/zod/schemas/sales.ts@@ -1,8 +1,8 @@-import { clickEventSchema } from "@/lib/webhook/schemas";import z from "@/lib/zod";-import { clickEventSchemaTB } from "./clicks";+import { clickEventSchema, clickEventSchemaTB } from "./clicks";import { customerSchema } from "./customers";-import { LinkSchema } from "./links";+import { commonDeprecatedEventFields } from "./deprecated";+import { linkEventSchema } from "./links";export const trackSaleRequestSchema = z.object({// Required@@ -112,18 +112,12 @@ export const saleEventEnrichedSchema = z.object({export const saleEventResponseSchema = z.object({event: z.literal("sale"),- timestamp: z.string(),- event_id: z.string(),- event_name: z.string(),+ timestamp: z.coerce.string(),+ eventId: z.string(),+ eventName: z.string(),// deprecated fields- link_id: z- .string()- .describe("Deprecated. Use `link.id` instead.")- .openapi({ deprecated: true }),- click_id: z- .string()- .describe("Deprecated. Use `click.id` instead.")- .openapi({ deprecated: true }),+ event_id: z.string().describe("Deprecated. Use `eventId` instead."),+ event_name: z.string().describe("Deprecated. Use `eventName` instead."),customer_name: z.string().describe("Deprecated. Use `customer.name` instead.")@@ -147,60 +141,8 @@ export const saleEventResponseSchema = zpayment_processor: z.string().describe("Deprecated. Use `sale.paymentProcessor` instead."),- metadata: z- .string()- .describe("Deprecated. Use `sale.metadata` instead.")- .openapi({ deprecated: true }),- domain: z- .string()- .describe("Deprecated. Use `link.domain` instead.")- .openapi({ deprecated: true }),- key: z- .string()- .describe("Deprecated. Use `link.key` instead.")- .openapi({ deprecated: true }),- url: z- .string()- .describe("Deprecated. Use `link.url` instead.")- .openapi({ deprecated: true }),- continent: z- .string()- .describe("Deprecated. Use `link.continent` instead.")- .openapi({ deprecated: true }),- country: z- .string()- .describe("Deprecated. Use `link.country` instead.")- .openapi({ deprecated: true }),- city: z- .string()- .describe("Deprecated. Use `link.city` instead.")- .openapi({ deprecated: true }),- device: z- .string()- .describe("Deprecated. Use `link.device` instead.")- .openapi({ deprecated: true }),- browser: z- .string()- .describe("Deprecated. Use `link.browser` instead.")- .openapi({ deprecated: true }),- os: z- .string()- .describe("Deprecated. Use `link.os` instead.")- .openapi({ deprecated: true }),- referer: z- .string()- .describe("Deprecated. Use `link.referer` instead.")- .openapi({ deprecated: true }),- qr: z- .number()- .describe("Deprecated. Use `link.qr` instead.")- .openapi({ deprecated: true }),- ip: z- .string()- .describe("Deprecated. Use `link.ip` instead.")- .openapi({ deprecated: true }),// nested objects- link: LinkSchema,+ link: linkEventSchema,click: clickEventSchema,customer: customerSchema,sale: trackSaleRequestSchema.pick({@@ -209,4 +151,5 @@ export const saleEventResponseSchema = zpaymentProcessor: true,}),})+ .merge(commonDeprecatedEventFields).openapi({ ref: "SaleEvent" });diff --git a/apps/web/ui/analytics/events/events-table.tsx b/apps/web/ui/analytics/events/events-table.tsxindex 07f7648a09..2d2e691116 100644--- a/apps/web/ui/analytics/events/events-table.tsx+++ b/apps/web/ui/analytics/events/events-table.tsx@@ -126,7 +126,7 @@ export default function EventsTable() {{id: "event",header: "Event",- accessorKey: "event_name",+ accessorKey: "eventName",enableHiding: false,cell: ({ getValue }) =>(@@ -204,7 +204,7 @@ export default function EventsTable() {{id: "continent",header: "Continent",- accessorKey: "continent",+ accessorKey: "click.continent",meta: {filterParams: ({ getValue }) => ({ continent: getValue() }),},@@ -223,7 +223,7 @@ export default function EventsTable() {{id: "country",header: "Country",- accessorKey: "country",+ accessorKey: "click.country",meta: {filterParams: ({ getValue }) => ({ country: getValue() }),},@@ -250,7 +250,7 @@ export default function EventsTable() {{id: "city",header: "City",- accessorKey: "city",+ accessorKey: "click.city",minSize: 160,cell: ({ getValue, row }) => (<div className="flex items-center gap-3" title={getValue()}>@@ -270,7 +270,7 @@ export default function EventsTable() {{id: "device",header: "Device",- accessorKey: "device",+ accessorKey: "click.device",meta: {filterParams: ({ getValue }) => ({ device: getValue() }),},@@ -288,7 +288,7 @@ export default function EventsTable() {{id: "browser",header: "Browser",- accessorKey: "browser",+ accessorKey: "click.browser",cell: ({ getValue }) => (<div className="flex items-center gap-3" title={getValue()}><DeviceIcon@@ -303,7 +303,7 @@ export default function EventsTable() {{id: "os",header: "OS",- accessorKey: "os",+ accessorKey: "click.os",cell: ({ getValue }) => (<div className="flex items-center gap-3" title={getValue()}><DeviceIcon@@ -318,7 +318,7 @@ export default function EventsTable() {{id: "referer",header: "Referer",- accessorKey: "referer",+ accessorKey: "click.referer",cell: ({ getValue }) => (<div className="flex items-center gap-3" title={getValue()}>{getValue() === "(direct)" ? (@@ -336,7 +336,7 @@ export default function EventsTable() {{id: "ip",header: "IP Address",- accessorKey: "ip",+ accessorKey: "click.ip",cell: ({ getValue }) =>getValue() ? (<span className="truncate" title={getValue()}>@@ -354,12 +354,12 @@ export default function EventsTable() {{id: "saleAmount",header: "Sale Amount",- accessorKey: "sale",+ accessorKey: "sale.amount",enableHiding: false,minSize: 120,cell: ({ getValue }) => (<div className="flex items-center gap-2">- <span>${nFormatter(getValue().amount / 100)}</span>+ <span>${nFormatter(getValue() / 100)}</span><span className="text-gray-400">USD</span></div>),@@ -368,7 +368,7 @@ export default function EventsTable() {{id: "timestamp",header: "Date",- accessorFn: (d) => new Date(d.timestamp),+ accessorFn: (d: { timestamp: string }) => new Date(d.timestamp),enableHiding: false,minSize: 100,cell: ({ getValue }) => (