diff --git a/.env.example b/.env.example index 648bb17..c169625 100644 --- a/.env.example +++ b/.env.example @@ -1,15 +1,27 @@ # Optional for the public site. Copy this file to .env at the repository root. # All workspace commands load root .env files; process variables take precedence. -# Neon PostgreSQL connection string; leave blank until database features are added. +# Neon runtime connection string; required for the forum, optional for Astro. # Example: postgresql://USER:PASSWORD@HOST/DATABASE?sslmode=require DATABASE_URL= -# Shared auth factories are ready for future use; no auth routes are mounted. +# Direct connections for migration and moderator commands. Never used interchangeably. +DEV_DATABASE_URL= +PROD_DATABASE_URL= + +# Authentication is hosted by the Next.js forum app. # Generate a secret with: openssl rand -base64 32 BETTER_AUTH_SECRET= +# Production on Vercel: https://forum.manipalosf.org (no /forum suffix). BETTER_AUTH_URL=http://localhost:3000 +# Cross-app links. Development defaults to localhost ports 3000 and 4321. +# Defaults to https://forum.manipalosf.org/ in production; override if needed. +PUBLIC_FORUM_URL= +# Defaults to https://manipalosf.org in production. +PUBLIC_SITE_URL= + +# Required for forum signup, email verification, and password recovery. # Resend API key and a sender address on your verified domain. # Local email previews do not need these values. RESEND_API_KEY= diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2151fed..9e4eb7d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,9 @@ jobs: - run: pnpm typecheck - run: pnpm lint - run: pnpm test + - run: pnpm db:check - run: pnpm build - - run: node scripts/prepare-vercel.mjs - - run: node scripts/verify-vercel.mjs + - name: Prepare and verify Astro service output + run: | + node scripts/prepare-vercel.mjs + node scripts/verify-vercel.mjs diff --git a/README.md b/README.md index 8d94f03..a8b941f 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Manipal OSF website -The Manipal OSF website lives in a pnpm and Turborepo monorepo modeled on [create-t3-turbo](https://github.com/t3-oss/create-t3-turbo). The public website uses Astro components and TypeScript browser scripts, with Vercel ISR for live GitHub data. +The Manipal OSF website lives in a pnpm and Turborepo monorepo modeled on [create-t3-turbo](https://github.com/t3-oss/create-t3-turbo). The public website uses Astro components and TypeScript browser scripts, with Vercel ISR for live GitHub data. A Next.js app hosts the community forum at https://forum.manipalosf.org/. Both apps deploy together through Vercel Services. ## Development @@ -11,7 +11,7 @@ pnpm install pnpm dev ``` -Open http://localhost:4321. The public website needs no service credentials. An optional `GITHUB_TOKEN` increases the GitHub API rate limit for statistics. +Open http://localhost:4321 for the public site or http://localhost:3000/ for the forum. The public website needs no service credentials. An optional `GITHUB_TOKEN` increases the GitHub API rate limit for statistics. ```sh pnpm typecheck @@ -19,11 +19,13 @@ pnpm lint pnpm test pnpm build # Vercel deployment output pnpm build:local # Node production build -pnpm start # Serve the Node build on port 4321 +pnpm start # Serve the Astro Node build on port 4321 +pnpm start:forum # Serve the Next.js production build on port 3000 +pnpm dev:forum # Run just the forum pnpm format ``` -`dev` starts workspaces under `apps/`. `build`, `lint`, `typecheck`, and `test` use Turbo's dependency graph and cache. Development servers and email previews are uncached. Turbo caches `dist/`, `.astro/`, and `.vercel/output/` build artifacts. Environment changes invalidate task caches. +`dev` starts workspaces under `apps/`. `build`, `lint`, `typecheck`, and `test` use Turbo's dependency graph and cache. Development servers and email previews are uncached. Turbo caches `dist/`, `.astro/`, and `.vercel/output/`, and `.next/` build artifacts (excluding the Next.js compiler cache). Environment changes invalidate task caches. To target the website directly: @@ -37,6 +39,7 @@ pnpm build --filter=@apps/astro... | Location | Package | Responsibility | | ---------------- | ----------------- | ------------------------------------------------------------- | | `apps/astro` | `@apps/astro` | Astro website, content, public assets, and site-specific code | +| `apps/nextjs` | `@apps/nextjs` | Next.js community forum and authentication | | `packages/env` | `@packages/env` | T3 Env validation and root environment loading | | `packages/db` | `@packages/db` | Lazy Neon HTTP / Drizzle database clients | | `packages/auth` | `@packages/auth` | Configurable Better Auth factory | @@ -60,16 +63,20 @@ cp .env.example .env Import `env` from `@packages/env` in server code. T3 Env and Zod validate supplied values, treat empty strings as unset, and prevent access to server variables in browser code. The filesystem loader is separate at `@packages/env/load`; do not import it into application runtime code. -| Variable | Purpose | -| -------------------- | --------------------------------------------------------------- | -| `DATABASE_URL` | Optional Neon PostgreSQL URL (`postgres://` or `postgresql://`) | -| `BETTER_AUTH_SECRET` | Optional auth secret, at least 32 characters | -| `BETTER_AUTH_URL` | Optional auth origin for a future app instance | -| `RESEND_API_KEY` | Required when calling the website's `getResend()` | -| `RESEND_FROM_EMAIL` | Optional sender address on a verified Resend domain | -| `GITHUB_TOKEN` | Optional higher GitHub API rate limit | - -All current variables are server-side. Keep `.env*` ignored except the credential-free example. When adding variables, update the shared validation schema, example file, and Turbo environment inputs together. Future apps can compose their own validation from this package as their requirements diverge. +| Variable | Purpose | +| -------------------- | -------------------------------------------------------------------------------------------------------------------- | +| `DATABASE_URL` | Optional Neon PostgreSQL URL (`postgres://` or `postgresql://`) | +| `BETTER_AUTH_SECRET` | Optional auth secret, at least 32 characters | +| `BETTER_AUTH_URL` | Forum auth origin: `http://localhost:3000` locally, `https://forum.manipalosf.org` in production | +| `DEV_DATABASE_URL` | Direct development connection for migrations/moderator commands | +| `PROD_DATABASE_URL` | Direct production connection for migrations/moderator commands | +| `PUBLIC_FORUM_URL` | Forum navigation URL; defaults to `http://localhost:3000/` locally and `https://forum.manipalosf.org/` in production | +| `PUBLIC_SITE_URL` | Forum link back to Astro; defaults to local Astro in development and `https://manipalosf.org` in production | +| `RESEND_API_KEY` | Required for forum signup, verification emails, and password recovery | +| `RESEND_FROM_EMAIL` | Required sender address on a verified Resend domain for forum authentication emails | +| `GITHUB_TOKEN` | Optional higher GitHub API rate limit | + +Only the two `PUBLIC_` link settings are public; credentials remain server-side. Migration URLs are read only by database tooling and never by application runtime code. Keep `.env*` ignored except the credential-free example. When adding variables, update the shared validation schema, example file, and Turbo environment inputs together. Future apps can compose their own validation from this package as their requirements diverge. ## Database and authentication @@ -77,15 +84,60 @@ All current variables are server-side. Keep `.env*` ignored except the credentia `@packages/auth` exports `createAuth({ db, schema, options })`. Supply an explicit Drizzle auth schema and app-specific `secret`, `baseURL`, and `trustedOrigins`; `options` also accepts Better Auth providers, plugins, and session configuration. The factory preserves plugin and additional-field inference, uses the PostgreSQL Drizzle adapter, and disables interactive transactions. It does not establish a global auth singleton or shared cookie domain. -The website does not instantiate auth or mount auth endpoints. Auth tables, login methods, schema generation, migrations, and login pages remain deferred. When implementing them, generate the schema from the final auth configuration, keep tables and migrations in `packages/db`, and mount the framework-specific handler inside the consuming app. Set each app's URL and trusted origins explicitly. Drizzle Kit is owned by the database package; migration commands will be added with the actual schema. +Astro does not mount authentication. The Next.js app instantiates the shared factory with the username plugin, app-specific origins, and schemas exported by `@packages/db/schema/auth`. The full schema is available at `@packages/db/schema`; the generic `createDb` and `getDb` APIs remain available. + +### Forum setup + +Set `DATABASE_URL`, `BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`, `RESEND_API_KEY`, and `RESEND_FROM_EMAIL` at the repository root, with runtime and migration connections pointing to the same database. Use an address on a verified Resend domain for `RESEND_FROM_EMAIL`. Set `DEV_DATABASE_URL` to the direct development connection, then run: + +```sh +pnpm db:migrate:dev +pnpm dev +``` + +Use **Log in** in the forum header, then **Create an account** to sign up. Signup requires a name, email, unique username (3–30 letters, digits, underscores, or dots), and an 8–128 character password. Signup sends a verification email and does not create a session. Members must verify their email before logging in with email or username; existing unverified members must verify before their next login. Verification links expire after one hour. `/verify-email` provides resend instructions and confirmation; after verification, members log in explicitly. Unverified login attempts also send a fresh verification email. Successful authentication returns to a validated local forum destination. Signed-in members see their username and Logout. Anonymous visitors can read, but participation requires a session. + +**Forgot password?** on login opens `/forgot-password`. Requests display the same confirmation for known and unknown addresses. The email opens `/reset-password`, where members enter and confirm an 8–128 character password. Reset links expire after one hour and can be used once. A successful reset revokes all existing sessions and requires a new login; it does not mark an unverified email as verified. Existing sessions otherwise remain valid until logout or expiry. Email callbacks use React Email templates and Resend; missing email configuration returns a sanitized 503 for email-dependent operations while forum reads and existing sessions remain available. Delivery failures offer retry instructions, and an account created before a failed verification email can request a new link. + +The auth handler lives at `/api/auth/[...all]`, including Better Auth's verification and password reset endpoints and rate limiting. Cookies are scoped to the forum host; the two apps do not share sessions. OAuth and profile editing are not included. Without database credentials, forum pages display an unavailable message and auth endpoints return a sanitized 503. Both apps still build without credentials. The existing auth tables support verification and recovery; no additional migration is needed. + +### Forum behavior + +The forum ports `feat/forum-legacy`: Top/New/Ask/Show feeds, search, pagination, link/text submissions, threaded replies, reversible upvotes, author editing/deletion, member activity/karma, reports, and moderation. User content is plain text with HTTP(S) links. Deleted comments retain their replies; hidden discussions conceal their replies; locked discussions reject new replies. Forum and auth pages use `noindex` metadata. + +Internal forum keys remain PostgreSQL BIGINT identities mapped to JavaScript `bigint`; public post/comment IDs remain 16-character NanoIDs. Preserve the comment-integrity trigger, indexes, database constraints, atomic writes, and the per-account rate limits in the ported schema/store. Signup cannot grant moderator access. Moderator actions require reasons and create audit records. + +```sh +pnpm forum:moderator add your_username # DEV_DATABASE_URL +pnpm forum:moderator remove your_username +pnpm forum:moderator add your_username prod # PROD_DATABASE_URL +``` + +### Schema and migrations + +Schemas and committed migration history live in `packages/db`. The legacy SQL, journal, and snapshots are preserved, so an existing migrated database does not need to be recreated. Subsequent changes must use additive migrations; never rewrite applied history. Keep generated auth tables separate from forum tables. + +```sh +pnpm auth:generate # Pinned auth@1.7.7 CLI, matching Better Auth +pnpm db:generate # Generate SQL from the shared schema +pnpm db:check # Check migration-history consistency +pnpm db:migrate # Alias for db:migrate:dev +pnpm db:migrate:dev # Requires DEV_DATABASE_URL +pnpm db:migrate:prod # Requires PROD_DATABASE_URL +pnpm test:forum # Forum, auth, and deployment tests +pnpm test:auth +pnpm test:db +``` + +Generation and history checks do not connect to a database. Migration and moderator commands load root environment files for the explicitly selected stage, honor injected values, and never fall back to another stage's URL or `DATABASE_URL`. Tests apply migrations twice to disposable PGlite databases, exercising actual PostgreSQL queries without Neon credentials. ## Shared UI and Tailwind -Import Astro components from `@packages/ui/components/avatar` and `@packages/ui/components/badge`, and `cn` from `@packages/ui/lib/utils`. The unused button and extra avatar components have been removed. There is no React/shadcn component-generation command. +Import Astro components from `@packages/ui/components/avatar` and `@packages/ui/components/badge`, and `cn` from `@packages/ui/lib/utils`. The unused button and extra avatar components have been removed. Next.js keeps its React forum controls inside its own app and reuses the shared `cn` helper; the Astro component exports remain framework-specific. `@tooling/tailwind/styles.css` provides Tailwind v4, animation imports, theme tokens, the `data-theme` dark variant, common base styles, and shared UI source registration. Applications import this CSS and register their own source directory with `@source`. The website retains its Nord light and Catppuccin dark palettes and self-hosted Cascadia Code font. -The website ships Astro HTML with small browser modules for theme switching, map controls, reading progress, and timeline effects. MapLibre is loaded near the viewport, with campus links available when the map cannot load. React remains in the email package for React Email templates. +The website ships Astro HTML with small browser modules for theme switching, map controls, reading progress, and timeline effects. MapLibre is loaded near the viewport, with campus links available when the map cannot load. React is used by the Next.js forum and React Email templates. ## Email templates @@ -93,18 +145,50 @@ The website ships Astro HTML with small browser modules for theme switching, map pnpm email:dev ``` -Open http://localhost:3001 to preview `packages/email/templates/example.tsx`. Previews need no API key and send no email. Apps can import the template from `@packages/email/example`. +Open http://localhost:3001 to preview the email verification and password reset templates. Previews use sample links, need no API key, and send no email. Apps can import templates from `@packages/email/verify-email` and `@packages/email/reset-password`. `@packages/email/render` renders auth emails to HTML and plain text. + +All templates use Nord light colors and switch to Catppuccin Mocha in clients that support dark-mode email styles. Inline Nord colors provide a fallback for clients that strip embedded CSS. + +The forum lazily creates its own server-only Resend client for authentication emails using `RESEND_API_KEY` and `RESEND_FROM_EMAIL`. Automatic sends are limited to auth flows; there is no general-purpose public email endpoint. The Astro website retains its separate lazy `getResend()` helper at `@/lib/resend`. Auth integration tests capture emails locally and exercise PostgreSQL migrations with PGlite; they never send live mail. + +## Vercel deployment + +The repository-root `vercel.json` deploys both applications as one Vercel project using [Vercel Services](https://vercel.com/docs/services), currently in beta. The `website` service builds Astro from `apps/astro`; the `forum` service builds Next.js from `apps/nextjs`. Each service owns its framework and build settings in this single configuration file. Both apps deploy and roll back together. + +Top-level hostname routing sends every request on `forum.manipalosf.org` to the forum, including `/api/auth`, Server Actions, and `/_next` assets. Remaining hosts, including the default Vercel deployment URL, serve Astro. Website redirects and image headers are scoped to the website service. The forum feed lives at `/`, with discussions at `/item/:publicId`, profiles at `/user/:username`, and `/comments`, `/submit`, and `/moderation` alongside them. Legacy `/forum` and `/forum/*` URLs permanently redirect to their new paths and retain query strings. -The website retains its lazy `getResend()` helper at `@/lib/resend`. There are no sending endpoints or automatic email triggers. +### Project and domains -## Vercel and additional apps +Use one Vercel project with its Root Directory at the repository root, select Node.js 24, and enable Corepack (`ENABLE_EXPERIMENTAL_COREPACK=1`) to use the pinned pnpm version. Allow workspace files outside service directories and remove old dashboard framework/build/output overrides; `services` in the root configuration owns the per-app settings. An existing project rooted at `apps/nextjs` is no longer required. -The root `vercel.json` deploys `@apps/astro` using a filtered Turbo build and the Vercel adapter's Build Output API artifacts. The deployment command copies `apps/astro/.vercel/output` into the root `.vercel/output` expected by Vercel, including functions, hourly ISR configuration, redirects, and PNG content types. Keep the Vercel project's Root Directory at the repository root, select Node.js 24, and enable Corepack (`ENABLE_EXPERIMENTAL_COREPACK=1`) to use the pinned pnpm version. Remove conflicting dashboard command overrides. No root framework dependency is needed. +Attach `manipalosf.org` and `forum.manipalosf.org` to this project under Settings → Domains, then configure the DNS records Vercel supplies. Reassign the forum hostname from any previous forum project. Domain ownership and DNS setup are managed in Vercel and your DNS provider, rather than in `vercel.json`. + +Set these environment values in the project's **Production** environment: + +| Variable | Value | +| ------------------------------ | -------------------------------------------------------------- | +| `ENABLE_EXPERIMENTAL_COREPACK` | `1` | +| `BETTER_AUTH_URL` | `https://forum.manipalosf.org` | +| `PUBLIC_SITE_URL` | `https://manipalosf.org` | +| `PUBLIC_FORUM_URL` | Optional override; defaults to `https://forum.manipalosf.org/` | +| `DATABASE_URL` | Forum runtime connection to the production database | +| `PROD_DATABASE_URL` | Direct migration connection to the same production database | +| `BETTER_AUTH_SECRET` | Auth secret, at least 32 characters | +| `RESEND_API_KEY` | Resend API key | +| `RESEND_FROM_EMAIL` | Sender address on a verified Resend domain | + +Preview deployment URLs default to Astro; continue using port 3000 for local forum development. A forum preview requires an explicitly assigned preview hostname, an additional forum host condition in the root configuration, and a matching preview `BETTER_AUTH_URL`. Preview database settings must use a development database: set `DEV_DATABASE_URL` and point preview `DATABASE_URL` to that same database. Keep secrets in Vercel environment settings and never commit them. Cross-app navigation uses ordinary links, and cookies remain scoped to the forum host. + +### Builds, migrations, and validation + +Astro's service build runs `pnpm run build` inside `apps/astro`, then `scripts/prepare-vercel.mjs` finalizes its own `apps/astro/.vercel/output`. It preserves packaged dependencies, hourly ISR, redirects, PNG content types, and authored offline responses. No output is copied to the repository root or merged with Next.js artifacts. Content pages, feeds, metadata, and social preview PNGs are prerendered. Home and team pages render on demand and use a 3,600-second ISR expiration; after expiry, a request triggers regeneration. Failed GitHub loads return an uncached 503 page with offline messaging or the authored timeline so failed regeneration does not replace successful cached content. Actual Vercel cache hits and regeneration must be verified on a deployment; local Node runs do not emulate the platform cache. -For a local production server, run `pnpm build:local`, then `pnpm start`. The local build explicitly selects `@astrojs/node`; the default `pnpm build` selects `@astrojs/vercel`. You can override the local server's interface and port using `HOST` and `PORT`. +The forum service runs its `build:vercel` script: history check, database migrations, then the Next.js build. `VERCEL_ENV=production` selects `PROD_DATABASE_URL`; `preview` and `development` select `DEV_DATABASE_URL`. Missing/unknown environments, missing migration URLs, and failed steps stop deployment. Ordinary `pnpm build` and CI builds never migrate live databases. Migrations remain applied if either service's build later fails, so keep changes compatible with the prior deployment. -Add future applications under `apps/`, name them `@apps/`, declare shared packages using `workspace:*`, and extend shared tooling. Each future app should have its own Vercel project, environment values, and app-specific deployment configuration. The root config remains specific to the current website; it does not deploy every app. For a project rooted in a new app directory, enable access to files outside that root so shared packages are available. Do not reuse the website's root build and output settings for another app. +GitHub Actions installs with the frozen lockfile and runs typecheck, lint, tests, migration-history checks, both production builds, and Astro service-output verification. No live database, migration, email, or deployment is required for CI. On Vercel, verify hostname isolation, forum routes and legacy redirects, authentication and email origins, assets, and Astro ISR before considering the rollout complete. + +For a local production server, run `pnpm build:local`, then `pnpm start`. The local build explicitly selects `@astrojs/node`; the default `pnpm build` selects `@astrojs/vercel`. You can override the local server's interface and port using `HOST` and `PORT`. -GitHub Actions installs with the frozen lockfile and runs typecheck, lint, content/GitHub and service-package tests, the Vercel production build, and execution of the packaged server functions with GitHub offline. No live database, migration, email, or deployment is required for these checks. +Add future applications under `apps/`, name them `@apps/`, declare shared packages using `workspace:*`, and add their service and routing rules to the root `vercel.json` when they should share this deployment. diff --git a/apps/astro/src/components/layout/NavLinks.astro b/apps/astro/src/components/layout/NavLinks.astro index 182253f..2bc24da 100644 --- a/apps/astro/src/components/layout/NavLinks.astro +++ b/apps/astro/src/components/layout/NavLinks.astro @@ -1,6 +1,12 @@ --- import { activeNavItem, navItems } from '@/lib/site'; +import { env } from '@packages/env'; const active = activeNavItem(Astro.url.pathname); +const forumUrl = + env.PUBLIC_FORUM_URL ?? + (import.meta.env.DEV + ? 'http://localhost:3000/' + : 'https://forum.manipalosf.org/'); --- { @@ -16,3 +22,12 @@ const active = activeNavItem(Astro.url.pathname); )) } +{ + forumUrl && ( +
  • + + Forum + +
  • + ) +} diff --git a/apps/nextjs/auth-schema.config.ts b/apps/nextjs/auth-schema.config.ts new file mode 100644 index 0000000..89914dd --- /dev/null +++ b/apps/nextjs/auth-schema.config.ts @@ -0,0 +1,6 @@ +import { betterAuth } from 'better-auth/minimal'; +import { authOptions } from './src/lib/auth-options'; + +// Tooling only: schema generation needs the plugins, never live credentials. +// The CLI's --adapter and --dialect flags select Drizzle/PostgreSQL. +export const auth = betterAuth(authOptions); diff --git a/apps/nextjs/eslint.config.mjs b/apps/nextjs/eslint.config.mjs new file mode 100644 index 0000000..cdcf865 --- /dev/null +++ b/apps/nextjs/eslint.config.mjs @@ -0,0 +1,5 @@ +import { defineConfig } from 'eslint/config'; +import next from '@next/eslint-plugin-next'; +import react from '@tooling/eslint/react'; + +export default defineConfig([...react, next.configs['core-web-vitals']]); diff --git a/apps/nextjs/next.config.ts b/apps/nextjs/next.config.ts new file mode 100644 index 0000000..973774c --- /dev/null +++ b/apps/nextjs/next.config.ts @@ -0,0 +1,13 @@ +import type { NextConfig } from 'next'; +import '@packages/env'; + +const config: NextConfig = { + reactStrictMode: true, + redirects() { + return [ + { source: '/forum/:path*', destination: '/:path*', permanent: true }, + ]; + }, +}; + +export default config; diff --git a/apps/nextjs/package.json b/apps/nextjs/package.json new file mode 100644 index 0000000..63cc191 --- /dev/null +++ b/apps/nextjs/package.json @@ -0,0 +1,50 @@ +{ + "name": "@apps/nextjs", + "private": true, + "type": "module", + "scripts": { + "dev": "with-env development next dev --port 3000", + "build": "with-env production next build", + "build:vercel": "node scripts/vercel-build.mjs", + "start": "with-env production next start --port 3000", + "lint": "eslint .", + "typecheck": "with-env production next typegen && tsc --noEmit", + "test": "tsx --test tests/*.test.ts", + "auth:generate": "pnpm dlx auth@1.7.7 generate --config ./auth-schema.config.ts --adapter drizzle --dialect postgresql --output ../../packages/db/src/schema/auth.ts --yes" + }, + "dependencies": { + "@base-ui/react": "1.8.0", + "@fontsource-variable/cascadia-code": "5.3.0", + "@packages/auth": "workspace:*", + "@packages/db": "workspace:*", + "@packages/email": "workspace:*", + "@packages/env": "workspace:*", + "@packages/ui": "workspace:*", + "better-auth": "1.7.7", + "class-variance-authority": "0.7.1", + "drizzle-orm": "catalog:", + "lucide-react": "1.52.0", + "nanoid": "6.0.2", + "next": "16.4.0", + "react": "catalog:", + "react-dom": "catalog:", + "resend": "^6.32.1", + "server-only": "0.0.1", + "zod": "catalog:" + }, + "devDependencies": { + "@better-auth/drizzle-adapter": "1.7.7", + "@electric-sql/pglite": "0.5.10", + "@next/eslint-plugin-next": "16.4.0", + "@tooling/eslint": "workspace:*", + "@tooling/tailwind": "workspace:*", + "@tooling/typescript": "workspace:*", + "@types/node": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "eslint": "catalog:", + "postcss": "catalog:", + "tsx": "4.23.15", + "typescript": "catalog:" + } +} diff --git a/apps/nextjs/postcss.config.mjs b/apps/nextjs/postcss.config.mjs new file mode 100644 index 0000000..47b83e4 --- /dev/null +++ b/apps/nextjs/postcss.config.mjs @@ -0,0 +1 @@ +export { default } from '@tooling/tailwind/postcss'; diff --git a/apps/nextjs/scripts/vercel-build.mjs b/apps/nextjs/scripts/vercel-build.mjs new file mode 100644 index 0000000..10bccc5 --- /dev/null +++ b/apps/nextjs/scripts/vercel-build.mjs @@ -0,0 +1,33 @@ +import { spawnSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; + +let migration; +switch (process.env.VERCEL_ENV) { + case 'production': + migration = 'db:migrate:prod'; + break; + case 'preview': + case 'development': + migration = 'db:migrate:dev'; + break; + default: + console.error('VERCEL_ENV must be production, preview, or development.'); + process.exit(1); +} + +const root = fileURLToPath(new URL('../../../', import.meta.url)); +for (const args of [ + ['--filter', '@packages/db', 'db:check'], + ['--filter', '@packages/db', migration], + ['--filter', '@apps/nextjs', 'build'], +]) { + const result = spawnSync('pnpm', args, { cwd: root, stdio: 'inherit' }); + if (result.error) { + console.error( + `Unable to run pnpm ${args.join(' ')}: ${result.error.message}`, + ); + } + if (result.status !== 0) { + process.exit(result.status ?? 1); + } +} diff --git a/apps/nextjs/src/app/(forum)/actions.ts b/apps/nextjs/src/app/(forum)/actions.ts new file mode 100644 index 0000000..551bb84 --- /dev/null +++ b/apps/nextjs/src/app/(forum)/actions.ts @@ -0,0 +1,72 @@ +'use server'; + +import { revalidatePath } from 'next/cache'; +import { z } from 'zod'; +import { getForumContext } from '@/lib/forum'; +import { ForumError } from '@/lib/forum-store'; +import type { ForumActionResult } from '@/types/forum'; + +export async function forumAction(form: FormData): Promise { + try { + const { store, viewer } = await getForumContext(); + if (!store) return { error: 'The forum database is not configured yet.' }; + if (!viewer) + return { error: 'Your session has ended. Log in again to participate.' }; + const input = Object.fromEntries(form.entries()); + let location: string | undefined; + let success = 'Saved.'; + switch (input.action) { + case 'post': { + const id = await store.createPost(viewer, input); + location = `/item/${id}`; + break; + } + case 'comment': { + const id = await store.createComment(viewer, { + ...input, + parentId: input.parentId || undefined, + }); + location = `/item/${input.postId}#comment-${id}`; + success = 'Comment posted.'; + break; + } + case 'vote': + await store.vote(viewer, { ...input, voted: input.voted === 'true' }); + break; + case 'edit': + await store.edit(viewer, input); + break; + case 'delete': + await store.remove(viewer, input); + success = 'Deleted.'; + break; + case 'report': + await store.report(viewer, input); + success = 'Report received. Thank you.'; + break; + case 'moderate': + await store.moderate(viewer, { + ...input, + reportId: input.reportId || undefined, + }); + break; + default: + return { error: 'Unknown forum action.' }; + } + revalidatePath('/(forum)', 'layout'); + return { success, location }; + } catch (error) { + if (error instanceof z.ZodError) + return { error: error.issues[0]?.message ?? 'Check your input.' }; + if (error instanceof ForumError) return { error: error.message }; + // Keep database errors, statements, and account information out of responses. + console.error( + 'Forum action failed', + error instanceof Error ? error.name : 'Unknown error', + ); + return { + error: + 'Could not save your changes. Your draft is still here. Please try again.', + }; + } +} diff --git a/apps/nextjs/src/app/(forum)/comments/page.tsx b/apps/nextjs/src/app/(forum)/comments/page.tsx new file mode 100644 index 0000000..42da7d7 --- /dev/null +++ b/apps/nextjs/src/app/(forum)/comments/page.tsx @@ -0,0 +1,32 @@ +import { getForumContext } from '@/lib/forum'; +import { forumPage } from '@/lib/forum-store'; +import ForumComments from '@/components/forum/ForumComments'; +import { + ForumPagination, + ForumUnavailable, +} from '@/components/forum/ForumDisplay'; + +export default async function CommentsPage({ + searchParams, +}: { + searchParams: Promise<{ page?: string }>; +}) { + const { store, viewer, moderator } = await getForumContext(); + if (!store) return ; + const result = await store.comments({ + viewer, + page: forumPage((await searchParams).page), + }); + return ( + <> +

    Recent comments

    + + + + ); +} diff --git a/apps/nextjs/src/app/(forum)/error.tsx b/apps/nextjs/src/app/(forum)/error.tsx new file mode 100644 index 0000000..52d2c5a --- /dev/null +++ b/apps/nextjs/src/app/(forum)/error.tsx @@ -0,0 +1,12 @@ +'use client'; + +export default function ForumError({ reset }: { reset: () => void }) { + return ( +
    +

    We could not load the forum. Please try again.

    + +
    + ); +} diff --git a/apps/nextjs/src/app/(forum)/item/[publicId]/page.tsx b/apps/nextjs/src/app/(forum)/item/[publicId]/page.tsx new file mode 100644 index 0000000..e5a8f91 --- /dev/null +++ b/apps/nextjs/src/app/(forum)/item/[publicId]/page.tsx @@ -0,0 +1,79 @@ +import { notFound } from 'next/navigation'; +import { getForumContext } from '@/lib/forum'; +import { + PostRow, + ForumUnavailable, + SafeText, +} from '@/components/forum/ForumDisplay'; +import { ContentControls } from '@/components/forum/ForumControls'; +import ForumComments from '@/components/forum/ForumComments'; +import ForumForm from '@/components/forum/ForumForm'; + +export default async function ItemPage({ + params, +}: { + params: Promise<{ publicId: string }>; +}) { + const { publicId } = await params; + const { store, viewer, moderator } = await getForumContext(); + if (!store) return ; + const post = await store.post(publicId, viewer); + if (!post) notFound(); + const { comments } = await store.comments({ postId: publicId, viewer }); + return ( +
    +

    {post.title}

    + + {post.body && ( +
    + +
    + )} + {viewer && !post.deleted && ( +
    + +
    + )} +
    + {post.hidden ? ( +

    + This discussion has been hidden by a moderator. +

    + ) : post.deleted ? ( +

    + The author deleted this submission. Existing replies remain below. +

    + ) : post.locked ? ( +

    + This discussion is locked to new replies. +

    + ) : viewer ? ( + +