@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.
Files changed (47) hide show
  1. package/dist/{app--uxnaIRV.js → app-B3P2N2vM.js} +1346 -310
  2. package/dist/client/.vite/manifest.json +2 -2
  3. package/dist/client/_assets/{client-auth-begiT1tq.js → client-auth-CeGBe0qG.js} +1 -1
  4. package/dist/client/_assets/{client-BT6kpcuG.js → client-nByuF0Ct.js} +1 -1
  5. package/dist/index.js +1 -1
  6. package/dist/node.js +2 -2
  7. package/package.json +1 -1
  8. package/src/__tests__/helpers/cursor-walk.ts +37 -7
  9. package/src/app.tsx +4 -0
  10. package/src/lib/__tests__/discover.test.ts +24 -0
  11. package/src/lib/__tests__/thread-fold.test.ts +43 -0
  12. package/src/lib/api-posts.ts +110 -2
  13. package/src/lib/api-public-posts.ts +263 -0
  14. package/src/lib/api-threads.ts +207 -0
  15. package/src/lib/discover.ts +34 -0
  16. package/src/lib/thread-fold.ts +83 -41
  17. package/src/lib/thread-query.ts +143 -0
  18. package/src/middleware/cors.ts +8 -1
  19. package/src/middleware/deprecation.ts +48 -0
  20. package/src/routes/api/__tests__/mcp.test.ts +143 -0
  21. package/src/routes/api/__tests__/posts.test.ts +78 -0
  22. package/src/routes/api/__tests__/public-access.test.ts +5 -0
  23. package/src/routes/api/__tests__/search.test.ts +104 -0
  24. package/src/routes/api/__tests__/threads.test.ts +115 -0
  25. package/src/routes/api/posts.ts +15 -104
  26. package/src/routes/api/public/__tests__/threads.test.ts +363 -0
  27. package/src/routes/api/public/archive.ts +82 -81
  28. package/src/routes/api/public/posts.ts +97 -298
  29. package/src/routes/api/public/threads.ts +141 -0
  30. package/src/routes/api/search.ts +31 -2
  31. package/src/routes/api/threads.ts +128 -0
  32. package/src/routes/auth/__tests__/setup-discover.test.ts +29 -1
  33. package/src/routes/auth/__tests__/setup-page.test.tsx +59 -1
  34. package/src/routes/auth/setup.tsx +48 -9
  35. package/src/routes/pages/__tests__/search.test.ts +58 -0
  36. package/src/routes/pages/search.tsx +3 -1
  37. package/src/services/__tests__/search.test.ts +211 -0
  38. package/src/services/__tests__/thread.test.ts +495 -0
  39. package/src/services/index.ts +4 -0
  40. package/src/services/mcp.ts +217 -57
  41. package/src/services/post.ts +222 -43
  42. package/src/services/search.ts +77 -66
  43. package/src/services/thread.ts +392 -0
  44. package/src/types/constants.ts +25 -0
  45. package/src/ui/feed/ThreadPreview.tsx +9 -14
  46. package/src/ui/feed/__tests__/thread-preview.test.ts +18 -22
  47. package/src/ui/feed/thread-preview-state.ts +0 -35
