1 Commits

Author SHA1 Message Date
Renovate Bot
5c6f25b095 Update dependency eslint to v9 2024-10-09 23:06:33 +00:00
24 changed files with 155 additions and 337 deletions

View File

@ -1,56 +0,0 @@
name: Deploy & Publish Image
on:
push:
branches: [ "master" ]
paths-ignore:
- README.md
- LICENSE
jobs:
deploy:
strategy:
matrix:
arch: [ "ubuntu-latest" ]
git-version: [ "2.44.0" ]
runs-on: ${{ matrix.arch }}
# Steps to run
steps:
# Checkout the repo
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
# Deploy to Dokku
- name: Deploy to Dokku
uses: dokku/github-action@master
with:
git_remote_url: "ssh://dokku@10.10.70.73:22/docs"
ssh_private_key: ${{ secrets.DOKKU_SSH_PRIVATE_KEY }}
# Set up Docker Buildx
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
# Login to the Docker registry
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
registry: git.rainnny.club
username: ${{ secrets.REGISTRY_USERNAME }}
password: ${{ secrets.REGISTRY_TOKEN }}
# Publish the image
- name: Build Image
uses: docker/build-push-action@v6
with:
context: .
file: ./Dockerfile
push: true
tags: |
git.rainnny.club/pulseapp/docs:${{ github.sha }}
git.rainnny.club/pulseapp/docs:latest
build-args: |
GIT_REV=${{ gitea.sha }}

View File

@ -0,0 +1,31 @@
name: Deploy
on:
push:
branches: [ "master" ]
paths-ignore:
- README.md
- LICENSE
jobs:
deploy:
strategy:
matrix:
arch: [ "ubuntu-latest" ]
git-version: [ "2.44.0" ]
runs-on: ${{ matrix.arch }}
# Steps to run
steps:
# Checkout the repo
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
# Deploy to Dokku
- name: Deploy to Dokku
uses: dokku/github-action@master
with:
git_remote_url: "ssh://dokku@10.10.70.73:22/docs"
ssh_private_key: ${{ secrets.DOKKU_SSH_PRIVATE_KEY }}

1
.gitignore vendored
View File

@ -6,6 +6,7 @@ node_modules
.env*.local .env*.local
next-env.d.ts next-env.d.ts
.sentryclirc .sentryclirc
config.json
sw.* sw.*
workbox-* workbox-*
swe-worker-* swe-worker-*

View File

@ -13,7 +13,8 @@ FROM base AS builder
WORKDIR /usr/src/app WORKDIR /usr/src/app
COPY --from=depends /usr/src/app/node_modules ./node_modules COPY --from=depends /usr/src/app/node_modules ./node_modules
COPY . . COPY . .
ENV NEXT_TELEMETRY_DISABLED=1 ENV NEXT_TELEMETRY_DISABLED 1
RUN --mount=type=bind,target=/config,from=docs cp /config/config.json ./config.json
RUN bun run build RUN bun run build
@ -32,15 +33,16 @@ COPY --from=builder --chown=nextjs:nextjs /usr/src/app/.next ./.next
COPY --from=builder --chown=nextjs:nextjs /usr/src/app/public ./public COPY --from=builder --chown=nextjs:nextjs /usr/src/app/public ./public
COPY --from=builder --chown=nextjs:nextjs /usr/src/app/next.config.mjs ./next.config.mjs COPY --from=builder --chown=nextjs:nextjs /usr/src/app/next.config.mjs ./next.config.mjs
COPY --from=builder --chown=nextjs:nextjs /usr/src/app/package.json ./package.json COPY --from=builder --chown=nextjs:nextjs /usr/src/app/package.json ./package.json
COPY --from=builder --chown=nextjs:nextjs /usr/src/app/config.json ./config.json
COPY --from=builder --chown=nextjs:nextjs /usr/src/app/docs ./docs COPY --from=builder --chown=nextjs:nextjs /usr/src/app/docs ./docs
ENV NODE_ENV=production ENV NODE_ENV production
# Exposting on port 80 so we can # Exposting on port 80 so we can
# access via a reverse proxy for Dokku # access via a reverse proxy for Dokku
ENV HOSTNAME="0.0.0.0" ENV HOSTNAME "0.0.0.0"
EXPOSE 80 EXPOSE 80
ENV PORT=80 ENV PORT 80
USER nextjs USER nextjs
CMD ["node", "server.js"] CMD node server.js

