Compare commits

...

227 commits

Author SHA1 Message Date
13d8489fd4 Merge pull request 'v1.14.2-present: event schedules, venues and map blocks, Present mode and its phone remote' (#33) from event-schedule into main
Reviewed-on: #33
2026-11-21 23:02:04 +00:00
Zaldimmar
48b61e6cc7 Version v1.14.2-present
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 16:57:32 -06:00
Zaldimmar
2d354a35c1 Docs: an nginx /api/admin/ block with a 4m body limit, so big saves don't get a 413
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 16:57:32 -06:00
Aidan Dona
5eebc20c4e Present: a remote, a phone at /remote/<code> drives a presenting screen
The screen shows a code on its setup and with its controls. Anyone with
it can step, pause and jump through the slides, send the screen back to
its setup, or change the setup and play it there. Server-sent events,
held in memory (routes/present.js); X-Accel-Buffering: no, so nginx
needs no block of its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 09:51:27 -06:00
Zaldimmar
3aef3b1c34 Present: dividers left off the slides
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 06:59:58 -06:00
Zaldimmar
b286cbddbf Present: a heading alone as a centered slide; just an events list
- A section left with only its heading and subheadings, and nothing
  after it to title, gets a centered slide of them
- Setup, per events block: A slide per event, so the list slide can
  show alone

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 06:57:38 -06:00
Zaldimmar
b2ef692155 Present: featured events lit on the list slide; schedule row fixes
- An events list slide tints, bars and stars its featured events
- A schedule block's sub-items sit a little in, not under the title
- An entry with no place, person or tags no longer shows a stray 0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 06:48:53 -06:00
Zaldimmar
7d31b3eea8 Present: Copy link for the setup's current choices
- addressFor builds the playing address from the choices, for Play
  and the new Copy link at the bottom of the setup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 06:42:40 -06:00
Zaldimmar
f46deac3cc Image block: a dark theme picture; presented pictures centered
- media_dark (102): shown in place of the image while the site is
  dark, the block's alt text and caption shared
- Present: pictures beside text centered on the slide's height, and a
  section of only pictures centered both ways

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 06:40:40 -06:00
Zaldimmar
a59702b7f3 Present: a section's pictures left or right of its text, fitted
- Setup, per section with pictures and text: Pictures in the text,
  left of it or right of it (`pictures`), in a column beside the rest
- That slide shrinks to fit (Fit), measured again as pictures load

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 06:04:48 -06:00
Zaldimmar
a0eb9d7e49 Image block: a Size (small, medium, large), centered
- image_size (101): blank the column's full width, else up to 20, 32
  or 48rem, centered and never wider than the column

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 05:58:49 -06:00
Zaldimmar
c26e662406 Present: a callout slide without its tint and bar
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 05:49:27 -06:00
Zaldimmar
c46a612226 Present: callout slides, Select all and Deselect all on the setup
- Setup, per callout block: a slide of its own, centered under the
  subheading above it (else the section's heading); Callouts seconds
- Select all and Deselect all over each list of the setup's checkboxes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 05:47:35 -06:00
Zaldimmar
afa95179ef Present: people roles picked on setup, an events list that fits
- Setup, per people block: each one's role or title under their name
  (`titles`)
- An events list slide: presenters under the titles, columns that
  flow, shrunk to fit rather than scrolled (Fit)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 05:32:09 -06:00
Zaldimmar
d58f630a8f Present: events picked on the setup screen, a titles list slide, people centered
- Setup, per events block: which events, and what's shown (list
  slide, picture, type and date, presenter, page content)
- An events block's list slide: titles and presenters as rows, not
  cards
- A slide of only people: title and photos centered both ways

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 05:20:42 -06:00
Zaldimmar
c4bb685bc0 Present: a list's slides picked on the setup screen, not the block
- Setup: Overview slide and A slide per item per list (`lists`), its
  items ticked on and off when either is picked
- The block's two fields and 098's columns go (100)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 05:02:06 -06:00
Zaldimmar
ae06cd2b4f Blocks: Shown on the page, in the presentation, or both
- present_show (099) replaces present_hide: only on the page, or only
  in the presentation, kept off the page and its contents list
- Blocks with the old Leave out ticked become Only on the page

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 04:59:11 -06:00
Zaldimmar
2282bee23c Present: list slides, centered people
- A list block's Overview slide and A slide per item (098): its
  items' text on one slide, and each item with its detail, centered
- Setup ticks a list's overview and items on and off; List overview
  and List items seconds
- A presented people row is centered

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 04:57:08 -06:00
Zaldimmar
584340b0ee Present: the logo as a plain image, no dark mode plate, full size
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 04:40:19 -06:00
Zaldimmar
c35e65be63 Present: the logo in the screen's corner, not inset
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 04:34:30 -06:00
Zaldimmar
b76f2a5707 Present: dark theme settings, a Theme pick, and a content inset
- Event Presentation, dark theme (096): background image and color,
  dim, accent, text color and logo for a dark screen; blank takes the
  light one
- Setup's Theme holds a screen light or dark while it plays (`theme=`)
- Inset top, right, bottom and left (097), percent of the screen, so
  the slides sit inside a frame drawn in the background image; with
  any set the image is stretched to the screen

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 04:14:14 -06:00
Zaldimmar
7e21a0dd40 Present: slide order, presentation settings, blocks drawn for a screen
- Setup's Order list: drag or move any slide; saved in the address
- A heading-only section titles the slides after it, no slide of its own
- Event Presentation settings (095): background image and color, dim,
  frame, accent, text color, logo
- Blocks: Presentation text and Leave out of the presentation; map
  blocks get a slide per section, map only, no details, location slides
- Presented, links are plain text, people a row of round photos and
  names, organizations their logos

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 03:41:06 -06:00
Zaldimmar
a79559d290 Admin preview: a map block's sections made as the API makes them
The preview handed MapBlock the form's sections (location_keys text),
so adding one crashed the page on section.keys. It now builds them as
shape.js does: keys the venue still has, empty ones dropped, the
venue cut to them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 03:45:43 -06:00
Zaldimmar
56a6e11655 Map block: sections of its own, shown one at a time
Migration 094 adds content_block_map_sections: a map block groups its
venue's locations for its page, eg. Main spaces, without changing the
venue. With sections the API cuts the block's venue to the locations
they hold, in their order; the list groups under their names, and
buttons (All, then each section) show one section's marks and rows.
A schedule's place links only when a map on the page shows it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 03:42:50 -06:00
Zaldimmar
06bf033448 Organizations block: its picker lists ministries too
The block picked from the `organizations` options, which leave
ministries out for pickers that link to a page. A card needs no page,
so the block has its own `block_orgs`, every kind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 03:32:01 -06:00
Zaldimmar
bd271ef02d Organizations block: the Partners page's cards, picked one by one or every one of a kind
Migration 093 adds the 'organizations' block type (rebuilding
content_blocks for its CHECK, as 088 did), content_blocks.org_kind and
content_block_items.org_id. OrgListCards takes `nested` for a block:
no page gutter, names a level under the block's heading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 03:23:58 -06:00
Zaldimmar
e9ea75a68d List block: bold text and a plain detail by default, with a Style to keep the old look
Migration 092 adds content_blocks.list_style: blank is bold text and
a detail in the body color, 'plain' the plain text and gray detail
lists had before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 03:20:00 -06:00
Zaldimmar
6a0271efd9 Map block: Google and Apple Maps buttons, a zoomable picture, links land at the map's top
Migration 091 adds google_maps_url and apple_maps_url to
venue_locations, shown as buttons at the right of each location's
row. The picture zooms (1x to 4x) and scrolls in its box. A link to a
location now scrolls to the top of the map block, not the mark.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 03:04:14 -06:00
Zaldimmar
8a79206998 Events block: featured events open in full above the cards, under a heading
Migration 090 adds heading and subheading to content_block_items. An
events block's item ticked Featured shows in full above the cards,
under its heading and subheading when set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 02:57:26 -06:00
Zaldimmar
a7495f09e5 Event page: the photo fills the column, as the blocks do
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 02:48:26 -06:00
Zaldimmar
b8a744cf41 Event page: a contents list, a links heading, full-width blocks; schedule tags in their own row
Migration 089 adds show_contents and links_heading to events (Page
group in the editor). The content blocks fill the column, beside the
contents list when it shows. A schedule's tag tabs sit in a row of
their own under the days, with a note on what they do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 02:44:57 -06:00
Zaldimmar
375c364861 Events block: a card opens the event in full, its own blocks too
An events block's events bring their own page's blocks (one level
deep, so events listing each other stop there), photo and place. A
card opens the event under the cards: photo, type and date, title,
place, person host, its blocks (else its card text) and a link to its
page. Reading mode shows them all in full, and the presentation's
event spotlight shows its blocks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 04:31:34 -06:00
Zaldimmar
df8052c75e Present: the whole event page, in sections at its headings
The presentation (now EventPresent) cuts the event's page into
sections at its Heading blocks: a section's text on one slide, then
its schedules' slides, a map block's map and each location lit up,
and an events block's grid and each event. One Present button on the
event page replaces the schedule's. Setup lists the sections, each
schedule's days and entries under its own; the address keys are now
skip and hide, numbered by schedule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 03:41:21 -06:00
Zaldimmar
818d648e91 Venues, map blocks and event blocks; schedule entries link to them
Data → Venues: a map picture with its locations marked as pins or
boxes (088). A Map block draws a venue with its locations listed;
a schedule names a venue and its entries pick a location, linking to
the map on the page with it lit up. Entries and sub-items can name
an event (a workshop) and take what they leave blank from it, and an
Events block shows event cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 03:21:18 -06:00
Zaldimmar
3d087da005 Present: scroll at seconds a screenful, the slide lengthened to fit
A long slide waits half its seconds, scrolls one screenful per Scroll seconds (setup, screen= in the address, default 8), then waits the other half. Pausing pauses the scroll.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 03:41:47 -06:00
Zaldimmar
d17e2596ba Present: a slide with more than the screen holds scrolls through it
The day overview, tag and block lists and the spotlight text hold, scroll to the end over the slide's seconds, then hold. The spotlight description is no longer cut at six lines. Reduced motion keeps them at the top.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 03:21:44 -06:00
Zaldimmar
b30f5f11fe Present: the tag filter's address key no longer collides with the tag slides' seconds
Both used 'tag', so on Play the seconds were read as the filter and every entry was cut.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 03:12:03 -06:00
Zaldimmar
edf0e0a177 Version: restore version.ts's characters, which the bump re-encoded
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 02:07:37 -06:00
Zaldimmar
d890efca2b Version v1.14.1-schedule
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 02:07:14 -06:00
Zaldimmar
71d58318b6 Schedule tags: a block's own tags, tag tabs, chips, a tag filter and tag slides
A schedule block gets its own tags (content_block_tags, migration 087):
a name, a color and whether it's a tab. Entries and sub-items pick them
from a checklist. Each tag is a tab after the days, gathering what it's
on from every day under the day's name; a tagged entry comes whole and
an untagged block brings only its tagged sub-items. Rows show their tags
as chips. The presentation can show only one tag's entries and adds a
slide per tag after the days.

Entries name a tag by a key the admin makes when the tag is added, so a
rename keeps them, since the block's rows are rewritten on every save.
For that the admin engine gets a function blank (fresh values for every
new row and copy, with a `seeded` column that doesn't count as input),
`lends` (a row's options for the collections nested in it) and a
checklist widget.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 02:04:06 -06:00
Zaldimmar
7885d10249 Schedule: entry types, picked times, striped rows, blocks in the presentation
Entries get a type (normal, block, break, heading) and a Featured tick.
Times are picked (start, optional end) and shown as 7:00pm or 9:00 to
10:30am; the typed time stays as the override, so existing entries look
the same. A block holds sub-items (content_block_subitems, migration 086),
each with every entry field. Rows alternate a faint tint. The presentation
gets a Blocks slide (its own seconds) before each sub-item's spotlight,
and sub-items get their own checkboxes on the setup page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 23:15:53 -06:00
274ffc26e0 Merge pull request 'v1.14.0-profiles: profile accounts, drafts, page management, Planning Center' (#32) from page-management into main 2026-10-28 07:00:09 +00:00
Zaldimmar
5ebc771272 Hero event card: photo always on top, words left and buttons stacked right from sm up
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 13:59:35 -05:00
Zaldimmar
8b741676f3 Page management: list pages with their id, so the admin home's page cards link to them
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 18:14:41 -05:00
Aidan Dona
54fc319d33 TODO: page management is part of v1.14.0-profiles
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 17:49:31 -05:00
Aidan Dona
e8aab4d7ec Planning Center: compare a People list with the site's people and apply what an admin picks
Migration 085 adds people.pco_id and Site settings' list. Data ->
Planning Center fetches the list, suggests matches (linked, same email,
same name), shows each field that would change (Planning Center wins),
and applies the chosen links, updates and new unpublished people in one
transaction. Needs PCO_APP_ID and PCO_SECRET.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:46:29 -05:00
Aidan Dona
a10ff6d75f Rotating words: {Next|Now} in titles and text cycles through its choices
Migration 084: site defaults for the motion (slide, flip, fade, type,
mirror), direction and seconds per word in Site settings, and a hero's
and a block's own. The hero's headline, section and band titles,
headings, paragraphs, callouts and quotes rotate; menus, tab titles,
search text and emails show the first word; less motion shows it still.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:43:59 -05:00
Aidan Dona
ab8dcdd608 Page management: no Delete button on the core pages the server won't delete
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:37:35 -05:00
Aidan Dona
f1a0b06ac2 Page management, step 3: section types with their own settings; the front page as sections
Migration 083 gives the section types that need more than blocks their
own tables (hero, slides, countdown, stats, paths, featured cards, the
Community blog's slots, pinned posts and feeds) and turns the front page
into Home's sections: the hero, then its bands in order. Any section can
be hidden. The Front page editor, its tables and the Community page's
are gone; /api/front-page and /api/community-blog fold into the page's
sections (sectionData.js). The admin engine reads and writes a child
collection's own side tables and gated nested collections.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:34:56 -05:00
Aidan Dona
f33c0008fe Page management, step 2: the core pages as sections
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>
2026-10-16 23:24:34 -05:00
Aidan Dona
1342691f49 Page management, step 1: every page in a registry, new pages, hidden and disabled
Migration 080 makes site_pages the list of every page: address, title,
intro, Hidden, Disabled (out of menus, sitemap and search) and card order.
site.json's pages and Navigation's page list move into it. Pages ->
Page management (one editor in place of six) makes new pages of sections
at any free address; the admin home opens Pages with a banner and a card
per page. A catch-all route draws whatever page is at an address; the
fixed pages take their words from the registry and can't be deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 23:19:54 -05:00
Aidan Dona
56acedf926 Featured event card beside the hero text; Word import: tabs, quotes, callouts, dividers, videos, buttons
From lg up the featured event's photo sits beside its words, so the card
is about as tall as the hero text. Word import turns a 'Tab:' line into a
tab, the Quote and Intense Quote styles into quotes and callouts, '---'
into a divider, a lone video link into a video and 'Button: label' into
a button; Blog posts shows the whole mapping beside Import from Word.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 20:43:25 -05:00
Aidan Dona
3b034eb00e v1.14.0-profiles: bump SITE_VERSION
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 20:20:04 -05:00
Aidan Dona
31afa889d6 Page features: directory and blog post tabs, image converter, version names
- Featured event badge: above the event's card from lg up, left out on phones
- Version names from the tag (The Region Cards Update) in the site and admin footers
- Tools -> Image converter (JPG, PNG, WebP in the browser) and Download as in Media
- People directory sections take several tags, a tab each (migration 078)
- Tab blocks split a blog post into tabs; contents follow the open tab (migration 079)
- The side nav sun fades out as the page scrolls into the footer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 19:37:07 -05:00
Aidan Dona
a6c66d4607 Drafts of every record, previewed on the real page
Migration 077 keeps one draft per record of any entity. Saving a draft
checks it by applying it in a transaction that is rolled back; Preview
opens the record's page in a tab that sends X-Draft-Preview, and the
server answers those reads from a second connection holding the applied
draft, then rolls back, so nobody else sees it. Publish is the ordinary
save, which drops the draft. tx() now nests as a savepoint.

Also commits TODO.md: the answered questions, and parts 1 to 3 moved to
Done.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 18:21:53 -05:00
Aidan Dona
e4c7e165d1 Profile accounts: invites, any-Google sign-in, claiming People, visibility, Discord
Migration 076 adds a member role below viewer (the site and its own
profile, never the admin: /api/admin now needs viewer), invites, person
claims, a Discord link on accounts and people.hide_* switches. Public reads
of people go through v_people_public, which nulls hidden fields, and the
views that read people are rebuilt over it.

Admins invite an email from Data -> Profile accounts (link shown once,
emailed on request). The invitee sets a password or signs in with any
Google account under that email, asks to claim their People record, and
once approved edits it and chooses what shows at /account.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 18:14:30 -05:00
Aidan Dona
0cc2a3f721 Navigation in the admin: header and footer links, page titles, hidden pages, Shop
Pages -> Navigation (migration 075) edits the header's pages and buttons
and the footer's links; navConfig.ts is now only the defaults. Page titles
and intros move there from Site settings. A hidden page answers Not found
below viewer (server and app) and is out of the menus and sitemap; signed
in, it shows with a bar. Adds a /shop page of sections, hidden, with its
header button.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 18:01:02 -05:00
b49497cc59 Merge pull request 'Cleanup: TODO.md, Claude settings and skills' (#31) from cleanup into main 2026-10-16 20:32:57 +01:00
Zaldimmar
5aad166054 TODO: the notes.txt items, each with questions to answer before building
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 14:29:40 -05:00
Zaldimmar
2b41b336f9 Skills: track design-taste-frontend once, in .agents, and add skills-lock.json
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 14:18:19 -05:00
Zaldimmar
bdec78010d Add TODO.md and the project's Claude settings and skills (graphify, design-taste-frontend)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 14:17:46 -05:00
2e6c8b45e6 Merge pull request 'Region featured cards, featured grid, video stills, media naming (v1.13.2-region-cards)' (#30) from region-featured-cards into main
Reviewed-on: #30
2026-10-16 20:13:16 +01:00
Zaldimmar
80b3036498 v1.13.2-region-cards: bump SITE_VERSION
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 14:10:35 -05:00
Aidan Dona
687ba898f6 Media: name files when saving, and rename them in the library (file and references)
Every upload and save (Upload, Frame at, Video thumbnails, a clip's
Save to library) has a prefilled Name box; the name is also the
readable part of the file's name, plus a short random ending. Fetch
preview names its picture after the page. Rename on the Media page
changes both, moving the file and its small copy and pointing every
record that names it at the new path in one transaction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 15:47:30 -05:00
Aidan Dona
14a22ca44d Video stills: Frame at on video blocks and the front page's video, and Tools > Video thumbnails (migration 074)
Frame at (a still from a YouTube or Facebook video at a typed time)
now also fills a video block's still and the front page's new Video
still, which the hero shows before its featured video plays. Tools >
Video thumbnails takes one from any link, to download or copy into a
field. All go through the existing POST /api/admin/video-frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 12:10:44 -05:00
Aidan Dona
31d9f78120 Front page: set the featured cards' grid by hand, columns and a size per card (migration 073)
Front page editor: Featured Content > Columns (2, 3 or 4 across on a
wide screen) and a Size on each card (normal, wide, tall, large).
Blank keeps today's layout: 3 across, the first of three or more
large. Regions and the Community blog stay automatic.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 17:24:10 -05:00
Aidan Dona
910aef78b5 Region list: a closed row previews its featured cards, faded, with a Show featured button
The preview is the top of the cards fading out (a mask, so it works
over the backdrop in both modes); it's inert and hidden from screen
readers, and the button opens the row, moving focus to its toggle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 17:03:53 -05:00
Aidan Dona
2977168af5 Regions: featured cards in the region list and on the region's page (migration 072)
A region owns featured cards like the front page does, set in its
editor (shown when Kind is region). They show in its row of the
region list when opened, and in a Featured section on its page.
featured_cards takes an 'organization' owner kind; the table is
rebuilt, and a region's cards go when it does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 16:56:14 -05:00
1edc82fcf7 Merge pull request 'Feature updates: photo framing, group pages, schedule images, content block placement' (#29) from feature-updates into main 2026-10-07 22:52:58 +01:00
Zaldimmar
07be48d770 Uploads: frame a photo before it goes (crop, zoom, position)
A photo field with a shape (crop: square for people, 16:9 for event
photos, covers and hero photos, the photo's own for block images and
schedule graphics) opens Frame the photo when a JPEG, PNG or WebP is
uploaded: drag or arrow keys to place it, a zoom slider, and a shape
menu. The framed part is drawn on a canvas and uploaded in place of
the original; Upload as is skips it. Logos, SVGs and GIFs go as they
are. No new dependency and nothing stored beside the picture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 16:21:26 -05:00
Zaldimmar
034ad95b8a Organization cards: logo first, the name under it as subtext
Most partners' logos carry their full name, so the logo leads, large
and centered, with the name as a small line under it (still the
card's heading). With no logo, its initials stand in. Cards sit raised
with a shadow and an accent top edge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 15:51:47 -05:00
Zaldimmar
8d6bb8c2b8 Content blocks: Shown in the page, the card only, or both (migration 071)
A card block also showed on the record's page (the pages printed the
card's paragraphs above the body), which the editor didn't say. Shown
in now offers The page, The card only, and The card and the page.
Every existing card block becomes both, so nothing on the site moves;
the pages no longer print card paragraphs, and a both block comes
with the page's blocks, in its place in the list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 05:27:33 -05:00
Zaldimmar
b55b088e16 Group pages: framed facts, tags for organizations and events, every website and email (migration 070)
- Email buttons went to the link's label, not its URL (splitLinks took
  the label); they use the URL now, with or without mailto:.
- Every website and email row is listed, each with its own label,
  instead of only the first.
- The facts at the top of an organization page sit in a framed card:
  City, Part of <name> Region, Ministry, Meets, Since, and its tags.
- Tags (070): Data -> Tags (Online, In-Person to start) replace the
  Online checkbox on organizations and events. Ticked records get the
  Online tag; v_events reads the "online" tag as is_online, so the
  calendar filter and place lines are unchanged. Tags show on the
  record's page and on group entries in the Community map list and
  grid. The map no longer keeps online groups off their state's tile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 04:58:56 -05:00
Zaldimmar
07c15ce96d Schedule presentation and map images for schedule entries (migration 069)
A schedule block on an event page has a Present button, opening
/events/<id>/present in a new tab: a setup screen (days, entries,
seconds for each kind of slide) and then an endless full screen
slideshow of day overviews, entry spotlights with their person,
graphics and map images, its settings kept in the address so a
signage screen can bookmark it.

Schedule entries take a Map image (069), shown in the fold-out in place
of the Google map and as a slide in the presentation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 04:47:25 -05:00
Zaldimmar
96b96c3e6c Group map: state hover, state subheadings, entry cards, scroll on click only
Hovering a tile outlines that state in ink while its region stays lit.
The list groups each region's groups under their state's subheading,
each entry a raised card, and leaves out the region's list of states
(its map note stays). The list no longer follows hover; clicking a
state jumps to its subheading (or its region when it has no groups),
and clicking a legend region to that region.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 04:31:19 -05:00
Zaldimmar
915a7bb570 Side nav: size the pill as the pill it is, not an ellipse
rounded-full draws straight sides with round ends, but its height was
worked out for an ellipse, so a narrow window made it about three times
the list's height, running down over the content.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 04:28:45 -05:00
Zaldimmar
de6d70a0d0 Event cards: clip sideways only, so the past events button isn't cut off on hover
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 04:14:48 -05:00
970730de20 Merge pull request 'v1.13.1-data: links/redirects, captions, partner picks, Plausible reports, migration baseline' (#28) from data into main 2026-10-06 10:10:56 +01:00
Zaldimmar
e996462231 v1.13.1-data: bump SITE_VERSION; drop comments from index.html
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 04:10:31 -05:00
Zaldimmar
5de3cae599 Redirects: still redirect when site.json can't be read
Only the Plausible report is skipped, with a warning, instead of the click failing with a 500.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 02:03:14 -05:00
Zaldimmar
0eea9ba13b Links/redirects: Copy link on a saved redirect
A manifest's idLink gives a saved record's own address, shown on its URL ID card with a Copy link button; redirects use it for the /go/ link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 00:48:33 -05:00
Zaldimmar
e060153798 Newsletter: Pick a redirect on every link field
Link fields with redirects: true get a list of Data > Links/redirects that fills in the short link's full address; the newsletter turns it on for its blocks' links and their items' links.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 00:39:52 -05:00
Zaldimmar
6289e7203f Links/redirects: /go/ short links with click counts, Plausible and UTM tags (migration 068)
Data > Links/redirects (editors and up) makes short links on our
domain. GET /go/<id> counts the click, reports it to Plausible as a
pageview of /go/<id> (the visitor's browser and address, no key
needed), and redirects (302, no-store) with the link's UTM tags added
to the destination. Unknown ids fall through to the not-found page.
The editor can show a fixed lead-in in the URL ID box (idPrefix).
Vite proxies /go in dev. docs/redirects.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 00:37:26 -05:00
Zaldimmar
3fafd7f92c Docs: newsletter colors are pickers now
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 23:29:01 -05:00
Zaldimmar
f52a74a383 Newsletter: title color, and color pickers instead of palette dropdowns
Every part color (band, underline, card bar, line, divider, and now the title) is any hex color from a picker; blank is the default, typing none still means no color. Saved drafts keep their colors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 23:28:52 -05:00
Zaldimmar
24450fba6c Newsletter: Save as a new draft beside Save draft when a draft is open
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 23:18:57 -05:00
Zaldimmar
ce6162d797 History decades: placeholder titles for 1970s to 2010s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 23:07:31 -05:00
Zaldimmar
77ce5709ef Region pages: drop the raw domestic/international scope from the facts line
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 22:50:44 -05:00
Zaldimmar
fd7e1b6fc1 Organization cards: list partners, ministries or a hand-picked set (migration 067)
The Partners section's preset gets "Cards: list" (partners by default,
ministries, or both) and an optional hand-picked list
(page_section_orgs, partners or ministries only, enforced by trigger)
that replaces it in its own order. /organizations takes kind=ministry
and ids=; the plain list still leaves ministries out. Ministry cards
link to their website only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 22:40:24 -05:00
Zaldimmar
635dd21083 Consolidate migrations 023 to 066 into one baseline plus a minimal seed
066_schema.sql is generated from the live v66 schema (checked identical
to the old migrations' result: every object, every table's columns);
066_seed.sql holds only what pages need: the single rows, event scopes,
home sections, site pages and their sections, the Musicians tag. Sample
content (hero words, paths, stats, the Organization address) is no
longer seeded. Both share version 66, so a database at v66 skips them;
one below v66 is refused and has to be brought up by 33be618 first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 22:01:55 -05:00
Zaldimmar
33be618331 Captions for uploaded videos (migration 066)
Video blocks get a Captions field and the hero a Video captions field,
each a WebVTT upload drawn as <track kind="captions" default> on a
video file. The media library takes .vtt (sniffed by its WEBVTT
header, kept as is, always in /uploads/captions/) with its own tab.
Newsletter parts leave the field out. nginx needs text/vtt in
mime.types: docs/media-uploads.md, step 5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 21:55:05 -05:00
Zaldimmar
aaab1a945c Docs: setting up the Plausible reports to Discord
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 21:46:32 -05:00
Zaldimmar
636388730f Plausible analytics reports to Discord (migration 065)
Daily (yesterday) and weekly (Mondays, last 7 days vs the 7 before)
summaries: visitors, pageviews, bounce rate, visit length, top pages
and sources. Each has its own switch in Site settings > Reports; off
until PLAUSIBLE_API_KEY and DISCORD_WEBHOOK_URL are set. Sent at 8:00
REPORT_TZ (default America/Chicago); analytics_reports keeps one a day.
node src/analyticsReport.js daily|weekly sends one by hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 21:44:25 -05:00
Zaldimmar
b8012c75e9 Video frame stills for featured cards; newsletter Pick from fix
- Image fields take frameFrom/frameWhen: "Frame at" saves a still from
  the row's YouTube or Facebook link to /uploads/thumbnails/
  (POST /api/admin/video-frame, grabFrame in clips.js). Used on video
  featured cards.
- clock/parseClock moved to src/lib/clock.ts, shared with Video clips.
- Newsletter: new drafts no longer store source 'events' (the Pick from
  select's blank choice), which showed as "events no longer exists";
  older drafts load it as blank.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 21:35:08 -05:00
3b45944094 Merge pull request 'People directories, ministries, organization contacts (v1.13.0-data)' (#27) from data into main 2026-10-04 08:04:09 +01:00
Zaldimmar
f8f1c42b2e Version v1.13.0-data
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 02:03:50 -05:00
Zaldimmar
0ed7315156 People directories, ministries, organization contacts (migrations 062 to 064)
- People tags (062): Data → People tags (Musicians seeded); a person's
  Directories repeater tags them and their Specialty line shows on
  their tile. A People directory section preset shows a tag's first
  12 and links to its full page, /directory/<tag>, with page meta and
  a sitemap entry. Tiles' details panels show a person's links.
- Ministries (063): a new organization kind. A group picks its
  ministry and its page says "Ministry: <name>", linked to the
  ministry's website. Ministries have no public page, list, sitemap
  or timeline entry, and aren't offered where a record links to its
  organization. organizations is rebuilt for the kind CHECK.
- Organization contacts (064): Data → Contact types; a private
  Contacts repeater on each organization (editors and up, readRole on
  a child collection). Tools → Newsletter → Recipients filters them
  by type, kind, region and published and downloads a Mailchimp CSV.
- A trigger refusing a save with a sentence is shown as that message.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 22:57:34 -05:00
07e56bfd20 Merge pull request 'Accessibility: reading mode for every page, full color blind palettes (v1.12.1-accessibility)' (#26) from accessibility into main 2026-10-04 04:30:54 +01:00
Zaldimmar
27e5fbd690 Reading mode: every page and section reads as text
The reader (ReaderView.tsx) now reads an icon-only link's label, puts
a card's link on its first line or picture when it has no heading,
gives each item of a row of facts or links its own line, keeps line
breaks, skips what CSS hides, turns a form into one line saying it
can't be used there, shows empty table cells as "-", keeps section and
heading ids so #links land, and opens file links as files.

What it can't read draws its own text version (useReadingMode()):
the hero, pathfinder, front page history, event lists (every event,
past ones too), org lists and groups map (every region and group,
linked), history timeline (every year open), schedules (every day,
fold-outs included), people tiles (everyone, with details) and videos.

Also: org names are linked headings, heading levels fixed where cards
repeated their section's, Team pages lose the doubled "Members",
Giving links the treasurer's email and names Church Center.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 17:12:27 -05:00
Zaldimmar
c79910ef8d Reading mode: text versions of the front page's bands
- Stats: one line per number, no longer stuck at 0 (the count waited
  for the band to scroll into view, which the hidden page never
  does); reduced motion shows the numbers at once too.
- Calendar: the next six weeks from today as a list (date, linked
  title, time, type, place), wherever a calendar is drawn.
- Featured cards: a linked heading and its words each; a video card
  links to its video.
- Countdown: left out, the retreats band shows the same event.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 16:54:55 -05:00
Zaldimmar
502a294940 Reading mode spacing, phone map width, no fixed back links
- Reading mode: parts the page draws on their own lines get a space
  between them, so words no longer run together; the column is 60rem
  (was 42rem) and headings are bold in the display face.
- Local groups map scales to its column on a phone instead of holding
  34rem and scrolling sideways.
- Group, region, partner and team pages drop their fixed back link
  (records are reached from many pages); orgListHref is gone.
  Not-found pages keep theirs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 16:46:41 -05:00
Zaldimmar
de17da7dc8 Accessibility: reader view and full palette swaps; version v1.12.1-accessibility
- Reading mode is now a reader view (ReaderView.tsx): the page renders
  hidden and its headings, paragraphs, links and described pictures
  are written out in one column, with no header, backdrop or footer.
- Color blind modes swap all three color families (teal, green,
  amber); palette hexes in components and CSS are now
  var(--pal-<family>-<shade>) so the modes reach them.
- CLAUDE.md and docs/updating-data-in-code.md describe both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 16:10:57 -05:00
f4868f19fc Merge pull request 'Accessibility, event photo and analytics (v1.12.0-accessibility)' (#25) from accessibility into main 2026-10-03 09:03:19 +01:00
Zaldimmar
420a8058b4 Plausible analytics from the API; version v1.12.0-accessibility
The API adds Plausible's script to every page it serves, counting
under the hostname of site.json's url, so each deployment reports as
itself (nginx proxies /pa/ to the self-hosted Plausible). One script,
no npm tracker: it follows the app's page changes on its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 03:03:07 -05:00
Zaldimmar
e324422f32 Events: a 16:9 event photo apart from the card background
- New Event photo and Photo description (migration 061), shown whole
  at the top of the event's page, as the front page's featured event,
  on featured cards, in newsletter picks and as the share preview.
- The front page's featured event box is 16:9 (was 16:7).
- Card background is only the faded background of the event's card.
- Each event's photo starts as its card background, so nothing
  changes on screen until it's replaced.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 16:03:54 -05:00
Zaldimmar
b816203c0c Accessibility: reading and color blind modes, audit fixes, calendar window
- Accessibility panel: the switch knob stays in its track; the panel
  follows its button in the Tab order and opens on its first switch.
- Reading mode is the page as plain text: one column, no colors,
  pictures, cards or motion; descriptions stay in place.
- Color blind mode (protanopia, deuteranopia, tritanopia, monochrome):
  palette swaps chosen by simulation, applied to code, data and CSS
  colors on public pages only. The newsletter uses the stored palette.
- Audit fixes: focus not hidden by the header, focus on page change
  and in-page jumps, focus return for the menu, day list and people
  details, labelled admin fields and dialogs, keyboard map tiles,
  scrollable tables, and more.
- Calendar asks /events for its six weeks only (?from=&to=); carousels
  take their 12 most recent past events (?past=12).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 14:33:09 -05:00
d067c02d33 Merge pull request 'Newsletter: every part editable and movable (v1.11.2-newsletter)' (#24) from newsletter-layout into main
Reviewed-on: #24
2026-10-02 19:50:03 +01:00
Zaldimmar
c81712ef32 Newsletter: a handle between the parts and the preview sets their widths
Drag it, or focus it and use the arrow keys, Home and End; 320px
(a phone's view of the email) up to all but 360px of the parts list.
Remembered in the browser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 01:07:13 -05:00
Zaldimmar
00170ca912 Newsletter: social bar and event countdown parts, full-width builder
- Social bar: a colored band of the site's platform icons, linked;
  no links added shows the footer's (src/data/socialLinks.ts, shared)
- Icons are white and ink PNGs in public/email/, made from
  PlatformIcon.tsx by scripts/email-icons.mjs (no SVG in Gmail/Outlook)
- Event countdown: a picture drawn by /api/countdown/<id>.png when the
  email is opened (days, hours, minutes to local midnight in
  America/Chicago; then happening now; then over), with a fixed line
  under it as of copying
- The builder takes the whole window (useWideAdminPage('full'))

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 00:43:28 -05:00
685e0b2aac Merge pull request 'Third audit, UI half; side nav and request buttons (v1.11.1-audit)' (#23) from audit-ui into main
Reviewed-on: #23
2026-10-02 01:41:42 +01:00
0373f7bde6 Merge pull request 'Third audit: security and server-side scalability (v1.11.0-audit)' (#22) from audit-3 into main
Reviewed-on: #22
2026-10-02 01:41:35 +01:00
Zaldimmar
a943ecd3a3 Version v1.11.2-newsletter
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 19:41:23 -05:00
Zaldimmar
3194fdbb7d Newsletter: every part editable and movable
A draft is one ordered list of parts (migration 060, newsletters.layout
as JSON), edited with the content block editor so any part can be
moved, copied or removed, each aligned left or center:
- header: words, a PNG/JPEG logo, band color or none
- title
- any email block; dividers take color, thickness and spacing
- picked items: events, posts or front page cards picked in order,
  with the heading, its underline, the card bar and the button label
- footer: its lines and the line above

Colors come from the palette or none. 057's fixed fields and blocks
are dropped; that migration never reached a live database.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 19:37:26 -05:00
Zaldimmar
222c9e69a2 Third audit, UI half; side nav on top; request button colors
- Event cards: lazy -640 photo, only nearby slides drawn, a counter
  past 12 events, past grid paged with Show more
- Community map: search over list and grid, 12 per region then Show
  all, list no longer redrawn on hover
- People tiles: one clip check for the list, Show all past 30
- Person pages: 6 events and posts then Show all; excerpts load only
  the first paragraph
- Admin: filter box on long pickers and the QR select, options sent
  per form, Media thumbnails from the small copy, debounced searches
  that drop stale answers
- Pages show their last data while refreshing after the cache TTL
- Side nav stacks above page content (the carousel arrows)
- No event request button on National Retreats; request buttons take
  their section's accent
- Version v1.11.1-audit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 19:09:21 -05:00
Zaldimmar
11a4555683 Version v1.11.0-audit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 18:45:46 -05:00
Zaldimmar
f99010252f Third audit: security fixes and server-side scalability
Security:
- docx unzip reads each part once (a repeated entry was a zip bomb)
- request files must be named for their type (no PDF named .html)
- team roster hidden when its organization is unpublished
- /people?ids= hides draft organizations, takes 200 ids
- v_events takes the first published host and reads event_hosts
  directly (migration 059, plus an index on person_awards.event_id)
- group accounts refused while access groups are off; group sync
  can't undo a superadmin's disable
- 64 KB body limit on login, feedback and csp-report
- Drive pick-up races no longer 500; random upload boundary

Scalability:
- /events filters by scope, host, status and type on the server;
  Home no longer prefetches every event
- /organizations leaves out bodies and leadership; the map's group
  panel fetches its own
- admin lists page with Show more and a real count
- content request record search and the newsletter's post list
  ask the server

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 18:29:26 -05:00
0bb4b8685f Merge page-fixes (v1.10.7 to v1.10.10) 2026-10-01 10:53:40 +01:00
Zaldimmar
902b4bce12 Version v1.10.10
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:53:15 -05:00
Zaldimmar
b2bf24dafb Side nav circle covers a 10-section list: ellipses where a circle can't, clear of the section edge
Stuck, the sun stays centered on the header's bottom left (no curving
back at the top) and becomes a quarter ellipse as tall as the list
needs. At rest it keeps 16px from the section's edge, taking the
least-tall ellipse that covers a tall list. The side nav shows from
2xl (1536px): narrower, a list of two-line titles is as wide as its
column and nothing inside it can cover it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:48:17 -05:00
Zaldimmar
4a937454a8 Side nav circle: a slight drop shadow
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:36:17 -05:00
Zaldimmar
5e77da9a66 Corner sun moves to take in the whole list when the window holds it small
Held by the column's width, the stuck circle's center moves down the
screen's edge until the list's corners are inside it, then off the
screen to the left (growing as much, so its right edge stays put).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:35:09 -05:00
Zaldimmar
c335774db5 Side nav circle becomes a quarter-circle sun in the corner once the nav sticks
Stuck, it centers on the header's bottom left and grows to reach past
the list's far corner (never wider than the nav column), easing
between that and its starting place on the list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:22:46 -05:00
Zaldimmar
e68a9be9bb Side nav sticks just under the header, its circle rising behind it like a corner sun
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:18:57 -05:00
Zaldimmar
f7b9af7101 Side nav starts level with the first section's title, still sticking just under the header
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:09:51 -05:00
Zaldimmar
7f45006253 Side nav entries take their section's color; the circle stays on the "On this page" heading
Hovered and lit entries use their section's accent (as heading text),
the editors' nav keeping the link teal. The circle's leftward shift
stops at the heading's center, so short titles no longer pull it off
the heading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:03:32 -05:00
Zaldimmar
37c555a7b8 Side nav circle takes the color of the section being read
Green and amber sections give it their palette's lightest shade, teal
and deep teal the teal one (the darkest in dark mode), the shades the
nav's text reads on, easing between them as the reader scrolls.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 03:56:33 -05:00
Zaldimmar
1db18a8f91 Side nav and its circle in front of the section lines, the circle starting just below the first
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 03:54:39 -05:00
Zaldimmar
a5c4e365cd Side nav circle shows above the first divider, sits further left, and slides left rather than being cut at the content
The nav column clipped on every side, cutting the circle off above
the first section line; it clips sideways only now. The circle keeps
its right edge inside the column, so a narrower window moves it off
the screen's left edge instead of cutting it at the content.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 03:49:41 -05:00
Zaldimmar
ac794d5ff1 Version v1.10.9
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 03:42:02 -05:00
Zaldimmar
857506abb7 Side nav circle: its own sticky layer behind the section lines, clipped at the nav column
The circle centers on the list's measured box, so it stays on the nav
at any width, and the column clips it (overflow: clip, which keeps the
sticky layers sticking) so it never covers content.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 03:41:06 -05:00
Zaldimmar
c0ae48b064 Version v1.10.8
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 03:37:06 -05:00
Zaldimmar
dc003a5487 Header dropdowns close after a click; a tint circle behind the side nav
The dropdowns opened on any focus inside, and a click leaves focus on
the link, so they stayed open after the pointer left; now only
keyboard focus (:focus-visible) opens them besides hover.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 03:36:20 -05:00
Zaldimmar
3308b5f1b5 Version v1.10.7
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 03:29:37 -05:00
Zaldimmar
f65664217e Details & Contact as blocks, not a preset; the side nav sits in the margin instead of shifting the sections
Migration 058 turns the organization_details preset into the
section's own blocks and drops it from page_sections' CHECK. The side
nav is placed in the left margin beside the 72rem content, from 88rem
screens up, so sections stay where they'd be without it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 03:28:03 -05:00
3e4a725c99 Merge page-updates (v1.10.3 to v1.10.6) 2026-10-01 09:23:30 +01:00
Zaldimmar
af58e8fab5 Version v1.10.6
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 01:21:59 -05:00
Zaldimmar
e8ac242e6d Newsletter drafts with content blocks, a footer and Post as blog post; Home has no header dropdown
Tools → Newsletter saves drafts (migration 057: newsletters, with
content blocks owned 'newsletter'), adds blocks written for the issue
and an editable footer (no unsubscribe link: Mailchimp adds one), and
turns a draft into an unpublished blog post. The admin engine binds
child owner ids as text, so an auto-numbered record's blocks are
owned by '1', not '1.0'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 00:21:32 -05:00
Zaldimmar
9daf7b1a4f Page editors: Retreats, Community, Resources, Organization and History built from sections
Each page is now a list of sections edited in Admin → Pages: a title
(30 characters at most, for the side nav), URL ID, blurb and accent,
its own content blocks, and an optional preset (Community blog, groups
map, region list, partner cards, events, timeline, NGU's details).
Migration 056 seeds every page as the code drew it and moves the
Organization editor's blocks and volunteering into its sections. The
Community blog's settings move into the Community editor. The header,
footer and side nav read each page's sections from the API.

The admin engine reads and writes nested collections to any depth.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 00:15:30 -05:00
Zaldimmar
4a1d6fd6e9 Footer site map full width; side nav fits 30-character titles over full-width dividers; Timeline under Data
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 00:04:29 -05:00
Zaldimmar
45b422641a Version v1.10.5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:39:24 -05:00
Zaldimmar
ed0f12022f Navigation: section dropdowns, a side nav, Home's sections from the front page
- The header's second strip is gone: each top link drops down its
  page's sections on hover or keyboard focus.
- Retreats, Community, Resources, Organization and History get the
  admin editors' "On this page" column (SectionNav), sticky at the
  left from lg up, with the section being read lit.
- Home's sections in the dropdown, mobile menu, footer site map, the
  feedback form and the QR maker are the bands the front page is
  showing, in its order and under its headings (navSections.ts,
  frontPageBands.ts, which Home.tsx now draws from too).
- Resources comes before Organization in the nav and footer.
- The Organization page draws from its own editor's content.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:37:36 -05:00
Zaldimmar
43797f38bc Cleanup of old-data fixes; an editor for the Organization page
Nothing before these changes was ever public, so the fixes kept for
older data go: the /leadership redirect (MOVED in routes/pages.js),
index.html's move of "ngu-" browser keys to "site-", the boot-time
sorting of images from before folders (media.js), and emoji path
icons (a path with no named icon shows a dot; migration 055 turns
the baseline's seeded emoji into their names).

Pages → Organization page (migration 055): a singleton with the
Mission, Vision & Values blocks, the Leadership blocks (a People
block per team, in order) with a heading and blurb, and Volunteering
(title, blurb, links). content_blocks gains the two owner kinds;
GET /organization-page serves it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:37:35 -05:00
Zaldimmar
1da79c128b Version v1.10.4
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:18:52 -05:00
Zaldimmar
8d319bcaaa Mobile: community map, cards, schedule, stats, banner, tap targets
- The community map keeps a readable size on a phone and scrolls
  sideways in its own box; group cards wrap their controls under the
  name, with smaller logos and 40px buttons; group details likewise.
- Org list cards, the stats numbers and the front page timeline rail
  cards size down on phones (the stats band unchanged from sm up).
- Schedule entries put the time on its own line on a phone; 40px
  fold-out toggles.
- The banner gives its text the room on a phone, with a 40px
  dismiss button.
- Email addresses may break anywhere (one rule for every mailto:
  link), so a long one can't push past the screen.
- Footer site-map links, the arrow links and the accessibility
  panel's close button are larger targets; the open accessibility
  panel sits above the privacy notice; the timeline's "still to
  come" list reads in full on touch screens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:44:27 -05:00
Zaldimmar
a907a47c24 Mobile: menu, page titles, hero, retreat carousel, people tiles
- The mobile menu centers when it fits and starts at the top when
  it's taller than the screen (safe center), so its top is
  reachable; its close button is a 44px target.
- Page titles and the hero headline start a size smaller on phones
  and break long words instead of being cut off.
- Hero: the split buttons stack on a phone (the slash from sm); the
  slide dots and pause button are 40px targets and wrap; photo heroes
  leave room for the caption above the buttons.
- Retreat carousel: phone-sized padding and type; on a phone the
  arrows sit beside the dots instead of over the text, dots are 40px
  targets, and a swipe turns it. The narrow event card layout gives
  the logo its own row (it had made a stray column).
- People tiles: the details panel slides to stay on screen with its
  notch under the tile; a third column only when tiles keep 60% of
  their width; a 40px close button.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:42:20 -05:00
Zaldimmar
2a926971f7 A newsletter builder (Tools → Newsletter)
Tick upcoming events, published blog posts and the front page's
featured cards, write a title and intro, and copy an email-ready
newsletter (table layout, inline styles, the palette in hex, a
plain-text copy alongside) into Mailchimp, Gmail or Church Center,
or download it. Picked posts are read from their public pages, so
only live posts make it in; links and images point at the live
site. Nothing is sent or stored. The builder is src/lib/newsletter.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:38:04 -05:00
Zaldimmar
177a65005e An accessibility button: a dyslexia-friendly font and a reading mode
A button fixed to the bottom right of every public page opens two
switches. Dyslexia-friendly font swaps every typeface for
OpenDyslexic (self-hosted, @fontsource/opendyslexic, downloaded
only when chosen). Reading mode steps the design back: no background
circles, motion or shadows, every layout one column, larger text and
underlined links. Both are data attributes on <html>, remembered in
the browser and set before the first paint like the theme. On a
phone the privacy notice sits above the button.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:34:40 -05:00
Zaldimmar
0f62b67ee0 Privacy: Church Center's page and its analytics; self-hosted Plausible
The Giving entry links ngu.churchcenteronline.com and says Church
Center's script loads with the Giving page and may use Google
Analytics in its form. Cookies and storage now say the site uses
self-hosted, cookieless Plausible Analytics and not Google
Analytics. Last updated September 30, 2026.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:29:40 -05:00
Zaldimmar
01de6272f3 People tiles: a whole list shares one row when it fits
When every group (a team's leads and members alike) fits side by
side with tiles at three quarters of full width or wider, 10 at most,
they share one line, each group's width following its head count; a
board of 7 is one row rather than 5 and 2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:28:42 -05:00
Zaldimmar
bc88b45ee1 Version v1.10.3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 21:12:13 -05:00
Zaldimmar
af7e99895a Request form: short field titles with a help line, and why to send a file
Detail fields can carry a help line under the title (RequestField
help). The blog post's card field is now Short description, saying
where it shows; other long titles became short ones with the detail
in the help. The Files note explains that a blog post sent as a
.docx can be imported straight onto the site.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 20:33:20 -05:00
Zaldimmar
79c4b243f5 A 404 page that suggests what the address was for
The closest static pages and public records to the failed address
(suggest.ts: letter-pair likeness of the address's last part to each
URL ID and name, and of the whole address to each path), so a typo,
a missing hyphen or an old /chapters/ link still finds its page; the
main pages below to start from.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 20:32:00 -05:00
Zaldimmar
499662b59a Leadership becomes the Organization page, at /organization
Three sections: Mission, Vision & Values from the national
organization record's own description and content blocks;
Leadership as that record's teams with their people; Details &
Contact with NGU's address, nonprofit status, email and the
record's contact links. /leadership answers with a 301 to
/organization (MOVED in routes/pages.js), and a page title or intro
saved for it in Site settings moves with it (migration 054).

OrganizationDetail's team list and contact buttons are now shared
components (OrgTeams, OrgContact), and NGU's address and email live
once in src/data/organizationDetails.ts for the footer, the page and
ComingSoon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 20:30:18 -05:00
Zaldimmar
7c7cdaac14 People blocks and host teams
- A "People" content block: a team's members as people tiles, people
  picked one by one as items (each with a title), or both.
  content_blocks gains team_id (migration 054 rebuilds it for the
  type CHECK); a picked person rides on the item's person_id.
- An organization host can name a team (any organization's) to show
  in its place: event_hosts.team_id, carried by v_event_hosts. The
  event page reads "Hosted by" the team, linked to its page.
- Admin fields can show on `when: { path, filled: true }`.
- The showcase post has a people block; the past showcase event is
  hosted by the region shown as its team.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 20:26:26 -05:00
6f86a113e0 Merge pull request 'Revised palette: teal, green, amber, ink' (#19) from palette-test into main 2026-09-30 23:59:33 +01:00
15c2d0e063 Merge pull request 'Design overhaul (v1.10.0 to v1.10.2)' (#18) from design-overhaul into main 2026-09-30 23:59:15 +01:00
Zaldimmar
79f1d09eef Try the revised palette (teal, green, amber, ink)
The suggested grid as the theme defaults, light and dark, with
PALETTE, the accents (olive becomes amber), the backdrop shades
and every literal from the old grid mapped over. Every text pair
passes the admin's 4.5:1 check; the hero's filled button is amber.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 16:51:14 -05:00
Zaldimmar
a2465f9359 Version v1.10.2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 16:45:10 -05:00
Zaldimmar
57f8020542 Video stills skip YouTube's gray placeholder; timeline back to teal dots; people rows fill
- A still that fails or comes back as YouTube's 120 x 90 "no
  thumbnail" image gives way to the next; with none left the player
  is a flat teal panel with the play button showing.
- Timeline: solid teal dots, a solid teal rail and teal decade tags
  (still on their branch), one color throughout, until a vine or
  tree drawing replaces them. The leaf colors are gone.
- People tiles fill each row with as many as fit (2 to 10), one
  fewer only when the last row would be a single tile, instead of
  evening rows out (8 where 6 fit had come out 4 and 4).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 16:44:42 -05:00
Zaldimmar
6506f65b1e Backdrop parallax in Firefox: a passive scroll fallback
Where scroll-driven animations are missing, a passive scroll handler
writes the scroll position to --pb-y at most once a frame and the
CSS moves each layer by its share, matching the scroll-timeline
version. Off under reduced motion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 16:35:25 -05:00
Zaldimmar
2df908f7c4 Backdrop: four parallax layers, laid out per page, tones per top-level section
Sixteen circles in four layers, big and slow at the back to small
and quicker at the front, each rising by its share of the page's
scroll (none at the page's own speed); how far is measured from the
page's height, so the back layer visibly moves on a long page. Each
path gets its own seeded arrangement. The tone moves on only when a
new top-level section arrives, and eases over 2.4s. Dark shades are
chosen so text passes 4.5:1 however many circles overlap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 16:28:55 -05:00
Zaldimmar
e5c14dffa3 Timeline on a brown branch with leaf-colored decade tags; solid featured entries; admin home in two alternating colors
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 16:26:38 -05:00
Zaldimmar
a397f3eac0 Overhaul fixes: raised cards, balanced people rows, solid map, small button radius
- Cards sit on a raised surface (white, or a touch of tint in dark
  mode) with a shadow: featured cards, the connect block, people
  tiles. tint-soft is a faint teal again, not green.
- Buttons: a small plain radius everywhere; no superellipse.
- Video stills use YouTube's 16:9 frame (the 4:3 one cropped as a
  fallback), have small rounded corners, and show a round, centered
  play button on hover or focus (always on touch screens).
- People tiles: rows balanced between 2 and 10 across, never ending
  on a lone tile where it can be helped.
- Map tiles and region tags are solid, dimmed by color, not opacity.
- Admin: white (surface) background, header and footer as wide as
  the content.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 16:24:36 -05:00
Zaldimmar
582c65077d Version v1.10.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:40:51 -05:00
Zaldimmar
f37c093dc0 Overhaul fixes: vertical parallax backdrop, bracket notices, list-framed people tiles
- Backdrop: two slow circles fixed to the window drift up as the
  page scrolls (a scroll-driven animation), three sit down the page
  and travel with their sections; tones still change per section.
- Notices are two corner brackets, no box or fill.
- People tiles: the frame is the list's, and details open right
  under the tile, closing on Escape or a click elsewhere.
- Featured cards and the connect section: 4px rules; video frames
  inset from the card edge.
- Calendar weekday row is a solid bar; History decade numerals are
  tags on the rail instead of a white box.
- Region and partner buttons say Request; the region list's group
  count is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:40:04 -05:00
Zaldimmar
8ca3b54b31 Version v1.10.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:32:22 -05:00
Zaldimmar
dd33ee2da0 Document the palette, square corners, notices and the page backdrop
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:55:21 -05:00
Zaldimmar
239c3fa293 Admin home: a palette color per group of cards
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:54:39 -05:00
Zaldimmar
d5428297a4 Timeline years as leaves, green now and turning autumn going back; notices instead of dashed boxes
A year's leaf eases from green to gold to autumn between this year
and 2000 (leafColor in color.ts); every year before 2000 is fully
turned. Empty-section and form notes use one notice style, a flat
tinted panel with a solid left bar.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:53:50 -05:00
Zaldimmar
592e07f614 People tiles: square photos, a frame, even heights, palette initials
Captions are a fixed two lines of name and two of title; what
doesn't fit ends in an ellipsis and gives the tile the down arrow,
whose details show it in full.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:50:59 -05:00
Zaldimmar
5dbb203519 Featured cards and the connect section as one ruled block; Give beside the footer logo
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:48:48 -05:00
Zaldimmar
6fc19d7ee3 One palette backdrop behind every page; flat hero, split hero buttons
PageBackdrop draws flat, overlapping palette circles behind the
public site and eases them to a new tone as each section reaches
the middle of the window, so sections no longer paint their own
bands (PageShell's background field is gone). The hero's brand
backdrop is a flat teal with the dove, its two buttons one cell cut
by a slash, and the countdown straddles the hero and the band
below. No glows: the drifting blobs, rings, live-dot pulse and the
stats band's blurred circle are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:46:48 -05:00
Zaldimmar
3dfc31fd85 Set titles and headings in Poppins Bold, subheadings regular
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:41:26 -05:00
Zaldimmar
d81f7bd856 Adopt the new palette; square corners, superellipse buttons
The theme defaults (light and dark) come from the 16-color grid,
kept as PALETTE in src/lib/color.ts; every text pair passes the
admin's 4.5:1 check. Nothing is rounded any more except buttons,
which share one btn utility (Poppins Bold, a superellipse corner
where the browser has corner-shape) and true dots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:40:39 -05:00
ecdcd4ec37 Merge pull request 'Groups instead of chapters, US spelling, wider admin home (v1.9.15-groups)' (#17) from groups-and-us-spelling into main 2026-09-30 19:28:05 +01:00
Zaldimmar
0f2fb2ccb3 Version v1.9.15-groups
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 13:27:45 -05:00
Zaldimmar
2ad65cdc15 Write the site in US English
color, center, canceled, labeled, recognize and the rest, in UI
text, help text, comments, docs and names (ColorInput, QrCenter).
Migration 053 renames the two Site settings color CHECKs, whose
names are the messages the admin shows. Kept: events.status's
stored value 'cancelled' (shown as canceled), aria-labelledby,
schema.org's EventCancelled, and old migrations as they ran.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 13:24:11 -05:00
Zaldimmar
38aff34c97 Call local chapters groups, everywhere
The organization kind is 'group', its side table is groups, pages
live at /groups/<id> and the Community page's section is #groups.
Migration 052 converts existing databases: the kind and the tables
whose CHECKs name chapters are rebuilt, the front page count and
request category follow, and the site's own /chapters/ and
#chapters links in records are rewritten. Request files now go in
Requests/Groups on the shared drive.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 13:19:51 -05:00
Zaldimmar
175a18976d Widen the admin home so its cards run three across
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 13:12:55 -05:00
c76df021a8 Merge pull request 'Request details, Drive folders, image folders, clip tool to Drive (v1.9.12 to v1.9.14-content-display)' (#16) from content-display into main 2026-09-30 19:05:25 +01:00
Zaldimmar
a4c09c9643 Version v1.9.14-content-display
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 00:16:49 -05:00
Zaldimmar
06a0e07a79 Let a downloaded video be saved whole, before or without cutting
Save to library and Save to Drive on a finished download, not only on
clips. The download stays on the server to cut clips from either way;
a clip's library save still clears its working file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 00:14:26 -05:00
Zaldimmar
6ccbc03b52 Let the image picker take photos sent with requests
A From requests tab in every image picker lists photos from the
Request form (they live in Drive), the request being edited from
first. Picking one copies it into the media library, in the field's
folder, once per file, and the field gets that copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 00:11:01 -05:00
Zaldimmar
110b655d5e Mark the message (and a request's name) as required on the forms
The send button waits for 10 characters of message; the field now says
Required, and a note under it counts down what's still needed. The
request form's name field is marked too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 00:09:22 -05:00
Zaldimmar
f983ecf26c Version v1.9.13-content-display
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 23:56:26 -05:00
Zaldimmar
42d1536ee6 Let the clip tool save a clip to a Drive folder
Save to Drive, beside Save to library, puts a finished clip in a folder
under Media (Videos or Audio chosen first to match it) as a Files
entry, shared by link, so pages can link to it (migration 051). The
clip streams from disk through a resumable upload, so a long one
isn't read into memory. A clip can be in both the library and Drive.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 23:29:28 -05:00
Zaldimmar
e1542d8d87 Manage request files: mark missing ones, remove them, list them all
Forms → Content requests and a new Tools → Media → Requests tab (by
type folder, each linked to its request) mark a file Drive no longer
has under Requests as Missing from Drive. Remove (admins and up)
trashes a file and takes it off its request. Drive is asked at most
every 30 seconds, and folder lookups now cache every level walked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 23:25:58 -05:00
Zaldimmar
9ff1cd6e99 Make link cards smaller, up to three in a row
One grid whatever the count, so a lone card takes a column rather than
the width. Also the Blog Posts request folder's name, as it is in Drive.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 23:21:48 -05:00
Zaldimmar
a98aea6bca Version v1.9.12-content-display
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 22:50:55 -05:00
Zaldimmar
7f05076a86 Add Drive folders: per request type, and managed from the Media page
Request files go in Requests/<type> (Chapters, Events...). Media →
Files shows a tab per folder under Media, up to three deep, and can
make, rename (files follow) and delete empty folders, move a file with
its Folder dropdown, and upload into the folder showing; Choose a file
has the same tabs. A folder made, or a file moved, in Drive by hand is
followed on the next look (migration 050 records each file's folder).

Deletes now move to Drive's trash: a shared drive's Content manager,
the service account's role, can't delete outright, so request and file
deletes would have failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 22:34:27 -05:00
Zaldimmar
9854da965e Keep uploaded images in folders by what they're for
logos/ for logo and icon fields, thumbnails/ for previews the site
saves (link previews, Drive first pages), images/ for everything else;
each small copy beside its image. Images from before folders are
sorted once at boot by their uses, and every record naming them is
rewritten in one transaction after the files move.

The Media page and image pickers get a tab per folder; a picker opens
on its field's folder and uploads there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 22:29:22 -05:00
Zaldimmar
4b249c9e52 Let a content request carry the record's details, and open its editor
The Request form asks each type for its main details (a chapter's
city, meeting time, website and email; an event's dates, venue and
registration link...), stored as one JSON column (migration 049). The
server only checks the shape; the fields are src/data/requestTypes.ts.

Forms → Content requests shows them, and for a new record opens the
New editor filled in (URL ID from the name, links and a description
paragraph added); for an update, picks the record (closest name
first) and opens it with each requested value beside the current one
to use or skip. Nothing is saved until Save.

Also centres the image and file pickers, which Tailwind's reset had
pinned to the top left.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 22:21:33 -05:00
Zaldimmar
7876e060e7 List a person's blog posts on their page
A Blog posts section, the same cards as the Community blog, for the
published and listed posts they're an author of.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 22:15:18 -05:00
f797e2c509 Merge pull request 'Content display, requests and Google Workspace (v1.9.5 to v1.9.11-content-display)' (#15) from content-display into main 2026-09-30 02:34:52 +01:00
Zaldimmar
1473f4d081 Version v1.9.11-content-display
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 20:02:35 -05:00
Zaldimmar
706abf6a03 Replace the last glyph icons with Phosphor
The editor's insert, duplicate and remove buttons, the image
library's close button and audio tile, the schedule's fold-out caret,
the admin menu's caret, the history timeline's caret and gap marker,
and the QR page's copied tick.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 19:43:48 -05:00
Zaldimmar
5292eda4a6 Version v1.9.10-content-display
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 19:35:46 -05:00
Zaldimmar
b504c24fb0 Keep page files in the shared drive's Media folder, not Blog
The folder isn't only for blog posts. A Blog folder made before this
can be renamed to Media in Drive; its files keep working.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 19:33:19 -05:00
Zaldimmar
6191322fea Pick up files added to the Blog folder in Drive, and name nginx errors
Opening Tools → Media → Files (or a Choose a file picker) now looks in
the shared drive's Blog folder, at most every 30 seconds, and adds
anything put there in Drive itself: shared as anyone with the link,
previewed, Google Docs, Sheets and Slides included, folders and
shortcuts left out. A file Drive won't share is named in a note and
tried again every ten minutes.

A reply that isn't the API's (nginx's own error page) now says what it
was: a 413 names nginx's upload limit, a 502 the service, a 504 the
timeout, instead of "Server did not return JSON".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 19:14:40 -05:00
Zaldimmar
5f13273e69 Version v1.9.9-content-display
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 18:43:38 -05:00
Zaldimmar
934598f954 Add a file library in Google Drive for pages to link to
Tools → Media → Files uploads PDF, Office (.docx, .xlsx, .pptx), MP3,
M4A and zip files, up to 50 MB, to the shared drive's Blog folder and
shares each as anyone with the link can view (migration 048). A file's
name and contents must agree.

Content block links get "Choose a file" (paragraph, button and image
links, list and link items, link cards). A link card also takes the
file's name and Drive's picture of its first page, fetched after
upload and saved into the image library; cards to Drive say "Google
Drive". Deleting a file says first what still links to it.

Setup and the nginx block: docs/google-drive-and-mail.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 18:37:15 -05:00
Zaldimmar
36c9226bd9 Version v1.9.8-content-display
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 17:54:33 -05:00
Zaldimmar
80877a4659 Let Google Workspace groups grant admin access
Site settings → Access names a group for each of admin, editor and
viewer (migration 047). Someone in one who signs in with Google gets a
Google-only account with their highest group's role, and the role
follows the groups: at every sign-in, hourly while signed in, and on
Panel → Google groups → Re-sync now. Out of every group, the account
is disabled and signed out until they're back in one.

Group accounts' roles are locked in the Panel; a superadmin's Disable
sticks. Superadmins and admin-cli accounts are never changed. If
Google can't be asked, sign-ins are refused but the hourly check
leaves accounts alone. Panel → Check their groups tests an email.

Lookups use the service account through the Directory API as
GOOGLE_DIRECTORY_AS. Setup: docs/google-sign-in.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 17:44:04 -05:00
Zaldimmar
d7835dd5d4 Version v1.9.7-content-display
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 17:19:58 -05:00
Zaldimmar
8fd3a9b15b Add a test notice button to Site settings
Panel → Site settings → Notices → Send a test notice emails the
addresses in the box now and shows where it came from, or Google's
reason for refusing, so the Gmail setup can be checked without the
journal. Superadmins only (POST /api/admin/panel/test-notice).

The docs now say the sender must be a Workspace user: a group can't
be acted as through delegation, though it can receive notices.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 17:18:43 -05:00
Zaldimmar
c63478a72a Version v1.9.6-content-display
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 16:59:19 -05:00
Zaldimmar
0f6a796021 Keep Drive files in named folders of one shared drive
GOOGLE_SHARED_DRIVE (the shared drive's bare id) replaces
GOOGLE_DRIVE_FOLDER. driveUpload takes a folder path, found by name in
the shared drive or made the first time, so each use gets its own
folder: "Requests" for the Request form now, others later. The docs
say plainly that the setting is the id only, not the address.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 16:53:40 -05:00
Zaldimmar
e7743829be Version v1.9.5-content-display
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:57:35 -05:00
Zaldimmar
dc53af238f Add a Request form, with files in Google Drive and email notices
One form at /request for blog posts, events, and new or updated
chapters, regions (updates only), partners, teams, awards and people.
?type= opens it on one; buttons on the Community sections, blog posts,
Retreats and the front page calendar do. Files (.docx, PDF, JPEG, PNG)
go to a Google Drive folder through a service account.

Requests are feedback rows of type 'content' (migration 046), in a
third Forms queue: files download from Drive, a .docx can become a
draft blog post, and deleting a request deletes its files. New content
and data requests email the addresses in Site settings through Gmail.

Setup: docs/google-drive-and-mail.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:54:00 -05:00
Zaldimmar
0e582c236b Move link cards into their own migration
044 had already run with only the table type, so a database that ran
it would never see the edited CHECK, and boot would refuse the cards
type. 044 is back as it was; 045 rebuilds content_blocks to allow
cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:53:58 -05:00
Zaldimmar
4e9b4e3329 Add link card blocks to post bodies
A "cards" content block: each item is a card with a picture, title and
description that links somewhere, like a link shared in a chat. Fetch
preview fills the card from the link. Migration 044 (not deployed yet)
now allows both table and cards.

Also fixes hidden-field clearing when two fields share a path, and adds
table and card blocks to the showcase post.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:40:24 -05:00
Zaldimmar
5dceeb5860 Let a blog post be downloaded as a PDF
Download PDF beside the byline opens the browser's print dialog (Save
as PDF) with a print layout: the site's header, footer and notices
hidden, the contents column dropped, the light palette whatever the
screen shows, and at the bottom the post's link and a QR code of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:34:43 -05:00
Zaldimmar
c03914a210 Move Blog posts from Pages to Data in the admin menu
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:33:09 -05:00
Zaldimmar
7f12824c93 Import a Word document as a blog post, and add table blocks
- Table content blocks (migration 044): a grid of text, a row per
  line, cells split by |, the first row the header; cells take the
  same formatting as a paragraph; wide tables scroll on a phone
- Blog posts -> Import from Word: the server reads the .docx (zip and
  XML read without a library, sizes capped) and creates an unpublished
  post through the CRUD engine: title, date, headings, paragraphs,
  lists, tables, bold, italic and links; the editor opens with a note
  of what came over and what didn't (images)
- docs/importing.md, and an nginx block for the upload

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 12:44:20 -05:00
adc88e5714 Merge pull request 'Codebase audits, privacy, dark mode, palette (v1.9.0 to v1.9.4-audit)' (#14) from audit into main 2026-09-29 18:07:24 +01:00
Zaldimmar
3993005918 Let the blog contents column stay in view while scrolling
The site wrapper's overflow-x: hidden made it a scroll container, so
nothing inside it could be position: sticky. overflow-x: clip keeps
the sideways clipping without that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 10:09:12 -05:00
Zaldimmar
d17a572916 Bump SITE_VERSION to v1.9.4-audit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 10:04:07 -05:00
Zaldimmar
2b009beac1 Use organization-neutral names in code and browser keys
- The timeline's ngu-tl classes and keyframes are site-tl; nguLogo is
  siteLogo; the event card's ngu grid area is org; window.__NGU_SITE__
  is window.__SITE__; QR downloads are qr-<page>.png
- Browser keys (theme, closed banner and privacy notice, chunk reload)
  start site-; the page's first script moves any old ngu- values over
  once, so nobody loses their theme or sees a closed notice again
- Session and Google sign-in cookies are site_session and site_oauth
  (__Host- over https); everyone signs in again once

Record ids, server paths, the service and the database file keep
their names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 09:23:29 -05:00
Zaldimmar
92e7938b64 Give blog posts an optional table of contents
Blog posts -> Show contents (migration 043, off by default): with two
or more headings, the post's headings sit in a sticky column beside
it with the one being read lit (an IntersectionObserver, not a scroll
listener), and fold out at the top on phones. Content-block headings
now carry anchor ids, so a link can point at one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 09:21:48 -05:00
Zaldimmar
f59ab314e0 Give the history timeline's small logos the dark-mode backing
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 09:19:52 -05:00
Zaldimmar
99d83eb090 Separate data requests from website feedback in the admin
Forms now has two queues, Website feedback and Data requests, each
its own card on the admin home and a tab on the page, with what's new
in each. The API takes ?kind=feedback|privacy and counts per queue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 09:19:06 -05:00
Zaldimmar
7c1723b0ad Keep the Church Center giving modal see-through in dark mode
Its transparent full-page iframe is drawn for light pages; with the
site in dark mode the browser painted the iframe opaque and the page
went white. The iframe is now declared light, matching its content.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 09:10:19 -05:00
Zaldimmar
adbc449029 Theme the last two light-only fills
The admin's Actioned feedback badge and the QR maker's empty
placeholder stayed light in dark mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 09:02:29 -05:00
Zaldimmar
f934b1dd93 Tidy the structure the audit found
- The colour defaults have one source, server/src/themeDefaults.js,
  read by the server and the admin; the build stops if src/index.css
  disagrees with it
- server/src/admin-schema.js split into admin-schema/, one file per
  entity plus columns.js (the registry checked identical)
- loadOwned() in shape.js replaces the same three loads on four
  detail routes (every public route checked identical); one NO_STORE
- One OrgLogo component for the org lists and the chapter map; an
  organization's own page now shows the same initials as the lists
- One localISO() for the viewer's calendar day, in place of three
- Boot refuses a descriptor dropdown value the table's CHECK doesn't
  allow, instead of it failing on save
- Deleted the unused Other.tsx and white-background logo;
  chapters.ts is useCommunity.ts; isSuper() in the Panel; stale
  comments and docs corrected

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 03:02:21 -05:00
Zaldimmar
048c7599ce Fix dark mode and bring the public design in line with the taste audit
- Dark mode: the countdown card, timeline section, Giving text, error
  text, the Leadership button, skeletons and the admin's dark text all
  follow the tokens; logos get a light plate in dark mode
- One BRAND accent (the button token, so the admin palette reaches
  every page) and one ACCENTS family in color.ts, replacing 20 local
  teal constants and the purple, ochre and rust section colours;
  neon green and gold become mint and brand green
- Shadows are tinted with the site's ink; glow shadows are gone
- One giving label, Give, in the nav, footer and Giving page
- Phosphor icons replace the hand-drawn SVGs and the glyph icons;
  Pathfinder paths pick a named icon (emoji still shown) and lose the
  watermark
- Home keeps two eyebrows; StatsBand's title is a real heading;
  section headings step down under the page title
- Nav links switch to the menu below lg, so they never wrap; jump
  links land clear of the header; press feedback on buttons
- Empty sections say what's coming and who to ask; loading is a
  skeleton; form placeholders and borders are readable; one
  corner-radius rule; theme-color for both modes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 02:54:03 -05:00
Zaldimmar
f72a9604d2 Make the site faster to load and lighter on the server
- Every page but Home, and the whole admin, loads on first visit: the
  main bundle drops from 579 kB to 314 kB (173 to 98 kB gzipped); a
  tab on an old build reloads once when a page chunk has gone
- Home asks for events and the timeline alongside its own data, and
  the server preloads /api/front-page and the first hero photo
- Hero headline rises in as one piece (it held back the page's
  largest paint), sized to stay within two lines; min-h in dvh; first
  slide fetched at high priority
- Every raster upload gets a 640px copy (at upload, and at boot for
  older files); logos, avatars and card pictures load it and fall
  back to the full file
- Login password checks run off the event loop; only admin requests
  are logged per request; ffmpeg runs at nice 19 on Linux
- Page HTML is no-cache, so a deploy can't strand a cached page on
  missing assets; source maps are no longer linked
- Migration 042: index person_awards by award
- docs/performance.md, and gzip and HTTP/2 for nginx

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 02:41:45 -05:00
Zaldimmar
be7e92417e Fix the Panel account bug and harden what the second audit found
- Panel: changing a role or disabling an account always failed
  (db.transaction doesn't exist on node:sqlite); it uses tx() now
- Feeds and link previews are scanned with indexOf, not whole-document
  regexes, so a hostile feed or page can't freeze the server; entity
  decoding can't throw; escaped-HTML descriptions make clean excerpts
- Feed reads share one fetch per feed and serve the stale copy while
  a refresh runs
- Deliberate HTTP errors (the CSRF 403) keep their status instead of
  becoming logged 500s; a JSON null body is handled
- url columns read the scheme the way the URL parser does, so
  control characters can't hide javascript:
- Google sign-in state cookie is __Host- and its return page is
  checked again; more reserved ranges blocked for previews and feeds,
  and a 15 s cap on each whole fetch
- Log lines from visitor text are made single-line and short; list
  limits can't go negative; entity names can't hit object prototypes
- A clip title can't point the clip tool at another file
- Uploads over 60 MP are refused before decoding; the Keep original
  help says a photo's location stays in it
- admin-cli add defaults to the editor role

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 02:34:26 -05:00
364 changed files with 36587 additions and 8534 deletions

File diff suppressed because it is too large Load diff

3
.claude/CLAUDE.md Normal file
View file

@ -0,0 +1,3 @@
# graphify
- **graphify** (`.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
When the user types `/graphify`, use the installed graphify skill or instructions before doing anything else.

34
.claude/settings.json Normal file
View file

@ -0,0 +1,34 @@
{
"permissions": {
"allow": [
"Bash(git add:*)",
"Bash(git commit:*)",
"Bash(git push origin:*)",
"Bash(tea pr create:*)"
]
},
"hooks": {
"PreToolUse": [
{
"matcher": "Bash|Grep",
"hooks": [
{
"type": "command",
"command": "graphify hook-guard search",
"timeout": 10
}
]
},
{
"matcher": "Read|Glob",
"hooks": [
{
"type": "command",
"command": "graphify hook-guard read",
"timeout": 10
}
]
}
]
}
}

View file

@ -0,0 +1 @@
0.9.71

View file

@ -0,0 +1,762 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
---
# /graphify
Turn any folder of files into a navigable knowledge graph with community detection, an honest audit trail, and three outputs: interactive HTML, GraphRAG-ready JSON, and a plain-language GRAPH_REPORT.md.
## Usage
```
/graphify # full pipeline on current directory (HTML viz; add --obsidian for a vault)
/graphify <path> # full pipeline on specific path
/graphify https://github.com/<owner>/<repo> # clone repo then run full pipeline on it
/graphify https://github.com/<owner>/<repo> --branch <branch> # clone a specific branch
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
/graphify <path> --no-viz # skip visualization, just report + JSON
/graphify <path> --html # (HTML is generated by default - this flag is a no-op)
/graphify <path> --svg # also export graph.svg (embeds in Notion, GitHub)
/graphify <path> --graphml # export graph.graphml (Gephi, yEd)
/graphify <path> --neo4j # generate graphify-out/cypher.txt for Neo4j
/graphify <path> --neo4j-push bolt://localhost:7687 # push directly to Neo4j
/graphify <path> --falkordb # generate graphify-out/cypher.txt for FalkorDB
/graphify <path> --falkordb-push falkordb://localhost:6379 # push directly to FalkorDB
/graphify <path> --mcp # start MCP stdio server for agent access
/graphify <path> --watch # watch folder, auto-rebuild on code changes (no LLM needed)
/graphify <path> --wiki # build agent-crawlable wiki (index.md + one article per community)
/graphify <path> --obsidian --obsidian-dir ~/vaults/my-project # write vault to custom path (e.g. existing vault)
/graphify add <url> # fetch URL, save to ./raw, update graph
/graphify add <url> --author "Name" # tag who wrote it
/graphify add <url> --contributor "Name" # tag who added it to the corpus
/graphify query "<question>" # BFS traversal - broad context
/graphify query "<question>" --dfs # DFS - trace a specific path
/graphify query "<question>" --budget 1500 # cap answer at N tokens
/graphify path "AuthModule" "Database" # shortest path between two concepts
/graphify explain "SwinTransformer" # plain-language explanation of a node
```
## What graphify is for
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
**Fast path — existing graph:** Before doing anything else, check whether `graphify-out/graph.json` exists. The expected location is `graphify-out/graph.json` relative to the **current working directory** (i.e. the project root where you are running commands). If it exists AND the user's request is a natural-language question about the codebase (e.g. "How does X work?", "What calls Y?", "Trace the data flow through Z") and NOT an explicit rebuild command (`--update`, `--cluster-only`, or a bare path/URL that implies fresh extraction): **skip Steps 1–5 entirely and jump straight to `## For /graphify query`.** Run `graphify query "<question>"` immediately. Do not run detect. Do not check corpus size. Do not ask the user to narrow. The graph is already built — use it.
If no path was given, use `.` (current directory). Do not ask the user for a path.
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
Follow these steps in order. Do not skip steps.
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
Only when the path is one or more `https://github.com/...` URLs, or several local subfolders to merge. See `references/github-and-merge.md` for the clone, cross-repo merge, and monorepo flow, then continue with the resolved local path. A plain local path skips this step.
### Step 1 - Ensure graphify is installed
```powershell
# Detect Python with graphify — uv/pipx-aware (fixes #831)
New-Item -ItemType Directory -Force -Path graphify-out | Out-Null
$GRAPHIFY_PYTHON = $null
function Find-GraphifyPython {
# 1. uv tool install — 'uv tool dir' is authoritative, respects UV_TOOL_DIR automatically
if (Get-Command uv -ErrorAction SilentlyContinue) {
$uvDir = (uv tool dir 2>$null).Trim()
if ($uvDir) {
$py = Join-Path $uvDir "graphifyy\Scripts\python.exe"
if (Test-Path $py) {
& $py -c "import graphify" 2>$null
if ($LASTEXITCODE -eq 0) { return $py }
}
}
}
# 2. pipx install — 'pipx environment' respects PIPX_HOME automatically
if (Get-Command pipx -ErrorAction SilentlyContinue) {
$venvs = (pipx environment --value PIPX_LOCAL_VENVS 2>$null).Trim()
if ($venvs) {
$py = Join-Path $venvs "graphifyy\Scripts\python.exe"
if (Test-Path $py) {
& $py -c "import graphify" 2>$null
if ($LASTEXITCODE -eq 0) { return $py }
}
}
}
# 3. Active venv / conda / pip-into-current-env
$pyCmd = Get-Command python -ErrorAction SilentlyContinue
if ($pyCmd) {
& $pyCmd.Source -c "import graphify" 2>$null
if ($LASTEXITCODE -eq 0) {
return (& $pyCmd.Source -c "import sys; print(sys.executable)").Trim()
}
}
return $null
}
# Try to find the right Python (uv → pipx → active env)
$GRAPHIFY_PYTHON = Find-GraphifyPython
# Not found — install then re-detect
if (-not $GRAPHIFY_PYTHON) {
if (Get-Command uv -ErrorAction SilentlyContinue) {
uv tool install --upgrade graphifyy -q 2>&1 | Select-Object -Last 3
} else {
pip install graphifyy -q 2>&1 | Select-Object -Last 3
}
$GRAPHIFY_PYTHON = Find-GraphifyPython
}
# Save interpreter path — all subsequent steps read this.
# `Out-File -Encoding utf8` always writes a BOM on Windows PowerShell 5.1 (utf8NoBOM
# only exists from PowerShell 6), and that BOM rides into the saved path, so the hook
# rebuild fails with WinError 123 (#3028). WriteAllText with an explicit BOM-less
# encoding writes the bytes POSIX writes, and adds no trailing newline.
$Utf8NoBom = New-Object System.Text.UTF8Encoding $false
[System.IO.File]::WriteAllText((Join-Path $PWD 'graphify-out\.graphify_python'), [string]$GRAPHIFY_PYTHON, $Utf8NoBom)
# Save scan root so `graphify update` (no args) knows where to look next time.
# INPUT_PATH is captured through a single-quoted (literal) here-string, never
# substituted directly into the command line: an unquoted bareword argument
# substituted here would let a malicious path (a stray `;`, `|`, or `$(...)`)
# execute as script code the moment this line runs.
$InputPathRaw = @'
INPUT_PATH
'@
[System.IO.File]::WriteAllText((Join-Path $PWD 'graphify-out\.graphify_root'), (Resolve-Path $InputPathRaw.Trim()).Path, $Utf8NoBom)
```
If the import succeeds, print nothing and move straight to Step 2.
**In every subsequent block, run Python through the saved interpreter — `& (Get-Content graphify-out\.graphify_python)` in place of a bare `python3` — so every step uses the interpreter that actually has graphify.**
### Step 2 - Detect files
```powershell
@'
import json
from graphify.detect import detect
from pathlib import Path
result = detect(Path('INPUT_PATH'))
# Write the sidecar from Python, not a shell redirect, so the same block renders
# on PowerShell hosts without console-encoding drift (#2528).
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
print(f'Detected {result["total_files"]} files')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
code: N files (.py .ts .go ...)
docs: N files (.md .txt ...)
papers: N files (.pdf ...)
images: N files
video: N files (.mp4 .mp3 ...)
```
Omit any category with 0 files from the summary.
Then act on it:
- If `total_files` is 0: stop with "No supported files found in [path]."
- If `skipped_sensitive` is non-empty: report the count and list the skipped file names, so a wrongly-flagged source or doc is visible and can be renamed or moved (#2106).
- If `total_words` > 2,000,000 OR `total_files` > 500: show the warning. Then compute the top 5 first-level subdirectories by file count:
- Read `scan_root` from the detect JSON (always an absolute path to the resolved INPUT_PATH).
- Concatenate all file lists across all types (`code`, `document`, `paper`, `image`, `video`).
- Filter out any path that starts with `scan_root + "/graphify-out/"` to exclude converted sidecars.
- For each file, strip the `scan_root` prefix and take the first path component. Files directly in `scan_root` with no subdirectory count as `(root)`.
- If all files are in `(root)` with no subdirectories, do not ask to narrow — no subfolders exist. Instead suggest `--no-cluster` to skip the expensive clustering step and proceed.
- Otherwise rank by count, show the top 5 with file counts, then ask which subfolder to run on. Wait for the user's answer before proceeding.
- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
### Step 2.5 - Video and audio (only if video files detected)
Skip this step entirely if `detect` returned zero `video` files. When the corpus has video or audio, see `references/transcribe.md` to transcribe them to text first, then treat the transcripts as doc files in Step 3.
### Step 3 - Extract entities and relationships
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (LLM, costs tokens).
> **graphify needs no API key. Never ask the user for one, and never block on one.** Code is extracted structurally (AST) with no LLM and no key at all — a code-only corpus (the common `/graphify .` on a repo) skips semantic extraction entirely, so it needs nothing here: go straight to Part A and skip Part B. Semantic extraction (only for docs, papers, and images) uses Gemini **only if** `GEMINI_API_KEY`/`GOOGLE_API_KEY` is already set; otherwise the host agent itself is the LLM. graphify does **not** read `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or any other provider key. If you catch yourself about to prompt for, wait on, or stop because of a missing API key, that is a misread of this skill — proceed without one.
**Before semantic extraction:** check whether `GEMINI_API_KEY` or `GOOGLE_API_KEY` is set. If neither is set, print this one-liner to the user:
> Tip: set `GEMINI_API_KEY` or `GOOGLE_API_KEY` to use Gemini for semantic extraction (`pip install 'graphifyy[gemini]'`).
Print it once, then continue — do not wait for the user to supply a key. If `GEMINI_API_KEY` or `GOOGLE_API_KEY` IS set, use `graphify.llm.extract_corpus_parallel(files, backend="gemini")` for semantic extraction instead of dispatching subagents. The default Gemini model is `gemini-3-flash-preview`; set `GRAPHIFY_GEMINI_MODEL` or pass `--model` in headless CLI flows to override it.
> **No other API keys are read.** When `GEMINI_API_KEY`/`GOOGLE_API_KEY` are unset, semantic extraction falls to the host agent itself — the running session is the LLM. On a host that dispatches subagents (e.g. Claude Code), dispatch them as written in Part B. On a host that runs the CLI directly in a terminal and cannot dispatch subagents, do not stall: a code-only corpus has no semantic work, so write the empty semantic file (Part B "Fast path") and continue to Part C; for a corpus with docs/papers/images, either set a Gemini key or extract those inline yourself, but in no case prompt for `ANTHROPIC_API_KEY` — that prompt is a misread of this skill.
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is deterministic and fast; start it while subagents are processing docs/papers.
#### Part A - Structural extraction for code files
For any code files detected, run AST extraction in parallel with Part B subagents:
```powershell
@'
import sys, json
from graphify.extract import collect_files, extract
from pathlib import Path
import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
if code_files:
result = extract(code_files, cache_root=Path('INPUT_PATH'))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'AST: {len(result["nodes"])} nodes, {len(result["edges"])} edges')
else:
Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding="utf-8")
print('No code files - skipping AST extraction')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
#### Part B - Semantic extraction (parallel subagents)
**Fast path:** If detection found zero docs, papers, and images (code-only corpus), skip Part B entirely and go straight to Part C. AST handles code - there is nothing for semantic subagents to do. **First write an empty semantic file** so Part C's merge has its input (it reads `.graphify_semantic.json` unconditionally; without this a code-only run hits `FileNotFoundError`):
```powershell
@'
import json
from pathlib import Path
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.**
Before dispatching subagents, print a timing estimate:
- Load `total_words` and file counts from `graphify-out/.graphify_detect.json`
- Estimate agents needed: `ceil(uncached_non_code_files / 22)` (chunk size is 20-25)
- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents/parallel_limit))
- Print: "Semantic extraction: ~N files → X agents, estimated ~Ys"
**Step B0 - Check extraction cache first**
Before dispatching any subagents, check which files already have cached extraction results:
SPEC_PATH below is the **absolute** path of the `references/extraction-spec.md` that ships beside this SKILL.md — the same file Step B2 loads and hands to every subagent. It is the extraction prompt, so cache entries are attributed to it: when a graphify upgrade changes the prompt, entries produced by the old one are re-extracted instead of replayed, and unchanged prompts keep their entries (#1939). Substitute the real path in both Step B0 and Step B3 — pass the same one to each, and do not drop the argument.
```powershell
@'
import json
from graphify.cache import check_semantic_cache
from pathlib import Path
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
# Only content files go to semantic extraction. Code is already covered structurally
# by the AST pass (Part A); flattening every category here makes subagents re-read
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
# run so Part C never merges a stale .graphify_cached.json (#1392).
if cached_nodes or cached_edges or cached_hyperedges:
Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}, ensure_ascii=False), encoding="utf-8")
else:
Path('graphify-out/.graphify_cached.json').unlink(missing_ok=True)
Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached), encoding="utf-8")
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Only dispatch subagents for files listed in `graphify-out/.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
**Step B1 - Split into chunks**
Load files from `graphify-out/.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted.
**Step B2 - Dispatch ALL subagents in a single message**
Call the Agent tool multiple times IN THE SAME RESPONSE - one call per chunk. This is the only way they run in parallel. If you make one Agent call, wait, then make another, you are doing it sequentially and defeating the purpose.
**IMPORTANT - subagent type:** Always use `subagent_type="general-purpose"`. Do NOT use `Explore` - it is read-only and cannot write chunk files to disk, which silently drops extraction results. General-purpose has Write and Bash access which the subagent needs.
Concrete example for 3 chunks:
```
[Agent tool call 1: files 1-15, subagent_type="general-purpose"]
[Agent tool call 2: files 16-30, subagent_type="general-purpose"]
[Agent tool call 3: files 31-45, subagent_type="general-purpose"]
```
All three in one message. Not three separate messages.
Each subagent receives this exact prompt (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
CHUNK_PATH must be an **absolute** path — derive it before dispatching:
```powershell
$PROJECT_ROOT = (Get-Location).Path # cwd — where Part C globs graphify-out\ (NOT .graphify_root/scan dir, #1392)
# Then for chunk N: $CHUNK_PATH = Join-Path $PROJECT_ROOT "graphify-out\.graphify_chunk_0N.json"
```
Subagent prompt template:
See `references/extraction-spec.md` for the exact subagent prompt (JSON schema, node-ID rules, confidence rubric, frontmatter, hyperedge, and vision rules). Load it only here, only when at least one chunk holds a doc, paper, or image; a pure-code corpus has skipped Part B and never reads it. Pass each subagent that prompt verbatim with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH substituted, and have it write the result to CHUNK_PATH.
**Step B3 - Collect, cache, and merge**
Wait for all subagents. For each result:
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
```powershell
@'
import json, glob
from pathlib import Path
chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
all_nodes, all_edges, all_hyperedges = [], [], []
total_in, total_out = 0, 0
for c in chunks:
d = json.loads(Path(c).read_text(encoding="utf-8"))
all_nodes += d.get('nodes', [])
all_edges += d.get('edges', [])
all_hyperedges += d.get('hyperedges', [])
total_in += d.get('input_tokens', 0)
total_out += d.get('output_tokens', 0)
Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
'input_tokens': total_in, 'output_tokens': total_out,
}, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Save new results to cache. Pass the same SPEC_PATH as Step B0 — it stamps each entry with the prompt that produced it, and a write under a different prompt than the read lands where the next run won't look (#1939):
```powershell
@'
import json
from graphify.cache import save_semantic_cache
from pathlib import Path
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_text(encoding="utf-8").splitlines() if line]
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH')
print(f'Cached {saved} files')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Merge cached + new results into `graphify-out/.graphify_semantic.json`:
```powershell
@'
import json
from pathlib import Path
cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
all_nodes = cached['nodes'] + new.get('nodes', [])
all_edges = cached['edges'] + new.get('edges', [])
all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])
seen = set()
deduped = []
for n in all_nodes:
if n['id'] not in seen:
seen.add(n['id'])
deduped.append(n)
merged = {
'nodes': deduped,
'edges': all_edges,
'hyperedges': all_hyperedges,
'input_tokens': new.get('input_tokens', 0),
'output_tokens': new.get('output_tokens', 0),
}
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached["nodes"])} from cache, {len(new.get("nodes",[]))} new)')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Clean up temp files: `Remove-Item -Force -ErrorAction SilentlyContinue graphify-out\.graphify_cached.json, graphify-out\.graphify_uncached.txt, graphify-out\.graphify_semantic_new.json`
#### Part C - Merge AST + semantic into final extraction
```powershell
@'
import sys, json
from pathlib import Path
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text(encoding="utf-8"))
sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text(encoding="utf-8"))
# Merge: AST nodes first, semantic nodes deduplicated by id
seen = {n['id'] for n in ast['nodes']}
merged_nodes = list(ast['nodes'])
for n in sem['nodes']:
if n['id'] not in seen:
merged_nodes.append(n)
seen.add(n['id'])
merged_edges = ast['edges'] + sem['edges']
merged_hyperedges = sem.get('hyperedges', [])
merged = {
'nodes': merged_nodes,
'edges': merged_edges,
'hyperedges': merged_hyperedges,
'input_tokens': sem.get('input_tokens', 0),
'output_tokens': sem.get('output_tokens', 0),
}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8")
total = len(merged_nodes)
edges = len(merged_edges)
print(f'Merged: {total} nodes, {edges} edges ({len(ast["nodes"])} AST + {len(sem["nodes"])} semantic)')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
```powershell
New-Item -ItemType Directory -Force -Path graphify-out | Out-Null
@'
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from graphify.export import to_json
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
if G.number_of_nodes() == 0:
print('ERROR: Graph is empty - extraction produced no nodes.')
print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
raise SystemExit(1)
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
gods = god_nodes(G)
surprises = surprising_connections(G, communities)
labels = {cid: 'Community ' + str(cid) for cid in communities}
# Placeholder questions - regenerated with real labels in Step 5
questions = suggest_questions(G, communities, labels)
# Export FIRST and honor the #479 shrink-guard: to_json returns False (writing
# nothing) when the new graph is smaller than the existing graph.json. Only write
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
# they never describe a graph that graph.json doesn't contain (#1392).
wrote = to_json(G, communities, 'graphify-out/graph.json')
if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
raise SystemExit(1)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8")
analysis = {
'communities': {str(k): v for k, v in communities.items()},
'cohesion': {str(k): v for k, v in cohesion.items()},
'gods': gods,
'surprises': surprises,
'questions': questions,
}
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
### Step 4.5 - Graph health check (read-only integrity gate)
A non-destructive diagnostic on the extraction, before labeling. It surfaces edge collapse, dangling/missing endpoints, and self-loops — the silent-corruption modes of incremental updates and AST/LLM id mismatches. Read-only; never aborts.
```powershell
@'
import json
from pathlib import Path
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
print(format_diagnostic_report(summary))
flags = [f'{summary[k]} {label}' for k, label in (
('dangling_endpoint_edges', 'dangling-endpoint edges'),
('missing_endpoint_edges', 'missing-endpoint edges'),
('self_loop_edges', 'self-loop edges'),
('directed_same_endpoint_collapsed_edges', 'collapsed (directed) edges'),
('undirected_same_endpoint_collapsed_edges', 'collapsed (undirected) edges'),
) if summary.get(k, 0)]
print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/corrupt.' if flags else 'Graph health: OK (no dangling/missing/collapsed edges).')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
### Step 5 - Label communities
Read `graphify-out/.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
Then regenerate the report and save the labels for the visualizer:
```powershell
@'
import sys, json
from graphify.build import build_from_json
from graphify.cluster import score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from graphify.export import to_json
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding="utf-8"))
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
# LABELS - replace these with the names you chose above
labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding="utf-8")
# Re-export so graph.json nodes carry the curated community_name (#2490).
# Same extraction as Step 4, so the #479 shrink-guard passes on node count;
# if it still refuses, surface the guard message - do not force past it.
wrote = to_json(G, communities, 'graphify-out/graph.json', community_labels=labels)
if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
print('Report updated with community labels')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
**Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was explicitly given** — skip it otherwise, it generates one file per node.
If `--obsidian` was given:
- If `--obsidian-dir <path>` was also given, pass it via `--dir`. Otherwise defaults to `graphify-out/obsidian`.
```powershell
graphify export obsidian
# or with custom dir: graphify export obsidian --dir ~/vaults/my-project
```
Generate the HTML graph (always, unless `--no-viz`):
```powershell
graphify export html # auto-aggregates to community view if graph > 5000 nodes
# or: graphify export html --no-viz
```
### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags)
These run only when their flag is present (`--wiki`, `--neo4j`/`--neo4j-push`, `--falkordb`/`--falkordb-push`, `--svg`, `--graphml`, `--mcp`) or, for the token-reduction benchmark, when `total_words` exceeds 5,000. A default run with no export flags skips all of them. See `references/exports.md` for each one. Run any `--wiki` export before Step 9 cleanup so `.graphify_labels.json` is still available.
---
### Step 9 - Save manifest, update cost tracker, clean up, and report
```powershell
@'
import json
from pathlib import Path
from datetime import datetime, timezone
from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
# root= relativizes the manifest keys to the scan root (same base as the build),
# so the on-disk manifest is portable across clones/machines and a later --update
# matches cached files instead of missing every one (#1417).
#
# Only stamp semantic files (docs/papers/images) that ACTUALLY produced output:
# a detected file whose chunk failed or was omitted must stay unstamped so the
# next --update re-queues it, otherwise it is marked done and its content is lost
# forever (#2015). This mirrors the library extract path exactly
# (cli._stamped_manifest_files + clear_semantic + scan_corpus); do not stamp the
# raw corpus. Code files are always stamped (AST is deterministic); only semantic
# types are gated on output.
from graphify.cli import _stamped_manifest_files
_corpus = detect.get('all_files') or detect['files']
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'))
# Files dispatched this run (the changed subset) but NOT stamped above still carry
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
# them instead of reading them as unchanged (#1948).
_sem_types = ('document', 'paper', 'image')
_dispatched = {f for t, fl in detect['files'].items() if t in _sem_types for f in fl}
_stamped = {f for fl in _manifest_files.values() for f in fl}
_cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus (not the stamp-filtered subset) so in-root
# files newly excluded since last run are dropped rather than masquerading as
# deletions; untouched files' prior rows are still preserved (#1908).
_scan = {f for fl in _corpus.values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
# Update cumulative cost tracker
input_tok = extract.get('input_tokens', 0)
output_tok = extract.get('output_tokens', 0)
cost_path = Path('graphify-out/cost.json')
if cost_path.exists():
cost = json.loads(cost_path.read_text(encoding="utf-8"))
else:
cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}
cost['runs'].append({
'date': datetime.now(timezone.utc).isoformat(),
'input_tokens': input_tok,
'output_tokens': output_tok,
'files': detect.get('total_files', 0),
})
cost['total_input_tokens'] += input_tok
cost['total_output_tokens'] += output_tok
cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost["total_input_tokens"]:,} input, {cost["total_output_tokens"]:,} output ({len(cost["runs"])} runs)')
'@ | & (Get-Content graphify-out\.graphify_python) -
Remove-Item -Force -ErrorAction SilentlyContinue graphify-out\.graphify_detect.json, graphify-out\.graphify_extract.json, graphify-out\.graphify_ast.json, graphify-out\.graphify_semantic.json, graphify-out\.graphify_analysis.json
Get-ChildItem graphify-out -Filter '.graphify_chunk_*.json' -File -ErrorAction SilentlyContinue | Remove-Item -Force
Remove-Item -Force -ErrorAction SilentlyContinue graphify-out\.needs_update
```
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
Tell the user (omit the obsidian line unless --obsidian was given):
```
Graph complete. Outputs in PATH_TO_DIR/graphify-out/
graph.html - interactive graph, open in browser
GRAPH_REPORT.md - audit report
graph.json - raw graph data
obsidian/ - Obsidian vault (only if --obsidian was given)
```
If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
Then paste these sections from GRAPH_REPORT.md directly into the chat:
- God Nodes
- Surprising Connections
- Suggested Questions
Do NOT paste the full report - just those three sections. Keep it concise.
Then immediately offer to explore. Pick the single most interesting suggested question from the report - the one that crosses the most community boundaries or has the most surprising bridge node - and ask:
> "The most interesting question this graph can answer: **[question]**. Want me to trace it?"
If the user says yes, run `/graphify query "[question]"` on the graph and walk them through the answer using the graph structure - which nodes connect, which community boundaries get crossed, what the path reveals. Keep going as long as they want to explore. Each answer should end with a natural follow-up ("this connects to X - want to go deeper?") so the session feels like navigation, not a one-shot report.
The graph is the map. Your job after the pipeline is to be the guide.
---
## Interpreter guard for subcommands
Before running any subcommand below (`--update`, `--cluster-only`, `query`, `path`, `explain`, `add`), check that `.graphify_python` exists. If it's missing (e.g. user deleted `graphify-out/`), re-resolve the interpreter first:
```powershell
if (-not (Test-Path graphify-out\.graphify_python)) {
$GRAPHIFY_PYTHON = $null
$graphifyCmd = Get-Command graphify -ErrorAction SilentlyContinue
if ($graphifyCmd) {
# The interpreter that owns the graphify entry point sits next to it
# (<env>\Scripts\python.exe for uv tool, pipx, and venv installs).
$py = Join-Path (Split-Path $graphifyCmd.Source) "python.exe"
if (Test-Path $py) { $GRAPHIFY_PYTHON = $py }
}
if (-not $GRAPHIFY_PYTHON) { $GRAPHIFY_PYTHON = "python" }
New-Item -ItemType Directory -Force -Path graphify-out | Out-Null
& $GRAPHIFY_PYTHON -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
}
```
## For --update and --cluster-only
Both are non-default subcommands. `--update` re-extracts only new or changed files; `--cluster-only` reruns clustering on the existing graph. See `references/update.md` for both flows.
---
## For /graphify query
When `graphify-out/graph.json` already exists and the user asks a question about the corpus, answer from the graph rather than rebuilding it:
```powershell
graphify query "<question>"
```
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
## For /graphify add and --watch
Neither is part of the default build. When the user runs `/graphify add <url>` to fetch a URL into the corpus, or passes `--watch` to auto-rebuild on file changes, see `references/add-watch.md`.
---
## For the commit hook and native CLAUDE.md integration
When the user asks to install the post-commit auto-rebuild hook or wire graphify into a project's CLAUDE.md, see `references/hooks.md`.
---
## Troubleshooting
### PowerShell 5.1: Vertical scrolling stops working
If vertical scrolling breaks in PowerShell after running graphify, this is caused by ANSI escape sequences from the `graspologic` library. Graphify v0.3.10+ suppresses this output, but if you still see the issue:
1. **Upgrade graphify**: `pip install --upgrade graphifyy`
2. **Use Windows Terminal** instead of the legacy PowerShell console — Windows Terminal handles ANSI codes correctly
3. **Reset your terminal**: close and reopen PowerShell
4. **Skip Leiden**: uninstall its backend (`pip uninstall graspologic` on Python < 3.13, `pip uninstall graspologic-native` on Python 3.13+) and graphify will fall back to NetworkX's built-in Louvain algorithm, which produces no ANSI output
---
## Honesty Rules
- Never invent an edge. If unsure, use AMBIGUOUS.
- Never skip the corpus check warning.
- Always show token cost in the report.
- Never hide cohesion scores behind symbols - show the raw number.
- Never run HTML viz on a graph with more than 5,000 nodes without warning the user.

View file

@ -0,0 +1,56 @@
# graphify reference: add a URL and watch a folder
Load this when the user ran `/graphify add <url>` or passed `--watch`. Neither is part of the default build.
## For /graphify add
Fetch a URL and add it to the corpus, then update the graph.
```bash
$(cat graphify-out/.graphify_python) -c "
import sys
from graphify.ingest import ingest
from pathlib import Path
try:
out = ingest('URL', Path('./raw'), author='AUTHOR', contributor='CONTRIBUTOR')
print(f'Saved to {out}')
except ValueError as e:
print(f'error: {e}', file=sys.stderr)
sys.exit(1)
except RuntimeError as e:
print(f'error: {e}', file=sys.stderr)
sys.exit(1)
"
```
Replace `URL` with the actual URL, `AUTHOR` with the user's name if provided, `CONTRIBUTOR` likewise. If the command exits with an error, tell the user what went wrong - do not silently continue. After a successful save, automatically run the `--update` pipeline on `./raw` to merge the new file into the existing graph.
Supported URL types (auto-detected):
- YouTube / any video URL → audio downloaded via yt-dlp, transcribed to `.txt` on next run (requires `pip install 'graphifyy[video]'`)
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
- arXiv → abstract + metadata saved as `.md`
- PDF → downloaded as `.pdf`
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
- Any webpage → converted to markdown via html2text
---
## For --watch
Start a background watcher that monitors a folder and auto-updates the graph when files change.
```bash
$(cat graphify-out/.graphify_python) -m graphify.watch "$(cat graphify-out/.graphify_root)" --debounce 3
```
This watches the same folder graphify extracted, read from the trusted `graphify-out/.graphify_root` that Step 1 resolved - there is no path to substitute, so a scan root containing shell metacharacters can never be re-interpreted here. Behavior depends on what changed:
- **Code files only (.py, .ts, .go, etc.):** re-runs AST extraction + rebuild + cluster immediately, no LLM needed. `graph.json` and `GRAPH_REPORT.md` are updated automatically.
- **Docs, papers, or images:** writes a `graphify-out/needs_update` flag and prints a notification to run `/graphify --update` (LLM semantic re-extraction required).
Debounce (default 3s): waits until file activity stops before triggering, so a wave of parallel agent writes doesn't trigger a rebuild per file.
Press Ctrl+C to stop.
For agentic workflows: run `--watch` in a background terminal. Code changes from agent waves are picked up automatically between waves. If agents are also writing docs or notes, you'll need a manual `/graphify --update` after those waves.

View file

@ -0,0 +1,87 @@
# graphify reference: extra exports and benchmark
Load this when the user passed one of the export flags (`--wiki`, `--neo4j`, `--neo4j-push`, `--falkordb`, `--falkordb-push`, `--svg`, `--graphml`, `--mcp`), or when the corpus is large enough for the token-reduction benchmark. Each step runs only for its own flag.
### Step 6b - Wiki (only if --wiki flag)
**Only run this step if `--wiki` was explicitly given in the original command.**
Run this before Step 9 (cleanup) so `.graphify_labels.json` is still available.
```bash
graphify export wiki
```
### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag)
**If `--neo4j`** - generate a Cypher file for manual import:
```bash
graphify export neo4j
```
**If `--neo4j-push <uri>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:
```bash
graphify export neo4j --push bolt://localhost:7687 --user neo4j --password PASSWORD
```
Default URI is `bolt://localhost:7687`, default user is `neo4j`. Uses MERGE - safe to re-run without creating duplicates.
### Step 7a - FalkorDB export (only if --falkordb or --falkordb-push flag)
**If `--falkordb`** - generate a Cypher file. The statements are OpenCypher, but FalkorDB's `GRAPH.QUERY` runs one statement at a time (no bulk script import like Neo4j's `cypher-shell`), so prefer `--falkordb-push` to load a graph. Use this only when you want the portable `cypher.txt` artifact:
```bash
graphify export falkordb
```
**If `--falkordb-push <uri>`** - push directly to a running FalkorDB instance. Credentials are optional; ask the user only if the instance requires auth:
```bash
graphify export falkordb --push falkordb://localhost:6379
```
Default URI is `falkordb://localhost:6379` (the scheme is informational - `redis://` or a bare `host:port` work too), auth is optional, and the target graph defaults to `graphify`. Uses MERGE - safe to re-run without creating duplicates.
### Step 7b - SVG export (only if --svg flag)
```bash
graphify export svg
```
### Step 7c - GraphML export (only if --graphml flag)
```bash
graphify export graphml
```
### Step 7d - MCP server (only if --mcp flag)
```bash
$(cat graphify-out/.graphify_python) -m graphify.serve graphify-out/graph.json
```
This starts a stdio MCP server that exposes tools: `query_graph`, `get_node`, `get_neighbors`, `get_community`, `god_nodes`, `graph_stats`, `shortest_path`. Add to Claude Desktop or any MCP-compatible agent orchestrator so other agents can query the graph live.
To configure in Claude Desktop, add to `claude_desktop_config.json`. Claude Desktop can't run `$(...)`, and under `uv tool install` the system `python3` can't import graphify — so set `command` to the **absolute interpreter path** printed by `cat graphify-out/.graphify_python`:
```json
{
"mcpServers": {
"graphify": {
"command": "<absolute path from: cat graphify-out/.graphify_python>",
"args": ["-m", "graphify.serve", "/absolute/path/to/graphify-out/graph.json"]
}
}
}
```
### Step 8 - Token reduction benchmark (only if total_words > 5000)
If `total_words` from `graphify-out/.graphify_detect.json` is greater than 5,000, run:
```bash
graphify benchmark
```
Print the output directly in chat. If `total_words <= 5000`, skip silently - the graph value is structural clarity, not token compression, for small corpora.

View file

@ -0,0 +1,70 @@
# graphify reference: extraction subagent prompt
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
```
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
Output ONLY valid JSON matching the schema below - no explanation, no markdown fences, no preamble.
Files (chunk CHUNK_NUM of TOTAL_CHUNKS):
FILE_LIST
Rules:
- EXTRACTED: relationship explicit in source (import, call, citation, "see §3.2")
- INFERRED: reasonable inference (shared data structure, implied dependency)
- AMBIGUOUS: uncertain - flag for review, do not omit
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
Do not re-extract imports - AST already has those.
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). `file_type` MUST be one of exactly these six values: `code`, `document`, `paper`, `image`, `rationale`, `concept`. Any other value is invalid and will be rejected.
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction. `calls` edges MUST stay within one language: a Python function cannot `calls` a JS/TS/Go/Rust/Java symbol and vice versa — cross-language call edges are phantom artifacts, never emit them.
Image files: use vision to understand what the image IS - do not just OCR.
UI screenshot: layout patterns, design decisions, key elements, purpose.
Chart: metric, trend/insight, data source.
Tweet/post: claim as node, author, concepts mentioned.
Diagram: components and connections.
Research figure: what it demonstrates, method, result.
Handwritten/whiteboard: ideas and arrows, mark uncertain readings AMBIGUOUS.
DEEP_MODE (if --mode deep was given): be aggressive with INFERRED edges - indirect deps,
shared assumptions, latent couplings. Mark uncertain ones AMBIGUOUS instead of omitting.
Semantic similarity: if two concepts in this chunk solve the same problem or represent the same idea without any structural link (no import, no call, no citation), add a `semantically_similar_to` edge marked INFERRED with a confidence_score reflecting how similar they are (0.6-0.95). Examples:
- Two functions that both validate user input but never call each other
- A class in code and a concept in a paper that describe the same algorithm
- Two error types that handle the same failure mode differently
Only add these when the similarity is genuinely non-obvious and cross-cutting. Do not add them for trivially similar things.
Hyperedges: if 3 or more nodes clearly participate together in a shared concept, flow, or pattern that is not captured by pairwise edges alone, add a hyperedge to a top-level `hyperedges` array. Examples:
- All classes that implement a common protocol or interface
- All functions in an authentication flow (even if they don't all call each other)
- All concepts from a paper section that form one coherent idea
Use sparingly — only when the group relationship adds information beyond the pairwise edges. Maximum 3 hyperedges per chunk.
If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author,
contributor onto every node from that file.
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
- EXTRACTED edges: confidence_score = 1.0 always
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
0.95 direct structural evidence (shared data structure, named cross-file reference).
0.85 strong inference (clear functional alignment, no direct symbol link).
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
0.65 weak inference (thematically related, no shape evidence).
0.55 speculative but plausible (surface-level co-occurrence only).
Models follow discrete rubrics better than continuous ranges; the bimodal
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
range guidance is being collapsed to a binary. If no value above fits, mark
the edge AMBIGUOUS rather than picking 0.4 or below.
- AMBIGUOUS edges: 0.1-0.3
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0}
source_file RULE (every node, edge, and hyperedge): set source_file to the path of the originating file EXACTLY as it appears in FILE_LIST — verbatim and absolute. Do NOT shorten to a basename, do NOT re-relativize, do NOT strip any directory prefix, and do NOT change separators (the engine canonicalizes separators and relativizes against the build root downstream). Copy the FILE_LIST entry character-for-character. This keeps the full build and incremental --update on the same base, so build_merge's replace-on-re-extract matches the existing node instead of accumulating a duplicate.
Then write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost):
CHUNK_PATH
```

View file

@ -0,0 +1,46 @@
# graphify reference: GitHub clone and cross-repo merge
Load this when the user passed one or more `https://github.com/...` URLs, or named several local subfolders to merge into one graph.
### Step 0 - Clone GitHub repo(s) (only if a GitHub URL was given)
**Single repo:**
```bash
LOCAL_PATH=$(graphify clone <github-url> [--branch <branch>])
# Use LOCAL_PATH as the target for all subsequent steps
```
**Multiple repos (cross-repo graph):**
```bash
# Clone each repo, run the full pipeline on each, then merge
graphify clone <url1> # → ~/.graphify/repos/<owner1>/<repo1>
graphify clone <url2> # → ~/.graphify/repos/<owner2>/<repo2>
# Run /graphify on each local path to produce their graph.json files
# Then merge:
graphify merge-graphs \
~/.graphify/repos/<owner1>/<repo1>/graphify-out/graph.json \
~/.graphify/repos/<owner2>/<repo2>/graphify-out/graph.json \
--out graphify-out/cross-repo-graph.json
```
Graphify clones into `~/.graphify/repos/<owner>/<repo>` and reuses existing clones on repeat runs. Each node in the merged graph carries a `repo` attribute so you can filter by origin.
**Multiple local subfolders (monorepo or multi-service layout):**
The skill pipeline writes all intermediate and final outputs to `graphify-out/` in the current working directory. Running the skill on each subfolder separately will clobber the same output dir. Instead, use the CLI directly for each subfolder — it places `graphify-out/` *inside* the scanned path:
```bash
graphify extract ./core/ # → ./core/graphify-out/graph.json
graphify extract ./service/ # → ./service/graphify-out/graph.json
graphify extract ./platform/ # → ./platform/graphify-out/graph.json
# Add --backend gemini|kimi|openai|deepseek|claude-cli depending on which API key you have set
# Then merge at the project root:
graphify merge-graphs \
./core/graphify-out/graph.json \
./service/graphify-out/graph.json \
./platform/graphify-out/graph.json \
--out graphify-out/graph.json
```
Once `graphify-out/graph.json` exists, the fast path above takes over: any codebase question runs `graphify query` directly on the merged graph — no re-extraction, no size gate.

View file

@ -0,0 +1,33 @@
# graphify reference: commit hook and native CLAUDE.md integration
Load this when the user asked to install the post-commit hook or wire graphify into a project's CLAUDE.md.
## For git commit hook
Install a post-commit hook that auto-rebuilds the graph after every commit. No background process needed - triggers once per commit, works with any editor.
```bash
graphify hook install # install
graphify hook uninstall # remove
graphify hook status # check
```
After every `git commit`, the hook detects which code files changed (via `git diff HEAD~1`), re-runs AST extraction on those files, and rebuilds `graph.json` and `GRAPH_REPORT.md`. Doc/image changes are ignored by the hook - run `/graphify --update` manually for those.
If a post-commit hook already exists, graphify appends to it rather than replacing it.
---
## For native CLAUDE.md integration
Run once per project to make graphify always-on in Claude Code sessions:
```bash
graphify claude install
```
This writes a `## graphify` section to the local `CLAUDE.md` that instructs Claude to check the graph before answering codebase questions and rebuild it after code changes. No manual `/graphify` needed in future sessions.
```bash
graphify claude uninstall # remove the section
```

View file

@ -0,0 +1,311 @@
# graphify reference: query, path, explain
Load this when the user asks a question against an existing graph, or runs `/graphify path` or `/graphify explain`. The core's query stub points here for the full traversal flow. These flows use the `graphify query` CLI when it is available and fall back to an inline NetworkX traversal otherwise.
Two traversal modes - choose based on the question:
| Mode | Flag | Best for |
|------|------|----------|
| BFS (default) | _(none)_ | "What is X connected to?" - broad context, nearest neighbors first |
| DFS | `--dfs` | "How does X reach Y?" - trace a specific chain or dependency path |
First check the graph exists:
```bash
$(cat graphify-out/.graphify_python) -c "
from pathlib import Path
if not Path('graphify-out/graph.json').exists():
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
raise SystemExit(1)
"
```
If it fails, stop and tell the user to run `/graphify <path>` first.
### Step 0 — Constrained query expansion (REQUIRED before traversal)
graphify's `query` CLI matches nodes via case-folded substring + IDF — there is **no stemming, no synonyms, no cross-language match** inside the binary, and the inline fallback below matches the same way. If the user's question uses different language or different domain vocabulary than the graph's labels (user says "обработчик" / graph says "handler"; user says "authentication" / graph says "Guardian"), the literal matcher returns 0 hits and the answer collapses to noise.
Fix this **without inventing tokens** by expanding the query against the actual graph vocabulary first:
1. Extract the token vocabulary from node labels:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, re
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8'))
vocab = set()
for n in data['nodes']:
for c in re.findall(r'[^\W\d_]+', n.get('label','') or '', re.UNICODE):
parts = re.findall(r'[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+', c) or [c]
for p in parts:
t = p.lower()
if 3 <= len(t) <= 30:
vocab.add(t)
Path('graphify-out/.vocab.txt').write_text('\n'.join(sorted(vocab)), encoding='utf-8')
print(f'vocab: {len(vocab)} tokens')
"
```
2. Read `graphify-out/.vocab.txt`. Then for the user's question, select **up to 12 tokens from this exact list** that semantically match the query intent. Hard constraints:
- You MUST pick only tokens present in the vocabulary file. Do NOT invent tokens.
- If a query concept has no plausible token in the vocab, skip it — do not substitute a near-synonym from training memory.
- If **no** vocab tokens match the query at all, output an empty list and tell the user the corpus has no relevant vocabulary for this question. Do not fabricate a search.
- Translate cross-language: Russian "аутентификация" → look for `auth`, `credential`, `token`, `security` IFF present in vocab.
- Morphology: "handlers" maps to `handler` IFF present; "todos" maps to `todo` IFF present.
3. Print the selection explicitly to the user before running the query, so the expansion is auditable:
```
Query expanded to (from graph vocab, N tokens): [token1, token2, ...]
```
If the list is empty, say so plainly and stop — do not proceed to traversal.
### Step 1 — Traversal
Build the **expanded query string** by joining the selected tokens with spaces. Use this string as `QUESTION` below — NOT the original user question. (The original question is preserved only for `save-result` at the end.)
Prefer the CLI when it is installed:
```bash
graphify query "QUESTION"
# or: graphify query "QUESTION" --dfs --budget 3000
```
If the CLI is unavailable, load `graphify-out/graph.json` and run the traversal inline:
1. Find the 1-3 nodes whose label best matches the expanded tokens.
2. Run the appropriate traversal from each starting node.
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
5. If the graph lacks enough information, say so - do not hallucinate edges.
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from networkx.readwrite import json_graph
import networkx as nx
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8'))
G = json_graph.node_link_graph(data, edges='links')
question = 'QUESTION'
mode = 'MODE' # 'bfs' or 'dfs'
terms = [t.lower() for t in question.split() if len(t) >= 3] # match the vocab threshold; keeps api/jwt/ios (#1392)
# Find best-matching start nodes
scored = []
for nid, ndata in G.nodes(data=True):
label = ndata.get('label', '').lower()
score = sum(1 for t in terms if t in label)
if score > 0:
scored.append((score, nid))
scored.sort(reverse=True)
start_nodes = [nid for _, nid in scored[:3]]
if not start_nodes:
print('No matching nodes found for query terms:', terms)
sys.exit(0)
subgraph_nodes = set()
subgraph_edges = []
if mode == 'dfs':
# DFS: follow one path as deep as possible before backtracking.
# Depth-limited to 6 to avoid traversing the whole graph.
visited = set()
stack = [(n, 0) for n in reversed(start_nodes)]
while stack:
node, depth = stack.pop()
if node in visited or depth > 6:
continue
visited.add(node)
subgraph_nodes.add(node)
for neighbor in G.neighbors(node):
if neighbor not in visited:
stack.append((neighbor, depth + 1))
subgraph_edges.append((node, neighbor))
else:
# BFS: explore all neighbors layer by layer up to depth 3.
frontier = set(start_nodes)
subgraph_nodes = set(start_nodes)
for _ in range(3):
next_frontier = set()
for n in frontier:
for neighbor in G.neighbors(n):
if neighbor not in subgraph_nodes:
next_frontier.add(neighbor)
subgraph_edges.append((n, neighbor))
subgraph_nodes.update(next_frontier)
frontier = next_frontier
# Token-budget aware output: rank by relevance, cut at budget (~4 chars/token)
token_budget = BUDGET # default 2000
char_budget = token_budget * 4
# Score each node by term overlap for ranked output
def relevance(nid):
label = G.nodes[nid].get('label', '').lower()
return sum(1 for t in terms if t in label)
ranked_nodes = sorted(subgraph_nodes, key=relevance, reverse=True)
lines = [f'Traversal: {mode.upper()} | Start: {[G.nodes[n].get(\"label\",n) for n in start_nodes]} | {len(subgraph_nodes)} nodes']
for nid in ranked_nodes:
d = G.nodes[nid]
lines.append(f' NODE {d.get(\"label\", nid)} [src={d.get(\"source_file\",\"\")} loc={d.get(\"source_location\",\"\")}]')
for u, v in subgraph_edges:
if u in subgraph_nodes and v in subgraph_nodes:
_raw = G[u][v]; d = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
lines.append(f' EDGE {G.nodes[u].get(\"label\",u)} --{d.get(\"relation\",\"\")} [{d.get(\"confidence\",\"\")}]--> {G.nodes[v].get(\"label\",v)}')
output = '\n'.join(lines)
if len(output) > char_budget:
output = output[:char_budget] + f'\n... (truncated at ~{token_budget} token budget - use --budget N for more)'
print(output)
"
```
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "ORIGINAL_QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
```
Replace `ORIGINAL_QUESTION` with the user's verbatim question, `ANSWER` with your full answer text (containing the expanded-token trace), `NODE1 NODE2` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
**Work memory (self-improving loop).** Add an `--outcome` so future sessions learn from this one — append `--outcome useful|dead_end|corrected` to the `save-result` command (and `--correction "the right answer"` when correcting):
- `useful` — the cited nodes answered the question well (they become *preferred sources*).
- `dead_end` — the question/path led nowhere; don't re-derive it next time.
- `corrected` — the saved answer was wrong; `--correction` records what was right.
At the **start** of graph work, refresh and read the lessons: run `graphify reflect --if-stale` (cheap, deterministic, no LLM; `--if-stale` makes it a no-op when `LESSONS.md` is already newer than every input, e.g. when the git hook just refreshed it), then read `graphify-out/reflections/LESSONS.md`. It lists **preferred sources** (start there), **known dead ends** (skip them), and prior **corrections**. Running `reflect` yourself keeps the lessons current even without the git hook installed; if the post-commit hook *is* installed, `--if-stale` means your session-start run costs almost nothing.
---
## For /graphify path
Find the shortest path between two named concepts in the graph. Prefer the CLI when installed:
```bash
graphify path "NODE_A" "NODE_B"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8'))
G = json_graph.node_link_graph(data, edges='links')
a_term = 'NODE_A'
b_term = 'NODE_B'
def find_node(term):
term = term.lower()
scored = sorted(
[(sum(1 for w in term.split() if w in G.nodes[n].get('label','').lower()), n)
for n in G.nodes()],
reverse=True
)
return scored[0][1] if scored and scored[0][0] > 0 else None
src = find_node(a_term)
tgt = find_node(b_term)
if not src or not tgt:
print(f'Could not find nodes matching: {a_term!r} or {b_term!r}')
sys.exit(0)
try:
path = nx.shortest_path(G, src, tgt)
print(f'Shortest path ({len(path)-1} hops):')
for i, nid in enumerate(path):
label = G.nodes[nid].get('label', nid)
if i < len(path) - 1:
_raw = G[nid][path[i+1]]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
print(f' {label} --{rel}--> [{conf}]')
else:
print(f' {label}')
except nx.NetworkXNoPath:
print(f'No path found between {a_term!r} and {b_term!r}')
except nx.NodeNotFound as e:
print(f'Node not found: {e}')
"
```
Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then explain the path in plain language - what each hop means, why it's significant.
After writing the explanation, save it back:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B
```
---
## For /graphify explain
Give a plain-language explanation of a single node - everything connected to it. Prefer the CLI when installed:
```bash
graphify explain "NODE_NAME"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8'))
G = json_graph.node_link_graph(data, edges='links')
term = 'NODE_NAME'
term_lower = term.lower()
# Find best matching node
scored = sorted(
[(sum(1 for w in term_lower.split() if w in G.nodes[n].get('label','').lower()), n)
for n in G.nodes()],
reverse=True
)
if not scored or scored[0][0] == 0:
print(f'No node matching {term!r}')
sys.exit(0)
nid = scored[0][1]
data_n = G.nodes[nid]
print(f'NODE: {data_n.get(\"label\", nid)}')
print(f' source: {data_n.get(\"source_file\",\"unknown\")}')
print(f' type: {data_n.get(\"file_type\",\"unknown\")}')
print(f' degree: {G.degree(nid)}')
print()
print('CONNECTIONS:')
for neighbor in G.neighbors(nid):
_raw = G[nid][neighbor]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
nlabel = G.nodes[neighbor].get('label', neighbor)
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
src_file = G.nodes[neighbor].get('source_file', '')
print(f' --{rel}--> {nlabel} [{conf}] ({src_file})')
"
```
Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sentence explanation of what this node is, what it connects to, and why those connections are significant. Use the source locations as citations.
After writing the explanation, save it back:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
```

View file

@ -0,0 +1,52 @@
# graphify reference: transcribe video and audio
Load this only when `detect` reported one or more `video` files. A corpus with no video never reads this.
### Step 2.5 - Transcribe video / audio files (only if video files detected)
Skip this step entirely if `detect` returned zero `video` files.
Video and audio files cannot be read directly. Transcribe them to text first, then treat the transcripts as doc files in Step 3.
**Strategy:** Read the god nodes from `graphify-out/.graphify_detect.json` (or the analysis file if it exists from a previous run). You are already a language model — write a one-sentence domain hint yourself from those labels. Then pass it to Whisper as the initial prompt. No separate API call needed.
**However**, if the corpus has *only* video files and no other docs/code, use the generic fallback prompt: `"Use proper punctuation and paragraph breaks."`
**Step 1 - Write the Whisper prompt yourself.**
Read the top god node labels from detect output or analysis, then compose a short domain hint sentence, for example:
- Labels: `transformer, attention, encoder, decoder` → `"Machine learning research on transformer architectures and attention mechanisms. Use proper punctuation and paragraph breaks."`
- Labels: `kubernetes, deployment, pod, helm` → `"DevOps discussion about Kubernetes deployments and Helm charts. Use proper punctuation and paragraph breaks."`
**Export** it as `GRAPHIFY_WHISPER_PROMPT` (the exact name the transcriber reads — and it must be `export`ed so the child Python process sees it) for the next command.
**Step 2 - Transcribe:**
```bash
export GRAPHIFY_WHISPER_MODEL=base # or whatever --whisper-model the user passed (must be exported)
export GRAPHIFY_WHISPER_PROMPT="<the one-sentence domain hint you composed in Step 1>"
$(cat graphify-out/.graphify_python) -c "
import json, os, sys
from pathlib import Path
from graphify.transcribe import transcribe_all
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
video_files = detect.get('files', {}).get('video', [])
prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')
transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
# Write the JSON from Python (NOT a shell '>' redirect): transcribe_all/Whisper
# print progress to stdout, which would otherwise corrupt the JSON file (#1392).
Path('graphify-out/.graphify_transcripts.json').write_text(json.dumps(transcript_paths, ensure_ascii=False), encoding=\"utf-8\")
print(f'Transcribed {len(transcript_paths)} file(s)', file=sys.stderr)
"
```
After transcription:
- Read the transcript paths from `graphify-out/.graphify_transcripts.json`
- Add them to the docs list before dispatching semantic subagents in Step 3B
- Print how many transcripts were created: `Transcribed N video file(s) -> treating as docs`
- If transcription fails for a file, print a warning and continue with the rest
**Whisper model:** Default is `base`. If the user passed `--whisper-model <name>`, `export GRAPHIFY_WHISPER_MODEL=<name>` (it must be exported, not just assigned) before running the command above.

View file

@ -0,0 +1,210 @@
# graphify reference: incremental update and cluster-only
Load this only when the user passed `--update` or `--cluster-only`. A first-time full build never reads this file.
## For --update (incremental re-extraction)
Use when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time.
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.detect import detect_incremental, save_manifest
from pathlib import Path
result = detect_incremental(Path('INPUT_PATH'))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2, ensure_ascii=False))
Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
deleted = list(result.get('deleted_files', []))
if new_total == 0 and not deleted:
print('No files changed since last run. Nothing to update.')
raise SystemExit(0)
if deleted:
print(f'{len(deleted)} deleted file(s) to prune.')
if new_total > 0:
print(f'{new_total} new/changed file(s) to re-extract.')
"
```
Then populate `.graphify_detect.json` so Steps 3A–6 (which read it unconditionally) see the right state for an incremental run. `files` carries the changed subset (drives Step 3A AST + Step 3B0 cache check on only what changed); `all_files` carries the full corpus for any step that needs corpus-wide context:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
r = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
Path('graphify-out/.graphify_detect.json').write_text(json.dumps({
'files': r.get('new_files', {}),
'all_files': r.get('files', {}),
'total_files': r.get('new_total', 0),
'total_words': r.get('total_words', 0),
'skipped_sensitive': r.get('skipped_sensitive', []),
'needs_graph': True,
}, ensure_ascii=False), encoding=\"utf-8\")
"
```
If new files exist, first check whether all changed files are code files:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
result = json.loads(open('graphify-out/.graphify_incremental.json', encoding='utf-8').read()) if Path('graphify-out/.graphify_incremental.json').exists() else {}
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc','.f','.F','.f90','.F90','.f95','.F95','.f03','.F03','.f08','.F08'}
new_files = result.get('new_files', {})
all_changed = [f for files in new_files.values() for f in files]
code_only = all(Path(f).suffix.lower() in code_exts for f in all_changed)
print('code_only:', code_only)
"
```
If `code_only` is True: print `[graphify update] Code-only changes detected - skipping semantic extraction (no LLM needed)`, run only Step 3A (AST) on the changed files, skip Step 3B entirely (no subagents), then go straight to merge and Steps 4–8.
If `code_only` is False (any changed file is a doc/paper/image/video): **first, if any changed file is in `new_files['video']`, run `references/transcribe.md` (Step 2.5) on those files, then rewrite `.graphify_detect.json` to move the resulting transcript paths into `files['document']` and drop `files['video']`** — otherwise raw `.mp4/.mp3` paths are fed to semantic subagents as unreadable media (#1392). Then run the full Steps 3A–3C pipeline as normal.
If no new files exist (only deletions), create an empty extraction so the merge step can prune:
```bash
if [ ! -f graphify-out/.graphify_extract.json ]; then
echo '[graphify update] Only deletions -- creating empty extraction for merge.'
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
Path('graphify-out/.graphify_extract.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
"
fi
```
Then:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
from graphify.build import build_merge
from graphify.detect import save_manifest
# Load new extraction and incremental state
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
deleted = list(incremental.get('deleted_files', []))
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
# new_chunks is dropped from the base before merge, so old/stale nodes don't survive.
# Do NOT add `changed` here: with root= passed, prune_set relativizes to the same base
# as the freshly merged nodes and would DELETE the re-extracted content (#1178 is moot
# now that replace — not the dedup pass — reconciles changed files).
prune = list(deleted) or None
# Use build_merge() — reads graph.json directly without NetworkX round-trip
# so edge direction (calls, implements, imports) is always preserved (#801).
# Pass root= so prune_sources (absolute paths from detect_incremental) are
# relativized to match the graph's relative source_file values; without it
# nothing is pruned and stale nodes accumulate on every update (#1361).
# directed=IS_DIRECTED: replace IS_DIRECTED with True if --directed was given, else
# False. Without it a --directed --update silently rebuilds undirected and collapses
# reciprocal A<->B edges (#1392).
G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
directed=IS_DIRECTED,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
# Write merged result back to .graphify_extract.json so Step 4 sees the full graph
merged_out = {
'nodes': [{'id': n, **d} for n, d in G.nodes(data=True)],
'edges': [
# Explicit source/target last so they win over any stale attrs in d.
{**{k: val for k, val in d.items() if k not in ('_src', '_tgt', 'source', 'target')},
'source': d.get('_src', u), 'target': d.get('_tgt', v)}
for u, v, d in G.edges(data=True)
],
# G.graph["hyperedges"] holds hyperedges from both existing graph.json
# and new_extraction (build_merge combines them). Falling back to
# new_extraction only would silently drop prior-run hyperedges (#801).
'hyperedges': list(G.graph.get('hyperedges', [])),
'input_tokens': new_extraction.get('input_tokens', 0),
'output_tokens': new_extraction.get('output_tokens', 0),
}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged_out, ensure_ascii=False), encoding=\"utf-8\")
print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])} nodes, {len(merged_out[\"edges\"])} edges)')
# Save manifest so next --update diffs against today's state, not the
# prior run's baseline (prevents ghost-node reports on subsequent updates).
# root= matches the build_merge call above so the manifest keys stay relative to
# the scan root — portable across clones/machines, so --update keeps matching
# cached files instead of missing every one after a move (#1417).
#
# Only stamp semantic files (docs/papers/images) that ACTUALLY produced output
# THIS run (new_extraction is this run's fresh extraction, read above before the
# merge overwrote the file): a changed doc whose chunk failed must stay unstamped
# so the next --update re-queues it, otherwise it is marked done and its content
# is lost forever (#2015). Mirrors the library extract path
# (cli._stamped_manifest_files + clear_semantic + scan_corpus).
from graphify.cli import _stamped_manifest_files
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'))
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
_sem_types = ('document', 'paper', 'image')
_dispatched = {f for t, fl in incremental.get('new_files', {}).items() if t in _sem_types for f in fl}
_stamped = {f for fl in _manifest_files.values() for f in fl}
_cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
_scan = {f for fl in incremental['files'].values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
print('[graphify update] Manifest saved.')
"
```
Then run Steps 4–8 on the merged graph as normal.
After Step 4, show the graph diff:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.analyze import graph_diff
from graphify.build import build_from_json
from networkx.readwrite import json_graph
import networkx as nx
from pathlib import Path
# Load old graph (before update) from backup written before merge
old_data = json.loads(Path('graphify-out/.graphify_old.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_old.json').exists() else None
new_extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
G_new = build_from_json(new_extract, directed=IS_DIRECTED)
if old_data:
G_old = json_graph.node_link_graph(old_data, edges='links')
diff = graph_diff(G_old, G_new)
print(diff['summary'])
if diff['new_nodes']:
print('New nodes:', ', '.join(n['label'] for n in diff['new_nodes'][:5]))
if diff['new_edges']:
print('New edges:', len(diff['new_edges']))
"
```
Before the merge step, save the old graph: `cp graphify-out/graph.json graphify-out/.graphify_old.json`
Clean up after: `rm -f graphify-out/.graphify_old.json`
---
## For --cluster-only
Skip Steps 1–3. Re-run clustering on the existing graph:
```bash
graphify cluster-only .
```
`graphify cluster-only .` is **self-contained**: it re-clusters, names communities, and regenerates `GRAPH_REPORT.md`, `graph.json`, and `graph.html` from the existing graph. **Do not re-run Steps 5–9** — they read intermediate files (`.graphify_extract.json`, `.graphify_detect.json`, `.graphify_analysis.json`) that a prior build's cleanup (Step 9) already deleted, so they raise `FileNotFoundError` (#1392). When it finishes, present the refreshed `GRAPH_REPORT.md` summary as usual.

4
.gitignore vendored
View file

@ -31,4 +31,6 @@ server/uploads/
server/clips/
# skills
graphify-out/
graphify-out/
# skill links into .agents/skills (installed from skills-lock.json)
.claude/skills/design-taste-frontend

View file

@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
# NGU-Web
Website for NGU (Next Generation of Unity), a Unity movement organization with regional chapters in the US and internationally. Full-stack app with a public site and a role-based admin panel.
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/`)
@ -22,7 +22,7 @@ Backend (`server/`, Node >= 22.13). The server reads `HOST` (default `127.0.0.1`
- `DB_PATH=./dev.db pnpm dev`: run with `node --watch`
- `DB_PATH=./dev.db pnpm migrate`: apply migrations without starting the server
- `DB_PATH=./dev.db node src/admin-cli.js add|list|passwd|role|disable|enable ...`: the only way accounts are created
- `DB_PATH=./dev.db node src/seed-showcase.js [--listed]`: writes fully filled test records (a region, chapter, team, award, person, three events and a blog post with every content block type), ids starting `showcase-`, for checking pages. Unlisted unless `--listed`. Refuses a database under /var/lib/ngu unless `--production` is also given.
- `DB_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 starting `showcase-`, for checking pages. Unlisted unless `--listed`. Refuses a database under /var/lib/ngu unless `--production` is also given.
In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API must listen on that port.
@ -32,10 +32,18 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
- Debugging: check `journalctl -u ngu-api -n 40 --no-pager` first. 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 in `docs/media-uploads.md`.
- Analytics: self-hosted Plausible, proxied by nginx at `/pa/`. The API adds its script to every page (`analyticsTag` in `server/src/pageMeta.js`), counting under the hostname of `site.json`'s `url`, so each deployment reports as itself. Nothing in `index.html` or the app. Daily and weekly reports go to Discord when Panel → Site settings → Reports turns them on and `PLAUSIBLE_API_KEY` and `DISCORD_WEBHOOK_URL` are 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 reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html), with Panel → Site settings (the `site_settings` table) laid over site.json, and serves `/robots.txt` from 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`.
- Present remote: a presenting screen (`/events/:id/present`) shows a code; a phone at `/remote/<code>` steps, pauses, jumps and changes its setup, anyone with the code (`server/src/routes/present.js`, `src/pages/PresentRemote.tsx`). Server-sent events held in memory (one process); the API sends `X-Accel-Buffering: no`, so nginx needs no block of its own.
- 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`, then `fc-cache`) or it falls back to a plain sans. The social bar's icons are static files in `public/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/docx` with 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.webp` small copy made at upload and at boot: `docs/performance.md`.
- Security headers: the API sends them (Hono `secureHeaders()`, plus a CSRF check on `/api` writes); nginx sends HSTS on everything and must pass `Host` and `X-Forwarded-For` to the API: `docs/security-headers.md`.
- Google sign-in for @nextgenerationofunity.org admin accounts: on when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set on the service. Only existing accounts (made by admin-cli) get in; passwords still work. Setup: `docs/google-sign-in.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 with `files: true` pick from it ("Choose a file"), and link cards take its first-page preview. Needs a `/api/admin/files` nginx block (51m). Off until `GOOGLE_SERVICE_ACCOUNT` plus `GOOGLE_SHARED_DRIVE` (the bare id, not a URL) / `GOOGLE_MAIL_FROM` are 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 the `v_people_public` view, never `people`. Discord linking is off until `DISCORD_CLIENT_ID` and `DISCORD_CLIENT_SECRET` are set: `docs/profile-accounts.md`.
- Planning Center (migration 085): Data → Planning Center compares a Planning Center People list (Site settings → Planning Center) with the site's people and applies what an admin picks: link (`people.pco_id`), update the name and private email and phone, or add unpublished. Off until `PCO_APP_ID` and `PCO_SECRET` are set: `docs/planning-center.md`.
- Google sign-in for @nextgenerationofunity.org admin accounts: on when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set on the service. Accounts made by admin-cli get in; with access groups set (Site settings → Access, plus `GOOGLE_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`.
@ -56,32 +64,38 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
- All pages use `PageShell.tsx` as the wrapper unless explicitly noted otherwise.
- Pages live in `src/pages/`; section-level components go in `src/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 in `src/lib/`.
- `navConfig.ts` is the single source of truth for navigation, routes, and actions (header, footer, pages).
- 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 is a page of sections, the front page included (its hero and bands are section types: `src/pages/sections/Bands.tsx`, their settings in `section_*` tables read by `server/src/sectionData.js`; forms and embeds are section types too, `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_PAGES` in `server/src/admin-schema/sitePages.js`: /give, /feedback, /request, /qr, /privacy, /terms) keep their address and can't be deleted. Record routes (`/events/:id`...) stay in `App.tsx`, and their first path segments are reserved. Menu links are Pages → Navigation (`site_nav_links`, `server/src/siteNav.js`, read through `src/lib/useSiteNav.ts`); `navConfig.ts` only holds the defaults the app starts from before that loads.
- `api.ts` is 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. A bare filename resolves to `/uploads/<file>` (`src/lib/media.ts`, and `server/src/pageMeta.js` for previews). Only the site's own chosen assets, the NGU logos in the nav, footer and admin, are bundled from `src/assets/logos/`. Logo images hide themselves on load error (`onError`).
- 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 sets `folder: "logos"` (`docs/media-uploads.md`, Folders). A bare filename resolves to `/uploads/<file>` (`src/lib/media.ts`, and `server/src/pageMeta.js` for previews). Only the site's own chosen assets, the NGU logos in the nav, footer and admin, are bundled from `src/assets/logos/`. Logo images hide themselves on load error (`onError`).
## Rules and gotchas
- **Role checks must use ladder comparisons, never equality.** Roles rank viewer → editor → admin → superadmin. Use the minimum-rank helpers from `src/lib/roles.ts` (`canWrite`, `canDelete`, `isSuper`, `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.
- **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/admin` needs viewer, `requireStaff`). Use the minimum-rank helpers from `src/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 `.js` before `.ts`**, so a `.js` and `.ts` file with the same base name will import the wrong one. Give new hooks distinct names.
- **Don't use `fallback: EMPTY` in api.ts hooks.** It silently returns empty arrays and hides server errors; let the error state surface.
- **Colours are tokens, not hex.** Admins can override any token (Panel → Site settings → Colours); the defaults live in three places that must agree: `src/index.css`, `THEME_DEFAULTS` in `server/src/theme.js`, `THEME_COLORS` in `src/lib/adminSchema/siteSettings.ts`. Use the utilities from `src/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 colour). Data colours (accents, event and region colours) go through `withAlpha`, `accentText` and `readableOn` in `src/lib/color.ts`, never `${color}55`.
- **Colors are tokens, not hex.** Admins can override any token (Panel → Site settings → Colors). The defaults are `server/src/themeDefaults.js` plus the same values as CSS in `src/index.css`; the build fails if they differ (`themeDefaultsCheck` in `vite.config.ts`), and migration 041's CHECK lists the token names. Use the utilities from `src/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 through `withAlpha`, `accentText` and `readableOn` in `src/lib/color.ts`, never `${color}55`. A palette color in a component or CSS file is `var(--pal-<family>-<shade>)`, not its hex, so the color blind modes reach it.
- **Icons are Phosphor** (`@phosphor-icons/react`), weight `bold` (or `fill` for 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) and `ACCENTS` (deep, green, olive), all from `PALETTE` (the site's 16-color grid). Not a new hex in a page.
- **Corners: square.** Everything is square except buttons, which use the `btn` utility (Poppins Bold, a small `var(--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 the `notice` utility (corner brackets), not a dashed border. Cards sit on `bg-raised` with 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 with `eg.`, and record ids are called "URL ID". Cut-off preview text uses `preview()` from `src/lib/text.ts`, which ends it with an ellipsis. See `docs/updating-data-in-code.md`.
## Admin CRUD engine
Descriptor-driven: `server/src/admin-crud.js` and `server/src/admin-schema.js` (server) 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.
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: false` prevents cross-entity sort order collisions.
- `check: (db, id) => void` runs after a save has written everything, inside its transaction; throwing an `HttpError` refuses the save (Site settings uses it for the colour contrast check, `server/src/theme.js`).
- A child collection can have `extensions` of its own (1:1 side tables keyed by the child row's id, eg. a page section's `section_hero`), and both those and its nested collections take a `when` on the row's values (a section's preset). A `when` value can be a list.
- `check: (db, id) => void` runs after a save has written everything, inside its transaction; throwing an `HttpError` refuses the save (Site settings uses it for the color contrast check, `server/src/theme.js`).
- The `OMIT` sentinel distinguishes unsent fields from deliberate clears.
- `admin-schema-sync.js` runs at boot and throws if descriptors don't match live `PRAGMA table_info`. If boot fails after a schema change, update the descriptor or migration so they agree.
- `admin-cli.js` imports `ROLES` and `destroyAllSessionsFor` from `auth.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 call `BEGIN` by hand. A new entity with a public page adds its path to `PREVIEW_PATHS` in `src/lib/adminSchema.ts`.
## Migrations
- `server/src/migrations/023_schema.sql` is the baseline: the whole schema, consolidated from the old 001–023. It only runs on an empty database; the runner refuses a database between v1 and v22. 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: `024_`, `025_`, ...
- `server/src/migrations/066_schema.sql` is 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.sql` runs 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...END` trigger body. Keep triggers last in a file, and put each `CREATE VIEW` before 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_check` before committing, so a table rebuild needs no `PRAGMA foreign_keys` of its own. When views or triggers name the table being rebuilt, wrap the drop-and-rename in `PRAGMA legacy_alter_table = ON` ... `OFF`, then recreate the rebuilt table's own indexes and triggers.

380
TODO.md Normal file
View file

@ -0,0 +1,380 @@
# TODO
- Instructions for this document: update it as things are completed, moving items from TODO to Done under the same category. Develop content here based on conversations. Leave the categories blank in Part 1: TODO when you are moving items out of them to Done.
- Status: everything up to v1.8.3-video-mgmt is tested and deployed. PR #14 (branch `audit`, v1.9.0 to v1.9.4-audit) was merged into main on 2026-09-29 (adc88e5). Branch `content-display` was merged as PR #15 (v1.9.5 to v1.9.11, 2026-09-29) and PR #16 (v1.9.12 to v1.9.14, 2026-09-30, c76df02). All of it is deployed and checked in a browser (2026-09-30). The design overhaul (PR #18, v1.10.0 to v1.10.2) and the revised palette (PR #19, branch `palette-test`) were merged into main on 2026-09-30 (6f86a11); not deployed yet. Branch `page-updates` (v1.10.3 to v1.10.6) was merged into main as PR #20 on 2026-10-01 (3e4a725); not deployed yet. Branch `page-fixes` (v1.10.7 to v1.10.10) was merged as PR #21 on 2026-10-01 (0bb4b86); not deployed yet. Back up the database before deploying (migrations 056 to 059: 056 and 057 rebuild content_blocks, 058 page_sections, 059 recreates v_events). Branch `audit-3` (v1.11.0-audit) is open as PR #22; branch `audit-ui` (v1.11.1-audit, on top of it) as PR #23; branch `newsletter-layout` (v1.11.2-newsletter, on top of that, migration 060) as PR #24.
---
# Part 1: TODO
- Items from notes.txt (2026-10-16). Each has questions under it: tick one when it's settled, or write the answer after "Answer:".
## Pages
- [ ] **Resources page by audience**: frame the page as For Young Adults, For Ministries, For All.
- [ ] Are these three tabs, three sections (each in the side nav), or a filter over one list? Answer:
- [ ] Does each resource belong to exactly one audience, or can it be in several (eg. a tag per audience)? Answer:
- [ ] What happens to the page's current sections: move under an audience, or replaced? Answer:
- [ ] **Library**: a library for NGUers.
- [ ] What goes in it: links out, uploaded files (Drive "Media"), books, videos, our own articles? Answer:
- [ ] Public, or only for NGUers? If only NGUers, how do they sign in (there are only admin accounts today)? Answer:
- [ ] Is the metaphysics dictionary / Metaphysical Bible Dictionary part of it (see Future: Poetry Builder needs the same import)? Answer:
- [ ] Is the Metaphysical Bible Dictionary free to republish (public domain edition), or only linked? Answer:
- [ ] **The Acronym Dictionary**: a page of acronyms (Unity, New Thought, NGU).
- [ ] A page of its own, or a part of the Library? Answer:
- [ ] Each entry: acronym, meaning, a short description, a link? Anything else (category, related org)? Answer:
- [ ] Who adds entries: admins in Data, or anyone through the request form? Answer:
- [ ] Do you have a starting list to import? Answer:
- [ ] **Retreat content index**: ideas and content from retreats, which event each was featured at, tabs for the major pillars, a table of contents to fill out (borrowed from YOU history). Also retreat templates.
- [ ] What are the major pillars (the tab names)? Answer:
- [ ] What is one entry: a talk, an activity, a theme, a workshop? Its fields (title, description, files, presenter, event)? Answer:
- [ ] Where does the YOU history version live, so I can see what to borrow? Answer:
- [ ] Public, or for retreat teams only? Answer:
- [ ] How does the feedback form fit: a form per retreat linked to its entries, or feedback shown on entries? Answer:
- [ ] Retreat templates: documents to download (Drive files), or a "start a new retreat from this one" copy in the admin? Answer:
- [ ] **Centralized scholarship and donor giving page**: one page for scholarships and giving.
- [ ] Does giving stay on Church Center (embeds), with this page gathering them, or something else? Answer:
- [ ] What is "etc.": scholarships, the Catalyst Fund, general giving, per-event giving? Answer:
- [ ] Do scholarships need an application (a form like /request), or only a description and a link? Answer:
- [ ] Show donors or totals (eg. a goal bar), or none? Answer:
- [ ] **Website changelog**: the site's construction as an evolving blog post, tabs marking each update.
- [ ] One blog post with a tab per version, or a blog post per version under a "Website updates" tag? Answer:
- [ ] Written by hand, or started from the tags and TODO.md Done list (then edited)? Answer:
- [ ] Does it go back to v1.0, or start from now? Answer:
- [ ] Linked from the footer next to the version, or only in the blog? Answer:
## Sections
## Page Features
- [ ] **Full profiles**: people get full profile pages. Profile accounts, claiming and visibility are done (Part 2, Accounts); what's left is the page itself.
- [ ] What is missing from a person's page today that makes it "full": bio, more photos, links, events they spoke at, groups, blog posts they wrote? Answer:
- [ ] Ties to Planning Center sync (Data) and the gamification below? Answer:
- [ ] **Page preview images per page**: the event's banner on event pages, the person's photo on theirs, the org's logo on org pages.
- Already done in `server/src/pageMeta.js`: events use the event photo, then the event logo, then its org's logo; people their photo; orgs, teams and awards their logo; blog posts their cover. SVG logos are skipped (social sites don't show them).
- [ ] Which page showed the wrong picture, and where (Discord, iMessage, Facebook)? Answer:
- [ ] Is it production (not deployed yet?) or the SVG skip? Should an SVG logo get a PNG copy made at upload for previews? Answer:
- [ ] Should event pages prefer the card background ("banner") over the event photo? Answer:
- [ ] **Gamification synced to Discord**: points, badges or levels on the site, synced to Discord. Linking a profile to Discord is done (Part 2, Accounts); the bot, points and badges are next.
- [ ] What earns points: going to events, writing for the blog, volunteering, Discord activity? Answer: all of the above, we could create badges on profiles.
- [ ] Where are they shown: on full profiles, a leaderboard, only in Discord? Answer: shown on profiles when logged in, no leaderboard for now, and when using a command in discord. this content would not show on the public bio section of a user when viewing from a people tile.
- [ ] Which way does it sync: site → Discord roles, Discord → site, or both? Is there a Discord bot already (or only the reports webhook)? Answer: would like a bot built, for if things in discord update or affect gamification shown on the website. most things will be assigned to users by moderators.
- [ ] How do we match a person to their Discord account (they link it themselves)? Answer: they can link it, admins can overwrite and update/set
- [ ] **Site version names**: in the footers now (Part 2, Page features); still to show them in the changelog once it's built (Pages: Website changelog).
## Accessibility Features
- [ ] Check the mobile fixes on a real phone (or the browser's phone view at 320, 375 and 430px), light and dark: every page, the menu, the hero, the retreat carousel, people tiles and their details, the community map, schedule blocks, the banner.
- [ ] **Listen to a page**: a screen reader or compiled audio for certain pages.
- [ ] The browser's own voice (free, reads the Reading mode text, sounds robotic), or recorded/generated audio files (better voice, has to be made for each page and kept current)? Answer:
- [ ] Which pages: blog posts, History, Organization, all? Answer:
- [ ] A Listen button in the Accessibility panel, or on each page by its title? Answer:
## Mobile
## Page Editing
- [ ] **Page management revamp**, in steps (answers from 2026-10-16: disabled means out of the menus, sitemap and search with the address still working; admins can make new pages; the front page, the Community blog's settings, the form and embed pages and Privacy/Terms all become pages of sections; section types like the hero, stats, featured cards, calendar and countdown can go on any page, each with its own content).
- [x] Step 1, the page registry (Done, below).
- [x] Step 2, the core pages as sections (Done, below).
- [x] Step 3, section types with their own settings and the front page as sections (Done, below).
## Admin
## Data
- [ ] **New Thought young adult directory**: the tabs are built (Part 2, Page features). Content: make the People tags (eg. Authors, Creators), tag people, and set Community's Directories section to them.
## Navigation
## Tools
## Content
- [ ] **Newsletter: featured partners and new partnerships**, maybe as a blog post.
- [ ] A newsletter part of its own (picks organizations, shows logos), or a blog post the newsletter links to? Answer:
- [ ] **Blog posts to write** (content, not code):
- [ ] The Catalyst Fund.
- [ ] How churches can engage with young people, through social media: what tools they use.
- [ ] Aidan's ultimate guide: church management systems, donor engagement platforms, free tools for nonprofits, nonprofit technology, AI (its benefits, and using tools ethically).
- [ ] Should any of these come out as a series (a tag), or one at a time? Answer:
## Production cleanup
## Audits
## Future
- Timeline vine/tree SVG (you'll provide it); until then the timeline is solid teal dots on a teal rail, one color throughout.
- Legal check of the Privacy Policy and Terms for NGU's state and nonprofit status (wording read 2026-09-28, fine for now).
- Enforce the Content-Security-Policy after watching its reports on the server (`journalctl -u ngu-api | grep csp`, `docs/security-headers.md`).
- Potentially make new vertical nav circle a sun svg later on.
- Poetry Builder, need to import the metaphysical bible dictionary and virtue list.
---
# Part 2: Done
## v1.14.0-profiles: page management (branch `page-management`, on top of `page-features`, no PR yet; migrations 080 to 085, back up the database before deploying)
- [x] **Planning Center sync** (Data, migration 085, `docs/planning-center.md`): Data → Planning Center (admins and up) fetches one Planning Center People list (Site settings → Planning Center) and compares each member with the site: linked, or suggested by the same email, else the same name, with the fields that would change (name, sort name, private email and phone) side by side. For each: link (and update; Planning Center wins), link to someone else, make a new unpublished person, or skip; Apply writes it all at once. One way, by hand. Off until `PCO_APP_ID` and `PCO_SECRET` are on the service. Tested against a stand-in for Planning Center's API only.
- [ ] Check with the real list: the token, a list number, a compare, an apply.
- [x] **Rotating words** (Sections, migration 084): text typed as `{Next|Now|Rising}` cycles through its choices, in the hero's headline, section titles (bands' too), headings, paragraphs, callouts and quotes, eg. `{Next|Now} Generation of {Unity|New Thought}`. Five motions (slide, flip like a card, fade, type letter by letter, mirror turning round), from the top or the bottom, a number of seconds per word: defaults in Site settings → Animated words, and a hero or a block can set its own. Each word's space is the longest's, so the line doesn't jump. Less motion (the system's setting, or reading mode) shows the first word, still, and screen readers always get the first; menus, tab titles, search descriptions and newsletters use the first word too (`src/components/RotatingWords.tsx`, `src/lib/words.ts`).
- [ ] Check in a browser: each motion and direction, a group in a section title and a paragraph, the space it keeps on a phone, reduced motion.
- [x] **Section types with their own settings, and the front page as sections** (migration 083): the front page is Home in Page management, a page of sections like the others: its hero first, then its bands in their old order (hidden ones stay hidden), each a section type that can go on any page with content of its own: Hero (words, buttons, photos, video, livestream or event), Event countdown, Event calendar, Numbers, Featured cards, Connect nav, and a Timeline shown as the rail of featured moments. The Community blog's slots, pinned posts and feeds moved into its section, so it can go on any page too. Any section can be Hidden. The Front page editor is gone (its fields are each section's), and so are its tables and the Community page's. On the front page the bands look as they did and any other section is a band in the same style; on other pages a band brings its own heading. The National Retreats band became an Events section with an All retreats button. The newsletter's "featured cards" come from the front page's featured card sections. Admin engine: a child collection can have its own side tables and gated nested collections.
- [ ] Check in a browser: the front page (every band, the countdown overlapping the hero, reading mode, the menu's Home dropdown), editing the hero and a band in Page management, a Hero and a Numbers section put on another page, hiding a section, the Community blog (pinned posts, feeds), a draft preview of the front page, the newsletter's featured cards.
- [x] **Core pages as sections** (migrations 081, 082): Feedback, Request, QR codes, Give, Privacy and Terms are pages of sections now, edited in Page management like any other. Their forms and embeds are section types any page can use (Website feedback form, Request form, Data request form, Giving button, QR code maker); Give's words, and all of Privacy and Terms, are blocks (headings, paragraphs, lists), with "Last updated" in the section's blurb. The privacy contact email was written into the policy's text and its Site settings field is gone. These pages keep their address (the site's code links to them) and can't be deleted. The privacy notice's link now goes to #cookies-and-browser-storage.
- [ ] Check in a browser: each of the six pages (reading width of Privacy and Terms, the giving modal opening), editing a Privacy paragraph, a Request form section put on another page.
- [x] **Page registry** (migration 080): every page of the site is a row in Pages → Page management (admins and up): its address, title, intro, Hidden (Not found below viewer) and Disabled (out of the menus, the sitemap and search; the address still works), and the order of its admin card. New pages are made there, as pages of sections at the address given (any address but the admin's, the API's, the records' and the account pages'). The admin home's Pages group opens with a Page management banner (New page, Menus), then a card per page. The six page editors (Retreats, Community...) are one editor now; site.json's `pages` and Navigation's page list moved into the registry and are gone. The fixed pages (Feedback, Request, Give, QR codes, Privacy, Terms, the front page) take their words from it too and can't be deleted.
- [ ] Check in a browser: the admin home's banner and page cards, making a page (address, sections) and opening it, hiding and disabling one (menus, the page signed out), renaming Feedback, the Under page select in Navigation.
## v1.14.0-profiles: page features (branch `page-features`, with `nav-access` under it, no PR yet; migrations 078 and 079, back up the database before deploying)
- [x] **Featured event label** (Mobile): the "Featured event" badge left the headline; from lg up it sits above the event's card it names, and on a phone (the card under the words) it's left out.
- [x] **Site version names**: the tag's words after the number are the version's name, `v1.13.2-region-cards` → "The Region Cards Update" (`src/lib/version.ts`), shown with the number in the site's footer and beside the version in the admin's footer and home.
- [x] **Image converter** (Tools → Image converter): pictures to JPG, PNG or WebP in the browser (nothing uploaded): pick or drop several, a quality slider for JPG and WebP, download each or all. JPG fills transparency white. Media's images each have a Download as… (JPG, PNG, WebP) doing the same (`src/lib/convertImage.ts`).
- [x] **Directory tabs** (migration 078): the People directory preset takes several People tags, a tab each in the order picked (Directory: tags under the section); one tag shows without tabs, reading mode lists every tag. Each section's old single tag became its first.
- [x] **Blog post tabs** (migration 079): a Tab block in a post (its text the tab's title) starts a tab holding the blocks after it; blocks before the first Tab are the intro above the tabs. The contents list follows the open tab, a link to a heading in another tab opens it, and Download PDF and reading mode show every tab under its title. Outside a post a Tab block reads as a heading.
- [x] **Featured event card height** (Sections): from lg up the event's photo sits beside its words instead of above them, with tighter type and buttons, so the card is about as tall as the hero's text beside it; stacked as before on a phone. The photo stays whole (16:9).
- [x] **Word import, more of it** (Page Features): a line starting `Tab:` (any style) starts a tab; the Quote style becomes a Quote (a dash and a name at the end is who said it), Intense Quote a Callout, a line of `---` a Divider, a YouTube, Vimeo or Facebook link alone on its line a Video, and `Button: Register` with Register linked a Button. Blog posts → What becomes what (beside Import from Word) shows the whole mapping; `docs/importing.md` too. The note after an import counts tabs and the rest.
- [x] **Side nav sun into the footer** (Navigation): the sun is far bigger than the sticky layer that carries it, so once the last section went up past the list it hung over the footer. It now fades out as the list leaves with the last section, and back in on the way up.
- [ ] Check in a browser: the featured event card beside a two-line headline at 1024, 1280 and 1536px; What becomes what and a real Word document with Tab: lines, a quote and a video link; the side nav sun fading at the end of a long page (2xl screen) and with a tall footer; the featured event hero at phone and desktop width, the footers' version line, converting a PNG with transparency to JPG and a JPG to WebP (and Download as in Media), a Directories section with two tags and with one, a post with an intro and three tabs (contents, keyboard arrows, PDF, reading mode).
## Page Editing (branch `nav-access`, no PR yet; migration 077)
- [x] **Drafts of every record** (migration 077, `docs/drafts.md`): an existing record of any kind (events, people, organizations, blog posts, the front page, the site pages, Navigation, Site settings...) can be saved as a draft instead of going live. One draft per record; anyone who can edit it can save, preview, publish or discard it. Opening a record with a draft opens the draft, saying who saved it and when, and warning when the live record was saved since. Lists mark records with a draft.
- [x] **Preview on the real page**: Preview saves the draft and opens the record's page in a new tab with it applied, under an amber "Previewing a draft" bar, for signed-in admin accounts only; anyone else sees the live page. The server answers that tab's reads from a second connection holding the draft in a transaction it rolls back, so no page needed code of its own.
- [ ] Check in a browser: save a draft of an event, a site page (a section's title) and Navigation (a link), preview each, publish one, discard one; open the same address signed out.
## Accounts (branch `nav-access`, no PR yet; migration 076, back up the database before deploying)
- [x] **Profile accounts** (migration 076, `docs/profile-accounts.md`): a member role below viewer, signed in to the site and their own profile, never the admin (`/api/admin` now refuses anything under viewer). By invite only: Data → Profile accounts (admins and up) adds an email and shows its link once; Email invite sends a fresh one through Gmail. The link (`/account/welcome`) sets a password, or they sign in with Google under that email, any Google account. A New sign-in link on the account doubles as a password reset.
- [x] **Claiming a People record**: on `/account` (Your profile; the footer's Sign in link) they ask to be a record; admins approve or decline it under Claims, or set it directly on the account.
- [x] **Editing it and choosing what shows**: with a record, they edit its pronouns, tagline, location, public email and phone, bio and photo, and hide any of photo, pronouns, tagline, bio, email, phone, location, links. Hidden parts stay in the record (the People editor shows the same switches) and are left out everywhere on the site: every public read of people goes through the new `v_people_public` view, and the views that read people were rebuilt over it.
- [x] **Discord linking**: a profile links its Discord account (identify scope: id and name) from `/account`; an admin can set or clear it on the account. Off until `DISCORD_CLIENT_ID` and `DISCORD_CLIENT_SECRET` are set on the service.
- [ ] Check in a browser: invite (copy link and Email invite), the welcome page with a password and with a non-org Google account, a claim and its approval, editing and hiding (then the person's page, a team page and a people tile signed out), Discord linking once it's set up, a member opening /admin.
## Navigation (branch `nav-access`, no PR yet; migration 075, back up the database before deploying)
- [x] **Pages → Navigation** (migration 075): the header's pages and buttons, the footer's Get in Touch and bottom row, edited in the admin (admins and up): place, order, label, link (a page, a #section or an address elsewhere), a header page set under another page's menu (after its sections), a filled button (Give's style, also beside the footer's logo), new tab. `navConfig.ts` is now only the defaults the app starts from before the nav loads. Page titles and intros moved here from Site settings (the old rows came along).
- [x] **Hidden pages**: a page ticked Hidden in Navigation answers Not found (404, noindex) to everyone below viewer, server and app both, and is out of the menus, the sitemap and the not-found page's suggestions; links to it are only sent to viewers and up. Signed in, it shows with a bar saying it's hidden. Its sections aren't cached (`server/src/siteNav.js`, `GET /api/nav`).
- [x] **Shop**: a Shop page of sections at `/shop` (Pages → Shop, empty for now), starting hidden, with a Shop button in the header (beside Contact Us and Give, and in the phone menu's list with them). Unhide it in Navigation once it has content; its sections can link out to the Bonfire store.
- [ ] Check in a browser: the header and phone menu, a page set under another's menu, the footer, signed out and signed in (the hidden bar, Shop showing), light and dark.
## Feature updates (branch `feature-updates`, v1.13.x, no PR yet; migrations 069 to 071, back up the database before deploying)
- [x] **Partner cards, logo first**: the organization cards (Partners, Ministries) lead with the logo, large and centered, the name under it as a small line (still the heading); with no logo, its initials. Cards sit raised with a shadow and an accent top edge.
- [x] **Frame a photo on upload**: photo fields (people, event photo and card background, blog cover and guest photo, hero photos, link card pictures, block images, schedule graphics and map images; not logos) open Frame the photo for a JPEG, PNG or WebP: drag (or arrow keys) to place, zoom slider, a shape menu (the field's own first; As uploaded keeps the photo's). The framed part is what uploads; Upload as is skips. Nothing stored beside the picture, so re-framing is uploading again.
- [ ] Check in a browser: the partner cards with and without logos (light, dark); framing a portrait into a square and a wide photo into 16:9, Upload as is, Cancel, and a PNG keeping its transparency.
- [x] **Content blocks: Shown in** (migration 071): The page, The card only, or The card and the page. A card block used to show on the page too without saying so; every existing card block became "both", so nothing moved. Pages no longer print card paragraphs separately; a "both" block comes with the page's blocks, in its place in the list.
- [ ] Check in a browser: an event with a "both" paragraph (on its card and page) and one with "card only" (card, not page); an organization, team and person page still show their text.
- [x] **Group pages**: the facts at the top sit in a framed card (City, Part of <name> Region, Ministry, Meets, Since, tags); email buttons go to the link's URL, not its label (`splitLinks` took the label); every website and email row is listed with its own label, not only the first.
- [x] **Tags** (migration 070): Data → Tags (Online and In-Person to start) replace the Online checkbox on organizations and events. Records ticked Online got the Online tag (nothing got In-Person). The tag with URL ID `online` still makes an event online (calendar filter, place line, search data) through `v_events`. Tags show on the record's page and on group entries in the Community map list and grid; the map no longer keeps online groups off their state's tile.
- [ ] Check in a browser: a group page's facts card (light, dark, reading mode), two emails and two websites, tags on a group and an event, the Tags list in Data, and the calendar's Online filter still working.
- [x] **Schedule presentation** (digital signage): an event page's schedule block has a Present button (everyone) opening `/events/<id>/present` in a new tab. A setup screen picks the days and entries and the seconds for each kind of slide (day overview, entry spotlight with the person's photo and name beside the entry, graphics, map images; 0 leaves one out); Play goes full screen and loops, the parts of each slide animating in, a bar showing the time left. The settings are in the address (bookmark it on a signage screen; `play=1` skips setup). Arrows step, Space pauses, S returns to setup; the screen is kept awake where the browser allows. Not by the clock: it loops what was picked.
- [x] **Map image on schedule entries** (migration 069): an entry's own map picture, shown in its fold-out in place of the Google map (the "Open in Google Maps" link stays when a place is set) and as a slide in the presentation.
- [ ] Check in a browser: the Present button, setup, each slide kind (light and dark, a long day of 9+ entries in two columns), full screen on the signage device, and a map image in the fold-out.
- [x] **Group map** (Community): hovering a state outlines it in ink while its region stays lit; the list puts each region's groups under their state's subheading, each entry a raised card; the region's list of states is gone from the list (its map note stays); the list no longer scrolls on hover, only on click (a state goes to its subheading, or its region when it has no groups; a legend region to that region).
- [x] **Side nav pill** too tall when the window narrows (Community): the pill (straight sides, round ends) was sized as an ellipse, about three times the list's height; it's sized as the pill now.
- [x] The "Hide past events" button was clipped at the bottom when it grew on hover: the event cards' root wrapper was `overflow-hidden`; it is `overflow-x-clip` now (the carousel still can't spill sideways).
## v1.13.1-data (branch `data`, merged as PR #28, 2026-10-06, 970730d; migrations 065 and 066, the consolidated baseline, then 067 and 068, back up the database before deploying; not checked in a browser yet)
- [x] Newsletter: a new draft's Coming Up "Pick from" showed "events no longer exists". Events is that select's blank choice, so new drafts now leave the source blank and older drafts' `events` loads as blank.
- [x] **Frame from a video**: a video featured card's Image field has "Frame at" (a typed time, prefilled from the link's `t=`); the server takes that one frame with yt-dlp and ffmpeg and saves it to `/uploads/thumbnails/` as the card's picture (`POST /api/admin/video-frame`, editors and up). Choosing any other picture already worked through the same field. Not tested end to end yet: needs yt-dlp, which is on the VPS but not the dev machine.
- [x] **Plausible reports to Discord** (migration 065): daily (yesterday) and weekly (Mondays, last 7 days with the change from the week before), each switched on in Panel → Site settings → Reports; sent at 8:00 America/Chicago. Needs `PLAUSIBLE_API_KEY` and `DISCORD_WEBHOOK_URL` on the ngu-api service (`PLAUSIBLE_URL` if Plausible isn't on 127.0.0.1:8000). Try it with `node src/analyticsReport.js daily`. Tested with a stubbed Plausible only.
- [x] **Captions for uploaded videos** (migration 066): video blocks have a Captions field and the hero a Video captions field, each taking a WebVTT (.vtt) upload (kept as is, in `/uploads/captions/`), drawn as `<track kind="captions" default>` on a video file (WCAG 1.2.2). Embeds bring their own. Needs `text/vtt vtt;` in nginx's mime.types if it isn't there (`docs/media-uploads.md`, step 5).
- [x] **Migrations consolidated** into `066_schema.sql` (generated from the live v66 schema, checked identical: 136 objects, every table's columns) and `066_seed.sql` (single rows, event scopes, home sections, the five site pages and their sections, the Musicians tag; the hero words, paths, stats and the Organization address and tax ID are no longer seeded). A database at v66 skips both; one below v66 is refused. **Deploy order:** production is below v66, so deploy 33be618 (the last commit with the old files) first, let it migrate to v66, then deploy this.
- [x] **Partners section picks its organizations** (migration 067): the organization cards preset (Community → Partners) has "Cards: list" (Partners by default, Ministries, or both, every published, listed one by name) and an optional hand-picked "Cards: organizations" list (partners or ministries, in order, published ones, listed or not) that replaces it. Ministry cards link to their website only (no page). `/organizations` now takes `kind=ministry` and `ids=`.
- [x] **Links/redirects** (migration 068): Data → Links/redirects makes short links, `/go/<URL ID>`, for the newsletter. Each click is counted (Clicks, Last click on the list), sent to Plausible as a pageview of `/go/<URL ID>`, and redirected with the link's optional UTM tags added. Editors and up. `docs/redirects.md`.
- [x] Newsletter: Save as a new draft beside Save draft; a Title color; every part color is a color picker (any hex, or none) instead of the palette dropdown.
- [x] Region pages no longer show the raw domestic/international scope.
- [x] Keywords question (2026-10-04): Google has ignored `<meta name="keywords">` since 2009, so nothing to add. What counts is the words on the page: titles, headings and descriptions, which `pageMeta.js` already fills per page. The Google side is Search Console, which shows the searches the pages appear for.
## Pages and Data (branch `data`, merged as PR #27, v1.13.0-data, 2026-10-04, 3b45944; migrations 062 to 064, back up the database before deploying; not checked in a browser yet)
- [x] **Musician directory, as people tags** (migration 062): Data → People tags lists what people can be tagged as (Musicians seeded); a person's Directories repeater tags them, and their new Specialty line ("Vocals, piano · Gospel, folk") shows on their tile in a directory, with their links in the details panel. A People directory section preset (Community, Resources, Organization) shows a tag's first 12 and links to its full page, `/directory/<tag>` (eg. `/directory/musician`), titled and indexed like any page. Another directory (Speakers) is a new tag, no code.
- [x] **Ministry organizations** (migration 063): a new organization kind for Unity ministries. A group picks its ministry (Group → Ministry), and its page says "Ministry: <name>", linked to the ministry's website link when it has one. Ministries have no page, list, sitemap entry, timeline entry or 404 suggestion on the public site, and aren't offered where a record links to its organization (event hosts, teams, awards, roles, home organization, featured cards, timeline).
- [x] **Organization contacts and the recipient export** (migration 064): Data → Contact types holds the roles you make (none seeded); each organization has a private Contacts repeater (type, name, email, phone; editors and up only). Tools → Newsletter → Recipients filters them by contact type, organization kind, region (the region and its groups) and published, previews the matches and downloads a CSV for Mailchimp (Email, First Name, Last Name, Phone, Organization, Kind, Region, Contact type). A type still in use can't be deleted.
- [ ] Check in a browser: tag a person, the directory section and page (light, dark, reading mode), a group's ministry line, contacts on an organization (as a viewer too), the export and its CSV.
## Accessibility, second round (branch `accessibility`, merged as PR #26, v1.12.1-accessibility, 2026-10-03, 07e56bf; not checked in a browser yet)
- [x] **Reading mode rebuilt** (`src/components/ReaderView.tsx`): the page as text only, headings, paragraphs, links and pictures with a description, in one column, with a line of links to the site's pages at the top. No header, footer, backdrop, buttons, cards or forms; the accessibility button stays, to turn it off. The real page still renders, hidden, and the reader writes out what it drew, again whenever it changes, so every page works without a version of its own. A card that is one link gives its heading the link; a button that opens something (a person's tile, a schedule row) keeps its words as a line; carousel copies and decorative pictures (empty alt) are left out.
- [x] **Color blind modes cover the whole site**: each mode now replaces all three color families (teal, green, amber), not just green, with sets picked by simulation (each family's darkness can differ, since a red-green color blind eye sees one blue to yellow line plus light and dark). The closest pair goes from 11.4 to 27.9 (protanopia), 19.5 to 24.7 (deuteranopia) and 6.4 to 21.1 (tritanopia); every theme token still meets 4.5:1 in light and dark mode. The theme tokens, the backdrop circles, the side nav circle, the header and menu, the hero, the stats band and data colors all follow (`--pal-*` variables in index.css, `SWAPS` in color.ts).
- [x] **Reading mode spacing and width**: words from parts the page draws on their own lines (a name above a title, a flex row's items) no longer run together; the column is 60rem (was 42rem) and headings are bold, in the display face.
- [x] **Front page in reading mode**: bands the reader can't read well draw a text version of their own (`useReadingMode()`): the numbers, one line each ("1,200+ Members"), no longer stuck at 0 (the count waited for the band to scroll into view, which the hidden page never does; reduced motion now shows them at once too); the calendar, the next six weeks from today as a list (date, linked title, time, type, place) on any page that has one; the featured cards, each a linked heading with its words, a video card linking to its video. The countdown is left out, since the retreats band shows that event.
- [x] **Reading mode, every page and section** (audited section by section): the reader itself now reads an icon-only link's aria-label, puts a card's link on its first line or picture when it has no heading, gives each item of a row of facts or link buttons its own line, keeps line breaks, skips what CSS hides (a blog post's print-only footer), turns a form into one line saying it can't be used there, shows empty table cells as "-", and keeps section and heading ids so #links land (side nav, a post's contents). What it can't read draws its own text version (`useReadingMode()`): the hero (its words, buttons, every slide's caption, livestream and video links), the pathfinder (every path and its actions), the front page history (linked entries), event lists (every event, past ones too, no carousel), the org lists and groups map (every region and all its groups, linked), the history timeline (every year open, upcoming too), schedules (every day, fold-outs included), people tiles (everyone, with their details) and videos (a link). Heading levels fixed where cards repeated their section's level; org names are linked headings; Team pages lose their doubled "Members"; Giving links the treasurer's email.
- [x] **Local groups map fits a phone**: it scales to the column's width instead of holding 34rem and scrolling sideways.
## Navigation (branch `accessibility`)
- [x] **No fixed back links on record pages**: a group, region or partner page no longer ends its facts line with "All groups" (and so on), and a team page no longer says "Back to <org>" (its "A team of" link stays); records are reached from many pages, so the browser's back is the right way back. Not-found pages keep their link, having nowhere else to send a visitor.
- [x] **Side nav label on its circle, dark mode**: the lit label was its accent mixed halfway to white, which for the deep teal (Unity Regions) left 4.2:1 on a circle of the same teal. Labels now use `--nav-text-mix` (30% in dark mode): 6.8:1 or better for every accent.
## Accessibility (branch `accessibility`, merged as PR #25, v1.12.0-accessibility, 2026-10-03; not checked in a browser yet)
- [x] **Plausible analytics**, self-hosted behind nginx at `/pa/`: the API adds its script to every page (`analyticsTag`, `server/src/pageMeta.js`), counting under site.json's url hostname, so dev and live report separately.
- [x] **Accessibility panel:** the switches' knob stays in its track (an absolute child of a `<button>` with no `left` started from the centered content). The panel comes after its button in the page, so Tab goes into it, and opens on its first switch; each switch reads its help line.
- [x] **Reading mode** is now the page as plain text: one 42rem column, ink on white (or white on near-black in dark mode), every color, background, border, shadow, picture, video, map and decoration gone, controls outlined, links underlined, no motion (JS scrolls, the hero slideshow and the stats count-up too, `src/lib/motion.ts`). A picture or video with a description leaves "Image: ..." in its place (`data-reading-alt`, set by the panel).
- [x] **Color blind mode** (Protanopia, Deuteranopia, Tritanopia, Monochrome), a select in the panel that reloads the page. Simulated with the Machado (2009) matrices, green and amber blur together for protanopia and tritanopia, so there the green family becomes violet (same contrasts; the closest pair of families goes from 11.4 to 17.4 and from 6.4 to 21.6 in CIELAB). For deuteranopia the palette already stays apart and is kept. In all three, a color picked off the palette snaps to the nearest palette shade. Colors from the database are swapped as they arrive (api.ts, never under /admin), colors from code through `visionColor` (color.ts), CSS through the `--green-*` variables (index.css). Monochrome is a grayscale filter on the root.
- [x] **Audit fixes:** the fixed header no longer covers what's focused or jumped to (`scroll-padding-top` from `--header-h`, now on the root; the per-section offsets it replaces are gone). A new page moves focus to its content; closing the phone menu returns focus to its button; Escape closes a desktop dropdown. In-page jumps (section nav, a post's contents, #links) move focus with the scroll (`jumpTo`, `src/lib/focus.ts`). Carousel arrows stay focusable at the ends. Calendar: canceled bars say so to screen readers; a day's list takes focus and gives it back to the day on Close. Thank-you messages, a started video, the livestream and a schedule map take focus (`focusOnMount`); closing a person's details returns to their tile. The countdown's ticking digits are out of its link name, and its title wraps instead of being cut. Wide tables scroll from the keyboard. Map tiles with groups are buttons for the keyboard. Request form radio errors and required fields are tied to their inputs. Admin: field errors, help and required marks reach screen readers; search boxes, the role select, the color picker and the two picker dialogs have names; the section nav's error dot says "needs attention".
- [x] **Calendar window** (from the third audit): the calendar asks `/events` for only the six weeks on screen (`?from=&to=`, undated events and open-ended series included), keeps the last month up while the next loads, and fetches from the month's end on only when a month is empty, to offer the jump to the next event. Carousels ask for only their 12 most recent past events (`?past=12`); the grid's past list still pages through them all.
- [x] **Event photo** (migration 061): events have two pictures. **Event photo** (16:9, with a description for screen readers) is shown whole at the top of the event's page, as the front page's featured event (its box is 16:9 now, was 16:7), on featured cards, in newsletter picks and as the share preview. **Card background** is only the faded background of the event's card again. Each event's photo starts as its card background, so nothing changes on screen until one is replaced. Sizes for both are in `Data Requirements.md`.
- [ ] Check in a browser, light and dark: the panel (Tab order, knobs, Escape), reading mode on the home page, a blog post and an event, each color blind mode (backdrop circles, side nav, footer links, event colors), the calendar paging months, the jump to the next event and the filters, a carousel's past events, keyboard focus after page changes and section jumps, the phone menu.
## Page fixes (branch `page-fixes`)
- [x] **Details & Contact is plain blocks** (migration 058): the address, tax ID and email preset is gone; Organization's Details & Contact section holds them as blocks (the address, the nonprofit line with the tax ID, an email button), edited like any section.
- [x] **Header dropdowns close after a click**: they opened on hover or on any focus inside, and a click leaves focus on the link, so the menu stayed open after the pointer left. Now only keyboard focus (:focus-visible) opens them besides hover.
- [x] **A circle behind the side nav**: a solid circle with a slight drop shadow in the light shade of the section being read (teal, green or amber; their darkest in dark mode), easing from one to the next as you scroll; each entry also takes its section's color when hovered or lit, centered on the list, which the nav's text reads on in both modes. It sticks with the nav as the page scrolls or grows, stays centered on the list however wide the screen, sits a little left of the list's center but never left of the "On this page" heading's center (centered on the whole list once its titles reach further right), shows above and below the list (clipped sideways only), keeps its right edge inside the nav column so it never covers content (a narrower window slides it off the screen's left edge instead), and, with the whole nav, sits in front of the section lines; "On this page" starts level with the first section's title (lower if the circle needs room to start a few pixels below the first line), and once scrolling the nav sticks just under the header, while its circle grows into a sun in the corner: centered on the header's bottom left, so a quarter of it shows, big enough to reach past the list (never wider than the nav column), easing between the two. Held narrower than that by the window, it stays centered on the header's edge (so below the header it only curves inward) and becomes a quarter ellipse, as tall as it takes to cover the list. At rest it keeps 16px clear of the section's edge and becomes an ellipse too for a tall list. Both cover the longest list a page may have, 10 sections of two-line titles; for that, the side nav now shows from 1536px (2xl) up instead of 1408px (narrower, the list is as wide as its column and nothing inside it can cover it).
- [x] **Side nav no longer shifts the sections**: it sits in the left margin beside the content instead of taking a column, so sections stay centered where they'd be without it. It shows on screens 1536px (2xl) wide and up, where the margin fits it and its circle (titles wrap onto a second line); narrower, the header's dropdowns list the sections.
## Page editors, navigation and tools (branch `page-updates`, after v1.10.5)
- [x] **Page editors with sections** (9daf7b1, migration 056): Pages → Retreats, Community, Resources, Organization, History. Each page is a list of sections, each with a title (30 characters at most, so it fits the side nav; the editor says so), URL ID, blurb, accent, its own content blocks, and an optional preset drawn under the blocks: Community blog, local groups map, Unity Regions list, partner cards (Community); event carousel or grid with scope, type and first view (Retreats); timeline (History); address, tax ID and email (Organization). Every page was seeded as it looked. Organization's Details & Contact is its third section; Volunteering became a heading, paragraph and link buttons at the end of Leadership. The Community blog's settings (slots, pinned posts, feeds) are in the Community editor; its heading and blurb are its section's. The header dropdowns, footer site map and side nav follow each page's sections. The admin engine now saves nested collections to any depth (page, sections, blocks, items).
- [x] **Timeline entries under Data** (4a1d6fd).
- [x] **Navigation** (4a1d6fd and this branch): the footer site map spans the full width; section divider lines run behind the side nav; the side nav fits 30-character titles; front page section headings fit about 60 (noted in its editor); Home has no dropdown in the header.
- [x] **Newsletter drafts** (migration 057): Tools → Newsletter saves drafts (title, intro, blocks, picks, footer) to open again later, adds content blocks written for the issue (those an email can show), an editable footer (blank: the site's name and address; no unsubscribe link, Mailchimp adds one), and Post as blog post, which makes an unpublished post (intro, blocks, then each section's picks as link cards) and opens it in the post editor.
## Entity pages and pages (branch `page-updates`)
- [x] **Cleanup** (43797f3): removed the old-data fixes, since nothing before them was public: the /leadership redirect, the "ngu-" browser key move, the boot-time image sorter, and emoji path icons (migration 055 turns the seeded emoji into named icons). Kept on purpose: OrganizationDetail's redirect from a wrong-kind URL (/groups/x for a region) to the right one, and the migrations' own data rewrites (they already ran).
- [x] **Organization page editor** (43797f3): Pages → Organization page. Mission blocks; Leadership heading, blurb and blocks (eg. a People block for the Board of Trustees, then one for the Retreat Team, in that order); Volunteering title, blurb and links under the leadership. The page reads only from this editor now (not the NGU organization record).
- [x] **Navigation** (ed0f120): the second strip is gone; each top link drops down its sections on hover or focus. Retreats, Community, Resources, Organization and History have a sticky "On this page" column from lg up (the admin editors' SectionNav). Home's sections everywhere follow the front page's visible bands, in order, under their headings. Resources now comes before Organization in the nav and footer.
- [x] **Mobile** (a907a47, 8d319bc): surveyed every public page at 320 to 430px and fixed what was cut off or hard to use. Menu scrolls to its top when tall; page titles and the hero headline size down and wrap; hero buttons stack, slide controls are 40px; the retreat carousel has phone-sized cards, arrows beside the dots, 40px dots and swipe; the narrow event card's logo row restored; people tile details stay on screen and tiles keep 60% of their width; the community map scrolls sideways at a readable size; group and org cards, schedule rows, stats numbers, timeline rail cards and the banner fit; long emails wrap; tap targets 40px; the accessibility panel sits above the privacy notice.
- [x] **Accessibility button** (177a650): a button at the bottom right of every public page opens two switches. Dyslexia-friendly font (OpenDyslexic, self-hosted, downloaded only when chosen); Reading mode (no background circles, motion or shadows, one column, larger text, underlined links). Remembered in the browser, applied before the first paint.
- [x] **Newsletter builder** (2a92697): Tools → Newsletter. Pick upcoming events, published blog posts and featured cards, add a title and intro, and copy email-ready HTML or plain text (or download it) for Mailchimp, Gmail or Church Center. Nothing is sent or stored. The header is the site name in type, since email clients don't show the SVG logo; a PNG logo could go there later.
- [x] **People tiles, one row** (01de627): a whole list (leads and members) shares one row when it fits with tiles at three quarters of full width or more, 10 at most; a board of 7 is one row at normal width.
- [x] **Privacy** (this branch): Giving links ngu.churchcenteronline.com (the address the site uses; the TODO said ngu.churchcenter.org) and says Church Center's script loads with the Giving page and may use Google Analytics in its form; Cookies says the site uses self-hosted, cookieless Plausible and not Google Analytics. Last updated September 30, 2026.
- [x] **People blocks** (7c7cdaa, migration 054): a "People" content block shows a team's members as people tiles, people picked one by one (each with a title), or both.
- [x] **Host teams** (7c7cdaa): an organization host can name a team (any organization's) to show in its place; the event page reads "Hosted by" the team, linked to its page.
- [x] **Organization page** (499662b): Leadership is now Organization, at /organization (/leadership 301s there). Mission, Vision & Values come from the NGU organization record's description and content blocks (Data → Organizations → NGU); Leadership is that record's teams with their people; Details & Contact has the address, nonprofit status, email and the record's contact links. Add the mission text and the teams (Board of Trustees, Retreat Team, Committees & Volunteers) on that record.
- [x] **404 page** (79c4b24): suggests the closest pages and records to the address (typos, old /chapters/ links), then the main pages.
- [x] **Request form wording** (this branch): short field titles with a help line; "Short description" for a post's card; the Files note says why to send a .docx.
- [x] **Cross-browser** (design): the backdrop parallax checked in Firefox and Chrome/Safari.
## Design (branch `design-overhaul`)
- [x] **Revised palette** (PR #19, 79f1d09): teal, green, amber and ink, four shades each (main, darkest, light, lightest), as the theme defaults in both modes; the old grid's literals mapped over, the hero's filled button amber. Every text pair passes 4.5:1.
- [x] **Overhaul fixes, third batch** (a397f3e to 2df908f, not yet tagged):
- Admin: header, strip and footer as wide as the content; white (surface) background in light mode, the page ink in dark; home cards alternate teal and green, with a shadow.
- `tint-soft` is a faint teal again (#e8fcfe / #00252b), not green; it's the hover and faint-panel color everywhere.
- Cards sit on a new raised surface (`bg-raised`: white, or a touch of tint in dark mode) with a shadow: featured cards, the connect block, people tile captions, the timeline's featured entries.
- Buttons: a small plain radius everywhere (superellipse removed).
- Video stills: YouTube's 16:9 frame (no black bars; the 4:3 one cropped as a fallback), small rounded corners, a round centered play button shown on hover or keyboard focus (always on touch screens).
- People tiles: rows balanced between 2 and 10 across, avoiding a lone tile on the last row where the width allows.
- Map tiles and region tags are solid, dimmed by color instead of transparency; map tiles are square.
- Backdrop: 16 circles in four parallax layers, all slower than the page, the back ones visibly moving on long pages; a different seeded arrangement per page; tone changes only at a new top-level section, easing over 2.4s. Text passes 4.5:1 however many overlap.
- Timeline: the rail is brown wood; decade numbers are tags off the rail on a short slanted branch, colored like their decade's leaves; featured entries and rosters are solid, not see-through.
- Cross-browser findings: the site needs Chrome/Edge 111+, Safari 16.4+, Firefox 128+ (Tailwind v4's own floor: color-mix, cascade layers). Everything else used (container queries, dialog, inert, line-clamp, ResizeObserver) is supported there. One gap: the backdrop's parallax uses scroll-driven animations, which Firefox doesn't have yet (Chrome/Edge 115+, Safari 26+); in Firefox the circles stay still, which is fine but flat. Done: option 2, a Firefox fallback (a passive scroll handler writing --pb-y once a frame, same motion as the scroll-driven version). Still possible: a dev-only Playwright check that screenshots key pages in Chromium, Firefox and WebKit, light and dark (a new dev dependency), for a repeatable browser pass.
- [x] **Overhaul fixes** (v1.10.1, f37c093):
- Backdrop: two slow circles fixed to the window drift up as you scroll (CSS scroll-driven animation, still in browsers without it and under reduced motion); three sit down the page and move with their sections. No sideways movement. Text stays 4.5:1 or better even where three circles overlap.
- Featured cards and the connect section: 4px rules; video frames inset from the card edge.
- Calendar: the weekday row is a solid dark bar with white Poppins labels.
- History: decade numerals are dark tags on the rail instead of a white box.
- Notices: two thick corner brackets (top left, bottom right), no box or fill.
- People tiles: the frame is around the whole list; details open right under the tile (flipping to the tile's right edge near the screen edge) and close on Escape or a click elsewhere.
- Community: "Request a region update" and "Request a partner listing"; the region list no longer shows a group count.
- Palette suggestion (not applied): the current grid has three near-duplicate pairs (#5ce7ff/#5cf4ff, #c2f6ff/#c2fbff, #004552/#004c52) and no mid-tone for secondary text or warm accent. Suggested grid, darkest to lightest per family, every 600 step usable as text and under white text: Teal #003a45 #00748a #5cd3e6 #d6f5fa; Green #23361a #4a7431 #9cc47c #e6f0dd; Amber #4a2e00 #8f5b00 #f0bd4f #fdf1d6; Ink #001011 #3b5456 #a3b8b9 #f5f9f8.
- [x] **Overhaul** (d81f7bd to dd33ee2), following design-taste-frontend with your notes first:
- **Palette:** the 16-color grid is the site's default colors, light and dark (`themeDefaults.js`, `index.css`, `PALETTE` in `src/lib/color.ts`); every text pair passes the admin's 4.5:1 check. #008fa8 is for borders and decoration (3.8:1 as text), text and buttons use the grid's dark shades.
- **Corners:** none anywhere; buttons share one `btn` utility (Poppins Bold, superellipse corners where the browser has `corner-shape`, a small radius elsewhere). Dots stay round.
- **Fonts:** Poppins Bold for titles, headings and buttons, subheadings Poppins regular, body Montserrat. The stat numbers keep their weight.
- **Front page:** hero buttons are one cell split by a slash (filled left, clear right); the brand backdrop is flat teal with the dove (no rings, blobs or glow); the countdown straddles the hero and the next band; featured cards and the connect section are one continuous block with a teal rule between cells, the first featured card large with the next two beside it; the calendar is square; stats unchanged except its blurred glow.
- **Page background:** `PageBackdrop` draws flat overlapping palette circles behind every public page, shifting tone as each section reaches the middle of the window; sections no longer paint their own bands.
- **Footer:** Give sits right of the logo.
- **People tiles:** square photos, a 2px frame, even heights (two lines of name and title, then an ellipsis and the down arrow, whose details show it whole); no photo shows the initials on a palette color picked by the name.
- **Notices:** empty sections and form notes use the `notice` style (tinted panel, solid left bar) instead of dashed borders.
- **Timeline:** each year is a leaf, green now and turning gold then autumn going back, fully turned before 2000 (History page and the front page rail).
- **Admin home:** each group of cards has its own palette color.
- **No glow** anywhere: blobs, rings, the live-dot pulse and the stats glow are gone.
- [ ] Check in a browser, light and dark: every page, the backdrop's tone shifts, the split hero buttons (and on a phone), featured cards with 1, 2 and 3+ cards, the connect tabs, people tiles with long titles, the timeline leaves, the admin home. Superellipse corners show in Chrome and Edge; other browsers get a small radius.
- [ ] Production: any colors saved in Panel → Site settings → Colors still override the new defaults; clear them to get the palette.
## Deployed and checked (2026-09-30)
- [x] **Groups and US spelling (PR #17, v1.9.15-groups):** database backed up; migrations 052 and 053 ran; Drive folder renamed Requests/Groups; old links, admin text and the showcase records handled.
- [x] **Main (PR #14):** Node 22.13+ on the VPS; production nginx has HSTS, gzip and HTTP/2; migrations 037 to 043 ran; 640px copies made; Connect Nav emoji icons replaced with named ones.
- [x] **Content display (PRs #15 and #16):** database and uploads backed up; migrations 044 to 051 ran; nginx blocks for `/api/requests`, `/api/admin/files` and `/api/admin/import/docx`; Google service account, shared drive, Gmail and access groups set up.
- [x] **After deploying:** request emails set in Notices and tested; a test request made into a post; a PDF uploaded to Files and used in a link card; groups checked in the Panel; privacy contact email set in Site settings.
- [x] **Browser checks** in light and dark mode: every page, logos on dark, the new icons, the nav between 768 and 1024px, anchors, the hero headline, empty sections, the loading skeleton, Privacy and Terms, the data request form, the privacy notice, click-to-load embeds, Site settings → Colours, the Panel, the Request buttons and form.
## Front-end pages
- [x] **Chapters are groups** (38aff34, migration 052): kind `group`, table `groups`, pages at `/groups/<id>`, Community `#groups`, the front page count, the Request form type and `Requests/Groups`; the site's own chapter links in records rewritten. Names and prose written in the admin left as written.
- [x] **US English** (2ad65cd, migration 053): color, center, canceled, labeled and the rest, in UI text, help, comments, docs and names. Kept: the stored event status `'cancelled'` (shown as canceled), `aria-labelledby`, schema.org's `EventCancelled`, old migrations.
- [x] **Front page: Featured Content section** (d4f65d9, migration 030): add it under Front page → Sections; draws Front page → Featured cards.
- Three card types: a record on the site (title, picture and link fill themselves, anything typed overrides), a link ("Fetch preview" reads the page's title, description and preview image into the library), and a video (thumbnail with a play button; the player loads only when pressed).
- Cards are shared: `featured_cards` is owned polymorphically and `FeaturedCards.tsx` draws them, so the Community blog reuses both.
- [x] **Front page: featured event hero** (migration 033): Front page → Feature → "Featured event". The event's card beside the headline (photo or colour, title, theme, dates or schedule, place, tagline, action buttons, "Event details") under a "Featured event" badge. Front page → Featured event picks one; blank uses the countdown's event, and a pinned event that's over falls back the same way.
- [x] **Community page: Community blog section** (d374f9a, migration 031): first on the Community page, heading and blurb from the admin. Two halves, each pinned first then newest up to its slots: our posts, and community posts (pinned link/video cards, then the newest items from RSS/Atom feeds, read about every 30 minutes).
- [x] **Blog posts:** pages at /blog/<id> (no index page), content-block body, cover image, excerpt, date, tags, authors as person tiles (People records and/or a guest name and photo). Drafts until published; Listed works as everywhere else. Also on the QR page.
- [x] **Blog post PDF** (5dceeb5): print layout with author information, cover as a banner, the post's link and a QR code.
- [x] **Request form** (migration 046): one form at `/request` (footer link too), a tile per kind: blog post (new only), event, chapter, region (update only), partner, team, award, person; then new or update, a name, details, up to 3 files (.docx, PDF, JPEG, PNG, 10 MB each) and an email. `?type=chapter` opens it on one.
- Buttons: Community blog section and the end of every blog post ("Write for the blog"), Retreats (first band) and the front page calendar ("Add or update an event"), Local Chapters, Unity Regions ("Update a region"), Partner Organizations. None for people, teams or awards.
- Each type asks for its main details (4b249c9, migration 049, `fields` in `src/data/requestTypes.ts`), stored as one JSON column.
- The message (and a request's name) is marked Required on the Request, feedback and data request forms, with a countdown of characters still needed (110b655).
- [x] **Privacy Policy and Terms** (ee61568): written from what the code does. Covers collected data, no data on minors displayed, AI use (builds the site's structure, no database access, data not ingested), third parties, cookie policy. Data deletion requests have their own form. Privacy contact email in Site settings (migration 039).
- [x] **Cookie notice:** a dismissible notice linking to the privacy page, since nothing third-party loads before a click. The hero video and the schedule map are click-to-load (ee61568).
- [x] **Community links** (c62dc84): nav and the org pages' "All regions" / "All chapters" pointed at #local and #virtual, which don't exist; now #chapters and #regions. "Virtual Community" renamed "Unity Regions".
## Content blocks and editing
- [x] **Showcase seed:** `DB_PATH=./dev.db node src/seed-showcase.js` (in server/) writes a fully filled record of every kind, ids starting `showcase-`: /regions/showcase-region, /chapters/showcase-chapter, /teams/showcase-team, /awards/showcase-award, /people/showcase-person, /events/showcase-event (upcoming retreat), /events/showcase-series (weekly), /events/showcase-past-event, /blog/content-block-showcase (every block type).
- Published but unlisted by default. `--listed` puts them in lists, the map, counts and History; rerun without it to take them out. Refuses /var/lib/ngu unless `--production` (back up first, leave `--listed` off on a live site).
- [x] **Block editor** (migration 032): each block type shows only its own fields, with a plain-English name and description; a live preview under each open block; insert-below and duplicate on every repeater row.
- Text formatting in paragraphs, callouts, quotes and list items: **bold**, *italic*, [text](url), line breaks, blank line for a new paragraph.
- Types added: video (click to play), button, callout. Quotes get an attribution, images alt text separate from the caption.
- [x] **Schedule block** (migration 034): entries have a day (the tab), time, title, detail, location, person and link, and fold out for a description, the person's photo and page link, a graphic, and a Google map. One tab per day in entry order; the tab for today's weekday opens first; entries with no day get their own tab; arrow keys, Home and End move between tabs.
- [x] **Table of contents** (92e7938, migration 043): Blog posts → Show contents (off by default). With two or more headings, a sticky "On this page" column, the heading being read lit; a fold-out on phones. Content-block headings carry anchor ids everywhere. Sticky fix merged with PR #14.
- [x] **Link cards block** (4e9b4e3, migration 045): link, title, description, picture; "Fetch preview" fills the rest. Smaller cards, a grid of up to three in a row (9ff1cd6). "Choose a file" picks from Media → Files, taking the file's name and Drive's first-page picture.
- [x] **Table block** (migration 044): a row per line, cells split by |; any page can use it.
- [x] **Import from Word** (7f12824): Blog posts → Import from Word turns a .docx into an unpublished post (title, date, headings, paragraphs, lists, tables, bold, italic, links; images don't come over, the editor says how many). PDFs: save as .docx first. `docs/importing.md`. Tested with the Church Management Systems comparison doc (untracked, not committed); imported, authored and published after deploying.
## Entities and data
- [x] **Listed flag** (cd393e4, migration 027): separate from Published (which stays the hard gate). Unlisted: own page works; left out of list routes, a region's chapters, an org's events/teams/awards, the QR page, front page counts and countdown. Still shown where attached by hand: rosters, hosts, billed people, award recipients, timeline, a pinned countdown.
- [x] **People pages list their blog posts** (7876e06): published and listed posts they're an author of, as Community blog cards.
- [x] **Event card background image** (eaff238, migration 029): Events → Appearance → "Card background", under a light veil (`CARD_IMAGE_VEIL` in `EventList-Cards.tsx`); card size unchanged. Gradients dropped (migration 040), colour borders kept.
- [x] **Create or update records from a request** (4b249c9): Forms → Content requests shows the requested details; "Create <type> from this" opens the New editor filled in (URL ID, links, a description paragraph); an update picks the record (closest name first) and shows each requested value beside the current one ("Use this" / "Add it"). Nothing saves until Save. Decided 2026-09-29.
- [x] **Every record image is an upload** (a67ca98): a bare filename resolves to `/uploads/<file>`; only the nav/footer/admin NGU logos are bundled from `src/assets/logos`. Missing files (eg. `ngu-logo-white-bg.svg`, old public/org-logos) copied to the server.
## Admin page
- [x] **Admin home three cards across** (175a189): the home asks for the wide admin column.
- [x] **Editor side nav:** sticky "On this page" left of every editor (field groups, then collections with row counts, current one lit, red dot on a section with a save error); "Jump to" dropdown below lg. Editor pages widen to fit (`src/lib/adminWidth.tsx`). Each collection has its own card; repeater rows start folded, with Expand all / Collapse all. Stays in view while scrolling (960c854).
- [x] **Nav groups:** header menus Data (Events, Organizations, Teams, Awards, People, Blog posts), Pages (Front page, Timeline, Community blog section), Forms, Tools (Media, QR code generator, Video clips), Panel. Hover or focus drops the group down; the strip under the header lists it (the touch path). The admin home shows the same groups as cards. One list: `adminNav.ts`. Tools on the admin home (99c3a87); blog posts moved to Data (c03914a).
- [x] **Forms split** (99d83eb): Website feedback and Data requests, a card each on the admin home and tabs with what's new in each. Content requests: same triage (status, notes, delete), files downloadable, "Make a blog post from it" on a .docx; deleting a request deletes its Drive files.
- [x] **Pickers:** both centred (Tailwind's reset had removed the dialog's auto margin). The image picker has folder tabs (All, Logos, Images, Previews) opening on the field's folder, and a From requests tab (6ccbc03: photos sent with requests, the one being edited first; picking one copies it into the library once). The file picker has a tab per Drive folder.
## Server (settings, auth, file management)
- [x] **Media uploads** (eaff238, migration 028): files in `/var/lib/ngu/uploads` served by nginx; editors and up upload, admins and up delete; resized and converted to WebP unless "Keep original". Every image field has Upload and "Choose from library"; Tools → Media. Production setup done (`docs/media-uploads.md`); `server/pnpm-lock.yaml` committed (be07bc1).
- [x] **Image folders:** `/uploads/logos/`, `/uploads/images/`, `/uploads/thumbnails/` (link and Drive previews); existing images sorted once at boot, records rewritten (`docs/media-uploads.md`, Folders).
- [x] **Google Drive and Gmail:** a service account (`server/src/googleService.js`, no library) uploads to, downloads from and trashes in a shared drive, a folder per use found or made by name; the same account sends mail as a Workspace user. `docs/google-drive-and-mail.md`.
- Request files go in `Requests/<type>` (migration 050). Tools → Media → Requests (by type folder, linked to its request) and Forms → Content requests mark files Drive no longer has as Missing from Drive; Remove (admins) trashes it and takes it off the request.
- **Files for pages** (migration 048): Tools → Media → Files uploads PDF, Office, MP3, M4A and zip (50 MB) to "Media", shared as anyone with the link (Drive's own sharing, decided 2026-09-29). Folders three deep, New folder, Rename, Delete when empty (admins), a Folder dropdown to move a file. Delete checks what links to a file first. Files and folders added in Drive by hand are picked up.
- [x] **Email notices** (v1.9.5 to v1.9.7): Site settings → Notices, "Email new requests to" (content and data requests), with a test button.
- [x] **Site settings** (migration 035): Panel → Site settings, superadmins only. Site name, description, preview image, favicon, home-screen icon, each static page's title and intro, search indexing on/off. A setting wins, a blank falls back to site.json. Colours (migration 041) and Access (migration 047) live here too.
- [x] **SEO and page previews:** the API fills in each page's title, description, preview image, canonical URL and structured data (Organization, Event, BlogPosting); serves /sitemap.xml and /robots.txt. Unlisted records are noindex; missing ones 404. site.json holds the site's name, address, default description and preview image. Deploy steps done (`docs/seo.md`), sitemap submitted.
- [x] **Google sign-in:** "Sign in with Google" above email and password. Server-side OAuth code flow with PKCE; checks issuer, audience, expiry, verified email and the Workspace domain. The first sign-in links an admin-cli account by email. OAuth client set up (`docs/google-sign-in.md`).
- [x] **Access groups** (migration 047): Site settings → Access names a group per role. Someone in one gets a Google-only account with their highest group's role, rechecked at sign-in, hourly and on Panel → Re-sync now. Out of every group: disabled and signed out, back on when they return. Superadmins and admin-cli accounts are untouched. Panel → Check their groups tests an email. Decided 2026-09-29.
- [x] **Security:** server-side auth, field allowlists, cookies, scrypt hashing, parameterized SQL, upload checks, escaping and trimmed responses were already right. Added: rate limits on the real client IP, CSRF check on /api writes, security headers (HSTS from nginx), 90-day session cap, `__Host-` session cookie, five wrong passwords lock an email for 15 minutes, CSP in Report-Only with /api/csp-report. Row-level security isn't a SQLite feature; route role checks, descriptor allowlists and published/listed filters do that job.
- [x] **Organization-agnostic names:** ngu-tl → site-tl, nguLogo → siteLogo, __NGU_SITE__ → __SITE__, browser keys ngu- → site-, cookies site_session / site_oauth, QR files qr-<page>. Kept on purpose: record ids (ngu-board), /var/lib/ngu, ngu.db, the ngu-api service, the logo file, NGU as the organization's name in text.
## Tools
- [x] **Video clips** (migration 036, admins and up): paste a YouTube or Facebook link; yt-dlp downloads it (up to 4 h / 4 GB). Cut clips by start and end, shaped as filmed, 16:9, square or 9:16 with a movable crop; MP4 or MP3. One job at a time with progress; everything swept after a day. VPS setup done (`docs/video-clips.md`).
- Save to library or Save to Drive (migration 051), with a folder picker (Videos or Audio chosen first), streamed with a resumable upload.
- A finished download can be saved whole (06a0e07); it stays on the server to cut from either way.
- [x] **QR code generator** (/qr): "In the centre" (nothing, NGU dove, or any SVG in `src/assets/qr`, embedded so SVG and PNG downloads carry it); "A link I type" (site path, full http(s) address, or bare domain); code, background and dove colours with a reset, warning under 4:1 contrast or when inverted.
## Design and accessibility
- [x] **Design system** (c74ad74): colour tokens in index.css, gradients gone (migration 040), data colours through `src/lib/color.ts`, one BRAND accent and ACCENTS family. One source for colour defaults with a build check (f934b1d).
- [x] **Dark mode:** follows the system with a header toggle. Fixed: the Church Center popup (7c1723b), the featured timeline background (048c759), a light plate behind every logo (048c759, f59ab31). Palette for both modes in Panel → Site settings → Colours; saving refuses text under 4.5:1 in either mode (`server/src/theme.js`).
- [x] **Accessibility** (185f983): contrast fixes, inert hidden carousel and past cards, keyboard links on admin rows, modal mobile menu, skip link, focus ring, reduced motion (JS smooth scrolls too), alt text for blog covers and schedule graphics (migration 038). Admin-chosen colours as text go through `accentText`/`readableOn`.
- [x] **Icons:** Phosphor everywhere; platform links show their brand icon (3c02eb8: `PLATFORMS` in `src/lib/platforms.ts`, icons in `PlatformIcon.tsx`, shared with the footer and event cards).
## Newsletter (branch `newsletter-layout`)
- [x] **Every part editable and movable** (migration 060): a draft is one list of parts, top to bottom, each moved, copied or removed like content blocks, and each aligned left or center: the header (words, a PNG or JPEG logo, its band color or no band; remove the part to leave it out), the title, any email block, picked items (upcoming events, blog posts or front page cards, picked one by one in order, with the section's heading, its underline, the cards' left bar and the button label), and the footer (its lines and the line above). Dividers take a color, thickness and space above. Colors are the palette or none. A new draft starts with the parts the email always had. 057's drafts (title, intro, picks, footer, blocks) are dropped: that migration never reached a live database.
- [x] **More parts and room** (this branch, after v1.11.2): the builder takes the whole window (the editor beside a 42rem preview; `useWideAdminPage('full')`). A **Social bar** part: a colored band (or none) of the site's platform icons, each linked; no links added shows the footer's (`src/data/socialLinks.ts`). Icons are white or ink PNGs in `public/email/` (made by `scripts/email-icons.mjs`), picked to read on the band. An **Event countdown** part: pick an upcoming dated event (not a series); the email shows a picture the API draws when it's opened (`/api/countdown/<id>.png`: days, hours and minutes to local midnight in America/Chicago on its start date, then "Happening now", then "Thanks for joining us"), with a fixed "10 days to go" line under it as of copying, for clients that block pictures. Gmail keeps the picture from its first open.
- [x] **Resizable builder**: a handle between the parts and the preview (from lg up) sets the preview's width, from 320px (as a phone shows the email) to all but 360px of the parts list; drag it, or focus it and use the arrow keys, Home and End. Remembered in the browser.
- [ ] Production: install Poppins on the VPS for the countdown picture (CLAUDE.md, Deployment), or it uses a plain sans.
- [ ] Check in a browser: build an issue with every part, move them, center some, turn off the band and the lines, pick items and reorder them, save and reopen the draft, Post as blog post, paste the HTML into Mailchimp and a Gmail test send.
## Navigation (branch `audit-ui`)
- [x] **Side nav over everything**: its column had no z-index, so later layers (the Retreats carousel arrows) drew over its circle; it's z-20 now, and its empty area lets clicks through.
- [x] **Request button**: the National Retreats band no longer shows "Add or update an event" (`NO_EVENT_REQUEST_SCOPES` in `src/lib/sections.tsx`); where a request button stays, it takes its section's accent (border, text, hover tint).
## Audits
- [x] **Third audit, UI half** (branch `audit-ui`, v1.11.1-audit, not checked in a browser yet):
- Event cards: the photo is a lazy `<img>` of the -640 copy under the veil (was a full-size CSS background); the carousel draws only slides within 2 of the current one; past 12 events the dots become a "7 / 200" counter; the past grid shows one row collapsed, then 12 at a time with Show more, newest first (was oldest first).
- Community map: a search box over the list and grid (name and place); each region's grid shows 12, then Show all; below lg the list scrolls in its own 36rem box; hovering a tile no longer redraws the list.
- People tiles: one clip check for the whole list (was an observer per tile); 30 tiles, then Show all.
- Person pages: 6 events and 6 posts, then Show all; blog excerpts load only each post's first paragraph.
- Admin: pickers and the QR page's record select get a filter box past 50 options (`src/components/OptionFilter.tsx`); `/admin/options?only=` sends only the lists a form uses; Media library thumbnails use the -640 copy, videos don't preload, search waits 250 ms and drops stale answers (Drive files too), and says when the newest 500 are shown.
- Coming back to a page after the 60 s cache shows its last data while it refreshes (api.ts `peek`), instead of the skeleton.
- [ ] Check in a browser, light and dark: the Retreats carousel with many events (counter, swipe, height between cards), the past grid, the side nav over the carousel arrow, request buttons' colors, Community search and Show all (and the phone list box), people tiles Show all and cut-off titles, a person page, admin pickers' filter, an editor's dropdowns all filled, the Media library.
- [x] **Third audit** (2026-10-01, branch `audit-3`): security after the Drive integration and in general, and scalability at hundreds of records. Fixed: a zip bomb through the request form's .docx (each part unpacked once); request files must be named for what they are (a PDF named .html is refused); a team's roster hidden with its unpublished organization; `/people?ids=` no longer names a draft organization, and takes 200 ids (was 50, which dropped people from big people blocks); v_events takes the first published host (a draft partner's name and logo leaked into an event's preview) and reads event_hosts directly, about 18 times faster per lookup (migration 059, with an index on person_awards.event_id); group accounts can't sign in while access groups are off, and a sync can't undo a superadmin's disable; 64 KB body limit on login, feedback and csp-report; Drive pick-up races no longer 500; random upload boundary. Scalability: /events filters by scope, host, status and type on the server (each band fetches only its own; Home no longer prefetches every event); /organizations leaves out bodies and leadership (the map's group panel fetches its group); admin lists page with "Show more" and a real count; Content requests "find the record" searches by name; the newsletter asks for published posts only. Kept: viewers see Forms (decided 2026-09-28).
- [x] **First audit** (v1.9.0-audit, 2026-09-28): security (4066e9e), bugs (693dd84), cleanup (5274e09: no em-dashes, import extensions, dead code, shared helpers, hooks moved to src/lib), accessibility (185f983), leftovers (e4a9c96: one mediaUrl, orgPath on orgHref, one Logo component, adminSchema split per entity), more cleanup (d1a6332: url column type refusing unsafe schemes).
- [x] **Second audit** (2026-09-29, after v1.9.3-audit): bugs and security (be7e924: Panel role changes, hostile feed markup, SSRF ranges, prototype keys), speed (f72a960: lazy pages, preloads, 640px copies, gzip and HTTP/2), dark mode and design (048c759), structure (f934b1d).
## Decided / left as they are
- `noImplicitAny` stays off (about 480 errors); decided 2026-09-29, noted in CLAUDE.md.
- Viewers may see feedback emails, including data requests (2026-09-28).
- Left alone: the two date-range formatters and the two findOr404 helpers (different, not duplicates); content.js as one file; the chapter grid in OrgList-Map; unused `export` keywords on internal helpers; RetreatsBand's name.

162
docs/analytics-reports.md Normal file
View file

@ -0,0 +1,162 @@
# Analytics reports to Discord
The API can post the site's Plausible numbers to a Discord channel
(`server/src/analyticsReport.js`, migration 065):
- **Daily**: yesterday's visitors, pageviews, bounce rate, visit length,
and the top 3 pages and sources.
- **Weekly**, on Mondays: the last 7 days (Monday to Sunday), each
total with its change from the week before, and the top 5 pages and
sources.
Each one has its own switch in Panel → Site settings → Reports, and both
are off until it's turned on. They go out at 8:00 in `REPORT_TZ`. If the
server is down then, they go out when it comes back up later that day.
A restart never posts the same report twice. Nothing else on the site
depends on this.
| Setting on the `ngu-api` service | What it is |
| --- | --- |
| `PLAUSIBLE_API_KEY` | A Plausible Stats API key (step 1) |
| `DISCORD_WEBHOOK_URL` | The channel's webhook address (step 2) |
| `PLAUSIBLE_URL` | Where the API can reach Plausible. Default `http://127.0.0.1:8000` |
| `REPORT_TZ` | The time zone for "yesterday" and 8:00. Default `America/Chicago` |
Without the first two, no reports are sent, whatever the switches say.
## 1. The Plausible API key
1. Sign in to Plausible (the self-hosted one behind `/pa/`) as an owner
of the site.
2. Account settings → API keys → New API key. Pick **Stats API** if it
asks for a type, and name it eg. `ngu-api reports`.
3. Copy the key now. Plausible shows it only once.
The site has to exist in Plausible under the same domain the pages count
under: the hostname of `site.json`'s `url`, eg. `nextgenerationofunity.org`
(not `www.` and not `https://`). It already does if the dashboard shows
visits.
The reports use the Stats API v2 (`/api/v2/query`), which needs
Plausible Community Edition 2.1 or later. Check Settings or the page
footer for the version, and upgrade an older one first.
### Where Plausible listens
`PLAUSIBLE_URL` is the address the API calls directly, not the public
`/pa/` path. nginx's proxy for `/pa/` already points at it:
```sh
grep proxy_pass /etc/nginx/snippets/plausible-proxy.conf
```
If that shows `http://127.0.0.1:8000`, leave `PLAUSIBLE_URL` unset.
Otherwise set it to that address, eg. `http://127.0.0.1:8001`, or
`https://plausible.io` for Plausible's own hosting.
## 2. The Discord webhook
1. In Discord, open the channel's settings (the gear by its name) →
Integrations → Webhooks → New Webhook.
2. Name it eg. `NGU analytics`, give it an avatar if you like, and check
that it posts to the right channel.
3. Copy Webhook URL. It looks like
`https://discord.com/api/webhooks/123456789/AbCdEf...`.
You need Manage Webhooks on the channel. Anyone who has the address can
post to the channel, so treat it as a password.
## 3. The service
Both values are secrets, so put them in a file only root can read
rather than in the unit itself (a `systemctl edit` override is readable
by every user on the box):
```sh
sudo mkdir -p /etc/ngu
sudo tee /etc/ngu/analytics-reports.env >/dev/null <<'EOF'
PLAUSIBLE_API_KEY=<the key from step 1>
DISCORD_WEBHOOK_URL=<the webhook address from step 2>
EOF
sudo chmod 600 /etc/ngu/analytics-reports.env
```
Add `PLAUSIBLE_URL=` or `REPORT_TZ=` lines to the same file if you need
them. Then point the service at it:
```sh
sudo systemctl edit ngu-api
```
```ini
[Service]
EnvironmentFile=/etc/ngu/analytics-reports.env
```
systemd reads the file as root before it starts the service, so the
service's own user doesn't need to be able to read it.
Back up the database first (migration 065 adds the switches and runs at
the next start), then:
```sh
sudo systemctl restart ngu-api
```
No nginx change is needed: the API calls Plausible and Discord itself.
## 4. Try it
Send one straight away, whatever the switches say, while the service is
running:
```sh
cd /srv/ngu-api
sudo bash -c 'set -a; . /etc/ngu/analytics-reports.env; set +a;
SITE_CONFIG=/srv/ngu-api/site.json DB_PATH=/var/lib/ngu/ngu.db \
node src/analyticsReport.js daily'
```
`Sent the daily report.` means it's in the channel. Use `weekly` for the
weekly one. Sending one by hand doesn't stop that day's scheduled
report.
## 5. Turn them on
Panel → Site settings → Reports: set **Daily analytics report** and/or
**Weekly analytics report** to On, and save. Set one back to Off (or
blank) to stop it. The change counts from the next check, within 15
minutes.
The switches are per database, so the dev server only posts if its own
database has them on and its own service has the settings. Leave the
settings off dev, or it reports as `dev.nextgenerationofunity.org`.
## Checking it
Every report is logged:
```sh
journalctl -u ngu-api --since today --no-pager | grep analytics
```
- `analytics daily report sent for 2026-10-05`: it went out.
- `Plausible answered 401`: the API key is wrong or was deleted. Make a
new one (step 1).
- `Plausible answered 400` or `404` naming the site: Plausible has no
site under that domain. Compare `site.json`'s `url` with the domain in
Plausible's site list.
- `Plausible answered 404` with no site named: Plausible is older than
2.1 and has no v2 API.
- `fetch failed` or `ECONNREFUSED`: Plausible isn't at `PLAUSIBLE_URL`
(see Where Plausible listens).
- `Discord answered 401` or `404`: the webhook was deleted or the
address is wrong. Make a new one (step 2).
- Nothing at all: check that both settings are in the service's
environment (`sudo systemctl show ngu-api -p EnvironmentFiles`), that
the switch is On, that it's past 8:00 in `REPORT_TZ`, and for the
weekly report, that it's Monday.
A failed report isn't retried that day, so a broken setup logs one line
a day, not one every 15 minutes. Fix the cause, then send it by hand
(step 4) if you still want it.

46
docs/drafts.md Normal file
View file

@ -0,0 +1,46 @@
# Drafts
Any record the admin edits (events, people, organizations, blog posts,
the front page, the site pages, Navigation, Site settings...) can be
saved as a draft instead of going live (migration 077). One draft per
record; anyone who can edit the record can save, preview, publish or
discard it.
## In the editor
- **Save draft** keeps the form as the record's draft. It's checked the
way a save is (same field errors), but nothing on the site changes.
- **Preview** saves the draft and opens the record's page in a new tab
showing it, with an amber bar ("Previewing a draft"). Only a
signed-in admin account (viewer and up) sees the draft; anyone else
opening that address sees the live page. Stop previewing in the bar
returns the tab to the live site.
- **Publish** (the Save button, while there's a draft) saves it for
real and drops the draft.
- **Discard draft** throws it away; the live version is untouched.
Opening a record that has a draft opens the draft, with a note saying
who saved it and when. If the live record was saved after the draft was
started, the note says so: publishing replaces those changes. Lists
mark records with a draft.
Records not yet created have no drafts: Create is the only save (leave
them unpublished until they're ready).
## How it works
`server/src/drafts.js`. A draft is the editor's whole form, as a save
would send it. Saving one applies it inside a transaction that is
always rolled back (`rolledBackSync` in `server/src/db.js`), so it's
validated without being written. A preview is a public API read sent
with `X-Draft-Preview: <entity>/<id>` (`src/lib/api.ts` adds it in a tab
opened with `?preview=`): the server opens a second connection to the
database, applies the draft in a transaction there, answers the read
from it, and rolls back. WAL keeps those writes unseen by every other
request. Public reads carry `Vary: X-Draft-Preview`, so a browser never
mixes a cached live answer with a preview.
`tx()` nests as a savepoint, which is what lets a save run inside the
rolled-back transaction. Where each entity's page is: `PREVIEW_PATHS` in
`src/lib/adminSchema.ts` (an entity without one has drafts but no
Preview button).

View file

@ -0,0 +1,251 @@
# Google Drive and Gmail
The site keeps files in one Google **shared drive**: the Request form
(`/request`) puts what people send in its "Requests" folder, and files
uploaded in Tools → Media → Files, for pages to link to, go in its
"Media" folder (see "Files for pages" below). New requests can be emailed to whoever is listed in
Panel → Site settings → Notices. Both go through one Google **service
account** (`server/src/googleService.js`). Nothing here is needed for
the rest of the site; until it's set up, the form takes no files and no
mail goes out.
| Setting on the `ngu-api` service | What it is |
| --- | --- |
| `GOOGLE_SERVICE_ACCOUNT` | Path to the service account's key file, eg. `/etc/ngu/google-service-account.json` |
| `GOOGLE_SHARED_DRIVE` | The shared drive's **id only**, eg. `0ACUt32ze-CVGUk9PVA`: never the whole address (see step 2) |
| `GOOGLE_MAIL_FROM` | The Workspace address notices are sent from, eg. `web@nextgenerationofunity.org` |
Files need the first two; mail needs the first and third.
## 1. The service account
1. In Google Cloud Console (the project that holds the Google sign-in
client is fine), enable the **Google Drive API** and the **Gmail
API**.
2. IAM & Admin → Service accounts → Create. Name it eg. `ngu-site`. It
needs no roles on the project.
3. Open it → Keys → Add key → JSON. Copy the file to the VPS, outside
the app and the repo:
```sh
sudo mkdir -p /etc/ngu
sudo mv ngu-site-*.json /etc/ngu/google-service-account.json
sudo chown <ngu-api user>: /etc/ngu/google-service-account.json
sudo chmod 600 /etc/ngu/google-service-account.json
```
Note the account's email (`ngu-site@<project>.iam.gserviceaccount.com`)
and, from its Details page, its **Client ID** (a long number).
## 2. The shared drive
A service account has no Drive storage of its own, so everything goes in
a **shared drive**.
1. In Google Drive, make (or pick) a shared drive, eg. "NGU Website".
2. Shared drive → Manage members → add the service account's email as
**Content manager** (it makes folders and deletes files).
3. Open the shared drive itself (not a folder in it). Its address is
`https://drive.google.com/drive/u/2/folders/0ACUt32ze-CVGUk9PVA`;
the id is only the part after `folders/`, here `0ACUt32ze-CVGUk9PVA`.
A shared drive's id starts with `0A`. Leave out the address, the
`/u/2/` part and anything after a `?`: pasting the whole URL gives
`404 File not found` on every upload.
### Folders in it
The site finds each folder it uses by name, at the top of the shared
drive, and makes it the first time it's needed. Nothing needs making by
hand.
| Folder | Used by | Set in |
| --- | --- | --- |
| `Requests/<type>` | Files sent with the Request form, a folder per type (`Requests/Groups`, `Requests/Blog Posts`...) | `DRIVE_FOLDER` and `TYPE_FOLDERS` in `server/src/routes/requests.js` |
| `Media` and folders in it | Files for pages to link to (Tools → Media → Files), in folders you make there | `FOLDER` in `server/src/routes/files.js` |
A new use calls `driveUpload("<Folder>", name, mime, bytes)` from
`server/src/googleService.js`; a path such as `"Media/2026"` makes each
level. Add it to this table.
Files for pages went in a folder called `Blog` before v1.9.10. If the
shared drive has one, rename it to `Media` in Drive: the files inside
keep working and stay listed, and nothing is made twice.
Folders are matched by name, so renaming or moving one in Drive makes
the site start a new one under the old name (files already stored keep
working: they're found by their own id). People can add their own
folders to the drive; the site ignores them.
Request files are named `Request 12 - original name.docx`, so the number
matches the one in Forms → Content requests. Deleting a request in the
admin deletes its files from Drive too. Request files from before the
per-type folders stay where they are, in `Requests` itself.
Tools → Media → **Requests** lists every request file by its type folder,
each with its request; Forms → Content requests lists a request's own.
Both say **Missing from Drive** for a file Drive no longer has under
`Requests` (deleted, or moved out, by hand): it can't be downloaded or
made into a post, but can be taken off the request. **Remove** (admins
and up) trashes a file in Drive and takes it off its request; the
request itself stays.
**Deleting means Drive's trash.** Whatever the admin deletes (a
request's files, a file, an empty folder) goes to the shared drive's
trash, which keeps it 30 days; restore it from there if needed. A
shared drive's Content manager, the service account's role, can trash
but not permanently delete.
## 3. Gmail (domain-wide delegation)
For the service account to send as a Workspace user:
1. Google Admin console → Security → Access and data control → API
controls → **Manage domain wide delegation** → Add new.
2. Client ID: the service account's Client ID from step 1.
OAuth scopes: `https://www.googleapis.com/auth/gmail.send` (and,
for access groups, `https://www.googleapis.com/auth/admin.directory.group.member.readonly`,
comma separated: `docs/google-sign-in.md`)
3. `GOOGLE_MAIL_FROM` is the address it sends as. It must be a
**user** in the Workspace, one that signs in and has Gmail: not a
group (eg. `webb-admin@`, even mail-enabled), not an alias. The
service account acts as that user, and a group can't be acted as;
Google answers `Client is unauthorized to retrieve access tokens`.
A dedicated user such as `web@` keeps the sent copies out of anyone's
own mailbox. A group is fine as a **recipient** (below): each member
gets the notice.
Then in the admin, Panel → Site settings → Notices → "Email new
requests to": one or more addresses, separated by commas. Each new
content request and data request sends one plain-text email with a link
to the queue; replying goes to the person who sent the request.
**Send a test notice**, under that box, emails whatever addresses are in
it (saved or not) straight away and shows the result on the page:
where it was sent from, or Google's reason for refusing. A new
delegation can take a while to start working, so retry it after a few
minutes before changing anything.
## 4. The service and nginx
```sh
sudo systemctl edit ngu-api
```
```ini
[Service]
Environment=GOOGLE_SERVICE_ACCOUNT=/etc/ngu/google-service-account.json
Environment=GOOGLE_SHARED_DRIVE=<shared drive id, eg. 0ACUt32ze-CVGUk9PVA>
Environment=GOOGLE_MAIL_FROM=web@nextgenerationofunity.org
```
nginx caps `/api/` bodies at 64k, so the form needs its own block in
the site's `server` block, beside `/api/admin/import/docx` (`nginx-dev`
has it):
```nginx
location = /api/requests {
proxy_pass http://127.0.0.1:3001;
# the usual proxy_set_header lines
proxy_read_timeout 120s;
client_max_body_size 31m;
}
# Tools → Media → Files: one file of up to 50 MB
location = /api/admin/files {
proxy_pass http://127.0.0.1:3001;
# the usual proxy_set_header lines
proxy_read_timeout 180s;
client_max_body_size 51m;
}
```
`sudo nginx -t && sudo systemctl reload nginx && sudo systemctl restart ngu-api`.
## Checking it
- Mail: Panel → Site settings → Notices → **Send a test notice**.
- Send a request with a small file at `/request`. The journal shows
`feedback #N (content: new blog, 1 files)`, and with mail on,
`feedback #N: notice sent to 1`.
- The file is in the shared drive's Requests folder (made on the first upload), and downloads from Forms → Content
requests.
- `Client is unauthorized to retrieve access tokens` (or
`unauthorized_client`) on mail: `GOOGLE_MAIL_FROM` is a group or alias
rather than a user, or the delegation (step 3) is missing, has the
wrong Client ID (the service account's numeric Unique ID), or a scope
other than exactly `https://www.googleapis.com/auth/gmail.send`, or
is too new to have taken effect. `404 File not
found` on upload means `GOOGLE_SHARED_DRIVE` isn't the bare id (a
whole URL, say) or the service account isn't a member of the shared
drive.
## What the form takes
Up to 3 files of 10 MB each: Word documents (.docx), PDFs, JPEG and PNG,
checked by their contents rather than their names
(`server/src/routes/requests.js`). A Word document on a request can be
turned into an unpublished blog post from the queue ("Make a blog post
from it"), the same conversion as Blog posts → Import from Word
(`docs/importing.md`).
## Files for pages
Tools → Media → **Files** (editors and up upload, admins and up delete)
puts a file in the shared drive's `Media` folder and shares it as
**anyone with the link can view**, so visitors open it in Drive's viewer
without signing in. Content block links pick from it with **Choose a
file**: paragraph, button and image links, list and link-button items,
and link cards. A link card also takes the file's name as its title and
Drive's picture of the first page as its picture; the card says "Google
Drive" above the title.
- Types: PDF, Word, Excel and PowerPoint (.docx, .xlsx, .pptx), MP3,
M4A and zip, up to 50 MB. The name and the contents must agree (a PDF
named `.mp3` is refused). Older Office formats (.doc, .ppt) aren't
taken: save them in the new format first.
- The first-page picture: Drive draws one for PDFs and Office files a
little after upload. The server asks at once and again over the next
few minutes, and saves it into the image library as an ordinary
upload. Audio and zips get an icon in the admin and no picture.
- **Files put in the Media folder in Drive itself** (dragged in, made
there, moved there) are listed too: opening the Files tab or a
"Choose a file" picker looks in the folder (at most every 30
seconds), adds anything new, shares it the same way and fetches its
preview. Google's own Docs, Sheets and Slides count; folders inside it
and shortcuts don't. A file Drive won't share with anyone who has the
link is named in a red note instead of listed, and tried again every
ten minutes.
- **Folders:** Media → Files has a tab per folder under `Media` (up to
three deep), and uploads go into the one showing. **New folder** makes
one inside it, **Rename** renames it (and everything in it follows),
and **Delete** (admins and up) removes it once it's empty. Each file
has a Folder dropdown to move it. Choose a file has the same tabs. A
folder made in Drive itself, and a file moved there by hand, show up
on the next look.
- Deleting a file in the admin moves it to Drive's trash; the delete says
first which records still link to it (those links stop working).
Deleting it in Drive by hand leaves a broken link and a list entry
that can still be deleted.
- **"Too large for the web server (HTTP 413)"** on upload (older builds
said "Server did not return JSON", with nothing in the journal): nginx
refused the file before it reached the API, because the site has no
`location = /api/admin/files` block (above), so the 64k `/api/` limit
applies. `sudo tail /var/log/nginx/error.log` shows "client intended
to send too large body".
**Sharing has to be allowed.** Uploads fail with "Drive wouldn't share
it with anyone who has the link" unless both allow it:
1. Admin console → Apps → Google Workspace → Drive and Docs → Sharing
settings: sharing outside nextgenerationofunity.org is on (at least
for the organizational unit the service account's delegated user is
in, and for shared drives: "Allow people outside ... to access files
in shared drives").
2. The shared drive itself → Shared drive settings: "Allow people who
aren't shared drive members to access files" and sharing outside the
organization are on.
Files the Request form stores are never shared this way; only files
uploaded in Tools → Media → Files are.

View file

@ -6,7 +6,18 @@ off until the service has an OAuth client ID and secret.
## Who gets in
Only accounts that already exist. Create them as before with
Three kinds of account can sign in with Google:
- **Group accounts**, when access groups are set up (below): anyone in
one of the site's Workspace groups. Their account is made at their
first sign-in, and their role follows the group.
- **Accounts made with admin-cli**, as before.
- **Profile accounts** (members, `docs/profile-accounts.md`), invited
from Data → Profile accounts. These are the one case outside the
Workspace: any Google account under the invited email, from the
site's `/sign-in` page or the invite's welcome page.
Created with
`admin-cli.js add <email>` (the password it asks for stays as a way in
if Google is ever unavailable). The first time that person signs in with
Google, their Google account is linked to the admin account with the
@ -14,12 +25,80 @@ same email; after that it matches by the link, even if the email later
changes. `admin-cli.js list` shows which accounts are linked.
Refused, with a message on the login page: no admin account for that
email, an email already linked to a different Google account, a
email (and in no access group), an email already linked to a different Google account, a
disabled account, any account outside the Workspace domain (checked by
Google's `hd` claim, not just the email), an unverified email.
Google's `hd` claim, not just the email) unless it's a profile account's,
an unverified email.
Code: `server/src/googleAuth.js` (the Google side) and
`server/src/routes/auth.js` (matching and linking accounts).
Code: `server/src/googleAuth.js` (the Google side),
`server/src/routes/auth.js` (matching and linking accounts) and
`server/src/accessGroups.js` (access groups).
## Access groups
Panel → Site settings → **Access (Google groups)** names a Workspace
group for each of Admin, Editor and Viewer, eg.
`web-admins@nextgenerationofunity.org`. Any of them may be blank.
- **First sign-in:** someone in one of the groups signs in with Google
and gets an account with the highest role their groups give (in both
the editors and viewers groups: editor). No password: Google only.
Groups inside groups count.
- **The role follows the group**, checked at every sign-in, about once
an hour while they're signed in, and whenever a superadmin presses
Panel → Google groups → **Re-sync now**. Moved to another group: the
role changes. Out of every group: the account is disabled and signed
out; put back in one, it's turned on again at the next sign-in or
re-sync.
- **In the Panel**, a group account says "Google group" and its role
can't be changed there (change the membership instead). Disable still
works, and sticks: no group check turns back on an account a
superadmin disabled.
- **Not affected:** superadmins (there's no superadmin group) and
accounts made with admin-cli, which keep the role set in the Panel
whatever groups they're in.
- **If Google can't be asked** (an outage, a setup mistake), a sign-in
is refused ("Couldn't check your Google groups"), but the hourly
check leaves accounts as they are and tries again; nobody is signed
out because Google was down. Password and admin-cli accounts still
get in.
Panel → Google groups → **Check their groups** shows what role an email
would get, changing nothing: the quickest check of the setup.
### Setting it up
Group lookups use the service account from
`docs/google-drive-and-mail.md` (step 1 there), through the Admin SDK
Directory API:
1. Cloud Console, the service account's project → APIs & Services →
Library → enable the **Admin SDK API**.
2. Admin console → Security → Access and data control → API controls →
Manage domain wide delegation → the service account's entry → Edit.
Add the scope (comma separated, beside `gmail.send`):
`https://www.googleapis.com/auth/admin.directory.group.member.readonly`
3. Pick a Workspace **user** who can see the groups' members: a super
admin, or an admin with a role that includes Groups → Read. The
lookups are made as them. Set it on the service:
```ini
Environment=GOOGLE_DIRECTORY_AS=<that user, eg. it-admin@nextgenerationofunity.org>
```
4. Make the groups in Google Admin (or Groups), add people, and put the
addresses in Site settings → Access. Restart `ngu-api` after the
`systemctl edit`.
`GOOGLE_SERVICE_ACCOUNT` and `GOOGLE_DIRECTORY_AS` without any groups
set changes nothing; groups set without them show a warning in the
Panel and Google sign-in works as before.
Errors in the Panel or journal (`grep access`): `groupKey` means a group
address in Site settings isn't a group Google knows; `unauthorized_client`
means the delegation or scope (step 2) is missing, or
`GOOGLE_DIRECTORY_AS` isn't a user; `Not Authorized to access this
resource` means that user can't read the group.
## Setting up the OAuth client

76
docs/importing.md Normal file
View file

@ -0,0 +1,76 @@
# Importing a Word document as a blog post
Admin → Data → Blog posts → **Import from Word** (editors and up). Pick
a `.docx`; the server turns it into a new blog post, **unpublished**, and
opens it in the editor with a note of what came over. Check it, add the
authors and a cover, then tick Published.
## What becomes what
| In the document | In the post |
| --- | --- |
| The Title, or the first Heading 1 | The post's title (the file name if there's neither) |
| A date line right under the title, eg. "Sep 28, 2026 · @Aidan" | The post's date (the rest of that line is dropped) |
| Heading 1 and Heading 2 | Heading blocks |
| Heading 3 and smaller | Subheading blocks |
| Paragraphs | Paragraph blocks |
| A run of bulleted or numbered paragraphs | One List block, one item each |
| Tables | Table blocks: a row per line, cells split by `\|`, the first row the header |
| Bold, italic, links (http, https, mailto) | `**bold**`, `*italic*`, `[text](url)`, in paragraphs, list items and table cells |
And lines written a certain way, in any style:
| In the document | In the post |
| --- | --- |
| A line starting `Tab:`, eg. `Tab: Overview` | A Tab block: the post is split into tabs from there (the blocks before the first are the intro above the tabs) |
| The Quote style | A Quote block; a dash and a name at the end (`... - Jane Doe`) is who said it |
| The Intense Quote style | A Callout block |
| A line of `---` alone | A Divider |
| A YouTube, Vimeo or Facebook link alone on its line (the link text can be anything) | A Video block |
| `Button: Register`, with "Register" linked | A Button block, its label and link |
The same table is on Blog posts, beside Import from Word (What becomes what).
A post with three headings or more gets **Show contents** turned on. The
URL ID is the title as a slug, with `-2`, `-3` when it's taken.
Not carried over: images and drawings (the note says how many; add them
as Image blocks), text boxes, footnotes, comments, colors and fonts.
Numbered lists come over as bulleted lists.
The conversion is `server/src/docx.js`; the route is
`server/src/routes/import.js`.
## PDFs
A PDF has no headings, lists or tables inside it, only positioned
text, so it can't be converted the same way. Open it in Word (or Google
Docs) and save it as `.docx` first, or have it converted by hand.
## Table blocks
Any page's content blocks can have one (Content blocks → Type → Table):
```
Platform | Monthly cost | Best for
Zeffy | Free | Fee-free giving
[Breeze](https://www.breezechms.com) | $72 | **Small churches**
```
A literal `|` inside a cell is written `\|`. On a phone a wide table
scrolls sideways in its box.
## nginx
nginx caps `/api/` bodies at 64k, so the upload needs its own block
(in the site's `server` block, beside `/api/admin/media`; `nginx-dev`
has it):
```nginx
location = /api/admin/import/docx {
proxy_pass http://127.0.0.1:3001;
# the usual proxy_set_header lines
proxy_read_timeout 60s;
client_max_body_size 11m;
}
```

View file

@ -15,18 +15,58 @@ in the `media` table (`server/src/migrations/028_media.sql`).
- **Keep original** stores the file exactly as uploaded (up to 10 MB),
metadata and all.
- SVGs are always kept as they are.
- Accepted types: JPEG, PNG, GIF, WebP, SVG. The type is read from the
file's contents, not its name.
- A photo field with a shape (people, event photos and card
backgrounds, blog covers, hero photos, link card pictures, block
images and schedule graphics; not logos) opens **Frame the photo**
before uploading a JPEG, PNG or WebP: drag and zoom it inside the
field's shape, or pick another (As uploaded keeps the photo's own).
The framed part is what's uploaded; nothing about the framing is
saved, so framing again means uploading again. Upload as is skips
it. A field's shape is its `crop` option (`src/components/admin/fields.tsx`).
- Accepted types: JPEG, PNG, GIF, WebP, SVG, and WebVTT captions
(`.vtt`, kept as they are, always in `captions/`). The type is read
from the file's contents, not its name: a captions file has to start
with `WEBVTT`.
- Every upload and save asks for a **Name** (prefilled: the file's own
name, "Video frame at 1:23", a clip's title and span). It's the
library's name and the readable part of the file's, plus a short
random ending: `images/spring-retreat-group-3f9c1a.webp`
(`slugify` and `storedNameFor` in `server/src/media.js`). Fetch preview
names its picture after the page's title.
- **Rename** (Media page, editors and up) changes both. The file and its
small copy move to a new name, and every record that names the file is
pointed at it in the same step (the same search the delete check
uses). Anything outside the site still holding the old address (a
sent newsletter, a shared link) stops working. A rename that only
changes capitals or punctuation keeps the file where it is.
- Editors and up can upload. Admins and up can delete. The Media page
shows which tables still use a file before deleting it, because
nothing stops a file a record uses from being deleted.
Limits and sizes are constants at the top of `server/src/media.js`.
## Folders
Images are kept in folders by what they're for (`FOLDERS` in
`server/src/media.js`), and the paths records store include them:
| Folder | What goes in it |
| --- | --- |
| `logos/` | Uploads from logo and icon fields (organization, team, award and event logos, the favicon and home-screen icon): the fields with `folder: "logos"` in `src/lib/adminSchema/` |
| `images/` | Every other upload: photos, backgrounds, covers, block images |
| `thumbnails/` | Pictures the site saves by itself: link previews (Fetch preview) and Drive files' first pages |
| `captions/` | WebVTT files for uploaded videos: the Captions field of video blocks and the hero's Video captions (migration 066). YouTube, Vimeo and Facebook videos show their own |
Each image's `-640.webp` small copy sits beside it. Video and audio
clips (Tools → Video clips) stay in the root. The Media page and every
image picker have a tab per folder; a picker opens on its field's
folder, and uploads there.
nginx needs no change: `location /uploads/` already serves the folders.
## Files copied in by hand
A file put straight into the uploads directory (with `scp`, say) shows
up in the library the next time the Media page or an image picker opens:
A file put straight into the uploads directory, or into one of its
folders (with `scp`, say), shows up in the library the next time the Media page or an image picker opens:
the server registers any image it finds there without a record, under
the file's own name, kept as it is (not resized). Anything that isn't a
JPEG, PNG, GIF, WebP or SVG is ignored. A record can name such a file by
@ -78,8 +118,22 @@ which git ignores). The API serves `/uploads/` itself, and Vite proxies
}
```
Filenames are random and never reused, so `immutable` is safe.
Every stored name ends in a random part and a new one is never an
existing file's, so `immutable` is safe; a rename makes a new name
rather than changing a file in place.
4. `sharp` is a server dependency now: run `pnpm install` in
`/srv/ngu-api` after the deploy. It ships prebuilt Linux binaries,
so no build tools are needed.
5. Captions need nginx to send `.vtt` files as `text/vtt` (Firefox
won't show them otherwise, and `nosniff` stops guessing). Check:
```sh
grep vtt /etc/nginx/mime.types
```
If nothing comes back, add `text/vtt vtt;` inside the `types { }`
block of `/etc/nginx/mime.types`, then
`sudo nginx -t && sudo systemctl reload nginx`. Not in the site's
own file: a `types` block there replaces the whole list.

70
docs/performance.md Normal file
View file

@ -0,0 +1,70 @@
# Performance
What keeps the site fast, and what nginx has to do for it.
## nginx
In the site's `server` block (both are in `nginx-dev`):
```nginx
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 5;
gzip_min_length 1024;
gzip_types text/css application/javascript text/javascript application/json
image/svg+xml application/xml application/rss+xml text/plain;
listen 443 ssl http2;
listen [::]:443 ssl http2;
```
Ubuntu's `nginx.conf` turns gzip on for `text/html` only, so without
`gzip_types` the JS, CSS, JSON and SVG go out full size (the main JS is
about 314 kB, about 98 kB gzipped). Check with
`curl -sI -H 'Accept-Encoding: gzip' https://<site>/assets/<file>.js | grep -i content-encoding`.
`http2` on the `listen` line works on every nginx; 1.25.1 and later
also take a separate `http2 on;`.
## Caching
- `/assets/` (hashed build files): a year, `immutable` (nginx).
- `/uploads/`: 30 days, `immutable` (nginx). Filenames are random and
never reused.
- Page HTML: `no-cache` (the API, `routes/pages.js`). The page names the
build's hashed assets, so a cached old page after a deploy would ask
for files that are gone.
- Public API reads: 60 s, plus 5 minutes stale while revalidating
(`CACHE` in `server/src/shape.js`).
- RSS feeds: read at most every 30 minutes; a visitor never waits for
one after the first read (`server/src/feeds.js`).
## The bundle
Every page, the front page included, and the whole admin, loads when
first visited (`src/App.tsx`). A tab still running an old build that
asks for a page removed by a deploy reloads once to pick up the new
one.
The server tells the browser to fetch the front page's data
(`/api/site-pages/home`) and its hero's first photo while the JS
downloads (`preload` in `server/src/pageMeta.js`).
## Images
Every raster upload gets a copy at most 640 px on its longer side,
`<name>-640.webp`, beside it in the uploads folder
(`server/src/media.js`). Logos, avatars and card pictures load that copy
(`useSmallImage` in `src/lib/useSmallImage.ts`) and fall back to the
full file if it's missing. The server makes any missing copies in the
background when it starts, so older uploads and files copied in by hand
get one too; deleting an upload deletes its copy.
## Server
- Password checks run off the event loop (`verifyPassword`, async
scrypt), so a login doesn't stall other requests.
- Only `/api/admin/*` is logged per request; nginx's access log has the
rest.
- ffmpeg encodes run at `nice 19` on Linux, so a clip doesn't slow the
site down.

46
docs/planning-center.md Normal file
View file

@ -0,0 +1,46 @@
# Planning Center
Admin → Data → Planning Center (admins and up) brings one Planning
Center People list into the site's people, by hand (migration 085).
One way: nothing is sent to Planning Center.
## Setup
1. In Planning Center, make (or pick) a People **list** of the people who
should be on the site, eg. "Website". Its number is in its address:
`people.planningcenteronline.com/lists/1234567`.
2. Admin → Panel → Site settings → **Planning Center → People list**: that
number.
3. A personal access token: https://api.planningcenteronline.com/oauth/applications
→ Personal Access Tokens → New, as an account that can see that list.
Put its two halves on the service (`systemctl edit ngu-api`):
```
[Service]
Environment=PCO_APP_ID=...
Environment=PCO_SECRET=...
```
then `systemctl restart ngu-api`. (`PCO_BASE` overrides the API's
address, for testing.)
## Using it
**Compare with Planning Center** fetches the list. Each member shows:
- the site person they're **linked** to, or one **suggested** by the
same email (private or public), else the same name;
- for that person, each field that would change: name, sort name
("Last, First"), private email and private phone, the site's value
beside Planning Center's.
For each, choose **Link to** the suggestion (and whether to update it
from Planning Center), link to **someone else**, **make a new person**
(unpublished, to fill in and publish later), or **Skip**. **Apply**
writes what you chose, all at once; nothing changes before. Planning
Center wins where both have a value; a blank in Planning Center leaves
the site's. Once linked, a person is matched by Planning Center's id
from then on, whatever their name or email becomes.
Code: `server/src/planningCenter.js` (the API, the comparison, the
writes), `server/src/routes/pco.js`, `src/pages/admin/AdminPco.tsx`.

78
docs/profile-accounts.md Normal file
View file

@ -0,0 +1,78 @@
# Profile accounts
People can have an account on the site for their own profile (migration
076). Nobody signs up: an admin invites them.
## How it goes
1. **Invite.** Data → Profile accounts → Invite someone (admins and up):
an email, and a name if you like. That makes a *member* account with
no password, and shows its invite link once, for 14 days. Copy it to
send yourself, or press Email invite to send a fresh one through
Gmail (needs Gmail set up, `docs/google-drive-and-mail.md`; the link
shown before stops working).
2. **Sign up.** The link opens `/account/welcome`: they set a password,
or continue with Google under the invited email (any Google account,
not only @nextgenerationofunity.org, when Google sign-in is on,
`docs/google-sign-in.md`). Either takes up the invite.
3. **Claim.** On `/account` (Your profile, also the footer's Sign in
link) they pick the People record that's them and send the request.
It waits under Claims on Data → Profile accounts until an admin
approves or declines it. An admin can also set an account's record
directly there.
4. **Edit.** With a record, they edit its pronouns, tagline, location,
public email and phone, bio and photo, and tick what to hide on the
site. Their name, publishing and everything else stay the admin's.
Changes are live as soon as they save.
A member is below viewer: signed in to the site, never to the admin
(`/api/admin` refuses anything under viewer, `requireStaff` in
`server/src/auth.js`). Staff accounts can claim a record too, from
`/account`.
Forgotten password: on the account's row, New sign-in link (or Email a
sign-in link); opening it sets a new password.
Turn off stops an account signing in and ends its sessions. Remove
deletes the account; its People record stays.
## What "hidden" does
Each hidden part (photo, pronouns, tagline, bio, public email, public
phone, location, links) stays in the record, and the admin's People
editor shows the same switches (Hidden on the site). The site never
shows it: every public read goes through the `v_people_public` view,
which nulls hidden fields, and person links are left out when links are
hidden (`loadLinks` in `server/src/shape.js`). When adding a public
query on people, read `v_people_public`, not `people`.
## Discord
A profile can link its Discord account (the `identify` scope only: the
Discord user id and name), kept for the gamification to come. Off until
the service has a Discord application:
1. https://discord.com/developers/applications → New Application.
2. OAuth2 → Redirects: add `https://nextgenerationofunity.org/api/account/discord/callback`
(and the dev server's address, if you test there).
3. Copy the Client ID and Client Secret into the service's environment
(`systemctl edit ngu-api`):
```
[Service]
Environment=DISCORD_CLIENT_ID=...
Environment=DISCORD_CLIENT_SECRET=...
```
`DISCORD_REDIRECT_URI` overrides the return address (default: site.json's
`url` plus `/api/account/discord/callback`).
4. `systemctl restart ngu-api`.
An admin can set or clear an account's Discord id by hand on its row
(the long number from Discord: Developer Mode, then Copy User ID).
Code: `server/src/invites.js`, `server/src/discordAuth.js`,
`server/src/routes/account.js` (the member's own routes),
`server/src/routes/profiles.js` (the admin's), `src/pages/Account.tsx`,
`src/pages/AccountWelcome.tsx`, `src/pages/SignIn.tsx`,
`src/pages/admin/AdminProfiles.tsx`.

53
docs/redirects.md Normal file
View file

@ -0,0 +1,53 @@
# Links/redirects
Short links on our own domain, made in Admin → Data → Links/redirects
(editors and up), eg. `nextgenerationofunity.org/go/retreat-signup`. Use
them in the newsletter, or anywhere else, so each click is counted.
Each link has:
- **URL ID**: the part after `/go/`. Lowercase letters, numbers and
hyphens, and it can't be changed once made, since it's already been
sent out.
- **Goes to**: a web address (`https://...`) or a page on this site
(`/retreats`). This can be changed at any time, and every copy of the
link already sent follows it.
- **Note**: what it's for. Only we see it.
- **UTM tags** (source, medium, campaign): added to the destination's
address, eg. `?utm_source=newsletter&utm_medium=email&utm_campaign=october-2026`.
A tag the destination already has is left as it is.
## What a click does
`GET /go/<URL ID>` (`server/src/routes/redirects.js`, migration 068):
1. Adds one to the link's **Clicks** and sets **Last click** (both on
the list page). A save in the editor never changes them.
2. Tells Plausible, as a pageview of `/go/<URL ID>` with the visitor's
browser and address, so it appears in Top Pages (and in the Discord
reports) like any page. A redirect never loads the page script, so
the server reports it. It uses `PLAUSIBLE_URL`, the same as the
reports (`docs/analytics-reports.md`), and needs no API key. If
Plausible can't be reached, the redirect still works and the
problem is logged once.
3. Sends the visitor on with a 302. It's never cached, so every click
reaches the server.
An unknown URL ID shows the site's not-found page.
## Reading the numbers
- **Clicks** counts every request, including link checkers. Some email
security scanners open every link in a message before the reader
does, so a newsletter link can show a few clicks straight away.
Plausible leaves out known bots, so its count is usually lower and
closer to real readers.
- In Plausible, filter by page `/go/` to see every short link, or by a
UTM source or campaign to see what those visitors did once they
landed on our site.
## Setup
Nothing beyond the migration: nginx already sends `/go/...` to the API
through its catch-all page block (`nginx-dev`, `ngu-prod`). In
development, Vite proxies `/go` to the API (`vite.config.ts`).

View file

@ -45,16 +45,28 @@ Both lines are already in every proxied block in `nginx-dev` and in
## Sign-in
- The session cookie is `__Host-ngu_session`: the browser only
- The session cookie is `__Host-site_session`: the browser only
accepts it Secure, on path `/`, with no Domain, so another
subdomain can't set or overwrite it. With `COOKIE_SECURE=false`
(plain-http local work) it's `ngu_session`, since the prefix needs
(plain-http local work) it's `site_session`, since the prefix needs
Secure.
- Logins are limited per IP where `/api/auth/login` is mounted (10
per 15 minutes, `server/src/index.js`) and per email in
`routes/auth.js`: five wrong passwords for one address lock it for
the rest of 15 minutes, from anywhere; a correct one clears the
count. Both are in memory and reset when the service restarts.
- The per-email lock is a trade-off: anyone who knows an admin's
address can keep password sign-in for it locked by guessing wrong
five times every 15 minutes. Google sign-in still works for that
account, and the lock clears on a restart.
- `clientIp` trusts the last `X-Forwarded-For` entry, the one nginx
adds. If a CDN or another proxy is ever put in front of nginx, that
entry becomes the proxy's address and every visitor shares one
rate-limit bucket: set nginx's `real_ip_header` and
`set_real_ip_from` for the proxy first.
- The Google sign-in state cookie is `__Host-site_oauth` (plain
`site_oauth` over local http), and the page it returns to is checked
again when the browser comes back.
## From nginx: HSTS

View file

@ -23,7 +23,7 @@ same build.
| --- | --- |
| Site name, address, default description | `site.json`: `title`, `url`, `description` (blank uses the front page's subhead) |
| Default preview image | `site.json`: `openGraph.image`, eg. `/uploads/<file>` from Admin → Tools → Media. Blank means pages without their own image have none. |
| Static pages (Retreats, Community, History…) | `site.json`: `pages`. The page's heading and intro read the same entry, so they can't drift. A new static page needs an entry. |
| The site's pages (Retreats, Community, History…) | Admin → Pages → Page management (`site_pages`). The page's heading and intro read the same row, so they can't drift. Disabled pages are `noindex` and out of the sitemap; hidden ones are a 404 to search engines. |
| Records (events, organizations, teams, awards, people, posts) | The database: the record's name, then its tagline or first paragraph; its own image (an event's card background, else its logo; a post's cover; a person's photo; an organization's logo). SVGs aren't used as previews. |
| Whether search may list it | `site.json` `robots.index` for the whole site; per record, published and listed is indexed, published but unlisted is `noindex`, anything else is a 404. `/admin` is always `noindex`. |
@ -111,6 +111,18 @@ with it off it blocks everything.
client_max_body_size 26m;
proxy_read_timeout 60s;
}
# The admin's saves send a record whole (every content block,
# schedule entry and sub-item), well over 64k for a big page or
# event: nginx answers 413 "Too large for the web server" without
# this. A longer prefix than /api/, so it wins; the exact and
# longer admin blocks (media, files, import, clips) still win over
# it. Same proxy_set_header lines as /api/.
location /api/admin/ {
proxy_pass http://127.0.0.1:3001;
client_max_body_size 4m;
proxy_read_timeout 30s;
}
```
Keep the existing `/api/` and `/uploads/` blocks; they're more

View file

@ -15,8 +15,8 @@ what a dropdown in the admin editor says.
- [Renaming what a dropdown shows](#renaming-what-a-dropdown-shows)
- [Adding, removing or renaming a stored value](#adding-removing-or-renaming-a-stored-value)
- [Every dropdown in the editor](#every-dropdown-in-the-editor)
- [Front page section names](#front-page-section-names)
- [Front page stat sources](#front-page-stat-sources)
- [Front page sections](#front-page-sections)
- [Stat sources](#stat-sources)
- [Other content that lives in code](#other-content-that-lives-in-code)
- [Writing text in the editor](#writing-text-in-the-editor)
- [Making the change](#making-the-change)
@ -28,12 +28,16 @@ what a dropdown in the admin editor says.
| If it's… | It lives in… | Change it by… |
| ------------------------------------------------------------ | ---------------- | ------------------------------------ |
| A record: an event, organization, person, team, award, timeline entry | the database | editing it in the admin |
| People tags (directories, eg. Musicians, at `/directory/<tag>`) and contact types (Minister, General info), and organizations' contacts | the database | Admin → Data → People tags, Contact types; who carries a tag is set on the person, contacts on the organization |
| Tags for organizations and events (Online, In-Person; URL ID `online` marks an event online for the calendar filter) | the database | Admin → Data → Tags; who carries a tag is set on the organization or event |
| The front page's words, photos, bands, stats and paths | the database | Admin → Pages → Front page |
| Blog posts, and the Community page's blog section (headings, pins, feeds) | the database | Admin → Pages → Blog posts, and Community blog section |
| Blog posts, and the Community page's blog settings (headings, pins, feeds) | the database | Admin → Data → Blog posts, and Admin → Pages → Community |
| The sections of Retreats, Community, Resources, Organization and History: titles, blurbs, accents, their content blocks and presets (the blog, groups map, regions, partners, events, timeline, a people directory) | the database | Admin → Pages → the page. A section title is 30 characters at most (it's listed in the side nav); a front page heading fits about 60. Preset names: `PRESETS` in `src/lib/adminSchema/sitePages.ts`, what each draws: `PRESETS` in `src/pages/SitePage.tsx` |
| The **label** a dropdown shows in the admin | code | [one file](#renaming-what-a-dropdown-shows) |
| The **list of allowed values** behind a fixed dropdown | database CHECK + code | [a migration and three files](#adding-removing-or-renaming-a-stored-value) |
| Navigation, page section titles, colours, the site banner, history decades, the map grid | code | [the file named below](#other-content-that-lives-in-code) |
| A static page's title and intro (also its search title and description), the site's name, description, preview image, icons, search indexing, privacy contact email | the database, over `site.json` | Admin → Panel → Site settings (superadmins). Blank uses `site.json`, which also holds the site's address and the pages' defaults. See `docs/seo.md` |
| Navigation, colors, the site banner, history decades, the map grid | code | [the file named below](#other-content-that-lives-in-code) |
| A page's title and intro (also its search title and description), its address, Hidden and Disabled | the database (`site_pages`, 080) | Admin → Pages → Page management (admins and up), where new pages are made too |
| The site's name, description, preview image, icons, search indexing, privacy contact email | the database, over `site.json` | Admin → Panel → Site settings (superadmins). Blank uses `site.json`, which also holds the site's address. See `docs/seo.md` |
| Uploaded images | disk + the `media` table | Admin → Tools → Media, or any image field. See `docs/media-uploads.md` |
The rule of thumb from `CLAUDE.md`: data belongs in the database,
@ -50,11 +54,11 @@ each entity:
| File | What it holds |
| ----------------------------- | ----------------------------------------------------- |
| `src/lib/adminSchema/` (one file per entity, `shared.ts` for common fields; `src/lib/adminSchema.ts` lists them) | The **form**: field labels, help text, dropdown labels, list columns and filters |
| `server/src/admin-schema.js` | What the server **accepts**: columns, types, the allowed values of each `enumeration(...)` |
| `server/src/admin-schema/` (one file per entity, `columns.js` for shared helpers; `server/src/admin-schema.js` lists them) | What the server **accepts**: columns, types, the allowed values of each `enumeration(...)` |
And the database itself holds the final word: most fixed lists are a
`CHECK (... IN (...))` constraint on the column (read them in
`server/src/migrations/023_schema.sql` and any later migration).
`server/src/migrations/066_schema.sql` and any later migration).
### Two kinds of dropdown
@ -85,7 +89,7 @@ options: [["speaker", "Speaker"], ["leader", "Leader"]] // shows: Speaker, Lead
A bare string is shown exactly as stored. A `[value, label]` pair
stores the first and shows the second. That difference is what makes
relabelling cheap.
relabeling cheap.
### Renaming what a dropdown shows
@ -145,13 +149,14 @@ together, in one branch:
**Renaming** a value also needs an `UPDATE` in the same migration so
existing rows move to the new value. **Removing** one needs you to
decide what existing rows become first.
2. **`server/src/admin-schema.js`**: the `enumeration("column", [...])`
2. **`server/src/admin-schema/<entity>.js`**: the `enumeration("column", [...])`
list for that column.
3. **`src/lib/adminSchema/<entity>.ts`**: the `options` on the form field, and on
the list filter if there is one.
4. **Anywhere the public site renders or relies on the value**, listed in
the table below (for example `EVENT_TYPES` for event types, or the
`SECTIONS` map in `Home.tsx` for front page sections).
the table below (for example `EVENT_TYPES` for event types, or
`PRESETS` in `SitePage.tsx` and `BANDS` in `sections/Bands.tsx` for
section types).
If the server descriptor and the database disagree, the API refuses to
start: `admin-schema-sync.js` compares them at boot and throws with a
@ -161,105 +166,100 @@ wrong rather than working around it.
### Every dropdown in the editor
**Fixed lists** (`options`: labels in `src/lib/adminSchema/`, values
also in `admin-schema.js` and a CHECK):
also in `server/src/admin-schema/` and a CHECK):
| Entity → field | Stored values | Labelled? | Also used on the public site by |
| Entity → field | Stored values | Labeled? | Also used on the public site by |
| --- | --- | --- | --- |
| Organizations → Kind (+ list filter) | national, region, chapter, partner | no, shows values | `ORG_KIND_LABEL` in `src/lib/hrefs.ts`, and the route each kind uses |
| Organizations → Kind (+ list filter) | national, region, group, partner, ministry | no, shows values | `ORG_BASE` in `src/lib/hrefs.ts` (the route each kind uses). A ministry has no page on the public site (the public routes, `pageMeta.js` and the sitemap leave it out); its groups name it, and an organization cards section lists it when asked to (below). `/organizations` returns ministries only when asked by kind or id. `KINDS` in `src/components/admin/NewsletterRecipients.tsx` (the export's filter) lists every kind too. |
| Organizations → Region → Scope | domestic, international, virtual | no | the Community page groups regions by it |
| Organizations → Region areas → Edge | top, bottom | no | the chapter map (`OrgList-Map.tsx`) |
| Organizations → Region areas → Edge | top, bottom | no | the group map (`OrgList-Map.tsx`) |
| Events → Type (+ list filter) | retreat, class, workshop, meeting, other | no | `EVENT_TYPES` in `src/lib/eventTypes.ts` (public labels and plurals) |
| Events → Status (+ list filter) | upcoming, past, cancelled | no | `STATUS_LABEL` in `src/pages/EventDetail.tsx` |
| Events → Status (+ list filter) | upcoming, past, cancelled (shown as canceled) | no | `STATUS_LABEL` in `src/pages/EventDetail.tsx` |
| Events → Series → Repeats | weekly, monthly_date, monthly_weekday | **yes** | `src/lib/eventSeries.ts` |
| Events → People → Role | speaker, leader, facilitator, host, musician, volunteer, attendee | no | `ROLE_LABEL` in `src/pages/EventDetail.tsx` |
| People → Affiliations → Role; Teams → Members → Role | lead, board, staff, volunteer, member | no | `ROLE_LABEL` in `src/pages/PersonDetail.tsx` |
| Links → Kind (on organizations, events, people, teams) | action, social, website, email | no | `splitLinks` in `server/src/shape.js` |
| Links → Platform | instagram, facebook, discord, youtube, tiktok, x, substack, spotify, linkedin | **yes**, `PLATFORMS` | `PlatformIcon.tsx` draws the icon on the button. **No CHECK and no `enumeration`**: the column is plain text, so adding one is an entry in `PLATFORMS` (`src/lib/platforms.ts`) and its icon in `src/components/PlatformIcon.tsx`, no migration. |
| Content blocks → Shown in (slot) | card, body | **yes** | `paragraphs()` in `server/src/shape.js` (card), `ContentBlocks.tsx` (body) |
| Content blocks → Type | heading, subheading, paragraph, list, links, quote, image, divider, video, button, callout, schedule | **yes**, `BLOCK_TYPES` (with each type's description) | `ContentBlocks.tsx` (one renderer per type). Which fields each type shows is `when` on the fields in `blocksChild` (`src/lib/adminSchema/shared.ts`). |
| Content blocks → Type | heading, subheading, paragraph, list, links, quote, image, divider, video, button, callout, schedule, table, cards, people, map, events, organizations | **yes**, `BLOCK_TYPES` (with each type's description) | `ContentBlocks.tsx` (one renderer per type). Which fields each type shows is `when` on the fields in `blocksChild` (`src/lib/adminSchema/shared.ts`). |
| Content blocks → Schedule items → Type | (blank: normal entry), block, break, heading | **yes**, migration 086 | `SCHEDULE_KINDS` in `src/lib/adminSchema/shared.ts`; drawn by `ScheduleBlock.tsx` and `EventPresent.tsx` (which slides each kind gets; the presentation cuts the event's page into sections at its Heading blocks). A block's sub-items are `content_block_subitems`. A schedule's own tags (087) are `content_block_tags`, rows of the block typed in the admin (not a fixed list); entries name them by `tag_key`, made in the admin as the tag is added. A schedule's Venue (088) lends its locations (Data → Venues, `venue_locations`) to its entries' Map location, named by `location_key` the same way; an entry's Event (a workshop) fills what it leaves blank in `shape.js` (`attachEvents`). |
| Content blocks → Image → Size | (blank: the column's full width), small (20rem), medium (32rem), large (48rem) | **yes**, migration 101 | The `image_size` field in `src/lib/adminSchema/shared.ts`; `IMAGE_SIZE` in `ContentBlocks.tsx` sets the widths |
| Content blocks → List → Style | (blank: bold text, normal detail), plain (plain text, gray detail) | **yes**, migration 092 | The Style field in `src/lib/adminSchema/shared.ts`; drawn by the `list` case in `ContentBlocks.tsx`. |
| Content blocks (an event's) → Shown | (blank: the page and the presentation), page, presentation | **yes**, migration 099 | `PRESENT_BLOCK_FIELDS` in `src/lib/adminSchema/shared.ts`; `ContentBlocks.tsx` leaves out a presentation-only block on the page and a page-only one presented, `sectionsOf` in `src/pages/EventPresent.tsx` too |
| Content blocks (an event's) → Map → Location slides | (blank: each marked location), picked (the Locations with a slide), none | **yes**, migration 095 | `PRESENT_BLOCK_FIELDS` in `src/lib/adminSchema/shared.ts`; read by `mapSlides` in `src/pages/EventPresent.tsx` |
| Events → Presentation → Frame | (blank: the accent bar, title line and timer), border, none | **yes**, migration 095 | The `present_frame` field in `src/lib/adminSchema/events.ts`; drawn by `Player` in `src/pages/EventPresent.tsx` |
| Content blocks → Organizations → List | (blank: only the picked ones), partner, region, group, ministry | **yes**, migration 093 | The `org_kind` field in `src/lib/adminSchema/shared.ts`; the `organizations` case in `ContentBlocks.tsx` passes it as the kind to `OrgListCards` (`nested`); items picked by `org_id` replace it |
| Timeline → Kind (+ list filter) | milestone, event, organization, award, people | no | `KIND_NAMES` in `src/pages/sections/history/TimelineEntry.tsx` |
| Timeline → Points at (+ list filter) | event, organization, award, person, team | no | `refHref` in `src/lib/hrefs.ts` |
| Timeline → Precision (and on events/orgs) | year, month, day | no | the history page's grouping |
| Front page → Countdown → Only this type | retreat, class, workshop, meeting, other | **yes** | `server/src/routes/home.js` (picks the countdown event). The same values as Events → Type, so adding a type widens both CHECKs. |
| Front page → Background | brand, photos | **yes** | `HeroStage.tsx` |
| Front page → Feature | none, livestream, video, event | **yes** | `HeroStage.tsx`; the event is picked in `server/src/routes/home.js` |
| Front page → Sections → Section | countdown, retreats, calendar, stats, timeline, connect, featured | **yes**, `FRONT_PAGE_SECTIONS` | `SECTIONS` in `src/pages/Home.tsx`; see [below](#front-page-section-names) |
| Front page → Stats → Number Source | manual, years_since, regions, … | **yes**, `STAT_SOURCES` | `STAT_QUERIES` in `server/src/routes/home.js`; see [below](#front-page-stat-sources) |
| Front page → Featured cards → Card type (Community blog section → Pinned community posts offers link and video only) | record, link, video | **yes**, `FEATURED_KINDS` | `FeaturedCards.tsx` (how each kind draws), `loadFeaturedCards` in `server/src/shape.js` |
| Front page → Featured cards → Record type | event, organization, person, team, award | no | `FEATURED_REFS` in `server/src/shape.js` (what each fills the card with); the triggers in `030_featured_cards.sql` |
| Pages → Sections → Countdown: only this type | retreat, class, workshop, meeting, other | **yes** | `server/src/sectionData.js` (picks the countdown event). The same values as Events → Type, so adding a type widens both CHECKs. |
| Pages → Sections → Hero: background | brand, photos | **yes** | `HeroStage.tsx` |
| Pages → Sections → Hero: feature | none, livestream, video, event | **yes** | `HeroStage.tsx`; the event is picked in `server/src/sectionData.js` |
| Pages → Sections → Numbers → Number Source | manual, years_since, regions, … | **yes**, `STAT_SOURCES` in `src/lib/adminSchema/sitePages.ts` | `STAT_QUERIES` in `server/src/sectionData.js`; see [below](#stat-sources) |
| Featured cards → Card type (a Community blog's pinned community posts offer link and video only) | record, link, video | **yes**, `FEATURED_KINDS` | `FeaturedCards.tsx` (how each kind draws), `loadFeaturedCards` in `server/src/shape.js` |
| Pages → Sections → Featured cards: columns (073) | 2, 3, 4 | **yes**, inline in `src/lib/adminSchema/sitePages.ts` | `GRID_COLUMNS` in `FeaturedCards.tsx`; the CHECK on `section_featured.columns` |
| Featured cards → Size (073; featured card sections only, regions and the Community blog stay automatic) | normal, wide, tall, large | **yes**, inline in `src/lib/adminSchema/sitePages.ts` | `SPANS` and `sizeOf` in `FeaturedCards.tsx`; the CHECK on `featured_cards.size` |
| Featured cards → Record type | event, organization, person, team, award | no | `FEATURED_REFS` in `server/src/shape.js` (what each fills the card with); the triggers in `030_featured_cards.sql` |
| Pages → Sections → Preset (section type) | community_blog, group_map, region_list, partner_list, events, timeline, people_directory, feedback_form, request_form, data_request_form, giving, qr_maker, hero, countdown, calendar, stats, featured_cards, connect | **yes**, `PRESETS` in `src/lib/adminSchema/sitePages.ts`, every page offers them all | `PRESETS` in `src/pages/SitePage.tsx`; the bands (hero, countdown, calendar, numbers, featured cards, connect, and a timeline shown as a rail) in `src/pages/sections/Bands.tsx`, their data from `server/src/sectionData.js`; forms and embeds in `src/pages/sections/FormSections.tsx`. A People directory shows each tag's first `DIRECTORY_PREVIEW` people (`src/pages/sections/PeopleDirectory.tsx`), linking to `/directory/<tag>`. |
| Pages → Sections → Cards: list (organization cards preset, 067) | partner, ministry, partner,ministry | **yes**, inline in `src/lib/adminSchema/sitePages.ts` | `partner_list` in `PRESETS` in `src/pages/SitePage.tsx` passes it as the kind to `OrgListCards`; a section's hand-picked Cards: organizations (`page_section_orgs`) replace it |
| Every list → Published / Listed / Featured filter | 1, 0 | **yes** | n/a |
"No, shows values" means the dropdown currently shows the raw value,
so relabelling it is just [adding labels](#renaming-what-a-dropdown-shows).
so relabeling it is just [adding labels](#renaming-what-a-dropdown-shows).
**Lists filled from records** (`optionsFrom`: edit the records, not
code):
| Dropdown | `optionsFrom` | Comes from |
| --- | --- | --- |
| Chapter → Region | `regions` | organizations of kind region |
| Event → Scope (+ list filter); Front page → Countdown → Only this scope | `event_scopes` | the `event_scopes` table (migration only) |
| Event hosts → Organization; affiliations; team and award "Organization" / "Awarded by"; person → Home organization | `organizations` | organizations, labelled by name |
| Group → Region | `regions` | organizations of kind region |
| Group → Ministry | `ministries` | organizations of kind ministry |
| People → Directories → Tag; Pages → Sections → Directory: tag | `person_tag_types` | Data → People tags |
| Organizations and Events → Tags → Tag | `tags` | Data → Tags |
| Organizations → Contacts → Type | `contact_types` | Data → Contact types |
| Event → Scope (+ list filter); Pages → Sections → Countdown: only this scope | `event_scopes` | the `event_scopes` table (migration only) |
| Event hosts → Organization; affiliations; team and award "Organization" / "Awarded by"; person → Home organization | `organizations` | organizations, labeled by name, except ministries (they have no page to link to) |
| Event hosts / event people / team members / timeline people → Person | `people` | people |
| Community blog section → Pinned posts → Post | `blog_posts` | blog posts, newest first |
| Timeline → Record; Featured cards → Record | `record_refs` | every event, organization, award, person and team, narrowed by the type picked beside it |
| Pages → Sections → Blog: pinned posts (ours) → Post | `blog_posts` | blog posts, newest first |
| Timeline → Record; Featured cards → Record | `record_refs` | every event, organization (but ministries), award, person and team, narrowed by the type picked beside it |
| Affiliations → Team | `teams` | teams, filtered to the chosen organization |
| Person awards → Award | `awards` | awards, labelled "Award (Organization)" |
| Person awards → Presented at; Front page → Count down to; Front page → Featured event | `events` | events |
| Timeline → Record | `timeline_refs` | all five kinds, filtered by "Points at" |
| Person awards → Award | `awards` | awards, labeled "Award (Organization)" |
| Person awards → Presented at; Pages → Sections → Count down to, Hero: featured event | `events` | events |
---
## Front page section names
## Front page sections
"Section name" means three different things on the front page, and
each is changed in a different place:
The front page is a page of sections like the others (Admin → Pages →
Page management → Home, migration 083): the hero first, then its
bands, each a section with a type. Its heading is the section's title
(up to 60 characters on the front page), its anchor the section's URL
ID (`#retreats`, `#calendar`, `#numbers`, `#connect`), which the
header's Home dropdown lists (not the hero or the countdown). Rename
a heading freely; change a URL ID only if you mean to break links to
it. The names in the section type dropdown are `PRESETS` in
`src/lib/adminSchema/sitePages.ts`.
| What you see | Where it's set |
| --- | --- |
| **The heading on the page** ("National Retreats", "What's on") | **Admin → Pages → Front page → Page sections → Heading.** Blank uses the default below. |
| The default heading when that field is blank | `SECTIONS` in `src/pages/Home.tsx`, the `title` of each entry |
| **The name in the admin's Section dropdown** ("Events Carousel (National Retreats)") | `FRONT_PAGE_SECTIONS` in `src/lib/adminSchema/frontPage.ts` |
| The subnav links under the header ("#Retreats", "#Calendar") | `PAGE_SECTIONS["/"]` in `src/navConfig.ts` |
To rename a band **for visitors**, use the admin. To rename how it
reads **in the editor's dropdown**, edit `FRONT_PAGE_SECTIONS`:
```ts
const FRONT_PAGE_SECTIONS = [
["countdown", "Event Countdown"],
["retreats", "Events Carousel (National Retreats)"], // ← the right-hand side is the label
["calendar", "Event Calendar"],
...
];
```
The subnav links jump to each band by its anchor: the `id` passed in
each band's `render` in `Home.tsx` (`#retreats`, `#calendar`,
`#numbers`, `#connect`, and `#hero` for the hero). If you rename a
subnav label in `navConfig.ts`, leave its `hash` alone unless you also
change the band's `id`.
**Adding a new kind of band** (not just renaming one) is a feature,
not a relabel: it needs a component, an entry in `SECTIONS` in
`Home.tsx`, the key added to `FRONT_PAGE_SECTIONS`, to the
`enumeration("section", …)` in `server/src/admin-schema.js`, to the
`FrontPageSectionKey` type in `src/lib/useFrontPage.ts`, and to the
CHECK on `front_page_sections.section` via a migration.
**Adding a new kind of band** is a feature, not a relabel: its
component and an entry in `BANDS` (`src/pages/sections/Bands.tsx`),
its settings table (a migration) and extension or collection in
`sectionsChild` (`server/src/admin-schema/sitePages.js`), its data in
`server/src/sectionData.js`, its fields in `src/lib/adminSchema/sitePages.ts`,
and its value added to the CHECK on `page_sections.preset`.
---
## Front page stat sources
## Stat sources
The numbers band's "Number Source" dropdown works the same way:
A Numbers section's "Number Source" dropdown works the same way:
- **Relabel a source:** `STAT_SOURCES` in `src/lib/adminSchema/frontPage.ts`.
- **Relabel a source:** `STAT_SOURCES` in `src/lib/adminSchema/sitePages.ts`.
- **Change what a count counts:** its query in `STAT_QUERIES` in
`server/src/routes/home.js`. Keep it counting exactly what the
`server/src/sectionData.js`. Keep it counting exactly what the
matching public page shows (published rows), or the number and the
page will disagree.
- **Add a source:** the CHECK on `front_page_stats.source` (migration),
the `enumeration("source", …)` in `server/src/admin-schema.js`,
- **Add a source:** the CHECK on `section_stats.source` (migration),
the `enumeration("source", …)` in `server/src/admin-schema/sitePages.js`,
`STAT_SOURCES`, and a query in `STAT_QUERIES`.
---
@ -268,19 +268,24 @@ The numbers band's "Number Source" dropdown works the same way:
| What | File | Notes |
| --- | --- | --- |
| Header and footer navigation, page subnav links | `src/navConfig.ts` | `PAGE_LINKS`, `PAGE_SECTIONS`, `NAV_ACTIONS`. A new page also needs a route in `src/App.tsx`. |
| Section titles, blurbs and colours on Retreats, Community, Leadership, Resources, Feedback, Privacy, Terms | the page file in `src/pages/` | the `SECTIONS` array at the top. A section's `id` must match its subnav `hash`. |
| Header and footer navigation, each page's sections (the header dropdowns, mobile menu and footer site map) | Admin → Pages → Navigation (the database, `075_site_nav.sql`); `src/navConfig.ts` is only the defaults the app starts from before it loads | Links: where each shows (header pages, header buttons, footer Get in Touch, footer bottom row), order, label, a header page set under another's menu, a filled button, new tab. Each page's sections aren't listed there: they follow the page itself, through `src/lib/navSections.ts` (every page's sections from Admin → Pages → Page management, the front page's included, but its hero and countdown). A new page is made in Page management, no code: it's a page of sections at the address given. |
| Site-wide announcement banner | `src/data/bannerConfig.ts` | `enabled: false` hides it. Bump `id` when the message changes, so people who dismissed the old one see the new one. |
| History page decade headers | `src/data/historyDecades.ts` | Title, tagline and blurb per decade. |
| Chapter map tiles and area names | `src/data/mapGrid.ts` | `AREAS` (tile positions) and `AREA_NAMES`. Which region paints which tile is in the database (Admin → Data → Organizations → a region → Map areas). |
| Group map tiles and area names | `src/data/mapGrid.ts` | `AREAS` (tile positions) and `AREA_NAMES`. Which region paints which tile is in the database (Admin → Data → Organizations → a region → Map areas). |
| Feedback form types | `src/data/feedbackTypes.ts` **and** `TYPES` in `server/src/routes/feedback.js` | Keep the ids identical in both; the server stores unknown ids as `general`. Labels and hints are client-only. `DATA_REQUEST` ('privacy') isn't a tile: the Privacy page's form sends it, and the server requires an email for it. |
| The site's colours, light and dark | the database over `src/index.css` | Admin → Panel → Site settings → Colours (superadmins): pick a colour, set its light and/or dark value; saving refuses anything that makes text hard to read. The defaults are the `@theme` tokens and dark block in `src/index.css`, and must stay the same in `THEME_DEFAULTS` (`server/src/theme.js`) and `THEME_COLORS` (`src/lib/adminSchema/siteSettings.ts`). Change a token's value in both modes and every use follows. Use the token utilities (`text-muted`, `bg-surface`, `border-brand/20`) or `var(--color-…)`, not hex. A colour that arrives as data (a page accent, an event's or region's colour) goes through `src/lib/color.ts`: `withAlpha` for tints, `accentText` for text in it, `readableOn` for text on it. |
| Privacy Policy and Terms wording | `src/pages/Privacy.tsx`, `src/pages/Terms.tsx` | The `PARTS` list, and `LAST_UPDATED` whenever the wording changes. The Privacy page must stay true of the code: what the feedback form stores, what the browser keeps, which embeds wait for a click. |
| Request form types (what `/request` can ask for) | `src/data/requestTypes.ts` **and** `CATEGORIES` in `server/src/routes/requests.js` **and** the CHECK on `feedback.category` (`046_content_requests.sql`) | Ids and allowed actions (new, update) identical in all three; a new id needs a migration. Labels, hints, the name field's question and each type's `fields` (the details it asks for, and where each lands in the admin editor: a field path, a link row or a description paragraph) are client-only: the server stores whatever detail keys come as JSON (`feedback.details`, 049), so adding a field needs no migration. A button to the form opened on one type: `request: { type, label }` on a section manifest entry, or `<RequestLink>` (`src/components/RequestLink.tsx`). |
| The site's colors, light and dark | the database over `src/index.css` | Admin → Panel → Site settings → Colors (superadmins): pick a color, set its light and/or dark value; saving refuses anything that makes text hard to read. The defaults are `THEME_DEFAULTS` in `server/src/themeDefaults.js` (the admin and the contrast check read it) and the same values as CSS in `src/index.css`; the build stops if the two differ. The admin's labels for them are `THEME_LABELS` in `src/lib/adminSchema/siteSettings.ts`. Change a token's value in both modes and every use follows. Use the token utilities (`text-muted`, `bg-surface`, `border-brand/20`) or `var(--color-…)`, not hex. A color that arrives as data (a page accent, an event's or region's color) goes through `src/lib/color.ts`: `withAlpha` for tints, `accentText` for text in it, `readableOn` for text on it. |
| The icons a Connect nav section's path can pick | `src/data/pathIcons.ts` (keys and labels) **and** `ICONS` in `src/pages/sections/home/Pathfinder.tsx` (the Phosphor icon for each key) | Add a line to both. A path saved with an emoji from before the list shows it as it is. |
| A page section's accent color | `BRAND` and `ACCENTS` in `src/lib/color.ts` | Pages pick from these (`accent: ACCENTS.green`); add a color there, not a hex in a page. Each is readable as text on white and the tints. |
| The palette (the 16-color grid the theme is drawn from) | `PALETTE` in `src/lib/color.ts` | Four families, a column each. `PALETTE_LIGHT` / `PALETTE_DARK` are the fills things colored by data use (a person's initials tile, `paletteFill`); the page background's layers (how many circles, their sizes and parallax speeds) are `LAYERS` in `src/components/PageBackdrop.tsx` and its shades are in `PageBackdrop.css`; the admin home's two alternating group colors are `BLOCK_COLORS` in `src/pages/admin/AdminHome.tsx`. |
| The accessibility panel's choices (bottom right of every public page) | `SETTINGS` in `src/components/AccessibilityPanel.tsx`; the color blind modes are `VISIONS` and `SWAPS` in `src/lib/color.ts` | Each choice is an attribute on `<html>` styled in `src/index.css`, and `index.html` sets it again before the first paint, so a new one goes in all three. A color blind mode replaces all three color families, teal, green and amber (`SWAPS`, picked by simulating each type: see the comment there), in code, in data colors as they load (`src/lib/api.ts`, never under /admin), in CSS (the `--pal-*` variables in `src/index.css`, which hold the same values as `SWAPS`: change both) and in the theme tokens drawn from them. A palette hex in a component or CSS file should be `var(--pal-<family>-<shade>)` (eg. `var(--pal-amber-2)`), or a color blind mode won't reach it. Reading mode is `src/components/ReaderView.tsx`, which reads the hidden page and writes out its headings, paragraphs, links and described pictures. A part it can't read well (a carousel, tabs, details behind a click, a map) draws its own text version when `useReadingMode()` (`src/lib/readingMode.ts`) is on: the hero, pathfinder, stats, history rail, event lists, calendar (the next six weeks), featured cards, org lists and groups map, history timeline, schedule, map block (its list alone), people tiles and video player; the countdown draws nothing. A new component with any of those should do the same. Something saved or sent (the newsletter's colors) is a stored hex, which is never swapped. |
| Privacy Policy and Terms wording | the database (082) | Admin → Pages → Page management → Privacy Policy or Terms of Service: their sections' blocks, and the "Last updated" date in the section's blurb whenever the wording changes. The privacy contact email is in the policy's text. The Privacy page must stay true of the code: what the feedback form stores, what the browser keeps, which embeds wait for a click. |
| Event type labels and plurals (public site) | `src/lib/eventTypes.ts` | Also the order of the type filter chips. |
| Event and person role labels (public site) | `ROLE_LABEL` in `src/pages/EventDetail.tsx` and `src/pages/PersonDetail.tsx` | |
| Organization kind labels ("Region", "Chapter") | `ORG_KIND_LABEL` in `src/lib/hrefs.ts` | |
| Organization kind labels ("Region", "Group") | the Kind options in `src/lib/adminSchema/organizations.ts` (admin) | |
| Admin account roles | `src/lib/roles.ts` (labels, notes) and `ROLES` in `server/src/auth.js` | Adding a role is also a CHECK change on `admin_users.role`. |
| Admin navigation | `src/pages/admin/adminNav.ts` | |
| Newsletter parts and their defaults (Tools → Newsletter) | `PARTS_SPEC`, `PART_TYPES` and `STARTER` in `src/pages/admin/AdminNewsletter.tsx`; `PICK_DEFAULTS`, `DEFAULT_TITLE` and `EMAIL_COLOR` in `src/lib/newsletter.ts` | A draft is one JSON list of parts (`newsletters.layout`, 060), so adding a part or a setting needs no migration: a field in `PARTS_SPEC` and its drawing in `newsletter.ts`. Part colors (the title, bands, lines, card bars) are color pickers taking any hex, or the word none; `EMAIL_COLOR` holds the defaults as hex, since an inbox has no theme tokens. `STARTER` is what a new draft starts with. The social bar's icons are PNGs in `public/email/` (Gmail and Outlook don't show SVG), made from `PlatformIcon.tsx` by `node scripts/email-icons.mjs`: run it again after adding a platform. A social bar with no links shows the footer's, `SOCIAL_LINKS` in `src/data/socialLinks.ts`. The countdown picture is `server/src/routes/countdown.js`, counting to local midnight in its `TIME_ZONE` (America/Chicago). |
| The live site's address (used by QR codes) | `SITE_ORIGIN` in `src/lib/site.ts` | |
| Version shown on the admin home page | `src/lib/version.ts` | |
| Image directories (where logos and photos are looked up) | `src/lib/media.ts` | |
@ -289,6 +294,14 @@ The numbers band's "Number Source" dropdown works the same way:
## Writing text in the editor
Rotating words: type the choices in braces, `{Next|Now|Rising}`, in a
hero headline, a section title, a heading, a paragraph, a callout or a
quote, and the word cycles through them. How it moves is Admin →
Panel → Site settings → Animated words, or the hero's or block's own
Rotating words fields. Menus, tab titles, search and emails show the
first choice. The component is `src/components/RotatingWords.tsx`; its
motions are CSS in `RotatingWords.css`.
Conventions for any label, help text or option added to the admin, so
the editor reads consistently:

View file

@ -9,11 +9,39 @@ Facebook links; the server downloads it, then you cut clips from it:
the crop; the white box over the video shows what's kept.
- **Format**: video (MP4, H.264 and AAC) or audio only (MP3).
A downloaded video can be kept whole too, before or without cutting
it: **Save to library** and **Save to Drive** on the download itself.
It stays on the server to cut clips from either way (until the day's
sweep).
The same tools take stills (editors and up), each saving the frame at
a typed time to `/uploads/thumbnails/` (`grabFrame` in
`server/src/clips.js`, `POST /api/admin/video-frame`). It downloads only
that frame, outside the queue. A link's own `t=` (eg. `?t=83`) fills in
the time. **Frame at** is on:
- a video featured card's Image field (the front page, a region)
- a video content block's Image field (its still)
- the front page's Video still (the hero's featured video, migration 074)
and **Tools → Video thumbnails** (`AdminVideoFrames.tsx`) takes one from
any link, to download or copy its path into a field.
Clips queue and run one at a time. A finished clip is deleted from the
server once it's downloaded, unless **Save to library** is pressed first,
which puts it in the media library as an upload (usable as a featured
video or in a video block). Everything is cleared a day after it's made.
**Save to Drive** puts a copy in a folder under Media in the shared
Google Drive (pick it, eg. `Media/Videos` or `Media/Audio`; the list is
Tools → Media → Files's folders, and the one named for the clip's kind
is chosen first). It becomes a Files entry, shared with anyone who has
the link, so pages link to it with Choose a file. It's uploaded straight
from the server's copy (the working file, or the library's), streamed
rather than read into memory, so a long clip is fine; nginx isn't in the
way. A clip can be in both the library and Drive. Needs Google Drive set
up (`docs/google-drive-and-mail.md`) and migration 051.
Only YouTube and Facebook links are accepted, and only for videos NGU owns
or has permission to use. Sources can be up to 4 hours and 4 GB; clips up
to an hour. Limits are constants at the top of `server/src/clips.js`.

View file

@ -5,13 +5,19 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title><!-- site:title --></title>
<!-- Theme before first paint, so a dark visitor never sees a white
flash: this browser's choice (ThemeToggle), else the system. -->
<meta name="theme-color" content="#073d4a" media="(prefers-color-scheme: light)" />
<meta name="theme-color" content="#0c1d21" media="(prefers-color-scheme: dark)" />
<script>
try {
var t = localStorage.getItem("ngu-theme");
var t = localStorage.getItem("site-theme");
document.documentElement.dataset.theme =
t === "dark" || t === "light" ? t : matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
if (localStorage.getItem("site-font") === "dyslexic") document.documentElement.dataset.font = "dyslexic";
if (!location.pathname.startsWith("/admin")) {
if (localStorage.getItem("site-reading") === "on") document.documentElement.dataset.reading = "on";
var v = localStorage.getItem("site-vision");
if (/^(protanopia|deuteranopia|tritanopia|monochrome)$/.test(v || "")) document.documentElement.dataset.vision = v;
}
} catch (e) {}
</script>
<!-- site:head-end -->

View file

@ -11,7 +11,9 @@
},
"dependencies": {
"@fontsource/montserrat": "^5.3.0",
"@fontsource/opendyslexic": "^5.3.0",
"@fontsource/poppins": "^5.3.0",
"@phosphor-icons/react": "^2.1.10",
"qrcode": "^1.5.4",
"react": "^19.0.0",
"react-dom": "^19.0.0",

23
pnpm-lock.yaml generated
View file

@ -11,9 +11,15 @@ importers:
'@fontsource/montserrat':
specifier: ^5.3.0
version: 5.3.0
'@fontsource/opendyslexic':
specifier: ^5.3.0
version: 5.3.0
'@fontsource/poppins':
specifier: ^5.3.0
version: 5.3.0
'@phosphor-icons/react':
specifier: ^2.1.10
version: 2.1.10(react-dom@19.3.0(react@19.3.0))(react@19.3.0)
qrcode:
specifier: ^1.5.4
version: 1.5.4
@ -63,6 +69,9 @@ packages:
'@fontsource/montserrat@5.3.0':
resolution: {integrity: sha512-iQPDtZOnmM5ih4JBGaMSXisRap0ixb9bAUw2hDtY7EjVfaqiiNlKtVuJl9XclxUwtwMMHNcWXfQR6zI9x05+Tg==}
'@fontsource/opendyslexic@5.3.0':
resolution: {integrity: sha512-BVYIW/ghc1U2iAghhYTN+GFWiZ3lnCy8Jf2KkZC23aHQHBNcMqKT718zckfqVxRx4qsXJmIMPWvczirRuhmtsg==}
'@fontsource/poppins@5.3.0':
resolution: {integrity: sha512-cms1nM7U6SN8epIV1WMVOV8VsA645aSm3wHfzIQnkk188U341ThbJGSl2Sv54V29gnDbT2arMPfLzvVIIVCceQ==}
@ -129,6 +138,13 @@ packages:
cpu: [x64]
os: [win32]
'@phosphor-icons/react@2.1.10':
resolution: {integrity: sha512-vt8Tvq8GLjheAZZYa+YG/pW7HDbov8El/MANW8pOAz4eGxrwhnbfrQZq0Cp4q8zBEu8NIhHdnr+r8thnfRSNYA==}
engines: {node: '>=10'}
peerDependencies:
react: '>= 16.8'
react-dom: '>= 16.8'
'@rolldown/binding-android-arm-eabi@1.2.9':
resolution: {integrity: sha512-tNISae1QEf/vkb3xkRcjV5SEdzPE97We5IVaa2Z8jSszQPZ8U60B/YCYpw4QI7VidYsBtKavczXf+DyDs9WGxw==}
engines: {node: ^20.19.0 || >=22.12.0}
@ -776,6 +792,8 @@ snapshots:
'@fontsource/montserrat@5.3.0': {}
'@fontsource/opendyslexic@5.3.0': {}
'@fontsource/poppins@5.3.0': {}
'@jridgewell/gen-mapping@0.3.13':
@ -823,6 +841,11 @@ snapshots:
'@oxfmt/win32-x64@0.2.0':
optional: true
'@phosphor-icons/react@2.1.10(react-dom@19.3.0(react@19.3.0))(react@19.3.0)':
dependencies:
react: 19.3.0
react-dom: 19.3.0(react@19.3.0)
'@rolldown/binding-android-arm-eabi@1.2.9':
optional: true

Binary file not shown.

After

Width:  |  Height:  |  Size: 997 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 838 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 921 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 806 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 608 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 531 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 445 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 401 B

BIN
public/email/tiktok-ink.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 864 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 746 B

BIN
public/email/x-ink.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

BIN
public/email/x-white.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1,017 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 622 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 522 B

30
scripts/email-icons.mjs Normal file
View file

@ -0,0 +1,30 @@
/* ═══════════════════════════════════════════════════════════════
EMAIL ICONS: node scripts/email-icons.mjs (from the repo root)
Gmail and Outlook don't show SVG, so a newsletter's social bar
(src/lib/newsletter.ts) uses PNG copies of the platform icons in
PlatformIcon.tsx: white and ink, 48px square (shown at 24), into
public/email/, which the build copies as they are, so the files
keep their addresses in emails already sent. Run it again after
adding a platform or changing an icon. Uses the server's sharp.
═══════════════════════════════════════════════════════════════ */
import { readFileSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
const sharp = createRequire(new URL("../server/package.json", import.meta.url))("sharp");
const source = readFileSync(new URL("../src/components/PlatformIcon.tsx", import.meta.url), "utf8");
const paths = {};
for (const [, id, d] of source.matchAll(/^\s*(\w+):\s*'([^']+)'/gm)) paths[id] = d;
for (const [, id, d] of source.matchAll(/^\s*(\w+):\s*\n\s*'([^']+)'/gm)) paths[id] = d;
paths.instagram = /INSTAGRAM_PATH =\s*'([^']+)'/.exec(source)[1];
const TONES = { white: "#ffffff", ink: "#001011" };
for (const [id, d] of Object.entries(paths)) {
for (const [tone, fill] of Object.entries(TONES)) {
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="48" height="48"><path fill="${fill}" d="${d}"/></svg>`;
writeFileSync(new URL(`../public/email/${id}-${tone}.png`, import.meta.url), await sharp(Buffer.from(svg)).png().toBuffer());
}
}
console.log(`${Object.keys(paths).length} icons: ${Object.keys(paths).join(", ")}`);

140
server/src/accessGroups.js Normal file
View file

@ -0,0 +1,140 @@
/* ═══════════════════════════════════════════════════════════════
ADMIN ACCESS BY GOOGLE GROUP
Panel → Site settings → Access names a Workspace group for each of
viewer, editor and admin. Someone in one of them who signs in with
Google gets an account (access_source 'group', no password) with
the highest of those roles; routes/auth.js calls groupRole() and
applyGroupRole() at every Google sign-in.
The role then follows the group:
at sign-in always checked
while signed in startGroupSync() rechecks accounts with a
live session every SYNC_EVERY_MS, once
their last check is STALE_AFTER_MS old
Panel → Re-sync now every group account, straight away
Out of every group: the account is disabled (group_disabled = 1)
and signed out; back in one, the next sign-in or sync turns it on
again. A superadmin's Disable in the Panel sets group_disabled = 0,
which no group check undoes.
Never touched: superadmins and 'manual' accounts (admin-cli, which
may also sign in with Google as before).
If Google can't be asked, a sign-in is refused (it can't be shown
to be allowed), but a background recheck leaves the account as it
is and tries again next time: an outage shouldn't sign everyone out.
Needs GOOGLE_DIRECTORY_AS (googleService.js) and at least one group.
Setup: docs/google-sign-in.md.
═══════════════════════════════════════════════════════════════ */
import { directoryReady, isGroupMember } from "./googleService.js";
const SYNC_EVERY_MS = 10 * 60 * 1000;
const STALE_AFTER_MS = 30 * 60 * 1000;
// Highest first: the first group someone is in gives their role.
const GROUP_ROLES = ["admin", "editor", "viewer"];
/* [[role, group address], ...], highest role first, set ones only. */
export function accessGroups(db) {
const row =
db
.prepare(
`SELECT access_group_viewer, access_group_editor, access_group_admin
FROM site_settings WHERE id = 'site'`,
)
.get() ?? {};
return GROUP_ROLES.map((role) => [role, String(row[`access_group_${role}`] ?? "").trim().toLowerCase()]).filter(
([, group]) => group,
);
}
export const accessEnabled = (db) => directoryReady() && accessGroups(db).length > 0;
/* The role someone's groups give them, or null for none. Throws a
GoogleError when Google can't say. */
export async function groupRole(db, email) {
for (const [role, group] of accessGroups(db)) {
if (await isGroupMember(group, email)) return role;
}
return null;
}
/* Brings a group account in line with `role` (null: in no group).
Returns what changed, as text for the log and the Panel, or null. */
export function applyGroupRole(db, user, role) {
// `user` was read before the group lookups were awaited, so each
// write rechecks that a superadmin hasn't disabled or promoted the
// account meanwhile.
const STILL_OURS = `AND role <> 'superadmin' AND (is_active = 1 OR group_disabled = 1)`;
let change = null;
if (!role) {
if (user.is_active === 1) {
const res = db
.prepare(`UPDATE admin_users SET is_active = 0, group_disabled = 1 WHERE id = ? ${STILL_OURS}`)
.run(user.id);
db.prepare(`DELETE FROM sessions WHERE user_id = ?`).run(user.id);
if (res.changes) change = "disabled: in no access group";
}
} else if (user.is_active !== 1 || user.role !== role) {
const res = db
.prepare(`UPDATE admin_users SET role = ?, is_active = 1, group_disabled = 0 WHERE id = ? ${STILL_OURS}`)
.run(role, user.id);
if (res.changes) change = user.is_active !== 1 ? `enabled as ${role}` : `${user.role} → ${role}`;
}
db.prepare(`UPDATE admin_users SET groups_checked_at = datetime('now') WHERE id = ?`).run(user.id);
if (change) console.log(`access: ${user.email} ${change}`);
return change;
}
/* Rechecks group accounts: all of them (Panel → Re-sync now), or only
those signed in whose last check is stale (the timer). Accounts a
superadmin disabled are left alone. */
export async function syncGroupAccounts(db, { all = false } = {}) {
const users = db
.prepare(
`SELECT u.id, u.email, u.role, u.is_active FROM admin_users u
WHERE u.access_source = 'group' AND u.role <> 'superadmin'
AND (u.is_active = 1 OR u.group_disabled = 1)
${
all
? ""
: `AND u.is_active = 1
AND EXISTS (SELECT 1 FROM sessions s WHERE s.user_id = u.id AND s.expires_at > datetime('now'))
AND (u.groups_checked_at IS NULL OR u.groups_checked_at <= datetime('now', ?))`
}`,
)
.all(...(all ? [] : [`-${STALE_AFTER_MS / 1000} seconds`]));
const result = { checked: 0, changes: [], failed: [] };
for (const user of users) {
try {
const change = applyGroupRole(db, user, await groupRole(db, user.email));
result.checked++;
if (change) result.changes.push(`${user.email}: ${change}`);
} catch (err) {
console.warn(`access: couldn't check ${user.email}: ${err.message}`);
result.failed.push(`${user.email}: ${err.message}`);
}
}
return result;
}
export function startGroupSync(db) {
let running = false;
const tick = async () => {
if (running || !accessEnabled(db)) return;
running = true;
try {
await syncGroupAccounts(db);
} catch (err) {
console.error("access sync failed", err);
} finally {
running = false;
}
};
setInterval(tick, SYNC_EVERY_MS).unref();
}

View file

@ -21,8 +21,8 @@
admin + delete records
superadmin + accounts, roles and sessions, via /admin/panel
add takes --role=editor, --name="Full Name". It defaults to
admin. Press enter at the password prompt and it generates one
add takes --role=admin, --name="Full Name". It defaults to
editor, the least that can change content; raise it on purpose. Press enter at the password prompt and it generates one
and prints it once.
The list comes from auth.js rather than being repeated here, so
@ -139,7 +139,7 @@ function warnIfLastSuper(db, user) {
async function add(db, email, flags) {
if (findUser(db, email)) fail(`${email} already exists. Use passwd to change it.`);
const role = checkRole(flags.role ?? "admin");
const role = checkRole(flags.role ?? "editor");
const password = await readPassword();

View file

@ -113,7 +113,9 @@ function coerceValue(column, raw, errors, prefix = "") {
}
case "url": {
const value = String(raw).trim();
const scheme = URL_SCHEME.exec(value)?.[1].toLowerCase();
// The URL parser ignores control characters, spaces and tabs
// inside a scheme ("java\tscript:"), so read it the same way.
const scheme = URL_SCHEME.exec(value.replace(/[\u0000-\u0020\u007f]/g, ""))?.[1].toLowerCase();
if (scheme && !SAFE_SCHEMES.has(scheme)) {
errors[key] = "Links must start with http://, https://, mailto: or tel:, or be a site path like /retreats.";
return null;
@ -137,7 +139,9 @@ function coerceRow(columns, data, { prefix = "" } = {}) {
return { values, errors };
}
const applies = (gate, row) => !gate || row[gate.column] === gate.value;
/* A gate on a column's value: one value, or any of a list. */
const applies = (gate, row) =>
!gate || (Array.isArray(gate.value) ? gate.value.includes(row[gate.column]) : row[gate.column] === gate.value);
/* ── Read ────────────────────────────────────────────────────── */
@ -160,19 +164,24 @@ export function listRows(db, entity, query = {}) {
params.push(...search.map(() => term));
}
const limit = Math.min(Number(query.limit) || 200, 500);
const limit = Math.max(1, Math.min(Number(query.limit) || 200, 500));
const offset = Math.max(0, Math.floor(Number(query.offset) || 0));
const whereSql = where.length ? `WHERE ${where.join(" AND ")}` : "";
const rows = db
.prepare(
`SELECT ${columns.join(", ")}
FROM ${entity.table}
${where.length ? `WHERE ${where.join(" AND ")}` : ""}
${whereSql}
ORDER BY ${order}
LIMIT ?`,
LIMIT ? OFFSET ?`,
)
.all(...params, limit);
.all(...params, limit, offset);
return { rows, total: rows.length };
// Every match, not just this page, so the list can say how many more.
const { total } = db.prepare(`SELECT COUNT(*) AS total FROM ${entity.table} ${whereSql}`).get(...params);
return { rows, total };
}
export function readRow(db, entity, rawId) {
@ -187,8 +196,9 @@ export function readRow(db, entity, rawId) {
row[ext.key] = readExtension(db, ext, id);
}
// As text, for the reason readChildren gives its nested ids.
for (const child of entity.children ?? []) {
row[child.key] = readChildren(db, child, id);
row[child.key] = readChildren(db, child, String(id));
}
return row;
@ -234,15 +244,19 @@ function readChildren(db, child, ownerId) {
)
.all(...params);
// A row's own 1:1 side tables (a section's settings for its type:
// its hero's words, its blog's slots).
for (const ext of child.extensions ?? []) {
for (const row of rows) row[ext.key] = readExtension(db, ext, row.id);
}
// Nested collections, to any depth: a page's sections, each
// section's blocks, each block's items. The id goes as text: a JS
// number binds as REAL, which a TEXT owner column (a section's
// blocks) holds as '13.0'; text suits an INTEGER owner just as well.
for (const child2 of child.children ?? []) {
for (const row of rows) {
row[child2.key] = db
.prepare(
`SELECT * FROM ${child2.table}
WHERE ${child2.owner.column} = ?
ORDER BY ${child2.order}`,
)
.all(row.id);
row[child2.key] = readChildren(db, child2, String(row.id));
}
}
@ -376,6 +390,14 @@ export function updateRow(db, entity, rawId, payload) {
`UPDATE ${entity.table} SET ${sets.join(", ")}
WHERE ${entity.idColumn} = ?`,
).run(...Object.values(values), id);
} else if (entity.concurrency) {
// A row that is only its collections (a site page and its
// sections) still marks the save, or the next stale save
// would pass the check above.
db.prepare(
`UPDATE ${entity.table} SET ${entity.concurrency} = datetime('now')
WHERE ${entity.idColumn} = ?`,
).run(id);
}
writeExtensions(db, entity, id, payload, merged);
@ -397,6 +419,10 @@ export function deleteRow(db, entity, rawId) {
}
const id = normalizeId(entity, rawId);
// Records the site can't do without (the pages it draws in code).
if (entity.undeletable?.includes(id)) {
throw new HttpError(405, "The site needs this one: it can be hidden or disabled, not deleted.");
}
const result = wrapDbErrors(() =>
db.prepare(`DELETE FROM ${entity.table} WHERE ${entity.idColumn} = ?`).run(id),
);
@ -405,7 +431,7 @@ export function deleteRow(db, entity, rawId) {
/* ── Write helpers ───────────────────────────────────────────── */
function writeExtensions(db, entity, id, payload, parentValues) {
function writeExtensions(db, entity, id, payload, parentValues, prefix = "") {
for (const ext of entity.extensions ?? []) {
if (!applies(ext.when, parentValues)) {
// The gate closed (the kind changed away from this side
@ -417,7 +443,7 @@ function writeExtensions(db, entity, id, payload, parentValues) {
}
const { values, errors } = coerceRow(ext.columns, payload[ext.key] ?? {}, {
prefix: `${ext.key}.`,
prefix: `${prefix}${ext.key}.`,
});
if (Object.keys(errors).length) {
throw new HttpError(422, "Validation failed", errors);
@ -468,6 +494,8 @@ function isBlankChildRow(child, raw) {
if (!raw || typeof raw !== "object") return true;
for (const column of child.columns) {
// A value the admin seeds every new row with (`seeded`), not input.
if (column.seeded) continue;
const value = raw[column.name];
if (value === undefined || value === null || value === "") continue;
// An unchecked box is the default state of a new row, not input.
@ -505,7 +533,10 @@ function keyedDbErrors(prefix, fn) {
}
}
function writeChildren(db, entity, id, payload, parentValues) {
function writeChildren(db, entity, rawId, payload, parentValues) {
// As text: an auto id is a JS number, which binds as REAL and
// lands in a TEXT owner column (a newsletter's blocks) as '1.0'.
const id = String(rawId);
for (const child of entity.children ?? []) {
if (!applies(child.when, parentValues)) {
deleteChildren(db, child, id);
@ -514,80 +545,68 @@ function writeChildren(db, entity, id, payload, parentValues) {
if (payload[child.key] === undefined) continue; // not sent, not touched
deleteChildren(db, child, id);
writeRows(db, child, id, payload[child.key], `${child.key}.`, parentValues);
}
}
const incoming = Array.isArray(payload[child.key]) ? payload[child.key] : [];
/* One collection's rows under one owner, then each row's own nested
collections under it, to any depth. Only the top level is deleted
first (writeChildren): a nested row goes with its owner, by a
foreign key's cascade or, for a polymorphic owner like a section's
blocks, by the owner table's cleanup trigger. */
function writeRows(db, child, ownerId, incomingRaw, prefix, parentValues) {
const incoming = Array.isArray(incomingRaw) ? incomingRaw : [];
// index is the row's place in what the client sent, so a
// validation error still points at the row the user is looking
// at. position counts only the rows that survive, so dropping a
// blank in the middle doesn't leave a gap in sort_order.
const rows = incoming
.map((raw, index) => ({ raw, index }))
.filter(({ raw }) => child.allowBlank || !isBlankChildRow(child, raw));
// index is the row's place in what the client sent, so a
// validation error still points at the row the user is looking
// at. position counts only the rows that survive, so dropping a
// blank in the middle doesn't leave a gap in sort_order.
const rows = incoming
.map((raw, index) => ({ raw, index }))
.filter(({ raw }) => child.allowBlank || !isBlankChildRow(child, raw));
rows.forEach(({ raw, index }, position) => {
const { values, errors } = coerceRow(child.columns, raw, {
prefix: `${child.key}.${index}.`,
});
if (Object.keys(errors).length) {
throw new HttpError(422, "Validation failed", errors);
}
rows.forEach(({ raw, index }, position) => {
const rowPrefix = `${prefix}${index}.`;
const { values, errors } = coerceRow(child.columns, raw, { prefix: rowPrefix });
if (Object.keys(errors).length) {
throw new HttpError(422, "Validation failed", errors);
}
const names = [child.owner.column, ...Object.keys(values)];
const params = [id, ...Object.values(values)];
const names = [child.owner.column, ...Object.keys(values)];
const params = [ownerId, ...Object.values(values)];
if (child.owner.kindColumn) {
names.push(child.owner.kindColumn);
params.push(child.owner.kindValue);
}
for (const [column, from] of Object.entries(child.owner.inherit ?? {})) {
if (names.includes(column)) continue;
names.push(column);
params.push(parentValues[from] ?? id);
}
if (child.order === "sort_order" && !names.includes("sort_order")) {
names.push("sort_order");
params.push(position);
}
if (child.owner.kindColumn) {
names.push(child.owner.kindColumn);
params.push(child.owner.kindValue);
}
for (const [column, from] of Object.entries(child.owner.inherit ?? {})) {
if (names.includes(column)) continue;
names.push(column);
params.push(parentValues[from] ?? ownerId);
}
if (child.order === "sort_order" && !names.includes("sort_order")) {
names.push("sort_order");
params.push(position);
}
const result = keyedDbErrors(`${child.key}.${index}.`, () =>
db
const result = keyedDbErrors(rowPrefix, () =>
db
.prepare(
`INSERT INTO ${child.table} (${names.join(", ")})
VALUES (${names.map(() => "?").join(", ")})`,
)
.run(...params),
);
);
for (const child2 of child.children ?? []) {
const incomingNested = Array.isArray(raw[child2.key]) ? raw[child2.key] : [];
const nested = incomingNested
.map((rawItem, i) => ({ rawItem, i }))
.filter(({ rawItem }) => child2.allowBlank || !isBlankChildRow(child2, rawItem));
nested.forEach(({ rawItem, i }, nestedPosition) => {
const item = coerceRow(child2.columns, rawItem, {
prefix: `${child.key}.${index}.${child2.key}.${i}.`,
});
if (Object.keys(item.errors).length) {
throw new HttpError(422, "Validation failed", item.errors);
}
const itemNames = [child2.owner.column, ...Object.keys(item.values)];
const itemParams = [result.lastInsertRowid, ...Object.values(item.values)];
if (!itemNames.includes("sort_order")) {
itemNames.push("sort_order");
itemParams.push(nestedPosition);
}
db.prepare(
`INSERT INTO ${child2.table} (${itemNames.join(", ")})
VALUES (${itemNames.map(() => "?").join(", ")})`,
).run(...itemParams);
});
}
});
}
const rowId = Number(result.lastInsertRowid);
// Its own side tables, gated on its values (a section's preset),
// then its collections, gated the same way.
if (child.extensions) writeExtensions(db, child, rowId, raw, values, rowPrefix);
for (const child2 of child.children ?? []) {
if (!applies(child2.when, values)) continue;
writeRows(db, child2, String(rowId), raw[child2.key], `${rowPrefix}${child2.key}.`, values);
}
});
}
function deleteChildren(db, child, ownerId) {
@ -669,6 +688,12 @@ function wrapDbErrors(fn) {
);
}
// A trigger that refuses with a sentence (RAISE(ABORT, 'A group's
// ministry must be a ministry.')) is its own message.
if (err.errcode === 1811 && /\s/.test(message) && /[.!?]$/.test(message)) {
throw new HttpError(422, message);
}
throw err;
}
}

View file

@ -22,6 +22,15 @@
than waiting to surface one row at a time.
═══════════════════════════════════════════════════════════════ */
/* The values a CHECK (column IN (...)) on the table allows, read from
its CREATE TABLE, or null when there's no such CHECK. */
function checkValues(db, table, column) {
const sql = db.prepare(`SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = ?`).get(table)?.sql ?? "";
const match = new RegExp(`\\b${column}"?\\s+IN\\s*\\(([^)]*)\\)`, "i").exec(sql);
if (!match) return null;
return new Set([...match[1].matchAll(/'((?:[^']|'')*)'/g)].map((m) => m[1].replace(/''/g, "'")));
}
function tableMeta(db, table) {
const rows = db.prepare(`PRAGMA table_info(${table})`).all();
if (!rows.length) return null;
@ -76,6 +85,13 @@ function collectGroups(entity) {
...Object.keys(child.owner.inherit ?? {}),
].filter(Boolean),
});
for (const ext of child.extensions ?? []) {
groups.push({
table: ext.table,
columns: ext.columns ?? [],
engineSupplied: [ext.idColumn, ext.owner?.column, ext.owner?.kindColumn].filter(Boolean),
});
}
for (const nested of child.children ?? []) walk(nested);
};
@ -114,6 +130,19 @@ export function syncDescriptorsWithSchema(db, entities) {
inferred.push(`${name}: ${group.table}.${column.name}`);
}
if (info.notNullable) column.notNullable = true;
// A dropdown value the table's CHECK refuses would only fail
// when someone saves it; say so at boot instead.
if (column.type === "enum") {
const allowed = checkValues(db, group.table, column.name);
const refused = allowed ? column.values.filter((value) => !allowed.has(value)) : [];
if (refused.length) {
problems.push(
`${name}: ${group.table}.${column.name} offers ${refused.join(", ")}, ` +
`which the table's CHECK doesn't allow.`,
);
}
}
}
for (const [columnName, info] of meta) {

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,36 @@
import { text, int, bool } from "./columns.js";
/* ── Awards ──────────────────────────────────────────────────── */
// org_id is who gives the award. Nullable, because
// an award can predate any decision about which organization owns
// it, and because person_awards rows must survive the awarding
// org being deleted.
//
// No children: 'award' is not in the owner_kind CHECK on
// content_blocks or links. If awards ever need a page of their
// own, that CHECK is a table rebuild, so decide before adding one
// rather than after.
export const awards = {
key: "awards",
table: "awards",
idColumn: "id",
idKind: "slug",
list: {
columns: ["id", "org_id", "name", "description", "is_published", "is_listed", "sort_order"],
filters: ["org_id", "is_published", "is_listed"],
search: ["name", "id", "description"],
order: "org_id, sort_order, name",
},
columns: [
text("org_id"),
text("name", { required: true }),
text("description"),
text("logo"),
bool("is_published"),
bool("is_listed"),
int("sort_order"),
],
};

View file

@ -0,0 +1,47 @@
import { text, bool, date, blocksChild } from "./columns.js";
/* ── Blog (031_blog.sql) ─────────────────────────────────────────
Posts of our own, with a content-block body and people as
authors. The Community page's blog section is edited with that
page (sitePages.js). ──────────────────────────────────────── */
export const blogPosts = {
key: "blog_posts",
table: "blog_posts",
idColumn: "id",
idKind: "slug",
concurrency: "updated_at",
list: {
columns: ["id", "title", "published_on", "tags", "is_published", "is_listed", "updated_at"],
filters: ["is_published", "is_listed"],
search: ["title", "id", "tags"],
order: "published_on IS NULL, published_on DESC, title",
},
columns: [
text("title", { required: true }),
text("excerpt"),
text("cover_image"),
text("cover_alt"),
bool("show_contents"),
date("published_on"),
text("tags"),
text("guest_author"),
text("guest_photo"),
bool("is_published"),
bool("is_listed"),
],
children: [
{
key: "authors",
table: "blog_post_authors",
owner: { column: "post_id" },
order: "sort_order",
columns: [text("person_id", { required: true })],
},
blocksChild("blog_post"),
],
};

View file

@ -0,0 +1,311 @@
/* Column helpers, and the field sets and child collections several
entities share. The descriptor anatomy is in ../admin-schema.js. */
/* ── Column helpers ──────────────────────────────────────────── */
export const text = (name, opts = {}) => ({ name, type: "text", ...opts });
// Text that is a link: refuses javascript:, data: and other schemes.
export const url = (name, opts = {}) => ({ name, type: "url", ...opts });
export const int = (name, opts = {}) => ({ name, type: "int", ...opts });
export const real = (name, opts = {}) => ({ name, type: "real", ...opts });
export const bool = (name, opts = {}) => ({ name, type: "bool", ...opts });
export const date = (name, opts = {}) => ({ name, type: "date", ...opts });
export const time = (name, opts = {}) => ({ name, type: "time", ...opts });
export const enumeration = (name, values, opts = {}) => ({
name,
type: "enum",
values,
...opts,
});
/* Place columns shared by organizations and events, in schema order. */
export const placeColumns = [
text("venue"),
text("address"),
text("locality"),
text("state_code"),
text("country"),
text("location_label"),
real("latitude"),
real("longitude"),
];
/* The affiliation's own fields, minus whichever end owns the row.
Both editors write the same shape so neither loses the other's
values on save. */
export const affiliationRole = [
text("title"),
enumeration("role", ["lead", "board", "staff", "volunteer", "member"], {
required: true,
}),
bool("is_owner"),
date("started_on"),
date("ended_on"),
bool("is_public"),
];
/* The editable half of a timeline entry, shared by the standalone
editor and by the in_timeline extension on events and organizations.
occurred_on is text, not date. "2012" and "2025-07" are legitimate
values (a backfilled entry often knows the year and nothing more),
and the date coercion would reject both. `precision` is what says how
much of it to believe. */
export const timelineFields = [
text("occurred_on"),
enumeration("precision", ["year", "month", "day"]),
text("title"),
text("blurb"),
text("meta"),
url("link_url"),
bool("is_featured"),
bool("is_published"),
int("sort_order"),
];
/* The extension that the in_timeline checkbox drives. Ticked, the row
is upserted; unticked, writeExtensions deletes it. Both happen in the
parent's transaction, so the flag and the row cannot disagree.
The conflict target is the UNIQUE (ref_kind, ref_id) constraint
on timeline_entries, which is also what stops a second save creating a
duplicate instead of updating the first. */
export const timelineExtension = (refKind) => ({
key: "timeline",
table: "timeline_entries",
owner: { column: "ref_id", kindColumn: "ref_kind", kindValue: refKind },
conflict: ["ref_kind", "ref_id"],
when: { column: "in_timeline", value: 1 },
columns: [
// Fixed for this end: an event's entry is always an event entry.
// Declared as a default rather than a form field so the column is
// written without asking.
enumeration(
"kind",
["milestone", "event", "organization", "award", "people"],
{ default: refKind === "organization" ? "organization" : refKind },
),
...timelineFields,
],
});
/* Featured cards (030_featured_cards.sql): polymorphic like links,
so the Community blog can own a set too. */
export const featuredCardsChild = (ownerKind) => ({
key: "featured_cards",
table: "featured_cards",
owner: { column: "owner_id", kindColumn: "owner_kind", kindValue: ownerKind },
order: "sort_order",
columns: [
enumeration("kind", ["record", "link", "video"], { required: true }),
enumeration("ref_kind", ["event", "organization", "person", "team", "award"]),
text("ref_id"),
url("url"),
text("eyebrow"),
text("title"),
text("blurb"),
text("image"),
// Its shape in the grid (073); only the Front page editor sets it.
enumeration("size", ["normal", "wide", "tall", "large"]),
],
});
/* The two polymorphic collections, parameterized by owner_kind. */
export const linksChild = (ownerKind) => ({
key: "links",
table: "links",
owner: { column: "owner_id", kindColumn: "owner_kind", kindValue: ownerKind },
order: "sort_order",
columns: [
enumeration("kind", ["action", "social", "website", "email"], {
required: true,
}),
text("platform"),
text("label", { required: true }),
url("url", { required: true }),
bool("is_primary"),
],
});
export const blocksChild = (ownerKind) => ({
key: "content_blocks",
table: "content_blocks",
owner: { column: "owner_id", kindColumn: "owner_kind", kindValue: ownerKind },
order: "sort_order",
columns: [
enumeration("slot", ["card", "body", "both"], { required: true }),
enumeration(
"type",
[
"heading",
"subheading",
"paragraph",
"list",
"links",
"quote",
"image",
"divider",
"video",
"button",
"callout",
"schedule",
"table",
"cards",
"people",
// A blog post's tab (079): its text is the tab's title.
"tab",
// A venue's map, and event cards (088).
"map",
"events",
// Organization cards (093).
"organizations",
],
{ required: true },
),
text("text"),
text("media"),
// Image blocks (102): shown in place of media in the dark theme.
text("media_dark"),
url("href"),
text("alt"),
text("cite"),
// Video blocks only (066): an uploaded video's WebVTT file.
text("captions"),
// Its rotating words (084): blank keeps the site's.
enumeration("word_motion", ["slide", "flip", "fade", "type", "mirror"]),
enumeration("word_direction", ["top", "bottom"]),
int("word_seconds"),
// People blocks only (054): whose team's tiles to show.
text("team_id"),
// Map and schedule blocks (088): whose map and locations.
text("venue_id"),
// List blocks (092): null bold text, 'plain' the old look.
enumeration("list_style", ["plain"]),
// Image blocks (101): null full width, else a narrower size.
enumeration("image_size", ["small", "medium", "large"]),
// Organizations blocks (093): the kind listed when none are picked.
enumeration("org_kind", ["region", "group", "partner", "ministry"]),
// How it's presented (095): EventPresent.tsx.
// Where it shows (099): null both, the page or the presentation.
enumeration("present_show", ["page", "presentation"]),
text("present_text"),
bool("present_map_split"),
bool("present_map_no_list"),
bool("present_map_no_details"),
enumeration("present_places", ["picked", "none"]),
text("present_place_keys"),
],
children: [
{
key: "items",
table: "content_block_items",
owner: { column: "block_id" },
order: "sort_order",
columns: [
text("text", { required: true }),
text("detail"),
url("url"),
// Schedule entries only (034_schedule_block.sql).
text("day"),
text("time"),
text("location"),
text("person_id"),
text("description"),
text("media"),
text("media_alt"),
text("map"),
text("map_image"),
// Its kind, picked times and Featured tick (086).
enumeration("kind", ["block", "break", "heading"]),
time("start_time"),
time("end_time"),
bool("featured"),
// The block's tags it has, by key, comma-separated (087).
text("tags"),
// A workshop or other event it is, and its place on the
// block's venue map (088).
text("event_id"),
text("location_key"),
// A featured event's heading and subheading (090).
text("heading"),
text("subheading"),
// An organizations block's organization (093).
text("org_id"),
],
children: [
{
// A block entry's sub-items (086).
key: "items",
table: "content_block_subitems",
owner: { column: "item_id" },
order: "sort_order",
when: { column: "kind", value: "block" },
columns: [
text("text", { required: true }),
text("detail"),
url("url"),
time("start_time"),
time("end_time"),
text("time"),
text("location"),
text("person_id"),
text("description"),
text("media"),
text("media_alt"),
text("map"),
text("map_image"),
bool("featured"),
text("tags"),
text("event_id"),
text("location_key"),
],
},
],
},
{
// A schedule's own tags (087).
key: "tags",
table: "content_block_tags",
owner: { column: "block_id" },
order: "sort_order",
when: { column: "type", value: "schedule" },
columns: [
// Made by the admin as the row is added, so it isn't input.
text("tag_key", { required: true, seeded: true }),
text("name", { required: true }),
text("color"),
bool("no_tab"),
],
},
{
// A map block's own sections of its venue's locations (094).
key: "map_sections",
table: "content_block_map_sections",
owner: { column: "block_id" },
order: "sort_order",
when: { column: "type", value: "map" },
columns: [text("name", { required: true }), text("location_keys")],
},
],
});
/* Hosts. One row is one host, ordered, each either an organization
or a person. The CHECK on event_hosts rejects both and the blank
filter drops neither, so the only bad row that reaches SQLite is
one with both selects filled, and that comes back keyed to the
row like any other field error.
Not parameterized the way links and blocks are: this table is
events-only, and the owner column says so.
sort_order isn't declared. The engine writes it from the row's
position because `order` is "sort_order", which is what makes
the first row the one v_events takes the logo and color from. */
export const hostsChild = {
key: "event_hosts",
table: "event_hosts",
owner: { column: "event_id" },
order: "sort_order",
// team_id (054): an organization host's team, shown in its place.
columns: [text("org_id"), text("person_id"), text("team_id")],
};

View file

@ -0,0 +1,25 @@
import { text, int } from "./columns.js";
/* ── Contact types (064_org_contacts.sql) ────────────────────────
The roles an organization's contacts hold (Minister, General
info...), made in the admin. Its own entity, not a repeater,
because organization_contacts points at it; a type still in use
can't be deleted. The contacts themselves are edited on the
organization. */
export const contactTypes = {
key: "contact_types",
table: "contact_types",
idColumn: "id",
idKind: "slug",
list: {
columns: ["id", "name", "sort_order"],
filters: [],
search: ["name", "id"],
order: "sort_order, name",
},
columns: [text("name", { required: true }), int("sort_order")],
};

View file

@ -0,0 +1,139 @@
import { text, int, real, bool, date, time, enumeration, placeColumns, timelineExtension, linksChild, blocksChild, hostsChild } from "./columns.js";
import { tagsChild } from "./tags.js";
/* ── Events ──────────────────────────────────────────────────── */
/* Column suffixes for the series weekday flags, Sunday first to
match Date#getDay. */
const SERIES_WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
export const events = {
key: "events",
table: "events",
idColumn: "id",
idKind: "slug",
concurrency: "updated_at",
list: {
columns: [
"id",
"title",
"scope_id",
"event_type",
"date_label",
"starts_on",
"status",
"is_published",
"is_listed",
"updated_at",
],
// No host filter: hosts are rows in another table now, and the
// engine's filters are columns on this one. The events a host
// owns are on that host's own page.
filters: ["scope_id", "event_type", "status", "is_published", "is_listed"],
search: ["title", "id", "theme"],
order: "starts_on IS NULL, starts_on DESC, title",
},
columns: [
text("scope_id", { required: true }),
// What kind of gathering, as against scope_id's whose gathering
// it is. Declared required even though the column has a
// DEFAULT: every select renders a blank first option, so without
// it a new event files itself as a retreat while nobody is
// looking. An existing row always loads with its value set, so
// this only ever asks on create.
enumeration(
"event_type",
["retreat", "class", "workshop", "meeting", "other"],
{ required: true },
),
text("title", { required: true }),
text("theme"),
text("tagline"),
date("starts_on"),
date("ends_on"),
text("date_label"),
enumeration("status", ["upcoming", "past", "cancelled"]),
...placeColumns,
text("org_logo"),
text("event_logo"),
text("color"),
text("card_image"),
text("photo"),
text("photo_alt"),
bool("is_published"),
bool("is_listed"),
bool("in_timeline"),
bool("show_contents"),
text("links_heading"),
// Its page presented (095).
text("present_background"),
text("present_background_color"),
int("present_dim"),
enumeration("present_frame", ["border", "none"]),
text("present_accent"),
text("present_text_color"),
text("present_logo"),
// The same in the dark theme (096), null the above.
text("present_background_dark"),
text("present_background_color_dark"),
int("present_dim_dark"),
text("present_accent_dark"),
text("present_text_color_dark"),
text("present_logo_dark"),
// Room clear at each edge, eg. inside a frame picture (097).
real("present_inset_top"),
real("present_inset_right"),
real("present_inset_bottom"),
real("present_inset_left"),
// A repeating schedule. Columns rather than a side table: the
// schedule is always exactly one per event, and the public view
// is SELECT e.*, so it reaches the site with no join. Ignored
// while is_series is 0. The events table in the schema says
// what each means.
bool("is_series"),
enumeration("series_frequency", ["weekly", "monthly_date", "monthly_weekday"]),
int("series_interval"),
...SERIES_WEEKDAYS.map((day) => bool(`series_${day}`)),
time("series_start_time"),
time("series_end_time"),
int("series_count"),
],
extensions: [timelineExtension("event")],
children: [
hostsChild,
tagsChild("event_tags", "event_id"),
linksChild("event"),
blocksChild("event"),
{
key: "event_people",
table: "event_people",
owner: { column: "event_id" },
order: "sort_order",
columns: [
text("person_id", { required: true }),
enumeration(
"role",
[
"speaker",
"leader",
"facilitator",
"host",
"musician",
"volunteer",
"attendee",
],
{ required: true },
),
text("title"),
bool("is_public"),
],
},
],
};

View file

@ -0,0 +1,26 @@
import { text } from "./columns.js";
/* ── Newsletter drafts (057, 060_newsletter_layout.sql) ─────────
Saved from Tools → Newsletter (AdminNewsletter.tsx), which is
their only editor: there is no list or form for them in Data.
`layout` is the builder's JSON list of parts, in order
(src/lib/newsletter.ts); `title` is the title part's text, kept
apart for the list of drafts. */
export const newsletters = {
key: "newsletters",
table: "newsletters",
idColumn: "id",
idKind: "auto",
concurrency: "updated_at",
list: {
columns: ["id", "title", "updated_at"],
filters: [],
search: ["title"],
order: "updated_at DESC, id DESC",
},
columns: [text("title"), text("layout", { required: true })],
};

View file

@ -0,0 +1,106 @@
import { text, int, real, bool, enumeration, placeColumns, timelineExtension, linksChild, blocksChild, featuredCardsChild } from "./columns.js";
import { tagsChild } from "./tags.js";
/* ── Organizations ───────────────────────────────────────────── */
export const organizations = {
key: "organizations",
table: "organizations",
idColumn: "id",
idKind: "slug",
concurrency: "updated_at",
list: {
columns: [
"id",
"kind",
"name",
"short_name",
"locality",
"state_code",
"is_published",
"is_listed",
"sort_order",
"updated_at",
],
filters: ["kind", "is_published", "is_listed"],
search: ["name", "id", "locality"],
order: "kind, sort_order, name",
},
columns: [
enumeration("kind", ["national", "region", "group", "partner", "ministry"], {
required: true,
}),
text("name", { required: true }),
text("short_name"),
text("tagline"),
text("color"),
text("logo"),
...placeColumns,
bool("is_published"),
bool("is_listed"),
int("sort_order"),
bool("in_timeline"),
],
extensions: [
timelineExtension("organization"),
{
key: "region",
table: "regions",
idColumn: "id",
when: { column: "kind", value: "region" },
columns: [
enumeration("scope", ["domestic", "international", "virtual"], {
required: true,
}),
text("map_note"),
],
},
{
key: "group",
table: "groups",
idColumn: "id",
when: { column: "kind", value: "group" },
columns: [text("region_id"), text("ministry_id"), text("meets"), text("started")],
},
],
children: [
tagsChild("organization_tags", "org_id"),
linksChild("organization"),
blocksChild("organization"),
// Who to write to there, by role (064_org_contacts.sql): private,
// for the Newsletter's recipient export.
{
key: "contacts",
table: "organization_contacts",
owner: { column: "org_id" },
order: "sort_order",
readRole: "editor",
columns: [
text("type_id", { required: true }),
text("name"),
text("email"),
text("phone"),
],
},
// A region's own featured cards (072), in its row of the region
// list and on its page.
{ ...featuredCardsChild("organization"), when: { column: "kind", value: "region" } },
{
key: "region_areas",
table: "region_areas",
owner: { column: "region_id" },
when: { column: "kind", value: "region" },
order: "area_code",
columns: [
text("area_code", { required: true }),
real("share"),
enumeration("edge", ["top", "bottom"]),
text("note"),
],
},
],
};

View file

@ -0,0 +1,111 @@
import { text, int, bool, date, affiliationRole, linksChild, blocksChild } from "./columns.js";
/* ── People ──────────────────────────────────────────────────── */
export const people = {
key: "people",
table: "people",
idColumn: "id",
idKind: "slug",
concurrency: "updated_at",
list: {
columns: [
"id",
"display_name",
"sort_name",
"tagline",
"locality",
"is_published",
"is_listed",
"updated_at",
],
filters: ["is_published", "is_listed"],
search: ["display_name", "sort_name", "id"],
order: "sort_name, display_name",
},
columns: [
text("display_name", { required: true }),
text("sort_name"),
text("pronouns"),
text("tagline"),
text("specialty"),
text("photo"),
text("bio"),
text("primary_org_id"),
text("public_email"),
text("public_phone"),
text("locality"),
text("state_code"),
text("country"),
text("location_label"),
bool("is_published"),
bool("is_listed"),
// What's taken off the site (076): its owner's choice on their
// profile, or an admin's. v_people_public applies it.
...["photo", "pronouns", "tagline", "bio", "email", "phone", "location", "links"].map((key) => bool(`hide_${key}`)),
],
extensions: [
{
key: "private",
table: "person_private",
idColumn: "person_id",
readRole: "editor", // viewers don't see birth dates, addresses, phones
touch: true, // has its own updated_at with no trigger behind it
columns: [
date("birth_date"),
text("private_email"),
text("private_phone"),
text("address"),
text("notes"),
],
},
],
children: [
// The directories they're in (person_tag_types).
{
key: "tags",
table: "person_tags",
owner: { column: "person_id" },
order: "sort_order",
columns: [text("tag_id", { required: true })],
},
linksChild("person"),
blocksChild("person"),
{
key: "affiliations",
table: "affiliations",
owner: { column: "person_id" },
// sort_order is where this person sits on that team, so it
// belongs to the team's editor. reindex: false stops this
// form renumbering by row position; declaring the column
// keeps the team's value intact across a save here.
reindex: false,
order: "org_id, team_id, sort_order",
columns: [
text("org_id", { required: true }),
text("team_id"),
...affiliationRole,
int("sort_order"),
],
},
{
key: "person_awards",
table: "person_awards",
owner: { column: "person_id" },
order: "awarded_on",
columns: [
text("award_id", { required: true }),
text("event_id"),
date("awarded_on"),
text("citation"),
bool("is_public"),
],
},
],
};

View file

@ -0,0 +1,24 @@
import { text, int } from "./columns.js";
/* ── People tags (062_people_tags.sql) ───────────────────────────
What a person can be tagged as for a directory (Musicians first).
Its own entity, not a repeater, because person_tags points at it:
deleting a tag takes its rows on people with it (cascade). Which
people carry a tag is edited on the person. */
export const personTagTypes = {
key: "person_tag_types",
table: "person_tag_types",
idColumn: "id",
idKind: "slug",
list: {
columns: ["id", "name", "blurb", "sort_order"],
filters: [],
search: ["name", "id"],
order: "sort_order, name",
},
columns: [text("name", { required: true }), text("blurb"), int("sort_order")],
};

View file

@ -0,0 +1,30 @@
import { text, url } from "./columns.js";
/* ── Links/redirects (068_redirects.sql) ─────────────────────────
Short links on our domain, /go/<id>, answered by
routes/redirects.js. clicks and last_clicked_at are the route's,
so they're listed but never written from here: a save can't reset
a count. */
export const redirects = {
key: "redirects",
table: "redirects",
idColumn: "id",
idKind: "slug",
list: {
columns: ["id", "target_url", "clicks", "last_clicked_at"],
filters: [],
search: ["id", "target_url", "note", "utm_campaign"],
order: "id",
},
columns: [
url("target_url", { required: true }),
text("note"),
text("utm_source"),
text("utm_medium"),
text("utm_campaign"),
],
};

View file

@ -0,0 +1,36 @@
import { text, bool, enumeration } from "./columns.js";
/* ── Navigation (075_site_nav.sql) ───────────────────────────────
Pages → Navigation: the header's and footer's links, in order
(siteNav.js reads them for the site; the pages themselves are
Page management's, sitePages.js). Admins and up. */
export const siteNav = {
key: "navigation",
table: "site_nav",
idColumn: "id",
idKind: "slug",
singleton: "site",
concurrency: "updated_at",
writeRole: "admin",
list: { columns: ["id", "updated_at"], filters: [], search: [], order: "id" },
columns: [],
children: [
{
key: "links",
table: "site_nav_links",
owner: { column: "nav_id" },
order: "sort_order",
columns: [
enumeration("place", ["main", "action", "footer", "legal"], { required: true }),
text("label", { required: true }),
text("path", { required: true }),
text("parent_path"),
enumeration("style", ["filled"]),
bool("new_tab"),
],
},
],
};

View file

@ -0,0 +1,264 @@
import { HttpError } from "../admin-crud.js";
import { text, url, int, bool, enumeration, featuredCardsChild, blocksChild } from "./columns.js";
/* ── The site's pages (056_site_pages.sql, 080_page_registry.sql) ──
Pages → Page management: every page of the site, one site_pages
row each (its address, title, intro, Hidden and Disabled), with
its sections nested under it and each section's blocks under that
(the blocks' items under them, as on any record). A section is
either its blocks or a preset, a prebuilt part of the site
(SitePage.tsx draws both). New pages are made here.
A section type that needs more than its blocks keeps its settings
in tables of its own (083_section_settings.sql), the section's
extensions and collections here, each gated on its preset: a
hero's words and slides, a countdown's event, a stats band's
numbers, a pathfinder's paths, featured cards, a Community blog's
slots, pinned posts and feeds. The front page is a page of
sections like the rest. */
/* Gates on the section's preset. */
const is = (preset) => ({ column: "preset", value: preset });
const sectionsChild = {
key: "sections",
table: "page_sections",
owner: { column: "page_id" },
order: "sort_order",
columns: [
text("anchor", { required: true }),
text("title", { required: true }),
text("blurb"),
enumeration("accent", ["teal", "deep", "green", "amber"]),
enumeration("preset", [
"community_blog",
"group_map",
"region_list",
"partner_list",
"events",
"timeline",
"people_directory",
// What used to be whole pages (081).
"feedback_form",
"request_form",
"data_request_form",
"giving",
"qr_maker",
// The front page's bands, on any page (083).
"hero",
"countdown",
"calendar",
"stats",
"featured_cards",
"connect",
]),
text("scope_id"),
enumeration("event_type", ["retreat", "class", "workshop", "meeting", "other"]),
enumeration("view", ["carousel", "grid", "map"]),
// Organization cards (067): the kinds listed by themselves.
enumeration("org_kinds", ["partner", "ministry", "partner,ministry"]),
bool("is_hidden"),
],
extensions: [
{
key: "hero",
table: "section_hero",
idColumn: "section_id",
when: is("hero"),
columns: [
text("eyebrow"),
text("headline"),
text("subhead"),
text("primary_label"),
url("primary_url"),
text("secondary_label"),
url("secondary_url"),
enumeration("backdrop", ["brand", "photos"]),
int("slide_seconds"),
enumeration("feature", ["none", "livestream", "video", "event"]),
url("livestream_url"),
text("livestream_title"),
url("video_url"),
text("video_title"),
text("video_captions"),
text("video_still"),
text("event_id"),
// Its rotating words (084).
enumeration("word_motion", ["slide", "flip", "fade", "type", "mirror"]),
enumeration("word_direction", ["top", "bottom"]),
int("word_seconds"),
],
},
{
key: "countdown",
table: "section_countdown",
idColumn: "section_id",
when: is("countdown"),
columns: [text("event_id"), text("scope_id"), enumeration("event_type", ["retreat", "class", "workshop", "meeting", "other"])],
},
{
key: "featured",
table: "section_featured",
idColumn: "section_id",
when: is("featured_cards"),
columns: [int("columns")],
},
{
key: "blog",
table: "section_blog",
idColumn: "section_id",
when: is("community_blog"),
columns: [
text("internal_title"),
int("internal_slots"),
text("external_title"),
int("external_slots"),
url("external_url"),
text("external_label"),
],
},
],
children: [
blocksChild("page_section"),
{
// A People directory's tags (078), a tab each, in order.
key: "tags",
table: "page_section_tags",
owner: { column: "section_id" },
order: "sort_order",
columns: [text("tag_id", { required: true })],
},
{
// Organization cards (067): a hand-picked list, shown instead.
key: "orgs",
table: "page_section_orgs",
owner: { column: "section_id" },
order: "sort_order",
columns: [text("org_id", { required: true })],
},
{
key: "slides",
table: "section_slides",
owner: { column: "section_id" },
order: "sort_order",
when: is("hero"),
columns: [text("media", { required: true }), text("alt"), text("caption"), url("link_url")],
},
{
key: "stats",
table: "section_stats",
owner: { column: "section_id" },
order: "sort_order",
when: is("stats"),
columns: [
text("label", { required: true }),
enumeration("source", [
"manual",
"years_since",
"regions",
"groups",
"partners",
"events_held",
"retreats_held",
"people",
"awards_given",
]),
text("value"),
text("suffix"),
text("note"),
],
},
{
key: "paths",
table: "section_paths",
owner: { column: "section_id" },
order: "sort_order",
when: is("connect"),
columns: [text("label", { required: true }), text("icon"), text("blurb")],
children: [
{
key: "actions",
table: "section_path_actions",
owner: { column: "path_id" },
order: "sort_order",
columns: [text("label", { required: true }), text("description"), url("url", { required: true })],
},
],
},
// Featured cards, and a Community blog's pinned community posts.
{ ...featuredCardsChild("page_section"), when: { column: "preset", value: ["featured_cards", "community_blog"] } },
{
key: "blog_posts",
table: "section_blog_posts",
owner: { column: "section_id" },
order: "sort_order",
when: is("community_blog"),
columns: [text("post_id", { required: true })],
},
{
key: "feeds",
table: "section_feeds",
owner: { column: "section_id" },
order: "sort_order",
when: is("community_blog"),
columns: [url("url", { required: true }), text("label")],
},
],
};
/* Pages the site's own code links to (the footer's defaults, the
Request buttons, the privacy notice, Tools → QR codes): renamed,
hidden or disabled, but never moved or deleted. */
export const CORE_PAGES = { home: "/", give: "/give", feedback: "/feedback", request: "/request", qr: "/qr", privacy: "/privacy", terms: "/terms" };
/* Addresses a page can't take: the admin, the API, the uploads, the
records' own pages, the account pages and the remote. */
const RESERVED = [
"admin", "api", "uploads", "assets", "pa", "go",
"events", "regions", "groups", "partners", "organizations", "teams", "awards", "people", "blog", "directory",
"sign-in", "account", "remote", "sitemap.xml", "robots.txt",
];
/* After a save: the address is one a page may have. */
function checkPage(db, id) {
const page = db.prepare(`SELECT path FROM site_pages WHERE id = ?`).get(id);
const first = page?.path.split("/")[1];
if (first && RESERVED.includes(first)) {
throw new HttpError(422, "Validation failed", { path: `/${first} belongs to another part of the site. Pick another address.` });
}
if (CORE_PAGES[id] && page.path !== CORE_PAGES[id]) {
throw new HttpError(422, "Validation failed", { path: `The site links to this page at ${CORE_PAGES[id]}, so its address stays.` });
}
if (id !== "home" && page.path === "/") throw new HttpError(422, "Validation failed", { path: "/ is the front page." });
}
export const pages = {
key: "pages",
table: "site_pages",
idColumn: "id",
idKind: "slug",
concurrency: "updated_at",
undeletable: Object.keys(CORE_PAGES),
list: {
columns: ["id", "title", "path", "is_hidden", "is_disabled", "updated_at"],
filters: [],
search: ["title", "path"],
order: "sort_order, title",
},
columns: [
text("path", { required: true }),
text("title", { required: true }),
text("description"),
bool("is_hidden"),
bool("is_disabled"),
int("sort_order"),
],
children: [sectionsChild],
check: checkPage,
};

View file

@ -0,0 +1,63 @@
import { THEME_TOKENS, checkTheme } from "../theme.js";
import { text, int, enumeration } from "./columns.js";
/* ── Site settings (035_site_settings.sql) ──────────────────────
A singleton of overrides for what site.json says: name,
description, preview image, icons and search indexing (static
pages' titles and intros are Pages → Navigation's, siteNav.js).
Superadmins only. pageMeta.js merges it
over site.json. */
export const siteSettings = {
key: "site_settings",
table: "site_settings",
idColumn: "id",
idKind: "slug",
singleton: "site",
concurrency: "updated_at",
writeRole: "superadmin",
list: {
columns: ["id", "site_name", "updated_at"],
filters: [],
search: [],
order: "id",
},
columns: [
text("site_name"),
text("description"),
text("preview_image"),
text("favicon"),
text("apple_touch_icon"),
enumeration("indexing", ["on", "off"]),
text("notify_emails"),
text("access_group_viewer"),
text("access_group_editor"),
text("access_group_admin"),
enumeration("report_daily", ["on", "off"]),
enumeration("report_weekly", ["on", "off"]),
// Rotating words' defaults (084).
enumeration("word_motion", ["slide", "flip", "fade", "type", "mirror"]),
enumeration("word_direction", ["top", "bottom"]),
int("word_seconds"),
// Data → Planning Center's list (085).
text("pco_list_id"),
],
children: [
{
key: "colors",
table: "site_setting_colors",
owner: { column: "settings_id" },
order: "sort_order",
columns: [
enumeration("token", THEME_TOKENS, { required: true }),
text("light"),
text("dark"),
],
},
],
// Refuses a palette that would make text hard to read (theme.js).
check: checkTheme,
};

View file

@ -0,0 +1,35 @@
import { text, int } from "./columns.js";
/* ── Tags (070_tags.sql) ─────────────────────────────────────────
Descriptor tags for organizations and events (Online, In-Person).
Its own entity, not a repeater, because organization_tags and
event_tags point at it: deleting a tag takes it off every record
(cascade). Which records carry a tag is edited on the record. The
URL ID "online" is what v_events reads as an online event. */
export const tags = {
key: "tags",
table: "tags",
idColumn: "id",
idKind: "slug",
list: {
columns: ["id", "name", "sort_order"],
filters: [],
search: ["name", "id"],
order: "sort_order, name",
},
columns: [text("name", { required: true }), int("sort_order")],
};
/* The Tags repeater on an organization or event: owner is the
record's id column in that tag table. */
export const tagsChild = (table, owner) => ({
key: "tags",
table,
owner: { column: owner },
order: "sort_order",
columns: [text("tag_id", { required: true })],
});

View file

@ -0,0 +1,66 @@
import { text, int, bool, affiliationRole, linksChild, blocksChild } from "./columns.js";
/* ── Teams ───────────────────────────────────────────────────── */
// A team belongs to exactly one organization, and affiliations
// point at the pair (team_id, org_id) rather than the team alone.
// Two consequences the form has to live with:
//
// · org_id cannot be changed once anyone is filed under the
// team. The composite foreign key has no ON UPDATE CASCADE, so
// SQLite aborts the UPDATE. That surfaces as a constraint
// error, which is the correct answer: reassign the members
// first.
//
// · deleting a team with members fails the same way, rather than
// quietly detaching them. Emptying the members list first is
// now something the form can do.
export const teams = {
key: "teams",
table: "teams",
idColumn: "id",
idKind: "slug",
concurrency: "updated_at",
list: {
columns: ["id", "org_id", "name", "tagline", "is_published", "is_listed", "sort_order", "updated_at"],
filters: ["org_id", "is_published", "is_listed"],
search: ["name", "id", "tagline"],
order: "org_id, sort_order, name",
},
columns: [
text("org_id", { required: true }),
text("name", { required: true }),
text("tagline"),
text("color"),
text("logo"),
bool("is_published"),
bool("is_listed"),
int("sort_order"),
],
children: [
// 'team' is already a valid owner_kind in both polymorphic
// tables, and teams_cleanup drops the rows on delete, so a team
// page comes free.
linksChild("team"),
blocksChild("team"),
{
key: "members",
table: "affiliations",
// org_id is inherited from the team rather than asked for:
// the composite foreign key (team_id, org_id) means a member
// of this team can only belong to this team's organization,
// so a second dropdown could only ever be wrong.
owner: { column: "team_id", inherit: { org_id: "org_id" } },
// Row position is the order they appear on the public site.
// This is the only editor that writes it.
order: "sort_order",
columns: [text("person_id", { required: true }), ...affiliationRole],
},
],
};

View file

@ -0,0 +1,63 @@
import { text, date, time, enumeration, timelineFields } from "./columns.js";
/* ── Timeline ────────────────────────────────────────────────── */
// The history page's spine, and the only entity whose id the table
// assigns. There is nothing to slug: an entry referencing an event has
// no name of its own, and one gets created every time somebody ticks a
// checkbox. idKind "auto" is what lets createRow skip the id entirely.
//
// ref_kind and ref_id are writable here and only here. The extension on
// events and organizations owns those two columns for rows it created,
// which is why they aren't in timelineFields.
//
// Deleting an entry takes its people with it (ON DELETE CASCADE) and
// nothing points at an entry, so the delete-and-reinsert child engine
// is safe on this one.
export const timeline = {
key: "timeline",
table: "timeline_entries",
idColumn: "id",
idKind: "auto",
concurrency: "updated_at",
list: {
columns: [
"id",
"kind",
"ref_kind",
"ref_id",
"occurred_on",
"title",
"is_featured",
"is_published",
"updated_at",
],
filters: ["kind", "ref_kind", "is_featured", "is_published"],
search: ["title", "blurb", "meta", "ref_id"],
// Undated entries sort last rather than first, so a missing date
// reads as something to fix instead of something to scroll past.
order: "occurred_on IS NULL, occurred_on DESC, sort_order",
},
columns: [
enumeration(
"kind",
["milestone", "event", "organization", "award", "people"],
{ required: true },
),
enumeration("ref_kind", ["event", "organization", "award", "person", "team"]),
text("ref_id"),
...timelineFields,
],
children: [
{
key: "people",
table: "timeline_entry_people",
owner: { column: "entry_id" },
order: "sort_order",
columns: [text("person_id", { required: true }), text("note")],
},
],
};

View file

@ -0,0 +1,47 @@
import { text, real, url } from "./columns.js";
/* ── Venues (088_venues.sql) ─────────────────────────────────────
A place we gather, with its map picture and the locations marked
on it. Map blocks draw it, and schedule entries link to its
locations. Its own entity because content_blocks.venue_id points
at it; nothing points at a location's row, entries name one by
location_key, so the locations can be replaced wholesale. */
export const venues = {
key: "venues",
table: "venues",
idColumn: "id",
idKind: "slug",
list: {
columns: ["id", "name", "address"],
filters: [],
search: ["name", "id", "address"],
order: "name",
},
columns: [text("name", { required: true }), text("address"), text("map_image"), text("map_alt")],
children: [
{
key: "locations",
table: "venue_locations",
owner: { column: "venue_id" },
order: "sort_order",
columns: [
// Made by the admin as the row is added, so it isn't input.
text("location_key", { required: true, seeded: true }),
text("name", { required: true }),
text("detail"),
real("x"),
real("y"),
real("w"),
real("h"),
// The place in Google and Apple Maps (091).
url("google_maps_url"),
url("apple_maps_url"),
],
},
],
};

View file

@ -0,0 +1,205 @@
/* ═══════════════════════════════════════════════════════════════
ANALYTICS REPORTS
Plausible's numbers for this site, posted to a Discord channel:
daily yesterday: visitors, pageviews, bounce rate, visit
length, top pages and sources
weekly Mondays: the last 7 days, with the change from the 7
before
Each is switched on in Panel → Site settings → Reports. Both go
out at SEND_HOUR in REPORT_TZ, or as soon after as the server is
up that day; analytics_reports (065) keeps it to one a day.
── Configuration (the ngu-api service environment) ──
PLAUSIBLE_API_KEY a Stats API key (Plausible → Account
settings → API keys)
DISCORD_WEBHOOK_URL the channel's webhook (Discord → channel
settings → Integrations → Webhooks)
PLAUSIBLE_URL default http://127.0.0.1:8000, where the
self-hosted Plausible listens
REPORT_TZ default America/Chicago
Off until the first two are set. The site counted is the hostname
of site.json's url, as in pageMeta.js's analyticsTag.
To send one now (eg. to try the setup), whatever the switches say:
DB_PATH=/var/lib/ngu/ngu.db node src/analyticsReport.js daily|weekly
Setup: docs/analytics-reports.md.
═══════════════════════════════════════════════════════════════ */
import { pathToFileURL } from "node:url";
import { siteFor } from "./pageMeta.js";
export const PLAUSIBLE_URL = (process.env.PLAUSIBLE_URL || "http://127.0.0.1:8000").replace(/\/$/, "");
const PLAUSIBLE_API_KEY = process.env.PLAUSIBLE_API_KEY || null;
const DISCORD_WEBHOOK_URL = process.env.DISCORD_WEBHOOK_URL || null;
const REPORT_TZ = process.env.REPORT_TZ || "America/Chicago";
const SEND_HOUR = 8;
const TICK_MS = 15 * 60 * 1000;
const KINDS = ["daily", "weekly"];
export const reportsReady = () => Boolean(PLAUSIBLE_API_KEY && DISCORD_WEBHOOK_URL);
/* Today's date and the hour in REPORT_TZ, and whether it's Monday. */
function localNow(now = new Date()) {
const parts = Object.fromEntries(
new Intl.DateTimeFormat("en-US", {
timeZone: REPORT_TZ,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
hourCycle: "h23",
weekday: "short",
})
.formatToParts(now)
.map((part) => [part.type, part.value]),
);
return { date: `${parts.year}-${parts.month}-${parts.day}`, hour: Number(parts.hour), monday: parts.weekday === "Mon" };
}
/* "2026-10-04" moved by `days`. */
function shift(date, days) {
const d = new Date(`${date}T00:00:00Z`);
d.setUTCDate(d.getUTCDate() + days);
return d.toISOString().slice(0, 10);
}
/* ── Plausible ─────────────────────────────────────────────── */
async function query(siteId, body) {
const res = await fetch(`${PLAUSIBLE_URL}/api/v2/query`, {
method: "POST",
headers: { Authorization: `Bearer ${PLAUSIBLE_API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ site_id: siteId, ...body }),
signal: AbortSignal.timeout(20_000),
});
if (!res.ok) throw new Error(`Plausible answered ${res.status}: ${(await res.text()).slice(0, 200)}`);
return (await res.json()).results ?? [];
}
const METRICS = ["visitors", "pageviews", "bounce_rate", "visit_duration"];
async function totals(siteId, range) {
const [row] = await query(siteId, { metrics: METRICS, date_range: range });
return Object.fromEntries(METRICS.map((metric, i) => [metric, row?.metrics[i] ?? 0]));
}
async function top(siteId, dimension, range, limit) {
const rows = await query(siteId, {
metrics: ["visitors"],
dimensions: [dimension],
date_range: range,
order_by: [["visitors", "desc"]],
pagination: { limit },
});
return rows.length ? rows.map((r) => `${r.dimensions[0]}: ${r.metrics[0]}`).join("\n") : "-";
}
/* ── The message ───────────────────────────────────────────── */
const duration = (seconds) => `${Math.floor(seconds / 60)}m ${Math.round(seconds % 60)}s`;
function change(now, before) {
if (!before) return now ? " (new)" : "";
const percent = Math.round(((now - before) / before) * 100);
return ` (${percent >= 0 ? "+" : ""}${percent}%)`;
}
/* The Discord message for `kind` as of `today` (a REPORT_TZ date):
yesterday, or the 7 days ending yesterday. */
export async function buildReport(db, kind, today) {
const siteId = new URL(siteFor(db).url).hostname;
const to = shift(today, -1);
const from = kind === "weekly" ? shift(to, -6) : to;
const range = [from, to];
const limit = kind === "weekly" ? 5 : 3;
const [now, before, pages, sources] = await Promise.all([
totals(siteId, range),
kind === "weekly" ? totals(siteId, [shift(from, -7), shift(to, -7)]) : null,
top(siteId, "event:page", range, limit),
top(siteId, "visit:source", range, limit),
]);
const vs = (metric) => (before ? change(now[metric], before[metric]) : "");
return {
embeds: [
{
title: kind === "weekly" ? `${siteId}: week of ${from} to ${to}` : `${siteId}: ${to}`,
fields: [
{ name: "Visitors", value: `${now.visitors}${vs("visitors")}`, inline: true },
{ name: "Pageviews", value: `${now.pageviews}${vs("pageviews")}`, inline: true },
{ name: "Bounce rate", value: `${now.bounce_rate}%`, inline: true },
{ name: "Visit length", value: duration(now.visit_duration), inline: true },
{ name: "Top pages", value: pages },
{ name: "Top sources", value: sources },
],
},
],
};
}
export async function sendReport(db, kind, today = localNow().date) {
const res = await fetch(DISCORD_WEBHOOK_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(await buildReport(db, kind, today)),
signal: AbortSignal.timeout(20_000),
});
if (!res.ok) throw new Error(`Discord answered ${res.status}: ${(await res.text()).slice(0, 200)}`);
}
/* ── Schedule ──────────────────────────────────────────────── */
export function startAnalyticsReports(db) {
if (!reportsReady()) return;
let running = false;
const tick = async () => {
const { date, hour, monday } = localNow();
if (running || hour < SEND_HOUR) return;
running = true;
try {
const settings = db.prepare(`SELECT report_daily, report_weekly FROM site_settings WHERE id = 'site'`).get() ?? {};
for (const kind of KINDS) {
if (settings[`report_${kind}`] !== "on" || (kind === "weekly" && !monday)) continue;
if (db.prepare(`SELECT 1 FROM analytics_reports WHERE kind = ? AND sent_for = ?`).get(kind, date)) continue;
// Marked before sending: a Plausible or Discord failure is
// logged once that day, not every tick.
db.prepare(
`INSERT INTO analytics_reports (kind, sent_for) VALUES (?, ?)
ON CONFLICT (kind) DO UPDATE SET sent_for = excluded.sent_for`,
).run(kind, date);
try {
await sendReport(db, kind, date);
console.log(`analytics ${kind} report sent for ${date}`);
} catch (err) {
console.error(`analytics ${kind} report failed: ${err.message}`);
}
}
} finally {
running = false;
}
};
tick();
setInterval(tick, TICK_MS).unref();
}
/* ── By hand ───────────────────────────────────────────────── */
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
const kind = process.argv[2];
if (!KINDS.includes(kind)) {
console.error("usage: node src/analyticsReport.js daily|weekly");
process.exit(1);
}
if (!reportsReady()) {
console.error("Set PLAUSIBLE_API_KEY and DISCORD_WEBHOOK_URL first.");
process.exit(1);
}
const { openDatabase } = await import("./db.js");
const db = await openDatabase(process.env.DB_PATH ?? "./ngu.db");
await sendReport(db, kind);
console.log(`Sent the ${kind} report.`);
}

View file

@ -18,9 +18,11 @@
import {
createHash,
randomBytes,
scrypt,
scryptSync,
timingSafeEqual,
} from "node:crypto";
import { promisify } from "node:util";
import { getCookie, setCookie, deleteCookie } from "hono/cookie";
const SESSION_DAYS = 30;
@ -37,7 +39,7 @@ export const SECURE_COOKIE = (process.env.COOKIE_SECURE ?? "true") !== "false";
// path /, with no Domain, so a sibling subdomain can't plant or
// overwrite it. Plain http (local work, COOKIE_SECURE=false) can't
// use the prefix, so it keeps the plain name.
export const COOKIE_NAME = SECURE_COOKIE ? "__Host-ngu_session" : "ngu_session";
export const COOKIE_NAME = SECURE_COOKIE ? "__Host-site_session" : "site_session";
const IP_SALT = process.env.IP_SALT ?? randomBytes(16).toString("hex");
@ -68,7 +70,11 @@ export function hashPassword(password) {
].join("$");
}
export function verifyPassword(password, stored) {
/* Async: a login's hash runs on libuv's thread pool, so the ~100 ms it
takes doesn't stall every other request while it runs. */
const scryptAsync = promisify(scrypt);
export async function verifyPassword(password, stored) {
if (typeof stored !== "string") return false;
const [scheme, N, r, p, saltHex, keyHex] = stored.split("$");
@ -76,7 +82,7 @@ export function verifyPassword(password, stored) {
let candidate;
try {
candidate = scryptSync(
candidate = await scryptAsync(
password.normalize("NFKC"),
Buffer.from(saltHex, "hex"),
Buffer.from(keyHex, "hex").length,
@ -91,6 +97,12 @@ export function verifyPassword(password, stored) {
return timingSafeEqual(candidate, expected);
}
/* Text a visitor controls, made safe for one log line: control
characters (a newline would start a forged line) become "?", and
it's cut short. */
export const logSafe = (value, max = 200) =>
String(value ?? "").replace(/[\u0000-\u001f\u007f]/g, "?").slice(0, max);
/* ── Hashing helpers ─────────────────────────────────────────── */
const sha256 = (value) => createHash("sha256").update(value).digest("hex");
@ -207,14 +219,27 @@ export async function requireAuth(c, next) {
await next();
}
export const ROLES = ["viewer", "editor", "admin", "superadmin"];
const RANK = { viewer: 1, editor: 2, admin: 3, superadmin: 4 };
/* member is a profile account (076): signed in to the site and their
own profile, below every admin role, so it passes no admin check.
/api/admin as a whole needs viewer (index.js, requireStaff). */
export const ROLES = ["member", "viewer", "editor", "admin", "superadmin"];
const RANK = { member: 1, viewer: 2, editor: 3, admin: 4, superadmin: 5 };
/* Whether a user is at least this rank. A ladder, never equality. */
export function hasRole(user, role) {
return (RANK[user?.role] ?? 0) >= (RANK[role] ?? Infinity);
}
/* Anyone who uses the admin: a signed-in account of viewer and up.
A profile account (member) is signed in but gets 403 here. */
export async function requireStaff(c, next) {
const user = currentUser(c.get("db"), c);
if (!user) return c.json({ error: "Not signed in." }, 401);
if (!hasRole(user, "viewer")) return c.json({ error: "Not allowed." }, 403);
c.set("user", user);
await next();
}
export function requireRole(...roles) {
const need = Math.min(...roles.map((r) => RANK[r] ?? Infinity));
return async (c, next) => {

View file

@ -49,10 +49,10 @@
import { spawn } from "node:child_process";
import { randomBytes } from "node:crypto";
import { access, constants, copyFile, mkdir, readdir, rm, stat } from "node:fs/promises";
import { access, constants, copyFile, mkdir, readFile, readdir, rm, stat } from "node:fs/promises";
import path from "node:path";
import { UPLOADS_DIR, PUBLIC_PREFIX } from "./media.js";
import { UPLOADS_DIR, publicPath, storedNameFor } from "./media.js";
export const CLIPS_DIR = path.resolve(process.env.CLIPS_DIR ?? "./clips");
const YTDLP = process.env.YTDLP_PATH ?? "yt-dlp";
@ -150,11 +150,16 @@ export function checkClip(input, source) {
/* Runs a tool, calling onLine for each line of its output, and
resolves with the tail of stderr, or rejects with it. */
function run(command, args, { onLine } = {}) {
function run(command, args, { onLine, background = false } = {}) {
return new Promise((resolve, reject) => {
let child;
// An encode takes every core it can get; at the lowest priority it
// still does, but the API and its pages come first. Linux only
// (the VPS); elsewhere it runs as it is.
const [cmd, argv] =
background && process.platform === "linux" ? ["nice", ["-n", "19", command, ...args]] : [command, args];
try {
child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
child = spawn(cmd, argv, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
} catch (err) {
reject(err);
return;
@ -330,8 +335,17 @@ async function download(db, job) {
if (percent) update(db, job.id, { progress: Math.min(0.99, Number(percent[1]) / 100) });
const t = line.match(/^TITLE (.+)$/);
if (t) title = t[1].slice(0, 300);
// Only this job's own output file counts: a video title with
// a newline in it could print a "FILE ..." line of its own.
const f = line.match(/^FILE (.+)$/);
if (f) file = f[1].trim();
const candidate = f?.[1].trim();
if (
candidate &&
path.resolve(path.dirname(candidate)) === path.resolve(CLIPS_DIR) &&
path.basename(candidate).startsWith(`source-${job.id}.`)
) {
file = candidate;
}
},
},
);
@ -372,7 +386,7 @@ async function cut(db, job) {
const { width, height } = await probe(input);
if (width && height) {
// Crop the source to the shape. The focus is where along the
// cropped direction the frame is centred (0 left/top, 1
// cropped direction the frame is centered (0 left/top, 1
// right/bottom); even sizes, as the H.264 encoder needs.
let w = width;
let h = height;
@ -416,6 +430,7 @@ async function cut(db, job) {
args.push("-progress", "pipe:1", "-nostats", filePath(name));
await run(FFMPEG, args, {
background: true,
onLine: (line) => {
const us = line.match(/^out_time_us=(\d+)/);
if (us) update(db, job.id, { progress: Math.min(0.99, Number(us[1]) / 1e6 / length) });
@ -431,6 +446,63 @@ async function cut(db, job) {
});
}
/* ── A single frame ──────────────────────────────────────── */
/* One frame of a YouTube or Facebook video as a JPEG, for a card's
picture. yt-dlp only finds the stream's address and ffmpeg seeks
in it, so nothing is downloaded but that frame; light enough to
run in the request, outside the queue. */
export async function grabFrame(sourceUrl, seconds) {
const link = checkSourceUrl(sourceUrl);
if (!Number.isFinite(seconds) || seconds < 0 || seconds > MAX_SOURCE_SECONDS) {
throw new ClipError(400, "That isn't a time in the video.");
}
await mkdir(CLIPS_DIR, { recursive: true });
const id = `frame-${randomBytes(6).toString("hex")}`;
const out = path.join(CLIPS_DIR, `${id}.jpg`);
const cookies = await cookieArgs(id);
let stream = null;
try {
await run(
YTDLP,
[
"--ignore-config",
...cookies.args,
"--js-runtimes",
`node:${process.execPath}`,
"--no-playlist",
"-f",
"bv*[height<=1080]/b[height<=1080]/b",
"--get-url",
"--",
link,
],
{ onLine: (line) => (stream ??= /^https:\/\//.test(line.trim()) ? line.trim() : null) },
);
} catch (err) {
if (err instanceof ClipError) throw err;
console.error(`frame ${link}: ${err.message}`);
throw new ClipError(422, "The video couldn't be opened. It may be private or removed.");
} finally {
await cookies.cleanup();
}
if (!stream) throw new ClipError(422, "The video couldn't be opened. It may be private or removed.");
try {
// -ss before -i seeks in the stream instead of reading up to it.
await run(FFMPEG, ["-hide_banner", "-loglevel", "error", "-ss", String(seconds), "-i", stream, "-frames:v", "1", "-q:v", "2", "-y", out]);
return await readFile(out);
} catch (err) {
// Past the end, ffmpeg finishes without writing anything.
if (err.code === "ENOENT") throw new ClipError(422, "The video doesn't run that long.");
if (err instanceof ClipError) throw err;
console.error(`frame ${link} at ${seconds}: ${err.message}`);
throw new ClipError(422, "The frame couldn't be taken from the video.");
} finally {
await rm(out, { force: true });
}
}
let running = false;
let dbRef = null;
@ -475,17 +547,25 @@ export function kick(db = dbRef) {
export const fileOf = (job) => (job?.file ? filePath(job.file) : null);
/* A finished clip into the media library: copied into the uploads
directory under a random name, given a media row, and its working
file deleted. Returns the media row's id. */
export async function saveToLibrary(db, job, userId) {
/* A finished clip, or a whole downloaded video, into the media
library: copied into the uploads directory, named for `name` (the
Save to library box; blank: its title and span), and
given a media row. A clip's working file is deleted; a video's is
kept for cutting. Returns the media row's id. */
export async function saveToLibrary(db, job, userId, name = null) {
const from = fileOf(job);
if (!from) throw new ClipError(410, "That clip's file is gone. Make it again.");
const audio = job.file.endsWith(".mp3");
const ext = audio ? ".mp3" : ".mp4";
const filename = `${randomBytes(12).toString("hex")}${ext}`;
const to = path.join(UPLOADS_DIR, filename);
const params = JSON.parse(job.params ?? "{}");
const stamp = (s) => `${Math.floor(s / 60)}m${String(Math.floor(s % 60)).padStart(2, "0")}s`;
// A whole download is named for itself; a clip for its span.
const label =
name ??
(job.kind === "source"
? `${job.title ?? "Video"}${ext}`
: `${job.title ?? "Clip"} (${stamp(params.start ?? 0)} to ${stamp(params.end ?? 0)})${ext}`);
// Each step says what it was doing if it fails, so the page can
// tell an admin (this tool is admin-only) what to fix: usually the
@ -503,6 +583,8 @@ export async function saveToLibrary(db, job, userId) {
};
await step(`making the uploads folder ${UPLOADS_DIR}`, () => mkdir(UPLOADS_DIR, { recursive: true }));
const filename = await step("choosing its file name", () => storedNameFor(label, ext));
const to = path.join(UPLOADS_DIR, filename);
await step(`copying the clip into ${UPLOADS_DIR}`, () => copyFile(from, to));
let id;
@ -511,9 +593,6 @@ export async function saveToLibrary(db, job, userId) {
? { width: null, height: null }
: await step("reading the clip's size", () => probe(from));
const { size } = await stat(from);
const params = JSON.parse(job.params ?? "{}");
const stamp = (s) => `${Math.floor(s / 60)}m${String(Math.floor(s % 60)).padStart(2, "0")}s`;
const label = `${job.title ?? "Clip"} (${stamp(params.start ?? 0)} to ${stamp(params.end ?? 0)})${ext}`;
id = await step("adding it to the media table", () =>
Number(
@ -531,9 +610,15 @@ export async function saveToLibrary(db, job, userId) {
throw err;
}
await rm(from, { force: true });
update(db, job.id, { saved_media_id: id, file: null });
return { id, url: `${PUBLIC_PREFIX}${filename}` };
// A clip's working file goes; a downloaded video's stays, to cut
// clips from (the day's sweep clears it).
if (job.kind === "source") {
update(db, job.id, { saved_media_id: id });
} else {
await rm(from, { force: true });
update(db, job.id, { saved_media_id: id, file: null });
}
return { id, url: publicPath(filename) };
}
/* After a clip has gone out in full: its file isn't needed. */

View file

@ -36,27 +36,67 @@ export async function openDatabase(path) {
db.exec("PRAGMA busy_timeout = 5000");
db.driverName = "node:sqlite";
// A draft's preview opens its own connection to the same file (drafts.js).
db.path = path;
return db;
}
/* ── Transactions ──────────────────────────────────────────────
node:sqlite has no db.transaction(), so do it by hand. Runs
fn() and commits, or rolls back and rethrows.
fn() and commits, or rolls back and rethrows. Inside another
tx() (or rolledBack(), below) it's a savepoint instead, so a
save can run inside a transaction that's then thrown away:
how a draft is checked and previewed (drafts.js).
───────────────────────────────────────────────────────────── */
export function tx(db, fn) {
db.exec("BEGIN");
const depth = db.txDepth ?? 0;
const savepoint = `tx_${depth}`;
db.exec(depth ? `SAVEPOINT ${savepoint}` : "BEGIN");
db.txDepth = depth + 1;
try {
const result = fn();
db.exec("COMMIT");
db.exec(depth ? `RELEASE ${savepoint}` : "COMMIT");
return result;
} catch (err) {
try {
db.exec("ROLLBACK");
db.exec(depth ? `ROLLBACK TO ${savepoint}; RELEASE ${savepoint}` : "ROLLBACK");
} catch {
/* already rolled back */
}
throw err;
} finally {
db.txDepth = depth;
}
}
/* Runs fn() in a transaction that is always rolled back, whatever
fn() does: its writes are seen only by fn() itself. fn() may wait,
so only on a connection of its own (a draft's preview, drafts.js):
on the main one, another request would see the writes meanwhile. */
export async function rolledBack(db, fn) {
if (db.txDepth) throw new Error("rolledBack() can't run inside a transaction.");
db.exec("BEGIN");
db.txDepth = 1;
try {
return await fn();
} finally {
db.txDepth = 0;
db.exec("ROLLBACK");
}
}
/* The same for a synchronous fn(), which nothing else can run
during, so the main connection is fine (checking a draft). */
export function rolledBackSync(db, fn) {
if (db.txDepth) throw new Error("rolledBackSync() can't run inside a transaction.");
db.exec("BEGIN");
db.txDepth = 1;
try {
return fn();
} finally {
db.txDepth = 0;
db.exec("ROLLBACK");
}
}
@ -84,6 +124,9 @@ export function tx(db, fn) {
baseline was built by those older files and has to be brought
up by a release that still has them; running the baseline over
it would fail halfway on CREATE TABLE, so this refuses first.
The baseline's seed shares its version (066_schema.sql, then
066_seed.sql): `current` is read once, so an empty database
runs both and one already at that version skips both.
───────────────────────────────────────────────────────────── */
export function migrate(db, { log = console.log } = {}) {
@ -129,7 +172,7 @@ export function migrate(db, { log = console.log } = {}) {
throw new Error(`${file} leaves ${orphans.length} foreign key violation(s): ${where}`);
}
// Not parameterisable, but version is a validated integer.
// Not parameterizable, but version is a validated integer.
db.exec(`PRAGMA user_version = ${version}`);
});

84
server/src/discordAuth.js Normal file
View file

@ -0,0 +1,84 @@
/* ═══════════════════════════════════════════════════════════════
DISCORD LINKING
A profile account links its Discord account (076): OAuth 2.0 with
the identify scope only, which gives the Discord user's id and
name and nothing else (no servers, no messages). The routes are in
routes/account.js; an admin can also set or clear it by hand
(routes/profiles.js). Kept for the gamification to come, which
matches Discord members to people by this id.
DISCORD_CLIENT_ID from the Discord developer portal
DISCORD_CLIENT_SECRET the same; never in the repo
DISCORD_REDIRECT_URI default <site.json url>/api/account/discord/callback
With no client id or secret it's off: the profile page doesn't
offer it and the routes answer 404. Setup: docs/profile-accounts.md.
═══════════════════════════════════════════════════════════════ */
import { randomBytes } from "node:crypto";
import { loadSite } from "./pageMeta.js";
const AUTHORIZE = "https://discord.com/oauth2/authorize";
const TOKEN = "https://discord.com/api/oauth2/token";
const ME = "https://discord.com/api/users/@me";
export function discordConfig() {
const clientId = process.env.DISCORD_CLIENT_ID;
const clientSecret = process.env.DISCORD_CLIENT_SECRET;
if (!clientId || !clientSecret) return null;
let redirectUri = process.env.DISCORD_REDIRECT_URI ?? null;
if (!redirectUri) {
try {
const origin = (loadSite().url ?? "").replace(/\/$/, "");
if (origin) redirectUri = `${origin}/api/account/discord/callback`;
} catch {
redirectUri = null;
}
}
return { clientId, clientSecret, redirectUri };
}
/* Where to send the browser, and the state to keep until it's back. */
export function startLink(config) {
const state = randomBytes(24).toString("base64url");
const url = new URL(AUTHORIZE);
url.search = new URLSearchParams({
client_id: config.clientId,
redirect_uri: config.redirectUri,
response_type: "code",
scope: "identify",
state,
prompt: "consent",
});
return { url: url.toString(), state };
}
/* Trade the code for a token, then ask who it is. Returns
{ id, name } or throws. */
export async function finishLink(config, code) {
const res = await fetch(TOKEN, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
client_id: config.clientId,
client_secret: config.clientSecret,
grant_type: "authorization_code",
code,
redirect_uri: config.redirectUri,
}),
signal: AbortSignal.timeout(10_000),
});
const token = await res.json().catch(() => ({}));
if (!res.ok || !token.access_token) throw new Error(`Discord didn't accept the link (${res.status}).`);
const me = await fetch(ME, {
headers: { Authorization: `Bearer ${token.access_token}` },
signal: AbortSignal.timeout(10_000),
});
const user = await me.json().catch(() => ({}));
if (!me.ok || !user.id) throw new Error(`Discord didn't say who you are (${me.status}).`);
return { id: String(user.id), name: String(user.global_name || user.username || "").slice(0, 100) || null };
}

301
server/src/docx.js Normal file
View file

@ -0,0 +1,301 @@
/* ═══════════════════════════════════════════════════════════════
DOCX → CONTENT BLOCKS
Reads a Word document and turns it into a blog post's content
blocks (routes/import.js; Blog posts → Import from Word):
the Title, or the first Heading 1 the post's title
a date line right under it the post's date
Heading 1 and 2 heading blocks
Heading 3 and below subheading blocks
paragraphs paragraph blocks
runs of list paragraphs one list block, one item each
tables table blocks (a row per line,
cells split by |)
bold, italic, links **bold**, *italic*, [text](url)
And a few lines written a certain way (docs/importing.md), any
style:
"Tab: Overview" a tab block (079): the post
is split into tabs there
the Quote style a quote block
the Intense Quote style a callout block
"---" alone a divider
a YouTube, Vimeo or Facebook link a video block
alone on its line
"Button: [Register](https://…)" a button block
Images, text boxes, footnotes and comments aren't carried over;
the result counts what was skipped so the editor can say so.
A .docx is a zip of XML. Both are read here with no library: the
zip through Node's own zlib, the XML with a small tokenizer. The
file is someone's upload, so every size is capped and the XML is
walked once, with no pattern that rescans it.
═══════════════════════════════════════════════════════════════ */
import { inflateRawSync } from "node:zlib";
export class DocxError extends Error {
constructor(message) {
super(message);
this.status = 400;
}
}
const MAX_PART_BYTES = 20 * 1024 * 1024; // any one XML part, unpacked
const PARTS = ["word/document.xml", "word/styles.xml", "word/_rels/document.xml.rels"];
/* ── Zip ───────────────────────────────────────────────────────── */
/* The named entries of a zip, unpacked. Reads the central directory
(the index at the end), so it never walks the whole file. */
function unzip(buf, wanted) {
const out = {};
// End of central directory: the last 0x06054b50 in the final 64 KB.
let eocd = -1;
for (let i = buf.length - 22; i >= Math.max(0, buf.length - 65557); i--) {
if (buf.readUInt32LE(i) === 0x06054b50) {
eocd = i;
break;
}
}
if (eocd === -1) throw new DocxError("That file isn't a Word document (.docx).");
const count = buf.readUInt16LE(eocd + 10);
let at = buf.readUInt32LE(eocd + 16);
for (let n = 0; n < count && at + 46 <= buf.length; n++) {
if (buf.readUInt32LE(at) !== 0x02014b50) break;
const method = buf.readUInt16LE(at + 10);
const packed = buf.readUInt32LE(at + 20);
const size = buf.readUInt32LE(at + 24);
const nameLen = buf.readUInt16LE(at + 28);
const extraLen = buf.readUInt16LE(at + 30);
const commentLen = buf.readUInt16LE(at + 32);
const local = buf.readUInt32LE(at + 42);
const name = buf.toString("utf8", at + 46, at + 46 + nameLen);
at += 46 + nameLen + extraLen + commentLen;
// Each part once: a zip can list the same name thousands of times.
if (!wanted.includes(name) || name in out) continue;
if (size > MAX_PART_BYTES) throw new DocxError("That document is too large to import.");
const dataAt = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
const data = buf.subarray(dataAt, dataAt + packed);
if (method === 0) out[name] = data.toString("utf8");
else if (method === 8) out[name] = inflateRawSync(data, { maxOutputLength: MAX_PART_BYTES }).toString("utf8");
}
return out;
}
/* ── XML ───────────────────────────────────────────────────────── */
const ENTITY = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
const decode = (s) =>
s.replace(/&(#x[0-9a-f]{1,6}|#\d{1,7}|amp|lt|gt|quot|apos);/gi, (_, e) => {
if (e[0] !== "#") return ENTITY[e.toLowerCase()];
const n = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : Number(e.slice(1));
return String.fromCodePoint(n <= 0x10ffff ? n : 0xfffd);
});
/* A tree of { name, attrs, children, text }. One pass of one global
regex over the tags, so its cost is the file's length. */
function parseXml(xml) {
const root = { name: "#root", attrs: {}, children: [] };
const stack = [root];
const token = /<!--[\s\S]*?-->|<\?[\s\S]*?\?>|<!\[CDATA\[([\s\S]*?)\]\]>|<(\/?)([^\s>/]+)([^>]*?)(\/?)>|([^<]+)/g;
let m;
while ((m = token.exec(xml))) {
const top = stack[stack.length - 1];
if (m[1] !== undefined) top.children.push({ name: "#text", text: m[1] });
else if (m[6] !== undefined) top.children.push({ name: "#text", text: decode(m[6]) });
else if (m[3]) {
if (m[2]) {
if (stack.length > 1) stack.pop();
} else {
const attrs = {};
for (const a of m[4].matchAll(/([\w:.-]+)\s*=\s*"([^"]*)"/g)) attrs[a[1]] = decode(a[2]);
const node = { name: m[3], attrs, children: [] };
top.children.push(node);
if (!m[5]) stack.push(node);
}
}
}
return root;
}
const kids = (node, name) => (node?.children ?? []).filter((c) => c.name === name);
const kid = (node, name) => (node?.children ?? []).find((c) => c.name === name);
function* all(node, name) {
for (const c of node?.children ?? []) {
if (c.name === name) yield c;
yield* all(c, name);
}
}
const on = (el) => el && !["0", "false"].includes(el.attrs["w:val"]);
/* ── Text ──────────────────────────────────────────────────────── */
function runText(r) {
let t = "";
for (const c of r.children) {
if (c.name === "w:t") t += c.children.map((x) => x.text ?? "").join("");
else if (c.name === "w:tab") t += " ";
else if (c.name === "w:br" || c.name === "w:cr") t += " ";
}
if (!t.trim()) return t;
const rpr = kid(r, "w:rPr");
const b = on(kid(rpr, "w:b"));
const i = on(kid(rpr, "w:i"));
const lead = t.match(/^\s*/)[0];
const trail = t.match(/\s*$/)[0];
const core = t.trim();
const marked = b && i ? `***${core}***` : b ? `**${core}**` : i ? `*${core}*` : core;
return lead + marked + trail;
}
const SAFE_LINK = /^(https?:|mailto:)/i;
function paragraphText(p, rels, counts) {
let out = "";
for (const c of p.children) {
if (c.name === "w:r") {
if (kid(c, "w:drawing") || kid(c, "w:pict")) counts.images++;
out += runText(c);
} else if (c.name === "w:hyperlink") {
const label = [...all(c, "w:r")].map(runText).join("").trim();
const href = rels[c.attrs["r:id"]];
out += href && SAFE_LINK.test(href) && label ? `[${label.replace(/[[\]]/g, "")}](${href})` : label;
} else if (c.name === "w:ins" || c.name === "w:smartTag" || c.name === "w:sdt") {
out += [...all(c, "w:r")].map(runText).join("");
}
}
// Word splits a phrase into runs; adjacent bold runs meet as "** **".
return out.replace(/\*\*(\s*)\*\*/g, "$1").replace(/\s+/g, " ").trim();
}
/* ── Document ──────────────────────────────────────────────────── */
const DATE_LINE = /^([A-Z][a-z]{2,8}\.? \d{1,2},? \d{4}|\d{4}-\d{2}-\d{2}|\d{1,2} [A-Z][a-z]{2,8} \d{4})\b/;
export function readDocx(buf) {
const parts = unzip(buf, PARTS);
if (!parts["word/document.xml"]) throw new DocxError("That file isn't a Word document (.docx).");
const rels = {};
for (const r of all(parseXml(parts["word/_rels/document.xml.rels"] ?? ""), "Relationship")) {
if (r.attrs.TargetMode === "External" || /^https?:|^mailto:/i.test(r.attrs.Target ?? "")) rels[r.attrs.Id] = r.attrs.Target;
}
const styleName = {};
for (const s of all(parseXml(parts["word/styles.xml"] ?? ""), "w:style")) {
styleName[s.attrs["w:styleId"]] = (kid(s, "w:name")?.attrs["w:val"] ?? s.attrs["w:styleId"]).toLowerCase();
}
const body = kid(kid(parseXml(parts["word/document.xml"]), "w:document"), "w:body");
if (!body) throw new DocxError("That document has no body to import.");
const counts = { images: 0 };
const blocks = [];
let title = null;
let date = null;
let list = null; // the list block being filled
const close = () => {
if (list) blocks.push(list);
list = null;
};
for (const el of body.children) {
if (el.name === "w:tbl") {
close();
const rows = kids(el, "w:tr").map((tr) =>
kids(tr, "w:tc")
.map((tc) =>
kids(tc, "w:p")
.map((p) => paragraphText(p, rels, counts))
.filter(Boolean)
.join(" / ")
.replace(/\|/g, "\\|"),
)
.join(" | "),
);
if (rows.some((r) => r.replace(/[|\s]/g, ""))) blocks.push({ type: "table", text: rows.join("\n") });
continue;
}
if (el.name !== "w:p") continue;
const ppr = kid(el, "w:pPr");
const style = styleName[kid(ppr, "w:pStyle")?.attrs["w:val"]] ?? "";
const text = paragraphText(el, rels, counts);
if (!text) continue;
const level = style === "title" ? 0 : Number(/^heading (\d)/.exec(style)?.[1] ?? NaN);
if (!title && (level === 0 || level === 1) && !lineBlock(text, style)) {
close();
title = text.replace(/\*/g, "");
continue;
}
// The line under the title, when it starts with a date ("Sep 28,
// 2026 · @Aidan"), is the post's date, not part of the body.
if (title && !date && blocks.length === 0 && !list) {
const d = DATE_LINE.exec(text.replace(/\*/g, ""));
const parsed = d && new Date(d[1]);
if (parsed && !Number.isNaN(parsed.getTime())) {
date = parsed.toISOString().slice(0, 10);
continue;
}
}
const special = lineBlock(text, style);
if (special) {
close();
blocks.push(special);
continue;
}
if (level >= 1) {
close();
blocks.push({ type: level <= 2 ? "heading" : "subheading", text: text.replace(/\*/g, "") });
continue;
}
if (kid(ppr, "w:numPr") || /list/.test(style)) {
if (!list) list = { type: "list", items: [] };
list.items.push({ text });
continue;
}
close();
blocks.push({ type: "paragraph", text });
}
close();
return { title, date, blocks, skipped: counts };
}
/* ── Lines written a certain way ──────────────────────────────── */
const VIDEO_HOST = /^https?:\/\/(www\.)?(youtube\.com|youtu\.be|m\.youtube\.com|vimeo\.com|player\.vimeo\.com|facebook\.com|fb\.watch)\//i;
/* The one link a line is made of, "[text](url)" or a bare url, or null. */
function loneLink(text) {
const md = /^\[[^\]]*\]\(([^)\s]+)\)$/.exec(text);
if (md) return md[1];
return /^https?:\/\/\S+$/.test(text) ? text : null;
}
/* A block a paragraph stands for by how it's written, or null for an
ordinary one (docs/importing.md). */
function lineBlock(text, style) {
const plain = text.replace(/\*/g, "").trim();
const tab = /^tab:\s*(.+)$/i.exec(plain);
if (tab) return { type: "tab", text: tab[1].trim().slice(0, 80) };
if (/^(-{3,}|_{3,})$/.test(plain)) return { type: "divider" };
const button = /^button:\s*\[([^\]]+)\]\(([^)\s]+)\)$/i.exec(text.trim());
if (button) return { type: "button", text: button[1].replace(/\*/g, ""), href: button[2] };
const link = loneLink(text.trim());
if (link && VIDEO_HOST.test(link)) return { type: "video", href: link };
if (style === "intense quote") return { type: "callout", text };
if (style === "quote") {
// A dash and a name at the end ("… - Jane Doe", any dash) is who said it.
const said = /^(.*\S)\s+[—–-]\s*([^—–-]{2,80})$/.exec(text);
return said ? { type: "quote", text: said[1], cite: said[2].trim() } : { type: "quote", text };
}
return null;
}

156
server/src/drafts.js Normal file
View file

@ -0,0 +1,156 @@
/* ═══════════════════════════════════════════════════════════════
DRAFTS (077_drafts.sql)
A record's changes saved without going live: one per record, of
any entity the admin edits. The draft is the editor's whole form,
exactly what a save would send, so publishing is that save
(PATCH, routes/admin-entities.js), which then drops the draft.
Nothing applies a draft for real until it's published. Twice it's
applied and thrown away:
checking when it's saved, in a transaction on the main
connection that's always rolled back
(rolledBackSync): updateRow is synchronous, so no
other request can see it, and a draft that a save
would refuse is refused now, with the same errors
preview a public API read sent with X-Draft-Preview:
<entity>/<id> by a signed-in viewer and up runs on a
connection of its own (the same file), inside a
transaction holding the applied draft, rolled back
when the answer is made (previewDrafts). The site
draws the real page from it, with no code of its own
for previews. WAL keeps that connection's writes
unseen by everyone else; it holds the write lock
meanwhile, a few milliseconds, which other writes
wait out (busy_timeout).
The draft is applied over the live record as it is now, so a
save made since the draft was started is overwritten when it's
published; the editor says when that's so (stale).
═══════════════════════════════════════════════════════════════ */
import { currentUser, hasRole } from "./auth.js";
import { openDatabase, rolledBack, rolledBackSync } from "./db.js";
import { HttpError, normalizeId, updateRow } from "./admin-crud.js";
import { ENTITIES } from "./admin-schema.js";
/* Who may preview a draft: anyone who can read the admin. */
export const PREVIEWS = "viewer";
export const entityNamed = (key) => (Object.hasOwn(ENTITIES, key) ? ENTITIES[key] : null);
const liveStamp = (db, entity, id) =>
entity.concurrency
? db
.prepare(`SELECT ${entity.concurrency} AS stamp FROM ${entity.table} WHERE ${entity.idColumn} = ?`)
.get(normalizeId(entity, id))?.stamp
: undefined;
/* Writes the draft over the live record, its concurrency stamp taken
from the live row so the check passes. Call inside a rolled-back
transaction, or as the real publish. */
function apply(db, entity, id, payload) {
const stamp = liveStamp(db, entity, id);
return updateRow(db, entity, id, entity.concurrency ? { ...payload, [entity.concurrency]: stamp } : payload);
}
export function readDraft(db, key, id) {
const entity = entityNamed(key);
const row = db
.prepare(
`SELECT d.*, u.name AS updated_by_name, u.email AS updated_by_email
FROM drafts d LEFT JOIN admin_users u ON u.id = d.updated_by
WHERE d.entity = ? AND d.record_id = ?`,
)
.get(key, String(id));
if (!row) return null;
const live = entity ? liveStamp(db, entity, id) : undefined;
return {
payload: JSON.parse(row.payload),
created_at: row.created_at,
updated_at: row.updated_at,
updated_by: row.updated_by_name ?? row.updated_by_email ?? null,
// The live record was saved after the draft was started.
stale: Boolean(entity?.concurrency && row.base_updated_at && live && live !== row.base_updated_at),
};
}
/* The ids of an entity's records that have a draft, for its list. */
export const draftIds = (db, key) =>
db.prepare(`SELECT record_id FROM drafts WHERE entity = ?`).all(key).map((row) => row.record_id);
/* Checks the draft by applying it and throwing that away, then keeps
it. An HttpError from the check (422 with fields, say) refuses it. */
export function saveDraft(db, key, id, payload, userId) {
const entity = entityNamed(key);
if (!entity) throw new HttpError(404, "Unknown entity.");
if (!payload || typeof payload !== "object") throw new HttpError(400, "Expected the record's form.");
rolledBackSync(db, () => apply(db, entity, id, payload));
const existing = db.prepare(`SELECT base_updated_at FROM drafts WHERE entity = ? AND record_id = ?`).get(key, String(id));
const base = existing ? existing.base_updated_at : (payload[entity.concurrency] ?? null);
db.prepare(
`INSERT INTO drafts (entity, record_id, payload, base_updated_at, created_by, updated_by)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT (entity, record_id) DO UPDATE
SET payload = excluded.payload, updated_by = excluded.updated_by, updated_at = datetime('now')`,
).run(key, String(id), JSON.stringify(payload), base, userId, userId);
return readDraft(db, key, id);
}
export function dropDraft(db, key, id) {
db.prepare(`DELETE FROM drafts WHERE entity = ? AND record_id = ?`).run(key, String(id));
}
/* Middleware for the public API: a GET carrying X-Draft-Preview from
a signed-in viewer and up is answered with that draft applied. Any
other request, or a draft that isn't there, goes on as usual. */
export async function previewDrafts(c, next) {
if (c.req.method !== "GET" || /^\/api\/(admin|auth|account)(\/|$)/.test(c.req.path)) return next();
await answer(c, next);
// A public read may be kept a minute (shape.js, CACHE): never hand
// the live copy to a preview tab, or a preview's to anyone.
c.res.headers.append("Vary", "X-Draft-Preview");
}
async function answer(c, next) {
const wanted = c.req.header("x-draft-preview");
if (!wanted) return next();
const main = c.get("db");
if (!hasRole(currentUser(main, c), PREVIEWS)) return next();
const slash = wanted.indexOf("/");
const key = wanted.slice(0, slash);
let id;
try {
id = decodeURIComponent(wanted.slice(slash + 1));
} catch {
return next();
}
const entity = entityNamed(key);
const draft = slash > 0 && entity ? readDraft(main, key, id) : null;
if (!draft) return next();
const db = await openDatabase(main.path);
try {
await rolledBack(db, async () => {
// A draft the record has outgrown (a field it no longer has,
// say) shows the live page rather than an error; saving it in
// the editor says what's wrong.
try {
apply(db, entity, id, draft.payload);
} catch (err) {
console.warn(`draft preview ${key}/${id} not applied: ${err.message}`);
}
c.set("db", db);
await next();
});
} finally {
db.close();
}
// Only for this tab, never kept.
c.res.headers.set("Cache-Control", "no-store");
}

View file

@ -2,7 +2,7 @@
FEEDS
Reads the RSS and Atom feeds the Community page's blog section
lists (community_page_feeds), for its "newest community posts".
lists (section_feeds, 083), for its "newest community posts".
A Substack's feed is https://<name>.substack.com/feed.
Each feed is fetched through linkPreview.js's safeGet, so it gets
@ -18,7 +18,7 @@
image on the page.
═══════════════════════════════════════════════════════════════ */
import { decodeEntities, safeGet } from "./linkPreview.js";
import { decodeEntities, elements, innerOf, openTags, safeGet } from "./linkPreview.js";
const CACHE_MS = 30 * 60 * 1000;
const MAX_FEED_BYTES = 3 * 1024 * 1024;
@ -34,24 +34,32 @@ function unwrap(text) {
}
/* The text inside the first <tag>…</tag>, CDATA unwrapped. Tag
names may carry a namespace prefix (content:encoded). */
names may carry a namespace prefix (content:encoded). Scanned with
indexOf, not a regex: the feed is someone else's (see "Scanning
markup" in linkPreview.js). */
function inner(xml, tag) {
const match = xml.match(new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${tag}>`, "i"));
return match ? unwrap(match[1]) : null;
const text = innerOf(xml, tag);
return text == null ? null : unwrap(text);
}
function attrOf(xml, tag, name, where = () => true) {
for (const match of xml.matchAll(new RegExp(`<${tag}\\b[^>]*>`, "gi"))) {
const el = match[0];
for (const el of openTags(xml, tag, 50)) {
const value = el.match(new RegExp(`\\b${name}\\s*=\\s*("([^"]*)"|'([^']*)')`, "i"));
if (value && where(el)) return value[2] ?? value[3];
}
return null;
}
// Enough of a body or summary to make an excerpt from, so the tag
// strip and entity decoding never see more than this.
const PLAIN_SCAN = 20_000;
function plain(html) {
if (!html) return null;
const text = decodeEntities(html.replace(/<[^>]+>/g, " "));
// Tags stripped both before and after decoding: a description is
// often HTML written as entities (&lt;p&gt;).
const strip = (s) => s.replace(/<[^>]*>/g, " ");
const text = decodeEntities(strip(decodeEntities(strip(html.slice(0, PLAIN_SCAN)))));
if (!text) return null;
return text.length > EXCERPT_CHARS ? `${text.slice(0, EXCERPT_CHARS).trimEnd()}…` : text;
}
@ -74,21 +82,34 @@ function isoDate(raw) {
}
function firstImage(html) {
return html?.match(/<img\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/i)?.[1] ?? null;
if (!html) return null;
for (const tag of openTags(html, "img", 20)) {
const src = tag.match(/\bsrc\s*=\s*["']([^"']+)["']/i)?.[1];
if (src) return src;
}
return null;
}
function parseFeed(xml, feedUrl) {
const isAtom = /<feed\b[^>]*xmlns=["']http:\/\/www\.w3\.org\/2005\/Atom/i.test(xml) && !/<rss\b/i.test(xml);
const channelTitle = decodeEntities(inner(xml.replace(/<(item|entry)\b[\s\S]*$/i, ""), "title") ?? "");
const blocks = xml.match(isAtom ? /<entry\b[\s\S]*?<\/entry>/gi : /<item\b[\s\S]*?<\/item>/gi) ?? [];
// The root element is near the top; nothing needs the rest for this.
const top = xml.slice(0, 8192);
const root = openTags(top, "feed", 1)[0] ?? "";
const isAtom = /xmlns=["']http:\/\/www\.w3\.org\/2005\/Atom/i.test(root) && openTags(top, "rss", 1).length === 0;
const tag = isAtom ? "entry" : "item";
// The channel's own title is the one before the first item.
const firstItem = xml.toLowerCase().indexOf(`<${tag}`);
const channelTitle = decodeEntities(
inner(firstItem === -1 ? xml : xml.slice(0, firstItem), "title")?.slice(0, 1000) ?? "",
);
const blocks = elements(xml, tag, MAX_ITEMS_PER_FEED);
const items = [];
for (const block of blocks.slice(0, MAX_ITEMS_PER_FEED)) {
for (const block of blocks) {
const link = isAtom
? attrOf(block, "link", "href", (el) => !/rel\s*=\s*["'](?!alternate)/i.test(el))
: inner(block, "link");
const url = safeUrl(link?.trim(), feedUrl);
const title = decodeEntities(inner(block, "title") ?? "");
const title = decodeEntities(inner(block, "title")?.slice(0, 1000) ?? "");
if (!url || !title) continue;
const body = inner(block, "content:encoded") ?? inner(block, "content");
@ -123,20 +144,37 @@ async function fetchFeed(url) {
return parseFeed(result.body.toString("utf8"), result.url.toString());
}
/* One fetch at a time per feed, shared by everyone who asks while it
runs. A failure keeps the last good copy and waits 5 minutes before
trying again, rather than retrying on every request. */
function refresh(url) {
const hit = cache.get(url);
if (hit?.pending) return hit.pending;
const pending = fetchFeed(url)
.then((feed) => {
cache.set(url, { at: Date.now(), feed });
return feed;
})
.catch((err) => {
console.warn(`feed ${url}: ${err.message}`);
const stale = hit?.feed ?? { title: null, items: [] };
cache.set(url, { at: Date.now() - CACHE_MS + 5 * 60 * 1000, feed: stale });
return stale;
});
cache.set(url, { ...hit, pending });
return pending;
}
/* A fresh copy as it is; a stale one straight away while a refresh
runs behind it, so no visitor waits on someone else's server once
the feed has been read once. Only the very first read waits. */
async function readFeed(url) {
const hit = cache.get(url);
if (hit && Date.now() - hit.at < CACHE_MS) return hit.feed;
try {
const feed = await fetchFeed(url);
cache.set(url, { at: Date.now(), feed });
return feed;
} catch (err) {
console.warn(`feed ${url}: ${err.message}`);
// Serve the last good copy, and don't retry on every request.
const stale = hit?.feed ?? { title: null, items: [] };
cache.set(url, { at: Date.now() - CACHE_MS + 5 * 60 * 1000, feed: stale });
return stale;
if (hit?.feed) {
if (Date.now() - hit.at >= CACHE_MS) refresh(url);
return hit.feed;
}
return refresh(url);
}
/* Every listed feed's items, newest first, each tagged with its

View file

@ -30,6 +30,12 @@
Nothing here creates an account. A Google login is only let in
if admin-cli has already made one for that email (see auth.js
routes), and is linked to it on first use.
Profile accounts (076) are the one case outside the domain: an
invited member may sign in with any Google account under the
invited email. finishLogin says whether the identity is in the
Workspace domain (inDomain) instead of refusing it, and the
callback lets an outside identity reach a member account only.
═══════════════════════════════════════════════════════════════ */
import { createHash, randomBytes } from "node:crypto";
@ -70,8 +76,10 @@ export function googleConfig() {
}
/* The first leg: where to send the browser, and the state and PKCE
verifier to keep (in a short-lived cookie) until it comes back. */
export function startLogin(config) {
verifier to keep (in a short-lived cookie) until it comes back.
anyDomain: a profile account's sign-in, so the account chooser
isn't narrowed to the Workspace. */
export function startLogin(config, { anyDomain = false } = {}) {
const state = base64url(randomBytes(24));
const verifier = base64url(randomBytes(48));
const challenge = base64url(createHash("sha256").update(verifier).digest());
@ -87,7 +95,7 @@ export function startLogin(config) {
code_challenge_method: "S256",
// Only a hint to Google's account chooser; the hd claim is what's
// actually checked on the way back.
hd: config.domain,
...(anyDomain ? {} : { hd: config.domain }),
prompt: "select_account",
});
@ -102,7 +110,7 @@ export class GoogleLoginError extends Error {
}
/* The second leg: trade the code for tokens and check the identity.
Returns { sub, email, name } or throws GoogleLoginError. */
Returns { sub, email, name, inDomain } or throws GoogleLoginError. */
export async function finishLogin(config, code, verifier) {
let res;
try {
@ -145,9 +153,7 @@ export async function finishLogin(config, code, verifier) {
if (!claims.email_verified || !email) {
throw new GoogleLoginError("unverified", "That Google account's email isn't verified.");
}
if (String(claims.hd ?? "").toLowerCase() !== config.domain || !email.endsWith(`@${config.domain}`)) {
throw new GoogleLoginError("wrong_domain", `Use your @${config.domain} account.`);
}
const inDomain = String(claims.hd ?? "").toLowerCase() === config.domain && email.endsWith(`@${config.domain}`);
return { sub: String(claims.sub), email, name: claims.name ?? null };
return { sub: String(claims.sub), email, name: claims.name ?? null, inDomain };
}

404
server/src/googleService.js Normal file
View file

@ -0,0 +1,404 @@
/* ═══════════════════════════════════════════════════════════════
GOOGLE SERVICE ACCOUNT: Drive files and Gmail
The server acting as itself (not a person signing in, that's
googleAuth.js). A service account's key signs a short JWT, which
Google swaps for an access token (RS256 with node:crypto, no
library). Three uses:
Drive one shared drive (a service account has no storage of
its own), with a folder per use: "Requests" for files sent
with the Request form, and so on. Each folder is found by
name, or made, the first time it's needed; a path such as
"Media/2026" makes each level.
Gmail new-request notices, sent as a Workspace user through
domain-wide delegation.
Groups who is in the admin access groups (accessGroups.js), read
through the Directory API as a Workspace admin, the same
delegation.
Configured by the service environment:
GOOGLE_SERVICE_ACCOUNT path to the key's .json file (never in
the repo)
GOOGLE_SHARED_DRIVE the shared drive's id: only the last part
of its address, not the whole URL
GOOGLE_MAIL_FROM the Workspace address notices come from
GOOGLE_DIRECTORY_AS a Workspace admin (a user) whose view of
groups is read
Each part is off until its settings are there: without a shared drive
the form offers no uploads, and without a sender no mail goes out.
Setup: docs/google-drive-and-mail.md.
═══════════════════════════════════════════════════════════════ */
import { createReadStream, readFileSync } from "node:fs";
import { stat } from "node:fs/promises";
import { Readable } from "node:stream";
import { createSign, randomBytes } from "node:crypto";
const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
const GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send";
const GROUPS_SCOPE = "https://www.googleapis.com/auth/admin.directory.group.member.readonly";
const DRIVE = "https://www.googleapis.com/drive/v3/files";
const DRIVE_UPLOAD = "https://www.googleapis.com/upload/drive/v3/files";
export class GoogleError extends Error {}
let key = null;
function serviceKey() {
const file = process.env.GOOGLE_SERVICE_ACCOUNT;
if (!file) return null;
if (!key) {
const parsed = JSON.parse(readFileSync(file, "utf8"));
if (!parsed.client_email || !parsed.private_key) throw new GoogleError(`${file} is not a service account key.`);
key = parsed;
}
return key;
}
export const driveReady = () => Boolean(process.env.GOOGLE_SERVICE_ACCOUNT && process.env.GOOGLE_SHARED_DRIVE);
export const mailReady = () => Boolean(process.env.GOOGLE_SERVICE_ACCOUNT && process.env.GOOGLE_MAIL_FROM);
export const directoryReady = () => Boolean(process.env.GOOGLE_SERVICE_ACCOUNT && process.env.GOOGLE_DIRECTORY_AS);
/* ── Access tokens, kept until a minute before they run out ──── */
const tokens = new Map();
async function accessToken(scope, subject) {
const cacheKey = `${scope} ${subject ?? ""}`;
const cached = tokens.get(cacheKey);
if (cached && cached.until > Date.now()) return cached.token;
const sa = serviceKey();
if (!sa) throw new GoogleError("GOOGLE_SERVICE_ACCOUNT is not set.");
const now = Math.floor(Date.now() / 1000);
const part = (obj) => Buffer.from(JSON.stringify(obj)).toString("base64url");
const unsigned = `${part({ alg: "RS256", typ: "JWT" })}.${part({
iss: sa.client_email,
scope,
aud: sa.token_uri ?? "https://oauth2.googleapis.com/token",
iat: now,
exp: now + 3600,
...(subject ? { sub: subject } : {}),
})}`;
const signature = createSign("RSA-SHA256").update(unsigned).sign(sa.private_key, "base64url");
const res = await fetch(sa.token_uri ?? "https://oauth2.googleapis.com/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
assertion: `${unsigned}.${signature}`,
}),
signal: AbortSignal.timeout(15_000),
});
const data = await res.json().catch(() => ({}));
if (!res.ok || !data.access_token) {
throw new GoogleError(`token refused: ${data.error_description ?? data.error ?? res.status}`);
}
tokens.set(cacheKey, { token: data.access_token, until: Date.now() + (data.expires_in - 60) * 1000 });
return data.access_token;
}
async function call(url, init, scope, subject, timeoutMs = 60_000) {
const res = await fetch(url, {
...init,
headers: { ...init.headers, Authorization: `Bearer ${await accessToken(scope, subject)}` },
signal: AbortSignal.timeout(timeoutMs),
});
if (!res.ok) {
const detail = await res.json().catch(() => null);
throw new GoogleError(`${res.status} ${detail?.error?.message ?? res.statusText}`);
}
return res;
}
/* ── Drive ───────────────────────────────────────────────────── */
const FOLDER = "application/vnd.google-apps.folder";
// Folder path → a promise of its id. A promise, so two uploads at
// once don't both make the folder. A failed lookup is forgotten.
const folders = new Map();
/* The id of a folder in the shared drive, eg. "Requests" or
"Media/2026", made if it isn't there. Found by name, so a folder
renamed in Drive is made again under the old name. */
export function driveFolder(path) {
path = path.split("/").filter(Boolean).join("/");
let pending = folders.get(path);
if (!pending) {
pending = findOrMakeFolder(path);
folders.set(path, pending);
pending.catch(() => folders.delete(path));
}
return pending;
}
/* After a folder is renamed or deleted: its path, and the paths
under it, are looked up afresh next time. */
export function forgetFolders(path) {
for (const key of folders.keys()) if (key === path || key.startsWith(`${path}/`)) folders.delete(key);
}
async function findOrMakeFolder(path) {
const drive = process.env.GOOGLE_SHARED_DRIVE;
let parent = drive;
const walked = [];
for (const name of path.split("/").filter(Boolean)) {
// Each level on the way is known too: "Requests" once
// "Requests/Groups" has been found.
if (walked.length && !folders.has(walked.join("/"))) folders.set(walked.join("/"), Promise.resolve(parent));
walked.push(name);
const quoted = name.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
const query = new URLSearchParams({
q: `name = '${quoted}' and mimeType = '${FOLDER}' and '${parent}' in parents and trashed = false`,
corpora: "drive",
driveId: drive,
includeItemsFromAllDrives: "true",
supportsAllDrives: "true",
fields: "files(id)",
});
const found = (await (await call(`${DRIVE}?${query}`, {}, DRIVE_SCOPE)).json()).files?.[0];
parent = found
? found.id
: (
await (
await call(
`${DRIVE}?supportsAllDrives=true&fields=id`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, mimeType: FOLDER, parents: [parent] }),
},
DRIVE_SCOPE,
)
).json()
).id;
}
return parent;
}
/* One file into a folder of the shared drive (driveFolder). Returns
{ id, webViewLink }: Drive's id, and the page that shows it. */
export async function driveUpload(folder, name, mime, buffer) {
// Random, so no file can carry it by chance or design.
const boundary = `ngu${randomBytes(16).toString("hex")}`;
const meta = JSON.stringify({ name, parents: [await driveFolder(folder)] });
const body = Buffer.concat([
Buffer.from(
`--${boundary}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n${meta}\r\n` +
`--${boundary}\r\nContent-Type: ${mime}\r\n\r\n`,
),
buffer,
Buffer.from(`\r\n--${boundary}--`),
]);
const res = await call(
`${DRIVE_UPLOAD}?uploadType=multipart&supportsAllDrives=true&fields=id,webViewLink`,
{ method: "POST", headers: { "Content-Type": `multipart/related; boundary=${boundary}` }, body },
DRIVE_SCOPE,
);
return await res.json();
}
/* Everything directly in a folder: [{ id, name, mimeType, size,
webViewLink }]. size is missing for Google's own Docs, Sheets and
Slides. */
async function driveChildren(parent) {
const found = [];
let pageToken = "";
do {
const query = new URLSearchParams({
q: `'${parent}' in parents and trashed = false`,
corpora: "drive",
driveId: process.env.GOOGLE_SHARED_DRIVE,
includeItemsFromAllDrives: "true",
supportsAllDrives: "true",
pageSize: "200",
fields: "nextPageToken,files(id,name,mimeType,size,webViewLink)",
...(pageToken ? { pageToken } : {}),
});
const page = await (await call(`${DRIVE}?${query}`, {}, DRIVE_SCOPE)).json();
found.push(...(page.files ?? []));
pageToken = page.nextPageToken ?? "";
} while (pageToken);
return found;
}
/* A folder and the folders under it, down to `depth` levels: the
folders' paths (relative to it, "" for itself) and ids, and every
file with the path of the folder it's in. */
export async function driveTree(path, depth = 3) {
const folderList = [{ path: "", id: await driveFolder(path) }];
const files = [];
for (let i = 0; i < folderList.length; i++) {
const here = folderList[i];
for (const item of await driveChildren(here.id)) {
if (item.mimeType === FOLDER) {
const sub = here.path ? `${here.path}/${item.name}` : item.name;
if (sub.split("/").length <= depth) {
folderList.push({ path: sub, id: item.id });
// Known now: no lookup needed to upload into it.
const full = `${path}/${sub}`;
if (!folders.has(full)) folders.set(full, Promise.resolve(item.id));
}
} else {
files.push({ ...item, folder: here.path });
}
}
}
return { folders: folderList, files };
}
/* Whether a folder has anything in it (files or folders). */
export async function driveFolderEmpty(id) {
return (await driveChildren(id)).length === 0;
}
/* A file or folder from one folder into another. */
export async function driveMove(id, fromParent, toParent) {
await call(
`${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true&addParents=${encodeURIComponent(toParent)}&removeParents=${encodeURIComponent(fromParent)}`,
{ method: "PATCH", headers: { "Content-Type": "application/json" }, body: "{}" },
DRIVE_SCOPE,
);
}
export async function driveRename(id, name) {
await call(
`${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true`,
{ method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }) },
DRIVE_SCOPE,
);
}
/* A file on disk into a folder of the shared drive, streamed through
a resumable upload rather than read into memory (a video clip can
be large). Returns { id, webViewLink }, as driveUpload does. */
export async function driveUploadFile(folder, name, mime, filePath) {
const { size } = await stat(filePath);
const start = await call(
`${DRIVE_UPLOAD}?uploadType=resumable&supportsAllDrives=true&fields=id,webViewLink`,
{
method: "POST",
headers: {
"Content-Type": "application/json; charset=UTF-8",
"X-Upload-Content-Type": mime,
"X-Upload-Content-Length": String(size),
},
body: JSON.stringify({ name, parents: [await driveFolder(folder)] }),
},
DRIVE_SCOPE,
);
const session = start.headers.get("location");
if (!session) throw new GoogleError("Drive didn't start the upload.");
const res = await call(
session,
{
method: "PUT",
headers: { "Content-Type": mime, "Content-Length": String(size) },
body: Readable.toWeb(createReadStream(filePath)),
duplex: "half",
},
DRIVE_SCOPE,
undefined,
30 * 60_000,
);
return await res.json();
}
/* Anyone with the link can view: for files the public site links to.
Refused when the shared drive (or the Workspace) doesn't allow
sharing outside the organization. */
export async function driveShareWithAnyone(id) {
await call(
`${DRIVE}/${encodeURIComponent(id)}/permissions?supportsAllDrives=true`,
{ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ type: "anyone", role: "reader" }) },
DRIVE_SCOPE,
);
}
/* Drive's picture of a file's first page (PDFs, Office files), as
image bytes about `edge` pixels on the long side, or null while
Drive hasn't drawn one (it does so a little after upload) or can't. */
export async function driveThumbnail(id, edge = 1280) {
const res = await call(
`${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true&fields=hasThumbnail,thumbnailLink`,
{},
DRIVE_SCOPE,
);
const { hasThumbnail, thumbnailLink } = await res.json();
if (!hasThumbnail || !thumbnailLink) return null;
// The link ends in its size, eg. =s220; ask for a bigger one.
const image = await call(thumbnailLink.replace(/=s\d+$/, `=s${edge}`), {}, DRIVE_SCOPE);
return Buffer.from(await image.arrayBuffer());
}
export async function driveDownload(id) {
const res = await call(`${DRIVE}/${encodeURIComponent(id)}?alt=media&supportsAllDrives=true`, {}, DRIVE_SCOPE);
return Buffer.from(await res.arrayBuffer());
}
/* Into Drive's trash (a shared drive keeps it 30 days), not deleted
outright: a shared drive's Content manager, the service account's
role, may trash but not permanently delete. */
export async function driveDelete(id) {
await call(
`${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true`,
{ method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ trashed: true }) },
DRIVE_SCOPE,
);
}
/* ── Gmail ───────────────────────────────────────────────────── */
// A header value can't be allowed to start a new header.
const oneLine = (value) => String(value ?? "").replace(/[\r\n]+/g, " ").trim();
const encodeWord = (value) => `=?UTF-8?B?${Buffer.from(oneLine(value)).toString("base64")}?=`;
/* Plain text mail from GOOGLE_MAIL_FROM. replyTo lets a reply go
straight to whoever filled in the form. */
export async function sendMail({ to, subject, text, replyTo }) {
const from = process.env.GOOGLE_MAIL_FROM;
const headers = [
`From: ${oneLine(from)}`,
`To: ${to.map(oneLine).join(", ")}`,
...(replyTo ? [`Reply-To: ${oneLine(replyTo)}`] : []),
`Subject: ${encodeWord(subject)}`,
"MIME-Version: 1.0",
"Content-Type: text/plain; charset=UTF-8",
"Content-Transfer-Encoding: base64",
];
const raw = `${headers.join("\r\n")}\r\n\r\n${Buffer.from(text).toString("base64")}`;
await call(
"https://gmail.googleapis.com/gmail/v1/users/me/messages/send",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ raw: Buffer.from(raw).toString("base64url") }),
},
GMAIL_SCOPE,
from,
);
}
/* ── Groups ──────────────────────────────────────────────────── */
/* Whether someone is in a group, directly or through a group inside
it (the Directory API's hasMember follows nesting in the domain). */
export async function isGroupMember(group, email) {
const url =
"https://admin.googleapis.com/admin/directory/v1/groups/" +
`${encodeURIComponent(group)}/hasMember/${encodeURIComponent(email)}`;
try {
const res = await call(url, {}, GROUPS_SCOPE, process.env.GOOGLE_DIRECTORY_AS);
return (await res.json()).isMember === true;
} catch (err) {
// An address Google doesn't know ("Invalid Input: memberKey",
// "Resource Not Found: memberKey") is in no group of ours. A group
// it doesn't know (groupKey) is a setup mistake, and throws.
if (/^40[04] .*memberKey/i.test(err.message)) return false;
throw new GoogleError(`${group}: ${err.message}`);
}
}

View file

@ -13,6 +13,8 @@ import { mkdir } from "node:fs/promises";
import { serve } from "@hono/node-server";
import { serveStatic } from "@hono/node-server/serve-static";
import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit";
import { HTTPException } from "hono/http-exception";
import { csrf } from "hono/csrf";
import { logger } from "hono/logger";
import { secureHeaders } from "hono/secure-headers";
@ -22,22 +24,34 @@ import { rateLimit } from "./rateLimit.js";
import content from "./routes/content.js";
import people from "./routes/people.js";
import history from "./routes/history.js";
import home from "./routes/home.js";
import directory from "./routes/directory.js";
import blog from "./routes/blog.js";
import sitePages from "./routes/sitePages.js";
import pages from "./routes/pages.js";
import feedback from "./routes/feedback.js";
import requests from "./routes/requests.js";
import auth from "./routes/auth.js";
import account from "./routes/account.js";
import profiles from "./routes/profiles.js";
import pco from "./routes/pco.js";
import admin from "./routes/admin.js";
import panel from "./routes/panel.js";
import adminEntities from "./routes/admin-entities.js";
import media from "./routes/media.js";
import clips from "./routes/clips.js";
import imports from "./routes/import.js";
import files from "./routes/files.js";
import countdown from "./routes/countdown.js";
import redirects from "./routes/redirects.js";
import present from "./routes/present.js";
import { CLIPS_DIR, startClipWorker } from "./clips.js";
import { UPLOADS_DIR } from "./media.js";
import { startSessionSweeper } from "./auth.js";
import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
import { logSafe, requireStaff, startSessionSweeper } from "./auth.js";
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
import { startGroupSync } from "./accessGroups.js";
import { startAnalyticsReports } from "./analyticsReport.js";
import { ENTITIES } from "./admin-schema.js";
import { previewDrafts } from "./drafts.js";
const HOST = process.env.HOST ?? "127.0.0.1";
const PORT = Number(process.env.PORT ?? 3001);
@ -52,12 +66,28 @@ syncDescriptorsWithSchema(db, ENTITIES);
console.log(`db ${DB_PATH} (${db.driverName}, schema v${version})`);
await mkdir(UPLOADS_DIR, { recursive: true });
console.log(`uploads ${UPLOADS_DIR}`);
// In the background: pages fall back to the full file until it's done.
writeMissingThumbs()
.then((made) => made && console.log(`uploads: made ${made} small copies`))
.catch((err) => console.warn(`uploads: small copies failed: ${err.message}`));
/* ── App ─────────────────────────────────────────────────────── */
const app = new Hono();
app.use("*", logger());
// One log line per admin request, for the record of who did what.
// Public traffic is left to nginx's access log: logging every request
// here too would double the lines and, under a spike, cost the event
// loop a synchronous write each.
app.use("/api/admin/*", logger());
/* A newsletter's countdown picture is shown inside other sites'
webmail, which the same-origin resource policy set below would
refuse. Registered first so it runs last, after secureHeaders. */
app.use("/api/countdown/*", async (c, next) => {
await next();
c.res.headers.set("Cross-Origin-Resource-Policy", "cross-origin");
});
/* Headers for every response. Referrer kept to the origin (YouTube
embeds refuse to play without one). No HSTS here: nginx sends it on
@ -69,7 +99,7 @@ app.use("*", logger());
/api/csp-report (journalctl -u ngu-api). Once a while of real use
logs nothing unexpected, switch contentSecurityPolicyReportOnly to
contentSecurityPolicy. 'unsafe-inline' scripts cover the page's
window.__NGU_SITE__ and the theme script in index.html. */
window.__SITE__ and the theme script in index.html. */
const EMBEDS = [
"https://www.youtube-nocookie.com",
"https://www.youtube.com",
@ -104,6 +134,12 @@ app.use(
}),
);
/* The public JSON writes read their whole body before trimming it,
so each is capped well above its longest real body (a 5000
character message) and far below nginx's limit. */
const smallBody = bodyLimit({ maxSize: 64 * 1024, onError: (c) => c.json({ error: "That's too long." }, 413) });
for (const path of ["/api/csp-report", "/api/feedback", "/api/auth/login", "/api/account/accept", "/api/account/claim", "/api/account/profile", "/api/present/*"]) app.use(path, smallBody);
/* What the policy above would have blocked. Browsers post these on
their own; a short line per report is plenty to go on. */
app.use("/api/csp-report", rateLimit({ windowMs: 60_000, max: 30 }));
@ -111,8 +147,9 @@ app.post("/api/csp-report", async (c) => {
const text = (await c.req.text()).slice(0, 4000);
try {
const report = JSON.parse(text)["csp-report"] ?? {};
const field = (name) => logSafe(report[name] ?? "?", 150);
console.warn(
`csp ${report["violated-directive"] ?? "?"} blocked ${report["blocked-uri"] ?? "?"} on ${report["document-uri"] ?? "?"}`,
`csp ${field("violated-directive")} blocked ${field("blocked-uri")} on ${field("document-uri")}`,
);
} catch {
// Not a report; nothing to log.
@ -145,6 +182,10 @@ app.use("*", async (c, next) => {
await next();
});
// A draft's preview (drafts.js): a public read from a signed-in
// viewer with X-Draft-Preview answers with that draft applied.
app.use("/api/*", previewDrafts);
app.get("/api/health", (c) =>
c.json({ ok: true, schema: version, driver: db.driverName }),
);
@ -152,23 +193,48 @@ app.get("/api/health", (c) =>
app.route("/api", content);
app.route("/api", people);
app.route("/api", history);
app.route("/api", home);
app.route("/api", directory);
app.route("/api", blog);
app.route("/api", sitePages);
// Opened by everyone a newsletter goes to, often through one mail
// proxy's address, so looser than the rest; each picture is kept for
// its minute (routes/countdown.js).
app.use("/api/countdown/*", rateLimit({ windowMs: 60_000, max: 600 }));
app.route("/api", countdown);
// Tighter limit on the write path than anything else gets.
// A presenting screen and its remotes, by the screen's code
// (routes/present.js): a cap far above tapping, far below guessing.
app.use("/api/present/*", rateLimit({ windowMs: 60_000, max: 300 }));
app.route("/api", present);
app.use("/api/feedback", rateLimit({ windowMs: 60_000, max: 5 }));
app.route("/api/feedback", feedback);
// Requests carry files: fewer again.
app.use("/api/requests", rateLimit({ windowMs: 10 * 60_000, max: 5 }));
app.route("/api/requests", requests);
app.use("/api/auth/login", rateLimit({ windowMs: 15 * 60_000, max: 10 }));
// Looser than a password guess: each Google sign-in is two requests,
// and Google has already checked the person by the second.
app.use("/api/auth/google/*", rateLimit({ windowMs: 15 * 60_000, max: 40 }));
// The whole admin is for viewer and up; a profile account (member)
// is signed in but kept out. Each router still checks its own.
app.use("/api/admin/*", requireStaff);
app.route("/api/admin/panel", panel);
app.route("/api/auth", auth);
// A profile account's own page (076); setting a password from an
// invite is held to the login's pace.
app.use("/api/account/accept", rateLimit({ windowMs: 15 * 60_000, max: 10 }));
app.use("/api/account/photo", rateLimit({ windowMs: 15 * 60_000, max: 20 }));
app.route("/api/account", account);
app.route("/api/admin", admin);
app.route("/api/admin", profiles);
app.route("/api/admin", pco);
// Before the entity routes, whose /:entity would claim /media.
app.route("/api/admin", media);
app.route("/api/admin", imports);
app.route("/api/admin", files);
app.route("/api/admin", clips);
app.route("/api/admin", adminEntities);
@ -192,17 +258,26 @@ app.use(
}),
);
// Short links, /go/<id> (routes/redirects.js); an unknown one falls
// through to the pages below.
app.route("/", redirects);
// Last: every other GET that isn't /api is a page of the site, sent
// with its metadata filled in (routes/pages.js).
app.route("/", pages);
startSessionSweeper(db);
startGroupSync(db);
startClipWorker(db);
startAnalyticsReports(db);
console.log(`clips ${CLIPS_DIR}`);
app.notFound((c) => c.json({ error: "Not found" }, 404));
app.onError((err, c) => {
// A deliberate refusal (the CSRF check's 403, say) is an answer,
// not a crash: send it as it is and keep it out of the error log.
if (err instanceof HTTPException) return err.getResponse();
console.error(err);
// Never leak internals to the browser.
return c.json({ error: "Something went wrong." }, 500);

89
server/src/invites.js Normal file
View file

@ -0,0 +1,89 @@
/* ═══════════════════════════════════════════════════════════════
INVITES: how a profile account (076) comes to exist
Nobody signs up. An admin adds an email (Data → Profile
accounts, routes/profiles.js), which makes a member account with
no password, and issues an invite: a link to /account/welcome
with a random token. The token itself is shown once, to the
admin, and emailed if they press Email invite; the database
keeps only its SHA-256, like a session's. Issuing a new one
replaces the old, so a link sent to the wrong place can be
killed by sending another.
The link lets its holder set a password (routes/account.js).
Signing in with Google under the invited email takes it up too
(routes/auth.js). Either way the token is cleared.
═══════════════════════════════════════════════════════════════ */
import { createHash, randomBytes } from "node:crypto";
import { loadSite } from "./pageMeta.js";
import { mailReady, sendMail } from "./googleService.js";
export const INVITE_DAYS = 14;
const sha256 = (value) => createHash("sha256").update(value).digest("hex");
/* A new invite for this account, replacing any before it. Returns
the link, which is never stored. */
export function issueInvite(db, accountId, invitedBy) {
const token = randomBytes(32).toString("base64url");
db.prepare(
`UPDATE admin_users
SET invite_hash = ?, invite_expires_at = datetime('now', ?),
invited_at = datetime('now'), invited_by = ?
WHERE id = ?`,
).run(sha256(token), `+${INVITE_DAYS} days`, invitedBy, accountId);
return inviteLink(token);
}
export function inviteLink(token) {
let origin = "";
try {
origin = (loadSite().url ?? "").replace(/\/$/, "");
} catch {
origin = "";
}
return `${origin}/account/welcome?token=${encodeURIComponent(token)}`;
}
/* The account an unexpired invite token belongs to, or null. */
export function accountForInvite(db, token) {
if (typeof token !== "string" || token.length < 20 || token.length > 100) return null;
return (
db
.prepare(
`SELECT id, email, name, role, is_active
FROM admin_users
WHERE invite_hash = ? AND invite_expires_at > datetime('now') AND is_active = 1`,
)
.get(sha256(token)) ?? null
);
}
/* The invite as an email, through Gmail (googleService.js). */
export async function emailInvite(db, account, link) {
if (!mailReady()) throw new Error("Gmail isn't set up on the server (docs/google-drive-and-mail.md).");
let site = { title: "Next Generation of Unity" };
try {
site = loadSite();
} catch {
// The default name will do.
}
const hello = account.name ? `Hi ${account.name},` : "Hi,";
await sendMail({
to: account.email,
subject: `Your ${site.title} profile`,
text: [
hello,
"",
`You're invited to make a profile account on the ${site.title} website. Open this link to set a password, or to sign in with Google under this email:`,
"",
link,
"",
`The link works once, for ${INVITE_DAYS} days. Once you're in, you can find your profile on the site, ask to claim it, and choose what of it shows.`,
"",
"If you weren't expecting this, you can ignore it.",
].join("\n"),
});
}

View file

@ -34,6 +34,8 @@ import net from "node:net";
import { MAX_UPLOAD_BYTES, MediaError } from "./media.js";
const TIMEOUT_MS = 8000;
// The whole request, however steadily the bytes trickle in.
const TOTAL_TIMEOUT_MS = 15000;
const MAX_REDIRECTS = 4;
const MAX_HTML_BYTES = 1024 * 1024;
const USER_AGENT = "NGU-LinkPreview/1.0 (+https://nextgenerationofunity.org)";
@ -48,12 +50,13 @@ const USER_AGENT = "NGU-LinkPreview/1.0 (+https://nextgenerationofunity.org)";
const BLOCKED = new net.BlockList();
for (const [ip, bits] of [
["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8],
["169.254.0.0", 16], ["172.16.0.0", 12], ["192.0.0.0", 24], ["192.168.0.0", 16],
["198.18.0.0", 15], ["224.0.0.0", 3],
["169.254.0.0", 16], ["172.16.0.0", 12], ["192.0.0.0", 24], ["192.0.2.0", 24],
["192.168.0.0", 16], ["198.18.0.0", 15], ["198.51.100.0", 24], ["203.0.113.0", 24],
["224.0.0.0", 3],
]) BLOCKED.addSubnet(ip, bits, "ipv4");
for (const [ip, bits] of [
["::", 96], ["::1", 128], ["64:ff9b::", 96], ["64:ff9b:1::", 48], ["2002::", 16],
["fc00::", 7], ["fe80::", 10], ["ff00::", 8],
["fc00::", 7], ["fe80::", 10], ["fec0::", 10], ["ff00::", 8], ["2001:db8::", 32],
]) BLOCKED.addSubnet(ip, bits, "ipv6");
function ipBlocked(ip) {
@ -146,6 +149,14 @@ function requestOnce({ url, address }, { maxBytes, accept, truncate = false }) {
},
);
req.on("timeout", () => req.destroy(new MediaError(504, "The site took too long to answer.")));
// `timeout` above only fires when the socket goes quiet; a server
// sending a byte every few seconds would hold the request open
// for hours. This caps the whole exchange.
const deadline = setTimeout(
() => req.destroy(new MediaError(504, "The site took too long to answer.")),
TOTAL_TIMEOUT_MS,
);
req.on("close", () => clearTimeout(deadline));
req.on("error", (err) =>
reject(err instanceof MediaError ? err : new MediaError(400, "That site couldn't be reached.")),
);
@ -169,15 +180,82 @@ export async function safeGet(raw, options) {
const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
// A code point past U+10FFFF would make fromCodePoint throw.
const codePoint = (n) => String.fromCodePoint(n <= 0x10ffff ? n : 0xfffd);
export function decodeEntities(text) {
return text
.replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCodePoint(parseInt(hex, 16)))
.replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(Number(dec)))
.replace(/&#x([0-9a-f]{1,6});/gi, (_, hex) => codePoint(parseInt(hex, 16)))
.replace(/&#(\d{1,7});/g, (_, dec) => codePoint(Number(dec)))
.replace(/&([a-z]+);/gi, (whole, name) => ENTITIES[name.toLowerCase()] ?? whole)
.replace(/\s+/g, " ")
.trim();
}
/* ── Scanning markup ───────────────────────────────────────────
Pages and feeds come from other people's servers, so nothing here
runs a regex over the whole document: a pattern like
/<meta[^>]*>/ restarts at every "<meta" and turns a few hundred KB
of unclosed tags into seconds of blocked event loop. These walk
the text once with indexOf; the regexes left only ever see one tag
or one short run of text.
───────────────────────────────────────────────────────────── */
const TAG_END = new Set([">", "/", " ", "\t", "\n", "\r"]);
/* Where the next <tag (followed by a space, / or >) starts, or -1. */
function tagStart(lower, name, from) {
for (let i = from; ; ) {
const at = lower.indexOf(name, i);
if (at === -1 || TAG_END.has(lower[at + name.length] ?? "")) return at;
i = at + name.length;
}
}
/* Each opening <tag ...> in text, up to `limit` of them. */
export function openTags(text, tag, limit = 200) {
const lower = text.toLowerCase();
const name = `<${tag.toLowerCase()}`;
const out = [];
for (let i = 0; out.length < limit; ) {
const start = tagStart(lower, name, i);
if (start === -1) break;
const end = lower.indexOf(">", start);
if (end === -1) break;
out.push(text.slice(start, end + 1));
i = end + 1;
}
return out;
}
/* Each whole <tag ...>…</tag> in text, up to `limit` of them. */
export function elements(text, tag, limit) {
const lower = text.toLowerCase();
const name = `<${tag.toLowerCase()}`;
const close = `</${tag.toLowerCase()}>`;
const out = [];
for (let i = 0; out.length < limit; ) {
const start = tagStart(lower, name, i);
if (start === -1) break;
const end = lower.indexOf(close, start);
if (end === -1) break;
out.push(text.slice(start, end + close.length));
i = end + close.length;
}
return out;
}
/* What's between the first <tag ...> and its </tag>, or null. */
export function innerOf(text, tag) {
const lower = text.toLowerCase();
const start = tagStart(lower, `<${tag.toLowerCase()}`, 0);
if (start === -1) return null;
const open = lower.indexOf(">", start);
if (open === -1) return null;
const end = lower.indexOf(`</${tag.toLowerCase()}>`, open);
return end === -1 ? null : text.slice(open + 1, end);
}
function attr(tag, name) {
const match = tag.match(new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i"));
return match ? (match[1] ?? match[2] ?? match[3] ?? "") : null;
@ -185,12 +263,12 @@ function attr(tag, name) {
function readMeta(html) {
const meta = {};
for (const tag of html.match(/<meta\b[^>]*>/gi) ?? []) {
for (const tag of openTags(html, "meta")) {
const key = (attr(tag, "property") ?? attr(tag, "name") ?? "").toLowerCase();
const content = attr(tag, "content");
if (key && content != null && !(key in meta)) meta[key] = decodeEntities(content);
if (key && content != null && !(key in meta)) meta[key] = decodeEntities(content.slice(0, 2000));
}
const title = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1];
const title = innerOf(html, "title")?.slice(0, 1000);
return {
title: meta["og:title"] || meta["twitter:title"] || (title ? decodeEntities(title) : null) || null,
description:

View file

@ -15,8 +15,9 @@
── What ──
The type is read from the file's first bytes, never from its
name or the browser's Content-Type, both of which the uploader
controls. JPEG, PNG, GIF, WebP and SVG are accepted; anything
else is refused.
controls. JPEG, PNG, GIF, WebP and SVG are accepted, and WebVTT
captions (a text file starting "WEBVTT"); anything else is
refused.
── Processing ──
By default a raster image is turned upright (EXIF orientation),
@ -24,11 +25,23 @@
which also drops its metadata, camera location included.
`keepOriginal` stores the bytes exactly as uploaded instead,
under the tighter KEEP_MAX_BYTES. An SVG is always kept as it
is: it's already small, and rasterising it would lose the point
of it.
is: it's already small, and rasterizing it would lose the point
of it. So is a WebVTT file, always into captions/.
Names are random, so two uploads of "logo.png" can't collide
and a filename says nothing about what's in it.
A stored name is made from the name it's given (the Name box on
every upload and save), plus a short random ending, so two
uploads called "Logo" can't collide: 'images/logo-3f9c1a.webp'.
The ending also means no name can end in -640, the small copies'
mark. Renaming (renameStored) makes a new stored name and moves
the file, its small copy and every record naming it to it.
── Folders ──
Each upload goes in a folder by what it's for (FOLDERS): logos/
for logo and icon fields, thumbnails/ for pictures the site saves
by itself (link previews, Drive files' first pages), captions/
for videos' WebVTT files, images/ for the rest. A stored name includes it: 'logos/3f9c….webp', served at
/uploads/logos/3f9c….webp. The small copy sits beside it. Clips
keep a bare name in the root.
── Files copied in by hand ──
A file put straight into UPLOADS_DIR has no media row, so the
@ -41,6 +54,7 @@
═══════════════════════════════════════════════════════════════ */
import { randomBytes } from "node:crypto";
import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
@ -56,6 +70,73 @@ const MB = 1024 * 1024;
/* The largest file accepted at all, before processing: room for a
full-size phone photo. */
/* Where an upload goes, by what it's for (see Folders above). */
export const FOLDERS = ["logos", "images", "thumbnails", "captions"];
export const folderOf = (value) => (FOLDERS.includes(value) ? value : "images");
/* A name this library stores: a bare name in the root, or one inside
a FOLDER. Anything else (a path out, a dotfile) is refused wherever
a name is joined onto UPLOADS_DIR. */
export function isStoredName(name) {
const parts = String(name ?? "").split("/");
const base = parts[parts.length - 1];
if (!base || base.startsWith(".") || path.basename(base) !== base) return false;
return parts.length === 1 || (parts.length === 2 && FOLDERS.includes(parts[0]));
}
/* A name as the readable part of a stored name: lowercase letters,
digits and hyphens, accents dropped, at most 60 characters.
Nothing usable (eg. only emoji) gives `fallback`. */
export function slugify(name, fallback = "file") {
const slug = String(name ?? "")
.normalize("NFKD")
.replace(/[̀-ͯ]/g, "")
.toLowerCase()
.replace(/\.[a-z0-9]{2,4}$/, "") // a typed "photo.jpg" keeps its own ending off
.replace(/[^a-z0-9]+/g, "-")
.slice(0, 60)
.replace(/^-+|-+$/g, "");
return slug || fallback;
}
/* A new stored name in `dir` ('' for the root) for something called
`name`, ending in `ext` ('.webp'), that no file has yet: writing
over one would lose it, and a failed save would then delete it. */
export async function storedNameFor(name, ext, dir = "") {
for (let tries = 0; tries < 8; tries++) {
const filename = `${dir ? `${dir}/` : ""}${slugify(name)}-${randomBytes(3).toString("hex")}${ext}`;
try {
await stat(path.join(UPLOADS_DIR, filename));
} catch (err) {
if (err.code === "ENOENT") return filename;
throw err;
}
}
throw new MediaError(500, "Couldn't find a free file name. Try again.");
}
/* The public path of a stored name, each part escaped. */
export const publicPath = (filename) =>
`${PUBLIC_PREFIX}${String(filename).split("/").map(encodeURIComponent).join("/")}`;
/* Every stored file's name: the root's, then each folder's. */
async function listStored() {
const names = [];
for (const dir of ["", ...FOLDERS]) {
let entries;
try {
entries = await readdir(path.join(UPLOADS_DIR, dir), { withFileTypes: true });
} catch (err) {
if (err.code === "ENOENT") continue;
throw err;
}
for (const entry of entries) {
if (entry.isFile() && !entry.name.startsWith(".")) names.push(dir ? `${dir}/${entry.name}` : entry.name);
}
}
return names;
}
export const MAX_UPLOAD_BYTES = 25 * MB;
/* The largest file kept as uploaded, unprocessed. */
@ -63,6 +144,10 @@ export const KEEP_MAX_BYTES = 10 * MB;
/* Longest side after processing, in pixels. Wide enough for a
full-bleed hero on a large screen. */
// About 60 megapixels (eg. 9000 x 6700): past any camera an editor
// uses, and it stops one giant image eating the VPS's memory while
// it's decoded. sharp's own default is 268 MP.
const MAX_INPUT_PIXELS = 60_000_000;
const MAX_EDGE = 2400;
const WEBP_QUALITY = 82;
@ -82,8 +167,12 @@ const TYPES = {
gif: { mime: "image/gif", ext: ".gif" },
webp: { mime: "image/webp", ext: ".webp" },
svg: { mime: "image/svg+xml", ext: ".svg" },
vtt: { mime: "text/vtt", ext: ".vtt" },
};
/* Kinds stored exactly as uploaded, with no small copy: text, not pixels. */
const AS_IS = new Set(["svg", "vtt"]);
function startsWith(buf, bytes, offset = 0) {
return bytes.every((byte, i) => buf[offset + i] === byte);
}
@ -102,6 +191,7 @@ function sniff(buf) {
if (/^(<\?xml[\s\S]*?\?>\s*)?(<!--[\s\S]*?-->\s*|<!DOCTYPE[^>]*>\s*)*<svg[\s>]/i.test(head)) {
return "svg";
}
if (/^WEBVTT(\s|$)/.test(head)) return "vtt";
return null;
}
@ -112,7 +202,7 @@ function sniff(buf) {
and leave nothing behind.
───────────────────────────────────────────────────────────── */
export async function store(buf, { keepOriginal = false } = {}) {
export async function store(buf, { keepOriginal = false, folder, name } = {}) {
if (buf.length === 0) throw new MediaError(400, "The file is empty.");
if (buf.length > MAX_UPLOAD_BYTES) {
throw new MediaError(413, `Files can be at most ${MAX_UPLOAD_BYTES / MB} MB.`);
@ -120,10 +210,10 @@ export async function store(buf, { keepOriginal = false } = {}) {
const kind = sniff(buf);
if (!kind) {
throw new MediaError(415, "Only JPEG, PNG, GIF, WebP and SVG images can be uploaded.");
throw new MediaError(415, "Only JPEG, PNG, GIF, WebP and SVG images, and WebVTT (.vtt) captions, can be uploaded.");
}
const convert = kind !== "svg" && !keepOriginal;
const convert = !AS_IS.has(kind) && !keepOriginal;
if (!convert && buf.length > KEEP_MAX_BYTES) {
throw new MediaError(
@ -141,7 +231,7 @@ export async function store(buf, { keepOriginal = false } = {}) {
try {
if (convert) {
// animated keeps every frame of a GIF or an animated WebP.
const { data, info } = await sharp(buf, { animated: true })
const { data, info } = await sharp(buf, { animated: true, limitInputPixels: MAX_INPUT_PIXELS })
.rotate()
.resize({ width: MAX_EDGE, height: MAX_EDGE, fit: "inside", withoutEnlargement: true })
.webp({ quality: WEBP_QUALITY })
@ -151,8 +241,8 @@ export async function store(buf, { keepOriginal = false } = {}) {
width = info.width;
// An animated image reports the whole strip's height.
height = info.pageHeight ?? info.height;
} else if (kind !== "svg") {
const meta = await sharp(buf).metadata();
} else if (!AS_IS.has(kind)) {
const meta = await sharp(buf, { limitInputPixels: MAX_INPUT_PIXELS }).metadata();
width = meta.width ?? null;
height = meta.pageHeight ?? meta.height ?? null;
}
@ -160,14 +250,16 @@ export async function store(buf, { keepOriginal = false } = {}) {
throw new MediaError(415, "That image couldn't be read. It may be damaged.");
}
const filename = `${randomBytes(12).toString("hex")}${type.ext}`;
await mkdir(UPLOADS_DIR, { recursive: true });
const dir = kind === "vtt" ? "captions" : folderOf(folder);
await mkdir(path.join(UPLOADS_DIR, dir), { recursive: true });
const filename = await storedNameFor(name, type.ext, dir);
const base = path.basename(filename);
// Written under a temporary name and renamed, so a half-written
// file is never served under its real one.
const tmp = path.join(UPLOADS_DIR, `.${filename}.tmp`);
const tmp = path.join(UPLOADS_DIR, dir, `.${base}.tmp`);
await writeFile(tmp, out);
await rename(tmp, path.join(UPLOADS_DIR, filename));
if (!AS_IS.has(kind)) await writeThumb(filename, out);
return {
filename,
@ -179,16 +271,106 @@ export async function store(buf, { keepOriginal = false } = {}) {
};
}
/* Deletes one stored file. A file that's already gone is not an
error: the row is what's being removed. */
/* ── Small copies ──────────────────────────────────────────────
Beside every raster upload, <name>-640.webp: the same image at most
640px on its longer side. Photos and logos shown small (avatars,
cards, marks) load it instead of the full file; the page falls back
to the full file if it's missing (src/lib/media.ts, mediaThumb).
Made when a file is uploaded, and at boot for any upload that
doesn't have one yet (files from before this, or copied in by hand).
───────────────────────────────────────────────────────────── */
export const THUMB_EDGE = 640;
const THUMB = /-640\.webp$/;
export const thumbName = (filename) => `${filename.replace(/\.[^.]+$/, "")}-640.webp`;
async function writeThumb(filename, buf) {
const name = thumbName(filename);
const tmp = path.join(UPLOADS_DIR, path.dirname(name), `.${path.basename(name)}.tmp`);
try {
await sharp(buf, { animated: true, limitInputPixels: MAX_INPUT_PIXELS })
.rotate()
.resize({ width: THUMB_EDGE, height: THUMB_EDGE, fit: "inside", withoutEnlargement: true })
.webp({ quality: WEBP_QUALITY })
.toFile(tmp);
await rename(tmp, path.join(UPLOADS_DIR, name));
} catch (err) {
// The full file is what matters; without a copy the page uses it.
await unlink(tmp).catch(() => {});
console.warn(`media: no small copy of ${filename}: ${err.message}`);
}
}
/* Makes the small copy for every raster upload that lacks one.
Returns how many it made. */
export async function writeMissingThumbs() {
const names = await listStored();
const present = new Set(names);
let made = 0;
for (const name of names) {
if (THUMB.test(name) || /\.(svg|vtt)$/i.test(name)) continue;
if (present.has(thumbName(name))) continue;
const buf = await readFile(path.join(UPLOADS_DIR, name)).catch(() => null);
if (!buf || !sniff(buf) || AS_IS.has(sniff(buf))) continue;
await writeThumb(name, buf);
made += 1;
}
return made;
}
/* Deletes one stored file and its small copy. A file that's already
gone is not an error: the row is what's being removed. */
export async function remove(filename) {
// filename comes from our own table, but it's joined onto a
// directory, so refuse anything that isn't a bare name.
if (path.basename(filename) !== filename) return;
// directory, so refuse anything that isn't a stored name.
if (!isStoredName(filename)) return;
for (const name of [filename, thumbName(filename)]) {
try {
await unlink(path.join(UPLOADS_DIR, name));
} catch (err) {
if (err.code !== "ENOENT") throw err;
}
}
}
/* ── Renaming ──────────────────────────────────────────────────
Moves a stored file (and its small copy) to a new name made
from `name`, keeping its folder and ending, and returns the new
stored name. `commit(newName)` writes the database's side (the
media row and every record naming the file) and must be
synchronous, so it runs in one transaction; if it throws, the
files go back where they were.
───────────────────────────────────────────────────────────── */
export async function renameStored(filename, name, commit) {
if (!isStoredName(filename)) throw new MediaError(400, "That file can't be renamed.");
const dir = filename.includes("/") ? filename.split("/")[0] : "";
const ext = path.extname(filename).toLowerCase();
const next = await storedNameFor(name, ext, dir);
const moves = [[filename, next]];
const thumb = thumbName(filename);
if (!THUMB.test(filename) && (await stat(path.join(UPLOADS_DIR, thumb)).catch(() => null))) {
moves.push([thumb, thumbName(next)]);
}
const done = [];
try {
await unlink(path.join(UPLOADS_DIR, filename));
for (const [from, to] of moves) {
await rename(path.join(UPLOADS_DIR, from), path.join(UPLOADS_DIR, to));
done.push([from, to]);
}
commit(next);
return next;
} catch (err) {
if (err.code !== "ENOENT") throw err;
for (const [from, to] of done.reverse()) {
await rename(path.join(UPLOADS_DIR, to), path.join(UPLOADS_DIR, from)).catch((undo) =>
console.error(`media: couldn't move ${to} back to ${from}: ${undo.message}`),
);
}
if (err.code === "ENOENT") throw new MediaError(404, "The file is missing from the uploads folder.");
throw err;
}
}
@ -207,9 +389,9 @@ async function describe(filename) {
let width = null;
let height = null;
if (kind !== "svg") {
if (!AS_IS.has(kind)) {
try {
const meta = await sharp(buf).metadata();
const meta = await sharp(buf, { limitInputPixels: MAX_INPUT_PIXELS }).metadata();
width = meta.width ?? null;
height = meta.pageHeight ?? meta.height ?? null;
} catch {
@ -231,13 +413,7 @@ async function describe(filename) {
how many it added. Safe to run often: it only reads the folder
and the table, and inserts nothing twice (filename is UNIQUE). */
export async function registerLooseFiles(db) {
let names;
try {
names = await readdir(UPLOADS_DIR);
} catch (err) {
if (err.code === "ENOENT") return 0;
throw err;
}
const names = await listStored();
const known = new Set(db.prepare(`SELECT filename FROM media`).all().map((row) => row.filename));
const insert = db.prepare(
@ -248,7 +424,7 @@ export async function registerLooseFiles(db) {
let added = 0;
for (const name of names) {
if (known.has(name) || name.startsWith(".") || path.basename(name) !== name) continue;
if (known.has(name) || THUMB.test(name) || !isStoredName(name)) continue;
let row;
try {
row = await describe(name);
@ -258,7 +434,7 @@ export async function registerLooseFiles(db) {
if (!row) continue;
const result = insert.run(
row.filename,
row.filename,
path.basename(row.filename),
row.content_type,
row.bytes,
row.width,
@ -270,3 +446,9 @@ export async function registerLooseFiles(db) {
if (added) console.log(`media: registered ${added} file(s) found in ${UPLOADS_DIR}`);
return added;
}
/* ── Into folders, once ───────────────────────────────────────── */
// Columns that hold a logo or a site icon: an image one of these
// names goes in logos/.

View file

@ -1,79 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 024 FRONT PAGE: FEATURED VIDEO
--
-- A fourth hero mode, 'video': a recorded video beside the words,
-- the way 'livestream' puts a stream there, but without the LIVE
-- badge and without autoplay: a visitor presses play.
--
-- Its own two columns rather than reusing the livestream's, so a
-- featured video and a stream can both be set up ahead of time and
-- the mode switches between them, as photos and livestream already
-- can.
--
-- video_url a YouTube, Vimeo or Facebook link (turned into an
-- embed), or a video file: a filename in
-- public/front-page/, a /path, or an https URL ending
-- in .mp4, .webm, .m4v, .mov or .ogv, which plays in
-- the browser's own player
-- video_title shown after "Featured video" above the headline
--
-- hero_mode's CHECK can't be altered in place, so front_page is
-- rebuilt. Its children (slides, sections, stats, paths) reference
-- it by name; the runner has foreign keys off, so the DROP leaves
-- them alone and the rename puts front_page back underneath them.
-- No view or other table's trigger names front_page, so the rename
-- needs no legacy_alter_table. front_page_touch goes with the old
-- table and is recreated last.
--
-- PRAGMA user_version; -- reads 23 before this file
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE front_page_new (
id TEXT PRIMARY KEY CHECK (id = 'home'),
hero_mode TEXT NOT NULL DEFAULT 'brand'
CHECK (hero_mode IN ('brand', 'photos', 'livestream', 'video')),
eyebrow TEXT,
headline TEXT NOT NULL DEFAULT 'Next Generation of Unity',
subhead TEXT,
primary_label TEXT,
primary_url TEXT,
secondary_label TEXT,
secondary_url TEXT,
slide_seconds INTEGER NOT NULL DEFAULT 7
CHECK (slide_seconds BETWEEN 3 AND 60),
livestream_url TEXT,
livestream_title TEXT,
video_url TEXT,
video_title TEXT,
countdown_event_id TEXT REFERENCES events (id) ON DELETE SET NULL,
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
INSERT INTO front_page_new
(id, hero_mode, eyebrow, headline, subhead,
primary_label, primary_url, secondary_label, secondary_url,
slide_seconds, livestream_url, livestream_title,
countdown_event_id, updated_at)
SELECT
id, hero_mode, eyebrow, headline, subhead,
primary_label, primary_url, secondary_label, secondary_url,
slide_seconds, livestream_url, livestream_title,
countdown_event_id, updated_at
FROM front_page;
DROP TABLE front_page;
ALTER TABLE front_page_new RENAME TO front_page;
CREATE TRIGGER front_page_touch
AFTER UPDATE ON front_page
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE front_page SET updated_at = datetime('now') WHERE id = new.id;
END;

View file

@ -1,40 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 025 HERO: BACKDROP AND FEATURE ARE SEPARATE CHOICES
--
-- hero_mode answered two questions with one value: what fills the
-- background (the brand animation or the photo slideshow) and what
-- sits beside the words (nothing, a livestream or a featured
-- video). A stream or a video could only ever sit on the brand
-- backdrop. Split, any backdrop goes with any feature.
--
-- hero_backdrop 'brand' | 'photos'
-- hero_feature 'none' | 'livestream' | 'video'
--
-- Today's modes map across exactly: photos → photos + none;
-- livestream and video → brand + that feature; brand → brand +
-- none. Photos mode still falls back to brand on the page when
-- there are no photos, as before.
--
-- ADD COLUMN takes a constant DEFAULT and a CHECK, and DROP COLUMN
-- allows a column whose only constraint is its own CHECK, so no
-- rebuild: front_page's children and its touch trigger are never
-- touched.
--
-- PRAGMA user_version; -- reads 24 before this file
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE front_page ADD COLUMN hero_backdrop TEXT NOT NULL DEFAULT 'brand'
CHECK (hero_backdrop IN ('brand', 'photos'));
ALTER TABLE front_page ADD COLUMN hero_feature TEXT NOT NULL DEFAULT 'none'
CHECK (hero_feature IN ('none', 'livestream', 'video'));
UPDATE front_page
SET hero_backdrop = CASE hero_mode WHEN 'photos' THEN 'photos' ELSE 'brand' END,
hero_feature = CASE hero_mode
WHEN 'livestream' THEN 'livestream'
WHEN 'video' THEN 'video'
ELSE 'none'
END;
ALTER TABLE front_page DROP COLUMN hero_mode;

View file

@ -1,29 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 026 COUNTDOWN: FILTER BY SCOPE AND TYPE
--
-- The countdown counts to the pinned event, or else to the next
-- published event that hasn't ended. These two narrow "the next
-- event": National + Retreat counts down to the next national
-- retreat and skips a regional class that happens sooner. Either or
-- both can be left null, meaning any. A pinned event still wins
-- whatever they say; the admin chose it by name.
--
-- countdown_scope_id an event_scopes id. A real foreign key,
-- so it can't name a scope that doesn't
-- exist; ON DELETE SET NULL puts it back to
-- "any" if a scope is ever removed.
-- countdown_event_type the same values as events.event_type.
-- Adding an event type now means widening
-- this CHECK too.
--
-- Plain ADD COLUMN: a REFERENCES column is allowed when its default
-- is NULL, and a CHECK is allowed on any. No rebuild.
--
-- PRAGMA user_version; -- reads 25 before this file
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE front_page ADD COLUMN countdown_scope_id TEXT
REFERENCES event_scopes (id) ON DELETE SET NULL;
ALTER TABLE front_page ADD COLUMN countdown_event_type TEXT
CHECK (countdown_event_type IN ('retreat', 'class', 'workshop', 'meeting', 'other'));

View file

@ -1,43 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 027 LISTED: PUBLISHED BUT ONLY BY LINK
--
-- is_published stays the hard gate: 0 is a draft (or, for people,
-- private), off the site entirely and a 404 at its own URL.
-- is_listed only means anything on a published row. 0 keeps the
-- record's own page working but leaves it out of every list the
-- site gathers by itself:
--
-- the /events, /organizations, /teams and /awards lists (and so
-- every band, calendar, map and card grid built on them), a
-- region's chapters, an organization's events, teams and awards,
-- the /directory the QR page reads, and the front page's counts
-- and next-event countdown.
--
-- It still appears wherever someone attached it by hand: rosters,
-- billed people, hosts, award recipients, timeline entries, and a
-- countdown pinned to it by name. Each of those rows has its own
-- is_public (or is_published) to hide it there.
--
-- Defaults to 1, so every existing row stays listed.
--
-- Plain ADD COLUMN: NOT NULL with a constant default and a CHECK is
-- allowed without a rebuild, STRICT tables included. v_events reads
-- e.*, so it picks the column up with no change of its own.
--
-- PRAGMA user_version; -- reads 26 before this file
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE organizations ADD COLUMN is_listed INTEGER NOT NULL DEFAULT 1
CHECK (is_listed IN (0, 1));
ALTER TABLE events ADD COLUMN is_listed INTEGER NOT NULL DEFAULT 1
CHECK (is_listed IN (0, 1));
ALTER TABLE people ADD COLUMN is_listed INTEGER NOT NULL DEFAULT 1
CHECK (is_listed IN (0, 1));
ALTER TABLE teams ADD COLUMN is_listed INTEGER NOT NULL DEFAULT 1
CHECK (is_listed IN (0, 1));
ALTER TABLE awards ADD COLUMN is_listed INTEGER NOT NULL DEFAULT 1
CHECK (is_listed IN (0, 1));

View file

@ -1,41 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 028 MEDIA: UPLOADED IMAGES
--
-- One row per file in UPLOADS_DIR (/var/lib/ngu/uploads in
-- production, outside the deployed app so an rsync can't touch
-- it). nginx serves the directory at /uploads/; the API only
-- writes and deletes.
--
-- An image field stores the file's public path, '/uploads/<file>',
-- not this row's id. That keeps every image column a plain TEXT
-- that also takes a filename in public/ or a full URL, as before,
-- and means media.ts needs no lookup. The cost is no foreign key:
-- deleting a file a record still names leaves that record showing
-- nothing (the <Logo> and <img> fallbacks already handle a missing
-- file), so the Media page warns before a delete.
--
-- filename the stored name: random, so it can't collide or
-- be guessed from the original. '3f9c…e1.webp'
-- original_name what the uploader's file was called, for the
-- library's search and display
-- processed 1 when resized and converted to WebP, 0 when
-- kept as uploaded
-- width, height null for an SVG, which has no pixel size
--
-- PRAGMA user_version; -- reads 27 before this file
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE media (
id INTEGER PRIMARY KEY AUTOINCREMENT,
filename TEXT NOT NULL UNIQUE,
original_name TEXT NOT NULL,
content_type TEXT NOT NULL,
bytes INTEGER NOT NULL CHECK (bytes >= 0),
width INTEGER,
height INTEGER,
processed INTEGER NOT NULL DEFAULT 1 CHECK (processed IN (0, 1)),
uploaded_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
CREATE INDEX media_created_idx ON media (created_at DESC);

View file

@ -1,15 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 029 EVENTS: CARD BACKGROUND IMAGE
--
-- A photo behind an event's card. The card keeps its size and its
-- layout; the image covers it, under a light veil (CARD_IMAGE_VEIL
-- in EventList-Cards.tsx) so the text on top stays readable.
--
-- Like every image column, it holds a path: '/uploads/<file>' from
-- the media library, a bare filename in public/event-backgrounds/,
-- or a full URL. Null draws the card as before.
--
-- PRAGMA user_version; -- reads 28 before this file
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE events ADD COLUMN card_image TEXT;

View file

@ -1,167 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 030 FEATURED CARDS
--
-- A row of cards that point somewhere: the front page's new
-- 'featured' band first, and the Community page's blog posts next.
-- One table for both, owned polymorphically like links and
-- content_blocks, so the card's shape and the code that draws it
-- are written once. owner_kind only allows 'front_page' today;
-- adding an owner is a rebuild of this table, which nothing
-- references, so it's a cheap one.
--
-- A card is one of three kinds:
--
-- record points at an event, organization, person, team or
-- award. Title, image and link come from that record at
-- read time, so renaming the event renames the card.
-- Any of title, blurb and image filled in here overrides.
-- link any URL, on the site or off it. Title and image are
-- the card's own (the editor can fetch them from the
-- page's preview tags).
-- video a YouTube, Vimeo or Facebook link, or a video file.
-- Drawn as a thumbnail that swaps in the player when
-- pressed. image overrides the thumbnail.
--
-- ref_kind + ref_id is checked by the triggers below, the same way
-- timeline_entries' is, and a deleted record takes its cards with
-- it. An unpublished record's card is left out when read.
--
-- Also: 'featured' joins front_page_sections.section. A CHECK can't
-- be altered in place, so that table is rebuilt. No view or trigger
-- names it, and nothing references it.
--
-- PRAGMA user_version; -- reads 29 before this file
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE front_page_sections_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id TEXT NOT NULL REFERENCES front_page (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
section TEXT NOT NULL
CHECK (section IN ('countdown', 'retreats', 'calendar', 'stats',
'timeline', 'connect', 'featured')),
title TEXT,
blurb TEXT,
is_hidden INTEGER NOT NULL DEFAULT 0 CHECK (is_hidden IN (0, 1)),
UNIQUE (page_id, section)
) STRICT;
INSERT INTO front_page_sections_new (id, page_id, sort_order, section, title, blurb, is_hidden)
SELECT id, page_id, sort_order, section, title, blurb, is_hidden
FROM front_page_sections;
DROP TABLE front_page_sections;
ALTER TABLE front_page_sections_new RENAME TO front_page_sections;
CREATE TABLE featured_cards (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_kind TEXT NOT NULL CHECK (owner_kind IN ('front_page')),
owner_id TEXT NOT NULL,
sort_order INTEGER NOT NULL DEFAULT 0,
kind TEXT NOT NULL DEFAULT 'link'
CHECK (kind IN ('record', 'link', 'video')),
ref_kind TEXT CHECK (ref_kind IN ('event', 'organization', 'person', 'team', 'award')),
ref_id TEXT,
url TEXT,
eyebrow TEXT, -- 'Article', 'Watch'
title TEXT,
blurb TEXT,
image TEXT, -- '/uploads/…', a filename, or a URL
CHECK ((ref_kind IS NULL) = (ref_id IS NULL)),
-- A record card needs its record; the other two need somewhere to
-- go. Named as sentences: the admin shows a sentence-shaped
-- constraint name as the error (wrapDbErrors in admin-crud.js).
CONSTRAINT "A record card needs a record to point at."
CHECK (kind != 'record' OR ref_kind IS NOT NULL),
CONSTRAINT "A link or video card needs a URL."
CHECK (kind = 'record' OR url IS NOT NULL)
) STRICT;
CREATE INDEX featured_cards_owner_idx ON featured_cards (owner_kind, owner_id, sort_order);
-- ── Triggers last (see CLAUDE.md, Migrations) ──
CREATE TRIGGER featured_cards_ref_exists
BEFORE INSERT ON featured_cards
BEGIN
SELECT CASE
WHEN new.ref_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such event')
WHEN new.ref_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such organization')
WHEN new.ref_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such person')
WHEN new.ref_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such team')
WHEN new.ref_kind = 'award'
AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such award')
END;
END;
CREATE TRIGGER featured_cards_ref_exists_update
BEFORE UPDATE OF ref_kind, ref_id ON featured_cards
BEGIN
SELECT CASE
WHEN new.ref_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such event')
WHEN new.ref_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such organization')
WHEN new.ref_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such person')
WHEN new.ref_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such team')
WHEN new.ref_kind = 'award'
AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such award')
END;
END;
-- A deleted record takes the cards that point at it. Separate
-- triggers rather than additions to the existing *_cleanup ones, so
-- this file doesn't have to drop and restate those.
CREATE TRIGGER events_featured_cleanup
AFTER DELETE ON events
BEGIN
DELETE FROM featured_cards WHERE ref_kind = 'event' AND ref_id = old.id;
END;
CREATE TRIGGER organizations_featured_cleanup
AFTER DELETE ON organizations
BEGIN
DELETE FROM featured_cards WHERE ref_kind = 'organization' AND ref_id = old.id;
END;
CREATE TRIGGER people_featured_cleanup
AFTER DELETE ON people
BEGIN
DELETE FROM featured_cards WHERE ref_kind = 'person' AND ref_id = old.id;
END;
CREATE TRIGGER teams_featured_cleanup
AFTER DELETE ON teams
BEGIN
DELETE FROM featured_cards WHERE ref_kind = 'team' AND ref_id = old.id;
END;
CREATE TRIGGER awards_featured_cleanup
AFTER DELETE ON awards
BEGIN
DELETE FROM featured_cards WHERE ref_kind = 'award' AND ref_id = old.id;
END;

View file

@ -1,254 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 031 BLOG
--
-- Posts of our own, at /blog/<id>, and the Community page's blog
-- section, which shows two subsections:
--
-- Our posts pinned blog_posts first, then the newest
-- published, listed ones, up to internal_slots
-- Community posts pinned featured_cards (owner 'community_page')
-- first, then the newest items from the RSS or
-- Atom feeds in community_page_feeds, up to
-- external_slots
--
-- blog_posts
-- A draft until published (is_published defaults to 0, as for
-- people): a half-written post shouldn't go live by accident.
-- is_listed works as it does everywhere (027): unticked, the post
-- is left out of "newest" but its page works and it can be pinned.
-- The body is content_blocks with owner_kind 'blog_post', slot
-- 'body'. Authors are people (blog_post_authors), or a guest named
-- on the post itself, or both. tags is a comma-separated list, eg.
-- 'Reflection, Event recap'; it is only displayed, never joined on.
--
-- content_blocks gains 'blog_post' as an owner. A CHECK can't be
-- altered in place, so the table is rebuilt; the *_cleanup triggers
-- on other tables name it, hence legacy_alter_table around the
-- rename. Its own index and owner trigger are recreated below.
--
-- featured_cards gains 'community_page' as an owner, the same way.
-- Nothing names it but its own triggers, recreated below.
--
-- community_page is a singleton like front_page: one row, made
-- here, which the admin edits and can't delete.
--
-- PRAGMA user_version; -- reads 30 before this file
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE blog_posts (
id TEXT PRIMARY KEY, -- slug: 'finding-unity-at-camp'
title TEXT NOT NULL,
excerpt TEXT, -- the card's text; else the body's start
cover_image TEXT, -- '/uploads/…', a filename, or a URL
published_on TEXT, -- 'YYYY-MM-DD'; newest first
tags TEXT, -- 'Reflection, Event recap'
guest_author TEXT, -- someone with no people row
guest_photo TEXT,
is_published INTEGER NOT NULL DEFAULT 0 CHECK (is_published IN (0, 1)),
is_listed INTEGER NOT NULL DEFAULT 1 CHECK (is_listed IN (0, 1)),
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
CREATE INDEX blog_posts_newest_idx ON blog_posts (is_published, is_listed, published_on DESC);
CREATE TABLE blog_post_authors (
post_id TEXT NOT NULL REFERENCES blog_posts (id) ON DELETE CASCADE,
person_id TEXT NOT NULL REFERENCES people (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (post_id, person_id)
) STRICT;
CREATE INDEX blog_post_authors_person_idx ON blog_post_authors (person_id);
CREATE TABLE community_page (
id TEXT PRIMARY KEY CHECK (id = 'community'),
blog_title TEXT, -- null → 'Community Blog'
blog_blurb TEXT,
internal_title TEXT, -- null → 'From NGU'
internal_slots INTEGER NOT NULL DEFAULT 3 CHECK (internal_slots BETWEEN 0 AND 12),
external_title TEXT, -- null → 'From our community'
external_slots INTEGER NOT NULL DEFAULT 3 CHECK (external_slots BETWEEN 0 AND 12),
external_url TEXT, -- the Substack home, for its button
external_label TEXT, -- null → 'Read more on Substack'
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
INSERT INTO community_page (id) VALUES ('community');
CREATE TABLE community_page_pinned_posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id TEXT NOT NULL REFERENCES community_page (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
post_id TEXT NOT NULL REFERENCES blog_posts (id) ON DELETE CASCADE,
UNIQUE (page_id, post_id)
) STRICT;
CREATE TABLE community_page_feeds (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id TEXT NOT NULL REFERENCES community_page (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
url TEXT NOT NULL, -- 'https://ngu.substack.com/feed'
label TEXT -- shown on its items; else the feed's own title
) STRICT;
-- ── content_blocks: add 'blog_post' ───────────────────────────
CREATE TABLE content_blocks_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_kind TEXT NOT NULL
CHECK (owner_kind IN ('organization', 'event', 'person', 'team', 'blog_post')),
owner_id TEXT NOT NULL,
slot TEXT NOT NULL DEFAULT 'body' CHECK (slot IN ('card', 'body')),
sort_order INTEGER NOT NULL DEFAULT 0,
type TEXT NOT NULL
CHECK (type IN ('heading', 'subheading', 'paragraph',
'list', 'links', 'quote', 'image', 'divider')),
text TEXT,
media TEXT,
href TEXT
) STRICT;
INSERT INTO content_blocks_new (id, owner_kind, owner_id, slot, sort_order, type, text, media, href)
SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href
FROM content_blocks;
PRAGMA legacy_alter_table = ON;
DROP TABLE content_blocks;
ALTER TABLE content_blocks_new RENAME TO content_blocks;
PRAGMA legacy_alter_table = OFF;
CREATE INDEX content_blocks_owner_idx
ON content_blocks (owner_kind, owner_id, slot, sort_order);
-- ── featured_cards: add 'community_page' ──────────────────────
CREATE TABLE featured_cards_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_kind TEXT NOT NULL CHECK (owner_kind IN ('front_page', 'community_page')),
owner_id TEXT NOT NULL,
sort_order INTEGER NOT NULL DEFAULT 0,
kind TEXT NOT NULL DEFAULT 'link'
CHECK (kind IN ('record', 'link', 'video')),
ref_kind TEXT CHECK (ref_kind IN ('event', 'organization', 'person', 'team', 'award')),
ref_id TEXT,
url TEXT,
eyebrow TEXT,
title TEXT,
blurb TEXT,
image TEXT,
CHECK ((ref_kind IS NULL) = (ref_id IS NULL)),
CONSTRAINT "A record card needs a record to point at."
CHECK (kind != 'record' OR ref_kind IS NOT NULL),
CONSTRAINT "A link or video card needs a URL."
CHECK (kind = 'record' OR url IS NOT NULL)
) STRICT;
INSERT INTO featured_cards_new
(id, owner_kind, owner_id, sort_order, kind, ref_kind, ref_id, url, eyebrow, title, blurb, image)
SELECT id, owner_kind, owner_id, sort_order, kind, ref_kind, ref_id, url, eyebrow, title, blurb, image
FROM featured_cards;
PRAGMA legacy_alter_table = ON;
DROP TABLE featured_cards;
ALTER TABLE featured_cards_new RENAME TO featured_cards;
PRAGMA legacy_alter_table = OFF;
CREATE INDEX featured_cards_owner_idx ON featured_cards (owner_kind, owner_id, sort_order);
-- ── Triggers last (see CLAUDE.md, Migrations) ──
CREATE TRIGGER content_blocks_owner_exists
BEFORE INSERT ON content_blocks
BEGIN
SELECT CASE
WHEN new.owner_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such event')
WHEN new.owner_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such organization')
WHEN new.owner_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such person')
WHEN new.owner_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such team')
WHEN new.owner_kind = 'blog_post'
AND NOT EXISTS (SELECT 1 FROM blog_posts WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such blog post')
END;
END;
CREATE TRIGGER featured_cards_ref_exists
BEFORE INSERT ON featured_cards
BEGIN
SELECT CASE
WHEN new.ref_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such event')
WHEN new.ref_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such organization')
WHEN new.ref_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such person')
WHEN new.ref_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such team')
WHEN new.ref_kind = 'award'
AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such award')
END;
END;
CREATE TRIGGER featured_cards_ref_exists_update
BEFORE UPDATE OF ref_kind, ref_id ON featured_cards
BEGIN
SELECT CASE
WHEN new.ref_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such event')
WHEN new.ref_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such organization')
WHEN new.ref_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such person')
WHEN new.ref_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such team')
WHEN new.ref_kind = 'award'
AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such award')
END;
END;
CREATE TRIGGER blog_posts_cleanup
AFTER DELETE ON blog_posts
BEGIN
DELETE FROM content_blocks WHERE owner_kind = 'blog_post' AND owner_id = old.id;
END;
CREATE TRIGGER blog_posts_touch
AFTER UPDATE ON blog_posts
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE blog_posts SET updated_at = datetime('now') WHERE id = new.id;
END;
CREATE TRIGGER community_page_touch
AFTER UPDATE ON community_page
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE community_page SET updated_at = datetime('now') WHERE id = new.id;
END;

View file

@ -1,34 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 033 HERO: A FEATURED EVENT
--
-- A fourth hero feature, 'event': an event's card beside the
-- headline, over whichever backdrop is chosen.
--
-- hero_event_id the event to feature. Null means the event the
-- countdown shows (its pin, or the next one that
-- hasn't ended, narrowed by its scope and type),
-- so the hero and the countdown can't disagree.
-- A pinned event that is over, unpublished or
-- deleted falls back the same way; ON DELETE SET
-- NULL does the last one.
--
-- hero_feature's CHECK gains 'event'. A CHECK can't be altered in
-- place, so the column is replaced the way 025 did it: a new column
-- with the new CHECK, the values copied across, the old one dropped
-- and the new one renamed into its place. Nothing else names the
-- column, so front_page itself needn't be rebuilt.
--
-- PRAGMA user_version; -- reads 32 before this file
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE front_page ADD COLUMN hero_feature_new TEXT NOT NULL DEFAULT 'none'
CHECK (hero_feature_new IN ('none', 'livestream', 'video', 'event'));
UPDATE front_page SET hero_feature_new = hero_feature;
ALTER TABLE front_page DROP COLUMN hero_feature;
ALTER TABLE front_page RENAME COLUMN hero_feature_new TO hero_feature;
ALTER TABLE front_page ADD COLUMN hero_event_id TEXT
REFERENCES events (id) ON DELETE SET NULL;

View file

@ -1,62 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 035 SITE SETTINGS
--
-- What the site says about itself, editable in the admin (Panel →
-- Site settings, superadmins only) instead of only in site.json.
-- Every column is an override: null means "whatever site.json
-- says", so a fresh database behaves exactly as before and the
-- built index.html (made from site.json) stays a true fallback for
-- when the API is down.
--
-- site_name the site's name, in every title
-- description the default search description
-- preview_image the default link-preview image
-- favicon the browser-tab icon ('/uploads/…', PNG or SVG)
-- apple_touch_icon the home-screen icon on iPhones (PNG, 180px)
-- indexing 'on' or 'off': whether search engines may list
-- the site. Per database, so the dev server can
-- say off while production says on, from one
-- build. Null follows site.json's robots.index.
--
-- site_setting_pages overrides a static page's title and intro
-- (site.json's "pages"), one row per page that differs. The path
-- must be one of site.json's pages; the admin only offers those.
--
-- A singleton like front_page: one row, made here, which the admin
-- edits and can't delete.
--
-- PRAGMA user_version; -- reads 34 before this file
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE site_settings (
id TEXT PRIMARY KEY CHECK (id = 'site'),
site_name TEXT,
description TEXT,
preview_image TEXT,
favicon TEXT,
apple_touch_icon TEXT,
indexing TEXT CHECK (indexing IN ('on', 'off')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
INSERT INTO site_settings (id) VALUES ('site');
CREATE TABLE site_setting_pages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
settings_id TEXT NOT NULL REFERENCES site_settings (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
path TEXT NOT NULL, -- '/retreats'
title TEXT,
description TEXT,
UNIQUE (settings_id, path)
) STRICT;
-- ── Triggers last (see CLAUDE.md, Migrations) ──
CREATE TRIGGER site_settings_touch
AFTER UPDATE ON site_settings
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE site_settings SET updated_at = datetime('now') WHERE id = new.id;
END;

View file

@ -1,53 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 036 VIDEO CLIPS
--
-- The admin's video clip tool (Tools → Video clips): download one of
-- our videos from YouTube or Facebook, cut clips from it, and take
-- them away as MP4 or MP3. One row per job, of two kinds:
--
-- source a download (yt-dlp) of source_url. When done, file is
-- the video in CLIPS_DIR and title/duration describe it.
-- clip a cut (ffmpeg) of a source: params holds the JSON
-- { start, end, shape, focus, format }. When done, file
-- is the clip in CLIPS_DIR.
--
-- Jobs run one at a time, oldest queued first (server/src/clips.js).
-- A job left 'running' by a restart is marked failed at boot.
--
-- Files are temporary. A clip's file is deleted once it has been
-- downloaded, unless it was saved to the media library first
-- (saved_media_id), and anything older than a day is swept, sources
-- included. Deleting a source deletes its clips.
--
-- PRAGMA user_version; -- reads 35 before this file
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE clip_jobs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
kind TEXT NOT NULL CHECK (kind IN ('source', 'clip')),
status TEXT NOT NULL DEFAULT 'queued'
CHECK (status IN ('queued', 'running', 'done', 'failed')),
progress REAL NOT NULL DEFAULT 0 CHECK (progress BETWEEN 0 AND 1),
source_url TEXT, -- kind 'source'
source_id INTEGER REFERENCES clip_jobs (id) ON DELETE CASCADE, -- kind 'clip'
params TEXT, -- kind 'clip': JSON
title TEXT,
duration REAL, -- seconds
file TEXT, -- a name in CLIPS_DIR, once done
bytes INTEGER,
error TEXT,
saved_media_id INTEGER REFERENCES media (id) ON DELETE SET NULL,
downloaded_at TEXT, -- a clip's file went out, and was deleted
created_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
finished_at TEXT,
CHECK ((kind = 'source') = (source_url IS NOT NULL)),
CHECK ((kind = 'clip') = (source_id IS NOT NULL))
) STRICT;
CREATE INDEX clip_jobs_queue_idx ON clip_jobs (status, id);
CREATE INDEX clip_jobs_source_idx ON clip_jobs (source_id);

View file

@ -1,39 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 037 LEADERSHIP VIEW: PUBLISHED HOME ORGS ONLY
--
-- v_org_leadership named a person's primary organization even when
-- that organization was unpublished, so a draft org's name could
-- show on a public leadership list. It now joins published ones
-- only; an unpublished one reads as no primary org.
-- ═══════════════════════════════════════════════════════════════
DROP VIEW v_org_leadership;
CREATE VIEW v_org_leadership AS
SELECT
a.org_id,
a.team_id,
t.name AS team_name,
t.sort_order AS team_sort_order,
a.person_id,
a.title,
a.role,
a.is_owner,
a.sort_order,
p.display_name,
p.sort_name,
p.pronouns,
p.tagline,
p.photo,
p.public_email,
p.location_label,
p.bio,
o.id AS primary_org_id,
o.name AS primary_org_name
FROM affiliations a
JOIN people p ON p.id = a.person_id AND p.is_published = 1
LEFT JOIN teams t ON t.id = a.team_id
LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1
WHERE a.is_public = 1
AND a.ended_on IS NULL
ORDER BY a.org_id, a.is_owner DESC, a.sort_order, p.sort_name;

Some files were not shown because too many files have changed in this diff Show more