@cloudhal/astro-renderer 0.0.0-stage → 0.1.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.
Files changed (164) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +36 -2
  3. package/dist/src/ambient-client.d.ts +17 -0
  4. package/dist/src/ambient-client.js +55 -0
  5. package/dist/src/analytics-client.d.ts +17 -0
  6. package/dist/src/analytics-client.js +96 -0
  7. package/dist/src/analytics-middleware.d.ts +6 -0
  8. package/dist/src/analytics-middleware.js +43 -0
  9. package/dist/src/analytics-node.d.ts +46 -0
  10. package/dist/src/analytics-node.js +134 -0
  11. package/dist/src/analytics.d.ts +117 -0
  12. package/dist/src/analytics.js +372 -0
  13. package/dist/src/archive.d.ts +106 -0
  14. package/dist/src/archive.js +207 -0
  15. package/dist/src/astro-env.d.ts +21 -0
  16. package/dist/src/block-html.d.ts +14 -0
  17. package/dist/src/block-html.js +103 -0
  18. package/dist/src/blocks.d.ts +24 -0
  19. package/dist/src/blocks.js +66 -0
  20. package/dist/src/cache-tags.d.ts +25 -0
  21. package/dist/src/cache-tags.js +59 -0
  22. package/dist/src/carousel-client.d.ts +28 -0
  23. package/dist/src/carousel-client.js +67 -0
  24. package/dist/src/chart.d.ts +34 -0
  25. package/dist/src/chart.js +182 -0
  26. package/dist/src/chrome-client.d.ts +27 -0
  27. package/dist/src/chrome-client.js +64 -0
  28. package/dist/src/cloudflare-entry.d.ts +87 -0
  29. package/dist/src/cloudflare-entry.js +548 -0
  30. package/dist/src/comments-client.d.ts +11 -0
  31. package/dist/src/comments-client.js +58 -0
  32. package/dist/src/comments-html.d.ts +42 -0
  33. package/dist/src/comments-html.js +303 -0
  34. package/dist/src/comments-middleware.d.ts +6 -0
  35. package/dist/src/comments-middleware.js +38 -0
  36. package/dist/src/comments-node.d.ts +42 -0
  37. package/dist/src/comments-node.js +112 -0
  38. package/dist/src/comments-view.d.ts +68 -0
  39. package/dist/src/comments-view.js +174 -0
  40. package/dist/src/comments.d.ts +66 -0
  41. package/dist/src/comments.js +258 -0
  42. package/dist/src/components/Block.astro +39 -0
  43. package/dist/src/components/Body.astro +43 -0
  44. package/dist/src/components/Comments.astro +19 -0
  45. package/dist/src/components/ContentList.astro +31 -0
  46. package/dist/src/components/EntryArticle.astro +31 -0
  47. package/dist/src/components/Hero.astro +36 -0
  48. package/dist/src/components/Image.astro +36 -0
  49. package/dist/src/components/RichText.astro +19 -0
  50. package/dist/src/components/Sections.astro +66 -0
  51. package/dist/src/components/SeoHead.astro +22 -0
  52. package/dist/src/components/Surface.astro +36 -0
  53. package/dist/src/components/SurfaceNode.astro +82 -0
  54. package/dist/src/components/index.d.ts +12 -0
  55. package/dist/src/components/index.js +12 -0
  56. package/dist/src/csp.d.ts +20 -0
  57. package/dist/src/csp.js +28 -0
  58. package/dist/src/embed-client.d.ts +38 -0
  59. package/dist/src/embed-client.js +98 -0
  60. package/dist/src/embed-middleware.d.ts +9 -0
  61. package/dist/src/embed-middleware.js +49 -0
  62. package/dist/src/feeds.d.ts +72 -0
  63. package/dist/src/feeds.js +246 -0
  64. package/dist/src/gates.d.ts +25 -0
  65. package/dist/src/gates.js +63 -0
  66. package/dist/src/index.d.ts +17 -0
  67. package/dist/src/index.js +17 -0
  68. package/dist/src/integration.d.ts +55 -0
  69. package/dist/src/integration.js +244 -0
  70. package/dist/src/kit.d.ts +48 -0
  71. package/dist/src/kit.js +83 -0
  72. package/dist/src/locale-feeds.d.ts +29 -0
  73. package/dist/src/locale-feeds.js +152 -0
  74. package/dist/src/locale-middleware.d.ts +5 -0
  75. package/dist/src/locale-middleware.js +26 -0
  76. package/dist/src/locales.d.ts +87 -0
  77. package/dist/src/locales.js +336 -0
  78. package/dist/src/markdown.d.ts +83 -0
  79. package/dist/src/markdown.js +533 -0
  80. package/dist/src/media-middleware.d.ts +5 -0
  81. package/dist/src/media-middleware.js +18 -0
  82. package/dist/src/media-route.d.ts +47 -0
  83. package/dist/src/media-route.js +238 -0
  84. package/dist/src/media.d.ts +109 -0
  85. package/dist/src/media.js +298 -0
  86. package/dist/src/motion-client.d.ts +39 -0
  87. package/dist/src/motion-client.js +115 -0
  88. package/dist/src/navigation.d.ts +127 -0
  89. package/dist/src/navigation.js +382 -0
  90. package/dist/src/not-found.d.ts +16 -0
  91. package/dist/src/not-found.js +41 -0
  92. package/dist/src/overlay-client.d.ts +20 -0
  93. package/dist/src/overlay-client.js +49 -0
  94. package/dist/src/prefs-client.d.ts +14 -0
  95. package/dist/src/prefs-client.js +18 -0
  96. package/dist/src/preview.d.ts +70 -0
  97. package/dist/src/preview.js +551 -0
  98. package/dist/src/resolver.d.ts +71 -0
  99. package/dist/src/resolver.js +206 -0
  100. package/dist/src/routing.d.ts +108 -0
  101. package/dist/src/routing.js +285 -0
  102. package/dist/src/runtime-workerd.d.ts +87 -0
  103. package/dist/src/runtime-workerd.js +275 -0
  104. package/dist/src/runtime.d.ts +59 -0
  105. package/dist/src/runtime.js +153 -0
  106. package/dist/src/safe-urls.d.ts +13 -0
  107. package/dist/src/safe-urls.js +35 -0
  108. package/dist/src/sanitize.d.ts +7 -0
  109. package/dist/src/sanitize.js +217 -0
  110. package/dist/src/search-client.d.ts +29 -0
  111. package/dist/src/search-client.js +92 -0
  112. package/dist/src/search-limit.d.ts +36 -0
  113. package/dist/src/search-limit.js +66 -0
  114. package/dist/src/search.d.ts +64 -0
  115. package/dist/src/search.js +155 -0
  116. package/dist/src/seo.d.ts +85 -0
  117. package/dist/src/seo.js +468 -0
  118. package/dist/src/site-dispatch.d.ts +37 -0
  119. package/dist/src/site-dispatch.js +86 -0
  120. package/dist/src/site-hosts.d.ts +35 -0
  121. package/dist/src/site-hosts.js +110 -0
  122. package/dist/src/source.d.ts +227 -0
  123. package/dist/src/source.js +794 -0
  124. package/dist/src/static-gates.d.ts +3 -0
  125. package/dist/src/static-gates.js +28 -0
  126. package/dist/src/static-headers.d.ts +30 -0
  127. package/dist/src/static-headers.js +140 -0
  128. package/dist/src/static-media.d.ts +4 -0
  129. package/dist/src/static-media.js +65 -0
  130. package/dist/src/static-redirects.d.ts +4 -0
  131. package/dist/src/static-redirects.js +40 -0
  132. package/dist/src/surface-client.d.ts +34 -0
  133. package/dist/src/surface-client.js +146 -0
  134. package/dist/src/surfaces/html.d.ts +35 -0
  135. package/dist/src/surfaces/html.js +184 -0
  136. package/dist/src/surfaces/markup.d.ts +57 -0
  137. package/dist/src/surfaces/markup.js +135 -0
  138. package/dist/src/surfaces/motion.d.ts +33 -0
  139. package/dist/src/surfaces/motion.js +132 -0
  140. package/dist/src/surfaces/primitives/carousel.d.ts +2 -0
  141. package/dist/src/surfaces/primitives/carousel.js +95 -0
  142. package/dist/src/surfaces/primitives/content.d.ts +13 -0
  143. package/dist/src/surfaces/primitives/content.js +159 -0
  144. package/dist/src/surfaces/primitives/data.d.ts +5 -0
  145. package/dist/src/surfaces/primitives/data.js +80 -0
  146. package/dist/src/surfaces/primitives/index.d.ts +54 -0
  147. package/dist/src/surfaces/primitives/index.js +106 -0
  148. package/dist/src/surfaces/primitives/inputs.d.ts +8 -0
  149. package/dist/src/surfaces/primitives/inputs.js +68 -0
  150. package/dist/src/surfaces/primitives/layout.d.ts +14 -0
  151. package/dist/src/surfaces/primitives/layout.js +61 -0
  152. package/dist/src/surfaces/primitives/motion.d.ts +9 -0
  153. package/dist/src/surfaces/primitives/motion.js +45 -0
  154. package/dist/src/surfaces/primitives/overlays.d.ts +6 -0
  155. package/dist/src/surfaces/primitives/overlays.js +79 -0
  156. package/dist/src/surfaces/tree.d.ts +107 -0
  157. package/dist/src/surfaces/tree.js +321 -0
  158. package/dist/src/surfaces.d.ts +14 -0
  159. package/dist/src/surfaces.js +33 -0
  160. package/dist/src/taxonomy.d.ts +86 -0
  161. package/dist/src/taxonomy.js +268 -0
  162. package/dist/src/theme-settings.d.ts +24 -0
  163. package/dist/src/theme-settings.js +111 -0
  164. package/package.json +219 -3
