Skip to content

armgit / dub

Public Imported from GitHub
0

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

Add webhook scope for link.clicked with folder support

Kiran Kc9ec098716b9
diff --git a/apps/web/app/api/webhooks/[webhookId]/folders/route.ts b/apps/web/app/api/webhooks/[webhookId]/folders/route.ts
new file mode 100644
index 0000000000..fdeded846c
--- /dev/null
+++ b/apps/web/app/api/webhooks/[webhookId]/folders/route.ts
@@ -0,0 +1,30 @@
+import { withWorkspace } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
+import { NextResponse } from "next/server";
+
+// GET /api/webhooks/[webhookId]/folders
+export const GET = withWorkspace(async ({ workspace, params }) => {
+ const { webhookId } = params;
+
+ const webhook = await prisma.webhook.findUniqueOrThrow({
+ where: {
+ id: webhookId,
+ projectId: workspace.id,
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ const folders = await prisma.folderWebhook.findMany({
+ where: {
+ webhookId: webhook.id,
+ },
+ select: {
+ folderId: true,
+ },
+ take: 100, // TODO: Enforce this limit other places too
+ });
+
+ return NextResponse.json(folders.map(({ folderId }) => folderId));
+});
diff --git a/apps/web/app/api/webhooks/[webhookId]/route.ts b/apps/web/app/api/webhooks/[webhookId]/route.ts
index 073e6bb6d2..71fc65ba9b 100644
--- a/apps/web/app/api/webhooks/[webhookId]/route.ts
+++ b/apps/web/app/api/webhooks/[webhookId]/route.ts
@@ -1,13 +1,12 @@
import { DubApiError } from "@/lib/api/errors";
-import { linkCache } from "@/lib/api/links/cache";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
-import { webhookCache } from "@/lib/webhook/cache";
-import { toggleWebhooksForWorkspace } from "@/lib/webhook/update-webhook";
-import { isLinkLevelWebhook } from "@/lib/webhook/utils";
+import { LINK_CLICK_WEBHOOK_TRIGGER } from "@/lib/webhook/constants";
+import { syncWorkspaceWebhookStatus } from "@/lib/webhook/update-webhook";
import { validateWebhook } from "@/lib/webhook/validate-webhook";
import { updateWebhookSchema, WebhookSchema } from "@/lib/zod/schemas/webhooks";
+import { arrayEqual } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
@@ -21,15 +20,6 @@ export const GET = withWorkspace(
id: webhookId,
projectId: workspace.id,
},
- select: {
- id: true,
- name: true,
- url: true,
- secret: true,
- triggers: true,
- disabledAt: true,
- installationId: true,
- },
});
return NextResponse.json(WebhookSchema.parse(webhook));
@@ -59,9 +49,13 @@ export const PATCH = withWorkspace(
id: webhookId,
projectId: workspace.id,
},
+ include: {
+ links: true,
+ folders: true,
+ },
});
- const { name, url, triggers, linkIds } = input;
+ const { name, url, triggers, scope, linkIds, folderIds } = input;
// If the webhook is managed by an integration, only the linkIds & triggers can be updated manually.
if (existingWebhook.installationId && (name || url)) {
@@ -79,115 +73,79 @@ export const PATCH = withWorkspace(
user: session.user,
});
- const oldLinks = await prisma.linkWebhook.findMany({
- where: {
- webhookId,
- },
- select: {
- linkId: true,
- },
- });
+ const hasLinkClicked =
+ triggers?.includes(LINK_CLICK_WEBHOOK_TRIGGER) ?? false;
+ const newScope = hasLinkClicked ? scope ?? null : null;
+ const existingLinkIds = existingWebhook.links.map((link) => link.linkId);
+ const existingFolderIds = existingWebhook.folders.map(
+ (folder) => folder.folderId,
+ );
- const webhook = await prisma.webhook.update({
- where: {
- id: webhookId,
- projectId: workspace.id,
- },
- data: {
- ...(name && { name }),
- ...(url && { url }),
- ...(triggers && { triggers }),
- ...(linkIds && {
- links: {
- deleteMany: {},
- create: linkIds.map((linkId) => ({
- linkId,
- })),
- },
- }),
- },
- select: {
- id: true,
- name: true,
- url: true,
- secret: true,
- triggers: true,
- disabledAt: true,
- installationId: true,
- links: {
- select: {
- linkId: true,
- },
+ const scopeChanged =
+ (triggers !== undefined || scope !== undefined) &&
+ newScope !== existingWebhook.scope;
+
+ const shouldSyncLinks =
+ (newScope !== "links" && existingLinkIds.length > 0) ||
+ (newScope === "links" &&
+ linkIds !== undefined &&
+ !arrayEqual(existingLinkIds, linkIds ?? []));
+
+ const shouldSyncFolders =
+ (newScope !== "folders" && existingFolderIds.length > 0) ||
+ (newScope === "folders" &&
+ folderIds !== undefined &&
+ !arrayEqual(existingFolderIds, folderIds ?? []));
+
+ const webhook = await prisma.$transaction(async (tx) => {
+ const updatedWebhook = await tx.webhook.update({
+ where: {
+ id: webhookId,
},
- },
- });
+ data: {
+ ...(name !== undefined && { name }),
+ ...(url !== undefined && { url }),
+ ...(triggers !== undefined && { triggers }),
+ ...(scopeChanged && { scope: newScope }),
+ },
+ });
- waitUntil(
- (async () => {
- // If the webhook is being changed from link level to workspace level, delete the cache
- if (
- isLinkLevelWebhook(existingWebhook) &&
- !isLinkLevelWebhook(webhook)
- ) {
- await webhookCache.delete(webhookId);
+ if (shouldSyncLinks) {
+ await tx.linkWebhook.deleteMany({
+ where: {
+ webhookId: webhookId,
+ },
+ });
- const links = await prisma.link.findMany({
- where: {
- id: { in: oldLinks.map(({ linkId }) => linkId) },
- },
- include: {
- webhooks: {
- select: {
- webhookId: true,
- },
- },
- },
+ if (newScope === "links" && linkIds?.length) {
+ await tx.linkWebhook.createMany({
+ data: linkIds.map((linkId) => ({
+ linkId,
+ webhookId,
+ })),
});
-
- await linkCache.mset(links);
}
+ }
- // If the webhook is being changed from workspace level to link level, set the cache
- else if (isLinkLevelWebhook(webhook)) {
- await webhookCache.set(webhook);
- }
-
- const newLinkIds = webhook.links.map(({ linkId }) => linkId);
- const oldLinkIds = oldLinks.map(({ linkId }) => linkId);
-
- if (!newLinkIds.length && !oldLinkIds.length) {
- return;
- }
-
- const linksAdded = newLinkIds.filter(
- (linkId) => !oldLinkIds.includes(linkId),
- );
-
- const linksRemoved = oldLinkIds.filter(
- (linkId) => !newLinkIds.includes(linkId),
- );
-
- // No changes in the links
- if (!linksAdded.length && !linksRemoved.length) {
- return;
- }
-
- const links = await prisma.link.findMany({
+ if (shouldSyncFolders) {
+ await tx.folderWebhook.deleteMany({
where: {
- id: { in: [...linksAdded, ...linksRemoved] },
- },
- include: {
- webhooks: {
- select: {
- webhookId: true,
- },
- },
+ webhookId,
},
});
- await linkCache.mset(links);
- })(),
- );
+ if (newScope === "folders" && folderIds?.length) {
+ await tx.folderWebhook.createMany({
+ data: folderIds.map((folderId) => ({
+ folderId,
+ webhookId,
+ })),
+ });
+ }
+ }
+
+ return updatedWebhook;
+ });
return NextResponse.json(WebhookSchema.parse(webhook));
},
@@ -216,15 +174,6 @@ export const DELETE = withWorkspace(
},
});
- const linkWebhooks = await prisma.linkWebhook.findMany({
- where: {
- webhookId,
- },
- select: {
- linkId: true,
- },
- });
-
await prisma.webhook.delete({
where: {
id: webhookId,
@@ -232,28 +181,9 @@ export const DELETE = withWorkspace(
});
waitUntil(
- (async () => {
- const links = await prisma.link.findMany({
- where: {
- id: { in: linkWebhooks.map(({ linkId }) => linkId) },
- },
- include: {
- webhooks: {
- select: {
- webhookId: true,
- },
- },
- },
- });
-
- await Promise.all([
- toggleWebhooksForWorkspace({
- workspaceId: workspace.id,
- }),
- linkCache.mset(links),
- webhookCache.delete(webhookId),
- ]);
- })(),
+ syncWorkspaceWebhookStatus({
+ workspaceId: workspace.id,
+ }),
);
return NextResponse.json({
diff --git a/apps/web/app/api/webhooks/route.ts b/apps/web/app/api/webhooks/route.ts
index 46ef43e8b1..8836a467b5 100644
--- a/apps/web/app/api/webhooks/route.ts
+++ b/apps/web/app/api/webhooks/route.ts
@@ -1,16 +1,10 @@
import { DubApiError } from "@/lib/api/errors";
-import { linkCache } from "@/lib/api/links/cache";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
-import { webhookCache } from "@/lib/webhook/cache";
import { createWebhook } from "@/lib/webhook/create-webhook";
import { getWebhooks } from "@/lib/webhook/get-webhooks";
-import { toggleWebhooksForWorkspace } from "@/lib/webhook/update-webhook";
-import {
- identifyWebhookReceiver,
- isLinkLevelWebhook,
-} from "@/lib/webhook/utils";
+import { identifyWebhookReceiver } from "@/lib/webhook/utils";
import { validateWebhook } from "@/lib/webhook/validate-webhook";
import { createWebhookSchema, WebhookSchema } from "@/lib/zod/schemas/webhooks";
import { sendEmail } from "@dub/email";
@@ -55,7 +49,7 @@ export const POST = withWorkspace(
user: session.user,
});
- const { name, url, triggers, linkIds, secret } = input;
+ const { name, url, triggers, scope, linkIds, folderIds } = input;
// Zapier use this endpoint to create webhooks from their app
const isZapierWebhook =
@@ -78,8 +72,9 @@ export const POST = withWorkspace(
url,
receiver: isZapierWebhook ? WebhookReceiver.zapier : WebhookReceiver.user,
triggers,
+ scope,
linkIds,
- secret,
+ folderIds,
workspace,
installationId: zapierInstallation ? zapierInstallation.id : undefined,
});
@@ -92,44 +87,20 @@ export const POST = withWorkspace(
}
waitUntil(
- (async () => {
- const links = await prisma.link.findMany({
- where: {
- id: { in: linkIds },
- projectId: workspace.id,
+ sendEmail({
+ to: session.user.email,
+ subject: "New webhook added",
+ react: WebhookAdded({
+ email: session.user.email,
+ workspace: {
+ name: workspace.name,
+ slug: workspace.slug,
},
- include: {
- webhooks: {
- select: {
- webhookId: true,
- },
- },
+ webhook: {
+ name,
},
- });
-
- await Promise.allSettled([
- toggleWebhooksForWorkspace({
- workspaceId: workspace.id,
- }),
- sendEmail({
- to: session.user.email,
- subject: "New webhook added",
- react: WebhookAdded({
- email: session.user.email,
- workspace: {
- name: workspace.name,
- slug: workspace.slug,
- },
- webhook: {
- name,
- },
- }),
- }),
- ...(links && links.length > 0 ? [linkCache.mset(links), []] : []),
-
- ...(isLinkLevelWebhook(webhook) ? [webhookCache.set(webhook)] : []),
- ]);
- })(),
+ }),
+ }),
);
return NextResponse.json(WebhookSchema.parse(webhook), { status: 201 });
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/webhooks/new/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/webhooks/new/page-client.tsx
index 0beedb8dc1..6adb3c3cdb 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/webhooks/new/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/webhooks/new/page-client.tsx
@@ -4,11 +4,7 @@ import useWorkspace from "@/lib/swr/use-workspace";
import AddEditWebhookForm from "@/ui/webhooks/add-edit-webhook-form";
import { redirect } from "next/navigation";
-export default function NewWebhookPageClient({
- newSecret,
-}: {
- newSecret: string;
-}) {
+export default function NewWebhookPageClient() {
const { slug, plan } = useWorkspace();
const needsHigherPlan = plan === "free" || plan === "pro";
@@ -17,5 +13,5 @@ export default function NewWebhookPageClient({
redirect(`/${slug}/settings/webhooks`);
}
- return <AddEditWebhookForm webhook={null} newSecret={newSecret} />;
+ return <AddEditWebhookForm webhook={null} />;
}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/webhooks/new/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/webhooks/new/page.tsx
index 036256a5b8..cc93d00cad 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/webhooks/new/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/webhooks/new/page.tsx
@@ -1,6 +1,5 @@
-import { createWebhookSecret } from "@/lib/webhook/secret";
import NewWebhookPageClient from "./page-client";
export default async function NewWebhookPage() {
- return <NewWebhookPageClient newSecret={createWebhookSecret()} />;
+ return <NewWebhookPageClient />;
}
diff --git a/apps/web/lib/actions/enable-disable-webhook.ts b/apps/web/lib/actions/enable-disable-webhook.ts
index 858c4dbff6..badcea32f9 100644
--- a/apps/web/lib/actions/enable-disable-webhook.ts
+++ b/apps/web/lib/actions/enable-disable-webhook.ts
@@ -4,7 +4,7 @@ import { prisma } from "@/lib/prisma";
import { waitUntil } from "@vercel/functions";
import * as z from "zod/v4";
import { webhookCache } from "../webhook/cache";
-import { toggleWebhooksForWorkspace } from "../webhook/update-webhook";
+import { syncWorkspaceWebhookStatus } from "../webhook/update-webhook";
import { authActionClient } from "./safe-action";
import { throwIfNoPermission } from "./throw-if-no-permission";
@@ -54,7 +54,7 @@ export const enableOrDisableWebhook = authActionClient
waitUntil(
(async () => {
await Promise.all([
- toggleWebhooksForWorkspace({
+ syncWorkspaceWebhookStatus({
workspaceId: workspace.id,
}),
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 1d22a6f4d0..5e7eba47b8 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -61,7 +61,6 @@ import {
import { MessageAttachmentSchema, MessageSchema } from "./messages/schemas";
import { POSTBACK_TRIGGERS } from "./postback/constants";
import { postbackEventInputSchemaTB, postbackSchema } from "./postback/schemas";
-import { WEBHOOK_TRIGGER_DESCRIPTIONS } from "./webhook/constants";
import {
activityLogActionSchema,
activityLogResourceTypeSchema,
@@ -469,8 +468,6 @@ export type InstalledIntegrationInfoProps = Pick<
webhookId?: string; // Only if the webhook is managed by an integration
};
-export type WebhookTrigger = keyof typeof WEBHOOK_TRIGGER_DESCRIPTIONS;
-
export type WebhookProps = z.infer<typeof WebhookSchema>;
export type NewWebhook = z.infer<typeof createWebhookSchema>;
diff --git a/apps/web/lib/webhook/constants.ts b/apps/web/lib/webhook/constants.ts
index ac1216d86a..c1f55f846c 100644
--- a/apps/web/lib/webhook/constants.ts
+++ b/apps/web/lib/webhook/constants.ts
@@ -1,3 +1,5 @@
+import { WebhookScope } from "@prisma/client";
+
export const WEBHOOK_SECRET_LENGTH = 16;
export const WEBHOOK_ID_PREFIX = "wh_";
@@ -23,18 +25,48 @@ export const PROGRAM_LEVEL_WEBHOOK_TRIGGERS = [
"payout.confirmed",
] as const;
+export const LINK_CLICK_WEBHOOK_TRIGGER = "link.clicked" as const;
+
export const LINK_LEVEL_WEBHOOK_TRIGGERS = ["link.clicked"] as const;
+export const WEBHOOK_SCOPE_DESCRIPTIONS: Record<WebhookScope, string> = {
+ all: "All links",
+ folders: "Specific folders",
+ links: "Specific links",
+} as const;
+
+export const WEBHOOK_SCOPE_OPTIONS = [
+ {
+ value: "all",
+ label: "All links",
+ description: "Trigger webhooks for all links in your workspace",
+ },
+ {
+ value: "folders",
+ label: "Include all links in a folder",
+ description: "Trigger webhooks for all links from a selected folder",
+ },
+ {
+ value: "links",
+ label: "Include specific links",
+ description:
+ "Trigger webhooks for the links you explicitly select (linkIds)",
+ },
+] as const satisfies ReadonlyArray<{
+ value: WebhookScope;
+ label: string;
+ description: string;
+}>;
+
export const WEBHOOK_TRIGGERS = [
...WORKSPACE_LEVEL_WEBHOOK_TRIGGERS,
...PROGRAM_LEVEL_WEBHOOK_TRIGGERS,
...LINK_LEVEL_WEBHOOK_TRIGGERS,
] as const;
-export const WEBHOOK_TRIGGER_DESCRIPTIONS: Record<
- (typeof WEBHOOK_TRIGGERS)[number],
- string
-> = {
+export type WebhookTrigger = (typeof WEBHOOK_TRIGGERS)[number];
+
+export const WEBHOOK_TRIGGER_DESCRIPTIONS: Record<WebhookTrigger, string> = {
"link.created": "Link created",
"link.updated": "Link updated",
"link.deleted": "Link deleted",
diff --git a/apps/web/lib/webhook/create-webhook.ts b/apps/web/lib/webhook/create-webhook.ts
index 633db7823b..c77d877992 100644
--- a/apps/web/lib/webhook/create-webhook.ts
+++ b/apps/web/lib/webhook/create-webhook.ts
@@ -1,9 +1,6 @@
import { createId } from "@/lib/api/create-id";
-import { linkCache } from "@/lib/api/links/cache";
import { prisma } from "@/lib/prisma";
-import { webhookCache } from "@/lib/webhook/cache";
import { WEBHOOK_ID_PREFIX } from "@/lib/webhook/constants";
-import { isLinkLevelWebhook } from "@/lib/webhook/utils";
import { Project, WebhookReceiver } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import * as z from "zod/v4";
@@ -15,7 +12,9 @@ export async function createWebhook({
url,
secret,
triggers,
+ scope,
linkIds,
+ folderIds,
workspace,
receiver,
installationId,
@@ -23,6 +22,7 @@ export async function createWebhook({
workspace: Pick<Project, "id" | "plan">;
receiver: WebhookReceiver;
installationId?: string;
+ secret?: string;
}) {
// Webhooks are only supported on Business plans and above
if (["free", "pro"].includes(workspace.plan)) {
@@ -39,27 +39,28 @@ export async function createWebhook({
installationId,
projectId: workspace.id,
secret: secret || createWebhookSecret(),
- links: {
- ...(linkIds &&
- linkIds.length > 0 && {
- create: linkIds.map((linkId) => ({
- linkId,
- })),
- }),
- },
- },
- select: {
- id: true,
- name: true,
- url: true,
- secret: true,
- triggers: true,
- links: true,
- disabledAt: true,
- installationId: true,
+ scope,
},
});
+ if (scope === "links" && linkIds && linkIds.length > 0) {
+ await prisma.linkWebhook.createMany({
+ data: linkIds.map((linkId) => ({
+ linkId,
+ webhookId: webhook.id,
+ })),
+ });
+ }
+
+ if (scope === "folders" && folderIds && folderIds.length > 0) {
+ await prisma.folderWebhook.createMany({
+ data: folderIds.map((folderId) => ({
+ folderId,
+ webhookId: webhook.id,
+ })),
+ });
+ }
+
await prisma.project.update({
where: {
id: workspace.id,
@@ -71,34 +72,7 @@ export async function createWebhook({
waitUntil(
(async () => {
- const links = await prisma.link.findMany({
- where: {
- id: { in: linkIds },
- projectId: workspace.id,
- },
- include: {
- webhooks: {
- select: {
- webhookId: true,
- },
- },
- },
- });
-
- const formatedLinks = links.map((link) => {
- return {
- ...link,
- webhookIds: link.webhooks.map((webhook) => webhook.webhookId),
- };
- });
-
- Promise.all([
- ...(links && links.length > 0
- ? [linkCache.mset(formatedLinks), []]
- : []),
-
- ...(isLinkLevelWebhook(webhook) ? [webhookCache.set(webhook)] : []),
- ]);
+ //
})(),
);
diff --git a/apps/web/lib/webhook/failure.ts b/apps/web/lib/webhook/failure.ts
index 6fd2b825d6..a653c8d4c9 100644
--- a/apps/web/lib/webhook/failure.ts
+++ b/apps/web/lib/webhook/failure.ts
@@ -8,7 +8,7 @@ import {
WEBHOOK_FAILURE_DISABLE_THRESHOLD,
WEBHOOK_FAILURE_NOTIFY_THRESHOLDS,
} from "./constants";
-import { toggleWebhooksForWorkspace } from "./update-webhook";
+import { syncWorkspaceWebhookStatus } from "./update-webhook";
export const handleWebhookFailure = async (webhookId: string) => {
const webhook = await prisma.webhook.update({
@@ -61,7 +61,7 @@ export const handleWebhookFailure = async (webhookId: string) => {
webhookCache.set(updatedWebhook),
// Update the project webhookEnabled flag
- toggleWebhooksForWorkspace({
+ syncWorkspaceWebhookStatus({
workspaceId: webhook.projectId,
}),
]);
diff --git a/apps/web/lib/webhook/get-webhooks.ts b/apps/web/lib/webhook/get-webhooks.ts
index 79ba46c591..50bbb8bd20 100644
--- a/apps/web/lib/webhook/get-webhooks.ts
+++ b/apps/web/lib/webhook/get-webhooks.ts
@@ -31,6 +31,7 @@ export async function getWebhooks({
url: true,
secret: true,
triggers: true,
+ scope: true,
disabledAt: true,
receiver: true,
installationId: true,
diff --git a/apps/web/lib/webhook/update-webhook.ts b/apps/web/lib/webhook/update-webhook.ts
index 04bce1c353..a3dc5a80d5 100644
--- a/apps/web/lib/webhook/update-webhook.ts
+++ b/apps/web/lib/webhook/update-webhook.ts
@@ -1,8 +1,8 @@
import { prisma } from "@/lib/prisma";
import { webhookCache } from "./cache";
-// Based on the webhook count, we toggle the webhook status for the workspace
-export const toggleWebhooksForWorkspace = async ({
+// Synchronize the workspace's webhook status with its active webhooks.
+export const syncWorkspaceWebhookStatus = async ({
workspaceId,
}: {
workspaceId: string;
@@ -43,6 +43,7 @@ export const propagateWebhookTriggerChanges = async ({
select: {
id: true,
triggers: true,
+ linkScope: true,
url: true,
secret: true,
disabledAt: true,
@@ -54,29 +55,29 @@ export const propagateWebhookTriggerChanges = async ({
},
});
- // Make the webhook a link-level
- // If it has links + doesn't have link.clicked trigger
- const linkLevelWebhooks = webhooks.filter(
+ // Promote to "links" scope: a webhook that now has links but isn't a link.clicked webhook yet
+ const promotedWebhooks = webhooks.filter(
(webhook) =>
webhook._count.links > 0 &&
!(webhook.triggers as string[])?.includes("link.clicked"),
);
- // Add link.clicked trigger to the webhook and cache it
- if (linkLevelWebhooks.length > 0) {
- const toUpdate = linkLevelWebhooks.map((webhook) => ({
+ // Add the link.clicked trigger + links scope to the webhook and cache it
+ if (promotedWebhooks.length > 0) {
+ const toUpdate = promotedWebhooks.map((webhook) => ({
...webhook,
triggers: [...(webhook.triggers as string[]), "link.clicked"],
}));
await Promise.all([
- ...linkLevelWebhooks.map((webhook) =>
+ ...promotedWebhooks.map((webhook) =>
prisma.webhook.update({
where: {
id: webhook.id,
},
data: {
triggers: [...(webhook.triggers as string[]), "link.clicked"],
+ linkScope: "links",
},
}),
),
@@ -85,30 +86,33 @@ export const propagateWebhookTriggerChanges = async ({
]);
}
- // Check if there are any webhooks downgraded to workspace level
- // If so, remove link.clicked trigger and remove it from the cache
- const workspaceLevelWebhooks = webhooks.filter(
+ // Demote to workspace level: a "links" scope webhook that no longer has any links.
+ // "all" / "folders" scope webhooks intentionally have no links, so they're never demoted.
+ const demotedWebhooks = webhooks.filter(
(webhook) =>
webhook._count.links === 0 &&
+ webhook.linkScope !== "all" &&
+ webhook.linkScope !== "folders" &&
(webhook.triggers as string[])?.includes("link.clicked"),
);
- if (workspaceLevelWebhooks.length > 0) {
+ if (demotedWebhooks.length > 0) {
await Promise.all([
- ...workspaceLevelWebhooks.map((webhook) =>
+ ...demotedWebhooks.map((webhook) =>
prisma.webhook.update({
where: {
id: webhook.id,
},
data: {
- triggers: (webhook.triggers as string[]) || [],
+ triggers: (webhook.triggers as string[]).filter(
+ (trigger) => trigger !== "link.clicked",
+ ),
+ linkScope: null,
},
}),
),
- webhookCache.deleteMany(
- workspaceLevelWebhooks.map((webhook) => webhook.id),
- ),
+ webhookCache.deleteMany(demotedWebhooks.map((webhook) => webhook.id)),
]);
}
};
diff --git a/apps/web/lib/webhook/validate-webhook.ts b/apps/web/lib/webhook/validate-webhook.ts
index 83aa356cec..789b64358c 100644
--- a/apps/web/lib/webhook/validate-webhook.ts
+++ b/apps/web/lib/webhook/validate-webhook.ts
@@ -19,7 +19,7 @@ export async function validateWebhook({
webhook?: Webhook;
user: Session["user"];
}) {
- const { url, linkIds, triggers } = input;
+ const { url, scope, linkIds, folderIds, triggers } = input;
// payout.confirmed trigger requires external payouts enabled
if (triggers && triggers.includes("payout.confirmed")) {
@@ -64,7 +64,7 @@ export async function validateWebhook({
}
}
- if (linkIds && linkIds.length > 0) {
+ if (scope === "links" && linkIds && linkIds.length > 0) {
const folders = await getFolders({
workspaceId: workspace.id,
userId: user.id,
@@ -94,4 +94,21 @@ export async function validateWebhook({
});
}
}
+
+ if (scope === "folders" && folderIds && folderIds.length > 0) {
+ const folders = await getFolders({
+ workspaceId: workspace.id,
+ userId: user.id,
+ });
+
+ const accessibleFolderIds = new Set(folders.map((folder) => folder.id));
+
+ if (!folderIds.every((folderId) => accessibleFolderIds.has(folderId))) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "Invalid folder IDs provided. Please check the folders you are adding the webhook to.",
+ });
+ }
+ }
}
diff --git a/apps/web/lib/zod/schemas/webhooks.ts b/apps/web/lib/zod/schemas/webhooks.ts
index cccb91a304..6afa740801 100644
--- a/apps/web/lib/zod/schemas/webhooks.ts
+++ b/apps/web/lib/zod/schemas/webhooks.ts
@@ -1,4 +1,5 @@
-import { WEBHOOK_TRIGGERS } from "@/lib/webhook/constants";
+import { WEBHOOK_TRIGGERS, WebhookTrigger } from "@/lib/webhook/constants";
+import { WebhookScope } from "@prisma/client";
import * as z from "zod/v4";
import { parseUrlSchema } from "./utils";
@@ -8,19 +9,77 @@ export const WebhookSchema = z.object({
url: z.string(),
secret: z.string(),
triggers: z.array(z.enum(WEBHOOK_TRIGGERS)),
+ scope: z.enum(WebhookScope).nullable(),
disabledAt: z.date().nullable(),
installationId: z.string().nullable(),
});
-export const createWebhookSchema = z.object({
+const validateWebhook = (
+ data: {
+ triggers: WebhookTrigger[];
+ scope?: WebhookScope | null;
+ linkIds?: string[] | null;
+ folderIds?: string[] | null;
+ },
+ ctx: z.RefinementCtx,
+) => {
+ // Only enforce when triggers are provided
+ if (!data.triggers) {
+ return;
+ }
+
+ if (!data.triggers.includes("link.clicked")) {
+ if (data.scope) {
+ ctx.addIssue({
+ code: "custom",
+ path: ["scope"],
+ message: `"scope" can only be set when the "link.clicked" trigger is enabled.`,
+ });
+ }
+ return;
+ }
+
+ if (!data.scope) {
+ ctx.addIssue({
+ code: "custom",
+ path: ["scope"],
+ message: `"scope" is required when the "link.clicked" trigger is enabled.`,
+ });
+ return;
+ }
+
+ if (data.scope === "links" && data.linkIds?.length === 0) {
+ ctx.addIssue({
+ code: "custom",
+ path: ["linkIds"],
+ message: "Select at least one link",
+ });
+ }
+
+ if (data.scope === "folders" && data.folderIds?.length === 0) {
+ ctx.addIssue({
+ code: "custom",
+ path: ["folderIds"],
+ message: "Select at least one folder.",
+ });
+ }
+};
+
+export const createWebhookSchemaBase = z.object({
name: z.string().min(1).max(40),
url: parseUrlSchema,
- secret: z.string().optional(),
triggers: z.array(z.enum(WEBHOOK_TRIGGERS)),
- linkIds: z.array(z.string()).optional(),
+ scope: z.enum(WebhookScope).nullish(),
+ linkIds: z.array(z.string()).nullish(),
+ folderIds: z.array(z.string()).nullish(),
});
-export const updateWebhookSchema = createWebhookSchema.partial();
+export const createWebhookSchema =
+ createWebhookSchemaBase.superRefine(validateWebhook);
+
+export const updateWebhookSchema = createWebhookSchemaBase
+ .partial()
+ .superRefine(validateWebhook);
// Schema of response sent to the webhook callback URL by QStash
export const webhookCallbackSchema = z.object({
diff --git a/apps/web/prisma/schema/folder.prisma b/apps/web/prisma/schema/folder.prisma
index c79087e5c5..2d38bdbf3c 100644
--- a/apps/web/prisma/schema/folder.prisma
+++ b/apps/web/prisma/schema/folder.prisma
@@ -28,6 +28,7 @@ model Folder {
links Link[]
users FolderUser[]
accessRequests FolderAccessRequest[]
+ webhooks FolderWebhook[]
dashboard Dashboard?
@@unique([name, projectId])
diff --git a/apps/web/prisma/schema/webhook.prisma b/apps/web/prisma/schema/webhook.prisma
index d6262344d3..474a9223a4 100644
--- a/apps/web/prisma/schema/webhook.prisma
+++ b/apps/web/prisma/schema/webhook.prisma
@@ -6,6 +6,12 @@ enum WebhookReceiver {
segment
}
+enum WebhookScope {
+ all // All links in the workspace
+ folders // Links inside specific folders
+ links // Specific links
+}
+
model Webhook {
id String @id
projectId String
@@ -15,6 +21,7 @@ model Webhook {
url String @db.LongText
secret String
triggers Json
+ scope WebhookScope? // Only set for webhooks with the link.clicked trigger
consecutiveFailures Int @default(0)
lastFailedAt DateTime?
disabledAt DateTime?
@@ -24,6 +31,7 @@ model Webhook {
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
installedIntegration InstalledIntegration? @relation(fields: [installationId], references: [id], onDelete: Cascade)
links LinkWebhook[]
+ folders FolderWebhook[]
@@index(projectId)
@@index(installationId)
@@ -40,3 +48,15 @@ model LinkWebhook {
@@unique([linkId, webhookId])
@@index(webhookId)
}
+
+model FolderWebhook {
+ id String @id @default(cuid())
+ folderId String
+ webhookId String
+
+ folder Folder @relation(fields: [folderId], references: [id], onUpdate: Cascade, onDelete: Cascade)
+ webhook Webhook @relation(fields: [webhookId], references: [id], onUpdate: Cascade, onDelete: Cascade)
+
+ @@unique([folderId, webhookId])
+ @@index(webhookId)
+}
diff --git a/apps/web/scripts/migrations/backfill-webhook-link-scope.ts b/apps/web/scripts/migrations/backfill-webhook-link-scope.ts
new file mode 100644
index 0000000000..9c9c0d2676
--- /dev/null
+++ b/apps/web/scripts/migrations/backfill-webhook-link-scope.ts
@@ -0,0 +1,23 @@
+import { prisma } from "@/lib/prisma";
+import "dotenv-flow/config";
+
+// Existing link.clicked webhooks are always scoped to specific links,
+// so backfill their linkScope to "links".
+
+async function main() {
+ const { count } = await prisma.webhook.updateMany({
+ where: {
+ scope: null,
+ triggers: {
+ array_contains: ["link.clicked"],
+ },
+ },
+ data: {
+ scope: "links",
+ },
+ });
+
+ console.log(`Updated ${count} webhooks`);
+}
+
+main();
diff --git a/apps/web/ui/webhooks/add-edit-webhook-form.tsx b/apps/web/ui/webhooks/add-edit-webhook-form.tsx
index 66926546af..6bf8167f74 100644
--- a/apps/web/ui/webhooks/add-edit-webhook-form.tsx
+++ b/apps/web/ui/webhooks/add-edit-webhook-form.tsx
@@ -5,35 +5,38 @@ import { EXTERNAL_PAYOUTS_PROGRAM_IDS } from "@/lib/constants/program";
import useWorkspace from "@/lib/swr/use-workspace";
import { NewWebhook, WebhookProps } from "@/lib/types";
import {
+ LINK_CLICK_WEBHOOK_TRIGGER,
LINK_LEVEL_WEBHOOK_TRIGGERS,
PROGRAM_LEVEL_WEBHOOK_TRIGGERS,
+ WEBHOOK_SCOPE_OPTIONS,
WEBHOOK_TRIGGER_DESCRIPTIONS,
WORKSPACE_LEVEL_WEBHOOK_TRIGGERS,
} from "@/lib/webhook/constants";
-import { Button, Checkbox, CopyButton, InfoTooltip } from "@dub/ui";
+import {
+ Button,
+ Checkbox,
+ CircleCheckFill,
+ CopyButton,
+ InfoTooltip,
+ RadioGroup,
+ RadioGroupItem,
+} from "@dub/ui";
import { cn, fetcher } from "@dub/utils";
+import { WebhookScope } from "@prisma/client";
import { useRouter } from "next/navigation";
-import { FormEvent, useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo } from "react";
+import { FormProvider, useForm, useFormContext } from "react-hook-form";
import { toast } from "sonner";
import useSWR, { mutate } from "swr";
+import { FoldersSelector } from "./folder-selector";
import { LinksSelector } from "./link-selector";
-const defaultValues: Omit<NewWebhook, "linkIds"> = {
- name: "",
- url: "",
- secret: "",
- triggers: [],
-};
-
export default function AddEditWebhookForm({
webhook,
- newSecret,
}: {
webhook: WebhookProps | null;
- newSecret?: string;
}) {
const router = useRouter();
- const [saving, setSaving] = useState(false);
const {
id: workspaceId,
slug: workspaceSlug,
@@ -41,71 +44,75 @@ export default function AddEditWebhookForm({
defaultProgramId,
} = useWorkspace();
- const [data, setData] = useState<WebhookProps | Omit<NewWebhook, "linkIds">>(
- webhook || {
- ...defaultValues,
- ...(newSecret && { secret: newSecret }),
+ const methods = useForm<NewWebhook>({
+ defaultValues: {
+ name: webhook?.name ?? "",
+ url: webhook?.url ?? "",
+ triggers: webhook?.triggers ?? [],
+ scope: webhook?.scope ?? "all",
+ linkIds: [],
+ folderIds: [],
},
- );
- const [linkIds, setLinkIds] = useState<string[]>([]);
- const [linkIdsInitialized, setLinkIdsInitialized] = useState(!webhook);
-
- const { name, url, secret, triggers } = data;
-
- const hasLinkLevelWebhook = LINK_LEVEL_WEBHOOK_TRIGGERS.some((trigger) =>
- triggers.includes(trigger),
- );
+ });
- const { data: fetchedLinkIds } = useSWR<string[]>(
- webhook && hasLinkLevelWebhook
- ? `/api/webhooks/${webhook.id}/links?workspaceId=${workspaceId}`
- : null,
- fetcher,
- );
+ const {
+ register,
+ handleSubmit,
+ watch,
+ setValue,
+ formState: { isSubmitting },
+ } = methods;
- useEffect(() => {
- if (fetchedLinkIds && !linkIdsInitialized) {
- setLinkIds(fetchedLinkIds);
- setLinkIdsInitialized(true);
- }
- }, [fetchedLinkIds, linkIdsInitialized]);
+ const [name, url, triggers, scope, linkIds, folderIds] = watch([
+ "name",
+ "url",
+ "triggers",
+ "scope",
+ "linkIds",
+ "folderIds",
+ ]);
const { error: permissionsError } = clientAccessCheck({
action: "webhooks.write",
role,
});
- // Determine the endpoint
const endpoint = useMemo(() => {
if (webhook) {
return {
- method: "PATCH",
+ method: "PATCH" as const,
url: `/api/webhooks/${webhook.id}?workspaceId=${workspaceId}`,
successMessage: "Webhook updated!",
};
- } else {
- return {
- method: "POST",
- url: `/api/webhooks?workspaceId=${workspaceId}`,
- successMessage: "Webhook created!",
- };
}
- }, [webhook]);
- // Save the form data
- const onSubmit = async (e: FormEvent) => {
- e.preventDefault();
- setSaving(true);
+ return {
+ method: "POST" as const,
+ url: `/api/webhooks?workspaceId=${workspaceId}`,
+ successMessage: "Webhook created!",
+ };
+ }, [webhook, workspaceId]);
+
+ const hasLinkClicked = triggers.includes(LINK_CLICK_WEBHOOK_TRIGGER);
+ const onSubmit = async (data: NewWebhook) => {
const response = await fetch(endpoint.url, {
method: endpoint.method,
headers: {
"Content-Type": "application/json",
},
- body: JSON.stringify({ ...data, linkIds }),
+ body: JSON.stringify({
+ name: data.name,
+ url: data.url,
+ triggers: data.triggers,
+ ...(hasLinkClicked && {
+ scope: data.scope,
+ ...(data.scope === "links" && { linkIds: data.linkIds }),
+ ...(data.scope === "folders" && { folderIds: data.folderIds }),
+ }),
+ }),
});
- setSaving(false);
const result = await response.json();
if (!response.ok) {
@@ -115,19 +122,30 @@ export default function AddEditWebhookForm({
if (endpoint.method === "POST") {
mutate(`/api/webhooks?workspaceId=${workspaceId}`);
- router.push(`/${workspaceSlug}/settings/webhooks`);
+ mutate(`/api/webhooks/${result.id}?workspaceId=${workspaceId}`, result);
+ router.push(`/${workspaceSlug}/settings/webhooks/${result.id}/edit`);
} else {
mutate(`/api/webhooks/${result.id}?workspaceId=${workspaceId}`, result);
mutate(
`/api/webhooks/${result.id}/links?workspaceId=${workspaceId}`,
- linkIds,
+ data.scope === "links" ? data.linkIds : [],
+ );
+ mutate(
+ `/api/webhooks/${result.id}/folders?workspaceId=${workspaceId}`,
+ data.scope === "folders" ? data.folderIds : [],
);
}
toast.success(endpoint.successMessage);
};
- const buttonDisabled = !name || !url || !triggers.length || saving;
+ const scopeInvalid =
+ hasLinkClicked &&
+ ((scope === "links" && linkIds?.length === 0) ||
+ (scope === "folders" && folderIds?.length === 0));
+
+ const buttonDisabled =
+ !name || !url || !triggers.length || isSubmitting || scopeInvalid;
const updateDisabled =
(webhook && webhook?.installationId !== null) || permissionsError !== false;
@@ -139,7 +157,7 @@ export default function AddEditWebhookForm({
? permissionsError
: undefined;
- const availableWebhookTriggers = useMemo(
+ const allWebhookTriggers = useMemo(
() => [
...WORKSPACE_LEVEL_WEBHOOK_TRIGGERS,
...(defaultProgramId
@@ -149,14 +167,29 @@ export default function AddEditWebhookForm({
EXTERNAL_PAYOUTS_PROGRAM_IDS.includes(defaultProgramId),
)
: []),
+ ...LINK_LEVEL_WEBHOOK_TRIGGERS,
],
[defaultProgramId],
);
+ const toggleTrigger = (
+ trigger: NewWebhook["triggers"][number],
+ checked: boolean | "indeterminate",
+ ) => {
+ if (checked === "indeterminate") {
+ return;
+ }
+
+ setValue(
+ "triggers",
+ checked ? [...triggers, trigger] : triggers.filter((t) => t !== trigger),
+ );
+ };
+
return (
- <>
+ <FormProvider {...methods}>
<form
- onSubmit={onSubmit}
+ onSubmit={handleSubmit(onSubmit)}
className="flex flex-col space-y-5 pb-20 text-left"
>
<div>
@@ -165,6 +198,7 @@ export default function AddEditWebhookForm({
</label>
<div className="relative mt-2 rounded-md shadow-sm">
<input
+ id="name"
className={cn(
"block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
{
@@ -172,12 +206,11 @@ export default function AddEditWebhookForm({
},
)}
required
- value={name}
- onChange={(e) => setData({ ...data, name: e.target.value })}
autoFocus
autoComplete="off"
placeholder="Webhook name"
disabled={updateDisabled}
+ {...register("name")}
/>
</div>
</div>
@@ -188,6 +221,7 @@ export default function AddEditWebhookForm({
</label>
<div className="relative mt-2 rounded-md shadow-sm">
<input
+ id="url"
className={cn(
"block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
{
@@ -195,134 +229,201 @@ export default function AddEditWebhookForm({
},
)}
required
- value={url}
- onChange={(e) => setData({ ...data, url: e.target.value })}
autoComplete="off"
placeholder="Webhook URL"
disabled={updateDisabled}
+ {...register("url")}
/>
</div>
</div>
- <div className="space-y-2">
- <label className="flex items-center space-x-2">
- <h2 className="text-sm font-medium text-neutral-900">
- Signing secret
- </h2>
- <InfoTooltip content="A secret token used to sign the webhook payload." />
- </label>
- <div className="flex items-center justify-between rounded-md border border-neutral-300 bg-white px-3 py-1">
- <p className="text-nowrap font-mono text-sm text-neutral-500">
- {secret}
- </p>
- <div className="flex flex-col gap-2">
- <CopyButton value={secret!} className="rounded-md" />
+ {webhook ? (
+ <div className="space-y-2">
+ <label className="flex items-center space-x-2">
+ <h2 className="text-sm font-medium text-neutral-900">
+ Signing secret
+ </h2>
+ <InfoTooltip content="A secret token used to sign the webhook payload." />
+ </label>
+ <div className="flex items-center justify-between rounded-md border border-neutral-300 bg-neutral-50 px-3 py-1">
+ <p className="text-nowrap font-mono text-sm text-neutral-500">
+ {webhook.secret}
+ </p>
+ <CopyButton value={webhook.secret} className="rounded-md" />
</div>
</div>
- </div>
+ ) : null}
- <div className="rounded-md border border-neutral-200 p-4">
- <label htmlFor="triggers" className="flex flex-col gap-1">
+ <div>
+ <label htmlFor="triggers">
<h2 className="text-sm font-medium text-neutral-900">
- Workspace level events
+ Webhook events
</h2>
- <span className="text-xs text-neutral-500">
- These events are triggered at the workspace level.
- </span>
</label>
<div className="mt-3 flex flex-col gap-2">
- {availableWebhookTriggers.map((trigger) => (
- <div key={trigger} className="group flex gap-2">
- <Checkbox
- value={trigger}
- id={trigger}
- checked={triggers.includes(trigger)}
- disabled={updateDisabled}
- onCheckedChange={(checked) => {
- setData({
- ...data,
- triggers: checked
- ? [...triggers, trigger]
- : triggers.filter((t) => t !== trigger),
- });
- }}
- />
- <label
- htmlFor={trigger}
- className="select-none text-sm text-neutral-600 group-hover:text-neutral-800"
- >
- {WEBHOOK_TRIGGER_DESCRIPTIONS[trigger]}
- </label>
- </div>
- ))}
- </div>
- </div>
+ {allWebhookTriggers.map((trigger) => (
+ <div key={trigger}>
+ <div className="group flex gap-2">
+ <Checkbox
+ value={trigger}
+ id={trigger}
+ checked={triggers.includes(trigger)}
+ disabled={updateDisabled}
+ onCheckedChange={(checked) =>
+ toggleTrigger(trigger, checked)
+ }
+ />
+ <label
+ htmlFor={trigger}
+ className="flex select-none items-center gap-2 text-sm text-neutral-600 group-hover:text-neutral-800"
+ >
+ {WEBHOOK_TRIGGER_DESCRIPTIONS[trigger]}
+ {trigger === LINK_CLICK_WEBHOOK_TRIGGER ? (
+ <span className="rounded bg-yellow-100 px-1 py-0.5 text-xs font-medium text-yellow-800">
+ High traffic
+ </span>
+ ) : null}
+ </label>
+ </div>
- <div className="rounded-md border border-neutral-200 p-4">
- <label htmlFor="triggers" className="flex flex-col gap-1">
- <h2 className="text-sm font-medium text-neutral-900">
- Link level events{" "}
- <span className="rounded bg-yellow-100 px-1 py-0.5 text-xs font-medium text-yellow-800">
- High traffic
- </span>
- </h2>
- <span className="text-xs text-neutral-500">
- These events are triggered at the link level.
- </span>
- </label>
- <div className="mt-3 flex flex-col gap-2">
- {LINK_LEVEL_WEBHOOK_TRIGGERS.map((trigger) => (
- <div key={trigger} className="group flex gap-2">
- <Checkbox
- value={trigger}
- id={trigger}
- checked={triggers.includes(trigger)}
- disabled={updateDisabled}
- onCheckedChange={(checked) => {
- setData({
- ...data,
- triggers: checked
- ? [...triggers, trigger]
- : triggers.filter((t) => t !== trigger),
- });
- }}
- />
- <label
- htmlFor={trigger}
- className="flex select-none items-center gap-2 text-sm text-neutral-600 group-hover:text-neutral-800"
- >
- {WEBHOOK_TRIGGER_DESCRIPTIONS[trigger]}
- </label>
+ {trigger === LINK_CLICK_WEBHOOK_TRIGGER && hasLinkClicked ? (
+ <LinkClickScopeFields
+ disabled={updateDisabled}
+ webhook={webhook}
+ workspaceId={workspaceId}
+ />
+ ) : null}
</div>
))}
</div>
-
- {hasLinkLevelWebhook && linkIds.length < 1000 ? (
- <div className="mt-4">
- <h2 className="text-sm font-medium text-neutral-900">
- Choose links we should send events for
- </h2>
- <div className="mt-3">
- <LinksSelector
- selectedLinkIds={linkIds}
- setSelectedLinkIds={setLinkIds}
- disabled={updateDisabled}
- />
- </div>
- </div>
- ) : null}
</div>
<Button
text={webhook ? "Save changes" : "Create webhook"}
disabled={buttonDisabled || updateDisabled}
- loading={saving}
+ loading={isSubmitting}
type="submit"
{...(disabledTooltip && {
disabledTooltip,
})}
/>
</form>
- </>
+ </FormProvider>
+ );
+}
+
+function LinkClickScopeFields({
+ disabled,
+ webhook,
+ workspaceId,
+}: {
+ disabled: boolean;
+ webhook: WebhookProps | null;
+ workspaceId: string | undefined;
+}) {
+ const { watch, setValue } = useFormContext<NewWebhook>();
+
+ const [scope = "all", linkIds = [], folderIds = []] = watch([
+ "scope",
+ "linkIds",
+ "folderIds",
+ ]);
+
+ const { data: fetchedLinkIds } = useSWR<string[]>(
+ webhook && webhook.scope === "links"
+ ? `/api/webhooks/${webhook.id}/links?workspaceId=${workspaceId}`
+ : null,
+ fetcher,
+ );
+
+ const { data: fetchedFolderIds } = useSWR<string[]>(
+ webhook && webhook.scope === "folders"
+ ? `/api/webhooks/${webhook.id}/folders?workspaceId=${workspaceId}`
+ : null,
+ fetcher,
+ );
+
+ useEffect(() => {
+ if (webhook?.scope === "links" && fetchedLinkIds) {
+ setValue("linkIds", fetchedLinkIds);
+ } else if (webhook?.scope === "folders" && fetchedFolderIds) {
+ setValue("folderIds", fetchedFolderIds);
+ }
+ }, [fetchedLinkIds, fetchedFolderIds, webhook?.scope, setValue]);
+
+ return (
+ <div className="ml-6 mt-3 rounded-md border border-neutral-200 bg-neutral-50 p-4">
+ <RadioGroup
+ value={scope}
+ onValueChange={(value) => setValue("scope", value as WebhookScope)}
+ className="flex flex-col gap-2"
+ disabled={disabled}
+ >
+ {WEBHOOK_SCOPE_OPTIONS.map((option) => {
+ const isSelected = scope === option.value;
+
+ return (
+ <div key={option.value}>
+ <label
+ className={cn(
+ "relative flex w-full cursor-pointer items-start gap-3 rounded-md border border-neutral-200 bg-white p-3 text-neutral-600 hover:bg-neutral-50",
+ "transition-all duration-150",
+ isSelected &&
+ "border-black bg-neutral-50 text-neutral-900 ring-1 ring-black",
+ disabled && "cursor-not-allowed opacity-60",
+ )}
+ >
+ <RadioGroupItem
+ value={option.value}
+ id={`scope-${option.value}`}
+ className="mt-0.5"
+ disabled={disabled}
+ />
+ <div className="flex grow flex-col text-sm">
+ <span className="font-medium">{option.label}</span>
+ <span className="text-neutral-500">{option.description}</span>
+ </div>
+ <CircleCheckFill
+ className={cn(
+ "-mr-px -mt-px flex size-4 scale-75 items-center justify-center rounded-full opacity-0 transition-[transform,opacity] duration-150",
+ isSelected && "scale-100 opacity-100",
+ )}
+ />
+ </label>
+
+ {isSelected && option.value === "folders" ? (
+ <div className="mt-3 pl-7">
+ <h3 className="text-sm font-medium text-neutral-900">
+ Included folders
+ </h3>
+ <div className="mt-2">
+ <FoldersSelector
+ selectedFolderIds={folderIds ?? []}
+ setSelectedFolderIds={(ids) => setValue("folderIds", ids)}
+ disabled={disabled}
+ />
+ </div>
+ </div>
+ ) : null}
+
+ {isSelected && option.value === "links" ? (
+ <div className="mt-3 pl-7">
+ <h3 className="text-sm font-medium text-neutral-900">
+ Included links
+ </h3>
+ <div className="mt-2">
+ <LinksSelector
+ selectedLinkIds={linkIds ?? []}
+ setSelectedLinkIds={(ids) => setValue("linkIds", ids)}
+ disabled={disabled}
+ />
+ </div>
+ </div>
+ ) : null}
+ </div>
+ );
+ })}
+ </RadioGroup>
+ </div>
);
}
diff --git a/apps/web/ui/webhooks/folder-selector.tsx b/apps/web/ui/webhooks/folder-selector.tsx
new file mode 100644
index 0000000000..9f075a7ce5
--- /dev/null
+++ b/apps/web/ui/webhooks/folder-selector.tsx
@@ -0,0 +1,126 @@
+"use client";
+
+import useFolders from "@/lib/swr/use-folders";
+import { Folder } from "@/lib/types";
+import { Combobox } from "@dub/ui";
+import { cn } from "@dub/utils";
+import { useMemo, useState } from "react";
+import { useDebounce } from "use-debounce";
+import { FolderIcon } from "../folders/folder-icon";
+
+const MAX_DISPLAYED_FOLDERS = 10;
+
+const getFolderOption = (folder: Folder) => ({
+ value: folder.id,
+ label: folder.name,
+ icon: (
+ <FolderIcon className="mr-1 shrink-0" folder={folder} shape="square" />
+ ),
+ meta: {
+ folder,
+ },
+});
+
+export function FoldersSelector({
+ selectedFolderIds,
+ setSelectedFolderIds,
+ disabled,
+}: {
+ selectedFolderIds: string[];
+ setSelectedFolderIds: (ids: string[]) => void;
+ disabled?: boolean;
+}) {
+ const [search, setSearch] = useState("");
+ const [debouncedSearch] = useDebounce(search, 500);
+
+ const { folders } = useFolders({
+ query: {
+ search: debouncedSearch,
+ },
+ options: {
+ keepPreviousData: false,
+ },
+ });
+
+ // Default (unsearched) list to resolve the names of already-selected folders
+ const { folders: selectedFolders } = useFolders();
+
+ const options = useMemo(
+ () => folders?.map((folder) => getFolderOption(folder)),
+ [folders],
+ );
+
+ const selectedOptions = useMemo(
+ () =>
+ selectedFolderIds
+ .map((id) =>
+ [...(folders || []), ...(selectedFolders || [])].find(
+ (f) => f.id === id,
+ ),
+ )
+ .filter(Boolean)
+ .map((f) => getFolderOption(f as Folder)),
+ [selectedFolderIds, folders, selectedFolders],
+ );
+
+ // Calculate how many additional folders are not displayed:
+ const plusCount =
+ selectedFolderIds.length > selectedOptions.length
+ ? selectedFolderIds.length -
+ Math.min(selectedOptions.length, MAX_DISPLAYED_FOLDERS)
+ : Math.max(0, selectedOptions.length - MAX_DISPLAYED_FOLDERS);
+
+ return (
+ <Combobox
+ multiple
+ caret
+ matchTriggerWidth
+ side="top" // Since this control is near the bottom of the page, prefer top to avoid jumping
+ options={options}
+ selected={selectedOptions ?? []}
+ onSelect={({ value: id }) =>
+ setSelectedFolderIds(
+ selectedFolderIds.includes(id)
+ ? selectedFolderIds.filter((sid) => sid !== id)
+ : [...selectedFolderIds, id],
+ )
+ }
+ shouldFilter={false}
+ onSearchChange={setSearch}
+ buttonProps={{
+ disabled,
+ className: cn(
+ "h-auto py-1.5 px-2.5 w-full max-w-full text-neutral-700 border-neutral-300 items-start",
+ ),
+ }}
+ >
+ {selectedFolderIds.length === 0 ? (
+ <div className="py-0.5">Select folders...</div>
+ ) : selectedOptions ? (
+ <div className="flex flex-wrap gap-2">
+ {selectedOptions.slice(0, MAX_DISPLAYED_FOLDERS).map((option) => (
+ <span
+ key={option.value}
+ className="animate-fade-in flex min-w-0 items-center gap-1 rounded-md bg-neutral-100 px-1.5 py-1 text-xs text-neutral-600"
+ >
+ <FolderIcon
+ folder={option.meta.folder}
+ shape="square"
+ className="shrink-0"
+ iconClassName="size-3"
+ />
+ <span className="min-w-0 truncate">{option.label}</span>
+ </span>
+ ))}
+ {plusCount > 0 && (
+ <span className="animate-fade-in flex rounded-md bg-neutral-100 px-1.5 py-1 text-xs font-medium text-neutral-600">
+ + {plusCount} more
+ </span>
+ )}
+ </div>
+ ) : (
+ <div className="my-0.5 h-5 w-1/3 animate-pulse rounded bg-neutral-200" />
+ )}
+ </Combobox>
+ );
+}