@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,540 @@
1
+ /**
2
+ * What counts as a page view, and the keys a view is filed under.
3
+ *
4
+ * A view is decided in two steps. Here, from the facts of one request and
5
+ * its response, whether it may count at all: a browser's top-level navigation
6
+ * announces itself in the `Sec-Fetch-*` headers every current engine sends
7
+ * and almost no crawler does, and the short User-Agent list below is only a
8
+ * backstop for the headless browsers that still say what they are. Then, in
9
+ * the browser, whether the page was seen: the reader bundle confirms the
10
+ * view after a few seconds in front of the reader or on the first
11
+ * interaction (`lib/view-token.ts`), which a crawler running a real browser
12
+ * never gets to. No cookie, no stored address. This module also reduces what
13
+ * is kept to a counter key: the site's calendar day and hour, the page, and
14
+ * where the reader came from — the source the link was tagged with, or else
15
+ * the referring host, either one folded to the address its source is listed
16
+ * under (`referrer-aliases.ts`), or the site itself.
17
+ */
18
+
19
+ import { ID_PREFIX, isTypeId } from "./ids.js";
20
+ import { canonicalSource } from "./referrer-aliases.js";
21
+
22
+ /**
23
+ * What the page a route rendered counts as: a Thread (by its root's id — a
24
+ * lone post is a Thread of one), a collection or a smart collection, by id,
25
+ * so a count survives a change of address and an alias and its canonical
26
+ * path are one page; or any other public page — the home page, the archive,
27
+ * an aggregate selection — by its path. Routes set it on the context
28
+ * (`viewTarget`) and `middleware/view-counter.ts` reads it after the
29
+ * response.
30
+ */
31
+ export type ViewTarget =
32
+ | { kind: "post" | "collection" | "smartCollection"; id: string }
33
+ | { kind: "path" };
34
+
35
+ /**
36
+ * The `page` and `referrer` of a site-day's overflow row, where new
37
+ * page-referrer pairs land once the day has `VIEW_COUNT_ROWS_PER_SITE_DAY`
38
+ * rows. Never a real page or host: a path starts with `/`, an id with its
39
+ * TypeID prefix, and a hostname has no `*`.
40
+ */
41
+ export const VIEW_OVERFLOW_KEY = "*";
42
+
43
+ /**
44
+ * The referrer of a view that came from another page of the site itself:
45
+ * a reader moving on from the home page to a post. Kept apart from a direct
46
+ * visit so that "Direct" means what it says, and never a host, since no
47
+ * hostname is `/`.
48
+ */
49
+ export const VIEW_INTERNAL_REFERRER = "/";
50
+
51
+ /** What a counter key names, told from its shape alone. */
52
+ export type ViewPageKind =
53
+ "post" | "collection" | "smartCollection" | "path" | "overflow";
54
+
55
+ /**
56
+ * What a counter key names. A key is self-describing: the overflow key,
57
+ * a path, or a TypeID whose prefix says which table the entity is in. The
58
+ * table needs no kind column for it.
59
+ *
60
+ * @param key - A `view_count.page` value
61
+ * @returns Its kind, or `null` for a string that could never be a key
62
+ * @example
63
+ * ```ts
64
+ * viewPageKind("/archive"); // "path"
65
+ * viewPageKind("pst_01h455vb4pex5vsknk084sn02q"); // "post"
66
+ * viewPageKind("nonsense"); // null
67
+ * ```
68
+ */
69
+ export function viewPageKind(key: string): ViewPageKind | null {
70
+ if (key === VIEW_OVERFLOW_KEY) return "overflow";
71
+ if (key.startsWith("/")) return "path";
72
+ if (isTypeId(key, ID_PREFIX.post)) return "post";
73
+ if (isTypeId(key, ID_PREFIX.collection)) return "collection";
74
+ if (isTypeId(key, ID_PREFIX.smartCollection)) return "smartCollection";
75
+ return null;
76
+ }
77
+
78
+ /** Longest page key stored; a path past this is nothing a site links to. */
79
+ const PAGE_KEY_MAX_LENGTH = 512;
80
+ /** A hostname's own limit. */
81
+ const HOST_MAX_LENGTH = 253;
82
+
83
+ /**
84
+ * Where a `Referer` may come from: the web, or an Android app that says which
85
+ * app opened the link (`android-app://com.example.app/`). Anything else is a
86
+ * direct visit.
87
+ */
88
+ const REFERER_SCHEMES = new Set(["http:", "https:", "android-app:"]);
89
+
90
+ const DAY_KEY = /^\d{4}-\d{2}-\d{2}$/;
91
+ const HOUR_KEY = /^\d{4}-\d{2}-\d{2}T\d{2}$/;
92
+
93
+ /**
94
+ * Machines that run a browser engine and say so, and HTTP libraries that send
95
+ * a `Sec-Fetch-Dest: document` of their own. Everything else is already kept
96
+ * out by the navigation check, so this list stays short and obvious rather
97
+ * than trying to be complete.
98
+ */
99
+ const BOT_USER_AGENT = new RegExp(
100
+ [
101
+ "bot",
102
+ "crawl",
103
+ "spider",
104
+ "slurp",
105
+ "scrape",
106
+ "fetch",
107
+ "preview",
108
+ "headless",
109
+ "phantom",
110
+ "selenium",
111
+ "puppeteer",
112
+ "playwright",
113
+ "lighthouse",
114
+ "pagespeed",
115
+ "python",
116
+ "curl/",
117
+ "wget/",
118
+ "java/",
119
+ "go-http-client",
120
+ "okhttp",
121
+ "libwww",
122
+ "httpclient",
123
+ "axios",
124
+ "feed",
125
+ "rss",
126
+ "validator",
127
+ "monitor",
128
+ "uptime",
129
+ "facebookexternalhit",
130
+ "embedly",
131
+ "whatsapp",
132
+ ].join("|"),
133
+ "i",
134
+ );
135
+
136
+ /**
137
+ * Whether a User-Agent names a machine rather than a reader's browser.
138
+ *
139
+ * A missing User-Agent counts as a machine: every browser sends one.
140
+ *
141
+ * @param userAgent - The request's `User-Agent`, if any
142
+ * @returns `true` when the request should not count as a view
143
+ * @example
144
+ * ```ts
145
+ * isBotUserAgent("Mozilla/5.0 (compatible; Googlebot/2.1)"); // true
146
+ * isBotUserAgent("Mozilla/5.0 (Macintosh) Safari/605.1.15"); // false
147
+ * ```
148
+ */
149
+ export function isBotUserAgent(userAgent: string | null | undefined): boolean {
150
+ if (!userAgent) return true;
151
+ return BOT_USER_AGENT.test(userAgent);
152
+ }
153
+
154
+ /** The facts of one request and its response that decide a view. */
155
+ export interface ViewCandidate {
156
+ method: string;
157
+ status: number;
158
+ /** The response's `Content-Type`. */
159
+ contentType: string | null;
160
+ isAuthenticated: boolean;
161
+ /** The request headers. */
162
+ headers: Headers;
163
+ }
164
+
165
+ /**
166
+ * Whether a request and its response are one reader opening one page.
167
+ *
168
+ * A view is a `GET` that answered `200` with HTML to someone who is not signed
169
+ * in, from a browser's top-level navigation (`Sec-Fetch-Dest: document`,
170
+ * `Sec-Fetch-Mode: navigate`) that is not a prefetch or prerender, with a
171
+ * User-Agent that is not a known machine. The `Sec-Fetch-*` requirement is
172
+ * what keeps out the long tail of crawlers and HTTP clients; it also keeps out
173
+ * browsers from before 2023 that never sent the headers, which by now is a
174
+ * share small enough to accept.
175
+ *
176
+ * @param candidate - The request and response facts
177
+ * @returns `true` when this response counts as a view
178
+ * @example
179
+ * ```ts
180
+ * shouldCountView({
181
+ * method: "GET",
182
+ * status: 200,
183
+ * contentType: "text/html; charset=UTF-8",
184
+ * isAuthenticated: false,
185
+ * headers: request.headers,
186
+ * });
187
+ * ```
188
+ */
189
+ export function shouldCountView(candidate: ViewCandidate): boolean {
190
+ if (candidate.method !== "GET") return false;
191
+ if (candidate.status !== 200) return false;
192
+ if (!candidate.contentType?.toLowerCase().startsWith("text/html")) {
193
+ return false;
194
+ }
195
+ if (candidate.isAuthenticated) return false;
196
+
197
+ const { headers } = candidate;
198
+ if (headers.get("sec-fetch-dest") !== "document") return false;
199
+ if (headers.get("sec-fetch-mode") !== "navigate") return false;
200
+
201
+ // Speculative loads: Chrome's speculation rules (`Sec-Purpose`), the older
202
+ // `Purpose` and `X-Purpose` hints, Firefox's `X-Moz`. A page fetched ahead
203
+ // of a click is not a page read.
204
+ const purpose = [
205
+ headers.get("sec-purpose"),
206
+ headers.get("purpose"),
207
+ headers.get("x-purpose"),
208
+ headers.get("x-moz"),
209
+ ]
210
+ .filter(Boolean)
211
+ .join(" ")
212
+ .toLowerCase();
213
+ if (
214
+ purpose.includes("prefetch") ||
215
+ purpose.includes("prerender") ||
216
+ purpose.includes("preview")
217
+ ) {
218
+ return false;
219
+ }
220
+
221
+ return !isBotUserAgent(headers.get("user-agent"));
222
+ }
223
+
224
+ function normalizeHost(host: string): string {
225
+ return host
226
+ .toLowerCase()
227
+ .replace(/\.$/, "")
228
+ .replace(/^www\./, "");
229
+ }
230
+
231
+ /**
232
+ * The host a view came from, reduced to what the stats keep.
233
+ *
234
+ * Lowercased, with a leading `www.` and a trailing dot removed, then folded
235
+ * to the address its source is listed under (`old.reddit.com` and `redd.it`
236
+ * are both `reddit.com`), so one site is one row. A link opened from an
237
+ * Android app names the app rather than a site; a known app folds to its
238
+ * site, an unknown one is kept by its package id. A link from the site
239
+ * itself is {@link VIEW_INTERNAL_REFERRER}. Empty for a direct visit and for
240
+ * any other scheme — browsers send only the origin across sites by default,
241
+ * and that is all that is wanted anyway.
242
+ *
243
+ * @param referer - The request's `Referer` header, if any
244
+ * @param ownHost - The host the site is being served on
245
+ * @returns The referring host, `/` for the site itself, or `""`
246
+ * @example
247
+ * ```ts
248
+ * referrerHost("https://www.Example.com/post?x=1", "blog.example"); // "example.com"
249
+ * referrerHost("https://old.reddit.com/r/blogs", "blog.example"); // "reddit.com"
250
+ * referrerHost("android-app://com.example.app/", "blog.example"); // "com.example.app"
251
+ * referrerHost("https://blog.example/", "blog.example"); // "/"
252
+ * referrerHost(null, "blog.example"); // ""
253
+ * ```
254
+ */
255
+ export function referrerHost(
256
+ referer: string | null | undefined,
257
+ ownHost: string,
258
+ ): string {
259
+ if (!referer) return "";
260
+ let url: URL;
261
+ try {
262
+ url = new URL(referer);
263
+ } catch {
264
+ return "";
265
+ }
266
+ if (!REFERER_SCHEMES.has(url.protocol)) return "";
267
+ const host = normalizeHost(url.hostname);
268
+ if (!host) return "";
269
+ if (host === normalizeHost(ownHost)) return VIEW_INTERNAL_REFERRER;
270
+ return canonicalSource(host).slice(0, HOST_MAX_LENGTH);
271
+ }
272
+
273
+ /** Query parameters whose value says where a link was shared, in the order tried. */
274
+ const SOURCE_QUERY_PARAMS = ["utm_source", "ref"] as const;
275
+
276
+ /**
277
+ * What a source parameter may look like once normalized: a hostname
278
+ * (`chatgpt.com`) or a plain word someone tagged a link with (`newsletter`,
279
+ * `hacker_news`). Anything else — spaces, slashes, markup, a long string —
280
+ * is not a name worth a row and is ignored.
281
+ */
282
+ const SOURCE_TOKEN = /^[a-z0-9][a-z0-9._-]{0,62}$/;
283
+
284
+ /**
285
+ * The referrer a view is filed under.
286
+ *
287
+ * A `utm_source` or `ref` parameter on the link wins when it names something:
288
+ * whoever tagged the link said where it would be shared, which beats the host
289
+ * the browser happened to report and is often the only signal — an app
290
+ * opening a link sends no `Referer`, and ChatGPT tags the links in its
291
+ * answers with `utm_source=chatgpt.com`. Without a usable tag the `Referer`
292
+ * host decides, as in {@link referrerHost}. Both are normalized and folded
293
+ * the same way, so a `utm_source=chatgpt.com` and a `Referer` from
294
+ * chatgpt.com are one row, and so are `utm_source=twitter` and a `Referer`
295
+ * from t.co. A view with no `Referer` at all is still the site's own when
296
+ * the browser says so in `Sec-Fetch-Site`, which no referrer policy
297
+ * suppresses.
298
+ *
299
+ * @param input - The request's `Referer` header, its URL (for the query
300
+ * string), the host the site is being served on, and the request's
301
+ * `Sec-Fetch-Site` header
302
+ * @returns The referrer key: a host or tag, `/` for the site itself, or
303
+ * `""` for a direct visit
304
+ * @example
305
+ * ```ts
306
+ * viewReferrer({
307
+ * referer: null,
308
+ * requestUrl: "https://blog.example/post?utm_source=chatgpt.com",
309
+ * ownHost: "blog.example",
310
+ * }); // "chatgpt.com"
311
+ * viewReferrer({
312
+ * referer: "https://t.co/abc",
313
+ * requestUrl: "https://blog.example/post?ref=newsletter",
314
+ * ownHost: "blog.example",
315
+ * }); // "newsletter"
316
+ * viewReferrer({
317
+ * referer: "https://news.ycombinator.com/",
318
+ * requestUrl: "https://blog.example/post",
319
+ * ownHost: "blog.example",
320
+ * }); // "news.ycombinator.com"
321
+ * ```
322
+ */
323
+ export function viewReferrer(input: {
324
+ referer: string | null | undefined;
325
+ requestUrl: string;
326
+ ownHost: string;
327
+ fetchSite?: string | null;
328
+ }): string {
329
+ const tagged = taggedSource(input.requestUrl, input.ownHost);
330
+ if (tagged !== null) return tagged;
331
+ const host = referrerHost(input.referer, input.ownHost);
332
+ if (host !== "") return host;
333
+ return input.fetchSite === "same-origin" || input.fetchSite === "same-site"
334
+ ? VIEW_INTERNAL_REFERRER
335
+ : "";
336
+ }
337
+
338
+ /**
339
+ * The source a link's own parameters name, or `null` when they name none.
340
+ * `""` is a tag naming the site itself, which is a direct visit.
341
+ */
342
+ function taggedSource(requestUrl: string, ownHost: string): string | null {
343
+ let params: URLSearchParams;
344
+ try {
345
+ params = new URL(requestUrl).searchParams;
346
+ } catch {
347
+ return null;
348
+ }
349
+ for (const name of SOURCE_QUERY_PARAMS) {
350
+ const value = params.get(name)?.trim();
351
+ if (!value) continue;
352
+ const token = normalizeHost(value);
353
+ if (!SOURCE_TOKEN.test(token)) continue;
354
+ if (token === normalizeHost(ownHost)) return "";
355
+ return canonicalSource(token);
356
+ }
357
+ return null;
358
+ }
359
+
360
+ /**
361
+ * The key a non-post page is counted under: its path, with the language
362
+ * view's prefix and any trailing slash removed, so `/en/archive/` and
363
+ * `/archive` are one page.
364
+ *
365
+ * @param path - The request's internal path, site prefix already removed
366
+ * @param viewBase - The language view's prefix (`/en`), or `""` on the root view
367
+ * @returns The page key
368
+ * @example
369
+ * ```ts
370
+ * viewPathKey("/en/archive", "/en"); // "/archive"
371
+ * viewPathKey("/en", "/en"); // "/"
372
+ * viewPathKey("/", ""); // "/"
373
+ * ```
374
+ */
375
+ export function viewPathKey(path: string, viewBase: string): string {
376
+ let key = path;
377
+ if (viewBase && (key === viewBase || key.startsWith(`${viewBase}/`))) {
378
+ key = key.slice(viewBase.length) || "/";
379
+ }
380
+ key = key.replace(/\/+$/, "") || "/";
381
+ return key.slice(0, PAGE_KEY_MAX_LENGTH);
382
+ }
383
+
384
+ const dayFormatters = new Map<string, Intl.DateTimeFormat>();
385
+
386
+ function dayFormatter(timeZone: string): Intl.DateTimeFormat {
387
+ let formatter = dayFormatters.get(timeZone);
388
+ if (!formatter) {
389
+ // `en-CA` writes dates as `YYYY-MM-DD`.
390
+ formatter = new Intl.DateTimeFormat("en-CA", {
391
+ timeZone,
392
+ year: "numeric",
393
+ month: "2-digit",
394
+ day: "2-digit",
395
+ });
396
+ dayFormatters.set(timeZone, formatter);
397
+ }
398
+ return formatter;
399
+ }
400
+
401
+ /**
402
+ * The calendar day a moment falls on in a time zone, as `YYYY-MM-DD`.
403
+ *
404
+ * An unknown time zone falls back to UTC rather than failing: a view is not
405
+ * worth an error, and the site's zone is validated where it is set.
406
+ *
407
+ * @param timestamp - Unix timestamp in seconds
408
+ * @param timeZone - IANA time zone, such as `Asia/Shanghai`
409
+ * @returns The day key
410
+ * @example
411
+ * ```ts
412
+ * formatDayKey(1_762_560_000, "Asia/Shanghai"); // "2025-11-08"
413
+ * formatDayKey(1_762_560_000, "UTC"); // "2025-11-08"
414
+ * ```
415
+ */
416
+ export function formatDayKey(timestamp: number, timeZone: string): string {
417
+ const date = new Date(timestamp * 1000);
418
+ try {
419
+ return dayFormatter(timeZone).format(date);
420
+ } catch {
421
+ return date.toISOString().slice(0, 10);
422
+ }
423
+ }
424
+
425
+ /**
426
+ * The hour a moment falls in, in a time zone, as `YYYY-MM-DDTHH`: the day key
427
+ * and the hour of the day, so a day's hours sort and compare as strings.
428
+ *
429
+ * @param timestamp - Unix timestamp in seconds
430
+ * @param timeZone - IANA time zone
431
+ * @returns The hour key
432
+ * @example
433
+ * ```ts
434
+ * formatHourKey(1_762_560_000, "Asia/Shanghai"); // "2025-11-08T08"
435
+ * ```
436
+ */
437
+ export function formatHourKey(timestamp: number, timeZone: string): string {
438
+ const date = new Date(timestamp * 1000);
439
+ let hour: string;
440
+ try {
441
+ hour =
442
+ new Intl.DateTimeFormat("en-US", {
443
+ timeZone,
444
+ hour: "2-digit",
445
+ hourCycle: "h23",
446
+ })
447
+ .formatToParts(date)
448
+ .find((part) => part.type === "hour")?.value ?? "00";
449
+ } catch {
450
+ hour = String(date.getUTCHours()).padStart(2, "0");
451
+ }
452
+ return `${formatDayKey(timestamp, timeZone)}T${hour}`;
453
+ }
454
+
455
+ /**
456
+ * Whether a string is a `YYYY-MM-DDTHH` hour key.
457
+ *
458
+ * @param value - The string to check
459
+ * @returns `true` for an hour key
460
+ * @example
461
+ * ```ts
462
+ * isHourKey("2026-11-09T14"); // true
463
+ * ```
464
+ */
465
+ export function isHourKey(value: string): boolean {
466
+ return HOUR_KEY.test(value);
467
+ }
468
+
469
+ /**
470
+ * The 24 hour keys of a day, in order.
471
+ *
472
+ * @param day - The day key
473
+ * @returns `day`'s hours, `T00` through `T23`
474
+ * @example
475
+ * ```ts
476
+ * hourKeysOfDay("2026-11-09")[14]; // "2026-11-09T14"
477
+ * ```
478
+ */
479
+ export function hourKeysOfDay(day: string): string[] {
480
+ return Array.from(
481
+ { length: 24 },
482
+ (_, hour) => `${day}T${String(hour).padStart(2, "0")}`,
483
+ );
484
+ }
485
+
486
+ /**
487
+ * Whether a string is a `YYYY-MM-DD` day key.
488
+ *
489
+ * @param value - The string to check
490
+ * @returns `true` for a day key
491
+ * @example
492
+ * ```ts
493
+ * isDayKey("2026-11-08"); // true
494
+ * isDayKey("2026-11-8"); // false
495
+ * ```
496
+ */
497
+ export function isDayKey(value: string): boolean {
498
+ return DAY_KEY.test(value);
499
+ }
500
+
501
+ /**
502
+ * A day key some days before or after another.
503
+ *
504
+ * Calendar arithmetic in UTC, so a local time zone's daylight-saving jumps
505
+ * never land a day on the wrong key.
506
+ *
507
+ * @param day - The starting day key
508
+ * @param days - Days to move; negative moves back
509
+ * @returns The resulting day key
510
+ * @example
511
+ * ```ts
512
+ * shiftDayKey("2026-03-01", -1); // "2026-02-28"
513
+ * shiftDayKey("2026-12-31", 1); // "2027-01-01"
514
+ * ```
515
+ */
516
+ export function shiftDayKey(day: string, days: number): string {
517
+ const [year, month, date] = day.split("-").map(Number);
518
+ return new Date(Date.UTC(year ?? 1970, (month ?? 1) - 1, (date ?? 1) + days))
519
+ .toISOString()
520
+ .slice(0, 10);
521
+ }
522
+
523
+ /**
524
+ * The run of day keys that ends on a day, oldest first.
525
+ *
526
+ * @param day - The last day of the run
527
+ * @param count - How many days, the last one included
528
+ * @returns `count` day keys ending at `day`
529
+ * @example
530
+ * ```ts
531
+ * dayKeysEndingAt("2026-11-08", 3); // ["2026-11-06", "2026-11-07", "2026-11-08"]
532
+ * ```
533
+ */
534
+ export function dayKeysEndingAt(day: string, count: number): string[] {
535
+ const keys: string[] = [];
536
+ for (let offset = count - 1; offset >= 0; offset--) {
537
+ keys.push(shiftDayKey(day, -offset));
538
+ }
539
+ return keys;
540
+ }