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.

Convert utils to individual files, add fetchWithTimeout

Steven Teyf4e13fa01d29
diff --git a/apps/web/app/api/edge/metatags/utils.ts b/apps/web/app/api/edge/metatags/utils.ts
index 20ecc9dda8..c80aa91fbb 100644
--- a/apps/web/app/api/edge/metatags/utils.ts
+++ b/apps/web/app/api/edge/metatags/utils.ts
@@ -1,31 +1,17 @@
import { parse } from "node-html-parser";
import he from "he";
import { recordMetatags } from "@/lib/upstash";
-import { isValidUrl } from "@dub/utils";
+import { fetchWithTimeout, isValidUrl } from "@dub/utils";
import { internal_runWithWaitUntil as waitUntil } from "next/dist/server/web/internal-edge-wait-until";
export const getHtml = async (url: string) => {
- 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 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;
- }
+ return await fetchWithTimeout(url, {
+ headers: {
+ "User-Agent": "dub-bot/1.0",
+ },
+ })
+ .then((r) => r.text())
+ .catch(() => null);
};
export const getHeadChildNodes = (html) => {
diff --git a/apps/web/app/api/projects/[slug]/import/short/route.ts b/apps/web/app/api/projects/[slug]/import/short/route.ts
index 8d603696a5..626266360a 100644
--- a/apps/web/app/api/projects/[slug]/import/short/route.ts
+++ b/apps/web/app/api/projects/[slug]/import/short/route.ts
@@ -3,7 +3,7 @@ import { withAuth } from "@/lib/auth";
import { qstash } from "@/lib/cron";
import prisma from "@/lib/prisma";
import { redis } from "@/lib/upstash";
-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { APP_DOMAIN_WITH_NGROK, fetchWithTimeout } from "@dub/utils";
import { NextResponse } from "next/server";
// GET /api/projects/[slug]/import/short – get all short.io domains for a project
@@ -28,7 +28,7 @@ export const GET = withAuth(async ({ project }) => {
data.map(async ({ id, hostname }: { id: number; hostname: string }) => ({
id,
domain: hostname,
- links: await fetch(
+ links: await fetchWithTimeout(
`https://api-v2.short.cm/statistics/domain/${id}?period=total`,
{
headers: {
@@ -39,7 +39,7 @@ export const GET = withAuth(async ({ project }) => {
)
.then((r) => r.json())
.then((data) => data.links - 1) // subtract 1 to exclude root domain
- .catch((e) => 0),
+ .catch(() => 0),
})),
);
diff --git a/packages/utils/src/constants/cctlds.ts b/packages/utils/src/constants/cctlds.ts
index 44ac32c872..a21b615315 100644
--- a/packages/utils/src/constants/cctlds.ts
+++ b/packages/utils/src/constants/cctlds.ts
@@ -1,4 +1,4 @@
-const ccTLDs = new Set([
+export const ccTLDs = new Set([
"af",
"ax",
"al",
@@ -272,5 +272,3 @@ const ccTLDs = new Set([
"zm",
"zw",
]);
-
-export default ccTLDs;
diff --git a/packages/utils/src/constants/countries.ts b/packages/utils/src/constants/countries.ts
index d8b7f4faa8..bfedee0579 100644
--- a/packages/utils/src/constants/countries.ts
+++ b/packages/utils/src/constants/countries.ts
@@ -1,4 +1,4 @@
-const COUNTRIES: { [key: string]: string } = {
+export const COUNTRIES: { [key: string]: string } = {
AF: "Afghanistan",
AL: "Albania",
DZ: "Algeria",
@@ -250,5 +250,3 @@ const COUNTRIES: { [key: string]: string } = {
SS: "South Sudan",
XK: "Kosovo",
};
-
-export default COUNTRIES;
diff --git a/packages/utils/src/constants/index.ts b/packages/utils/src/constants/index.ts
index d85ae489e4..00389f9b75 100644
--- a/packages/utils/src/constants/index.ts
+++ b/packages/utils/src/constants/index.ts
@@ -1,5 +1,5 @@
-export { default as ccTLDs } from "./cctlds";
-export { default as COUNTRIES } from "./countries";
+export * from "./cctlds";
+export * from "./countries";
export * from "./pricing";
export const LOCALHOST_GEO_DATA = {
diff --git a/packages/utils/src/functions/capitalize.ts b/packages/utils/src/functions/capitalize.ts
new file mode 100644
index 0000000000..d38b9985ec
--- /dev/null
+++ b/packages/utils/src/functions/capitalize.ts
@@ -0,0 +1,4 @@
+export function capitalize(str?: string | null) {
+ if (!str || typeof str !== "string") return str;
+ return str.charAt(0).toUpperCase() + str.slice(1);
+}
diff --git a/packages/utils/src/functions/chunk.ts b/packages/utils/src/functions/chunk.ts
new file mode 100644
index 0000000000..8336625937
--- /dev/null
+++ b/packages/utils/src/functions/chunk.ts
@@ -0,0 +1,13 @@
+export const chunk = <T>(array: T[], chunk_size: number): T[][] => {
+ return array.reduce((resultArray, item, index) => {
+ const chunkIndex = Math.floor(index / chunk_size);
+
+ if (!resultArray[chunkIndex]) {
+ resultArray[chunkIndex] = []; // start a new chunk
+ }
+
+ resultArray[chunkIndex].push(item);
+
+ return resultArray;
+ }, [] as T[][]);
+};
diff --git a/packages/utils/src/functions/cn.ts b/packages/utils/src/functions/cn.ts
new file mode 100644
index 0000000000..a5ef193506
--- /dev/null
+++ b/packages/utils/src/functions/cn.ts
@@ -0,0 +1,6 @@
+import { clsx, type ClassValue } from "clsx";
+import { twMerge } from "tailwind-merge";
+
+export function cn(...inputs: ClassValue[]) {
+ return twMerge(clsx(inputs));
+}
diff --git a/packages/utils/src/functions/construct-metadata.ts b/packages/utils/src/functions/construct-metadata.ts
new file mode 100644
index 0000000000..2bacc0db94
--- /dev/null
+++ b/packages/utils/src/functions/construct-metadata.ts
@@ -0,0 +1,63 @@
+import { Metadata } from "next";
+import { HOME_DOMAIN } from "../constants";
+
+export function constructMetadata({
+ title = `${process.env.NEXT_PUBLIC_APP_NAME} - Link Management for Modern Marketing Teams`,
+ description = `${process.env.NEXT_PUBLIC_APP_NAME} is the open-source link management infrastructure for modern marketing teams to create, share, and track short links.`,
+ image = "https://dub.co/_static/thumbnail.png",
+ icons = [
+ {
+ rel: "apple-touch-icon",
+ sizes: "32x32",
+ url: "/apple-touch-icon.png",
+ },
+ {
+ rel: "icon",
+ type: "image/png",
+ sizes: "32x32",
+ url: "/favicon-32x32.png",
+ },
+ {
+ rel: "icon",
+ type: "image/png",
+ sizes: "16x16",
+ url: "/favicon-16x16.png",
+ },
+ ],
+ noIndex = false,
+}: {
+ title?: string;
+ description?: string;
+ image?: string;
+ icons?: Metadata["icons"];
+ noIndex?: boolean;
+} = {}): Metadata {
+ return {
+ title,
+ description,
+ openGraph: {
+ title,
+ description,
+ images: [
+ {
+ url: image,
+ },
+ ],
+ },
+ twitter: {
+ card: "summary_large_image",
+ title,
+ description,
+ images: [image],
+ creator: "@dubdotco",
+ },
+ icons,
+ metadataBase: new URL(HOME_DOMAIN),
+ ...(noIndex && {
+ robots: {
+ index: false,
+ follow: false,
+ },
+ }),
+ };
+}
diff --git a/packages/utils/src/functions/datetime.ts b/packages/utils/src/functions/datetime.ts
new file mode 100644
index 0000000000..fdae91392c
--- /dev/null
+++ b/packages/utils/src/functions/datetime.ts
@@ -0,0 +1,74 @@
+export const getDateTimeLocal = (timestamp?: Date): string => {
+ const d = timestamp ? new Date(timestamp) : new Date();
+ if (d.toString() === "Invalid Date") return "";
+ return new Date(d.getTime() - d.getTimezoneOffset() * 60000)
+ .toISOString()
+ .split(":")
+ .slice(0, 2)
+ .join(":");
+};
+
+export const formatDate = (dateString: string) => {
+ return new Date(`${dateString}T00:00:00Z`).toLocaleDateString("en-US", {
+ day: "numeric",
+ month: "long",
+ year: "numeric",
+ timeZone: "UTC",
+ });
+};
+
+export const getFirstAndLastDay = (day: number) => {
+ const today = new Date();
+ const currentDay = today.getDate();
+ const currentMonth = today.getMonth();
+ const currentYear = today.getFullYear();
+ if (currentDay >= day) {
+ // if the current day is greater than target day, it means that we just passed it
+ return {
+ firstDay: new Date(currentYear, currentMonth, day),
+ lastDay: new Date(currentYear, currentMonth + 1, day - 1),
+ };
+ } else {
+ // if the current day is less than target day, it means that we haven't passed it yet
+ const lastYear = currentMonth === 0 ? currentYear - 1 : currentYear; // if the current month is January, we need to go back a year
+ const lastMonth = currentMonth === 0 ? 11 : currentMonth - 1; // if the current month is January, we need to go back to December
+ return {
+ firstDay: new Date(lastYear, lastMonth, day),
+ lastDay: new Date(currentYear, currentMonth, day - 1),
+ };
+ }
+};
+
+// Function to get the last day of the current month
+export const getLastDayOfMonth = () => {
+ const today = new Date();
+ const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0); // This will give the last day of the current month
+ return lastDay.getDate();
+};
+
+// Adjust the billingCycleStart based on the number of days in the current month
+export const getAdjustedBillingCycleStart = (billingCycleStart: number) => {
+ const lastDay = getLastDayOfMonth();
+ if (billingCycleStart > lastDay) {
+ return lastDay;
+ } else {
+ return billingCycleStart;
+ }
+};
+
+export const getBillingStartDate = (billingCycleStart: number) => {
+ const today = new Date();
+ const currentDay = today.getDate();
+ const currentMonth = today.getMonth();
+ const currentYear = today.getFullYear();
+ const adjustedBillingCycleStart =
+ getAdjustedBillingCycleStart(billingCycleStart);
+ if (currentDay <= adjustedBillingCycleStart) {
+ // if the current day is less than the billing cycle start, we need to go back a month
+ const lastMonth = currentMonth === 0 ? 11 : currentMonth - 1; // if the current month is January, we need to go back to December
+ const lastYear = currentMonth === 0 ? currentYear - 1 : currentYear; // if the current month is January, we need to go back a year
+ return new Date(lastYear, lastMonth, adjustedBillingCycleStart);
+ } else {
+ return new Date(currentYear, currentMonth, adjustedBillingCycleStart);
+ }
+};
diff --git a/packages/utils/src/functions/deep-equal.ts b/packages/utils/src/functions/deep-equal.ts
new file mode 100644
index 0000000000..311d3339f4
--- /dev/null
+++ b/packages/utils/src/functions/deep-equal.ts
@@ -0,0 +1,34 @@
+type DeepEqual = (
+ obj1: Record<string, any>,
+ obj2: Record<string, any>,
+) => boolean;
+
+export const deepEqual: DeepEqual = (obj1, obj2) => {
+ if (obj1 === obj2) {
+ return true;
+ }
+
+ if (
+ typeof obj1 !== "object" ||
+ typeof obj2 !== "object" ||
+ obj1 === null ||
+ obj2 === null
+ ) {
+ return false;
+ }
+
+ const keys1 = Object.keys(obj1);
+ const keys2 = Object.keys(obj2);
+
+ if (keys1.length !== keys2.length) {
+ return false;
+ }
+
+ for (const key of keys1) {
+ if (!keys2.includes(key) || !deepEqual(obj1[key], obj2[key])) {
+ return false;
+ }
+ }
+
+ return true;
+};
diff --git a/packages/utils/src/functions/domains.ts b/packages/utils/src/functions/domains.ts
new file mode 100644
index 0000000000..bc1e1784e8
--- /dev/null
+++ b/packages/utils/src/functions/domains.ts
@@ -0,0 +1,91 @@
+import slugify from "@sindresorhus/slugify";
+import {
+ DUB_DOMAINS,
+ SECOND_LEVEL_DOMAINS,
+ SPECIAL_APEX_DOMAINS,
+ ccTLDs,
+} from "../constants";
+import { isValidUrl } from "./urls";
+
+export const generateDomainFromName = (name: string) => {
+ const normalizedName = slugify(name, { separator: "" });
+ if (normalizedName.length < 3) {
+ return "";
+ }
+ if (ccTLDs.has(normalizedName.slice(-2))) {
+ return `${normalizedName.slice(0, -2)}.${normalizedName.slice(-2)}`;
+ }
+ // remove vowels
+ const devowel = normalizedName.replace(/[aeiou]/g, "");
+ if (devowel.length >= 3 && ccTLDs.has(devowel.slice(-2))) {
+ return `${devowel.slice(0, -2)}.${devowel.slice(-2)}`;
+ }
+
+ const shortestString = [normalizedName, devowel].reduce((a, b) =>
+ a.length < b.length ? a : b,
+ );
+
+ return `${shortestString}.to`;
+};
+
+// courtesy of ChatGPT: https://sharegpt.com/c/pUYXtRs
+export const validDomainRegex = new RegExp(
+ /^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,
+);
+
+export const validKeyRegex = new RegExp(/^[0-9A-Za-z\u0080-\uFFFF\/\-]*$/u);
+
+export const validSlugRegex = new RegExp(/^[a-zA-Z0-9\-]+$/);
+
+export const getSubdomain = (name: string, apexName: string) => {
+ if (name === apexName) return null;
+ return name.slice(0, name.length - apexName.length - 1);
+};
+
+export const getApexDomain = (url: string) => {
+ let domain;
+ try {
+ // replace any custom scheme (e.g. notion://) with https://
+ // use the URL constructor to get the hostname
+ domain = new URL(url.replace(/^[a-zA-Z]+:\/\//, "https://")).hostname;
+ } catch (e) {
+ return "";
+ }
+ if (domain === "youtu.be") return "youtube.com";
+ if (domain === "raw.githubusercontent.com") return "github.com";
+ if (domain.endsWith(".vercel.app")) return "vercel.app";
+
+ const parts = domain.split(".");
+ if (parts.length > 2) {
+ if (
+ // if this is a second-level TLD (e.g. co.uk, .com.ua, .org.tt), we need to return the last 3 parts
+ (SECOND_LEVEL_DOMAINS.has(parts[parts.length - 2]) &&
+ ccTLDs.has(parts[parts.length - 1])) ||
+ // if it's a special subdomain for website builders (e.g. weathergpt.vercel.app/)
+ SPECIAL_APEX_DOMAINS.has(parts.slice(-2).join("."))
+ ) {
+ return parts.slice(-3).join(".");
+ }
+ // otherwise, it's a subdomain (e.g. dub.vercel.app), so we return the last 2 parts
+ return parts.slice(-2).join(".");
+ }
+ // if it's a normal domain (e.g. dub.co), we return the domain
+ return domain;
+};
+
+export const getDomainWithoutWWW = (url: string) => {
+ if (isValidUrl(url)) {
+ return new URL(url).hostname.replace(/^www\./, "");
+ }
+ try {
+ if (url.includes(".") && !url.includes(" ")) {
+ return new URL(`https://${url}`).hostname.replace(/^www\./, "");
+ }
+ } catch (e) {
+ return null;
+ }
+};
+
+export const isDubDomain = (domain: string) => {
+ return DUB_DOMAINS.some((d) => d.slug === domain);
+};
diff --git a/packages/utils/src/functions/fetch-with-timeout.ts b/packages/utils/src/functions/fetch-with-timeout.ts
new file mode 100644
index 0000000000..07a5d13239
--- /dev/null
+++ b/packages/utils/src/functions/fetch-with-timeout.ts
@@ -0,0 +1,22 @@
+export function fetchWithTimeout(
+ input: RequestInfo | URL,
+ init?: RequestInit | undefined,
+ timeout: number = 5000,
+) {
+ return new Promise<Response>((resolve, reject) => {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => {
+ controller.abort();
+ reject(new Error("Request timed out"));
+ }, timeout);
+ fetch(input, { ...init, signal: controller.signal })
+ .then((response) => {
+ clearTimeout(timeoutId);
+ resolve(response);
+ })
+ .catch((error) => {
+ clearTimeout(timeoutId);
+ reject(error);
+ });
+ });
+}
diff --git a/packages/utils/src/functions/fetcher.ts b/packages/utils/src/functions/fetcher.ts
new file mode 100644
index 0000000000..837b49dd90
--- /dev/null
+++ b/packages/utils/src/functions/fetcher.ts
@@ -0,0 +1,19 @@
+interface SWRError extends Error {
+ status: number;
+}
+
+export async function fetcher<JSON = any>(
+ input: RequestInfo,
+ init?: RequestInit,
+): Promise<JSON> {
+ const res = await fetch(input, init);
+
+ if (!res.ok) {
+ const error = await res.text();
+ const err = new Error(error) as SWRError;
+ err.status = res.status;
+ throw err;
+ }
+
+ return res.json();
+}
diff --git a/packages/utils/src/functions/hash.ts b/packages/utils/src/functions/hash.ts
new file mode 100644
index 0000000000..8e7ed92eec
--- /dev/null
+++ b/packages/utils/src/functions/hash.ts
@@ -0,0 +1,16 @@
+export async function generateMD5Hash(message: string) {
+ // Convert the message string to a Uint8Array
+ const encoder = new TextEncoder();
+ const data = encoder.encode(message);
+
+ // Generate the hash using the SubtleCrypto interface
+ const hashBuffer = await crypto.subtle.digest("MD5", data);
+
+ // Convert the hash to a hexadecimal string
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
+ const hashHex = hashArray
+ .map((byte) => byte.toString(16).padStart(2, "0"))
+ .join("");
+
+ return hashHex;
+}
diff --git a/packages/utils/src/functions/index.ts b/packages/utils/src/functions/index.ts
new file mode 100644
index 0000000000..aff360c3ed
--- /dev/null
+++ b/packages/utils/src/functions/index.ts
@@ -0,0 +1,18 @@
+export * from "./capitalize";
+export * from "./chunk";
+export * from "./cn";
+export * from "./construct-metadata";
+export * from "./datetime";
+export * from "./deep-equal";
+export * from "./domains";
+export * from "./fetch-with-timeout";
+export * from "./fetcher";
+export * from "./hash";
+export * from "./link-constructor";
+export * from "./log";
+export * from "./misc";
+export * from "./nanoid";
+export * from "./nformatter";
+export * from "./time-ago";
+export * from "./truncate";
+export * from "./urls";
diff --git a/packages/utils/src/functions/link-constructor.ts b/packages/utils/src/functions/link-constructor.ts
new file mode 100644
index 0000000000..2668e8d128
--- /dev/null
+++ b/packages/utils/src/functions/link-constructor.ts
@@ -0,0 +1,20 @@
+export function linkConstructor({
+ domain = "dub.sh",
+ key,
+ localhost,
+ pretty,
+ noDomain,
+}: {
+ domain?: string;
+ key?: string;
+ localhost?: boolean;
+ pretty?: boolean;
+ noDomain?: boolean;
+}) {
+ const link = `${
+ localhost ? "http://home.localhost:8888" : `https://${domain}`
+ }${key && key !== "_root" ? `/${key}` : ""}`;
+
+ if (noDomain) return `/${key}`;
+ return pretty ? link.replace(/^https?:\/\//, "") : link;
+}
diff --git a/packages/utils/src/functions/log.ts b/packages/utils/src/functions/log.ts
new file mode 100644
index 0000000000..97780c9f11
--- /dev/null
+++ b/packages/utils/src/functions/log.ts
@@ -0,0 +1,45 @@
+const logTypeToEnv = {
+ cron: process.env.DUB_SLACK_HOOK_CRON,
+ links: process.env.DUB_SLACK_HOOK_LINKS,
+};
+
+export const log = async ({
+ message,
+ type,
+ mention = false,
+}: {
+ message: string;
+ type: "cron" | "links";
+ mention?: boolean;
+}) => {
+ if (
+ process.env.NODE_ENV === "development" ||
+ !process.env.DUB_SLACK_HOOK_CRON ||
+ !process.env.DUB_SLACK_HOOK_LINKS
+ )
+ console.log(message);
+ /* Log a message to the console */
+ const HOOK = logTypeToEnv[type];
+ if (!HOOK) return;
+ try {
+ return await fetch(HOOK, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ blocks: [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: `${mention ? "<@U0404G6J3NJ> " : ""}${message}`,
+ },
+ },
+ ],
+ }),
+ });
+ } catch (e) {
+ console.log(`Failed to log to Dub Slack. Error: ${e}`);
+ }
+};
diff --git a/packages/utils/src/functions/misc.ts b/packages/utils/src/functions/misc.ts
new file mode 100644
index 0000000000..ea3528207f
--- /dev/null
+++ b/packages/utils/src/functions/misc.ts
@@ -0,0 +1,5 @@
+import { PLANS } from "../constants";
+
+export const getPlanFromPriceId = (priceId: string) => {
+ return PLANS.find((plan) => plan.price.ids?.includes(priceId)) || null;
+};
diff --git a/packages/utils/src/functions/nanoid.ts b/packages/utils/src/functions/nanoid.ts
new file mode 100644
index 0000000000..4cbca2cd38
--- /dev/null
+++ b/packages/utils/src/functions/nanoid.ts
@@ -0,0 +1,6 @@
+import { customAlphabet } from "nanoid";
+
+export const nanoid = customAlphabet(
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
+ 7,
+); // 7-character random string
diff --git a/packages/utils/src/functions/nformatter.ts b/packages/utils/src/functions/nformatter.ts
new file mode 100644
index 0000000000..019ef186f0
--- /dev/null
+++ b/packages/utils/src/functions/nformatter.ts
@@ -0,0 +1,30 @@
+export function nFormatter(
+ num?: number,
+ opts: { digits?: number; full?: boolean } = {
+ digits: 1,
+ },
+) {
+ if (!num) return "0";
+ if (opts.full) {
+ return Intl.NumberFormat("en-US").format(num);
+ }
+ const lookup = [
+ { value: 1, symbol: "" },
+ { value: 1e3, symbol: "K" },
+ { value: 1e6, symbol: "M" },
+ { value: 1e9, symbol: "G" },
+ { value: 1e12, symbol: "T" },
+ { value: 1e15, symbol: "P" },
+ { value: 1e18, symbol: "E" },
+ ];
+ const rx = /\.0+$|(\.[0-9]*[1-9])0+$/;
+ var item = lookup
+ .slice()
+ .reverse()
+ .find(function (item) {
+ return num >= item.value;
+ });
+ return item
+ ? (num / item.value).toFixed(opts.digits).replace(rx, "$1") + item.symbol
+ : "0";
+}
diff --git a/packages/utils/src/functions/time-ago.ts b/packages/utils/src/functions/time-ago.ts
new file mode 100644
index 0000000000..69147da6fa
--- /dev/null
+++ b/packages/utils/src/functions/time-ago.ts
@@ -0,0 +1,28 @@
+import ms from "ms";
+
+export const timeAgo = (
+ timestamp: Date | null,
+ {
+ withAgo,
+ }: {
+ withAgo?: boolean;
+ } = {},
+): string => {
+ if (!timestamp) return "Never";
+ const diff = Date.now() - new Date(timestamp).getTime();
+ if (diff < 1000) {
+ // less than 1 second
+ return "Just now";
+ } else if (diff > 82800000) {
+ // more than 23 hours – similar to how Twitter displays timestamps
+ return new Date(timestamp).toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ year:
+ new Date(timestamp).getFullYear() !== new Date().getFullYear()
+ ? "numeric"
+ : undefined,
+ });
+ }
+ return `${ms(diff)}${withAgo ? " ago" : ""}`;
+};
diff --git a/packages/utils/src/functions/truncate.ts b/packages/utils/src/functions/truncate.ts
new file mode 100644
index 0000000000..eca1877a1e
--- /dev/null
+++ b/packages/utils/src/functions/truncate.ts
@@ -0,0 +1,4 @@
+export const truncate = (str: string | null, length: number) => {
+ if (!str || str.length <= length) return str;
+ return `${str.slice(0, length - 3)}...`;
+};
diff --git a/packages/utils/src/functions/urls.ts b/packages/utils/src/functions/urls.ts
new file mode 100644
index 0000000000..7e00dc11e2
--- /dev/null
+++ b/packages/utils/src/functions/urls.ts
@@ -0,0 +1,85 @@
+export const isValidUrl = (url: string) => {
+ try {
+ new URL(url);
+ return true;
+ } catch (e) {
+ return false;
+ }
+};
+
+export const getUrlFromString = (str: string) => {
+ if (isValidUrl(str)) return new URL(str).toString();
+ try {
+ if (str.includes(".") && !str.includes(" ")) {
+ return new URL(`https://${str}`).toString();
+ }
+ } catch (e) {
+ return null;
+ }
+};
+
+export const getSearchParams = (url: string) => {
+ // Create a params object
+ let params = {} as Record<string, string>;
+
+ new URL(url).searchParams.forEach(function (val, key) {
+ params[key] = val;
+ });
+
+ return params;
+};
+
+export const getParamsFromURL = (url: string) => {
+ if (!url) return {};
+ try {
+ const params = new URL(url).searchParams;
+ const paramsObj: Record<string, string> = {};
+ for (const [key, value] of params.entries()) {
+ if (value && value !== "") {
+ paramsObj[key] = value;
+ }
+ }
+ return paramsObj;
+ } catch (e) {
+ return {};
+ }
+};
+
+export const constructURLFromUTMParams = (
+ url: string,
+ utmParams: Record<string, string>,
+) => {
+ if (!url) return "";
+ try {
+ const newURL = new URL(url);
+ for (const [key, value] of Object.entries(utmParams)) {
+ if (value === "") {
+ newURL.searchParams.delete(key);
+ } else {
+ newURL.searchParams.set(key, value);
+ }
+ }
+ return newURL.toString();
+ } catch (e) {
+ return "";
+ }
+};
+
+export const paramsMetadata = [
+ { display: "Referral (ref)", key: "ref", examples: "twitter, facebook" },
+ { display: "UTM Source", key: "utm_source", examples: "twitter, facebook" },
+ { display: "UTM Medium", key: "utm_medium", examples: "social, email" },
+ { display: "UTM Campaign", key: "utm_campaign", examples: "summer_sale" },
+ { display: "UTM Term", key: "utm_term", examples: "blue_shoes" },
+ { display: "UTM Content", key: "utm_content", examples: "logolink" },
+];
+
+export const getUrlWithoutUTMParams = (url: string) => {
+ try {
+ const newURL = new URL(url);
+ paramsMetadata.forEach((param) => newURL.searchParams.delete(param.key));
+ return newURL.toString();
+ } catch (e) {
+ return url;
+ }
+};
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index f356234595..27e55f0866 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -1,555 +1,2 @@
-import slugify from "@sindresorhus/slugify";
-import { clsx, type ClassValue } from "clsx";
-import ms from "ms";
-import { customAlphabet } from "nanoid";
-import { Metadata } from "next";
-import { twMerge } from "tailwind-merge";
-import {
- DUB_DOMAINS,
- HOME_DOMAIN,
- PLANS,
- SECOND_LEVEL_DOMAINS,
- SPECIAL_APEX_DOMAINS,
- ccTLDs,
-} from "./constants";
-
export * from "./constants";
-
-export function cn(...inputs: ClassValue[]) {
- return twMerge(clsx(inputs));
-}
-
-export function constructMetadata({
- title = `${process.env.NEXT_PUBLIC_APP_NAME} - Link Management for Modern Marketing Teams`,
- description = `${process.env.NEXT_PUBLIC_APP_NAME} is the open-source link management infrastructure for modern marketing teams to create, share, and track short links.`,
- image = "https://dub.co/_static/thumbnail.png",
- icons = [
- {
- rel: "apple-touch-icon",
- sizes: "32x32",
- url: "/apple-touch-icon.png",
- },
- {
- rel: "icon",
- type: "image/png",
- sizes: "32x32",
- url: "/favicon-32x32.png",
- },
- {
- rel: "icon",
- type: "image/png",
- sizes: "16x16",
- url: "/favicon-16x16.png",
- },
- ],
- noIndex = false,
-}: {
- title?: string;
- description?: string;
- image?: string;
- icons?: Metadata["icons"];
- noIndex?: boolean;
-} = {}): Metadata {
- return {
- title,
- description,
- openGraph: {
- title,
- description,
- images: [
- {
- url: image,
- },
- ],
- },
- twitter: {
- card: "summary_large_image",
- title,
- description,
- images: [image],
- creator: "@dubdotco",
- },
- icons,
- metadataBase: new URL(HOME_DOMAIN),
- ...(noIndex && {
- robots: {
- index: false,
- follow: false,
- },
- }),
- };
-}
-
-export const nanoid = customAlphabet(
- "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
- 7,
-); // 7-character random string
-
-interface SWRError extends Error {
- status: number;
-}
-
-export async function fetcher<JSON = any>(
- input: RequestInfo,
- init?: RequestInit,
-): Promise<JSON> {
- const res = await fetch(input, init);
-
- if (!res.ok) {
- const error = await res.text();
- const err = new Error(error) as SWRError;
- err.status = res.status;
- throw err;
- }
-
- return res.json();
-}
-
-export function nFormatter(
- num?: number,
- opts: { digits?: number; full?: boolean } = {
- digits: 1,
- },
-) {
- if (!num) return "0";
- if (opts.full) {
- return Intl.NumberFormat("en-US").format(num);
- }
- const lookup = [
- { value: 1, symbol: "" },
- { value: 1e3, symbol: "K" },
- { value: 1e6, symbol: "M" },
- { value: 1e9, symbol: "G" },
- { value: 1e12, symbol: "T" },
- { value: 1e15, symbol: "P" },
- { value: 1e18, symbol: "E" },
- ];
- const rx = /\.0+$|(\.[0-9]*[1-9])0+$/;
- var item = lookup
- .slice()
- .reverse()
- .find(function (item) {
- return num >= item.value;
- });
- return item
- ? (num / item.value).toFixed(opts.digits).replace(rx, "$1") + item.symbol
- : "0";
-}
-
-export function capitalize(str?: string | null) {
- if (!str || typeof str !== "string") return str;
- return str.charAt(0).toUpperCase() + str.slice(1);
-}
-
-export const chunk = <T>(array: T[], chunk_size: number): T[][] => {
- return array.reduce((resultArray, item, index) => {
- const chunkIndex = Math.floor(index / chunk_size);
-
- if (!resultArray[chunkIndex]) {
- resultArray[chunkIndex] = []; // start a new chunk
- }
-
- resultArray[chunkIndex].push(item);
-
- return resultArray;
- }, [] as T[][]);
-};
-
-export function linkConstructor({
- domain = "dub.sh",
- key,
- localhost,
- pretty,
- noDomain,
-}: {
- domain?: string;
- key?: string;
- localhost?: boolean;
- pretty?: boolean;
- noDomain?: boolean;
-}) {
- const link = `${
- localhost ? "http://home.localhost:8888" : `https://${domain}`
- }${key && key !== "_root" ? `/${key}` : ""}`;
-
- if (noDomain) return `/${key}`;
- return pretty ? link.replace(/^https?:\/\//, "") : link;
-}
-
-export const timeAgo = (
- timestamp: Date | null,
- {
- withAgo,
- }: {
- withAgo?: boolean;
- } = {},
-): string => {
- if (!timestamp) return "Never";
- const diff = Date.now() - new Date(timestamp).getTime();
- if (diff < 1000) {
- // less than 1 second
- return "Just now";
- } else if (diff > 82800000) {
- // more than 23 hours – similar to how Twitter displays timestamps
- return new Date(timestamp).toLocaleDateString("en-US", {
- month: "short",
- day: "numeric",
- year:
- new Date(timestamp).getFullYear() !== new Date().getFullYear()
- ? "numeric"
- : undefined,
- });
- }
- return `${ms(diff)}${withAgo ? " ago" : ""}`;
-};
-
-export const getDateTimeLocal = (timestamp?: Date): string => {
- const d = timestamp ? new Date(timestamp) : new Date();
- if (d.toString() === "Invalid Date") return "";
- return new Date(d.getTime() - d.getTimezoneOffset() * 60000)
- .toISOString()
- .split(":")
- .slice(0, 2)
- .join(":");
-};
-
-export const formatDate = (dateString: string) => {
- return new Date(`${dateString}T00:00:00Z`).toLocaleDateString("en-US", {
- day: "numeric",
- month: "long",
- year: "numeric",
- timeZone: "UTC",
- });
-};
-
-export const getFirstAndLastDay = (day: number) => {
- const today = new Date();
- const currentDay = today.getDate();
- const currentMonth = today.getMonth();
- const currentYear = today.getFullYear();
- if (currentDay >= day) {
- // if the current day is greater than target day, it means that we just passed it
- return {
- firstDay: new Date(currentYear, currentMonth, day),
- lastDay: new Date(currentYear, currentMonth + 1, day - 1),
- };
- } else {
- // if the current day is less than target day, it means that we haven't passed it yet
- const lastYear = currentMonth === 0 ? currentYear - 1 : currentYear; // if the current month is January, we need to go back a year
- const lastMonth = currentMonth === 0 ? 11 : currentMonth - 1; // if the current month is January, we need to go back to December
- return {
- firstDay: new Date(lastYear, lastMonth, day),
- lastDay: new Date(currentYear, currentMonth, day - 1),
- };
- }
-};
-
-// Function to get the last day of the current month
-export const getLastDayOfMonth = () => {
- const today = new Date();
- const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0); // This will give the last day of the current month
- return lastDay.getDate();
-};
-
-// Adjust the billingCycleStart based on the number of days in the current month
-export const getAdjustedBillingCycleStart = (billingCycleStart: number) => {
- const lastDay = getLastDayOfMonth();
- if (billingCycleStart > lastDay) {
- return lastDay;
- } else {
- return billingCycleStart;
- }
-};
-
-export const getBillingStartDate = (billingCycleStart: number) => {
- const today = new Date();
- const currentDay = today.getDate();
- const currentMonth = today.getMonth();
- const currentYear = today.getFullYear();
- const adjustedBillingCycleStart =
- getAdjustedBillingCycleStart(billingCycleStart);
- if (currentDay <= adjustedBillingCycleStart) {
- // if the current day is less than the billing cycle start, we need to go back a month
- const lastMonth = currentMonth === 0 ? 11 : currentMonth - 1; // if the current month is January, we need to go back to December
- const lastYear = currentMonth === 0 ? currentYear - 1 : currentYear; // if the current month is January, we need to go back a year
- return new Date(lastYear, lastMonth, adjustedBillingCycleStart);
- } else {
- return new Date(currentYear, currentMonth, adjustedBillingCycleStart);
- }
-};
-
-export const getPlanFromPriceId = (priceId: string) => {
- return PLANS.find((plan) => plan.price.ids?.includes(priceId)) || null;
-};
-
-export const generateDomainFromName = (name: string) => {
- const normalizedName = slugify(name, { separator: "" });
- if (normalizedName.length < 3) {
- return "";
- }
- if (ccTLDs.has(normalizedName.slice(-2))) {
- return `${normalizedName.slice(0, -2)}.${normalizedName.slice(-2)}`;
- }
- // remove vowels
- const devowel = normalizedName.replace(/[aeiou]/g, "");
- if (devowel.length >= 3 && ccTLDs.has(devowel.slice(-2))) {
- return `${devowel.slice(0, -2)}.${devowel.slice(-2)}`;
- }
-
- const shortestString = [normalizedName, devowel].reduce((a, b) =>
- a.length < b.length ? a : b,
- );
-
- return `${shortestString}.to`;
-};
-
-// courtesy of ChatGPT: https://sharegpt.com/c/pUYXtRs
-export const validDomainRegex = new RegExp(
- /^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,
-);
-
-export const validKeyRegex = new RegExp(/^[0-9A-Za-z\u0080-\uFFFF\/\-]*$/u);
-
-export const validSlugRegex = new RegExp(/^[a-zA-Z0-9\-]+$/);
-
-export const getSubdomain = (name: string, apexName: string) => {
- if (name === apexName) return null;
- return name.slice(0, name.length - apexName.length - 1);
-};
-
-export const getApexDomain = (url: string) => {
- let domain;
- try {
- // replace any custom scheme (e.g. notion://) with https://
- // use the URL constructor to get the hostname
- domain = new URL(url.replace(/^[a-zA-Z]+:\/\//, "https://")).hostname;
- } catch (e) {
- return "";
- }
- if (domain === "youtu.be") return "youtube.com";
- if (domain === "raw.githubusercontent.com") return "github.com";
- if (domain.endsWith(".vercel.app")) return "vercel.app";
-
- const parts = domain.split(".");
- if (parts.length > 2) {
- if (
- // if this is a second-level TLD (e.g. co.uk, .com.ua, .org.tt), we need to return the last 3 parts
- (SECOND_LEVEL_DOMAINS.has(parts[parts.length - 2]) &&
- ccTLDs.has(parts[parts.length - 1])) ||
- // if it's a special subdomain for website builders (e.g. weathergpt.vercel.app/)
- SPECIAL_APEX_DOMAINS.has(parts.slice(-2).join("."))
- ) {
- return parts.slice(-3).join(".");
- }
- // otherwise, it's a subdomain (e.g. dub.vercel.app), so we return the last 2 parts
- return parts.slice(-2).join(".");
- }
- // if it's a normal domain (e.g. dub.co), we return the domain
- return domain;
-};
-
-export const isValidUrl = (url: string) => {
- try {
- new URL(url);
- return true;
- } catch (e) {
- return false;
- }
-};
-
-export const getUrlFromString = (str: string) => {
- if (isValidUrl(str)) return new URL(str).toString();
- try {
- if (str.includes(".") && !str.includes(" ")) {
- return new URL(`https://${str}`).toString();
- }
- } catch (e) {
- return null;
- }
-};
-
-export const getDomainWithoutWWW = (url: string) => {
- if (isValidUrl(url)) {
- return new URL(url).hostname.replace(/^www\./, "");
- }
- try {
- if (url.includes(".") && !url.includes(" ")) {
- return new URL(`https://${url}`).hostname.replace(/^www\./, "");
- }
- } catch (e) {
- return null;
- }
-};
-
-export const isDubDomain = (domain: string) => {
- return DUB_DOMAINS.some((d) => d.slug === domain);
-};
-
-export const getSearchParams = (url: string) => {
- // Create a params object
- let params = {} as Record<string, string>;
-
- new URL(url).searchParams.forEach(function (val, key) {
- params[key] = val;
- });
-
- return params;
-};
-
-export const truncate = (str: string | null, length: number) => {
- if (!str || str.length <= length) return str;
- return `${str.slice(0, length - 3)}...`;
-};
-
-export const getParamsFromURL = (url: string) => {
- if (!url) return {};
- try {
- const params = new URL(url).searchParams;
- const paramsObj: Record<string, string> = {};
- for (const [key, value] of params.entries()) {
- if (value && value !== "") {
- paramsObj[key] = value;
- }
- }
- return paramsObj;
- } catch (e) {
- return {};
- }
-};
-
-export const constructURLFromUTMParams = (
- url: string,
- utmParams: Record<string, string>,
-) => {
- if (!url) return "";
- try {
- const newURL = new URL(url);
- for (const [key, value] of Object.entries(utmParams)) {
- if (value === "") {
- newURL.searchParams.delete(key);
- } else {
- newURL.searchParams.set(key, value);
- }
- }
- return newURL.toString();
- } catch (e) {
- return "";
- }
-};
-
-export const paramsMetadata = [
- { display: "Referral (ref)", key: "ref", examples: "twitter, facebook" },
- { display: "UTM Source", key: "utm_source", examples: "twitter, facebook" },
- { display: "UTM Medium", key: "utm_medium", examples: "social, email" },
- { display: "UTM Campaign", key: "utm_campaign", examples: "summer_sale" },
- { display: "UTM Term", key: "utm_term", examples: "blue_shoes" },
- { display: "UTM Content", key: "utm_content", examples: "logolink" },
-];
-
-export const getUrlWithoutUTMParams = (url: string) => {
- try {
- const newURL = new URL(url);
- paramsMetadata.forEach((param) => newURL.searchParams.delete(param.key));
- return newURL.toString();
- } catch (e) {
- return url;
- }
-};
-
-export async function generateMD5Hash(message: string) {
- // Convert the message string to a Uint8Array
- const encoder = new TextEncoder();
- const data = encoder.encode(message);
-
- // Generate the hash using the SubtleCrypto interface
- const hashBuffer = await crypto.subtle.digest("MD5", data);
-
- // Convert the hash to a hexadecimal string
- const hashArray = Array.from(new Uint8Array(hashBuffer));
- const hashHex = hashArray
- .map((byte) => byte.toString(16).padStart(2, "0"))
- .join("");
-
- return hashHex;
-}
-
-const logTypeToEnv = {
- cron: process.env.DUB_SLACK_HOOK_CRON,
- links: process.env.DUB_SLACK_HOOK_LINKS,
-};
-
-export const log = async ({
- message,
- type,
- mention = false,
-}: {
- message: string;
- type: "cron" | "links";
- mention?: boolean;
-}) => {
- if (
- process.env.NODE_ENV === "development" ||
- !process.env.DUB_SLACK_HOOK_CRON ||
- !process.env.DUB_SLACK_HOOK_LINKS
- )
- console.log(message);
- /* Log a message to the console */
- const HOOK = logTypeToEnv[type];
- if (!HOOK) return;
- try {
- return await fetch(HOOK, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- blocks: [
- {
- type: "section",
- text: {
- type: "mrkdwn",
- text: `${mention ? "<@U0404G6J3NJ> " : ""}${message}`,
- },
- },
- ],
- }),
- });
- } catch (e) {
- console.log(`Failed to log to Dub Slack. Error: ${e}`);
- }
-};
-
-type DeepEqual = (
- obj1: Record<string, any>,
- obj2: Record<string, any>,
-) => boolean;
-
-export const deepEqual: DeepEqual = (obj1, obj2) => {
- if (obj1 === obj2) {
- return true;
- }
-
- if (
- typeof obj1 !== "object" ||
- typeof obj2 !== "object" ||
- obj1 === null ||
- obj2 === null
- ) {
- return false;
- }
-
- const keys1 = Object.keys(obj1);
- const keys2 = Object.keys(obj2);
-
- if (keys1.length !== keys2.length) {
- return false;
- }
-
- for (const key of keys1) {
- if (!keys2.includes(key) || !deepEqual(obj1[key], obj2[key])) {
- return false;
- }
- }
-
- return true;
-};
+export * from "./functions";