@cloudhal/astro-renderer 0.6.4 → 0.7.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.
@@ -36,8 +36,12 @@
36
36
  * before the first publish, `preview-expired` for a preview token that does not verify,
37
37
  * `unavailable` for a Worker that serves no site — and answers page paths with the renderer's
38
38
  * own page (`status-page.ts`: 503/410, `Retry-After`, `no-store`, its own CSP), restyled by the
39
- * theme's optional `statusPage` hook. A failure anywhere becomes the `error` page (500) with the
40
- * `cf-ray` as its reference. `GET /__cloudhal/health` answers `{ ok, state }` for monitors.
39
+ * theme's optional `statusPage` hook. Machine paths get a short plain answer for an invalid
40
+ * preview token or an unreadable store (`status-entry.ts`). A store that cannot be read before
41
+ * rendering is `unavailable` (503, `Retry-After: 300`); a thrown error or Astro's own 500 page
42
+ * becomes the `error` page (500) with the `cf-ray` as its reference, in the site's language
43
+ * once the request has read the site; any 5xx the theme or renderer answers on purpose passes.
44
+ * `GET /__cloudhal/health` answers `{ ok, state }` for monitors.
41
45
  */
42
46
  import { type CommentsRateLimit } from "./comments.js";
43
47
  import { type RedirectEnv } from "./host-redirect.js";
@@ -36,8 +36,12 @@
36
36
  * before the first publish, `preview-expired` for a preview token that does not verify,
37
37
  * `unavailable` for a Worker that serves no site — and answers page paths with the renderer's
38
38
  * own page (`status-page.ts`: 503/410, `Retry-After`, `no-store`, its own CSP), restyled by the
39
- * theme's optional `statusPage` hook. A failure anywhere becomes the `error` page (500) with the
40
- * `cf-ray` as its reference. `GET /__cloudhal/health` answers `{ ok, state }` for monitors.
39
+ * theme's optional `statusPage` hook. Machine paths get a short plain answer for an invalid
40
+ * preview token or an unreadable store (`status-entry.ts`). A store that cannot be read before
41
+ * rendering is `unavailable` (503, `Retry-After: 300`); a thrown error or Astro's own 500 page
42
+ * becomes the `error` page (500) with the `cf-ray` as its reference, in the site's language
43
+ * once the request has read the site; any 5xx the theme or renderer answers on purpose passes.
44
+ * `GET /__cloudhal/health` answers `{ ok, state }` for monitors.
41
45
  */
42
46
 
43
47
  import { cache } from "cloudflare:workers";
