@jant/core 1.1.0 → 1.3.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 (196) hide show
  1. package/bin/commands/site/import.js +2 -1
  2. package/bin/lib/site-snapshot.js +10 -0
  3. package/dist/{app-CKQ9PqAr.js → app-C8dETvgL.js} +9267 -5697
  4. package/dist/client/.vite/manifest.json +82 -93
  5. package/dist/client/_assets/chunks/{confirm-CMe01lne.js → confirm-BQebcuNB.js} +1 -1
  6. package/dist/client/_assets/chunks/{create-editor-BQkrw8Ax.js → create-editor-B8KuszlS.js} +38 -38
  7. package/dist/client/_assets/chunks/footnote-rail-DUrqz0Py.js +2 -0
  8. package/dist/client/_assets/chunks/{jant-locale-picker-2L4rkDaz.js → jant-locale-picker-CLq0iKDH.js} +1 -1
  9. package/dist/client/_assets/chunks/lit-BN4mrI3j.js +2 -0
  10. package/dist/client/_assets/chunks/{settings-paths-B0bNUaih.js → settings-paths-_fry4yWW.js} +1 -1
  11. package/dist/client/_assets/chunks/{slug-format-CYmQE5ln.js → slug-format-bcJ2ozr4.js} +1 -1
  12. package/dist/client/_assets/chunks/sortable-list-Bz2Na2E9.js +2 -0
  13. package/dist/client/_assets/chunks/types-DrYFqJH2.js +1 -0
  14. package/dist/client/_assets/chunks/{unsafe-html-CWos3v6N.js → unsafe-html-OJ9m154w.js} +1 -1
  15. package/dist/client/_assets/chunks/unsafe-svg-DVJ4NPcb.js +1 -0
  16. package/dist/client/_assets/client-CoNHvipV.css +2 -0
  17. package/dist/client/_assets/{client-auth-CG55rWb5.js → client-auth-CbnZkLJ6.js} +99 -129
  18. package/dist/client/_assets/{client-author-CGVvrNZ8.css → client-author-2WYBkgni.css} +1 -1
  19. package/dist/client/_assets/client-compose-DYtDlYm-.js +2008 -0
  20. package/dist/client/_assets/{client-manage-DnYdQAhf.js → client-manage-BODyYP5Z.js} +157 -157
  21. package/dist/client/_assets/client-pq6sVS7y.js +354 -0
  22. package/dist/client/_assets/{client-settings-CHgsIqXJ.js → client-settings-DDpe_tXJ.js} +166 -166
  23. package/dist/client/_assets/client-share-B9OsXx9p.js +149 -0
  24. package/dist/{constants-DEgyqWDl.js → constants-C2CdWAqt.js} +55 -5
  25. package/dist/index.js +1 -1
  26. package/dist/node.js +3 -2
  27. package/package.json +2 -1
  28. package/src/app.tsx +9 -0
  29. package/src/client/components/compose-types.ts +6 -1
  30. package/src/client/components/jant-compose-dialog.ts +26 -4
  31. package/src/client/components/jant-compose-editor.ts +30 -0
  32. package/src/client/components/jant-compose-fullscreen.ts +1 -0
  33. package/src/client/components/jant-media-lightbox.ts +18 -3
  34. package/src/client/components/jant-nav-manager.ts +2 -0
  35. package/src/client/components/jant-post-menu.ts +42 -89
  36. package/src/client/components/nav-manager-types.ts +2 -0
  37. package/src/client/components/settings-types.ts +1 -1
  38. package/src/client/compose-bridge.ts +61 -1
  39. package/src/client/feed-video-player.ts +6 -0
  40. package/src/client/list-views.ts +382 -0
  41. package/src/client/media-lightbox-events.ts +12 -0
  42. package/src/client/runtime-paths.ts +12 -0
  43. package/src/client/share-capture.ts +63 -0
  44. package/src/client/share-launch.ts +36 -9
  45. package/src/client/tiptap/bubble-menu.ts +25 -2
  46. package/src/client/tiptap/create-editor.ts +6 -0
  47. package/src/client/tiptap/embed-node.ts +3 -1
  48. package/src/client/tiptap/extensions.ts +4 -0
  49. package/src/client/tiptap/html-block-node.ts +3 -1
  50. package/src/client/tiptap/image-node.ts +3 -1
  51. package/src/client/video-processor.ts +106 -52
  52. package/src/client/view-confirm.ts +136 -0
  53. package/src/client.ts +2 -0
  54. package/src/db/migrations/0035_brainy_next_avengers.sql +9 -0
  55. package/src/db/migrations/0036_gorgeous_smasher.sql +7 -0
  56. package/src/db/migrations/0037_round_post.sql +16 -0
  57. package/src/db/migrations/0038_flashy_changeling.sql +15 -0
  58. package/src/db/migrations/0039_mixed_sister_grimm.sql +1 -0
  59. package/src/db/migrations/meta/0035_snapshot.json +2877 -0
  60. package/src/db/migrations/meta/0036_snapshot.json +2924 -0
  61. package/src/db/migrations/meta/0037_snapshot.json +2932 -0
  62. package/src/db/migrations/meta/0038_snapshot.json +2924 -0
  63. package/src/db/migrations/meta/0039_snapshot.json +2931 -0
  64. package/src/db/migrations/meta/_journal.json +35 -0
  65. package/src/db/migrations/pg/0033_cute_magdalene.sql +10 -0
  66. package/src/db/migrations/pg/0034_material_agent_brand.sql +8 -0
  67. package/src/db/migrations/pg/0035_flimsy_outlaw_kid.sql +3 -0
  68. package/src/db/migrations/pg/0036_milky_wolverine.sql +5 -0
  69. package/src/db/migrations/pg/0037_fuzzy_hammerhead.sql +1 -0
  70. package/src/db/migrations/pg/meta/0033_snapshot.json +3719 -0
  71. package/src/db/migrations/pg/meta/0034_snapshot.json +3766 -0
  72. package/src/db/migrations/pg/meta/0035_snapshot.json +3773 -0
  73. package/src/db/migrations/pg/meta/0036_snapshot.json +3766 -0
  74. package/src/db/migrations/pg/meta/0037_snapshot.json +3772 -0
  75. package/src/db/migrations/pg/meta/_journal.json +35 -0
  76. package/src/db/pg/schema.ts +41 -0
  77. package/src/db/post-visibility.ts +37 -6
  78. package/src/db/schema.ts +64 -0
  79. package/src/i18n/locales/glossary.zh-Hans.yml +4 -0
  80. package/src/i18n/locales/glossary.zh-Hant.yml +4 -0
  81. package/src/i18n/locales/public/en.po +26 -7
  82. package/src/i18n/locales/public/en.ts +1 -1
  83. package/src/i18n/locales/public/zh-Hans.po +25 -6
  84. package/src/i18n/locales/public/zh-Hans.ts +1 -1
  85. package/src/i18n/locales/public/zh-Hant.po +25 -6
  86. package/src/i18n/locales/public/zh-Hant.ts +1 -1
  87. package/src/i18n/locales/settings/en.po +159 -0
  88. package/src/i18n/locales/settings/en.ts +1 -1
  89. package/src/i18n/locales/settings/zh-Hans.po +159 -0
  90. package/src/i18n/locales/settings/zh-Hans.ts +1 -1
  91. package/src/i18n/locales/settings/zh-Hant.po +159 -0
  92. package/src/i18n/locales/settings/zh-Hant.ts +1 -1
  93. package/src/lib/api-public-posts.ts +10 -0
  94. package/src/lib/env.ts +20 -0
  95. package/src/lib/feed-policy.ts +2 -2
  96. package/src/lib/filter-dimensions.ts +11 -4
  97. package/src/lib/github-app-state.ts +1 -1
  98. package/src/lib/github-app.ts +183 -1
  99. package/src/lib/hugo-markdown.ts +7 -0
  100. package/src/lib/icons.ts +2 -0
  101. package/src/lib/link-preview.ts +499 -0
  102. package/src/lib/list-views.ts +117 -0
  103. package/src/lib/markdown-manager.ts +169 -2
  104. package/src/lib/navigation.ts +1 -1
  105. package/src/lib/post-meta.ts +13 -3
  106. package/src/lib/referrer-aliases.ts +311 -0
  107. package/src/lib/render.tsx +10 -0
  108. package/src/lib/resolve-config.ts +14 -0
  109. package/src/lib/share-card.ts +4 -3
  110. package/src/lib/summary.ts +152 -54
  111. package/src/lib/thread-query.ts +6 -2
  112. package/src/lib/timeline.ts +12 -11
  113. package/src/lib/tiptap-render.ts +1 -0
  114. package/src/lib/upload.ts +21 -1
  115. package/src/lib/url-fetch.ts +291 -74
  116. package/src/lib/video-playback.ts +55 -0
  117. package/src/lib/view-buffer.ts +201 -0
  118. package/src/lib/view-counting.ts +540 -0
  119. package/src/lib/view-token.ts +199 -0
  120. package/src/lib/view.ts +30 -1
  121. package/src/middleware/view-counter.ts +145 -0
  122. package/src/node/runtime.ts +4 -0
  123. package/src/preset.css +36 -17
  124. package/src/routes/api/media.ts +21 -3
  125. package/src/routes/api/search.ts +1 -1
  126. package/src/routes/dash/settings.tsx +434 -169
  127. package/src/routes/feed/sitemap.ts +1 -1
  128. package/src/routes/pages/archive.tsx +26 -19
  129. package/src/routes/pages/collection.tsx +9 -3
  130. package/src/routes/pages/collections.tsx +1 -0
  131. package/src/routes/pages/featured.tsx +1 -0
  132. package/src/routes/pages/home.tsx +1 -0
  133. package/src/routes/pages/page.tsx +18 -3
  134. package/src/routes/pages/search.tsx +3 -3
  135. package/src/routes/pages/smart-collection.tsx +2 -0
  136. package/src/routes/pages/subscribe.tsx +1 -0
  137. package/src/routes/view-confirm.ts +71 -0
  138. package/src/services/collection.ts +1 -1
  139. package/src/services/export-theme/assets/client-site.js +19 -19
  140. package/src/services/export-theme/layouts/archive/list.html +4 -2
  141. package/src/services/export-theme/layouts/partials/collection-members.html +4 -3
  142. package/src/services/export-theme/layouts/partials/featured-members.html +3 -3
  143. package/src/services/export-theme/layouts/partials/head.html +2 -0
  144. package/src/services/export-theme/layouts/partials/latest-members.html +4 -4
  145. package/src/services/export-theme/layouts/partials/post-card.html +1 -9
  146. package/src/services/export-theme/layouts/partials/reply.html +1 -9
  147. package/src/services/export-theme/layouts/partials/smart-collection-members.html +4 -3
  148. package/src/services/export-theme/layouts/post/list.html +1 -9
  149. package/src/services/export-theme/styles/main.css +41 -47
  150. package/src/services/export.ts +12 -3
  151. package/src/services/index.ts +17 -0
  152. package/src/services/mcp.ts +36 -6
  153. package/src/services/media.ts +63 -0
  154. package/src/services/navigation.ts +9 -4
  155. package/src/services/post.ts +102 -112
  156. package/src/services/search.ts +22 -7
  157. package/src/services/smart-collection.ts +3 -3
  158. package/src/services/stats.ts +1137 -0
  159. package/src/services/thread.ts +6 -2
  160. package/src/styles/components-author.css +242 -3
  161. package/src/styles/components.css +11 -3
  162. package/src/styles/tokens.css +89 -55
  163. package/src/styles/ui-author.css +140 -353
  164. package/src/styles/ui.css +90 -45
  165. package/src/types/app-context.ts +9 -0
  166. package/src/types/bindings.ts +5 -0
  167. package/src/types/config.ts +54 -0
  168. package/src/types/constants.ts +68 -4
  169. package/src/types/entities.ts +1 -0
  170. package/src/types/views.ts +8 -0
  171. package/src/ui/compose/ComposeDialog.tsx +26 -1
  172. package/src/ui/dash/StatusBadge.tsx +11 -0
  173. package/src/ui/dash/appearance/FontThemeContent.tsx +1 -1
  174. package/src/ui/dash/appearance/NavigationContent.tsx +8 -0
  175. package/src/ui/dash/settings/SettingsRootContent.tsx +24 -6
  176. package/src/ui/dash/settings/StatsContent.tsx +855 -0
  177. package/src/ui/feed/LinkCard.tsx +19 -2
  178. package/src/ui/feed/PostStatusBadges.tsx +19 -3
  179. package/src/ui/feed/TimelineFeed.tsx +3 -0
  180. package/src/ui/font-themes.ts +56 -6
  181. package/src/ui/layouts/BaseLayout.tsx +4 -2
  182. package/src/ui/layouts/SiteLayout.tsx +8 -3
  183. package/src/ui/pages/ArchivePage.tsx +1 -0
  184. package/src/ui/shared/MediaGallery.tsx +19 -3
  185. package/src/ui/shared/PostFooter.tsx +1 -22
  186. package/src/ui/shared/custom-icons.ts +5 -5
  187. package/dist/client/_assets/chunks/footnote-rail-B08scyhW.js +0 -2
  188. package/dist/client/_assets/chunks/lit-Bw_voPoW.js +0 -2
  189. package/dist/client/_assets/chunks/runtime-paths-y0_gHowM.js +0 -1
  190. package/dist/client/_assets/chunks/sortable-list-t11Ma1Ek.js +0 -2
  191. package/dist/client/_assets/chunks/types-D5iF3H1a.js +0 -1
  192. package/dist/client/_assets/chunks/unsafe-svg-DZl-yjas.js +0 -1
  193. package/dist/client/_assets/client-B0-s9sqx.css +0 -2
  194. package/dist/client/_assets/client-Dp46QSht.js +0 -354
  195. package/dist/client/_assets/client-compose-DkUTuavR.js +0 -2004
  196. package/dist/client/_assets/client-share-C59mOLJ1.js +0 -149
