The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Fix Typescript Errors, added Button UI component
Steven Teyd003d3c01939
diff --git a/app/ui/button.tsx b/app/ui/button.tsxnew file mode 100644index 0000000000..ef408242eb--- /dev/null+++ b/app/ui/button.tsx@@ -0,0 +1,55 @@+"use client";++import { LoadingDots } from "@/components/shared/icons";+import Tooltip from "@/components/shared/tooltip";+import clsx from "clsx";+import { ReactNode } from "react";++export default function Button({+ text,+ variant = "primary",+ onClick,+ disabled,+ loading,+ disabledTooltip,+}: {+ text: string;+ variant?: "primary" | "secondary" | "danger";+ onClick?: () => void;+ disabled?: boolean;+ loading?: boolean;+ disabledTooltip?: string | ReactNode;+}) {+ if (disabledTooltip) {+ return (+ <Tooltip content={disabledTooltip}>+ <div 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>{text}</p>+ </div>+ </Tooltip>+ );+ }+ return (+ <button+ // if onClick is passed, it's a "button" type, otherwise it's being used in a form, hence "submit"+ type={onClick ? "button" : "submit"}+ className={clsx(+ "flex h-10 w-full items-center justify-center rounded-md border text-sm transition-all focus:outline-none",+ disabled || loading+ ? "cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400"+ : {+ "border-black bg-black text-white hover:bg-white hover:text-black":+ variant === "primary",+ "border-gray-200 bg-white text-gray-500 hover:border-black hover:text-black":+ variant === "secondary",+ "border-red-500 bg-red-500 text-white hover:bg-white hover:text-red-500":+ variant === "danger",+ },+ )}+ {...(onClick ? { onClick } : {})}+ disabled={disabled || loading}+ >+ {loading ? <LoadingDots color="#808080" /> : <p>{text}</p>}+ </button>+ );+}diff --git a/components/app/modals/add-edit-domain-modal.tsx b/components/app/modals/add-edit-domain-modal.tsxindex 9238fb2a6b..433ef3f9bf 100644--- a/components/app/modals/add-edit-domain-modal.tsx+++ b/components/app/modals/add-edit-domain-modal.tsx@@ -11,7 +11,6 @@ import { mutate } from "swr";import { useDebounce } from "use-debounce";import BlurImage from "@/components/shared/blur-image";import { AlertCircleFill, Lock } from "@/components/shared/icons";-import LoadingDots from "@/components/shared/icons/loading-dots";import Modal from "@/components/shared/modal";import { DomainProps } from "@/lib/types";import Tooltip, { TooltipContent } from "@/components/shared/tooltip";@@ -20,6 +19,7 @@ import { AnimatePresence, motion } from "framer-motion";import { SWIPE_REVEAL_ANIMATION_SETTINGS } from "@/lib/constants";import Switch from "@/components/shared/switch";import useDomains from "@/lib/swr/use-domains";+import Button from "app/ui/button";function AddEditDomainModal({showAddEditDomainModal,@@ -63,7 +63,7 @@ function AddEditDomainModal({const [lockDomain, setLockDomain] = useState(true);const [saving, setSaving] = useState(false);- const [domainError, setDomainError] = useState(null);+ const [domainError, setDomainError] = useState<string | null>(null);const [deleting, setDeleting] = useState(false);const saveDisabled = useMemo(() => {@@ -310,46 +310,34 @@ function AddEditDomainModal({<Switchfn={() => setData((prev) => ({ ...prev, primary: !primary }))}checked={primary}- disabled={props && domains.length === 1}+ disabled={props?.primary}/></div><div className="grid gap-2">- <button+ <Button+ text={props ? "Save changes" : "Add domain"}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" />+ loading={saving}+ />+ {props &&+ (props.primary ? (+ <Button+ disabledTooltip="You can't delete your primary domain."+ text="Delete domain"+ />) : (- <p>{props ? "Save changes" : "Add domain"}</p>- )}- </button>- {props && domains.length > 1 && (- <button- type="button"- className={`${- deleting- ? "cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400"- : "border-red-500 bg-red-500 text-white hover:bg-white hover:text-red-500"- } flex h-10 w-full items-center justify-center rounded-md border text-sm transition-all focus:outline-none`}- onClick={() => {- window.confirm(- "Warning: Deleting your project's domain will delete all existing short links using the domain. Are you sure you want to continue?",- ) && deleteDomain();- }}- >- {deleting ? (- <LoadingDots color="#808080" />- ) : (- <p>Delete domain</p>- )}- </button>- )}+ <Button+ variant="danger"+ text="Delete domain"+ onClick={() => {+ window.confirm(+ "Warning: Deleting your project's domain will delete all existing short links using the domain. Are you sure you want to continue?",+ ) && deleteDomain();+ }}+ loading={deleting}+ />+ ))}</div></form></div>diff --git a/components/app/modals/add-edit-link-modal/android-section.tsx b/components/app/modals/add-edit-link-modal/android-section.tsxindex 99b12bd262..deb0e3eafe 100644--- a/components/app/modals/add-edit-link-modal/android-section.tsx+++ b/components/app/modals/add-edit-link-modal/android-section.tsx@@ -9,7 +9,7 @@ export default function AndroidSection({data,setData,}: {- props: LinkProps;+ props?: LinkProps;data: LinkProps;setData: Dispatch<SetStateAction<LinkProps>>;}) {@@ -44,7 +44,7 @@ export default function AndroidSection({id="android-url"type="url"placeholder="https://play.google.com/store/apps/details?id=com.disney.disneyplus"- value={android}+ value={android || ""}onChange={(e) => {setData({ ...data, android: e.target.value });}}diff --git a/components/app/modals/add-edit-link-modal/expiration-section.tsx b/components/app/modals/add-edit-link-modal/expiration-section.tsxindex 22655a1b54..d01c3f44f2 100644--- a/components/app/modals/add-edit-link-modal/expiration-section.tsx+++ b/components/app/modals/add-edit-link-modal/expiration-section.tsx@@ -10,7 +10,7 @@ export default function ExpirationSection({data,setData,}: {- props: LinkProps;+ props?: LinkProps;data: LinkProps;setData: Dispatch<SetStateAction<LinkProps>>;}) {diff --git a/components/app/modals/add-edit-link-modal/index.tsx b/components/app/modals/add-edit-link-modal/index.tsxindex d4735ecc65..8d9c994e7f 100644--- a/components/app/modals/add-edit-link-modal/index.tsx+++ b/components/app/modals/add-edit-link-modal/index.tsx@@ -28,6 +28,7 @@ import {getQueryString,getUrlWithoutUTMParams,linkConstructor,+ truncate,} from "@/lib/utils";import ExpirationSection from "./expiration-section";import OGSection from "./og-section";@@ -152,7 +153,15 @@ function AddEditLinkModal({fetch(`/api/edge/metatags?url=${debouncedUrl}`).then(async (res) => {if (res.status === 200) {const results = await res.json();- setData((prev) => ({ ...prev, ...results }));+ setData((prev) => ({+ ...prev,+ // TODO: can remove this eventually when I figure out Why am I storing the metatags data for links with proxy: false???+ ...{+ title: truncate(results.title, 120),+ description: truncate(results.description, 240),+ image: results.image,+ },+ }));}// set timeout to prevent flickeringsetTimeout(() => setGeneratingMetatags(false), 200);@@ -166,11 +175,14 @@ function AddEditLinkModal({}, [debouncedUrl, password, showAddEditLinkModal, proxy]);const logo = useMemo(() => {+ // if the link is password protected, or if it's a new link and there's no URL yet,+ // return the default Dub logoif (password || (!debouncedUrl && !props)) {return "/_static/logo.png";+ // otherwise, get the favicon of the URL} else {return `https://www.google.com/s2/favicons?sz=64&domain_url=${getApexDomain(- debouncedUrl || props.url,+ debouncedUrl || props?.url || "https://dub.sh",)}`;}}, [password, debouncedUrl, props]);@@ -210,6 +222,7 @@ function AddEditLinkModal({- saving is in progress- key is invalid- url is invalid+ - metatags is being generated- for an existing link, there's no changes*/if (@@ -217,14 +230,30 @@ function AddEditLinkModal({saving ||keyExistsError ||urlError ||+ generatingMetatags ||(props &&- Object.entries(props).every(([key, value]) => data[key] === value))+ Object.entries(props).every(([key, value]) => {+ // only check for discrepancy in title and description if proxy is enabled+ if (proxy && (key === "title" || key === "description")) {+ return true;+ } else {+ return data[key] === value;+ }+ }))) {return true;} else {return false;}- }, [showAddEditLinkModal, saving, keyExistsError, urlError, props, data]);+ }, [+ showAddEditLinkModal,+ saving,+ keyExistsError,+ urlError,+ generatingMetatags,+ props,+ data,+ ]);const randomIdx = Math.floor(Math.random() * 100);diff --git a/components/app/modals/add-edit-link-modal/ios-section.tsx b/components/app/modals/add-edit-link-modal/ios-section.tsxindex ed7731c358..4ddbbedb7b 100644--- a/components/app/modals/add-edit-link-modal/ios-section.tsx+++ b/components/app/modals/add-edit-link-modal/ios-section.tsx@@ -9,7 +9,7 @@ export default function IOSSection({data,setData,}: {- props: LinkProps;+ props?: LinkProps;data: LinkProps;setData: Dispatch<SetStateAction<LinkProps>>;}) {@@ -44,7 +44,7 @@ export default function IOSSection({id="ios-url"type="url"placeholder="https://apps.apple.com/app/1611158928"- value={ios}+ value={ios || ""}onChange={(e) => {setData({ ...data, ios: e.target.value });}}diff --git a/components/app/modals/add-edit-link-modal/og-section.tsx b/components/app/modals/add-edit-link-modal/og-section.tsxindex 2c5b69237f..9a444fcdf3 100644--- a/components/app/modals/add-edit-link-modal/og-section.tsx+++ b/components/app/modals/add-edit-link-modal/og-section.tsx@@ -7,7 +7,6 @@ import {} from "react";import { motion } from "framer-motion";import TextareaAutosize from "react-textarea-autosize";-import BlurImage from "@/components/shared/blur-image";import { LoadingCircle, UploadCloud } from "@/components/shared/icons";import { LinkProps } from "@/lib/types";import Switch from "@/components/shared/switch";@@ -19,7 +18,7 @@ export default function OGSection({setData,generatingMetatags,}: {- props: LinkProps;+ props?: LinkProps;data: LinkProps;setData: Dispatch<SetStateAction<LinkProps>>;generatingMetatags: boolean;@@ -39,7 +38,7 @@ export default function OGSection({} else {const reader = new FileReader();reader.onload = (e) => {- setData((prev) => ({ ...prev, image: e.target.result as string }));+ setData((prev) => ({ ...prev, image: e.target?.result as string }));};reader.readAsDataURL(file);}diff --git a/components/app/modals/add-edit-link-modal/password-section.tsx b/components/app/modals/add-edit-link-modal/password-section.tsxindex 52e0547338..2465ccd30e 100644--- a/components/app/modals/add-edit-link-modal/password-section.tsx+++ b/components/app/modals/add-edit-link-modal/password-section.tsx@@ -10,7 +10,7 @@ export default function PasswordSection({data,setData,}: {- props: LinkProps;+ props?: LinkProps;data: LinkProps;setData: Dispatch<SetStateAction<LinkProps>>;}) {diff --git a/components/app/modals/add-edit-link-modal/utm-section.tsx b/components/app/modals/add-edit-link-modal/utm-section.tsxindex d59258b26c..226c62b621 100644--- a/components/app/modals/add-edit-link-modal/utm-section.tsx+++ b/components/app/modals/add-edit-link-modal/utm-section.tsx@@ -15,7 +15,7 @@ export default function UTMSection({data,setData,}: {- props: LinkProps;+ props?: LinkProps;data: LinkProps;setData: Dispatch<SetStateAction<LinkProps>>;}) {diff --git a/components/app/settings/plan-usage.tsx b/components/app/settings/plan-usage.tsxindex 003cd55a37..2a096dd7cc 100644--- a/components/app/settings/plan-usage.tsx+++ b/components/app/settings/plan-usage.tsx@@ -50,7 +50,7 @@ export default function PlanUsage() {mutate(`/api/projects/${slug}`);// track upgrade to pro eventva.track("Upgraded Plan", {- plan,+ plan: "pro",});}, 1000);}@@ -84,7 +84,7 @@ export default function PlanUsage() {</p></div><div className="border-b border-gray-200" />- <div className="grid grid-cols-1 divide-y divide-gray-200 sm:grid-cols-2 sm:divide-y-0 sm:divide-x">+ <div className="grid grid-cols-1 divide-y divide-gray-200 sm:grid-cols-2 sm:divide-x sm:divide-y-0"><div className="flex flex-col space-y-2 p-10"><div className="flex items-center"><h3 className="font-medium">Total Link Clicks</h3>@@ -94,7 +94,7 @@ export default function PlanUsage() {</div></Tooltip></div>- {usageLimit ? (+ {usage && usageLimit ? (<p className="text-sm text-gray-600">{nFormatter(usage)} / {nFormatter(usageLimit)} clicks ({((usage / usageLimit) * 100).toFixed(1)}%)@@ -106,11 +106,14 @@ export default function PlanUsage() {<motion.divinitial={{ width: 0 }}animate={{- width: usageLimit ? (usage / usageLimit) * 100 + "%" : "0%",+ width:+ usage && usageLimit ? (usage / usageLimit) * 100 + "%" : "0%",}}transition={{ duration: 0.5, type: "spring" }}className={`${- usage > usageLimit ? "bg-red-500" : "bg-blue-500"+ usage && usageLimit && usage > usageLimit+ ? "bg-red-500"+ : "bg-blue-500"} h-3 rounded-full`}/></div>diff --git a/components/app/settings/project-name.tsx b/components/app/settings/project-name.tsxindex 582c8bf0b5..fae9551896 100644--- a/components/app/settings/project-name.tsx+++ b/components/app/settings/project-name.tsx@@ -10,7 +10,7 @@ export default function ProjectName() {const { slug } = router.query as { slug: string };const { name } = useProject();- const [newName, setNewName] = useState(null);+ const [newName, setNewName] = useState<string | undefined | null>(null);useEffect(() => {setNewName(name);}, [name]);diff --git a/components/app/settings/project-slug.tsx b/components/app/settings/project-slug.tsxindex f7edbb90a1..e3bae54339 100644--- a/components/app/settings/project-slug.tsx+++ b/components/app/settings/project-slug.tsx@@ -8,7 +8,7 @@ export default function ProjectSlug() {const router = useRouter();const { slug } = router.query as { slug: string };- const [newSlug, setNewSlug] = useState(null);+ const [newSlug, setNewSlug] = useState<string | undefined | null>(null);useEffect(() => {setNewSlug(slug);}, [slug]);diff --git a/components/home/link-card.tsx b/components/home/link-card.tsxindex 5fd912be17..6c2e6f8730 100644--- a/components/home/link-card.tsx+++ b/components/home/link-card.tsx@@ -42,7 +42,7 @@ export default function LinkCard({const [constrained, setConstrained] = useState(true);- const [velocity, setVelocity] = useState<number>();+ const [velocity, setVelocity] = useState<number>(0);const isDelete = (childNode, parentNode) => {const childRect = childNode.getBoundingClientRect();@@ -61,7 +61,9 @@ export default function LinkCard({const flyAway = (min) => {const flyAwayDistance = (direction) => {const parentWidth =+ // @ts-ignorecardElem.current.parentNode.getBoundingClientRect().width;+ // @ts-ignoreconst childWidth = cardElem.current.getBoundingClientRect().width;return direction === "left"? -parentWidth / 2 - childWidth / 2@@ -80,6 +82,7 @@ export default function LinkCard({const unsubscribeX = x.onChange(() => {if (cardElem.current) {const childNode = cardElem.current;+ // @ts-ignoreconst parentNode = cardElem.current.parentNode;const deleted = isDelete(childNode, parentNode);if (deleted) {diff --git a/components/shared/tooltip.tsx b/components/shared/tooltip.tsxindex e81b089a5c..6c2a222965 100644--- a/components/shared/tooltip.tsx+++ b/components/shared/tooltip.tsx@@ -25,6 +25,7 @@ export default function Tooltip({async function handleDragEnd(_, info) {const offset = info.offset.y;const velocity = info.velocity.y;+ // @ts-ignoreconst height = mobileTooltipRef.current.getBoundingClientRect().height;if (offset > height / 2 || velocity > 800) {await controls.start({ y: "100%", transition: transitionProps });@@ -133,7 +134,7 @@ export function TooltipContent({{cta && ctaLink && (<Linkhref={ctaLink}- className="mt-4 rounded-full border border-black bg-black py-1.5 px-3 text-sm text-white transition-all hover:bg-white hover:text-black"+ className="mt-4 rounded-full border border-black bg-black px-3 py-1.5 text-sm text-white transition-all hover:bg-white hover:text-black">{cta}</Link>diff --git a/lib/api/links.ts b/lib/api/links.tsindex 9055becbef..5d345786a1 100644--- a/lib/api/links.ts+++ b/lib/api/links.ts@@ -70,7 +70,7 @@ export async function getLinksForProject({tag?: string;search?: string;sort?: "createdAt" | "clicks"; // always descending for both- userId?: string;+ userId?: string | null;}): Promise<LinkProps[]> {return await prisma.link.findMany({where: {@@ -97,7 +97,7 @@ export async function getLinksCount({}: {req: NextApiRequest;projectId: string;- userId?: string;+ userId?: string | null;}) {const { groupBy, search, domain } = req.query as {groupBy?: "domain";@@ -226,6 +226,7 @@ export async function addLink(link: LinkProps) {android,},{+ // @ts-ignorenx: true,// if the key has an expiry, set exat...(exat && { exat }),@@ -315,10 +316,7 @@ export async function editLink(link: LinkProps, oldKey: string) {ios,android,},- {- // if the key has an expiry, set exat- ...(exat && { exat }),- },+ exat ? { exat } : {},),// if key is changed: rename resource in Cloudinary, delete the old key in Redis and change the clicks key name...(changedKeydiff --git a/lib/auth.ts b/lib/auth.tsindex 22d6edb19c..4e5a5b35f4 100644--- a/lib/auth.ts+++ b/lib/auth.ts@@ -6,9 +6,9 @@ import { authOptions } from "@/pages/api/auth/[...nextauth]";export interface Session {user: {- email?: string | null;- id?: string | null;- name?: string | null;+ email: string;+ id: string;+ name: string;};}@@ -16,14 +16,15 @@ export async function getServerSession(req: NextApiRequest,res: NextApiResponse,) {+ // @ts-ignorereturn (await unstable_getServerSession(req, res, authOptions)) as Session;}interface WithProjectNextApiHandler {(req: NextApiRequest,res: NextApiResponse,- project?: ProjectProps,- session?: Session,+ project: ProjectProps,+ session: Session,): Promise<void>;}@@ -78,7 +79,7 @@ const withProjectAuth =if (project) {// project exists but user is not part of it- if (project.users.length === 0) {+ if (project.users && project.users.length === 0) {const pendingInvites = await prisma.projectInvite.findUnique({where: {email_projectId: {diff --git a/lib/cron/domains.tsx b/lib/cron/domains.tsxindex b18ed0da7d..6b5b58c351 100644--- a/lib/cron/domains.tsx+++ b/lib/cron/domains.tsx@@ -57,9 +57,16 @@ export const handleDomainUpdates = async ({},},});+ if (!project) {+ await log(+ `Domain *${domain}* is invalid but not associated with any project, skipping.`,+ "cron",+ );+ return;+ }const projectSlug = project.slug;const sentEmails = project.sentEmails.map((email) => email.type);- const ownerEmail = project.users[0].user.email;+ const ownerEmail = project.users[0].user.email as string;// if domain is invalid for more than 30 days, check if we can delete itif (invalidDays >= 30) {diff --git a/lib/stats.ts b/lib/stats.tsindex 7435e3c9e7..d9b18acd15 100644--- a/lib/stats.ts+++ b/lib/stats.ts@@ -116,7 +116,7 @@ export const getStats = async ({domain: string;key: string;endpoint: string;- interval?: string;+ interval?: string | null;}) => {if (!process.env.TINYBIRD_API_KEY) {return null;diff --git a/lib/types.ts b/lib/types.tsindex dcc1640ac4..1dd290a893 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -22,7 +22,7 @@ export interface LinkProps {android: string | null;clicks: number;- userId?: string;+ userId?: string | null;createdAt?: Date;updatedAt?: Date;diff --git a/lib/upstash.ts b/lib/upstash.tsindex 1aea3cf378..b9afecd387 100644--- a/lib/upstash.ts+++ b/lib/upstash.ts@@ -25,7 +25,11 @@ export const ratelimit = (limiter: Ratelimit.slidingWindow(requests, seconds),analytics: true,})- : null;+ : // if Redis is not configured, return a dummy ratelimiter+ // with the function limit() that always returns true+ {+ limit: () => ({ success: true }),+ };};// only for dub.sh public demodiff --git a/lib/utils.ts b/lib/utils.tsindex 8ac18704fd..5bd90e22d3 100644--- a/lib/utils.ts+++ b/lib/utils.ts@@ -284,7 +284,7 @@ export const setQueryString = (});};-export const truncate = (str: string, length: number) => {+export const truncate = (str: string | null, length: number) => {if (!str || str.length <= length) return str;return `${str.slice(0, length)}...`;};diff --git a/package.json b/package.jsonindex 9cdaadd979..c4f5a0dd84 100644--- a/package.json+++ b/package.json@@ -42,6 +42,7 @@"@visx/shape": "^2.12.2","@visx/tooltip": "^2.16.0","cloudinary": "^1.32.0",+ "clsx": "^1.2.1","cobe": "^0.6.2","contentlayer": "^0.3.2","crisp-sdk-web": "^1.0.18",diff --git a/pages/api/edge/coordinates.ts b/pages/api/edge/coordinates.tsindex c5aa320634..5e15662a40 100644--- a/pages/api/edge/coordinates.ts+++ b/pages/api/edge/coordinates.ts@@ -13,7 +13,7 @@ interface CoordinateProps {export default async function handler(req: NextRequest) {if (req.method === "GET") {const count = 50;- let latestCoordinates = [];+ let latestCoordinates: CoordinateProps[] = [];// Check if coordinates are cached in Redisconst cachedCoordinates = await redis.get<CoordinateProps[]>("coordinates");diff --git a/pages/api/edge/links/[key]/stats/[endpoint].ts b/pages/api/edge/links/[key]/stats/[endpoint].tsindex 64d58b381f..904a336f88 100644--- a/pages/api/edge/links/[key]/stats/[endpoint].ts+++ b/pages/api/edge/links/[key]/stats/[endpoint].ts@@ -11,7 +11,7 @@ export default async function handler(req: NextRequest) {if (req.method === "GET") {const key = req.nextUrl.pathname.split("/")[4];const interval = req.nextUrl.searchParams.get("interval");- const endpoint = req.nextUrl.searchParams.get("endpoint");+ const endpoint = req.nextUrl.searchParams.get("endpoint") as string;let domain = req.nextUrl.hostname;if (isHomeHostname(domain)) domain = "dub.sh";diff --git a/pages/api/edge/metatags.ts b/pages/api/edge/metatags.tsindex d7b64da874..7430aadc88 100644--- a/pages/api/edge/metatags.ts+++ b/pages/api/edge/metatags.ts@@ -13,7 +13,7 @@ export const config = {export default async function handler(req: NextRequest, ev: NextFetchEvent) {if (req.method === "GET") {let url = req.nextUrl.searchParams.get("url");- if (!isValidUrl(url)) {+ if (!url || !isValidUrl(url)) {return new Response("Invalid URL", { status: 400 });}diff --git a/pages/api/projects/[slug]/billing/manage.ts b/pages/api/projects/[slug]/billing/manage.tsindex 14b3fbf339..665ca4c0ad 100644--- a/pages/api/projects/[slug]/billing/manage.ts+++ b/pages/api/projects/[slug]/billing/manage.ts@@ -5,6 +5,9 @@ export default withProjectAuth(async (req, res, project) => {// POST /api/projects/[slug]/billing/manage – manage a user's subscriptionif (req.method === "POST") {const { slug } = req.query as { slug: string };+ if (!project.stripeId) {+ return res.status(400).json({ error: "No Stripe customer ID" });+ }const { url } = await stripe.billingPortal.sessions.create({customer: project.stripeId,return_url: `${diff --git a/pages/api/projects/[slug]/domains/[domain]/index.ts b/pages/api/projects/[slug]/domains/[domain]/index.tsindex 7296cd82ac..b6fc998d6e 100644--- a/pages/api/projects/[slug]/domains/[domain]/index.ts+++ b/pages/api/projects/[slug]/domains/[domain]/index.ts@@ -26,99 +26,82 @@ export default withProjectAuth(async (req, res, project) => {if (req.method === "PUT") {const { slug: newDomain, target, type, primary } = req.body;- /*- If the domain is being changed (and the new domain is valid), we need to:- 1. Remove the old domain from Vercel- 2. Add the new domain to Vercel- 3. If there's a landing page set, update the root domain in Redis- 4. Update all links in the project to point to the new domain- 5. Update all images in the project to point to the new domain- 6. If the domain is being set as the primary domain, set all other domains to not be the primary domain- 7. Update the domain in the database along with its primary status- */- if (newDomain !== domain) {- const validDomain = await validateDomain(newDomain);+ const validDomain = await validateDomain(newDomain);+ if (!validDomain) {+ return res.status(422).json({+ domainError: validDomain,+ });+ }- if (validDomain !== true) {- return res.status(422).json({- domainError: validDomain,- });- }- const response = await Promise.allSettled([- removeDomain(domain),- addDomain(newDomain),- target && setRootDomain(domain, target, type === "rewrite", newDomain),- changeDomainForLinks(domain, newDomain),- changeDomainForImages(domain, newDomain),- primary &&- prisma.domain.updateMany({- where: {- projectId: project.id,- primary: true,- },- data: {- primary: false,- },- }),- prisma.domain.update({+ const response = await Promise.allSettled([+ // if the domain is being changed, we need to:+ // 1. Remove the old domain from Vercel+ // 2. Add the new domain to Vercel+ // 3. Update all links in the project to point to the new domain+ // 4. Update all images in the project to point to the new domain+ ...(newDomain !== domain+ ? [+ removeDomain(domain),+ addDomain(newDomain),+ changeDomainForLinks(domain, newDomain),+ changeDomainForImages(domain, newDomain),+ ]+ : []),+ // if there's a landing page set, and if the project is not a free plan, we can then:+ // - Set the root domain to the target in Redis+ // - if the domain is being changed, also change the root domain key in Redis+ target &&+ project.plan !== "free" &&+ setRootDomain(+ domain,+ target,+ type === "rewrite",+ newDomain !== domain && newDomain,+ ),+ // if the domain is being set as the primary domain, set the current primary domain to false+ primary &&+ prisma.domain.updateMany({where: {- slug: domain,+ projectId: project.id,+ primary: true,},data: {- slug: newDomain,- target,- type,- primary,+ primary: false,},}),- ]);- return res.status(200).json(response);- } else {- /*- If the domain is not being changed, we only need to:- 1. If there's a landing page set, update the root domain in Redis- 2. If the domain is being set as the primary domain, set all other domains to not be the primary domain- 3. Then, update the domain in the database along with its primary status- */- const response = await Promise.allSettled([- target && setRootDomain(domain, target, type === "rewrite"),- primary &&- prisma.domain.updateMany({- where: {- projectId: project.id,- primary: true,- },- data: {- primary: false,- },+ // Update the domain in the database along with its primary status+ prisma.domain.update({+ where: {+ slug: domain,+ },+ data: {+ ...(newDomain !== domain && {+ slug: newDomain,}),- prisma.domain.update({- where: {- slug: domain,- },- data: {- target,- type,- primary,- },- }),- ]);- return res.status(200).json(response);- }+ ...(target &&+ project.plan !== "free" && {+ target,+ }),+ type,+ primary,+ },+ }),+ ]);++ return res.status(200).json(response);++ // DELETE /api/projects/[slug]/domains/[domain] delete a project's domain} else if (req.method === "DELETE") {const response = await Promise.allSettled([removeDomain(domain),deleteDomainLinks(domain),+ prisma.domain.delete({+ where: {+ slug: domain,+ },+ }),]);- const deletedDomain = await prisma.domain.delete({- where: {- slug: domain,- },- });- return res.status(200).json({- ...response,- deletedDomain,- });+ return res.status(200).json(response);} else {res.setHeader("Allow", ["PUT", "DELETE"]);return res.status(405).json({ error: `Method ${req.method} Not Allowed` });diff --git a/pages/api/projects/index.ts b/pages/api/projects/index.tsindex 292d1b2057..9aa9346a0e 100644--- a/pages/api/projects/index.ts+++ b/pages/api/projects/index.ts@@ -31,7 +31,7 @@ export default withUserAuth(.status(422).json({ error: "Missing name or slug or domain" });}- let slugError = null;+ let slugError: string | null = null;if (slug.includes(" ") || slug.includes(".")) {slugError = "Slug cannot contain spaces or periods";} else if ((await isReservedKey(slug)) || DEFAULT_REDIRECTS[slug]) {diff --git a/tsconfig.json b/tsconfig.jsonindex cb5c364308..068302c0ed 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -23,21 +23,13 @@"jsx": "preserve","incremental": true,"strict": false,- // TODO: Add these back in when we're ready for a full Typescript audit 🥴- // "plugins": [- // {- // "name": "next"- // }- // ],- // "strictNullChecks": true- "strictNullChecks": true+ "strictNullChecks": true,+ "plugins": [+ {+ "name": "next"+ }+ ]},- "include": [- "next-env.d.ts",- "**/*.ts",- "**/*.tsx"- // TODO: Ditto from above- //".next/types/**/*.ts"- ],+ "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],"exclude": ["node_modules"]}diff --git a/yarn.lock b/yarn.lockindex c6f555a515..9dd18422e1 100644--- a/yarn.lock+++ b/yarn.lock@@ -692,10 +692,10 @@resolved "https://registry.yarnpkg.com/@next/env/-/env-13.1.6.tgz#c4925609f16142ded1a5cb833359ab17359b7a93"integrity sha512-s+W9Fdqh5MFk6ECrbnVmmAOwxKQuhGMT7xXHrkYIBMBcTiOqNWhv5KbJIboKR5STXxNXl32hllnvKaffzFaWQg==-"@next/[email protected]":- version "13.4.0"- resolved "https://registry.yarnpkg.com/@next/env/-/env-13.4.0.tgz#8f044b8d8e4e8205a8e250866cfc6fbca44a786d"- integrity sha512-LKofmUuxwGXk2OZJSSJ2SlJE62s6z+56aRsze7chc5TPoVouLR9liTiSWxzYuVzuxk0ui2wtIjyR2tcgS1dIyw==+"@next/[email protected]":+ version "13.4.1"+ resolved "https://registry.yarnpkg.com/@next/env/-/env-13.4.1.tgz#57322da2630b6bb6d7204577b0a18f6f9324db0c"+ integrity sha512-eD6WCBMFjLFooLM19SIhSkWBHtaFrZFfg2Cxnyl3vS3DAdFRfnx5TY2RxlkuKXdIRCC0ySbtK9JXXt8qLCqzZg=="@next/[email protected]":version "13.1.6"@@ -712,20 +712,20 @@resolved "https://registry.yarnpkg.com/@next/swc-darwin-arm64/-/swc-darwin-arm64-13.1.6.tgz#ec1b90fd9bf809d8b81004c5182e254dced4ad96"integrity sha512-KKRQH4DDE4kONXCvFMNBZGDb499Hs+xcFAwvj+rfSUssIDrZOlyfJNy55rH5t2Qxed1e4K80KEJgsxKQN1/fyw==-"@next/[email protected]":- version "13.4.0"- resolved "https://registry.yarnpkg.com/@next/swc-darwin-arm64/-/swc-darwin-arm64-13.4.0.tgz#4d741fc1d71f8353ad9f42789636155e6cb6917f"- integrity sha512-C39AGL3ANXA+P3cFclQjFZaJ4RHPmuBhskmyy0N3VyCntDmRrNkS4aXeNY4Xwure9IL1nuw02D8bM55I+FsbuQ==+"@next/[email protected]":+ version "13.4.1"+ resolved "https://registry.yarnpkg.com/@next/swc-darwin-arm64/-/swc-darwin-arm64-13.4.1.tgz#3748040d2dd0d89d3cdcc897f96aeda5130eed8f"+ integrity sha512-eF8ARHtYfnoYtDa6xFHriUKA/Mfj/cCbmKb3NofeKhMccs65G6/loZ15a6wYCCx4rPAd6x4t1WmVYtri7EdeBg=="@next/[email protected]":version "13.1.6"resolved "https://registry.yarnpkg.com/@next/swc-darwin-x64/-/swc-darwin-x64-13.1.6.tgz#e869ac75d16995eee733a7d1550322d9051c1eb4"integrity sha512-/uOky5PaZDoaU99ohjtNcDTJ6ks/gZ5ykTQDvNZDjIoCxFe3+t06bxsTPY6tAO6uEAw5f6vVFX5H5KLwhrkZCA==-"@next/[email protected]":- version "13.4.0"- resolved "https://registry.yarnpkg.com/@next/swc-darwin-x64/-/swc-darwin-x64-13.4.0.tgz#da9ff9c0ffe20fb5755f7ce562cd3084d29890b8"- integrity sha512-nj6nx6o7rnBXjo1woZFWLk7OUs7y0SQ0k65SX62kc88GqXtYi3BCqbBznjOX8qtrO//NmtAde/Jd5qkjSgINUQ==+"@next/[email protected]":+ version "13.4.1"+ resolved "https://registry.yarnpkg.com/@next/swc-darwin-x64/-/swc-darwin-x64-13.4.1.tgz#c59fc270005f17e04eb7eab4fd68793d0e3409a4"+ integrity sha512-7cmDgF9tGWTgn5Gw+vP17miJbH4wcraMHDCOHTYWkO/VeKT73dUWG23TNRLfgtCNSPgH4V5B4uLHoZTanx9bAw=="@next/[email protected]":version "13.1.6"@@ -742,70 +742,70 @@resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-13.1.6.tgz#87a71db21cded3f7c63d1d19079845c59813c53d"integrity sha512-yCH+yDr7/4FDuWv6+GiYrPI9kcTAO3y48UmaIbrKy8ZJpi7RehJe3vIBRUmLrLaNDH3rY1rwoHi471NvR5J5NQ==-"@next/[email protected]":- version "13.4.0"- resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-13.4.0.tgz#ca6a8bcc0e4a2c0159217fd8153aba8d2304310d"- integrity sha512-FBYL7kpzI2KG3lv8gO4xVYmWcFohptjzD9RCLdXsAz+Kqz5VCJILF21DoRcz4Nwj/jMe0SO7l5kBVW4POl4EaQ==+"@next/[email protected]":+ version "13.4.1"+ resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-13.4.1.tgz#1aef371bcef5d832d7f7e3aec3e68cfb98282393"+ integrity sha512-qwJqmCri2ie8aTtE5gjTSr8S6O8B67KCYgVZhv9gKH44yvc/zXbAY8u23QGULsYOyh1islWE5sWfQNLOj9iryg=="@next/[email protected]":version "13.1.6"resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-13.1.6.tgz#c5aac8619331b9fd030603bbe2b36052011e11de"integrity sha512-ECagB8LGX25P9Mrmlc7Q/TQBb9rGScxHbv/kLqqIWs2fIXy6Y/EiBBiM72NTwuXUFCNrWR4sjUPSooVBJJ3ESQ==-"@next/[email protected]":- version "13.4.0"- resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-13.4.0.tgz#97b7c0eb3bea44a0ce08f12af39b2118d7c0cd4d"- integrity sha512-S3htBbcovnLMgVn0z1ThrP1iAeEM43fw8B7S3KyHTAGe0I21ww4rvUkLdgPCqLNvMpv899lmG7NU5rs6rTkGvg==+"@next/[email protected]":+ version "13.4.1"+ resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-13.4.1.tgz#2522927cb0af6918405a49f5a1d1687d6847f3ec"+ integrity sha512-qcC54tWNGDv/VVIFkazxhqH1Bnagjfs4enzELVRlUOoJPD2BGJTPI7z08pQPbbgxLtRiu8gl2mXvpB8WlOkMeA=="@next/[email protected]":version "13.1.6"resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-13.1.6.tgz#9513d36d540bbfea575576746736054c31aacdea"integrity sha512-GT5w2mruk90V/I5g6ScuueE7fqj/d8Bui2qxdw6lFxmuTgMeol5rnzAv4uAoVQgClOUO/MULilzlODg9Ib3Y4Q==-"@next/[email protected]":- version "13.4.0"- resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-13.4.0.tgz#13a378c8640057a70033adcae4c0609745cbd42f"- integrity sha512-H8GhCgQwFl6iWJ6azQ2tG/GY8BUg1nhPtg4Tp2kIPljdyQypTGJe8oRnPDx0N48WWvB2fNeA7LNEwzVuSidH2w==+"@next/[email protected]":+ version "13.4.1"+ resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-13.4.1.tgz#5ec9418a35510048a5ceb79ed300463e1a9b312d"+ integrity sha512-9TeWFlpLsBosZ+tsm/rWBaMwt5It9tPH8m3nawZqFUUrZyGRfGcI67js774vtx0k3rL9qbyY6+3pw9BCVpaYUA=="@next/[email protected]":version "13.1.6"resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-13.1.6.tgz#d61fc6884899f5957251f4ce3f522e34a2c479b7"integrity sha512-keFD6KvwOPzmat4TCnlnuxJCQepPN+8j3Nw876FtULxo8005Y9Ghcl7ACcR8GoiKoddAq8gxNBrpjoxjQRHeAQ==-"@next/[email protected]":- version "13.4.0"- resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-13.4.0.tgz#d1a6a7f733fff357cb99bae793cd4050de648963"- integrity sha512-mztVybRPY39NfPOA3QrRQKzYuw7A/D8ElR6ruvM1cBsXMEfF5xTzdZqfTtrE/gNTPUFug9FJPpiRpkZ4mDUl8w==+"@next/[email protected]":+ version "13.4.1"+ resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-13.4.1.tgz#3478b9c89b75c1d0e7def9f35a9a77cb15d1a115"+ integrity sha512-sNDGaWmSqTS4QRUzw61wl4mVPeSqNIr1OOjLlQTRuyInxMxtqImRqdvzDvFTlDfdeUMU/DZhWGYoHrXLlZXe6A=="@next/[email protected]":version "13.1.6"resolved "https://registry.yarnpkg.com/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-13.1.6.tgz#fac2077a8ae9768e31444c9ae90807e64117cda7"integrity sha512-OwertslIiGQluFvHyRDzBCIB07qJjqabAmINlXUYt7/sY7Q7QPE8xVi5beBxX/rxTGPIbtyIe3faBE6Z2KywhQ==-"@next/[email protected]":- version "13.4.0"- resolved "https://registry.yarnpkg.com/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-13.4.0.tgz#3c029b1eeed78a375d99c924e52ec84d32d984cb"- integrity sha512-mdVh/n0QqT2uXqn8kaTywUoLxY1OYqTpiKbt5b51pDwOStqgbIbqBqG0A7XDaiqWa7RKwllOYxPlPm16EDfWUA==+"@next/[email protected]":+ version "13.4.1"+ resolved "https://registry.yarnpkg.com/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-13.4.1.tgz#efe53d48ff51d2485eabb910ab7caee78425fc01"+ integrity sha512-+CXZC7u1iXdLRudecoUYbhbsXpglYv8KFYsFxKBPn7kg+bk7eJo738wAA4jXIl8grTF2mPdmO93JOQym+BlYGA=="@next/[email protected]":version "13.1.6"resolved "https://registry.yarnpkg.com/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-13.1.6.tgz#498bc11c91b4c482a625bf4b978f98ae91111e46"integrity sha512-g8zowiuP8FxUR9zslPmlju7qYbs2XBtTLVSxVikPtUDQedhcls39uKYLvOOd1JZg0ehyhopobRoH1q+MHlIN/w==-"@next/[email protected]":- version "13.4.0"- resolved "https://registry.yarnpkg.com/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-13.4.0.tgz#e32f0e30cd479805aab0e938e90788726dec36c7"- integrity sha512-GNRqT2mqxxH0x9VthFqziBj8X8HsoBUougmLe3kOouRq/jF73LpKXG0Qs2MYkylqvv/Wg31EYjFNcJnBi1Nimg==+"@next/[email protected]":+ version "13.4.1"+ resolved "https://registry.yarnpkg.com/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-13.4.1.tgz#952cdf1c53df46a90d5151d99310195d2c384e55"+ integrity sha512-vIoXVVc7UYO68VwVMDKwJC2+HqAZQtCYiVlApyKEeIPIQpz2gpufzGxk1z3/gwrJt/kJ5CDZjlhYDCzd3hdz+g=="@next/[email protected]":version "13.1.6"resolved "https://registry.yarnpkg.com/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-13.1.6.tgz#17ed919c723426b7d0ce1cd73d40ce3dcd342089"integrity sha512-Ls2OL9hi3YlJKGNdKv8k3X/lLgc3VmLG3a/DeTkAd+lAituJp8ZHmRmm9f9SL84fT3CotlzcgbdaCDfFwFA6bA==-"@next/[email protected]":- version "13.4.0"- resolved "https://registry.yarnpkg.com/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-13.4.0.tgz#19ab6fe9afd770a223f00694149d0465b35518e4"- integrity sha512-0AkvhUBUqeb4WKN75IW1KjPkN3HazQFA0OpMuTK+6ptJUXMaMwDDcF3sIPCI741BJ2fpODB7BPM4C63hXWEypg==+"@next/[email protected]":+ version "13.4.1"+ resolved "https://registry.yarnpkg.com/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-13.4.1.tgz#447b7dcee5f5d4824cdff331a4ec34b13d0b449d"+ integrity sha512-n8V5ImLQZibKTu10UUdI3nIeTLkliEXe628qxqW9v8My3BAH2a7H0SaCqkV2OgqFnn8sG1wxKYw9/SNJ632kSA=="@nodelib/[email protected]":version "2.1.5"@@ -3151,6 +3151,11 @@ cloudinary@^1.32.0:optionalDependencies:proxy-agent "^5.0.0"+clsx@^1.2.1:+ version "1.2.1"+ resolved "https://registry.yarnpkg.com/clsx/-/clsx-1.2.1.tgz#0ddc4a20a549b59c93a4116bb26f5294ca17dc12"+ integrity sha512-EcR6r5a8bj6pu3ycsa/E/cKVGuTgZJZdsyUYHOksG/UHIiKfjxzRxYJpyVBwYaQeOvghal9fcc4PidlgzugAQg==+cmd-shim@^6.0.0:version "6.0.0"resolved "https://registry.yarnpkg.com/cmd-shim/-/cmd-shim-6.0.0.tgz#6c4eb6437defacf0ae8e9d281d5b06749730a65b"@@ -6712,12 +6717,12 @@ [email protected]:"@next/swc-win32-ia32-msvc" "13.1.6""@next/swc-win32-x64-msvc" "13.1.6"-next@^13.4.0:- version "13.4.0"- resolved "https://registry.yarnpkg.com/next/-/next-13.4.0.tgz#b6c2c65f9c5a06145b75fd52c723bc6b57cb0be7"- integrity sha512-y3E+2ZjiVrphkz7zcJvd2rEG6miOekI8krPfWV4AZZ9TaF0LDuFdP/f+RQ5M9wRvsz6GWw8k8+7jsO860GxSqg==+next@^13.3.2:+ version "13.4.1"+ resolved "https://registry.yarnpkg.com/next/-/next-13.4.1.tgz#8d23f94c81b3f9cc8b34165ad528457e5befd726"+ integrity sha512-JBw2kAIyhKDpjhEWvNVoFeIzNp9xNxg8wrthDOtMctfn3EpqGCmW0FSviNyGgOSOSn6zDaX48pmvbdf6X2W9xA==dependencies:- "@next/env" "13.4.0"+ "@next/env" "13.4.1""@swc/helpers" "0.5.1"busboy "1.6.0"caniuse-lite "^1.0.30001406"@@ -6725,15 +6730,15 @@ next@^13.4.0:styled-jsx "5.1.1"zod "3.21.4"optionalDependencies:- "@next/swc-darwin-arm64" "13.4.0"- "@next/swc-darwin-x64" "13.4.0"- "@next/swc-linux-arm64-gnu" "13.4.0"- "@next/swc-linux-arm64-musl" "13.4.0"- "@next/swc-linux-x64-gnu" "13.4.0"- "@next/swc-linux-x64-musl" "13.4.0"- "@next/swc-win32-arm64-msvc" "13.4.0"- "@next/swc-win32-ia32-msvc" "13.4.0"- "@next/swc-win32-x64-msvc" "13.4.0"+ "@next/swc-darwin-arm64" "13.4.1"+ "@next/swc-darwin-x64" "13.4.1"+ "@next/swc-linux-arm64-gnu" "13.4.1"+ "@next/swc-linux-arm64-musl" "13.4.1"+ "@next/swc-linux-x64-gnu" "13.4.1"+ "@next/swc-linux-x64-musl" "13.4.1"+ "@next/swc-win32-arm64-msvc" "13.4.1"+ "@next/swc-win32-ia32-msvc" "13.4.1"+ "@next/swc-win32-x64-msvc" "13.4.1"no-case@^2.2.0:version "2.3.2"