@foliwake/server
Generated from
packages/server/README.md, the README published with the package on npm.
@foliwake/server is the server toolkit for any app that shows Foliwake pages, with no framework dependency: Web Request/Response and plain functions. It parses the app's foliwake.remote.json, reads a page's body from the site's live or preview origin with the credential, checks and prepares it per request, serves the page's code release and pictures through your app's origin (proxies), builds a Content-Security-Policy, and computes preload hints. @foliwake/next is built on it; use this package directly with another server framework (a Vite or Remix server, Hono, Express with Web adapters, a worker).
| Entry | What |
|---|---|
@foliwake/server/config | loadFoliwakeConfig, parseFoliwakeConfig, clientSettings, pageAllowed, FoliwakeConfigError |
@foliwake/server/origin | createOriginClient: the only place a password is read (per request, from the variable the config names) |
@foliwake/server/page | readEnvelope (primitive inputs: safe inside a cache function), preparePage, FoliwakePageError |
@foliwake/server/handlers | codeHandler, mediaHandler: the code and media proxies |
@foliwake/server/html | the strict body check: checkPlainBody, checkBody, serialize, srcsetCandidates |
@foliwake/server/csp | foliwakeCsp |
@foliwake/server/preload | preloadHints: modulepreload and stylesheet hints for a page's blocks |
@foliwake/server/hook | verifyFoliwakeSignature, parseFoliwakeHook: the signed hook a Foliwake server sends after a change |
@foliwake/server/handler | createFoliwakeHandler: every Foliwake route of an app (code, media, hook, health) as one (request) => Promise<Response> |
@foliwake/server/hook-endpoint | createHookEndpoint: the hook endpoint without a framework (verify, parse, expire, answer) |
@foliwake/server/discovery | fetchDiscovery, parseDiscovery: the site's /.well-known/foliwake.json |
@foliwake/server/resolve | loadAppConfig, readConfigSnapshot, configFromSnapshot: FOLIWAKE_URL + discovery + the optional version 3 file, or a version 2 file |
@foliwake/server/schemas/remote-2.schema.json | the JSON Schema of the config file (version 2) |
@foliwake/server/schemas/remote-3.schema.json | the JSON Schema of the optional version 3 file (overrides) |
Install
The packages are published on npm (npmjs.com) under the @foliwake scope; no registry setup or token is needed. Install an exact version, the same for every @foliwake/* package:
pnpm add @foliwake/server@0.3.0The config file sits in the app's root and holds no secrets, only the names of the variables with passwords or keys:
{
"$schema": "./node_modules/@foliwake/server/schemas/remote-2.schema.json",
"version": 2,
"site": "mysite",
"live": { "url": "https://mysite.example.org" },
"preview": { "url": "https://preview.mysite.example.org", "auth": { "type": "basic", "username": "preview", "passwordEnv": "MYSITE_PREVIEW_TOKEN" } },
"app": {
"pages": ["/**"],
"proxies": { "code": "/foliwake-code", "media": "/foliwake-media", "pages": null },
"blocks": { "entry": "scripts/blocks.js", "contract": "foliwake-blocks/2", "eventPrefix": "demo" },
"revalidate": 300
}
}An endpoint is open (no auth), behind HTTP Basic ("type": "basic"), or behind a delivery that checks service tokens (for example an edge worker in front of the site's storage):
"live": {
"url": "https://mysite.worker.example.org",
"auth": { "type": "service-token", "issuer": "mysite-app", "kid": "mysite-app-2026-11", "privateKeyEnv": "MYSITE_LIVE_SIGNING_KEY" }
}With service-token, every origin request carries Authorization: Bearer <JWT>, signed for that request alone: ES256, header kid, claims iss (= issuer, the delivery's TOKEN_ISSUER), aud: site:<site>, iat, exp = iat + 60 and path, the exact path of the request as sent, without the query (/lessons/a.plain.html, /lessons/query-index.json). A token for a page does not open its .plain.html. The variable holds the ES256 private key as JWK JSON text; the delivery holds the public key under the same kid. Tokens are never cached, reused or logged.
Minimal example
import { loadFoliwakeConfig } from '@foliwake/server/config';
import { createOriginClient } from '@foliwake/server/origin';
import { preparePage, readEnvelope } from '@foliwake/server/page';
const config = await loadFoliwakeConfig(); // FOLIWAKE_REMOTE, else ./foliwake.remote.json
const client = createOriginClient(config, process.env);
const envelope = await readEnvelope(config, client, config.site, 'live', '/lessons/a'); // cacheable
const page = preparePage(config, envelope); // per request: checked, rewritten, serialisable
console.log(page.identity, page.blocks);Examples
A page endpoint for the browser, with a cache of envelopes
Cache only the envelope (what the origin answered) and prepare per request, so your callbacks (rewriteLink, transform) always run on the current code. The prepared page is what @foliwake/client or @foliwake/react mount.
import { loadFoliwakeConfig } from '@foliwake/server/config';
import { createOriginClient } from '@foliwake/server/origin';
import { FoliwakePageError, preparePage, readEnvelope, type PageEnvelope } from '@foliwake/server/page';
import { preloadHints } from '@foliwake/server/preload';
const config = await loadFoliwakeConfig();
const client = createOriginClient(config, process.env);
const cache = new Map<string, { at: number; envelope: PageEnvelope }>();
async function liveEnvelope(path: string): Promise<PageEnvelope> {
const hit = cache.get(path);
if (hit && Date.now() - hit.at < config.app!.revalidate * 1000) return hit.envelope;
const envelope = await readEnvelope(config, client, config.site, 'live', path);
cache.set(path, { at: Date.now(), envelope });
return envelope;
}
/** GET /api/page?path=/lessons/a */
export async function pageEndpoint(request: Request): Promise<Response> {
const path = new URL(request.url).searchParams.get('path') ?? '/';
try {
const page = preparePage(config, await liveEnvelope(path), { rewriteLink: (href) => `/learn${href}` });
page.preload = await preloadHints(config, client, page);
return Response.json(page, { headers: { 'Cache-Control': 'private, no-store' } });
} catch (error) {
if (error instanceof FoliwakePageError && (error.kind === 'not_found' || error.kind === 'not_allowed')) return new Response(null, { status: 404 });
throw error;
}
}Refresh the cache when the site changes
A Foliwake server whose site lists your app as a hook target POSTs delivery.settled once a change is live and the caches in front of the origin serve it. The body names the live generation, and either the changed paths (pages, at most 100: pages and other files such as an index) or all: true. Check the signature on the raw body, then drop what you cached:
import { parseFoliwakeHook, verifyFoliwakeSignature } from '@foliwake/server/hook';
const cached = new Map<string, unknown>();
/** POST /api/webhooks/foliwake */
export async function hookEndpoint(request: Request): Promise<Response> {
const body = new Uint8Array(await request.arrayBuffer());
const signature = request.headers.get('foliwake-signature');
const secrets = [process.env.FOLIWAKE_HOOK_SECRET, process.env.FOLIWAKE_HOOK_SECRET_PREVIOUS];
if (!verifyFoliwakeSignature(body, signature, secrets).ok) return new Response(null, { status: 401 });
const payload = parseFoliwakeHook(body);
if (payload.event === 'ping') return Response.json({ ok: true, site: payload.site });
if (payload.all) cached.clear();
else for (const path of payload.pages ?? []) cached.delete(path);
return Response.json({ ok: true });
}The signature is t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>, accepted within 300 s of the app's clock. Answer 2xx only once the change is handled: anything else is sent again. Limit the body to 64 KiB (HOOK_BODY_LIMIT) and check that payload.site is yours.
Code and media proxies
Mount the handlers under the prefixes of app.proxies and pass them the path segments after the prefix. They serve only files of a cd_… code release and hashed pictures, add the credential on the server and forward nothing from the browser. Live files are cached for a year (immutable); preview answers are private, no-store and need authorizePreview.
import { loadFoliwakeConfig } from '@foliwake/server/config';
import { codeHandler, mediaHandler } from '@foliwake/server/handlers';
import { createOriginClient } from '@foliwake/server/origin';
const config = await loadFoliwakeConfig();
const client = createOriginClient(config, process.env);
const isAuthor = async (request: Request) => (request.headers.get('cookie') ?? '').includes('role=author'); // your sign-in
const code = codeHandler(config, client, { authorizePreview: isAuthor });
const media = mediaHandler(config, client, { authorizePreview: isAuthor });
/** Route requests under /foliwake-code/ and /foliwake-media/ (app.proxies) to the handlers. */
export async function proxies(request: Request): Promise<Response | null> {
const { pathname } = new URL(request.url);
const segments = (prefix: string) => pathname.slice(prefix.length + 1).split('/').filter(Boolean);
if (pathname.startsWith(`${config.app!.proxies.code}/`)) return code(request, { path: segments(config.app!.proxies.code) });
if (pathname.startsWith(`${config.app!.proxies.media}/`)) return media(request, { path: segments(config.app!.proxies.media) });
return null;
}CSP and browser settings
import { clientSettings, loadFoliwakeConfig } from '@foliwake/server/config';
import { foliwakeCsp } from '@foliwake/server/csp';
const config = await loadFoliwakeConfig();
// One header value for every route: blocks load from your own origin, so no Foliwake host is named.
export const csp = foliwakeCsp({
strategy: 'self-inline',
mediaBase: config.app?.media?.base ?? null,
reportUri: '/csp-report',
dev: process.env.NODE_ENV === 'development',
});
// The only part of the config a browser may see: site, proxy prefixes, blocks contract and event prefix.
export const settingsForBrowser = clientSettings(config);Compatibility
| Node.js | 22.22 or newer (Web fetch, Request, Response, streams) |
| Foliwake origin | plain/2: X-Code-Release with every .plain.html (a body without it is refused) |
| Config | foliwake.remote.json version 2 |
| Blocks contract | foliwake-blocks/2 |
Changes per version, breaking ones marked: CHANGELOG.md in the package (node_modules/@foliwake/server/CHANGELOG.md).
Good to know
- Bodies are checked before and after your
transform: no scripts, styles, frames, inline SVG or MathML, noon…attributes orjavascript:URLs;srcsetand entities are parsed like a browser does. What is returned is serialised from the checked tree. A refused body throwsFoliwakePageErrorwith kindinvalid. - Origin responses are size-limited while streaming (body 2 MB, code 5 MB, media 25 MB); requests time out after 10 s.
- Credentials never appear in messages; a missing or malformed password or key variable is a
FoliwakeConfigErrorthat names the variable, not its value. The secret is read at each request, so a rotated secret works without a restart. A private key whose ownkiddiffers from the config's is refused. - Rotating the hook secret: give the app the new secret as the previous one too (both accepted), switch the server to it, then drop the old one.
- Rotating a service-token key: add the new public key to the delivery's key set first (both
kids listed), then switch the app'skidand private key, then remove the old public key. preparePageleavespage.preloadempty;preloadHintsfills it from the release'scomponents/components.json(only blocks that declare a.jsor.cssget hints).
See also
@foliwake/next: this toolkit wired into a Next.js App Router app.@foliwake/clientand@foliwake/react: mount the prepared page in the browser.
License: Apache-2.0.
API
@foliwake/server/config
Functions and components
appOf()
The app settings; throws when the config has none.
function appOf(config: FoliwakeAppConfig): FoliwakeAppSettingsReturns FoliwakeAppSettings
checkEnvName()
Validates an environment variable NAME (never a value).
function checkEnvName(value: unknown, where: string, extra?: ParseOptions['envNameProblem']): stringReturns string
checkUsername()
Validates a Basic user name (no : or control characters, at most 128 characters).
function checkUsername(value: unknown, where: string): stringReturns string
clientSettings()
The explicit browser projection: nothing else of the config reaches a browser.
function clientSettings(config: FoliwakeAppConfig): ClientSettingsReturns ClientSettings
configFilePath()
Which file: an explicit file beats FOLIWAKE_REMOTE beats <cwd>/foliwake.remote.json.
function configFilePath(opts?: {
cwd?: string;
file?: string;
env?: NodeJS.ProcessEnv;
}): stringReturns string
endpointOf()
The endpoint of a channel; a missing one is an error, never replaced by the other channel.
function endpointOf(config: FoliwakeAppConfig, channel: ChannelName): FoliwakeEndpointReturns FoliwakeEndpoint
isLoopbackName()
True for 127.x, localhost, *.localhost and ::1.
function isLoopbackName(hostname: string): booleanReturns boolean
loadFoliwakeConfig()
Reads and parses the config file (see configFilePath).
function loadFoliwakeConfig(opts?: {
cwd?: string;
file?: string;
env?: NodeJS.ProcessEnv;
} & Omit<ParseOptions, 'file'>): Promise<FoliwakeAppConfig>Returns Promise<FoliwakeAppConfig>
pageAllowed()
Whether the app may read this page path (app.pages).
function pageAllowed(config: FoliwakeAppConfig, pagePath: string): booleanReturns boolean
parseFoliwakeConfig()
Parses the text of a version 2 config. Throws FoliwakeConfigError with a message that names the field.
function parseFoliwakeConfig(text: string, opts?: ParseOptions): FoliwakeAppConfigReturns FoliwakeAppConfig
parseRemoteUrl()
A site origin: https (http only for loopback), no credentials, path, query or fragment.
function parseRemoteUrl(value: unknown, where: string): stringReturns string
Classes
FoliwakeConfigError
A configuration problem; the message is shown as is (it never contains a secret).
class FoliwakeConfigError extends Error| Member | Type | Description |
|---|---|---|
name | string |
Constants
CHANNELS
The channels a config can name.
const CHANNELS: readonly ChannelName[]CONFIG_ENV
The environment variable that names another config file.
const CONFIG_ENV = "FOLIWAKE_REMOTE"CONFIG_FILE
The default config file name, looked up in the current directory.
const CONFIG_FILE = "foliwake.remote.json"Interfaces
BasicAuth
HTTP Basic credentials: a user name and the NAME of the variable holding the password.
interface BasicAuth| Member | Type | Description |
|---|---|---|
type | 'basic' | |
username | string | |
passwordEnv | string |
FoliwakeAppConfig
A validated app config: a foliwake.remote.json version 2, or (version 3) the site's discovery document merged with the optional version 3 file. It holds credential variable names, never secrets.
interface FoliwakeAppConfig| Member | Type | Description |
|---|---|---|
version | 2 | 3 | |
site | string | |
live | FoliwakeEndpoint | null | |
preview | FoliwakeEndpoint | null | |
app | FoliwakeAppSettings | null | Null only when parsed with requireApp: false (the engine CLI). |
from | string | Where the config came from, for messages. |
FoliwakeAppSettings
The app part of the config, with defaults applied.
interface FoliwakeAppSettings| Member | Type | Description |
|---|---|---|
pages | readonly string[] | Page globs the app may read. |
proxies | { code: string; media: string; pages: null; } | App-origin URL prefixes of the proxies. |
blocks | { entry: string | null; contract: string; major: number; eventPrefix: string; fromRelease: boolean; } | Where mountBlocks lives in a code release; null: bodies stay static. fromRelease: the config names no blocks (version 3), so each page's code release names them (X-Foliwake-Blocks); false for version 2. |
media | { base: string; transform: 'cloudflare-images' | null; } | null | Live media through a transforming host; null: media through the proxy. |
revalidate | number | Seconds before a cached envelope is stale (stale-while-revalidate). |
FoliwakeEndpoint
A channel's origin and its optional credential.
interface FoliwakeEndpoint| Member | Type | Description |
|---|---|---|
origin | string | Origin only: scheme, host, port. |
auth | RemoteAuth | null |
ParseOptions
Options of parseFoliwakeConfig.
interface ParseOptions| Member | Type | Description |
|---|---|---|
file? | string | For messages (default foliwake.remote.json). |
requireApp? | boolean | Refuse a file without app (default true; the CLI passes false). |
envNameProblem? | (name: string, what: string) => string | null | An additional rule for credential variable names (the engine CLI passes its own). |
ServiceTokenAuth
A service token: each request carries a fresh ES256 JWT for its exact path, signed with the private key in the variable privateKeyEnv (a JWK as JSON text). Delivery checks it with the public key of kid.
interface ServiceTokenAuth| Member | Type | Description |
|---|---|---|
type | 'service-token' | |
issuer | string | The iss the delivery expects (its TOKEN_ISSUER). |
kid | string | The key id the delivery looks the public key up by. |
privateKeyEnv | string | The NAME of the variable holding the private key. |
Types
RemoteAuth
The credential of an endpoint.
type RemoteAuth = BasicAuth | ServiceTokenAuthAlso exported (documented where they are defined)
- from
@foliwake/blocks-contract/page:ClientSettings
@foliwake/server/origin
Functions and components
createOriginClient()
The client for the config's origins. The secret is read from the environment at each request (a rotated secret takes effect without a restart) and goes only into the Authorization header: basic sends the password of passwordEnv; service-token signs a fresh token for the request's exact path with the private key of privateKeyEnv.
function createOriginClient(config: FoliwakeAppConfig, env?: NodeJS.ProcessEnv, opts?: OriginClientOptions): OriginClient| Parameter | Type | Description |
|---|---|---|
config | FoliwakeAppConfig | |
env? | NodeJS.ProcessEnv | Where secrets are read (default process.env). |
opts? | OriginClientOptions |
Returns OriginClient
Constants
SERVICE_TOKEN_LIFETIME_SECONDS
Seconds a service token lives: exp = iat + 60. Delivery accepts at most 120, with 5 s of clock skew.
const SERVICE_TOKEN_LIFETIME_SECONDS = 60Interfaces
OriginClient
Requests to the configured live and preview origins, with the credential added per request.
interface OriginClient| Member | Type | Description |
|---|---|---|
readonly config | FoliwakeAppConfig | |
originOf() | (channel: ChannelName) => string | The origin of a channel (for messages and loopback checks). |
request() | (channel: ChannelName, path: string, opts?: OriginRequestOptions) => Promise<Response> | GET/HEAD <origin><path>; redirect: 'manual', 10 s timeout unless signal is given. |
OriginClientOptions
Options of createOriginClient.
interface OriginClientOptions| Member | Type | Description |
|---|---|---|
fetch? | typeof fetch | A fetch implementation (tests); default globalThis.fetch. |
timeoutMs? | number | |
now? | () => number | The clock of service tokens, in milliseconds (tests); default Date.now. |
OriginRequestOptions
Options of one origin request.
interface OriginRequestOptions| Member | Type | Description |
|---|---|---|
method? | 'GET' | 'HEAD' | |
signal? | AbortSignal | |
headers? | Record<string, string> | Only these headers are sent (never a browser's). |
@foliwake/server/page
Functions and components
blocksUrlOf()
The same-origin URL of the blocks module, or null without an entry.
function blocksUrlOf(config: FoliwakeAppConfig, channel: ChannelName, codeRelease: CodeReleaseId, entry?: string | null): {
base: string;
url: string;
} | null| Parameter | Type | Description |
|---|---|---|
config | FoliwakeAppConfig | |
channel | ChannelName | |
codeRelease | CodeReleaseId | |
entry? | string | null | The module inside the code release; default the config's app.blocks.entry. |
Returns { base: string; url: string; } \| null
pageBlocksOf()
The blocks a page mounts: the config's, or (version 3 without app.blocks) the ones its code release names.
function pageBlocksOf(config: FoliwakeAppConfig, envelope: PageEnvelope): {
entry: string | null;
major: number;
eventPrefix: string;
}Returns { entry: string \| null; major: number; eventPrefix: string; }
plainPath()
The origin URL path of a page's body (/ → /index.plain.html).
function plainPath(pagePath: string): stringReturns string
preparePage()
Per request, after the cache: check → rewrite media/links → transform → check again → serialise.
function preparePage(config: FoliwakeAppConfig, envelope: PageEnvelope, opts?: PrepareOptions): FoliwakePageData| Parameter | Type | Description |
|---|---|---|
config | FoliwakeAppConfig | |
envelope | PageEnvelope | What readEnvelope (or a cached copy of it) returned. |
opts? | PrepareOptions |
Returns FoliwakePageData: The serialisable page for a client component (preload is empty; readPage of the Next package fills it). Throws FoliwakePageError('invalid') when the body or the transform's output is refused.
readEnvelope()
Reads <path>.plain.html from the channel's origin. Primitive inputs only, no callbacks and no signal (an internal 10 s timeout), so it can run inside a cache function. Refuses paths outside app.pages.
function readEnvelope(config: FoliwakeAppConfig, client: OriginClient, site: string, channel: ChannelName, path: string): Promise<PageEnvelope>| Parameter | Type | Description |
|---|---|---|
config | FoliwakeAppConfig | |
client | OriginClient | |
site | string | The config's site (config.site); another site is refused. |
channel | ChannelName | |
path | string | The page path (/, /lessons/a). |
Returns Promise<PageEnvelope>: The envelope; throws FoliwakePageError (not_found, not_allowed, origin, unauthorized, …).
Classes
FoliwakePageError
A page that cannot be shown. status: the origin's HTTP status when there was one.
class FoliwakePageError extends Error
new FoliwakePageError(kind: PageErrorKind, message: string, opts?: {
status?: number;
cause?: unknown;
})| Member | Type | Description |
|---|---|---|
name | string | |
readonly kind | PageErrorKind | |
readonly status? | number |
Interfaces
PrepareOptions
Options of preparePage.
interface PrepareOptions| Member | Type | Description |
|---|---|---|
mode? | string | The site's mode of the page (a token, [a-z][a-z0-9-], at most 32 characters), given to the blocks as host.mode; absent → none. exam is refused: the assessment extension's exam needs answers stripped by the origin, which does not exist yet, so an exam body would carry its answers. |
rewriteLink? | (href: string) => string | Root-relative links (/x) of <a href>; returns the app's URL. |
transform? | (html: string, envelope: PageEnvelope) => string | The app's own change of the body (allow-list, artwork, …); its output is checked again. |
Types
PageErrorKind
Why a page cannot be shown (FoliwakePageError.kind).
type PageErrorKind = 'not_found' | 'not_allowed' | 'origin' | 'invalid' | 'unauthorized' | 'too_large'Also exported (documented where they are defined)
- from
@foliwake/blocks-contract/import-map:pageImportMap - from
@foliwake/blocks-contract/page:FoliwakePageData,PageEnvelope
@foliwake/server/handlers
Functions and components
codeHandler()
GET|HEAD <proxies.code>/[preview/]<cd>/<path inside the code release>.
function codeHandler(config: FoliwakeAppConfig, client: OriginClient, opts: ProxyOptions): HandlerReturns Handler
mediaHandler()
GET|HEAD <proxies.media>/[preview/]<sha256>.<ext>: images only, one hashed segment.
function mediaHandler(config: FoliwakeAppConfig, client: OriginClient, opts: ProxyOptions): HandlerReturns Handler
Interfaces
ProxyOptions
Options of codeHandler and mediaHandler.
interface ProxyOptions| Member | Type | Description |
|---|---|---|
authorizePreview | AuthorizePreview | The app's author check for preview/… requests, or false to answer them 404. Required. |
Types
AuthorizePreview
The app's author check for preview requests, or false (preview answers 404).
type AuthorizePreview = ((request: Request) => boolean | Promise<boolean>) | falseHandler
A proxy handler: the request and the path segments after the proxy prefix.
type Handler = (request: Request, params: {
path: string[];
}) => Promise<Response>@foliwake/server/html
Functions and components
checkBody()
Parses and checks a body; returns the checked tree. Throws FoliwakePageError('invalid').
function checkBody(html: string, pagePath?: string): HtmlNode[]Returns HtmlNode[]
checkPlainBody()
Checks a body (the strict body check); throws FoliwakePageError('invalid').
function checkPlainBody(html: string, pagePath?: string): voidReturns void
componentNames()
Distinct data-component names, sorted.
function componentNames(nodes: readonly HtmlNode[]): string[]Returns string[]
elements()
Every element below nodes, depth first.
function elements(nodes: readonly HtmlNode[]): Generator<HtmlElement>Returns Generator<HtmlElement>
parseStrict()
Parses a body strictly. Comments are dropped; a doctype or processing instruction is an error.
function parseStrict(html: string): HtmlNode[]Returns HtmlNode[]
sanitizedHtml()
The checked body, serialised from its tree.
function sanitizedHtml(nodes: readonly HtmlNode[]): stringReturns string
serialize()
Serialises the tree as HTML (the WHATWG fragment serialisation rules for the elements a body may hold).
function serialize(nodes: readonly HtmlNode[]): stringReturns string
srcsetCandidates()
Splits a srcset into candidates: the URL ends at whitespace; descriptors run to the next comma.
function srcsetCandidates(srcset: string): {
url: string;
descriptor: string;
}[]Returns { url: string; descriptor: string; }[]
urlProblem()
Why a URL value is not allowed for this element/attribute, or null. Values are entity-decoded already.
function urlProblem(element: string, attribute: string, value: string, pagePath?: string): string | nullReturns string \| null
Classes
HtmlParseError
A body that cannot be parsed strictly.
class HtmlParseError extends Error| Member | Type | Description |
|---|---|---|
name | string |
Constants
COMPONENT_NAME
A valid data-component name.
const COMPONENT_NAME: RegExpREFUSED_ELEMENTS
Elements a body may not hold (incl. foreign content: no inline SVG or MathML in 0.1). <form> is allowed only as the engine writes it for the question block: an explicit method="dialog", no action, target or enctype; no control may override the submission (formmethod, formaction, formtarget, formenctype) or associate itself with another form (form). Such a form closes a dialog at most; it submits nowhere.
const REFUSED_ELEMENTS: ReadonlySet<string>Types
HtmlElement
An element of a parsed body.
type HtmlElement = {
type: 'tag';
name: string;
attribs: Record<string, string>;
children: HtmlNode[];
}HtmlNode
A node of a parsed body.
type HtmlNode = HtmlText | HtmlElementHtmlText
A text node of a parsed body.
type HtmlText = {
type: 'text';
data: string;
}@foliwake/server/csp
Functions and components
foliwakeCsp()
The policy as one header value.
function foliwakeCsp(opts: CspOptions): stringReturns string
Constants
REACT_SHELL_SCRIPT
React DOM 19.2's inline requestAnimationFrame(function(){$RT=performance.now()}); in PPR static shells.
const REACT_SHELL_SCRIPT = "requestAnimationFrame(function(){$RT=performance.now()});"REACT_SHELL_SCRIPT_HASH
The CSP hash source of REACT_SHELL_SCRIPT (used by the nonce strategy).
const REACT_SHELL_SCRIPT_HASH = "'sha256-7mu4H06fwDCjmnxxr/xNHyuQC6pLTHr4M2E4jXw5WZs='"Interfaces
CspOptions
Options of foliwakeCsp.
interface CspOptions| Member | Type | Description |
|---|---|---|
strategy | 'self-inline' | 'nonce' | self-inline (recommended; works with partial prerendering) or nonce (experimental, not recommended). |
nonce? | string | Required with 'nonce'. |
mediaBase? | string | null | The media host whose pictures pages show: app.media.base (live pictures through a transforming host), or the site's own CDN when the site resizes images on one (media.resize: "cdn", whose cdnBase is in every live srcset). An https address; only its origin (scheme and host) is added to img-src. |
dev? | boolean | Development: adds 'unsafe-eval' (React's debugging) and websocket connections for HMR. |
reportUri? | string | Where browsers report violations (report-uri). |
extra? | Partial<Record<string, string[]>> | More sources per directive, e.g. { 'connect-src': ['https://api.example.org'] }. |
@foliwake/server/preload
Functions and components
clearPreloadCache()
Forgets every remembered code file (tests).
function clearPreloadCache(): voidReturns void
codePath()
A path inside the code release the proxy would serve, or null.
function codePath(relative: string): string | nullReturns string \| null
preloadHints()
Hints for a prepared page: modulepreload for its modules, preload as=style for its block stylesheets.
function preloadHints(config: FoliwakeAppConfig, client: OriginClient, page: FoliwakePageData): Promise<PreloadHint[]>Returns Promise<PreloadHint[]>
resolveInRelease()
Resolves specifier against the module at from (both inside the release), or null when it leaves it.
function resolveInRelease(from: string, specifier: string): string | nullReturns string \| null
staticImports()
The relative static import specifiers of an ES module's text, and the kit's (KIT_SPECIFIER).
function staticImports(source: string): string[]Returns string[]
Also exported (documented where they are defined)
- from
@foliwake/blocks-contract/page:PreloadHint
@foliwake/server/hook
Functions and components
isFoliwakePagePath()
Whether a path of pages is a page (/lessons/a), not another file such as /lessons/query-index.json.
function isFoliwakePagePath(path: string): booleanReturns boolean
parseFoliwakeHook()
Parses a hook body (after its signature was checked). Unknown fields are ignored; an unknown operation kind is accepted, so a newer server's operations still refresh the app.
function parseFoliwakeHook(body: Body): FoliwakeHookPayload| Parameter | Type | Description |
|---|---|---|
body | Body | The raw body. |
Returns FoliwakeHookPayload: The payload; throws FoliwakeHookError when it is not a version 1 delivery.settled or ping.
signFoliwakeHook()
The Foliwake-Signature value for a body: what a Foliwake server sends; useful in an app's tests.
function signFoliwakeHook(body: Body, secret: string, t?: number): string| Parameter | Type | Description |
|---|---|---|
body | Body | The raw body, byte for byte as sent. |
secret | string | The shared secret. |
t? | number | The signature time in unix seconds (default: now). |
Returns string
verifyFoliwakeSignature()
Checks Foliwake-Signature against the raw body. Every secret is tried (the current one and, while it is rotated, the previous one); the comparison is constant-time.
function verifyFoliwakeSignature(body: Body, header: string | null, secrets: readonly (string | null | undefined)[], options?: VerifySignatureOptions): SignatureCheck| Parameter | Type | Description |
|---|---|---|
body | Body | The raw request body, byte for byte as received. |
header | string | null | The Foliwake-Signature header, or null. |
secrets | readonly (string | null | undefined)[] | The accepted secrets; empty or blank ones are ignored. |
options? | VerifySignatureOptions | now (ms) and toleranceS (default 300). |
Returns SignatureCheck: { ok: true }, or { ok: false, reason }: malformed, expired, mismatch or no_secret.
Classes
FoliwakeHookError
A hook body that is not a valid payload.
class FoliwakeHookError extends Error| Member | Type | Description |
|---|---|---|
name | string |
Constants
HOOK_BODY_LIMIT
The largest hook body an app accepts, in bytes.
const HOOK_BODY_LIMIT: numberHOOK_PAGES_LIMIT
The most pages a delivery lists; a larger change is sent as all: true.
const HOOK_PAGES_LIMIT = 100HOOK_TOLERANCE_SECONDS
How far the signature time may be from the app's clock by default, in seconds.
const HOOK_TOLERANCE_SECONDS = 300Interfaces
FoliwakeDeliveryPayload
delivery.settled: the live site is at generation, and the caches in front of the origin serve it.
interface FoliwakeDeliveryPayload| Member | Type | Description |
|---|---|---|
version | 1 | |
event | 'delivery.settled' | |
site | string | |
generation | number | The live generation; it only grows, except that init starts a new history. |
release | string | null | The site release (sr_…), or null. |
codeRelease | string | null | The code release (cd_…), or null. |
operation | { id: string; kind: FoliwakeOperationKind | (string & {}); } | |
pages? | string[] | The changed paths (pages, indexes); present only when all is false. A hint, at most 100. |
all | boolean | Every live page may have changed. |
verified | boolean | Whether the server read the new generation back through its own cache before sending. |
sentAt | string |
FoliwakePingPayload
ping: the server checks the endpoint and its secret; the app changes nothing.
interface FoliwakePingPayload| Member | Type | Description |
|---|---|---|
version | 1 | |
event | 'ping' | |
site | string | |
sentAt | string |
VerifySignatureOptions
Options of verifyFoliwakeSignature.
interface VerifySignatureOptions| Member | Type | Description |
|---|---|---|
now? | number | The app's clock, in milliseconds since the epoch (default Date.now()). |
toleranceS? | number | The allowed distance between the signature time and now, in seconds (default 300). |
Types
FoliwakeHookPayload
Any hook body.
type FoliwakeHookPayload = FoliwakeDeliveryPayload | FoliwakePingPayloadFoliwakeOperationKind
The operations a delivery reports; a newer server may send others, which an app treats like any change.
type FoliwakeOperationKind = 'content_publish' | 'unpublish' | 'rollback_full' | 'code_release' | 'rollback_code' | 'site_migration' | 'recovery_purge' | 'engine_update' | 'init'SignatureCheck
The result of verifyFoliwakeSignature.
type SignatureCheck = {
ok: true;
} | {
ok: false;
reason: SignatureFailure;
}SignatureFailure
Why a signature was refused.
type SignatureFailure = 'malformed' | 'expired' | 'mismatch' | 'no_secret'@foliwake/server/handler
Functions and components
createFoliwakeHandler()
The Foliwake routes of an app as one (request) => Promise<Response>. The config is read on the first request (FOLIWAKE_URL and its discovery document, unless config is given) and kept; a failed read is tried again on the next request and answers 503 meanwhile.
function createFoliwakeHandler(opts?: FoliwakeHandlerOptions): FoliwakeFetchHandler| Parameter | Type | Description |
|---|---|---|
opts? | FoliwakeHandlerOptions | config, base, authorizePreview (default false), hook, env, fetch, log. |
Returns FoliwakeFetchHandler
Constants
HANDLER_BASE
Where the handler is mounted by default: /foliwake/hook, /foliwake/health.
const HANDLER_BASE = "/foliwake"HOOK_SECRET_ENV
The variable the hook's shared secret is read from by default.
const HOOK_SECRET_ENV = "FOLIWAKE_HOOK_SECRET"Interfaces
FoliwakeHandlerOptions
Options of createFoliwakeHandler.
interface FoliwakeHandlerOptions| Member | Type | Description |
|---|---|---|
config? | FoliwakeAppConfig | (() => FoliwakeAppConfig | Promise<FoliwakeAppConfig>) | The app config, or how to get it; default loadAppConfig() (FOLIWAKE_URL + the optional file), once. |
base? | string | The app path of the hook and health routes; default /foliwake. |
authorizePreview? | AuthorizePreview | The app's author check for preview files; default false (preview answers 404). |
hook? | false | FoliwakeHookOptions | The hook endpoint's options; false answers 404 on <base>/hook. |
env? | NodeJS.ProcessEnv | Where secrets and FOLIWAKE_URL are read; default process.env. |
fetch? | typeof fetch | A fetch implementation (tests); default globalThis.fetch. |
log? | Pick<Console, 'warn' | 'error'> |
FoliwakeHookOptions
The hook endpoint of the handler.
interface FoliwakeHookOptions| Member | Type | Description |
|---|---|---|
secretEnv? | string | The variable holding the shared secret; default FOLIWAKE_HOOK_SECRET. |
previousSecretEnv? | string | While the secret is rotated: the variable holding the previous one, also accepted. |
onDelivery? | (payload: FoliwakeDeliveryPayload) => void | Promise<void> | Called for every delivery (expire your own caches here); a throw answers 500 and the server retries. |
toleranceS? | number | The allowed clock distance of the signature, in seconds; default 300. |
endpoint? | (request: Request) => Promise<Response> | Replaces the endpoint (a framework adapter's own, such as Next's tag expiry). |
Types
FoliwakeFetchHandler
A request handler on the Web Fetch API.
type FoliwakeFetchHandler = (request: Request) => Promise<Response>@foliwake/server/hook-endpoint
Functions and components
createHookEndpoint()
The hook endpoint as a function of a Request: 413 over 64 KiB, 401 on a bad or expired signature, 400 on a body that is not a payload or names another site, 200 otherwise.
function createHookEndpoint(deps: HookEndpointDeps): (request: Request) => Promise<Response>Returns (request: Request) => Promise<Response>
deliveryTags()
The tags a delivery expires: the site's live tag on all, else one tag per listed path.
function deliveryTags(payload: FoliwakeDeliveryPayload, liveTag: (path?: string) => string): string[]Returns string[]
hookSecretsFrom()
The secrets() of the hook endpoint read from environment variables: each value is trimmed of leading and trailing whitespace and newlines (a secret pasted from openssl rand -hex 32 often ends in one), and an all-whitespace value counts as unset. The first time trimming changes a variable's value, one warning names the variable, never the value.
function hookSecretsFrom(source: HookSecretSource): () => (string | undefined)[]Returns () => (string \| undefined)[]
warmPaths()
The pages read again after a delivery: none on all, page paths only, at most WARM_LIMIT.
function warmPaths(payload: FoliwakeDeliveryPayload): string[]Returns string[]
Constants
WARM_LIMIT
At most this many pages are read again right after a delivery (warm); never on all.
const WARM_LIMIT = 20Interfaces
HookEndpointDeps
What the endpoint needs from the framework and from the app.
interface HookEndpointDeps| Member | Type | Description |
|---|---|---|
site | string | The configured site. |
sdk | string | What a ping answers as sdk: the package and its version (@foliwake/next/0.9.0). |
secrets() | () => (string | undefined)[] | The accepted secrets, read per request (current, then previous). |
liveTag() | (path?: string) => string | The live tag of the site (no path) or of one path. |
expire() | (tag: string) => void | Expires one tag (revalidateTag with the chosen profile). |
warm() | (path: string) => Promise<unknown> | Reads one page into the cache again. |
schedule() | (task: () => Promise<void>) => void | Runs work after the response is sent. |
warmPages | boolean | Whether pages are read again after a delivery. |
onDelivery? | (payload: FoliwakeDeliveryPayload) => void | Promise<void> | |
toleranceS? | number | |
now? | () => number | |
log | Pick<Console, 'warn' | 'error'> |
HookSecretSource
Where hookSecretsFrom reads and what it warns on.
interface HookSecretSource| Member | Type | Description |
|---|---|---|
names | readonly (string | undefined)[] | The variables, current first, then the previous one while it is rotated; undefined entries are skipped. |
env? | NodeJS.ProcessEnv | Where the variables are read, per call; default process.env. |
log | Pick<Console, 'warn'> |
@foliwake/server/discovery
Functions and components
fetchDiscovery()
Reads and validates the discovery document of the site at siteUrl (FOLIWAKE_URL: https, or http for loopback hosts; origin only). 5 s per attempt, one retry, no redirects, at most 16 KiB of JSON.
function fetchDiscovery(siteUrl: string, opts?: FetchDiscoveryOptions): Promise<FoliwakeDiscovery>Returns Promise<FoliwakeDiscovery>
parseDiscovery()
Validates a discovery document read from origin (the scheme, host and port of FOLIWAKE_URL). Throws FoliwakeConfigError naming the field.
function parseDiscovery(value: unknown, origin: string): FoliwakeDiscoveryReturns FoliwakeDiscovery
Constants
DISCOVERY_LIMIT
The largest discovery document read, in bytes.
const DISCOVERY_LIMIT: numberDISCOVERY_PATH
Where a site serves its discovery document, on each of its hosts.
const DISCOVERY_PATH = "/.well-known/foliwake.json"DISCOVERY_VERSION
The major of the discovery format this package reads.
const DISCOVERY_VERSION = 1PLAIN_CONTRACT
The plain HTML contract this package reads (X-Code-Release on .plain.html).
const PLAIN_CONTRACT = 2URL_ENV
The environment variable with the site's live origin.
const URL_ENV = "FOLIWAKE_URL"Interfaces
FetchDiscoveryOptions
Options of fetchDiscovery.
interface FetchDiscoveryOptions| Member | Type | Description |
|---|---|---|
fetch? | typeof fetch | A fetch implementation (tests); default globalThis.fetch. |
timeoutMs? | number | Per attempt; default 5000. |
FoliwakeDiscovery
A validated discovery document. Unknown keys are ignored, so a newer engine may add some.
interface FoliwakeDiscovery| Member | Type | Description |
|---|---|---|
site | string | |
live | { url: string; } | |
preview | { url: string; } | null | Null when the site has no preview host. Its Basic user is always preview. |
media | { cdn: string; } | null | The CDN that resizes live images (its origin), or null. |
contracts | { plain: number; html: number | null; blocks: number | null; hook: number | null; } |
@foliwake/server/resolve
Functions and components
configFromSnapshot()
The app config of a snapshot (no I/O). Throws FoliwakeConfigError naming the field.
function configFromSnapshot(snapshot: FoliwakeConfigSnapshot): FoliwakeAppConfigReturns FoliwakeAppConfig
loadAppConfig()
readConfigSnapshot, then configFromSnapshot.
function loadAppConfig(opts?: ReadSnapshotOptions): Promise<FoliwakeAppConfig>Returns Promise<FoliwakeAppConfig>
readConfigSnapshot()
Reads the inputs: FOLIWAKE_URL and its discovery document (fetched now), and the config file when there is one (a file named explicitly or by FOLIWAKE_REMOTE must exist). Throws FoliwakeConfigError.
function readConfigSnapshot(opts?: ReadSnapshotOptions): Promise<FoliwakeConfigSnapshot>Returns Promise<FoliwakeConfigSnapshot>
Constants
PREVIEW_TOKEN_ENV
The variable the default preview credential reads: Basic preview:<site preview token>.
const PREVIEW_TOKEN_ENV = "FOLIWAKE_PREVIEW_TOKEN"Interfaces
FoliwakeConfigSnapshot
The inputs of an app's config, as plain JSON.
interface FoliwakeConfigSnapshot| Member | Type | Description |
|---|---|---|
url | string | null | FOLIWAKE_URL, or null. |
discovery | FoliwakeDiscovery | null | The site's discovery document read from url, or null without it. |
file | string | null | The config file's name (for messages) and text, or null when there is none. |
text | string | null |
ReadSnapshotOptions
Options of readConfigSnapshot and loadAppConfig.
interface ReadSnapshotOptions extends FetchDiscoveryOptions| Member | Type | Description |
|---|---|---|
cwd? | string | |
env? | NodeJS.ProcessEnv | Default process.env: FOLIWAKE_URL, FOLIWAKE_REMOTE. |
file? | string | The config file (default FOLIWAKE_REMOTE, else ./foliwake.remote.json). |
Also exported (documented where they are defined)
- from
@foliwake/server/discovery:DISCOVERY_PATH,FoliwakeDiscovery,URL_ENV
@foliwake/server/schemas/remote-2.schema.json
A file, not a module: schemas/remote-2.schema.json in the package.
@foliwake/server/schemas/remote-3.schema.json
A file, not a module: schemas/remote-3.schema.json in the package.