@@ -0,0 +1,115 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { createTestApp } from "../../../__tests__/helpers/app.js";
3
+ import { walkThreadPages } from "../../../__tests__/helpers/cursor-walk.js";
4
+ import type { CreatePost } from "../../../types.js";
5
+ import { threadsApiRoutes } from "../threads.js";
6
+
7
+ const DAY = 86_400;
8
+ const BASE = Date.UTC(2025, 0, 1) / 1000;
9
+ const day = (n: number) => BASE + n * DAY;
10
+
11
+ function setup(authenticated = true) {
12
+ const testApp = createTestApp({ authenticated });
13
+ testApp.app.route("/api/threads", threadsApiRoutes);
14
+ const post = (data: Partial<CreatePost>) =>
15
+ testApp.services.posts.create({
16
+ format: "note",
17
+ bodyMarkdown: "body",
18
+ ...data,
19
+ });
20
+ const get = async (path: string) => {
21
+ const res = await testApp.app.request(path);
22
+ return { status: res.status, body: await res.json() };
23
+ };
24
+ return { ...testApp, post, get };
25
+ }
26
+
27
+ const ids = (items: Array<{ id: string }>) => items.map((item) => item.id);
28
+
29
+ describe("Threads API Routes", () => {
30
+ it.each(["/api/threads", "/api/threads/pst_x", "/api/threads/pst_x/posts"])(
31
+ "requires authentication for %s",
32
+ async (path) => {
33
+ const { app } = setup(false);
34
+ expect((await app.request(path)).status).toBe(401);
35
+ },
36
+ );
37
+
38
+ it("lists every visibility by default, in the editing view", async () => {
39
+ const { post, get } = setup();
40
+ const shown = await post({ publishedAt: day(1) });
41
+ const hidden = await post({
42
+ publishedAt: day(2),
43
+ visibility: "latest_hidden",
44
+ });
45
+ const secret = await post({ publishedAt: day(3), visibility: "private" });
46
+ await post({ status: "draft" });
47
+
48
+ const { status, body } = await get("/api/threads");
49
+ expect(status).toBe(200);
50
+ expect(ids(body.threads)).toEqual([secret.id, hidden.id, shown.id]);
51
+ expect(body.threads[0].root).toMatchObject({
52
+ id: secret.id,
53
+ body: expect.any(String),
54
+ displayTitle: expect.any(String),
55
+ threadPostCount: 1,
56
+ });
57
+
58
+ const privateOnly = await get("/api/threads?visibility=private");
59
+ expect(ids(privateOnly.body.threads)).toEqual([secret.id]);
60
+ });
61
+
62
+ it("lists drafts by status", async () => {
63
+ const { post, get } = setup();
64
+ const draft = await post({ status: "draft" });
65
+ await post({ publishedAt: day(1) });
66
+ const { body } = await get("/api/threads?status=draft");
67
+ expect(ids(body.threads)).toEqual([draft.id]);
68
+ expect(body.threads[0].postCount).toBe(0);
69
+ });
70
+
71
+ it("walks with a cursor", async () => {
72
+ const { post, get, app } = setup();
73
+ for (let i = 0; i < 4; i++) await post({ publishedAt: day(i) });
74
+ const { body } = await get("/api/threads?sort=published&limit=100");
75
+ expect(
76
+ await walkThreadPages(app, "/api/threads?sort=published", 1),
77
+ ).toEqual(ids(body.threads));
78
+ });
79
+
80
+ it("returns a Thread, drafts included, by any of its Posts", async () => {
81
+ const { post, get } = setup();
82
+ const draft = await post({ status: "draft" });
83
+ const root = await post({ publishedAt: day(1) });
84
+ const reply = await post({ replyToId: root.id, publishedAt: day(2) });
85
+
86
+ const found = await get(`/api/threads/${reply.id}?include=fold`);
87
+ expect(found.status).toBe(200);
88
+ expect(found.body).toMatchObject({ id: root.id, postCount: 2 });
89
+ expect(found.body.fold).toEqual({
90
+ leading: [],
91
+ hidden: 0,
92
+ gap: null,
93
+ trailing: [expect.objectContaining({ id: reply.id })],
94
+ });
95
+
96
+ expect((await get(`/api/threads/${draft.id}`)).status).toBe(200);
97
+ expect((await get("/api/threads/not-an-id")).status).toBe(400);
98
+ expect(
99
+ (await get("/api/threads/pst_01jpyx3m7gw4w3h7m4bknq0v1d")).status,
100
+ ).toBe(404);
101
+ });
102
+
103
+ it("lists a Thread's Posts by status", async () => {
104
+ const { post, get } = setup();
105
+ const root = await post({ publishedAt: day(1) });
106
+ const reply = await post({ replyToId: root.id, publishedAt: day(2) });
107
+ const unsent = await post({ replyToId: reply.id, status: "draft" });
108
+
109
+ const published = await get(`/api/threads/${root.id}/posts`);
110
+ expect(ids(published.body.posts)).toEqual([root.id, reply.id]);
111
+ expect(published.body.posts[1].threadPostCount).toBe(2);
112
+ const drafts = await get(`/api/threads/${root.id}/posts?status=draft`);
113
+ expect(ids(drafts.body.posts)).toEqual([unsent.id]);
114
+ });
115
+ });
@@ -16,7 +16,11 @@ import {
16
16
  parseValidated,
17
17
  } from "../../lib/schemas.js";
18
18
  import { requireAuthApi } from "../../middleware/auth.js";
