@jant/core 0.8.0 → 0.9.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.
- package/dist/{app-CFsmRVJN.js → app-BzH8jmh3.js} +1619 -500
- package/dist/client/.vite/manifest.json +2 -2
- package/dist/client/_assets/{client-DTLBOHqD.js → client-S8oryJ0m.js} +1 -1
- package/dist/client/_assets/{client-auth-D6Ix6SmE.js → client-auth-Ds9G0IgR.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/node.js +2 -2
- package/package.json +1 -1
- package/src/__tests__/fixtures/releases/0.8.0/site-export/README.md +130 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/2thjq/_index.md +25 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/2u5e5/_index.md +35 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/41q27/0x4nv/index.md +18 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/41q27/_index.md +44 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/41q27/faqyt/index.md +30 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/41q27/the-potting-mix-guide-i-keep-rereading/index.md +20 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/5kayp/_index.md +23 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/5ynfs/_index.md +31 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/5ynfs/hu597/index.md +21 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/_index.md +5 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/a-night-heron-field-guide-for-my-walk-folder/_index.md +31 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/a-quiet-saturday-after-a-busy-week/_index.md +36 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/archive/_index.md +8 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/are-na-is-the-only-bookmark-pile-i-still-revisit/_index.md +30 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/bought-too-many-lemons-again/_index.md +37 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/city-walks/_index.md +12 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/cleanshot-for-screenshots-ocr-and-screen-recording-on-the-mac/_index.md +33 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/cleanshotmac-shang-de-jie-tu-ocr-lu-ping-gong-ju/_index.md +32 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/co344/_index.md +25 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/collections/_index.md +5 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/current-tea-rotation/_index.md +34 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/derek-sivers-still-writes-the-kind-of-internet-i-want-more-of/_index.md +30 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/desk-but-better/_index.md +25 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/e0kcg/_index.md +22 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/egi3c/_index.md +24 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/evf9j/_index.md +152 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/featured/_index.md +8 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/from-basho/_index.md +25 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/from-epictetus/_index.md +25 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/from-marcus-aurelius/_index.md +25 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/from-seneca/_index.md +26 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/from-thoreau/_index.md +25 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/gkbvv/2cl6d/index.md +18 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/gkbvv/3zqv7/index.md +30 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/gkbvv/5oxsv/index.md +18 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/gkbvv/_index.md +39 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/gwob9/_index.md +25 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/home-cooking/_index.md +12 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/hz729/_index.md +24 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/inaturalist-ai-zi-ran-she-qu/_index.md +44 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/j4v0q/_index.md +35 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/k278t/_index.md +25 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/k4eee/_index.md +22 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/k5vh8/_index.md +32 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/k5vh8/a-reading-log-idea-i-might-steal/index.md +20 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/k5vh8/a83qu/index.md +18 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/k5vh8/from-seneca-5hibo/index.md +21 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/kan-qi-lai-bi-jiao-ku-de-gong-si-men/_index.md +41 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/l2m7y/_index.md +29 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/lan-ya-yao-kong-qi-chuang-shang-yue-du-de-fan-ye-shen-qi/_index.md +57 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/mynoise-for-rainy-afternoons/_index.md +30 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/n09le/_index.md +23 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/ni-fu-jin-de-wei-ji-bai-ke-tiao-mu/_index.md +42 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/nts-archives-are-good-cleaning-music/_index.md +30 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/qgfcu/_index.md +32 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/qgfcu/c91j0/index.md +18 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/qgfcu/qyucy/index.md +18 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/qgfcu/wsgck/index.md +18 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/rain-makes-my-neighborhood-look-better/_index.md +46 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/reading-notes/_index.md +12 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/s4r3e/_index.md +25 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/serious-eats-on-tomato-and-egg-soup/_index.md +30 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/te812/_index.md +44 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/te812/cxiu6/index.md +18 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/te812/t77ms/index.md +18 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/te812/the-soup-trick-i-always-forget/index.md +20 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/telk3/_index.md +30 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/telk3/from-thoreau-pawt2/index.md +21 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/the-five-minute-reset-is-still-the-best-habit-i-have/_index.md +36 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/the-hallway-light-took-12-minutes-and-3-months/_index.md +32 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/the-recurse-center-manual-is-weirdly-calming/_index.md +30 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/tiny-projects/_index.md +12 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/tong-wang-xing-fu-zhi-lu/_index.md +68 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/tou-ma-yan-jiang-ju-le-bu-chu-ti-yan/_index.md +62 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/useful-links/_index.md +12 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/weekend-notes/_index.md +12 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/content/what-i-actually-use-my-notebook-for/_index.md +52 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/data/jant.toml +124 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/hugo.toml +45 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/_redirects +25 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/15d51730a4f7-med_01kn8jtq3penf98tfq4gzmh9g9.png +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01kn8jtx8qenf98tm9ahxr48sw.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01kn8jv0jdenf98tp6qr9zgjjc.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01kn8jv452enf98trbkwrvhvgd.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01kn8jvb16enf98txp7p0pf5ge.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01kn8jve5nenf98tzap11gpxzr.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01kn8jvq58enf98v538w5vsqp4.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01kn8jvsaeenf98v6ct4gjzppc.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01kn8jw26cenf98vc7k0ppz5k8.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m313q1hme4e8cmby77dn66yy.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m313q2w7e4e8cmc20036yh66.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m313q7d2e4e8cmdeqjmyafby.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m313q887e4e8cmdjssych7yh.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167jx2f6ct88pkz45j3ycp-poster.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167jx2f6ct88pkz45j3ycp.mp4 +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167mbdf6ct88pr4ga1b9kf-poster.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167mbdf6ct88pr4ga1b9kf.mp4 +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167nsvf6ct88q1anhz4svb-poster.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167nsvf6ct88q1anhz4svb.mp4 +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167qaxf6ct88qfndwzxx83-poster.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167qaxf6ct88qfndwzxx83.mp4 +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167sm0f6ct88qw5brtsgcw.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167tf8f6ct88r169s51j49.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167vaaf6ct88rbx5ztenwb.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167w51f6ct88rp19pybkw1.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167x0nf6ct88rzajb84tw3.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167xxbf6ct88s5t2300bjk.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167yq5f6ct88s9pjwt5fxg.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167zg4f6ct88sge8jp28ja.webp +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/themes/jant/static/apple-touch-icon.png +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/themes/jant/static/custom.css +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/themes/jant/static/favicon.ico +0 -0
- package/src/__tests__/fixtures/releases/0.8.0/site-export/wrangler.jsonc +24 -0
- package/src/__tests__/fixtures/releases/0.8.0/snapshot/db.sql +322 -0
- package/src/__tests__/fixtures/releases/0.8.0/snapshot/meta.json +11 -0
- package/src/__tests__/helpers/cursor-walk.ts +82 -0
- package/src/__tests__/release-fixtures.test.ts +6 -2
- package/src/app.tsx +4 -0
- package/src/lib/__tests__/post-list-cursor.test.ts +105 -0
- package/src/lib/__tests__/thread-fold.test.ts +43 -0
- package/src/lib/__tests__/timeline.test.ts +14 -14
- package/src/lib/api-posts.ts +110 -2
- package/src/lib/api-public-posts.ts +263 -0
- package/src/lib/api-threads.ts +207 -0
- package/src/lib/post-list-cursor.ts +211 -0
- package/src/lib/thread-fold.ts +83 -41
- package/src/lib/thread-query.ts +143 -0
- package/src/middleware/cors.ts +8 -1
- package/src/middleware/deprecation.ts +48 -0
- package/src/routes/api/__tests__/mcp.test.ts +147 -0
- package/src/routes/api/__tests__/posts.test.ts +157 -0
- package/src/routes/api/__tests__/public-access.test.ts +5 -0
- package/src/routes/api/__tests__/threads.test.ts +115 -0
- package/src/routes/api/posts.ts +19 -112
- package/src/routes/api/public/__tests__/archive.test.ts +261 -0
- package/src/routes/api/public/__tests__/posts.test.ts +344 -19
- package/src/routes/api/public/__tests__/threads.test.ts +363 -0
- package/src/routes/api/public/archive.ts +82 -79
- package/src/routes/api/public/posts.ts +97 -299
- package/src/routes/api/public/threads.ts +141 -0
- package/src/routes/api/threads.ts +128 -0
- package/src/services/__tests__/post.test.ts +342 -36
- package/src/services/__tests__/thread.test.ts +495 -0
- package/src/services/index.ts +4 -0
- package/src/services/mcp.ts +213 -63
- package/src/services/post.ts +734 -361
- package/src/services/thread.ts +392 -0
- package/src/types/constants.ts +25 -0
- package/src/ui/feed/ThreadPreview.tsx +9 -14
- package/src/ui/feed/__tests__/thread-preview.test.ts +18 -22
- package/src/ui/feed/thread-preview-state.ts +0 -35
- package/src/ui/shared/Pagination.tsx +1 -1
|
@@ -5344,9 +5344,9 @@ function normalizeThemeColorForMeta(color) {
|
|
|
5344
5344
|
*
|
|
5345
5345
|
* The dev flag itself lives in `build-env.ts`, which client bundles can import
|
|
5346
5346
|
* without these Worker-only globals.
|
|
5347
|
-
*/ var CORE_VERSION = "0.
|
|
5348
|
-
var CLIENT_JS_FILE = "/_assets/client-
|
|
5349
|
-
var CLIENT_AUTH_JS_FILE = "/_assets/client-auth-
|
|
5347
|
+
*/ var CORE_VERSION = "0.9.0-f5f1d977f9cb3f8e";
|
|
5348
|
+
var CLIENT_JS_FILE = "/_assets/client-S8oryJ0m.js";
|
|
5349
|
+
var CLIENT_AUTH_JS_FILE = "/_assets/client-auth-Ds9G0IgR.js";
|
|
5350
5350
|
var CLIENT_COMPOSE_PRELOAD = [
|
|
5351
5351
|
"/_assets/client-compose-D6rExKVK.js",
|
|
5352
5352
|
"/_assets/chunks/create-editor-B-m7X7S5.js",
|
|
@@ -5943,7 +5943,7 @@ var IconSprite = () => {
|
|
|
5943
5943
|
const authorStylesheetPath = resolvedClientBundle === "full" ? IS_VITE_DEV ? assetPath("/src/style-author.css") : toPublicAssetPath(CLIENT_AUTHOR_CSS_FILE, assetBasePath) : null;
|
|
5944
5944
|
const clientScriptPath = IS_VITE_DEV ? resolvedClientBundle === "full" ? assetPath("/src/client-auth.ts") : assetPath("/src/client.ts") : toPublicAssetPath(resolvedClientBundle === "full" ? CLIENT_AUTH_JS_FILE : CLIENT_JS_FILE, assetBasePath);
|
|
5945
5945
|
const composePreloadPaths = !IS_VITE_DEV && resolvedClientBundle === "full" ? CLIENT_COMPOSE_PRELOAD.map((file) => toPublicAssetPath(file, assetBasePath)) : [];
|
|
5946
|
-
const faviconAssetVersion = resolvedFaviconVersion || "0.
|
|
5946
|
+
const faviconAssetVersion = resolvedFaviconVersion || "0.9.0-f5f1d977f9cb3f8e";
|
|
5947
5947
|
const resolvedFaviconHref = faviconHref ?? (faviconAssetVersion ? toPublicPath(`/favicon.ico?v=${faviconAssetVersion}`, sitePathPrefix) : toPublicPath("/favicon.ico", sitePathPrefix));
|
|
5948
5948
|
const resolvedAppleTouchHref = appleTouchHref ?? (faviconAssetVersion ? toPublicPath(`/apple-touch-icon.png?v=${faviconAssetVersion}`, sitePathPrefix) : toPublicPath("/apple-touch-icon.png", sitePathPrefix));
|
|
5949
5949
|
const socialImageHref = resolvedSocialImagePath ? toAbsoluteAssetUrl(resolvedSocialImagePath, appConfig?.siteUrl || "", sitePathPrefix) : "";
|
|
@@ -6431,6 +6431,28 @@ var LATEST_FILTERABLE_YEAR = 9999;
|
|
|
6431
6431
|
* said the same thing in different words; folding it into `newest` left one
|
|
6432
6432
|
* menu the reader can learn once.
|
|
6433
6433
|
*/ var SMART_COLLECTION_SORT_ORDERS = COLLECTION_SORT_ORDERS;
|
|
6434
|
+
/**
|
|
6435
|
+
* How the Threads API orders a list of Threads — each value one the site
|
|
6436
|
+
* already shows somewhere, named for the axis it reads:
|
|
6437
|
+
*
|
|
6438
|
+
* - `activity`: the homepage, and a collection's `newest`. A Thread moves up
|
|
6439
|
+
* when it gains an announced post.
|
|
6440
|
+
* - `published`: the archive's default. Newest root publication first; a reply
|
|
6441
|
+
* never moves a Thread, so this is the order to walk a whole site in.
|
|
6442
|
+
* - `updated`: the archive's `?sort=updated`. Like `activity`, but a quiet
|
|
6443
|
+
* reply counts too.
|
|
6444
|
+
* - `oldest`: a collection's `oldest`. Oldest root publication first.
|
|
6445
|
+
* - `rating`: a collection's `rating_desc`. Highest rating first, then activity.
|
|
6446
|
+
*
|
|
6447
|
+
* Not `SORT_ORDERS`: `newest` means activity on a collection and would read as
|
|
6448
|
+
* publication here.
|
|
6449
|
+
*/ var THREAD_SORTS = [
|
|
6450
|
+
"activity",
|
|
6451
|
+
"published",
|
|
6452
|
+
"updated",
|
|
6453
|
+
"oldest",
|
|
6454
|
+
"rating"
|
|
6455
|
+
];
|
|
6434
6456
|
var NAV_ITEM_TYPES = [
|
|
6435
6457
|
"link",
|
|
6436
6458
|
"system",
|
|
@@ -18641,6 +18663,52 @@ var TimelineItemFromPost = ({ post, mode, display }) => {
|
|
|
18641
18663
|
return Math.max(0, totalReplyCount - shown.size);
|
|
18642
18664
|
}
|
|
18643
18665
|
/**
|
|
18666
|
+
* Fold a thread from its ranked windows: the replies each end of the fold
|
|
18667
|
+
* keeps, before any overlap between them is removed.
|
|
18668
|
+
*
|
|
18669
|
+
* Both access paths arrive here. The feed slices the windows out of the whole
|
|
18670
|
+
* chain; the site and the API rank them in SQL (`getThreadTimelineContext`),
|
|
18671
|
+
* which hands them over overlapping on purpose. A short thread's windows
|
|
18672
|
+
* overlap, and the hero is inside both of them on the shortest ones: with a
|
|
18673
|
+
* single reply, that reply is the newest *and* the whole leading window. Each
|
|
18674
|
+
* list therefore drops whatever an earlier one already shows, hero first.
|
|
18675
|
+
*
|
|
18676
|
+
* @param buckets.leadingReplies - The first `THREAD_LEADING_REPLIES` replies
|
|
18677
|
+
* @param buckets.trailingReplies - The replies just before the newest, oldest
|
|
18678
|
+
* first
|
|
18679
|
+
* @param buckets.latestReply - The newest reply
|
|
18680
|
+
* @param buckets.nextReply - The reply right after the leading window, the
|
|
18681
|
+
* only candidate for the gap; `null` when the thread has no such reply
|
|
18682
|
+
* @param buckets.totalReplyCount - Every published reply in the thread
|
|
18683
|
+
* @returns The fold
|
|
18684
|
+
* @example
|
|
18685
|
+
* foldReplyWindows({ leadingReplies: [r1, r2], trailingReplies: [r6, r7],
|
|
18686
|
+
* latestReply: r8, nextReply: r3, totalReplyCount: 8 });
|
|
18687
|
+
* // leading [r1, r2], trailing [r6, r7], latest r8, firstHidden r3, hidden 3
|
|
18688
|
+
*/ function foldReplyWindows({ leadingReplies: leadingWindow, trailingReplies: trailingWindow, latestReply, nextReply, totalReplyCount }) {
|
|
18689
|
+
const shown = /* @__PURE__ */ new Set([latestReply.id]);
|
|
18690
|
+
const keepUnshown = (replies) => replies.filter((reply) => {
|
|
18691
|
+
if (shown.has(reply.id)) return false;
|
|
18692
|
+
shown.add(reply.id);
|
|
18693
|
+
return true;
|
|
18694
|
+
});
|
|
18695
|
+
const leadingReplies = keepUnshown(leadingWindow);
|
|
18696
|
+
const trailingReplies = keepUnshown(trailingWindow);
|
|
18697
|
+
const hiddenCount = getThreadHiddenCount({
|
|
18698
|
+
leadingReplies,
|
|
18699
|
+
trailingReplies,
|
|
18700
|
+
latestReply,
|
|
18701
|
+
totalReplyCount
|
|
18702
|
+
});
|
|
18703
|
+
return {
|
|
18704
|
+
leadingReplies,
|
|
18705
|
+
trailingReplies,
|
|
18706
|
+
latestReply,
|
|
18707
|
+
firstHiddenReply: hiddenCount > 0 && nextReply && !shown.has(nextReply.id) ? nextReply : null,
|
|
18708
|
+
hiddenCount
|
|
18709
|
+
};
|
|
18710
|
+
}
|
|
18711
|
+
/**
|
|
18644
18712
|
* Fold a thread whose replies are already in hand.
|
|
18645
18713
|
*
|
|
18646
18714
|
* Takes the same slices the SQL path ranks for: the first
|
|
@@ -18657,50 +18725,17 @@ var TimelineItemFromPost = ({ post, mode, display }) => {
|
|
|
18657
18725
|
*/ function foldThreadReplies(replies) {
|
|
18658
18726
|
const latestReply = replies.at(-1);
|
|
18659
18727
|
if (!latestReply) return null;
|
|
18660
|
-
|
|
18661
|
-
|
|
18662
|
-
|
|
18663
|
-
const shown = /* @__PURE__ */ new Set([
|
|
18664
|
-
...leadingIds,
|
|
18665
|
-
...trailingReplies.map((reply) => reply.id),
|
|
18666
|
-
latestReply.id
|
|
18667
|
-
]);
|
|
18668
|
-
return {
|
|
18669
|
-
leadingReplies,
|
|
18670
|
-
trailingReplies,
|
|
18728
|
+
return foldReplyWindows({
|
|
18729
|
+
leadingReplies: replies.slice(0, 2),
|
|
18730
|
+
trailingReplies: replies.slice(-3, -1),
|
|
18671
18731
|
latestReply,
|
|
18672
|
-
|
|
18673
|
-
|
|
18674
|
-
|
|
18675
|
-
trailingReplies,
|
|
18676
|
-
latestReply,
|
|
18677
|
-
totalReplyCount: replies.length
|
|
18678
|
-
})
|
|
18679
|
-
};
|
|
18732
|
+
nextReply: replies[2] ?? null,
|
|
18733
|
+
totalReplyCount: replies.length
|
|
18734
|
+
});
|
|
18680
18735
|
}
|
|
18681
18736
|
//#endregion
|
|
18682
18737
|
//#region src/ui/feed/thread-preview-state.ts
|
|
18683
18738
|
/**
|
|
18684
|
-
* What the preview needs to know about its own fold.
|
|
18685
|
-
*
|
|
18686
|
-
* The count itself lives in `lib/thread-fold.ts`, where the feed reads it too —
|
|
18687
|
-
* a card and a feed entry that disagreed about how many posts are hidden would
|
|
18688
|
-
* be describing different threads.
|
|
18689
|
-
*
|
|
18690
|
-
* @param selection - The replies this preview shows, and the thread's total
|
|
18691
|
-
* @returns The hidden-post count the gap link announces
|
|
18692
|
-
* @example
|
|
18693
|
-
* getThreadPreviewState({ leadingReplies, trailingReplies, latestReply,
|
|
18694
|
-
* totalReplyCount: 8 }); // { hiddenCount: 3 }
|
|
18695
|
-
*/ function getThreadPreviewState({ leadingReplies, trailingReplies, latestReply, totalReplyCount }) {
|
|
18696
|
-
return { hiddenCount: getThreadHiddenCount({
|
|
18697
|
-
leadingReplies,
|
|
18698
|
-
trailingReplies,
|
|
18699
|
-
latestReply,
|
|
18700
|
-
totalReplyCount
|
|
18701
|
-
}) };
|
|
18702
|
-
}
|
|
18703
|
-
/**
|
|
18704
18739
|
* A lone root post shorter than this (plain-text code points) comfortably
|
|
18705
18740
|
* fits the thread-context height cap. Pairs with the
|
|
18706
18741
|
* `--site-thread-context-max-height` token (160px) in tokens.css — revisit
|
|
@@ -18744,12 +18779,14 @@ var CONTEXT_DISPLAY = {
|
|
|
18744
18779
|
var HERO_DISPLAY = {};
|
|
18745
18780
|
var ThreadPreview = ({ rootPost, leadingReplies, trailingReplies, latestReply, gapHref, totalReplyCount }) => {
|
|
18746
18781
|
const { i18n } = useLingui();
|
|
18747
|
-
const
|
|
18782
|
+
const fold = foldReplyWindows({
|
|
18748
18783
|
leadingReplies,
|
|
18749
18784
|
trailingReplies,
|
|
18750
18785
|
latestReply,
|
|
18786
|
+
nextReply: null,
|
|
18751
18787
|
totalReplyCount
|
|
18752
18788
|
});
|
|
18789
|
+
const hiddenCount = fold.hiddenCount;
|
|
18753
18790
|
const assumeOverflow = threadContextAssumesOverflow({
|
|
18754
18791
|
rootPost,
|
|
18755
18792
|
totalReplyCount
|
|
@@ -18757,14 +18794,8 @@ var ThreadPreview = ({ rootPost, leadingReplies, trailingReplies, latestReply, g
|
|
|
18757
18794
|
const hiddenPostsLabel = i18n._({ id: "oO0hKx" }, { count: hiddenCount });
|
|
18758
18795
|
const showMoreLabel = i18n._({ id: "fMPkxb" });
|
|
18759
18796
|
const showLessLabel = i18n._({ id: "6lGV3K" });
|
|
18760
|
-
const
|
|
18761
|
-
const
|
|
18762
|
-
if (visibleReplyIds.has(reply.id)) return false;
|
|
18763
|
-
visibleReplyIds.add(reply.id);
|
|
18764
|
-
return true;
|
|
18765
|
-
});
|
|
18766
|
-
const renderedLeadingReplies = dedupeReplies(leadingReplies);
|
|
18767
|
-
const renderedTrailingReplies = dedupeReplies(trailingReplies);
|
|
18797
|
+
const renderedLeadingReplies = fold.leadingReplies;
|
|
18798
|
+
const renderedTrailingReplies = fold.trailingReplies;
|
|
18768
18799
|
const gapLinkHref = gapHref ?? latestReply.permalink;
|
|
18769
18800
|
const rootItem = /*#__PURE__*/ jsxDEV$1("div", {
|
|
18770
18801
|
class: "thread-item thread-item-context",
|
|
@@ -36678,6 +36709,24 @@ customUrlsRoutes.post("/:id/delete", async (c) => {
|
|
|
36678
36709
|
});
|
|
36679
36710
|
//#endregion
|
|
36680
36711
|
//#region src/lib/api-posts.ts
|
|
36712
|
+
/**
|
|
36713
|
+
* The order `GET /api/posts` and `jant_posts_list` walk Posts in.
|
|
36714
|
+
*
|
|
36715
|
+
* Published Posts run newest-published first, pins ignored: a Post's place
|
|
36716
|
+
* then depends on its own publication alone, and a reply added to an old
|
|
36717
|
+
* Thread doesn't lift the root past a walk's cursor. Drafts keep the editing
|
|
36718
|
+
* order the composer's draft list reads, last edited first.
|
|
36719
|
+
*
|
|
36720
|
+
* @param status - The status the list is filtered to
|
|
36721
|
+
* @returns The `PostFilters` ordering fields for that list
|
|
36722
|
+
* @example
|
|
36723
|
+
* posts.listPage({ status, ...apiPostListOrder(status) }, { limit: 100 });
|
|
36724
|
+
*/ function apiPostListOrder(status) {
|
|
36725
|
+
return status === "draft" ? {} : {
|
|
36726
|
+
sortBy: "published",
|
|
36727
|
+
ignorePinnedSort: true
|
|
36728
|
+
};
|
|
36729
|
+
}
|
|
36681
36730
|
function toApiAttachment(media, r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix) {
|
|
36682
36731
|
const publicUrl = getPublicUrlForProvider(media.provider, r2PublicUrl, s3PublicUrl, localPublicUrl);
|
|
36683
36732
|
const url = getMediaUrl(media.storageKey, publicUrl, sitePathPrefix);
|
|
@@ -36715,7 +36764,7 @@ function toApiAttachment(media, r2PublicUrl, imageTransformUrl, s3PublicUrl, loc
|
|
|
36715
36764
|
chars: media.chars
|
|
36716
36765
|
};
|
|
36717
36766
|
}
|
|
36718
|
-
function toApiPost(post, extras
|
|
36767
|
+
function toApiPost(post, extras) {
|
|
36719
36768
|
const { title, url, ...rest } = post;
|
|
36720
36769
|
const displayTitle = getPostDisplayTitle(post);
|
|
36721
36770
|
if (post.format === "quote") return {
|
|
@@ -36733,6 +36782,46 @@ function toApiPost(post, extras = {}) {
|
|
|
36733
36782
|
url: url ?? null
|
|
36734
36783
|
};
|
|
36735
36784
|
}
|
|
36785
|
+
/**
|
|
36786
|
+
* API responses for Posts already loaded. Attachments, Thread Post counts,
|
|
36787
|
+
* and (when asked) Thread collections are each read in one batch for the
|
|
36788
|
+
* whole set, so a page costs the same few round trips however long it is.
|
|
36789
|
+
*
|
|
36790
|
+
* @param deps - Services and app config; a request's `c.var` or an MCP context
|
|
36791
|
+
* @param posts - Posts to respond with, in order
|
|
36792
|
+
* @param options - `collectionIds` adds each Post's shared Thread collections
|
|
36793
|
+
* @returns One response per Post, in the same order
|
|
36794
|
+
* @example
|
|
36795
|
+
* const responses = await loadApiPostResponses(c.var, page.posts);
|
|
36796
|
+
*/ async function loadApiPostResponses(deps, posts, options = {}) {
|
|
36797
|
+
if (posts.length === 0) return [];
|
|
36798
|
+
const { services, appConfig } = deps;
|
|
36799
|
+
const postIds = posts.map((post) => post.id);
|
|
36800
|
+
const [mediaMap, threadPostCounts, collectionsMap] = await Promise.all([
|
|
36801
|
+
services.media.getByPostIds(postIds),
|
|
36802
|
+
services.posts.countThreadPosts(posts.map((post) => post.threadId)),
|
|
36803
|
+
options.collectionIds ? services.collections.getCollectionsByPostIds(postIds) : Promise.resolve(null)
|
|
36804
|
+
]);
|
|
36805
|
+
return posts.map((post) => toApiPost(post, {
|
|
36806
|
+
threadPostCount: threadPostCounts.get(post.threadId) ?? 0,
|
|
36807
|
+
attachments: (mediaMap.get(post.id) ?? []).map((media) => toApiAttachment(media, appConfig.r2PublicUrl, appConfig.imageTransformUrl, appConfig.s3PublicUrl, appConfig.localPublicUrl, appConfig.sitePathPrefix)),
|
|
36808
|
+
...collectionsMap ? { collectionIds: (collectionsMap.get(post.id) ?? []).map((collection) => collection.id) } : {}
|
|
36809
|
+
}));
|
|
36810
|
+
}
|
|
36811
|
+
/**
|
|
36812
|
+
* One Post's API response. See {@link loadApiPostResponses}.
|
|
36813
|
+
*
|
|
36814
|
+
* @param deps - Services and app config
|
|
36815
|
+
* @param post - The Post
|
|
36816
|
+
* @param options - `collectionIds` adds the Post's shared Thread collections
|
|
36817
|
+
* @returns The Post's response
|
|
36818
|
+
* @example
|
|
36819
|
+
* return c.json(await loadApiPostResponse(c.var, post));
|
|
36820
|
+
*/ async function loadApiPostResponse(deps, post, options = {}) {
|
|
36821
|
+
const [response] = await loadApiPostResponses(deps, [post], options);
|
|
36822
|
+
if (!response) throw new Error(`No response built for post ${post.id}`);
|
|
36823
|
+
return response;
|
|
36824
|
+
}
|
|
36736
36825
|
//#endregion
|
|
36737
36826
|
//#region src/lib/address.ts
|
|
36738
36827
|
/**
|
|
@@ -36795,18 +36884,18 @@ var PostSlugQuerySchema = z.discriminatedUnion("mode", [z.object({
|
|
|
36795
36884
|
})]);
|
|
36796
36885
|
postsApiRoutes.get("/", requireAuthApi(), async (c) => {
|
|
36797
36886
|
const { format, status, cursor, limit } = parseValidated(ListPostsQuerySchema, c.req.query());
|
|
36798
|
-
const
|
|
36887
|
+
const listStatus = status ?? "published";
|
|
36888
|
+
const { posts, nextCursor } = await c.var.services.posts.listPage({
|
|
36799
36889
|
format,
|
|
36800
|
-
status:
|
|
36801
|
-
|
|
36890
|
+
status: listStatus,
|
|
36891
|
+
...apiPostListOrder(listStatus)
|
|
36892
|
+
}, {
|
|
36893
|
+
cursor,
|
|
36802
36894
|
limit
|
|
36803
36895
|
});
|
|
36804
|
-
const postIds = posts.map((p) => p.id);
|
|
36805
|
-
const mediaMap = await c.var.services.media.getByPostIds(postIds);
|
|
36806
|
-
const { r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix } = c.var.appConfig;
|
|
36807
36896
|
return c.json({
|
|
36808
|
-
posts:
|
|
36809
|
-
nextCursor
|
|
36897
|
+
posts: await loadApiPostResponses(c.var, posts),
|
|
36898
|
+
nextCursor
|
|
36810
36899
|
});
|
|
36811
36900
|
});
|
|
36812
36901
|
postsApiRoutes.get("/slug", requireAuthApi(), async (c) => {
|
|
@@ -36831,20 +36920,10 @@ postsApiRoutes.get("/:id/content", requireAuthApi(), async (c) => {
|
|
|
36831
36920
|
});
|
|
36832
36921
|
postsApiRoutes.get("/:id", requireAuthApi(), async (c) => {
|
|
36833
36922
|
const id = parseIdParam(c.req.param("id"), ID_PREFIX.post);
|
|
36834
|
-
const [post,
|
|
36835
|
-
c.var.services.posts.getById(id),
|
|
36836
|
-
c.var.services.media.getByPostId(id),
|
|
36837
|
-
c.var.services.collections.getCollectionsByPostId(id),
|
|
36838
|
-
c.var.services.posts.getThreadPosition(id)
|
|
36839
|
-
]);
|
|
36923
|
+
const [post, threadPosition] = await Promise.all([c.var.services.posts.getById(id), c.var.services.posts.getThreadPosition(id)]);
|
|
36840
36924
|
const foundPost = assertFound(post, "Post");
|
|
36841
|
-
const { r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix } = c.var.appConfig;
|
|
36842
|
-
const collectionIds = threadCollections.map((col) => col.id);
|
|
36843
36925
|
return c.json({
|
|
36844
|
-
...
|
|
36845
|
-
collectionIds,
|
|
36846
|
-
attachments: mediaList.map((m) => toApiAttachment(m, r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix))
|
|
36847
|
-
}),
|
|
36926
|
+
...await loadApiPostResponse(c.var, foundPost, { collectionIds: true }),
|
|
36848
36927
|
threadPosition
|
|
36849
36928
|
});
|
|
36850
36929
|
});
|
|
@@ -36884,10 +36963,8 @@ postsApiRoutes.post("/", requireAuthApi(), async (c) => {
|
|
|
36884
36963
|
maxParagraphs: c.var.appConfig.summaryMaxParagraphs,
|
|
36885
36964
|
maxChars: c.var.appConfig.summaryMaxChars
|
|
36886
36965
|
});
|
|
36887
|
-
const mediaList = await c.var.services.media.getByPostId(post.id);
|
|
36888
|
-
const { r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix } = c.var.appConfig;
|
|
36889
36966
|
await triggerGitHubSyncInline(c);
|
|
36890
|
-
return c.json(
|
|
36967
|
+
return c.json(await loadApiPostResponse(c.var, post), 201);
|
|
36891
36968
|
});
|
|
36892
36969
|
postsApiRoutes.put("/:id", requireAuthApi(), async (c) => {
|
|
36893
36970
|
const id = parseIdParam(c.req.param("id"), ID_PREFIX.post);
|
|
@@ -36923,9 +37000,7 @@ postsApiRoutes.put("/:id", requireAuthApi(), async (c) => {
|
|
|
36923
37000
|
maxChars: c.var.appConfig.summaryMaxChars
|
|
36924
37001
|
}), "Post");
|
|
36925
37002
|
await triggerGitHubSyncInline(c);
|
|
36926
|
-
|
|
36927
|
-
const { r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix } = c.var.appConfig;
|
|
36928
|
-
return c.json(toApiPost(post, { attachments: mediaList.map((m) => toApiAttachment(m, r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix)) }));
|
|
37003
|
+
return c.json(await loadApiPostResponse(c.var, post));
|
|
36929
37004
|
});
|
|
36930
37005
|
var SetLanguageSchema = z.object({ language: ContentLanguageSchema });
|
|
36931
37006
|
var TranslationCandidatesQuerySchema = z.object({
|
|
@@ -37038,6 +37113,417 @@ postsApiRoutes.delete("/:id", requireAuthApi(), async (c) => {
|
|
|
37038
37113
|
return c.json({ success: true });
|
|
37039
37114
|
});
|
|
37040
37115
|
//#endregion
|
|
37116
|
+
//#region src/lib/tiptap-to-markdown.ts
|
|
37117
|
+
/**
|
|
37118
|
+
* Tiptap JSON → Markdown Converter
|
|
37119
|
+
*
|
|
37120
|
+
* Converts Tiptap JSON documents to Markdown using the official
|
|
37121
|
+
* Tiptap MarkdownManager and Jant's shared markdown schema.
|
|
37122
|
+
*/
|
|
37123
|
+
/**
|
|
37124
|
+
* Converts a Tiptap JSON document to a Markdown string.
|
|
37125
|
+
*
|
|
37126
|
+
* Throws rather than returning an empty string: a caller writing the result
|
|
37127
|
+
* somewhere (an export, a text attachment) would otherwise replace the
|
|
37128
|
+
* content with nothing and say nothing.
|
|
37129
|
+
*
|
|
37130
|
+
* @param json - Tiptap JSON document string
|
|
37131
|
+
* @returns Markdown string
|
|
37132
|
+
* @throws {SyntaxError} When `json` is not JSON
|
|
37133
|
+
* @throws {Error} When the root node is not a `doc`
|
|
37134
|
+
*
|
|
37135
|
+
* @example
|
|
37136
|
+
* ```ts
|
|
37137
|
+
* const md = tiptapJsonToMarkdown('{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Hello"}]}]}');
|
|
37138
|
+
* // "Hello"
|
|
37139
|
+
* ```
|
|
37140
|
+
*/ function tiptapJsonToMarkdown(json) {
|
|
37141
|
+
const doc = JSON.parse(json);
|
|
37142
|
+
if (doc.type !== "doc") throw new Error(`A TipTap body's root must be a doc node, not ${JSON.stringify(doc.type)}.`);
|
|
37143
|
+
return serializeMarkdownDocument(doc).trimEnd();
|
|
37144
|
+
}
|
|
37145
|
+
//#endregion
|
|
37146
|
+
//#region src/lib/api-public-posts.ts
|
|
37147
|
+
/**
|
|
37148
|
+
* Public API Post responses
|
|
37149
|
+
*
|
|
37150
|
+
* The reading view of a Post that `/api/public/*` returns: rendered body or
|
|
37151
|
+
* Markdown, public permalink, and public collection references.
|
|
37152
|
+
*/
|
|
37153
|
+
/**
|
|
37154
|
+
* The public Markdown for a post, or null for a historical body that isn't
|
|
37155
|
+
* TipTap JSON. One unreadable row answers null and is logged, rather than
|
|
37156
|
+
* failing the whole listing; `bodyHtml` still falls back to stored HTML.
|
|
37157
|
+
*/ function toPublicBodyMarkdown(postId, body) {
|
|
37158
|
+
try {
|
|
37159
|
+
return tiptapJsonToMarkdown(body);
|
|
37160
|
+
} catch (error) {
|
|
37161
|
+
console.error(`Couldn't convert the body of post ${postId} to Markdown`, error);
|
|
37162
|
+
return null;
|
|
37163
|
+
}
|
|
37164
|
+
}
|
|
37165
|
+
/**
|
|
37166
|
+
* One Post's reading view, from its attachments, its Thread's collections, and
|
|
37167
|
+
* its Thread's Post count.
|
|
37168
|
+
*
|
|
37169
|
+
* @param post - The Post
|
|
37170
|
+
* @param related - What was read about it in the same batch as its page
|
|
37171
|
+
* @param appConfig - Media URLs and the site path prefix
|
|
37172
|
+
* @param options - `content: "markdown"` returns `bodyMarkdown` instead of the
|
|
37173
|
+
* rendered body
|
|
37174
|
+
* @returns The public response
|
|
37175
|
+
* @example
|
|
37176
|
+
* toPublicPost(post, { media: [], collections: [], threadPostCount: 1 }, config);
|
|
37177
|
+
*/ function toPublicPost(post, related, appConfig, options) {
|
|
37178
|
+
const { r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix, storageDriver } = appConfig;
|
|
37179
|
+
const previewImagePublicUrl = getPublicUrlForProvider(storageDriver, r2PublicUrl, s3PublicUrl, localPublicUrl);
|
|
37180
|
+
const previewImageUrl = post.previewImageKey ? getImageUrl(getMediaUrl(post.previewImageKey, previewImagePublicUrl, sitePathPrefix), imageTransformUrl, {
|
|
37181
|
+
width: 1280,
|
|
37182
|
+
quality: 80,
|
|
37183
|
+
format: "auto",
|
|
37184
|
+
fit: "scale-down"
|
|
37185
|
+
}) : null;
|
|
37186
|
+
const base = {
|
|
37187
|
+
id: post.id,
|
|
37188
|
+
format: post.format,
|
|
37189
|
+
status: "published",
|
|
37190
|
+
visibility: post.visibility,
|
|
37191
|
+
slug: post.slug,
|
|
37192
|
+
permalink: toPublicPath(`/${post.slug}`, sitePathPrefix),
|
|
37193
|
+
quoteText: post.quoteText,
|
|
37194
|
+
summary: post.summary,
|
|
37195
|
+
rating: post.rating,
|
|
37196
|
+
previewKind: post.previewKind,
|
|
37197
|
+
previewProvider: post.previewProvider,
|
|
37198
|
+
previewImageUrl,
|
|
37199
|
+
replyToId: post.replyToId,
|
|
37200
|
+
threadId: post.threadId,
|
|
37201
|
+
language: post.language,
|
|
37202
|
+
translationGroupId: post.translationGroupId,
|
|
37203
|
+
quietReply: post.quietReply,
|
|
37204
|
+
pinnedAt: post.pinnedAt,
|
|
37205
|
+
featuredAt: post.featuredAt,
|
|
37206
|
+
publishedAt: post.publishedAt,
|
|
37207
|
+
lastActivityAt: post.lastActivityAt,
|
|
37208
|
+
threadUpdatedAt: post.threadUpdatedAt,
|
|
37209
|
+
threadPostCount: related.threadPostCount,
|
|
37210
|
+
createdAt: post.createdAt,
|
|
37211
|
+
updatedAt: post.updatedAt,
|
|
37212
|
+
attachments: related.media.map((media) => toApiAttachment(media, r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix)),
|
|
37213
|
+
collections: related.collections.map((collection) => ({
|
|
37214
|
+
id: collection.id,
|
|
37215
|
+
slug: collection.slug,
|
|
37216
|
+
title: collection.title,
|
|
37217
|
+
url: toPublicPath(getCollectionPagePath(collection.slug), sitePathPrefix)
|
|
37218
|
+
}))
|
|
37219
|
+
};
|
|
37220
|
+
const contentFields = options?.content === "markdown" ? { bodyMarkdown: post.body ? toPublicBodyMarkdown(post.id, post.body) : null } : {
|
|
37221
|
+
bodyHtml: post.bodyHtml,
|
|
37222
|
+
bodyText: post.bodyText
|
|
37223
|
+
};
|
|
37224
|
+
if (post.format === "quote") return {
|
|
37225
|
+
...base,
|
|
37226
|
+
...contentFields,
|
|
37227
|
+
sourceName: post.title,
|
|
37228
|
+
sourceUrl: post.url
|
|
37229
|
+
};
|
|
37230
|
+
return {
|
|
37231
|
+
...base,
|
|
37232
|
+
...contentFields,
|
|
37233
|
+
title: post.title,
|
|
37234
|
+
url: post.url
|
|
37235
|
+
};
|
|
37236
|
+
}
|
|
37237
|
+
/**
|
|
37238
|
+
* Reading-view responses for Posts already loaded. Attachments, Thread
|
|
37239
|
+
* collections, and Thread Post counts are each read in one batch.
|
|
37240
|
+
*
|
|
37241
|
+
* @param deps - Services and app config; a request's `c.var`
|
|
37242
|
+
* @param posts - Posts to respond with, in order
|
|
37243
|
+
* @param options - `content: "markdown"` returns `bodyMarkdown`
|
|
37244
|
+
* @returns One response per Post, in the same order
|
|
37245
|
+
* @example
|
|
37246
|
+
* const responses = await loadPublicPostResponses(c.var, page.posts, {});
|
|
37247
|
+
*/ async function loadPublicPostResponses(deps, posts, options = {}) {
|
|
37248
|
+
if (posts.length === 0) return [];
|
|
37249
|
+
const { services, appConfig } = deps;
|
|
37250
|
+
const postIds = posts.map((post) => post.id);
|
|
37251
|
+
const [mediaMap, collectionsMap, threadPostCounts] = await Promise.all([
|
|
37252
|
+
services.media.getByPostIds(postIds),
|
|
37253
|
+
services.collections.getCollectionsByPostIds(postIds),
|
|
37254
|
+
services.posts.countThreadPosts(posts.map((post) => post.threadId))
|
|
37255
|
+
]);
|
|
37256
|
+
return posts.map((post) => toPublicPost(post, {
|
|
37257
|
+
media: mediaMap.get(post.id) ?? [],
|
|
37258
|
+
collections: collectionsMap.get(post.id) ?? [],
|
|
37259
|
+
threadPostCount: threadPostCounts.get(post.threadId) ?? 0
|
|
37260
|
+
}, appConfig, options));
|
|
37261
|
+
}
|
|
37262
|
+
//#endregion
|
|
37263
|
+
//#region src/lib/api-threads.ts
|
|
37264
|
+
/**
|
|
37265
|
+
* API Thread responses
|
|
37266
|
+
*
|
|
37267
|
+
* The Thread object the author API, the public API, and MCP return. One shape
|
|
37268
|
+
* for all three, parameterized by how each surface renders a Post and how it
|
|
37269
|
+
* names one: the author API's Post is the editing view, the public API's the
|
|
37270
|
+
* reading view.
|
|
37271
|
+
*/
|
|
37272
|
+
/**
|
|
37273
|
+
* Every Post a set of Thread responses renders, so their attachments and
|
|
37274
|
+
* counts can be read in one batch: each root, then the replies its fold shows.
|
|
37275
|
+
*
|
|
37276
|
+
* @param summaries - Threads to respond with
|
|
37277
|
+
* @returns The Posts, each once
|
|
37278
|
+
* @example
|
|
37279
|
+
* const responses = await render(collectThreadResponsePosts(summaries));
|
|
37280
|
+
*/ function collectThreadResponsePosts(summaries) {
|
|
37281
|
+
const seen = /* @__PURE__ */ new Map();
|
|
37282
|
+
for (const { root, fold } of summaries) {
|
|
37283
|
+
seen.set(root.id, root);
|
|
37284
|
+
if (!fold) continue;
|
|
37285
|
+
for (const post of [
|
|
37286
|
+
...fold.leadingReplies,
|
|
37287
|
+
...fold.trailingReplies,
|
|
37288
|
+
fold.latestReply
|
|
37289
|
+
]) seen.set(post.id, post);
|
|
37290
|
+
}
|
|
37291
|
+
return [...seen.values()];
|
|
37292
|
+
}
|
|
37293
|
+
/**
|
|
37294
|
+
* One Thread's response, from Post responses already rendered.
|
|
37295
|
+
*
|
|
37296
|
+
* @param summary - The Thread
|
|
37297
|
+
* @param respond - The rendered response for a Post in it
|
|
37298
|
+
* @param reference - How the surface names the Post a fold leaves out
|
|
37299
|
+
* @returns The Thread object
|
|
37300
|
+
* @example
|
|
37301
|
+
* toApiThreadResponse(summary, (post) => byId.get(post.id)!, toGap);
|
|
37302
|
+
*/ function toApiThreadResponse(summary, respond, reference) {
|
|
37303
|
+
const { root, fold } = summary;
|
|
37304
|
+
const response = {
|
|
37305
|
+
id: root.id,
|
|
37306
|
+
postCount: summary.postCount,
|
|
37307
|
+
lastActivityAt: root.lastActivityAt,
|
|
37308
|
+
threadUpdatedAt: root.threadUpdatedAt,
|
|
37309
|
+
root: respond(root)
|
|
37310
|
+
};
|
|
37311
|
+
if (fold === null) response.fold = {
|
|
37312
|
+
leading: [],
|
|
37313
|
+
hidden: 0,
|
|
37314
|
+
gap: null,
|
|
37315
|
+
trailing: []
|
|
37316
|
+
};
|
|
37317
|
+
else if (fold) response.fold = {
|
|
37318
|
+
leading: fold.leadingReplies.map(respond),
|
|
37319
|
+
hidden: fold.hiddenCount,
|
|
37320
|
+
gap: fold.firstHiddenReply ? reference(fold.firstHiddenReply) : null,
|
|
37321
|
+
trailing: [...fold.trailingReplies, fold.latestReply].map(respond)
|
|
37322
|
+
};
|
|
37323
|
+
return response;
|
|
37324
|
+
}
|
|
37325
|
+
/**
|
|
37326
|
+
* The author API's and MCP's Thread objects for Threads already listed.
|
|
37327
|
+
*
|
|
37328
|
+
* @param deps - Services and app config
|
|
37329
|
+
* @param summaries - Threads to respond with, in order
|
|
37330
|
+
* @returns One Thread object per summary, in the same order
|
|
37331
|
+
* @example
|
|
37332
|
+
* const threads = await loadApiThreadResponses(c.var, page.threads);
|
|
37333
|
+
*/ async function loadApiThreadResponses(deps, summaries) {
|
|
37334
|
+
return buildThreadResponses(summaries, (posts) => loadApiPostResponses(deps, posts), (post) => ({
|
|
37335
|
+
id: post.id,
|
|
37336
|
+
slug: post.slug
|
|
37337
|
+
}));
|
|
37338
|
+
}
|
|
37339
|
+
/**
|
|
37340
|
+
* The public API's Thread objects for Threads already listed.
|
|
37341
|
+
*
|
|
37342
|
+
* @param deps - Services and app config
|
|
37343
|
+
* @param summaries - Threads to respond with, in order
|
|
37344
|
+
* @param options - `content: "markdown"` returns `bodyMarkdown` on every Post
|
|
37345
|
+
* @returns One Thread object per summary, in the same order
|
|
37346
|
+
* @example
|
|
37347
|
+
* const threads = await loadPublicThreadResponses(c.var, page.threads, {});
|
|
37348
|
+
*/ async function loadPublicThreadResponses(deps, summaries, options = {}) {
|
|
37349
|
+
return buildThreadResponses(summaries, (posts) => loadPublicPostResponses(deps, posts, options), (post) => ({
|
|
37350
|
+
id: post.id,
|
|
37351
|
+
slug: post.slug,
|
|
37352
|
+
permalink: toPublicPath(`/${post.slug}`, deps.appConfig.sitePathPrefix)
|
|
37353
|
+
}));
|
|
37354
|
+
}
|
|
37355
|
+
/** Render every Post the Threads show in one batch, then assemble them. */ async function buildThreadResponses(summaries, render, reference) {
|
|
37356
|
+
const posts = collectThreadResponsePosts(summaries);
|
|
37357
|
+
const responses = await render(posts);
|
|
37358
|
+
const byId = new Map(posts.map((post, index) => [post.id, responses[index]]));
|
|
37359
|
+
return summaries.map((summary) => toApiThreadResponse(summary, (post) => {
|
|
37360
|
+
const response = byId.get(post.id);
|
|
37361
|
+
if (!response) throw new Error(`No response built for post ${post.id}`);
|
|
37362
|
+
return response;
|
|
37363
|
+
}, reference));
|
|
37364
|
+
}
|
|
37365
|
+
//#endregion
|
|
37366
|
+
//#region src/lib/thread-query.ts
|
|
37367
|
+
/**
|
|
37368
|
+
* Thread list queries
|
|
37369
|
+
*
|
|
37370
|
+
* Reads the filter dimensions a Thread list takes — the archive's, from the
|
|
37371
|
+
* same registry — out of an HTTP query string or MCP arguments, so the public
|
|
37372
|
+
* API, the author API, and MCP accept one vocabulary.
|
|
37373
|
+
*
|
|
37374
|
+
* One word differs from the archive page. A Thread list left unfiltered shows
|
|
37375
|
+
* what the homepage shows, so it needs a word for "every visibility a reader
|
|
37376
|
+
* may see": `visibility=any`. The registry's `visibility=all` is an old
|
|
37377
|
+
* spelling of leaving the parameter out, which here would mean the homepage's
|
|
37378
|
+
* set — the opposite of what the word says — so a Thread list refuses it.
|
|
37379
|
+
*/ var READER_VISIBILITIES = [
|
|
37380
|
+
"public",
|
|
37381
|
+
"featured",
|
|
37382
|
+
"hidden",
|
|
37383
|
+
"any"
|
|
37384
|
+
];
|
|
37385
|
+
var AUTHOR_VISIBILITIES = [...READER_VISIBILITIES, "private"];
|
|
37386
|
+
/** Spellings the registry reads that stay valid here. */ var LEGACY_VISIBILITIES = ["latest_hidden"];
|
|
37387
|
+
function allowedVisibilities(audience) {
|
|
37388
|
+
return audience === "reader" ? READER_VISIBILITIES : AUTHOR_VISIBILITIES;
|
|
37389
|
+
}
|
|
37390
|
+
/**
|
|
37391
|
+
* Read a Thread list's filter dimensions.
|
|
37392
|
+
*
|
|
37393
|
+
* @param read - Reads one parameter; `undefined` when absent
|
|
37394
|
+
* @param present - Every parameter name the request carries
|
|
37395
|
+
* @param options.allow - The endpoint's own parameters, which aren't
|
|
37396
|
+
* dimensions; anything else unknown is refused
|
|
37397
|
+
* @param options.audience - A reader may not name `private`
|
|
37398
|
+
* @param options.loadCollections - Loads the collection vocabulary, called only
|
|
37399
|
+
* when a collection is named
|
|
37400
|
+
* @returns The selection, or `empty` when a named collection doesn't exist
|
|
37401
|
+
* @throws {ValidationError} On an unknown parameter or an unreadable value
|
|
37402
|
+
* @example
|
|
37403
|
+
* const parsed = await parseThreadSelection(read, Object.keys(query), {
|
|
37404
|
+
* allow: ["cursor", "limit"],
|
|
37405
|
+
* audience: "reader",
|
|
37406
|
+
* loadCollections: () => services.collections.list(),
|
|
37407
|
+
* });
|
|
37408
|
+
*/ async function parseThreadSelection(read, present, options) {
|
|
37409
|
+
const visibility = read("visibility");
|
|
37410
|
+
if (visibility !== void 0) {
|
|
37411
|
+
const allowed = allowedVisibilities(options.audience);
|
|
37412
|
+
if (visibility === "all") throw new ValidationError("visibility=all isn't accepted here. Leave visibility out for what the homepage lists, or pass visibility=any for everything.");
|
|
37413
|
+
if (!allowed.includes(visibility) && !LEGACY_VISIBILITIES.includes(visibility)) throw new ValidationError(`Invalid visibility value. Allowed: ${allowed.join(", ")}`);
|
|
37414
|
+
}
|
|
37415
|
+
const includeHidden = visibility === "any";
|
|
37416
|
+
const readDimension = (key) => key === "visibility" && includeHidden ? void 0 : read(key);
|
|
37417
|
+
const parsed = parsePostFilterSelectionStrict(readDimension, present, { collections: readCollectionSlugs(readDimension).length > 0 ? buildCollectionVocabulary(await options.loadCollections()) : EMPTY_COLLECTION_VOCABULARY }, { allow: options.allow });
|
|
37418
|
+
if (parsed.ok) return {
|
|
37419
|
+
kind: "selection",
|
|
37420
|
+
selection: parsed.selection,
|
|
37421
|
+
includeHidden
|
|
37422
|
+
};
|
|
37423
|
+
if (parsed.issues.every((issue) => issue.param === "collection")) return { kind: "empty" };
|
|
37424
|
+
throw new ValidationError(parsed.issues[0]?.message ?? "Validation failed");
|
|
37425
|
+
}
|
|
37426
|
+
/**
|
|
37427
|
+
* Read `include`: a comma-separated list of extras to attach to each Thread.
|
|
37428
|
+
*
|
|
37429
|
+
* @param raw - The parameter's value, or `undefined`
|
|
37430
|
+
* @returns Whether the fold was asked for
|
|
37431
|
+
* @throws {ValidationError} On a value this endpoint doesn't offer
|
|
37432
|
+
* @example
|
|
37433
|
+
* parseThreadInclude("fold"); // { fold: true }
|
|
37434
|
+
*/ function parseThreadInclude(raw) {
|
|
37435
|
+
if (raw === void 0 || raw === "") return { fold: false };
|
|
37436
|
+
const values = raw.split(",").map((value) => value.trim());
|
|
37437
|
+
for (const value of values) if (value !== "fold") throw new ValidationError(`Invalid include value "${value}". Allowed: fold`);
|
|
37438
|
+
return { fold: values.includes("fold") };
|
|
37439
|
+
}
|
|
37440
|
+
//#endregion
|
|
37441
|
+
//#region src/routes/api/threads.ts
|
|
37442
|
+
/**
|
|
37443
|
+
* Threads API Routes
|
|
37444
|
+
*
|
|
37445
|
+
* The author's view of Threads: every status and visibility, Posts in the
|
|
37446
|
+
* editing view. The reader's view is `/api/public/threads`.
|
|
37447
|
+
*/ var threadsApiRoutes = new Hono();
|
|
37448
|
+
threadsApiRoutes.use("*", requireAuthApi());
|
|
37449
|
+
/** The list's own parameters; everything else is a filter dimension. */ var ListThreadsQuerySchema$1 = z.object({
|
|
37450
|
+
status: StatusSchema.optional(),
|
|
37451
|
+
lang: ContentLanguageSchema.optional(),
|
|
37452
|
+
sort: z.enum(THREAD_SORTS).optional(),
|
|
37453
|
+
include: z.string().optional(),
|
|
37454
|
+
cursor: z.string().optional(),
|
|
37455
|
+
limit: z.coerce.number().int().min(1).max(100).optional().default(20)
|
|
37456
|
+
});
|
|
37457
|
+
var LIST_PARAMS$1 = [
|
|
37458
|
+
"status",
|
|
37459
|
+
"lang",
|
|
37460
|
+
"sort",
|
|
37461
|
+
"include",
|
|
37462
|
+
"cursor",
|
|
37463
|
+
"limit"
|
|
37464
|
+
];
|
|
37465
|
+
var GetThreadQuerySchema$1 = z.object({ include: z.string().optional() });
|
|
37466
|
+
var ListThreadPostsQuerySchema$1 = z.object({
|
|
37467
|
+
status: StatusSchema.optional(),
|
|
37468
|
+
cursor: z.string().optional(),
|
|
37469
|
+
limit: z.coerce.number().int().min(1).max(100).optional().default(100)
|
|
37470
|
+
});
|
|
37471
|
+
threadsApiRoutes.get("/", async (c) => {
|
|
37472
|
+
const query = parseValidated(ListThreadsQuerySchema$1, c.req.query());
|
|
37473
|
+
const { fold } = parseThreadInclude(query.include);
|
|
37474
|
+
const parsed = await parseThreadSelection((key) => c.req.query(key), Object.keys(c.req.query()), {
|
|
37475
|
+
allow: LIST_PARAMS$1,
|
|
37476
|
+
audience: "author",
|
|
37477
|
+
loadCollections: () => c.var.services.collections.list()
|
|
37478
|
+
});
|
|
37479
|
+
if (parsed.kind === "empty") return c.json({
|
|
37480
|
+
threads: [],
|
|
37481
|
+
nextCursor: null
|
|
37482
|
+
});
|
|
37483
|
+
const { threads, nextCursor } = await c.var.services.threads.listThreads({
|
|
37484
|
+
audience: "author",
|
|
37485
|
+
status: query.status,
|
|
37486
|
+
selection: parsed.selection,
|
|
37487
|
+
lang: query.lang,
|
|
37488
|
+
sort: query.sort,
|
|
37489
|
+
fold
|
|
37490
|
+
}, {
|
|
37491
|
+
cursor: query.cursor,
|
|
37492
|
+
limit: query.limit
|
|
37493
|
+
});
|
|
37494
|
+
return c.json({
|
|
37495
|
+
threads: await loadApiThreadResponses(c.var, threads),
|
|
37496
|
+
nextCursor
|
|
37497
|
+
});
|
|
37498
|
+
});
|
|
37499
|
+
threadsApiRoutes.get("/:id", async (c) => {
|
|
37500
|
+
const id = parseIdParam(c.req.param("id"), ID_PREFIX.post);
|
|
37501
|
+
const { include } = parseValidated(GetThreadQuerySchema$1, c.req.query());
|
|
37502
|
+
const root = await c.var.services.threads.findRoot({ id }, "author");
|
|
37503
|
+
if (!root) throw new NotFoundError("Thread");
|
|
37504
|
+
const summaries = await c.var.services.threads.summarize([root], parseThreadInclude(include));
|
|
37505
|
+
const [thread] = await loadApiThreadResponses(c.var, summaries);
|
|
37506
|
+
if (!thread) throw new NotFoundError("Thread");
|
|
37507
|
+
return c.json(thread);
|
|
37508
|
+
});
|
|
37509
|
+
threadsApiRoutes.get("/:id/posts", async (c) => {
|
|
37510
|
+
const id = parseIdParam(c.req.param("id"), ID_PREFIX.post);
|
|
37511
|
+
const { status, cursor, limit } = parseValidated(ListThreadPostsQuerySchema$1, c.req.query());
|
|
37512
|
+
const root = await c.var.services.threads.findRoot({ id }, "author");
|
|
37513
|
+
if (!root) throw new NotFoundError("Thread");
|
|
37514
|
+
const { posts, nextCursor } = await c.var.services.threads.listPosts(root.id, {
|
|
37515
|
+
audience: "author",
|
|
37516
|
+
status
|
|
37517
|
+
}, {
|
|
37518
|
+
cursor,
|
|
37519
|
+
limit
|
|
37520
|
+
});
|
|
37521
|
+
return c.json({
|
|
37522
|
+
posts: await loadApiPostResponses(c.var, posts),
|
|
37523
|
+
nextCursor
|
|
37524
|
+
});
|
|
37525
|
+
});
|
|
37526
|
+
//#endregion
|
|
37041
37527
|
//#region src/routes/api/attachments.ts
|
|
37042
37528
|
/**
|
|
37043
37529
|
* Attachments API Routes
|
|
@@ -38190,10 +38676,82 @@ var AddCollectionThreadToolSchema = z.object({
|
|
|
38190
38676
|
threadId: PostIdSchema
|
|
38191
38677
|
});
|
|
38192
38678
|
var RemoveCollectionThreadToolSchema = AddCollectionThreadToolSchema;
|
|
38679
|
+
/**
|
|
38680
|
+
* The filter dimensions `jant_threads_list` takes, spelled as the HTTP API
|
|
38681
|
+
* and the archive spell them. They reach the same registry parser as a query
|
|
38682
|
+
* string would, so the vocabularies can't drift.
|
|
38683
|
+
*/ var THREAD_FILTER_TOOL_PROPERTIES = {
|
|
38684
|
+
format: {
|
|
38685
|
+
type: "string",
|
|
38686
|
+
enum: [...FORMATS]
|
|
38687
|
+
},
|
|
38688
|
+
collection: {
|
|
38689
|
+
type: "string",
|
|
38690
|
+
description: "Collection slug, or several comma-separated"
|
|
38691
|
+
},
|
|
38692
|
+
year: {
|
|
38693
|
+
type: "integer",
|
|
38694
|
+
description: "Publication year (UTC)"
|
|
38695
|
+
},
|
|
38696
|
+
media: {
|
|
38697
|
+
type: "string",
|
|
38698
|
+
description: "any, none, or comma-separated kinds: image, video, audio, text, document"
|
|
38699
|
+
},
|
|
38700
|
+
title: {
|
|
38701
|
+
type: "string",
|
|
38702
|
+
enum: ["any", "none"]
|
|
38703
|
+
},
|
|
38704
|
+
replies: {
|
|
38705
|
+
type: "string",
|
|
38706
|
+
enum: ["any", "none"]
|
|
38707
|
+
},
|
|
38708
|
+
visibility: {
|
|
38709
|
+
type: "string",
|
|
38710
|
+
enum: [
|
|
38711
|
+
"public",
|
|
38712
|
+
"featured",
|
|
38713
|
+
"hidden",
|
|
38714
|
+
"private"
|
|
38715
|
+
]
|
|
38716
|
+
}
|
|
38717
|
+
};
|
|
38718
|
+
var ListThreadsToolSchema = z.object({
|
|
38719
|
+
cursor: z.string().optional(),
|
|
38720
|
+
limit: z.coerce.number().int().min(1).max(100).optional().default(20),
|
|
38721
|
+
status: StatusSchema.optional(),
|
|
38722
|
+
sort: z.enum(THREAD_SORTS).optional(),
|
|
38723
|
+
fold: z.boolean().optional(),
|
|
38724
|
+
lang: ContentLanguageSchema.optional(),
|
|
38725
|
+
format: z.string().optional(),
|
|
38726
|
+
collection: z.string().optional(),
|
|
38727
|
+
year: z.number().int().optional(),
|
|
38728
|
+
media: z.string().optional(),
|
|
38729
|
+
title: z.string().optional(),
|
|
38730
|
+
replies: z.string().optional(),
|
|
38731
|
+
visibility: z.string().optional()
|
|
38732
|
+
});
|
|
38733
|
+
var LIST_THREADS_OWN_PARAMS = [
|
|
38734
|
+
"cursor",
|
|
38735
|
+
"limit",
|
|
38736
|
+
"status",
|
|
38737
|
+
"sort",
|
|
38738
|
+
"fold",
|
|
38739
|
+
"lang"
|
|
38740
|
+
];
|
|
38741
|
+
var GetThreadToolSchema = z.object({
|
|
38742
|
+
id: PostIdSchema,
|
|
38743
|
+
fold: z.boolean().optional()
|
|
38744
|
+
});
|
|
38745
|
+
var ListThreadPostsToolSchema = z.object({
|
|
38746
|
+
id: PostIdSchema,
|
|
38747
|
+
cursor: z.string().optional(),
|
|
38748
|
+
limit: z.coerce.number().int().min(1).max(100).optional().default(100),
|
|
38749
|
+
status: StatusSchema.optional()
|
|
38750
|
+
});
|
|
38193
38751
|
var mcpTools = [
|
|
38194
38752
|
{
|
|
38195
38753
|
name: "jant_posts_list",
|
|
38196
|
-
description: "List posts, with optional format, status, cursor, and limit filters.",
|
|
38754
|
+
description: "List posts, with optional format, status, cursor, and limit filters. Pass nextCursor back as cursor for the next page.",
|
|
38197
38755
|
inputSchema: {
|
|
38198
38756
|
type: "object",
|
|
38199
38757
|
properties: {
|
|
@@ -38217,15 +38775,18 @@ var mcpTools = [
|
|
|
38217
38775
|
},
|
|
38218
38776
|
async execute(args, context) {
|
|
38219
38777
|
const input = ListPostsToolSchema.parse(args ?? {});
|
|
38220
|
-
const
|
|
38221
|
-
|
|
38778
|
+
const status = input.status ?? "published";
|
|
38779
|
+
const { posts, nextCursor } = await context.services.posts.listPage({
|
|
38222
38780
|
format: input.format,
|
|
38223
|
-
|
|
38224
|
-
status
|
|
38781
|
+
status,
|
|
38782
|
+
...apiPostListOrder(status)
|
|
38783
|
+
}, {
|
|
38784
|
+
cursor: input.cursor,
|
|
38785
|
+
limit: input.limit
|
|
38225
38786
|
});
|
|
38226
38787
|
return {
|
|
38227
38788
|
posts: await serializePosts(posts, context),
|
|
38228
|
-
nextCursor
|
|
38789
|
+
nextCursor
|
|
38229
38790
|
};
|
|
38230
38791
|
}
|
|
38231
38792
|
},
|
|
@@ -38267,6 +38828,133 @@ var mcpTools = [
|
|
|
38267
38828
|
return content;
|
|
38268
38829
|
}
|
|
38269
38830
|
},
|
|
38831
|
+
{
|
|
38832
|
+
name: "jant_threads_list",
|
|
38833
|
+
description: "List Threads (a root post and its replies), each with its post count. Takes the archive's filters; sort is activity (default), published, updated, oldest, or rating. Set fold to include the replies the homepage shows. Pass nextCursor back as cursor for the next page.",
|
|
38834
|
+
inputSchema: {
|
|
38835
|
+
type: "object",
|
|
38836
|
+
properties: {
|
|
38837
|
+
cursor: { type: "string" },
|
|
38838
|
+
limit: {
|
|
38839
|
+
type: "integer",
|
|
38840
|
+
minimum: 1,
|
|
38841
|
+
maximum: 100,
|
|
38842
|
+
default: 20
|
|
38843
|
+
},
|
|
38844
|
+
status: {
|
|
38845
|
+
type: "string",
|
|
38846
|
+
enum: [...STATUSES]
|
|
38847
|
+
},
|
|
38848
|
+
sort: {
|
|
38849
|
+
type: "string",
|
|
38850
|
+
enum: [...THREAD_SORTS]
|
|
38851
|
+
},
|
|
38852
|
+
fold: { type: "boolean" },
|
|
38853
|
+
lang: {
|
|
38854
|
+
type: "string",
|
|
38855
|
+
description: "BCP 47 content language"
|
|
38856
|
+
},
|
|
38857
|
+
...THREAD_FILTER_TOOL_PROPERTIES
|
|
38858
|
+
},
|
|
38859
|
+
additionalProperties: false
|
|
38860
|
+
},
|
|
38861
|
+
async execute(args, context) {
|
|
38862
|
+
const input = ListThreadsToolSchema.parse(args ?? {});
|
|
38863
|
+
const filterArgs = Object.fromEntries(Object.entries(input).filter(([key, value]) => value !== void 0 && !LIST_THREADS_OWN_PARAMS.includes(key)));
|
|
38864
|
+
const parsed = await parseThreadSelection((key) => {
|
|
38865
|
+
const value = filterArgs[key];
|
|
38866
|
+
return value === void 0 ? void 0 : String(value);
|
|
38867
|
+
}, Object.keys(filterArgs), {
|
|
38868
|
+
allow: [],
|
|
38869
|
+
audience: "author",
|
|
38870
|
+
loadCollections: () => context.services.collections.list()
|
|
38871
|
+
});
|
|
38872
|
+
if (parsed.kind === "empty") return {
|
|
38873
|
+
threads: [],
|
|
38874
|
+
nextCursor: null
|
|
38875
|
+
};
|
|
38876
|
+
const { threads, nextCursor } = await context.services.threads.listThreads({
|
|
38877
|
+
audience: "author",
|
|
38878
|
+
status: input.status,
|
|
38879
|
+
selection: parsed.selection,
|
|
38880
|
+
lang: input.lang,
|
|
38881
|
+
sort: input.sort,
|
|
38882
|
+
fold: input.fold
|
|
38883
|
+
}, {
|
|
38884
|
+
cursor: input.cursor,
|
|
38885
|
+
limit: input.limit
|
|
38886
|
+
});
|
|
38887
|
+
return {
|
|
38888
|
+
threads: await loadApiThreadResponses(context, threads),
|
|
38889
|
+
nextCursor
|
|
38890
|
+
};
|
|
38891
|
+
}
|
|
38892
|
+
},
|
|
38893
|
+
{
|
|
38894
|
+
name: "jant_threads_get",
|
|
38895
|
+
description: "Get the Thread any post belongs to: its root and post count, and with fold the replies the homepage shows.",
|
|
38896
|
+
inputSchema: {
|
|
38897
|
+
type: "object",
|
|
38898
|
+
properties: {
|
|
38899
|
+
id: {
|
|
38900
|
+
type: "string",
|
|
38901
|
+
description: "TypeID of any post in the Thread"
|
|
38902
|
+
},
|
|
38903
|
+
fold: { type: "boolean" }
|
|
38904
|
+
},
|
|
38905
|
+
required: ["id"],
|
|
38906
|
+
additionalProperties: false
|
|
38907
|
+
},
|
|
38908
|
+
async execute(args, context) {
|
|
38909
|
+
const input = GetThreadToolSchema.parse(args ?? {});
|
|
38910
|
+
const root = await context.services.threads.findRoot({ id: input.id }, "author");
|
|
38911
|
+
if (!root) throw new NotFoundError("Thread");
|
|
38912
|
+
const [thread] = await loadApiThreadResponses(context, await context.services.threads.summarize([root], { fold: input.fold }));
|
|
38913
|
+
return thread;
|
|
38914
|
+
}
|
|
38915
|
+
},
|
|
38916
|
+
{
|
|
38917
|
+
name: "jant_threads_list_posts",
|
|
38918
|
+
description: "List the posts of the Thread any post belongs to, root first, in Thread order. Pass nextCursor back as cursor for the next page.",
|
|
38919
|
+
inputSchema: {
|
|
38920
|
+
type: "object",
|
|
38921
|
+
properties: {
|
|
38922
|
+
id: {
|
|
38923
|
+
type: "string",
|
|
38924
|
+
description: "TypeID of any post in the Thread"
|
|
38925
|
+
},
|
|
38926
|
+
cursor: { type: "string" },
|
|
38927
|
+
limit: {
|
|
38928
|
+
type: "integer",
|
|
38929
|
+
minimum: 1,
|
|
38930
|
+
maximum: 100,
|
|
38931
|
+
default: 100
|
|
38932
|
+
},
|
|
38933
|
+
status: {
|
|
38934
|
+
type: "string",
|
|
38935
|
+
enum: [...STATUSES]
|
|
38936
|
+
}
|
|
38937
|
+
},
|
|
38938
|
+
required: ["id"],
|
|
38939
|
+
additionalProperties: false
|
|
38940
|
+
},
|
|
38941
|
+
async execute(args, context) {
|
|
38942
|
+
const input = ListThreadPostsToolSchema.parse(args ?? {});
|
|
38943
|
+
const root = await context.services.threads.findRoot({ id: input.id }, "author");
|
|
38944
|
+
if (!root) throw new NotFoundError("Thread");
|
|
38945
|
+
const { posts, nextCursor } = await context.services.threads.listPosts(root.id, {
|
|
38946
|
+
audience: "author",
|
|
38947
|
+
status: input.status
|
|
38948
|
+
}, {
|
|
38949
|
+
cursor: input.cursor,
|
|
38950
|
+
limit: input.limit
|
|
38951
|
+
});
|
|
38952
|
+
return {
|
|
38953
|
+
posts: await serializePosts(posts, context),
|
|
38954
|
+
nextCursor
|
|
38955
|
+
};
|
|
38956
|
+
}
|
|
38957
|
+
},
|
|
38270
38958
|
{
|
|
38271
38959
|
name: "jant_posts_create",
|
|
38272
38960
|
description: "Create a post. Supports the same JSON body as POST /api/posts.",
|
|
@@ -39052,28 +39740,15 @@ async function uploadMediaFromBase64(input, context) {
|
|
|
39052
39740
|
if (!media) throw new NotFoundError("Media");
|
|
39053
39741
|
return serializeMedia(media, context.appConfig);
|
|
39054
39742
|
}
|
|
39055
|
-
|
|
39056
|
-
|
|
39057
|
-
const postIds = posts.map((post) => post.id);
|
|
39058
|
-
const [mediaMap, collectionMap] = await Promise.all([context.services.media.getByPostIds(postIds), context.services.collections.getCollectionsByPostIds(postIds)]);
|
|
39059
|
-
return posts.map((post) => toApiPost(post, {
|
|
39060
|
-
attachments: serializeAttachments(mediaMap.get(post.id) ?? [], context.appConfig),
|
|
39061
|
-
collectionIds: (collectionMap.get(post.id) ?? []).map((collection) => collection.id)
|
|
39062
|
-
}));
|
|
39743
|
+
function serializePosts(posts, context) {
|
|
39744
|
+
return loadApiPostResponses(context, posts, { collectionIds: true });
|
|
39063
39745
|
}
|
|
39064
|
-
|
|
39065
|
-
|
|
39066
|
-
return toApiPost(post, {
|
|
39067
|
-
attachments: serializeAttachments(mediaList, context.appConfig),
|
|
39068
|
-
collectionIds: threadCollections.map((collection) => collection.id)
|
|
39069
|
-
});
|
|
39746
|
+
function serializePost(post, context) {
|
|
39747
|
+
return loadApiPostResponse(context, post, { collectionIds: true });
|
|
39070
39748
|
}
|
|
39071
39749
|
function serializeMedia(media, appConfig) {
|
|
39072
39750
|
return toApiMedia(media, appConfig);
|
|
39073
39751
|
}
|
|
39074
|
-
function serializeAttachments(mediaList, appConfig) {
|
|
39075
|
-
return mediaList.map((media) => toApiAttachment(media, appConfig.r2PublicUrl, appConfig.imageTransformUrl, appConfig.s3PublicUrl, appConfig.localPublicUrl, appConfig.sitePathPrefix));
|
|
39076
|
-
}
|
|
39077
39752
|
//#endregion
|
|
39078
39753
|
//#region src/routes/api/mcp.ts
|
|
39079
39754
|
var mcpApiRoutes = new Hono();
|
|
@@ -39225,36 +39900,6 @@ customUrlsApiRoutes.delete("/:id", requireAuthApi(), async (c) => {
|
|
|
39225
39900
|
return root.lastActivityAt ?? root.publishedAt ?? root.updatedAt;
|
|
39226
39901
|
}
|
|
39227
39902
|
//#endregion
|
|
39228
|
-
//#region src/lib/tiptap-to-markdown.ts
|
|
39229
|
-
/**
|
|
39230
|
-
* Tiptap JSON → Markdown Converter
|
|
39231
|
-
*
|
|
39232
|
-
* Converts Tiptap JSON documents to Markdown using the official
|
|
39233
|
-
* Tiptap MarkdownManager and Jant's shared markdown schema.
|
|
39234
|
-
*/
|
|
39235
|
-
/**
|
|
39236
|
-
* Converts a Tiptap JSON document to a Markdown string.
|
|
39237
|
-
*
|
|
39238
|
-
* Throws rather than returning an empty string: a caller writing the result
|
|
39239
|
-
* somewhere (an export, a text attachment) would otherwise replace the
|
|
39240
|
-
* content with nothing and say nothing.
|
|
39241
|
-
*
|
|
39242
|
-
* @param json - Tiptap JSON document string
|
|
39243
|
-
* @returns Markdown string
|
|
39244
|
-
* @throws {SyntaxError} When `json` is not JSON
|
|
39245
|
-
* @throws {Error} When the root node is not a `doc`
|
|
39246
|
-
*
|
|
39247
|
-
* @example
|
|
39248
|
-
* ```ts
|
|
39249
|
-
* const md = tiptapJsonToMarkdown('{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Hello"}]}]}');
|
|
39250
|
-
* // "Hello"
|
|
39251
|
-
* ```
|
|
39252
|
-
*/ function tiptapJsonToMarkdown(json) {
|
|
39253
|
-
const doc = JSON.parse(json);
|
|
39254
|
-
if (doc.type !== "doc") throw new Error(`A TipTap body's root must be a doc node, not ${JSON.stringify(doc.type)}.`);
|
|
39255
|
-
return serializeMarkdownDocument(doc).trimEnd();
|
|
39256
|
-
}
|
|
39257
|
-
//#endregion
|
|
39258
39903
|
//#region src/lib/hugo-markdown.ts
|
|
39259
39904
|
/**
|
|
39260
39905
|
* Shared Hugo Markdown parsing utilities.
|
|
@@ -41016,6 +41661,137 @@ internalApiTokensRoutes.post("/purge", requireInternalAdminApi(), async (c) => {
|
|
|
41016
41661
|
if (options.lang) conditions.push(sql`${post.language} = ${options.lang}`);
|
|
41017
41662
|
return conditions;
|
|
41018
41663
|
}
|
|
41664
|
+
//#endregion
|
|
41665
|
+
//#region src/lib/post-list-cursor.ts
|
|
41666
|
+
/**
|
|
41667
|
+
* The cursor `posts.listPage()` and `posts.listCollectionThreadRootPage()`
|
|
41668
|
+
* hand out as `nextCursor`.
|
|
41669
|
+
*
|
|
41670
|
+
* A cursor says where the previous page ended: the sort mode it was taken in
|
|
41671
|
+
* and the full sort-key tuple of that page's last row, key for key as the
|
|
41672
|
+
* ORDER BY reads them. Resuming is a pure keyset comparison against those
|
|
41673
|
+
* values, so the post the page ended on can be deleted, unpublished, or edited
|
|
41674
|
+
* before the next request without moving the position. The two lists name
|
|
41675
|
+
* their sort modes apart, so a cursor from one never resumes the other.
|
|
41676
|
+
*
|
|
41677
|
+
* Wire format: `base64url(JSON { v, s, k })` — format version, sort mode, and
|
|
41678
|
+
* key tuple. It is not signed. A caller who edits one can only move their own
|
|
41679
|
+
* position on an axis they may already read; the values are never looked up.
|
|
41680
|
+
* Filters stay out: a position on the sort axis is valid under any filter.
|
|
41681
|
+
*
|
|
41682
|
+
* Callers treat the string as opaque. The one other shape still accepted is
|
|
41683
|
+
* the bare post TypeID earlier releases returned; see
|
|
41684
|
+
* {@link isLegacyPostListCursor}.
|
|
41685
|
+
*/
|
|
41686
|
+
/** Bumped when the payload shape changes; older versions are rejected. */ var POST_LIST_CURSOR_VERSION = 1;
|
|
41687
|
+
/**
|
|
41688
|
+
* Longest encoded cursor accepted. The largest tuple (pinned, rating, time,
|
|
41689
|
+
* id) encodes to under 200 characters; the cap only keeps a hostile value from
|
|
41690
|
+
* reaching the decoder.
|
|
41691
|
+
*/ var MAX_ENCODED_LENGTH = 512;
|
|
41692
|
+
var BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/;
|
|
41693
|
+
var UNREADABLE_MESSAGE = "This cursor can't be read. Pass back nextCursor unchanged, or leave cursor out to start from the first page.";
|
|
41694
|
+
var VERSION_MESSAGE = "This cursor is from a different version of Jant. Leave cursor out to start from the first page.";
|
|
41695
|
+
var MODE_MESSAGE = "This cursor is from a list in a different order. Leave cursor out to start from the first page.";
|
|
41696
|
+
/**
|
|
41697
|
+
* A legacy cursor naming a Post that is gone, or that the caller can't see.
|
|
41698
|
+
* One message for both, so a cursor can't be used to probe for private Posts.
|
|
41699
|
+
*/ var MISSING_LEGACY_CURSOR_MESSAGE = "This cursor names a post that can't be found. Leave cursor out to start from the first page.";
|
|
41700
|
+
function encodeBase64Url(text) {
|
|
41701
|
+
return btoa(text).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
41702
|
+
}
|
|
41703
|
+
function decodeBase64Url(encoded) {
|
|
41704
|
+
const padded = encoded.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((encoded.length + 3) % 4);
|
|
41705
|
+
try {
|
|
41706
|
+
return atob(padded);
|
|
41707
|
+
} catch {
|
|
41708
|
+
return null;
|
|
41709
|
+
}
|
|
41710
|
+
}
|
|
41711
|
+
function isPlainObject(value) {
|
|
41712
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
41713
|
+
}
|
|
41714
|
+
function matchesKind(value, kind) {
|
|
41715
|
+
return kind === "number" ? Number.isSafeInteger(value) : typeof value === "string" && isTypeId(value, ID_PREFIX.post);
|
|
41716
|
+
}
|
|
41717
|
+
/**
|
|
41718
|
+
* Encode the position after a page's last row.
|
|
41719
|
+
*
|
|
41720
|
+
* @param mode - The sort mode the page was read in
|
|
41721
|
+
* @param values - That row's sort-key tuple, in ORDER BY order
|
|
41722
|
+
* @returns The opaque cursor string
|
|
41723
|
+
* @example
|
|
41724
|
+
* ```ts
|
|
41725
|
+
* encodePostListCursor("newest:activity:pinned", [-1, 1706000000, post.id]);
|
|
41726
|
+
* ```
|
|
41727
|
+
*/ function encodePostListCursor(mode, values) {
|
|
41728
|
+
const payload = {
|
|
41729
|
+
v: POST_LIST_CURSOR_VERSION,
|
|
41730
|
+
s: mode,
|
|
41731
|
+
k: [...values]
|
|
41732
|
+
};
|
|
41733
|
+
return encodeBase64Url(JSON.stringify(payload));
|
|
41734
|
+
}
|
|
41735
|
+
/**
|
|
41736
|
+
* Decode a cursor for the current request, strictly.
|
|
41737
|
+
*
|
|
41738
|
+
* Nothing here falls back to the first page: a cursor that can't be read, that
|
|
41739
|
+
* an unknown format version wrote, that was taken in another sort mode, or
|
|
41740
|
+
* whose tuple doesn't fit the mode's keys is rejected, because answering with
|
|
41741
|
+
* page 1 would hand the caller posts it already has.
|
|
41742
|
+
*
|
|
41743
|
+
* @param raw - The `cursor` the caller sent
|
|
41744
|
+
* @param shape - The current request's sort mode and key kinds
|
|
41745
|
+
* @returns The key tuple, in ORDER BY order
|
|
41746
|
+
* @throws {ValidationError} When the cursor doesn't resume this request
|
|
41747
|
+
* @example
|
|
41748
|
+
* ```ts
|
|
41749
|
+
* const after = decodePostListCursor(cursor, {
|
|
41750
|
+
* mode: "newest:published:unpinned",
|
|
41751
|
+
* kinds: ["number", "id"],
|
|
41752
|
+
* });
|
|
41753
|
+
* ```
|
|
41754
|
+
*/ function decodePostListCursor(raw, shape) {
|
|
41755
|
+
if (raw.length > MAX_ENCODED_LENGTH || !BASE64URL_PATTERN.test(raw)) throw new ValidationError(UNREADABLE_MESSAGE);
|
|
41756
|
+
const text = decodeBase64Url(raw);
|
|
41757
|
+
if (text === null) throw new ValidationError(UNREADABLE_MESSAGE);
|
|
41758
|
+
let parsed;
|
|
41759
|
+
try {
|
|
41760
|
+
parsed = JSON.parse(text);
|
|
41761
|
+
} catch {
|
|
41762
|
+
throw new ValidationError(UNREADABLE_MESSAGE);
|
|
41763
|
+
}
|
|
41764
|
+
if (!isPlainObject(parsed) || !Number.isSafeInteger(parsed.v)) throw new ValidationError(UNREADABLE_MESSAGE);
|
|
41765
|
+
if (parsed.v !== POST_LIST_CURSOR_VERSION) throw new ValidationError(VERSION_MESSAGE);
|
|
41766
|
+
const { s: mode, k: values } = parsed;
|
|
41767
|
+
if (Object.keys(parsed).length !== 3 || typeof mode !== "string" || !Array.isArray(values)) throw new ValidationError(UNREADABLE_MESSAGE);
|
|
41768
|
+
if (mode !== shape.mode) throw new ValidationError(MODE_MESSAGE);
|
|
41769
|
+
if (values.length !== shape.kinds.length) throw new ValidationError(UNREADABLE_MESSAGE);
|
|
41770
|
+
const tuple = [];
|
|
41771
|
+
for (const [index, kind] of shape.kinds.entries()) {
|
|
41772
|
+
const value = values[index];
|
|
41773
|
+
if (!matchesKind(value, kind)) throw new ValidationError(UNREADABLE_MESSAGE);
|
|
41774
|
+
tuple.push(value);
|
|
41775
|
+
}
|
|
41776
|
+
return tuple;
|
|
41777
|
+
}
|
|
41778
|
+
/**
|
|
41779
|
+
* Whether a cursor is the bare post TypeID that releases before the opaque
|
|
41780
|
+
* format returned as `nextCursor`.
|
|
41781
|
+
*
|
|
41782
|
+
* Accepted indefinitely — a stored cursor, or one a client built from a post
|
|
41783
|
+
* ID, must keep resuming. An encoded cursor can never look like one: it opens
|
|
41784
|
+
* with the base64url of `{"`, never with `pst_`.
|
|
41785
|
+
*
|
|
41786
|
+
* @param raw - The `cursor` the caller sent
|
|
41787
|
+
* @returns Whether to resolve it as a post ID
|
|
41788
|
+
* @example
|
|
41789
|
+
* ```ts
|
|
41790
|
+
* isLegacyPostListCursor("pst_01jpyx3m7gw4w3h7m4bknq0v1d"); // => true
|
|
41791
|
+
* ```
|
|
41792
|
+
*/ function isLegacyPostListCursor(raw) {
|
|
41793
|
+
return isTypeId(raw, ID_PREFIX.post);
|
|
41794
|
+
}
|
|
41019
41795
|
/**
|
|
41020
41796
|
* Render canonical post JSON with a stable page-wide footnote namespace.
|
|
41021
41797
|
*
|
|
@@ -73063,6 +73839,10 @@ function createPathService(db, siteId, databaseSchema = sqliteSchemaBundle) {
|
|
|
73063
73839
|
* visibility (public/latest_hidden/private), featuredAt, and pinnedAt timestamp.
|
|
73064
73840
|
*/
|
|
73065
73841
|
/**
|
|
73842
|
+
* The sort mode a cursor into one Thread's Posts records. Distinct from every
|
|
73843
|
+
* `list()` and collection mode, so a position in one never resumes another.
|
|
73844
|
+
*/ var THREAD_POSTS_SORT_MODE = "thread";
|
|
73845
|
+
/**
|
|
73066
73846
|
* Rebuild body HTML using the site's current runtime summary settings.
|
|
73067
73847
|
*
|
|
73068
73848
|
* Internal maintenance routes do not run behind the normal app-config
|
|
@@ -73182,13 +73962,32 @@ function createPostService(db, config, siteId, paths, databaseSchema = sqliteSch
|
|
|
73182
73962
|
* db.select().from(posts).orderBy(posts.threadId, ...threadOrder());
|
|
73183
73963
|
* sql`ROW_NUMBER() OVER (ORDER BY ${sql.join(threadOrder(), sql`, `)})`;
|
|
73184
73964
|
*/ function threadOrder(direction = "asc") {
|
|
73185
|
-
const terms =
|
|
73186
|
-
sql`CASE WHEN ${posts.replyToId} IS NULL THEN 0 ELSE 1 END`,
|
|
73187
|
-
sql`${posts.createdAt}`,
|
|
73188
|
-
sql`${posts.id}`
|
|
73189
|
-
];
|
|
73965
|
+
const terms = threadSortKeys().map((key) => key.expr);
|
|
73190
73966
|
return direction === "asc" ? terms : terms.map((term) => desc(term));
|
|
73191
73967
|
}
|
|
73968
|
+
/**
|
|
73969
|
+
* {@link threadOrder} as paged sort keys, for walking one Thread with a
|
|
73970
|
+
* cursor. The one definition both read, so a page of a Thread and the
|
|
73971
|
+
* Thread page itself cannot order its posts differently.
|
|
73972
|
+
*/ function threadSortKeys() {
|
|
73973
|
+
return [
|
|
73974
|
+
{
|
|
73975
|
+
expr: sql`CASE WHEN ${posts.replyToId} IS NULL THEN 0 ELSE 1 END`.mapWith(Number),
|
|
73976
|
+
direction: "asc",
|
|
73977
|
+
kind: "number"
|
|
73978
|
+
},
|
|
73979
|
+
{
|
|
73980
|
+
expr: sql`${posts.createdAt}`.mapWith(Number),
|
|
73981
|
+
direction: "asc",
|
|
73982
|
+
kind: "number"
|
|
73983
|
+
},
|
|
73984
|
+
{
|
|
73985
|
+
expr: sql`${posts.id}`,
|
|
73986
|
+
direction: "asc",
|
|
73987
|
+
kind: "id"
|
|
73988
|
+
}
|
|
73989
|
+
];
|
|
73990
|
+
}
|
|
73192
73991
|
function buildYearMonthExpr(column) {
|
|
73193
73992
|
return databaseDialect === "pg" ? sql`to_char(timezone('UTC', to_timestamp(${column})), 'YYYY-MM')` : sql`strftime('%Y-%m', ${column}, 'unixepoch')`;
|
|
73194
73993
|
}
|
|
@@ -73374,25 +74173,112 @@ function createPostService(db, config, siteId, paths, databaseSchema = sqliteSch
|
|
|
73374
74173
|
}
|
|
73375
74174
|
return conditions;
|
|
73376
74175
|
}
|
|
73377
|
-
|
|
73378
|
-
|
|
73379
|
-
|
|
73380
|
-
|
|
74176
|
+
/**
|
|
74177
|
+
* How `list()` orders a set of filters.
|
|
74178
|
+
*
|
|
74179
|
+
* A Featured list runs newest-published-first whatever `sortOrder` and
|
|
74180
|
+
* `sortBy` say. It is that order and no variant of it, so a cursor moves
|
|
74181
|
+
* between a Featured list and any other newest-published one. Everything
|
|
74182
|
+
* else takes both from the filters, defaulting to newest by announced
|
|
74183
|
+
* activity.
|
|
74184
|
+
*/ function resolveListSort(filters) {
|
|
74185
|
+
const pinned = !filters.ignorePinnedSort;
|
|
74186
|
+
if (filters.featured) return {
|
|
74187
|
+
order: "newest",
|
|
74188
|
+
axis: "published",
|
|
74189
|
+
pinned
|
|
74190
|
+
};
|
|
74191
|
+
return {
|
|
74192
|
+
order: filters.sortOrder ?? "newest",
|
|
74193
|
+
axis: filters.sortBy ?? "activity",
|
|
74194
|
+
pinned
|
|
74195
|
+
};
|
|
74196
|
+
}
|
|
74197
|
+
/**
|
|
74198
|
+
* The sort mode a cursor records. Two requests share a mode exactly when
|
|
74199
|
+
* their ORDER BY reads the same keys in the same directions, so a position
|
|
74200
|
+
* taken in one resumes the other.
|
|
74201
|
+
*/ function listSortMode(sort) {
|
|
74202
|
+
return `${sort.order}:${sort.axis}:${sort.pinned ? "pinned" : "unpinned"}`;
|
|
74203
|
+
}
|
|
74204
|
+
/**
|
|
74205
|
+
* Where a Post sits on one of `list()`'s time axes. See `PostFilters.sortBy`.
|
|
74206
|
+
*
|
|
74207
|
+
* On the activity axis a draft, which has announced nothing, sits at its last
|
|
74208
|
+
* edit. When the status filter already settles which case applies, only
|
|
74209
|
+
* that column is read.
|
|
74210
|
+
*/ function listAxisExpr(axis, status) {
|
|
74211
|
+
switch (axis) {
|
|
74212
|
+
case "published": return sql`coalesce(${posts.publishedAt}, ${posts.createdAt})`;
|
|
74213
|
+
case "thread_updated": return sql`${posts.threadUpdatedAt}`;
|
|
74214
|
+
case "activity":
|
|
74215
|
+
if (status === "draft") return sql`${posts.updatedAt}`;
|
|
74216
|
+
if (status === "published") return sql`${posts.lastActivityAt}`;
|
|
74217
|
+
return sql`CASE
|
|
74218
|
+
WHEN ${posts.status} = 'draft' THEN ${posts.updatedAt}
|
|
74219
|
+
ELSE ${posts.lastActivityAt}
|
|
74220
|
+
END`;
|
|
74221
|
+
}
|
|
73381
74222
|
}
|
|
73382
74223
|
/**
|
|
73383
|
-
*
|
|
74224
|
+
* `list()`'s sort keys, in ORDER BY order — the one definition of it.
|
|
73384
74225
|
*
|
|
73385
|
-
*
|
|
73386
|
-
*
|
|
73387
|
-
|
|
73388
|
-
|
|
73389
|
-
|
|
73390
|
-
|
|
73391
|
-
|
|
73392
|
-
|
|
73393
|
-
|
|
73394
|
-
|
|
73395
|
-
|
|
74226
|
+
* The ORDER BY, the keyset condition that resumes after a cursor, and the
|
|
74227
|
+
* values a cursor records are all built from this list, so they cannot read
|
|
74228
|
+
* different expressions. Two of them used to, and a page boundary then
|
|
74229
|
+
* skipped or repeated Posts.
|
|
74230
|
+
*
|
|
74231
|
+
* Every nullable key is wrapped in `coalesce(…, -1)`. SQLite sorts NULLs
|
|
74232
|
+
* last under DESC and Postgres sorts them first, and a keyset comparison
|
|
74233
|
+
* against NULL is never true on either; with the wrap both engines order,
|
|
74234
|
+
* compare, and return the same values. The Post ID ends every list, so no
|
|
74235
|
+
* two rows share a tuple.
|
|
74236
|
+
*/ function listSortKeys(sort, status) {
|
|
74237
|
+
const numberKey = (expr, direction) => ({
|
|
74238
|
+
expr: sql`coalesce(${expr}, -1)`.mapWith(Number),
|
|
74239
|
+
direction,
|
|
74240
|
+
kind: "number"
|
|
74241
|
+
});
|
|
74242
|
+
const idKey = (direction) => ({
|
|
74243
|
+
expr: sql`${posts.id}`,
|
|
74244
|
+
direction,
|
|
74245
|
+
kind: "id"
|
|
74246
|
+
});
|
|
74247
|
+
const pinnedKeys = sort.pinned ? [numberKey(sql`${posts.pinnedAt}`, "desc")] : [];
|
|
74248
|
+
const time = listAxisExpr(sort.axis, status);
|
|
74249
|
+
switch (sort.order) {
|
|
74250
|
+
case "oldest": return [
|
|
74251
|
+
...pinnedKeys,
|
|
74252
|
+
numberKey(time, "asc"),
|
|
74253
|
+
idKey("asc")
|
|
74254
|
+
];
|
|
74255
|
+
case "rating_desc": return [
|
|
74256
|
+
...pinnedKeys,
|
|
74257
|
+
numberKey(sql`${posts.rating}`, "desc"),
|
|
74258
|
+
numberKey(time, "desc"),
|
|
74259
|
+
idKey("desc")
|
|
74260
|
+
];
|
|
74261
|
+
case "newest": return [
|
|
74262
|
+
...pinnedKeys,
|
|
74263
|
+
numberKey(time, "desc"),
|
|
74264
|
+
idKey("desc")
|
|
74265
|
+
];
|
|
74266
|
+
}
|
|
74267
|
+
}
|
|
74268
|
+
function listOrderBy(keys) {
|
|
74269
|
+
return keys.map((key) => key.direction === "desc" ? desc(key.expr) : asc(key.expr));
|
|
74270
|
+
}
|
|
74271
|
+
/** The sort keys as select fields, `k0`, `k1`, …, in ORDER BY order. */ function listSortKeyFields(keys) {
|
|
74272
|
+
return Object.fromEntries(keys.map((key, index) => [`k${index}`, key.expr]));
|
|
74273
|
+
}
|
|
74274
|
+
/** Read back the tuple {@link listSortKeyFields} selected. */ function readListSortKeyValues(keys, fields) {
|
|
74275
|
+
return keys.map((key, index) => {
|
|
74276
|
+
const value = fields[`k${index}`];
|
|
74277
|
+
if (key.kind === "number") {
|
|
74278
|
+
if (typeof value === "number" && Number.isSafeInteger(value)) return value;
|
|
74279
|
+
} else if (typeof value === "string") return value;
|
|
74280
|
+
throw new Error(`Sort key ${index} read back as ${String(value)}`);
|
|
74281
|
+
});
|
|
73396
74282
|
}
|
|
73397
74283
|
function buildLexicographicCursorCondition(keys) {
|
|
73398
74284
|
const [first, ...rest] = keys;
|
|
@@ -73403,82 +74289,40 @@ function createPostService(db, config, siteId, paths, databaseSchema = sqliteSch
|
|
|
73403
74289
|
OR (${first.expr} = ${first.value} AND ${buildLexicographicCursorCondition(rest)})
|
|
73404
74290
|
)`;
|
|
73405
74291
|
}
|
|
73406
|
-
|
|
73407
|
-
|
|
73408
|
-
|
|
73409
|
-
|
|
73410
|
-
|
|
73411
|
-
|
|
73412
|
-
|
|
73413
|
-
|
|
73414
|
-
|
|
73415
|
-
|
|
73416
|
-
|
|
73417
|
-
|
|
73418
|
-
|
|
73419
|
-
|
|
73420
|
-
|
|
73421
|
-
|
|
73422
|
-
|
|
73423
|
-
|
|
73424
|
-
|
|
73425
|
-
|
|
73426
|
-
|
|
73427
|
-
|
|
73428
|
-
|
|
73429
|
-
|
|
73430
|
-
|
|
73431
|
-
|
|
73432
|
-
|
|
73433
|
-
|
|
73434
|
-
|
|
73435
|
-
|
|
73436
|
-
|
|
73437
|
-
|
|
73438
|
-
|
|
73439
|
-
|
|
73440
|
-
switch (filters.sortOrder ?? "newest") {
|
|
73441
|
-
case "oldest": return buildLexicographicCursorCondition(withPinnedSortKey([{
|
|
73442
|
-
direction: "asc",
|
|
73443
|
-
expr: sortTimestampSortExpr,
|
|
73444
|
-
value: cursorSortTimestamp
|
|
73445
|
-
}, {
|
|
73446
|
-
direction: "asc",
|
|
73447
|
-
expr: posts.id,
|
|
73448
|
-
value: cursorPost.id
|
|
73449
|
-
}]));
|
|
73450
|
-
case "rating_desc": return buildLexicographicCursorCondition(withPinnedSortKey([
|
|
73451
|
-
{
|
|
73452
|
-
direction: "desc",
|
|
73453
|
-
expr: ratingPresenceExpr,
|
|
73454
|
-
value: cursorRatingPresence
|
|
73455
|
-
},
|
|
73456
|
-
{
|
|
73457
|
-
direction: "desc",
|
|
73458
|
-
expr: ratingSortExpr,
|
|
73459
|
-
value: cursorRating
|
|
73460
|
-
},
|
|
73461
|
-
{
|
|
73462
|
-
direction: "desc",
|
|
73463
|
-
expr: sortTimestampSortExpr,
|
|
73464
|
-
value: cursorSortTimestamp
|
|
73465
|
-
},
|
|
73466
|
-
{
|
|
73467
|
-
direction: "desc",
|
|
73468
|
-
expr: posts.id,
|
|
73469
|
-
value: cursorPost.id
|
|
73470
|
-
}
|
|
73471
|
-
]));
|
|
73472
|
-
case "newest": return buildLexicographicCursorCondition(withPinnedSortKey([{
|
|
73473
|
-
direction: "desc",
|
|
73474
|
-
expr: sortTimestampSortExpr,
|
|
73475
|
-
value: cursorSortTimestamp
|
|
73476
|
-
}, {
|
|
73477
|
-
direction: "desc",
|
|
73478
|
-
expr: posts.id,
|
|
73479
|
-
value: cursorPost.id
|
|
73480
|
-
}]));
|
|
73481
|
-
}
|
|
74292
|
+
/** Rows strictly after `values` in the order `keys` describe. */ function buildListKeysetCondition(keys, values) {
|
|
74293
|
+
const [first, ...rest] = keys.map((key, index) => {
|
|
74294
|
+
const value = values[index];
|
|
74295
|
+
if (value === void 0) throw new Error(`Cursor holds no value for sort key ${index}`);
|
|
74296
|
+
return {
|
|
74297
|
+
direction: key.direction,
|
|
74298
|
+
expr: key.expr,
|
|
74299
|
+
value
|
|
74300
|
+
};
|
|
74301
|
+
});
|
|
74302
|
+
if (!first) throw new Error("A list has at least one sort key");
|
|
74303
|
+
return buildLexicographicCursorCondition([first, ...rest]);
|
|
74304
|
+
}
|
|
74305
|
+
/**
|
|
74306
|
+
* The position a cursor names, as the tuple of sort-key values after which
|
|
74307
|
+
* the page starts.
|
|
74308
|
+
*
|
|
74309
|
+
* A bare post ID, the cursor earlier releases returned, is looked up — but
|
|
74310
|
+
* only among Posts the caller could have been shown: the request's status,
|
|
74311
|
+
* and nothing private when the request excludes it. A deleted Post, a draft,
|
|
74312
|
+
* and a private Post all get the same rejection, so the lookup can't be used
|
|
74313
|
+
* to learn whether a Post exists or when it was published. Its values come
|
|
74314
|
+
* from the same key expressions as the ORDER BY.
|
|
74315
|
+
*/ async function resolveListCursor(cursor, sort, keys, filters) {
|
|
74316
|
+
if (!isLegacyPostListCursor(cursor)) return decodePostListCursor(cursor, {
|
|
74317
|
+
mode: listSortMode(sort),
|
|
74318
|
+
kinds: keys.map((key) => key.kind)
|
|
74319
|
+
});
|
|
74320
|
+
const row = (await db.select(listSortKeyFields(keys)).from(posts).where(and(eq(posts.siteId, siteId), eq(posts.id, cursor), ...buildReaderVisibilityConditions(posts, siteId, {
|
|
74321
|
+
status: filters.status,
|
|
74322
|
+
excludePrivate: filters.excludePrivate
|
|
74323
|
+
}))).limit(1))[0];
|
|
74324
|
+
if (!row) throw new ValidationError(MISSING_LEGACY_CURSOR_MESSAGE);
|
|
74325
|
+
return readListSortKeyValues(keys, row);
|
|
73482
74326
|
}
|
|
73483
74327
|
function toPost(row, slug, visibility) {
|
|
73484
74328
|
return {
|
|
@@ -73610,6 +74454,10 @@ function createPostService(db, config, siteId, paths, databaseSchema = sqliteSch
|
|
|
73610
74454
|
)`);
|
|
73611
74455
|
if (options?.hasRating) conditions.push(isNotNull(posts.rating));
|
|
73612
74456
|
if (options?.threadIds !== void 0) conditions.push(inArray(posts.threadId, options.threadIds));
|
|
74457
|
+
if (options?.rootFilters) conditions.push(inArray(posts.threadId, db.select({ id: posts.id }).from(posts).where(and(...buildFilterConditions({
|
|
74458
|
+
...options.rootFilters,
|
|
74459
|
+
excludeReplies: true
|
|
74460
|
+
})))));
|
|
73613
74461
|
return conditions;
|
|
73614
74462
|
}
|
|
73615
74463
|
/**
|
|
@@ -73633,31 +74481,99 @@ function createPostService(db, config, siteId, paths, databaseSchema = sqliteSch
|
|
|
73633
74481
|
)
|
|
73634
74482
|
)`.as(alias);
|
|
73635
74483
|
}
|
|
73636
|
-
|
|
74484
|
+
/**
|
|
74485
|
+
* The sort mode a collection cursor records. Distinct from every
|
|
74486
|
+
* {@link listSortMode}: a collection orders Threads by its own pins, so a
|
|
74487
|
+
* position in `list()` never resumes a collection or the other way round.
|
|
74488
|
+
*/ function collectionThreadSortMode(order) {
|
|
74489
|
+
return `collection:${order}`;
|
|
74490
|
+
}
|
|
74491
|
+
/**
|
|
74492
|
+
* A collection's matching Threads, one row per Thread with its sort keys as
|
|
74493
|
+
* columns, those keys in ORDER BY order, and the sort mode a cursor taken
|
|
74494
|
+
* in that order records — the one definition of how a collection orders
|
|
74495
|
+
* its Threads. `options.sortOrder` defaults to `newest`.
|
|
74496
|
+
*
|
|
74497
|
+
* The keys are aggregates over the Thread's matching members, computed once
|
|
74498
|
+
* in the grouped subquery; the ORDER BY, the keyset condition that resumes
|
|
74499
|
+
* after a cursor, and the values a cursor records all read the subquery's
|
|
74500
|
+
* columns through `keys`. As in {@link listSortKeys}, no key is ever NULL,
|
|
74501
|
+
* so SQLite and Postgres order and compare alike: a missing pin, rating, or
|
|
74502
|
+
* publication time folds to -1, and Thread activity falls back to the
|
|
74503
|
+
* member's own times.
|
|
74504
|
+
*
|
|
74505
|
+
* - `newest`: pinned in the collection first, then Thread activity, newest
|
|
74506
|
+
* first.
|
|
74507
|
+
* - `oldest`: pinned first, then the Thread's first publication, oldest
|
|
74508
|
+
* first. A new reply doesn't move a Thread.
|
|
74509
|
+
* - `rating_desc`: pinned first, then the Thread's highest rating (unrated
|
|
74510
|
+
* last, since ratings run 1 to 5), then Thread activity.
|
|
74511
|
+
*
|
|
74512
|
+
* The Thread root ID ends every order, so no two rows share a tuple.
|
|
74513
|
+
*/ function buildCollectionThreadSort(collectionIds, options) {
|
|
74514
|
+
const order = options.sortOrder ?? "newest";
|
|
73637
74515
|
const conditions = [...buildThreadRootPageConditions(options), buildCollectionMembershipCondition(collectionIds)];
|
|
73638
|
-
const
|
|
73639
|
-
|
|
73640
|
-
|
|
73641
|
-
|
|
73642
|
-
|
|
73643
|
-
|
|
73644
|
-
|
|
73645
|
-
|
|
73646
|
-
|
|
73647
|
-
|
|
73648
|
-
|
|
74516
|
+
const sortedThreads = db.select({
|
|
74517
|
+
threadId: posts.threadId,
|
|
74518
|
+
collectionPinnedAt: sql`MAX(coalesce(${threadCollections.pinnedAt}, -1))`.as("collection_pinned_at"),
|
|
74519
|
+
firstPublishedAt: sql`coalesce(MIN(${posts.publishedAt}), -1)`.as("first_published_at"),
|
|
74520
|
+
threadActivityAt: buildCollectionThreadActivityExpr("thread_activity_at"),
|
|
74521
|
+
ratingValue: sql`MAX(coalesce(${posts.rating}, -1))`.as("rating_value")
|
|
74522
|
+
}).from(posts).innerJoin(threadCollections, and(eq(threadCollections.siteId, posts.siteId), eq(threadCollections.threadId, posts.threadId))).where(and(...conditions)).groupBy(posts.threadId).as("collection_thread_sort");
|
|
74523
|
+
const numberKey = (column, direction) => ({
|
|
74524
|
+
expr: sql`${column}`.mapWith(Number),
|
|
74525
|
+
direction,
|
|
74526
|
+
kind: "number"
|
|
74527
|
+
});
|
|
74528
|
+
const idKey = (direction) => ({
|
|
74529
|
+
expr: sql`${sortedThreads.threadId}`,
|
|
74530
|
+
direction,
|
|
74531
|
+
kind: "id"
|
|
74532
|
+
});
|
|
74533
|
+
const pinned = numberKey(sortedThreads.collectionPinnedAt, "desc");
|
|
74534
|
+
const activity = numberKey(sortedThreads.threadActivityAt, "desc");
|
|
73649
74535
|
return {
|
|
73650
|
-
|
|
73651
|
-
|
|
73652
|
-
|
|
73653
|
-
|
|
73654
|
-
|
|
73655
|
-
|
|
73656
|
-
|
|
73657
|
-
|
|
73658
|
-
|
|
74536
|
+
sortedThreads,
|
|
74537
|
+
keys: (() => {
|
|
74538
|
+
switch (order) {
|
|
74539
|
+
case "oldest": return [
|
|
74540
|
+
pinned,
|
|
74541
|
+
numberKey(sortedThreads.firstPublishedAt, "asc"),
|
|
74542
|
+
idKey("asc")
|
|
74543
|
+
];
|
|
74544
|
+
case "rating_desc": return [
|
|
74545
|
+
pinned,
|
|
74546
|
+
numberKey(sortedThreads.ratingValue, "desc"),
|
|
74547
|
+
activity,
|
|
74548
|
+
idKey("desc")
|
|
74549
|
+
];
|
|
74550
|
+
case "newest": return [
|
|
74551
|
+
pinned,
|
|
74552
|
+
activity,
|
|
74553
|
+
idKey("desc")
|
|
74554
|
+
];
|
|
74555
|
+
}
|
|
74556
|
+
})(),
|
|
74557
|
+
mode: collectionThreadSortMode(order)
|
|
73659
74558
|
};
|
|
73660
74559
|
}
|
|
74560
|
+
/**
|
|
74561
|
+
* The position a collection cursor names, as the tuple of sort-key values
|
|
74562
|
+
* after which the page starts.
|
|
74563
|
+
*
|
|
74564
|
+
* A bare root ID, the cursor earlier releases returned, is looked up in the
|
|
74565
|
+
* request's own `sortedThreads`, so only among Threads this request could
|
|
74566
|
+
* list. A Thread that is gone, private, a draft, or no longer in the
|
|
74567
|
+
* collection gets the same rejection as an ID that never existed.
|
|
74568
|
+
*/ async function resolveCollectionThreadCursor(cursor, sort) {
|
|
74569
|
+
if (!isLegacyPostListCursor(cursor)) return decodePostListCursor(cursor, {
|
|
74570
|
+
mode: sort.mode,
|
|
74571
|
+
kinds: sort.keys.map((key) => key.kind)
|
|
74572
|
+
});
|
|
74573
|
+
const row = (await db.select(listSortKeyFields(sort.keys)).from(sort.sortedThreads).where(eq(sort.sortedThreads.threadId, cursor)).limit(1))[0];
|
|
74574
|
+
if (!row) throw new ValidationError(MISSING_LEGACY_CURSOR_MESSAGE);
|
|
74575
|
+
return readListSortKeyValues(sort.keys, row);
|
|
74576
|
+
}
|
|
73661
74577
|
function isMediaAttachmentInput(attachment) {
|
|
73662
74578
|
return attachment.type === "media";
|
|
73663
74579
|
}
|
|
@@ -73789,52 +74705,29 @@ function createPostService(db, config, siteId, paths, databaseSchema = sqliteSch
|
|
|
73789
74705
|
return isSlugAvailableForPost(slug, excludePostId);
|
|
73790
74706
|
},
|
|
73791
74707
|
async list(filters = {}) {
|
|
74708
|
+
const keys = listSortKeys(resolveListSort(filters), filters.status);
|
|
73792
74709
|
const conditions = buildFilterConditions(filters);
|
|
73793
|
-
|
|
73794
|
-
if (filters.cursor && !cursorCondition) return [];
|
|
73795
|
-
const sortTimestamp = buildSortTimestampExpr(filters);
|
|
73796
|
-
if (cursorCondition) conditions.push(cursorCondition);
|
|
73797
|
-
const ratingPresence = sql`CASE
|
|
73798
|
-
WHEN ${posts.rating} IS NULL THEN 0
|
|
73799
|
-
ELSE 1
|
|
73800
|
-
END`;
|
|
73801
|
-
const pinnedSortExpr = sql`coalesce(${posts.pinnedAt}, -1)`;
|
|
73802
|
-
const featuredPublishedSortExpr = sql`coalesce(
|
|
73803
|
-
${posts.publishedAt}, ${posts.createdAt}, -1
|
|
73804
|
-
)`;
|
|
73805
|
-
const sortTimestampSortExpr = sql`coalesce(${sortTimestamp}, -1)`;
|
|
73806
|
-
const pinnedOrder = filters.ignorePinnedSort ? [] : [desc(pinnedSortExpr)];
|
|
73807
|
-
const baseQuery = db.select().from(posts).where(conditions.length > 0 ? and(...conditions) : void 0).limit(filters.limit ?? 100);
|
|
73808
|
-
const buildOrderBy = () => {
|
|
73809
|
-
if (filters.featured) return [
|
|
73810
|
-
...pinnedOrder,
|
|
73811
|
-
desc(featuredPublishedSortExpr),
|
|
73812
|
-
desc(posts.id)
|
|
73813
|
-
];
|
|
73814
|
-
switch (filters.sortOrder ?? "newest") {
|
|
73815
|
-
case "oldest": return [
|
|
73816
|
-
...pinnedOrder,
|
|
73817
|
-
asc(sortTimestampSortExpr),
|
|
73818
|
-
asc(posts.id)
|
|
73819
|
-
];
|
|
73820
|
-
case "rating_desc": return [
|
|
73821
|
-
...pinnedOrder,
|
|
73822
|
-
desc(ratingPresence),
|
|
73823
|
-
desc(posts.rating),
|
|
73824
|
-
desc(sortTimestampSortExpr),
|
|
73825
|
-
desc(posts.id)
|
|
73826
|
-
];
|
|
73827
|
-
case "newest": return [
|
|
73828
|
-
...pinnedOrder,
|
|
73829
|
-
desc(sortTimestampSortExpr),
|
|
73830
|
-
desc(posts.id)
|
|
73831
|
-
];
|
|
73832
|
-
}
|
|
73833
|
-
};
|
|
73834
|
-
let query = baseQuery.orderBy(...buildOrderBy());
|
|
74710
|
+
let query = db.select().from(posts).where(conditions.length > 0 ? and(...conditions) : void 0).orderBy(...listOrderBy(keys)).limit(filters.limit ?? 100);
|
|
73835
74711
|
if (filters.offset !== void 0) query = query.offset(filters.offset);
|
|
73836
74712
|
return hydratePosts(await query);
|
|
73837
74713
|
},
|
|
74714
|
+
async listPage(filters, { cursor, limit }) {
|
|
74715
|
+
const sort = resolveListSort(filters);
|
|
74716
|
+
const keys = listSortKeys(sort, filters.status);
|
|
74717
|
+
const conditions = buildFilterConditions(filters);
|
|
74718
|
+
if (cursor) conditions.push(buildListKeysetCondition(keys, await resolveListCursor(cursor, sort, keys, filters)));
|
|
74719
|
+
const rows = await db.select({
|
|
74720
|
+
post: posts,
|
|
74721
|
+
sortKey: listSortKeyFields(keys)
|
|
74722
|
+
}).from(posts).where(conditions.length > 0 ? and(...conditions) : void 0).orderBy(...listOrderBy(keys)).limit(limit + 1);
|
|
74723
|
+
const pageRows = rows.slice(0, limit);
|
|
74724
|
+
const lastRow = pageRows[pageRows.length - 1];
|
|
74725
|
+
const nextCursor = rows.length > limit && lastRow ? encodePostListCursor(listSortMode(sort), readListSortKeyValues(keys, lastRow.sortKey)) : null;
|
|
74726
|
+
return {
|
|
74727
|
+
posts: await hydratePosts(pageRows.map((row) => row.post)),
|
|
74728
|
+
nextCursor
|
|
74729
|
+
};
|
|
74730
|
+
},
|
|
73838
74731
|
async listForSitemap({ afterId, limit }) {
|
|
73839
74732
|
const conditions = buildFilterConditions({
|
|
73840
74733
|
status: "published",
|
|
@@ -74524,6 +75417,46 @@ function createPostService(db, config, siteId, paths, databaseSchema = sqliteSch
|
|
|
74524
75417
|
async getThread(rootId) {
|
|
74525
75418
|
return hydratePosts(await db.select().from(posts).where(and(eq(posts.siteId, siteId), eq(posts.threadId, rootId))).orderBy(...threadOrder()));
|
|
74526
75419
|
},
|
|
75420
|
+
async listThreadPostsPage(threadId, options, { cursor, limit }) {
|
|
75421
|
+
const keys = threadSortKeys();
|
|
75422
|
+
const conditions = [
|
|
75423
|
+
eq(posts.siteId, siteId),
|
|
75424
|
+
eq(posts.threadId, threadId),
|
|
75425
|
+
eq(posts.status, options.status ?? "published")
|
|
75426
|
+
];
|
|
75427
|
+
if (cursor) {
|
|
75428
|
+
let values;
|
|
75429
|
+
if (isLegacyPostListCursor(cursor)) {
|
|
75430
|
+
const row = (await db.select(listSortKeyFields(keys)).from(posts).where(and(...conditions, eq(posts.id, cursor))).limit(1))[0];
|
|
75431
|
+
if (!row) throw new ValidationError(MISSING_LEGACY_CURSOR_MESSAGE);
|
|
75432
|
+
values = readListSortKeyValues(keys, row);
|
|
75433
|
+
} else values = decodePostListCursor(cursor, {
|
|
75434
|
+
mode: THREAD_POSTS_SORT_MODE,
|
|
75435
|
+
kinds: keys.map((key) => key.kind)
|
|
75436
|
+
});
|
|
75437
|
+
conditions.push(buildListKeysetCondition(keys, values));
|
|
75438
|
+
}
|
|
75439
|
+
const rows = await db.select({
|
|
75440
|
+
post: posts,
|
|
75441
|
+
sortKey: listSortKeyFields(keys)
|
|
75442
|
+
}).from(posts).where(and(...conditions)).orderBy(...listOrderBy(keys)).limit(limit + 1);
|
|
75443
|
+
const pageRows = rows.slice(0, limit);
|
|
75444
|
+
const lastRow = pageRows[pageRows.length - 1];
|
|
75445
|
+
return {
|
|
75446
|
+
posts: await hydratePosts(pageRows.map((row) => row.post)),
|
|
75447
|
+
nextCursor: rows.length > limit && lastRow ? encodePostListCursor(THREAD_POSTS_SORT_MODE, readListSortKeyValues(keys, lastRow.sortKey)) : null
|
|
75448
|
+
};
|
|
75449
|
+
},
|
|
75450
|
+
async countThreadPosts(threadIds) {
|
|
75451
|
+
const counts = /* @__PURE__ */ new Map();
|
|
75452
|
+
if (threadIds.length === 0) return counts;
|
|
75453
|
+
const rows = await batchQueryRows([...new Set(threadIds)], (chunk) => db.select({
|
|
75454
|
+
threadId: posts.threadId,
|
|
75455
|
+
count: sql`CAST(count(*) AS INTEGER)`.as("count")
|
|
75456
|
+
}).from(posts).where(and(eq(posts.siteId, siteId), inArray(posts.threadId, chunk), eq(posts.status, "published"))).groupBy(posts.threadId));
|
|
75457
|
+
for (const row of rows) counts.set(row.threadId, row.count);
|
|
75458
|
+
return counts;
|
|
75459
|
+
},
|
|
74527
75460
|
async getThreadPosition(postId) {
|
|
74528
75461
|
const target = (await db.select({
|
|
74529
75462
|
replyToId: posts.replyToId,
|
|
@@ -74818,28 +75751,30 @@ function createPostService(db, config, siteId, paths, databaseSchema = sqliteSch
|
|
|
74818
75751
|
},
|
|
74819
75752
|
async getThreadTimelineContext(rootIds) {
|
|
74820
75753
|
if (rootIds.length === 0) return /* @__PURE__ */ new Map();
|
|
74821
|
-
const
|
|
74822
|
-
|
|
74823
|
-
|
|
74824
|
-
|
|
75754
|
+
const contextRows = await batchQueryRows([...new Set(rootIds)], (chunk) => {
|
|
75755
|
+
const rankedReplies = db.select({
|
|
75756
|
+
id: posts.id,
|
|
75757
|
+
threadId: posts.threadId,
|
|
75758
|
+
firstReplyRank: sql`CAST(ROW_NUMBER() OVER (
|
|
74825
75759
|
PARTITION BY ${posts.threadId}
|
|
74826
75760
|
ORDER BY ${sql.join(threadOrder(), sql`, `)}
|
|
74827
75761
|
) AS INTEGER)`.as("first_reply_rank"),
|
|
74828
|
-
|
|
75762
|
+
latestReplyRank: sql`CAST(ROW_NUMBER() OVER (
|
|
74829
75763
|
PARTITION BY ${posts.threadId}
|
|
74830
75764
|
ORDER BY ${sql.join(threadOrder("desc"), sql`, `)}
|
|
74831
75765
|
) AS INTEGER)`.as("latest_reply_rank"),
|
|
74832
|
-
|
|
75766
|
+
totalReplyCount: sql`CAST(COUNT(*) OVER (
|
|
74833
75767
|
PARTITION BY ${posts.threadId}
|
|
74834
75768
|
) AS INTEGER)`.as("total_reply_count")
|
|
74835
|
-
|
|
74836
|
-
|
|
74837
|
-
|
|
74838
|
-
|
|
74839
|
-
|
|
74840
|
-
|
|
74841
|
-
|
|
74842
|
-
|
|
75769
|
+
}).from(posts).where(and(eq(posts.siteId, siteId), inArray(posts.threadId, chunk), eq(posts.status, "published"), isNotNull(posts.replyToId))).as("ranked_replies");
|
|
75770
|
+
return db.select({
|
|
75771
|
+
threadId: rankedReplies.threadId,
|
|
75772
|
+
id: rankedReplies.id,
|
|
75773
|
+
firstReplyRank: rankedReplies.firstReplyRank,
|
|
75774
|
+
latestReplyRank: rankedReplies.latestReplyRank,
|
|
75775
|
+
totalReplyCount: rankedReplies.totalReplyCount
|
|
75776
|
+
}).from(rankedReplies).where(or(lte(rankedReplies.firstReplyRank, 3), lte(rankedReplies.latestReplyRank, 3)));
|
|
75777
|
+
});
|
|
74843
75778
|
const hydratedPosts = await hydratePostsById(contextRows.map((row) => row.id));
|
|
74844
75779
|
const contextByThreadId = /* @__PURE__ */ new Map();
|
|
74845
75780
|
for (const row of contextRows) {
|
|
@@ -74944,77 +75879,32 @@ function createPostService(db, config, siteId, paths, databaseSchema = sqliteSch
|
|
|
74944
75879
|
return this.listCollectionThreadRootIdsForCollections([collectionId], options);
|
|
74945
75880
|
},
|
|
74946
75881
|
async listCollectionThreadRootIdsForCollections(collectionIds, options = {}) {
|
|
74947
|
-
const {
|
|
74948
|
-
let
|
|
74949
|
-
if (options.cursor) {
|
|
74950
|
-
const cursorRow = (await db.select().from(sortedThreads).where(eq(sortedThreads.threadId, options.cursor)).limit(1))[0];
|
|
74951
|
-
if (!cursorRow) return [];
|
|
74952
|
-
const pinnedKey = {
|
|
74953
|
-
direction: "desc",
|
|
74954
|
-
expr: sortedThreads.collectionPinnedAt,
|
|
74955
|
-
value: cursorRow.collectionPinnedAt
|
|
74956
|
-
};
|
|
74957
|
-
cursorCondition = sortOrder === "oldest" ? buildLexicographicCursorCondition([
|
|
74958
|
-
pinnedKey,
|
|
74959
|
-
{
|
|
74960
|
-
direction: "asc",
|
|
74961
|
-
expr: sortedThreads.publishedAt,
|
|
74962
|
-
value: cursorRow.publishedAt
|
|
74963
|
-
},
|
|
74964
|
-
{
|
|
74965
|
-
direction: "asc",
|
|
74966
|
-
expr: sortedThreads.threadId,
|
|
74967
|
-
value: cursorRow.threadId
|
|
74968
|
-
}
|
|
74969
|
-
]) : sortOrder === "rating_desc" ? buildLexicographicCursorCondition([
|
|
74970
|
-
pinnedKey,
|
|
74971
|
-
{
|
|
74972
|
-
direction: "desc",
|
|
74973
|
-
expr: sortedThreads.ratingPresence,
|
|
74974
|
-
value: cursorRow.ratingPresence
|
|
74975
|
-
},
|
|
74976
|
-
{
|
|
74977
|
-
direction: "desc",
|
|
74978
|
-
expr: sortedThreads.ratingValue,
|
|
74979
|
-
value: cursorRow.ratingValue
|
|
74980
|
-
},
|
|
74981
|
-
{
|
|
74982
|
-
direction: "desc",
|
|
74983
|
-
expr: sortedThreads.threadActivityAt,
|
|
74984
|
-
value: cursorRow.threadActivityAt
|
|
74985
|
-
},
|
|
74986
|
-
{
|
|
74987
|
-
direction: "desc",
|
|
74988
|
-
expr: sortedThreads.threadId,
|
|
74989
|
-
value: cursorRow.threadId
|
|
74990
|
-
}
|
|
74991
|
-
]) : buildLexicographicCursorCondition([
|
|
74992
|
-
pinnedKey,
|
|
74993
|
-
{
|
|
74994
|
-
direction: "desc",
|
|
74995
|
-
expr: sortedThreads.threadActivityAt,
|
|
74996
|
-
value: cursorRow.threadActivityAt
|
|
74997
|
-
},
|
|
74998
|
-
{
|
|
74999
|
-
direction: "desc",
|
|
75000
|
-
expr: sortedThreads.threadId,
|
|
75001
|
-
value: cursorRow.threadId
|
|
75002
|
-
}
|
|
75003
|
-
]);
|
|
75004
|
-
}
|
|
75005
|
-
const baseQuery = db.select().from(sortedThreads).where(cursorCondition);
|
|
75006
|
-
let query = sortOrder === "oldest" ? baseQuery.orderBy(desc(sortedThreads.collectionPinnedAt), asc(sortedThreads.publishedAt), asc(sortedThreads.threadId)) : sortOrder === "rating_desc" ? baseQuery.orderBy(desc(sortedThreads.collectionPinnedAt), desc(sortedThreads.ratingPresence), desc(sortedThreads.ratingValue), desc(sortedThreads.threadActivityAt), desc(sortedThreads.threadId)) : baseQuery.orderBy(desc(sortedThreads.collectionPinnedAt), desc(sortedThreads.threadActivityAt), desc(sortedThreads.threadId));
|
|
75882
|
+
const { sortedThreads, keys } = buildCollectionThreadSort(collectionIds, options);
|
|
75883
|
+
let query = db.select({ threadId: sortedThreads.threadId }).from(sortedThreads).orderBy(...listOrderBy(keys));
|
|
75007
75884
|
if (options.limit !== void 0) query = query.limit(options.limit);
|
|
75008
75885
|
if (options.offset !== void 0) query = query.offset(options.offset);
|
|
75009
75886
|
return (await query).map((row) => row.threadId);
|
|
75010
75887
|
},
|
|
75011
|
-
async
|
|
75012
|
-
const
|
|
75888
|
+
async listCollectionThreadRootPage(collectionIds, options, { cursor, limit }) {
|
|
75889
|
+
const sort = buildCollectionThreadSort(collectionIds, options);
|
|
75890
|
+
const { sortedThreads, keys } = sort;
|
|
75891
|
+
const after = cursor ? buildListKeysetCondition(keys, await resolveCollectionThreadCursor(cursor, sort)) : void 0;
|
|
75892
|
+
const rows = await db.select({
|
|
75893
|
+
threadId: sortedThreads.threadId,
|
|
75894
|
+
sortKey: listSortKeyFields(keys)
|
|
75895
|
+
}).from(sortedThreads).where(after).orderBy(...listOrderBy(keys)).limit(limit + 1);
|
|
75896
|
+
const pageRows = rows.slice(0, limit);
|
|
75897
|
+
const lastRow = pageRows[pageRows.length - 1];
|
|
75898
|
+
const nextCursor = rows.length > limit && lastRow ? encodePostListCursor(sort.mode, readListSortKeyValues(keys, lastRow.sortKey)) : null;
|
|
75899
|
+
const rootIds = pageRows.map((row) => row.threadId);
|
|
75013
75900
|
const rootsById = await hydratePostsById(rootIds);
|
|
75014
|
-
return
|
|
75015
|
-
|
|
75016
|
-
|
|
75017
|
-
|
|
75901
|
+
return {
|
|
75902
|
+
posts: rootIds.flatMap((rootId) => {
|
|
75903
|
+
const root = rootsById.get(rootId);
|
|
75904
|
+
return root ? [root] : [];
|
|
75905
|
+
}),
|
|
75906
|
+
nextCursor
|
|
75907
|
+
};
|
|
75018
75908
|
},
|
|
75019
75909
|
async listCollectionFeedEntries(collectionId, options = {}) {
|
|
75020
75910
|
return this.listCollectionFeedEntriesForCollections([collectionId], options);
|
|
@@ -76984,6 +77874,98 @@ internalUploadsRoutes.post("/cleanup", requireInternalAdminApi(), async (c) => {
|
|
|
76984
77874
|
return c.json(result);
|
|
76985
77875
|
});
|
|
76986
77876
|
//#endregion
|
|
77877
|
+
//#region src/middleware/deprecation.ts
|
|
77878
|
+
/**
|
|
77879
|
+
* Deprecated API endpoints.
|
|
77880
|
+
*
|
|
77881
|
+
* A deprecated endpoint keeps answering exactly as before until the major
|
|
77882
|
+
* release that removes it, and says so on every response, errors included:
|
|
77883
|
+
* `Deprecation` (RFC 9745) carries when it was deprecated, and `Link` with
|
|
77884
|
+
* `rel="successor-version"` names what replaces it. The docs and the release
|
|
77885
|
+
* notes say the same thing in words.
|
|
77886
|
+
*/
|
|
77887
|
+
/**
|
|
77888
|
+
* When 0.9 deprecated the Thread lists that `/api/public/threads` replaces:
|
|
77889
|
+
* the `GET /api/public/posts` list and `GET /api/public/archive`.
|
|
77890
|
+
*/ var THREAD_LIST_DEPRECATED_AT = Date.UTC(2026, 8, 27) / 1e3;
|
|
77891
|
+
/**
|
|
77892
|
+
* Mark every response of a route as deprecated.
|
|
77893
|
+
*
|
|
77894
|
+
* @param deprecatedAt - Unix seconds the endpoint was deprecated
|
|
77895
|
+
* @param successor - The replacement, as a site path (the site path prefix is
|
|
77896
|
+
* added)
|
|
77897
|
+
* @returns Hono middleware that sets `Deprecation` and `Link`
|
|
77898
|
+
* @example
|
|
77899
|
+
* ```ts
|
|
77900
|
+
* routes.get("/", deprecated(THREAD_LIST_DEPRECATED_AT, "/api/public/threads"), handler);
|
|
77901
|
+
* ```
|
|
77902
|
+
*/ function deprecated(deprecatedAt, successor) {
|
|
77903
|
+
return async (c, next) => {
|
|
77904
|
+
await next();
|
|
77905
|
+
c.header("Deprecation", `@${deprecatedAt}`);
|
|
77906
|
+
c.header("Link", `<${toPublicPath(successor, c.var.appConfig.sitePathPrefix)}>; rel="successor-version"`);
|
|
77907
|
+
};
|
|
77908
|
+
}
|
|
77909
|
+
//#endregion
|
|
77910
|
+
//#region src/routes/api/public/archive.ts
|
|
77911
|
+
var publicArchiveApiRoutes = new Hono();
|
|
77912
|
+
publicArchiveApiRoutes.use("*", requirePublicApiEnabled());
|
|
77913
|
+
/**
|
|
77914
|
+
* The endpoint's own parameters — everything that is not a filter dimension.
|
|
77915
|
+
*
|
|
77916
|
+
* The dimensions themselves are read by the shared registry, so this endpoint
|
|
77917
|
+
* cannot drift from the page it mirrors. They are listed here only so the strict
|
|
77918
|
+
* parser can tell them apart from a parameter nobody understands.
|
|
77919
|
+
*/ var ListPublicArchiveQuerySchema = z.object({
|
|
77920
|
+
/** Restrict to one content language. See `/api/public/posts`. */ lang: ContentLanguageSchema.optional(),
|
|
77921
|
+
cursor: z.string().optional(),
|
|
77922
|
+
limit: z.coerce.number().int().min(1).max(100).optional().default(20),
|
|
77923
|
+
content: z.enum(["markdown"]).optional()
|
|
77924
|
+
});
|
|
77925
|
+
var ENDPOINT_PARAMS = [
|
|
77926
|
+
"lang",
|
|
77927
|
+
"cursor",
|
|
77928
|
+
"limit",
|
|
77929
|
+
"content"
|
|
77930
|
+
];
|
|
77931
|
+
var INVALID_VISIBILITY_MESSAGE = "Invalid visibility value. Allowed: " + PUBLIC_ARCHIVE_VISIBILITIES.map((value) => value === "latest_hidden" ? "hidden" : value).join(", ");
|
|
77932
|
+
/**
|
|
77933
|
+
* Deprecated in 0.9 for `GET /api/public/threads?visibility=any&sort=published`,
|
|
77934
|
+
* which takes the same filters. Answers as it always has until 1.0.1 removes it.
|
|
77935
|
+
*/ publicArchiveApiRoutes.get("/", deprecated(THREAD_LIST_DEPRECATED_AT, "/api/public/threads?visibility=any&sort=published"), async (c) => {
|
|
77936
|
+
const { lang, cursor, limit, content } = parseValidated(ListPublicArchiveQuerySchema, c.req.query());
|
|
77937
|
+
const read = (key) => c.req.query(key);
|
|
77938
|
+
const ctx = { collections: readCollectionSlugs(read).length > 0 ? buildCollectionVocabulary(await c.var.services.collections.list()) : EMPTY_COLLECTION_VOCABULARY };
|
|
77939
|
+
const parsed = parsePostFilterSelectionStrict(read, Object.keys(c.req.query()), ctx, { allow: ENDPOINT_PARAMS });
|
|
77940
|
+
if (!parsed.ok && parsed.issues.every((issue) => issue.param === "collection")) return c.json({
|
|
77941
|
+
posts: [],
|
|
77942
|
+
nextCursor: null
|
|
77943
|
+
});
|
|
77944
|
+
if (!parsed.ok) {
|
|
77945
|
+
const first = parsed.issues[0];
|
|
77946
|
+
throw new ValidationError(first?.message ?? "Validation failed");
|
|
77947
|
+
}
|
|
77948
|
+
const visibility = parsed.selection.visibility;
|
|
77949
|
+
if (visibility !== void 0 && !PUBLIC_ARCHIVE_VISIBILITIES.includes(visibility)) throw new ValidationError(INVALID_VISIBILITY_MESSAGE);
|
|
77950
|
+
const { posts, nextCursor } = await c.var.services.posts.listPage({
|
|
77951
|
+
lang,
|
|
77952
|
+
status: "published",
|
|
77953
|
+
excludePrivate: true,
|
|
77954
|
+
excludeLatestHidden: false,
|
|
77955
|
+
excludeReplies: true,
|
|
77956
|
+
...toPostFilters(parsed.selection, { yearAxis: "published" }),
|
|
77957
|
+
sortBy: "published",
|
|
77958
|
+
ignorePinnedSort: true
|
|
77959
|
+
}, {
|
|
77960
|
+
cursor,
|
|
77961
|
+
limit
|
|
77962
|
+
});
|
|
77963
|
+
return c.json({
|
|
77964
|
+
posts: await loadPublicPostResponses(c.var, posts, { content }),
|
|
77965
|
+
nextCursor
|
|
77966
|
+
});
|
|
77967
|
+
});
|
|
77968
|
+
//#endregion
|
|
76987
77969
|
//#region src/routes/api/public/posts.ts
|
|
76988
77970
|
var publicPostsApiRoutes = new Hono();
|
|
76989
77971
|
publicPostsApiRoutes.use("*", requirePublicApiEnabled());
|
|
@@ -77000,81 +77982,14 @@ var ListPublicPostsQuerySchema = z.object({
|
|
|
77000
77982
|
content: z.enum(["markdown"]).optional()
|
|
77001
77983
|
});
|
|
77002
77984
|
var PublicPostContentQuerySchema = z.object({ content: z.enum(["markdown"]).optional() });
|
|
77003
|
-
/**
|
|
77004
|
-
* The public Markdown for a post, or null for a historical body that isn't
|
|
77005
|
-
* TipTap JSON. One unreadable row answers null and is logged, rather than
|
|
77006
|
-
* failing the whole listing; `bodyHtml` still falls back to stored HTML.
|
|
77007
|
-
*/ function toPublicBodyMarkdown(postId, body) {
|
|
77008
|
-
try {
|
|
77009
|
-
return tiptapJsonToMarkdown(body);
|
|
77010
|
-
} catch (error) {
|
|
77011
|
-
console.error(`Couldn't convert the body of post ${postId} to Markdown`, error);
|
|
77012
|
-
return null;
|
|
77013
|
-
}
|
|
77014
|
-
}
|
|
77015
77985
|
function isPublicDetailVisible(post) {
|
|
77016
77986
|
return post !== null && post.status === "published" && post.visibility !== "private";
|
|
77017
77987
|
}
|
|
77018
|
-
|
|
77019
|
-
|
|
77020
|
-
|
|
77021
|
-
|
|
77022
|
-
|
|
77023
|
-
quality: 80,
|
|
77024
|
-
format: "auto",
|
|
77025
|
-
fit: "scale-down"
|
|
77026
|
-
}) : null;
|
|
77027
|
-
const base = {
|
|
77028
|
-
id: post.id,
|
|
77029
|
-
format: post.format,
|
|
77030
|
-
status: "published",
|
|
77031
|
-
visibility: post.visibility,
|
|
77032
|
-
slug: post.slug,
|
|
77033
|
-
permalink: toPublicPath(`/${post.slug}`, sitePathPrefix),
|
|
77034
|
-
quoteText: post.quoteText,
|
|
77035
|
-
summary: post.summary,
|
|
77036
|
-
rating: post.rating,
|
|
77037
|
-
previewKind: post.previewKind,
|
|
77038
|
-
previewProvider: post.previewProvider,
|
|
77039
|
-
previewImageUrl,
|
|
77040
|
-
replyToId: post.replyToId,
|
|
77041
|
-
threadId: post.threadId,
|
|
77042
|
-
language: post.language,
|
|
77043
|
-
translationGroupId: post.translationGroupId,
|
|
77044
|
-
quietReply: post.quietReply,
|
|
77045
|
-
pinnedAt: post.pinnedAt,
|
|
77046
|
-
featuredAt: post.featuredAt,
|
|
77047
|
-
publishedAt: post.publishedAt,
|
|
77048
|
-
lastActivityAt: post.lastActivityAt,
|
|
77049
|
-
threadUpdatedAt: post.threadUpdatedAt,
|
|
77050
|
-
createdAt: post.createdAt,
|
|
77051
|
-
updatedAt: post.updatedAt,
|
|
77052
|
-
attachments: mediaList.map((media) => toApiAttachment(media, r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix)),
|
|
77053
|
-
collections: threadCollections.map((collection) => ({
|
|
77054
|
-
id: collection.id,
|
|
77055
|
-
slug: collection.slug,
|
|
77056
|
-
title: collection.title,
|
|
77057
|
-
url: toPublicPath(getCollectionPagePath(collection.slug), sitePathPrefix)
|
|
77058
|
-
}))
|
|
77059
|
-
};
|
|
77060
|
-
const contentFields = options?.content === "markdown" ? { bodyMarkdown: post.body ? toPublicBodyMarkdown(post.id, post.body) : null } : {
|
|
77061
|
-
bodyHtml: post.bodyHtml,
|
|
77062
|
-
bodyText: post.bodyText
|
|
77063
|
-
};
|
|
77064
|
-
if (post.format === "quote") return {
|
|
77065
|
-
...base,
|
|
77066
|
-
...contentFields,
|
|
77067
|
-
sourceName: post.title,
|
|
77068
|
-
sourceUrl: post.url
|
|
77069
|
-
};
|
|
77070
|
-
return {
|
|
77071
|
-
...base,
|
|
77072
|
-
...contentFields,
|
|
77073
|
-
title: post.title,
|
|
77074
|
-
url: post.url
|
|
77075
|
-
};
|
|
77076
|
-
}
|
|
77077
|
-
publicPostsApiRoutes.get("/", async (c) => {
|
|
77988
|
+
/**
|
|
77989
|
+
* Deprecated in 0.9 for `GET /api/public/threads`, which lists the same Thread
|
|
77990
|
+
* roots with the archive's filters and the homepage's defaults. Answers as it
|
|
77991
|
+
* always has until 1.0.1 removes it.
|
|
77992
|
+
*/ publicPostsApiRoutes.get("/", deprecated(THREAD_LIST_DEPRECATED_AT, "/api/public/threads"), async (c) => {
|
|
77078
77993
|
const { format, lang, collection, sort, cursor, limit, content } = parseValidated(ListPublicPostsQuerySchema, c.req.query());
|
|
77079
77994
|
let collectionIds;
|
|
77080
77995
|
let sortOrder;
|
|
@@ -77102,30 +78017,30 @@ publicPostsApiRoutes.get("/", async (c) => {
|
|
|
77102
78017
|
}, 2));
|
|
77103
78018
|
sortOrder = resolveCollectionSortOrder(sort, resolveCollectionSortOrder(void 0, requestedDefaultSort, showRatingSort), showRatingSort);
|
|
77104
78019
|
}
|
|
77105
|
-
const posts = collectionIds ? await c.var.services.posts.
|
|
78020
|
+
const { posts, nextCursor } = collectionIds ? await c.var.services.posts.listCollectionThreadRootPage(collectionIds, {
|
|
77106
78021
|
status: "published",
|
|
77107
78022
|
excludePrivate: true,
|
|
77108
78023
|
excludeLatestHidden: true,
|
|
77109
78024
|
rootFormat: format,
|
|
77110
78025
|
lang,
|
|
77111
|
-
sortOrder
|
|
77112
|
-
|
|
78026
|
+
sortOrder
|
|
78027
|
+
}, {
|
|
78028
|
+
cursor,
|
|
77113
78029
|
limit
|
|
77114
|
-
}) : await c.var.services.posts.
|
|
78030
|
+
}) : await c.var.services.posts.listPage({
|
|
77115
78031
|
format,
|
|
77116
78032
|
lang,
|
|
77117
78033
|
status: "published",
|
|
77118
|
-
cursor: cursor ?? void 0,
|
|
77119
|
-
limit,
|
|
77120
78034
|
excludePrivate: true,
|
|
77121
78035
|
excludeLatestHidden: true,
|
|
77122
78036
|
excludeReplies: true
|
|
78037
|
+
}, {
|
|
78038
|
+
cursor,
|
|
78039
|
+
limit
|
|
77123
78040
|
});
|
|
77124
|
-
const postIds = posts.map((post) => post.id);
|
|
77125
|
-
const [mediaMap, collectionsMap] = await Promise.all([c.var.services.media.getByPostIds(postIds), c.var.services.collections.getCollectionsByPostIds(postIds)]);
|
|
77126
78041
|
return c.json({
|
|
77127
|
-
posts:
|
|
77128
|
-
nextCursor
|
|
78042
|
+
posts: await loadPublicPostResponses(c.var, posts, { content }),
|
|
78043
|
+
nextCursor
|
|
77129
78044
|
});
|
|
77130
78045
|
});
|
|
77131
78046
|
publicPostsApiRoutes.get("/:slug", async (c) => {
|
|
@@ -77133,63 +78048,94 @@ publicPostsApiRoutes.get("/:slug", async (c) => {
|
|
|
77133
78048
|
const slug = c.req.param("slug");
|
|
77134
78049
|
const post = await c.var.services.posts.getBySlug(slug);
|
|
77135
78050
|
if (!isPublicDetailVisible(post)) throw new NotFoundError("Post");
|
|
77136
|
-
const [
|
|
77137
|
-
return c.json(
|
|
78051
|
+
const [response] = await loadPublicPostResponses(c.var, [post], { content });
|
|
78052
|
+
return c.json(response);
|
|
77138
78053
|
});
|
|
77139
78054
|
//#endregion
|
|
77140
|
-
//#region src/routes/api/public/
|
|
77141
|
-
|
|
77142
|
-
|
|
77143
|
-
|
|
77144
|
-
* The
|
|
77145
|
-
*
|
|
77146
|
-
*
|
|
77147
|
-
*
|
|
77148
|
-
|
|
77149
|
-
|
|
77150
|
-
|
|
78055
|
+
//#region src/routes/api/public/threads.ts
|
|
78056
|
+
/**
|
|
78057
|
+
* Public Threads API Routes
|
|
78058
|
+
*
|
|
78059
|
+
* The reader's view of Threads: what the site shows anyone, in the reading
|
|
78060
|
+
* view. A list left unfiltered is the homepage's — Threads hidden from Latest
|
|
78061
|
+
* left out, newest activity first, pins on top — and takes the archive's
|
|
78062
|
+
* filters to narrow or widen it.
|
|
78063
|
+
*/ var publicThreadsApiRoutes = new Hono();
|
|
78064
|
+
publicThreadsApiRoutes.use("*", requirePublicApiEnabled());
|
|
78065
|
+
var ContentSchema = z.enum(["markdown"]).optional();
|
|
78066
|
+
/** The list's own parameters; everything else is a filter dimension. */ var ListThreadsQuerySchema = z.object({
|
|
78067
|
+
lang: ContentLanguageSchema.optional(),
|
|
78068
|
+
sort: z.enum(THREAD_SORTS).optional(),
|
|
78069
|
+
include: z.string().optional(),
|
|
77151
78070
|
cursor: z.string().optional(),
|
|
77152
78071
|
limit: z.coerce.number().int().min(1).max(100).optional().default(20),
|
|
77153
|
-
content:
|
|
78072
|
+
content: ContentSchema
|
|
77154
78073
|
});
|
|
77155
|
-
var
|
|
78074
|
+
var LIST_PARAMS = [
|
|
77156
78075
|
"lang",
|
|
78076
|
+
"sort",
|
|
78077
|
+
"include",
|
|
77157
78078
|
"cursor",
|
|
77158
78079
|
"limit",
|
|
77159
78080
|
"content"
|
|
77160
78081
|
];
|
|
77161
|
-
var
|
|
77162
|
-
|
|
77163
|
-
|
|
77164
|
-
|
|
77165
|
-
|
|
77166
|
-
|
|
77167
|
-
|
|
77168
|
-
|
|
78082
|
+
var GetThreadQuerySchema = z.object({
|
|
78083
|
+
include: z.string().optional(),
|
|
78084
|
+
content: ContentSchema
|
|
78085
|
+
});
|
|
78086
|
+
var ListThreadPostsQuerySchema = z.object({
|
|
78087
|
+
cursor: z.string().optional(),
|
|
78088
|
+
limit: z.coerce.number().int().min(1).max(100).optional().default(100),
|
|
78089
|
+
content: ContentSchema
|
|
78090
|
+
});
|
|
78091
|
+
publicThreadsApiRoutes.get("/", async (c) => {
|
|
78092
|
+
const query = parseValidated(ListThreadsQuerySchema, c.req.query());
|
|
78093
|
+
const { fold } = parseThreadInclude(query.include);
|
|
78094
|
+
const parsed = await parseThreadSelection((key) => c.req.query(key), Object.keys(c.req.query()), {
|
|
78095
|
+
allow: LIST_PARAMS,
|
|
78096
|
+
audience: "reader",
|
|
78097
|
+
loadCollections: () => c.var.services.collections.list()
|
|
78098
|
+
});
|
|
78099
|
+
if (parsed.kind === "empty") return c.json({
|
|
78100
|
+
threads: [],
|
|
77169
78101
|
nextCursor: null
|
|
77170
78102
|
});
|
|
77171
|
-
|
|
77172
|
-
|
|
77173
|
-
|
|
77174
|
-
|
|
77175
|
-
|
|
77176
|
-
|
|
77177
|
-
|
|
77178
|
-
|
|
77179
|
-
|
|
77180
|
-
|
|
77181
|
-
|
|
77182
|
-
|
|
77183
|
-
|
|
77184
|
-
|
|
77185
|
-
|
|
77186
|
-
|
|
78103
|
+
const { threads, nextCursor } = await c.var.services.threads.listThreads({
|
|
78104
|
+
audience: "reader",
|
|
78105
|
+
selection: parsed.selection,
|
|
78106
|
+
includeHidden: parsed.includeHidden,
|
|
78107
|
+
lang: query.lang,
|
|
78108
|
+
sort: query.sort,
|
|
78109
|
+
fold
|
|
78110
|
+
}, {
|
|
78111
|
+
cursor: query.cursor,
|
|
78112
|
+
limit: query.limit
|
|
78113
|
+
});
|
|
78114
|
+
return c.json({
|
|
78115
|
+
threads: await loadPublicThreadResponses(c.var, threads, { content: query.content }),
|
|
78116
|
+
nextCursor
|
|
78117
|
+
});
|
|
78118
|
+
});
|
|
78119
|
+
publicThreadsApiRoutes.get("/:slug", async (c) => {
|
|
78120
|
+
const { include, content } = parseValidated(GetThreadQuerySchema, c.req.query());
|
|
78121
|
+
const root = await c.var.services.threads.findRoot({ slug: c.req.param("slug") }, "reader");
|
|
78122
|
+
if (!root) throw new NotFoundError("Thread");
|
|
78123
|
+
const summaries = await c.var.services.threads.summarize([root], parseThreadInclude(include));
|
|
78124
|
+
const [thread] = await loadPublicThreadResponses(c.var, summaries, { content });
|
|
78125
|
+
if (!thread) throw new NotFoundError("Thread");
|
|
78126
|
+
return c.json(thread);
|
|
78127
|
+
});
|
|
78128
|
+
publicThreadsApiRoutes.get("/:slug/posts", async (c) => {
|
|
78129
|
+
const { cursor, limit, content } = parseValidated(ListThreadPostsQuerySchema, c.req.query());
|
|
78130
|
+
const root = await c.var.services.threads.findRoot({ slug: c.req.param("slug") }, "reader");
|
|
78131
|
+
if (!root) throw new NotFoundError("Thread");
|
|
78132
|
+
const { posts, nextCursor } = await c.var.services.threads.listPosts(root.id, { audience: "reader" }, {
|
|
78133
|
+
cursor,
|
|
78134
|
+
limit
|
|
77187
78135
|
});
|
|
77188
|
-
const postIds = posts.map((post) => post.id);
|
|
77189
|
-
const [mediaMap, collectionsMap] = await Promise.all([c.var.services.media.getByPostIds(postIds), c.var.services.collections.getCollectionsByPostIds(postIds)]);
|
|
77190
78136
|
return c.json({
|
|
77191
|
-
posts:
|
|
77192
|
-
nextCursor
|
|
78137
|
+
posts: await loadPublicPostResponses(c.var, posts, { content }),
|
|
78138
|
+
nextCursor
|
|
77193
78139
|
});
|
|
77194
78140
|
});
|
|
77195
78141
|
//#endregion
|
|
@@ -77604,7 +78550,7 @@ manifestRoutes.get("/manifest.webmanifest", (c) => {
|
|
|
77604
78550
|
});
|
|
77605
78551
|
//#endregion
|
|
77606
78552
|
//#region ../../docs/skill.md?raw
|
|
77607
|
-
var skill_default = "---\nname: jant-site\ndescription: >-\n Work with the Jant site identified in this document through its HTTP API or\n MCP interface. Use when the user asks an AI assistant to read, publish, edit,\n organize, search, or migrate content, upload media, manage Collections, or\n update site settings.\n---\n\n# Jant Site Skill\n\nThis page is written for AI assistants working with one Jant site. Use it when the user asks you to read, publish, edit, organize, search, or migrate site content through Jant's HTTP API or MCP interface.\n\nThe full HTTP API reference lives at <https://jant.me/docs/API.md>. This skill explains how to choose the right interface, work safely, understand Jant's content model, and run common workflows. Consult the reference for complete request and response schemas instead of guessing fields.\n\n---\n\n## Scope and Safety\n\n- Use this skill only for the target site identified below. Do not substitute another site without the user's confirmation.\n- Start with read-only inspection when the state of the site or the user's intent is unclear.\n- Get explicit confirmation before bulk publishing, bulk deletion, destructive settings changes, or any action that is difficult to reverse. A request to perform a specific ordinary write, such as publishing one post, already supplies that confirmation.\n- For uncertain or bulk content changes, ask whether to save posts as drafts or publish them immediately.\n- Treat API tokens like passwords. Never log, commit, or repeat a token back to the user after they provide it.\n- Use the public API or MCP interface. Do not edit the database directly and do not call `/api/internal/*`; those endpoints belong to the hosted control plane.\n- Keep bulk writes sequential. Save returned IDs after each successful write so interrupted work can resume without creating duplicates.\n\n---\n\n## Choose an Interface\n\nJant exposes the same site-owner capabilities through two interfaces:\n\n| Interface | Use it when |\n| ----------------------- | ---------------------------------------------------------------------------------------------------- |\n| HTTP JSON API | Writing scripts, making a few direct requests, or running a one-time migration. This is the default. |\n| MCP at `<site>/api/mcp` | The caller already supports MCP and benefits from tool discovery and structured tool calls. |\n\nFor MCP, call `initialize`, then `tools/list`, and use the returned schemas rather than assuming tool arguments. The tool groups cover posts, media, attachments, Collections, settings, and search.\n\nFor HTTP, these are the main entry points:\n\n| Task | Endpoint |\n| ---------------------------- | ---------------------------------------------------------------- |\n| Read public posts | `GET /api/public/posts`, `GET /api/public/posts/:slug` |\n| List or inspect all posts | `GET /api/posts`, `GET /api/posts/:id` |\n| Create, update, delete | `POST /api/posts`, `PUT /api/posts/:id`, `DELETE /api/posts/:id` |\n| Upload or manage media | `/api/upload` or `/api/uploads` |\n| Manage Collections | `/api/collections` |\n| Search published content | `GET /api/search` |\n| Read or update site settings | `GET /api/settings`, `PUT /api/settings` |\n\nPublic post, Collection, navigation, and search reads can work without a token. A site can disable anonymous API reads; `/api/public/*` then becomes unavailable, while Collection, navigation, and search JSON reads require a browser session or Bearer token. Private content and all writes always require authentication.\n\n---\n\n## Confirm the Target and Authenticate\n\nBefore an authenticated or multi-step operation, confirm:\n\n- The Jant site URL (e.g. `https://example.com`).\n- The exact outcome the user wants, including which content may change.\n- For bulk work, whether new posts should use `status: \"published\"` or `status: \"draft\"`.\n\nHave the user create an API token when the operation needs authentication:\n\n1. Sign in to Jant at `<site>/signin`.\n2. Open **Settings → API Tokens**.\n3. Create a token and copy it immediately. It is shown only once.\n\nSend the token as `Authorization: Bearer jnt_...`.\n\n```bash\nexport JANT_API_TOKEN=jnt_...\nexport JANT_SITE=https://example.com\n```\n\n---\n\n## Understand the Content Model\n\nJant is a single-author microblog. There are no users, comments, likes, followers, or social relationships to manage.\n\nThree concepts shape almost every content operation:\n\n1. **Posts have three formats** — `note`, `link`, and `quote`. Preserve the semantic format instead of coercing everything into `note`.\n2. **Threads connect posts** — a reply is a post whose `replyToId` points to another post. There is no separate comments table.\n3. **Collections curate Threads** — they are intentional groupings, not tags. A Thread can belong to multiple Collections; its root and replies share the same memberships.\n\n### `note` — original writing\n\nUse for essays, journal entries, status updates, photo posts with captions, and other content written by the site owner.\n\n- Required: `format: \"note\"`\n- Recommended: `bodyMarkdown`\n- Optional: `title`\n\n### `link` — a shared reference\n\nUse when the post is fundamentally pointing readers to another resource.\n\n- Required: `format: \"link\"`, `title`, `url`\n- Optional: `bodyMarkdown` for the owner's commentary\n\n### `quote` — a cited passage\n\nUse when the post is built around someone else's words.\n\n- Required: `format: \"quote\"`, `quoteText`\n- Optional: `sourceName`, `sourceUrl`, and `bodyMarkdown` for commentary\n- Do not send `title` or `url`; quote posts use `sourceName` and `sourceUrl` instead.\n\n---\n\n## Common Content Operations\n\nRead the current state before modifying existing content. Use `GET /api/posts/:id` when you need fields that may not appear in a list response, including Thread-level Collection memberships.\n\nCreate a note with an explicit status and visibility:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/posts\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"format\": \"note\",\n \"bodyMarkdown\": \"Hello from Jant.\",\n \"status\": \"published\",\n \"visibility\": \"public\"\n }'\n```\n\nUse `PUT /api/posts/:id` to update a post and `DELETE /api/posts/:id` to delete one. Fetch the post first, preserve fields the user did not ask to change, and confirm before deletion.\n\nUse `POST /api/upload` for an ordinary single-file script or one-time migration. Use the session-based `/api/uploads` flow for large files, unreliable connections, or clients that need resumable transport. Save the returned `med_*` ID before attaching media to a post.\n\nUse `GET /api/settings` before `PUT /api/settings`. Settings values are strings in the HTTP API; preserve settings outside the user's requested change.\n\nFor exact fields, filters, pagination, and response schemas, read the [full HTTP API reference](https://jant.me/docs/API.md).\n\n---\n\n## Import Content from Another Platform\n\nUse this workflow when the user wants to move an old blog, site, or archive into this Jant site. The request may arrive as one sentence, with no export and no token yet. Lead the user through the rest.\n\n### Lead the user\n\nAsk for one thing at a time, when the next step needs it. Name the menus the user clicks, not API endpoints.\n\n1. Check that you can send HTTP requests to `<site>` and read files the user gives you. If you cannot, say so first and suggest an assistant that can, such as a coding agent with shell access. Do not hand over a script unless the user asks for one.\n2. Ask which platform the old blog is on and where it lives.\n3. Get the content. Use an export if the user has one. If not, tell them where their platform exports it (the table under \"Read the source\" lists the usual places) and wait for the file. When the old blog is public and its feed carries full posts, you can read the feed instead. Feeds usually hold only recent posts, so compare the count with the old blog's archive before relying on one.\n4. Ask for the API token just before the first write, using the steps in \"Confirm the Target and Authenticate\". Do not ask for it at the start.\n\n### Plan before writing\n\n1. Inspect the target site so you know whether it already contains content.\n2. Inspect 3–5 representative source posts end to end before deciding how to transform anything.\n3. Report what you found: source formats, item counts, dates, media, internal links, categories, and anything unsupported.\n4. Ask how to handle ambiguous categories or tags. Map them to Collections, drop them, or fold them into post bodies only with the user's direction.\n5. Agree on draft versus published status and on a duplicate policy before creating posts.\n6. Build a resumable source-ID map and persist `{ sourceId -> jantId, slug }` after every successful write.\n\nA slug or path collision returns `409 CONFLICT`, but that does not make an import automatically idempotent. Items with new or generated slugs can still be duplicated, so use the source-ID map rather than relying on conflicts.\n\n### Read the source\n\nCommon source shapes include:\n\n| Source | Typical export |\n| --------------------- | ----------------------------------------------------------------------- |\n| WordPress | WXR XML (`Tools → Export`), with media URLs pointing at the source host |\n| Ghost | JSON export from `Settings → Labs → Export` |\n| Substack | ZIP with `posts.csv` and `posts/*.html` |\n| Medium | ZIP with `posts/*.html` |\n| Tumblr | API dump or `tumblr-utils` archive |\n| Hugo / Jekyll / Astro | Markdown files with YAML or TOML front matter |\n| Notion | Markdown plus a media ZIP |\n| Custom | SQL dump, HTML folder, RSS feed, or another structured source |\n\nDo not assume the source schema from the platform name alone. Check titles, bodies, dates, embedded media, internal links, categories, and source identifiers in real records.\n\n### Map source formats\n\nUse these heuristics as a starting point:\n\n- WordPress, Ghost, and Substack standard posts → `note` with `title` and `bodyMarkdown`.\n- Linklog posts that are primarily an external URL plus commentary → `link`.\n- WordPress or Tumblr quote posts → `quote`.\n- Tumblr photo posts with captions → `note` with uploaded images.\n- Tumblr link posts → `link`.\n- Reblogs or reposts → ask the user. Jant has no native reblog concept; `quote` with `sourceUrl` is often the closest representation.\n\nWhen uncertain, prefer `note`. Turning a real `link` or `quote` into a `note` loses semantic information, while turning original writing into a `link` or `quote` invents structure.\n\n### Convert bodies to Markdown\n\nSend `bodyMarkdown`, not `body`. The `body` field expects TipTap JSON and is intended for editor integrations.\n\n- Convert HTML with a real HTML-to-Markdown tool such as Turndown or Pandoc. Do not strip tags with regular expressions.\n- Preserve headings, lists, tables, fenced code blocks, blockquotes, and inline formatting.\n- A blank line starts a new paragraph. Use two trailing spaces or a backslash for a hard line break.\n- Preserve `<!--more-->` when the source has an intentional excerpt break.\n- Upload embedded media to Jant instead of leaving remote `<img>` references that may disappear with the old site.\n- Rewrite internal links after the destination slugs are known. Either build the slug map first or use a two-pass process: create posts, then update their bodies.\n\n### Upload media first\n\nPosts reference uploaded media by `med_*` ID. For a one-time migration, the one-shot endpoint is usually enough:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/upload\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -F \"file=@./photo.jpg\" \\\n -F \"alt=A red door\"\n# → { \"id\": \"med_...\", \"url\": \"/media/med_....jpg\", ... }\n```\n\nUse `/api/uploads` when a file is large or the connection is unreliable. Its session flow initializes the upload, transfers one or more parts, optionally adds a video poster, and completes the session to produce the final `med_*` record.\n\nPreserve source alt text. If the source has no alt text, leave it unset rather than inventing a description.\n\n### Create Collections when needed\n\nCreate approved Collections before the posts that use them:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/collections\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"slug\": \"reading\",\n \"title\": \"Reading\",\n \"description\": \"Books worth coming back to\",\n \"sortOrder\": \"newest\"\n }'\n```\n\nSave each returned `col_*` ID. Send `collectionIds` on standalone posts and Thread roots, not on replies.\n\n### Create posts\n\n`POST /api/posts` creates every post format. Send one post at a time and record the result before continuing.\n\nMinimal `note`:\n\n```json\n{\n \"format\": \"note\",\n \"title\": \"Hello world\",\n \"bodyMarkdown\": \"First post on the new site.\",\n \"publishedAt\": 1706000000,\n \"status\": \"draft\"\n}\n```\n\nMinimal `link`:\n\n```json\n{\n \"format\": \"link\",\n \"title\": \"An interesting article\",\n \"url\": \"https://example.com/post\",\n \"bodyMarkdown\": \"Worth your fifteen minutes.\"\n}\n```\n\nMinimal `quote`:\n\n```json\n{\n \"format\": \"quote\",\n \"quoteText\": \"What stands in the way becomes the way.\",\n \"sourceName\": \"Marcus Aurelius\",\n \"sourceUrl\": \"https://example.com/meditations\"\n}\n```\n\nFields commonly needed during migration:\n\n| Field | Purpose |\n| --------------- | ------------------------------------------------------------------------------------------ |\n| `publishedAt` | Original publication time as Unix seconds, preserving archive chronology. |\n| `slug` | Original stable slug when it should remain the canonical URL. |\n| `path` | Alternative to `slug` for an original path such as `2024/01/hello-world`; never send both. |\n| `status` | `published` or `draft`; set it explicitly according to the import plan. |\n| `visibility` | `public`, `latest_hidden`, or `private`. |\n| `pinned` | Preserve a pinned state when the source had one; replies cannot be pinned. |\n| `featured` | Preserve a featured or starred state when it has the same meaning. |\n| `collectionIds` | Approved `col_*` IDs on standalone posts and Thread roots. |\n| `attachments` | Ordered media or text attachments. |\n| `replyToId` | Destination `pst_*` ID of the parent when importing a Thread reply. |\n\nRemember these validation rules:\n\n- Send either `body` or `bodyMarkdown`, never both.\n- Send either `slug` or `path`, never both.\n- `note` rejects link- and quote-specific fields.\n- `link` requires `title` and `url`.\n- `quote` requires `quoteText`, uses `sourceName` and `sourceUrl`, and rejects `title` and `url`.\n\nA successful create returns `201` with the full post. Save `id`, `slug`, and `threadId` under the source ID for replies, link rewriting, verification, and recovery.\n\n### Rebuild Threads\n\n1. Import the Thread root first.\n2. Import replies in parent-first order with `replyToId` set to the destination parent's `pst_*` ID.\n3. Do not set `threadId`; Jant derives it from `replyToId`.\n4. Set `collectionIds` on the root only. Replies share the Thread's Collection memberships.\n5. Replies inherit root visibility and status unless explicitly created as drafts. They cannot be pinned or receive independent visibility changes.\n\n### Verify and report\n\nAfter the import:\n\n- Compare source and destination counts by format, media type, Collection, and Thread.\n- Fetch representative posts through `GET /api/posts/:id` and verify dates, slugs, bodies, attachments, Collection memberships, and reply relationships.\n- Open representative public URLs and verify rendered Markdown, media, and rewritten internal links.\n- Report anything skipped, transformed, duplicated, or unresolved, with a short list of URLs for manual review.\n\nIf an import stops partway through, resume from the persisted source-ID map. If cleanup is required, identify only the posts, media, and Collections created by that run, show the user the cleanup scope, and get confirmation before deleting them. Do not use account deletion as an automated recovery strategy.\n\n---\n\n## Handle Errors\n\nHTTP API errors use this shape:\n\n```json\n{ \"error\": \"...\", \"code\": \"VALIDATION_ERROR\", \"details\": {} }\n```\n\n| Code | Response |\n| --------------------- | ------------------------------------------------------------------------------------------------- |\n| `VALIDATION_ERROR` | Read `details.fieldErrors`, correct the request, and do not retry unchanged input. |\n| `UNAUTHORIZED` | Stop. The token is missing, invalid, or revoked; ask the user to create or provide a valid token. |\n| `FORBIDDEN` | Stop and explain which operation was denied. Do not look for an internal bypass. |\n| `NOT_FOUND` | Re-check the target site and resource ID before deciding whether the item was removed. |\n| `CONFLICT` | Resolve the reported state conflict; never silently change a user-selected canonical slug. |\n| `RATE_LIMIT` | Respect `Retry-After` when present, back off, and keep bulk writes sequential. |\n| `CONFIGURATION_ERROR` | Surface the server message; the site owner may need to correct deployment configuration. |\n\nFor MCP, transport and protocol failures use JSON-RPC errors. Tool validation and domain failures are returned as tool results with `isError: true`; inspect their structured content before retrying.\n\n---\n\n## Reference\n\n- Full HTTP API: <https://jant.me/docs/API.md> — endpoints, fields, filters, and response schemas.\n- Automation overview: <https://jant.me/docs/automation-and-api.md> — tokens, HTTP, MCP, and debugging.\n- Round-trip Jant exports: <https://jant.me/docs/export-and-import.md> — use `site export` and `site import` when both ends are Jant.\n- Public documentation index: <https://jant.me/docs/SUMMARY.md>.\n";
|
|
78553
|
+
var skill_default = "---\nname: jant-site\ndescription: >-\n Work with the Jant site identified in this document through its HTTP API or\n MCP interface. Use when the user asks an AI assistant to read, publish, edit,\n organize, search, or migrate content, upload media, manage Collections, or\n update site settings.\n---\n\n# Jant Site Skill\n\nThis page is written for AI assistants working with one Jant site. Use it when the user asks you to read, publish, edit, organize, search, or migrate site content through Jant's HTTP API or MCP interface.\n\nThe full HTTP API reference lives at <https://jant.me/docs/API.md>. This skill explains how to choose the right interface, work safely, understand Jant's content model, and run common workflows. Consult the reference for complete request and response schemas instead of guessing fields.\n\n---\n\n## Scope and Safety\n\n- Use this skill only for the target site identified below. Do not substitute another site without the user's confirmation.\n- Start with read-only inspection when the state of the site or the user's intent is unclear.\n- Get explicit confirmation before bulk publishing, bulk deletion, destructive settings changes, or any action that is difficult to reverse. A request to perform a specific ordinary write, such as publishing one post, already supplies that confirmation.\n- For uncertain or bulk content changes, ask whether to save posts as drafts or publish them immediately.\n- Treat API tokens like passwords. Never log, commit, or repeat a token back to the user after they provide it.\n- Use the public API or MCP interface. Do not edit the database directly and do not call `/api/internal/*`; those endpoints belong to the hosted control plane.\n- Keep bulk writes sequential. Save returned IDs after each successful write so interrupted work can resume without creating duplicates.\n\n---\n\n## Choose an Interface\n\nJant exposes the same site-owner capabilities through two interfaces:\n\n| Interface | Use it when |\n| ----------------------- | ---------------------------------------------------------------------------------------------------- |\n| HTTP JSON API | Writing scripts, making a few direct requests, or running a one-time migration. This is the default. |\n| MCP at `<site>/api/mcp` | The caller already supports MCP and benefits from tool discovery and structured tool calls. |\n\nFor MCP, call `initialize`, then `tools/list`, and use the returned schemas rather than assuming tool arguments. The tool groups cover posts, Threads, media, attachments, Collections, settings, and search.\n\nFor HTTP, these are the main entry points:\n\n| Task | Endpoint |\n| ---------------------------- | ---------------------------------------------------------------- |\n| Read public Threads | `GET /api/public/threads`, `GET /api/public/threads/:slug/posts` |\n| Read one public post | `GET /api/public/posts/:slug` |\n| List or inspect all posts | `GET /api/posts`, `GET /api/posts/:id` |\n| List or read whole Threads | `GET /api/threads`, `GET /api/threads/:id/posts` |\n| Create, update, delete | `POST /api/posts`, `PUT /api/posts/:id`, `DELETE /api/posts/:id` |\n| Upload or manage media | `/api/upload` or `/api/uploads` |\n| Manage Collections | `/api/collections` |\n| Search published content | `GET /api/search` |\n| Read or update site settings | `GET /api/settings`, `PUT /api/settings` |\n\nPublic post, Thread, Collection, navigation, and search reads can work without a token. A site can disable anonymous API reads; `/api/public/*` then becomes unavailable, while Collection, navigation, and search JSON reads require a browser session or Bearer token. Private content and all writes always require authentication.\n\n---\n\n## Confirm the Target and Authenticate\n\nBefore an authenticated or multi-step operation, confirm:\n\n- The Jant site URL (e.g. `https://example.com`).\n- The exact outcome the user wants, including which content may change.\n- For bulk work, whether new posts should use `status: \"published\"` or `status: \"draft\"`.\n\nHave the user create an API token when the operation needs authentication:\n\n1. Sign in to Jant at `<site>/signin`.\n2. Open **Settings → API Tokens**.\n3. Create a token and copy it immediately. It is shown only once.\n\nSend the token as `Authorization: Bearer jnt_...`.\n\n```bash\nexport JANT_API_TOKEN=jnt_...\nexport JANT_SITE=https://example.com\n```\n\n---\n\n## Understand the Content Model\n\nJant is a single-author microblog. There are no users, comments, likes, followers, or social relationships to manage.\n\nThree concepts shape almost every content operation:\n\n1. **Posts have three formats** — `note`, `link`, and `quote`. Preserve the semantic format instead of coercing everything into `note`.\n2. **Threads connect posts** — a reply is a post whose `replyToId` points to another post. There is no separate comments table. A post's `threadPostCount` says how many posts its Thread holds; read them all with `GET /api/threads/:id/posts`, passing any post's ID, rather than collecting replies from the post list.\n3. **Collections curate Threads** — they are intentional groupings, not tags. A Thread can belong to multiple Collections; its root and replies share the same memberships.\n\n### `note` — original writing\n\nUse for essays, journal entries, status updates, photo posts with captions, and other content written by the site owner.\n\n- Required: `format: \"note\"`\n- Recommended: `bodyMarkdown`\n- Optional: `title`\n\n### `link` — a shared reference\n\nUse when the post is fundamentally pointing readers to another resource.\n\n- Required: `format: \"link\"`, `title`, `url`\n- Optional: `bodyMarkdown` for the owner's commentary\n\n### `quote` — a cited passage\n\nUse when the post is built around someone else's words.\n\n- Required: `format: \"quote\"`, `quoteText`\n- Optional: `sourceName`, `sourceUrl`, and `bodyMarkdown` for commentary\n- Do not send `title` or `url`; quote posts use `sourceName` and `sourceUrl` instead.\n\n---\n\n## Common Content Operations\n\nRead the current state before modifying existing content. Use `GET /api/posts/:id` when you need fields that may not appear in a list response, including Thread-level Collection memberships.\n\nCreate a note with an explicit status and visibility:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/posts\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"format\": \"note\",\n \"bodyMarkdown\": \"Hello from Jant.\",\n \"status\": \"published\",\n \"visibility\": \"public\"\n }'\n```\n\nUse `PUT /api/posts/:id` to update a post and `DELETE /api/posts/:id` to delete one. Fetch the post first, preserve fields the user did not ask to change, and confirm before deletion.\n\nUse `POST /api/upload` for an ordinary single-file script or one-time migration. Use the session-based `/api/uploads` flow for large files, unreliable connections, or clients that need resumable transport. Save the returned `med_*` ID before attaching media to a post.\n\nUse `GET /api/settings` before `PUT /api/settings`. Settings values are strings in the HTTP API; preserve settings outside the user's requested change.\n\nFor exact fields, filters, pagination, and response schemas, read the [full HTTP API reference](https://jant.me/docs/API.md).\n\n---\n\n## Import Content from Another Platform\n\nUse this workflow when the user wants to move an old blog, site, or archive into this Jant site. The request may arrive as one sentence, with no export and no token yet. Lead the user through the rest.\n\n### Lead the user\n\nAsk for one thing at a time, when the next step needs it. Name the menus the user clicks, not API endpoints.\n\n1. Check that you can send HTTP requests to `<site>` and read files the user gives you. If you cannot, say so first and suggest an assistant that can, such as a coding agent with shell access. Do not hand over a script unless the user asks for one.\n2. Ask which platform the old blog is on and where it lives.\n3. Get the content. Use an export if the user has one. If not, tell them where their platform exports it (the table under \"Read the source\" lists the usual places) and wait for the file. When the old blog is public and its feed carries full posts, you can read the feed instead. Feeds usually hold only recent posts, so compare the count with the old blog's archive before relying on one.\n4. Ask for the API token just before the first write, using the steps in \"Confirm the Target and Authenticate\". Do not ask for it at the start.\n\n### Plan before writing\n\n1. Inspect the target site so you know whether it already contains content.\n2. Inspect 3–5 representative source posts end to end before deciding how to transform anything.\n3. Report what you found: source formats, item counts, dates, media, internal links, categories, and anything unsupported.\n4. Ask how to handle ambiguous categories or tags. Map them to Collections, drop them, or fold them into post bodies only with the user's direction.\n5. Agree on draft versus published status and on a duplicate policy before creating posts.\n6. Build a resumable source-ID map and persist `{ sourceId -> jantId, slug }` after every successful write.\n\nA slug or path collision returns `409 CONFLICT`, but that does not make an import automatically idempotent. Items with new or generated slugs can still be duplicated, so use the source-ID map rather than relying on conflicts.\n\n### Read the source\n\nCommon source shapes include:\n\n| Source | Typical export |\n| --------------------- | ----------------------------------------------------------------------- |\n| WordPress | WXR XML (`Tools → Export`), with media URLs pointing at the source host |\n| Ghost | JSON export from `Settings → Labs → Export` |\n| Substack | ZIP with `posts.csv` and `posts/*.html` |\n| Medium | ZIP with `posts/*.html` |\n| Tumblr | API dump or `tumblr-utils` archive |\n| Hugo / Jekyll / Astro | Markdown files with YAML or TOML front matter |\n| Notion | Markdown plus a media ZIP |\n| Custom | SQL dump, HTML folder, RSS feed, or another structured source |\n\nDo not assume the source schema from the platform name alone. Check titles, bodies, dates, embedded media, internal links, categories, and source identifiers in real records.\n\n### Map source formats\n\nUse these heuristics as a starting point:\n\n- WordPress, Ghost, and Substack standard posts → `note` with `title` and `bodyMarkdown`.\n- Linklog posts that are primarily an external URL plus commentary → `link`.\n- WordPress or Tumblr quote posts → `quote`.\n- Tumblr photo posts with captions → `note` with uploaded images.\n- Tumblr link posts → `link`.\n- Reblogs or reposts → ask the user. Jant has no native reblog concept; `quote` with `sourceUrl` is often the closest representation.\n\nWhen uncertain, prefer `note`. Turning a real `link` or `quote` into a `note` loses semantic information, while turning original writing into a `link` or `quote` invents structure.\n\n### Convert bodies to Markdown\n\nSend `bodyMarkdown`, not `body`. The `body` field expects TipTap JSON and is intended for editor integrations.\n\n- Convert HTML with a real HTML-to-Markdown tool such as Turndown or Pandoc. Do not strip tags with regular expressions.\n- Preserve headings, lists, tables, fenced code blocks, blockquotes, and inline formatting.\n- A blank line starts a new paragraph. Use two trailing spaces or a backslash for a hard line break.\n- Preserve `<!--more-->` when the source has an intentional excerpt break.\n- Upload embedded media to Jant instead of leaving remote `<img>` references that may disappear with the old site.\n- Rewrite internal links after the destination slugs are known. Either build the slug map first or use a two-pass process: create posts, then update their bodies.\n\n### Upload media first\n\nPosts reference uploaded media by `med_*` ID. For a one-time migration, the one-shot endpoint is usually enough:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/upload\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -F \"file=@./photo.jpg\" \\\n -F \"alt=A red door\"\n# → { \"id\": \"med_...\", \"url\": \"/media/med_....jpg\", ... }\n```\n\nUse `/api/uploads` when a file is large or the connection is unreliable. Its session flow initializes the upload, transfers one or more parts, optionally adds a video poster, and completes the session to produce the final `med_*` record.\n\nPreserve source alt text. If the source has no alt text, leave it unset rather than inventing a description.\n\n### Create Collections when needed\n\nCreate approved Collections before the posts that use them:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/collections\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"slug\": \"reading\",\n \"title\": \"Reading\",\n \"description\": \"Books worth coming back to\",\n \"sortOrder\": \"newest\"\n }'\n```\n\nSave each returned `col_*` ID. Send `collectionIds` on standalone posts and Thread roots, not on replies.\n\n### Create posts\n\n`POST /api/posts` creates every post format. Send one post at a time and record the result before continuing.\n\nMinimal `note`:\n\n```json\n{\n \"format\": \"note\",\n \"title\": \"Hello world\",\n \"bodyMarkdown\": \"First post on the new site.\",\n \"publishedAt\": 1706000000,\n \"status\": \"draft\"\n}\n```\n\nMinimal `link`:\n\n```json\n{\n \"format\": \"link\",\n \"title\": \"An interesting article\",\n \"url\": \"https://example.com/post\",\n \"bodyMarkdown\": \"Worth your fifteen minutes.\"\n}\n```\n\nMinimal `quote`:\n\n```json\n{\n \"format\": \"quote\",\n \"quoteText\": \"What stands in the way becomes the way.\",\n \"sourceName\": \"Marcus Aurelius\",\n \"sourceUrl\": \"https://example.com/meditations\"\n}\n```\n\nFields commonly needed during migration:\n\n| Field | Purpose |\n| --------------- | ------------------------------------------------------------------------------------------ |\n| `publishedAt` | Original publication time as Unix seconds, preserving archive chronology. |\n| `slug` | Original stable slug when it should remain the canonical URL. |\n| `path` | Alternative to `slug` for an original path such as `2024/01/hello-world`; never send both. |\n| `status` | `published` or `draft`; set it explicitly according to the import plan. |\n| `visibility` | `public`, `latest_hidden`, or `private`. |\n| `pinned` | Preserve a pinned state when the source had one; replies cannot be pinned. |\n| `featured` | Preserve a featured or starred state when it has the same meaning. |\n| `collectionIds` | Approved `col_*` IDs on standalone posts and Thread roots. |\n| `attachments` | Ordered media or text attachments. |\n| `replyToId` | Destination `pst_*` ID of the parent when importing a Thread reply. |\n\nRemember these validation rules:\n\n- Send either `body` or `bodyMarkdown`, never both.\n- Send either `slug` or `path`, never both.\n- `note` rejects link- and quote-specific fields.\n- `link` requires `title` and `url`.\n- `quote` requires `quoteText`, uses `sourceName` and `sourceUrl`, and rejects `title` and `url`.\n\nA successful create returns `201` with the full post. Save `id`, `slug`, and `threadId` under the source ID for replies, link rewriting, verification, and recovery.\n\n### Rebuild Threads\n\n1. Import the Thread root first.\n2. Import replies in parent-first order with `replyToId` set to the destination parent's `pst_*` ID.\n3. Do not set `threadId`; Jant derives it from `replyToId`.\n4. Set `collectionIds` on the root only. Replies share the Thread's Collection memberships.\n5. Replies inherit root visibility and status unless explicitly created as drafts. They cannot be pinned or receive independent visibility changes.\n\n### Verify and report\n\nAfter the import:\n\n- Compare source and destination counts by format, media type, Collection, and Thread.\n- Fetch representative posts through `GET /api/posts/:id` and verify dates, slugs, bodies, attachments, Collection memberships, and reply relationships.\n- Open representative public URLs and verify rendered Markdown, media, and rewritten internal links.\n- Report anything skipped, transformed, duplicated, or unresolved, with a short list of URLs for manual review.\n\nIf an import stops partway through, resume from the persisted source-ID map. If cleanup is required, identify only the posts, media, and Collections created by that run, show the user the cleanup scope, and get confirmation before deleting them. Do not use account deletion as an automated recovery strategy.\n\n---\n\n## Handle Errors\n\nHTTP API errors use this shape:\n\n```json\n{ \"error\": \"...\", \"code\": \"VALIDATION_ERROR\", \"details\": {} }\n```\n\n| Code | Response |\n| --------------------- | ------------------------------------------------------------------------------------------------- |\n| `VALIDATION_ERROR` | Read `details.fieldErrors`, correct the request, and do not retry unchanged input. |\n| `UNAUTHORIZED` | Stop. The token is missing, invalid, or revoked; ask the user to create or provide a valid token. |\n| `FORBIDDEN` | Stop and explain which operation was denied. Do not look for an internal bypass. |\n| `NOT_FOUND` | Re-check the target site and resource ID before deciding whether the item was removed. |\n| `CONFLICT` | Resolve the reported state conflict; never silently change a user-selected canonical slug. |\n| `RATE_LIMIT` | Respect `Retry-After` when present, back off, and keep bulk writes sequential. |\n| `CONFIGURATION_ERROR` | Surface the server message; the site owner may need to correct deployment configuration. |\n\nFor MCP, transport and protocol failures use JSON-RPC errors. Tool validation and domain failures are returned as tool results with `isError: true`; inspect their structured content before retrying.\n\n---\n\n## Reference\n\n- Full HTTP API: <https://jant.me/docs/API.md> — endpoints, fields, filters, and response schemas.\n- Automation overview: <https://jant.me/docs/automation-and-api.md> — tokens, HTTP, MCP, and debugging.\n- Round-trip Jant exports: <https://jant.me/docs/export-and-import.md> — use `site export` and `site import` when both ends are Jant.\n- Public documentation index: <https://jant.me/docs/SUMMARY.md>.\n";
|
|
77608
78554
|
//#endregion
|
|
77609
78555
|
//#region src/lib/site-skill.ts
|
|
77610
78556
|
var INTRODUCTION = "This page is written for AI assistants working with one Jant site. Use it when the user asks you to read, publish, edit, organize, search, or migrate site content through Jant's HTTP API or MCP interface.";
|
|
@@ -77633,7 +78579,7 @@ function replaceLiteral(content, search, replacement) {
|
|
|
77633
78579
|
const normalizedSiteUrl = normalizeSiteUrl(siteUrl);
|
|
77634
78580
|
if (!normalizedSiteUrl) throw new Error("A public site URL is required to render /skill.md");
|
|
77635
78581
|
const targetSiteUrl = normalizedSiteUrl.replace(/\/$/, "");
|
|
77636
|
-
if (!"---\nname: jant-site\ndescription: >-\n Work with the Jant site identified in this document through its HTTP API or\n MCP interface. Use when the user asks an AI assistant to read, publish, edit,\n organize, search, or migrate content, upload media, manage Collections, or\n update site settings.\n---\n\n# Jant Site Skill\n\nThis page is written for AI assistants working with one Jant site. Use it when the user asks you to read, publish, edit, organize, search, or migrate site content through Jant's HTTP API or MCP interface.\n\nThe full HTTP API reference lives at <https://jant.me/docs/API.md>. This skill explains how to choose the right interface, work safely, understand Jant's content model, and run common workflows. Consult the reference for complete request and response schemas instead of guessing fields.\n\n---\n\n## Scope and Safety\n\n- Use this skill only for the target site identified below. Do not substitute another site without the user's confirmation.\n- Start with read-only inspection when the state of the site or the user's intent is unclear.\n- Get explicit confirmation before bulk publishing, bulk deletion, destructive settings changes, or any action that is difficult to reverse. A request to perform a specific ordinary write, such as publishing one post, already supplies that confirmation.\n- For uncertain or bulk content changes, ask whether to save posts as drafts or publish them immediately.\n- Treat API tokens like passwords. Never log, commit, or repeat a token back to the user after they provide it.\n- Use the public API or MCP interface. Do not edit the database directly and do not call `/api/internal/*`; those endpoints belong to the hosted control plane.\n- Keep bulk writes sequential. Save returned IDs after each successful write so interrupted work can resume without creating duplicates.\n\n---\n\n## Choose an Interface\n\nJant exposes the same site-owner capabilities through two interfaces:\n\n| Interface | Use it when |\n| ----------------------- | ---------------------------------------------------------------------------------------------------- |\n| HTTP JSON API | Writing scripts, making a few direct requests, or running a one-time migration. This is the default. |\n| MCP at `<site>/api/mcp` | The caller already supports MCP and benefits from tool discovery and structured tool calls. |\n\nFor MCP, call `initialize`, then `tools/list`, and use the returned schemas rather than assuming tool arguments. The tool groups cover posts, media, attachments, Collections, settings, and search.\n\nFor HTTP, these are the main entry points:\n\n| Task | Endpoint |\n| ---------------------------- | ---------------------------------------------------------------- |\n| Read public posts | `GET /api/public/posts`, `GET /api/public/posts/:slug` |\n| List or inspect all posts | `GET /api/posts`, `GET /api/posts/:id` |\n| Create, update, delete | `POST /api/posts`, `PUT /api/posts/:id`, `DELETE /api/posts/:id` |\n| Upload or manage media | `/api/upload` or `/api/uploads` |\n| Manage Collections | `/api/collections` |\n| Search published content | `GET /api/search` |\n| Read or update site settings | `GET /api/settings`, `PUT /api/settings` |\n\nPublic post, Collection, navigation, and search reads can work without a token. A site can disable anonymous API reads; `/api/public/*` then becomes unavailable, while Collection, navigation, and search JSON reads require a browser session or Bearer token. Private content and all writes always require authentication.\n\n---\n\n## Confirm the Target and Authenticate\n\nBefore an authenticated or multi-step operation, confirm:\n\n- The Jant site URL (e.g. `https://example.com`).\n- The exact outcome the user wants, including which content may change.\n- For bulk work, whether new posts should use `status: \"published\"` or `status: \"draft\"`.\n\nHave the user create an API token when the operation needs authentication:\n\n1. Sign in to Jant at `<site>/signin`.\n2. Open **Settings → API Tokens**.\n3. Create a token and copy it immediately. It is shown only once.\n\nSend the token as `Authorization: Bearer jnt_...`.\n\n```bash\nexport JANT_API_TOKEN=jnt_...\nexport JANT_SITE=https://example.com\n```\n\n---\n\n## Understand the Content Model\n\nJant is a single-author microblog. There are no users, comments, likes, followers, or social relationships to manage.\n\nThree concepts shape almost every content operation:\n\n1. **Posts have three formats** — `note`, `link`, and `quote`. Preserve the semantic format instead of coercing everything into `note`.\n2. **Threads connect posts** — a reply is a post whose `replyToId` points to another post. There is no separate comments table.\n3. **Collections curate Threads** — they are intentional groupings, not tags. A Thread can belong to multiple Collections; its root and replies share the same memberships.\n\n### `note` — original writing\n\nUse for essays, journal entries, status updates, photo posts with captions, and other content written by the site owner.\n\n- Required: `format: \"note\"`\n- Recommended: `bodyMarkdown`\n- Optional: `title`\n\n### `link` — a shared reference\n\nUse when the post is fundamentally pointing readers to another resource.\n\n- Required: `format: \"link\"`, `title`, `url`\n- Optional: `bodyMarkdown` for the owner's commentary\n\n### `quote` — a cited passage\n\nUse when the post is built around someone else's words.\n\n- Required: `format: \"quote\"`, `quoteText`\n- Optional: `sourceName`, `sourceUrl`, and `bodyMarkdown` for commentary\n- Do not send `title` or `url`; quote posts use `sourceName` and `sourceUrl` instead.\n\n---\n\n## Common Content Operations\n\nRead the current state before modifying existing content. Use `GET /api/posts/:id` when you need fields that may not appear in a list response, including Thread-level Collection memberships.\n\nCreate a note with an explicit status and visibility:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/posts\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"format\": \"note\",\n \"bodyMarkdown\": \"Hello from Jant.\",\n \"status\": \"published\",\n \"visibility\": \"public\"\n }'\n```\n\nUse `PUT /api/posts/:id` to update a post and `DELETE /api/posts/:id` to delete one. Fetch the post first, preserve fields the user did not ask to change, and confirm before deletion.\n\nUse `POST /api/upload` for an ordinary single-file script or one-time migration. Use the session-based `/api/uploads` flow for large files, unreliable connections, or clients that need resumable transport. Save the returned `med_*` ID before attaching media to a post.\n\nUse `GET /api/settings` before `PUT /api/settings`. Settings values are strings in the HTTP API; preserve settings outside the user's requested change.\n\nFor exact fields, filters, pagination, and response schemas, read the [full HTTP API reference](https://jant.me/docs/API.md).\n\n---\n\n## Import Content from Another Platform\n\nUse this workflow when the user wants to move an old blog, site, or archive into this Jant site. The request may arrive as one sentence, with no export and no token yet. Lead the user through the rest.\n\n### Lead the user\n\nAsk for one thing at a time, when the next step needs it. Name the menus the user clicks, not API endpoints.\n\n1. Check that you can send HTTP requests to `<site>` and read files the user gives you. If you cannot, say so first and suggest an assistant that can, such as a coding agent with shell access. Do not hand over a script unless the user asks for one.\n2. Ask which platform the old blog is on and where it lives.\n3. Get the content. Use an export if the user has one. If not, tell them where their platform exports it (the table under \"Read the source\" lists the usual places) and wait for the file. When the old blog is public and its feed carries full posts, you can read the feed instead. Feeds usually hold only recent posts, so compare the count with the old blog's archive before relying on one.\n4. Ask for the API token just before the first write, using the steps in \"Confirm the Target and Authenticate\". Do not ask for it at the start.\n\n### Plan before writing\n\n1. Inspect the target site so you know whether it already contains content.\n2. Inspect 3–5 representative source posts end to end before deciding how to transform anything.\n3. Report what you found: source formats, item counts, dates, media, internal links, categories, and anything unsupported.\n4. Ask how to handle ambiguous categories or tags. Map them to Collections, drop them, or fold them into post bodies only with the user's direction.\n5. Agree on draft versus published status and on a duplicate policy before creating posts.\n6. Build a resumable source-ID map and persist `{ sourceId -> jantId, slug }` after every successful write.\n\nA slug or path collision returns `409 CONFLICT`, but that does not make an import automatically idempotent. Items with new or generated slugs can still be duplicated, so use the source-ID map rather than relying on conflicts.\n\n### Read the source\n\nCommon source shapes include:\n\n| Source | Typical export |\n| --------------------- | ----------------------------------------------------------------------- |\n| WordPress | WXR XML (`Tools → Export`), with media URLs pointing at the source host |\n| Ghost | JSON export from `Settings → Labs → Export` |\n| Substack | ZIP with `posts.csv` and `posts/*.html` |\n| Medium | ZIP with `posts/*.html` |\n| Tumblr | API dump or `tumblr-utils` archive |\n| Hugo / Jekyll / Astro | Markdown files with YAML or TOML front matter |\n| Notion | Markdown plus a media ZIP |\n| Custom | SQL dump, HTML folder, RSS feed, or another structured source |\n\nDo not assume the source schema from the platform name alone. Check titles, bodies, dates, embedded media, internal links, categories, and source identifiers in real records.\n\n### Map source formats\n\nUse these heuristics as a starting point:\n\n- WordPress, Ghost, and Substack standard posts → `note` with `title` and `bodyMarkdown`.\n- Linklog posts that are primarily an external URL plus commentary → `link`.\n- WordPress or Tumblr quote posts → `quote`.\n- Tumblr photo posts with captions → `note` with uploaded images.\n- Tumblr link posts → `link`.\n- Reblogs or reposts → ask the user. Jant has no native reblog concept; `quote` with `sourceUrl` is often the closest representation.\n\nWhen uncertain, prefer `note`. Turning a real `link` or `quote` into a `note` loses semantic information, while turning original writing into a `link` or `quote` invents structure.\n\n### Convert bodies to Markdown\n\nSend `bodyMarkdown`, not `body`. The `body` field expects TipTap JSON and is intended for editor integrations.\n\n- Convert HTML with a real HTML-to-Markdown tool such as Turndown or Pandoc. Do not strip tags with regular expressions.\n- Preserve headings, lists, tables, fenced code blocks, blockquotes, and inline formatting.\n- A blank line starts a new paragraph. Use two trailing spaces or a backslash for a hard line break.\n- Preserve `<!--more-->` when the source has an intentional excerpt break.\n- Upload embedded media to Jant instead of leaving remote `<img>` references that may disappear with the old site.\n- Rewrite internal links after the destination slugs are known. Either build the slug map first or use a two-pass process: create posts, then update their bodies.\n\n### Upload media first\n\nPosts reference uploaded media by `med_*` ID. For a one-time migration, the one-shot endpoint is usually enough:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/upload\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -F \"file=@./photo.jpg\" \\\n -F \"alt=A red door\"\n# → { \"id\": \"med_...\", \"url\": \"/media/med_....jpg\", ... }\n```\n\nUse `/api/uploads` when a file is large or the connection is unreliable. Its session flow initializes the upload, transfers one or more parts, optionally adds a video poster, and completes the session to produce the final `med_*` record.\n\nPreserve source alt text. If the source has no alt text, leave it unset rather than inventing a description.\n\n### Create Collections when needed\n\nCreate approved Collections before the posts that use them:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/collections\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"slug\": \"reading\",\n \"title\": \"Reading\",\n \"description\": \"Books worth coming back to\",\n \"sortOrder\": \"newest\"\n }'\n```\n\nSave each returned `col_*` ID. Send `collectionIds` on standalone posts and Thread roots, not on replies.\n\n### Create posts\n\n`POST /api/posts` creates every post format. Send one post at a time and record the result before continuing.\n\nMinimal `note`:\n\n```json\n{\n \"format\": \"note\",\n \"title\": \"Hello world\",\n \"bodyMarkdown\": \"First post on the new site.\",\n \"publishedAt\": 1706000000,\n \"status\": \"draft\"\n}\n```\n\nMinimal `link`:\n\n```json\n{\n \"format\": \"link\",\n \"title\": \"An interesting article\",\n \"url\": \"https://example.com/post\",\n \"bodyMarkdown\": \"Worth your fifteen minutes.\"\n}\n```\n\nMinimal `quote`:\n\n```json\n{\n \"format\": \"quote\",\n \"quoteText\": \"What stands in the way becomes the way.\",\n \"sourceName\": \"Marcus Aurelius\",\n \"sourceUrl\": \"https://example.com/meditations\"\n}\n```\n\nFields commonly needed during migration:\n\n| Field | Purpose |\n| --------------- | ------------------------------------------------------------------------------------------ |\n| `publishedAt` | Original publication time as Unix seconds, preserving archive chronology. |\n| `slug` | Original stable slug when it should remain the canonical URL. |\n| `path` | Alternative to `slug` for an original path such as `2024/01/hello-world`; never send both. |\n| `status` | `published` or `draft`; set it explicitly according to the import plan. |\n| `visibility` | `public`, `latest_hidden`, or `private`. |\n| `pinned` | Preserve a pinned state when the source had one; replies cannot be pinned. |\n| `featured` | Preserve a featured or starred state when it has the same meaning. |\n| `collectionIds` | Approved `col_*` IDs on standalone posts and Thread roots. |\n| `attachments` | Ordered media or text attachments. |\n| `replyToId` | Destination `pst_*` ID of the parent when importing a Thread reply. |\n\nRemember these validation rules:\n\n- Send either `body` or `bodyMarkdown`, never both.\n- Send either `slug` or `path`, never both.\n- `note` rejects link- and quote-specific fields.\n- `link` requires `title` and `url`.\n- `quote` requires `quoteText`, uses `sourceName` and `sourceUrl`, and rejects `title` and `url`.\n\nA successful create returns `201` with the full post. Save `id`, `slug`, and `threadId` under the source ID for replies, link rewriting, verification, and recovery.\n\n### Rebuild Threads\n\n1. Import the Thread root first.\n2. Import replies in parent-first order with `replyToId` set to the destination parent's `pst_*` ID.\n3. Do not set `threadId`; Jant derives it from `replyToId`.\n4. Set `collectionIds` on the root only. Replies share the Thread's Collection memberships.\n5. Replies inherit root visibility and status unless explicitly created as drafts. They cannot be pinned or receive independent visibility changes.\n\n### Verify and report\n\nAfter the import:\n\n- Compare source and destination counts by format, media type, Collection, and Thread.\n- Fetch representative posts through `GET /api/posts/:id` and verify dates, slugs, bodies, attachments, Collection memberships, and reply relationships.\n- Open representative public URLs and verify rendered Markdown, media, and rewritten internal links.\n- Report anything skipped, transformed, duplicated, or unresolved, with a short list of URLs for manual review.\n\nIf an import stops partway through, resume from the persisted source-ID map. If cleanup is required, identify only the posts, media, and Collections created by that run, show the user the cleanup scope, and get confirmation before deleting them. Do not use account deletion as an automated recovery strategy.\n\n---\n\n## Handle Errors\n\nHTTP API errors use this shape:\n\n```json\n{ \"error\": \"...\", \"code\": \"VALIDATION_ERROR\", \"details\": {} }\n```\n\n| Code | Response |\n| --------------------- | ------------------------------------------------------------------------------------------------- |\n| `VALIDATION_ERROR` | Read `details.fieldErrors`, correct the request, and do not retry unchanged input. |\n| `UNAUTHORIZED` | Stop. The token is missing, invalid, or revoked; ask the user to create or provide a valid token. |\n| `FORBIDDEN` | Stop and explain which operation was denied. Do not look for an internal bypass. |\n| `NOT_FOUND` | Re-check the target site and resource ID before deciding whether the item was removed. |\n| `CONFLICT` | Resolve the reported state conflict; never silently change a user-selected canonical slug. |\n| `RATE_LIMIT` | Respect `Retry-After` when present, back off, and keep bulk writes sequential. |\n| `CONFIGURATION_ERROR` | Surface the server message; the site owner may need to correct deployment configuration. |\n\nFor MCP, transport and protocol failures use JSON-RPC errors. Tool validation and domain failures are returned as tool results with `isError: true`; inspect their structured content before retrying.\n\n---\n\n## Reference\n\n- Full HTTP API: <https://jant.me/docs/API.md> — endpoints, fields, filters, and response schemas.\n- Automation overview: <https://jant.me/docs/automation-and-api.md> — tokens, HTTP, MCP, and debugging.\n- Round-trip Jant exports: <https://jant.me/docs/export-and-import.md> — use `site export` and `site import` when both ends are Jant.\n- Public documentation index: <https://jant.me/docs/SUMMARY.md>.\n".includes(INTRODUCTION)) throw new Error("The site skill template introduction could not be found");
|
|
78582
|
+
if (!"---\nname: jant-site\ndescription: >-\n Work with the Jant site identified in this document through its HTTP API or\n MCP interface. Use when the user asks an AI assistant to read, publish, edit,\n organize, search, or migrate content, upload media, manage Collections, or\n update site settings.\n---\n\n# Jant Site Skill\n\nThis page is written for AI assistants working with one Jant site. Use it when the user asks you to read, publish, edit, organize, search, or migrate site content through Jant's HTTP API or MCP interface.\n\nThe full HTTP API reference lives at <https://jant.me/docs/API.md>. This skill explains how to choose the right interface, work safely, understand Jant's content model, and run common workflows. Consult the reference for complete request and response schemas instead of guessing fields.\n\n---\n\n## Scope and Safety\n\n- Use this skill only for the target site identified below. Do not substitute another site without the user's confirmation.\n- Start with read-only inspection when the state of the site or the user's intent is unclear.\n- Get explicit confirmation before bulk publishing, bulk deletion, destructive settings changes, or any action that is difficult to reverse. A request to perform a specific ordinary write, such as publishing one post, already supplies that confirmation.\n- For uncertain or bulk content changes, ask whether to save posts as drafts or publish them immediately.\n- Treat API tokens like passwords. Never log, commit, or repeat a token back to the user after they provide it.\n- Use the public API or MCP interface. Do not edit the database directly and do not call `/api/internal/*`; those endpoints belong to the hosted control plane.\n- Keep bulk writes sequential. Save returned IDs after each successful write so interrupted work can resume without creating duplicates.\n\n---\n\n## Choose an Interface\n\nJant exposes the same site-owner capabilities through two interfaces:\n\n| Interface | Use it when |\n| ----------------------- | ---------------------------------------------------------------------------------------------------- |\n| HTTP JSON API | Writing scripts, making a few direct requests, or running a one-time migration. This is the default. |\n| MCP at `<site>/api/mcp` | The caller already supports MCP and benefits from tool discovery and structured tool calls. |\n\nFor MCP, call `initialize`, then `tools/list`, and use the returned schemas rather than assuming tool arguments. The tool groups cover posts, Threads, media, attachments, Collections, settings, and search.\n\nFor HTTP, these are the main entry points:\n\n| Task | Endpoint |\n| ---------------------------- | ---------------------------------------------------------------- |\n| Read public Threads | `GET /api/public/threads`, `GET /api/public/threads/:slug/posts` |\n| Read one public post | `GET /api/public/posts/:slug` |\n| List or inspect all posts | `GET /api/posts`, `GET /api/posts/:id` |\n| List or read whole Threads | `GET /api/threads`, `GET /api/threads/:id/posts` |\n| Create, update, delete | `POST /api/posts`, `PUT /api/posts/:id`, `DELETE /api/posts/:id` |\n| Upload or manage media | `/api/upload` or `/api/uploads` |\n| Manage Collections | `/api/collections` |\n| Search published content | `GET /api/search` |\n| Read or update site settings | `GET /api/settings`, `PUT /api/settings` |\n\nPublic post, Thread, Collection, navigation, and search reads can work without a token. A site can disable anonymous API reads; `/api/public/*` then becomes unavailable, while Collection, navigation, and search JSON reads require a browser session or Bearer token. Private content and all writes always require authentication.\n\n---\n\n## Confirm the Target and Authenticate\n\nBefore an authenticated or multi-step operation, confirm:\n\n- The Jant site URL (e.g. `https://example.com`).\n- The exact outcome the user wants, including which content may change.\n- For bulk work, whether new posts should use `status: \"published\"` or `status: \"draft\"`.\n\nHave the user create an API token when the operation needs authentication:\n\n1. Sign in to Jant at `<site>/signin`.\n2. Open **Settings → API Tokens**.\n3. Create a token and copy it immediately. It is shown only once.\n\nSend the token as `Authorization: Bearer jnt_...`.\n\n```bash\nexport JANT_API_TOKEN=jnt_...\nexport JANT_SITE=https://example.com\n```\n\n---\n\n## Understand the Content Model\n\nJant is a single-author microblog. There are no users, comments, likes, followers, or social relationships to manage.\n\nThree concepts shape almost every content operation:\n\n1. **Posts have three formats** — `note`, `link`, and `quote`. Preserve the semantic format instead of coercing everything into `note`.\n2. **Threads connect posts** — a reply is a post whose `replyToId` points to another post. There is no separate comments table. A post's `threadPostCount` says how many posts its Thread holds; read them all with `GET /api/threads/:id/posts`, passing any post's ID, rather than collecting replies from the post list.\n3. **Collections curate Threads** — they are intentional groupings, not tags. A Thread can belong to multiple Collections; its root and replies share the same memberships.\n\n### `note` — original writing\n\nUse for essays, journal entries, status updates, photo posts with captions, and other content written by the site owner.\n\n- Required: `format: \"note\"`\n- Recommended: `bodyMarkdown`\n- Optional: `title`\n\n### `link` — a shared reference\n\nUse when the post is fundamentally pointing readers to another resource.\n\n- Required: `format: \"link\"`, `title`, `url`\n- Optional: `bodyMarkdown` for the owner's commentary\n\n### `quote` — a cited passage\n\nUse when the post is built around someone else's words.\n\n- Required: `format: \"quote\"`, `quoteText`\n- Optional: `sourceName`, `sourceUrl`, and `bodyMarkdown` for commentary\n- Do not send `title` or `url`; quote posts use `sourceName` and `sourceUrl` instead.\n\n---\n\n## Common Content Operations\n\nRead the current state before modifying existing content. Use `GET /api/posts/:id` when you need fields that may not appear in a list response, including Thread-level Collection memberships.\n\nCreate a note with an explicit status and visibility:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/posts\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"format\": \"note\",\n \"bodyMarkdown\": \"Hello from Jant.\",\n \"status\": \"published\",\n \"visibility\": \"public\"\n }'\n```\n\nUse `PUT /api/posts/:id` to update a post and `DELETE /api/posts/:id` to delete one. Fetch the post first, preserve fields the user did not ask to change, and confirm before deletion.\n\nUse `POST /api/upload` for an ordinary single-file script or one-time migration. Use the session-based `/api/uploads` flow for large files, unreliable connections, or clients that need resumable transport. Save the returned `med_*` ID before attaching media to a post.\n\nUse `GET /api/settings` before `PUT /api/settings`. Settings values are strings in the HTTP API; preserve settings outside the user's requested change.\n\nFor exact fields, filters, pagination, and response schemas, read the [full HTTP API reference](https://jant.me/docs/API.md).\n\n---\n\n## Import Content from Another Platform\n\nUse this workflow when the user wants to move an old blog, site, or archive into this Jant site. The request may arrive as one sentence, with no export and no token yet. Lead the user through the rest.\n\n### Lead the user\n\nAsk for one thing at a time, when the next step needs it. Name the menus the user clicks, not API endpoints.\n\n1. Check that you can send HTTP requests to `<site>` and read files the user gives you. If you cannot, say so first and suggest an assistant that can, such as a coding agent with shell access. Do not hand over a script unless the user asks for one.\n2. Ask which platform the old blog is on and where it lives.\n3. Get the content. Use an export if the user has one. If not, tell them where their platform exports it (the table under \"Read the source\" lists the usual places) and wait for the file. When the old blog is public and its feed carries full posts, you can read the feed instead. Feeds usually hold only recent posts, so compare the count with the old blog's archive before relying on one.\n4. Ask for the API token just before the first write, using the steps in \"Confirm the Target and Authenticate\". Do not ask for it at the start.\n\n### Plan before writing\n\n1. Inspect the target site so you know whether it already contains content.\n2. Inspect 3–5 representative source posts end to end before deciding how to transform anything.\n3. Report what you found: source formats, item counts, dates, media, internal links, categories, and anything unsupported.\n4. Ask how to handle ambiguous categories or tags. Map them to Collections, drop them, or fold them into post bodies only with the user's direction.\n5. Agree on draft versus published status and on a duplicate policy before creating posts.\n6. Build a resumable source-ID map and persist `{ sourceId -> jantId, slug }` after every successful write.\n\nA slug or path collision returns `409 CONFLICT`, but that does not make an import automatically idempotent. Items with new or generated slugs can still be duplicated, so use the source-ID map rather than relying on conflicts.\n\n### Read the source\n\nCommon source shapes include:\n\n| Source | Typical export |\n| --------------------- | ----------------------------------------------------------------------- |\n| WordPress | WXR XML (`Tools → Export`), with media URLs pointing at the source host |\n| Ghost | JSON export from `Settings → Labs → Export` |\n| Substack | ZIP with `posts.csv` and `posts/*.html` |\n| Medium | ZIP with `posts/*.html` |\n| Tumblr | API dump or `tumblr-utils` archive |\n| Hugo / Jekyll / Astro | Markdown files with YAML or TOML front matter |\n| Notion | Markdown plus a media ZIP |\n| Custom | SQL dump, HTML folder, RSS feed, or another structured source |\n\nDo not assume the source schema from the platform name alone. Check titles, bodies, dates, embedded media, internal links, categories, and source identifiers in real records.\n\n### Map source formats\n\nUse these heuristics as a starting point:\n\n- WordPress, Ghost, and Substack standard posts → `note` with `title` and `bodyMarkdown`.\n- Linklog posts that are primarily an external URL plus commentary → `link`.\n- WordPress or Tumblr quote posts → `quote`.\n- Tumblr photo posts with captions → `note` with uploaded images.\n- Tumblr link posts → `link`.\n- Reblogs or reposts → ask the user. Jant has no native reblog concept; `quote` with `sourceUrl` is often the closest representation.\n\nWhen uncertain, prefer `note`. Turning a real `link` or `quote` into a `note` loses semantic information, while turning original writing into a `link` or `quote` invents structure.\n\n### Convert bodies to Markdown\n\nSend `bodyMarkdown`, not `body`. The `body` field expects TipTap JSON and is intended for editor integrations.\n\n- Convert HTML with a real HTML-to-Markdown tool such as Turndown or Pandoc. Do not strip tags with regular expressions.\n- Preserve headings, lists, tables, fenced code blocks, blockquotes, and inline formatting.\n- A blank line starts a new paragraph. Use two trailing spaces or a backslash for a hard line break.\n- Preserve `<!--more-->` when the source has an intentional excerpt break.\n- Upload embedded media to Jant instead of leaving remote `<img>` references that may disappear with the old site.\n- Rewrite internal links after the destination slugs are known. Either build the slug map first or use a two-pass process: create posts, then update their bodies.\n\n### Upload media first\n\nPosts reference uploaded media by `med_*` ID. For a one-time migration, the one-shot endpoint is usually enough:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/upload\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -F \"file=@./photo.jpg\" \\\n -F \"alt=A red door\"\n# → { \"id\": \"med_...\", \"url\": \"/media/med_....jpg\", ... }\n```\n\nUse `/api/uploads` when a file is large or the connection is unreliable. Its session flow initializes the upload, transfers one or more parts, optionally adds a video poster, and completes the session to produce the final `med_*` record.\n\nPreserve source alt text. If the source has no alt text, leave it unset rather than inventing a description.\n\n### Create Collections when needed\n\nCreate approved Collections before the posts that use them:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/collections\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"slug\": \"reading\",\n \"title\": \"Reading\",\n \"description\": \"Books worth coming back to\",\n \"sortOrder\": \"newest\"\n }'\n```\n\nSave each returned `col_*` ID. Send `collectionIds` on standalone posts and Thread roots, not on replies.\n\n### Create posts\n\n`POST /api/posts` creates every post format. Send one post at a time and record the result before continuing.\n\nMinimal `note`:\n\n```json\n{\n \"format\": \"note\",\n \"title\": \"Hello world\",\n \"bodyMarkdown\": \"First post on the new site.\",\n \"publishedAt\": 1706000000,\n \"status\": \"draft\"\n}\n```\n\nMinimal `link`:\n\n```json\n{\n \"format\": \"link\",\n \"title\": \"An interesting article\",\n \"url\": \"https://example.com/post\",\n \"bodyMarkdown\": \"Worth your fifteen minutes.\"\n}\n```\n\nMinimal `quote`:\n\n```json\n{\n \"format\": \"quote\",\n \"quoteText\": \"What stands in the way becomes the way.\",\n \"sourceName\": \"Marcus Aurelius\",\n \"sourceUrl\": \"https://example.com/meditations\"\n}\n```\n\nFields commonly needed during migration:\n\n| Field | Purpose |\n| --------------- | ------------------------------------------------------------------------------------------ |\n| `publishedAt` | Original publication time as Unix seconds, preserving archive chronology. |\n| `slug` | Original stable slug when it should remain the canonical URL. |\n| `path` | Alternative to `slug` for an original path such as `2024/01/hello-world`; never send both. |\n| `status` | `published` or `draft`; set it explicitly according to the import plan. |\n| `visibility` | `public`, `latest_hidden`, or `private`. |\n| `pinned` | Preserve a pinned state when the source had one; replies cannot be pinned. |\n| `featured` | Preserve a featured or starred state when it has the same meaning. |\n| `collectionIds` | Approved `col_*` IDs on standalone posts and Thread roots. |\n| `attachments` | Ordered media or text attachments. |\n| `replyToId` | Destination `pst_*` ID of the parent when importing a Thread reply. |\n\nRemember these validation rules:\n\n- Send either `body` or `bodyMarkdown`, never both.\n- Send either `slug` or `path`, never both.\n- `note` rejects link- and quote-specific fields.\n- `link` requires `title` and `url`.\n- `quote` requires `quoteText`, uses `sourceName` and `sourceUrl`, and rejects `title` and `url`.\n\nA successful create returns `201` with the full post. Save `id`, `slug`, and `threadId` under the source ID for replies, link rewriting, verification, and recovery.\n\n### Rebuild Threads\n\n1. Import the Thread root first.\n2. Import replies in parent-first order with `replyToId` set to the destination parent's `pst_*` ID.\n3. Do not set `threadId`; Jant derives it from `replyToId`.\n4. Set `collectionIds` on the root only. Replies share the Thread's Collection memberships.\n5. Replies inherit root visibility and status unless explicitly created as drafts. They cannot be pinned or receive independent visibility changes.\n\n### Verify and report\n\nAfter the import:\n\n- Compare source and destination counts by format, media type, Collection, and Thread.\n- Fetch representative posts through `GET /api/posts/:id` and verify dates, slugs, bodies, attachments, Collection memberships, and reply relationships.\n- Open representative public URLs and verify rendered Markdown, media, and rewritten internal links.\n- Report anything skipped, transformed, duplicated, or unresolved, with a short list of URLs for manual review.\n\nIf an import stops partway through, resume from the persisted source-ID map. If cleanup is required, identify only the posts, media, and Collections created by that run, show the user the cleanup scope, and get confirmation before deleting them. Do not use account deletion as an automated recovery strategy.\n\n---\n\n## Handle Errors\n\nHTTP API errors use this shape:\n\n```json\n{ \"error\": \"...\", \"code\": \"VALIDATION_ERROR\", \"details\": {} }\n```\n\n| Code | Response |\n| --------------------- | ------------------------------------------------------------------------------------------------- |\n| `VALIDATION_ERROR` | Read `details.fieldErrors`, correct the request, and do not retry unchanged input. |\n| `UNAUTHORIZED` | Stop. The token is missing, invalid, or revoked; ask the user to create or provide a valid token. |\n| `FORBIDDEN` | Stop and explain which operation was denied. Do not look for an internal bypass. |\n| `NOT_FOUND` | Re-check the target site and resource ID before deciding whether the item was removed. |\n| `CONFLICT` | Resolve the reported state conflict; never silently change a user-selected canonical slug. |\n| `RATE_LIMIT` | Respect `Retry-After` when present, back off, and keep bulk writes sequential. |\n| `CONFIGURATION_ERROR` | Surface the server message; the site owner may need to correct deployment configuration. |\n\nFor MCP, transport and protocol failures use JSON-RPC errors. Tool validation and domain failures are returned as tool results with `isError: true`; inspect their structured content before retrying.\n\n---\n\n## Reference\n\n- Full HTTP API: <https://jant.me/docs/API.md> — endpoints, fields, filters, and response schemas.\n- Automation overview: <https://jant.me/docs/automation-and-api.md> — tokens, HTTP, MCP, and debugging.\n- Round-trip Jant exports: <https://jant.me/docs/export-and-import.md> — use `site export` and `site import` when both ends are Jant.\n- Public documentation index: <https://jant.me/docs/SUMMARY.md>.\n".includes(INTRODUCTION)) throw new Error("The site skill template introduction could not be found");
|
|
77637
78583
|
const missingMarker = GENERIC_SITE_MARKERS.find((marker) => !skill_default.includes(marker));
|
|
77638
78584
|
if (missingMarker) throw new Error(`The site skill template target marker could not be found: ${missingMarker}`);
|
|
77639
78585
|
let content = skill_default;
|
|
@@ -78571,7 +79517,12 @@ var cors = (options) => {
|
|
|
78571
79517
|
"Authorization",
|
|
78572
79518
|
"MCP-Protocol-Version"
|
|
78573
79519
|
],
|
|
78574
|
-
exposeHeaders: [
|
|
79520
|
+
exposeHeaders: [
|
|
79521
|
+
"Content-Type",
|
|
79522
|
+
"MCP-Protocol-Version",
|
|
79523
|
+
"Deprecation",
|
|
79524
|
+
"Link"
|
|
79525
|
+
],
|
|
78575
79526
|
credentials: origins !== "*",
|
|
78576
79527
|
maxAge: 86400
|
|
78577
79528
|
})(c, next);
|
|
@@ -81010,6 +81961,168 @@ function createSearchService(rawQuery, siteId, databaseDialect = "sqlite") {
|
|
|
81010
81961
|
} };
|
|
81011
81962
|
}
|
|
81012
81963
|
//#endregion
|
|
81964
|
+
//#region src/services/thread.ts
|
|
81965
|
+
/**
|
|
81966
|
+
* Thread Service
|
|
81967
|
+
*
|
|
81968
|
+
* Threads as a resource of their own: a list of Thread roots in one of the
|
|
81969
|
+
* orders the site shows, each with its Post count and, on request, the fold the
|
|
81970
|
+
* homepage draws; one Thread by any of its Posts; and a Thread's Posts in Thread
|
|
81971
|
+
* order.
|
|
81972
|
+
*
|
|
81973
|
+
* Every read goes through `PostService`. What lives here is the choice of read:
|
|
81974
|
+
* which order a request names, when a collection's own order and pins apply,
|
|
81975
|
+
* and what a reader may see as opposed to the author.
|
|
81976
|
+
*/ var FEATURED_SORT_MESSAGE = "Featured posts are listed newest-published first. Leave sort out, or pass sort=published.";
|
|
81977
|
+
/**
|
|
81978
|
+
* How a plain Thread list orders each `ThreadSort`, as `PostFilters` fields.
|
|
81979
|
+
* Only `activity`, the homepage's order, puts pinned Threads first.
|
|
81980
|
+
*/ function toListOrder(sort) {
|
|
81981
|
+
switch (sort) {
|
|
81982
|
+
case "activity": return {
|
|
81983
|
+
sortBy: "activity",
|
|
81984
|
+
sortOrder: "newest"
|
|
81985
|
+
};
|
|
81986
|
+
case "published": return {
|
|
81987
|
+
sortBy: "published",
|
|
81988
|
+
sortOrder: "newest",
|
|
81989
|
+
ignorePinnedSort: true
|
|
81990
|
+
};
|
|
81991
|
+
case "updated": return {
|
|
81992
|
+
sortBy: "thread_updated",
|
|
81993
|
+
sortOrder: "newest",
|
|
81994
|
+
ignorePinnedSort: true
|
|
81995
|
+
};
|
|
81996
|
+
case "oldest": return {
|
|
81997
|
+
sortBy: "published",
|
|
81998
|
+
sortOrder: "oldest",
|
|
81999
|
+
ignorePinnedSort: true
|
|
82000
|
+
};
|
|
82001
|
+
case "rating": return {
|
|
82002
|
+
sortBy: "activity",
|
|
82003
|
+
sortOrder: "rating_desc",
|
|
82004
|
+
ignorePinnedSort: true
|
|
82005
|
+
};
|
|
82006
|
+
}
|
|
82007
|
+
}
|
|
82008
|
+
/**
|
|
82009
|
+
* The collection order a `ThreadSort` names, or null for the two that read a
|
|
82010
|
+
* collection as a plain filter.
|
|
82011
|
+
*/ function toCollectionOrder(sort) {
|
|
82012
|
+
switch (sort) {
|
|
82013
|
+
case "activity": return "newest";
|
|
82014
|
+
case "oldest": return "oldest";
|
|
82015
|
+
case "rating": return "rating_desc";
|
|
82016
|
+
case "published":
|
|
82017
|
+
case "updated": return null;
|
|
82018
|
+
}
|
|
82019
|
+
}
|
|
82020
|
+
/**
|
|
82021
|
+
* Create the Thread service.
|
|
82022
|
+
*
|
|
82023
|
+
* @param deps - The Post and collection services it reads through
|
|
82024
|
+
* @returns The Thread service
|
|
82025
|
+
* @example
|
|
82026
|
+
* const threads = createThreadService({ posts, collections });
|
|
82027
|
+
*/ function createThreadService(deps) {
|
|
82028
|
+
const { posts, collections } = deps;
|
|
82029
|
+
/**
|
|
82030
|
+
* The order a collection's page would use: its configured order when it is
|
|
82031
|
+
* the only one named, activity for several. A rating order with fewer than
|
|
82032
|
+
* two rated Threads falls back, as the page does — for the default only; a
|
|
82033
|
+
* caller who asks for `rating` gets it.
|
|
82034
|
+
*/ async function resolveDefaultCollectionOrder(collectionIds, options) {
|
|
82035
|
+
const [onlyId, ...others] = collectionIds;
|
|
82036
|
+
if (!onlyId || others.length > 0) return "newest";
|
|
82037
|
+
const collection = await collections.getById(onlyId);
|
|
82038
|
+
if (!collection) return "newest";
|
|
82039
|
+
const ratedThreadCount = await posts.countCollectionThreadRootsUpToForCollections([onlyId], {
|
|
82040
|
+
...options,
|
|
82041
|
+
hasRating: true
|
|
82042
|
+
}, 2);
|
|
82043
|
+
return resolveCollectionSortOrder(void 0, collection.sortOrder, supportsCollectionRatingSort(ratedThreadCount));
|
|
82044
|
+
}
|
|
82045
|
+
const service = {
|
|
82046
|
+
async listThreads(query, page) {
|
|
82047
|
+
const reader = query.audience === "reader";
|
|
82048
|
+
const { selection } = query;
|
|
82049
|
+
const visibility = selection.visibility;
|
|
82050
|
+
if (reader && visibility === "private") throw new ValidationError("Private posts aren't listed here.");
|
|
82051
|
+
if (visibility === "featured" && query.sort !== void 0 && query.sort !== "published") throw new ValidationError(FEATURED_SORT_MESSAGE);
|
|
82052
|
+
const base = {
|
|
82053
|
+
status: reader ? "published" : query.status ?? "published",
|
|
82054
|
+
excludePrivate: reader,
|
|
82055
|
+
excludeLatestHidden: reader && visibility === void 0 && !query.includeHidden,
|
|
82056
|
+
lang: query.lang
|
|
82057
|
+
};
|
|
82058
|
+
const collectionIds = selection.collection;
|
|
82059
|
+
if (collectionIds && visibility !== "featured") {
|
|
82060
|
+
const { collection: _named, ...rootSelection } = selection;
|
|
82061
|
+
const options = {
|
|
82062
|
+
...base,
|
|
82063
|
+
rootFilters: toPostFilters(rootSelection, { yearAxis: "published" })
|
|
82064
|
+
};
|
|
82065
|
+
const collectionOrder = query.sort === void 0 ? await resolveDefaultCollectionOrder(collectionIds, options) : toCollectionOrder(query.sort);
|
|
82066
|
+
if (collectionOrder) {
|
|
82067
|
+
const result = await posts.listCollectionThreadRootPage([...collectionIds], {
|
|
82068
|
+
...options,
|
|
82069
|
+
sortOrder: collectionOrder
|
|
82070
|
+
}, page);
|
|
82071
|
+
return {
|
|
82072
|
+
threads: await service.summarize(result.posts, query),
|
|
82073
|
+
nextCursor: result.nextCursor
|
|
82074
|
+
};
|
|
82075
|
+
}
|
|
82076
|
+
}
|
|
82077
|
+
const result = await posts.listPage({
|
|
82078
|
+
...base,
|
|
82079
|
+
excludeReplies: true,
|
|
82080
|
+
...toPostFilters(selection, { yearAxis: "published" }),
|
|
82081
|
+
...visibility === "featured" ? toListOrder("published") : toListOrder(query.sort ?? "activity")
|
|
82082
|
+
}, page);
|
|
82083
|
+
return {
|
|
82084
|
+
threads: await service.summarize(result.posts, query),
|
|
82085
|
+
nextCursor: result.nextCursor
|
|
82086
|
+
};
|
|
82087
|
+
},
|
|
82088
|
+
async findRoot(ref, audience) {
|
|
82089
|
+
const post = "id" in ref ? await posts.getById(ref.id) : await posts.getBySlug(ref.slug);
|
|
82090
|
+
if (!post) return null;
|
|
82091
|
+
if (audience === "reader" && post.status !== "published") return null;
|
|
82092
|
+
const root = post.threadId === post.id ? post : await posts.getById(post.threadId);
|
|
82093
|
+
if (!root) return null;
|
|
82094
|
+
if (audience === "reader" && (root.status !== "published" || root.visibility === "private")) return null;
|
|
82095
|
+
return root;
|
|
82096
|
+
},
|
|
82097
|
+
async summarize(roots, options) {
|
|
82098
|
+
if (roots.length === 0) return [];
|
|
82099
|
+
const rootIds = roots.map((root) => root.id);
|
|
82100
|
+
const [counts, contexts] = await Promise.all([posts.countThreadPosts(rootIds), options.fold ? posts.getThreadTimelineContext(rootIds) : Promise.resolve(null)]);
|
|
82101
|
+
return roots.map((root) => {
|
|
82102
|
+
const summary = {
|
|
82103
|
+
root,
|
|
82104
|
+
postCount: counts.get(root.id) ?? 0
|
|
82105
|
+
};
|
|
82106
|
+
if (contexts) {
|
|
82107
|
+
const context = contexts.get(root.id);
|
|
82108
|
+
summary.fold = context ? foldReplyWindows({
|
|
82109
|
+
leadingReplies: context.leadingReplies,
|
|
82110
|
+
trailingReplies: context.trailingReplies,
|
|
82111
|
+
latestReply: context.latestReply,
|
|
82112
|
+
nextReply: context.firstHiddenReply,
|
|
82113
|
+
totalReplyCount: context.totalReplyCount
|
|
82114
|
+
}) : null;
|
|
82115
|
+
}
|
|
82116
|
+
return summary;
|
|
82117
|
+
});
|
|
82118
|
+
},
|
|
82119
|
+
async listPosts(rootId, query, page) {
|
|
82120
|
+
return posts.listThreadPostsPage(rootId, { status: query.audience === "reader" ? "published" : query.status ?? "published" }, page);
|
|
82121
|
+
}
|
|
82122
|
+
};
|
|
82123
|
+
return service;
|
|
82124
|
+
}
|
|
82125
|
+
//#endregion
|
|
81013
82126
|
//#region src/services/navigation.ts
|
|
81014
82127
|
/**
|
|
81015
82128
|
* Nav Item Service (v2)
|
|
@@ -83131,6 +84244,10 @@ function createTelegramService(db, siteId, databaseSchema = sqliteSchemaBundle)
|
|
|
83131
84244
|
site,
|
|
83132
84245
|
paths,
|
|
83133
84246
|
posts,
|
|
84247
|
+
threads: createThreadService({
|
|
84248
|
+
posts,
|
|
84249
|
+
collections
|
|
84250
|
+
}),
|
|
83134
84251
|
customUrls: createCustomUrlService(db, siteId, paths, databaseSchema),
|
|
83135
84252
|
media,
|
|
83136
84253
|
uploads: createUploadSessionService(db, siteId, media, databaseSchema),
|
|
@@ -83931,9 +85048,11 @@ async function servePublicStorage(c) {
|
|
|
83931
85048
|
app.use("*", requireRssFeedsEnabled());
|
|
83932
85049
|
app.route("/", siteSkillRoutes);
|
|
83933
85050
|
app.route("/api/public/posts", publicPostsApiRoutes);
|
|
85051
|
+
app.route("/api/public/threads", publicThreadsApiRoutes);
|
|
83934
85052
|
app.route("/api/public/archive", publicArchiveApiRoutes);
|
|
83935
85053
|
app.route("/api/discover", discoverApiRoutes);
|
|
83936
85054
|
app.route("/api/posts", postsApiRoutes);
|
|
85055
|
+
app.route("/api/threads", threadsApiRoutes);
|
|
83937
85056
|
app.route("/api/nav-items", navItemsApiRoutes);
|
|
83938
85057
|
app.route("/api/collections", collectionsApiRoutes);
|
|
83939
85058
|
app.route("/api/smart-collections", smartCollectionsApiRoutes);
|