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.

Fix a few more TS errors, some minor bugs

Steven Teya3d453d66734
diff --git a/components/app/links/link-card.tsx b/components/app/links/link-card.tsx
index 509ea054f0..106fe699cb 100644
--- a/components/app/links/link-card.tsx
+++ b/components/app/links/link-card.tsx
@@ -31,6 +31,7 @@ import useIntersectionObserver from "@/lib/hooks/use-intersection-observer";
import useDomains from "@/lib/swr/use-domains";
import { CopyPlus, Edit3 } from "lucide-react";
import punycode from "punycode/";
+import { GOOGLE_FAVICON_URL } from "@/lib/constants";
export default function LinkCard({ props }: { props: LinkProps }) {
const { key, domain, url, createdAt, archived, expiresAt } = props;
@@ -154,7 +155,7 @@ export default function LinkCard({ props }: { props: LinkProps }) {
<li className="relative flex items-center justify-between">
<div className="relative flex shrink items-center space-x-2 sm:space-x-4">
<BlurImage
- src={`https://www.google.com/s2/favicons?sz=64&domain_url=${apexDomain}`}
+ src={`${GOOGLE_FAVICON_URL}${apexDomain}`}
alt={apexDomain}
className="h-8 w-8 rounded-full sm:h-10 sm:w-10"
width={20}
diff --git a/components/app/modals/add-edit-link-modal/index.tsx b/components/app/modals/add-edit-link-modal/index.tsx
index 8d9c994e7f..3cd8276b96 100644
--- a/components/app/modals/add-edit-link-modal/index.tsx
+++ b/components/app/modals/add-edit-link-modal/index.tsx
@@ -37,11 +37,12 @@ import UTMSection from "./utm-section";
import IOSSection from "./ios-section";
import Preview from "./preview";
import AndroidSection from "./android-section";
-import { DEFAULT_LINK_PROPS } from "@/lib/constants";
+import { DEFAULT_LINK_PROPS, GOOGLE_FAVICON_URL } from "@/lib/constants";
import useDomains from "@/lib/swr/use-domains";
import { toast } from "react-hot-toast";
import va from "@vercel/analytics";
import punycode from "punycode/";
+import Button from "app/ui/button";
function AddEditLinkModal({
showAddEditLinkModal,
@@ -181,7 +182,7 @@ function AddEditLinkModal({
return "/_static/logo.png";
// otherwise, get the favicon of the URL
} else {
- return `https://www.google.com/s2/favicons?sz=64&domain_url=${getApexDomain(
+ return `${GOOGLE_FAVICON_URL}${getApexDomain(
debouncedUrl || props?.url || "https://dub.sh",
)}`;
}
@@ -230,30 +231,24 @@ function AddEditLinkModal({
saving ||
keyExistsError ||
urlError ||
- generatingMetatags ||
(props &&
Object.entries(props).every(([key, value]) => {
- // only check for discrepancy in title and description if proxy is enabled
- if (proxy && (key === "title" || key === "description")) {
+ // If the key is "title" or "description" and proxy is not enabled, return true (skip the check)
+ if (
+ (key === "title" || key === "description" || key === "image") &&
+ !proxy
+ ) {
return true;
- } else {
- return data[key] === value;
}
+ // Otherwise, check for discrepancy in the current key-value pair
+ return data[key] === value;
}))
) {
return true;
} else {
return false;
}
- }, [
- showAddEditLinkModal,
- saving,
- keyExistsError,
- urlError,
- generatingMetatags,
- props,
- data,
- ]);
+ }, [showAddEditLinkModal, saving, keyExistsError, urlError, props, data]);
const randomIdx = Math.floor(Math.random() * 100);
@@ -538,34 +533,16 @@ function AddEditLinkModal({
} z-10 bg-gray-50 px-4 py-8 transition-all sm:sticky sm:bottom-0 sm:px-16`}
>
{homepageDemo ? (
- <Tooltip
- content="This is a demo link. You can't edit it."
- fullWidth
- >
- <button
- disabled={true}
- className=" flex h-10 w-full cursor-not-allowed items-center justify-center rounded-md border border-gray-200 bg-gray-100 text-sm text-gray-400 transition-all focus:outline-none"
- >
- <p className="text-sm">Save changes</p>
- </button>
- </Tooltip>
+ <Button
+ disabledTooltip="This is a demo link. You can't edit it."
+ text="Save changes"
+ />
) : (
- <button
+ <Button
disabled={saveDisabled}
- className={`${
- saveDisabled
- ? "cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400"
- : "border-black bg-black text-white hover:bg-white hover:text-black"
- } flex h-10 w-full items-center justify-center rounded-md border text-sm transition-all focus:outline-none`}
- >
- {saving ? (
- <LoadingDots color="#808080" />
- ) : (
- <p className="text-sm">
- {props ? "Save changes" : "Create link"}
- </p>
- )}
- </button>
+ loading={saving}
+ text={props ? "Save changes" : "Create link"}
+ />
)}
</div>
</form>
diff --git a/components/app/modals/archive-link-modal.tsx b/components/app/modals/archive-link-modal.tsx
index 38cf816d2a..6bc92dfbd8 100644
--- a/components/app/modals/archive-link-modal.tsx
+++ b/components/app/modals/archive-link-modal.tsx
@@ -13,6 +13,7 @@ import Modal from "@/components/shared/modal";
import useProject from "@/lib/swr/use-project";
import { LinkProps } from "@/lib/types";
import { getApexDomain, getQueryString, linkConstructor } from "@/lib/utils";
+import { GOOGLE_FAVICON_URL } from "@/lib/constants";
function ArchiveLinkModal({
showArchiveLinkModal,
@@ -48,7 +49,7 @@ function ArchiveLinkModal({
<div className="inline-block w-full transform overflow-hidden bg-white align-middle shadow-xl transition-all sm:max-w-md sm:rounded-2xl sm:border sm:border-gray-200">
<div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 px-4 py-4 pt-8 text-center sm:px-16">
<BlurImage
- src={`https://www.google.com/s2/favicons?sz=64&domain_url=${apexDomain}`}
+ src={`${GOOGLE_FAVICON_URL}${apexDomain}`}
alt={apexDomain}
className="h-10 w-10 rounded-full"
width={20}
diff --git a/components/app/modals/delete-link-modal.tsx b/components/app/modals/delete-link-modal.tsx
index e98251898e..987e12a1a9 100644
--- a/components/app/modals/delete-link-modal.tsx
+++ b/components/app/modals/delete-link-modal.tsx
@@ -13,6 +13,7 @@ import Modal from "@/components/shared/modal";
import { LinkProps } from "@/lib/types";
import { getApexDomain, getQueryString, linkConstructor } from "@/lib/utils";
import { toast } from "react-hot-toast";
+import { GOOGLE_FAVICON_URL } from "@/lib/constants";
function DeleteLinkModal({
showDeleteLinkModal,
@@ -46,7 +47,7 @@ function DeleteLinkModal({
<div className="inline-block w-full transform overflow-hidden bg-white align-middle shadow-xl transition-all sm:max-w-md sm:rounded-2xl sm:border sm:border-gray-200">
<div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 px-4 py-4 pt-8 sm:px-16">
<BlurImage
- src={`https://www.google.com/s2/favicons?sz=64&domain_url=${apexDomain}`}
+ src={`${GOOGLE_FAVICON_URL}${apexDomain}`}
alt={apexDomain}
className="h-10 w-10 rounded-full"
width={20}
diff --git a/components/app/modals/link-qr-modal.tsx b/components/app/modals/link-qr-modal.tsx
index 40c26b63e9..dfc984a060 100644
--- a/components/app/modals/link-qr-modal.tsx
+++ b/components/app/modals/link-qr-modal.tsx
@@ -20,6 +20,7 @@ import IconMenu from "@/components/shared/icon-menu";
import { Download, Photo } from "@/components/shared/icons";
import Popover from "@/components/shared/popover";
import toast from "react-hot-toast";
+import { GOOGLE_FAVICON_URL } from "@/lib/constants";
function LinkQRModalHelper({
showLinkQRModal,
@@ -36,7 +37,7 @@ function LinkQRModalHelper({
try {
const apexDomain = getApexDomain(props.url);
return {
- avatarUrl: `https://www.google.com/s2/favicons?sz=64&domain_url=${apexDomain}`,
+ avatarUrl: `${GOOGLE_FAVICON_URL}${apexDomain}`,
apexDomain,
};
} catch (e) {
diff --git a/components/app/projects/project-card.tsx b/components/app/projects/project-card.tsx
index 0d8c4ee917..82cc2af694 100644
--- a/components/app/projects/project-card.tsx
+++ b/components/app/projects/project-card.tsx
@@ -7,6 +7,7 @@ import { ProjectWithDomainProps } from "@/lib/types";
import { fetcher, nFormatter } from "@/lib/utils";
import { BarChart2, Globe, Link2 } from "lucide-react";
import PlanBadge from "../settings/plan-badge";
+import { GOOGLE_FAVICON_URL } from "@/lib/constants";
export default function ProjectCard({
name,
@@ -30,10 +31,7 @@ export default function ProjectCard({
<div className="flex items-start justify-between">
<div className="flex items-center space-x-3">
<BlurImage
- src={
- logo ||
- `https://www.google.com/s2/favicons?sz=64&domain_url=${primaryDomain?.slug}`
- }
+ src={logo || `${GOOGLE_FAVICON_URL}${primaryDomain?.slug}`}
alt={slug}
className="h-10 w-10 flex-shrink-0 overflow-hidden rounded-full"
width={48}
diff --git a/components/home/globe.tsx b/components/home/globe.tsx
index 7f667cb34b..58d9b9d38f 100644
--- a/components/home/globe.tsx
+++ b/components/home/globe.tsx
@@ -57,14 +57,16 @@ export default function Globe() {
webglSupported ? "min-h-[500px] sm:min-h-[1000px]" : "min-h-[50px]"
} h-full`}
>
- {webglSupported && showGlobe && <GlobeAnimation markers={markers} />}
+ {webglSupported && showGlobe && (
+ <GlobeAnimation markers={markers || []} />
+ )}
</div>
);
}
const GlobeAnimation = ({ markers }: { markers: MarkerProps[] }) => {
const canvasRef = useRef<any>();
- const pointerInteracting = useRef(null);
+ const pointerInteracting = useRef<number | null>(null);
const pointerInteractionMovement = useRef(0);
const [{ r }, api] = useSpring(() => ({
@@ -127,7 +129,7 @@ const GlobeAnimation = ({ markers }: { markers: MarkerProps[] }) => {
className="group absolute left-0 right-0 z-10 mx-auto max-w-sm rounded-md border border-gray-200 bg-white bg-opacity-90 px-5 py-4 shadow-md backdrop-blur-md sm:py-7"
>
<button
- className="group visible absolute top-0 right-0 float-right m-3 rounded-full p-1 transition-all duration-75 hover:bg-gray-100 focus:outline-none active:scale-75 group-hover:visible sm:invisible"
+ className="group visible absolute right-0 top-0 float-right m-3 rounded-full p-1 transition-all duration-75 hover:bg-gray-100 focus:outline-none active:scale-75 group-hover:visible sm:invisible"
autoFocus={false}
onClick={() => setShowModal(false)}
>
diff --git a/components/home/link-card.tsx b/components/home/link-card.tsx
index 6c2e6f8730..530d83d3f0 100644
--- a/components/home/link-card.tsx
+++ b/components/home/link-card.tsx
@@ -10,6 +10,7 @@ import { Chart, LoadingDots, QR, ThreeDots } from "@/components/shared/icons";
import {
DEFAULT_LINK_PROPS,
FRAMER_MOTION_LIST_ITEM_VARIANTS,
+ GOOGLE_FAVICON_URL,
} from "@/lib/constants";
import { SimpleLinkProps } from "@/lib/types";
import {
@@ -35,7 +36,7 @@ export default function LinkCard({
}) {
const apexDomain = getApexDomain(url);
- const cardElem = useRef(null);
+ const cardElem = useRef<HTMLDivElement | null>(null);
const x = useMotionValue(0);
const controls = useAnimation();
@@ -62,9 +63,8 @@ export default function LinkCard({
const flyAwayDistance = (direction) => {
const parentWidth =
// @ts-ignore
- cardElem.current.parentNode.getBoundingClientRect().width;
- // @ts-ignore
- const childWidth = cardElem.current.getBoundingClientRect().width;
+ cardElem.current?.parentNode?.getBoundingClientRect().width || 0;
+ const childWidth = cardElem.current?.getBoundingClientRect().width || 0;
return direction === "left"
? -parentWidth / 2 - childWidth / 2
: parentWidth / 2 + childWidth / 2;
@@ -144,7 +144,7 @@ export default function LinkCard({
>
<div className="flex items-center space-x-3">
<BlurImage
- src={`https://www.google.com/s2/favicons?sz=64&domain_url=${apexDomain}`}
+ src={`${GOOGLE_FAVICON_URL}${apexDomain}`}
alt={apexDomain}
className="pointer-events-none h-10 w-10 rounded-full"
width={20}
diff --git a/components/home/pricing.tsx b/components/home/pricing.tsx
index da74255a9f..115a0b8c12 100644
--- a/components/home/pricing.tsx
+++ b/components/home/pricing.tsx
@@ -54,7 +54,7 @@ const pricingItems = [
{
plan: "Pro",
tagline: "For larger teams with increased usage",
- quota: PLANS.find((p) => p.slug === "pro").quota,
+ quota: PLANS.find((p) => p.slug === "pro")!.quota,
features: [
{ text: "Unlimited users" },
{ text: "Unlimited branded links" },
@@ -85,7 +85,7 @@ const pricingItems = [
{
plan: "Enterprise",
tagline: "For businesses with custom needs",
- quota: PLANS.find((p) => p.slug === "enterprise").quota,
+ quota: PLANS.find((p) => p.slug === "enterprise")!.quota,
features: [
{ text: "Unlimited users" },
{ text: "Unlimited branded links" },
@@ -255,7 +255,7 @@ const Pricing = ({ homePage }: { homePage?: boolean }) => {
setClicked(true);
fetch(
`/api/projects/${slug}/billing/upgrade?priceId=${
- PLANS.find((p) => p.slug === plan.toLowerCase())
+ PLANS.find((p) => p.slug === plan.toLowerCase())!
.price[period].priceIds[env]
}`,
{
@@ -266,7 +266,7 @@ const Pricing = ({ homePage }: { homePage?: boolean }) => {
const data = await res.json();
const { id: sessionId } = data;
const stripe = await getStripe();
- stripe.redirectToCheckout({ sessionId });
+ stripe?.redirectToCheckout({ sessionId });
})
.catch((err) => {
alert(err);
diff --git a/components/layout/app/project-select.tsx b/components/layout/app/project-select.tsx
index b12b645e36..7919a24521 100644
--- a/components/layout/app/project-select.tsx
+++ b/components/layout/app/project-select.tsx
@@ -8,6 +8,7 @@ import Popover from "@/components/shared/popover";
import { PlanProps, ProjectWithDomainProps } from "@/lib/types";
import useProjects from "@/lib/swr/use-projects";
import PlanBadge from "@/components/app/settings/plan-badge";
+import { GOOGLE_FAVICON_URL } from "@/lib/constants";
export default function ProjectSelect() {
const { projects } = useProjects();
@@ -29,7 +30,7 @@ export default function ProjectSelect() {
...selectedProject,
image:
selectedProject?.logo ||
- `https://www.google.com/s2/favicons?sz=64&domain_url=${selectedProject?.primaryDomain?.slug}`,
+ `${GOOGLE_FAVICON_URL}${selectedProject?.primaryDomain?.slug}`,
};
} else {
return {
@@ -107,7 +108,7 @@ function ProjectList({
plan: PlanProps;
};
projects: ProjectWithDomainProps[];
- setShowAddProjectModal?: (show: boolean) => void;
+ setShowAddProjectModal: (show: boolean) => void;
}) {
const router = useRouter();
@@ -122,10 +123,7 @@ function ProjectList({
onClick={() => router.push(`/${slug}`)}
>
<BlurImage
- src={
- logo ||
- `https://www.google.com/s2/favicons?sz=64&domain_url=${primaryDomain?.slug}`
- }
+ src={logo || `${GOOGLE_FAVICON_URL}${primaryDomain?.slug}`}
alt={slug}
className="h-7 w-7 overflow-hidden rounded-full"
width={48}
diff --git a/components/shared/modal.tsx b/components/shared/modal.tsx
index 2da5c12495..62ff466e04 100644
--- a/components/shared/modal.tsx
+++ b/components/shared/modal.tsx
@@ -26,8 +26,8 @@ export default function Modal({
}) {
const router = useRouter();
const { key } = router.query;
- const mobileModalRef = useRef(null);
- const desktopModalRef = useRef(null);
+ const mobileModalRef = useRef<HTMLDivElement | null>(null);
+ const desktopModalRef = useRef<HTMLDivElement | null>(null);
const closeModal = useCallback(
(closeWithX?: boolean) => {
@@ -65,7 +65,7 @@ export default function Modal({
async function handleDragEnd(_, info) {
const offset = info.offset.y;
const velocity = info.velocity.y;
- const height = mobileModalRef.current.getBoundingClientRect().height;
+ const height = mobileModalRef.current?.getBoundingClientRect().height || 0;
if (offset > height / 2 || velocity > 800) {
await controls.start({ y: "100%", transition: transitionProps });
closeModal();
diff --git a/components/shared/popover.tsx b/components/shared/popover.tsx
index 6237ff520f..20ec6bd7b5 100644
--- a/components/shared/popover.tsx
+++ b/components/shared/popover.tsx
@@ -19,14 +19,15 @@ export default function Popover({
}) {
const router = useRouter();
- const mobileTooltipRef = useRef(null);
+ const mobileTooltipRef = useRef<HTMLDivElement | null>(null);
const controls = useAnimation();
const transitionProps = { type: "spring", stiffness: 500, damping: 30 };
async function handleDragEnd(_, info) {
const offset = info.offset.y;
const velocity = info.velocity.y;
- const height = mobileTooltipRef.current.getBoundingClientRect().height;
+ const height =
+ mobileTooltipRef.current?.getBoundingClientRect().height || 0;
if (offset > height / 2 || velocity > 800) {
await controls.start({ y: "100%", transition: transitionProps });
setOpenPopover(false);
diff --git a/components/stats/devices.tsx b/components/stats/devices.tsx
index 60ce5f886c..e8c75b2896 100644
--- a/components/stats/devices.tsx
+++ b/components/stats/devices.tsx
@@ -1,4 +1,4 @@
-import { useState } from "react";
+import { useMemo, useState } from "react";
import { useRouter } from "next/router";
import { motion } from "framer-motion";
import BadgeSelect from "@/components/shared/badge-select";
@@ -65,8 +65,11 @@ export default function Devices() {
width: `${
(d.clicks /
(tab === "bot"
- ? data?.reduce((acc, curr) => acc + curr.clicks, 0)
- : totalClicks)) *
+ ? data?.reduce(
+ (acc, curr) => acc + curr.clicks,
+ 0,
+ ) || 0
+ : totalClicks || 0)) *
100
}%`,
}}
diff --git a/components/stats/locations.tsx b/components/stats/locations.tsx
index b81f0ce6d7..0fc038aea2 100644
--- a/components/stats/locations.tsx
+++ b/components/stats/locations.tsx
@@ -60,7 +60,7 @@ export default function Locations() {
</span>
<motion.div
style={{
- width: `${(clicks / totalClicks) * 100}%`,
+ width: `${(clicks / (totalClicks || 0)) * 100}%`,
}}
className="absolute h-8 origin-left bg-orange-100"
transition={{ ease: "easeOut", duration: 0.3 }}
diff --git a/components/stats/referer.tsx b/components/stats/referer.tsx
index c6a4b41fca..f8fbad9f50 100644
--- a/components/stats/referer.tsx
+++ b/components/stats/referer.tsx
@@ -6,6 +6,7 @@ import { nFormatter } from "@/lib/utils";
import useSWR from "swr";
import { fetcher } from "@/lib/utils";
import useEndpoint from "@/lib/hooks/use-endpoint";
+import { GOOGLE_FAVICON_URL } from "@/lib/constants";
export default function Referer() {
const router = useRouter();
@@ -44,7 +45,7 @@ export default function Referer() {
<Link className="h-4 w-4" />
) : (
<BlurImage
- src={`https://www.google.com/s2/favicons?sz=64&domain_url=${referer}`}
+ src={`${GOOGLE_FAVICON_URL}${referer}`}
alt={referer}
width={20}
height={20}
@@ -55,7 +56,7 @@ export default function Referer() {
</span>
<motion.div
style={{
- width: `${(clicks / totalClicks) * 100}%`,
+ width: `${(clicks / (totalClicks || 0)) * 100}%`,
}}
className="absolute h-8 origin-left rounded bg-red-100"
transition={{ ease: "easeOut", duration: 0.3 }}
diff --git a/lib/constants/index.ts b/lib/constants/index.ts
index 8dfed0d3e2..8295aad193 100644
--- a/lib/constants/index.ts
+++ b/lib/constants/index.ts
@@ -89,6 +89,8 @@ export const REDIRECT_HEADERS = {
};
export const FAVICON_FOLDER = "/_static/favicons";
+export const GOOGLE_FAVICON_URL =
+ "https://www.google.com/s2/favicons?sz=64&domain_url=";
export { default as COUNTRIES } from "./countries";
export { default as ccTLDs } from "./cctlds";
diff --git a/lib/cron/domains.tsx b/lib/cron/domains.tsx
index 6b5b58c351..95391763c5 100644
--- a/lib/cron/domains.tsx
+++ b/lib/cron/domains.tsx
@@ -20,7 +20,11 @@ export const handleDomainUpdates = async ({
linksCount: number;
}) => {
if (changed) {
- await log(`Domain *${domain}* changed status to *${verified}*`, "cron");
+ await log(
+ `Domain *${domain}* changed status to *${verified}*`,
+ "cron",
+ verified,
+ );
}
if (verified) return;
@@ -61,6 +65,7 @@ export const handleDomainUpdates = async ({
await log(
`Domain *${domain}* is invalid but not associated with any project, skipping.`,
"cron",
+ true,
);
return;
}
@@ -96,6 +101,7 @@ export const handleDomainUpdates = async ({
console.log(
`Domain *${domain}* has been invalid for > 30 days but has links, not deleting.`,
"cron",
+ true,
);
}
return;
diff --git a/lib/cron/usage.tsx b/lib/cron/usage.tsx
index d193b38da2..a769811fd3 100644
--- a/lib/cron/usage.tsx
+++ b/lib/cron/usage.tsx
@@ -53,6 +53,7 @@ export const updateUsage = async () => {
await log(
`${name} is over usage limit. Usage: ${usage}, Limit: ${usageLimit}`,
"cron",
+ true,
);
const sentFirstUsageLimitEmail = sentEmails.some(
(email) => email.type === "firstUsageLimitEmail",
diff --git a/lib/hooks/use-endpoint.ts b/lib/hooks/use-endpoint.ts
index 5653a0b555..c6bc163021 100644
--- a/lib/hooks/use-endpoint.ts
+++ b/lib/hooks/use-endpoint.ts
@@ -18,8 +18,8 @@ export default function useEndpoint(staticDomain?: string) {
const queryString =
interval || domainSlug
? `?${new URLSearchParams({
- interval,
- domain: domainSlug,
+ ...(interval && { interval }),
+ ...(domainSlug && { domain: domainSlug }),
}).toString()}`
: "";
diff --git a/lib/middleware/utils.ts b/lib/middleware/utils.ts
index 094259e2cf..509e32e261 100644
--- a/lib/middleware/utils.ts
+++ b/lib/middleware/utils.ts
@@ -2,7 +2,7 @@ import { NextRequest } from "next/server";
import { HOME_HOSTNAMES } from "@/lib/constants";
export const parse = (req: NextRequest) => {
- let domain = req.headers.get("host");
+ let domain = req.headers.get("host") as string;
domain = domain.replace("www.", ""); // remove www. from domain
if (HOME_HOSTNAMES.has(domain)) domain = "dub.sh";
const path = req.nextUrl.pathname;
diff --git a/lib/qr/index.tsx b/lib/qr/index.tsx
index a2ac0b9900..48f9ddff18 100644
--- a/lib/qr/index.tsx
+++ b/lib/qr/index.tsx
@@ -1,3 +1,5 @@
+// @ts-nocheck
+
/**
* @license qrcode.react
* Copyright (c) Paul O'Shannessy
diff --git a/lib/utils.ts b/lib/utils.ts
index 5bd90e22d3..1a9c2b2568 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -363,9 +363,14 @@ export async function generateMD5Hash(message) {
const logTypeToEnv = {
cron: process.env.DUB_SLACK_HOOK_CRON,
links: process.env.DUB_SLACK_HOOK_LINKS,
+ error: process.env.DUB_SLACK_HOOK_ERROR,
};
-export const log = async (message: string, type: "cron" | "links") => {
+export const log = async (
+ message: string,
+ type: "cron" | "links" | "error",
+ mention?: boolean,
+) => {
/* Log a message to the console */
const HOOK = logTypeToEnv[type];
if (!HOOK) return;
@@ -381,7 +386,7 @@ export const log = async (message: string, type: "cron" | "links") => {
type: "section",
text: {
type: "mrkdwn",
- text: message,
+ text: `${mention ? "<@U0404G6J3NJ> " : ""}${message}`,
},
},
],
diff --git a/pages/_proxy/[domain]/[key].tsx b/pages/_proxy/[domain]/[key].tsx
index 8dc8f16d78..feb616af65 100644
--- a/pages/_proxy/[domain]/[key].tsx
+++ b/pages/_proxy/[domain]/[key].tsx
@@ -3,6 +3,7 @@ import Head from "next/head";
import { unescape } from "html-escaper";
import prisma from "@/lib/prisma";
import { getApexDomain } from "@/lib/utils";
+import { GOOGLE_FAVICON_URL } from "@/lib/constants";
export default function LinkPage({
shortLink,
@@ -35,9 +36,7 @@ export default function LinkPage({
<meta charSet="utf-8" />
<link
rel="icon"
- href={`https://www.google.com/s2/favicons?sz=64&domain_url=${unescape(
- apexDomain,
- )}`}
+ href={`${GOOGLE_FAVICON_URL}${unescape(apexDomain)}`}
/>
</Head>
<main className="flex h-screen w-screen items-center justify-center">
@@ -51,9 +50,7 @@ export default function LinkPage({
/>
<div className="flex space-x-3 bg-gray-100 p-5">
<Image
- src={`https://www.google.com/s2/favicons?sz=64&domain_url=${unescape(
- apexDomain,
- )}`}
+ src={`${GOOGLE_FAVICON_URL}${unescape(apexDomain)}`}
alt={title}
width={300}
height={300}
diff --git a/pages/api/auth/[...nextauth].tsx b/pages/api/auth/[...nextauth].tsx
index 3e68398923..7ce85ec490 100644
--- a/pages/api/auth/[...nextauth].tsx
+++ b/pages/api/auth/[...nextauth].tsx
@@ -38,13 +38,13 @@ export const authOptions: NextAuthOptions = {
},
callbacks: {
signIn: async ({ user }) => {
- if (await isBlacklistedEmail(user.email)) {
+ if (!user.email || (await isBlacklistedEmail(user.email))) {
return false;
}
return true;
},
jwt: async ({ token, account }) => {
- if (await isBlacklistedEmail(token.email)) {
+ if (!token.email || (await isBlacklistedEmail(token.email))) {
return {};
}
if (account) {
@@ -64,7 +64,7 @@ export const authOptions: NextAuthOptions = {
events: {
async signIn(message) {
if (message.isNewUser) {
- const email = message.user.email;
+ const email = message.user.email as string;
await sendMarketingMail({
subject: "✨ Welcome to Dub",
to: email,
diff --git a/pages/api/auth/account-exists.ts b/pages/api/auth/account-exists.ts
index 1dc92f608f..dbefcfa831 100644
--- a/pages/api/auth/account-exists.ts
+++ b/pages/api/auth/account-exists.ts
@@ -18,6 +18,12 @@ export default async function handler(req: NextRequest) {
const { email } = (await req.json()) as { email: string };
+ if (!conn) {
+ return new Response("Database connection not established", {
+ status: 500,
+ });
+ }
+
const user = await conn
.execute("SELECT email FROM User WHERE email = ?", [email])
.then((res) => res.rows[0]);
diff --git a/pages/api/auth/decrypt-password.ts b/pages/api/auth/decrypt-password.ts
index ca8bbb34fc..7758b21a2f 100644
--- a/pages/api/auth/decrypt-password.ts
+++ b/pages/api/auth/decrypt-password.ts
@@ -7,10 +7,14 @@ export default async function handler(
) {
if (req.method === "POST") {
const { domain, key, password } = req.body;
- const { url, password: realPassword } = await prisma.link.findUnique({
+ const link = await prisma.link.findUnique({
where: { domain_key: { domain, key } },
select: { url: true, password: true },
});
+ if (!link) {
+ return res.status(404).json({ error: "Link not found" });
+ }
+ const { url, password: realPassword } = link;
const validPassword = password === realPassword;
if (validPassword) {
return res.status(200).json({ url });
diff --git a/pages/api/edge/metatags.ts b/pages/api/edge/metatags.ts
index 7430aadc88..c7476da7ce 100644
--- a/pages/api/edge/metatags.ts
+++ b/pages/api/edge/metatags.ts
@@ -43,17 +43,27 @@ export default async function handler(req: NextRequest, ev: NextFetchEvent) {
}
const getHtml = async (url: string) => {
- const controller = new AbortController();
- const timeoutId = setTimeout(() => controller.abort(), 5000); // timeout if it takes longer than 5 seconds
- return await fetch(url, {
- signal: controller.signal,
- headers: {
- "User-Agent": "dub-bot/1.0",
- },
- }).then((res) => {
+ try {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 5000); // timeout if it takes longer than 5 seconds
+ const response = await fetch(url, {
+ signal: controller.signal,
+ headers: {
+ "User-Agent": "dub-bot/1.0",
+ },
+ });
clearTimeout(timeoutId);
- return res.text();
- });
+ return await response.text();
+ } catch (error) {
+ if (error.name === "AbortError") {
+ // Handle fetch request abort (e.g., due to timeout)
+ console.error("Fetch request aborted due to timeout.");
+ } else {
+ // Handle other fetch errors
+ console.error("Fetch request failed:", error);
+ }
+ return null;
+ }
};
const getHeadChildNodes = (html) => {
@@ -91,6 +101,13 @@ const getRelativeUrl = (url: string, imageUrl: string) => {
export const getMetaTags = async (url: string, ev: NextFetchEvent) => {
const html = await getHtml(url);
+ if (!html) {
+ return {
+ title: url,
+ description: "No description",
+ image: null,
+ };
+ }
const { metaTags, title: titleTag, linkTags } = getHeadChildNodes(html);
let object = {};
@@ -126,8 +143,8 @@ export const getMetaTags = async (url: string, ev: NextFetchEvent) => {
);
return {
- title,
- description,
+ title: title || url,
+ description: description || "No description",
image: getRelativeUrl(url, image),
};
};
diff --git a/pages/api/links/[key]/index.ts b/pages/api/links/[key]/index.ts
index 211e3bd277..712bdc5e39 100644
--- a/pages/api/links/[key]/index.ts
+++ b/pages/api/links/[key]/index.ts
@@ -2,7 +2,8 @@ import { NextApiRequest, NextApiResponse } from "next";
import { deleteLink, editLink } from "@/lib/api/links";
import { Session, withUserAuth } from "@/lib/auth";
import prisma from "@/lib/prisma";
-import { isBlacklistedDomain, isBlacklistedKey } from "@/lib/utils";
+import { isBlacklistedDomain, isBlacklistedKey, log } from "@/lib/utils";
+import { GOOGLE_FAVICON_URL } from "@/lib/constants";
export const config = {
api: {
@@ -27,7 +28,7 @@ export default withUserAuth(
},
});
- const isOwner = link.userId === session.user.id;
+ const isOwner = link?.userId === session.user.id;
if (!isOwner) {
return res.status(403).json({ error: "Not authorized" });
@@ -50,17 +51,29 @@ export default withUserAuth(
if (domainBlacklisted) {
return res.status(400).json({ error: "Invalid url" });
}
- const response = await editLink(
- {
- domain,
- ...req.body,
- userId: session.user.id,
- },
- oldKey,
- );
+ const [response, invalidFavicon] = await Promise.allSettled([
+ editLink(
+ {
+ domain,
+ ...req.body,
+ userId: session.user.id,
+ },
+ oldKey,
+ ),
+ fetch(`${GOOGLE_FAVICON_URL}${url}}`).then((res) => !res.ok),
+ // @ts-ignore
+ ]).then((results) => results.map((result) => result.value));
+
if (response === null) {
return res.status(400).json({ error: "Key already exists" });
}
+ await log(
+ `*${session.user.email}* edited a link (*dub.sh${key}*) to the ${url} ${
+ invalidFavicon ? " but it has an invalid favicon :thinking_face:" : ""
+ }`,
+ "links",
+ invalidFavicon ? true : false,
+ );
return res.status(200).json(response);
} else if (req.method === "DELETE") {
const response = await deleteLink(domain, oldKey);
diff --git a/pages/api/links/index.ts b/pages/api/links/index.ts
index d5ad9a2062..a3419753e4 100644
--- a/pages/api/links/index.ts
+++ b/pages/api/links/index.ts
@@ -3,7 +3,7 @@ import { addLink, getLinksForProject } from "@/lib/api/links";
import { Session, withUserAuth } from "@/lib/auth";
import { isBlacklistedDomain, isBlacklistedKey } from "@/lib/utils";
import { log } from "@/lib/utils";
-import { DUB_PROJECT_ID } from "@/lib/constants";
+import { DUB_PROJECT_ID, GOOGLE_FAVICON_URL } from "@/lib/constants";
export const config = {
api: {
@@ -48,17 +48,29 @@ export default withUserAuth(
if (domainBlacklisted) {
return res.status(400).json({ error: "Invalid url" });
}
- const response = await addLink({
- ...req.body,
- domain: "dub.sh",
- projectId: DUB_PROJECT_ID,
- userId: session.user.id,
- });
+ const [response, invalidFavicon] = await Promise.allSettled([
+ addLink({
+ ...req.body,
+ domain: "dub.sh",
+ projectId: DUB_PROJECT_ID,
+ userId: session.user.id,
+ }),
+ fetch(`${GOOGLE_FAVICON_URL}${url}}`).then((res) => !res.ok),
+ // @ts-ignore
+ ]).then((results) => results.map((result) => result.value));
if (response === null) {
return res.status(403).json({ error: "Key already exists" });
}
- await log(`${session.user.email} created a new link for ${url}`, "links");
+ await log(
+ `*${
+ session.user.email
+ }* created a new link (*dub.sh${key}*) for ${url} ${
+ invalidFavicon ? " but it has an invalid favicon :thinking_face:" : ""
+ }`,
+ "links",
+ invalidFavicon ? true : false,
+ );
return res.status(200).json(response);
} else {
res.setHeader("Allow", ["GET", "POST"]);
diff --git a/pages/api/links/random.ts b/pages/api/links/random.ts
index ae6a170e94..d77dbc3c3d 100644
--- a/pages/api/links/random.ts
+++ b/pages/api/links/random.ts
@@ -7,7 +7,6 @@ export default async function handler(
) {
if (req.method === "GET") {
const response = await getRandomKey("dub.sh");
- console.log(response);
return res.status(200).json(response);
} else {
res.setHeader("Allow", ["GET"]);
diff --git a/pages/api/projects/[slug]/domains/[domain]/verify.ts b/pages/api/projects/[slug]/domains/[domain]/verify.ts
index eacd748610..85600e43b3 100644
--- a/pages/api/projects/[slug]/domains/[domain]/verify.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/verify.ts
@@ -55,7 +55,7 @@ export default withProjectAuth(async (req, res) => {
});
}
- let prismaResponse = null;
+ let prismaResponse: any = null;
if (!configJson.misconfigured) {
prismaResponse = await prisma.domain.update({
where: {
diff --git a/pages/api/stripe/webhook.ts b/pages/api/stripe/webhook.ts
index 25687961b1..c6dab82b02 100644
--- a/pages/api/stripe/webhook.ts
+++ b/pages/api/stripe/webhook.ts
@@ -15,7 +15,7 @@ export const config = {
};
async function buffer(readable: Readable) {
- const chunks = [];
+ const chunks: Buffer[] = [];
for await (const chunk of readable) {
chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
}
@@ -50,6 +50,24 @@ export default async function webhookHandler(
if (event.type === "checkout.session.completed") {
const checkoutSession = event.data.object as Stripe.Checkout.Session;
+ if (checkoutSession.client_reference_id === null) {
+ await log(
+ "Missing client reference ID in Stripe webhook callback",
+ "cron",
+ true,
+ );
+ return;
+ }
+
+ if (checkoutSession.customer === null) {
+ await log(
+ "Missing customer ID in Stripe webhook callback",
+ "cron",
+ true,
+ );
+ return;
+ }
+
// when the project subscribes to a plan, set their stripe customer ID
// in the database for easy identification in future webhook events
// also update the billingCycleStart to today's date
@@ -74,7 +92,7 @@ export default async function webhookHandler(
(plan) =>
plan.price.monthly.priceIds[env] === newPriceId ||
plan.price.yearly.priceIds[env] === newPriceId,
- );
+ )!;
const usageLimit = plan.quota;
const stripeId = subscriptionUpdated.customer.toString();
@@ -105,6 +123,15 @@ export default async function webhookHandler(
},
});
+ if (!project) {
+ await log(
+ "Project not found in Stripe webhook `customer.subscription.deleted` callback",
+ "cron",
+ true,
+ );
+ return;
+ }
+
const projectDomains = project.domains.map((domain) => domain.slug);
const pipeline = redis.pipeline();
@@ -126,15 +153,19 @@ export default async function webhookHandler(
pipeline.exec(),
log(
":cry: Project *`" + name + "`* deleted their subscription",
- "links",
+ "cron",
+ true,
),
]);
- console.log(response);
} else {
throw new Error("Unhandled relevant event!");
}
} catch (error) {
- console.log(error);
+ await log(
+ `Stripe wekbook failed. Error: ${error.message}`,
+ "cron",
+ true,
+ );
return res
.status(400)
.send('Webhook error: "Webhook handler failed. View logs."');
diff --git a/pages/metatags.tsx b/pages/metatags.tsx
index 01b8266b79..47c0e1477f 100644
--- a/pages/metatags.tsx
+++ b/pages/metatags.tsx
@@ -11,7 +11,6 @@ import getTweetsMetadata from "@/lib/twitter";
import Tweet from "@/components/shared/tweet";
import { useMemo, useState } from "react";
import Background from "@/components/shared/background";
-import Meta from "@/components/layout/meta";
import { useDebounce } from "use-debounce";
import { fetcher, getDomainWithoutWWW, getUrlFromString } from "@/lib/utils";
import useSWR from "swr";
@@ -20,7 +19,7 @@ export default function Metatags({ tweets }: { tweets: any }) {
const [url, setUrl] = useState("https://github.com/steven-tey/dub");
const [debouncedUrl] = useDebounce(getUrlFromString(url), 500);
const hostname = useMemo(() => {
- return getDomainWithoutWWW(debouncedUrl);
+ return getDomainWithoutWWW(debouncedUrl || "");
}, [debouncedUrl]);
const { data, isValidating } = useSWR<{
@@ -115,7 +114,7 @@ export default function Metatags({ tweets }: { tweets: any }) {
<div className="mb-1 h-4 w-full rounded-md bg-gray-100" />
)}
{description ? (
- <p className="text-sm text-[#536471] line-clamp-2">
+ <p className="line-clamp-2 text-sm text-[#536471]">
{description}
</p>
) : (
@@ -128,7 +127,7 @@ export default function Metatags({ tweets }: { tweets: any }) {
</div>
<button
- className="hover:bg/black-[0.08] group relative flex cursor-copy items-center space-x-5 rounded-full bg-black/5 py-2.5 pr-3 pl-5 transition-all"
+ className="hover:bg/black-[0.08] group relative flex cursor-copy items-center space-x-5 rounded-full bg-black/5 py-2.5 pl-5 pr-3 transition-all"
onClick={() => {
navigator.clipboard.writeText(
`https://api.dub.sh/metatags?url=${getUrlFromString(url)}`,
@@ -145,7 +144,7 @@ export default function Metatags({ tweets }: { tweets: any }) {
<span className="text-amber-600">{getUrlFromString(url)}</span>
</p>
</div>
- <span className="absolute inset-y-0 top-1 right-1 flex h-8 w-8 items-center justify-center rounded-full bg-black/[0.07] transition-all group-hover:bg-black/10">
+ <span className="absolute inset-y-0 right-1 top-1 flex h-8 w-8 items-center justify-center rounded-full bg-black/[0.07] transition-all group-hover:bg-black/10">
{copied ? (
<Tick className="h-4 w-4 text-gray-700" />
) : (
diff --git a/pages/sitemap.xml.tsx b/pages/sitemap.xml.tsx
index 23f952843e..ef8908d496 100644
--- a/pages/sitemap.xml.tsx
+++ b/pages/sitemap.xml.tsx
@@ -46,7 +46,7 @@ export async function getServerSideProps({
req: NextApiRequest;
res: NextApiResponse;
}) {
- let domain = req.headers.host;
+ let domain = req.headers.host as string;
if (isHomeHostname(domain)) domain = "dub.sh";
// Get top 100 links (sorted by clicks in descending order)
diff --git a/pages/stats/[key].tsx b/pages/stats/[key].tsx
index e5c78c9d3d..14438be7ae 100644
--- a/pages/stats/[key].tsx
+++ b/pages/stats/[key].tsx
@@ -37,7 +37,7 @@ export const getServerSideProps: GetServerSideProps = async ({
params,
}) => {
const { key } = params as { key: string };
- let domain = req.headers.host;
+ let domain = req.headers.host as string;
if (isHomeHostname(domain)) domain = "dub.sh";
const data = await getLinkViaEdge(domain, key);
diff --git a/tsconfig.json b/tsconfig.json
index 068302c0ed..143c701255 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -31,5 +31,5 @@
]
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
- "exclude": ["node_modules"]
+ "exclude": ["node_modules", "pages/api/scripts"]
}