@@ -0,0 +1,275 @@
1
+ /**
2
+ * `workerd` build of `@cloudhal/astro-renderer/runtime` (selected by the `workerd` export
3
+ * condition): the deployed Site Worker. Storage comes from bindings — D1 `DB` for nodes and the
4
+ * published pointer, R2 `BLOBS` for snapshot bodies — and every request is resolved on its own:
5
+ * published snapshot by default, drafts/any snapshot behind a signed preview link.
6
+ *
7
+ * Response headers set here drive the Workers Cache (ADR-0012): published pages are cached at the
8
+ * edge under `Cache-Tag: cloudhal-site-<siteId>` until a publish/rollback purges that tag, and
9
+ * never past the snapshot's next time gate (RFC-0008 §7.4); previews are never cached.
10
+ */
11
+
12
+ import { env, waitUntil } from "cloudflare:workers";
13
+ import { AsyncLocalStorage } from "node:async_hooks";
14
+ import { SqlCommentStore } from "@cloudhal/comments/sql";
15
+
16
+ import { SiteGraphStore, searchProviderFromEnv } from "@cloudhal/core-ts";
17
+ import { edgeMaxAge } from "@cloudhal/core-ts/availability";
18
+
19
+ import { D1Driver } from "@cloudhal/storage/d1";
20
+ import { R2BlobStore } from "@cloudhal/storage/r2";
21
+ import { siteCacheTag } from "./cache-tags.js";
22
+ import { usableCommentsKey } from "./comments.js";
23
+
24
+
25
+ import { matchMediaRoute, serveMediaRequest } from "./media-route.js";
26
+ import { PREVIEW_PARAM, SiteResolver } from "./resolver.js";
27
+
28
+
29
+ /** RFC-0029 §3: `AI_SEARCH`, `SEARCH_BUCKET` and `CLOUDHAL_SEARCH_*` turn on semantic search. */
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+  
38
+
39
+
40
+
41
+ /** Minimal shape of the Astro global the page passes in. */
42
+
43
+
44
+
45
+
46
+
47
+ /**
48
+ * RFC-0034 §4: the site this request is for, set by the entry (from the hostname on a multi-site
49
+ * Worker) around everything the request runs, Astro's render included. Module state, not a header:
50
+ * a client cannot choose it.
51
+ */
52
+ const requestSite = new AsyncLocalStorage ();
53
+
54
+ /** Runs `fn` (and everything it awaits) as a request for `siteId`. */
55
+ export function withRequestSite (siteId , fn ) {
56
+ return requestSite.run(siteId, fn);
57
+ }
58
+
59
+ /** The request's site: the entry's choice, else `CLOUDHAL_SITE_ID`, else the build's. */
60
+ function siteOf(fallback ) {
61
+ return requestSite.getStore() ?? (env ).CLOUDHAL_SITE_ID ?? fallback;
62
+ }
63
+
64
+ /** One resolver per site the isolate has served (pointer, snapshot and bundle caches). */
65
+ const resolvers = new Map ();
66
+
67
+ /** The site's store; with the deployment's search provider when it has one (RFC-0029 §3). */
68
+ function siteStore(e ) {
69
+ const sql = new D1Driver(e.DB);
70
+ const search = searchProviderFromEnv(e, sql, {
71
+ onError: (err) => console.error("semantic search failed, FTS5 answered:", err),
72
+ });
73
+ return new SiteGraphStore({
74
+ sql,
75
+ blobs: new R2BlobStore(e.BLOBS),
76
+ ...(search ? { search } : {}),
77
+ });
78
+ }
79
+
80
+ function getResolver(siteId ) {
81
+ const e = env ;
82
+ const known = resolvers.get(siteId);
83
+ if (known) return known;
84
+ const resolver = new SiteResolver({
85
+ store: siteStore(e),
86
+ siteId,
87
+ previewSecret: e.CLOUDHAL_PREVIEW_SECRET,
88
+ // The edge cache absorbs repeat traffic; a cache miss must see the pointer as it is now,
89
+ // otherwise a just-purged page could be re-cached from a stale pointer.
90
+ pointerTtlMs: 0,
91
+ // Previews travel in the URL (links are rewritten by the entry), not in a cookie: the edge
92
+ // cache does not vary on cookies, so a cookie-carried preview could be served a cached page.
93
+ previewCookie: false,
94
+ // RFC-0010: the published snapshot's bundle is written after the response, the first time
95
+ // this deployment renders it without one (release runs, rollbacks, pushes, lifecycle expiry).
96
+ persistBundle: (task) => waitUntil(task),
97
+ });
98
+ resolvers.set(siteId, resolver);
99
+ return resolver;
100
+ }
101
+
102
+ /** Test/purge hook: forget cached state in this isolate, for one site or all of them. */
103
+ export function resetSource(siteId ) {
104
+ for (const [id, r] of resolvers) if (!siteId || id === siteId) r.invalidate();
105
+ }
106
+
107
+ /**
108
+ * What site analytics read on the Site Worker (`SiteAnalytics`, RFC-0006 §5.2): D1 for settings and
109
+ * the daily salt, the site row (published pointer, domains) and the isolate's snapshot cache.
110
+ */
111
+ export function analyticsBackend(
112
+ siteId ,
113
+ /** Ignored here (bindings decide); the Node build reads the local store from `dataDir`. */
114
+ _config ,
115
+ )
116
+
117
+
118
+
119
+
120
+ {
121
+ const r = getResolver(siteId);
122
+ let sql ;
123
+ const driver = () => {
124
+ sql ??= new D1Driver((env ).DB);
125
+ return sql;
126
+ };
127
+ return {
128
+ sql: driver,
129
+ open: async () => driver(),
130
+ site: () => r.store.getSite(siteId),
131
+ snapshot: (id) => r.snapshot(id),
132
+ };
133
+ }
134
+
135
+ export { CACHE_TAG_PREFIX } from "./cache-tags.js";
136
+
137
+ /**
138
+ * RFC-0034 §6: the other sites of the project that publish a version of `node`'s work (language
139
+ * editions), for `hreflang` and the language switcher. Only what those sites have published
140
+ * counts: their published snapshot is read, never their drafts. A site without a hostname is
141
+ * left out (there is no address to point to).
142
+ */
143
+ export async function peerEditions(
144
+ config ,
145
+ node ,
146
+ ) {
147
+ const siteId = siteOf(config.siteId);
148
+ if (!siteId) return [];
149
+ const store = getResolver(siteId).store;
150
+ const site = await store.getSite(siteId);
151
+ if (!site) return [];
152
+ const siblings = (await store.listSites(site.projectId)).filter(
153
+ (s) => s.id !== siteId && s.publishedSnapshotId && s.domains.length > 0,
154
+ );
155
+ if (siblings.length === 0) return [];
156
+ const group = node.translation?.group ?? node.id;
157
+ const rows = await store.sql.all (
158
+ `SELECT DISTINCT site_id FROM nodes WHERE kind = ? AND site_id IN (${siblings.map(() => "?").join(", ")})
159
+ AND (id = ? OR json_extract(body, '$.translation.group') = ?)`,
160
+ ["path" in node ? "page" : "contentEntry", ...siblings.map((s) => s.id), group, group],
161
+ );
162
+ const now = Date.now();
163
+ const out = [];
164
+ for (const { site_id } of rows) {
165
+ const peer = siblings.find((s) => s.id === site_id);
166
+ const host = peer?.domains.find((d) => d.primary)?.hostname ?? peer?.domains[0]?.hostname;
167
+ if (!peer?.publishedSnapshotId || !host) continue;
168
+ const source = (await getResolver(peer.id).snapshot(peer.publishedSnapshotId)).at(now);
169
+ out.push({ source, origin: `https://${host}` });
170
+ }
171
+ return out;
172
+ }
173
+
174
+ let commentStore ;
175
+
176
+ /**
177
+ * The comment store for pages on the Site Worker (RFC-0007 §8.1): D1. `undefined` when the build
178
+ * has no comments module (`comments.available: false`) or the Worker has no usable
179
+ * `CLOUDHAL_COMMENTS_KEY` — comments are then off, and the entry answers their endpoints `404`.
180
+ */
181
+ export async function commentsBackend(
182
+ config ,
183
+ ) {
184
+ const e = env ;
185
+ if (!config.commentsScript || !usableCommentsKey(e.CLOUDHAL_COMMENTS_KEY)) return undefined;
186
+ commentStore ??= new SqlCommentStore(new D1Driver(e.DB));
187
+ return { store: commentStore };
188
+ }
189
+
190
+ /**
191
+ * Resolves the source for this request and sets caching/preview headers on the response.
192
+ * Returns `undefined` when the site has never been published (the page should answer 503).
193
+ */
194
+ export async function getSource(
195
+ config ,
196
+ astro ,
197
+ ) {
198
+ if (!astro) throw new Error("on Cloudflare, pass the Astro global: getSource(config, Astro)");
199
+ const siteId = siteOf(config.siteId) ;
200
+ const r = getResolver(siteId);
201
+ const resolution = await r.resolve(astro.request);
202
+ const h = astro.response.headers;
203
+ if (resolution.kind === "preview") {
204
+ h.set("cache-control", "private, no-store");
205
+ h.set("cloudflare-cdn-cache-control", "no-store");
206
+ h.set("x-robots-tag", "noindex");
207
+ h.set("x-cloudhal-mode", "preview");
208
+ const token = new URL(astro.request.url).searchParams.get(PREVIEW_PARAM);
209
+ if (token) h.set("x-cloudhal-preview-token", token);
210
+ return resolution.source;
211
+ }
212
+ if (resolution.kind === "unpublished") {
213
+ h.set("cache-control", "no-store");
214
+ h.set("cloudflare-cdn-cache-control", "no-store");
215
+ h.set("x-cloudhal-mode", "unpublished");
216
+ return undefined;
217
+ }
218
+ // Published: browsers revalidate, the edge keeps it until a publish purges the tag — or, when a
219
+ // time gate lies ahead, until that gate (RFC-0008 §7.4): any page may list any entry, so the
220
+ // cap is site-wide and a gate needs no purge.
221
+ h.set("cache-control", "public, max-age=0, must-revalidate");
222
+ h.set(
223
+ "cloudflare-cdn-cache-control",
224
+ `public, max-age=${edgeMaxAge(await resolution.source.nextGate(), resolution.at)}`,
225
+ );
226
+ // Pages add per-node tags next to this one (`addCacheTags`, `cache-tags.ts`).
227
+ h.set("cache-tag", siteCacheTag(siteId));
228
+ h.set("x-cloudhal-mode", "published");
229
+ h.set("x-cloudhal-snapshot", resolution.snapshotId);
230
+ if (resolution.previewError) {
231
+ // An invalid preview link must not poison the cache entry for this URL.
232
+ h.set("cloudflare-cdn-cache-control", "no-store");
233
+ h.set("x-cloudhal-preview-error", resolution.previewError);
234
+ }
235
+ return resolution.source;
236
+ }
237
+
238
+ /**
239
+ * The media route (RFC-0004 §7.1), answered by the Site Worker entry before Astro: the asset comes
240
+ * from the published snapshot, or from the preview target behind a valid token (invariant 15).
241
+ * Returns `undefined` for paths that are not media URLs.
242
+ */
243
+ export async function serveMedia(
244
+ request ,
245
+ options = {},
246
+ ) {
247
+ if (!matchMediaRoute(new URL(request.url).pathname)) return undefined;
248
+ const siteId = siteOf(options.siteId);
249
+ if (!siteId) return undefined;
250
+ const r = getResolver(siteId);
251
+ const resolution = await r.resolve(request);
252
+ if (resolution.kind === "unpublished")
253
+ return new Response("not found", {
254
+ status: 404,
255
+ headers: { "cache-control": "no-store", "cloudflare-cdn-cache-control": "no-store" },
256
+ });
257
+ const source = resolution.source;
258
+ const token = new URL(request.url).searchParams.get(PREVIEW_PARAM);
259
+ const preview = resolution.kind === "preview";
260
+ const store = r.store;
261
+ const response = await serveMediaRequest(request, {
262
+ siteId,
263
+ mode: preview ? "preview" : "published",
264
+ assetByPrefix: async (prefix) => source.assetByPrefix?.(prefix),
265
+ blobState: (sha256) => store.blobState(siteId, sha256),
266
+ blobs: store.blobs,
267
+ ...(preview && token ? { keepQuery: `${PREVIEW_PARAM}=${encodeURIComponent(token)}` } : {}),
268
+ });
269
+ if (response && resolution.kind === "published" && resolution.previewError) {
270
+ // An invalid preview link must not poison the edge cache entry for this URL.
271
+ response.headers.set("cloudflare-cdn-cache-control", "no-store");
272
+ response.headers.set("x-cloudhal-preview-error", resolution.previewError);
273
+ }
274
+ return response;
275
+ }
@@ -0,0 +1,59 @@
1
+ import { SqlCommentStore } from "@cloudhal/comments/sql";
2
+ import type { Site } from "@cloudhal/core-contracts";
3
+ import type { SqlDriver } from "@cloudhal/storage";
4
+ import type { CloudhalRendererConfig } from "./integration.js";
5
+ import type { PeerEdition } from "./locales.js";
6
+ import { type GraphSource } from "./source.js";
7
+ /**
8
+ * The page-side entry point: returns the configured `GraphSource`, created once per process and
9
+ * selector. `CLOUDHAL_SOURCE=live | snapshot:<id>` overrides the integration config (used by
10
+ * `cloudhal build`); a later build in the same process with another selector gets a new source.
11
+ */
12
+ export declare function getSource(config: CloudhalRendererConfig,
13
+ /** Ignored on Node (one source per process); the `workerd` build resolves per request. */
14
+ _astro?: {
15
+ request: Request;
16
+ response: {
17
+ headers: Headers;
18
+ };
19
+ }): Promise<GraphSource>;
20
+ /** Test hook. `cloudhal dev` serves one site, so `_siteId` changes nothing. */
21
+ export declare function resetSource(_siteId?: string): void;
22
+ /**
23
+ * RFC-0034 §4: on a multi-site Worker the entry runs each request for its site; `cloudhal dev`
24
+ * serves the project's one site, so this only runs `fn`.
25
+ */
26
+ export declare function withRequestSite<T>(_siteId: string, fn: () => T): T;
27
+ /**
28
+ * RFC-0034 §6: other sites' published versions of a work. `cloudhal dev` renders the project's one
29
+ * site from its local store, so there are none.
30
+ */
31
+ export declare function peerEditions(_config: Partial<CloudhalRendererConfig>, _node: unknown): Promise<PeerEdition[]>;
32
+ /**
33
+ * The media route for `cloudhal dev` (RFC-0004 §7.8): served from the local blob store with
34
+ * `no-store`, drafts included, matching the live preview. `undefined` for other paths.
35
+ */
36
+ export declare function serveMedia(request: Request, options: Partial<CloudhalRendererConfig>): Promise<Response | undefined>;
37
+ /**
38
+ * What site analytics read on Node (`cloudhal dev`, self-host; RFC-0006 §11): the local SQLite
39
+ * store for settings, the salt and raw events, the site row, and published snapshots (cached per
40
+ * process). Same name and shape as the `workerd` build, which reads the D1/R2 bindings instead.
41
+ * `open()` must have resolved before `sql()` is called.
42
+ */
43
+ export declare function analyticsBackend(siteId: string, config?: Partial<CloudhalRendererConfig>): {
44
+ sql: () => SqlDriver;
45
+ site: () => Promise<Site | undefined>;
46
+ snapshot: (id: string) => Promise<GraphSource>;
47
+ open: () => Promise<SqlDriver>;
48
+ };
49
+ /**
50
+ * The comment store for pages on Node (`cloudhal dev`; RFC-0007 §8.5): the local SQLite store.
51
+ * `undefined` when the integration did not build the comments module (static builds have no
52
+ * endpoint, or `comments.available: false`). Same name and shape as the `workerd` build, which
53
+ * reads D1 and also needs a usable `CLOUDHAL_COMMENTS_KEY`.
54
+ */
55
+ export declare function commentsBackend(config: Partial<CloudhalRendererConfig>): Promise<{
56
+ store: SqlCommentStore;
57
+ } | undefined>;
58
+ /** Shared with the `workerd` runtime so code importing either build sees the same names. */
59
+ export { CACHE_TAG_PREFIX } from "./cache-tags.js";
@@ -0,0 +1,153 @@
1
+ import { SqlCommentStore } from "@cloudhal/comments/sql";
2
+
3
+ import { openLocalStore } from "@cloudhal/core-ts/local";
4
+
5
+
6
+
7
+ import { matchMediaRoute, serveMediaRequest } from "./media-route.js";
8
+ import { SiteResolver } from "./resolver.js";
9
+ import { LiveSource, SnapshotSource } from "./source.js";
10
+
11
+ let cached ;
12
+
13
+ /**
14
+ * The page-side entry point: returns the configured `GraphSource`, created once per process and
15
+ * selector. `CLOUDHAL_SOURCE=live | snapshot:<id>` overrides the integration config (used by
16
+ * `cloudhal build`); a later build in the same process with another selector gets a new source.
17
+ */
18
+ export function getSource(
19
+ config ,
20
+ /** Ignored on Node (one source per process); the `workerd` build resolves per request. */
21
+ _astro ,
22
+ ) {
23
+ const selector = process.env.CLOUDHAL_SOURCE ?? config.source ?? "live";
24
+ const key = `${config.dataDir}\n${config.siteId}\n${selector}`;
25
+ if (cached?.key !== key) cached = { key, source: open(config, selector) };
26
+ return cached.source;
27
+ }
28
+
29
+ let local ;
30
+
31
+ /** One local store per data directory and process. */
32
+ function localStore(dataDir ) {
33
+ if (local?.dir !== dataDir) local = { dir: dataDir, store: openLocalStore(dataDir) };
34
+ return local.store;
35
+ }
36
+
37
+ function open(config , selector ) {
38
+ return (async () => {
39
+ const { store } = await localStore(config.dataDir);
40
+ if (selector === "live") return new LiveSource(store, config.siteId);
41
+ if (selector.startsWith("snapshot:"))
42
+ return SnapshotSource.open(store, selector.slice("snapshot:".length));
43
+ throw new Error(`invalid CLOUDHAL_SOURCE "${selector}" (expected "live" or "snapshot:<id>")`);
44
+ })();
45
+ }
46
+
47
+ /** Test hook. `cloudhal dev` serves one site, so `_siteId` changes nothing. */
48
+ export function resetSource(_siteId ) {
49
+ cached = undefined;
50
+ }
51
+
52
+ /**
53
+ * RFC-0034 §4: on a multi-site Worker the entry runs each request for its site; `cloudhal dev`
54
+ * serves the project's one site, so this only runs `fn`.
55
+ */
56
+ export function withRequestSite (_siteId , fn ) {
57
+ return fn();
58
+ }
59
+
60
+ /**
61
+ * RFC-0034 §6: other sites' published versions of a work. `cloudhal dev` renders the project's one
62
+ * site from its local store, so there are none.
63
+ */
64
+ export async function peerEditions(
65
+ _config ,
66
+ _node ,
67
+ ) {
68
+ return [];
69
+ }
70
+
71
+ /**
72
+ * The media route for `cloudhal dev` (RFC-0004 §7.8): served from the local blob store with
73
+ * `no-store`, drafts included, matching the live preview. `undefined` for other paths.
74
+ */
75
+ export async function serveMedia(
76
+ request ,
77
+ options ,
78
+ ) {
79
+ if (!matchMediaRoute(new URL(request.url).pathname)) return undefined;
80
+ if (!options.dataDir || !options.siteId) return undefined;
81
+ const config = {
82
+ ...options,
83
+ dataDir: options.dataDir,
84
+ siteId: options.siteId,
85
+ };
86
+ const { store, blobs } = await localStore(config.dataDir);
87
+ const source = await getSource(config);
88
+ return serveMediaRequest(request, {
89
+ siteId: config.siteId,
90
+ mode: "dev",
91
+ assetByPrefix: async (prefix) => source.assetByPrefix?.(prefix),
92
+ blobState: (sha256) => store.blobState(config.siteId, sha256),
93
+ blobs,
94
+ });
95
+ }
96
+
97
+ let analyticsResolver ;
98
+
99
+ /**
100
+ * What site analytics read on Node (`cloudhal dev`, self-host; RFC-0006 §11): the local SQLite
101
+ * store for settings, the salt and raw events, the site row, and published snapshots (cached per
102
+ * process). Same name and shape as the `workerd` build, which reads the D1/R2 bindings instead.
103
+ * `open()` must have resolved before `sql()` is called.
104
+ */
105
+ export function analyticsBackend(
106
+ siteId ,
107
+ config ,
108
+ )
109
+
110
+
111
+
112
+
113
+ {
114
+ const dataDir = config?.dataDir;
115
+ if (!dataDir) throw new Error("analyticsBackend on Node needs the renderer config's dataDir");
116
+ const key = `${dataDir}|${siteId}`;
117
+ if (analyticsResolver?.key !== key)
118
+ analyticsResolver = {
119
+ key,
120
+ resolver: localStore(dataDir).then((l) => new SiteResolver({ store: l.store, siteId })),
121
+ };
122
+ const pending = analyticsResolver.resolver;
123
+ let sql ;
124
+ return {
125
+ sql: () => {
126
+ if (!sql) throw new Error("analyticsBackend: await open() first");
127
+ return sql;
128
+ },
129
+ open: async () => {
130
+ sql ??= (await localStore(dataDir)).sql;
131
+ return sql;
132
+ },
133
+ site: async () => (await pending).store.getSite(siteId),
134
+ snapshot: async (id) => (await pending).snapshot(id),
135
+ };
136
+ }
137
+
138
+ /**
139
+ * The comment store for pages on Node (`cloudhal dev`; RFC-0007 §8.5): the local SQLite store.
140
+ * `undefined` when the integration did not build the comments module (static builds have no
141
+ * endpoint, or `comments.available: false`). Same name and shape as the `workerd` build, which
142
+ * reads D1 and also needs a usable `CLOUDHAL_COMMENTS_KEY`.
143
+ */
144
+ export async function commentsBackend(
145
+ config ,
146
+ ) {
147
+ if (!config.commentsScript || !config.dataDir || config.comments?.available === false)
148
+ return undefined;
149
+ return { store: new SqlCommentStore((await localStore(config.dataDir)).sql) };
150
+ }
151
+
152
+ /** Shared with the `workerd` runtime so code importing either build sees the same names. */
153
+ export { CACHE_TAG_PREFIX } from "./cache-tags.js";
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The URL checks every renderer path shares: markdown links and images, section images and CTAs,
3
+ * SEO images, and the HTML body sanitizer (RFC-0012).
4
+ */
5
+ /**
6
+ * Link targets markdown may produce. Everything else (javascript:, data:, vbscript:, …) is dropped.
7
+ * The check runs on what a browser would parse (WHATWG URL): C0 controls and spaces trimmed at the
8
+ * ends, tabs and newlines removed anywhere (`java\tscript:` is `javascript:`), and a backslash read
9
+ * as a slash, so `/\host` and `\\host` are protocol-relative like `//host`.
10
+ */
11
+ export declare function safeHref(href: string): string | undefined;
12
+ /** Image sources: what `safeHref` allows (no mailto/tel) plus raster data: URLs. */
13
+ export declare function safeSrc(src: string): string | undefined;
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The URL checks every renderer path shares: markdown links and images, section images and CTAs,
3
+ * SEO images, and the HTML body sanitizer (RFC-0012).
4
+ */
5
+
6
+ /**
7
+ * Link targets markdown may produce. Everything else (javascript:, data:, vbscript:, …) is dropped.
8
+ * The check runs on what a browser would parse (WHATWG URL): C0 controls and spaces trimmed at the
9
+ * ends, tabs and newlines removed anywhere (`java\tscript:` is `javascript:`), and a backslash read
10
+ * as a slash, so `/\host` and `\\host` are protocol-relative like `//host`.
11
+ */
12
+ export function safeHref(href ) {
13
+ const value = asParsed(href);
14
+ if (/^(https?:|mailto:|tel:)/i.test(value)) return value;
15
+ if (/^[a-z][a-z0-9+.-]*:/i.test(value) || /^[/\\]{2}/.test(value)) return undefined;
16
+ return value; // relative path, fragment or query
17
+ }
18
+
19
+ /** A URL as a browser reads it: no tabs or newlines, no C0 controls or spaces at either end. */
20
+ function asParsed(href ) {
21
+ const value = href.replace(/[\t\n\r]/g, "");
22
+ let start = 0;
23
+ let end = value.length;
24
+ while (start < end && value.charCodeAt(start) <= 0x20) start++;
25
+ while (end > start && value.charCodeAt(end - 1) <= 0x20) end--;
26
+ return value.slice(start, end);
27
+ }
28
+
29
+ /** Image sources: what `safeHref` allows (no mailto/tel) plus raster data: URLs. */
30
+ export function safeSrc(src ) {
31
+ const value = src.trim();
32
+ if (/^data:image\/(png|jpe?g|gif|webp|avif);base64,[a-z0-9+/=\s]+$/i.test(value)) return value;
33
+ const safe = safeHref(value);
34
+ return safe && !/^(mailto|tel):/i.test(safe) ? safe : undefined;
35
+ }
@@ -0,0 +1,7 @@
1
+ /** What survives, for docs and tests. */
2
+ export declare const HTML_ALLOWLIST: {
3
+ readonly elements: Readonly<Record<string, readonly string[]>>;
4
+ readonly global: readonly string[];
5
+ };
6
+ /** The sanitized HTML of a stored `html` body. */
7
+ export declare function sanitizeHtml(html: string): string;