create-spillway 0.1.22 → 0.1.24
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.
- package/README.md +11 -7
- package/dist/cli.d.ts +5 -1
- package/dist/cli.js +47 -4
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +44 -5
- package/dist/index.js +109 -11
- package/dist/index.js.map +1 -1
- package/package.json +11 -7
- package/templates/astro/README.md +16 -3
- package/templates/astro/public/spillway-suggest.js +133 -0
- package/templates/astro/src/layouts/Layout.astro +21 -6
- package/templates/astro/src/lib/spillway.ts +88 -15
- package/templates/astro/src/pages/[...path].astro +58 -6
- package/templates/astro/src/pages/api/search/suggest.ts +16 -0
- package/templates/astro/src/styles/site.css +121 -0
- package/templates/next/README.md +19 -3
- package/templates/next/app/[[...slug]]/page.tsx +7 -4
- package/templates/next/app/api/search/suggest/route.ts +18 -0
- package/templates/next/app/globals.css +121 -0
- package/templates/next/app/layout.tsx +11 -21
- package/templates/next/app/not-found.tsx +11 -6
- package/templates/next/app/search/page.tsx +29 -0
- package/templates/next/components/LanguageSwitcher.tsx +19 -0
- package/templates/next/components/SearchPage.tsx +67 -0
- package/templates/next/components/SiteShell.tsx +38 -0
- package/templates/next/lib/spillway.ts +49 -1
- package/templates/next/next.config.ts +2 -1
- package/templates/next/public/spillway-suggest.js +133 -0
- package/templates/nuxt/.env.example +27 -0
- package/templates/nuxt/README.md +75 -0
- package/templates/nuxt/_gitignore +15 -0
- package/templates/nuxt/app/app.vue +3 -0
- package/templates/nuxt/app/assets/site.css +217 -0
- package/templates/nuxt/app/assets/spillway-brand.css +1 -0
- package/templates/nuxt/app/assets/spillway-brand.json +3 -0
- package/templates/nuxt/app/components/SearchPage.vue +36 -0
- package/templates/nuxt/app/components/SiteShell.vue +30 -0
- package/templates/nuxt/app/components/SpillwayMenu.vue +15 -0
- package/templates/nuxt/app/pages/[...slug].vue +54 -0
- package/templates/nuxt/nuxt.config.ts +18 -0
- package/templates/nuxt/package.json +32 -0
- package/templates/nuxt/public/spillway-suggest.js +133 -0
- package/templates/nuxt/scripts/brand.mjs +40 -0
- package/templates/nuxt/server/api/_spillway/view.get.ts +14 -0
- package/templates/nuxt/server/api/preview/exit.ts +13 -0
- package/templates/nuxt/server/api/preview/index.get.ts +31 -0
- package/templates/nuxt/server/api/revalidate.post.ts +45 -0
- package/templates/nuxt/server/api/search/suggest.get.ts +17 -0
- package/templates/nuxt/server/middleware/redirects.ts +17 -0
- package/templates/nuxt/server/routes/robots.txt.ts +7 -0
- package/templates/nuxt/server/routes/sitemap.xml.ts +18 -0
- package/templates/nuxt/server/utils/cache.ts +52 -0
- package/templates/nuxt/server/utils/preview.ts +6 -0
- package/templates/nuxt/server/utils/spillway.ts +211 -0
- package/templates/nuxt/shared/spillway.ts +60 -0
- package/templates/nuxt/tsconfig.json +9 -0
- package/templates/sveltekit/.env.example +27 -0
- package/templates/sveltekit/README.md +75 -0
- package/templates/sveltekit/_gitignore +11 -0
- package/templates/sveltekit/package.json +34 -0
- package/templates/sveltekit/scripts/brand.mjs +40 -0
- package/templates/sveltekit/src/app.d.ts +14 -0
- package/templates/sveltekit/src/app.html +11 -0
- package/templates/sveltekit/src/env.ts +20 -0
- package/templates/sveltekit/src/hooks.server.ts +26 -0
- package/templates/sveltekit/src/lib/components/SearchPage.svelte +41 -0
- package/templates/sveltekit/src/lib/components/SiteShell.svelte +36 -0
- package/templates/sveltekit/src/lib/components/SpillwayMenu.svelte +18 -0
- package/templates/sveltekit/src/lib/server/cache.ts +54 -0
- package/templates/sveltekit/src/lib/server/preview.ts +6 -0
- package/templates/sveltekit/src/lib/server/spillway.ts +203 -0
- package/templates/sveltekit/src/lib/site.css +204 -0
- package/templates/sveltekit/src/lib/spillway-brand.css +1 -0
- package/templates/sveltekit/src/lib/spillway-brand.json +3 -0
- package/templates/sveltekit/src/lib/view.ts +60 -0
- package/templates/sveltekit/src/routes/+layout.server.ts +4 -0
- package/templates/sveltekit/src/routes/+layout.svelte +8 -0
- package/templates/sveltekit/src/routes/[...path]/+page.server.ts +15 -0
- package/templates/sveltekit/src/routes/[...path]/+page.svelte +54 -0
- package/templates/sveltekit/src/routes/api/preview/+server.ts +30 -0
- package/templates/sveltekit/src/routes/api/preview/exit/+server.ts +10 -0
- package/templates/sveltekit/src/routes/api/revalidate/+server.ts +45 -0
- package/templates/sveltekit/src/routes/api/search/suggest/+server.ts +16 -0
- package/templates/sveltekit/src/routes/robots.txt/+server.ts +6 -0
- package/templates/sveltekit/src/routes/sitemap.xml/+server.ts +19 -0
- package/templates/sveltekit/static/spillway-suggest.js +133 -0
- package/templates/sveltekit/tsconfig.json +8 -0
- package/templates/sveltekit/vite.config.ts +17 -0
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# __PROJECT_NAME__
|
|
2
|
+
|
|
3
|
+
A SvelteKit front end on a [Spillway CMS](https://spillwaycms.com) site, made with `create-spillway`. Editors keep working in Spillway's admin; this site places the block area Spillway renders as HTML inside Svelte pages of its own, keeps pages in memory and drops them the moment a webhook says they changed.
|
|
4
|
+
|
|
5
|
+
## Set up
|
|
6
|
+
|
|
7
|
+
1. Install and start it:
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install
|
|
11
|
+
npm run dev # http://localhost:5173
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
2. Check `.env` (written for you; `.env.example` explains every value). `SPILLWAY_URL` is your Spillway site's address. The webhook and preview secrets were generated for you; keep the file out of version control.
|
|
15
|
+
3. In Spillway, under **Site settings → Notifications**, add a rule with the channel **Webhook** for each of the events published, unpublished, deleted, menu changed, redirects changed, site settings changed and brand published (`entity.published`, `entity.unpublished`, `entity.deleted`, `menu.updated`, `redirects.updated`, `site.updated`, `brand.published`), all pointing at `https://<this front end>/api/revalidate` with the secret `SPILLWAY_WEBHOOK_SECRET`. **Test send** on a rule should show as delivered in the **Outbox** below the rules. If you gave `create-spillway` the address this front end will have (`--deploy-url`) and a token with `site.settings`, it added these rules for you; check them there.
|
|
16
|
+
4. For draft previews, create an API token under the account menu → **API tokens** with `content.view_drafts` and set it as `SPILLWAY_TOKEN`. Release share links work without it. Previews need `SPILLWAY_PREVIEW_SECRET`.
|
|
17
|
+
|
|
18
|
+
## What is in it
|
|
19
|
+
|
|
20
|
+
| File | What it does |
|
|
21
|
+
| --- | --- |
|
|
22
|
+
| `vite.config.ts` | SvelteKit on the Node adapter |
|
|
23
|
+
| `src/env.ts` | The environment variables, read on the server from `$app/env/private` |
|
|
24
|
+
| `src/lib/server/spillway.ts` | The server-side client and `resolveView`: what a request shows (a Spillway page, the search page or a 404) with its head and the shell around it. Canonical links on `SITE_URL`; redirects; the signed preview cookie |
|
|
25
|
+
| `src/lib/server/cache.ts` | The in-memory cache, tagged with Spillway's cache tags and the path; `SPILLWAY_CACHE_SECONDS` bounds it |
|
|
26
|
+
| `src/routes/[...path]/` | Every path: `+page.server.ts` loads the view, `+page.svelte` writes the head (title, description, canonical, hreflang, Open Graph, JSON-LD, Spillway's CSS) and the page, the search page or the 404 |
|
|
27
|
+
| `src/lib/components/` | `SiteShell.svelte` (the site name, the `main` and `footer` menus, the language switcher, the preview bar), `SpillwayMenu.svelte`, `SearchPage.svelte` |
|
|
28
|
+
| `src/hooks.server.ts` | Spillway's redirects (301 and 302) before any page; the page's language on `<html>`; the 404 status |
|
|
29
|
+
| `src/routes/api/revalidate/+server.ts` | The webhook target: verifies `X-Spillway-Signature` and purges the paths and tags the event touched (`affectedByWebhook`) |
|
|
30
|
+
| `src/routes/api/preview/+server.ts`, `exit/+server.ts` | Starts a preview from a release share link or `?preview=1&secret=`, and ends it |
|
|
31
|
+
| `src/routes/api/search/suggest/+server.ts`, `static/spillway-suggest.js` | Search suggestions while visitors type |
|
|
32
|
+
| `src/routes/sitemap.xml/`, `robots.txt/` | `/sitemap.xml` from the published paths, `/robots.txt` |
|
|
33
|
+
| `scripts/brand.mjs` | Writes the brand stylesheet (`src/lib/spillway-brand.css`) with `@spillway-cms/brand`; runs before every build |
|
|
34
|
+
|
|
35
|
+
## How the page is put together
|
|
36
|
+
|
|
37
|
+
Spillway renders the block area: `client.renderHtml(path)` (`GET /api/public/render/<path>?format=html`) answers the page's blocks and regions as HTML, the CSS they need (the theme variables, the block styles and the page's block-style rules) and the few scripts some blocks run (the motion and media players), with the SEO data, the menus and the cache tags. This starter puts that HTML in the page as it is and owns everything around it: the routing, the head, the header and footer, the search page and the cache. The blocks look and behave as on Spillway, Form blocks post to Spillway itself (the form endpoint accepts posts from other origins) and media load from it. Write your own components around the block area; to change a block, change it in Spillway.
|
|
38
|
+
|
|
39
|
+
Pages are sent without SvelteKit's client scripts (`export const csr = false` in `src/routes/+layout.server.ts`): Spillway's HTML brings the scripts its blocks need and every link loads the next page as a whole. When you add components that need to run in the browser, turn `csr` on for those routes only, and keep `data-sveltekit-reload` on the block area's links (or `csr` off around it): scripts inside Spillway's HTML run only when the page loads as a whole.
|
|
40
|
+
|
|
41
|
+
## Search
|
|
42
|
+
|
|
43
|
+
`/search` (and `/es/search` and so on, on a site with several languages) is the search page: the published pages that match, ten a page, read from Spillway's search without `SPILLWAY_TOKEN`, so drafts never show. Spillway's Search block sends visitors there. While visitors type, `static/spillway-suggest.js` suggests pages from this site's `/api/search/suggest`, unless suggestions are off under **Site settings → Search**.
|
|
44
|
+
|
|
45
|
+
## Languages
|
|
46
|
+
|
|
47
|
+
On a site with more than one language (**Site settings → Languages**), every language but the default lives under its prefix (`/es/about`), as on Spillway, and the header has a language switcher: each language links to the translation of the page, or to that language's home page when the page has none. The `<html lang>`, the menus and the search page follow the page's language. The links come from `languageLinks` in `@spillway-cms/client` (`src/lib/server/spillway.ts`).
|
|
48
|
+
|
|
49
|
+
## Members
|
|
50
|
+
|
|
51
|
+
Signing members in on this front end (sign up, log in, the account page and the pages only members see) is coming: Spillway will be an OpenID Connect provider, so the starter signs members in with the library its framework already uses. Until then, members-only pages answer 404 here; members read them on Spillway's own pages.
|
|
52
|
+
|
|
53
|
+
## Previews
|
|
54
|
+
|
|
55
|
+
- **A release share link**: `/api/preview?path=/about&release=<release id>&token=<share token>`. Spillway checks the token.
|
|
56
|
+
- **The latest drafts**: `/api/preview?path=/about&preview=1&secret=<SPILLWAY_PREVIEW_SECRET>`, read through `SPILLWAY_TOKEN`.
|
|
57
|
+
|
|
58
|
+
Both set the preview cookie (a draft preview's is signed with `SPILLWAY_PREVIEW_SECRET` and lasts an hour, so a cookie written by hand opens nothing; Spillway checks a share link on every request), and show the preview bar; **Exit preview** (`/api/preview/exit`) ends it. Preview pages are never cached.
|
|
59
|
+
|
|
60
|
+
## The brand
|
|
61
|
+
|
|
62
|
+
`src/lib/spillway-brand.css` holds the brand as Spillway publishes it (colors, fonts, type scale, spacing as `--sw-*` variables), and every page carries it inline ahead of Spillway's CSS. `npm run brand` refreshes it, and every build does. When someone publishes a brand change, the `brand.published` webhook purges the cache and pages use the new brand until the next build writes it; set `DEPLOY_HOOK_URL` to have that webhook start the build.
|
|
63
|
+
|
|
64
|
+
With Tailwind v4, add `@tailwindcss/vite` to `vite.config.ts`, write `brandStylesheet(brand, { tailwind: 'v4' })` in `scripts/brand.mjs` and import `spillway-brand.css` after `@import "tailwindcss";` in a stylesheet of your own: `bg-primary`, `text-primary-700`, `font-heading` and `rounded-brand` then follow the brand.
|
|
65
|
+
|
|
66
|
+
## Deploy
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
npm run build
|
|
70
|
+
npm start # node build with .env loaded; PORT and HOST set the address
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Run it on any host with Node 22 (a container, Fly.io, Render, a VM) with the variables from `.env.example` and `SITE_URL` the public address, then point the webhook rules at it. The cache lives in the server process: with several instances or a CDN in front, purge those in `src/routes/api/revalidate/+server.ts` too (`affected.tags` are the tags Spillway sends as `Cache-Tag`). For a serverless host, swap `@sveltejs/adapter-node` for that host's adapter.
|
|
74
|
+
|
|
75
|
+
See [the headless docs](https://github.com/kwall-llc/spillway-cms/blob/main/docs/adapters.md) for the API and the starters.
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "spillway-sveltekit-starter",
|
|
3
|
+
"private": true,
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"description": "A SvelteKit front end on Spillway CMS, made with create-spillway",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"dev": "vite dev",
|
|
9
|
+
"brand": "node scripts/brand.mjs",
|
|
10
|
+
"prebuild": "node scripts/brand.mjs",
|
|
11
|
+
"build": "vite build",
|
|
12
|
+
"start": "node --env-file-if-exists=.env build",
|
|
13
|
+
"preview": "vite preview",
|
|
14
|
+
"prepare": "svelte-kit sync || echo ''",
|
|
15
|
+
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json"
|
|
16
|
+
},
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@spillway-cms/brand": "latest",
|
|
19
|
+
"@spillway-cms/client": "latest"
|
|
20
|
+
},
|
|
21
|
+
"devDependencies": {
|
|
22
|
+
"@sveltejs/adapter-node": "^6.0.5",
|
|
23
|
+
"@sveltejs/kit": "^3.4.0",
|
|
24
|
+
"@sveltejs/vite-plugin-svelte": "^7.3.1",
|
|
25
|
+
"@types/node": "^22.0.0",
|
|
26
|
+
"svelte": "^5.58.0",
|
|
27
|
+
"svelte-check": "^4.7.8",
|
|
28
|
+
"typescript": "^6.0.3",
|
|
29
|
+
"vite": "^8.3.8"
|
|
30
|
+
},
|
|
31
|
+
"engines": {
|
|
32
|
+
"node": ">=22.17"
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Writes the Spillway site's published brand (GET /api/public/brand) into the project with @spillway-cms/brand: the
|
|
2
|
+
// stylesheet with the --sw-* variables and fonts, and its version (the layout compares it with the live brand).
|
|
3
|
+
// Runs before every build (prebuild) and by hand with `npm run brand`. When Spillway cannot be reached it keeps the files
|
|
4
|
+
// it has, so a build never fails for it.
|
|
5
|
+
//
|
|
6
|
+
// Using Tailwind v4? Write brandStylesheet(brand, { tailwind: 'v4' }) below and import this file after
|
|
7
|
+
// @import "tailwindcss"; then bg-primary, text-primary-700, font-heading and rounded-brand follow the brand.
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import { brandStylesheet, fetchBrand } from '@spillway-cms/brand';
|
|
10
|
+
|
|
11
|
+
const CSS = 'src/lib/spillway-brand.css';
|
|
12
|
+
const JSON_FILE = 'src/lib/spillway-brand.json';
|
|
13
|
+
|
|
14
|
+
for (const file of ['.env']) {
|
|
15
|
+
try {
|
|
16
|
+
process.loadEnvFile(file); // never overrides a variable that is already set
|
|
17
|
+
} catch {
|
|
18
|
+
// no such file
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const url = process.env.SPILLWAY_URL;
|
|
23
|
+
if (!url) {
|
|
24
|
+
console.warn(`[brand] SPILLWAY_URL is not set; keeping ${CSS}`);
|
|
25
|
+
} else {
|
|
26
|
+
try {
|
|
27
|
+
const site = process.env.SPILLWAY_SITE ? { site: process.env.SPILLWAY_SITE, token: process.env.SPILLWAY_TOKEN } : {};
|
|
28
|
+
const brand = await fetchBrand(url, { ...site, requestInit: { signal: AbortSignal.timeout(15_000) } });
|
|
29
|
+
const css = brandStylesheet(brand);
|
|
30
|
+
if (fs.existsSync(CSS) && fs.readFileSync(CSS, 'utf8') === css) {
|
|
31
|
+
console.log(`[brand] version ${brand.version} unchanged`);
|
|
32
|
+
} else {
|
|
33
|
+
fs.writeFileSync(CSS, css);
|
|
34
|
+
fs.writeFileSync(JSON_FILE, JSON.stringify({ version: brand.version }, null, 2) + '\n');
|
|
35
|
+
console.log(`[brand] version ${brand.version} written to ${CSS}`);
|
|
36
|
+
}
|
|
37
|
+
} catch (err) {
|
|
38
|
+
console.warn(`[brand] could not fetch the brand from ${url} (${err instanceof Error ? err.message : err}); keeping ${CSS}`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// See https://svelte.dev/docs/kit/types#app.d.ts
|
|
2
|
+
declare global {
|
|
3
|
+
namespace App {
|
|
4
|
+
interface Locals {
|
|
5
|
+
/** Set by the page's load: the language and the motion level for <html> (src/hooks.server.ts writes them). */
|
|
6
|
+
lang?: string;
|
|
7
|
+
motion?: string | null;
|
|
8
|
+
/** Set by the page's load when there is no page at the address, so the answer is a 404. */
|
|
9
|
+
notFound?: boolean;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export {};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="%spillway.lang%"%spillway.motion%>
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
6
|
+
%sveltekit.head%
|
|
7
|
+
</head>
|
|
8
|
+
<body>
|
|
9
|
+
<div style="display: contents">%sveltekit.body%</div>
|
|
10
|
+
</body>
|
|
11
|
+
</html>
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The environment variables this front end reads, on the server only (`$app/env/private`). `.env` holds them in
|
|
3
|
+
* development (create-spillway wrote it; .env.example explains each), and they are read when the server starts, never
|
|
4
|
+
* written into the build: `npm start` loads .env, a host sets them itself.
|
|
5
|
+
*/
|
|
6
|
+
import { defineEnvVars } from '@sveltejs/kit/env';
|
|
7
|
+
|
|
8
|
+
const optional = (value: string | undefined) => value || undefined;
|
|
9
|
+
const address = (fallback: string) => (value: string | undefined) => (value || fallback).replace(/\/+$/, '');
|
|
10
|
+
|
|
11
|
+
export const variables = defineEnvVars({
|
|
12
|
+
SPILLWAY_URL: { description: 'The Spillway site this front end reads, its public address.', schema: address('http://localhost:3000') },
|
|
13
|
+
SPILLWAY_TOKEN: { description: 'An API token with content.view_drafts, for draft previews; optional.', schema: optional },
|
|
14
|
+
SPILLWAY_SITE: { description: "The site's key on a multisite instance; optional.", schema: optional },
|
|
15
|
+
SPILLWAY_WEBHOOK_SECRET: { description: 'The secret of the webhook rules that post to /api/revalidate.', schema: optional },
|
|
16
|
+
SPILLWAY_PREVIEW_SECRET: { description: 'Guards /api/preview?preview=1 and signs its cookie.', schema: optional },
|
|
17
|
+
DEPLOY_HOOK_URL: { description: 'A deploy hook the revalidation route calls on brand.published; optional.', schema: optional },
|
|
18
|
+
SITE_URL: { description: "This front end's own address.", schema: address('http://localhost:5173') },
|
|
19
|
+
SPILLWAY_CACHE_SECONDS: { description: 'Seconds a page stays in the in-memory cache; 0 turns it off.', schema: optional },
|
|
20
|
+
});
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every request passes here. Spillway's redirects (Marketing → Redirects) are answered before any page, as on a
|
|
3
|
+
* Spillway-rendered site: 301 or 302 to the target, with the query string kept; the list is cached and purged by the
|
|
4
|
+
* redirects.updated webhook. Pages then get the language and motion level of what they show on <html>, and the 404
|
|
5
|
+
* status when there is nothing at the address.
|
|
6
|
+
*/
|
|
7
|
+
import type { Handle } from '@sveltejs/kit/hooks';
|
|
8
|
+
import { redirectFor } from './lib/server/spillway';
|
|
9
|
+
|
|
10
|
+
const SKIP = ['/api/', '/_app/'];
|
|
11
|
+
const attr = (value: string) => value.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<');
|
|
12
|
+
|
|
13
|
+
export const handle: Handle = async ({ event, resolve }) => {
|
|
14
|
+
const { pathname, search } = event.url;
|
|
15
|
+
const method = event.request.method;
|
|
16
|
+
if ((method === 'GET' || method === 'HEAD') && !SKIP.some((p) => pathname.startsWith(p))) {
|
|
17
|
+
const hit = await redirectFor(pathname);
|
|
18
|
+
if (hit) return new Response(null, { status: hit.status, headers: { location: search && !hit.to.includes('?') ? `${hit.to}${search}` : hit.to, 'cache-control': 'no-store' } });
|
|
19
|
+
}
|
|
20
|
+
const response = await resolve(event, {
|
|
21
|
+
transformPageChunk: ({ html }) =>
|
|
22
|
+
html.replace('%spillway.lang%', attr(event.locals.lang ?? 'en')).replace('%spillway.motion%', event.locals.motion ? ` data-sw-motion="${attr(event.locals.motion)}"` : ''),
|
|
23
|
+
});
|
|
24
|
+
if (event.locals.notFound && response.status === 200) return new Response(response.body, { status: 404, statusText: 'Not Found', headers: response.headers });
|
|
25
|
+
return response;
|
|
26
|
+
};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
<script lang="ts">
|
|
2
|
+
/**
|
|
3
|
+
* The search page: a GET form, the published pages that match (read as a visitor, so drafts never show) and a pager.
|
|
4
|
+
* With suggestions on in Spillway (Site settings → Search), static/spillway-suggest.js suggests pages while visitors type.
|
|
5
|
+
*/
|
|
6
|
+
import type { SearchView, Shell } from '../view';
|
|
7
|
+
|
|
8
|
+
let { search, shell }: { search: SearchView; shell: Shell } = $props();
|
|
9
|
+
const pageHref = (n: number) => `${shell.searchPath}?q=${encodeURIComponent(search.q)}${n > 1 ? `&page=${n}` : ''}`;
|
|
10
|
+
</script>
|
|
11
|
+
|
|
12
|
+
<section class="search-page">
|
|
13
|
+
<h1>Search</h1>
|
|
14
|
+
<form class="search-form" role="search" method="get" action={shell.searchPath}>
|
|
15
|
+
<label class="sw-visually-hidden" for="search-q">Search this site</label>
|
|
16
|
+
<input id="search-q" type="search" name="q" value={search.q} placeholder="Search" enterkeyhint="search" data-sw-suggest={shell.suggestions ? '' : undefined} data-sw-locale={shell.suggestions ? shell.lang : undefined} />
|
|
17
|
+
<button type="submit">Search</button>
|
|
18
|
+
</form>
|
|
19
|
+
{#if search.error}
|
|
20
|
+
<p role="alert">Search is not available right now. Please try again later.</p>
|
|
21
|
+
{:else if search.q}
|
|
22
|
+
<p role="status">{search.total === 1 ? '1 result' : `${search.total} results`} for “{search.q}”</p>
|
|
23
|
+
{#if search.results.length}
|
|
24
|
+
<ol class="search-results">
|
|
25
|
+
{#each search.results as r (r.id)}
|
|
26
|
+
<li>
|
|
27
|
+
<h2><a href={r.href}>{r.title}</a></h2>
|
|
28
|
+
{#if r.snippet.length}<p>{#each r.snippet as part, i (i)}{#if part.hit}<mark>{part.text}</mark>{:else}{part.text}{/if}{/each}</p>{/if}
|
|
29
|
+
</li>
|
|
30
|
+
{/each}
|
|
31
|
+
</ol>
|
|
32
|
+
{/if}
|
|
33
|
+
{#if search.pages > 1}
|
|
34
|
+
<nav class="search-pager" aria-label="Result pages">
|
|
35
|
+
{#if search.page > 1}<a href={pageHref(search.page - 1)} rel="prev">Previous</a>{/if}
|
|
36
|
+
<span>Page {search.page} of {search.pages}</span>
|
|
37
|
+
{#if search.page < search.pages}<a href={pageHref(search.page + 1)} rel="next">Next</a>{/if}
|
|
38
|
+
</nav>
|
|
39
|
+
{/if}
|
|
40
|
+
{/if}
|
|
41
|
+
</section>
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
<script lang="ts">
|
|
2
|
+
/** The shell around every page: the site name, the main and footer menus, the language switcher and the preview bar. */
|
|
3
|
+
import type { Snippet } from 'svelte';
|
|
4
|
+
import type { Shell } from '../view';
|
|
5
|
+
import SpillwayMenu from './SpillwayMenu.svelte';
|
|
6
|
+
|
|
7
|
+
let { shell, children }: { shell: Shell; children: Snippet } = $props();
|
|
8
|
+
</script>
|
|
9
|
+
|
|
10
|
+
<a class="skip-link" href="#main">Skip to content</a>
|
|
11
|
+
{#if shell.preview}
|
|
12
|
+
<div class="preview-bar" role="status">
|
|
13
|
+
<span>Preview: you are seeing unpublished content.</span>
|
|
14
|
+
<a href="/api/preview/exit">Exit preview</a>
|
|
15
|
+
</div>
|
|
16
|
+
{/if}
|
|
17
|
+
<header class="site-header">
|
|
18
|
+
<a class="site-name" href="/">{shell.siteName}</a>
|
|
19
|
+
<nav class="site-nav" aria-label="Main"><SpillwayMenu items={shell.main} /></nav>
|
|
20
|
+
{#if shell.languages.length}
|
|
21
|
+
<nav class="language-switcher" aria-label="Language">
|
|
22
|
+
<ul>
|
|
23
|
+
{#each shell.languages as l (l.locale)}
|
|
24
|
+
<li><a href={l.href} hreflang={l.locale} lang={l.locale} aria-current={l.current ? 'true' : undefined}>{l.label}</a></li>
|
|
25
|
+
{/each}
|
|
26
|
+
</ul>
|
|
27
|
+
</nav>
|
|
28
|
+
{/if}
|
|
29
|
+
</header>
|
|
30
|
+
<main id="main">{@render children()}</main>
|
|
31
|
+
<footer class="site-footer">
|
|
32
|
+
<nav class="site-nav" aria-label="Footer"><SpillwayMenu items={shell.footer} /></nav>
|
|
33
|
+
{#each shell.footerNote as line, i (i)}
|
|
34
|
+
<p>{line}</p>
|
|
35
|
+
{/each}
|
|
36
|
+
</footer>
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
<script lang="ts">
|
|
2
|
+
/** A Spillway menu (Structure → Menus) as a nested list; the item for the current page is marked. */
|
|
3
|
+
import type { PublicMenuItem } from '@spillway-cms/client';
|
|
4
|
+
import SpillwayMenu from './SpillwayMenu.svelte';
|
|
5
|
+
|
|
6
|
+
let { items }: { items: PublicMenuItem[] } = $props();
|
|
7
|
+
</script>
|
|
8
|
+
|
|
9
|
+
{#if items.length}
|
|
10
|
+
<ul>
|
|
11
|
+
{#each items as item (`${item.href}:${item.label}`)}
|
|
12
|
+
<li class={item.current ? 'is-current' : undefined}>
|
|
13
|
+
<a href={item.href} aria-current={item.current ? 'page' : undefined} target={item.newTab ? '_blank' : undefined} rel={item.newTab ? 'noopener' : undefined}>{item.label}</a>
|
|
14
|
+
{#if item.children?.length}<SpillwayMenu items={item.children} />{/if}
|
|
15
|
+
</li>
|
|
16
|
+
{/each}
|
|
17
|
+
</ul>
|
|
18
|
+
{/if}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A small in-memory cache for what the site reads from Spillway, keyed by name and tagged with Spillway's cache tags
|
|
3
|
+
* (`entity:<id>`, `type:page`, `site:<id>`, `menu:main`, ...) and the page's path. src/pages/api/revalidate.ts purges it
|
|
4
|
+
* when a webhook says something changed; entries also expire after SPILLWAY_CACHE_SECONDS (300 by default, 0 turns the
|
|
5
|
+
* cache off) so a missed webhook heals itself.
|
|
6
|
+
*
|
|
7
|
+
* It lives in this server process. With more than one instance, or a CDN in front, purge those from the webhook too
|
|
8
|
+
* (`affected.tags` carries the tags Spillway sends in its Cache-Tag header).
|
|
9
|
+
*/
|
|
10
|
+
import { SPILLWAY_CACHE_SECONDS } from '$app/env/private';
|
|
11
|
+
|
|
12
|
+
interface Entry {
|
|
13
|
+
value: unknown;
|
|
14
|
+
tags: Set<string>;
|
|
15
|
+
expires: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const store = new Map<string, Entry>();
|
|
19
|
+
|
|
20
|
+
function ttlMs(): number {
|
|
21
|
+
const raw = Number(SPILLWAY_CACHE_SECONDS ?? 300);
|
|
22
|
+
return Number.isFinite(raw) && raw > 0 ? raw * 1000 : 0;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The cached value under `key`, or what `load` answers, stored with its tags unless `keep` is false. Errors are never
|
|
27
|
+
* cached.
|
|
28
|
+
*/
|
|
29
|
+
export async function cached<T>(key: string, load: () => Promise<{ value: T; tags: string[]; keep?: boolean }>): Promise<T> {
|
|
30
|
+
const ttl = ttlMs();
|
|
31
|
+
const hit = store.get(key);
|
|
32
|
+
if (hit && hit.expires > Date.now()) return hit.value as T;
|
|
33
|
+
const { value, tags, keep = true } = await load();
|
|
34
|
+
if (ttl > 0 && keep) store.set(key, { value, tags: new Set(tags), expires: Date.now() + ttl });
|
|
35
|
+
return value;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Drops every entry carrying one of `tags` or tagged with one of `paths` (as `path:<path>`). Returns how many went. */
|
|
39
|
+
export function purge(tags: string[], paths: string[] = []): number {
|
|
40
|
+
const wanted = new Set([...tags, ...paths.map((p) => `path:${p}`)]);
|
|
41
|
+
let dropped = 0;
|
|
42
|
+
for (const [key, entry] of store) {
|
|
43
|
+
if ([...entry.tags].some((t) => wanted.has(t))) {
|
|
44
|
+
store.delete(key);
|
|
45
|
+
dropped += 1;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return dropped;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Empties the cache. */
|
|
52
|
+
export function purgeAll(): void {
|
|
53
|
+
store.clear();
|
|
54
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { PREVIEW_COOKIE } from '@spillway-cms/client';
|
|
2
|
+
|
|
3
|
+
/** The Set-Cookie value for the preview cookie: this site only, never readable by scripts. */
|
|
4
|
+
export function previewCookie(value: string, secure: boolean, maxAge?: number): string {
|
|
5
|
+
return [`${PREVIEW_COOKIE}=${encodeURIComponent(value)}`, 'Path=/', 'HttpOnly', 'SameSite=Lax', ...(secure ? ['Secure'] : []), ...(maxAge !== undefined ? [`Max-Age=${maxAge}`] : [])].join('; ');
|
|
6
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Everything this front end reads from Spillway, on the server only (src/lib/server is never sent to a browser): the
|
|
3
|
+
* client (with SPILLWAY_TOKEN), the in-memory cache in ./cache.ts, and `resolveView`, which turns a request into what a
|
|
4
|
+
* page shows: a Spillway page with its block area rendered by Spillway (the HTML render), the search page, or a 404, with
|
|
5
|
+
* the shell around it (the site name, menus, language switcher, brand and preview bar). The Svelte pages only lay that out.
|
|
6
|
+
*/
|
|
7
|
+
import {
|
|
8
|
+
SpillwayError,
|
|
9
|
+
createClient,
|
|
10
|
+
languageLinks,
|
|
11
|
+
localizedPath,
|
|
12
|
+
previewFromRequest,
|
|
13
|
+
splitLocalePath,
|
|
14
|
+
type PreviewState,
|
|
15
|
+
type PublicRedirect,
|
|
16
|
+
type PublicRender,
|
|
17
|
+
type PublicSite,
|
|
18
|
+
} from '@spillway-cms/client';
|
|
19
|
+
import { SITE_URL, SPILLWAY_PREVIEW_SECRET, SPILLWAY_SITE, SPILLWAY_TOKEN, SPILLWAY_URL } from '$app/env/private';
|
|
20
|
+
import type { HeadData, SearchHit, SearchView, Shell, View } from '../view';
|
|
21
|
+
// The brand as the last build wrote it (scripts/brand.mjs); a newer published brand is inlined until the next build.
|
|
22
|
+
import builtBrand from '../spillway-brand.json';
|
|
23
|
+
import { cached } from './cache';
|
|
24
|
+
|
|
25
|
+
export { SITE_URL, SPILLWAY_URL };
|
|
26
|
+
|
|
27
|
+
/** Tag of the entries every webhook purges: the site settings, the brand, the menus, the redirects and the path list. */
|
|
28
|
+
export const SHELL_TAG = 'shell';
|
|
29
|
+
|
|
30
|
+
/** The server-side client. The preview secret checks /api/preview and signs the draft preview cookie. */
|
|
31
|
+
export const spillway = createClient({ baseUrl: SPILLWAY_URL, token: SPILLWAY_TOKEN, site: SPILLWAY_SITE, previewSecret: SPILLWAY_PREVIEW_SECRET });
|
|
32
|
+
|
|
33
|
+
/** Search and suggestions read as a visitor: without the token, which would also find drafts. */
|
|
34
|
+
export const visitor = spillway.with({ token: undefined, site: undefined });
|
|
35
|
+
|
|
36
|
+
/** The preview this request is in, from the cookie /api/preview set; null for a visitor. */
|
|
37
|
+
export function readPreview(request: Request): PreviewState | null {
|
|
38
|
+
return previewFromRequest(request, { secret: spillway.options.previewSecret });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// ---------- What a page shows (the types are in ../view.ts) ----------
|
|
42
|
+
|
|
43
|
+
/** A page with its block area rendered by Spillway (`client.renderHtml`). */
|
|
44
|
+
export type HtmlPage = PublicRender & { html: NonNullable<PublicRender['html']> };
|
|
45
|
+
|
|
46
|
+
/** Query parameters that open a preview rather than reach the page's blocks. */
|
|
47
|
+
const PREVIEW_PARAMS = new Set(['release', 'workstream', 'token', 'preview', 'secret']);
|
|
48
|
+
|
|
49
|
+
/** The site settings (name, locales, search), cached; null when Spillway does not answer. */
|
|
50
|
+
export function loadSite(preview: PreviewState | null = null): Promise<PublicSite | null> {
|
|
51
|
+
const load = () => spillway.withPreview(preview).site();
|
|
52
|
+
return (preview ? load() : cached('site', async () => ({ value: await load(), tags: [SHELL_TAG] }))).catch(() => null);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The page at `path`, or null when Spillway has none. A preview skips the cache; so does a page whose blocks read the query. */
|
|
56
|
+
export async function loadPage(path: string, query: Record<string, string>, preview: PreviewState | null): Promise<HtmlPage | null> {
|
|
57
|
+
const fetchPage = async (params: Record<string, string>) => {
|
|
58
|
+
try {
|
|
59
|
+
return await spillway.renderHtml(path, { previewState: preview, params });
|
|
60
|
+
} catch (err) {
|
|
61
|
+
// Not found, or members-only (signing members in on this front end is still to come; see README.md, Members).
|
|
62
|
+
if (err instanceof SpillwayError && (err.status === 404 || err.code === 'members_only')) return null;
|
|
63
|
+
throw err;
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
if (preview) return fetchPage(query);
|
|
67
|
+
const page = await cached(`render:${path}`, async () => {
|
|
68
|
+
const value = await fetchPage({});
|
|
69
|
+
// A 404 is not kept: the page may be published any moment.
|
|
70
|
+
return { value, tags: value ? [...value.cacheTags, `path:${path}`] : [], keep: value !== null };
|
|
71
|
+
});
|
|
72
|
+
// Exposed filters, a pager or a calendar read the query string: render this request on its own (Spillway caches it briefly).
|
|
73
|
+
return page?.queryDependent && Object.keys(query).length ? fetchPage(query) : page;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function loadShellParts(locale: string, preview: PreviewState | null) {
|
|
77
|
+
const c = spillway.withPreview(preview);
|
|
78
|
+
const read = <T>(key: string, load: () => Promise<T>): Promise<T | null> =>
|
|
79
|
+
(preview ? load() : cached(key, async () => ({ value: await load(), tags: [SHELL_TAG] }))).catch(() => null);
|
|
80
|
+
const [brand, main, footer] = await Promise.all([
|
|
81
|
+
read('brand', () => c.brand()),
|
|
82
|
+
read(`menu:main:${locale}`, () => c.menu('main', { locale })),
|
|
83
|
+
read(`menu:footer:${locale}`, () => c.menu('footer', { locale })),
|
|
84
|
+
]);
|
|
85
|
+
return { brand, main: main?.items ?? [], footer: footer?.items ?? [] };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** A URL on the Spillway site rewritten onto this front end (canonical links and alternates name Spillway's pages). */
|
|
89
|
+
export function onSite(href: string | undefined, origin: string): string | undefined {
|
|
90
|
+
if (!href || !origin) return href;
|
|
91
|
+
return href === origin || href.startsWith(`${origin}/`) ? SITE_URL + href.slice(origin.length) : href;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Spillway marks the matched words in a search snippet «like this»; the parts, for a <mark> around each match. */
|
|
95
|
+
export function snippetParts(snippet: string): SearchHit['snippet'] {
|
|
96
|
+
const parts: SearchHit['snippet'] = [];
|
|
97
|
+
for (const [i, text] of snippet.split(/[«»]/).entries()) if (text) parts.push({ text, hit: i % 2 === 1 });
|
|
98
|
+
return parts;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const jsonLd = (value: unknown) => JSON.stringify(value).replace(/</g, '\\u003c');
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Spillway's HTML with the form posts and downloads pointed at Spillway itself: the Form block posts to
|
|
105
|
+
* /api/forms/<key>/submit and the Collection block links its downloads under /api/collections/, which live on Spillway
|
|
106
|
+
* (the form endpoint accepts posts from other origins). Media URLs are already absolute.
|
|
107
|
+
*/
|
|
108
|
+
export function pointApiAtSpillway(html: string, origin: string): string {
|
|
109
|
+
return origin ? html.replace(/ action="\/api\/forms\//g, ` action="${origin}/api/forms/`).replace(/ href="\/api\/collections\//g, ` href="${origin}/api/collections/`) : html;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** What the request at `path` (with its query string) shows. */
|
|
113
|
+
export async function resolveView(path: string, query: Record<string, string>, request: Request): Promise<View> {
|
|
114
|
+
const preview = readPreview(request);
|
|
115
|
+
const params = Object.fromEntries(Object.entries(query).filter(([k]) => !PREVIEW_PARAMS.has(k)));
|
|
116
|
+
const site = await loadSite(preview);
|
|
117
|
+
const local = site ? splitLocalePath(site, path) : { locale: 'en', path, prefixed: false };
|
|
118
|
+
const isSearch = local.path === '/search';
|
|
119
|
+
const page = isSearch ? null : await loadPage(path, params, preview);
|
|
120
|
+
const locale = page?.locale ?? local.locale;
|
|
121
|
+
const parts = await loadShellParts(locale, preview);
|
|
122
|
+
const siteName = site?.name ?? page?.site.name ?? 'Spillway site';
|
|
123
|
+
const searchPath = site ? localizedPath(site, locale, '/search') : '/search';
|
|
124
|
+
const shell: Shell = {
|
|
125
|
+
siteName,
|
|
126
|
+
footerNote: site?.footerNote?.split('\n').filter(Boolean) ?? [],
|
|
127
|
+
lang: locale,
|
|
128
|
+
main: page?.menus.main ?? parts.main,
|
|
129
|
+
footer: page?.menus.footer ?? parts.footer,
|
|
130
|
+
languages: [],
|
|
131
|
+
brandCss: parts.brand && parts.brand.version !== builtBrand.version ? parts.brand.css : null,
|
|
132
|
+
suggestions: site?.searchSuggestions ?? true,
|
|
133
|
+
searchPath,
|
|
134
|
+
preview: Boolean(preview),
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
if (page) {
|
|
138
|
+
const origin = page.site.origin;
|
|
139
|
+
shell.languages = site ? languageLinks(site, { locale: page.locale, path: page.path, alternates: page.seo.alternates }) : [];
|
|
140
|
+
const head: HeadData = {
|
|
141
|
+
title: page.seo.title,
|
|
142
|
+
...(page.seo.description ? { description: page.seo.description } : {}),
|
|
143
|
+
...(page.seo.canonical ? { canonical: onSite(page.seo.canonical, origin) } : {}),
|
|
144
|
+
alternates: page.seo.alternates.map((a) => ({ hreflang: a.hreflang, href: onSite(a.href, origin) ?? a.href })),
|
|
145
|
+
...(page.seo.ogImage ? { ogImage: page.seo.ogImage } : {}),
|
|
146
|
+
noindex: page.seo.noindex,
|
|
147
|
+
jsonLd: page.seo.jsonLd.map(jsonLd),
|
|
148
|
+
css: [page.html.css.theme, page.html.css.blocks, page.html.css.styles].filter(Boolean),
|
|
149
|
+
motion: page.html.motion,
|
|
150
|
+
};
|
|
151
|
+
return { kind: 'page', shell, head, body: pointApiAtSpillway(page.html.body, origin), scripts: page.html.scripts };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const head: HeadData = { title: siteName, alternates: [], noindex: true, jsonLd: [], css: site?.themeCss ? [site.themeCss] : [], motion: null };
|
|
155
|
+
if (isSearch) {
|
|
156
|
+
const q = (query.q ?? '').trim().slice(0, 200);
|
|
157
|
+
const pageNo = Math.max(1, Math.min(100, Number.parseInt(query.page ?? '1', 10) || 1));
|
|
158
|
+
shell.languages = site ? languageLinks(site, { locale, alternates: [] }).map((l) => ({ ...l, href: `${localizedPath(site, l.locale, '/search')}${q ? `?q=${encodeURIComponent(q)}` : ''}`, translated: true })) : [];
|
|
159
|
+
const search: SearchView = { q, page: pageNo, pages: 0, total: 0, results: [] };
|
|
160
|
+
if (q) {
|
|
161
|
+
try {
|
|
162
|
+
const found = await visitor.search(q, { locale, page: pageNo, limit: 10 });
|
|
163
|
+
search.results = found.items.filter((r) => r.path).map((r) => ({ id: r.id, title: r.title, href: r.path!, snippet: snippetParts(r.snippet) }));
|
|
164
|
+
search.total = found.total;
|
|
165
|
+
search.pages = Math.ceil(found.total / (found.limit || 10));
|
|
166
|
+
} catch (err) {
|
|
167
|
+
search.error = err instanceof Error ? err.message : String(err);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return { kind: 'search', shell, head: { ...head, title: q ? `Search: ${q} | ${siteName}` : `Search | ${siteName}` }, search };
|
|
171
|
+
}
|
|
172
|
+
shell.languages = site ? languageLinks(site, { locale, alternates: [] }) : [];
|
|
173
|
+
return { kind: 'not-found', shell, head: { ...head, title: `Page not found | ${siteName}` } };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// ---------- Redirects ----------
|
|
177
|
+
|
|
178
|
+
/** Redirect matching as Spillway does it: case-insensitive, without a trailing slash or a query. */
|
|
179
|
+
export function normalizePath(raw: string): string {
|
|
180
|
+
let p = raw;
|
|
181
|
+
try {
|
|
182
|
+
p = decodeURIComponent(p);
|
|
183
|
+
} catch {
|
|
184
|
+
// keep it as it is; a malformed escape never matches a stored path
|
|
185
|
+
}
|
|
186
|
+
const q = p.indexOf('?');
|
|
187
|
+
if (q >= 0) p = p.slice(0, q);
|
|
188
|
+
p = p.replace(/\/{2,}/g, '/').toLowerCase();
|
|
189
|
+
if (!p.startsWith('/')) p = `/${p}`;
|
|
190
|
+
if (p.length > 1) p = p.replace(/\/+$/, '');
|
|
191
|
+
return p;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** The redirect from `path` in Spillway's list (Marketing → Redirects), if there is one. */
|
|
195
|
+
export async function redirectFor(path: string): Promise<PublicRedirect | undefined> {
|
|
196
|
+
try {
|
|
197
|
+
const list = await cached('redirects', async () => ({ value: await spillway.redirects(), tags: [SHELL_TAG, 'redirects'] }));
|
|
198
|
+
const want = normalizePath(path);
|
|
199
|
+
return list.find((r) => normalizePath(r.from) === want);
|
|
200
|
+
} catch {
|
|
201
|
+
return undefined; // an older Spillway without the list, or Spillway is down: serve the page
|
|
202
|
+
}
|
|
203
|
+
}
|