create-spillway 0.1.26 → 0.1.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +3 -1
  2. package/dist/index.d.ts +6 -2
  3. package/dist/index.js +9 -3
  4. package/dist/index.js.map +1 -1
  5. package/package.json +6 -6
  6. package/templates/astro/.env.example +6 -0
  7. package/templates/astro/README.md +29 -6
  8. package/templates/astro/astro.config.mjs +46 -5
  9. package/templates/astro/package.json +3 -0
  10. package/templates/astro/public/spillway-search.js +85 -0
  11. package/templates/astro/public/spillway-suggest.js +10 -3
  12. package/templates/astro/src/layouts/Layout.astro +19 -7
  13. package/templates/astro/src/lib/output.ts +28 -0
  14. package/templates/astro/src/lib/spillway.ts +10 -4
  15. package/templates/astro/src/lib/static-paths.ts +26 -0
  16. package/templates/astro/src/middleware.ts +4 -2
  17. package/templates/astro/src/pages/[...path].astro +26 -8
  18. package/templates/next/.env.example +6 -0
  19. package/templates/next/README.md +30 -7
  20. package/templates/next/app/[[...slug]]/page.static.tsx +103 -0
  21. package/templates/next/app/layout.tsx +8 -4
  22. package/templates/next/app/not-found.tsx +3 -2
  23. package/templates/next/app/robots.ts +3 -0
  24. package/templates/next/app/sitemap.ts +3 -0
  25. package/templates/next/components/MembersOnly.tsx +10 -1
  26. package/templates/next/components/Nav.tsx +7 -4
  27. package/templates/next/components/SiteShell.tsx +24 -7
  28. package/templates/next/components/StaticSearchPage.tsx +35 -0
  29. package/templates/next/lib/output.ts +36 -0
  30. package/templates/next/lib/spillway.ts +7 -9
  31. package/templates/next/next.config.ts +37 -4
  32. package/templates/next/package.json +3 -0
  33. package/templates/next/public/spillway-search.js +85 -0
  34. package/templates/next/public/spillway-suggest.js +10 -3
  35. package/templates/nuxt/README.md +2 -0
  36. package/templates/nuxt/package.json +3 -0
  37. package/templates/nuxt/public/spillway-suggest.js +10 -3
  38. package/templates/sveltekit/README.md +2 -0
  39. package/templates/sveltekit/package.json +3 -0
  40. package/templates/sveltekit/static/spillway-suggest.js +10 -3
  41. /package/templates/astro/src/{pages → server-routes}/api/preview/exit.ts +0 -0
  42. /package/templates/astro/src/{pages → server-routes}/api/preview/index.ts +0 -0
  43. /package/templates/astro/src/{pages → server-routes}/api/revalidate.ts +0 -0
  44. /package/templates/astro/src/{pages → server-routes}/api/search/suggest.ts +0 -0
  45. /package/templates/astro/src/{pages → server-routes}/auth/callback.ts +0 -0
  46. /package/templates/astro/src/{pages → server-routes}/auth/login.ts +0 -0
  47. /package/templates/astro/src/{pages → server-routes}/auth/logout.ts +0 -0
  48. /package/templates/next/app/[[...slug]]/{page.tsx → page.server.tsx} +0 -0
  49. /package/templates/next/app/api/preview/exit/{route.ts → route.server.ts} +0 -0
  50. /package/templates/next/app/api/preview/{route.ts → route.server.ts} +0 -0
  51. /package/templates/next/app/api/revalidate/{route.ts → route.server.ts} +0 -0
  52. /package/templates/next/app/api/search/suggest/{route.ts → route.server.ts} +0 -0
  53. /package/templates/next/app/auth/callback/{route.ts → route.server.ts} +0 -0
  54. /package/templates/next/app/auth/login/{route.ts → route.server.ts} +0 -0
  55. /package/templates/next/app/auth/logout/{route.ts → route.server.ts} +0 -0
  56. /package/templates/next/app/member/[[...slug]]/{page.tsx → page.server.tsx} +0 -0
  57. /package/templates/next/app/search/{page.tsx → page.server.tsx} +0 -0
  58. /package/templates/next/{proxy.ts → proxy.server.ts} +0 -0
@@ -3,18 +3,27 @@
3
3
  * Every path: the published page Spillway has there, rendered with the core block library; the search page (/search,
4
4
  * /es/search); or a 404. The fetch happens here in the frontmatter, before the layout starts streaming, so the 404
5
5
  * status still reaches the browser.
6
+ *
7
+ * Static output (README.md, Static output): `getStaticPaths` lists every published path, every redirect in Spillway (a
8
+ * page that sends the browser on), each language's search page (its results read in the browser) and the 404 page.
6
9
  */
7
10
  import { pathFromParams } from '@spillway-cms/astro';
8
11
  import { renderPage } from '@spillway-cms/astro/render';
9
12
  import Layout from '../layouts/Layout.astro';
10
- import { blockParams, loadPage, loadSite, pageLanguages, readPreview, routeOf, searchLanguages, searchPath, searchSite } from '../lib/spillway';
13
+ import { blockParams, loadPage, loadSite, pageLanguages, readPreview, redirectFor, routeOf, searchLanguages, searchPath, searchSite } from '../lib/spillway';
11
14
  import { loadMemberPage, members } from '../lib/members';
15
+ import { BASE_PATH, SPILLWAY_URL, STATIC, href } from '../lib/output';
12
16
  import { SpillwayError, type PublicRender } from '@spillway-cms/client';
17
+ // Static output: the paths to write (src/lib/static-paths.ts). A server renders every path on request instead.
18
+ export * from '../lib/static-paths';
13
19
 
14
20
  const path = pathFromParams(Astro.params);
15
- const preview = readPreview(Astro.cookies);
21
+ const preview = STATIC ? null : readPreview(Astro.cookies);
16
22
  const site = await loadSite(preview);
17
23
  const route = routeOf(site, path);
