@foliwake/server 0.8.0 → 0.10.0

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.
@@ -0,0 +1,35 @@
1
+ import { type FoliwakeDeliveryPayload } from './hook.js';
2
+ /** At most this many pages are read again right after a delivery (`warm`); never on `all`. */
3
+ export declare const WARM_LIMIT = 20;
4
+ /** What the endpoint needs from the framework and from the app. */
5
+ export interface HookEndpointDeps {
6
+ /** The configured site. */
7
+ site: string;
8
+ /** What a `ping` answers as `sdk`: the package and its version (`@foliwake/next/0.9.0`). */
9
+ sdk: string;
10
+ /** The accepted secrets, read per request (current, then previous). */
11
+ secrets(): (string | undefined)[];
12
+ /** The live tag of the site (no path) or of one path. */
13
+ liveTag(path?: string): string;
14
+ /** Expires one tag (revalidateTag with the chosen profile). */
15
+ expire(tag: string): void;
16
+ /** Reads one page into the cache again. */
17
+ warm(path: string): Promise<unknown>;
18
+ /** Runs work after the response is sent. */
19
+ schedule(task: () => Promise<void>): void;
20
+ /** Whether pages are read again after a delivery. */
21
+ warmPages: boolean;
22
+ onDelivery?: (payload: FoliwakeDeliveryPayload) => void | Promise<void>;
23
+ toleranceS?: number;
24
+ now?: () => number;
25
+ log: Pick<Console, 'warn' | 'error'>;
26
+ }
27
+ /** The tags a delivery expires: the site's live tag on `all`, else one tag per listed path. */
28
+ export declare function deliveryTags(payload: FoliwakeDeliveryPayload, liveTag: (path?: string) => string): string[];
29
+ /** The pages read again after a delivery: none on `all`, page paths only, at most WARM_LIMIT. */
30
+ export declare function warmPaths(payload: FoliwakeDeliveryPayload): string[];
31
+ /**
32
+ * The hook endpoint as a function of a Request: 413 over 64 KiB, 401 on a bad or expired signature, 400 on a
33
+ * body that is not a payload or names another site, 200 otherwise.
34
+ */
35
+ export declare function createHookEndpoint(deps: HookEndpointDeps): (request: Request) => Promise<Response>;
@@ -0,0 +1,143 @@
1
+ // The hook endpoint without a framework: verify, parse, expire tags, answer. `@foliwake/next/revalidate` wires it to
2
+ // next/cache and next/server; `@foliwake/server/handler` uses it with the app's own callbacks; tests drive it with
3
+ // plain Request objects.
4
+ import { FoliwakeHookError, HOOK_BODY_LIMIT, isFoliwakePagePath, parseFoliwakeHook, verifyFoliwakeSignature, } from './hook.js';
5
+ /** At most this many pages are read again right after a delivery (`warm`); never on `all`. */
6
+ export const WARM_LIMIT = 20;
7
+ class TooLarge extends Error {
8
+ }
9
+ function answer(status, body) {
10
+ return Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } });
11
+ }
12
+ function refuse(status, error) {
13
+ return answer(status, { ok: false, error });
14
+ }
15
+ function declaredTooLarge(request) {
16
+ const length = Number(request.headers.get('content-length') ?? '0');
17
+ return Number.isFinite(length) && length > HOOK_BODY_LIMIT;
18
+ }
19
+ function joined(chunks, total) {
20
+ const out = new Uint8Array(total);
21
+ let at = 0;
22
+ for (const chunk of chunks) {
23
+ out.set(chunk, at);
24
+ at += chunk.byteLength;
25
+ }
26
+ return out;
27
+ }
28
+ /** The body, cut at HOOK_BODY_LIMIT whatever Content-Length says. */
29
+ async function readBody(request) {
30
+ if (declaredTooLarge(request))
31
+ throw new TooLarge();
32
+ if (!request.body)
33
+ return new Uint8Array();
34
+ const reader = request.body.getReader();
35
+ const chunks = [];
36
+ let total = 0;
37
+ for (let read = await reader.read(); !read.done; read = await reader.read()) {
38
+ total += read.value.byteLength;
39
+ if (total > HOOK_BODY_LIMIT) {
40
+ await reader.cancel().catch(() => { });
41
+ throw new TooLarge();
42
+ }
43
+ chunks.push(read.value);
44
+ }
45
+ return joined(chunks, total);
46
+ }
47
+ /** The tags a delivery expires: the site's live tag on `all`, else one tag per listed path. */
48
+ export function deliveryTags(payload, liveTag) {
49
+ if (payload.all)
50
+ return [liveTag()];
51
+ return (payload.pages ?? []).map((path) => liveTag(path));
52
+ }
53
+ /** The pages read again after a delivery: none on `all`, page paths only, at most WARM_LIMIT. */
54
+ export function warmPaths(payload) {
55
+ if (payload.all)
56
+ return [];
57
+ return (payload.pages ?? []).filter(isFoliwakePagePath).slice(0, WARM_LIMIT);
58
+ }
59
+ function scheduleWarm(deps, payload) {
60
+ const paths = warmPaths(payload);
61
+ if (!deps.warmPages || paths.length === 0)
62
+ return;
63
+ deps.schedule(async () => {
64
+ const results = await Promise.allSettled(paths.map((path) => deps.warm(path)));
65
+ const failed = results.filter((r) => r.status === 'rejected').length;
66
+ if (failed > 0)
67
+ deps.log.warn(`[foliwake] hook: ${failed} of ${paths.length} pages were not read again`);
68
+ });
69
+ }
70
+ async function deliver(deps, payload) {
71
+ const tags = deliveryTags(payload, deps.liveTag);
72
+ for (const tag of tags)
73
+ deps.expire(tag);
74
+ try {
75
+ await deps.onDelivery?.(payload);
76
+ }
77
+ catch (error) {
78
+ deps.log.error('[foliwake] hook: onDelivery failed; the server will send the delivery again', error);
79
+ return refuse(500, 'on_delivery_failed');
80
+ }
81
+ scheduleWarm(deps, payload);
82
+ return answer(200, { ok: true, revalidated: tags });
83
+ }
84
+ function verified(deps, body, request) {
85
+ const check = verifyFoliwakeSignature(body, request.headers.get('foliwake-signature'), deps.secrets(), {
86
+ now: deps.now?.(),
87
+ toleranceS: deps.toleranceS,
88
+ });
89
+ if (check.ok)
90
+ return null;
91
+ if (check.reason !== 'no_secret')
92
+ return refuse(401, `signature_${check.reason}`);
93
+ deps.log.error('[foliwake] hook: no secret is set; every delivery is refused');
94
+ return refuse(500, 'no_secret');
95
+ }
96
+ function payloadOf(body) {
97
+ try {
98
+ return parseFoliwakeHook(body);
99
+ }
100
+ catch (error) {
101
+ if (error instanceof FoliwakeHookError)
102
+ return refuse(400, error.message);
103
+ throw error;
104
+ }
105
+ }
106
+ function eventMismatch(request, payload) {
107
+ const event = request.headers.get('foliwake-event');
108
+ return event !== null && event !== payload.event;
109
+ }
110
+ async function handle(deps, request) {
111
+ if (request.method !== 'POST')
112
+ return refuse(405, 'method_not_allowed');
113
+ const body = await readBody(request);
114
+ const refused = verified(deps, body, request);
115
+ if (refused)
116
+ return refused;
117
+ const payload = payloadOf(body);
118
+ if (payload instanceof Response)
119
+ return payload;
120
+ if (eventMismatch(request, payload))
121
+ return refuse(400, 'Foliwake-Event does not match the body');
122
+ if (payload.site !== deps.site)
123
+ return refuse(400, `this app serves the site ${deps.site}`);
124
+ if (payload.event === 'ping')
125
+ return answer(200, { ok: true, site: deps.site, sdk: deps.sdk });
126
+ return deliver(deps, payload);
127
+ }
128
+ /**
129
+ * The hook endpoint as a function of a Request: 413 over 64 KiB, 401 on a bad or expired signature, 400 on a
130
+ * body that is not a payload or names another site, 200 otherwise.
131
+ */
132
+ export function createHookEndpoint(deps) {
133
+ return async (request) => {
134
+ try {
135
+ return await handle(deps, request);
136
+ }
137
+ catch (error) {
138
+ if (error instanceof TooLarge)
139
+ return refuse(413, 'body_too_large');
140
+ throw error;
141
+ }
142
+ };
143
+ }
package/dist/hook.d.ts ADDED
@@ -0,0 +1,91 @@
1
+ /** The largest hook body an app accepts, in bytes. */
2
+ export declare const HOOK_BODY_LIMIT: number;
3
+ /** How far the signature time may be from the app's clock by default, in seconds. */
4
+ export declare const HOOK_TOLERANCE_SECONDS = 300;
5
+ /** The most `pages` a delivery lists; a larger change is sent as `all: true`. */
6
+ export declare const HOOK_PAGES_LIMIT = 100;
7
+ /** The operations a delivery reports; a newer server may send others, which an app treats like any change. */
8
+ export type FoliwakeOperationKind = 'content_publish' | 'unpublish' | 'rollback_full' | 'code_release' | 'rollback_code' | 'site_migration' | 'recovery_purge' | 'engine_update' | 'init';
9
+ /** `delivery.settled`: the live site is at `generation`, and the caches in front of the origin serve it. */
10
+ export interface FoliwakeDeliveryPayload {
11
+ version: 1;
12
+ event: 'delivery.settled';
13
+ site: string;
14
+ /** The live generation; it only grows, except that `init` starts a new history. */
15
+ generation: number;
16
+ /** The site release (`sr_…`), or null. */
17
+ release: string | null;
18
+ /** The code release (`cd_…`), or null. */
19
+ codeRelease: string | null;
20
+ operation: {
21
+ id: string;
22
+ kind: FoliwakeOperationKind | (string & {});
23
+ };
24
+ /** The changed paths (pages, indexes); present only when `all` is false. A hint, at most 100. */
25
+ pages?: string[];
26
+ /** Every live page may have changed. */
27
+ all: boolean;
28
+ /** Whether the server read the new generation back through its own cache before sending. */
29
+ verified: boolean;
30
+ sentAt: string;
31
+ }
32
+ /** `ping`: the server checks the endpoint and its secret; the app changes nothing. */
33
+ export interface FoliwakePingPayload {
34
+ version: 1;
35
+ event: 'ping';
36
+ site: string;
37
+ sentAt: string;
38
+ }
39
+ /** Any hook body. */
40
+ export type FoliwakeHookPayload = FoliwakeDeliveryPayload | FoliwakePingPayload;
41
+ /** Options of `verifyFoliwakeSignature`. */
42
+ export interface VerifySignatureOptions {
43
+ /** The app's clock, in milliseconds since the epoch (default `Date.now()`). */
44
+ now?: number;
45
+ /** The allowed distance between the signature time and `now`, in seconds (default 300). */
46
+ toleranceS?: number;
47
+ }
48
+ /** Why a signature was refused. */
49
+ export type SignatureFailure = 'malformed' | 'expired' | 'mismatch' | 'no_secret';
50
+ /** The result of `verifyFoliwakeSignature`. */
51
+ export type SignatureCheck = {
52
+ ok: true;
53
+ } | {
54
+ ok: false;
55
+ reason: SignatureFailure;
56
+ };
57
+ /** A hook body that is not a valid payload. */
58
+ export declare class FoliwakeHookError extends Error {
59
+ name: string;
60
+ }
61
+ type Body = string | Uint8Array;
62
+ /**
63
+ * The `Foliwake-Signature` value for a body: what a Foliwake server sends; useful in an app's tests.
64
+ *
65
+ * @param body - The raw body, byte for byte as sent.
66
+ * @param secret - The shared secret.
67
+ * @param t - The signature time in unix seconds (default: now).
68
+ */
69
+ export declare function signFoliwakeHook(body: Body, secret: string, t?: number): string;
70
+ /**
71
+ * Checks `Foliwake-Signature` against the raw body. Every secret is tried (the current one and, while it is
72
+ * rotated, the previous one); the comparison is constant-time.
73
+ *
74
+ * @param body - The raw request body, byte for byte as received.
75
+ * @param header - The `Foliwake-Signature` header, or null.
76
+ * @param secrets - The accepted secrets; empty or blank ones are ignored.
77
+ * @param options - `now` (ms) and `toleranceS` (default 300).
78
+ * @returns `{ ok: true }`, or `{ ok: false, reason }`: `malformed`, `expired`, `mismatch` or `no_secret`.
79
+ */
80
+ export declare function verifyFoliwakeSignature(body: Body, header: string | null, secrets: readonly (string | null | undefined)[], options?: VerifySignatureOptions): SignatureCheck;
81
+ /** Whether a path of `pages` is a page (`/lessons/a`), not another file such as `/lessons/query-index.json`. */
82
+ export declare function isFoliwakePagePath(path: string): boolean;
83
+ /**
84
+ * Parses a hook body (after its signature was checked). Unknown fields are ignored; an unknown operation kind is
85
+ * accepted, so a newer server's operations still refresh the app.
86
+ *
87
+ * @param body - The raw body.
88
+ * @returns The payload; throws FoliwakeHookError when it is not a version 1 `delivery.settled` or `ping`.
89
+ */
90
+ export declare function parseFoliwakeHook(body: Body): FoliwakeHookPayload;
91
+ export {};
package/dist/hook.js ADDED
@@ -0,0 +1,188 @@
1
+ // @foliwake/server/hook: the signed POST a Foliwake server sends an app once a change is live and the caches in
2
+ // front of the origin are refreshed (`delivery.settled`), or to check the app's endpoint (`ping`).
3
+ // Wire format, version 1:
4
+ // Foliwake-Event: delivery.settled | ping
5
+ // Foliwake-Delivery: <uuid v4>, new on every attempt
6
+ // Foliwake-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, `${t}.${raw body}`)>
7
+ // No framework here: the Next.js route handler is `foliwakeRevalidateHandler` of `@foliwake/next/revalidate`.
8
+ import { createHmac, timingSafeEqual } from 'node:crypto';
9
+ import { PAGE_PATH_PATTERN } from './constants.js';
10
+ /** The largest hook body an app accepts, in bytes. */
11
+ export const HOOK_BODY_LIMIT = 64 * 1024;
12
+ /** How far the signature time may be from the app's clock by default, in seconds. */
13
+ export const HOOK_TOLERANCE_SECONDS = 300;
14
+ /** The most `pages` a delivery lists; a larger change is sent as `all: true`. */
15
+ export const HOOK_PAGES_LIMIT = 100;
16
+ /** A hook body that is not a valid payload. */
17
+ export class FoliwakeHookError extends Error {
18
+ name = 'FoliwakeHookError';
19
+ }
20
+ const SIGNATURE_TIME = /^\d{1,12}$/;
21
+ const SIGNATURE_HEX = /^[0-9a-f]{64}$/;
22
+ const TOKEN = /^[a-z][a-z0-9_.]{0,63}$/;
23
+ function bytesOf(body) {
24
+ return typeof body === 'string' ? new TextEncoder().encode(body) : body;
25
+ }
26
+ function hmacHex(secret, t, body) {
27
+ return createHmac('sha256', secret).update(`${t}.`).update(body).digest('hex');
28
+ }
29
+ /**
30
+ * The `Foliwake-Signature` value for a body: what a Foliwake server sends; useful in an app's tests.
31
+ *
32
+ * @param body - The raw body, byte for byte as sent.
33
+ * @param secret - The shared secret.
34
+ * @param t - The signature time in unix seconds (default: now).
35
+ */
36
+ export function signFoliwakeHook(body, secret, t = Math.floor(Date.now() / 1000)) {
37
+ const time = String(Math.trunc(t));
38
+ return `t=${time},v1=${hmacHex(secret, time, bytesOf(body))}`;
39
+ }
40
+ function parseSignatureHeader(header) {
41
+ if (header === null)
42
+ return null;
43
+ let t = null;
44
+ const signatures = [];
45
+ for (const part of header.split(',')) {
46
+ const [key, value] = part.trim().split('=', 2);
47
+ if (key === 't' && value !== undefined && SIGNATURE_TIME.test(value))
48
+ t = value;
49
+ else if (key === 'v1' && value !== undefined && SIGNATURE_HEX.test(value))
50
+ signatures.push(value);
51
+ }
52
+ return t === null || signatures.length === 0 ? null : { t, signatures };
53
+ }
54
+ function sameHex(a, b) {
55
+ return timingSafeEqual(Buffer.from(a, 'hex'), Buffer.from(b, 'hex'));
56
+ }
57
+ function matchesAny(parsed, secrets, body) {
58
+ let matched = false;
59
+ for (const secret of secrets) {
60
+ const expected = hmacHex(secret, parsed.t, body);
61
+ for (const signature of parsed.signatures)
62
+ matched = sameHex(expected, signature) || matched;
63
+ }
64
+ return matched;
65
+ }
66
+ /**
67
+ * Checks `Foliwake-Signature` against the raw body. Every secret is tried (the current one and, while it is
68
+ * rotated, the previous one); the comparison is constant-time.
69
+ *
70
+ * @param body - The raw request body, byte for byte as received.
71
+ * @param header - The `Foliwake-Signature` header, or null.
72
+ * @param secrets - The accepted secrets; empty or blank ones are ignored.
73
+ * @param options - `now` (ms) and `toleranceS` (default 300).
74
+ * @returns `{ ok: true }`, or `{ ok: false, reason }`: `malformed`, `expired`, `mismatch` or `no_secret`.
75
+ */
76
+ export function verifyFoliwakeSignature(body, header, secrets, options = {}) {
77
+ const usable = secrets.filter((s) => typeof s === 'string' && s.length > 0);
78
+ if (usable.length === 0)
79
+ return { ok: false, reason: 'no_secret' };
80
+ const parsed = parseSignatureHeader(header);
81
+ if (parsed === null)
82
+ return { ok: false, reason: 'malformed' };
83
+ const nowS = (options.now ?? Date.now()) / 1000;
84
+ const tolerance = options.toleranceS ?? HOOK_TOLERANCE_SECONDS;
85
+ if (Math.abs(nowS - Number(parsed.t)) > tolerance)
86
+ return { ok: false, reason: 'expired' };
87
+ if (!matchesAny(parsed, usable, bytesOf(body)))
88
+ return { ok: false, reason: 'mismatch' };
89
+ return { ok: true };
90
+ }
91
+ function fail(message) {
92
+ throw new FoliwakeHookError(message);
93
+ }
94
+ function objectOf(value, what) {
95
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
96
+ fail(`${what} is not an object`);
97
+ return value;
98
+ }
99
+ function stringOf(fields, key) {
100
+ const value = fields[key];
101
+ if (typeof value !== 'string' || value.length === 0 || value.length > 256)
102
+ fail(`${key} is not a string`);
103
+ return value;
104
+ }
105
+ function nullableStringOf(fields, key) {
106
+ return fields[key] === null || fields[key] === undefined ? null : stringOf(fields, key);
107
+ }
108
+ function booleanOf(fields, key) {
109
+ if (typeof fields[key] !== 'boolean')
110
+ fail(`${key} is not a boolean`);
111
+ return fields[key];
112
+ }
113
+ function generationOf(fields) {
114
+ const value = fields.generation;
115
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)
116
+ fail('generation is not an integer');
117
+ return value;
118
+ }
119
+ function operationOf(fields) {
120
+ const operation = objectOf(fields.operation, 'operation');
121
+ const kind = stringOf(operation, 'kind');
122
+ if (!TOKEN.test(kind))
123
+ fail('operation.kind is not a token');
124
+ return { id: stringOf(operation, 'id'), kind };
125
+ }
126
+ /** Whether a path of `pages` is a page (`/lessons/a`), not another file such as `/lessons/query-index.json`. */
127
+ export function isFoliwakePagePath(path) {
128
+ return PAGE_PATH_PATTERN.test(path);
129
+ }
130
+ function isHookPath(value) {
131
+ return typeof value === 'string' && value.startsWith('/') && value.length <= 1024;
132
+ }
133
+ function pagesOf(fields) {
134
+ const pages = fields.pages;
135
+ if (!Array.isArray(pages))
136
+ fail('pages is missing while all is false');
137
+ if (pages.length > HOOK_PAGES_LIMIT)
138
+ fail(`pages lists more than ${HOOK_PAGES_LIMIT} paths`);
139
+ if (!pages.every(isHookPath))
140
+ fail('pages holds a value that is not a path');
141
+ return [...new Set(pages)];
142
+ }
143
+ function deliveryOf(fields, site, sentAt) {
144
+ const all = booleanOf(fields, 'all');
145
+ const payload = {
146
+ version: 1,
147
+ event: 'delivery.settled',
148
+ site,
149
+ generation: generationOf(fields),
150
+ release: nullableStringOf(fields, 'release'),
151
+ codeRelease: nullableStringOf(fields, 'codeRelease'),
152
+ operation: operationOf(fields),
153
+ all,
154
+ verified: booleanOf(fields, 'verified'),
155
+ sentAt,
156
+ };
157
+ if (!all)
158
+ payload.pages = pagesOf(fields);
159
+ return payload;
160
+ }
161
+ function jsonOf(body) {
162
+ try {
163
+ const text = typeof body === 'string' ? body : new TextDecoder('utf-8', { fatal: true }).decode(body);
164
+ return JSON.parse(text);
165
+ }
166
+ catch {
167
+ return fail('the body is not JSON');
168
+ }
169
+ }
170
+ /**
171
+ * Parses a hook body (after its signature was checked). Unknown fields are ignored; an unknown operation kind is
172
+ * accepted, so a newer server's operations still refresh the app.
173
+ *
174
+ * @param body - The raw body.
175
+ * @returns The payload; throws FoliwakeHookError when it is not a version 1 `delivery.settled` or `ping`.
176
+ */
177
+ export function parseFoliwakeHook(body) {
178
+ const fields = objectOf(jsonOf(body), 'the body');
179
+ if (fields.version !== 1)
180
+ fail('version is not 1');
181
+ const site = stringOf(fields, 'site');
182
+ const sentAt = stringOf(fields, 'sentAt');
183
+ if (fields.event === 'ping')
184
+ return { version: 1, event: 'ping', site, sentAt };
185
+ if (fields.event === 'delivery.settled')
186
+ return deliveryOf(fields, site, sentAt);
187
+ return fail('event is neither delivery.settled nor ping');
188
+ }
@@ -0,0 +1,3 @@
1
+ import { type HtmlNode } from './html.js';
2
+ /** The first `<h1>`'s text, or null when there is none or it is empty. */
3
+ export declare function firstHeading(nodes: readonly HtmlNode[]): string | null;
@@ -0,0 +1,16 @@
1
+ // The title of a prepared body: the text of its first <h1>, whitespace collapsed, at most 200 characters.
2
+ import { elements } from './html.js';
3
+ const MAX_TITLE = 200;
4
+ function textOf(nodes) {
5
+ return nodes.map((node) => (node.type === 'text' ? node.data : textOf(node.children))).join('');
6
+ }
7
+ /** The first `<h1>`'s text, or null when there is none or it is empty. */
8
+ export function firstHeading(nodes) {
9
+ for (const element of elements(nodes)) {
10
+ if (element.name !== 'h1')
11
+ continue;
12
+ const text = textOf(element.children).replace(/\s+/g, ' ').trim().slice(0, MAX_TITLE);
13
+ return text === '' ? null : text;
14
+ }
15
+ return null;
16
+ }
package/dist/page.d.ts CHANGED
@@ -28,11 +28,21 @@ export interface PrepareOptions {
28
28
  /** The app's own change of the body (allow-list, artwork, …); its output is checked again. */
29
29
  transform?: (html: string, envelope: PageEnvelope) => string;
30
30
  }