19
- import { toApiAttachment, toApiPost } from "../../lib/api-posts.js";
19
+ import {
20
+ apiPostListOrder,
21
+ loadApiPostResponse,
22
+ loadApiPostResponses,
23
+ } from "../../lib/api-posts.js";
20
24
  import { getPostDisplayTitle } from "../../lib/post-meta.js";
21
25
  import { assertFound, NotFoundError, parseIdParam } from "../../lib/errors.js";
22
26
  import { AddressQuerySchema, requestInternalPath } from "../../lib/address.js";
@@ -59,37 +63,14 @@ postsApiRoutes.get("/", requireAuthApi(), async (c) => {
59
63
  c.req.query(),
60
64
  );
61
65
 
66
+ const listStatus = status ?? "published";
62
67
  const { posts, nextCursor } = await c.var.services.posts.listPage(
63
- { format, status: status ?? "published" },
68
+ { format, status: listStatus, ...apiPostListOrder(listStatus) },
64
69
  { cursor, limit },
65
70
  );
66
71
 
67
- // Batch load media for all posts
68
- const postIds = posts.map((p) => p.id);
69
- const mediaMap = await c.var.services.media.getByPostIds(postIds);
70
- const {
71
- r2PublicUrl,
72
- imageTransformUrl,
73
- s3PublicUrl,
74
- localPublicUrl,
75
- sitePathPrefix,
76
- } = c.var.appConfig;
77
-
78
72
  return c.json({
79
- posts: posts.map((p) =>
80
- toApiPost(p, {
81
- attachments: (mediaMap.get(p.id) ?? []).map((m) =>
82
- toApiAttachment(
83
- m,
84
- r2PublicUrl,
85
- imageTransformUrl,
86
- s3PublicUrl,
87
- localPublicUrl,
88
- sitePathPrefix,
89
- ),
90
- ),
91
- }),
92
- ),
73
+ posts: await loadApiPostResponses(c.var, posts),
93
74
  nextCursor,
94
75
  });
95
76
  });
@@ -131,39 +112,14 @@ postsApiRoutes.get("/:id/content", requireAuthApi(), async (c) => {
131
112
  postsApiRoutes.get("/:id", requireAuthApi(), async (c) => {
132
113
  const id = parseIdParam(c.req.param("id"), ID_PREFIX.post);
133
114
 
134
- // Fetch post, media, collections and thread position in parallel (all keyed
135
- // by the same id)
136
- const [post, mediaList, threadCollections, threadPosition] =
137
- await Promise.all([
138
- c.var.services.posts.getById(id),
139
- c.var.services.media.getByPostId(id),
140
- c.var.services.collections.getCollectionsByPostId(id),
141
- c.var.services.posts.getThreadPosition(id),
142
- ]);
115
+ const [post, threadPosition] = await Promise.all([
116
+ c.var.services.posts.getById(id),
117
+ c.var.services.posts.getThreadPosition(id),
118
+ ]);
143
119
  const foundPost = assertFound(post, "Post");
144
- const {
145
- r2PublicUrl,
146
- imageTransformUrl,
147
- s3PublicUrl,
148
- localPublicUrl,
149
- sitePathPrefix,
150
- } = c.var.appConfig;
151
- const collectionIds = threadCollections.map((col) => col.id);
152
120
 
153
121
  return c.json({
154
- ...toApiPost(foundPost, {
155
- collectionIds,
156
- attachments: mediaList.map((m) =>
157
- toApiAttachment(
158
- m,
159
- r2PublicUrl,
160
- imageTransformUrl,
161
- s3PublicUrl,
162
- localPublicUrl,
163
- sitePathPrefix,
164
- ),
165
- ),
166
- }),
122
+ ...(await loadApiPostResponse(c.var, foundPost, { collectionIds: true })),
167
123
  threadPosition,
168
124
  });
169
125
  });
@@ -215,33 +171,10 @@ postsApiRoutes.post("/", requireAuthApi(), async (c) => {
215
171
  },
216
172
  );
217
173
 
218
- const mediaList = await c.var.services.media.getByPostId(post.id);
219
- const {
220
- r2PublicUrl,
221
- imageTransformUrl,
222
- s3PublicUrl,
223
- localPublicUrl,
224
- sitePathPrefix,
225
- } = c.var.appConfig;
226
-
227
174
  // Trigger GitHub Sync in background (no-op when sync isn't enabled).
228
175
  await triggerGitHubSyncInline(c);
229
176
 
230
- return c.json(
231
- toApiPost(post, {
232
- attachments: mediaList.map((m) =>
233
- toApiAttachment(
234
- m,
235
- r2PublicUrl,
236
- imageTransformUrl,
237
- s3PublicUrl,
238
- localPublicUrl,
239
- sitePathPrefix,
240
- ),
241
- ),
242
- }),
243
- 201,
244
- );
177
+ return c.json(await loadApiPostResponse(c.var, post), 201);
245
178
  });