@@ -48,8 +52,8 @@ import { WaeWriter } from "@cloudhal/analytics/wae";
48
52
  import {
49
53
  analyticsBackend,
50
54
  CACHE_TAG_PREFIX,
55
+ loadedSite,
51
56
  resetSource,
52
-
53
57
  serveMedia,
54
58
  siteState,
55
59
  withRequestSite,
@@ -71,10 +75,19 @@ import { EMBED_HEADER, withEmbedFrames } from "./embed-client.js";
71
75
  import { hostRedirect, } from "./host-redirect.js";
72
76
  import { PREVIEW_PARAM } from "./resolver.js";
73
77
  import { SearchLimiter, searchCost } from "./search-limit.js";
74
- import { SiteDispatch, unknownHost, withNoindex } from "./site-dispatch.js";
78
+ import { SiteDispatch, unknownHost, withNoindex } from "./site-dispatch.js";
79
+ import {
80
+ errorPage,
81
+ HEALTH_PATH,
82
+ health,
83
+ hostLookupFailed,
84
+
85
+ statusStep,
86
+ withErrorPage,
87
+ } from "./status-entry.js";
75
88
  import { renderStatus, themeStatusHook } from "./status-hook.js";
76
- import { statusPage } from "./status-page.js";
77
- import { isStatusPagePath, statusInput } from "./status-serve.js";
89
+
90
+ import { statusInput } from "./status-serve.js";
78
91
 
79
92
 
80
93
 
@@ -157,65 +170,6 @@ let dispatch ;
157
170
  /** RFC-0043 §1.7: the theme's `statusPage` hook, loaded the first time a status page is drawn. */
158
171
  const statusHook = themeStatusHook(loadTheme, (m, e) => console.error(m, e));
159
172
 
160
- /** RFC-0043 §1.3: the `error` page's reference — Cloudflare's ray id, else a random one. */
161
- function referenceId(request ) {
162
- return (
163
- request.headers.get("cf-ray") ??
164
- Array.from(crypto.getRandomValues(new Uint8Array(8)), (b) =>
165
- b.toString(16).padStart(2, "0"),
166
- ).join("")
167
- );
168
- }
169
-
170
- /** The `error` page (RFC-0043 §1.2): never the theme's hook, nothing read from the store. */
171
- function errorPage(request , error ) {
172
- const rayId = referenceId(request);
173
- console.error(`cloudhal: request failed (reference ${rayId})`, error);
174
- return statusPage("error", { locale: "en", now: Date.now(), rayId }, { method: request.method });
175
- }
176
-
177
- /**
178
- * A 5xx HTML answer from Astro becomes the `error` page unless the theme marked it as its own
179
- * (`x-cloudhal-error-page: theme`, a theme's `500.astro`).
180
- */
181
- function withErrorPage(response , request ) {
182
- if (
183
- response.status < 500 ||
184
- !(response.headers.get("content-type") ?? "").includes("text/html") ||
185
- response.headers.get("x-cloudhal-error-page") === "theme"
186
- )
187
- return response;
188
- return errorPage(request, new Error(`Astro answered ${response.status}`));
189
- }
190
-
191
- /**
192
- * RFC-0043 §1.9: `{ ok, state }`, the admin's `/api/health` shape plus the site's state, so one
193
- * monitor rule reads both. Public, never cached, never indexed; reads only the memoised pointer.
194
- */
195
- async function health(request ) {
196
- const headers = {
197
- "cache-control": "no-store",
198
- "cloudflare-cdn-cache-control": "no-store",
199
- "x-robots-tag": "noindex",
200
- };
201
- if (request.method !== "GET" && request.method !== "HEAD")
202
- return Response.json(
203
- { error: "method_not_allowed" },
204
- { status: 405, headers: { ...headers, allow: "GET" } },
205
- );
206
- try {
207
- const state = await siteState(request);
208
- if (state.kind === "unavailable") return Response.json({ ok: false }, { status: 503, headers });
209
- return Response.json(
210
- { ok: true, state: state.kind === "not-published" ? "not-published" : "published" },
211
- { headers },
212
- );
213
- } catch (error) {
214
- console.error("cloudhal: health check could not read the store", error);
215
- return Response.json({ ok: false }, { status: 503, headers });
216
- }
217
- }
218
-
219
173
  /** One per isolate: which site a request is for (RFC-0034 §4). */
220
174
  function siteDispatch(env , siteIdFromBuild ) {
221
175
  dispatch ??= new SiteDispatch({
@@ -582,6 +536,7 @@ async function serveSite(
582
536
  cacheOnlySuccess((await handle(request, env , ctx)) ),
583
537
  ),
584
538
  request,
539
+ { site: loadedSite() },
585
540
  );
586
541
  // Server-side render events (§5.4), off the response path: published HTML 200s (cache
587
542
  // misses), redirects, 404, 410, 451 and 5xx; never previews or HEAD.
@@ -611,7 +566,7 @@ async function serveSite(
611
566
  */
612
567
  async function statusResponse(
613
568
  call ,
614
- state ,
569
+ state ,
615
570
  siteId ,
616
571
  ) {
617
572
  const { request, env, ctx } = call;
@@ -643,6 +598,20 @@ async function statusResponse(
643
598
  return response;
644
599
  }
645
600
 
601
+ /** A status page before any site is known (the hostname map failed): English, no site data. */
602
+ async function siteless(request , state ) {
603
+ return renderStatus(
604
+ state.kind,
605
+ { locale: "en", now: Date.now() },
606
+ {
607
+ hook: await statusHook(),
608
+ method: request.method,
609
+ csp: SITE_CSP,
610
+ onFailure: (m, e) => console.error(m, e),
611
+ },
612
+ );
613
+ }
614
+
646
615
  export function createSiteWorker(options = {}) {
647
616
  const searchLimiter = new SearchLimiter();
648
617
  async function route(request , env , ctx ) {
@@ -653,19 +622,30 @@ export function createSiteWorker(options = {}) {
653
622
  if (moved) return moved;
654
623
  // RFC-0034 §4: the hostname picks the site on a multi-site Worker; everything the request
655
624
  // runs (Astro's render included) then sees that site.
656
- const choice = await siteDispatch(env, options.siteId).choose(request);
625
+ let choice ;
626
+ try {
627
+ choice = await siteDispatch(env, options.siteId).choose(request);
628
+ } catch (error) {
629
+ // A store that cannot be read is `unavailable` (503), as health says, never `error`.
630
+ return hostLookupFailed(request, error, { page: (state) => siteless(request, state) });
631
+ }
657
632
  if (choice.kind === "unknown") return unknownHost();
658
633
  // Without `CLOUDHAL_SITE_ID` a single-site Worker serves the site it was built for, as
659
634
  // Astro's `getSource` always did; `unavailable` is for a site row that is gone (§2.5).
660
635
  const siteId = choice.siteId ?? config.siteId;
661
636
  const call = { request, env, ctx };
662
637
  const run = async () => {
663
- if (url.pathname === "/__cloudhal/health") return health(request);
664
- const page =
665
- (request.method === "GET" || request.method === "HEAD") && isStatusPagePath(url.pathname);
666
- const state = page ? await siteState(request) : undefined;
667
- if (state && state.kind !== "serve") return statusResponse(call, state, siteId);
668
- return serveSite(call, siteId, searchLimiter);
638
+ try {
639
+ if (url.pathname === HEALTH_PATH) return await health(request, () => siteState(request));
640
+ const status = await statusStep(request, {
641
+ state: () => siteState(request),
642
+ page: (state) => statusResponse(call, state, siteId),
643
+ });
644
+ return status ?? (await serveSite(call, siteId, searchLimiter));
645
+ } catch (error) {
646
+ // RFC-0043 §1.6: inside the request's site, so the page can use what it already read.
647
+ return errorPage(request, error, { site: loadedSite() });
648
+ }
669
649
  };
670
650
  const response = await withRequestSite(siteId, run);
671
651
  return choice.noindex ? withNoindex(response) : response;
package/dist/src/feeds.js CHANGED
@@ -5,6 +5,7 @@
5
5
  */
6
6
 
7
7
  import { collectionSettings, entryPath } from "@cloudhal/core-ts";
8
+ import { trimEndChar } from "@cloudhal/core-ts/names";
8
9
 
9
10
  import { markdownText, renderBody } from "./markdown.js";
10
11
 
@@ -214,7 +215,7 @@ export function redirectsFile(redirects ) {
214
215
  .sort((a, b) => b.from.length - a.from.length || a.from.localeCompare(b.from));
215
216
  const splat = (to ) => {
216
217
  const i = to.search(/[?#]/);
217
- const head = (i < 0 ? to : to.slice(0, i)).replace(/\/+$/, "");
218
+ const head = trimEndChar(i < 0 ? to : to.slice(0, i), "/");
218
219
  return `${head}/:splat${i < 0 ? "" : to.slice(i)}`;
219
220
  };
220
221
  const lines = [
@@ -9,6 +9,7 @@
9
9
 
10
10
  import { entryPath, termSlug } from "@cloudhal/core-ts";
11
11
  import { localeRouting, localeUrl, localizedPath } from "@cloudhal/core-ts/locale-paths";
12
+ import { trimEndChar } from "@cloudhal/core-ts/names";
12
13
  import { routableEntries } from "./entry-views.js";
13
14
 
14
15
 
@@ -247,7 +248,7 @@ export function localizeLinks(html , localize )
247
248
  const cut = url.search(/[?#]/);
248
249
  const path = cut < 0 ? url : url.slice(0, cut);
249
250
  const suffix = cut < 0 ? "" : url.slice(cut);
250
- return `${head}${localize(path.length > 1 ? path.replace(/\/+$/, "") : path)}${suffix}${tail}`;
251
+ return `${head}${localize(path.length > 1 ? trimEndChar(path, "/") : path)}${suffix}${tail}`;
251
252
  };
252
253
  return html
253
254
  .replace(/(<(?:a|form)\b[^>]*?\s(?:href|action)=")(\/[^"]*)(")/gi, swap)
@@ -3,6 +3,7 @@ import { createBlockRegistry } from "@cloudhal/core-ts/block
3
3
  import { directiveExtension } from "@cloudhal/core-ts/body-blocks";
4
4
  import { checkDirective, directiveProps } from "@cloudhal/core-ts/directives";
5
5
  import { ASSET_HREF, assetUrl, mediaPath } from "@cloudhal/core-ts/media";
6
+ import { trimChar } from "@cloudhal/core-ts/names";
6
7
  import { parseSurfaceFence } from "@cloudhal/core-ts/surfaces";
7
8
  import { Marked } from "marked";
8
9
  import { builtInBlockHtml, isBuiltInBlock, missingBlockHtml } from "./block-html.js";
@@ -48,17 +49,14 @@ const RESERVED_ID = /^(?:comment|cloudhal|ch-)/;
48
49
  * Latin letters or digits falls back to `section`; repeats get `-2`, `-3`, ….
49
50
  */
50
51
  export function headingSlug(text , taken ) {
51
- const base =
52
- text
53
- .replace(/[ıİşŞğĞ]/g, (c) => TURKISH[c] ?? c)
54
- .normalize("NFKD")
55
- .replace(/[̀-ͯ]/g, "")
56
- .toLowerCase()
57
- .replace(/ß/g, "ss")
58
- .replace(/[^a-z0-9]+/g, "-")
59
- .replace(/^-+|-+$/g, "")
60
- .slice(0, 64)
61
- .replace(/-+$/, "") || "section";
52
+ const dashed = text
53
+ .replace(/[ıİşŞğĞ]/g, (c) => TURKISH[c] ?? c)
54
+ .normalize("NFKD")
55
+ .replace(/[̀-ͯ]/g, "")
56
+ .toLowerCase()
57
+ .replace(/ß/g, "ss")
58
+ .replace(/[^a-z0-9]+/g, "-");
59
+ const base = trimChar(trimChar(dashed, "-").slice(0, 64), "-") || "section";
62
60
  const slug = RESERVED_ID.test(base) || /^\d/.test(base) ? `h-${base}` : base;
63
61
  if (!taken) return slug;
64
62
  const seen = taken.get(slug) ?? 0;
@@ -66,6 +66,13 @@ export declare class SiteResolver {
66
66
  /** Forget the cached pointer (e.g. after a publish handled in the same isolate). */
67
67
  invalidate(): void;
68
68
  site(): Promise<Site>;
69
+ /**
70
+ * RFC-0043 §1.6: the site node a public page may name for `resolution`, never a new store
71
+ * read: the published snapshot's (already loaded, or loaded for the render anyway) for a
72
+ * published site, so an unpublished rename or locale never shows; the live row `resolve` just
73
+ * read before the first publish; nothing for a preview. `undefined` when it cannot be read.
74
+ */
75
+ publicSite(resolution: Resolution): Promise<Site | undefined>;
69
76
  snapshot(id: string): Promise<SnapshotSource>;
70
77
  resolve(request: Request): Promise<Resolution>;
71
78
  }
@@ -115,6 +115,18 @@ export class SiteResolver {
115
115
  return this.#pointer.site;
116
116
  }
117
117
 
118
+ /**
119
+ * RFC-0043 §1.6: the site node a public page may name for `resolution`, never a new store
120
+ * read: the published snapshot's (already loaded, or loaded for the render anyway) for a
121
+ * published site, so an unpublished rename or locale never shows; the live row `resolve` just
122
+ * read before the first publish; nothing for a preview. `undefined` when it cannot be read.
123
+ */
124
+ async publicSite(resolution ) {
125
+ if (resolution.kind === "preview") return undefined;
126
+ if (resolution.kind === "unpublished") return this.#pointer?.site;
127
+ return resolution.source.site().catch(() => undefined);
128
+ }
129
+
118
130
  snapshot(id ) {
119
131
  let entry = this.#snapshots.get(id);
120
132
  if (entry) {
@@ -36,6 +36,12 @@ export interface AstroLike {
36
36
  }
37
37
  /** Runs `fn` (and everything it awaits) as a request for `siteId`. */
38
38
  export declare function withRequestSite<T>(siteId: string, fn: () => T): T;
39
+ /**
40
+ * RFC-0043 §1.6: the site node this request already read (its name and locales), for the
41
+ * `error` page; `undefined` before a successful read. Never reads the store: it may be what
42
+ * failed. Only inside `withRequestSite`.
43
+ */
44
+ export declare function loadedSite(): Site | undefined;
39
45
  /** Runs `fn` (and everything it awaits) as a request for `siteId` over `store`. */
40
46
  export declare function withRequestStore<T>(store: SiteGraphStore, siteId: string, fn: () => T): T;
41
47
  /** Test/purge hook: forget cached state in this isolate, for one site or all of them. */
@@ -25,6 +25,7 @@ import { usableCommentsKey } from "./comments.js";
25
25
  import { matchMediaRoute, serveMediaRequest } from "./media-route.js";
26
26
  import { PREVIEW_PARAM, SiteResolver } from "./resolver.js";
27
27
 
28
+ import { markInvalidPreview } from "./status-serve.js";
28
29
 
29
30
  /** RFC-0029 §3: `AI_SEARCH`, `SEARCH_BUCKET` and `CLOUDHAL_SEARCH_*` turn on semantic search. */
30
31
 
@@ -49,11 +50,20 @@ import { PREVIEW_PARAM, SiteResolver } from "./resolver.js";
49
50
  * Worker) around everything the request runs, Astro's render included. Module state, not a header:
50
51
  * a client cannot choose it.
51
52
  */
52
- const requestSite = new AsyncLocalStorage ();
53
+ const requestSite = new AsyncLocalStorage ();
53
54
 
54
55
  /** Runs `fn` (and everything it awaits) as a request for `siteId`. */
55
56
  export function withRequestSite (siteId , fn ) {
56
- return requestSite.run(siteId, fn);
57
+ return requestSite.run({ siteId }, fn);
58
+ }
59
+
60
+ /**
61
+ * RFC-0043 §1.6: the site node this request already read (its name and locales), for the
62
+ * `error` page; `undefined` before a successful read. Never reads the store: it may be what
63
+ * failed. Only inside `withRequestSite`.
64
+ */
65
+ export function loadedSite() {
66
+ return requestSite.getStore()?.site;
57
67
  }
58
68
 
59
69
  /**
@@ -73,7 +83,7 @@ export function withRequestStore (store , siteId , fn
73
83
  function siteOf(fallback ) {
74
84
  return (
75
85
  requestStore.getStore()?.siteId ??
76
- requestSite.getStore() ??
86
+ requestSite.getStore()?.siteId ??
77
87
  (env ).CLOUDHAL_SITE_ID ??
78
88
  fallback
79
89
  );
@@ -155,6 +165,19 @@ function resolveRequest(r , request )
155
165
  if (!pending) {
156
166
  pending = r.resolve(request);
157
167
  resolutions.set(request, pending);
168
+ const context = requestSite.getStore();
169
+ // RFC-0043 §1.6: the `error` page's site, filled in the background, never awaited here (a
170
+ // published site's node comes with the snapshot load, which a render awaits anyway, so it is
171
+ // known by the time one fails). Health renders no page and reads only the pointer.
172
+ if (context && new URL(request.url).pathname !== "/__cloudhal/health")
173
+ pending
174
+ .then((resolution) => r.publicSite(resolution))
175
+ .then(
176
+ (site) => {
177
+ if (site?.id === context.siteId) context.site = site;
178
+ },
179
+ () => {},
180
+ );
158
181
  }
159
182
  return pending;
160
183
  }
@@ -335,11 +358,7 @@ export async function getSource(
335
358
  h.set("cache-tag", siteCacheTag(siteId));
336
359
  h.set("x-cloudhal-mode", "published");
337
360
  h.set("x-cloudhal-snapshot", resolution.snapshotId);
338
- if (resolution.previewError) {
339
- // An invalid preview link must not poison the cache entry for this URL.
340
- h.set("cloudflare-cdn-cache-control", "no-store");
341
- h.set("x-cloudhal-preview-error", resolution.previewError);
342
- }
361
+ if (resolution.previewError) markInvalidPreview(h);
343
362
  return resolution.source;
344
363
  }
345
364
 
@@ -374,10 +393,7 @@ export async function serveMedia(
374
393
  blobs: store.blobs,
375
394
  ...(preview && token ? { keepQuery: `${PREVIEW_PARAM}=${encodeURIComponent(token)}` } : {}),
376
395
  });
377
- if (response && resolution.kind === "published" && resolution.previewError) {
378
- // An invalid preview link must not poison the edge cache entry for this URL.
379
- response.headers.set("cloudflare-cdn-cache-control", "no-store");
380
- response.headers.set("x-cloudhal-preview-error", resolution.previewError);
381
- }
396
+ if (response && resolution.kind === "published" && resolution.previewError)
397
+ markInvalidPreview(response.headers);
382
398
  return response;
383
399
  }
@@ -25,6 +25,8 @@ export declare function resetSource(_siteId?: string): void;
25
25
  * serves the project's one site, so this only runs `fn`.
26
26
  */
27
27
  export declare function withRequestSite<T>(_siteId: string, fn: () => T): T;
28
+ /** RFC-0043 §1.6: the `workerd` build's per-request site; `cloudhal dev` keeps none. */
29
+ export declare function loadedSite(): Site | undefined;
28
30
  /**
29
31
  * RFC-0036 §4: on workerd a playground runs each request over its session's store; `cloudhal dev`
30
32
  * renders from the project's local store, so this only runs `fn`.
@@ -58,6 +58,11 @@ export function withRequestSite (_siteId , fn ) {
58
58
  return fn();
59
59
  }
60
60
 
61
+ /** RFC-0043 §1.6: the `workerd` build's per-request site; `cloudhal dev` keeps none. */
62
+ export function loadedSite() {
63
+ return undefined;
64
+ }
65
+
61
66
  /**
62
67
  * RFC-0036 §4: on workerd a playground runs each request over its session's store; `cloudhal dev`
63
68
  * renders from the project's local store, so this only runs `fn`.
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The Site Worker entry's status step, `error` page, health endpoint and the answer when the
3
+ * hostname cannot be mapped to a site (RFC-0043 §1.2, §1.8, §1.9, §2.5), apart from
4
+ * `cloudflare-entry.ts` so unit tests run them: no bindings, no Astro, no `cloudflare:` imports.
5
+ * Worker-safe.
6
+ */
7
+ import type { Site } from "@cloudhal/core-contracts";
8
+ import type { SiteStateResult } from "./runtime-workerd.js";
9
+ /** A state the entry answers itself. */
10
+ export type StatusState = Exclude<SiteStateResult, {
11
+ kind: "serve";
12
+ }>;
13
+ type Log = (message: string, error?: unknown) => void;
14
+ /** §1.3: the `error` page's reference — Cloudflare's ray id, else a random one. */
15
+ export declare function referenceId(request: Request): string;
16
+ export interface ErrorPageOptions {
17
+ /** The site node this request already read (`loadedSite()`); never read here (§1.6). */
18
+ readonly site?: Site | undefined;
19
+ readonly log?: Log | undefined;
20
+ readonly now?: number | undefined;
21
+ }
22
+ /**
23
+ * The `error` page (§1.2): never the theme's hook, nothing read from the store. In the site's
24
+ * locale and with its name when this request already read the site (§1.4, §1.6), else English.
25
+ */
26
+ export declare function errorPage(request: Request, error: unknown, options?: ErrorPageOptions): Response;
27
+ /**
28
+ * §1.8: Astro's own 500 (a render that threw) becomes the `error` page — HTML, or Astro's empty
29
+ * fallback (`new Response(null, { status: 500 })` when no `500.astro` renders: the starter's
30
+ * catch-all route matches `/500` and throws again). What the renderer or the theme answered on
31
+ * purpose passes unchanged and logs nothing: a status page (`x-cloudhal-state`, e.g. the
32
+ * starter's `not-published` 503 for a request that reaches Astro), a theme's `500.astro`
33
+ * (`x-cloudhal-error-page: theme`), a 500 with an explicit non-HTML type, and any other 5xx.
34
+ */
35
+ export declare function withErrorPage(response: Response, request: Request, options?: ErrorPageOptions): Response;
36
+ export interface StatusStepOptions {
37
+ /** The request's verdict (the runtime's `siteState`); a throw is a store read failure. */
38
+ readonly state: () => Promise<SiteStateResult>;
39
+ /** Draws the status page for a page path (theme hook, render event). */
40
+ readonly page: (state: StatusState) => Promise<Response>;
41
+ readonly log?: Log | undefined;
42
+ readonly now?: (() => number) | undefined;
43
+ }
44
+ /**
45
+ * §2.5 step 6, for `GET`/`HEAD`: the status answer for this request, or `undefined` to serve the
46
+ * site. Page paths get the page of every state. Machine paths (§2.3) get a short plain or JSON
47
+ * answer for `preview-expired` (decision 12: never the published content) and `unavailable`;
48
+ * before the first publish they keep the theme's own `statusPlain`. A store that cannot be read
49
+ * is `unavailable` (503, `Retry-After: 300`), as `/__cloudhal/health` reports it.
50
+ */
51
+ export declare function statusStep(request: Request, options: StatusStepOptions): Promise<Response | undefined>;
52
+ export declare const HEALTH_PATH = "/__cloudhal/health";
53
+ /**
54
+ * §1.9: `{ ok, state }`, the admin's `/api/health` shape plus the site's state, so one monitor
55
+ * rule reads both. Public, never cached, never indexed; reads only the memoised pointer.
56
+ */
57
+ export declare function health(request: Request, state: () => Promise<SiteStateResult>, log?: Log): Promise<Response>;
58
+ /**
59
+ * RFC-0034 §4 with §1.2: on a multi-site Worker the hostname map could not be read (the store
60
+ * failed past the map's TTL), so no site is known. Treated as a store failure, never as `error`:
61
+ * health answers `503 { ok: false }`; `GET`/`HEAD` page paths the `unavailable` page and machine
62
+ * paths its plain answer (503, `Retry-After: 300`, English, no site name); anything else a
63
+ * plain 503.
64
+ */
65
+ export declare function hostLookupFailed(request: Request, error: unknown, options: Pick<StatusStepOptions, "page" | "log" | "now">): Promise<Response>;
66
+ export {};
@@ -0,0 +1,193 @@
1
+ /**
2
+ * The Site Worker entry's status step, `error` page, health endpoint and the answer when the
3
+ * hostname cannot be mapped to a site (RFC-0043 §1.2, §1.8, §1.9, §2.5), apart from
4
+ * `cloudflare-entry.ts` so unit tests run them: no bindings, no Astro, no `cloudflare:` imports.
5
+ * Worker-safe.
6
+ */
7
+
8
+
9
+ import { statusPage, statusPlain } from "./status-page.js";
10
+ import { statusInput, statusPathKind } from "./status-serve.js";
11
+
12
+ /** A state the entry answers itself. */
13
+
14
+
15
+
16
+
17
+ /** §1.3: the `error` page's reference — Cloudflare's ray id, else a random one. */
18
+ export function referenceId(request ) {
19
+ return (
20
+ request.headers.get("cf-ray") ??
21
+ Array.from(crypto.getRandomValues(new Uint8Array(8)), (b) =>
22
+ b.toString(16).padStart(2, "0"),
23
+ ).join("")
24
+ );
25
+ }
26
+
27
+
28
+  
29
+
30
+
31
+
32
+
33
+
34
+ /**
35
+ * The `error` page (§1.2): never the theme's hook, nothing read from the store. In the site's
36
+ * locale and with its name when this request already read the site (§1.4, §1.6), else English.
37
+ */
38
+ export function errorPage(
39
+ request ,
40
+ error ,
41
+ options = {},
42
+ ) {
43
+ const rayId = referenceId(request);
44
+ (options.log ?? console.error)(`cloudhal: request failed (reference ${rayId})`, error);
45
+ const now = options.now ?? Date.now();
46
+ let input = { locale: "en", now };
47
+ try {
48
+ const url = new URL(request.url);
49
+ input = statusInput(
50
+ "error",
51
+ { live: options.site },
52
+ { host: url.host, pathname: url.pathname },
53
+ now,
54
+ );
55
+ } catch {
56
+ // a malformed site node: the English page without a name
57
+ }
58
+ return statusPage("error", { ...input, rayId }, { method: request.method });
59
+ }
60
+
61
+ /**
62
+ * §1.8: Astro's own 500 (a render that threw) becomes the `error` page — HTML, or Astro's empty
63
+ * fallback (`new Response(null, { status: 500 })` when no `500.astro` renders: the starter's
64
+ * catch-all route matches `/500` and throws again). What the renderer or the theme answered on
65
+ * purpose passes unchanged and logs nothing: a status page (`x-cloudhal-state`, e.g. the
66
+ * starter's `not-published` 503 for a request that reaches Astro), a theme's `500.astro`
67
+ * (`x-cloudhal-error-page: theme`), a 500 with an explicit non-HTML type, and any other 5xx.
68
+ */
69
+ export function withErrorPage(
70
+ response ,
71
+ request ,
72
+ options = {},
73
+ ) {
74
+ const type = response.headers.get("content-type") ?? "";
75
+ if (
76
+ response.status !== 500 ||
77
+ (type !== "" && !type.includes("text/html")) ||
78
+ response.headers.has("x-cloudhal-state") ||
79
+ response.headers.get("x-cloudhal-error-page") === "theme"
80
+ )
81
+ return response;
82
+ return errorPage(request, new Error("Astro answered 500"), options);
83
+ }
84
+
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
+
93
+
94
+ /**
95
+ * §2.5 step 6, for `GET`/`HEAD`: the status answer for this request, or `undefined` to serve the
96
+ * site. Page paths get the page of every state. Machine paths (§2.3) get a short plain or JSON
97
+ * answer for `preview-expired` (decision 12: never the published content) and `unavailable`;
98
+ * before the first publish they keep the theme's own `statusPlain`. A store that cannot be read
99
+ * is `unavailable` (503, `Retry-After: 300`), as `/__cloudhal/health` reports it.
100
+ */
101
+ export async function statusStep(
102
+ request ,
103
+ options ,
104
+ ) {
105
+ if (request.method !== "GET" && request.method !== "HEAD") return undefined;
106
+ const url = new URL(request.url);
107
+ const kind = statusPathKind(url.pathname);
108
+ if (!kind) return undefined;
109
+ let state ;
110
+ try {
111
+ state = await options.state();
112
+ } catch (error) {
113
+ (options.log ?? console.error)("cloudhal: the store could not be read before rendering", error);
114
+ state = { kind: "unavailable" };
115
+ }
116
+ if (state.kind === "serve") return undefined;
117
+ if (kind === "page") return options.page(state);
118
+ if (state.kind === "not-published") return undefined;
119
+ const sites =
120
+ state.kind === "unavailable" ? {} : { live: state.site, published: state.published };
121
+ const input = statusInput(
122
+ state.kind,
123
+ sites,
124
+ { host: url.host, pathname: url.pathname },
125
+ (options.now ?? Date.now)(),
126
+ );
127
+ const as = url.pathname.toLowerCase().endsWith(".json") ? "json" : "text";
128
+ return statusPlain(state.kind, input, as, { method: request.method });
129
+ }
130
+
131
+ export const HEALTH_PATH = "/__cloudhal/health";
132
+
133
+ const HEALTH_HEADERS = {
134
+ "cache-control": "no-store",
135
+ "cloudflare-cdn-cache-control": "no-store",
136
+ "x-robots-tag": "noindex",
137
+ } ;
138
+
139
+ /** §1.9: the store cannot be read, so the site is down for monitors. */
140
+ function healthDown() {
141
+ return Response.json({ ok: false }, { status: 503, headers: HEALTH_HEADERS });
142
+ }
143
+
144
+ /**
145
+ * §1.9: `{ ok, state }`, the admin's `/api/health` shape plus the site's state, so one monitor
146
+ * rule reads both. Public, never cached, never indexed; reads only the memoised pointer.
147
+ */
148
+ export async function health(
149
+ request ,
150
+ state ,
151
+ log = console.error,
152
+ ) {
153
+ if (request.method !== "GET" && request.method !== "HEAD")
154
+ return Response.json(
155
+ { error: "method_not_allowed" },
156
+ { status: 405, headers: { ...HEALTH_HEADERS, allow: "GET" } },
157
+ );
158
+ try {
159
+ const result = await state();
160
+ if (result.kind === "unavailable") return healthDown();
161
+ return Response.json(
162
+ { ok: true, state: result.kind === "not-published" ? "not-published" : "published" },
163
+ { headers: HEALTH_HEADERS },
164
+ );
165
+ } catch (error) {
166
+ log("cloudhal: health check could not read the store", error);
167
+ return healthDown();
168
+ }
169
+ }
170
+
171
+ /**
172
+ * RFC-0034 §4 with §1.2: on a multi-site Worker the hostname map could not be read (the store
173
+ * failed past the map's TTL), so no site is known. Treated as a store failure, never as `error`:
174
+ * health answers `503 { ok: false }`; `GET`/`HEAD` page paths the `unavailable` page and machine
175
+ * paths its plain answer (503, `Retry-After: 300`, English, no site name); anything else a
176
+ * plain 503.
177
+ */
178
+ export async function hostLookupFailed(
179
+ request ,
180
+ error ,
181
+ options ,
182
+ ) {
183
+ (options.log ?? console.error)("cloudhal: the site's hostnames could not be read", error);
184
+ if (new URL(request.url).pathname === HEALTH_PATH) return healthDown();
185
+ const answer = await statusStep(request, {
186
+ state: () => Promise.reject(error),
187
+ page: options.page,
188
+ log: () => {},
189
+ now: options.now,
190
+ });
191
+ const input = { locale: "en", now: (options.now ?? Date.now)() };
192
+ return answer ?? statusPlain("unavailable", input, "text", { method: request.method });
193
+ }
@@ -13,6 +13,18 @@ export declare const MACHINE_PATH: RegExp;
13
13
  * operator endpoints, comment endpoints and machine paths keep their own answers.
14
14
  */
15
15
  export declare function isStatusPagePath(pathname: string): boolean;
16
+ /**
17
+ * How the entry's state step treats a path (§2.3, §2.5): `page` gets the status page, `machine`
18
+ * (feeds, sitemaps, `llms.txt`, search JSON) a short plain or JSON answer where the state calls
19
+ * for one, `undefined` keeps its own answer.
20
+ */
21
+ export declare function statusPathKind(pathname: string): "page" | "machine" | undefined;
22
+ /**
23
+ * Decision 12: a response served despite a preview token that did not verify (media, and paths
24
+ * the state step leaves to the theme) is kept out of the edge cache and says only that the link
25
+ * is invalid; why it failed (expired, signature, another site, previews off) is never echoed.
26
+ */
27
+ export declare function markInvalidPreview(headers: Headers): void;
16
28
  /** What choosing the locale needs of a site (`localeRequest` reads nothing else). */
17
29
  export interface LocaleSite {
18
30
  readonly locales: readonly string[];
@@ -18,11 +18,37 @@ export const MACHINE_PATH = /\.(?:xml|txt|json|rss|atom|webmanifest)$/i;
18
18
  * operator endpoints, comment endpoints and machine paths keep their own answers.
19
19
  */
20
20
  export function isStatusPagePath(pathname ) {
21
- if (pathname === "/robots.txt") return false;
22
- if (matchMediaRoute(pathname)) return false;
23
- if (/^\/(?:_astro|_cloudhal|__cloudhal|\.well-known)\//.test(pathname)) return false;
24
- if (isCommentsPath(pathname)) return false;
25
- return !MACHINE_PATH.test(pathname);
21
+ return !keepsOwnAnswer(pathname) && !MACHINE_PATH.test(pathname);
22
+ }
23
+
24
+ /** `robots.txt`, media, static assets, `/.well-known/`, operator and comment endpoints. */
25
+ function keepsOwnAnswer(pathname ) {
26
+ return (
27
+ pathname === "/robots.txt" ||
28
+ matchMediaRoute(pathname) !== undefined ||
29
+ /^\/(?:_astro|_cloudhal|__cloudhal|\.well-known)\//.test(pathname) ||
30
+ isCommentsPath(pathname)
31
+ );
32
+ }
33
+
34
+ /**
35
+ * How the entry's state step treats a path (§2.3, §2.5): `page` gets the status page, `machine`
36
+ * (feeds, sitemaps, `llms.txt`, search JSON) a short plain or JSON answer where the state calls
37
+ * for one, `undefined` keeps its own answer.
38
+ */
39
+ export function statusPathKind(pathname ) {
40
+ if (keepsOwnAnswer(pathname)) return undefined;
41
+ return MACHINE_PATH.test(pathname) ? "machine" : "page";
42
+ }
43
+
44
+ /**
45
+ * Decision 12: a response served despite a preview token that did not verify (media, and paths
46
+ * the state step leaves to the theme) is kept out of the edge cache and says only that the link
47
+ * is invalid; why it failed (expired, signature, another site, previews off) is never echoed.
48
+ */
49
+ export function markInvalidPreview(headers ) {
50
+ headers.set("cloudflare-cdn-cache-control", "no-store");
51
+ headers.set("x-cloudhal-preview-error", "invalid");
26
52
  }
27
53
 
28
54
  /** What choosing the locale needs of a site (`localeRequest` reads nothing else). */
@@ -98,7 +124,9 @@ export function statusInput(
98
124
  ) {
99
125
  const site = sites.published ?? sites.live;
100
126
  const locale = site ? statusLocale(site, request.host, request.pathname) : "en";
101
- if (state === "unavailable" || state === "error" || !site) return { locale, now };
127
+ if (state === "unavailable" || !site) return { locale, now };
128
+ // `error`: the name of a site this request already read, nothing else (§1.6).
129
+ if (state === "error") return { locale, now, site: { name: site.name } };
102
130
  const showsBrand = sites.published !== undefined && state !== "not-published";
103
131
  return {
104
132
  locale,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudhal/astro-renderer",
3
- "version": "0.6.4",
3
+ "version": "0.7.0",
4
4
  "description": "Render a Cloudhal Site Graph with Astro: data sources (live/snapshot), section components and the cloudhal() integration",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://cloudhal.dev",
@@ -223,14 +223,14 @@
223
223
  "README.md"
224
224
  ],
225
225
  "dependencies": {
226
- "@cloudhal/core-contracts": "0.6.4",
227
- "@cloudhal/core-ts": "0.6.4",
228
- "@cloudhal/storage": "0.6.4",
226
+ "@cloudhal/core-contracts": "0.7.0",
227
+ "@cloudhal/core-ts": "0.7.0",
228
+ "@cloudhal/storage": "0.7.0",
229
229
  "marked": "^18.1.1",
230
230
  "parse5": "8.0.1",
231
- "@cloudhal/analytics": "0.6.4",
231
+ "@cloudhal/analytics": "0.7.0",
232
232
  "vite": "^8.3.5",
233
- "@cloudhal/comments": "0.6.4"
233
+ "@cloudhal/comments": "0.7.0"
234
234
  },
235
235
  "peerDependencies": {
236
236
  "astro": "^7.4.0",