Skip to content

Commit

Permalink
refactor: replace isValidUrl with URL.canParse for URL validation
Browse files Browse the repository at this point in the history
  • Loading branch information
michaltarasiuk committed Dec 21, 2024
1 parent d571cc3 commit 7db1fb0
Show file tree
Hide file tree
Showing 11 changed files with 21 additions and 40 deletions.
4 changes: 2 additions & 2 deletions apps/web/app/api/metatags/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { recordMetatags } from "@/lib/upstash";
import { fetchWithTimeout, isValidUrl } from "@dub/utils";
import { fetchWithTimeout } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import he from "he";
import { parse } from "node-html-parser";
Expand Down Expand Up @@ -39,7 +39,7 @@ export const getRelativeUrl = (url: string, imageUrl: string) => {
if (!imageUrl) {
return null;
}
if (isValidUrl(imageUrl)) {
if (URL.canParse(imageUrl)) {
return imageUrl;
}
const { protocol, host } = new URL(url);
Expand Down
4 changes: 2 additions & 2 deletions apps/web/app/api/track/click/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { parseRequestBody } from "@/lib/api/utils";
import { getLinkViaEdge } from "@/lib/planetscale";
import { recordClick } from "@/lib/tinybird";
import { ratelimit, redis } from "@/lib/upstash";
import { isValidUrl, LOCALHOST_IP, nanoid } from "@dub/utils";
import { LOCALHOST_IP, nanoid } from "@dub/utils";
import { ipAddress, waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";

Expand Down Expand Up @@ -48,7 +48,7 @@ export const POST = async (req: Request) => {
});
}

const finalUrl = isValidUrl(url) ? url : link.url;
const finalUrl = URL.canParse(url) ? url : link.url;

const cacheKey = `recordClick:${link.id}:${ip}`;

Expand Down
5 changes: 2 additions & 3 deletions apps/web/lib/api/links/process-link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import {
getDomainWithoutWWW,
getUrlFromString,
isDubDomain,
isValidUrl,
log,
parseDateTime,
pluralize,
Expand Down Expand Up @@ -78,7 +77,7 @@ export async function processLink<T extends Record<string, any>>({
// if URL is defined, perform URL checks
if (url) {
url = getUrlFromString(url);
if (!isValidUrl(url)) {
if (!URL.canParse(url)) {
return {
link: payload,
error: "Invalid destination URL",
Expand Down Expand Up @@ -453,7 +452,7 @@ export async function processLink<T extends Record<string, any>>({
expiresAt = datetime;
if (expiredUrl) {
expiredUrl = getUrlFromString(expiredUrl);
if (!isValidUrl(expiredUrl)) {
if (!URL.canParse(expiredUrl)) {
return {
link: payload,
error: "Invalid expired URL.",
Expand Down
4 changes: 2 additions & 2 deletions apps/web/lib/zod/schemas/utils.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import z from "@/lib/zod";
import { getUrlFromString, isValidUrl, parseDateTime } from "@dub/utils";
import { getUrlFromString, parseDateTime } from "@dub/utils";

export const parseUrlSchema = z
.string()
.transform((v) => getUrlFromString(v))
.refine((v) => isValidUrl(v), { message: "Invalid URL" });
.refine((v) => URL.canParse(v), { message: "Invalid URL" });

export const parseUrlSchemaAllowEmpty = ({
maxLength,
Expand Down
3 changes: 1 addition & 2 deletions apps/web/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import {
API_HOSTNAMES,
APP_HOSTNAMES,
DEFAULT_REDIRECTS,
isValidUrl,
} from "@dub/utils";
import { PARTNERS_HOSTNAMES } from "@dub/utils/src/constants";
import { NextFetchEvent, NextRequest, NextResponse } from "next/server";
Expand Down Expand Up @@ -65,7 +64,7 @@ export default async function middleware(req: NextRequest, ev: NextFetchEvent) {
return PartnersMiddleware(req);
}

if (isValidUrl(fullKey)) {
if (URL.canParse(fullKey)) {
return CreateLinkMiddleware(req);
}

Expand Down
5 changes: 2 additions & 3 deletions apps/web/ui/modals/link-builder/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import {
DEFAULT_LINK_PROPS,
getApexDomain,
getUrlWithoutUTMParams,
isValidUrl,
linkConstructor,
} from "@dub/utils";
import { useParams, useSearchParams } from "next/navigation";
Expand Down Expand Up @@ -401,7 +400,7 @@ function LinkBuilderInner({
error={errors.url?.message || undefined}
right={
<div className="-mb-1 h-6">
{isValidUrl(url) && (
{URL.canParse(url) && (
<UTMTemplatesButton
onLoad={(params) => {
setValue(
Expand Down Expand Up @@ -556,7 +555,7 @@ export function CreateLinkButton({
// - workspace has not exceeded links limit
if (
pastedContent &&
isValidUrl(pastedContent) &&
URL.canParse(pastedContent) &&
target.tagName !== "INPUT" &&
target.tagName !== "TEXTAREA" &&
!existingModalBackdrop &&
Expand Down
4 changes: 2 additions & 2 deletions apps/web/ui/modals/link-builder/options-list.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { AlertCircleFill, CheckCircleFill, X } from "@/ui/shared/icons";
import { Tooltip, useMediaQuery } from "@dub/ui";
import { LoadingSpinner } from "@dub/ui/icons";
import { cn, fetcher, isValidUrl as isValidUrlFn } from "@dub/utils";
import { cn, fetcher } from "@dub/utils";
import { AnimatePresence, motion } from "framer-motion";
import { ReactNode, useMemo } from "react";
import { useFormContext } from "react-hook-form";
Expand Down Expand Up @@ -102,7 +102,7 @@ function LinkCloakingToggleBadge({
const [url, domain] = watch(["url", "domain"]);
const [debouncedUrl] = useDebounce(url, 500);
const isValidUrl = useMemo(
() => debouncedUrl && isValidUrlFn(debouncedUrl),
() => debouncedUrl && URL.canParse(debouncedUrl),
[debouncedUrl],
);

Expand Down
3 changes: 1 addition & 2 deletions apps/web/ui/modals/link-builder/targeting-modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import {
constructURLFromUTMParams,
COUNTRIES,
getParamsFromURL,
isValidUrl,
pluralize,
} from "@dub/utils";
import {
Expand Down Expand Up @@ -74,7 +73,7 @@ function TargetingModal({
// Get UTM parameters from the parent URL that need to be added on blur
const getNewParams = useCallback(
(targetURL: string) => {
if (!targetURL?.trim() || !isValidUrl(targetURL)) return;
if (!targetURL?.trim() || !URL.canParse(targetURL)) return;

const parentUrl = getValuesParent("url");
const parentParams = getParamsFromURL(parentUrl);
Expand Down
13 changes: 4 additions & 9 deletions apps/web/ui/modals/link-builder/utm-modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,7 @@ import {
UTM_PARAMETERS,
UTMBuilder,
} from "@dub/ui";
import {
cn,
constructURLFromUTMParams,
getParamsFromURL,
isValidUrl,
} from "@dub/utils";
import { cn, constructURLFromUTMParams, getParamsFromURL } from "@dub/utils";
import {
Dispatch,
SetStateAction,
Expand Down Expand Up @@ -213,15 +208,15 @@ function UTMModalInner({ setShowUTMModal }: UTMModalProps) {
);
}}
disabledTooltip={
isValidUrl(url)
URL.canParse(url)
? undefined
: "Enter a destination URL to add UTM parameters"
}
autoFocus
/>
</div>

{isValidUrl(url) && (
{URL.canParse(url) && (
<div className="mt-4 grid gap-y-1">
<span className="block text-sm font-medium text-gray-700">
URL Preview
Expand All @@ -242,7 +237,7 @@ function UTMModalInner({ setShowUTMModal }: UTMModalProps) {
});
}}
disabledTooltip={
isValidUrl(url)
URL.canParse(url)
? undefined
: "Enter a destination URL to use UTM templates"
}
Expand Down
3 changes: 1 addition & 2 deletions packages/utils/src/functions/domains.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
SPECIAL_APEX_DOMAINS,
ccTLDs,
} from "../constants";
import { isValidUrl } from "./urls";

export const generateDomainFromName = (name: string) => {
const normalizedName = slugify(name, { separator: "" });
Expand Down Expand Up @@ -70,7 +69,7 @@ export const getApexDomain = (url: string) => {
};

export const getDomainWithoutWWW = (url: string) => {
if (isValidUrl(url)) {
if (URL.canParse(url)) {
return new URL(url).hostname.replace(/^www\./, "");
}
try {
Expand Down
13 changes: 2 additions & 11 deletions packages/utils/src/functions/urls.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,5 @@
export const isValidUrl = (url: string) => {
try {
new URL(url);
return true;
} catch (e) {
return false;
}
};

export const getUrlFromString = (str: string) => {
if (isValidUrl(str)) return str;
if (URL.canParse(str)) return str;
try {
if (str.includes(".") && !str.includes(" ")) {
return new URL(`https://${str}`).toString();
Expand All @@ -18,7 +9,7 @@ export const getUrlFromString = (str: string) => {
};

export const getUrlFromStringIfValid = (str: string) => {
if (isValidUrl(str)) return str;
if (URL.canParse(str)) return str;
try {
if (str.includes(".") && !str.includes(" ")) {
return new URL(`https://${str}`).toString();
Expand Down

0 comments on commit 7db1fb0

Please sign in to comment.