246
179
 
247
180
  // Update post (requires auth)
@@ -293,29 +226,7 @@ postsApiRoutes.put("/:id", requireAuthApi(), async (c) => {
293
226
  // Trigger GitHub Sync in background (no-op when sync isn't enabled).
294
227
  await triggerGitHubSyncInline(c);
295
228
 
296
- const mediaList = await c.var.services.media.getByPostId(post.id);
297
- const {
298
- r2PublicUrl,
299
- imageTransformUrl,
300
- s3PublicUrl,
301
- localPublicUrl,
302
- sitePathPrefix,
303
- } = c.var.appConfig;
304
-
305
- return c.json(
306
- toApiPost(post, {
307
- attachments: mediaList.map((m) =>
308
- toApiAttachment(
309
- m,
310
- r2PublicUrl,
311
- imageTransformUrl,
312
- s3PublicUrl,
313
- localPublicUrl,
314
- sitePathPrefix,
315
- ),
316
- ),
317
- }),
318
- );
229
+ return c.json(await loadApiPostResponse(c.var, post));
319
230
  });
320
231
 
321
232
  // =============================================================================
@@ -0,0 +1,363 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { createTestApp } from "../../../../__tests__/helpers/app.js";
3
+ import { enforceD1BoundParameterLimit } from "../../../../__tests__/helpers/db.js";
4
+ import {
5
+ walkPostPages,
6
+ walkThreadPages,
7
+ } from "../../../../__tests__/helpers/cursor-walk.js";
8
+ import type { CreatePost, Post } from "../../../../types.js";
9
+ import { publicArchiveApiRoutes } from "../archive.js";
10
+ import { publicPostsApiRoutes } from "../posts.js";
11
+ import { publicThreadsApiRoutes } from "../threads.js";
12
+
13
+ const DAY = 86_400;
14
+ const BASE = Date.UTC(2025, 0, 1) / 1000;
15
+ const day = (n: number) => BASE + n * DAY;
16
+
17
+ function setup() {
18
+ const testApp = createTestApp({ authenticated: false });
19
+ testApp.app.route("/api/public/threads", publicThreadsApiRoutes);
20
+ testApp.app.route("/api/public/posts", publicPostsApiRoutes);
21
+ testApp.app.route("/api/public/archive", publicArchiveApiRoutes);
22
+ const { services } = testApp;
23
+ const post = (data: Partial<CreatePost>) =>
24
+ services.posts.create({ format: "note", bodyMarkdown: "body", ...data });
25
+ /** A root and `replies` replies, one a day, each created when published. */
26
+ const thread = async (replies: number, root: Partial<CreatePost> = {}) => {
27
+ const first = await post({
28
+ publishedAt: day(0),
29
+ createdAt: day(0),
30
+ ...root,
31
+ });
32
+ const all: Post[] = [first];
33
+ let parent = first;
34
+ for (let i = 1; i <= replies; i++) {
35
+ parent = await post({
36
+ replyToId: parent.id,
37
+ publishedAt: day(i),
38
+ createdAt: day(i),
39
+ });
40
+ all.push(parent);
41
+ }
42
+ return all;
43
+ };
44
+ const get = async (path: string) => {
45
+ const res = await testApp.app.request(path);
46
+ return { status: res.status, headers: res.headers, body: await res.json() };
47
+ };
48
+ return { ...testApp, post, thread, get };
49
+ }
50
+
51
+ const ids = (items: Array<{ id: string }>) => items.map((item) => item.id);
52
+
53
+ describe("GET /api/public/threads", () => {
54
+ it("lists what the homepage lists, as Thread objects", async () => {
55
+ const { post, thread, get } = setup();
56
+ const [root, reply] = await thread(1);
57
+ const lone = await post({ publishedAt: day(5) });
58
+ await post({ publishedAt: day(6), visibility: "latest_hidden" });
59
+ await post({ publishedAt: day(7), visibility: "private" });
60
+
61
+ const { status, body } = await get("/api/public/threads");
62
+ expect(status).toBe(200);
63
+ expect(ids(body.threads)).toEqual([lone.id, root?.id]);
64
+ expect(body.nextCursor).toBeNull();
65
+
66
+ const [loneThread, rootThread] = body.threads;
67
+ expect(rootThread).toMatchObject({
68
+ id: root?.id,
69
+ postCount: 2,
70
+ lastActivityAt: reply?.publishedAt,
71
+ root: { id: root?.id, threadPostCount: 2, permalink: `/${root?.slug}` },
72
+ });
73
+ expect(rootThread.fold).toBeUndefined();
74
+ expect(loneThread.postCount).toBe(1);
75
+ });
76
+
77
+ it("attaches the homepage fold on request", async () => {
78
+ const { post, thread, get } = setup();
79
+ const all = await thread(8);
80
+ const lone = await post({ publishedAt: day(1) });
81
+
82
+ const { body } = await get("/api/public/threads?include=fold&sort=oldest");
83
+ const [long, single] = body.threads;
84
+ expect(long.id).toBe(all[0]?.id);
85
+ expect(ids(long.fold.leading)).toEqual(ids(all.slice(1, 3)));
86
+ expect(long.fold.hidden).toBe(3);
87
+ expect(long.fold.gap).toEqual({
88
+ id: all[3]?.id,
89
+ slug: all[3]?.slug,
90
+ permalink: `/${all[3]?.slug}`,
91
+ });
92
+ // Oldest first, the newest reply last.
93
+ expect(ids(long.fold.trailing)).toEqual(ids(all.slice(6)));
94
+ expect(long.fold.trailing[2].threadPostCount).toBe(9);
95
+
96
+ expect(single.id).toBe(lone.id);
97
+ expect(single.fold).toEqual({
98
+ leading: [],
99
+ hidden: 0,
100
+ gap: null,
101
+ trailing: [],
102
+ });
103
+ });
104
+
105
+ it("opens the run a fold hides with one request", async () => {
106
+ const { thread, get, app } = setup();
107
+ const all = await thread(10);
108
+ const {
109
+ body: { threads },
110
+ } = await get("/api/public/threads?include=fold");
111
+ const fold = threads[0].fold;
112
+ const lastLeading = fold.leading[fold.leading.length - 1].id;
113
+
114
+ const { body } = await get(
115
+ `/api/public/threads/${all[0]?.slug}/posts?cursor=${lastLeading}&limit=${fold.hidden}`,
116
+ );
117
+ expect(body.posts[0].id).toBe(fold.gap.id);
118
+ expect(ids(body.posts)).toEqual(ids(all.slice(3, 3 + fold.hidden)));
119
+
120
+ expect(
121
+ await walkPostPages(app, `/api/public/threads/${all[0]?.slug}/posts`, 3),
122
+ ).toEqual(ids(all));
123
+ });
124
+
125
+ it("widens to every visibility a reader may see with visibility=any", async () => {
126
+ const { post, get } = setup();
127
+ const shown = await post({ publishedAt: day(1) });
128
+ const hidden = await post({
129
+ publishedAt: day(2),
130
+ visibility: "latest_hidden",
131
+ });
132
+ await post({ publishedAt: day(3), visibility: "private" });
133
+
134
+ const any = await get("/api/public/threads?visibility=any");
135
+ expect(ids(any.body.threads)).toEqual([hidden.id, shown.id]);
136
+ const only = await get("/api/public/threads?visibility=hidden");
137
+ expect(ids(only.body.threads)).toEqual([hidden.id]);
138
+ });
139
+
140
+ it("walks a whole site in publication order", async () => {
141
+ const { post, thread, app } = setup();
142
+ const [old] = await thread(1);
143
+ await post({ publishedAt: day(4), visibility: "latest_hidden" });
144
+ await post({ publishedAt: day(3), pinned: true });
145
+ await post({ publishedAt: day(2) });
146
+
147
+ const full = await app.request(
148
+ "/api/public/threads?visibility=any&sort=published&limit=100",
149
+ );
150
+ const expected = ids((await full.json()).threads);
151
+ expect(expected).toHaveLength(4);
152
+ expect(expected[3]).toBe(old?.id);
153
+ expect(
154
+ await walkThreadPages(
155
+ app,
156
+ "/api/public/threads?visibility=any&sort=published",
157
+ 1,
158
+ ),
159
+ ).toEqual(expected);
160
+ });
161
+
162
+ it("takes the archive's filters", async () => {
163
+ const { services, post, get } = setup();
164
+ const collection = await services.collections.create({
165
+ slug: "books",
166
+ title: "Books",
167
+ });
168
+ const titled = await post({
169
+ title: "A title",
170
+ publishedAt: day(1),
171
+ collectionIds: [collection.id],
172
+ });
173
+ await post({ publishedAt: day(2), collectionIds: [collection.id] });
174
+ await post({ title: "Elsewhere", publishedAt: day(3) });
175
+
176
+ const { body } = await get(
177
+ "/api/public/threads?collection=books&title=any",
178
+ );
179
+ expect(ids(body.threads)).toEqual([titled.id]);
180
+ const missing = await get("/api/public/threads?collection=nope");
181
+ expect(missing.status).toBe(200);
182
+ expect(missing.body).toEqual({ threads: [], nextCursor: null });
183
+ });
184
+
185
+ it.each([
186
+ ["an unknown parameter", "?sorting=published"],
187
+ ["visibility=all", "?visibility=all"],
188
+ ["visibility=private", "?visibility=private"],
189
+ ["an unknown include", "?include=replies"],
190
+ ["an unknown sort", "?sort=newest"],
191
+ ["featured with another order", "?visibility=featured&sort=activity"],
192
+ ])("refuses %s", async (_label, query) => {
193
+ const { get } = setup();
194
+ const { status, body } = await get(`/api/public/threads${query}`);
195
+ expect(status).toBe(400);
196
+ expect(typeof body.error).toBe("string");
197
+ });
198
+
199
+ // D1 refuses a statement with more than 100 bound parameters, and a full
200
+ // page with the fold asks about 100 Threads at once.
201
+ it("serves a full page with the fold within D1's parameter limit", async () => {
202
+ const { services, sqlite, get } = setup();
203
+ for (let i = 0; i < 101; i++) {
204
+ const root = await services.posts.create({
205
+ format: "note",
206
+ bodyMarkdown: `root ${i}`,
207
+ publishedAt: day(i),
208
+ });
209
+ if (i % 10 === 0) {
210
+ await services.posts.create({
211
+ format: "note",
212
+ bodyMarkdown: `reply ${i}`,
213
+ replyToId: root.id,
214
+ publishedAt: day(i) + 1,
215
+ });
216
+ }
217
+ }
218
+ enforceD1BoundParameterLimit(sqlite);
219
+
220
+ const { status, body } = await get(
221
+ "/api/public/threads?limit=100&include=fold",
222
+ );
223
+ expect(status).toBe(200);
224
+ expect(body.threads).toHaveLength(100);
225
+ expect(
226
+ body.threads.filter(
227
+ (thread: { fold: { trailing: unknown[] } }) =>
228
+ thread.fold.trailing.length === 1,
229
+ ),
230
+ ).toHaveLength(10);
231
+ expect(body.nextCursor).not.toBeNull();
232
+ });
233
+
234
+ it("returns Markdown on request", async () => {
235
+ const { post, get } = setup();
236
+ await post({ publishedAt: day(1), bodyMarkdown: "Some *text*" });
237
+ const { body } = await get("/api/public/threads?content=markdown");
238
+ expect(body.threads[0].root.bodyMarkdown).toBe("Some *text*");
239
+ expect(body.threads[0].root.bodyHtml).toBeUndefined();
240
+ });
241
+ });
242
+
243
+ describe("GET /api/public/threads/:slug", () => {
244
+ it("returns the Thread any of its Posts names", async () => {
245
+ const { thread, get } = setup();
246
+ const all = await thread(2);
247
+ const { status, body } = await get(
248
+ `/api/public/threads/${all[2]?.slug}?include=fold`,
249
+ );
250
+ expect(status).toBe(200);
251
+ expect(body).toMatchObject({ id: all[0]?.id, postCount: 3 });
252
+ expect(ids(body.fold.leading)).toEqual(ids(all.slice(1, 2)));
253
+ expect(ids(body.fold.trailing)).toEqual(ids(all.slice(2)));
254
+ });
255
+
256
+ it("finds a Thread hidden from Latest", async () => {
257
+ const { thread, get } = setup();
258
+ const [root] = await thread(0, { visibility: "latest_hidden" });
259
+ expect((await get(`/api/public/threads/${root?.slug}`)).status).toBe(200);
260
+ });
261
+
262
+ it("returns 404 for what a reader can't see", async () => {
263
+ const { services, post, thread, get } = setup();
264
+ const secret = await post({ publishedAt: day(1), visibility: "private" });
265
+ const draft = await post({ status: "draft" });
266
+ const all = await thread(1);
267
+ const unsent = await services.posts.create({
268
+ format: "note",
269
+ bodyMarkdown: "unsent",
270
+ replyToId: all[1]?.id,
271
+ status: "draft",
272
+ });
273
+
274
+ for (const slug of [secret.slug, draft.slug, unsent.slug, "missing"]) {
275
+ expect((await get(`/api/public/threads/${slug}`)).status).toBe(404);
276
+ expect((await get(`/api/public/threads/${slug}/posts`)).status).toBe(404);
277
+ }
278
+ });
279
+ });
280
+
281
+ describe("GET /api/public/threads/:slug/posts", () => {
282
+ it("lists published Posts in Thread order", async () => {
283
+ const { services, thread, get } = setup();
284
+ const all = await thread(3);
285
+ await services.posts.create({
286
+ format: "note",
287
+ bodyMarkdown: "unsent",
288
+ replyToId: all[3]?.id,
289
+ status: "draft",
290
+ });
291
+
292
+ const { body } = await get(`/api/public/threads/${all[1]?.slug}/posts`);
293
+ expect(ids(body.posts)).toEqual(ids(all));
294
+ expect(body.posts[0].threadPostCount).toBe(4);
295
+ expect(body.nextCursor).toBeNull();
296
+ });
297
+
298
+ it("pages a Thread longer than one page", async () => {
299
+ const { thread, get, sqlite } = setup();
300
+ const all = await thread(104);
301
+ enforceD1BoundParameterLimit(sqlite);
302
+
303
+ const path = `/api/public/threads/${all[0]?.slug}/posts`;
304
+ const first = await get(path);
305
+ expect(first.status).toBe(200);
306
+ expect(first.body.posts).toHaveLength(100);
307
+ expect(first.body.posts[0].threadPostCount).toBe(105);
308
+ const second = await get(`${path}?cursor=${first.body.nextCursor}`);
309
+ expect(second.body.nextCursor).toBeNull();
310
+ expect([...ids(first.body.posts), ...ids(second.body.posts)]).toEqual(
311
+ ids(all),
312
+ );
313
+ });
314
+
315
+ it("refuses a cursor that names a Post outside the Thread", async () => {
316
+ const { post, thread, get } = setup();
317
+ const all = await thread(1);
318
+ const other = await post({ publishedAt: day(3) });
319
+ const { status } = await get(
320
+ `/api/public/threads/${all[0]?.slug}/posts?cursor=${other.id}`,
321
+ );
322
+ expect(status).toBe(400);
323
+ });
324
+ });
325
+
326
+ describe("deprecated Thread lists", () => {
327
+ it.each([
328
+ ["/api/public/posts", "</api/public/threads>"],
329
+ [
330
+ "/api/public/archive",
331
+ "</api/public/threads?visibility=any&sort=published>",
332
+ ],
333
+ ])(
334
+ "%s names its replacement and still answers as before",
335
+ async (path, successor) => {
336
+ const { thread, get } = setup();
337
+ const [root] = await thread(2);
338
+
339
+ const { status, headers, body } = await get(path);
340
+ expect(status).toBe(200);
341
+ expect(headers.get("Deprecation")).toMatch(/^@\d+$/);
342
+ expect(headers.get("Link")).toBe(`${successor}; rel="successor-version"`);
343
+ expect(ids(body.posts)).toEqual([root?.id]);
344
+ expect(body.posts[0].threadPostCount).toBe(3);
345
+
346
+ // Errors carry the headers too.
347
+ const refused = await get(`${path}?limit=0`);
348
+ expect(refused.status).toBe(400);
349
+ expect(refused.headers.get("Deprecation")).toMatch(/^@\d+$/);
350
+ },
351
+ );
352
+
353
+ it("leaves the single-post endpoint undeprecated", async () => {
354
+ const { thread, get } = setup();
355
+ const all = await thread(1);
356
+ const { status, headers, body } = await get(
357
+ `/api/public/posts/${all[1]?.slug}`,
358
+ );
359
+ expect(status).toBe(200);
360
+ expect(headers.get("Deprecation")).toBeNull();
361
+ expect(body.threadPostCount).toBe(2);
362
+ });
363
+ });