Production-ready animations, transitions, backgrounds, and scenes for Remotion
TypeScript ai-agentsclaude-codedemo-videomcpmcp-servermodel-context-protocolmotion-designproduct-demoreactremotionshadcnvideo
feat: create generate github stars video pag
dev_wandrye6830d007802
diff --git a/app/(home)/components/sections/hero.tsx b/app/(home)/components/sections/hero.tsxindex 5754df36..65a28749 100644--- a/app/(home)/components/sections/hero.tsx+++ b/app/(home)/components/sections/hero.tsx@@ -5,6 +5,7 @@ import { ArrowRight, Pause, Play } from "lucide-react";import { motion } from "motion/react";import Link from "next/link";import { useCallback, useRef, useState } from "react";+import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { INSTALL_COMMAND, SPRING_BOUNCE } from "@/config/site";import { useTrackEvent } from "@/lib/analytics";@@ -54,7 +55,31 @@ export function Hero() {<div className="section"><div className="flex flex-col items-center text-center">- <FadeUp delay={0.06}>+ <FadeUp delay={0.06} className="flex flex-col items-center">+ <Badge+ variant="outline"+ className="mb-5 h-7 gap-1.5 rounded-full px-3 text-xs"+ render={+ <Link+ href="/stars"+ onClick={() =>+ trackEvent("cta_clicked", {+ cta: "hero_stars_badge",+ destination: "/stars",+ })+ }+ />+ }+ >+ <span className="font-semibold text-foreground">New</span>+ <span aria-hidden className="text-muted-foreground/60">+ ·+ </span>+ <span className="text-muted-foreground">+ Turn your repo’s stars into a video+ </span>+ <ArrowRight className="size-3" aria-hidden="true" />+ </Badge><h1 className="max-w-3xl text-balance text-3xl font-semibold leading-[1.1] tracking-tight text-foreground sm:text-4xl md:text-5xl">Cinematic video components,<br className="hidden sm:block" /> now copy-pasteablediff --git a/app/(home)/stars/components/stars-tool.tsx b/app/(home)/stars/components/stars-tool.tsxnew file mode 100644index 00000000..41c43db4--- /dev/null+++ b/app/(home)/stars/components/stars-tool.tsx@@ -0,0 +1,742 @@+"use client";++import { Player, type PlayerRef } from "@remotion/player";+import {+ ArrowRight,+ BookOpen,+ Download,+ Pause,+ Play,+ RotateCcw,+ Settings2,+ X,+} from "lucide-react";+import { motion } from "motion/react";+import Link from "next/link";+import { useQueryState } from "nuqs";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { toast } from "sonner";+import { ComponentCustomizer } from "@/components/docs/component-customizer";+import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Progress } from "@/components/ui/progress";+import { Skeleton } from "@/components/ui/skeleton";+import { Toaster } from "@/components/ui/sonner";+import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@/components/ui/tooltip";+import { SPRING_BOUNCE } from "@/config/site";+import type { ControlConfig } from "@/lib/customizer-config";+import { formatStars } from "@/lib/github";+import { parseRepoInput } from "@/lib/parse-repo";+import { usePrefersReducedMotion } from "@/lib/use-prefers-reduced-motion";+import registry, { type RegistryEntry } from "@/registry/__index__";+import { FadeUp } from "../../components/fade-up";+import { InstallCommand } from "../../components/install-command";++type Orientation = "horizontal" | "vertical";++/** Exactly the success shape returned by GET /api/stargazers. */+type StargazersPayload = {+ owner: string;+ repo: string;+ totalStars: number;+ truncated: boolean;+ stargazers: { login: string; avatarUrl: string; starredAt: string }[];+};++const INSTALL = "npx shadcn@latest add remocn/github-stars";++/** 1280×720 ↔ 720×1280 — the two presets the composition + export render at. */+function dims(orientation: Orientation) {+ return orientation === "vertical"+ ? { width: 720, height: 1280 }+ : { width: 1280, height: 720 };+}++/** Scalar controls surfaced in the optional Customize panel (no array control). */+const CUSTOM_CONTROLS: ControlConfig = {+ accentColor: { type: "color", default: "#ffbb00", label: "Accent" },+ theme: {+ type: "select",+ default: "light",+ options: ["light", "dark"],+ label: "Theme",+ },+ speed: {+ type: "number",+ default: 1,+ min: 1,+ max: 4,+ step: 0.25,+ label: "Speed",+ },+};++export function StarsTool() {+ const entry = registry["github-stars"];+ const reduced = usePrefersReducedMotion();++ // URL state (project rule: nuqs, not raw useSearchParams). `?repo=` reopens a+ // shared link; `?o=h|v` persists the orientation.+ const [repoParam, setRepoParam] = useQueryState("repo", {+ defaultValue: "",+ });+ const [oParam, setOParam] = useQueryState("o", { defaultValue: "h" });+ const orientation: Orientation = oParam === "v" ? "vertical" : "horizontal";++ const [status, setStatus] = useState<"idle" | "generating" | "ready">("idle");+ const [inputValue, setInputValue] = useState(repoParam ?? "");+ const [zeroStars, setZeroStars] = useState(false);+ const [data, setData] = useState<StargazersPayload | null>(null);++ // Customizer values (scalar inputProps only).+ const [accentColor, setAccentColor] = useState("#ffbb00");+ const [theme, setTheme] = useState<"light" | "dark">("light");+ const [speed, setSpeed] = useState(1);+ const [showCustomizer, setShowCustomizer] = useState(false);++ const genAbortRef = useRef<AbortController | null>(null);++ const parsed = parseRepoInput(inputValue);+ const canGenerate = parsed !== null;++ // ---- generation --------------------------------------------------------++ const handleApiError = useCallback((statusCode: number, code?: string) => {+ if (code === "not_found" || statusCode === 404) {+ toast.error("Repository not found — check owner/name");+ } else if (code === "rate_limited" || statusCode === 429) {+ toast.error("GitHub rate limit hit — try again shortly");+ } else if (code === "invalid_repo" || statusCode === 400) {+ toast.error("Invalid repository. Use owner/name");+ } else {+ toast.error("Couldn't reach GitHub — retry");+ }+ }, []);++ const runGeneration = useCallback(+ async (rawRepo: string) => {+ const valid = parseRepoInput(rawRepo);+ if (!valid) {+ toast.error("Enter a repo as owner/name");+ return;+ }+ setZeroStars(false);+ setStatus("generating");++ const controller = new AbortController();+ genAbortRef.current = controller;++ try {+ const res = await fetch(+ `/api/stargazers?repo=${encodeURIComponent(rawRepo)}`,+ { signal: controller.signal },+ );++ if (!res.ok) {+ const body = (await res.json().catch(() => null)) as {+ code?: string;+ } | null;+ handleApiError(res.status, body?.code);+ setStatus("idle");+ return;+ }++ const json = (await res.json()) as StargazersPayload;++ // Zero-star repos come back 200 with an empty list — a friendly inline+ // state, not a hard error.+ if (json.totalStars === 0 || json.stargazers.length === 0) {+ setZeroStars(true);+ setStatus("idle");+ return;+ }++ setData(json);+ setStatus("ready");+ } catch (err) {+ // Cancel (AbortController) returns to idle silently.+ if (err instanceof DOMException && err.name === "AbortError") {+ setStatus("idle");+ return;+ }+ toast.error("Couldn't reach GitHub — retry");+ setStatus("idle");+ } finally {+ genAbortRef.current = null;+ }+ },+ [handleApiError],+ );++ // Auto-advance past idle when the page loads with a valid `?repo=` (shared link).+ const didAutoStart = useRef(false);+ useEffect(() => {+ if (didAutoStart.current) return;+ didAutoStart.current = true;+ if (repoParam && parseRepoInput(repoParam)) {+ setInputValue(repoParam);+ void runGeneration(repoParam);+ }+ }, [repoParam, runGeneration]);++ const handleSubmit = useCallback(() => {+ const value = inputValue.trim();+ if (!parseRepoInput(value)) {+ toast.error("Enter a repo as owner/name");+ return;+ }+ void setRepoParam(value);+ void runGeneration(value);+ }, [inputValue, runGeneration, setRepoParam]);++ const cancelGeneration = useCallback(() => {+ genAbortRef.current?.abort();+ setStatus("idle");+ }, []);++ // ---- render-on-web export ---------------------------------------------++ const [supportsExport, setSupportsExport] = useState(false);+ const [exporting, setExporting] = useState(false);+ const [exportProgress, setExportProgress] = useState(0);+ const exportAbortRef = useRef<AbortController | null>(null);++ useEffect(() => {+ // Feature-detect WebCodecs after mount (avoids hydration mismatch).+ setSupportsExport(+ typeof window !== "undefined" &&+ typeof window.VideoEncoder !== "undefined",+ );+ }, []);++ const inputProps = useMemo(+ () =>+ data+ ? {+ repo: `${data.owner}/${data.repo}`,+ totalStars: data.totalStars,+ stargazers: data.stargazers,+ orientation,+ accentColor,+ speed,+ theme,+ }+ : null,+ [data, orientation, accentColor, speed, theme],+ );++ const handleDownload = useCallback(async () => {+ if (!supportsExport) {+ toast.info("MP4 export needs Chrome or Edge");+ return;+ }+ if (!entry || !data || !inputProps) return;++ const controller = new AbortController();+ exportAbortRef.current = controller;+ setExporting(true);+ setExportProgress(0);++ try {+ const { renderMediaOnWeb } = await import("@remotion/web-renderer");+ const { width, height } = dims(orientation);+ const { getBlob } = await renderMediaOnWeb({+ composition: {+ id: "github-stars",+ component: entry.Component,+ durationInFrames: entry.config.durationInFrames,+ fps: entry.config.fps,+ width,+ height,+ },+ inputProps,+ container: "mp4",+ signal: controller.signal,+ onProgress: ({ progress }) => setExportProgress(progress),+ });++ const blob = await getBlob();+ const url = URL.createObjectURL(blob);+ const a = document.createElement("a");+ a.href = url;+ a.download = `${data.owner}-${data.repo}-stars.mp4`;+ document.body.appendChild(a);+ a.click();+ a.remove();+ URL.revokeObjectURL(url);+ } catch (err) {+ if (!(err instanceof DOMException && err.name === "AbortError")) {+ toast.error("Export failed — try again");+ }+ } finally {+ setExporting(false);+ exportAbortRef.current = null;+ }+ }, [supportsExport, entry, data, inputProps, orientation]);++ const cancelExport = useCallback(() => {+ exportAbortRef.current?.abort();+ }, []);++ // Clear the current repo and return to the idle input so the user can paste a+ // different one. The `didAutoStart` ref stays set, so wiping `?repo=` here does+ // NOT re-trigger the auto-advance (that only runs on a fresh page load).+ const handleReset = useCallback(() => {+ genAbortRef.current?.abort();+ exportAbortRef.current?.abort();+ setData(null);+ setZeroStars(false);+ setInputValue("");+ void setRepoParam(null);+ setStatus("idle");+ }, [setRepoParam]);++ const onCustomChange = useCallback((key: string, value: unknown) => {+ if (key === "accentColor") setAccentColor(value as string);+ else if (key === "theme") setTheme(value as "light" | "dark");+ else if (key === "speed") setSpeed(value as number);+ }, []);++ return (+ <TooltipProvider>+ <Toaster />+ <section className="relative overflow-hidden pt-10 pb-16 sm:pt-16 sm:pb-24">+ {/* Backdrop: dotted grid that fades out. No glow ornaments. */}+ <div aria-hidden className="absolute inset-0 -z-10">+ <div className="absolute inset-0 bg-grid-fade" />+ </div>++ <div className="section">+ {status === "idle" && (+ <IdleView+ inputValue={inputValue}+ setInputValue={(v) => {+ setInputValue(v);+ if (zeroStars) setZeroStars(false);+ }}+ onSubmit={handleSubmit}+ canGenerate={canGenerate}+ zeroStars={zeroStars}+ />+ )}++ {status === "generating" && (+ <GeneratingView reduced={reduced} onCancel={cancelGeneration} />+ )}++ {status === "ready" && entry && data && inputProps && (+ // Constant width regardless of orientation — the preview frame stays+ // put when toggling horizontal/vertical (refinement #3).+ <div className="mx-auto max-w-5xl">+ {data.truncated && (+ <Alert className="mb-4">+ <AlertTitle>Showing a sample</AlertTitle>+ <AlertDescription>+ This repo has {formatStars(data.totalStars)} stars — the+ clip animates an evenly sampled subset for a smooth render.+ </AlertDescription>+ </Alert>+ )}++ <ReadyView+ entry={entry}+ inputProps={inputProps}+ repo={`${data.owner}/${data.repo}`}+ totalStars={data.totalStars}+ onReset={handleReset}+ orientation={orientation}+ onOrientationChange={(o) =>+ void setOParam(o === "vertical" ? "v" : "h")+ }+ reduced={reduced}+ showCustomizer={showCustomizer}+ onToggleCustomizer={() => setShowCustomizer((s) => !s)}+ customValues={{ accentColor, theme, speed }}+ onCustomChange={onCustomChange}+ supportsExport={supportsExport}+ exporting={exporting}+ exportProgress={exportProgress}+ onDownload={() => void handleDownload()}+ onCancelExport={cancelExport}+ />+ </div>+ )}+ </div>+ </section>+ </TooltipProvider>+ );+}++// ---- idle ----------------------------------------------------------------++function IdleView({+ inputValue,+ setInputValue,+ onSubmit,+ canGenerate,+ zeroStars,+}: {+ inputValue: string;+ setInputValue: (v: string) => void;+ onSubmit: () => void;+ canGenerate: boolean;+ zeroStars: boolean;+}) {+ return (+ <div className="flex min-h-[70vh] flex-col items-center justify-center text-center">+ <FadeUp delay={0.06} className="flex flex-col items-center">+ <h1 className="max-w-3xl text-balance text-3xl font-semibold leading-[1.1] tracking-tight text-foreground sm:text-4xl md:text-5xl">+ Turn your repo’s stars into a video+ </h1>+ </FadeUp>++ <FadeUp delay={0.12}>+ <p className="mt-4 max-w-2xl text-balance text-base leading-relaxed text-muted-foreground sm:text-lg">+ Paste a GitHub repo. We fetch every stargazer and animate it into a+ shareable clip.+ </p>+ </FadeUp>++ <FadeUp delay={0.18} className="w-full">+ <form+ className="mt-7 flex flex-col items-center gap-3 sm:flex-row sm:justify-center"+ onSubmit={(e) => {+ e.preventDefault();+ onSubmit();+ }}+ >+ <Input+ value={inputValue}+ onChange={(e) => setInputValue(e.target.value)}+ aria-label="GitHub repository"+ placeholder="github.com/owner/repo or owner/repo"+ className="h-11 w-full rounded-full px-5 sm:max-w-sm"+ />+ <Button+ type="submit"+ size="lg"+ disabled={!canGenerate}+ className="h-11 gap-2 rounded-full px-6"+ >+ Generate+ <ArrowRight className="size-4" aria-hidden="true" />+ </Button>+ </form>+ </FadeUp>+ </div>+ );+}++// ---- generating ----------------------------------------------------------++function GeneratingView({+ reduced,+ onCancel,+}: {+ reduced: boolean;+ onCancel: () => void;+}) {+ const [tick, setTick] = useState(0);+ const [progress, setProgress] = useState(0);++ useEffect(() => {+ if (reduced) {+ setProgress(90);+ return;+ }+ const id = setInterval(() => {+ setTick((t) => t + Math.floor(Math.random() * 40) + 10);+ setProgress((v) => Math.min(v + (90 - v) * 0.12, 90));+ }, 160);+ return () => clearInterval(id);+ }, [reduced]);++ return (+ <div className="flex min-h-[70vh] flex-col items-center justify-center">+ <div className="surface-card mx-auto w-full max-w-xl rounded-3xl p-8">+ {/* Ghost avatar chips streaming in — the "stargazers flying in" tease. */}+ <div className="flex flex-wrap justify-center gap-2">+ {Array.from({ length: 9 }).map((_, i) => (+ <motion.div+ // biome-ignore lint/suspicious/noArrayIndexKey: fixed-length decorative placeholders+ key={i}+ initial={reduced ? false : { opacity: 0, x: -12 }}+ animate={{ opacity: 1, x: 0 }}+ transition={+ reduced ? undefined : { ...SPRING_BOUNCE, delay: i * 0.06 }+ }+ >+ <Skeleton className="size-9 rounded-full" />+ </motion.div>+ ))}+ </div>++ <div className="mt-6">+ <Progress value={progress} />+ </div>++ <p className="mt-4 text-center text-sm font-medium text-foreground">+ Fetching stargazers…{" "}+ <span className="tabular-nums text-muted-foreground">+ {tick.toLocaleString("en-US")}+ </span>+ </p>++ <div className="mt-6 flex justify-center">+ <Button variant="ghost" onClick={onCancel} className="rounded-full">+ Cancel+ </Button>+ </div>+ </div>+ </div>+ );+}++// ---- ready ---------------------------------------------------------------++function ReadyView({+ entry,+ inputProps,+ repo,+ totalStars,+ onReset,+ orientation,+ onOrientationChange,+ reduced,+ showCustomizer,+ onToggleCustomizer,+ customValues,+ onCustomChange,+ supportsExport,+ exporting,+ exportProgress,+ onDownload,+ onCancelExport,+}: {+ entry: RegistryEntry;+ inputProps: Record<string, unknown>;+ repo: string;+ totalStars: number;+ onReset: () => void;+ orientation: Orientation;+ onOrientationChange: (o: Orientation) => void;+ reduced: boolean;+ showCustomizer: boolean;+ onToggleCustomizer: () => void;+ customValues: Record<string, unknown>;+ onCustomChange: (key: string, value: unknown) => void;+ supportsExport: boolean;+ exporting: boolean;+ exportProgress: number;+ onDownload: () => void;+ onCancelExport: () => void;+}) {+ const playerRef = useRef<PlayerRef>(null);+ const [playing, setPlaying] = useState(!reduced);++ const togglePlay = useCallback(() => {+ const p = playerRef.current;+ if (!p) return;+ if (p.isPlaying()) {+ p.pause();+ setPlaying(false);+ } else {+ p.play();+ setPlaying(true);+ }+ }, []);++ const { width, height } = dims(orientation);++ return (+ <motion.div+ initial={reduced ? false : { y: 40, opacity: 0 }}+ animate={{ y: 0, opacity: 1 }}+ transition={{ ...SPRING_BOUNCE, delay: 0.05 }}+ >+ {/* Repo header + reset to a different repo. */}+ <div className="mb-3 flex items-center justify-between gap-3">+ <p className="min-w-0 truncate text-sm font-medium text-foreground">+ {repo}+ <span className="ml-2 font-normal text-muted-foreground">+ {formatStars(totalStars)} stars+ </span>+ </p>+ <Button+ variant="ghost"+ size="sm"+ onClick={onReset}+ className="shrink-0 gap-2 rounded-full"+ >+ <RotateCcw className="size-4" aria-hidden="true" />+ Change repository+ </Button>+ </div>++ {/* Controls bar */}+ <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">+ <ToggleGroup+ value={[orientation === "vertical" ? "v" : "h"]}+ onValueChange={(value: string[]) => {+ const next = value[0];+ if (next)+ onOrientationChange(next === "v" ? "vertical" : "horizontal");+ }}+ aria-label="Video orientation"+ className="w-full sm:w-auto"+ >+ <ToggleGroupItem value="h" className="flex-1 sm:flex-none">+ Horizontal+ </ToggleGroupItem>+ <ToggleGroupItem value="v" className="flex-1 sm:flex-none">+ Vertical+ </ToggleGroupItem>+ </ToggleGroup>++ <Button+ variant="ghost"+ size="sm"+ onClick={onToggleCustomizer}+ aria-expanded={showCustomizer}+ className="gap-2 rounded-full"+ >+ <Settings2 className="size-4" aria-hidden="true" />+ Customize+ </Button>+ </div>++ {/* Player card — a fixed 16:9 frame so toggling orientation never reflows+ the page. Vertical renders pillarboxed + centered inside it, while the+ Player still gets the true 720×1280 composition so the exported MP4 is+ genuinely vertical (only the on-page container width stays constant). */}+ <div+ className="group surface-card relative w-full overflow-hidden rounded-2xl shadow-2xl shadow-black/5 sm:rounded-3xl dark:shadow-black/40"+ style={{ aspectRatio: "1280 / 720" }}+ >+ <div className="absolute inset-0 flex items-center justify-center">+ <div+ className="h-full"+ style={+ orientation === "vertical"+ ? {+ height: "100%",+ width: "auto",+ aspectRatio: `${width} / ${height}`,+ }+ : { width: "100%", height: "100%" }+ }+ >+ <Player+ ref={playerRef}+ component={entry.Component}+ inputProps={inputProps}+ durationInFrames={entry.config.durationInFrames}+ fps={entry.config.fps}+ compositionWidth={width}+ compositionHeight={height}+ style={{ width: "100%", height: "100%", display: "block" }}+ autoPlay={!reduced}+ loop+ acknowledgeRemotionLicense+ />+ </div>+ </div>+ <button+ type="button"+ onClick={togglePlay}+ aria-label={playing ? "Pause preview" : "Play preview"}+ className="absolute inset-0 flex items-center justify-center bg-transparent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40"+ >+ <span+ aria-hidden+ data-show={!playing}+ className="pointer-events-none flex size-14 items-center justify-center rounded-full bg-background/70 text-foreground opacity-0 backdrop-blur-md transition-opacity duration-200 group-hover:opacity-100 motion-reduce:transition-none data-[show=true]:opacity-100"+ >+ {playing ? (+ <Pause className="size-5" />+ ) : (+ <Play className="size-5 translate-x-0.5" />+ )}+ </span>+ </button>+ </div>++ {/* Optional customizer panel (scalar inputProps). */}+ {showCustomizer && (+ <div className="mt-4">+ <ComponentCustomizer+ controls={CUSTOM_CONTROLS}+ values={customValues}+ onChange={onCustomChange}+ />+ </div>+ )}++ {/* Footer row: install advert + export. */}+ <div className="mt-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">+ <div className="flex flex-col items-stretch gap-2 sm:flex-row sm:items-center">+ <InstallCommand command={INSTALL} />+ <Button+ variant="outline"+ size="lg"+ className="h-11 gap-2 rounded-full"+ render={<Link href="/docs/social/github-stars" />}+ >+ <BookOpen className="size-4" aria-hidden="true" />+ View component docs+ </Button>+ </div>++ {exporting ? (+ <div className="flex w-full items-center gap-3 sm:w-72">+ <Progress+ value={Math.round(exportProgress * 100)}+ className="flex-1"+ />+ <Button+ variant="ghost"+ size="icon"+ onClick={onCancelExport}+ aria-label="Cancel export"+ className="rounded-full"+ >+ <X className="size-4" />+ </Button>+ </div>+ ) : supportsExport ? (+ <Button size="lg" onClick={onDownload} className="gap-2 rounded-full">+ <Download className="size-4" aria-hidden="true" />+ Download MP4+ </Button>+ ) : (+ <Tooltip>+ <TooltipTrigger+ render={+ // Not the native `disabled` attribute — a disabled button+ // suppresses hover/click, hiding the tooltip and the info toast.+ // Style it muted and let onDownload surface the Chrome/Edge hint.+ <Button+ size="lg"+ aria-disabled+ onClick={onDownload}+ className="gap-2 rounded-full opacity-50"+ >+ <Download className="size-4" aria-hidden="true" />+ Download MP4+ </Button>+ }+ />+ <TooltipContent>MP4 export needs Chrome or Edge</TooltipContent>+ </Tooltip>+ )}+ </div>+ </motion.div>+ );+}diff --git a/app/(home)/stars/page.tsx b/app/(home)/stars/page.tsxnew file mode 100644index 00000000..cec28df2--- /dev/null+++ b/app/(home)/stars/page.tsx@@ -0,0 +1,19 @@+import type { Metadata } from "next";+import { StarsTool } from "./components/stars-tool";++export const metadata: Metadata = {+ title: "GitHub Stars Video Generator",+ description:+ "Turn your repo's stars into a shareable animated video. Paste a GitHub repo and we animate every stargazer into a clip you can own.",+ openGraph: {+ title: "GitHub Stars Video Generator · remocn",+ description:+ "Turn your repo's stars into a shareable animated video. Paste a GitHub repo and we animate every stargazer into a clip you can own.",+ },+};++// The (home) layout already wraps pages in PageShell + SiteHeader + SiteFooter,+// so this server shell only supplies metadata and mounts the client tool.+export default function StarsPage() {+ return <StarsTool />;+}diff --git a/app/api/stargazers/__tests__/route.test.ts b/app/api/stargazers/__tests__/route.test.tsnew file mode 100644index 00000000..0c0ea071--- /dev/null+++ b/app/api/stargazers/__tests__/route.test.ts@@ -0,0 +1,259 @@+/**+ * Unit tests for app/api/stargazers/route.ts+ *+ * Run with: bunx vitest run app/api/stargazers/__tests__/route.test.ts+ *+ * fetchStargazers is mocked so no real network is hit.+ */++import { afterEach, describe, expect, it, vi } from "vitest";++// ---------------------------------------------------------------------------+// Mock the data-layer module before importing the route handler.+// ---------------------------------------------------------------------------+vi.mock("@/lib/github-stargazers", async (importOriginal) => {+ const actual =+ await importOriginal<typeof import("@/lib/github-stargazers")>();+ return {+ ...actual,+ fetchStargazers: vi.fn(),+ };+});++import { GET } from "@/app/api/stargazers/route";+import {+ StargazersError,+ fetchStargazers,+} from "@/lib/github-stargazers";++const mockFetchStargazers = vi.mocked(fetchStargazers);++afterEach(() => {+ vi.clearAllMocks();+ delete process.env.GITHUB_TOKEN;+});++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++/** Build a minimal NextRequest-compatible object. */+function makeRequest(repoParam?: string): Request {+ const url = repoParam+ ? `http://localhost/api/stargazers?repo=${encodeURIComponent(repoParam)}`+ : "http://localhost/api/stargazers";+ return new Request(url);+}++const SAMPLE_STARGAZERS = [+ {+ login: "alice",+ avatarUrl: "https://avatars.githubusercontent.com/u/1",+ starredAt: "2021-01-01T00:00:00Z",+ },+];++// ---------------------------------------------------------------------------+// 400 — invalid / missing ?repo=+// ---------------------------------------------------------------------------++describe("GET /api/stargazers — 400 invalid_repo", () => {+ it("returns 400 when ?repo= is missing entirely", async () => {+ const res = await GET(makeRequest() as never);+ expect(res.status).toBe(400);+ const body = await res.json();+ expect(body.code).toBe("invalid_repo");+ });++ it("returns 400 when ?repo= is an empty string", async () => {+ const res = await GET(makeRequest("") as never);+ expect(res.status).toBe(400);+ const body = await res.json();+ expect(body.code).toBe("invalid_repo");+ });++ it("returns 400 when ?repo= is not a valid owner/name", async () => {+ const res = await GET(makeRequest("not-a-valid-repo-string") as never);+ expect(res.status).toBe(400);+ const body = await res.json();+ expect(body.code).toBe("invalid_repo");+ });++ it("returns 400 on bare owner with no slash", async () => {+ const res = await GET(makeRequest("justowner") as never);+ expect(res.status).toBe(400);+ const body = await res.json();+ expect(body.code).toBe("invalid_repo");+ });+});++// ---------------------------------------------------------------------------+// 200 — success shape+// ---------------------------------------------------------------------------++describe("GET /api/stargazers — 200 success", () => {+ it("returns 200 with correct shape on a valid repo", async () => {+ mockFetchStargazers.mockResolvedValueOnce({+ stargazers: SAMPLE_STARGAZERS,+ totalStars: 42,+ truncated: false,+ });++ const res = await GET(makeRequest("vercel/next.js") as never);+ expect(res.status).toBe(200);++ const body = await res.json();+ expect(body).toMatchObject({+ owner: "vercel",+ repo: "next.js",+ totalStars: 42,+ truncated: false,+ stargazers: SAMPLE_STARGAZERS,+ });+ });++ it("includes all required top-level keys", async () => {+ mockFetchStargazers.mockResolvedValueOnce({+ stargazers: [],+ totalStars: 0,+ truncated: false,+ });++ const res = await GET(makeRequest("facebook/react") as never);+ const body = await res.json();+ expect(Object.keys(body).sort()).toEqual(+ ["owner", "repo", "totalStars", "truncated", "stargazers"].sort(),+ );+ });++ it("accepts a full github.com URL as ?repo=", async () => {+ mockFetchStargazers.mockResolvedValueOnce({+ stargazers: [],+ totalStars: 1,+ truncated: false,+ });++ const res = await GET(+ makeRequest("https://github.com/vercel/next.js") as never,+ );+ expect(res.status).toBe(200);+ const body = await res.json();+ expect(body.owner).toBe("vercel");+ expect(body.repo).toBe("next.js");+ });++ it("totalStars in the response matches what fetchStargazers returned", async () => {+ mockFetchStargazers.mockResolvedValueOnce({+ stargazers: SAMPLE_STARGAZERS,+ totalStars: 9999,+ truncated: true,+ });++ const res = await GET(makeRequest("owner/repo") as never);+ const body = await res.json();+ expect(body.totalStars).toBe(9999);+ expect(body.truncated).toBe(true);+ });+});++// ---------------------------------------------------------------------------+// Error code → HTTP status mapping+// ---------------------------------------------------------------------------++describe("GET /api/stargazers — error code mapping", () => {+ it("maps StargazersError not_found → 404", async () => {+ mockFetchStargazers.mockRejectedValueOnce(+ new StargazersError("not_found", "Repository not found.", 404),+ );++ const res = await GET(makeRequest("owner/missing") as never);+ expect(res.status).toBe(404);+ const body = await res.json();+ expect(body.code).toBe("not_found");+ });++ it("maps StargazersError rate_limited → 429", async () => {+ mockFetchStargazers.mockRejectedValueOnce(+ new StargazersError("rate_limited", "Rate limit exceeded.", 429),+ );++ const res = await GET(makeRequest("owner/repo") as never);+ expect(res.status).toBe(429);+ const body = await res.json();+ expect(body.code).toBe("rate_limited");+ });++ it("maps StargazersError fetch_failed → 502", async () => {+ mockFetchStargazers.mockRejectedValueOnce(+ new StargazersError("fetch_failed", "Network error.", 502),+ );++ const res = await GET(makeRequest("owner/repo") as never);+ expect(res.status).toBe(502);+ const body = await res.json();+ expect(body.code).toBe("fetch_failed");+ });++ it("maps AbortError (client cancel) → 499 with empty body", async () => {+ const abort = new Error("aborted");+ abort.name = "AbortError";+ mockFetchStargazers.mockRejectedValueOnce(abort);++ const res = await GET(makeRequest("owner/repo") as never);+ expect(res.status).toBe(499);+ // Body must be null/empty — not JSON+ const text = await res.text();+ expect(text).toBe("");+ });++ it("maps an unexpected Error → 502 fetch_failed", async () => {+ mockFetchStargazers.mockRejectedValueOnce(new Error("something broke"));++ const res = await GET(makeRequest("owner/repo") as never);+ expect(res.status).toBe(502);+ const body = await res.json();+ expect(body.code).toBe("fetch_failed");+ });+});++// ---------------------------------------------------------------------------+// Security: GITHUB_TOKEN must never appear in any response body+// ---------------------------------------------------------------------------++describe("GET /api/stargazers — token never leaks", () => {+ it("does not include GITHUB_TOKEN in a 200 response", async () => {+ process.env.GITHUB_TOKEN = "ghp_supersecret_200";++ mockFetchStargazers.mockResolvedValueOnce({+ stargazers: SAMPLE_STARGAZERS,+ totalStars: 1,+ truncated: false,+ });++ const res = await GET(makeRequest("owner/repo") as never);+ const text = await res.text();+ expect(text).not.toContain("ghp_supersecret_200");+ });++ it("does not include GITHUB_TOKEN in a 404 error response", async () => {+ process.env.GITHUB_TOKEN = "ghp_supersecret_404";++ mockFetchStargazers.mockRejectedValueOnce(+ new StargazersError("not_found", "Not found.", 404),+ );++ const res = await GET(makeRequest("owner/missing") as never);+ const text = await res.text();+ expect(text).not.toContain("ghp_supersecret_404");+ });++ it("does not include GITHUB_TOKEN in a 502 error response", async () => {+ process.env.GITHUB_TOKEN = "ghp_supersecret_502";++ mockFetchStargazers.mockRejectedValueOnce(new Error("boom"));++ const res = await GET(makeRequest("owner/repo") as never);+ const text = await res.text();+ expect(text).not.toContain("ghp_supersecret_502");+ });+});diff --git a/app/api/stargazers/route.ts b/app/api/stargazers/route.tsnew file mode 100644index 00000000..a515fd7c--- /dev/null+++ b/app/api/stargazers/route.ts@@ -0,0 +1,66 @@+import { type NextRequest, NextResponse } from "next/server";++import {+ fetchStargazers,+ parseRepoInput,+ StargazersError,+} from "@/lib/github-stargazers";++// Node runtime: the GitHub token + larger paginated responses want full Node.+export const runtime = "nodejs";++/**+ * GET /api/stargazers?repo=<owner/name | github.com URL>+ *+ * Validates the repo reference, fetches stargazers server-side (token never+ * leaves the server), and returns a compact, downsampled payload for the+ * `github-stars` animation. Errors come back as `{ error, code }` with a status.+ */+export async function GET(request: NextRequest) {+ const repoParam = request.nextUrl.searchParams.get("repo");++ if (!repoParam) {+ return NextResponse.json(+ { error: "Missing ?repo= parameter.", code: "invalid_repo" },+ { status: 400 },+ );+ }++ const parsed = parseRepoInput(repoParam);+ if (!parsed) {+ return NextResponse.json(+ {+ error: "Invalid repository. Use owner/name or a github.com URL.",+ code: "invalid_repo",+ },+ { status: 400 },+ );+ }++ const { owner, repo } = parsed;++ try {+ const { stargazers, totalStars, truncated } = await fetchStargazers({+ owner,+ repo,+ signal: request.signal,+ });++ return NextResponse.json({ owner, repo, totalStars, truncated, stargazers });+ } catch (err) {+ if (err instanceof StargazersError) {+ return NextResponse.json(+ { error: err.message, code: err.code },+ { status: err.status },+ );+ }+ // Client aborted (AbortController) — not an application error.+ if (err instanceof Error && err.name === "AbortError") {+ return new NextResponse(null, { status: 499 });+ }+ return NextResponse.json(+ { error: "Failed to fetch stargazers.", code: "fetch_failed" },+ { status: 502 },+ );+ }+}diff --git a/bun.lock b/bun.lockindex 5435674f..bc33f9f9 100644--- a/bun.lock+++ b/bun.lock@@ -10,6 +10,7 @@"@react-three/fiber": "^9.3.0","@react-three/postprocessing": "^3.0.4","@remotion/player": "^4.0.392",+ "@remotion/web-renderer": "^4.0.473","class-variance-authority": "^0.7.1","clsx": "^2.1.1","cmdk": "^1.1.1",@@ -287,6 +288,12 @@"@mdx-js/mdx": ["@mdx-js/[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdx": "^2.0.0", "acorn": "^8.0.0", "collapse-white-space": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "estree-util-scope": "^1.0.0", "estree-walker": "^3.0.0", "hast-util-to-jsx-runtime": "^2.0.0", "markdown-extensions": "^2.0.0", "recma-build-jsx": "^1.0.0", "recma-jsx": "^1.0.0", "recma-stringify": "^1.0.0", "rehype-recma": "^1.0.0", "remark-mdx": "^3.0.0", "remark-parse": "^11.0.0", "remark-rehype": "^11.0.0", "source-map": "^0.7.0", "unified": "^11.0.0", "unist-util-position-from-estree": "^2.0.0", "unist-util-stringify-position": "^4.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-f6ZO2ifpwAQIpzGWaBQT2TXxPv6z3RBzQKpVftEWN78Vl/YweF1uwussDx8ECAXVtr3Rs89fKyG9YlzUs9DyGQ=="],+ "@mediabunny/aac-encoder": ["@mediabunny/[email protected]", "", { "peerDependencies": { "mediabunny": "^1.0.0" } }, "sha512-vLQw8cY7Me6pvTTMkMhOiH9UCuINzfTOETCeDxbGNeNfDqc/7QlxloUH1Ylp/Zz2ek0O8kc6YdygV2vWAPakrA=="],++ "@mediabunny/flac-encoder": ["@mediabunny/[email protected]", "", { "peerDependencies": { "mediabunny": "^1.0.0" } }, "sha512-LfKbAMZVkxRS7PpEIVnWOY/l0KcHv+rjO7pYY3O0TPCZvbHWfrnQjn8JPacPIfuq6Yv7r4f8lhcl7yHSynoRkQ=="],++ "@mediabunny/mp3-encoder": ["@mediabunny/[email protected]", "", { "peerDependencies": { "mediabunny": "^1.0.0" } }, "sha512-Bobi6AaQYEc7TWmPJ8Q0/hcUtBN7pLUC2qjoC7oZR4FcGqGztby6k7A1SWlmswoMOEIhYsOrgDaemrSDAC0QVQ=="],+"@modelcontextprotocol/sdk": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ=="],"@mswjs/interceptors": ["@mswjs/[email protected]", "", { "dependencies": { "@open-draft/deferred-promise": "^2.2.0", "@open-draft/logger": "^0.3.0", "@open-draft/until": "^2.0.0", "is-node-process": "^1.2.0", "outvariant": "^1.4.3", "strict-event-emitter": "^0.5.1" } }, "sha512-cXu86tF4VQVfwz8W1SPbhoRyHJkti6mjH/XJIxp40jhO4j2k1m4KYrEykxqWPkFF3vrK4rgQppBh//AwyGSXPA=="],@@ -409,8 +416,12 @@"@reduxjs/toolkit": ["@reduxjs/[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "@standard-schema/utils": "^0.3.0", "immer": "^11.0.0", "redux": "^5.0.1", "redux-thunk": "^3.1.0", "reselect": "^5.1.0" }, "peerDependencies": { "react": "^16.9.0 || ^17.0.0 || ^18 || ^19", "react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0" }, "optionalPeers": ["react", "react-redux"] }, "sha512-Kd6kAHTA6/nUpp8mySPqj3en3dm0tdMIgbttnQ1xFMVpufoj+ADi8pXLBsd4xzTRHQa7t/Jv8W5UnCuW4kuWMQ=="],+ "@remotion/licensing": ["@remotion/[email protected]", "", {}, "sha512-BBw6SuEWuUD/lYXbLKEC0TTUzW7aLsO0X72pG38W1dOUyfU2KZYYfWGZkd+ermZTWWJ8cW+mevIwloUGk7FRaQ=="],+"@remotion/player": ["@remotion/[email protected]", "", { "dependencies": { "remotion": "4.0.446" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-l3sYiMmT0yx39qgGsWKkv/auTQ7BJYmEb+FPzwacBe5Oi1R1klBWABsbO+L4OSN6lDOCrI2U8uWfpsPZv1sqxA=="],+ "@remotion/web-renderer": ["@remotion/[email protected]", "", { "dependencies": { "@mediabunny/aac-encoder": "1.45.0", "@mediabunny/flac-encoder": "1.45.0", "@mediabunny/mp3-encoder": "1.45.0", "@remotion/licensing": "4.0.473", "mediabunny": "1.45.0", "remotion": "4.0.473" }, "peerDependencies": { "react": ">=18.0.0", "react-dom": ">=18.0.0" } }, "sha512-WTyFdBdqsmmqrMpW1k6Uhcze2z8tZvKc15BYu1FwmDgdQ1QeaAMgEsyp5qRLzKZ/000XafK4q8bUjdEQoudc8A=="],+"@rrweb/types": ["@rrweb/[email protected]", "", {}, "sha512-RbnDgKxA/odwB1R4gF7eUUj+rdSrq6ROQJsnMw7MIsGzlbSYvJeZN8YY4XqU0G6sKJvXI6bSzk7w/G94jNwzhw=="],"@rrweb/utils": ["@rrweb/[email protected]", "", {}, "sha512-MTQOmhPRe39C0fYaCnnVYOufQsyGzwNXpUStKiyFSfGLUJrzuwhbRoUAKR5w6W2j5XuA0bIz3ZDIBztkquOhLw=="],@@ -503,6 +514,10 @@"@types/debug": ["@types/[email protected]", "", { "dependencies": { "@types/ms": "*" } }, "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="],+ "@types/dom-mediacapture-transform": ["@types/[email protected]", "", { "dependencies": { "@types/dom-webcodecs": "*" } }, "sha512-Y2p+nGf1bF2XMttBnsVPHUWzRRZzqUoJAKmiP10b5umnO6DDrWI0BrGDJy1pOHoOULVmGSfFNkQrAlC5dcj6nQ=="],++ "@types/dom-webcodecs": ["@types/[email protected]", "", {}, "sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ=="],+"@types/estree": ["@types/[email protected]", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="],"@types/estree-jsx": ["@types/[email protected]", "", { "dependencies": { "@types/estree": "*" } }, "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg=="],@@ -1075,6 +1090,8 @@"media-typer": ["[email protected]", "", {}, "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw=="],+ "mediabunny": ["[email protected]", "", { "dependencies": { "@types/dom-mediacapture-transform": "^0.1.11", "@types/dom-webcodecs": "0.1.13" } }, "sha512-oK3sMMYbucoF6LUX62L/2M9d+p9ve6KDQgL87kNfhsB0/XmTe9iRLUcgQgg9Gpgvi8Sb96zYfOUL6i17y0bdNg=="],+"merge-descriptors": ["[email protected]", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="],"merge-stream": ["[email protected]", "", {}, "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w=="],@@ -1581,6 +1598,8 @@"@reduxjs/toolkit/immer": ["[email protected]", "", {}, "sha512-XREFCPo6ksxVzP4E0ekD5aMdf8WMwmdNaz6vuvxgI40UaEiu6q3p8X52aU6GdyvLY3XXX/8R7JOTXStz/nBbRw=="],+ "@remotion/web-renderer/remotion": ["[email protected]", "", { "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-Li2u4cVxlbxWgxQPn5oBpUlmNKYFpLUmpE9OHMP7QurvOMfvVK1tcC7utxVEwYFZf18tXwqIPBwmuFvdzMu+YA=="],+"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" }, "bundled": true }, "sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA=="],"@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw=="],diff --git a/content/docs/social/github-stars.mdx b/content/docs/social/github-stars.mdxindex 90efce18..f53f3810 100644--- a/content/docs/social/github-stars.mdx+++ b/content/docs/social/github-stars.mdx@@ -5,6 +5,10 @@ description: Stargazer list fly-through with a synced odometer counter — rende<ComponentPreview name="github-stars" />+<Note title="Live generator">+ Want to see it with your own repo before installing? Head to [/stars](/stars), paste any GitHub repo URL, preview the animation, and download an MP4 — it's the live demo of this component.+</Note>+## Installation<InstallBlock name="github-stars" />diff --git a/lib/__tests__/github-stargazers.test.ts b/lib/__tests__/github-stargazers.test.tsnew file mode 100644index 00000000..7460ef5a--- /dev/null+++ b/lib/__tests__/github-stargazers.test.ts@@ -0,0 +1,374 @@+/**+ * Unit tests for lib/github-stargazers.ts+ *+ * Run with: bunx vitest run lib/__tests__/github-stargazers.test.ts+ *+ * All network is mocked — no real GitHub requests are made.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ type Stargazer,+ StargazersError,+ fetchStargazers,+ parseRepoInput,+} from "@/lib/github-stargazers";++// ---------------------------------------------------------------------------+// parseRepoInput+// ---------------------------------------------------------------------------++describe("parseRepoInput", () => {+ describe("valid inputs", () => {+ it("accepts owner/name", () => {+ expect(parseRepoInput("vercel/next.js")).toEqual({+ owner: "vercel",+ repo: "next.js",+ });+ });++ it("accepts https://github.com/owner/name", () => {+ expect(parseRepoInput("https://github.com/vercel/next.js")).toEqual({+ owner: "vercel",+ repo: "next.js",+ });+ });++ it("accepts http://github.com/owner/name/ (trailing slash)", () => {+ expect(parseRepoInput("http://github.com/vercel/next.js/")).toEqual({+ owner: "vercel",+ repo: "next.js",+ });+ });++ it("accepts github.com/owner/name (no scheme)", () => {+ expect(parseRepoInput("github.com/vercel/next.js")).toEqual({+ owner: "vercel",+ repo: "next.js",+ });+ });++ it("accepts owner/name.git suffix", () => {+ expect(parseRepoInput("vercel/next.js.git")).toEqual({+ owner: "vercel",+ repo: "next.js",+ });+ });++ it("accepts https URL with /tree/main extra path", () => {+ expect(+ parseRepoInput("https://github.com/vercel/next.js/tree/main"),+ ).toEqual({ owner: "vercel", repo: "next.js" });+ });++ it("accepts URL with query string", () => {+ expect(+ parseRepoInput("https://github.com/vercel/next.js?tab=readme"),+ ).toEqual({ owner: "vercel", repo: "next.js" });+ });++ it("accepts single-char owner and repo", () => {+ expect(parseRepoInput("a/b")).toEqual({ owner: "a", repo: "b" });+ });++ it("extracts correct owner and repo values", () => {+ const result = parseRepoInput("facebook/react");+ expect(result?.owner).toBe("facebook");+ expect(result?.repo).toBe("react");+ });++ it("strips .git from https URL variant", () => {+ expect(+ parseRepoInput("https://github.com/facebook/react.git"),+ ).toEqual({ owner: "facebook", repo: "react" });+ });+ });++ describe("invalid inputs", () => {+ it("rejects empty string", () => {+ expect(parseRepoInput("")).toBeNull();+ });++ it("rejects whitespace-only string", () => {+ expect(parseRepoInput(" ")).toBeNull();+ });++ it("rejects bare owner with no repo (\"owner\")", () => {+ expect(parseRepoInput("owner")).toBeNull();+ });++ it("rejects leading-slash with repo only (\"/name\")", () => {+ expect(parseRepoInput("/name")).toBeNull();+ });++ it("rejects input with spaces", () => {+ expect(parseRepoInput("owner name/repo")).toBeNull();+ });++ it("rejects random garbage", () => {+ expect(parseRepoInput("not a repo at all!")).toBeNull();+ });++ it("rejects javascript: scheme", () => {+ expect(parseRepoInput("javascript:alert(1)")).toBeNull();+ });++ it("rejects owner with invalid characters", () => {+ // underscore is not valid in a GitHub owner name+ expect(parseRepoInput("owner_bad/repo")).toBeNull();+ });+ });+});++// ---------------------------------------------------------------------------+// fetchStargazers (mocked fetch)+// ---------------------------------------------------------------------------++describe("fetchStargazers", () => {+ const originalFetch = global.fetch;++ afterEach(() => {+ global.fetch = originalFetch;+ vi.restoreAllMocks();+ delete process.env.GITHUB_TOKEN;+ });++ /** Build a minimal mock Response object. */+ function mockResponse(+ body: unknown,+ {+ status = 200,+ headers = {},+ }: { status?: number; headers?: Record<string, string> } = {},+ ): Response {+ return {+ ok: status >= 200 && status < 300,+ status,+ statusText: status === 200 ? "OK" : String(status),+ headers: {+ get: (key: string) => headers[key.toLowerCase()] ?? null,+ },+ json: async () => body,+ } as unknown as Response;+ }++ /** Build a raw stargazer entry as GitHub returns it. */+ function rawEntry(+ login: string,+ starredAt: string,+ avatarUrl = `https://avatars.githubusercontent.com/u/1?login=${login}`,+ ) {+ return {+ starred_at: starredAt,+ user: { login, avatar_url: avatarUrl },+ };+ }++ it("maps starred_at, user.login, and user.avatar_url into a Stargazer", async () => {+ const repoBody = { stargazers_count: 1 };+ const starBody = [rawEntry("alice", "2021-01-01T00:00:00Z")];++ global.fetch = vi+ .fn()+ .mockResolvedValueOnce(mockResponse(repoBody))+ .mockResolvedValueOnce(mockResponse(starBody));++ const result = await fetchStargazers({ owner: "test", repo: "repo" });++ expect(result.stargazers).toHaveLength(1);+ expect(result.stargazers[0]).toEqual<Stargazer>({+ login: "alice",+ avatarUrl: "https://avatars.githubusercontent.com/u/1?login=alice",+ starredAt: "2021-01-01T00:00:00Z",+ });+ });++ it("sorts stargazers ascending by starredAt", async () => {+ const repoBody = { stargazers_count: 3 };+ const starBody = [+ rawEntry("charlie", "2023-01-03T00:00:00Z"),+ rawEntry("alice", "2021-01-01T00:00:00Z"),+ rawEntry("bob", "2022-01-02T00:00:00Z"),+ ];++ global.fetch = vi+ .fn()+ .mockResolvedValueOnce(mockResponse(repoBody))+ .mockResolvedValueOnce(mockResponse(starBody));++ const result = await fetchStargazers({ owner: "test", repo: "repo" });+ const logins = result.stargazers.map((s) => s.login);+ expect(logins).toEqual(["alice", "bob", "charlie"]);+ });++ it("returns totalStars from the repo endpoint, not the array length", async () => {+ const repoBody = { stargazers_count: 5000 };+ // Only one page worth of data returned+ const starBody = [rawEntry("alice", "2021-01-01T00:00:00Z")];++ global.fetch = vi+ .fn()+ .mockResolvedValueOnce(mockResponse(repoBody))+ .mockResolvedValueOnce(mockResponse(starBody));++ const result = await fetchStargazers({ owner: "test", repo: "repo" });+ expect(result.totalStars).toBe(5000);+ });++ it("downsamples to ≤60 keyframes keeping first and last", async () => {+ const total = 200;+ const repoBody = { stargazers_count: total };+ // Build 200 entries on a single page+ const starBody = Array.from({ length: total }, (_, i) =>+ rawEntry(`user${i}`, `2021-01-${String(i + 1).padStart(2, "0")}T00:00:00Z`),+ );++ global.fetch = vi+ .fn()+ .mockResolvedValueOnce(mockResponse(repoBody))+ .mockResolvedValueOnce(mockResponse(starBody));++ const result = await fetchStargazers({ owner: "test", repo: "repo" });++ expect(result.stargazers.length).toBeLessThanOrEqual(60);+ // Sorted ascending, so first is user0 and last is user199+ expect(result.stargazers[0].login).toBe("user0");+ expect(result.stargazers[result.stargazers.length - 1].login).toBe(+ "user199",+ );+ });++ it("sets truncated=true when the repo has more pages than MAX_PAGES (50)", async () => {+ const repoBody = { stargazers_count: 99999 };+ // First page link header signals 100 total pages (> MAX_PAGES=50)+ const linkHeader =+ '<https://api.github.com/repos/test/repo/stargazers?page=100>; rel="last"';+ const starBody = [rawEntry("alice", "2021-01-01T00:00:00Z")];++ // Repo fetch + page 1 + pages 2-50 (all return same one-entry body)+ global.fetch = vi.fn().mockImplementation((url: string) => {+ if (String(url).includes("/repos/test/repo") && !String(url).includes("stargazers")) {+ return Promise.resolve(mockResponse(repoBody));+ }+ return Promise.resolve(+ mockResponse(starBody, { headers: { link: linkHeader } }),+ );+ });++ const result = await fetchStargazers({ owner: "test", repo: "repo" });+ expect(result.truncated).toBe(true);+ });++ it("sets truncated=false when the repo fits within MAX_PAGES", async () => {+ const repoBody = { stargazers_count: 3 };+ const linkHeader = null; // only one page+ const starBody = [rawEntry("alice", "2021-01-01T00:00:00Z")];++ global.fetch = vi+ .fn()+ .mockResolvedValueOnce(mockResponse(repoBody))+ .mockResolvedValueOnce(mockResponse(starBody));++ const result = await fetchStargazers({ owner: "test", repo: "repo" });+ expect(result.truncated).toBe(false);+ });++ it("maps 404 response to StargazersError with code 'not_found'", async () => {+ global.fetch = vi+ .fn()+ .mockResolvedValueOnce(mockResponse({}, { status: 404 }));++ await expect(+ fetchStargazers({ owner: "test", repo: "nonexistent" }),+ ).rejects.toMatchObject({ code: "not_found", status: 404 });+ });++ it("maps 403 with x-ratelimit-remaining:0 to code 'rate_limited'", async () => {+ global.fetch = vi.fn().mockResolvedValueOnce(+ mockResponse(+ { message: "API rate limit exceeded" },+ { status: 403, headers: { "x-ratelimit-remaining": "0" } },+ ),+ );++ await expect(+ fetchStargazers({ owner: "test", repo: "repo" }),+ ).rejects.toMatchObject({ code: "rate_limited", status: 429 });+ });++ it("maps 429 response to code 'rate_limited'", async () => {+ global.fetch = vi+ .fn()+ .mockResolvedValueOnce(mockResponse({}, { status: 429 }));++ await expect(+ fetchStargazers({ owner: "test", repo: "repo" }),+ ).rejects.toMatchObject({ code: "rate_limited", status: 429 });+ });++ it("handles 0-star repo: returns [] and totalStars 0 without throwing", async () => {+ const repoBody = { stargazers_count: 0 };++ global.fetch = vi+ .fn()+ .mockResolvedValueOnce(mockResponse(repoBody));++ const result = await fetchStargazers({ owner: "test", repo: "repo" });+ expect(result.stargazers).toEqual([]);+ expect(result.totalStars).toBe(0);+ expect(result.truncated).toBe(false);+ });++ it("does NOT include the token in returned Stargazer data", async () => {+ process.env.GITHUB_TOKEN = "ghp_supersecrettoken";++ const repoBody = { stargazers_count: 1 };+ const starBody = [rawEntry("alice", "2021-01-01T00:00:00Z")];++ global.fetch = vi+ .fn()+ .mockResolvedValueOnce(mockResponse(repoBody))+ .mockResolvedValueOnce(mockResponse(starBody));++ const result = await fetchStargazers({ owner: "test", repo: "repo" });+ const serialized = JSON.stringify(result);+ expect(serialized).not.toContain("ghp_supersecrettoken");+ });++ it("sends Accept: application/vnd.github.star+json header for stargazers pages", async () => {+ const repoBody = { stargazers_count: 1 };+ const starBody = [rawEntry("alice", "2021-01-01T00:00:00Z")];++ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(mockResponse(repoBody))+ .mockResolvedValueOnce(mockResponse(starBody));+ global.fetch = fetchMock;++ await fetchStargazers({ owner: "test", repo: "repo" });++ // Second call is the stargazers page fetch+ const [_url, init] = fetchMock.mock.calls[1] as [string, RequestInit];+ const headers = init?.headers as Record<string, string>;+ expect(headers["Accept"]).toBe("application/vnd.github.star+json");+ });++ it("filters out entries with missing login, avatarUrl, or starredAt", async () => {+ const repoBody = { stargazers_count: 3 };+ const starBody = [+ rawEntry("alice", "2021-01-01T00:00:00Z"),+ { starred_at: "2021-01-02T00:00:00Z", user: null }, // no user+ { starred_at: null, user: { login: "bob", avatar_url: "https://example.com/b.png" } }, // no date+ ];++ global.fetch = vi+ .fn()+ .mockResolvedValueOnce(mockResponse(repoBody))+ .mockResolvedValueOnce(mockResponse(starBody));++ const result = await fetchStargazers({ owner: "test", repo: "repo" });+ // Only alice should survive the filter+ expect(result.stargazers).toHaveLength(1);+ expect(result.stargazers[0].login).toBe("alice");+ });+});diff --git a/lib/github-stargazers.ts b/lib/github-stargazers.tsnew file mode 100644index 00000000..703b7444--- /dev/null+++ b/lib/github-stargazers.ts@@ -0,0 +1,252 @@+// Server-only module: reads `process.env.GITHUB_TOKEN` and is imported only by+// the `/api/stargazers` route handler. Never import this from a client component.+import { formatStars } from "@/lib/github";++// Re-export so the /stars consumer can format counts without a second import.+export { formatStars };++/** A single stargazer keyframe — mirrors the registry `github-stars` component. */+export type Stargazer = {+ login: string;+ avatarUrl: string;+ /** ISO timestamp, e.g. "2021-03-04T11:22:33Z". */+ starredAt: string;+};++export type StargazersResult = {+ stargazers: Stargazer[];+ totalStars: number;+ /** True when the repo has more pages than `MAX_PAGES` allows us to fetch. */+ truncated: boolean;+};++export type StargazersErrorCode =+ | "invalid_repo"+ | "not_found"+ | "rate_limited"+ | "fetch_failed";++/** Typed error so the route handler can map cleanly to a status + JSON code. */+export class StargazersError extends Error {+ readonly code: StargazersErrorCode;+ readonly status: number;+ constructor(code: StargazersErrorCode, message: string, status: number) {+ super(message);+ this.name = "StargazersError";+ this.code = code;+ this.status = status;+ }+}++/**+ * GitHub caps the REST stargazers endpoint at ~400 pages; we cap far lower so a+ * runaway repo can't exhaust the serverless function budget. 50 × 100 = 5000+ * stargazers fetched, then `truncated: true`. The animation downsamples anyway.+ */+const MAX_PAGES = 50;+const PER_PAGE = 100;+const CONCURRENCY = 6;+/** Keyframe cap kept in lockstep with the component's `downsampleStargazers`. */+const KEYFRAME_CAP = 60;+const API_BASE = "https://api.github.com";++// `parseRepoInput` lives in a client-safe module so the `/stars` client tool can+// validate input without importing this server-only file. Re-exported here so+// the route handler + tests keep their existing `@/lib/github-stargazers` import.+export { parseRepoInput } from "@/lib/parse-repo";++function buildHeaders(accept: string): HeadersInit {+ const headers: Record<string, string> = {+ Accept: accept,+ "X-GitHub-Api-Version": "2022-11-28",+ };+ const token = process.env.GITHUB_TOKEN;+ if (token) headers.Authorization = `Bearer ${token}`;+ return headers;+}++/** Map a non-OK GitHub response to a typed error (rate limit vs. not found). */+function errorForResponse(res: Response, context: string): StargazersError {+ if (res.status === 404) {+ return new StargazersError("not_found", "Repository not found.", 404);+ }+ const remaining = res.headers.get("x-ratelimit-remaining");+ if (res.status === 429 || (res.status === 403 && remaining === "0")) {+ return new StargazersError(+ "rate_limited",+ "GitHub API rate limit exceeded. Add a GITHUB_TOKEN to raise the limit.",+ 429,+ );+ }+ return new StargazersError(+ "fetch_failed",+ `GitHub request failed (${context}): ${res.status} ${res.statusText}`,+ 502,+ );+}++/** Pull the `rel="last"` page number out of a GitHub Link header, if any. */+function parseLastPage(link: string | null): number | null {+ if (!link) return null;+ for (const part of link.split(",")) {+ const match = part.match(/[?&]page=(\d+)[^>]*>\s*;\s*rel="last"/);+ if (match) return Number(match[1]);+ }+ return null;+}++type RawStargazer = {+ starred_at?: string;+ user?: { login?: string; avatar_url?: string } | null;+};++function mapEntry(raw: RawStargazer): Stargazer | null {+ const user = raw?.user;+ if (!user?.login || !user.avatar_url || !raw.starred_at) return null;+ return {+ login: user.login,+ avatarUrl: user.avatar_url,+ starredAt: raw.starred_at,+ };+}++/**+ * Evenly sample down to `max` keyframes, always keeping the first and last+ * entry. Replicated from the component's `downsampleStargazers` so the data+ * layer stays free of the `"use client"` registry module.+ */+function downsample(stargazers: Stargazer[], max = KEYFRAME_CAP): Stargazer[] {+ const len = stargazers.length;+ if (len <= max) return stargazers;+ if (max <= 1) return len ? [stargazers[0]] : [];+ const out: Stargazer[] = [];+ for (let i = 0; i < max; i++) {+ out.push(stargazers[Math.round((i * (len - 1)) / (max - 1))]);+ }+ return out;+}++/** Run `fn` over `items` with a bounded number of in-flight requests. */+async function mapWithConcurrency<T, R>(+ items: T[],+ limit: number,+ fn: (item: T) => Promise<R>,+): Promise<R[]> {+ const results = new Array<R>(items.length);+ let cursor = 0;+ const workers = Array.from(+ { length: Math.min(limit, items.length) },+ async () => {+ while (cursor < items.length) {+ const index = cursor++;+ results[index] = await fn(items[index]);+ }+ },+ );+ await Promise.all(workers);+ return results;+}++async function fetchStargazerPage(+ owner: string,+ repo: string,+ page: number,+ signal?: AbortSignal,+): Promise<{ entries: RawStargazer[]; link: string | null }> {+ const url = `${API_BASE}/repos/${owner}/${repo}/stargazers?per_page=${PER_PAGE}&page=${page}`;+ let res: Response;+ try {+ res = await fetch(url, {+ headers: buildHeaders("application/vnd.github.star+json"),+ signal,+ next: { revalidate: 3600 },+ });+ } catch (err) {+ if (err instanceof StargazersError) throw err;+ throw new StargazersError(+ "fetch_failed",+ `Network error fetching stargazers page ${page}.`,+ 502,+ );+ }+ if (!res.ok) throw errorForResponse(res, `stargazers page ${page}`);+ const entries = (await res.json()) as RawStargazer[];+ return { entries, link: res.headers.get("link") };+}++/**+ * Fetch a repository's stargazers with `starred_at` timestamps, sorted oldest+ * → newest and downsampled to a small keyframe set for the animation.+ *+ * - Uses `Accept: application/vnd.github.star+json` (required for `starred_at`).+ * - Sends `Authorization: Bearer ${GITHUB_TOKEN}` only when the env var is set;+ * works unauthenticated (60/hr) too.+ * - Reads the total page count from the first response's Link header and fetches+ * the rest in parallel (bounded), capped at `MAX_PAGES` → `truncated: true`.+ * - Throws {@link StargazersError} for not-found / rate-limited / fetch failures.+ */+export async function fetchStargazers({+ owner,+ repo,+ signal,+}: {+ owner: string;+ repo: string;+ signal?: AbortSignal;+}): Promise<StargazersResult> {+ // 1. Repo endpoint → existence check (404) + authoritative star total.+ let repoRes: Response;+ try {+ repoRes = await fetch(`${API_BASE}/repos/${owner}/${repo}`, {+ headers: buildHeaders("application/vnd.github+json"),+ signal,+ next: { revalidate: 3600 },+ });+ } catch (err) {+ if (err instanceof StargazersError) throw err;+ throw new StargazersError(+ "fetch_failed",+ "Network error fetching repository.",+ 502,+ );+ }+ if (!repoRes.ok) throw errorForResponse(repoRes, "repo");+ const repoData = (await repoRes.json()) as { stargazers_count?: number };+ const totalStars =+ typeof repoData.stargazers_count === "number"+ ? repoData.stargazers_count+ : 0;++ // 2. Zero-star repo: nothing to paginate, render gracefully.+ if (totalStars === 0) {+ return { stargazers: [], totalStars: 0, truncated: false };+ }++ // 3. First page drives the page count via its Link header.+ const first = await fetchStargazerPage(owner, repo, 1, signal);+ const lastPage = parseLastPage(first.link) ?? 1;+ const cappedLastPage = Math.min(lastPage, MAX_PAGES);+ const truncated = lastPage > MAX_PAGES;++ const rawEntries: RawStargazer[] = [...first.entries];++ // 4. Remaining pages in parallel (bounded concurrency).+ if (cappedLastPage > 1) {+ const pages: number[] = [];+ for (let p = 2; p <= cappedLastPage; p++) pages.push(p);+ const pageResults = await mapWithConcurrency(pages, CONCURRENCY, (page) =>+ fetchStargazerPage(owner, repo, page, signal),+ );+ for (const result of pageResults) rawEntries.push(...result.entries);+ }++ // 5. Map → filter → sort ascending by starredAt → downsample.+ const mapped = rawEntries+ .map(mapEntry)+ .filter((s): s is Stargazer => s !== null)+ .sort((a, b) => a.starredAt.localeCompare(b.starredAt));++ const stargazers = downsample(mapped);++ return { stargazers, totalStars, truncated };+}diff --git a/lib/parse-repo.ts b/lib/parse-repo.tsnew file mode 100644index 00000000..cb60279e--- /dev/null+++ b/lib/parse-repo.ts@@ -0,0 +1,48 @@+// Client-safe repo parsing — no `process.env`, no GitHub token, no fetch. Lives+// apart from `github-stargazers.ts` (a server-only module) so the `/stars`+// client tool can validate input without pulling server code into the bundle.++// GitHub owner: alphanumerics + single hyphens, max 39 chars (lenient on edges).+const OWNER_RE = /^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,37}[a-zA-Z0-9])?$/;+// Repo name: alphanumerics, dot, hyphen, underscore.+const REPO_RE = /^[a-zA-Z0-9._-]+$/;++/**+ * Normalize a user-supplied repo reference into `{ owner, repo }`.+ *+ * Accepts `owner/name`, a full `https://github.com/owner/name` URL, trailing+ * slashes, a `.git` suffix, and extra path segments (`/tree/main`, etc.).+ * Returns `null` on anything that doesn't yield a charset-valid owner + repo.+ */+export function parseRepoInput(+ input: string,+): { owner: string; repo: string } | null {+ if (typeof input !== "string") return null;+ let s = input.trim();+ if (!s) return null;++ // Drop scheme and a leading github.com host if present.+ s = s.replace(/^[a-z]+:\/\//i, "");+ s = s.replace(/^(?:www\.)?github\.com\//i, "");+ // Drop any query string or hash fragment (e.g. "?tab=readme", "#readme") so+ // it can't contaminate the repo segment after the slash split.+ s = s.replace(/[?#].*$/, "");+ // Collapse leading/trailing slashes.+ s = s.replace(/^\/+/, "").replace(/\/+$/, "");+ if (!s) return null;++ const segments = s.split("/");+ if (segments.length < 2) return null;++ const owner = segments[0];+ let repo = segments[1];+ repo = repo.replace(/\.git$/i, "");++ if (!owner || !repo) return null;+ if (!OWNER_RE.test(owner)) return null;+ if (!REPO_RE.test(repo)) return null;+ // A bare "." or ".." repo is invalid on GitHub.+ if (repo === "." || repo === "..") return null;++ return { owner, repo };+}diff --git a/package.json b/package.jsonindex c1e2919c..9f99f308 100644--- a/package.json+++ b/package.json@@ -13,10 +13,11 @@},"dependencies": {"@base-ui/react": "^1.3.0",+ "@openpanel/nextjs": "^1.0.13","@react-three/fiber": "^9.3.0","@react-three/postprocessing": "^3.0.4",- "@openpanel/nextjs": "^1.0.13","@remotion/player": "^4.0.392",+ "@remotion/web-renderer": "^4.0.473","class-variance-authority": "^0.7.1","clsx": "^2.1.1","cmdk": "^1.1.1",diff --git a/registry/remocn/github-stars/config.ts b/registry/remocn/github-stars/config.tsindex a8a50255..5fb7cd0a 100644--- a/registry/remocn/github-stars/config.ts+++ b/registry/remocn/github-stars/config.ts@@ -28,7 +28,7 @@ export const githubStarsConfig: ComponentConfig = {options: ["horizontal", "vertical"],label: "Orientation",},- accentColor: { type: "color", default: "#f5a623", label: "Accent" },+ accentColor: { type: "color", default: "#ffbb00", label: "Accent" },theme: {type: "select",default: "light",diff --git a/registry/remocn/github-stars/index.tsx b/registry/remocn/github-stars/index.tsxindex d6f36434..fe836363 100644--- a/registry/remocn/github-stars/index.tsx+++ b/registry/remocn/github-stars/index.tsx@@ -1051,7 +1051,7 @@ export function GitHubStars({totalStars = 24813,stargazers = SAMPLE_STARGAZERS,orientation = "horizontal",- accentColor = "#f5a623",+ accentColor = "#ffbb00",speed = 1,theme = "light",}: GitHubStarsProps) {