@@ -0,0 +1,199 @@
1
+ /**
2
+ * The token a page carries so the browser that opened it can confirm it was
3
+ * seen.
4
+ *
5
+ * A request alone cannot tell a reader from a crawler that runs a real
6
+ * browser: the headers are the same. What differs is what happens after the
7
+ * HTML arrives. A reader keeps the page in front of them, scrolls, taps; a
8
+ * crawler closes it in a second. So the page is counted only once the
9
+ * browser says it was seen, and this token is how the page says which view
10
+ * that was without the server keeping anything in the meantime.
11
+ *
12
+ * The server decides everything about the view at request time, as before
13
+ * (which page, where the reader came from), seals it into the token with an
14
+ * HMAC over `AUTH_SECRET`, and writes the token into the page. The browser
15
+ * posts the token back after the page has been visible for a while or on the
16
+ * first interaction. The endpoint verifies the signature, checks the token is
17
+ * fresh and is this site's, and counts the view with the day and hour of
18
+ * that moment.
19
+ *
20
+ * A list page's token also names the Threads the page shows whole
21
+ * (`data-view-unit`, `lib/list-views.ts`). The browser posts the token again,
22
+ * followed by the ones a reader read there in full, and only those the token
23
+ * names are counted: a token for the home page cannot count a post that was
24
+ * never on it.
25
+ *
26
+ * The time in the token is a ten-minute slot, not a timestamp, so every
27
+ * response for the same page and source within a slot carries the same
28
+ * token: the HTML stays byte-identical across readers, as it was. A token is
29
+ * accepted for the current slot and the three before it, half an hour or so,
30
+ * long enough to read a page slowly, short enough that a harvested token is
31
+ * worthless the next day.
32
+ */
33
+
34
+ import { hmacHex, timingSafeEqualText } from "./crypto.js";
35
+
36
+ /** The `<meta name>` the page carries the token under. */
37
+ export const VIEW_TOKEN_META_NAME = "jant-view";
38
+
39
+ /** Where the browser posts the token. Under `/_`, with the other reserved paths. */
40
+ export const VIEW_CONFIRM_PATH = "/_/seen";
41
+
42
+ /** Seconds in a token's time slot. */
43
+ export const VIEW_TOKEN_SLOT_SECONDS = 600;
44
+
45
+ /** Slots a token is accepted for: the current one and the ones before it. */
46
+ export const VIEW_TOKEN_SLOTS_ACCEPTED = 4;
47
+
48
+ /** Hex characters of the HMAC kept: 128 bits. */
49
+ const SIGNATURE_LENGTH = 32;
50
+
51
+ /**
52
+ * Longer than any token this module writes, a list page's hundred Threads
53
+ * included; a longer one is not ours.
54
+ */
55
+ const TOKEN_MAX_LENGTH = 8192;
56
+
57
+ /** What a token says about the view. */
58
+ export interface ViewTokenClaims {
59
+ siteId: string;
60
+ /** The counter key of the page: an id or a path. */
61
+ page: string;
62
+ /** The referrer key: a host or tag, the site itself, or `""`. */
63
+ referrer: string;
64
+ /**
65
+ * The Threads, by root id, the page shows whole in its lists: the ones a
66
+ * report of Threads read may name. Empty for any other page.
67
+ */
68
+ units: string[];
69
+ }
70
+
71
+ function toBase64Url(text: string): string {
72
+ const bytes = new TextEncoder().encode(text);
73
+ let binary = "";
74
+ for (const byte of bytes) binary += String.fromCharCode(byte);
75
+ return btoa(binary)
76
+ .replace(/\+/g, "-")
77
+ .replace(/\//g, "_")
78
+ .replace(/=+$/, "");
79
+ }
80
+
81
+ function fromBase64Url(text: string): string | null {
82
+ try {
83
+ const padded =
84
+ text.replace(/-/g, "+").replace(/_/g, "/") +
85
+ "=".repeat((4 - (text.length % 4)) % 4);
86
+ const binary = atob(padded);
87
+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
88
+ // Malformed UTF-8 decodes to replacement characters and fails the JSON
89
+ // and shape checks that follow.
90
+ return new TextDecoder().decode(bytes);
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+
96
+ /**
97
+ * The time slot a moment falls in.
98
+ *
99
+ * @param timestamp - Unix timestamp in seconds
100
+ * @returns The slot number
101
+ * @example
102
+ * viewTokenSlot(1_762_560_000); // 2937600
103
+ */
104
+ export function viewTokenSlot(timestamp: number): number {
105
+ return Math.floor(timestamp / VIEW_TOKEN_SLOT_SECONDS);
106
+ }
107
+
108
+ async function signature(secret: string, payload: string): Promise<string> {
109
+ const hex = await hmacHex(secret, `jant-view:${payload}`);
110
+ return hex.slice(0, SIGNATURE_LENGTH);
111
+ }
112
+
113
+ /**
114
+ * The token for a view, to be written into the page.
115
+ *
116
+ * @param secret - The deployment's `AUTH_SECRET`
117
+ * @param claims - Which page, where the reader came from, and the Threads
118
+ * it shows whole
119
+ * @param timestamp - Unix timestamp in seconds, now
120
+ * @returns `payload.signature`, both URL-safe
121
+ * @example
122
+ * ```ts
123
+ * const token = await signViewToken(
124
+ * secret,
125
+ * { siteId, page: post.threadId, referrer: "", units: [] },
126
+ * now(),
127
+ * );
128
+ * ```
129
+ */
130
+ export async function signViewToken(
131
+ secret: string,
132
+ claims: ViewTokenClaims,
133
+ timestamp: number,
134
+ ): Promise<string> {
135
+ const payload = toBase64Url(
136
+ JSON.stringify({
137
+ s: claims.siteId,
138
+ p: claims.page,
139
+ r: claims.referrer,
140
+ t: viewTokenSlot(timestamp),
141
+ ...(claims.units.length > 0 ? { l: claims.units } : {}),
142
+ }),
143
+ );
144
+ return `${payload}.${await signature(secret, payload)}`;
145
+ }
146
+
147
+ /**
148
+ * What a token posted back says, if it is ours and still fresh.
149
+ *
150
+ * @param secret - The deployment's `AUTH_SECRET`
151
+ * @param token - What the browser posted
152
+ * @param timestamp - Unix timestamp in seconds, now
153
+ * @returns The claims, or `null` for a token that is forged, altered,
154
+ * malformed, from the future, or past its slots
155
+ * @example
156
+ * ```ts
157
+ * const claims = await verifyViewToken(secret, await c.req.text(), now());
158
+ * if (claims && claims.siteId === site.id) count(claims);
159
+ * ```
160
+ */
161
+ export async function verifyViewToken(
162
+ secret: string,
163
+ token: string,
164
+ timestamp: number,
165
+ ): Promise<ViewTokenClaims | null> {
166
+ if (token.length === 0 || token.length > TOKEN_MAX_LENGTH) return null;
167
+ const dot = token.lastIndexOf(".");
168
+ if (dot <= 0) return null;
169
+ const payload = token.slice(0, dot);
170
+ const given = token.slice(dot + 1);
171
+ if (given.length !== SIGNATURE_LENGTH) return null;
172
+ if (!timingSafeEqualText(await signature(secret, payload), given)) {
173
+ return null;
174
+ }
175
+
176
+ const json = fromBase64Url(payload);
177
+ if (json === null) return null;
178
+ let parsed: unknown;
179
+ try {
180
+ parsed = JSON.parse(json);
181
+ } catch {
182
+ return null;
183
+ }
184
+ if (typeof parsed !== "object" || parsed === null) return null;
185
+ const { s, p, r, t, l = [] } = parsed as Record<string, unknown>;
186
+ if (
187
+ typeof s !== "string" ||
188
+ typeof p !== "string" ||
189
+ typeof r !== "string" ||
190
+ typeof t !== "number" ||
191
+ !Array.isArray(l) ||
192
+ !l.every((unit) => typeof unit === "string")
193
+ ) {
194
+ return null;
195
+ }
196
+ const age = viewTokenSlot(timestamp) - t;
197
+ if (age < 0 || age >= VIEW_TOKEN_SLOTS_ACCEPTED) return null;
198
+ return { siteId: s, page: p, referrer: r, units: l as string[] };
199
+ }
package/src/lib/view.ts CHANGED
@@ -36,6 +36,7 @@ import {
36
36
  } from "./time.js";
37
37
  import { getCollectionPagePath } from "./collection-paths.js";
38
38
  import { getMediaUrl, getImageUrl, getPublicUrlForProvider } from "./image.js";
39
+ import { getLinkPreviewIconImageOptions } from "./link-preview.js";
39
40
  import {
40
41
  extractSummaryHtml,
41
42
  extractBodyText,
@@ -46,6 +47,7 @@ import {
46
47
  NOTE_SUMMARY_MIN_HIDDEN_CHARS,
47
48
  } from "./summary.js";
48
49
  import { renderTiptapDocumentAroundBoundary } from "./tiptap-render.js";
50
+ import { toMediaKind } from "./upload.js";
49
51
  import { highlightText } from "./search-snippet.js";
50
52
  import { getPostPath, isFullUrl, toPublicPath, toSameSitePath } from "./url.js";
51
53
 
@@ -275,7 +277,10 @@ export function toPostView(
275
277
  //
276
278
  // - Titled (article-style) posts get an excerpt teaser (`summaryHtml`) and a
277
279
  // "Continue" link to the full page; a `#continue` anchor is spliced into the
278
- // body for scroll targeting on that page.
280
+ // body for scroll targeting on that page. The teaser keeps one inline image
281
+ // from ahead of the cut, unless the post has an image or video attachment:
282
+ // the card shows that gallery below the teaser, and one card carries one
283
+ // set of pictures.
279
284
  // - Untitled notes render their body in full and expand in place. When the
280
285
  // body is long enough to truncate (larger limit + tolerance guard) we splice
281
286
  // a `data-note-break` marker at the boundary so the feed can clamp the tail
@@ -287,12 +292,20 @@ export function toPostView(
287
292
  let bodyHtmlWithAnchor = post.bodyHtml;
288
293
  if (post.body) {
289
294
  const isArticle = !!post.title;
295
+ const hasVisualAttachment = post.mediaAttachments.some((m) => {
296
+ const kind = toMediaKind(m.mimeType);
297
+ return kind === "image" || kind === "video";
298
+ });
290
299
  const result = extractSummaryHtml(
291
300
  post.body,
292
301
  isArticle ? ARTICLE_SUMMARY_MAX_BLOCKS : NOTE_SUMMARY_MAX_BLOCKS,
293
302
  isArticle ? ARTICLE_SUMMARY_MAX_CHARS : NOTE_SUMMARY_MAX_CHARS,
294
303
  isArticle ? 0 : NOTE_SUMMARY_MIN_HIDDEN_CHARS,
295
304
  { namespace: id },
305
+ {
306
+ includeImages: isArticle && !hasVisualAttachment,
307
+ stopAtHeading: isArticle,
308
+ },
296
309
  );
297
310
  if (result && isArticle) {
298
311
  summaryHtml = result.html;
@@ -392,6 +405,22 @@ export function toPostView(
392
405
  { width: 1280, quality: 80, format: "auto", fit: "scale-down" },
393
406
  )
394
407
  : undefined,
408
+ previewIconUrl: post.previewIconKey
409
+ ? getImageUrl(
410
+ getMediaUrl(
411
+ post.previewIconKey,
412
+ getPublicUrlForProvider(
413
+ ctx.storageDriver ?? "r2",
414
+ ctx.r2PublicUrl,
415
+ ctx.s3PublicUrl,
416
+ ctx.localPublicUrl,
417
+ ),
418
+ ctx.sitePathPrefix,
419
+ ),
420
+ ctx.imageTransformUrl,
421
+ getLinkPreviewIconImageOptions(post.previewIconKey),
422
+ )
423
+ : undefined,
395
424
  publishedAt: toISOString(publishedAt),
396
425
  publishedAtFormatted: formatDate(publishedAt, timeZone),
397
426
  publishedAtTime: formatTime(publishedAt, timeZone),
@@ -0,0 +1,145 @@
1
+ /**
2
+ * View Counter Middleware
3
+ *
4
+ * Runs after the route and, when the route named what it rendered
5
+ * (`c.var.viewTarget`) and the request was one reader opening that page,
6
+ * writes a signed view token into the page's `<head>`. On a list page the
7
+ * token also names the Threads the page shows whole, read from the marks the
8
+ * feed left on them (`lib/list-views.ts`). The view is counted
9
+ * only when the browser posts that token back (`routes/view-confirm.ts`),
10
+ * which the reader bundle does once the page has been in front of the reader
11
+ * for a few seconds or on the first interaction: a request can look exactly
12
+ * like a reader's and still be a crawler running a browser, and what tells
13
+ * them apart happens after the HTML arrives. The reader never waits on any
14
+ * of it.
15
+ *
16
+ * Everything that decides whether a response may count lives in
17
+ * `lib/view-counting.ts`; the token in `lib/view-token.ts`; when a confirmed
18
+ * view is written in `lib/view-buffer.ts`; what is kept and for how long in
19
+ * `services/stats.ts`. This file connects the first two to a response.
20
+ */
21
+
22
+ import type { Context, MiddlewareHandler } from "hono";
23
+ import type { Bindings } from "../types.js";
24
+ import type { AppVariables } from "../types/app-context.js";
25
+ import { getEnvString } from "../lib/env.js";
26
+ import { now } from "../lib/time.js";
27
+ import type { ViewSink } from "../lib/view-buffer.js";
28
+ import {
29
+ formatDayKey,
30
+ shouldCountView,
31
+ viewPathKey,
32
+ viewReferrer,
33
+ } from "../lib/view-counting.js";
34
+ import { viewUnitsInHtml } from "../lib/list-views.js";
35
+ import { signViewToken, VIEW_TOKEN_META_NAME } from "../lib/view-token.js";
36
+ import { viewBasePath } from "../lib/view-language.js";
37
+
38
+ type Env = { Bindings: Bindings; Variables: AppVariables };
39
+
40
+ /**
41
+ * Where a confirmed view's hit goes: the site's stats service, with the
42
+ * flush kept alive past the response on Workers.
43
+ *
44
+ * @param c - The request the hit belongs to
45
+ * @returns The sink for `ViewBuffer.add`
46
+ * @example
47
+ * buffer.add(hit, viewSinkFor(c));
48
+ */
49
+ export function viewSinkFor(c: Context<Env>): ViewSink {
50
+ const { services, appConfig } = c.var;
51
+ const { dailyLimit } = appConfig.stats;
52
+ return {
53
+ record: (entries) =>
54
+ services.stats.record(entries, {
55
+ dailyLimit,
56
+ today: formatDayKey(now(), "UTC"),
57
+ }),
58
+ keepAlive: (promise) => {
59
+ try {
60
+ c.executionCtx.waitUntil(promise);
61
+ } catch {
62
+ // Node and tests have no ExecutionContext; the timer runs anyway.
63
+ }
64
+ },
65
+ };
66
+ }
67
+
68
+ /**
69
+ * Middleware that marks a page a reader opened with its view token.
70
+ *
71
+ * Mount it after `withConfig()`, since the stats switch comes from the
72
+ * resolved config, and before the page routes, so it wraps them.
73
+ *
74
+ * @returns Hono middleware
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * app.use("*", withConfig());
79
+ * app.use("*", viewCounter());
80
+ * ```
81
+ */
82
+ export function viewCounter(): MiddlewareHandler<Env> {
83
+ return async (c, next) => {
84
+ await next();
85
+
86
+ const target = c.get("viewTarget");
87
+ if (!target) return;
88
+
89
+ const { appConfig } = c.var;
90
+ if (!appConfig.stats.enabled) return;
91
+ if (
92
+ !shouldCountView({
93
+ method: c.req.method,
94
+ status: c.res.status,
95
+ contentType: c.res.headers.get("content-type"),
96
+ isAuthenticated: c.var.isAuthenticated,
97
+ headers: c.req.raw.headers,
98
+ })
99
+ ) {
100
+ return;
101
+ }
102
+ const secret = getEnvString(c.env, "AUTH_SECRET");
103
+ if (!secret) return;
104
+
105
+ // `c.req.path` carries no query string: the second page of the home
106
+ // feed and a filtered archive are the page they belong to.
107
+ const page =
108
+ target.kind === "path"
109
+ ? viewPathKey(c.req.path, viewBasePath(c))
110
+ : target.id;
111
+
112
+ // The body is a rendered string; reading it consumes it, so the response
113
+ // is rebuilt either way.
114
+ const html = await c.res.text();
115
+ const token = await signViewToken(
116
+ secret,
117
+ {
118
+ siteId: c.var.currentSite.id,
119
+ page,
120
+ referrer: viewReferrer({
121
+ referer: c.req.header("referer"),
122
+ requestUrl: c.req.url,
123
+ ownHost: new URL(c.var.publicRequestUrl).hostname,
124
+ fetchSite: c.req.header("sec-fetch-site"),
125
+ }),
126
+ units: viewUnitsInHtml(html),
127
+ },
128
+ now(),
129
+ );
130
+
131
+ // The token is base64url and hex: safe as-is in an attribute.
132
+ const head = html.indexOf("</head>");
133
+ const body =
134
+ head === -1
135
+ ? html
136
+ : `${html.slice(0, head)}<meta name="${VIEW_TOKEN_META_NAME}" content="${token}">${html.slice(head)}`;
137
+ const headers = new Headers(c.res.headers);
138
+ headers.delete("content-length");
139
+ c.res = new Response(body, {
140
+ status: c.res.status,
141
+ statusText: c.res.statusText,
142
+ headers,
143
+ });
144
+ };
145
+ }
@@ -8,6 +8,7 @@ import {
8
8
  resolvePort,
9
9
  } from "./request-handler.js";
10
10
  import { registerTelegramPoolWebhooks } from "../lib/telegram-pool-webhooks.js";
11
+ import { viewBuffer } from "../lib/view-buffer.js";
11
12
 
12
13
  export {
13
14
  applyNodeRuntimeEnvDefaults,
@@ -96,6 +97,9 @@ export async function start(
96
97
  });
97
98
  });
98
99
  } finally {
100
+ // Counted views still waiting in the buffer go out before the
101
+ // database they go to is closed.
102
+ await viewBuffer.flush();
99
103
  await handler.close();
100
104
  }
101
105
  },
package/src/preset.css CHANGED
@@ -249,6 +249,10 @@ html {
249
249
  margin-bottom: 1.4rem;
250
250
  }
251
251
 
252
+ /* A heading binds to the text it introduces: the space above it is two to
253
+ three times the space below, and the space below is less than a paragraph
254
+ gap. With equal margins on both sides, as before, a heading floated
255
+ halfway between the sections. */
252
256
  :where(h1) {
253
257
  font-size: var(--type-content-display);
254
258
  margin-top: 4rem;
@@ -257,25 +261,36 @@ html {
257
261
 
258
262
  :where(h2) {
259
263
  font-size: var(--type-content-title);
260
- margin-top: 2.1rem;
261
- margin-bottom: 1.4rem;
264
+ margin-top: 2.6rem;
265
+ margin-bottom: 0.9rem;
262
266
  }
263
267
 
264
268
  :where(h3) {
265
269
  font-size: var(--type-content-subtitle);
266
- margin-top: 2rem;
267
- margin-bottom: 1.4rem;
270
+ margin-top: 2.2rem;
271
+ margin-bottom: 0.75rem;
268
272
  }
269
273
 
270
- :where(h4, h5, h6) {
274
+ :where(h4) {
271
275
  font-size: var(--type-content-body);
272
- font-weight: var(--fw-medium);
276
+ margin-top: 1.8rem;
277
+ margin-bottom: 0.6rem;
273
278
  }
274
279
 
275
280
  :where(h5, h6) {
281
+ font-size: var(--type-content-body);
282
+ font-weight: var(--fw-medium);
276
283
  color: var(--site-reading-meta);
277
284
  }
278
285
 
286
+ /* The block after a heading gives up its own top margin, so the heading's
287
+ bottom margin is the whole gap. Left in place, a paragraph's 1.4rem wins
288
+ the margin collapse against any smaller heading margin, and the heading
289
+ floats 1.4rem from both neighbours whatever its margins say. */
290
+ :where(h1, h2, h3, h4, h5, h6) + :where(*) {
291
+ margin-top: 0;
292
+ }
293
+
279
294
  :where(ul, ol) {
280
295
  margin: 1.25em 0;
281
296
  padding-left: 1.4em;
@@ -507,17 +522,19 @@ html {
507
522
  */
508
523
  [data-post]:not(.post-detail) [data-post-body].prose {
509
524
  :where(h1, h2) {
510
- font-size: calc(var(--type-content-body) * 1.12);
511
- font-weight: var(--fw-medium);
512
- margin-top: 1.45rem;
513
- margin-bottom: 0.55rem;
525
+ font-size: calc(var(--type-content-body) * 1.2);
526
+ font-weight: var(--type-heading-weight);
527
+ margin-top: 1.6rem;
528
+ margin-bottom: 0.6rem;
514
529
  }
515
530
 
531
+ /* Still a step above the body: at body size in the medium weight these
532
+ read as a stray line, since the CJK serif faces render 500 as Regular. */
516
533
  :where(h3, h4) {
517
- font-size: var(--type-content-body);
518
- font-weight: var(--fw-medium);
519
- margin-top: 1.2rem;
520
- margin-bottom: 0.45rem;
534
+ font-size: calc(var(--type-content-body) * 1.08);
535
+ font-weight: var(--type-heading-weight);
536
+ margin-top: 1.4rem;
537
+ margin-bottom: 0.5rem;
521
538
  }
522
539
 
523
540
  :where(h5, h6) {
@@ -588,10 +605,12 @@ html {
588
605
  overflow-wrap: break-word;
589
606
  }
590
607
 
591
- /* Attribution and domain lay their parts out with flex, so each part is a flex
592
- item that refuses to shrink below its min-content width. `break-word` leaves
608
+ /* The attribution lays its parts out with flex, so each part is a flex item
609
+ that refuses to shrink below its min-content width. `break-word` leaves
593
610
  min-content at the longest word and the item still overflows; `anywhere` also
594
- shrinks min-content, which is what lets the row wrap. */
611
+ shrinks min-content, which is what lets the row wrap. The domain row is
612
+ inline text, where either value would do; it keeps `anywhere` so a long
613
+ domain breaks the same way in both rows. */
595
614
  .feed-quote-attribution,
596
615
  .feed-link-domain {
597
616
  overflow-wrap: anywhere;
@@ -2,9 +2,9 @@
2
2
  * Media API Routes
3
3
  *
4
4
  * The author's uploaded files as a resource: list, read, change alt text,
5
- * delete. Uploading happens at `POST /api/upload` (one request) or
6
- * `/api/uploads` (a resumable session); the MCP media tools share these
7
- * responses.
5
+ * give a video its poster, delete. Uploading happens at `POST /api/upload`
6
+ * (one request) or `/api/uploads` (a resumable session); the MCP media tools
7
+ * share these responses.
8
8
  */
9
9
 
10
10
  import { Hono } from "hono";
@@ -17,6 +17,7 @@ import { assertFound, parseIdParam } from "../../lib/errors.js";
17
17
  import { ID_PREFIX } from "../../lib/ids.js";
18
18
  import { pageLimitSchema } from "../../lib/schemas.js";
19
19
  import { toApiMedia } from "../../lib/api-media.js";
20
+ import { requireStorage } from "../../lib/storage.js";
20
21
 
21
22
  type Env = { Bindings: Bindings; Variables: AppVariables };
22
23
 
@@ -69,6 +70,23 @@ mediaApiRoutes.put("/:id", validate("json", UpdateMediaSchema), async (c) => {
69
70
  return c.json(toApiMedia(media, c.var.appConfig));
70
71
  });
71
72
 
73
+ // A video uploaded without a poster can be given one afterwards: the body is
74
+ // the WebP or PNG bytes, as for `PUT /api/uploads/:id/poster`.
75
+ mediaApiRoutes.put("/:id/poster", async (c) => {
76
+ const storage = requireStorage(c.var.storage);
77
+ const id = parseIdParam(c.req.param("id"), ID_PREFIX.media);
78
+
79
+ const media = assertFound(
80
+ await c.var.services.media.setPoster(
81
+ id,
82
+ new Uint8Array(await c.req.arrayBuffer()),
83
+ { storage },
84
+ ),
85
+ "Media",
86
+ );
87
+ return c.json(toApiMedia(media, c.var.appConfig));
88
+ });
89
+
72
90
  mediaApiRoutes.delete("/:id", async (c) => {
73
91
  const id = parseIdParam(c.req.param("id"), ID_PREFIX.media);
74
92
  assertFound(await c.var.services.media.getById(id), "Media");
@@ -30,7 +30,7 @@ searchApiRoutes.get(
30
30
  const results = await c.var.services.search.search(query, {
31
31
  limit,
32
32
  status: ["published"],
33
- includePrivate: true,
33
+ asAuthor: true,
34
34
  });
35
35
 
36
36
  return c.json({