@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,303 @@
1
+ /**
2
+ * The reader-comments section as HTML (RFC-0007 §8.1–§8.2), a pure function of a `CommentsView`
3
+ * so it can be tested as text. `<Comments />` (`components/Comments.astro`) renders it.
4
+ *
5
+ * - Approved comments, oldest first, two visible levels (`<ol>`/`<li id="comment-<id>">`/
6
+ * `<article>`): the escaped name, a staff badge, `<time datetime>`, the text through
7
+ * `commentTextHtml` (plain text; only `https:` URLs become links, `rel="ugc nofollow noopener
8
+ * noreferrer"`), "in reply to <name>" for replies to replies, and a "Report" disclosure with a
9
+ * small plain form per comment. A removed top-level comment with approved replies reads
10
+ * "This comment was removed".
11
+ * - Open threads get the plain HTML form (`method=post action=/__cloudhal/comments`, a honeypot,
12
+ * hidden challenge fields the module fills) and the module tag; closed ones "Comments are
13
+ * closed"; hidden and off threads render nothing.
14
+ * - The outcome notes (`#comment-pending`, `#comment-invalid`, …) are hidden until the fragment
15
+ * names them (`:target`), so a JavaScript-less post's `303` lands on the cached page and still
16
+ * explains itself.
17
+ *
18
+ * No third-party resource, no inline script; the only `<style>` is functional (notes, the
19
+ * honeypot, the live region) and themes style the rest through the `cloudhal-comment*` classes.
20
+ */
21
+ import { commentTextHtml, escapeHtml, } from "@cloudhal/comments";
22
+ import { COMMENTS_PATH, COMMENTS_REPORT_PATH } from "./comments.js";
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+
73
+
74
+ const EN = {
75
+ heading: (n) => (n === 0 ? "Comments" : n === 1 ? "1 comment" : `${n} comments`),
76
+ preview: "Comments appear on the published page.",
77
+ closed: "Comments are closed.",
78
+ removed: "This comment was removed.",
79
+ anonymous: "Anonymous",
80
+ author: "Author",
81
+ team: "Team",
82
+ inReplyTo: (name) => `in reply to ${name}`,
83
+ reply: "Reply",
84
+ cancelReply: "Cancel reply",
85
+ replyingTo: "Replying to",
86
+ report: "Report",
87
+ reportReason: "Why should we look at this comment?",
88
+ reasons: {
89
+ spam: "Spam",
90
+ abuse: "Abuse or harassment",
91
+ "personal-data": "Someone's personal data",
92
+ "illegal-content": "Illegal content",
93
+ other: "Something else",
94
+ },
95
+ reportDetails: "Details (optional)",
96
+ reportEmail: "Your email (optional, never shown)",
97
+ sendReport: "Send report",
98
+ more: "More comments",
99
+ pages: "Comment pages",
100
+ formTitle: "Leave a comment",
101
+ name: "Name",
102
+ nameHint: "Shown with your comment.",
103
+ email: "Email (optional)",
104
+ emailHint: "Never shown; used only if you ask us about your comment.",
105
+ comment: "Comment",
106
+ website: "Leave this field empty",
107
+ moderation:
108
+ "Comments are reviewed before they appear. We store your name and comment, and your email if you give one; no cookies.",
109
+ scriptRequired: "Comments on this site need JavaScript.",
110
+ submit: "Post comment",
111
+ sending: "Sending…",
112
+ awaiting: "Awaiting moderation",
113
+ notes: {
114
+ pending: "Thanks — your comment will appear once a moderator approves it.",
115
+ invalid: "Please check your name and comment, then try again.",
116
+ closed: "Comments on this article are closed.",
117
+ "script-required": "Comments on this site need JavaScript.",
118
+ "slow-down": "You are commenting a little fast. Please wait a moment and try again.",
119
+ "try-again": "Your comment could not be sent. Please try again.",
120
+ paused: "Comments are paused for today. Please try again tomorrow.",
121
+ reported: "Thank you — a person will look at the comment you reported.",
122
+ },
123
+ };
124
+
125
+ const TR = {
126
+ heading: (n) => (n === 0 ? "Yorumlar" : `${n} yorum`),
127
+ preview: "Yorumlar yayımlanan sayfada görünür.",
128
+ closed: "Yorumlar kapalı.",
129
+ removed: "Bu yorum kaldırıldı.",
130
+ anonymous: "Anonim",
131
+ author: "Yazar",
132
+ team: "Ekip",
133
+ inReplyTo: (name) => `${name} adlı kişiye yanıt`,
134
+ reply: "Yanıtla",
135
+ cancelReply: "Yanıtı iptal et",
136
+ replyingTo: "Yanıtlanan:",
137
+ report: "Bildir",
138
+ reportReason: "Bu yoruma neden bakmalıyız?",
139
+ reasons: {
140
+ spam: "Spam",
141
+ abuse: "Taciz veya hakaret",
142
+ "personal-data": "Birinin kişisel verisi",
143
+ "illegal-content": "Yasa dışı içerik",
144
+ other: "Başka bir şey",
145
+ },
146
+ reportDetails: "Ayrıntılar (isteğe bağlı)",
147
+ reportEmail: "E-postanız (isteğe bağlı, gösterilmez)",
148
+ sendReport: "Bildirimi gönder",
149
+ more: "Diğer yorumlar",
150
+ pages: "Yorum sayfaları",
151
+ formTitle: "Yorum yazın",
152
+ name: "Ad",
153
+ nameHint: "Yorumunuzla birlikte gösterilir.",
154
+ email: "E-posta (isteğe bağlı)",
155
+ emailHint: "Gösterilmez; yalnızca yorumunuzla ilgili bize yazarsanız kullanılır.",
156
+ comment: "Yorum",
157
+ website: "Bu alanı boş bırakın",
158
+ moderation:
159
+ "Yorumlar yayımlanmadan önce incelenir. Adınızı ve yorumunuzu, verirseniz e-postanızı saklarız; çerez kullanmayız.",
160
+ scriptRequired: "Bu sitede yorum yazmak için JavaScript gerekir.",
161
+ submit: "Yorumu gönder",
162
+ sending: "Gönderiliyor…",
163
+ awaiting: "Onay bekliyor",
164
+ notes: {
165
+ pending: "Teşekkürler — yorumunuz bir moderatör onayladığında görünecek.",
166
+ invalid: "Lütfen adınızı ve yorumunuzu kontrol edip yeniden deneyin.",
167
+ closed: "Bu yazıya yorumlar kapandı.",
168
+ "script-required": "Bu sitede yorum yazmak için JavaScript gerekir.",
169
+ "slow-down": "Biraz hızlı yorum yazıyorsunuz. Lütfen biraz bekleyip yeniden deneyin.",
170
+ "try-again": "Yorumunuz gönderilemedi. Lütfen yeniden deneyin.",
171
+ paused: "Yorumlar bugünlük durduruldu. Lütfen yarın yeniden deneyin.",
172
+ reported: "Teşekkürler — bildirdiğiniz yoruma bir kişi bakacak.",
173
+ },
174
+ };
175
+
176
+ /** The section's words for a locale (English for languages without a translation). */
177
+ export function commentStrings(locale ) {
178
+ return locale.toLowerCase().split("-")[0] === "tr" ? TR : EN;
179
+ }
180
+
181
+ const e = escapeHtml;
182
+
183
+ /** Only the functional rules; themes style the rest (zero-specificity `:where`). */
184
+ const STYLE = `<style>:where(.cloudhal-comment-note){display:none}:where(.cloudhal-comment-note:target){display:block}.cloudhal-comment-hp,.cloudhal-comments-live{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}</style>`;
185
+
186
+ function authorName(c , t ) {
187
+ return c.author.kind === "erased" ? t.anonymous : c.author.name;
188
+ }
189
+
190
+ function formatDate(iso , locale ) {
191
+ try {
192
+ return new Intl.DateTimeFormat(locale, { dateStyle: "long", timeZone: "UTC" }).format(
193
+ new Date(iso),
194
+ );
195
+ } catch {
196
+ return iso.slice(0, 10);
197
+ }
198
+ }
199
+
200
+ function reportForm(c , t ) {
201
+ const id = `report-${c.id}`;
202
+ const options = Object.entries(t.reasons)
203
+ .map(([value, label]) => `<option value="${e(value)}">${e(label)}</option>`)
204
+ .join("");
205
+ return `<details class="cloudhal-comment-report"><summary>${e(t.report)}</summary><form class="cloudhal-report-form" method="post" action="${COMMENTS_REPORT_PATH}" data-kind="report"><input type="hidden" name="commentId" value="${e(c.id)}"><p><label for="${id}-reason">${e(t.reportReason)}</label> <select id="${id}-reason" name="reason" required>${options}</select></p><p><label for="${id}-details">${e(t.reportDetails)}</label> <textarea id="${id}-details" name="details" maxlength="1000" rows="3"></textarea></p><p><label for="${id}-email">${e(t.reportEmail)}</label> <input id="${id}-email" name="email" type="email" maxlength="254" autocomplete="email"></p><div class="cloudhal-comment-hp" aria-hidden="true"><label for="${id}-website">${e(t.website)}</label><input id="${id}-website" name="website" tabindex="-1" autocomplete="off"></div><input type="hidden" name="challenge" value=""><input type="hidden" name="solution" value=""><div data-turnstile></div><p><button type="submit">${e(t.sendReport)}</button></p></form></details>`;
206
+ }
207
+
208
+ function commentHtml(
209
+ c ,
210
+ view ,
211
+ t ,
212
+ names ,
213
+ top ,
214
+ inner = "",
215
+ ) {
216
+ const name = authorName(c, t);
217
+ const badge =
218
+ c.author.kind === "staff"
219
+ ? ` <span class="cloudhal-comment-badge">${e(c.author.badge === "author" ? t.author : t.team)}</span>`
220
+ : "";
221
+ const answered = c.inReplyToId ? names.get(c.inReplyToId) : undefined;
222
+ const context =
223
+ c.inReplyToId && answered !== undefined
224
+ ? ` <a class="cloudhal-comment-context" href="#comment-${e(c.inReplyToId)}">${e(t.inReplyTo(answered))}</a>`
225
+ : "";
226
+ const reply =
227
+ view.state === "open"
228
+ ? `<button type="button" class="cloudhal-comment-reply" data-reply="${e(c.id)}" data-name="${e(name)}" hidden>${e(t.reply)}</button> `
229
+ : "";
230
+ return `<li id="comment-${e(c.id)}" class="cloudhal-comment"${top ? " data-thread" : ""}><article aria-labelledby="comment-${e(c.id)}-author"><header class="cloudhal-comment-meta"><strong class="cloudhal-comment-author" id="comment-${e(c.id)}-author">${e(name)}</strong>${badge} <a class="cloudhal-comment-time" href="#comment-${e(c.id)}"><time datetime="${e(c.createdAt)}">${e(formatDate(c.createdAt, view.locale))}</time></a>${context}</header><div class="cloudhal-comment-body">${c.body ? commentTextHtml(c.body.text) : ""}</div><footer class="cloudhal-comment-actions">${reply}${reportForm(c, t)}</footer></article>${inner}</li>`;
231
+ }
232
+
233
+ function itemHtml(
234
+ item ,
235
+ view ,
236
+ t ,
237
+ names ,
238
+ ) {
239
+ const replies = item.replies.length
240
+ ? `<ol class="cloudhal-comment-replies">${item.replies.map((r) => commentHtml(r, view, t, names, false)).join("")}</ol>`
241
+ : "";
242
+ if ("comment" in item) return commentHtml(item.comment, view, t, names, true, replies);
243
+ return `<li id="comment-${e(item.removed.id)}" class="cloudhal-comment cloudhal-comment-removed" data-thread><p>${e(t.removed)}</p>${replies}</li>`;
244
+ }
245
+
246
+ function formHtml(view , t ) {
247
+ const noScript = view.allowWithoutScript
248
+ ? ""
249
+ : `<noscript><p class="cloudhal-comment-noscript">${e(t.scriptRequired)}</p></noscript>`;
250
+ return `<form id="comment-form" class="cloudhal-comment-form" method="post" action="${COMMENTS_PATH}" data-kind="comment" aria-labelledby="comment-form-title"><h3 id="comment-form-title">${e(t.formTitle)}</h3><p class="cloudhal-comment-replying" data-replying hidden></p>${noScript}<input type="hidden" name="nodeId" value="${e(view.nodeId)}"><input type="hidden" name="parentId" value=""><p><label for="comment-name">${e(t.name)}</label> <input id="comment-name" name="name" required maxlength="80" autocomplete="name" aria-describedby="comment-name-hint"> <small id="comment-name-hint">${e(t.nameHint)}</small></p><p><label for="comment-email">${e(t.email)}</label> <input id="comment-email" name="email" type="email" maxlength="254" autocomplete="email" aria-describedby="comment-email-hint"> <small id="comment-email-hint">${e(t.emailHint)}</small></p><p><label for="comment-body">${e(t.comment)}</label> <textarea id="comment-body" name="body" required minlength="2" maxlength="5000" rows="6"></textarea></p><div class="cloudhal-comment-hp" aria-hidden="true"><label for="comment-website">${e(t.website)}</label><input id="comment-website" name="website" tabindex="-1" autocomplete="off"></div><input type="hidden" name="challenge" value=""><input type="hidden" name="solution" value=""><div data-turnstile></div><p class="cloudhal-comment-privacy">${e(t.moderation)}</p><p class="cloudhal-comment-submit"><button type="submit">${e(t.submit)}</button> <button type="button" data-cancel-reply hidden>${e(t.cancelReply)}</button></p></form>`;
251
+ }
252
+
253
+ /**
254
+ * The section's HTML for a view, or `""` when nothing is shown (hidden and off threads, or no
255
+ * view). Previews get a placeholder and never show comments.
256
+ */
257
+ export function commentsHtml(view , strings ) {
258
+ if (!view) return "";
259
+ const t = strings ?? commentStrings(view.locale);
260
+ if (view.state === "preview")
261
+ return `<section class="cloudhal-comments cloudhal-comments-preview" id="comments"><p>${e(t.preview)}</p></section>`;
262
+ if (view.state !== "open" && view.state !== "closed") return "";
263
+ const page = view.page;
264
+ const items = page?.items ?? [];
265
+ const names = new Map ();
266
+ for (const item of items)
267
+ for (const c of "comment" in item ? [item.comment, ...item.replies] : item.replies)
268
+ names.set(c.id, authorName(c, t));
269
+ const open = view.state === "open";
270
+ const notes = Object.entries(t.notes)
271
+ .map(
272
+ ([id, text]) =>
273
+ `<p class="cloudhal-comment-note" id="comment-${id}" tabindex="-1">${e(text)}</p>`,
274
+ )
275
+ .join("");
276
+ const attrs = [
277
+ `class="cloudhal-comments"`,
278
+ `id="comments"`,
279
+ `aria-labelledby="comments-title"`,
280
+ `data-cloudhal-comments`,
281
+ `data-state="${view.state}"`,
282
+ ...(open
283
+ ? [
284
+ `data-protection="${e(view.protection)}"`,
285
+ ...(view.protection === "turnstile" && view.turnstileSiteKey
286
+ ? [`data-sitekey="${e(view.turnstileSiteKey)}"`]
287
+ : []),
288
+ `data-sending="${e(t.sending)}"`,
289
+ `data-pending-label="${e(t.awaiting)}"`,
290
+ `data-reply-label="${e(t.replyingTo)}"`,
291
+ ]
292
+ : []),
293
+ ].join(" ");
294
+ const list = `<ol class="cloudhal-comment-list"${items.length ? "" : " hidden"}>${items.map((i) => itemHtml(i, view, t, names)).join("")}</ol>`;
295
+ const more =
296
+ page && page.page < page.pageCount
297
+ ? `<nav class="cloudhal-comments-pages" aria-label="${e(t.pages)}"><a href="${e(view.path)}?comments=${page.page + 1}#comments" data-more>${e(t.more)}</a></nav>`
298
+ : "";
299
+ const tail = open
300
+ ? `${formHtml(view, t)}${view.script ? `<script type="module" src="${e(view.script)}"></script>` : ""}`
301
+ : `<p class="cloudhal-comments-closed">${e(t.closed)}</p>`;
302
+ return `<section ${attrs}>${STYLE}<h2 id="comments-title">${e(t.heading(page?.total ?? 0))}</h2><div class="cloudhal-comment-notes">${notes}</div><p class="cloudhal-comments-live" data-live aria-live="polite"></p>${list}${more}${tail}</section>`;
303
+ }
@@ -0,0 +1,6 @@
1
+ interface MiddlewareContext {
2
+ request: Request;
3
+ clientAddress?: string;
4
+ }
5
+ export declare function onRequest(context: MiddlewareContext, next: () => Promise<Response>): Promise<Response>;
6
+ export {};
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Comments middleware (added by the `cloudhal()` integration in `cloudhal dev`; RFC-0007 §15.2):
3
+ * answers the comment endpoints and serves the built module and worker, writing into the local
4
+ * SQLite store (`comments-node.ts`). The Cloudflare Site Worker does the same in its entry
5
+ * (`cloudflare-entry.ts`).
6
+ */
7
+ import client from "virtual:cloudhal/comments-client";
8
+ import config from "virtual:cloudhal/config";
9
+ import { analyticsBackend } from "@cloudhal/astro-renderer/runtime";
10
+ import { createNodeComments, localCommentsKey, } from "./comments-node.js";
11
+
12
+
13
+
14
+
15
+
16
+
17
+ const handler = createNodeComments({
18
+ siteId: config.siteId,
19
+ // the same local store, site row and published snapshots analytics read
20
+ backend: analyticsBackend(config.siteId, config) ,
21
+ client: config.comments?.available === false ? null : client,
22
+ secret: () => localCommentsKey(config.dataDir),
23
+ onError: (m, e) => console.warn(`cloudhal: ${m}`, e),
24
+ });
25
+
26
+ export async function onRequest(
27
+ context ,
28
+ next ,
29
+ ) {
30
+ // The socket address (Astro's `clientAddress`), never a request header.
31
+ let ip ;
32
+ try {
33
+ ip = context.clientAddress;
34
+ } catch {
35
+ ip = undefined;
36
+ }
37
+ return handler(context.request, next, ip);
38
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Reader comments on Node (RFC-0007 §8.5, §15.2): what the `cloudhal()` integration's comments
3
+ * middleware does for `cloudhal dev` (and, later, a Node self-host server). The same
4
+ * `SiteComments` as the Site Worker, on the local SQLite store:
5
+ *
6
+ * - the three endpoints (`/__cloudhal/comments`, `/report`, `/challenge`), resolved against the
7
+ * **published** snapshot of the local store, with the socket address as the client address;
8
+ * - `/_cloudhal/c.<hash>.js` and `/_cloudhal/cw.<hash>.js` from memory (the Site Worker build ships
9
+ * them as static assets instead).
10
+ *
11
+ * The comments key is `CLOUDHAL_COMMENTS_KEY` from the environment or, locally, a random key kept
12
+ * in the data directory (`comments.key`, created on first use, never committed: the data directory
13
+ * is ignored), so comments can be tried without any setup. There is no edge cache to purge.
14
+ */
15
+ import type { Site } from "@cloudhal/core-contracts";
16
+ import type { SqlDriver } from "@cloudhal/storage";
17
+ import type { CommentsClient } from "./comments-client.js";
18
+ import type { GraphSource } from "./source.js";
19
+ export interface NodeCommentsBackend {
20
+ readonly open: () => Promise<SqlDriver>;
21
+ readonly site: () => Promise<Site | undefined>;
22
+ readonly snapshot: (id: string) => Promise<GraphSource>;
23
+ }
24
+ export interface NodeCommentsOptions {
25
+ readonly siteId: string;
26
+ readonly backend: NodeCommentsBackend;
27
+ /** The built module and worker (dev serves them from memory); `null` = comments unavailable. */
28
+ readonly client: Pick<CommentsClient, "module" | "solver"> | null;
29
+ /** The comments key (environment or the local key file). */
30
+ readonly secret: () => Promise<string | undefined>;
31
+ readonly now?: () => Date;
32
+ readonly onError?: (message: string, error?: unknown) => void;
33
+ }
34
+ /** The local key file inside the data directory. */
35
+ export declare const LOCAL_KEY_FILE = "comments.key";
36
+ /**
37
+ * `CLOUDHAL_COMMENTS_KEY` from the environment, else the data directory's own random key (created
38
+ * once, 256 bits, owner-only).
39
+ */
40
+ export declare function localCommentsKey(dataDir: string, env?: Record<string, string | undefined>): Promise<string>;
41
+ /** A request handler around the page pipeline (`next`). */
42
+ export declare function createNodeComments(options: NodeCommentsOptions): (request: Request, next: () => Promise<Response>, clientAddress?: string) => Promise<Response>;
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Reader comments on Node (RFC-0007 §8.5, §15.2): what the `cloudhal()` integration's comments
3
+ * middleware does for `cloudhal dev` (and, later, a Node self-host server). The same
4
+ * `SiteComments` as the Site Worker, on the local SQLite store:
5
+ *
6
+ * - the three endpoints (`/__cloudhal/comments`, `/report`, `/challenge`), resolved against the
7
+ * **published** snapshot of the local store, with the socket address as the client address;
8
+ * - `/_cloudhal/c.<hash>.js` and `/_cloudhal/cw.<hash>.js` from memory (the Site Worker build ships
9
+ * them as static assets instead).
10
+ *
11
+ * The comments key is `CLOUDHAL_COMMENTS_KEY` from the environment or, locally, a random key kept
12
+ * in the data directory (`comments.key`, created on first use, never committed: the data directory
13
+ * is ignored), so comments can be tried without any setup. There is no edge cache to purge.
14
+ */
15
+
16
+ import { readFile, writeFile } from "node:fs/promises";
17
+ import path from "node:path";
18
+ import { randomBytes, toBase64Url } from "@cloudhal/comments";
19
+ import { SqlCommentStore } from "@cloudhal/comments/sql";
20
+
21
+
22
+ import { SiteComments, usableCommentsKey } from "./comments.js";
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+ /** The local key file inside the data directory. */
44
+ export const LOCAL_KEY_FILE = "comments.key";
45
+
46
+ /**
47
+ * `CLOUDHAL_COMMENTS_KEY` from the environment, else the data directory's own random key (created
48
+ * once, 256 bits, owner-only).
49
+ */
50
+ export async function localCommentsKey(
51
+ dataDir ,
52
+ env = process.env,
53
+ ) {
54
+ if (usableCommentsKey(env.CLOUDHAL_COMMENTS_KEY)) return env.CLOUDHAL_COMMENTS_KEY;
55
+ const file = path.join(dataDir, LOCAL_KEY_FILE);
56
+ try {
57
+ const stored = (await readFile(file, "utf8")).trim();
58
+ if (usableCommentsKey(stored)) return stored;
59
+ } catch {
60
+ // no key yet
61
+ }
62
+ const key = toBase64Url(randomBytes(32));
63
+ await writeFile(file, `${key}\n`, { mode: 0o600 });
64
+ return key;
65
+ }
66
+
67
+ const JS = { "content-type": "text/javascript; charset=utf-8", "cache-control": "no-cache" };
68
+
69
+ /** A request handler around the page pipeline (`next`). */
70
+ export function createNodeComments(
71
+ options ,
72
+ ) {
73
+ let comments ;
74
+ const get = () => {
75
+ comments ??= (async () => {
76
+ let store ;
77
+ return new SiteComments({
78
+ siteId: options.siteId,
79
+ secret: await options.secret(),
80
+ available: options.client !== null,
81
+ store: async () => {
82
+ store ??= new SqlCommentStore(await options.backend.open());
83
+ return store;
84
+ },
85
+ site: options.backend.site,
86
+ snapshot: options.backend.snapshot,
87
+ // local servers answer on whatever host they are reached by
88
+ acceptRequestHost: () => true,
89
+ ...(options.now ? { now: options.now } : {}),
90
+ ...(options.onError ? { onError: options.onError } : {}),
91
+ });
92
+ })();
93
+ comments.catch(() => {
94
+ comments = undefined;
95
+ });
96
+ return comments;
97
+ };
98
+
99
+ return async (request, next, clientAddress) => {
100
+ const url = new URL(request.url);
101
+ if (options.client) {
102
+ for (const file of [options.client.module, options.client.solver])
103
+ if (url.pathname === file.path)
104
+ return new Response(request.method === "HEAD" ? null : file.code, { headers: JS });
105
+ }
106
+ if (url.pathname.startsWith("/__cloudhal/comments")) {
107
+ const answer = await (await get()).handle(request, { clientAddress });
108
+ if (answer) return answer;
109
+ }
110
+ return next();
111
+ };
112
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Reader comments in a page (RFC-0007 §8.1), the theme boundary: an article route calls
3
+ * `loadComments` in its frontmatter (response headers can only be set there) and places
4
+ * `<Comments view={…} />` after the article.
5
+ *
6
+ * ```astro
7
+ * const comments = route.kind === "entry" ? await loadComments(config, Astro, route.entry) : undefined;
8
+ * if (comments?.notFound) return new Response(null, { status: 404 });
9
+ * …
10
+ * <Comments view={comments} />
11
+ * ```
12
+ *
13
+ * `loadComments`:
14
+ * - returns `undefined` when the deployment has no comments (no usable `CLOUDHAL_COMMENTS_KEY` on
15
+ * Cloudflare, `comments.available: false`, or a static build, which has no endpoint);
16
+ * - tags the response `cloudhal-comments-<entryId>` (published responses on Cloudflare only), so
17
+ * moderation purges that article and its comment pages, never archives or feeds — every entry
18
+ * page carries it, so turning comments on for a collection reaches pages cached while it was off;
19
+ * - previews (and drafts in `cloudhal dev`) get a placeholder and never read comments;
20
+ * - otherwise reads the settings, the thread row and one page of approved comments
21
+ * (`?comments=<n>`, 50 top-level comments a page; an out-of-range page is `notFound`, which the
22
+ * route answers with a `404`, never cached) and computes the thread state with `threadState`;
23
+ * - on a page with an **open** form on a Turnstile site, sets the page's own CSP with Turnstile's
24
+ * origin added (every other page keeps the default).
25
+ *
26
+ * A read error renders no section (fail closed); the page itself still renders.
27
+ */
28
+ import { type Protection, type RenderPage } from "@cloudhal/comments";
29
+ import type { ContentEntry } from "@cloudhal/core-contracts";
30
+ import type { CloudhalRendererConfig } from "./integration.js";
31
+ export { type CommentStrings, commentStrings, commentsHtml } from "./comments-html.js";
32
+ /** What `<Comments />` renders. */
33
+ export interface CommentsView {
34
+ readonly nodeId: string;
35
+ /** The thread's effective state, or `preview` (a placeholder, nothing read). */
36
+ readonly state: "open" | "closed" | "hidden" | "off" | "preview";
37
+ /** One page of approved comments (absent for previews and unreadable threads). */
38
+ readonly page?: RenderPage;
39
+ /** The entry's path (the "more comments" link). */
40
+ readonly path: string;
41
+ readonly locale: string;
42
+ readonly protection: Protection;
43
+ readonly turnstileSiteKey: string | null;
44
+ readonly allowWithoutScript: boolean;
45
+ /** The module URL (`/_cloudhal/c.<hash>.js`), present when the integration built it. */
46
+ readonly script?: string;
47
+ /** `?comments=<n>` named a page that does not exist: answer `404`. */
48
+ readonly notFound: boolean;
49
+ }
50
+ /** Minimal shape of the Astro global the page passes in. */
51
+ export interface CommentsAstro {
52
+ readonly request: Request;
53
+ readonly url: URL;
54
+ readonly response: {
55
+ readonly headers: Headers;
56
+ };
57
+ }
58
+ /** `?comments=<n>`: `1` when absent, `undefined` when malformed. */
59
+ export declare function commentsPageParam(url: URL): number | undefined;
60
+ /** The JSON-LD the article's `BlogPosting` gains (§8.1): `commentCount` and the first 10. */
61
+ export declare function commentsJsonLd(view: CommentsView | undefined, origin: string): {
62
+ commentCount: number;
63
+ comment?: object[];
64
+ } | undefined;
65
+ export declare function loadComments(config: CloudhalRendererConfig, astro: CommentsAstro, entry: ContentEntry, options?: {
66
+ readonly locale?: string;
67
+ readonly now?: Date;
68
+ }): Promise<CommentsView | undefined>;