24
+ // Static output: a redirect in Spillway is a page that sends the browser on (in server output, src/middleware.ts answers it).
25
+ const moved = STATIC && !route.search ? await redirectFor(path) : undefined;
26
+ if (moved) return Astro.redirect(href(moved.to), moved.status === 301 ? 301 : 302);
18
27
  // Members (README.md, Members): a signed-in member's pages are read with their own token and never cached; for a visitor, a
19
28
  // members-only page asks to sign in.
20
29
  const member = Astro.locals.member ?? null;
@@ -35,8 +44,9 @@ if (preview) Astro.response.headers.set('cache-control', 'private, no-store');
35
44
 
36
45
  // The search page: a GET form, the published pages that match (read as a visitor, so drafts never show) and a pager.
37
46
  // With suggestions on in Spillway (Site settings → Search), public/spillway-suggest.js suggests pages while visitors type.
38
- const q = route.search ? (Astro.url.searchParams.get('q') ?? '').trim().slice(0, 200) : '';
39
- const pageNo = Math.max(1, Math.min(100, Number.parseInt(Astro.url.searchParams.get('page') ?? '1', 10) || 1));
47
+ // With static output the page is one file for every query: public/spillway-search.js reads the results in the browser.
48
+ const q = route.search && !STATIC ? (Astro.url.searchParams.get('q') ?? '').trim().slice(0, 200) : '';
49
+ const pageNo = Math.max(1, Math.min(100, Number.parseInt((STATIC ? null : Astro.url.searchParams.get('page')) ?? '1', 10) || 1));
40
50
  const found = route.search ? await searchSite(q, route.locale, pageNo) : null;
41
51
  const action = searchPath(site, route.locale);
42
52
  const pageHref = (n: number) => `${action}?q=${encodeURIComponent(q)}${n > 1 ? `&page=${n}` : ''}`;
@@ -53,12 +63,14 @@ const siteName = site?.name ?? 'Spillway site';
53
63
  {...(route.search ? { title: q ? `Search: ${q} | ${siteName}` : `Search | ${siteName}` } : {})}
54
64
  >
