Migrations 081 and 082: Feedback, Request, QR codes, Give, Privacy and Terms become pages of sections. Their forms and embeds are section types any page can use; Give's words and all of Privacy and Terms become blocks. The privacy contact email is written into the policy and its setting goes. Core pages keep their address and can't be deleted. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
17 KiB
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
NGU-Web
Website for NGU (Next Generation of Unity), a Unity movement organization with regional groups in the US and internationally. Full-stack app with a public site and a role-based admin panel.
Stack
- Frontend: React, TypeScript, Tailwind CSS, React Router, Vite (in
src/) - Backend: Hono on Node.js, SQLite (WAL mode, STRICT tables) via node:sqlite (in
server/) - Package manager: pnpm only (never npm or yarn)
Commands
Frontend (repo root):
pnpm dev/pnpm build/pnpm preview: Vitepnpm format: oxfmtpnpm exec tsc: type-check (noEmit; there is no separate lint or typecheck script).noImplicitAnyis off on purpose: turning it on shows about 480 errors (untyped props and params, mostly in OrgList-Map, admin fields, EntityEdit, EventList-Cards). Decided 2026-09-29 not to fix them; don't turn it on or start typing files for it unless asked. New code should still type its props.- There is no test suite.
Backend (server/, Node >= 22.13). The server reads HOST (default 127.0.0.1), PORT (default 3001), DB_PATH (default ./ngu.db) and UPLOADS_DIR (default ./uploads); locally, use DB_PATH=./dev.db:
DB_PATH=./dev.db pnpm dev: run withnode --watchDB_PATH=./dev.db pnpm migrate: apply migrations without starting the serverDB_PATH=./dev.db node src/admin-cli.js add|list|passwd|role|disable|enable ...: the only way accounts are createdDB_PATH=./dev.db node src/seed-showcase.js [--listed]: writes fully filled test records (a region, group, team, award, person, three events and a blog post with every content block type), ids startingshowcase-, for checking pages. Unlisted unless--listed. Refuses a database under /var/lib/ngu unless--productionis also given.
In dev, Vite proxies /api to the target set in vite.config.ts, so the API must listen on that port.
Deployment (production)
- Ubuntu VPS, nginx reverse proxy, systemd service
ngu-api - App deployed to
/srv/ngu-api; database at/var/lib/ngu/ngu.db - Debugging: check
journalctl -u ngu-api -n 40 --no-pagerfirst. Make sure rsync ran from the repo (not the deployed copy) before restarting the service. - Never run commands against the production server or database unless explicitly asked.
- Uploaded media:
UPLOADS_DIR=/var/lib/ngu/uploads, served by nginx at/uploads/. Setup and the nginx block are indocs/media-uploads.md. - Analytics: self-hosted Plausible, proxied by nginx at
/pa/. The API adds its script to every page (analyticsTaginserver/src/pageMeta.js), counting under the hostname ofsite.json'surl, so each deployment reports as itself. Nothing inindex.htmlor the app. Daily and weekly reports go to Discord when Panel → Site settings → Reports turns them on andPLAUSIBLE_API_KEYandDISCORD_WEBHOOK_URLare set (server/src/analyticsReport.js):docs/analytics-reports.md. Short links/go/<id>(Data → Links/redirects,server/src/routes/redirects.js) count clicks, report each to Plausible as a pageview and add the link's UTM tags:docs/redirects.md. - Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (
server/src/pageMeta.js), and serves/sitemap.xml. It readsSITE_CONFIG(site.json) andSITE_INDEX(the built index.html), with Panel → Site settings (thesite_settingstable) laid over site.json, and serves/robots.txtfrom the same merge. nginx setup:docs/seo.md. - Video clips (Tools, admins and up): yt-dlp downloads our YouTube/Facebook videos into
CLIPS_DIR, ffmpeg cuts them; one job at a time, files swept after a day (server/src/clips.js). Needs yt-dlp and ffmpeg on the VPS:docs/video-clips.md. - Newsletter countdown pictures:
/api/countdown/:id.png(server/src/routes/countdown.js), drawn with sharp when an email is opened; it uses the VPS's fonts, so install Poppins there (eg. into/usr/local/share/fonts, thenfc-cache) or it falls back to a plain sans. The social bar's icons are static files inpublic/email/. - Word import: Blog posts → Import from Word turns a .docx into an unpublished post (headings, paragraphs, lists, tables, links); nginx needs a block for
/api/admin/import/docxwith an 11m body limit:docs/importing.md. - Speed: nginx must gzip JS/CSS/JSON/SVG and speak HTTP/2; page HTML is
no-cache; uploads get a-640.webpsmall copy made at upload and at boot:docs/performance.md. - Security headers: the API sends them (Hono
secureHeaders(), plus a CSRF check on/apiwrites); nginx sends HSTS on everything and must passHostandX-Forwarded-Forto the API:docs/security-headers.md. - Request form (
/request): files go to the "Requests" folder of a Google shared drive and new-request emails go out through Gmail, both via a service account (server/src/googleService.js).driveUpload(folder, ...)finds or makes the named folder in the shared drive, so other uses get their own folder. Tools → Media → Files uploads to "Media" and shares each file as anyone-with-the-link (server/src/routes/files.js, migration 048); link fields withfiles: truepick from it ("Choose a file"), and link cards take its first-page preview. Needs a/api/admin/filesnginx block (51m). Off untilGOOGLE_SERVICE_ACCOUNTplusGOOGLE_SHARED_DRIVE(the bare id, not a URL) /GOOGLE_MAIL_FROMare set. Needs its own nginx block. Setup:docs/google-drive-and-mail.md. - Profile accounts (migration 076): admins invite an email (Data → Profile accounts), the person sets a password from the link or signs in with any Google account under that email, claims their People record (an admin approves), then edits it and hides parts at
/account. Public reads of people go through thev_people_publicview, neverpeople. Discord linking is off untilDISCORD_CLIENT_IDandDISCORD_CLIENT_SECRETare set:docs/profile-accounts.md. - Google sign-in for @nextgenerationofunity.org admin accounts: on when
GOOGLE_CLIENT_IDandGOOGLE_CLIENT_SECRETare set on the service. Accounts made by admin-cli get in; with access groups set (Site settings → Access, plusGOOGLE_DIRECTORY_AS), anyone in one gets a Google-only account whose role follows the group, rechecked at sign-in, hourly and by Panel → Re-sync now (server/src/accessGroups.js); superadmins and admin-cli accounts are never changed by groups. Passwords still work. Setup:docs/google-sign-in.md.
Git workflow
- Remote is a self-hosted Forgejo server, not GitHub. Do not use
gh. - Open pull requests with
tea:tea pr create --base main --head <branch> --title "..." --description "..." - Never commit directly to main. Create a branch per change, push it, open a PR.
- Versions are marked with annotated tags (v1.0, v1.3...). Don't create or move tags unless asked.
server/dev.dband other*.dbfiles are local only and never committed.
How to work in this repo
- Read the relevant existing files before writing anything. Follow existing patterns exactly: descriptors, field syntax, extension shape, import conventions.
- Ask questions up front before implementing non-trivial features.
- Prefer targeted edits when surrounding code is stable; full rewrites only when a component is being substantially reworked.
- Fix root causes. No redirect shims or workarounds.
- Keep data logic in the database and presentation logic in code. Make things configurable via constants, not hardcoded in components.
- Name components for what they do, not what they currently filter.
Project layout
- All pages use
PageShell.tsxas the wrapper unless explicitly noted otherwise. - Pages live in
src/pages/; section-level components go insrc/pages/sections/. src/data/holds only hardcoded data shared across multiple section files (e.g.historyDecades.ts, map grid). Everything else comes from SQLite, through hooks insrc/lib/.- Pages are rows of
site_pages(migration 080), edited in Pages → Page management: address, title, intro, Hidden (Not found below viewer) and Disabled (out of the menus, sitemap and search). Every page but the front page is a page of sections (forms and embeds are section types,src/pages/sections/FormSections.tsx), and new ones are made there;PageAtPath.tsx(the*route) draws whatever page is at an address. The pages the code links to (CORE_PAGESinserver/src/admin-schema/sitePages.js: /give, /feedback, /request, /qr, /privacy, /terms) keep their address and can't be deleted. Record routes (/events/:id...) stay inApp.tsx, and their first path segments are reserved. Menu links are Pages → Navigation (site_nav_links,server/src/siteNav.js, read throughsrc/lib/useSiteNav.ts);navConfig.tsonly holds the defaults the app starts from before that loads. api.tsis the shared caching client used by frontend data hooks.docs/updating-data-in-code.md: where content that isn't in the database lives (admin dropdown labels, fixed value lists, nav, banner, decades, map grid) and how to change it. Keep it current when adding a dropdown or code-owned content.- Images: every record image (logos, photos, backgrounds, block images) is an upload, in a folder by use:
/uploads/logos/,/uploads/images/,/uploads/thumbnails/(saved previews),/uploads/captions/(videos' .vtt files); a logo or icon image field setsfolder: "logos"(docs/media-uploads.md, Folders). A bare filename resolves to/uploads/<file>(src/lib/media.ts, andserver/src/pageMeta.jsfor previews). Only the site's own chosen assets, the NGU logos in the nav, footer and admin, are bundled fromsrc/assets/logos/. Logo images hide themselves on load error (onError).
Rules and gotchas
- Role checks must use ladder comparisons, never equality. Roles rank member → viewer → editor → admin → superadmin (member is a profile account: the site and its own profile, never the admin;
/api/adminneeds viewer,requireStaff). Use the minimum-rank helpers fromsrc/lib/roles.ts(canWrite,canDelete,isSuper,isStaff,atLeast). Where a local variable shadows the name, import with an alias, e.g.canWrite as roleCanWrite.role === "admin"silently excludes higher roles and has caused repeated bugs. - Imports need explicit extensions (
.ts,.tsx,.js) everywhere. - Vite resolves
.jsbefore.ts, so a.jsand.tsfile with the same base name will import the wrong one. Give new hooks distinct names. - Don't use
fallback: EMPTYin api.ts hooks. It silently returns empty arrays and hides server errors; let the error state surface. - Colors are tokens, not hex. Admins can override any token (Panel → Site settings → Colors). The defaults are
server/src/themeDefaults.jsplus the same values as CSS insrc/index.css; the build fails if they differ (themeDefaultsCheckinvite.config.ts), and migration 041's CHECK lists the token names. Use the utilities fromsrc/index.css(text-ink,text-body,text-muted,text-link,bg-surface,bg-tint,bg-action,border-brand/20...) so dark mode works; a literal only for something that must look the same in both modes (white on a dark band, a platform's color). Data colors (accents, event and region colors) go throughwithAlpha,accentTextandreadableOninsrc/lib/color.ts, never${color}55. A palette color in a component or CSS file isvar(--pal-<family>-<shade>), not its hex, so the color blind modes reach it. - Icons are Phosphor (
@phosphor-icons/react), weightbold(orfillfor play/star). No hand-drawn<svg>icons and no Unicode glyphs as icons (× › ▶ →). Brand marks are the exception:DoveMark,PlatformIcon, the Google logo, the group map. - Accents come from
src/lib/color.ts:BRAND(the teal, via the button token so the admin palette reaches it) andACCENTS(deep, green, olive), all fromPALETTE(the site's 16-color grid). Not a new hex in a page. - Corners: square. Everything is square except buttons, which use the
btnutility (Poppins Bold, a smallvar(--btn-radius)corner, also for plain CSS), video players (small rounded) and things round by nature (dots, radio marks, the play button). A note in place of content (empty section, "coming soon") uses thenoticeutility (corner brackets), not a dashed border. Cards sit onbg-raisedwith a shadow so they stand off the page. Nothing glows: no blur blobs, no glow shadows. - Sections paint no background.
PageBackdrop(in Layout) draws the page's palette circles behind every public page; a band that needs its own color (the hero, the stats band, the footer) is a deliberate exception. - No em-dashes (U+2014) anywhere: UI text, help text, comments, docs, commit messages. Use a colon, comma or parentheses. An empty table cell shows
-. - Admin editor text: blank select options read
Default: …(what blank means), examples in help text start witheg., and record ids are called "URL ID". Cut-off preview text usespreview()fromsrc/lib/text.ts, which ends it with an ellipsis. Seedocs/updating-data-in-code.md.
Admin CRUD engine
Descriptor-driven: server/src/admin-crud.js and server/src/admin-schema/ (server, one file per entity, registered in admin-schema.js) and src/lib/adminSchema/ (client, one file per entity, registered in adminSchema.ts) generate SQL and form fields from declarative entity configs. Adding an entity should mean adding a descriptor, not new CRUD code.
- Child collections are deleted and reinserted wholesale. Unsafe for entities referenced by foreign keys elsewhere.
reindex: falseprevents cross-entity sort order collisions.check: (db, id) => voidruns after a save has written everything, inside its transaction; throwing anHttpErrorrefuses the save (Site settings uses it for the color contrast check,server/src/theme.js).- The
OMITsentinel distinguishes unsent fields from deliberate clears. admin-schema-sync.jsruns at boot and throws if descriptors don't match livePRAGMA table_info. If boot fails after a schema change, update the descriptor or migration so they agree.admin-cli.jsimportsROLESanddestroyAllSessionsForfromauth.js. Keep it that way to prevent drift.- Drafts (migration 077,
server/src/drafts.js,docs/drafts.md): any existing record can be saved as a draft (one per record), previewed on the real page and published (the ordinary PATCH, which drops the draft). Checking and previewing apply the draft in a transaction that is rolled back;tx()nests as a savepoint for that, so never callBEGINby hand. A new entity with a public page adds its path toPREVIEW_PATHSinsrc/lib/adminSchema.ts.
Migrations
server/src/migrations/066_schema.sqlis the baseline: the whole schema, consolidated on 2026-10-04 from the old 023–066 (generated from the live schema, so the comments are the ones inside each table).066_seed.sqlruns right after it with the least a new database needs (single rows, event scopes, the site pages' sections, the Musicians tag); content is typed in through the admin. Both only run on an empty database; the runner refuses a database between v1 and v65 (bring it to v66 with a release from before the consolidation first). It's the place to read the schema, not to change it: a database that already exists never re-runs it.- Changes go in new sequential files after it:
067_,068_, ... - The runner may drop statements after a
BEGIN...ENDtrigger body. Keep triggers last in a file, and put eachCREATE VIEWbefore any trigger or in its own file. - The runner turns foreign keys off around every migration (it can't be done inside the file's transaction) and runs
PRAGMA foreign_key_checkbefore committing, so a table rebuild needs noPRAGMA foreign_keysof its own. When views or triggers name the table being rebuilt, wrap the drop-and-rename inPRAGMA legacy_alter_table = ON...OFF, then recreate the rebuilt table's own indexes and triggers.
Integrations
- Church Center (ngu.churchcenteronline.com): Planning Center embeds for giving.
graphify
This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.
Rules:
- For codebase questions, first run
graphify query "<question>"when graphify-out/graph.json exists. Usegraphify path "<A>" "<B>"for relationships andgraphify explain "<concept>"for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output. - If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing.
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context.
- After modifying code, run
graphify update .to keep the graph current (AST-only, no API cost).