31
- /** The same-origin URL of the blocks module, or null when the config names no blocks entry. */
32
- export declare function blocksUrlOf(config: FoliwakeAppConfig, channel: ChannelName, codeRelease: CodeReleaseId): {
31
+ /**
32
+ * The same-origin URL of the blocks module, or null without an entry.
33
+ *
34
+ * @param entry - The module inside the code release; default the config's `app.blocks.entry`.
35
+ */
36
+ export declare function blocksUrlOf(config: FoliwakeAppConfig, channel: ChannelName, codeRelease: CodeReleaseId, entry?: string | null): {
33
37
  base: string;
34
38
  url: string;
35
39
  } | null;
40
+ /** The blocks a page mounts: the config's, or (version 3 without `app.blocks`) the ones its code release names. */
41
+ export declare function pageBlocksOf(config: FoliwakeAppConfig, envelope: PageEnvelope): {
42
+ entry: string | null;
43
+ major: number;
44
+ eventPrefix: string;
45
+ };
36
46
  /**
37
47
  * Per request, after the cache: check → rewrite media/links → transform → check again → serialise.
38
48
  *
package/dist/page.js CHANGED
@@ -1,10 +1,12 @@
1
1
  // Reading a page from the origin (the envelope: the only thing an app caches) and preparing it per request
2
2
  // (design §6.5, §9.4): check → rewrite media and links → the app's transform → check again.
3
3
  import { createHash } from 'node:crypto';
4
+ import { BLOCKS_HEADER, parseBlocksHeader } from './blocks-header.js';
4
5
  import { appOf, isLoopbackName, pageAllowed } from './config.js';
5
6
  import { CODE_ID_PATTERN, LIMITS, PAGE_PATH_PATTERN } from './constants.js';
6
7
  import { FoliwakePageError } from './errors.js';
7
8
  import { checkBody, componentNames, elements, serialize } from './html.js';
9
+ import { firstHeading } from './page-title.js';
8
10
  import { mediaRewriter } from './media-rewrite.js';
9
11
  import { readLimited, TooLargeError } from './stream.js';
10
12
  export { FoliwakePageError } from './errors.js';
@@ -12,7 +14,7 @@ export { pageImportMap } from '@foliwake/blocks-contract/import-map';
12
14
  const HTML_CONTRACT = /^\d{1,4}$/;
13
15
  const LANG = /^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*$/;
14
16
  const PAGE_ID = /^[A-Za-z0-9_-]{1,128}$/;
15
- const GENERATION = /^[A-Za-z0-9_.:-]{1,128}$/;
17
+ const GENERATION = /^\d{1,15}$/;
16
18
  const MODE = /^[a-z][a-z0-9-]{0,31}$/;
17
19
  /** The origin URL path of a page's body (`/` → `/index.plain.html`). */
18
20
  export function plainPath(pagePath) {
@@ -29,6 +31,10 @@ function header(response, name, pattern, required = false) {
29
31
  throw new FoliwakePageError('invalid', `The origin answered an invalid ${name}.`);
30
32
  return value;
31
33
  }
34
+ /** `X-Site-Generation` as a number: a non-negative integer, or null when the origin sent none. */
35
+ function generationOf(value) {
36
+ return value === null ? null : Number(value);
37
+ }
32
38
  const NO_CODE_RELEASE = 'The origin answered without X-Code-Release: it is not a plain/2 Foliwake origin.';
33
39
  function codeReleaseOf(response, client, channel) {
34
40
  const value = response.headers.get('x-code-release');
@@ -87,8 +93,9 @@ export async function readEnvelope(config, client, site, channel, path) {
87
93
  const htmlContract = header(response, 'x-html-contract', HTML_CONTRACT, true);
88
94
  const lang = header(response, 'content-language', LANG);
89
95
  const pageId = header(response, 'x-page-id', PAGE_ID);
90
- const generation = header(response, 'x-site-generation', GENERATION);
96
+ const generation = generationOf(header(response, 'x-site-generation', GENERATION));
91
97
  const etag = response.headers.get('etag');
98
+ const blocks = parseBlocksHeader(response.headers.get(BLOCKS_HEADER));
92
99
  let bytes;
93
100
  try {
94
101
  bytes = await readLimited(response, LIMITS.body);
@@ -106,7 +113,8 @@ export async function readEnvelope(config, client, site, channel, path) {
106
113
  throw new FoliwakePageError('invalid', 'The body is not UTF-8.');
107
114
  }
108
115
  checkBody(html, path); // an invalid body is refused before anything caches it
109
- return { site, channel, path, html, codeRelease, htmlContract, lang, pageId, etag: etag && etag.length <= 200 ? etag : null, generation };
116
+ const keptEtag = etag && etag.length <= 200 ? etag : null;
117
+ return { site, channel, path, html, codeRelease, htmlContract, lang, pageId, etag: keptEtag, generation, blocks };
110
118
  }
111
119
  function rewrite(nodes, config, channel, rewriteLink) {
112
120
  const media = mediaRewriter(appOf(config), channel);
@@ -127,13 +135,24 @@ function rewrite(nodes, config, channel, rewriteLink) {
127
135
  }
128
136
  }
129
137
  }
130
- /** The same-origin URL of the blocks module, or null when the config names no blocks entry. */
131
- export function blocksUrlOf(config, channel, codeRelease) {
132
- const app = appOf(config);
133
- if (!app.blocks.entry)
138
+ /**
139
+ * The same-origin URL of the blocks module, or null without an entry.
140
+ *
141
+ * @param entry - The module inside the code release; default the config's `app.blocks.entry`.
142
+ */
143
+ export function blocksUrlOf(config, channel, codeRelease, entry = appOf(config).blocks.entry) {
144
+ if (!entry)
134
145
  return null;
135
- const base = `${app.proxies.code}${channel === 'preview' ? '/preview' : ''}/${codeRelease}/`;
136
- return { base, url: `${base}${app.blocks.entry}` };
146
+ const base = `${appOf(config).proxies.code}${channel === 'preview' ? '/preview' : ''}/${codeRelease}/`;
147
+ return { base, url: `${base}${entry}` };
148
+ }
149
+ /** The blocks a page mounts: the config's, or (version 3 without `app.blocks`) the ones its code release names. */
150
+ export function pageBlocksOf(config, envelope) {
151
+ const own = appOf(config).blocks;
152
+ const named = envelope.blocks ?? null;
153
+ if (!own.fromRelease || named === null)
154
+ return { entry: own.entry, major: own.major, eventPrefix: own.eventPrefix };
155
+ return { entry: named.entry, major: named.contract, eventPrefix: named.eventPrefix };
137
156
  }
138
157
  /** The React key of a prepared page: see `FoliwakePageData.identity`. */
139
158
  function identityOf(envelope, mode, digest) {
@@ -148,7 +167,6 @@ function identityOf(envelope, mode, digest) {
148
167
  * fills it). Throws FoliwakePageError('invalid') when the body or the transform's output is refused.
149
168
  */
150
169
  export function preparePage(config, envelope, opts = {}) {
151
- const app = appOf(config);
152
170
  const mode = opts.mode ?? null;
153
171
  if (mode !== null && (typeof mode !== 'string' || !MODE.test(mode)))
154
172
  throw new FoliwakePageError('invalid', `mode must be a token [a-z][a-z0-9-], at most 32 characters`);
@@ -161,8 +179,9 @@ export function preparePage(config, envelope, opts = {}) {
161
179
  html = opts.transform(html, envelope);
162
180
  const final = checkBody(html, envelope.path); // a transform cannot add what the first check refused
163
181
  html = serialize(final);
164
- const blocks = blocksUrlOf(config, envelope.channel, envelope.codeRelease);
165
- const contract = { major: app.blocks.major, eventPrefix: app.blocks.eventPrefix };
182
+ const named = pageBlocksOf(config, envelope);
183
+ const blocks = blocksUrlOf(config, envelope.channel, envelope.codeRelease, named.entry);
184
+ const contract = { major: named.major, eventPrefix: named.eventPrefix };
166
185
  // The digest covers what the browser mounts: the final prepared body (after the app's transform, so two
167
186
  // transforms of one envelope differ, and a missing ETag cannot collide) and every mount-defining setting.
168
187
  const digest = createHash('sha256')
@@ -176,6 +195,7 @@ export function preparePage(config, envelope, opts = {}) {
176
195
  path: envelope.path,
177
196
  mode,
178
197
  html,
198
+ title: firstHeading(final),
179
199
  codeRelease: envelope.codeRelease,
180
200
  htmlContract: envelope.htmlContract,
181
201
  lang: envelope.lang,
package/dist/preload.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { FoliwakePageData, PreloadHint } from '@foliwake/blocks-contract/page';
2
- import { type FoliwakeAppConfig } from './config.js';
2
+ import type { FoliwakeAppConfig } from './config.js';
3
3
  import type { OriginClient } from './origin.js';
4
4
  export type { PreloadHint } from '@foliwake/blocks-contract/page';
5
5
  /** A path inside the code release the proxy would serve, or null. */
package/dist/preload.js CHANGED
@@ -12,7 +12,6 @@
12
12
  // optimisation: a failed read gives fewer hints, never an error. Every href is a same-origin proxy URL
13
13
  // (`<proxies.code>[/preview]/<cd>/<path>`) that the code proxy's allow-list accepts, so CSP 'self' covers it.
14
14
  import { KIT_PATH, KIT_SPECIFIER } from '@foliwake/blocks-contract/import-map';
15
- import { appOf } from './config.js';
16
15
  import { CODE_ROOTS, CODE_SEGMENT } from './constants.js';
17
16
  import { readLimited } from './stream.js';
18
17
  const MAX_MODULES = 48;
@@ -82,9 +81,10 @@ async function readText(client, channel, cd, file) {
82
81
  }
83
82
  /** Hints for a prepared page: modulepreload for its modules, preload as=style for its block stylesheets. */
84
83
  export async function preloadHints(config, client, page) {
85
- const app = appOf(config);
86
- if (!page.codeBase || !page.codeRelease || !app.blocks.entry)
84
+ // The entry is the page's (the config's, or the one its code release names), as preparePage chose it.
85
+ if (!page.codeBase || !page.codeRelease || !page.blocksUrl?.startsWith(page.codeBase))
87
86
  return [];
87
+ const entry = page.blocksUrl.slice(page.codeBase.length);
88
88
  const cd = page.codeRelease;
89
89
  const descriptorText = await readText(client, page.channel, cd, 'components/components.json');
90
90
  let declared = {};
@@ -96,7 +96,7 @@ export async function preloadHints(config, client, page) {
96
96
  catch {
97
97
  declared = {};
98
98
  }
99
- const roots = [app.blocks.entry];
99
+ const roots = [entry];
100
100
  const styles = [];
101
101
  for (const name of page.blocks) {
102
102
  const entry = declared[name];