@jant/core 0.8.1 → 0.9.1
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--uxnaIRV.js → app-B3P2N2vM.js} +1346 -310
- package/dist/client/.vite/manifest.json +2 -2
- package/dist/client/_assets/{client-auth-begiT1tq.js → client-auth-CeGBe0qG.js} +1 -1
- package/dist/client/_assets/{client-BT6kpcuG.js → client-nByuF0Ct.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/node.js +2 -2
- package/package.json +1 -1
- package/src/__tests__/helpers/cursor-walk.ts +37 -7
- package/src/app.tsx +4 -0
- package/src/lib/__tests__/discover.test.ts +24 -0
- package/src/lib/__tests__/thread-fold.test.ts +43 -0
- 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/discover.ts +34 -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 +143 -0
- package/src/routes/api/__tests__/posts.test.ts +78 -0
- package/src/routes/api/__tests__/public-access.test.ts +5 -0
- package/src/routes/api/__tests__/search.test.ts +104 -0
- package/src/routes/api/__tests__/threads.test.ts +115 -0
- package/src/routes/api/posts.ts +15 -104
- package/src/routes/api/public/__tests__/threads.test.ts +363 -0
- package/src/routes/api/public/archive.ts +82 -81
- package/src/routes/api/public/posts.ts +97 -298
- package/src/routes/api/public/threads.ts +141 -0
- package/src/routes/api/search.ts +31 -2
- package/src/routes/api/threads.ts +128 -0
- package/src/routes/auth/__tests__/setup-discover.test.ts +29 -1
- package/src/routes/auth/__tests__/setup-page.test.tsx +59 -1
- package/src/routes/auth/setup.tsx +48 -9
- package/src/routes/pages/__tests__/search.test.ts +58 -0
- package/src/routes/pages/search.tsx +3 -1
- package/src/services/__tests__/search.test.ts +211 -0
- package/src/services/__tests__/thread.test.ts +495 -0
- package/src/services/index.ts +4 -0
- package/src/services/mcp.ts +217 -57
- package/src/services/post.ts +222 -43
- package/src/services/search.ts +77 -66
- 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
|
@@ -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.1-d7610f6379632ea6";
|
|
5348
|
+
var CLIENT_JS_FILE = "/_assets/client-nByuF0Ct.js";
|
|
5349
|
+
var CLIENT_AUTH_JS_FILE = "/_assets/client-auth-CeGBe0qG.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.1-d7610f6379632ea6";
|
|
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",
|
|
@@ -10251,6 +10273,36 @@ var DISCOVER_SETTINGS = [
|
|
|
10251
10273
|
* directory never builds the address itself.
|
|
10252
10274
|
*/ var DISCOVER_STATUS_PATH = "/api/discover/posts";
|
|
10253
10275
|
/**
|
|
10276
|
+
* Languages the jant.me directory lists, as primary language subtags.
|
|
10277
|
+
*
|
|
10278
|
+
* The directory's rule — its `accepted_languages` — stated here for the same
|
|
10279
|
+
* reason as `DISCOVER_MIN_PUBLIC_POSTS`, and read by setup alone: the Discover
|
|
10280
|
+
* question is asked there only when the answer can lead somewhere. An author
|
|
10281
|
+
* writing in a language the directory does not list would be handed a promise
|
|
10282
|
+
* nobody keeps, ticked in advance on hosted Jant.
|
|
10283
|
+
*
|
|
10284
|
+
* Nothing else reads it. The settings checkbox records consent rather than
|
|
10285
|
+
* applying for a listing, and a site can take on a listed language later
|
|
10286
|
+
* through multilingual content, so it stays for everyone.
|
|
10287
|
+
*
|
|
10288
|
+
* Simplified and Traditional Chinese are one list there, which is why the
|
|
10289
|
+
* match is on the primary subtag rather than on the script.
|
|
10290
|
+
*/ var DISCOVER_LANGUAGES = ["zh"];
|
|
10291
|
+
/**
|
|
10292
|
+
* Whether the jant.me directory lists posts written in a language.
|
|
10293
|
+
*
|
|
10294
|
+
* @param tag - A BCP 47 language tag, as the content language is stored
|
|
10295
|
+
* @returns True when the tag's primary subtag is in `DISCOVER_LANGUAGES`
|
|
10296
|
+
* @example
|
|
10297
|
+
* ```ts
|
|
10298
|
+
* isDiscoverLanguage("zh-Hant"); // true
|
|
10299
|
+
* isDiscoverLanguage("en"); // false
|
|
10300
|
+
* ```
|
|
10301
|
+
*/ function isDiscoverLanguage(tag) {
|
|
10302
|
+
const primary = tag.split("-")[0]?.toLowerCase() ?? "";
|
|
10303
|
+
return DISCOVER_LANGUAGES.includes(primary);
|
|
10304
|
+
}
|
|
10305
|
+
/**
|
|
10254
10306
|
* The directory's names for its two format lists.
|
|
10255
10307
|
*
|
|
10256
10308
|
* Proper names that stay in English in every locale, as the directory's own
|
|
@@ -10632,6 +10684,12 @@ var DISCOVER_SETTINGS = [
|
|
|
10632
10684
|
})] });
|
|
10633
10685
|
};
|
|
10634
10686
|
/**
|
|
10687
|
+
* `isDiscoverLanguage` as a Datastar expression over the language signal, so
|
|
10688
|
+
* the Discover question follows the picker without a round trip. The list is
|
|
10689
|
+
* the same constant the server reads, and a test holds the two readings of it
|
|
10690
|
+
* together.
|
|
10691
|
+
*/ var DISCOVER_LANGUAGE_EXPRESSION = `${JSON.stringify(DISCOVER_LANGUAGES)}.includes($contentLanguage.split('-')[0].toLowerCase())`;
|
|
10692
|
+
/**
|
|
10635
10693
|
* The one question setup asks about the world outside this site.
|
|
10636
10694
|
*
|
|
10637
10695
|
* It earns a place on a screen that asks as little as it can because the
|
|
@@ -10640,6 +10698,11 @@ var DISCOVER_SETTINGS = [
|
|
|
10640
10698
|
* settings page's own: one control appearing twice should not describe itself
|
|
10641
10699
|
* two ways.
|
|
10642
10700
|
*
|
|
10701
|
+
* Only on screen while the chosen language is one the directory lists. For any
|
|
10702
|
+
* other, learning the directory exists leads nowhere, and on hosted Jant the box
|
|
10703
|
+
* would arrive ticked — a promise nobody keeps. It follows the language picker
|
|
10704
|
+
* above it, since both are answered on the same screen.
|
|
10705
|
+
*
|
|
10643
10706
|
* The words come from the same `getDiscoverCopy` the settings page uses,
|
|
10644
10707
|
* which is what keeps the two surfaces from drifting when either is edited.
|
|
10645
10708
|
* The label is the settings page's; the help line is the settings page's
|
|
@@ -10648,10 +10711,12 @@ var DISCOVER_SETTINGS = [
|
|
|
10648
10711
|
* first one — the directory's name links to the directory for anyone who wants
|
|
10649
10712
|
* more. Where to find the setting again is left to the screen's footnote, which
|
|
10650
10713
|
* says it once for every answer on it.
|
|
10651
|
-
*/ var DiscoverField = ({ copy, pages }) => {
|
|
10714
|
+
*/ var DiscoverField = ({ copy, pages, shown }) => {
|
|
10652
10715
|
const runs = discoverIntroRuns(copy.about, copy, pages);
|
|
10653
10716
|
return /*#__PURE__*/ jsxDEV$1("div", {
|
|
10654
10717
|
class: "field mt-2",
|
|
10718
|
+
"data-show": DISCOVER_LANGUAGE_EXPRESSION,
|
|
10719
|
+
style: shown ? void 0 : "display:none",
|
|
10655
10720
|
children: [/*#__PURE__*/ jsxDEV$1("label", {
|
|
10656
10721
|
class: "flex items-center gap-2 cursor-pointer",
|
|
10657
10722
|
for: "setup-discover",
|
|
@@ -10809,7 +10874,8 @@ var SetupContent = (props) => {
|
|
|
10809
10874
|
const emptyLabel = i18n._({ id: "Ox3+3h" });
|
|
10810
10875
|
const discoverField = discoverAvailable ? /*#__PURE__*/ jsxDEV$1(DiscoverField, {
|
|
10811
10876
|
copy: getDiscoverCopy(i18n),
|
|
10812
|
-
pages: discoverPages
|
|
10877
|
+
pages: discoverPages,
|
|
10878
|
+
shown: isDiscoverLanguage(contentLanguage)
|
|
10813
10879
|
}) : null;
|
|
10814
10880
|
const signals = [
|
|
10815
10881
|
askSiteName ? "siteName: ''" : null,
|
|
@@ -10890,6 +10956,12 @@ var SetupContent = (props) => {
|
|
|
10890
10956
|
* is the whole point of asking. An absent field is not a refusal — an older
|
|
10891
10957
|
* client or a scripted setup sends none — and leaves the default in force.
|
|
10892
10958
|
*
|
|
10959
|
+
* Neither is a value sent with a language the directory does not list. The
|
|
10960
|
+
* question was not on screen for it, but the signal behind the hidden box still
|
|
10961
|
+
* went out holding its starting state, and storing that would record an answer
|
|
10962
|
+
* to a question nobody was asked. It is dropped, and the default stays in
|
|
10963
|
+
* force — the same as sending nothing.
|
|
10964
|
+
*
|
|
10893
10965
|
* A yes is announced immediately, on the same terms as the settings page's own
|
|
10894
10966
|
* switch. A directory decides eligibility for itself and re-reads the feed on
|
|
10895
10967
|
* its own schedule, so a site with nothing published yet loses nothing by
|
|
@@ -10904,8 +10976,10 @@ var SetupContent = (props) => {
|
|
|
10904
10976
|
* page's status block reads it back with a Retry beside it.
|
|
10905
10977
|
*
|
|
10906
10978
|
* @param c - The setup request, for its services and its config
|
|
10907
|
-
* @param
|
|
10908
|
-
|
|
10979
|
+
* @param answers - The validated answers: the checkbox, or undefined when the
|
|
10980
|
+
* form carried no field, and the language it was answered for
|
|
10981
|
+
*/ async function storeDiscoverAnswer(c, answers) {
|
|
10982
|
+
const answer = isDiscoverLanguage(answers.contentLanguage) ? answers.discover : void 0;
|
|
10909
10983
|
if (answer === void 0) return;
|
|
10910
10984
|
const stored = answer ? "latest" : "off";
|
|
10911
10985
|
const { shouldAnnounce } = await c.var.services.settings.updateDiscoverSetting(stored, { demoMode: c.var.appConfig.demoMode });
|
|
@@ -11088,7 +11162,7 @@ setupRoutes.get("/setup", async (c) => {
|
|
|
11088
11162
|
headers: c.req.raw.headers
|
|
11089
11163
|
});
|
|
11090
11164
|
} : null });
|
|
11091
|
-
await storeDiscoverAnswer(c, answers
|
|
11165
|
+
await storeDiscoverAnswer(c, answers);
|
|
11092
11166
|
return dsRedirect(toPublicPath("/", c.var.appConfig.sitePathPrefix));
|
|
11093
11167
|
}
|
|
11094
11168
|
setupRoutes.post("/setup", async (c) => {
|
|
@@ -18641,6 +18715,52 @@ var TimelineItemFromPost = ({ post, mode, display }) => {
|
|
|
18641
18715
|
return Math.max(0, totalReplyCount - shown.size);
|
|
18642
18716
|
}
|
|
18643
18717
|
/**
|
|
18718
|
+
* Fold a thread from its ranked windows: the replies each end of the fold
|
|
18719
|
+
* keeps, before any overlap between them is removed.
|
|
18720
|
+
*
|
|
18721
|
+
* Both access paths arrive here. The feed slices the windows out of the whole
|
|
18722
|
+
* chain; the site and the API rank them in SQL (`getThreadTimelineContext`),
|
|
18723
|
+
* which hands them over overlapping on purpose. A short thread's windows
|
|
18724
|
+
* overlap, and the hero is inside both of them on the shortest ones: with a
|
|
18725
|
+
* single reply, that reply is the newest *and* the whole leading window. Each
|
|
18726
|
+
* list therefore drops whatever an earlier one already shows, hero first.
|
|
18727
|
+
*
|
|
18728
|
+
* @param buckets.leadingReplies - The first `THREAD_LEADING_REPLIES` replies
|
|
18729
|
+
* @param buckets.trailingReplies - The replies just before the newest, oldest
|
|
18730
|
+
* first
|
|
18731
|
+
* @param buckets.latestReply - The newest reply
|
|
18732
|
+
* @param buckets.nextReply - The reply right after the leading window, the
|
|
18733
|
+
* only candidate for the gap; `null` when the thread has no such reply
|
|
18734
|
+
* @param buckets.totalReplyCount - Every published reply in the thread
|
|
18735
|
+
* @returns The fold
|
|
18736
|
+
* @example
|
|
18737
|
+
* foldReplyWindows({ leadingReplies: [r1, r2], trailingReplies: [r6, r7],
|
|
18738
|
+
* latestReply: r8, nextReply: r3, totalReplyCount: 8 });
|
|
18739
|
+
* // leading [r1, r2], trailing [r6, r7], latest r8, firstHidden r3, hidden 3
|
|
18740
|
+
*/ function foldReplyWindows({ leadingReplies: leadingWindow, trailingReplies: trailingWindow, latestReply, nextReply, totalReplyCount }) {
|
|
18741
|
+
const shown = /* @__PURE__ */ new Set([latestReply.id]);
|
|
18742
|
+
const keepUnshown = (replies) => replies.filter((reply) => {
|
|
18743
|
+
if (shown.has(reply.id)) return false;
|
|
18744
|
+
shown.add(reply.id);
|
|
18745
|
+
return true;
|
|
18746
|
+
});
|
|
18747
|
+
const leadingReplies = keepUnshown(leadingWindow);
|
|
18748
|
+
const trailingReplies = keepUnshown(trailingWindow);
|
|
18749
|
+
const hiddenCount = getThreadHiddenCount({
|
|
18750
|
+
leadingReplies,
|
|
18751
|
+
trailingReplies,
|
|
18752
|
+
latestReply,
|
|
18753
|
+
totalReplyCount
|
|
18754
|
+
});
|
|
18755
|
+
return {
|
|
18756
|
+
leadingReplies,
|
|
18757
|
+
trailingReplies,
|
|
18758
|
+
latestReply,
|
|
18759
|
+
firstHiddenReply: hiddenCount > 0 && nextReply && !shown.has(nextReply.id) ? nextReply : null,
|
|
18760
|
+
hiddenCount
|
|
18761
|
+
};
|
|
18762
|
+
}
|
|
18763
|
+
/**
|
|
18644
18764
|
* Fold a thread whose replies are already in hand.
|
|
18645
18765
|
*
|
|
18646
18766
|
* Takes the same slices the SQL path ranks for: the first
|
|
@@ -18657,50 +18777,17 @@ var TimelineItemFromPost = ({ post, mode, display }) => {
|
|
|
18657
18777
|
*/ function foldThreadReplies(replies) {
|
|
18658
18778
|
const latestReply = replies.at(-1);
|
|
18659
18779
|
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,
|
|
18780
|
+
return foldReplyWindows({
|
|
18781
|
+
leadingReplies: replies.slice(0, 2),
|
|
18782
|
+
trailingReplies: replies.slice(-3, -1),
|
|
18671
18783
|
latestReply,
|
|
18672
|
-
|
|
18673
|
-
|
|
18674
|
-
|
|
18675
|
-
trailingReplies,
|
|
18676
|
-
latestReply,
|
|
18677
|
-
totalReplyCount: replies.length
|
|
18678
|
-
})
|
|
18679
|
-
};
|
|
18784
|
+
nextReply: replies[2] ?? null,
|
|
18785
|
+
totalReplyCount: replies.length
|
|
18786
|
+
});
|
|
18680
18787
|
}
|
|
18681
18788
|
//#endregion
|
|
18682
18789
|
//#region src/ui/feed/thread-preview-state.ts
|
|
18683
18790
|
/**
|
|
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
18791
|
* A lone root post shorter than this (plain-text code points) comfortably
|
|
18705
18792
|
* fits the thread-context height cap. Pairs with the
|
|
18706
18793
|
* `--site-thread-context-max-height` token (160px) in tokens.css — revisit
|
|
@@ -18744,12 +18831,14 @@ var CONTEXT_DISPLAY = {
|
|
|
18744
18831
|
var HERO_DISPLAY = {};
|
|
18745
18832
|
var ThreadPreview = ({ rootPost, leadingReplies, trailingReplies, latestReply, gapHref, totalReplyCount }) => {
|
|
18746
18833
|
const { i18n } = useLingui();
|
|
18747
|
-
const
|
|
18834
|
+
const fold = foldReplyWindows({
|
|
18748
18835
|
leadingReplies,
|
|
18749
18836
|
trailingReplies,
|
|
18750
18837
|
latestReply,
|
|
18838
|
+
nextReply: null,
|
|
18751
18839
|
totalReplyCount
|
|
18752
18840
|
});
|
|
18841
|
+
const hiddenCount = fold.hiddenCount;
|
|
18753
18842
|
const assumeOverflow = threadContextAssumesOverflow({
|
|
18754
18843
|
rootPost,
|
|
18755
18844
|
totalReplyCount
|
|
@@ -18757,14 +18846,8 @@ var ThreadPreview = ({ rootPost, leadingReplies, trailingReplies, latestReply, g
|
|
|
18757
18846
|
const hiddenPostsLabel = i18n._({ id: "oO0hKx" }, { count: hiddenCount });
|
|
18758
18847
|
const showMoreLabel = i18n._({ id: "fMPkxb" });
|
|
18759
18848
|
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);
|
|
18849
|
+
const renderedLeadingReplies = fold.leadingReplies;
|
|
18850
|
+
const renderedTrailingReplies = fold.trailingReplies;
|
|
18768
18851
|
const gapLinkHref = gapHref ?? latestReply.permalink;
|
|
18769
18852
|
const rootItem = /*#__PURE__*/ jsxDEV$1("div", {
|
|
18770
18853
|
class: "thread-item thread-item-context",
|
|
@@ -27666,6 +27749,7 @@ var SearchPage = ({ query, results, error, hasMore, page, basePath = "", isAuthe
|
|
|
27666
27749
|
limit: pageSize + 1,
|
|
27667
27750
|
offset: (page - 1) * pageSize,
|
|
27668
27751
|
status: ["published"],
|
|
27752
|
+
includePrivate: c.var.isAuthenticated,
|
|
27669
27753
|
lang: getViewLang(c) ?? void 0
|
|
27670
27754
|
});
|
|
27671
27755
|
hasMore = results.length > pageSize;
|
|
@@ -36678,6 +36762,24 @@ customUrlsRoutes.post("/:id/delete", async (c) => {
|
|
|
36678
36762
|
});
|
|
36679
36763
|
//#endregion
|
|
36680
36764
|
//#region src/lib/api-posts.ts
|
|
36765
|
+
/**
|
|
36766
|
+
* The order `GET /api/posts` and `jant_posts_list` walk Posts in.
|
|
36767
|
+
*
|
|
36768
|
+
* Published Posts run newest-published first, pins ignored: a Post's place
|
|
36769
|
+
* then depends on its own publication alone, and a reply added to an old
|
|
36770
|
+
* Thread doesn't lift the root past a walk's cursor. Drafts keep the editing
|
|
36771
|
+
* order the composer's draft list reads, last edited first.
|
|
36772
|
+
*
|
|
36773
|
+
* @param status - The status the list is filtered to
|
|
36774
|
+
* @returns The `PostFilters` ordering fields for that list
|
|
36775
|
+
* @example
|
|
36776
|
+
* posts.listPage({ status, ...apiPostListOrder(status) }, { limit: 100 });
|
|
36777
|
+
*/ function apiPostListOrder(status) {
|
|
36778
|
+
return status === "draft" ? {} : {
|
|
36779
|
+
sortBy: "published",
|
|
36780
|
+
ignorePinnedSort: true
|
|
36781
|
+
};
|
|
36782
|
+
}
|
|
36681
36783
|
function toApiAttachment(media, r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix) {
|
|
36682
36784
|
const publicUrl = getPublicUrlForProvider(media.provider, r2PublicUrl, s3PublicUrl, localPublicUrl);
|
|
36683
36785
|
const url = getMediaUrl(media.storageKey, publicUrl, sitePathPrefix);
|
|
@@ -36715,7 +36817,7 @@ function toApiAttachment(media, r2PublicUrl, imageTransformUrl, s3PublicUrl, loc
|
|
|
36715
36817
|
chars: media.chars
|
|
36716
36818
|
};
|
|
36717
36819
|
}
|
|
36718
|
-
function toApiPost(post, extras
|
|
36820
|
+
function toApiPost(post, extras) {
|
|
36719
36821
|
const { title, url, ...rest } = post;
|
|
36720
36822
|
const displayTitle = getPostDisplayTitle(post);
|
|
36721
36823
|
if (post.format === "quote") return {
|
|
@@ -36733,6 +36835,46 @@ function toApiPost(post, extras = {}) {
|
|
|
36733
36835
|
url: url ?? null
|
|
36734
36836
|
};
|
|
36735
36837
|
}
|
|
36838
|
+
/**
|
|
36839
|
+
* API responses for Posts already loaded. Attachments, Thread Post counts,
|
|
36840
|
+
* and (when asked) Thread collections are each read in one batch for the
|
|
36841
|
+
* whole set, so a page costs the same few round trips however long it is.
|
|
36842
|
+
*
|
|
36843
|
+
* @param deps - Services and app config; a request's `c.var` or an MCP context
|
|
36844
|
+
* @param posts - Posts to respond with, in order
|
|
36845
|
+
* @param options - `collectionIds` adds each Post's shared Thread collections
|
|
36846
|
+
* @returns One response per Post, in the same order
|
|
36847
|
+
* @example
|
|
36848
|
+
* const responses = await loadApiPostResponses(c.var, page.posts);
|
|
36849
|
+
*/ async function loadApiPostResponses(deps, posts, options = {}) {
|
|
36850
|
+
if (posts.length === 0) return [];
|
|
36851
|
+
const { services, appConfig } = deps;
|
|
36852
|
+
const postIds = posts.map((post) => post.id);
|
|
36853
|
+
const [mediaMap, threadPostCounts, collectionsMap] = await Promise.all([
|
|
36854
|
+
services.media.getByPostIds(postIds),
|
|
36855
|
+
services.posts.countThreadPosts(posts.map((post) => post.threadId)),
|
|
36856
|
+
options.collectionIds ? services.collections.getCollectionsByPostIds(postIds) : Promise.resolve(null)
|
|
36857
|
+
]);
|
|
36858
|
+
return posts.map((post) => toApiPost(post, {
|
|
36859
|
+
threadPostCount: threadPostCounts.get(post.threadId) ?? 0,
|
|
36860
|
+
attachments: (mediaMap.get(post.id) ?? []).map((media) => toApiAttachment(media, appConfig.r2PublicUrl, appConfig.imageTransformUrl, appConfig.s3PublicUrl, appConfig.localPublicUrl, appConfig.sitePathPrefix)),
|
|
36861
|
+
...collectionsMap ? { collectionIds: (collectionsMap.get(post.id) ?? []).map((collection) => collection.id) } : {}
|
|
36862
|
+
}));
|
|
36863
|
+
}
|
|
36864
|
+
/**
|
|
36865
|
+
* One Post's API response. See {@link loadApiPostResponses}.
|
|
36866
|
+
*
|
|
36867
|
+
* @param deps - Services and app config
|
|
36868
|
+
* @param post - The Post
|
|
36869
|
+
* @param options - `collectionIds` adds the Post's shared Thread collections
|
|
36870
|
+
* @returns The Post's response
|
|
36871
|
+
* @example
|
|
36872
|
+
* return c.json(await loadApiPostResponse(c.var, post));
|
|
36873
|
+
*/ async function loadApiPostResponse(deps, post, options = {}) {
|
|
36874
|
+
const [response] = await loadApiPostResponses(deps, [post], options);
|
|
36875
|
+
if (!response) throw new Error(`No response built for post ${post.id}`);
|
|
36876
|
+
return response;
|
|
36877
|
+
}
|
|
36736
36878
|
//#endregion
|
|
36737
36879
|
//#region src/lib/address.ts
|
|
36738
36880
|
/**
|
|
@@ -36795,18 +36937,17 @@ var PostSlugQuerySchema = z.discriminatedUnion("mode", [z.object({
|
|
|
36795
36937
|
})]);
|
|
36796
36938
|
postsApiRoutes.get("/", requireAuthApi(), async (c) => {
|
|
36797
36939
|
const { format, status, cursor, limit } = parseValidated(ListPostsQuerySchema, c.req.query());
|
|
36940
|
+
const listStatus = status ?? "published";
|
|
36798
36941
|
const { posts, nextCursor } = await c.var.services.posts.listPage({
|
|
36799
36942
|
format,
|
|
36800
|
-
status:
|
|
36943
|
+
status: listStatus,
|
|
36944
|
+
...apiPostListOrder(listStatus)
|
|
36801
36945
|
}, {
|
|
36802
36946
|
cursor,
|
|
36803
36947
|
limit
|
|
36804
36948
|
});
|
|
36805
|
-
const postIds = posts.map((p) => p.id);
|
|
36806
|
-
const mediaMap = await c.var.services.media.getByPostIds(postIds);
|
|
36807
|
-
const { r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix } = c.var.appConfig;
|
|
36808
36949
|
return c.json({
|
|
36809
|
-
posts:
|
|
36950
|
+
posts: await loadApiPostResponses(c.var, posts),
|
|
36810
36951
|
nextCursor
|
|
36811
36952
|
});
|
|
36812
36953
|
});
|
|
@@ -36832,20 +36973,10 @@ postsApiRoutes.get("/:id/content", requireAuthApi(), async (c) => {
|
|
|
36832
36973
|
});
|
|
36833
36974
|
postsApiRoutes.get("/:id", requireAuthApi(), async (c) => {
|
|
36834
36975
|
const id = parseIdParam(c.req.param("id"), ID_PREFIX.post);
|
|
36835
|
-
const [post,
|
|
36836
|
-
c.var.services.posts.getById(id),
|
|
36837
|
-
c.var.services.media.getByPostId(id),
|
|
36838
|
-
c.var.services.collections.getCollectionsByPostId(id),
|
|
36839
|
-
c.var.services.posts.getThreadPosition(id)
|
|
36840
|
-
]);
|
|
36976
|
+
const [post, threadPosition] = await Promise.all([c.var.services.posts.getById(id), c.var.services.posts.getThreadPosition(id)]);
|
|
36841
36977
|
const foundPost = assertFound(post, "Post");
|
|
36842
|
-
const { r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix } = c.var.appConfig;
|
|
36843
|
-
const collectionIds = threadCollections.map((col) => col.id);
|
|
36844
36978
|
return c.json({
|
|
36845
|
-
...
|
|
36846
|
-
collectionIds,
|
|
36847
|
-
attachments: mediaList.map((m) => toApiAttachment(m, r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix))
|
|
36848
|
-
}),
|
|
36979
|
+
...await loadApiPostResponse(c.var, foundPost, { collectionIds: true }),
|
|
36849
36980
|
threadPosition
|
|
36850
36981
|
});
|
|
36851
36982
|
});
|
|
@@ -36885,10 +37016,8 @@ postsApiRoutes.post("/", requireAuthApi(), async (c) => {
|
|
|
36885
37016
|
maxParagraphs: c.var.appConfig.summaryMaxParagraphs,
|
|
36886
37017
|
maxChars: c.var.appConfig.summaryMaxChars
|
|
36887
37018
|
});
|
|
36888
|
-
const mediaList = await c.var.services.media.getByPostId(post.id);
|
|
36889
|
-
const { r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix } = c.var.appConfig;
|
|
36890
37019
|
await triggerGitHubSyncInline(c);
|
|
36891
|
-
return c.json(
|
|
37020
|
+
return c.json(await loadApiPostResponse(c.var, post), 201);
|
|
36892
37021
|
});
|
|
36893
37022
|
postsApiRoutes.put("/:id", requireAuthApi(), async (c) => {
|
|
36894
37023
|
const id = parseIdParam(c.req.param("id"), ID_PREFIX.post);
|
|
@@ -36924,9 +37053,7 @@ postsApiRoutes.put("/:id", requireAuthApi(), async (c) => {
|
|
|
36924
37053
|
maxChars: c.var.appConfig.summaryMaxChars
|
|
36925
37054
|
}), "Post");
|
|
36926
37055
|
await triggerGitHubSyncInline(c);
|
|
36927
|
-
|
|
36928
|
-
const { r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix } = c.var.appConfig;
|
|
36929
|
-
return c.json(toApiPost(post, { attachments: mediaList.map((m) => toApiAttachment(m, r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix)) }));
|
|
37056
|
+
return c.json(await loadApiPostResponse(c.var, post));
|
|
36930
37057
|
});
|
|
36931
37058
|
var SetLanguageSchema = z.object({ language: ContentLanguageSchema });
|
|
36932
37059
|
var TranslationCandidatesQuerySchema = z.object({
|
|
@@ -37039,6 +37166,417 @@ postsApiRoutes.delete("/:id", requireAuthApi(), async (c) => {
|
|
|
37039
37166
|
return c.json({ success: true });
|
|
37040
37167
|
});
|
|
37041
37168
|
//#endregion
|
|
37169
|
+
//#region src/lib/tiptap-to-markdown.ts
|
|
37170
|
+
/**
|
|
37171
|
+
* Tiptap JSON → Markdown Converter
|
|
37172
|
+
*
|
|
37173
|
+
* Converts Tiptap JSON documents to Markdown using the official
|
|
37174
|
+
* Tiptap MarkdownManager and Jant's shared markdown schema.
|
|
37175
|
+
*/
|
|
37176
|
+
/**
|
|
37177
|
+
* Converts a Tiptap JSON document to a Markdown string.
|
|
37178
|
+
*
|
|
37179
|
+
* Throws rather than returning an empty string: a caller writing the result
|
|
37180
|
+
* somewhere (an export, a text attachment) would otherwise replace the
|
|
37181
|
+
* content with nothing and say nothing.
|
|
37182
|
+
*
|
|
37183
|
+
* @param json - Tiptap JSON document string
|
|
37184
|
+
* @returns Markdown string
|
|
37185
|
+
* @throws {SyntaxError} When `json` is not JSON
|
|
37186
|
+
* @throws {Error} When the root node is not a `doc`
|
|
37187
|
+
*
|
|
37188
|
+
* @example
|
|
37189
|
+
* ```ts
|
|
37190
|
+
* const md = tiptapJsonToMarkdown('{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Hello"}]}]}');
|
|
37191
|
+
* // "Hello"
|
|
37192
|
+
* ```
|
|
37193
|
+
*/ function tiptapJsonToMarkdown(json) {
|
|
37194
|
+
const doc = JSON.parse(json);
|
|
37195
|
+
if (doc.type !== "doc") throw new Error(`A TipTap body's root must be a doc node, not ${JSON.stringify(doc.type)}.`);
|
|
37196
|
+
return serializeMarkdownDocument(doc).trimEnd();
|
|
37197
|
+
}
|
|
37198
|
+
//#endregion
|
|
37199
|
+
//#region src/lib/api-public-posts.ts
|
|
37200
|
+
/**
|
|
37201
|
+
* Public API Post responses
|
|
37202
|
+
*
|
|
37203
|
+
* The reading view of a Post that `/api/public/*` returns: rendered body or
|
|
37204
|
+
* Markdown, public permalink, and public collection references.
|
|
37205
|
+
*/
|
|
37206
|
+
/**
|
|
37207
|
+
* The public Markdown for a post, or null for a historical body that isn't
|
|
37208
|
+
* TipTap JSON. One unreadable row answers null and is logged, rather than
|
|
37209
|
+
* failing the whole listing; `bodyHtml` still falls back to stored HTML.
|
|
37210
|
+
*/ function toPublicBodyMarkdown(postId, body) {
|
|
37211
|
+
try {
|
|
37212
|
+
return tiptapJsonToMarkdown(body);
|
|
37213
|
+
} catch (error) {
|
|
37214
|
+
console.error(`Couldn't convert the body of post ${postId} to Markdown`, error);
|
|
37215
|
+
return null;
|
|
37216
|
+
}
|
|
37217
|
+
}
|
|
37218
|
+
/**
|
|
37219
|
+
* One Post's reading view, from its attachments, its Thread's collections, and
|
|
37220
|
+
* its Thread's Post count.
|
|
37221
|
+
*
|
|
37222
|
+
* @param post - The Post
|
|
37223
|
+
* @param related - What was read about it in the same batch as its page
|
|
37224
|
+
* @param appConfig - Media URLs and the site path prefix
|
|
37225
|
+
* @param options - `content: "markdown"` returns `bodyMarkdown` instead of the
|
|
37226
|
+
* rendered body
|
|
37227
|
+
* @returns The public response
|
|
37228
|
+
* @example
|
|
37229
|
+
* toPublicPost(post, { media: [], collections: [], threadPostCount: 1 }, config);
|
|
37230
|
+
*/ function toPublicPost(post, related, appConfig, options) {
|
|
37231
|
+
const { r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix, storageDriver } = appConfig;
|
|
37232
|
+
const previewImagePublicUrl = getPublicUrlForProvider(storageDriver, r2PublicUrl, s3PublicUrl, localPublicUrl);
|
|
37233
|
+
const previewImageUrl = post.previewImageKey ? getImageUrl(getMediaUrl(post.previewImageKey, previewImagePublicUrl, sitePathPrefix), imageTransformUrl, {
|
|
37234
|
+
width: 1280,
|
|
37235
|
+
quality: 80,
|
|
37236
|
+
format: "auto",
|
|
37237
|
+
fit: "scale-down"
|
|
37238
|
+
}) : null;
|
|
37239
|
+
const base = {
|
|
37240
|
+
id: post.id,
|
|
37241
|
+
format: post.format,
|
|
37242
|
+
status: "published",
|
|
37243
|
+
visibility: post.visibility,
|
|
37244
|
+
slug: post.slug,
|
|
37245
|
+
permalink: toPublicPath(`/${post.slug}`, sitePathPrefix),
|
|
37246
|
+
quoteText: post.quoteText,
|
|
37247
|
+
summary: post.summary,
|
|
37248
|
+
rating: post.rating,
|
|
37249
|
+
previewKind: post.previewKind,
|
|
37250
|
+
previewProvider: post.previewProvider,
|
|
37251
|
+
previewImageUrl,
|
|
37252
|
+
replyToId: post.replyToId,
|
|
37253
|
+
threadId: post.threadId,
|
|
37254
|
+
language: post.language,
|
|
37255
|
+
translationGroupId: post.translationGroupId,
|
|
37256
|
+
quietReply: post.quietReply,
|
|
37257
|
+
pinnedAt: post.pinnedAt,
|
|
37258
|
+
featuredAt: post.featuredAt,
|
|
37259
|
+
publishedAt: post.publishedAt,
|
|
37260
|
+
lastActivityAt: post.lastActivityAt,
|
|
37261
|
+
threadUpdatedAt: post.threadUpdatedAt,
|
|
37262
|
+
threadPostCount: related.threadPostCount,
|
|
37263
|
+
createdAt: post.createdAt,
|
|
37264
|
+
updatedAt: post.updatedAt,
|
|
37265
|
+
attachments: related.media.map((media) => toApiAttachment(media, r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix)),
|
|
37266
|
+
collections: related.collections.map((collection) => ({
|
|
37267
|
+
id: collection.id,
|
|
37268
|
+
slug: collection.slug,
|
|
37269
|
+
title: collection.title,
|
|
37270
|
+
url: toPublicPath(getCollectionPagePath(collection.slug), sitePathPrefix)
|
|
37271
|
+
}))
|
|
37272
|
+
};
|
|
37273
|
+
const contentFields = options?.content === "markdown" ? { bodyMarkdown: post.body ? toPublicBodyMarkdown(post.id, post.body) : null } : {
|
|
37274
|
+
bodyHtml: post.bodyHtml,
|
|
37275
|
+
bodyText: post.bodyText
|
|
37276
|
+
};
|
|
37277
|
+
if (post.format === "quote") return {
|
|
37278
|
+
...base,
|
|
37279
|
+
...contentFields,
|
|
37280
|
+
sourceName: post.title,
|
|
37281
|
+
sourceUrl: post.url
|
|
37282
|
+
};
|
|
37283
|
+
return {
|
|
37284
|
+
...base,
|
|
37285
|
+
...contentFields,
|
|
37286
|
+
title: post.title,
|
|
37287
|
+
url: post.url
|
|
37288
|
+
};
|
|
37289
|
+
}
|
|
37290
|
+
/**
|
|
37291
|
+
* Reading-view responses for Posts already loaded. Attachments, Thread
|
|
37292
|
+
* collections, and Thread Post counts are each read in one batch.
|
|
37293
|
+
*
|
|
37294
|
+
* @param deps - Services and app config; a request's `c.var`
|
|
37295
|
+
* @param posts - Posts to respond with, in order
|
|
37296
|
+
* @param options - `content: "markdown"` returns `bodyMarkdown`
|
|
37297
|
+
* @returns One response per Post, in the same order
|
|
37298
|
+
* @example
|
|
37299
|
+
* const responses = await loadPublicPostResponses(c.var, page.posts, {});
|
|
37300
|
+
*/ async function loadPublicPostResponses(deps, posts, options = {}) {
|
|
37301
|
+
if (posts.length === 0) return [];
|
|
37302
|
+
const { services, appConfig } = deps;
|
|
37303
|
+
const postIds = posts.map((post) => post.id);
|
|
37304
|
+
const [mediaMap, collectionsMap, threadPostCounts] = await Promise.all([
|
|
37305
|
+
services.media.getByPostIds(postIds),
|
|
37306
|
+
services.collections.getCollectionsByPostIds(postIds),
|
|
37307
|
+
services.posts.countThreadPosts(posts.map((post) => post.threadId))
|
|
37308
|
+
]);
|
|
37309
|
+
return posts.map((post) => toPublicPost(post, {
|
|
37310
|
+
media: mediaMap.get(post.id) ?? [],
|
|
37311
|
+
collections: collectionsMap.get(post.id) ?? [],
|
|
37312
|
+
threadPostCount: threadPostCounts.get(post.threadId) ?? 0
|
|
37313
|
+
}, appConfig, options));
|
|
37314
|
+
}
|
|
37315
|
+
//#endregion
|
|
37316
|
+
//#region src/lib/api-threads.ts
|
|
37317
|
+
/**
|
|
37318
|
+
* API Thread responses
|
|
37319
|
+
*
|
|
37320
|
+
* The Thread object the author API, the public API, and MCP return. One shape
|
|
37321
|
+
* for all three, parameterized by how each surface renders a Post and how it
|
|
37322
|
+
* names one: the author API's Post is the editing view, the public API's the
|
|
37323
|
+
* reading view.
|
|
37324
|
+
*/
|
|
37325
|
+
/**
|
|
37326
|
+
* Every Post a set of Thread responses renders, so their attachments and
|
|
37327
|
+
* counts can be read in one batch: each root, then the replies its fold shows.
|
|
37328
|
+
*
|
|
37329
|
+
* @param summaries - Threads to respond with
|
|
37330
|
+
* @returns The Posts, each once
|
|
37331
|
+
* @example
|
|
37332
|
+
* const responses = await render(collectThreadResponsePosts(summaries));
|
|
37333
|
+
*/ function collectThreadResponsePosts(summaries) {
|
|
37334
|
+
const seen = /* @__PURE__ */ new Map();
|
|
37335
|
+
for (const { root, fold } of summaries) {
|
|
37336
|
+
seen.set(root.id, root);
|
|
37337
|
+
if (!fold) continue;
|
|
37338
|
+
for (const post of [
|
|
37339
|
+
...fold.leadingReplies,
|
|
37340
|
+
...fold.trailingReplies,
|
|
37341
|
+
fold.latestReply
|
|
37342
|
+
]) seen.set(post.id, post);
|
|
37343
|
+
}
|
|
37344
|
+
return [...seen.values()];
|
|
37345
|
+
}
|
|
37346
|
+
/**
|
|
37347
|
+
* One Thread's response, from Post responses already rendered.
|
|
37348
|
+
*
|
|
37349
|
+
* @param summary - The Thread
|
|
37350
|
+
* @param respond - The rendered response for a Post in it
|
|
37351
|
+
* @param reference - How the surface names the Post a fold leaves out
|
|
37352
|
+
* @returns The Thread object
|
|
37353
|
+
* @example
|
|
37354
|
+
* toApiThreadResponse(summary, (post) => byId.get(post.id)!, toGap);
|
|
37355
|
+
*/ function toApiThreadResponse(summary, respond, reference) {
|
|
37356
|
+
const { root, fold } = summary;
|
|
37357
|
+
const response = {
|
|
37358
|
+
id: root.id,
|
|
37359
|
+
postCount: summary.postCount,
|
|
37360
|
+
lastActivityAt: root.lastActivityAt,
|
|
37361
|
+
threadUpdatedAt: root.threadUpdatedAt,
|
|
37362
|
+
root: respond(root)
|
|
37363
|
+
};
|
|
37364
|
+
if (fold === null) response.fold = {
|
|
37365
|
+
leading: [],
|
|
37366
|
+
hidden: 0,
|
|
37367
|
+
gap: null,
|
|
37368
|
+
trailing: []
|
|
37369
|
+
};
|
|
37370
|
+
else if (fold) response.fold = {
|
|
37371
|
+
leading: fold.leadingReplies.map(respond),
|
|
37372
|
+
hidden: fold.hiddenCount,
|
|
37373
|
+
gap: fold.firstHiddenReply ? reference(fold.firstHiddenReply) : null,
|
|
37374
|
+
trailing: [...fold.trailingReplies, fold.latestReply].map(respond)
|
|
37375
|
+
};
|
|
37376
|
+
return response;
|
|
37377
|
+
}
|
|
37378
|
+
/**
|
|
37379
|
+
* The author API's and MCP's Thread objects for Threads already listed.
|
|
37380
|
+
*
|
|
37381
|
+
* @param deps - Services and app config
|
|
37382
|
+
* @param summaries - Threads to respond with, in order
|
|
37383
|
+
* @returns One Thread object per summary, in the same order
|
|
37384
|
+
* @example
|
|
37385
|
+
* const threads = await loadApiThreadResponses(c.var, page.threads);
|
|
37386
|
+
*/ async function loadApiThreadResponses(deps, summaries) {
|
|
37387
|
+
return buildThreadResponses(summaries, (posts) => loadApiPostResponses(deps, posts), (post) => ({
|
|
37388
|
+
id: post.id,
|
|
37389
|
+
slug: post.slug
|
|
37390
|
+
}));
|
|
37391
|
+
}
|
|
37392
|
+
/**
|
|
37393
|
+
* The public API's Thread objects for Threads already listed.
|
|
37394
|
+
*
|
|
37395
|
+
* @param deps - Services and app config
|
|
37396
|
+
* @param summaries - Threads to respond with, in order
|
|
37397
|
+
* @param options - `content: "markdown"` returns `bodyMarkdown` on every Post
|
|
37398
|
+
* @returns One Thread object per summary, in the same order
|
|
37399
|
+
* @example
|
|
37400
|
+
* const threads = await loadPublicThreadResponses(c.var, page.threads, {});
|
|
37401
|
+
*/ async function loadPublicThreadResponses(deps, summaries, options = {}) {
|
|
37402
|
+
return buildThreadResponses(summaries, (posts) => loadPublicPostResponses(deps, posts, options), (post) => ({
|
|
37403
|
+
id: post.id,
|
|
37404
|
+
slug: post.slug,
|
|
37405
|
+
permalink: toPublicPath(`/${post.slug}`, deps.appConfig.sitePathPrefix)
|
|
37406
|
+
}));
|
|
37407
|
+
}
|
|
37408
|
+
/** Render every Post the Threads show in one batch, then assemble them. */ async function buildThreadResponses(summaries, render, reference) {
|
|
37409
|
+
const posts = collectThreadResponsePosts(summaries);
|
|
37410
|
+
const responses = await render(posts);
|
|
37411
|
+
const byId = new Map(posts.map((post, index) => [post.id, responses[index]]));
|
|
37412
|
+
return summaries.map((summary) => toApiThreadResponse(summary, (post) => {
|
|
37413
|
+
const response = byId.get(post.id);
|
|
37414
|
+
if (!response) throw new Error(`No response built for post ${post.id}`);
|
|
37415
|
+
return response;
|
|
37416
|
+
}, reference));
|
|
37417
|
+
}
|
|
37418
|
+
//#endregion
|
|
37419
|
+
//#region src/lib/thread-query.ts
|
|
37420
|
+
/**
|
|
37421
|
+
* Thread list queries
|
|
37422
|
+
*
|
|
37423
|
+
* Reads the filter dimensions a Thread list takes — the archive's, from the
|
|
37424
|
+
* same registry — out of an HTTP query string or MCP arguments, so the public
|
|
37425
|
+
* API, the author API, and MCP accept one vocabulary.
|
|
37426
|
+
*
|
|
37427
|
+
* One word differs from the archive page. A Thread list left unfiltered shows
|
|
37428
|
+
* what the homepage shows, so it needs a word for "every visibility a reader
|
|
37429
|
+
* may see": `visibility=any`. The registry's `visibility=all` is an old
|
|
37430
|
+
* spelling of leaving the parameter out, which here would mean the homepage's
|
|
37431
|
+
* set — the opposite of what the word says — so a Thread list refuses it.
|
|
37432
|
+
*/ var READER_VISIBILITIES = [
|
|
37433
|
+
"public",
|
|
37434
|
+
"featured",
|
|
37435
|
+
"hidden",
|
|
37436
|
+
"any"
|
|
37437
|
+
];
|
|
37438
|
+
var AUTHOR_VISIBILITIES = [...READER_VISIBILITIES, "private"];
|
|
37439
|
+
/** Spellings the registry reads that stay valid here. */ var LEGACY_VISIBILITIES = ["latest_hidden"];
|
|
37440
|
+
function allowedVisibilities(audience) {
|
|
37441
|
+
return audience === "reader" ? READER_VISIBILITIES : AUTHOR_VISIBILITIES;
|
|
37442
|
+
}
|
|
37443
|
+
/**
|
|
37444
|
+
* Read a Thread list's filter dimensions.
|
|
37445
|
+
*
|
|
37446
|
+
* @param read - Reads one parameter; `undefined` when absent
|
|
37447
|
+
* @param present - Every parameter name the request carries
|
|
37448
|
+
* @param options.allow - The endpoint's own parameters, which aren't
|
|
37449
|
+
* dimensions; anything else unknown is refused
|
|
37450
|
+
* @param options.audience - A reader may not name `private`
|
|
37451
|
+
* @param options.loadCollections - Loads the collection vocabulary, called only
|
|
37452
|
+
* when a collection is named
|
|
37453
|
+
* @returns The selection, or `empty` when a named collection doesn't exist
|
|
37454
|
+
* @throws {ValidationError} On an unknown parameter or an unreadable value
|
|
37455
|
+
* @example
|
|
37456
|
+
* const parsed = await parseThreadSelection(read, Object.keys(query), {
|
|
37457
|
+
* allow: ["cursor", "limit"],
|
|
37458
|
+
* audience: "reader",
|
|
37459
|
+
* loadCollections: () => services.collections.list(),
|
|
37460
|
+
* });
|
|
37461
|
+
*/ async function parseThreadSelection(read, present, options) {
|
|
37462
|
+
const visibility = read("visibility");
|
|
37463
|
+
if (visibility !== void 0) {
|
|
37464
|
+
const allowed = allowedVisibilities(options.audience);
|
|
37465
|
+
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.");
|
|
37466
|
+
if (!allowed.includes(visibility) && !LEGACY_VISIBILITIES.includes(visibility)) throw new ValidationError(`Invalid visibility value. Allowed: ${allowed.join(", ")}`);
|
|
37467
|
+
}
|
|
37468
|
+
const includeHidden = visibility === "any";
|
|
37469
|
+
const readDimension = (key) => key === "visibility" && includeHidden ? void 0 : read(key);
|
|
37470
|
+
const parsed = parsePostFilterSelectionStrict(readDimension, present, { collections: readCollectionSlugs(readDimension).length > 0 ? buildCollectionVocabulary(await options.loadCollections()) : EMPTY_COLLECTION_VOCABULARY }, { allow: options.allow });
|
|
37471
|
+
if (parsed.ok) return {
|
|
37472
|
+
kind: "selection",
|
|
37473
|
+
selection: parsed.selection,
|
|
37474
|
+
includeHidden
|
|
37475
|
+
};
|
|
37476
|
+
if (parsed.issues.every((issue) => issue.param === "collection")) return { kind: "empty" };
|
|
37477
|
+
throw new ValidationError(parsed.issues[0]?.message ?? "Validation failed");
|
|
37478
|
+
}
|
|
37479
|
+
/**
|
|
37480
|
+
* Read `include`: a comma-separated list of extras to attach to each Thread.
|
|
37481
|
+
*
|
|
37482
|
+
* @param raw - The parameter's value, or `undefined`
|
|
37483
|
+
* @returns Whether the fold was asked for
|
|
37484
|
+
* @throws {ValidationError} On a value this endpoint doesn't offer
|
|
37485
|
+
* @example
|
|
37486
|
+
* parseThreadInclude("fold"); // { fold: true }
|
|
37487
|
+
*/ function parseThreadInclude(raw) {
|
|
37488
|
+
if (raw === void 0 || raw === "") return { fold: false };
|
|
37489
|
+
const values = raw.split(",").map((value) => value.trim());
|
|
37490
|
+
for (const value of values) if (value !== "fold") throw new ValidationError(`Invalid include value "${value}". Allowed: fold`);
|
|
37491
|
+
return { fold: values.includes("fold") };
|
|
37492
|
+
}
|
|
37493
|
+
//#endregion
|
|
37494
|
+
//#region src/routes/api/threads.ts
|
|
37495
|
+
/**
|
|
37496
|
+
* Threads API Routes
|
|
37497
|
+
*
|
|
37498
|
+
* The author's view of Threads: every status and visibility, Posts in the
|
|
37499
|
+
* editing view. The reader's view is `/api/public/threads`.
|
|
37500
|
+
*/ var threadsApiRoutes = new Hono();
|
|
37501
|
+
threadsApiRoutes.use("*", requireAuthApi());
|
|
37502
|
+
/** The list's own parameters; everything else is a filter dimension. */ var ListThreadsQuerySchema$1 = z.object({
|
|
37503
|
+
status: StatusSchema.optional(),
|
|
37504
|
+
lang: ContentLanguageSchema.optional(),
|
|
37505
|
+
sort: z.enum(THREAD_SORTS).optional(),
|
|
37506
|
+
include: z.string().optional(),
|
|
37507
|
+
cursor: z.string().optional(),
|
|
37508
|
+
limit: z.coerce.number().int().min(1).max(100).optional().default(20)
|
|
37509
|
+
});
|
|
37510
|
+
var LIST_PARAMS$1 = [
|
|
37511
|
+
"status",
|
|
37512
|
+
"lang",
|
|
37513
|
+
"sort",
|
|
37514
|
+
"include",
|
|
37515
|
+
"cursor",
|
|
37516
|
+
"limit"
|
|
37517
|
+
];
|
|
37518
|
+
var GetThreadQuerySchema$1 = z.object({ include: z.string().optional() });
|
|
37519
|
+
var ListThreadPostsQuerySchema$1 = z.object({
|
|
37520
|
+
status: StatusSchema.optional(),
|
|
37521
|
+
cursor: z.string().optional(),
|
|
37522
|
+
limit: z.coerce.number().int().min(1).max(100).optional().default(100)
|
|
37523
|
+
});
|
|
37524
|
+
threadsApiRoutes.get("/", async (c) => {
|
|
37525
|
+
const query = parseValidated(ListThreadsQuerySchema$1, c.req.query());
|
|
37526
|
+
const { fold } = parseThreadInclude(query.include);
|
|
37527
|
+
const parsed = await parseThreadSelection((key) => c.req.query(key), Object.keys(c.req.query()), {
|
|
37528
|
+
allow: LIST_PARAMS$1,
|
|
37529
|
+
audience: "author",
|
|
37530
|
+
loadCollections: () => c.var.services.collections.list()
|
|
37531
|
+
});
|
|
37532
|
+
if (parsed.kind === "empty") return c.json({
|
|
37533
|
+
threads: [],
|
|
37534
|
+
nextCursor: null
|
|
37535
|
+
});
|
|
37536
|
+
const { threads, nextCursor } = await c.var.services.threads.listThreads({
|
|
37537
|
+
audience: "author",
|
|
37538
|
+
status: query.status,
|
|
37539
|
+
selection: parsed.selection,
|
|
37540
|
+
lang: query.lang,
|
|
37541
|
+
sort: query.sort,
|
|
37542
|
+
fold
|
|
37543
|
+
}, {
|
|
37544
|
+
cursor: query.cursor,
|
|
37545
|
+
limit: query.limit
|
|
37546
|
+
});
|
|
37547
|
+
return c.json({
|
|
37548
|
+
threads: await loadApiThreadResponses(c.var, threads),
|
|
37549
|
+
nextCursor
|
|
37550
|
+
});
|
|
37551
|
+
});
|
|
37552
|
+
threadsApiRoutes.get("/:id", async (c) => {
|
|
37553
|
+
const id = parseIdParam(c.req.param("id"), ID_PREFIX.post);
|
|
37554
|
+
const { include } = parseValidated(GetThreadQuerySchema$1, c.req.query());
|
|
37555
|
+
const root = await c.var.services.threads.findRoot({ id }, "author");
|
|
37556
|
+
if (!root) throw new NotFoundError("Thread");
|
|
37557
|
+
const summaries = await c.var.services.threads.summarize([root], parseThreadInclude(include));
|
|
37558
|
+
const [thread] = await loadApiThreadResponses(c.var, summaries);
|
|
37559
|
+
if (!thread) throw new NotFoundError("Thread");
|
|
37560
|
+
return c.json(thread);
|
|
37561
|
+
});
|
|
37562
|
+
threadsApiRoutes.get("/:id/posts", async (c) => {
|
|
37563
|
+
const id = parseIdParam(c.req.param("id"), ID_PREFIX.post);
|
|
37564
|
+
const { status, cursor, limit } = parseValidated(ListThreadPostsQuerySchema$1, c.req.query());
|
|
37565
|
+
const root = await c.var.services.threads.findRoot({ id }, "author");
|
|
37566
|
+
if (!root) throw new NotFoundError("Thread");
|
|
37567
|
+
const { posts, nextCursor } = await c.var.services.threads.listPosts(root.id, {
|
|
37568
|
+
audience: "author",
|
|
37569
|
+
status
|
|
37570
|
+
}, {
|
|
37571
|
+
cursor,
|
|
37572
|
+
limit
|
|
37573
|
+
});
|
|
37574
|
+
return c.json({
|
|
37575
|
+
posts: await loadApiPostResponses(c.var, posts),
|
|
37576
|
+
nextCursor
|
|
37577
|
+
});
|
|
37578
|
+
});
|
|
37579
|
+
//#endregion
|
|
37042
37580
|
//#region src/routes/api/attachments.ts
|
|
37043
37581
|
/**
|
|
37044
37582
|
* Attachments API Routes
|
|
@@ -38113,7 +38651,30 @@ function toSearchApiResult(post, snippet, sitePathPrefix) {
|
|
|
38113
38651
|
//#region src/routes/api/search.ts
|
|
38114
38652
|
/**
|
|
38115
38653
|
* Search API Routes
|
|
38116
|
-
*/ var
|
|
38654
|
+
*/ var DEFAULT_SEARCH_LIMIT = 20;
|
|
38655
|
+
var MAX_SEARCH_LIMIT = 50;
|
|
38656
|
+
/**
|
|
38657
|
+
* Read `limit` from the query string, clamped to 1–50.
|
|
38658
|
+
*
|
|
38659
|
+
* Clamped rather than rejected: the endpoint has always capped a large value
|
|
38660
|
+
* at 50, and a small one gets the same treatment. Anything that isn't a number
|
|
38661
|
+
* falls back to the default.
|
|
38662
|
+
*
|
|
38663
|
+
* @param value - Raw `limit` query parameter
|
|
38664
|
+
* @returns A page size between 1 and 50
|
|
38665
|
+
*
|
|
38666
|
+
* @example
|
|
38667
|
+
* ```ts
|
|
38668
|
+
* parseSearchLimit(undefined); // 20
|
|
38669
|
+
* parseSearchLimit("-1"); // 1
|
|
38670
|
+
* parseSearchLimit("500"); // 50
|
|
38671
|
+
* ```
|
|
38672
|
+
*/ function parseSearchLimit(value) {
|
|
38673
|
+
const parsed = value === void 0 ? NaN : Number.parseInt(value, 10);
|
|
38674
|
+
if (Number.isNaN(parsed)) return DEFAULT_SEARCH_LIMIT;
|
|
38675
|
+
return Math.min(Math.max(parsed, 1), MAX_SEARCH_LIMIT);
|
|
38676
|
+
}
|
|
38677
|
+
var searchApiRoutes = new Hono();
|
|
38117
38678
|
searchApiRoutes.use("*", requirePublicApiAccess());
|
|
38118
38679
|
searchApiRoutes.use("*", async (c, next) => rateLimit({
|
|
38119
38680
|
name: "search",
|
|
@@ -38124,12 +38685,12 @@ searchApiRoutes.get("/", async (c) => {
|
|
|
38124
38685
|
const query = c.req.query("q");
|
|
38125
38686
|
if (!query || query.trim().length === 0) throw new ValidationError("Query parameter 'q' is required");
|
|
38126
38687
|
if (query.length > 200) throw new ValidationError("Query too long");
|
|
38127
|
-
const
|
|
38128
|
-
const limit = limitParam ? Math.min(parseInt(limitParam, 10) || 20, 50) : 20;
|
|
38688
|
+
const limit = parseSearchLimit(c.req.query("limit"));
|
|
38129
38689
|
try {
|
|
38130
38690
|
const results = await c.var.services.search.search(query, {
|
|
38131
38691
|
limit,
|
|
38132
|
-
status: ["published"]
|
|
38692
|
+
status: ["published"],
|
|
38693
|
+
includePrivate: false
|
|
38133
38694
|
});
|
|
38134
38695
|
return c.json({
|
|
38135
38696
|
query,
|
|
@@ -38191,6 +38752,78 @@ var AddCollectionThreadToolSchema = z.object({
|
|
|
38191
38752
|
threadId: PostIdSchema
|
|
38192
38753
|
});
|
|
38193
38754
|
var RemoveCollectionThreadToolSchema = AddCollectionThreadToolSchema;
|
|
38755
|
+
/**
|
|
38756
|
+
* The filter dimensions `jant_threads_list` takes, spelled as the HTTP API
|
|
38757
|
+
* and the archive spell them. They reach the same registry parser as a query
|
|
38758
|
+
* string would, so the vocabularies can't drift.
|
|
38759
|
+
*/ var THREAD_FILTER_TOOL_PROPERTIES = {
|
|
38760
|
+
format: {
|
|
38761
|
+
type: "string",
|
|
38762
|
+
enum: [...FORMATS]
|
|
38763
|
+
},
|
|
38764
|
+
collection: {
|
|
38765
|
+
type: "string",
|
|
38766
|
+
description: "Collection slug, or several comma-separated"
|
|
38767
|
+
},
|
|
38768
|
+
year: {
|
|
38769
|
+
type: "integer",
|
|
38770
|
+
description: "Publication year (UTC)"
|
|
38771
|
+
},
|
|
38772
|
+
media: {
|
|
38773
|
+
type: "string",
|
|
38774
|
+
description: "any, none, or comma-separated kinds: image, video, audio, text, document"
|
|
38775
|
+
},
|
|
38776
|
+
title: {
|
|
38777
|
+
type: "string",
|
|
38778
|
+
enum: ["any", "none"]
|
|
38779
|
+
},
|
|
38780
|
+
replies: {
|
|
38781
|
+
type: "string",
|
|
38782
|
+
enum: ["any", "none"]
|
|
38783
|
+
},
|
|
38784
|
+
visibility: {
|
|
38785
|
+
type: "string",
|
|
38786
|
+
enum: [
|
|
38787
|
+
"public",
|
|
38788
|
+
"featured",
|
|
38789
|
+
"hidden",
|
|
38790
|
+
"private"
|
|
38791
|
+
]
|
|
38792
|
+
}
|
|
38793
|
+
};
|
|
38794
|
+
var ListThreadsToolSchema = z.object({
|
|
38795
|
+
cursor: z.string().optional(),
|
|
38796
|
+
limit: z.coerce.number().int().min(1).max(100).optional().default(20),
|
|
38797
|
+
status: StatusSchema.optional(),
|
|
38798
|
+
sort: z.enum(THREAD_SORTS).optional(),
|
|
38799
|
+
fold: z.boolean().optional(),
|
|
38800
|
+
lang: ContentLanguageSchema.optional(),
|
|
38801
|
+
format: z.string().optional(),
|
|
38802
|
+
collection: z.string().optional(),
|
|
38803
|
+
year: z.number().int().optional(),
|
|
38804
|
+
media: z.string().optional(),
|
|
38805
|
+
title: z.string().optional(),
|
|
38806
|
+
replies: z.string().optional(),
|
|
38807
|
+
visibility: z.string().optional()
|
|
38808
|
+
});
|
|
38809
|
+
var LIST_THREADS_OWN_PARAMS = [
|
|
38810
|
+
"cursor",
|
|
38811
|
+
"limit",
|
|
38812
|
+
"status",
|
|
38813
|
+
"sort",
|
|
38814
|
+
"fold",
|
|
38815
|
+
"lang"
|
|
38816
|
+
];
|
|
38817
|
+
var GetThreadToolSchema = z.object({
|
|
38818
|
+
id: PostIdSchema,
|
|
38819
|
+
fold: z.boolean().optional()
|
|
38820
|
+
});
|
|
38821
|
+
var ListThreadPostsToolSchema = z.object({
|
|
38822
|
+
id: PostIdSchema,
|
|
38823
|
+
cursor: z.string().optional(),
|
|
38824
|
+
limit: z.coerce.number().int().min(1).max(100).optional().default(100),
|
|
38825
|
+
status: StatusSchema.optional()
|
|
38826
|
+
});
|
|
38194
38827
|
var mcpTools = [
|
|
38195
38828
|
{
|
|
38196
38829
|
name: "jant_posts_list",
|
|
@@ -38218,9 +38851,11 @@ var mcpTools = [
|
|
|
38218
38851
|
},
|
|
38219
38852
|
async execute(args, context) {
|
|
38220
38853
|
const input = ListPostsToolSchema.parse(args ?? {});
|
|
38854
|
+
const status = input.status ?? "published";
|
|
38221
38855
|
const { posts, nextCursor } = await context.services.posts.listPage({
|
|
38222
38856
|
format: input.format,
|
|
38223
|
-
status
|
|
38857
|
+
status,
|
|
38858
|
+
...apiPostListOrder(status)
|
|
38224
38859
|
}, {
|
|
38225
38860
|
cursor: input.cursor,
|
|
38226
38861
|
limit: input.limit
|
|
@@ -38269,6 +38904,133 @@ var mcpTools = [
|
|
|
38269
38904
|
return content;
|
|
38270
38905
|
}
|
|
38271
38906
|
},
|
|
38907
|
+
{
|
|
38908
|
+
name: "jant_threads_list",
|
|
38909
|
+
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.",
|
|
38910
|
+
inputSchema: {
|
|
38911
|
+
type: "object",
|
|
38912
|
+
properties: {
|
|
38913
|
+
cursor: { type: "string" },
|
|
38914
|
+
limit: {
|
|
38915
|
+
type: "integer",
|
|
38916
|
+
minimum: 1,
|
|
38917
|
+
maximum: 100,
|
|
38918
|
+
default: 20
|
|
38919
|
+
},
|
|
38920
|
+
status: {
|
|
38921
|
+
type: "string",
|
|
38922
|
+
enum: [...STATUSES]
|
|
38923
|
+
},
|
|
38924
|
+
sort: {
|
|
38925
|
+
type: "string",
|
|
38926
|
+
enum: [...THREAD_SORTS]
|
|
38927
|
+
},
|
|
38928
|
+
fold: { type: "boolean" },
|
|
38929
|
+
lang: {
|
|
38930
|
+
type: "string",
|
|
38931
|
+
description: "BCP 47 content language"
|
|
38932
|
+
},
|
|
38933
|
+
...THREAD_FILTER_TOOL_PROPERTIES
|
|
38934
|
+
},
|
|
38935
|
+
additionalProperties: false
|
|
38936
|
+
},
|
|
38937
|
+
async execute(args, context) {
|
|
38938
|
+
const input = ListThreadsToolSchema.parse(args ?? {});
|
|
38939
|
+
const filterArgs = Object.fromEntries(Object.entries(input).filter(([key, value]) => value !== void 0 && !LIST_THREADS_OWN_PARAMS.includes(key)));
|
|
38940
|
+
const parsed = await parseThreadSelection((key) => {
|
|
38941
|
+
const value = filterArgs[key];
|
|
38942
|
+
return value === void 0 ? void 0 : String(value);
|
|
38943
|
+
}, Object.keys(filterArgs), {
|
|
38944
|
+
allow: [],
|
|
38945
|
+
audience: "author",
|
|
38946
|
+
loadCollections: () => context.services.collections.list()
|
|
38947
|
+
});
|
|
38948
|
+
if (parsed.kind === "empty") return {
|
|
38949
|
+
threads: [],
|
|
38950
|
+
nextCursor: null
|
|
38951
|
+
};
|
|
38952
|
+
const { threads, nextCursor } = await context.services.threads.listThreads({
|
|
38953
|
+
audience: "author",
|
|
38954
|
+
status: input.status,
|
|
38955
|
+
selection: parsed.selection,
|
|
38956
|
+
lang: input.lang,
|
|
38957
|
+
sort: input.sort,
|
|
38958
|
+
fold: input.fold
|
|
38959
|
+
}, {
|
|
38960
|
+
cursor: input.cursor,
|
|
38961
|
+
limit: input.limit
|
|
38962
|
+
});
|
|
38963
|
+
return {
|
|
38964
|
+
threads: await loadApiThreadResponses(context, threads),
|
|
38965
|
+
nextCursor
|
|
38966
|
+
};
|
|
38967
|
+
}
|
|
38968
|
+
},
|
|
38969
|
+
{
|
|
38970
|
+
name: "jant_threads_get",
|
|
38971
|
+
description: "Get the Thread any post belongs to: its root and post count, and with fold the replies the homepage shows.",
|
|
38972
|
+
inputSchema: {
|
|
38973
|
+
type: "object",
|
|
38974
|
+
properties: {
|
|
38975
|
+
id: {
|
|
38976
|
+
type: "string",
|
|
38977
|
+
description: "TypeID of any post in the Thread"
|
|
38978
|
+
},
|
|
38979
|
+
fold: { type: "boolean" }
|
|
38980
|
+
},
|
|
38981
|
+
required: ["id"],
|
|
38982
|
+
additionalProperties: false
|
|
38983
|
+
},
|
|
38984
|
+
async execute(args, context) {
|
|
38985
|
+
const input = GetThreadToolSchema.parse(args ?? {});
|
|
38986
|
+
const root = await context.services.threads.findRoot({ id: input.id }, "author");
|
|
38987
|
+
if (!root) throw new NotFoundError("Thread");
|
|
38988
|
+
const [thread] = await loadApiThreadResponses(context, await context.services.threads.summarize([root], { fold: input.fold }));
|
|
38989
|
+
return thread;
|
|
38990
|
+
}
|
|
38991
|
+
},
|
|
38992
|
+
{
|
|
38993
|
+
name: "jant_threads_list_posts",
|
|
38994
|
+
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.",
|
|
38995
|
+
inputSchema: {
|
|
38996
|
+
type: "object",
|
|
38997
|
+
properties: {
|
|
38998
|
+
id: {
|
|
38999
|
+
type: "string",
|
|
39000
|
+
description: "TypeID of any post in the Thread"
|
|
39001
|
+
},
|
|
39002
|
+
cursor: { type: "string" },
|
|
39003
|
+
limit: {
|
|
39004
|
+
type: "integer",
|
|
39005
|
+
minimum: 1,
|
|
39006
|
+
maximum: 100,
|
|
39007
|
+
default: 100
|
|
39008
|
+
},
|
|
39009
|
+
status: {
|
|
39010
|
+
type: "string",
|
|
39011
|
+
enum: [...STATUSES]
|
|
39012
|
+
}
|
|
39013
|
+
},
|
|
39014
|
+
required: ["id"],
|
|
39015
|
+
additionalProperties: false
|
|
39016
|
+
},
|
|
39017
|
+
async execute(args, context) {
|
|
39018
|
+
const input = ListThreadPostsToolSchema.parse(args ?? {});
|
|
39019
|
+
const root = await context.services.threads.findRoot({ id: input.id }, "author");
|
|
39020
|
+
if (!root) throw new NotFoundError("Thread");
|
|
39021
|
+
const { posts, nextCursor } = await context.services.threads.listPosts(root.id, {
|
|
39022
|
+
audience: "author",
|
|
39023
|
+
status: input.status
|
|
39024
|
+
}, {
|
|
39025
|
+
cursor: input.cursor,
|
|
39026
|
+
limit: input.limit
|
|
39027
|
+
});
|
|
39028
|
+
return {
|
|
39029
|
+
posts: await serializePosts(posts, context),
|
|
39030
|
+
nextCursor
|
|
39031
|
+
};
|
|
39032
|
+
}
|
|
39033
|
+
},
|
|
38272
39034
|
{
|
|
38273
39035
|
name: "jant_posts_create",
|
|
38274
39036
|
description: "Create a post. Supports the same JSON body as POST /api/posts.",
|
|
@@ -38794,7 +39556,7 @@ var mcpTools = [
|
|
|
38794
39556
|
},
|
|
38795
39557
|
{
|
|
38796
39558
|
name: "jant_search_posts",
|
|
38797
|
-
description: "Search published posts.",
|
|
39559
|
+
description: "Search published posts, including private ones. Each result carries its visibility.",
|
|
38798
39560
|
inputSchema: {
|
|
38799
39561
|
type: "object",
|
|
38800
39562
|
properties: {
|
|
@@ -38817,12 +39579,16 @@ var mcpTools = [
|
|
|
38817
39579
|
const input = SearchPostsToolSchema.parse(args ?? {});
|
|
38818
39580
|
const results = await context.services.search.search(input.query, {
|
|
38819
39581
|
limit: input.limit,
|
|
38820
|
-
status: ["published"]
|
|
39582
|
+
status: ["published"],
|
|
39583
|
+
includePrivate: true
|
|
38821
39584
|
});
|
|
38822
39585
|
return {
|
|
38823
39586
|
count: results.length,
|
|
38824
39587
|
query: input.query,
|
|
38825
|
-
results: results.map((result) =>
|
|
39588
|
+
results: results.map((result) => ({
|
|
39589
|
+
...toSearchApiResult(result.post, result.snippet, context.appConfig.sitePathPrefix),
|
|
39590
|
+
visibility: result.post.visibility
|
|
39591
|
+
}))
|
|
38826
39592
|
};
|
|
38827
39593
|
}
|
|
38828
39594
|
}
|
|
@@ -39054,28 +39820,15 @@ async function uploadMediaFromBase64(input, context) {
|
|
|
39054
39820
|
if (!media) throw new NotFoundError("Media");
|
|
39055
39821
|
return serializeMedia(media, context.appConfig);
|
|
39056
39822
|
}
|
|
39057
|
-
|
|
39058
|
-
|
|
39059
|
-
const postIds = posts.map((post) => post.id);
|
|
39060
|
-
const [mediaMap, collectionMap] = await Promise.all([context.services.media.getByPostIds(postIds), context.services.collections.getCollectionsByPostIds(postIds)]);
|
|
39061
|
-
return posts.map((post) => toApiPost(post, {
|
|
39062
|
-
attachments: serializeAttachments(mediaMap.get(post.id) ?? [], context.appConfig),
|
|
39063
|
-
collectionIds: (collectionMap.get(post.id) ?? []).map((collection) => collection.id)
|
|
39064
|
-
}));
|
|
39823
|
+
function serializePosts(posts, context) {
|
|
39824
|
+
return loadApiPostResponses(context, posts, { collectionIds: true });
|
|
39065
39825
|
}
|
|
39066
|
-
|
|
39067
|
-
|
|
39068
|
-
return toApiPost(post, {
|
|
39069
|
-
attachments: serializeAttachments(mediaList, context.appConfig),
|
|
39070
|
-
collectionIds: threadCollections.map((collection) => collection.id)
|
|
39071
|
-
});
|
|
39826
|
+
function serializePost(post, context) {
|
|
39827
|
+
return loadApiPostResponse(context, post, { collectionIds: true });
|
|
39072
39828
|
}
|
|
39073
39829
|
function serializeMedia(media, appConfig) {
|
|
39074
39830
|
return toApiMedia(media, appConfig);
|
|
39075
39831
|
}
|
|
39076
|
-
function serializeAttachments(mediaList, appConfig) {
|
|
39077
|
-
return mediaList.map((media) => toApiAttachment(media, appConfig.r2PublicUrl, appConfig.imageTransformUrl, appConfig.s3PublicUrl, appConfig.localPublicUrl, appConfig.sitePathPrefix));
|
|
39078
|
-
}
|
|
39079
39832
|
//#endregion
|
|
39080
39833
|
//#region src/routes/api/mcp.ts
|
|
39081
39834
|
var mcpApiRoutes = new Hono();
|
|
@@ -39227,36 +39980,6 @@ customUrlsApiRoutes.delete("/:id", requireAuthApi(), async (c) => {
|
|
|
39227
39980
|
return root.lastActivityAt ?? root.publishedAt ?? root.updatedAt;
|
|
39228
39981
|
}
|
|
39229
39982
|
//#endregion
|
|
39230
|
-
//#region src/lib/tiptap-to-markdown.ts
|
|
39231
|
-
/**
|
|
39232
|
-
* Tiptap JSON → Markdown Converter
|
|
39233
|
-
*
|
|
39234
|
-
* Converts Tiptap JSON documents to Markdown using the official
|
|
39235
|
-
* Tiptap MarkdownManager and Jant's shared markdown schema.
|
|
39236
|
-
*/
|
|
39237
|
-
/**
|
|
39238
|
-
* Converts a Tiptap JSON document to a Markdown string.
|
|
39239
|
-
*
|
|
39240
|
-
* Throws rather than returning an empty string: a caller writing the result
|
|
39241
|
-
* somewhere (an export, a text attachment) would otherwise replace the
|
|
39242
|
-
* content with nothing and say nothing.
|
|
39243
|
-
*
|
|
39244
|
-
* @param json - Tiptap JSON document string
|
|
39245
|
-
* @returns Markdown string
|
|
39246
|
-
* @throws {SyntaxError} When `json` is not JSON
|
|
39247
|
-
* @throws {Error} When the root node is not a `doc`
|
|
39248
|
-
*
|
|
39249
|
-
* @example
|
|
39250
|
-
* ```ts
|
|
39251
|
-
* const md = tiptapJsonToMarkdown('{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Hello"}]}]}');
|
|
39252
|
-
* // "Hello"
|
|
39253
|
-
* ```
|
|
39254
|
-
*/ function tiptapJsonToMarkdown(json) {
|
|
39255
|
-
const doc = JSON.parse(json);
|
|
39256
|
-
if (doc.type !== "doc") throw new Error(`A TipTap body's root must be a doc node, not ${JSON.stringify(doc.type)}.`);
|
|
39257
|
-
return serializeMarkdownDocument(doc).trimEnd();
|
|
39258
|
-
}
|
|
39259
|
-
//#endregion
|
|
39260
39983
|
//#region src/lib/hugo-markdown.ts
|
|
39261
39984
|
/**
|
|
39262
39985
|
* Shared Hugo Markdown parsing utilities.
|
|
@@ -73196,6 +73919,10 @@ function createPathService(db, siteId, databaseSchema = sqliteSchemaBundle) {
|
|
|
73196
73919
|
* visibility (public/latest_hidden/private), featuredAt, and pinnedAt timestamp.
|
|
73197
73920
|
*/
|
|
73198
73921
|
/**
|
|
73922
|
+
* The sort mode a cursor into one Thread's Posts records. Distinct from every
|
|
73923
|
+
* `list()` and collection mode, so a position in one never resumes another.
|
|
73924
|
+
*/ var THREAD_POSTS_SORT_MODE = "thread";
|
|
73925
|
+
/**
|
|
73199
73926
|
* Rebuild body HTML using the site's current runtime summary settings.
|
|
73200
73927
|
*
|
|
73201
73928
|
* Internal maintenance routes do not run behind the normal app-config
|
|
@@ -73315,13 +74042,32 @@ function createPostService(db, config, siteId, paths, databaseSchema = sqliteSch
|
|
|
73315
74042
|
* db.select().from(posts).orderBy(posts.threadId, ...threadOrder());
|
|
73316
74043
|
* sql`ROW_NUMBER() OVER (ORDER BY ${sql.join(threadOrder(), sql`, `)})`;
|
|
73317
74044
|
*/ function threadOrder(direction = "asc") {
|
|
73318
|
-
const terms =
|
|
73319
|
-
sql`CASE WHEN ${posts.replyToId} IS NULL THEN 0 ELSE 1 END`,
|
|
73320
|
-
sql`${posts.createdAt}`,
|
|
73321
|
-
sql`${posts.id}`
|
|
73322
|
-
];
|
|
74045
|
+
const terms = threadSortKeys().map((key) => key.expr);
|
|
73323
74046
|
return direction === "asc" ? terms : terms.map((term) => desc(term));
|
|
73324
74047
|
}
|
|
74048
|
+
/**
|
|
74049
|
+
* {@link threadOrder} as paged sort keys, for walking one Thread with a
|
|
74050
|
+
* cursor. The one definition both read, so a page of a Thread and the
|
|
74051
|
+
* Thread page itself cannot order its posts differently.
|
|
74052
|
+
*/ function threadSortKeys() {
|
|
74053
|
+
return [
|
|
74054
|
+
{
|
|
74055
|
+
expr: sql`CASE WHEN ${posts.replyToId} IS NULL THEN 0 ELSE 1 END`.mapWith(Number),
|
|
74056
|
+
direction: "asc",
|
|
74057
|
+
kind: "number"
|
|
74058
|
+
},
|
|
74059
|
+
{
|
|
74060
|
+
expr: sql`${posts.createdAt}`.mapWith(Number),
|
|
74061
|
+
direction: "asc",
|
|
74062
|
+
kind: "number"
|
|
74063
|
+
},
|
|
74064
|
+
{
|
|
74065
|
+
expr: sql`${posts.id}`,
|
|
74066
|
+
direction: "asc",
|
|
74067
|
+
kind: "id"
|
|
74068
|
+
}
|
|
74069
|
+
];
|
|
74070
|
+
}
|
|
73325
74071
|
function buildYearMonthExpr(column) {
|
|
73326
74072
|
return databaseDialect === "pg" ? sql`to_char(timezone('UTC', to_timestamp(${column})), 'YYYY-MM')` : sql`strftime('%Y-%m', ${column}, 'unixepoch')`;
|
|
73327
74073
|
}
|
|
@@ -73788,6 +74534,10 @@ function createPostService(db, config, siteId, paths, databaseSchema = sqliteSch
|
|
|
73788
74534
|
)`);
|
|
73789
74535
|
if (options?.hasRating) conditions.push(isNotNull(posts.rating));
|
|
73790
74536
|
if (options?.threadIds !== void 0) conditions.push(inArray(posts.threadId, options.threadIds));
|
|
74537
|
+
if (options?.rootFilters) conditions.push(inArray(posts.threadId, db.select({ id: posts.id }).from(posts).where(and(...buildFilterConditions({
|
|
74538
|
+
...options.rootFilters,
|
|
74539
|
+
excludeReplies: true
|
|
74540
|
+
})))));
|
|
73791
74541
|
return conditions;
|
|
73792
74542
|
}
|
|
73793
74543
|
/**
|
|
@@ -74747,6 +75497,46 @@ function createPostService(db, config, siteId, paths, databaseSchema = sqliteSch
|
|
|
74747
75497
|
async getThread(rootId) {
|
|
74748
75498
|
return hydratePosts(await db.select().from(posts).where(and(eq(posts.siteId, siteId), eq(posts.threadId, rootId))).orderBy(...threadOrder()));
|
|
74749
75499
|
},
|
|
75500
|
+
async listThreadPostsPage(threadId, options, { cursor, limit }) {
|
|
75501
|
+
const keys = threadSortKeys();
|
|
75502
|
+
const conditions = [
|
|
75503
|
+
eq(posts.siteId, siteId),
|
|
75504
|
+
eq(posts.threadId, threadId),
|
|
75505
|
+
eq(posts.status, options.status ?? "published")
|
|
75506
|
+
];
|
|
75507
|
+
if (cursor) {
|
|
75508
|
+
let values;
|
|
75509
|
+
if (isLegacyPostListCursor(cursor)) {
|
|
75510
|
+
const row = (await db.select(listSortKeyFields(keys)).from(posts).where(and(...conditions, eq(posts.id, cursor))).limit(1))[0];
|
|
75511
|
+
if (!row) throw new ValidationError(MISSING_LEGACY_CURSOR_MESSAGE);
|
|
75512
|
+
values = readListSortKeyValues(keys, row);
|
|
75513
|
+
} else values = decodePostListCursor(cursor, {
|
|
75514
|
+
mode: THREAD_POSTS_SORT_MODE,
|
|
75515
|
+
kinds: keys.map((key) => key.kind)
|
|
75516
|
+
});
|
|
75517
|
+
conditions.push(buildListKeysetCondition(keys, values));
|
|
75518
|
+
}
|
|
75519
|
+
const rows = await db.select({
|
|
75520
|
+
post: posts,
|
|
75521
|
+
sortKey: listSortKeyFields(keys)
|
|
75522
|
+
}).from(posts).where(and(...conditions)).orderBy(...listOrderBy(keys)).limit(limit + 1);
|
|
75523
|
+
const pageRows = rows.slice(0, limit);
|
|
75524
|
+
const lastRow = pageRows[pageRows.length - 1];
|
|
75525
|
+
return {
|
|
75526
|
+
posts: await hydratePosts(pageRows.map((row) => row.post)),
|
|
75527
|
+
nextCursor: rows.length > limit && lastRow ? encodePostListCursor(THREAD_POSTS_SORT_MODE, readListSortKeyValues(keys, lastRow.sortKey)) : null
|
|
75528
|
+
};
|
|
75529
|
+
},
|
|
75530
|
+
async countThreadPosts(threadIds) {
|
|
75531
|
+
const counts = /* @__PURE__ */ new Map();
|
|
75532
|
+
if (threadIds.length === 0) return counts;
|
|
75533
|
+
const rows = await batchQueryRows([...new Set(threadIds)], (chunk) => db.select({
|
|
75534
|
+
threadId: posts.threadId,
|
|
75535
|
+
count: sql`CAST(count(*) AS INTEGER)`.as("count")
|
|
75536
|
+
}).from(posts).where(and(eq(posts.siteId, siteId), inArray(posts.threadId, chunk), eq(posts.status, "published"))).groupBy(posts.threadId));
|
|
75537
|
+
for (const row of rows) counts.set(row.threadId, row.count);
|
|
75538
|
+
return counts;
|
|
75539
|
+
},
|
|
74750
75540
|
async getThreadPosition(postId) {
|
|
74751
75541
|
const target = (await db.select({
|
|
74752
75542
|
replyToId: posts.replyToId,
|
|
@@ -75041,28 +75831,30 @@ function createPostService(db, config, siteId, paths, databaseSchema = sqliteSch
|
|
|
75041
75831
|
},
|
|
75042
75832
|
async getThreadTimelineContext(rootIds) {
|
|
75043
75833
|
if (rootIds.length === 0) return /* @__PURE__ */ new Map();
|
|
75044
|
-
const
|
|
75045
|
-
|
|
75046
|
-
|
|
75047
|
-
|
|
75834
|
+
const contextRows = await batchQueryRows([...new Set(rootIds)], (chunk) => {
|
|
75835
|
+
const rankedReplies = db.select({
|
|
75836
|
+
id: posts.id,
|
|
75837
|
+
threadId: posts.threadId,
|
|
75838
|
+
firstReplyRank: sql`CAST(ROW_NUMBER() OVER (
|
|
75048
75839
|
PARTITION BY ${posts.threadId}
|
|
75049
75840
|
ORDER BY ${sql.join(threadOrder(), sql`, `)}
|
|
75050
75841
|
) AS INTEGER)`.as("first_reply_rank"),
|
|
75051
|
-
|
|
75842
|
+
latestReplyRank: sql`CAST(ROW_NUMBER() OVER (
|
|
75052
75843
|
PARTITION BY ${posts.threadId}
|
|
75053
75844
|
ORDER BY ${sql.join(threadOrder("desc"), sql`, `)}
|
|
75054
75845
|
) AS INTEGER)`.as("latest_reply_rank"),
|
|
75055
|
-
|
|
75846
|
+
totalReplyCount: sql`CAST(COUNT(*) OVER (
|
|
75056
75847
|
PARTITION BY ${posts.threadId}
|
|
75057
75848
|
) AS INTEGER)`.as("total_reply_count")
|
|
75058
|
-
|
|
75059
|
-
|
|
75060
|
-
|
|
75061
|
-
|
|
75062
|
-
|
|
75063
|
-
|
|
75064
|
-
|
|
75065
|
-
|
|
75849
|
+
}).from(posts).where(and(eq(posts.siteId, siteId), inArray(posts.threadId, chunk), eq(posts.status, "published"), isNotNull(posts.replyToId))).as("ranked_replies");
|
|
75850
|
+
return db.select({
|
|
75851
|
+
threadId: rankedReplies.threadId,
|
|
75852
|
+
id: rankedReplies.id,
|
|
75853
|
+
firstReplyRank: rankedReplies.firstReplyRank,
|
|
75854
|
+
latestReplyRank: rankedReplies.latestReplyRank,
|
|
75855
|
+
totalReplyCount: rankedReplies.totalReplyCount
|
|
75856
|
+
}).from(rankedReplies).where(or(lte(rankedReplies.firstReplyRank, 3), lte(rankedReplies.latestReplyRank, 3)));
|
|
75857
|
+
});
|
|
75066
75858
|
const hydratedPosts = await hydratePostsById(contextRows.map((row) => row.id));
|
|
75067
75859
|
const contextByThreadId = /* @__PURE__ */ new Map();
|
|
75068
75860
|
for (const row of contextRows) {
|
|
@@ -77162,6 +77954,98 @@ internalUploadsRoutes.post("/cleanup", requireInternalAdminApi(), async (c) => {
|
|
|
77162
77954
|
return c.json(result);
|
|
77163
77955
|
});
|
|
77164
77956
|
//#endregion
|
|
77957
|
+
//#region src/middleware/deprecation.ts
|
|
77958
|
+
/**
|
|
77959
|
+
* Deprecated API endpoints.
|
|
77960
|
+
*
|
|
77961
|
+
* A deprecated endpoint keeps answering exactly as before until the major
|
|
77962
|
+
* release that removes it, and says so on every response, errors included:
|
|
77963
|
+
* `Deprecation` (RFC 9745) carries when it was deprecated, and `Link` with
|
|
77964
|
+
* `rel="successor-version"` names what replaces it. The docs and the release
|
|
77965
|
+
* notes say the same thing in words.
|
|
77966
|
+
*/
|
|
77967
|
+
/**
|
|
77968
|
+
* When 0.9 deprecated the Thread lists that `/api/public/threads` replaces:
|
|
77969
|
+
* the `GET /api/public/posts` list and `GET /api/public/archive`.
|
|
77970
|
+
*/ var THREAD_LIST_DEPRECATED_AT = Date.UTC(2026, 8, 27) / 1e3;
|
|
77971
|
+
/**
|
|
77972
|
+
* Mark every response of a route as deprecated.
|
|
77973
|
+
*
|
|
77974
|
+
* @param deprecatedAt - Unix seconds the endpoint was deprecated
|
|
77975
|
+
* @param successor - The replacement, as a site path (the site path prefix is
|
|
77976
|
+
* added)
|
|
77977
|
+
* @returns Hono middleware that sets `Deprecation` and `Link`
|
|
77978
|
+
* @example
|
|
77979
|
+
* ```ts
|
|
77980
|
+
* routes.get("/", deprecated(THREAD_LIST_DEPRECATED_AT, "/api/public/threads"), handler);
|
|
77981
|
+
* ```
|
|
77982
|
+
*/ function deprecated(deprecatedAt, successor) {
|
|
77983
|
+
return async (c, next) => {
|
|
77984
|
+
await next();
|
|
77985
|
+
c.header("Deprecation", `@${deprecatedAt}`);
|
|
77986
|
+
c.header("Link", `<${toPublicPath(successor, c.var.appConfig.sitePathPrefix)}>; rel="successor-version"`);
|
|
77987
|
+
};
|
|
77988
|
+
}
|
|
77989
|
+
//#endregion
|
|
77990
|
+
//#region src/routes/api/public/archive.ts
|
|
77991
|
+
var publicArchiveApiRoutes = new Hono();
|
|
77992
|
+
publicArchiveApiRoutes.use("*", requirePublicApiEnabled());
|
|
77993
|
+
/**
|
|
77994
|
+
* The endpoint's own parameters — everything that is not a filter dimension.
|
|
77995
|
+
*
|
|
77996
|
+
* The dimensions themselves are read by the shared registry, so this endpoint
|
|
77997
|
+
* cannot drift from the page it mirrors. They are listed here only so the strict
|
|
77998
|
+
* parser can tell them apart from a parameter nobody understands.
|
|
77999
|
+
*/ var ListPublicArchiveQuerySchema = z.object({
|
|
78000
|
+
/** Restrict to one content language. See `/api/public/posts`. */ lang: ContentLanguageSchema.optional(),
|
|
78001
|
+
cursor: z.string().optional(),
|
|
78002
|
+
limit: z.coerce.number().int().min(1).max(100).optional().default(20),
|
|
78003
|
+
content: z.enum(["markdown"]).optional()
|
|
78004
|
+
});
|
|
78005
|
+
var ENDPOINT_PARAMS = [
|
|
78006
|
+
"lang",
|
|
78007
|
+
"cursor",
|
|
78008
|
+
"limit",
|
|
78009
|
+
"content"
|
|
78010
|
+
];
|
|
78011
|
+
var INVALID_VISIBILITY_MESSAGE = "Invalid visibility value. Allowed: " + PUBLIC_ARCHIVE_VISIBILITIES.map((value) => value === "latest_hidden" ? "hidden" : value).join(", ");
|
|
78012
|
+
/**
|
|
78013
|
+
* Deprecated in 0.9 for `GET /api/public/threads?visibility=any&sort=published`,
|
|
78014
|
+
* which takes the same filters. Answers as it always has until 1.0.1 removes it.
|
|
78015
|
+
*/ publicArchiveApiRoutes.get("/", deprecated(THREAD_LIST_DEPRECATED_AT, "/api/public/threads?visibility=any&sort=published"), async (c) => {
|
|
78016
|
+
const { lang, cursor, limit, content } = parseValidated(ListPublicArchiveQuerySchema, c.req.query());
|
|
78017
|
+
const read = (key) => c.req.query(key);
|
|
78018
|
+
const ctx = { collections: readCollectionSlugs(read).length > 0 ? buildCollectionVocabulary(await c.var.services.collections.list()) : EMPTY_COLLECTION_VOCABULARY };
|
|
78019
|
+
const parsed = parsePostFilterSelectionStrict(read, Object.keys(c.req.query()), ctx, { allow: ENDPOINT_PARAMS });
|
|
78020
|
+
if (!parsed.ok && parsed.issues.every((issue) => issue.param === "collection")) return c.json({
|
|
78021
|
+
posts: [],
|
|
78022
|
+
nextCursor: null
|
|
78023
|
+
});
|
|
78024
|
+
if (!parsed.ok) {
|
|
78025
|
+
const first = parsed.issues[0];
|
|
78026
|
+
throw new ValidationError(first?.message ?? "Validation failed");
|
|
78027
|
+
}
|
|
78028
|
+
const visibility = parsed.selection.visibility;
|
|
78029
|
+
if (visibility !== void 0 && !PUBLIC_ARCHIVE_VISIBILITIES.includes(visibility)) throw new ValidationError(INVALID_VISIBILITY_MESSAGE);
|
|
78030
|
+
const { posts, nextCursor } = await c.var.services.posts.listPage({
|
|
78031
|
+
lang,
|
|
78032
|
+
status: "published",
|
|
78033
|
+
excludePrivate: true,
|
|
78034
|
+
excludeLatestHidden: false,
|
|
78035
|
+
excludeReplies: true,
|
|
78036
|
+
...toPostFilters(parsed.selection, { yearAxis: "published" }),
|
|
78037
|
+
sortBy: "published",
|
|
78038
|
+
ignorePinnedSort: true
|
|
78039
|
+
}, {
|
|
78040
|
+
cursor,
|
|
78041
|
+
limit
|
|
78042
|
+
});
|
|
78043
|
+
return c.json({
|
|
78044
|
+
posts: await loadPublicPostResponses(c.var, posts, { content }),
|
|
78045
|
+
nextCursor
|
|
78046
|
+
});
|
|
78047
|
+
});
|
|
78048
|
+
//#endregion
|
|
77165
78049
|
//#region src/routes/api/public/posts.ts
|
|
77166
78050
|
var publicPostsApiRoutes = new Hono();
|
|
77167
78051
|
publicPostsApiRoutes.use("*", requirePublicApiEnabled());
|
|
@@ -77178,81 +78062,14 @@ var ListPublicPostsQuerySchema = z.object({
|
|
|
77178
78062
|
content: z.enum(["markdown"]).optional()
|
|
77179
78063
|
});
|
|
77180
78064
|
var PublicPostContentQuerySchema = z.object({ content: z.enum(["markdown"]).optional() });
|
|
77181
|
-
/**
|
|
77182
|
-
* The public Markdown for a post, or null for a historical body that isn't
|
|
77183
|
-
* TipTap JSON. One unreadable row answers null and is logged, rather than
|
|
77184
|
-
* failing the whole listing; `bodyHtml` still falls back to stored HTML.
|
|
77185
|
-
*/ function toPublicBodyMarkdown(postId, body) {
|
|
77186
|
-
try {
|
|
77187
|
-
return tiptapJsonToMarkdown(body);
|
|
77188
|
-
} catch (error) {
|
|
77189
|
-
console.error(`Couldn't convert the body of post ${postId} to Markdown`, error);
|
|
77190
|
-
return null;
|
|
77191
|
-
}
|
|
77192
|
-
}
|
|
77193
78065
|
function isPublicDetailVisible(post) {
|
|
77194
78066
|
return post !== null && post.status === "published" && post.visibility !== "private";
|
|
77195
78067
|
}
|
|
77196
|
-
|
|
77197
|
-
|
|
77198
|
-
|
|
77199
|
-
|
|
77200
|
-
|
|
77201
|
-
quality: 80,
|
|
77202
|
-
format: "auto",
|
|
77203
|
-
fit: "scale-down"
|
|
77204
|
-
}) : null;
|
|
77205
|
-
const base = {
|
|
77206
|
-
id: post.id,
|
|
77207
|
-
format: post.format,
|
|
77208
|
-
status: "published",
|
|
77209
|
-
visibility: post.visibility,
|
|
77210
|
-
slug: post.slug,
|
|
77211
|
-
permalink: toPublicPath(`/${post.slug}`, sitePathPrefix),
|
|
77212
|
-
quoteText: post.quoteText,
|
|
77213
|
-
summary: post.summary,
|
|
77214
|
-
rating: post.rating,
|
|
77215
|
-
previewKind: post.previewKind,
|
|
77216
|
-
previewProvider: post.previewProvider,
|
|
77217
|
-
previewImageUrl,
|
|
77218
|
-
replyToId: post.replyToId,
|
|
77219
|
-
threadId: post.threadId,
|
|
77220
|
-
language: post.language,
|
|
77221
|
-
translationGroupId: post.translationGroupId,
|
|
77222
|
-
quietReply: post.quietReply,
|
|
77223
|
-
pinnedAt: post.pinnedAt,
|
|
77224
|
-
featuredAt: post.featuredAt,
|
|
77225
|
-
publishedAt: post.publishedAt,
|
|
77226
|
-
lastActivityAt: post.lastActivityAt,
|
|
77227
|
-
threadUpdatedAt: post.threadUpdatedAt,
|
|
77228
|
-
createdAt: post.createdAt,
|
|
77229
|
-
updatedAt: post.updatedAt,
|
|
77230
|
-
attachments: mediaList.map((media) => toApiAttachment(media, r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix)),
|
|
77231
|
-
collections: threadCollections.map((collection) => ({
|
|
77232
|
-
id: collection.id,
|
|
77233
|
-
slug: collection.slug,
|
|
77234
|
-
title: collection.title,
|
|
77235
|
-
url: toPublicPath(getCollectionPagePath(collection.slug), sitePathPrefix)
|
|
77236
|
-
}))
|
|
77237
|
-
};
|
|
77238
|
-
const contentFields = options?.content === "markdown" ? { bodyMarkdown: post.body ? toPublicBodyMarkdown(post.id, post.body) : null } : {
|
|
77239
|
-
bodyHtml: post.bodyHtml,
|
|
77240
|
-
bodyText: post.bodyText
|
|
77241
|
-
};
|
|
77242
|
-
if (post.format === "quote") return {
|
|
77243
|
-
...base,
|
|
77244
|
-
...contentFields,
|
|
77245
|
-
sourceName: post.title,
|
|
77246
|
-
sourceUrl: post.url
|
|
77247
|
-
};
|
|
77248
|
-
return {
|
|
77249
|
-
...base,
|
|
77250
|
-
...contentFields,
|
|
77251
|
-
title: post.title,
|
|
77252
|
-
url: post.url
|
|
77253
|
-
};
|
|
77254
|
-
}
|
|
77255
|
-
publicPostsApiRoutes.get("/", async (c) => {
|
|
78068
|
+
/**
|
|
78069
|
+
* Deprecated in 0.9 for `GET /api/public/threads`, which lists the same Thread
|
|
78070
|
+
* roots with the archive's filters and the homepage's defaults. Answers as it
|
|
78071
|
+
* always has until 1.0.1 removes it.
|
|
78072
|
+
*/ publicPostsApiRoutes.get("/", deprecated(THREAD_LIST_DEPRECATED_AT, "/api/public/threads"), async (c) => {
|
|
77256
78073
|
const { format, lang, collection, sort, cursor, limit, content } = parseValidated(ListPublicPostsQuerySchema, c.req.query());
|
|
77257
78074
|
let collectionIds;
|
|
77258
78075
|
let sortOrder;
|
|
@@ -77301,10 +78118,8 @@ publicPostsApiRoutes.get("/", async (c) => {
|
|
|
77301
78118
|
cursor,
|
|
77302
78119
|
limit
|
|
77303
78120
|
});
|
|
77304
|
-
const postIds = posts.map((post) => post.id);
|
|
77305
|
-
const [mediaMap, collectionsMap] = await Promise.all([c.var.services.media.getByPostIds(postIds), c.var.services.collections.getCollectionsByPostIds(postIds)]);
|
|
77306
78121
|
return c.json({
|
|
77307
|
-
posts:
|
|
78122
|
+
posts: await loadPublicPostResponses(c.var, posts, { content }),
|
|
77308
78123
|
nextCursor
|
|
77309
78124
|
});
|
|
77310
78125
|
});
|
|
@@ -77313,64 +78128,93 @@ publicPostsApiRoutes.get("/:slug", async (c) => {
|
|
|
77313
78128
|
const slug = c.req.param("slug");
|
|
77314
78129
|
const post = await c.var.services.posts.getBySlug(slug);
|
|
77315
78130
|
if (!isPublicDetailVisible(post)) throw new NotFoundError("Post");
|
|
77316
|
-
const [
|
|
77317
|
-
return c.json(
|
|
78131
|
+
const [response] = await loadPublicPostResponses(c.var, [post], { content });
|
|
78132
|
+
return c.json(response);
|
|
77318
78133
|
});
|
|
77319
78134
|
//#endregion
|
|
77320
|
-
//#region src/routes/api/public/
|
|
77321
|
-
|
|
77322
|
-
|
|
77323
|
-
|
|
77324
|
-
* The
|
|
77325
|
-
*
|
|
77326
|
-
*
|
|
77327
|
-
*
|
|
77328
|
-
|
|
77329
|
-
|
|
77330
|
-
|
|
78135
|
+
//#region src/routes/api/public/threads.ts
|
|
78136
|
+
/**
|
|
78137
|
+
* Public Threads API Routes
|
|
78138
|
+
*
|
|
78139
|
+
* The reader's view of Threads: what the site shows anyone, in the reading
|
|
78140
|
+
* view. A list left unfiltered is the homepage's — Threads hidden from Latest
|
|
78141
|
+
* left out, newest activity first, pins on top — and takes the archive's
|
|
78142
|
+
* filters to narrow or widen it.
|
|
78143
|
+
*/ var publicThreadsApiRoutes = new Hono();
|
|
78144
|
+
publicThreadsApiRoutes.use("*", requirePublicApiEnabled());
|
|
78145
|
+
var ContentSchema = z.enum(["markdown"]).optional();
|
|
78146
|
+
/** The list's own parameters; everything else is a filter dimension. */ var ListThreadsQuerySchema = z.object({
|
|
78147
|
+
lang: ContentLanguageSchema.optional(),
|
|
78148
|
+
sort: z.enum(THREAD_SORTS).optional(),
|
|
78149
|
+
include: z.string().optional(),
|
|
77331
78150
|
cursor: z.string().optional(),
|
|
77332
78151
|
limit: z.coerce.number().int().min(1).max(100).optional().default(20),
|
|
77333
|
-
content:
|
|
78152
|
+
content: ContentSchema
|
|
77334
78153
|
});
|
|
77335
|
-
var
|
|
78154
|
+
var LIST_PARAMS = [
|
|
77336
78155
|
"lang",
|
|
78156
|
+
"sort",
|
|
78157
|
+
"include",
|
|
77337
78158
|
"cursor",
|
|
77338
78159
|
"limit",
|
|
77339
78160
|
"content"
|
|
77340
78161
|
];
|
|
77341
|
-
var
|
|
77342
|
-
|
|
77343
|
-
|
|
77344
|
-
|
|
77345
|
-
|
|
77346
|
-
|
|
77347
|
-
|
|
77348
|
-
|
|
78162
|
+
var GetThreadQuerySchema = z.object({
|
|
78163
|
+
include: z.string().optional(),
|
|
78164
|
+
content: ContentSchema
|
|
78165
|
+
});
|
|
78166
|
+
var ListThreadPostsQuerySchema = z.object({
|
|
78167
|
+
cursor: z.string().optional(),
|
|
78168
|
+
limit: z.coerce.number().int().min(1).max(100).optional().default(100),
|
|
78169
|
+
content: ContentSchema
|
|
78170
|
+
});
|
|
78171
|
+
publicThreadsApiRoutes.get("/", async (c) => {
|
|
78172
|
+
const query = parseValidated(ListThreadsQuerySchema, c.req.query());
|
|
78173
|
+
const { fold } = parseThreadInclude(query.include);
|
|
78174
|
+
const parsed = await parseThreadSelection((key) => c.req.query(key), Object.keys(c.req.query()), {
|
|
78175
|
+
allow: LIST_PARAMS,
|
|
78176
|
+
audience: "reader",
|
|
78177
|
+
loadCollections: () => c.var.services.collections.list()
|
|
78178
|
+
});
|
|
78179
|
+
if (parsed.kind === "empty") return c.json({
|
|
78180
|
+
threads: [],
|
|
77349
78181
|
nextCursor: null
|
|
77350
78182
|
});
|
|
77351
|
-
|
|
77352
|
-
|
|
77353
|
-
|
|
77354
|
-
|
|
77355
|
-
|
|
77356
|
-
|
|
77357
|
-
|
|
77358
|
-
lang,
|
|
77359
|
-
status: "published",
|
|
77360
|
-
excludePrivate: true,
|
|
77361
|
-
excludeLatestHidden: false,
|
|
77362
|
-
excludeReplies: true,
|
|
77363
|
-
...toPostFilters(parsed.selection, { yearAxis: "published" }),
|
|
77364
|
-
sortBy: "published",
|
|
77365
|
-
ignorePinnedSort: true
|
|
78183
|
+
const { threads, nextCursor } = await c.var.services.threads.listThreads({
|
|
78184
|
+
audience: "reader",
|
|
78185
|
+
selection: parsed.selection,
|
|
78186
|
+
includeHidden: parsed.includeHidden,
|
|
78187
|
+
lang: query.lang,
|
|
78188
|
+
sort: query.sort,
|
|
78189
|
+
fold
|
|
77366
78190
|
}, {
|
|
78191
|
+
cursor: query.cursor,
|
|
78192
|
+
limit: query.limit
|
|
78193
|
+
});
|
|
78194
|
+
return c.json({
|
|
78195
|
+
threads: await loadPublicThreadResponses(c.var, threads, { content: query.content }),
|
|
78196
|
+
nextCursor
|
|
78197
|
+
});
|
|
78198
|
+
});
|
|
78199
|
+
publicThreadsApiRoutes.get("/:slug", async (c) => {
|
|
78200
|
+
const { include, content } = parseValidated(GetThreadQuerySchema, c.req.query());
|
|
78201
|
+
const root = await c.var.services.threads.findRoot({ slug: c.req.param("slug") }, "reader");
|
|
78202
|
+
if (!root) throw new NotFoundError("Thread");
|
|
78203
|
+
const summaries = await c.var.services.threads.summarize([root], parseThreadInclude(include));
|
|
78204
|
+
const [thread] = await loadPublicThreadResponses(c.var, summaries, { content });
|
|
78205
|
+
if (!thread) throw new NotFoundError("Thread");
|
|
78206
|
+
return c.json(thread);
|
|
78207
|
+
});
|
|
78208
|
+
publicThreadsApiRoutes.get("/:slug/posts", async (c) => {
|
|
78209
|
+
const { cursor, limit, content } = parseValidated(ListThreadPostsQuerySchema, c.req.query());
|
|
78210
|
+
const root = await c.var.services.threads.findRoot({ slug: c.req.param("slug") }, "reader");
|
|
78211
|
+
if (!root) throw new NotFoundError("Thread");
|
|
78212
|
+
const { posts, nextCursor } = await c.var.services.threads.listPosts(root.id, { audience: "reader" }, {
|
|
77367
78213
|
cursor,
|
|
77368
78214
|
limit
|
|
77369
78215
|
});
|
|
77370
|
-
const postIds = posts.map((post) => post.id);
|
|
77371
|
-
const [mediaMap, collectionsMap] = await Promise.all([c.var.services.media.getByPostIds(postIds), c.var.services.collections.getCollectionsByPostIds(postIds)]);
|
|
77372
78216
|
return c.json({
|
|
77373
|
-
posts:
|
|
78217
|
+
posts: await loadPublicPostResponses(c.var, posts, { content }),
|
|
77374
78218
|
nextCursor
|
|
77375
78219
|
});
|
|
77376
78220
|
});
|
|
@@ -77786,7 +78630,7 @@ manifestRoutes.get("/manifest.webmanifest", (c) => {
|
|
|
77786
78630
|
});
|
|
77787
78631
|
//#endregion
|
|
77788
78632
|
//#region ../../docs/skill.md?raw
|
|
77789
|
-
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";
|
|
78633
|
+
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 public posts | `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";
|
|
77790
78634
|
//#endregion
|
|
77791
78635
|
//#region src/lib/site-skill.ts
|
|
77792
78636
|
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.";
|
|
@@ -77815,7 +78659,7 @@ function replaceLiteral(content, search, replacement) {
|
|
|
77815
78659
|
const normalizedSiteUrl = normalizeSiteUrl(siteUrl);
|
|
77816
78660
|
if (!normalizedSiteUrl) throw new Error("A public site URL is required to render /skill.md");
|
|
77817
78661
|
const targetSiteUrl = normalizedSiteUrl.replace(/\/$/, "");
|
|
77818
|
-
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");
|
|
78662
|
+
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 public posts | `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");
|
|
77819
78663
|
const missingMarker = GENERIC_SITE_MARKERS.find((marker) => !skill_default.includes(marker));
|
|
77820
78664
|
if (missingMarker) throw new Error(`The site skill template target marker could not be found: ${missingMarker}`);
|
|
77821
78665
|
let content = skill_default;
|
|
@@ -78753,7 +79597,12 @@ var cors = (options) => {
|
|
|
78753
79597
|
"Authorization",
|
|
78754
79598
|
"MCP-Protocol-Version"
|
|
78755
79599
|
],
|
|
78756
|
-
exposeHeaders: [
|
|
79600
|
+
exposeHeaders: [
|
|
79601
|
+
"Content-Type",
|
|
79602
|
+
"MCP-Protocol-Version",
|
|
79603
|
+
"Deprecation",
|
|
79604
|
+
"Link"
|
|
79605
|
+
],
|
|
78757
79606
|
credentials: origins !== "*",
|
|
78758
79607
|
maxAge: 86400
|
|
78759
79608
|
})(c, next);
|
|
@@ -81003,6 +81852,47 @@ function buildPgPrefixTsQuery(query) {
|
|
|
81003
81852
|
if (terms.length === 0) return null;
|
|
81004
81853
|
return terms.map((term) => `${term}:*`).join(" & ");
|
|
81005
81854
|
}
|
|
81855
|
+
/**
|
|
81856
|
+
* A post's visibility after Thread-root inheritance, in the raw-SQL form every
|
|
81857
|
+
* search statement shares. Each one joins the root as `root_post`. This is the
|
|
81858
|
+
* same rule as `buildEffectiveVisibilityExpr` in `db/post-visibility.ts`.
|
|
81859
|
+
*/ var EFFECTIVE_VISIBILITY_SQL = "COALESCE(post.visibility, root_post.visibility)";
|
|
81860
|
+
/**
|
|
81861
|
+
* The conditions every search statement applies after its own match clause:
|
|
81862
|
+
* site, status, audience, format, and language.
|
|
81863
|
+
*
|
|
81864
|
+
* Built once so that no statement can leave one out. Each dialect and each
|
|
81865
|
+
* match strategy has its own SQL, and a statement missing the visibility
|
|
81866
|
+
* clause does not fail — it returns private posts.
|
|
81867
|
+
*
|
|
81868
|
+
* @param siteId - Site the search is scoped to
|
|
81869
|
+
* @param options - Caller's search options
|
|
81870
|
+
* @returns `AND …` lines to follow the match clause, and their bound values in order
|
|
81871
|
+
*
|
|
81872
|
+
* @example
|
|
81873
|
+
* ```ts
|
|
81874
|
+
* const filters = buildSearchFilters(siteId, { status: ["published"] });
|
|
81875
|
+
* // filters.sql: "AND post.site_id = ?\nAND post.status IN (?)\nAND COALESCE(…) != 'private'"
|
|
81876
|
+
* // filters.params: [siteId, "published"]
|
|
81877
|
+
* ```
|
|
81878
|
+
*/ function buildSearchFilters(siteId, options) {
|
|
81879
|
+
const status = options.status ?? ["published"];
|
|
81880
|
+
const conditions = ["post.site_id = ?", `post.status IN (${status.map(() => "?").join(", ")})`];
|
|
81881
|
+
const params = [siteId, ...status];
|
|
81882
|
+
if (!options.includePrivate) conditions.push(`${EFFECTIVE_VISIBILITY_SQL} != 'private'`);
|
|
81883
|
+
if (options.format) {
|
|
81884
|
+
conditions.push("post.format = ?");
|
|
81885
|
+
params.push(options.format);
|
|
81886
|
+
}
|
|
81887
|
+
if (options.lang) {
|
|
81888
|
+
conditions.push("post.language = ?");
|
|
81889
|
+
params.push(options.lang);
|
|
81890
|
+
}
|
|
81891
|
+
return {
|
|
81892
|
+
sql: conditions.map((condition) => `AND ${condition}`).join("\n"),
|
|
81893
|
+
params
|
|
81894
|
+
};
|
|
81895
|
+
}
|
|
81006
81896
|
var PG_TS_HEADLINE_OPTIONS = [
|
|
81007
81897
|
"MaxWords=18",
|
|
81008
81898
|
"MinWords=6",
|
|
@@ -81016,19 +81906,14 @@ function createSearchService(rawQuery, siteId, databaseDialect = "sqlite") {
|
|
|
81016
81906
|
async function searchFts(query, options) {
|
|
81017
81907
|
const limit = options.limit ?? 20;
|
|
81018
81908
|
const offset = options.offset ?? 0;
|
|
81019
|
-
const
|
|
81020
|
-
const statusPlaceholders = status.map(() => "?").join(", ");
|
|
81021
|
-
const formatFilter = options.format ? "AND post.format = ?" : "";
|
|
81022
|
-
const formatParams = options.format ? [options.format] : [];
|
|
81023
|
-
const langFilter = options.lang ? "AND post.language = ?" : "";
|
|
81024
|
-
const langParams = options.lang ? [options.lang] : [];
|
|
81909
|
+
const filters = buildSearchFilters(siteId, options);
|
|
81025
81910
|
if (databaseDialect === "sqlite") {
|
|
81026
81911
|
const ftsQuery = buildSqliteFtsQuery(query);
|
|
81027
81912
|
if (!ftsQuery) return [];
|
|
81028
81913
|
const { results } = await rawQuery.prepare(`
|
|
81029
81914
|
SELECT
|
|
81030
81915
|
post.*,
|
|
81031
|
-
|
|
81916
|
+
${EFFECTIVE_VISIBILITY_SQL} AS effective_visibility,
|
|
81032
81917
|
path_registry.path AS slug,
|
|
81033
81918
|
post_fts.rank AS rank,
|
|
81034
81919
|
snippet(post_fts, 1, char(2), char(3), '...', 32) AS snippet
|
|
@@ -81040,13 +81925,10 @@ function createSearchService(rawQuery, siteId, databaseDialect = "sqlite") {
|
|
|
81040
81925
|
AND path_registry.site_id = post.site_id
|
|
81041
81926
|
AND path_registry.kind = 'slug'
|
|
81042
81927
|
WHERE post_fts MATCH ?
|
|
81043
|
-
|
|
81044
|
-
AND post.status IN (${statusPlaceholders})
|
|
81045
|
-
${formatFilter}
|
|
81046
|
-
${langFilter}
|
|
81928
|
+
${filters.sql}
|
|
81047
81929
|
ORDER BY post_fts.rank
|
|
81048
81930
|
LIMIT ? OFFSET ?
|
|
81049
|
-
`).bind(ftsQuery,
|
|
81931
|
+
`).bind(ftsQuery, ...filters.params, limit, offset).all();
|
|
81050
81932
|
return withSnippetFallback((results || []).map(mapRow), query);
|
|
81051
81933
|
}
|
|
81052
81934
|
if (databaseDialect !== "pg") return [];
|
|
@@ -81058,7 +81940,7 @@ function createSearchService(rawQuery, siteId, databaseDialect = "sqlite") {
|
|
|
81058
81940
|
)
|
|
81059
81941
|
SELECT
|
|
81060
81942
|
post.*,
|
|
81061
|
-
|
|
81943
|
+
${EFFECTIVE_VISIBILITY_SQL} AS effective_visibility,
|
|
81062
81944
|
path_registry.path AS slug,
|
|
81063
81945
|
ts_rank_cd(post.search_document, search_query.tsq, 32) AS rank,
|
|
81064
81946
|
NULLIF(
|
|
@@ -81105,30 +81987,22 @@ function createSearchService(rawQuery, siteId, databaseDialect = "sqlite") {
|
|
|
81105
81987
|
AND path_registry.site_id = post.site_id
|
|
81106
81988
|
AND path_registry.kind = 'slug'
|
|
81107
81989
|
WHERE post.search_document @@ search_query.tsq
|
|
81108
|
-
|
|
81109
|
-
AND post.status IN (${statusPlaceholders})
|
|
81110
|
-
${formatFilter}
|
|
81111
|
-
${langFilter}
|
|
81990
|
+
${filters.sql}
|
|
81112
81991
|
ORDER BY rank DESC, post.published_at DESC NULLS LAST, post.id DESC
|
|
81113
81992
|
LIMIT ? OFFSET ?
|
|
81114
|
-
`).bind(tsQuery,
|
|
81993
|
+
`).bind(tsQuery, ...filters.params, limit, offset).all();
|
|
81115
81994
|
return withSnippetFallback((results || []).map(mapRow), query);
|
|
81116
81995
|
}
|
|
81117
81996
|
async function searchLike(query, options) {
|
|
81118
81997
|
const limit = options.limit ?? 20;
|
|
81119
81998
|
const offset = options.offset ?? 0;
|
|
81120
|
-
const status = options.status ?? ["published"];
|
|
81121
81999
|
const like = `%${query}%`;
|
|
81122
|
-
const
|
|
81123
|
-
const formatFilter = options.format ? "AND post.format = ?" : "";
|
|
81124
|
-
const formatParams = options.format ? [options.format] : [];
|
|
81125
|
-
const langFilter = options.lang ? "AND post.language = ?" : "";
|
|
81126
|
-
const langParams = options.lang ? [options.lang] : [];
|
|
82000
|
+
const filters = buildSearchFilters(siteId, options);
|
|
81127
82001
|
if (databaseDialect === "pg") {
|
|
81128
82002
|
const { results } = await rawQuery.prepare(`
|
|
81129
82003
|
SELECT
|
|
81130
82004
|
post.*,
|
|
81131
|
-
|
|
82005
|
+
${EFFECTIVE_VISIBILITY_SQL} AS effective_visibility,
|
|
81132
82006
|
path_registry.path AS slug,
|
|
81133
82007
|
GREATEST(
|
|
81134
82008
|
similarity(coalesce(post.title, ''), ?),
|
|
@@ -81144,20 +82018,17 @@ function createSearchService(rawQuery, siteId, databaseDialect = "sqlite") {
|
|
|
81144
82018
|
AND path_registry.site_id = post.site_id
|
|
81145
82019
|
AND path_registry.kind = 'slug'
|
|
81146
82020
|
WHERE post.search_text ILIKE ?
|
|
81147
|
-
|
|
81148
|
-
AND post.status IN (${statusPlaceholders})
|
|
81149
|
-
${formatFilter}
|
|
81150
|
-
${langFilter}
|
|
82021
|
+
${filters.sql}
|
|
81151
82022
|
ORDER BY rank DESC, post.published_at DESC NULLS LAST, post.id DESC
|
|
81152
82023
|
LIMIT ? OFFSET ?
|
|
81153
|
-
`).bind(query, query, query, query, like,
|
|
82024
|
+
`).bind(query, query, query, query, like, ...filters.params, limit, offset).all();
|
|
81154
82025
|
return withSnippetFallback((results || []).map(mapRow), query);
|
|
81155
82026
|
}
|
|
81156
82027
|
const likeOperator = "LIKE";
|
|
81157
82028
|
const { results } = await rawQuery.prepare(`
|
|
81158
82029
|
SELECT
|
|
81159
82030
|
post.*,
|
|
81160
|
-
|
|
82031
|
+
${EFFECTIVE_VISIBILITY_SQL} AS effective_visibility,
|
|
81161
82032
|
path_registry.path AS slug,
|
|
81162
82033
|
0 AS rank,
|
|
81163
82034
|
NULL AS snippet
|
|
@@ -81173,13 +82044,10 @@ function createSearchService(rawQuery, siteId, databaseDialect = "sqlite") {
|
|
|
81173
82044
|
post.quote_text ${likeOperator} ? OR
|
|
81174
82045
|
post.url ${likeOperator} ?
|
|
81175
82046
|
)
|
|
81176
|
-
|
|
81177
|
-
AND post.status IN (${statusPlaceholders})
|
|
81178
|
-
${formatFilter}
|
|
81179
|
-
${langFilter}
|
|
82047
|
+
${filters.sql}
|
|
81180
82048
|
ORDER BY post.published_at DESC
|
|
81181
82049
|
LIMIT ? OFFSET ?
|
|
81182
|
-
`).bind(like, like, like, like,
|
|
82050
|
+
`).bind(like, like, like, like, ...filters.params, limit, offset).all();
|
|
81183
82051
|
return withSnippetFallback((results || []).map(mapRow), query);
|
|
81184
82052
|
}
|
|
81185
82053
|
return { async search(query, options = {}) {
|
|
@@ -81192,6 +82060,168 @@ function createSearchService(rawQuery, siteId, databaseDialect = "sqlite") {
|
|
|
81192
82060
|
} };
|
|
81193
82061
|
}
|
|
81194
82062
|
//#endregion
|
|
82063
|
+
//#region src/services/thread.ts
|
|
82064
|
+
/**
|
|
82065
|
+
* Thread Service
|
|
82066
|
+
*
|
|
82067
|
+
* Threads as a resource of their own: a list of Thread roots in one of the
|
|
82068
|
+
* orders the site shows, each with its Post count and, on request, the fold the
|
|
82069
|
+
* homepage draws; one Thread by any of its Posts; and a Thread's Posts in Thread
|
|
82070
|
+
* order.
|
|
82071
|
+
*
|
|
82072
|
+
* Every read goes through `PostService`. What lives here is the choice of read:
|
|
82073
|
+
* which order a request names, when a collection's own order and pins apply,
|
|
82074
|
+
* and what a reader may see as opposed to the author.
|
|
82075
|
+
*/ var FEATURED_SORT_MESSAGE = "Featured posts are listed newest-published first. Leave sort out, or pass sort=published.";
|
|
82076
|
+
/**
|
|
82077
|
+
* How a plain Thread list orders each `ThreadSort`, as `PostFilters` fields.
|
|
82078
|
+
* Only `activity`, the homepage's order, puts pinned Threads first.
|
|
82079
|
+
*/ function toListOrder(sort) {
|
|
82080
|
+
switch (sort) {
|
|
82081
|
+
case "activity": return {
|
|
82082
|
+
sortBy: "activity",
|
|
82083
|
+
sortOrder: "newest"
|
|
82084
|
+
};
|
|
82085
|
+
case "published": return {
|
|
82086
|
+
sortBy: "published",
|
|
82087
|
+
sortOrder: "newest",
|
|
82088
|
+
ignorePinnedSort: true
|
|
82089
|
+
};
|
|
82090
|
+
case "updated": return {
|
|
82091
|
+
sortBy: "thread_updated",
|
|
82092
|
+
sortOrder: "newest",
|
|
82093
|
+
ignorePinnedSort: true
|
|
82094
|
+
};
|
|
82095
|
+
case "oldest": return {
|
|
82096
|
+
sortBy: "published",
|
|
82097
|
+
sortOrder: "oldest",
|
|
82098
|
+
ignorePinnedSort: true
|
|
82099
|
+
};
|
|
82100
|
+
case "rating": return {
|
|
82101
|
+
sortBy: "activity",
|
|
82102
|
+
sortOrder: "rating_desc",
|
|
82103
|
+
ignorePinnedSort: true
|
|
82104
|
+
};
|
|
82105
|
+
}
|
|
82106
|
+
}
|
|
82107
|
+
/**
|
|
82108
|
+
* The collection order a `ThreadSort` names, or null for the two that read a
|
|
82109
|
+
* collection as a plain filter.
|
|
82110
|
+
*/ function toCollectionOrder(sort) {
|
|
82111
|
+
switch (sort) {
|
|
82112
|
+
case "activity": return "newest";
|
|
82113
|
+
case "oldest": return "oldest";
|
|
82114
|
+
case "rating": return "rating_desc";
|
|
82115
|
+
case "published":
|
|
82116
|
+
case "updated": return null;
|
|
82117
|
+
}
|
|
82118
|
+
}
|
|
82119
|
+
/**
|
|
82120
|
+
* Create the Thread service.
|
|
82121
|
+
*
|
|
82122
|
+
* @param deps - The Post and collection services it reads through
|
|
82123
|
+
* @returns The Thread service
|
|
82124
|
+
* @example
|
|
82125
|
+
* const threads = createThreadService({ posts, collections });
|
|
82126
|
+
*/ function createThreadService(deps) {
|
|
82127
|
+
const { posts, collections } = deps;
|
|
82128
|
+
/**
|
|
82129
|
+
* The order a collection's page would use: its configured order when it is
|
|
82130
|
+
* the only one named, activity for several. A rating order with fewer than
|
|
82131
|
+
* two rated Threads falls back, as the page does — for the default only; a
|
|
82132
|
+
* caller who asks for `rating` gets it.
|
|
82133
|
+
*/ async function resolveDefaultCollectionOrder(collectionIds, options) {
|
|
82134
|
+
const [onlyId, ...others] = collectionIds;
|
|
82135
|
+
if (!onlyId || others.length > 0) return "newest";
|
|
82136
|
+
const collection = await collections.getById(onlyId);
|
|
82137
|
+
if (!collection) return "newest";
|
|
82138
|
+
const ratedThreadCount = await posts.countCollectionThreadRootsUpToForCollections([onlyId], {
|
|
82139
|
+
...options,
|
|
82140
|
+
hasRating: true
|
|
82141
|
+
}, 2);
|
|
82142
|
+
return resolveCollectionSortOrder(void 0, collection.sortOrder, supportsCollectionRatingSort(ratedThreadCount));
|
|
82143
|
+
}
|
|
82144
|
+
const service = {
|
|
82145
|
+
async listThreads(query, page) {
|
|
82146
|
+
const reader = query.audience === "reader";
|
|
82147
|
+
const { selection } = query;
|
|
82148
|
+
const visibility = selection.visibility;
|
|
82149
|
+
if (reader && visibility === "private") throw new ValidationError("Private posts aren't listed here.");
|
|
82150
|
+
if (visibility === "featured" && query.sort !== void 0 && query.sort !== "published") throw new ValidationError(FEATURED_SORT_MESSAGE);
|
|
82151
|
+
const base = {
|
|
82152
|
+
status: reader ? "published" : query.status ?? "published",
|
|
82153
|
+
excludePrivate: reader,
|
|
82154
|
+
excludeLatestHidden: reader && visibility === void 0 && !query.includeHidden,
|
|
82155
|
+
lang: query.lang
|
|
82156
|
+
};
|
|
82157
|
+
const collectionIds = selection.collection;
|
|
82158
|
+
if (collectionIds && visibility !== "featured") {
|
|
82159
|
+
const { collection: _named, ...rootSelection } = selection;
|
|
82160
|
+
const options = {
|
|
82161
|
+
...base,
|
|
82162
|
+
rootFilters: toPostFilters(rootSelection, { yearAxis: "published" })
|
|
82163
|
+
};
|
|
82164
|
+
const collectionOrder = query.sort === void 0 ? await resolveDefaultCollectionOrder(collectionIds, options) : toCollectionOrder(query.sort);
|
|
82165
|
+
if (collectionOrder) {
|
|
82166
|
+
const result = await posts.listCollectionThreadRootPage([...collectionIds], {
|
|
82167
|
+
...options,
|
|
82168
|
+
sortOrder: collectionOrder
|
|
82169
|
+
}, page);
|
|
82170
|
+
return {
|
|
82171
|
+
threads: await service.summarize(result.posts, query),
|
|
82172
|
+
nextCursor: result.nextCursor
|
|
82173
|
+
};
|
|
82174
|
+
}
|
|
82175
|
+
}
|
|
82176
|
+
const result = await posts.listPage({
|
|
82177
|
+
...base,
|
|
82178
|
+
excludeReplies: true,
|
|
82179
|
+
...toPostFilters(selection, { yearAxis: "published" }),
|
|
82180
|
+
...visibility === "featured" ? toListOrder("published") : toListOrder(query.sort ?? "activity")
|
|
82181
|
+
}, page);
|
|
82182
|
+
return {
|
|
82183
|
+
threads: await service.summarize(result.posts, query),
|
|
82184
|
+
nextCursor: result.nextCursor
|
|
82185
|
+
};
|
|
82186
|
+
},
|
|
82187
|
+
async findRoot(ref, audience) {
|
|
82188
|
+
const post = "id" in ref ? await posts.getById(ref.id) : await posts.getBySlug(ref.slug);
|
|
82189
|
+
if (!post) return null;
|
|
82190
|
+
if (audience === "reader" && post.status !== "published") return null;
|
|
82191
|
+
const root = post.threadId === post.id ? post : await posts.getById(post.threadId);
|
|
82192
|
+
if (!root) return null;
|
|
82193
|
+
if (audience === "reader" && (root.status !== "published" || root.visibility === "private")) return null;
|
|
82194
|
+
return root;
|
|
82195
|
+
},
|
|
82196
|
+
async summarize(roots, options) {
|
|
82197
|
+
if (roots.length === 0) return [];
|
|
82198
|
+
const rootIds = roots.map((root) => root.id);
|
|
82199
|
+
const [counts, contexts] = await Promise.all([posts.countThreadPosts(rootIds), options.fold ? posts.getThreadTimelineContext(rootIds) : Promise.resolve(null)]);
|
|
82200
|
+
return roots.map((root) => {
|
|
82201
|
+
const summary = {
|
|
82202
|
+
root,
|
|
82203
|
+
postCount: counts.get(root.id) ?? 0
|
|
82204
|
+
};
|
|
82205
|
+
if (contexts) {
|
|
82206
|
+
const context = contexts.get(root.id);
|
|
82207
|
+
summary.fold = context ? foldReplyWindows({
|
|
82208
|
+
leadingReplies: context.leadingReplies,
|
|
82209
|
+
trailingReplies: context.trailingReplies,
|
|
82210
|
+
latestReply: context.latestReply,
|
|
82211
|
+
nextReply: context.firstHiddenReply,
|
|
82212
|
+
totalReplyCount: context.totalReplyCount
|
|
82213
|
+
}) : null;
|
|
82214
|
+
}
|
|
82215
|
+
return summary;
|
|
82216
|
+
});
|
|
82217
|
+
},
|
|
82218
|
+
async listPosts(rootId, query, page) {
|
|
82219
|
+
return posts.listThreadPostsPage(rootId, { status: query.audience === "reader" ? "published" : query.status ?? "published" }, page);
|
|
82220
|
+
}
|
|
82221
|
+
};
|
|
82222
|
+
return service;
|
|
82223
|
+
}
|
|
82224
|
+
//#endregion
|
|
81195
82225
|
//#region src/services/navigation.ts
|
|
81196
82226
|
/**
|
|
81197
82227
|
* Nav Item Service (v2)
|
|
@@ -83313,6 +84343,10 @@ function createTelegramService(db, siteId, databaseSchema = sqliteSchemaBundle)
|
|
|
83313
84343
|
site,
|
|
83314
84344
|
paths,
|
|
83315
84345
|
posts,
|
|
84346
|
+
threads: createThreadService({
|
|
84347
|
+
posts,
|
|
84348
|
+
collections
|
|
84349
|
+
}),
|
|
83316
84350
|
customUrls: createCustomUrlService(db, siteId, paths, databaseSchema),
|
|
83317
84351
|
media,
|
|
83318
84352
|
uploads: createUploadSessionService(db, siteId, media, databaseSchema),
|
|
@@ -84113,9 +85147,11 @@ async function servePublicStorage(c) {
|
|
|
84113
85147
|
app.use("*", requireRssFeedsEnabled());
|
|
84114
85148
|
app.route("/", siteSkillRoutes);
|
|
84115
85149
|
app.route("/api/public/posts", publicPostsApiRoutes);
|
|
85150
|
+
app.route("/api/public/threads", publicThreadsApiRoutes);
|
|
84116
85151
|
app.route("/api/public/archive", publicArchiveApiRoutes);
|
|
84117
85152
|
app.route("/api/discover", discoverApiRoutes);
|
|
84118
85153
|
app.route("/api/posts", postsApiRoutes);
|
|
85154
|
+
app.route("/api/threads", threadsApiRoutes);
|
|
84119
85155
|
app.route("/api/nav-items", navItemsApiRoutes);
|
|
84120
85156
|
app.route("/api/collections", collectionsApiRoutes);
|
|
84121
85157
|
app.route("/api/smart-collections", smartCollectionsApiRoutes);
|