1
mirror of https://github.com/jakejarvis/jarv.is.git synced 2025-04-26 04:45:22 -04:00

remove dependency on uglify-js

This commit is contained in:
Jake Jarvis 2024-02-26 10:49:14 -05:00
parent ace50ff2c9
commit 955cfe421f
Signed by: jake
SSH Key Fingerprint: SHA256:nCkvAjYA6XaSPUqc4TfbBQTpzr8Xj7ritg/sGInCdkc
19 changed files with 239 additions and 418 deletions

View File

@ -1,10 +1,10 @@
AIRTABLE_API_KEY=
AIRTABLE_BASE=
# absolutely required:
NEXT_PUBLIC_BASE_URL=
GH_PUBLIC_TOKEN=
HCAPTCHA_SECRET_KEY=
NEXT_PUBLIC_HCAPTCHA_SITE_KEY=
POSTGRES_URL=
POSTGRES_URL_NON_POOLING=
SPOTIFY_CLIENT_ID=
SPOTIFY_CLIENT_SECRET=
SPOTIFY_REFRESH_TOKEN=
# optional (but not really):
AIRTABLE_API_KEY=
AIRTABLE_BASE=
HCAPTCHA_SECRET_KEY=

View File

@ -1,6 +1,7 @@
import HCaptcha from "@hcaptcha/react-hcaptcha";
import useHasMounted from "../../hooks/useHasMounted";
import useTheme from "../../hooks/useTheme";
import { hcaptchaSiteKey } from "../../lib/config";
export type CaptchaProps = {
size?: "normal" | "compact" | "invisible";
@ -27,7 +28,7 @@ const Captcha = ({ size = "normal", theme, className, ...rest }: CaptchaProps) =
<div className={className}>
{hasMounted && (
<HCaptcha
sitekey={process.env.NEXT_PUBLIC_HCAPTCHA_SITE_KEY || ""}
sitekey={hcaptchaSiteKey || "10000000-ffff-ffff-ffff-000000000001"}
reCaptchaCompat={false}
tabIndex={0}
size={size}

View File

@ -43,7 +43,10 @@ const Link = ({ href, rel, target, prefetch = false, underline = true, openInNew
// links) or a new tab (the default for external links). Defaults can be overridden with `openInNewTab={true}`.
const isExternal =
typeof href === "string" &&
!(href[0] === "/" || href[0] === "#" || (process.env.BASE_URL && href.startsWith(process.env.BASE_URL)));
!(
["/", "#"].includes(href[0]) ||
(process.env.NEXT_PUBLIC_BASE_URL && href.startsWith(process.env.NEXT_PUBLIC_BASE_URL))
);
if (openInNewTab || isExternal) {
return (

View File

@ -18,6 +18,7 @@ module.exports = {
verifyGoogle: "qQhmLTwjNWYgQ7W42nSTq63xIrTch13X_11mmxBE9zk",
verifyBing: "164551986DA47F7F6FC0D21A93FFFCA6",
fathomSiteId: "PIUEIVIZ",
hcaptchaSiteKey: "60d959de-b01b-4e22-a901-ce395ed086cb",
giscusConfig: {
// https://github.com/giscus/giscus-component/tree/main/packages/react#readme
repo: "jakejarvis/jarv.is",

View File

@ -3,6 +3,8 @@ import { meJpg, faviconPng, faviconIco, appleTouchIconPng } from "./favicons";
import type { DefaultSeoProps, SocialProfileJsonLdProps, ArticleJsonLdProps } from "next-seo";
const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || `https://${config.siteDomain}`;
// Most of this file simply takes the data already defined in ./config.js and translates it into objects that are
// compatible with next-seo's props:
// https://github.com/garmeeh/next-seo#default-seo-configuration
@ -17,7 +19,7 @@ export const defaultSeo: DefaultSeoProps = {
type: "website",
images: [
{
url: `${process.env.BASE_URL}${meJpg.src}`,
url: `${baseUrl}${meJpg.src}`,
alt: `${config.siteName} ${config.shortDescription}`,
},
],
@ -95,9 +97,9 @@ export const defaultSeo: DefaultSeoProps = {
export const socialProfileJsonLd: SocialProfileJsonLdProps = {
type: "Person",
name: config.authorName,
url: `${process.env.BASE_URL}/`,
url: `${baseUrl}/`,
sameAs: [
`${process.env.BASE_URL}/`,
`${baseUrl}/`,
`https://github.com/${config.authorSocial?.github}`,
`https://keybase.io/${config.authorSocial?.keybase}`,
`https://twitter.com/${config.authorSocial?.twitter}`,
@ -114,8 +116,8 @@ export const socialProfileJsonLd: SocialProfileJsonLdProps = {
export const articleJsonLd: Pick<ArticleJsonLdProps, "authorName" | "publisherName" | "publisherLogo"> = {
authorName: {
name: config.authorName,
url: `${process.env.BASE_URL}/`,
url: `${baseUrl}/`,
},
publisherName: config.siteName,
publisherLogo: `${process.env.BASE_URL}${meJpg.src}`,
publisherLogo: `${baseUrl}${meJpg.src}`,
};

View File

@ -18,23 +18,24 @@ export const buildFeed = async (
options?: BuildFeedOptions
): Promise<ReturnType<GetServerSideFeedProps>> => {
const { res } = context;
const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || `https://${config.siteDomain}`;
// https://github.com/jpmonette/feed#example
const feed = new Feed({
id: `${process.env.BASE_URL}/`,
link: `${process.env.BASE_URL}/`,
id: `${baseUrl}/`,
link: `${baseUrl}/`,
title: config.siteName,
description: config.longDescription,
copyright: config.licenseUrl,
updated: new Date(process.env.RELEASE_DATE || Date.now()),
image: `${process.env.BASE_URL}${meJpg.src}`,
image: `${baseUrl}${meJpg.src}`,
feedLinks: {
rss: `${process.env.BASE_URL}/feed.xml`,
atom: `${process.env.BASE_URL}/feed.atom`,
rss: `${baseUrl}/feed.xml`,
atom: `${baseUrl}/feed.atom`,
},
author: {
name: config.authorName,
link: `${process.env.BASE_URL}/`,
link: `${baseUrl}/`,
email: config.authorEmail,
},
});
@ -47,11 +48,11 @@ export const buildFeed = async (
link: note.permalink,
title: note.title,
description: note.description,
image: note.image && `${process.env.BASE_URL}${note.image}`,
image: note.image && `${baseUrl}${note.image}`,
author: [
{
name: config.authorName,
link: `${process.env.BASE_URL}/`,
link: `${baseUrl}/`,
},
],
date: new Date(note.date),

View File

@ -1,5 +1,4 @@
import { serialize } from "next-mdx-remote/serialize";
import { minify } from "uglify-js";
import { getNoteData } from "./parse-notes";
import type { NoteWithSource } from "../../types";
@ -12,7 +11,7 @@ export const compileNote = async (slug: string): Promise<NoteWithSource> => {
"./remark-rehype-plugins"
);
const source = await serialize(content, {
const { compiledSource } = await serialize(content, {
parseFrontmatter: false,
mdxOptions: {
remarkPlugins: [
@ -40,19 +39,6 @@ export const compileNote = async (slug: string): Promise<NoteWithSource> => {
},
});
// TODO: next-mdx-remote v4 doesn't (yet?) minify compiled JSX output, see:
// https://github.com/hashicorp/next-mdx-remote/pull/211#issuecomment-1013658514
// ...so for now, let's do it manually (and conservatively) with uglify-js when building for production.
const compiledSource =
process.env.NODE_ENV === "production"
? minify(source.compiledSource, {
toplevel: true,
parse: {
bare_returns: true,
},
}).code
: source.compiledSource;
return {
frontMatter,
source: {

View File

@ -69,7 +69,7 @@ export const getNoteData = async (
title,
htmlTitle,
slug,
permalink: `${process.env.BASE_URL}/notes/${slug}/`,
permalink: `${process.env.NEXT_PUBLIC_BASE_URL || ""}/notes/${slug}/`,
date: formatDate(data.date), // validate/normalize the date string provided from front matter
},
content,

View File

@ -16,13 +16,6 @@ const nextConfig = {
"react-tweet", // https://react-tweet.vercel.app/next#troubleshooting
],
env: {
BASE_URL:
// start with production check on Vercel, then see if this is a deploy preview, then fallback to local dev server.
process.env.NEXT_PUBLIC_VERCEL_ENV === "production"
? `https://${config.siteDomain}`
: process.env.NEXT_PUBLIC_VERCEL_URL
? `https://${process.env.NEXT_PUBLIC_VERCEL_URL}` // https://vercel.com/docs/concepts/projects/environment-variables#system-environment-variables
: `http://localhost:${process.env.PORT || 3000}`, // https://nextjs.org/docs/api-reference/cli#development
// freeze timestamp at build time for when server-side pages need a "last updated" date. calling Date.now() from
// pages using getServerSideProps will return the current(ish) time instead, which is usually not what we want.
RELEASE_DATE: new Date().toISOString(),

View File

@ -18,12 +18,12 @@
"postinstall": "prisma generate"
},
"dependencies": {
"@giscus/react": "^2.4.0",
"@giscus/react": "^3.0.0",
"@hcaptcha/react-hcaptcha": "^1.10.1",
"@novnc/novnc": "1.4.0",
"@octokit/graphql": "^7.0.2",
"@octokit/graphql-schema": "^14.56.0",
"@prisma/client": "^5.9.1",
"@octokit/graphql-schema": "^14.57.0",
"@prisma/client": "^5.10.2",
"@react-spring/web": "^9.7.3",
"@stitches/react": "1.3.1-1",
"@vercel/edge": "^1.1.1",
@ -44,14 +44,14 @@
"p-memoize": "^7.1.1",
"polished": "^4.3.1",
"prop-types": "^15.8.1",
"query-string": "^8.2.0",
"query-string": "^9.0.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-error-boundary": "^4.0.12",
"react-frame-component": "^5.2.6",
"react-icons": "^5.0.1",
"react-innertext": "^1.1.5",
"react-intersection-observer": "^9.8.0",
"react-intersection-observer": "^9.8.1",
"react-is": "18.2.0",
"react-player": "^2.14.1",
"react-textarea-autosize": "^8.5.3",
@ -73,27 +73,25 @@
"devDependencies": {
"@jakejarvis/eslint-config": "^3.1.0",
"@types/comma-number": "^2.1.2",
"@types/node": "^20.11.19",
"@types/node": "^20.11.20",
"@types/novnc__novnc": "^1.3.4",
"@types/prop-types": "^15.7.11",
"@types/react": "^18.2.56",
"@types/react": "^18.2.58",
"@types/react-dom": "^18.2.19",
"@types/react-is": "^18.2.4",
"@types/uglify-js": "^3.17.4",
"@typescript-eslint/eslint-plugin": "^7.0.2",
"@typescript-eslint/parser": "^7.0.2",
"cross-env": "^7.0.3",
"eslint": "~8.56.0",
"eslint": "~8.57.0",
"eslint-config-next": "14.1.0",
"eslint-config-prettier": "~9.1.0",
"eslint-plugin-mdx": "~3.1.5",
"eslint-plugin-prettier": "~5.1.3",
"lint-staged": "^15.2.2",
"prettier": "^3.2.5",
"prisma": "^5.9.1",
"prisma": "^5.10.2",
"simple-git-hooks": "^2.9.0",
"typescript": "^5.3.3",
"uglify-js": "^3.17.4"
"typescript": "^5.3.3"
},
"optionalDependencies": {
"sharp": "^0.33.2"

View File

@ -23,7 +23,7 @@ const App = ({ Component, pageProps }: AppProps) => {
// get this page's URL with full domain, and hack around query parameters and anchors
// NOTE: this assumes trailing slashes are enabled in next.config.js
const canonical = `${process.env.BASE_URL}${router.pathname === "/" ? "" : router.pathname}/`;
const canonical = `${process.env.NEXT_PUBLIC_BASE_URL || ""}${router.pathname === "/" ? "" : router.pathname}/`;
useEffect(() => {
// don't track pageviews on branch/deploy previews and localhost

View File

@ -1,10 +1,10 @@
import { NextResponse } from "next/server";
import queryString from "query-string";
import { siteDomain, hcaptchaSiteKey } from "../../lib/config";
import type { NextRequest } from "next/server";
// fallback to dummy secret for testing: https://docs.hcaptcha.com/#integration-testing-test-keys
const HCAPTCHA_SITE_KEY =
process.env.HCAPTCHA_SITE_KEY || process.env.NEXT_PUBLIC_HCAPTCHA_SITE_KEY || "10000000-ffff-ffff-ffff-000000000001";
const HCAPTCHA_SITE_KEY = hcaptchaSiteKey || "10000000-ffff-ffff-ffff-000000000001";
const HCAPTCHA_SECRET_KEY = process.env.HCAPTCHA_SECRET_KEY || "0x0000000000000000000000000000000000000000";
const HCAPTCHA_API_ENDPOINT = "https://hcaptcha.com/siteverify";
@ -19,7 +19,7 @@ export const config = {
export default async (req: NextRequest) => {
// redirect GET requests to this endpoint to the contact form itself
if (req.method === "GET") {
return NextResponse.redirect(`${process.env.BASE_URL}/contact/`);
return NextResponse.redirect(`${process.env.NEXT_PUBLIC_BASE_URL || `https://${siteDomain}`}/contact/`);
}
// possible weirdness? https://github.com/orgs/vercel/discussions/78#discussioncomment-5089059

View File

@ -1,117 +0,0 @@
// Fetches my Spotify most-played tracks or currently playing track.
// Heavily inspired by @leerob: https://leerob.io/snippets/spotify
import queryString from "query-string";
import { NextResponse } from "next/server";
import type { Track } from "../../types";
const { SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET, SPOTIFY_REFRESH_TOKEN } = process.env;
// https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow
const TOKEN_ENDPOINT = "https://accounts.spotify.com/api/token";
// https://developer.spotify.com/documentation/web-api/reference/#endpoint-get-the-users-currently-playing-track
const NOW_PLAYING_ENDPOINT = "https://api.spotify.com/v1/me/player/currently-playing";
// https://developer.spotify.com/documentation/web-api/reference/#endpoint-get-users-top-artists-and-tracks
const TOP_TRACKS_ENDPOINT = "https://api.spotify.com/v1/me/top/tracks?time_range=long_term&limit=10";
type SpotifyTrackSchema = {
name: string;
artists: Array<{
name: string;
}>;
album: {
name: string;
images?: Array<{
url: URL | string;
}>;
};
imageUrl?: URL | string;
external_urls: {
spotify: URL | string;
};
};
export const config = {
runtime: "edge",
};
// eslint-disable-next-line import/no-anonymous-default-export
export default async () => {
const token = await getAccessToken();
const [playing, top] = await Promise.all([getNowPlaying(token), getTopTracks(token)]);
return NextResponse.json({ playing, top }, { status: 200 });
};
const getAccessToken = async () => {
const basic = Buffer.from(`${SPOTIFY_CLIENT_ID}:${SPOTIFY_CLIENT_SECRET}`).toString("base64");
const response = await fetch(TOKEN_ENDPOINT, {
method: "POST",
headers: {
Authorization: `Basic ${basic}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body: queryString.stringify({
grant_type: "refresh_token",
refresh_token: SPOTIFY_REFRESH_TOKEN,
}),
});
const { access_token: token } = await response.json();
return token;
};
const getNowPlaying = async (token: string): Promise<Track | false> => {
const response = await fetch(NOW_PLAYING_ENDPOINT, {
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "application/json",
},
});
if (response.status === 204 || response.status > 400) {
return false;
}
const active = (await response.json()) as {
is_playing: boolean;
item?: SpotifyTrackSchema;
};
if (active?.is_playing === true && active?.item) {
return {
artist: active.item.artists.map((artist) => artist.name).join(", "),
title: active.item.name,
album: active.item.album.name,
image: active.item.album.images ? active.item.album.images[0].url : undefined,
url: active.item.external_urls.spotify,
};
}
return false;
};
const getTopTracks = async (token: string): Promise<Track[]> => {
const response = await fetch(TOP_TRACKS_ENDPOINT, {
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "application/json",
},
});
const { items } = (await response.json()) as { items: SpotifyTrackSchema[] };
const tracks = items.map<Track>((track) => ({
artist: track.artists.map((artist) => artist.name).join(", "),
title: track.name,
album: track.album.name,
image: track.album.images ? track.album.images[0].url : undefined,
url: track.external_urls.spotify,
}));
return tracks;
};

View File

@ -32,7 +32,7 @@ const Note = ({ frontMatter, source }: InferGetStaticPropsType<typeof getStaticP
},
images: [
{
url: `${process.env.BASE_URL}${frontMatter.image || meJpg.src}`,
url: `${process.env.NEXT_PUBLIC_BASE_URL || ""}${frontMatter.image || meJpg.src}`,
alt: frontMatter.title,
},
],
@ -47,7 +47,7 @@ const Note = ({ frontMatter, source }: InferGetStaticPropsType<typeof getStaticP
description={frontMatter.description || config.longDescription}
datePublished={frontMatter.date}
dateModified={frontMatter.date}
images={[`${process.env.BASE_URL}${frontMatter.image || meJpg.src}`]}
images={[`${process.env.NEXT_PUBLIC_BASE_URL || ""}${frontMatter.image || meJpg.src}`]}
{...articleJsonLd}
/>

View File

@ -11,7 +11,7 @@ ${
? `Disallow: /`
: `Allow: /
Sitemap: ${process.env.BASE_URL}/sitemap.xml`
Sitemap: ${process.env.NEXT_PUBLIC_BASE_URL || ""}/sitemap.xml`
}
`;

View File

@ -1,11 +1,12 @@
import { SitemapStream, EnumChangefreq } from "sitemap";
import { getAllNotes } from "../lib/helpers/parse-notes";
import { siteDomain } from "../lib/config";
import type { GetServerSideProps } from "next";
import type { SitemapItemLoose } from "sitemap";
export const getServerSideProps: GetServerSideProps<Record<string, never>> = async (context) => {
const { res } = context;
const stream = new SitemapStream({ hostname: process.env.BASE_URL });
const stream = new SitemapStream({ hostname: process.env.NEXT_PUBLIC_BASE_URL || `https://${siteDomain}` });
// cache on edge for 12 hours
res.setHeader("cache-control", "public, max-age=0, s-maxage=43200, stale-while-revalidate");

416
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

1
types/index.d.ts vendored
View File

@ -1,4 +1,3 @@
export * from "./note";
export * from "./project";
export * from "./stats";
export * from "./track";

7
types/track.d.ts vendored
View File

@ -1,7 +0,0 @@
export type Track = {
artist: string;
title: string;
album: string;
url: URL | string;
image?: URL | string;
};