55
65
  {page ? (
56
- <Fragment set:html={renderPage(page)} />
66
+ <Fragment set:html={renderPage(page, STATIC ? { links: { basePath: BASE_PATH } } : {})} />
57
67
  ) : restricted ? (
58
68
  <section class="members-only">
59
69
  <h1>{restricted === 'forbidden' ? 'Not available' : 'Members only'}</h1>
60
70
  {restricted === 'forbidden' ? (
61
71
  <p>This page is for other members of the site.</p>
72
+ ) : STATIC ? (
73
+ <p>This page is for members of the site. <a href={`${SPILLWAY_URL}/account/login?next=${encodeURIComponent(path)}`}>Sign in on the site</a> to see it.</p>
62
74
  ) : members ? (
63
75
  <p>This page is for members of the site. <a href={`/auth/login?returnTo=${encodeURIComponent(path)}`}>Sign in</a> to see it.</p>
64
76
  ) : (
@@ -68,12 +80,18 @@ const siteName = site?.name ?? 'Spillway site';
68
80
  ) : found ? (
69
81
  <section class="search-page">
70
82
  <h1>Search</h1>
71
- <form class="search-form" role="search" method="get" action={action}>
83
+ <form class="search-form" role="search" method="get" action={href(action)}>
72
84
  <label class="sw-visually-hidden" for="search-q">Search this site</label>
73
85
  <input id="search-q" type="search" name="q" value={q} placeholder="Search" enterkeyhint="search" data-sw-suggest={suggest ? '' : undefined} data-sw-locale={suggest ? route.locale : undefined} />
74
86
  <button type="submit">Search</button>
75
87
  </form>
76
- {found.error ? (
88
+ {STATIC ? (
89
+ <>
90
+ <div data-sw-search-results="" data-sw-endpoint={`${SPILLWAY_URL}/api/search`} data-sw-locale={route.locale} data-sw-base={BASE_PATH}></div>
91
+ <noscript><p>Searching here needs JavaScript. <a href={`${SPILLWAY_URL}${action}`}>Search on the site</a> instead.</p></noscript>
92
+ <script is:inline src={`${BASE_PATH}/spillway-search.js`} defer></script>
93
+ </>
94
+ ) : found.error ? (
77
95
  <p role="alert">Search is not available right now. Please try again later.</p>
78
96
  ) : q && (
79
97
  <>
@@ -101,7 +119,7 @@ const siteName = site?.name ?? 'Spillway site';
101
119
  ) : (
102
120
  <section class="not-found">
103
121
  <h1>Page not found</h1>
104
- <p>There is no published page at this address. <a href="/">Go to the home page</a>.</p>
122
+ <p>There is no published page at this address. <a href={href('/')}>Go to the home page</a>.</p>
105
123
  </section>
106
124
  )}
107
125
  </Layout>
@@ -30,3 +30,9 @@ MEMBER_SESSION_SECRET=
30
30
 
31
31
  # This front end's own address: canonical links, the sitemap and robots.txt use it.
32
32
  SITE_URL=http://localhost:3001
33
+
34
+ # Optional. static: `npm run build` writes plain files to out/ for any static host instead of a server (README.md,
35
+ # Static output). Every page is read from Spillway while it builds; leave it out for server output.
36
+ SPILLWAY_OUTPUT=
37
+ # Optional, with static output: the path the site is served under, such as /site; empty for the root of its address.
38
+ SPILLWAY_BASE_PATH=
@@ -20,16 +20,18 @@ A Next.js (App Router) front end on a [Spillway CMS](https://spillwaycms.com) si
20
20
  | File | What it does |
21
21
  | --- | --- |
22
22
  | `lib/spillway.ts` | The server-side client (`createSpillwayClient`): every read is tagged in Next's cache. Redirect matching and canonical links on `SITE_URL` |
23
- | `app/[[...slug]]/page.tsx` | Every published path, prerendered at build time (`generateStaticParams`), new paths rendered on demand; the blocks, JSON-LD and metadata (title, description, canonical, hreflang, Open Graph) from Spillway; Spillway's redirects first; a 404 for unknown paths |
24
- | `app/search/page.tsx` | The search page at `/search`, rendered for each request; `next.config.ts` rewrites `/es/search` and the other languages' search pages to it |
23
+ | `lib/output.ts` | Server or static output (`SPILLWAY_OUTPUT`), the base path, and `href()` for links with static output |
24
+ | `app/[[...slug]]/page.server.tsx` | Every published path, prerendered at build time (`generateStaticParams`), new paths rendered on demand; the blocks, JSON-LD and metadata (title, description, canonical, hreflang, Open Graph) from Spillway; Spillway's redirects first; a 404 for unknown paths |
25
+ | `app/search/page.server.tsx` | The search page at `/search`, rendered for each request; `next.config.ts` rewrites `/es/search` and the other languages' search pages to it |
25
26
  | `components/SearchPage.tsx`, `components/LanguageSwitcher.tsx` | The search page, and the language switcher |
26
- | `app/api/search/suggest/route.ts`, `public/spillway-suggest.js` | Search suggestions while visitors type |
27
+ | `app/api/search/suggest/route.server.ts`, `public/spillway-suggest.js` | Search suggestions while visitors type |
27
28
  | `app/layout.tsx` | The document: the block stylesheet, the brand, search suggestions and, in a preview, the preview bar |
28
29
  | `components/SiteShell.tsx` | The header and footer each page renders in its language: the site name, the `main` and `footer` menus (Structure → Menus), the language switcher |
29
- | `app/api/revalidate/route.ts` | The webhook target: verifies `X-Spillway-Signature` and revalidates the paths and tags the event touched (`affectedByWebhook`) |
30
- | `app/api/preview/route.ts`, `exit/route.ts` | Draft mode from a release share link or `?preview=1&secret=`, and back |
30
+ | `app/api/revalidate/route.server.ts` | The webhook target: verifies `X-Spillway-Signature` and revalidates the paths and tags the event touched (`affectedByWebhook`) |
31
+ | `app/api/preview/route.server.ts`, `exit/route.server.ts` | Draft mode from a release share link or `?preview=1&secret=`, and back |
31
32
  | `app/sitemap.ts`, `app/robots.ts` | `/sitemap.xml` from the published paths, `/robots.txt` |
32
- | `next.config.ts` | Rewrites `/api/forms/*` and `/media/*` to Spillway, so the Form block and media work from this origin, and each language's search page to `app/search` |
33
+ | `next.config.ts` | Rewrites `/api/forms/*` and `/media/*` to Spillway, so the Form block and media work from this origin, and each language's search page to `app/search`; with static output, the export to `out/` |
34
+ | `app/[[...slug]]/page.static.tsx`, `components/StaticSearchPage.tsx`, `public/spillway-search.js` | Static output only: every page, redirect and search page as a file, the search results read in the browser |
33
35
  | `scripts/brand.mjs` | Writes the brand stylesheet (`app/spillway-brand.css`) with `@spillway-cms/brand`; runs before every build |
34
36
 
35
37
  ## Search
@@ -48,7 +50,7 @@ Members of the Spillway site sign in on this front end through the site's own Op
48
50
  2. Set `SPILLWAY_MEMBERS_CLIENT_ID` (and `SPILLWAY_MEMBERS_CLIENT_SECRET` for a confidential front end) in the env file. `MEMBER_SESSION_SECRET` seals the session cookie; create-spillway wrote a random one. `SPILLWAY_URL` must be the site's own address, the provider's issuer.
49
51
  3. Restart. The header has **Sign in**; a members-only page asks visitors to sign in, and shows a member what Spillway shows them.
50
52
 
51
- The session is one `HttpOnly` cookie, sealed with `MEMBER_SESSION_SECRET`, holding the member's tokens; the browser cannot read it, and over https it is named `__Host-spillway_member`, so no other site, not even a sibling subdomain, can plant one. `proxy.ts` refreshes the session when its access token is about to expire and sends a signed-in member's page requests to `app/member`, which reads Spillway with the member's own access token and is never cached; visitors keep the static pages. The routes are `app/auth/login`, `app/auth/callback` and `app/auth/logout`; `lib/member-auth.ts` and `lib/members.ts` hold the rest. Sign out ends the sign-in at Spillway too. The flow is `@spillway-cms/client/members`: the authorization code flow with PKCE, `state` and `nonce`, and the ID token checked against the site's keys, with no other dependency.
53
+ The session is one `HttpOnly` cookie, sealed with `MEMBER_SESSION_SECRET`, holding the member's tokens; the browser cannot read it, and over https it is named `__Host-spillway_member`, so no other site, not even a sibling subdomain, can plant one. `proxy.server.ts` refreshes the session when its access token is about to expire and sends a signed-in member's page requests to `app/member`, which reads Spillway with the member's own access token and is never cached; visitors keep the static pages. The routes are `app/auth/login`, `app/auth/callback` and `app/auth/logout`; `lib/member-auth.ts` and `lib/members.ts` hold the rest. Sign out ends the sign-in at Spillway too. The flow is `@spillway-cms/client/members`: the authorization code flow with PKCE, `state` and `nonce`, and the ID token checked against the site's keys, with no other dependency.
52
54
 
53
55
  ## Previews
54
56
 
@@ -67,4 +69,25 @@ With Tailwind v4, install `tailwindcss` and `@tailwindcss/postcss`, write `brand
67
69
 
68
70
  Any host that runs Next.js with a server works (Vercel, Netlify, a container with `npm run build && npm start`). Set the variables from `.env.example` there, with `SITE_URL` the public address, then point the webhook rules at it. Spillway serves the media and receives the form posts; this app proxies both.
69
71
 
72
+ ## Static output
73
+
74
+ With `SPILLWAY_OUTPUT=static`, `npm run build` writes plain files to `out/` (Next's static export) for a host that only serves files, such as a host that builds the front end and publishes what the build writes:
75
+
76
+ ```bash
77
+ SPILLWAY_OUTPUT=static SPILLWAY_BASE_PATH=/site npm run build # SPILLWAY_BASE_PATH is optional
78
+ npx serve out # look at it locally
79
+ ```
80
+
81
+ Every page is read from Spillway while it builds, as a visitor sees it: one file for each published path (`about.html`, `es/about.html`), for each redirect in Spillway (a page that sends the browser on), for each language's search page, and `404.html` for the rest. A page published later appears with the next build, so rebuild on a publish: point the webhook rules at your host's deploy hook instead of `/api/revalidate`. The build stops with the reason when Spillway cannot be read, rather than writing a site without pages. It does not use `SPILLWAY_TOKEN`, and `SPILLWAY_SITE` needs it, so set `SPILLWAY_URL` to the site's own address.
82
+
83
+ What changes:
84
+
85
+ - **Files named `*.server.ts` and `*.server.tsx` are left out** (`pageExtensions` in `next.config.ts`), since they need a server: `/api/revalidate`, `/api/preview`, `/api/search/suggest`, the sign-in routes under `app/auth`, the member pages in `app/member` and `proxy.server.ts`. The `*.static.tsx` files are used only here. Keep that naming for routes of your own that need a server.
86
+ - **`SPILLWAY_BASE_PATH`**: the path the site is served under (`/site`). Next's `basePath` puts it on its own files; `href()` in `lib/output.ts` and `<SpillwayBlocks links>` put it on the menus, the language switcher and the links in Spillway's blocks. `SITE_URL` is the address with or without it.
87
+ - **Forms post to Spillway**, and media load from it, since there is no proxy: `<SpillwayBlocks links>` points the Form block, and any link to Spillway's own paths (`/account`, `/media`), at `SPILLWAY_URL`.
88
+ - **Search runs in the browser.** `public/spillway-suggest.js` asks Spillway's public `GET /api/search/suggest` for suggestions, and `public/spillway-search.js` shows the results on the search page from `GET /api/search`; Spillway lets any origin read both, and they show published pages only. Without JavaScript, the search page links to the search on the Spillway site.
89
+ - **Members sign in on the Spillway site.** Members-only pages are not in the build (the public API leaves them out). On a site with accounts on (Site settings → Accounts), the header links **Sign in** and **Account** to the site's own account pages, and a members-only page links to the site's sign-in, which returns to that page on the site.
90
+ - **Blocks that read the address** (a Collection's filters and pager, a calendar's month) show their first view: a file is the same for every query string.
91
+ - **Previews stay with Spillway**: the admin's Preview and release share links show Spillway's own render.
92
+
70
93
  See [the headless docs](https://github.com/kwall-llc/spillway-cms/blob/main/docs/adapters.md) for the API and the adapters.
@@ -0,0 +1,103 @@
1
+ import type { Metadata } from 'next';
2
+ import { notFound } from 'next/navigation';
3
+ import { cache } from 'react';
4
+ import { SpillwayError, pathFromParams } from '@spillway-cms/next';
5
+ import { SpillwayBlocks, SpillwayJsonLd, metadataFor } from '@spillway-cms/next/page';
6
+ import { siteLocales, splitLocalePath, type PublicRender, type PublicSite } from '@spillway-cms/client';
7
+ import { SiteShell } from '../../components/SiteShell';
8
+ import { MembersOnly } from '../../components/MembersOnly';
9
+ import { StaticSearchPage } from '../../components/StaticSearchPage';
10
+ import { BASE_PATH, href } from '../../lib/output';
11
+ import { pageLanguages, redirectFor, searchPath, spillway, withSiteUrls } from '../../lib/spillway';
12
+
13
+ /**
14
+ * Static output (README.md, Static output): one file per published path, per redirect in Spillway (a page that sends the
15
+ * browser on) and per language's search page, all read from Spillway at build time. Nothing renders on request, so a path
16
+ * published later appears with the next build, and an unknown path is the host's 404 page (app/not-found.tsx).
17
+ */
18
+ type Props = { params: Promise<{ slug?: string[] }> };
19
+
20
+ export const dynamicParams = false;
21
+
22
+ export async function generateStaticParams(): Promise<{ slug: string[] }[]> {
23
+ let site: PublicSite;
24
+ let paths: string[];
25
+ try {
26
+ site = await spillway.site();
27
+ paths = (await spillway.paths()).map((p) => p.path);
28
+ } catch (err) {
29
+ throw new Error(`Static output: Spillway's published paths could not be read (${err instanceof Error ? err.message : String(err)}). A static build needs them; check SPILLWAY_URL.`);
30
+ }
31
+ const redirects = await spillway.redirects().catch(() => []);
32
+ const searches = siteLocales(site).map((locale) => searchPath(site, locale));
33
+ const all = new Set([...paths, ...redirects.map((r) => r.from), ...searches]);
34
+ return [...all].filter((p) => p.startsWith('/')).map((p) => ({ slug: p.split('/').filter(Boolean) }));
35
+ }
36
+
37
+ /** The locale whose search page (/search, /es/search) `path` is, or null. */
38
+ function searchLocale(site: PublicSite | null, path: string): string | null {
39
+ const local = site ? splitLocalePath(site, path) : { locale: 'en', path };
40
+ return local.path === '/search' ? local.locale : null;
41
+ }
42
+
43
+ /** The page at a path; null when Spillway has none, 'members' when it is for members (they read it on the Spillway site). */
44
+ const loadPage = cache(async (path: string): Promise<PublicRender | 'members' | null> => {
45
+ try {
46
+ return await spillway.render(path);
47
+ } catch (err) {
48
+ if (err instanceof SpillwayError && err.code === 'members_only') return 'members';
49
+ if (err instanceof SpillwayError && err.status === 404) return null;
50
+ throw err;
51
+ }
52
+ });
53
+
54
+ export async function generateMetadata({ params }: Props): Promise<Metadata> {
55
+ const path = pathFromParams(await params);
56
+ const site = await spillway.site().catch(() => null);
57
+ if (searchLocale(site, path)) return { title: `Search | ${site?.name ?? 'Spillway site'}`, robots: { index: false } };
58
+ const moved = await redirectFor(path);
59
+ if (moved) return { title: site?.name ?? 'Spillway site', robots: { index: false } };
60
+ const page = await loadPage(path).catch(() => null);
61
+ if (page === 'members') return { title: 'Members only', robots: { index: false } };
62
+ return page ? (metadataFor(withSiteUrls(page)) as Metadata) : {};
63
+ }
64
+
65
+ export default async function Page({ params }: Props) {
66
+ const path = pathFromParams(await params);
67
+ const site = await spillway.site().catch(() => null);
68
+
69
+ const locale = searchLocale(site, path);
70
+ if (locale) return <StaticSearchPage site={site} locale={locale} />;
71
+
72
+ // A redirect in Spillway is a page that sends the browser on: static files have no status codes of their own.
73
+ const moved = await redirectFor(path);
74
+ if (moved) {
75
+ const to = href(moved.to);
76
+ return (
77
+ <>
78
+ <meta httpEquiv="refresh" content={`0; url=${to}`} />
79
+ <link rel="canonical" href={to} />
80
+ <p className="redirect">
81
+ This page has moved to <a href={to}>{to}</a>.
82
+ </p>
83
+ </>
84
+ );
85
+ }
86
+
87
+ const page = await loadPage(path);
88
+ if (!page) notFound();
89
+ // Members-only pages are not in a static build (the public API leaves them out); members read them on the Spillway site.
90
+ if (page === 'members') {
91
+ return (
92
+ <SiteShell>
93
+ <MembersOnly path={path} signedIn={false} membersOn />
94
+ </SiteShell>
95
+ );
96
+ }
97
+ return (
98
+ <SiteShell locale={page.locale} menus={page.menus} languages={pageLanguages(site, page)}>
99
+ <SpillwayJsonLd page={page} />
100
+ <SpillwayBlocks page={page} links={{ basePath: BASE_PATH }} />
101
+ </SiteShell>
102
+ );
103
+ }
@@ -2,6 +2,7 @@ import type { Metadata } from 'next';
2
2
  import type { ReactNode } from 'react';
3
3
  import { SpillwayStyles } from '@spillway-cms/next/page';
4
4
  import { currentPreview } from '@spillway-cms/next/server';
5
+ import { BASE_PATH, SPILLWAY_URL, STATIC } from '../lib/output';
5
6
  import { SITE_URL, spillway } from '../lib/spillway';
6
7
  import builtBrand from './spillway-brand.json';
7
8
  // The brand as it was at build time (scripts/brand.mjs, run before every build): colors, fonts, type scale and spacing as
@@ -18,9 +19,9 @@ export async function generateMetadata(): Promise<Metadata> {
18
19
  };
19
20
  }
20
21
 
21
- /** The site settings and the brand, read through the preview when there is one. */
22
+ /** The site settings and the brand, read through the preview when there is one (never with static output). */
22
23
  async function loadShell() {
23
- const preview = await currentPreview({ secret: spillway.options.previewSecret });
24
+ const preview = STATIC ? null : await currentPreview({ secret: spillway.options.previewSecret });
24
25
  const client = preview ? spillway.withPreview(preview) : spillway;
25
26
  const [site, brand] = await Promise.all([client.site().catch(() => null), client.brand().catch(() => null)]);
26
27
  return { preview, site, brand };
@@ -41,8 +42,11 @@ export default async function RootLayout({ children }: { children: ReactNode })
41
42
  {/* The block stylesheet, so Spillway's blocks look as they do on the Spillway site. */}
42
43
  <SpillwayStyles />
43
44
  {newerBrand ? <style id="spillway-brand" dangerouslySetInnerHTML={{ __html: newerBrand }} /> : null}
44
- {/* Search suggestions while visitors type (Site settings → Search), for the search page and the Search blocks. */}
45
- {site?.searchSuggestions !== false ? <script src="/spillway-suggest.js" defer /> : null}
45
+ {/* Search suggestions while visitors type (Site settings → Search), for the search page and the Search blocks. With
46
+ static output the browser asks Spillway's public API itself. */}
47
+ {site?.searchSuggestions !== false ? (
48
+ STATIC ? <script src={`${BASE_PATH}/spillway-suggest.js`} data-sw-endpoint={`${SPILLWAY_URL}/api/search/suggest`} data-sw-base={BASE_PATH} defer /> : <script src="/spillway-suggest.js" defer />
49
+ ) : null}
46
50
  </head>
47
51
  <body>
48
52
  <a className="skip-link" href="#main">
@@ -1,13 +1,14 @@
1
1
  import { SiteShell } from '../components/SiteShell';
2
+ import { href } from '../lib/output';
2
3
 
3
- /** The 404 page, in the site's default language. */
4
+ /** The 404 page, in the site's default language. With static output it is 404.html, which the host serves for unknown paths. */
4
5
  export default function NotFound() {
5
6
  return (
6
7
  <SiteShell>
7
8
  <section className="not-found">
8
9
  <h1>Page not found</h1>
9
10
  <p>
10
- There is no published page at this address. <a href="/">Go to the home page</a>.
11
+ There is no published page at this address. <a href={href('/')}>Go to the home page</a>.
11
12
  </p>
12
13
  </section>
13
14
  </SiteShell>
@@ -1,6 +1,9 @@
1
1
  import type { MetadataRoute } from 'next';
2
2
  import { SITE_URL } from '../lib/spillway';
3
3
 
4
+ // The same for every request; with static output, written as a file.
5
+ export const dynamic = 'force-static';
6
+
4
7
  /** /robots.txt: everything may be crawled except the API routes; the sitemap is on this front end's address. */
5
8
  export default function robots(): MetadataRoute.Robots {
6
9
  return {
@@ -1,6 +1,9 @@
1
1
  import type { MetadataRoute } from 'next';
2
2
  import { SITE_URL, spillway } from '../lib/spillway';
3
3
 
4
+ // Read once at build time and revalidated with the pages; with static output, written as a file.
5
+ export const dynamic = 'force-static';
6
+
4
7
  /** /sitemap.xml from every published path in Spillway, on this front end's address. Revalidated with the pages. */
5
8
  export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
6
9
  try {
@@ -1,10 +1,19 @@
1
- /** What a members-only page shows to someone who may not see it (README.md, Members). */
1
+ import { SPILLWAY_URL, STATIC } from '../lib/output';
2
+
3
+ /**
4
+ * What a members-only page shows to someone who may not see it (README.md, Members). With static output, members sign in
5
+ * and read the page on the Spillway site itself.
6
+ */
2
7
  export function MembersOnly({ path, signedIn, membersOn }: { path: string; signedIn: boolean; membersOn: boolean }) {
3
8
  return (
4
9
  <section className="members-only">
5
10
  <h1>{signedIn ? 'Not available' : 'Members only'}</h1>
6
11
  {signedIn ? (
7
12
  <p>This page is for other members of the site.</p>
13
+ ) : STATIC ? (
14
+ <p>
15
+ This page is for members of the site. <a href={`${SPILLWAY_URL}/account/login?next=${encodeURIComponent(path)}`}>Sign in on the site</a> to see it.
16
+ </p>
8
17
  ) : membersOn ? (
9
18
  <p>
10
19
  This page is for members of the site. <a href={`/auth/login?returnTo=${encodeURIComponent(path)}`}>Sign in</a> to see it.
@@ -1,10 +1,13 @@
1
1
  'use client';
2
2
 
3
3
  import { usePathname } from 'next/navigation';
4
- import type { PublicMenuItem } from '@spillway-cms/client';
4
+ import { frontEndUrl, type FrontEndUrlOptions, type PublicMenuItem } from '@spillway-cms/client';
5
5
 
6
- /** A Spillway menu (Structure → Menus) as a nested list; the item for the current page is marked. */
7
- export function Nav({ items, label }: { items: PublicMenuItem[]; label: string }) {
6
+ /**
7
+ * A Spillway menu (Structure → Menus) as a nested list; the item for the current page is marked. With static output,
8
+ * `links` puts the base path on the site's pages and sends Spillway's own paths to the site.
9
+ */
10
+ export function Nav({ items, label, links }: { items: PublicMenuItem[]; label: string; links?: FrontEndUrlOptions }) {
8
11
  const pathname = usePathname();
9
12
  if (!items.length) return null;
10
13
  const list = (entries: PublicMenuItem[]) => (
@@ -13,7 +16,7 @@ export function Nav({ items, label }: { items: PublicMenuItem[]; label: string }
13
16
  const current = item.href === pathname;
14
17
  return (
15
18
  <li key={`${item.href}:${item.label}`}>
16
- <a href={item.href} aria-current={current ? 'page' : undefined} {...(item.newTab ? { target: '_blank', rel: 'noopener' } : {})}>
19
+ <a href={links ? frontEndUrl(item.href, links) : item.href} aria-current={current ? 'page' : undefined} {...(item.newTab ? { target: '_blank', rel: 'noopener' } : {})}>
17
20
  {item.label}
18
21
  </a>
19
22
  {item.children?.length ? list(item.children) : null}
@@ -1,6 +1,7 @@
1
1
  import type { ReactNode } from 'react';
2
2
  import type { LanguageLink, PublicMenuItem } from '@spillway-cms/client';
3
3
  import { currentPreview } from '@spillway-cms/next/server';
4
+ import { BASE_PATH, SPILLWAY_URL, STATIC, href } from '../lib/output';
4
5
  import { spillway } from '../lib/spillway';
5
6
  import { LanguageSwitcher } from './LanguageSwitcher';
6
7
  import { Nav } from './Nav';
@@ -11,10 +12,11 @@ import { members } from '../lib/members';
11
12
  * The header and footer around a page: the site name, the `main` and `footer` menus (Structure → Menus) and the language
12
13
  * switcher, in the page's language. A page passes the menus Spillway rendered with it; the search page and the 404 read
13
14
  * them for their language. It lives in the pages rather than in app/layout.tsx because a layout does not know its page.
14
- * With members set up, the header has Sign in, or the member's name and Sign out (`member`, given by app/member).
15
+ * With members set up, the header has Sign in, or the member's name and Sign out (`member`, given by app/member). With
16
+ * static output, Sign in and Account go to the Spillway site's own account pages, when the site has accounts on.
15
17
  */
16
18
  export async function SiteShell({ locale, menus, languages = [], member = null, children }: { locale?: string; menus?: { main?: PublicMenuItem[]; footer?: PublicMenuItem[] }; languages?: LanguageLink[]; member?: { name?: string; email?: string } | null; children: ReactNode }) {
17
- const preview = await currentPreview({ secret: spillway.options.previewSecret });
19
+ const preview = STATIC ? null : await currentPreview({ secret: spillway.options.previewSecret });
18
20
  const client = preview ? spillway.withPreview(preview) : spillway;
19
21
  const opts = locale ? { locale } : {};
20
22
  const [site, main, footer] = await Promise.all([
@@ -22,19 +24,34 @@ export async function SiteShell({ locale, menus, languages = [], member = null,
22
24
  menus?.main ? null : client.menu('main', opts).catch(() => null),
23
25
  menus?.footer ? null : client.menu('footer', opts).catch(() => null),
24
26
  ]);
27
+ // With static output, menu links get the base path, and links to Spillway's own paths go to the site.
28
+ const links = STATIC ? { basePath: BASE_PATH, origin: SPILLWAY_URL } : undefined;
25
29
  return (
26
30
  <div lang={locale ?? site?.defaultLocale}>
27
31
  <header className="site-header">
28
- <a className="site-name" href="/">
32
+ <a className="site-name" href={href('/')}>
29
33
  {site?.name ?? 'Spillway site'}
30
34
  </a>
31
- <Nav items={menus?.main ?? main?.items ?? []} label="Main" />
32
- <LanguageSwitcher links={languages} />
33
- {members ? <MemberLinks member={member} /> : null}
35
+ <Nav items={menus?.main ?? main?.items ?? []} label="Main" links={links} />
36
+ <LanguageSwitcher links={languages.map((l) => ({ ...l, href: href(l.href) }))} />
37
+ {STATIC ? (
38
+ site?.accounts ? (
39
+ <nav className="member-links" aria-label="Account">
40
+ <a className="member-link" href={`${SPILLWAY_URL}/account/login`}>
41
+ Sign in
42
+ </a>
43
+ <a className="member-link" href={`${SPILLWAY_URL}/account`}>
44
+ Account
45
+ </a>
46
+ </nav>
47
+ ) : null
48
+ ) : members ? (
49
+ <MemberLinks member={member} />
50
+ ) : null}
34
51
  </header>
35
52
  <main id="main">{children}</main>
36
53
  <footer className="site-footer">
37
- <Nav items={menus?.footer ?? footer?.items ?? []} label="Footer" />
54
+ <Nav items={menus?.footer ?? footer?.items ?? []} label="Footer" links={links} />
38
55
  {site?.footerNote?.split('\n').map((line, i) => <p key={i}>{line}</p>)}
39
56
  </footer>
40
57
  </div>
@@ -0,0 +1,35 @@
1
+ import type { PublicSite } from '@spillway-cms/client';
2
+ import { BASE_PATH, SPILLWAY_URL, href } from '../lib/output';
3
+ import { searchLanguages, searchPath } from '../lib/spillway';
4
+ import { SiteShell } from './SiteShell';
5
+
6
+ /**
7
+ * The search page with static output (/search, /es/search): the same form as components/SearchPage.tsx, with the results
8
+ * read in the browser from Spillway's public search (`GET /api/search`, published pages only) by public/spillway-search.js.
9
+ * Without JavaScript, a link searches on the Spillway site instead.
10
+ */
11
+ export async function StaticSearchPage({ site, locale }: { site: PublicSite | null; locale: string }) {
12
+ const action = searchPath(site, locale);
13
+ const suggest = site?.searchSuggestions !== false;
14
+ return (
15
+ <SiteShell locale={locale} languages={searchLanguages(site, locale, '')}>
16
+ <section className="search-page">
17
+ <h1>Search</h1>
18
+ <form className="search-form" role="search" method="get" action={href(action)}>
19
+ <label className="sw-visually-hidden" htmlFor="search-q">
20
+ Search this site
21
+ </label>
22
+ <input id="search-q" type="search" name="q" placeholder="Search" enterKeyHint="search" {...(suggest ? { 'data-sw-suggest': '', 'data-sw-locale': locale } : {})} />
23
+ <button type="submit">Search</button>
24
+ </form>
25
+ <div data-sw-search-results="" data-sw-endpoint={`${SPILLWAY_URL}/api/search`} data-sw-locale={locale} data-sw-base={BASE_PATH} />
26
+ <noscript>
27
+ <p>
28
+ Searching here needs JavaScript. <a href={`${SPILLWAY_URL}${action}`}>Search on the site</a> instead.
29
+ </p>
30
+ </noscript>
31
+ <script src={`${BASE_PATH}/spillway-search.js`} defer />
32
+ </section>
33
+ </SiteShell>
34
+ );
35
+ }
@@ -0,0 +1,36 @@
1
+ import { frontEndUrl, normalizeBasePath } from '@spillway-cms/client';
2
+
3
+ /**
4
+ * How this front end is built (README.md, Static output). By default it is a Next.js server: pages render on request,
5
+ * the webhook revalidates them, members sign in here and previews work. With `SPILLWAY_OUTPUT=static`, `next build`
6
+ * writes plain files to out/ for any static host instead: the routes in files named `*.server.ts(x)` are left out
7
+ * (next.config.ts), the `*.static.tsx` ones are used, and every page is read from Spillway at build time.
8
+ */
9
+ const output = (process.env.SPILLWAY_OUTPUT ?? '').trim().toLowerCase();
10
+ if (output && output !== 'server' && output !== 'static') {
11
+ throw new Error(`SPILLWAY_OUTPUT is "${process.env.SPILLWAY_OUTPUT}": set it to static for plain files, or leave it out (server) for a Next.js server.`);
12
+ }
13
+
14
+ /** True for a static build (`SPILLWAY_OUTPUT=static`). */
15
+ export const STATIC = output === 'static';
16
+
17
+ /** The Spillway site (SPILLWAY_URL in .env.local). */
18
+ export const SPILLWAY_URL = (process.env.SPILLWAY_URL || 'http://localhost:3000').replace(/\/+$/, '');
19
+
20
+ /** With static output, the path this front end is served under (`SPILLWAY_BASE_PATH=/site`); '' for the root. */
21
+ export const BASE_PATH = STATIC ? normalizeBasePath(process.env.SPILLWAY_BASE_PATH) : '';
22
+
23
+ /** This front end's own address with its base path, for canonical links, the sitemap and robots.txt. */
24
+ export const SITE_URL = withBase((process.env.SITE_URL || 'http://localhost:3001').replace(/\/+$/, ''));
25
+
26
+ function withBase(url: string): string {
27
+ return BASE_PATH && !url.endsWith(BASE_PATH) ? `${url}${BASE_PATH}` : url;
28
+ }
29
+
30
+ /**
31
+ * A link on this front end: with static output, a page's path gets the base path and Spillway's own paths (the account
32
+ * area, media, form posts) go to the Spillway site, which has no proxy here. With server output it is unchanged.
33
+ */
34
+ export function href(path: string): string {
35
+ return STATIC ? frontEndUrl(path, { basePath: BASE_PATH, origin: SPILLWAY_URL }) : path;
36
+ }
@@ -1,23 +1,21 @@
1
1
  import { createSpillwayClient } from '@spillway-cms/next';
2
2
  import { languageLinks, localizedPath, type LanguageLink, type PublicRedirect, type PublicRender, type PublicSite } from '@spillway-cms/client';
3
+ import { SITE_URL, SPILLWAY_URL, STATIC } from './output';
3
4
 
4
- /** The Spillway site (SPILLWAY_URL in .env.local). */
5
- export const SPILLWAY_URL = (process.env.SPILLWAY_URL || 'http://localhost:3000').replace(/\/+$/, '');
6
-
7
- /** This front end's own address, for canonical links, the sitemap and robots.txt. */
8
- export const SITE_URL = (process.env.SITE_URL || 'http://localhost:3001').replace(/\/+$/, '');
5
+ export { SITE_URL, SPILLWAY_URL };
9
6
 
10
7
  /**
11
8
  * One server-side client for the whole app. Every read goes through Next's data cache under tags (`spillway`,
12
9
  * `spillway:path:/about`, `spillway:menu:main`, ...) that app/api/revalidate clears when Spillway says something changed.
13
- * The token stays on the server: never import this file from a client component.
10
+ * The token stays on the server: never import this file from a client component. A static build reads what the public
11
+ * API shows a visitor, without the token (next.config.ts says so when one is set).
14
12
  */
15
13
  export const spillway = createSpillwayClient({
16
14
  baseUrl: SPILLWAY_URL,
17
- token: process.env.SPILLWAY_TOKEN || undefined,
18
- site: process.env.SPILLWAY_SITE || undefined,
15
+ token: (!STATIC && process.env.SPILLWAY_TOKEN) || undefined,
16
+ site: (!STATIC && process.env.SPILLWAY_SITE) || undefined,
19
17
  // Checks /api/preview?preview=1 and signs the draft preview cookie, which the pages verify with it. Server only.
20
- previewSecret: process.env.SPILLWAY_PREVIEW_SECRET || undefined,
18
+ previewSecret: (!STATIC && process.env.SPILLWAY_PREVIEW_SECRET) || undefined,
21
19
  });
22
20
 
23
21
  /** Redirect matching as Spillway does it: case-insensitive, without a trailing slash or a query. */
@@ -1,9 +1,11 @@
1
1
  import type { NextConfig } from 'next';
2
2
  import { spillwayRewrites } from '@spillway-cms/next';
3
+ import { BASE_PATH, SPILLWAY_URL, STATIC } from './lib/output';
3
4
 
4
- const SPILLWAY_URL = process.env.SPILLWAY_URL || 'http://localhost:3000';
5
-
6
- const config: NextConfig = {
5
+ // Server output (the default): every route below app/, proxy.server.ts and the rewrites. Files named *.static.tsx are
6
+ // left out.
7
+ const server: NextConfig = {
8
+ pageExtensions: ['server.tsx', 'server.ts', 'tsx', 'ts'],
7
9
  // Form posts (/api/forms/*) and media (/media/*) go to Spillway through this origin, so the blocks' relative URLs work.
8
10
  // The search page in each language (/es/search) is app/search with ?locale=es.
9
11
  // Do not list @puckeditor/core or @spillway-cms/blocks in serverExternalPackages: Next must bundle them with its React.
@@ -12,4 +14,35 @@ const config: NextConfig = {
12
14
  },
13
15
  };
14
16
 
15
- export default config;
17
+ // Static output (SPILLWAY_OUTPUT=static, README.md): plain files in out/, under SPILLWAY_BASE_PATH. Files named
18
+ // *.server.ts(x) are left out, since they need a server: the API routes, sign-in, the member pages and proxy.server.ts.
19
+ // Form blocks post to Spillway, and search runs in the browser against its public API.
20
+ const staticExport: NextConfig = {
21
+ output: 'export',
22
+ pageExtensions: ['static.tsx', 'static.ts', 'tsx', 'ts'],
23
+ ...(BASE_PATH ? { basePath: BASE_PATH } : {}),
24
+ };
25
+
26
+ export default async function config(): Promise<NextConfig> {
27
+ if (!STATIC) return server;
28
+ await checkStaticBuild();
29
+ return staticExport;
30
+ }
31
+
32
+ /**
33
+ * A static build reads every page from Spillway while it builds, so it stops at once, with the reason, when it cannot;
34
+ * and it names the settings only a server uses.
35
+ */
36
+ async function checkStaticBuild(): Promise<void> {
37
+ if (process.env.SPILLWAY_SITE) {
38
+ throw new Error("Static output: SPILLWAY_SITE needs SPILLWAY_TOKEN, which a static build does not use. Set SPILLWAY_URL to the site's own address instead.");
39
+ }
40
+ try {
41
+ const res = await fetch(`${SPILLWAY_URL}/api/public/site`, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(15_000) });
42
+ if (!res.ok) throw new Error(`it answered ${res.status}`);
43
+ } catch (err) {
44
+ throw new Error(`Static output: the build reads every page from Spillway, and ${SPILLWAY_URL} could not be read (${err instanceof Error ? err.message : String(err)}). Check SPILLWAY_URL.`);
45
+ }
46
+ if (process.env.SPILLWAY_TOKEN) console.warn('[spillway] static output: SPILLWAY_TOKEN is not used. The build reads what Spillway shows a visitor; previews need server output.');
47
+ if (process.env.SPILLWAY_MEMBERS_CLIENT_ID) console.warn("[spillway] static output: SPILLWAY_MEMBERS_CLIENT_ID is not used. Members sign in on the Spillway site; signing in here needs server output.");
48
+ }
@@ -30,5 +30,8 @@
30
30
  },
31
31
  "engines": {
32
32
  "node": ">=20.16"
33
+ },
34
+ "spillway": {
35
+ "starter": "next"
33
36
  }
34
37
  }