BIN
bun.lockb

Binary file not shown.

View File

@ -1,6 +1,5 @@
{ {
"siteName": "Pulse App", "siteName": "Pulse App",
"ogApiUrl": "https://docs.pulseapp.cc/api/og?title={title}",
"metadata": { "metadata": {
"title": { "title": {
"default": "Pulse Docs", "default": "Pulse Docs",
@ -23,8 +22,7 @@
"viewport": { "viewport": {
"themeColor": "#A855F7" "themeColor": "#A855F7"
}, },
"contentSource": "https://git.rainnny.club/PulseApp/docs-content.git", "contentSource": "{process}/docs",
"contentEditUrl": "https://git.rainnny.club/PulseApp/docs-content/src/branch/master/{slug}{ext}",
"socialLinks": [ "socialLinks": [
{ {
"name": "GitHub", "name": "GitHub",

View File

@ -1,10 +0,0 @@
services:
app:
image: git.rainnny.club/pulseapp/docs:latest
restart: unless-stopped
container_name: docs
ports:
- "8080:80"
volumes:
- ./config.json:/usr/src/app/config.json
- ./docs:/usr/src/app/docs

View File

@ -0,0 +1,9 @@
---
title: '🐋 Docker'
updated: '2024-10-07'
summary: 'petentium usu tota noluisse errem elaboraret auctor.'
order: 4
---
# 🐋 Deploying on Docker
...

View File

@ -0,0 +1,9 @@
---
title: '🧩 Components'
updated: '2024-10-07'
summary: 'petentium usu tota noluisse errem elaboraret auctor.'
order: 2
---
# 🧩 Components
...

View File

@ -0,0 +1,9 @@
---
title: '✔️ Supported Services'
updated: '2024-10-07'
summary: 'petentium usu tota noluisse errem elaboraret auctor.'
order: 3
---
# ✔️ Supported Services
Below is a list of all the services that are currently supported by Pulse App. Are we missing a service? Please [open an issue](https://git.rainnny.club/PulseApp/API/issues)!

View File

@ -1,9 +1,22 @@
--- ---
title: 'Example' title: '🚀 Introduction'
updated: '2024-10-06' updated: '2024-10-06'
summary: 'petentium usu tota noluisse errem elaboraret auctor.' summary: 'petentium usu tota noluisse errem elaboraret auctor.'
order: 1 order: 1
--- ---
# Hello World > [!IMPORTANT]
This is an example content file. > These docs are currently a work in progress and are subject to change.
# <span className="flex gap-2.5 items-center"><Activity className="w-6 h-6 text-primary" /> Pulse App</span>
A lightweight service monitoring solution for tracking the availability of whatever service your heart desires!
## Getting Started
Let's get you up and running—this will only take a few minutes! Start by [creating your account](#creating-your-account) and
making your first status page. You can do this on our cloud or on your [own instance](/self-hosting). Once done, you can add
your services and start monitoring them. See [Next Steps](#next-steps) for more.
### Creating your Account
- First, head to our [Dashboard](https://pulseapp.cc/dashboard) and fill out the form. ![Registering](https://cdn.rainnny.club/auhNOjrcYz6u.png)
- Next, complete the onboarding process and set up your first organization, and status page. ![Onboarding](https://cdn.rainnny.club/AfDgjHG5QTpZ.png)
- Finally, you can [start monitoring your services](#next-steps)!

View File

@ -20,12 +20,11 @@
"@radix-ui/react-separator": "^1.1.0", "@radix-ui/react-separator": "^1.1.0",
"@radix-ui/react-slot": "^1.1.0", "@radix-ui/react-slot": "^1.1.0",
"@radix-ui/react-tooltip": "^1.1.3", "@radix-ui/react-tooltip": "^1.1.3",
"@vercel/og": "^0.6.3",
"class-variance-authority": "^0.7.0", "class-variance-authority": "^0.7.0",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"cmdk": "1.0.0", "cmdk": "1.0.0",
"framer-motion": "^11.11.1", "framer-motion": "^11.11.1",
"lucide-react": "^0.452.0", "lucide-react": "^0.447.0",
"luxon": "^3.5.0", "luxon": "^3.5.0",
"next": "^15.0.0-canary.179", "next": "^15.0.0-canary.179",
"next-themes": "^0.3.0", "next-themes": "^0.3.0",
@ -42,8 +41,8 @@
"@types/node": "^22.0.0", "@types/node": "^22.0.0",
"@types/react": "^18", "@types/react": "^18",
"@types/react-dom": "^18", "@types/react-dom": "^18",
"eslint": "^8", "eslint": "^9.0.0",
"eslint-config-next": "15.1.3", "eslint-config-next": "14.2.15",
"postcss": "^8", "postcss": "^8",
"tailwindcss": "^3.4.1", "tailwindcss": "^3.4.1",
"typescript": "^5" "typescript": "^5"

View File

@ -14,7 +14,6 @@ import { Metadata } from "next";
import Embed from "@/components/embed"; import Embed from "@/components/embed";
import DocsFooter from "@/components/docs-footer"; import DocsFooter from "@/components/docs-footer";
import OnThisPage from "@/components/on-this-page"; import OnThisPage from "@/components/on-this-page";
import config from "@/config";
/** /**
* The page to render the documentation markdown content. * The page to render the documentation markdown content.
@ -35,7 +34,7 @@ const DocsPage = async ({
const decodedSlug: string = decodeURIComponent(slug || ""); const decodedSlug: string = decodeURIComponent(slug || "");
const page: DocsContentMetadata | undefined = pages.find( const page: DocsContentMetadata | undefined = pages.find(
(metadata: DocsContentMetadata): boolean => (metadata: DocsContentMetadata): boolean =>
metadata.slug === (decodedSlug || pages[0].slug) metadata.slug === (decodedSlug || "intro")
); );
if (!page) { if (!page) {
notFound(); notFound();
@ -100,19 +99,17 @@ export const generateMetadata = async ({
}): Promise<Metadata | undefined> => { }): Promise<Metadata | undefined> => {
const slug: string = (((await params).slug as string[]) || undefined)?.join( const slug: string = (((await params).slug as string[]) || undefined)?.join(
"/" "/"
); ); // The slug of the content
if (slug) { if (slug) {
const pages: DocsContentMetadata[] = await getDocsContent(); const content: DocsContentMetadata | undefined = (
const decodedSlug: string = decodeURIComponent(slug || ""); await getDocsContent()
const page: DocsContentMetadata | undefined = pages.find( ).find(
(metadata: DocsContentMetadata): boolean => (metadata: DocsContentMetadata): boolean => metadata.slug === slug
metadata.slug === (decodedSlug || pages[0].slug) ); // Get the content based on the provided slug
); if (content) {
if (page) {
return Embed({ return Embed({
title: page.title, title: content.title,
description: page.summary, description: content.summary,
thumbnail: config.ogApiUrl.replace("{title}", page.title),
}); });
} }
} }

View File

@ -1,30 +0,0 @@
import { ImageResponse } from "next/og";
import config from "@/config";
export const GET = async (request: Request) => {
const { searchParams } = new URL(request.url);
const title: string | undefined = searchParams.has("title")
? searchParams.get("title")?.slice(0, 100)
: "Hello World (:";
return new ImageResponse(
(
<div tw="w-full h-full flex flex-col justify-center items-center bg-black/95 text-white">
{/* Logo */}
<img
src={(config.metadata.openGraph?.images as any)[0].url}
alt={`${config.siteName} Logo`}
width={96}
height={96}
/>
{/* Title */}
<h1 tw="text-5xl font-bold">{title}</h1>
</div>
),
{
width: 1200,
height: 630,
}
);
};

View File

@ -15,8 +15,6 @@ import config from "@/config";
export const metadata: Metadata = config.metadata; export const metadata: Metadata = config.metadata;
export const viewport: Viewport = config.viewport; export const viewport: Viewport = config.viewport;
export const dynamic = "force-dynamic";
/** /**
* The primary layout for this app. * The primary layout for this app.
*/ */
@ -28,22 +26,17 @@ const RootLayout = async ({
const pages: DocsContentMetadata[] = await getDocsContent(); const pages: DocsContentMetadata[] = await getDocsContent();
return ( return (
<html lang="en"> <html lang="en">
<body <ThemeProvider attribute="class" defaultTheme="dark" enableSystem>
className="scroll-smooth antialiased" <body
style={{ className="scroll-smooth antialiased"
background: "var(--background-gradient)", style={{
}} background: "var(--background-gradient)",
> }}
<ThemeProvider
attribute="class"
defaultTheme="dark"
enableSystem
disableTransitionOnChange
> >
<TooltipProvider delayDuration={100}> <TooltipProvider delayDuration={100}>
<div className="px-3 md:px-7 max-w-screen-2xl min-h-screen mx-auto flex flex-col transition-transform"> <div className="px-3 md:px-7 max-w-screen-2xl min-h-screen mx-auto flex flex-col transition-all">
<Navbar pages={pages} /> <Navbar pages={pages} />
<div className="pt-[4.5rem] w-full h-full flex flex-grow gap-5 sm:gap-8 transition-transform transform-gpu"> <div className="pt-[4.5rem] w-full h-full flex flex-grow gap-5 sm:gap-8 transition-all transform-gpu">
<div className="relative hidden xs:flex"> <div className="relative hidden xs:flex">
<Sidebar pages={pages} /> <Sidebar pages={pages} />
</div> </div>
@ -52,8 +45,8 @@ const RootLayout = async ({
</div> </div>
<Footer /> <Footer />
</TooltipProvider> </TooltipProvider>
</ThemeProvider> </body>
</body> </ThemeProvider>
</html> </html>
); );
}; };

View File

@ -6,11 +6,6 @@ export type Config = {
*/ */
siteName: string; siteName: string;
/**
* The URL to use for generating OG images.
*/
ogApiUrl: string;
/** /**
* The metadata for this app. * The metadata for this app.
*/ */
@ -28,11 +23,6 @@ export type Config = {
*/ */
contentSource: string; contentSource: string;
/**
* The URL to link to for editing content of a page.
*/
contentEditUrl: string;
/** /**
* Social links for this app. * Social links for this app.
*/ */

View File

@ -17,8 +17,7 @@ const DocsFooter = ({
const current: number = pages.findIndex( const current: number = pages.findIndex(
(page: DocsContentMetadata) => (page: DocsContentMetadata) =>
(path === "/" && page.slug === pages[0].slug) || (path === "/" && page.slug === "intro") || path === `/${page.slug}`
path === `/${page.slug}`
); );
const previous: DocsContentMetadata | undefined = const previous: DocsContentMetadata | undefined =
current > 0 ? pages[current - 1] : undefined; current > 0 ? pages[current - 1] : undefined;

View File

@ -13,11 +13,6 @@ type EmbedProps = {
* The description of the embed. * The description of the embed.
*/ */
description: string; description: string;
/**
* The optional thumbnail image of the embed.
*/
thumbnail?: string | undefined;
}; };
/** /**
@ -26,25 +21,13 @@ type EmbedProps = {
* @param props the embed props * @param props the embed props
* @returns the embed jsx * @returns the embed jsx
*/ */
const Embed = ({ title, description, thumbnail }: EmbedProps): Metadata => { const Embed = ({ title, description }: EmbedProps): Metadata => {
return { return {
title: title, title: title,
openGraph: { openGraph: {
title: `${title}`, title: `${title}`,
description: description, description: description,
...(thumbnail && {
images: [
{
url: thumbnail,
},
],
}),
}, },
...(thumbnail && {
twitter: {
card: "summary_large_image",
},
}),
}; };
}; };
export default Embed; export default Embed;

View File

@ -8,8 +8,6 @@ import { motion, useInView } from "framer-motion";
import { Separator } from "@/components/ui/separator"; import { Separator } from "@/components/ui/separator";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { AlignLeftIcon, ArrowUpFromDot, MoveRight } from "lucide-react"; import { AlignLeftIcon, ArrowUpFromDot, MoveRight } from "lucide-react";
import config from "@/config";
import { Skeleton } from "@/components/ui/skeleton";
type Header = { type Header = {
id: string; id: string;
@ -18,7 +16,6 @@ type Header = {
}; };
const OnThisPage = ({ page }: { page: DocsContentMetadata }): ReactElement => { const OnThisPage = ({ page }: { page: DocsContentMetadata }): ReactElement => {
const [loading, setLoading] = useState<boolean>(true);
const [headers, setHeaders] = useState<Header[]>([]); const [headers, setHeaders] = useState<Header[]>([]);
const [activeHeader, setActiveHeader] = useState<string | undefined>( const [activeHeader, setActiveHeader] = useState<string | undefined>(
undefined undefined
@ -46,7 +43,6 @@ const OnThisPage = ({ page }: { page: DocsContentMetadata }): ReactElement => {
} }
setHeaders(extractedHeaders); setHeaders(extractedHeaders);
setLoading(false);
}, [page.content]); }, [page.content]);
useEffect(() => { useEffect(() => {
@ -84,7 +80,7 @@ const OnThisPage = ({ page }: { page: DocsContentMetadata }): ReactElement => {
<motion.div <motion.div
ref={ref} ref={ref}
className="sticky top-[7.5rem] w-44 max-h-[calc(100vh-3.5rem)] flex flex-col gap-2 text-sm select-none" className="sticky top-[7.5rem] w-44 max-h-[calc(100vh-3.5rem)] flex flex-col gap-2 text-sm select-none"
initial={{ opacity: 1 }} initial={{ opacity: 0 }}
animate={{ opacity: inView ? 1 : 0 }} animate={{ opacity: inView ? 1 : 0 }}
transition={{ duration: 0.2 }} transition={{ duration: 0.2 }}
> >
@ -96,45 +92,37 @@ const OnThisPage = ({ page }: { page: DocsContentMetadata }): ReactElement => {
{/* Headers */} {/* Headers */}
<ul className="relative"> <ul className="relative">
{loading ? ( {headers.map((header: Header) => (
<Skeleton className="w-full h-5 bg-accent rounded-lg" /> <li
) : headers.length === 0 ? ( key={header.id}
<span className="opacity-75">Nothing ):</span> className={cn(
) : ( "hover:opacity-80 transition-all transform-gpu relative",
headers.map((header: Header) => ( activeHeader === header.id
<li ? "font-semibold text-primary"
key={header.id} : "opacity-65"
className={cn( )}
"hover:opacity-80 transition-all transform-gpu relative", style={{ paddingLeft: `${(header.level - 1) * 16}px` }}
activeHeader === header.id >
? "font-semibold text-primary" {/* Indentation */}
: "opacity-65" {header.level > 1 && (
)} <div
style={{ className="absolute left-0 top-0 bottom-0 border-l border-accent"
paddingLeft: `${(header.level - 1) * 16}px`, style={{
}} left: `${(header.level - 2) * 16 + 4}px`,
> }}
{/* Indentation */} />
{header.level > 1 && ( )}
<div
className="absolute left-0 top-0 bottom-0 border-l border-accent"
style={{
left: `${(header.level - 2) * 16 + 4}px`,
}}
/>
)}
{/* Header */} {/* Header */}
<Link <Link
href={`#${header.id}`} href={`#${header.id}`}
draggable={false} draggable={false}
className="block py-1" className="block py-1"
> >
{truncateText(header.text, 20)} {truncateText(header.text, 20)}
</Link> </Link>
</li> </li>
)) ))}
)}
</ul> </ul>
{/* Footer */} {/* Footer */}
@ -160,9 +148,7 @@ const Footer = ({ page }: { page: DocsContentMetadata }): ReactElement => {
{/* Edit on Git */} {/* Edit on Git */}
<Link <Link
className="flex gap-1.5 items-center text-xs hover:opacity-75 transition-all transform-gpu group" className="flex gap-1.5 items-center text-xs hover:opacity-75 transition-all transform-gpu group"
href={config.contentEditUrl href={`https://git.rainnny.club/PulseApp/docs/src/branch/master/docs/${page.slug}${page.extension}`}
.replace("{slug}", page.slug as string)
.replace("{ext}", page.extension as string)}
target="_blank" target="_blank"
draggable={false} draggable={false}
> >

View File

@ -22,7 +22,7 @@ const SidebarLinks = ({
return ( return (
<div className="flex flex-col gap-1"> <div className="flex flex-col gap-1">
{Object.values(tree).map((node: TreeNode) => ( {Object.values(tree).map((node: TreeNode) => (
<CategoryItem key={node.slug} pages={pages} node={node} /> <CategoryItem key={node.slug} node={node} />
))} ))}
</div> </div>
); );
@ -36,20 +36,17 @@ type TreeNode = {
}; };
const CategoryItem = ({ const CategoryItem = ({
pages,
node, node,
depth = 0, depth = 0,
isLast = true, isLast = true,
}: { }: {
pages: DocsContentMetadata[];
node: TreeNode; node: TreeNode;
depth?: number; depth?: number;
isLast?: boolean; isLast?: boolean;
}) => { }) => {
const path = decodeURIComponent(usePathname()); const path = decodeURIComponent(usePathname());
const active = const active =
(path === "/" && node.slug === pages[0].slug) || (path === "/" && node.slug === "intro") || path === `/${node.slug}`;
path === `/${node.slug}`;
const [isOpen, setIsOpen] = useState(true); const [isOpen, setIsOpen] = useState(true);
const hasChildren = Object.keys(node.children).length > 0; const hasChildren = Object.keys(node.children).length > 0;
@ -75,7 +72,7 @@ const CategoryItem = ({
> >
<Button <Button
className={cn( className={cn(
`relative w-full px-1.5 h-8 justify-between hover:bg-accent/35 hover:opacity-90`, `relative w-full px-1.5 h-8 justify-between hover:bg-accent/35`,
node.isFolder node.isFolder
? "mb-0.5 text-sm font-semibold" ? "mb-0.5 text-sm font-semibold"
: "lg:text-base", : "lg:text-base",
@ -124,7 +121,6 @@ const CategoryItem = ({
(child, index, array) => ( (child, index, array) => (
<CategoryItem <CategoryItem
key={child.slug} key={child.slug}
pages={pages}
node={child} node={child}
depth={depth + 1} depth={depth + 1}
isLast={index === array.length - 1} isLast={index === array.length - 1}

View File

@ -1,10 +1,10 @@
import { ReactElement } from "react"; import { ReactElement } from "react";
import { Separator } from "@/components/ui/separator";
import SidebarLinks from "@/components/sidebar/sidebar-links"; import SidebarLinks from "@/components/sidebar/sidebar-links";
import ThemeSwitcher from "@/components/theme-switcher";
import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet"; import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
import QuickSearchDialog from "@/components/navbar/search-dialog"; import QuickSearchDialog from "@/components/navbar/search-dialog";
import { AlignRightIcon } from "lucide-react"; import { AlignRightIcon } from "lucide-react";
import { Separator } from "@/components/ui/separator";
import ThemeSwitcher from "@/components/theme-switcher";
const Sidebar = ({ pages }: { pages: DocsContentMetadata[] }): ReactElement => ( const Sidebar = ({ pages }: { pages: DocsContentMetadata[] }): ReactElement => (
<> <>
@ -21,7 +21,7 @@ const Sidebar = ({ pages }: { pages: DocsContentMetadata[] }): ReactElement => (
</div> </div>
{/* Desktop */} {/* Desktop */}
<div className="hidden xs:flex sticky top-[4.5rem] max-h-[calc(100vh-4.5rem)] min-w-32 w-40 lg:w-52 py-5 pb-3 flex-col justify-between transition-all transform-gpu overflow-y-auto"> <div className="hidden xs:flex sticky top-[4.5rem] max-h-[calc(100vh-3.5rem)] overflow-y-auto min-w-32 w-40 lg:w-52 py-5 flex-col justify-between transition-all transform-gpu">
<SidebarContent pages={pages} /> <SidebarContent pages={pages} />
</div> </div>
</> </>

View File

@ -1,15 +0,0 @@
import { cn } from "@/lib/utils";
function Skeleton({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
className={cn("animate-pulse rounded-md bg-primary/10", className)}
{...props}
/>
);
}
export { Skeleton };

View File

@ -4,8 +4,6 @@ import path from "node:path";
import config from "@/config"; import config from "@/config";
import simpleGit from "simple-git"; import simpleGit from "simple-git";
import os from "node:os"; import os from "node:os";
import { cache } from "react";
import "server-only";
/** /**
* The regex to match for metadata. * The regex to match for metadata.
@ -26,64 +24,24 @@ const DOCS_DIR: string = isGitUrl(config.contentSource)
? config.contentSource ? config.contentSource
: path.join(config.contentSource.replace("{process}", process.cwd())); : path.join(config.contentSource.replace("{process}", process.cwd()));
const LAST_UPDATE_FILE = path.join(
os.tmpdir(),
"docs_cache",
"last_update.json"
);
const CACHE_DURATION_MS: number = 5 * 60 * 1000; // 5 minutes in milliseconds
/** /**
* Clone the Git repository if DOCS_DIR is a URL, else use the local directory. * Clone the Git repository if DOCS_DIR is a URL, else use the local directory.
* If it's a Git URL, clone it to a cache directory and reuse it. * If it's a Git URL, clone it to a cache directory and reuse it.
*/ */
const getDocsDirectory = cache(async (): Promise<string> => { const getDocsDirectory = async (): Promise<string> => {
if (isGitUrl(DOCS_DIR)) { if (isGitUrl(DOCS_DIR)) {
const repoHash: string = Buffer.from(DOCS_DIR).toString("base64"); // Create a unique identifier based on the repo URL const repoHash: string = Buffer.from(DOCS_DIR).toString("base64"); // Create a unique identifier based on the repo URL
const cacheDir: string = path.join(os.tmpdir(), "docs_cache", repoHash); const cacheDir: string = path.join(os.tmpdir(), "docs_cache", repoHash);
// Pull the latest changes from the repo if we don't have it // Pull the latest changes from the repo if we don't have it
if (!fs.existsSync(cacheDir) || fs.readdirSync(cacheDir).length < 1) { if (!fs.existsSync(cacheDir) || fs.readdirSync(cacheDir).length < 1) {
console.log("Cloning initial docs content from Git..."); await simpleGit().clone(DOCS_DIR, cacheDir, { "--depth": 1 });
try {
await simpleGit().clone(DOCS_DIR, cacheDir, { "--depth": 1 });
storeUpdatedRepoTime();
} catch (error) {
// Simply ignore this error. When cloning the repo for
// the first time, it'll sometimes error saying the dir
// is already created.
}
} else if (shouldUpdateRepo()) {
// Pull the latest changes from Git
console.log("Pulling docs content from Git...");
await simpleGit(cacheDir)
.reset(["--hard"]) // Reset any local changes
.pull(); // Pull latest changes
storeUpdatedRepoTime();
} }
return cacheDir; return cacheDir;
} }
return DOCS_DIR; return DOCS_DIR;
});
const shouldUpdateRepo = (): boolean => {
if (!fs.existsSync(LAST_UPDATE_FILE)) {
return true;
}
return (
Date.now() -
JSON.parse(fs.readFileSync(LAST_UPDATE_FILE, "utf-8")).lastUpdate >
CACHE_DURATION_MS
);
}; };
const storeUpdatedRepoTime = () =>
fs.writeFileSync(
LAST_UPDATE_FILE,
JSON.stringify({ lastUpdate: Date.now() }),
"utf-8"
);
/** /**
* Get the content to display in the docs. * Get the content to display in the docs.
*/ */
@ -117,27 +75,18 @@ const getMetadata = <T extends MDXMetadata>(
const extension: string = path.extname(file); // The file extension const extension: string = path.extname(file); // The file extension
return extension === ".md" || extension === ".mdx"; return extension === ".md" || extension === ".mdx";
}); // Read the MDX files }); // Read the MDX files
const metadata: T[] = []; return files.map((file: string): T => {
for (let i = files.length - 1; i >= 0; i--) {
const file: string = files[i];
const filePath: string = path.join(directory, file); // The path of the file const filePath: string = path.join(directory, file); // The path of the file
const fileMetadata: T | undefined = parseMetadata<T>( return {
fs.readFileSync(filePath, "utf-8")
);
if (!fileMetadata) {
continue;
}
metadata.push({
slug: filePath slug: filePath
.replace(parent, "") .replace(parent, "")
.replace(/\\/g, "/") // Normalize the path .replace(/\\/g, "/") // Normalize the path
.replace(/\.mdx?$/, "") .replace(/\.mdx?$/, "")
.substring(1), .substring(1),
extension: path.extname(file), extension: path.extname(file),
...fileMetadata, ...parseMetadata<T>(fs.readFileSync(filePath, "utf-8")),
}); }; // Map each file to its metadata
} });
return metadata;
}; };
/** /**
@ -148,15 +97,8 @@ const getMetadata = <T extends MDXMetadata>(
* @returns the metadata and content * @returns the metadata and content
* @template T the type of metadata * @template T the type of metadata
*/ */
const parseMetadata = <T extends MDXMetadata>( const parseMetadata = <T extends MDXMetadata>(content: string): T => {
content: string const metadataBlock: string = METADATA_REGEX.exec(content)![1]; // Get the block of metadata
): T | undefined => {
const extracted = METADATA_REGEX.exec(content);
const metadataBlock: string | undefined =
extracted && extracted.length > 1 ? extracted[1] : undefined; // Get the block of metadata
if (!metadataBlock) {
return undefined;
}
content = content.replace(METADATA_REGEX, "").trim(); // Remove the metadata block from the content content = content.replace(METADATA_REGEX, "").trim(); // Remove the metadata block from the content
const metadata: Partial<{ const metadata: Partial<{
[key: string]: string; [key: string]: string;

View File

@ -1,28 +0,0 @@
import { type NextRequest, NextResponse } from "next/server";
export function middleware(request: NextRequest): NextResponse {
const before: number = Date.now();
const response: NextResponse = NextResponse.next();
if (process.env.NODE_ENV === "production") {
const ip: string | null =
request.headers.get("CF-Connecting-IP") ||
request.headers.get("X-Forwarded-For");
console.log(
`${ip} | ${request.method} ${request.nextUrl.pathname} ${response.status} in ${(Date.now() - before).toFixed(0)}ms`
);
}
return response;
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
"/((?!api|_next/static|_next/image|favicon.ico).*)",
],
};