@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,143 @@
1
+ /**
2
+ * Thread list queries
3
+ *
4
+ * Reads the filter dimensions a Thread list takes — the archive's, from the
5
+ * same registry — out of an HTTP query string or MCP arguments, so the public
6
+ * API, the author API, and MCP accept one vocabulary.
7
+ *
8
+ * One word differs from the archive page. A Thread list left unfiltered shows
9
+ * what the homepage shows, so it needs a word for "every visibility a reader
10
+ * may see": `visibility=any`. The registry's `visibility=all` is an old
11
+ * spelling of leaving the parameter out, which here would mean the homepage's
12
+ * set — the opposite of what the word says — so a Thread list refuses it.
13
+ */
14
+
15
+ import type { ThreadAudience } from "../services/thread.js";
16
+ import type { Collection } from "../types.js";
17
+ import { ValidationError } from "./errors.js";
18
+ import {
19
+ buildCollectionVocabulary,
20
+ EMPTY_COLLECTION_VOCABULARY,
21
+ parsePostFilterSelectionStrict,
22
+ readCollectionSlugs,
23
+ type ParamReader,
24
+ type PostFilterSelection,
25
+ } from "./filter-dimensions.js";
26
+
27
+ /** What a Thread list's filter parameters asked for. */
28
+ export type ThreadSelectionParse =
29
+ | {
30
+ kind: "selection";
31
+ selection: PostFilterSelection;
32
+ /** `visibility=any`: include what the homepage hides. */
33
+ includeHidden: boolean;
34
+ }
35
+ /** A named collection doesn't exist, so nothing can match. */
36
+ | { kind: "empty" };
37
+
38
+ const READER_VISIBILITIES = ["public", "featured", "hidden", "any"] as const;
39
+ const AUTHOR_VISIBILITIES = [...READER_VISIBILITIES, "private"] as const;
40
+ /** Spellings the registry reads that stay valid here. */
41
+ const LEGACY_VISIBILITIES = ["latest_hidden"] as const;
42
+
43
+ function allowedVisibilities(audience: ThreadAudience): readonly string[] {
44
+ return audience === "reader" ? READER_VISIBILITIES : AUTHOR_VISIBILITIES;
45
+ }
46
+
47
+ /**
48
+ * Read a Thread list's filter dimensions.
49
+ *
50
+ * @param read - Reads one parameter; `undefined` when absent
51
+ * @param present - Every parameter name the request carries
52
+ * @param options.allow - The endpoint's own parameters, which aren't
53
+ * dimensions; anything else unknown is refused
54
+ * @param options.audience - A reader may not name `private`
55
+ * @param options.loadCollections - Loads the collection vocabulary, called only
56
+ * when a collection is named
57
+ * @returns The selection, or `empty` when a named collection doesn't exist
58
+ * @throws {ValidationError} On an unknown parameter or an unreadable value
59
+ * @example
60
+ * const parsed = await parseThreadSelection(read, Object.keys(query), {
61
+ * allow: ["cursor", "limit"],
62
+ * audience: "reader",
63
+ * loadCollections: () => services.collections.list(),
64
+ * });
65
+ */
66
+ export async function parseThreadSelection(
67
+ read: ParamReader,
68
+ present: readonly string[],
69
+ options: {
70
+ allow: readonly string[];
71
+ audience: ThreadAudience;
72
+ loadCollections: () => Promise<Collection[]>;
73
+ },
74
+ ): Promise<ThreadSelectionParse> {
75
+ const visibility = read("visibility");
76
+ if (visibility !== undefined) {
77
+ const allowed = allowedVisibilities(options.audience);
78
+ if (visibility === "all") {
79
+ throw new ValidationError(
80
+ "visibility=all isn't accepted here. Leave visibility out for what the homepage lists, or pass visibility=any for everything.",
81
+ );
82
+ }
83
+ if (
84
+ !allowed.includes(visibility) &&
85
+ !(LEGACY_VISIBILITIES as readonly string[]).includes(visibility)
86
+ ) {
87
+ throw new ValidationError(
88
+ `Invalid visibility value. Allowed: ${allowed.join(", ")}`,
89
+ );
90
+ }
91
+ }
92
+
93
+ const includeHidden = visibility === "any";
94
+ // `any` isn't a registry value: it widens the audience's default rather
95
+ // than filtering, so the registry reads the query as if it were absent.
96
+ const readDimension: ParamReader = (key) =>
97
+ key === "visibility" && includeHidden ? undefined : read(key);
98
+
99
+ // Resolving a slug costs a round trip, paid only when one is named.
100
+ const collections =
101
+ readCollectionSlugs(readDimension).length > 0
102
+ ? buildCollectionVocabulary(await options.loadCollections())
103
+ : EMPTY_COLLECTION_VOCABULARY;
104
+ const parsed = parsePostFilterSelectionStrict(
105
+ readDimension,
106
+ present,
107
+ { collections },
108
+ { allow: options.allow },
109
+ );
110
+
111
+ if (parsed.ok) {
112
+ return { kind: "selection", selection: parsed.selection, includeHidden };
113
+ }
114
+ // A collection that doesn't exist is answered with nothing rather than a
115
+ // rejection: the caller's words were understood, and the site simply holds
116
+ // no such collection.
117
+ if (parsed.issues.every((issue) => issue.param === "collection")) {
118
+ return { kind: "empty" };
119
+ }
120
+ throw new ValidationError(parsed.issues[0]?.message ?? "Validation failed");
121
+ }
122
+
123
+ /**
124
+ * Read `include`: a comma-separated list of extras to attach to each Thread.
125
+ *
126
+ * @param raw - The parameter's value, or `undefined`
127
+ * @returns Whether the fold was asked for
128
+ * @throws {ValidationError} On a value this endpoint doesn't offer
129
+ * @example
130
+ * parseThreadInclude("fold"); // { fold: true }
131
+ */
132
+ export function parseThreadInclude(raw: string | undefined): { fold: boolean } {
133
+ if (raw === undefined || raw === "") return { fold: false };
134
+ const values = raw.split(",").map((value) => value.trim());
135
+ for (const value of values) {
136
+ if (value !== "fold") {
137
+ throw new ValidationError(
138
+ `Invalid include value "${value}". Allowed: fold`,
139
+ );
140
+ }
141
+ }
142
+ return { fold: values.includes("fold") };
143
+ }
@@ -39,7 +39,14 @@ export function apiCors(): MiddlewareHandler<Env> {
39
39
  origin: origins,
40
40
  allowMethods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
41
41
  allowHeaders: ["Content-Type", "Authorization", "MCP-Protocol-Version"],
42
- exposeHeaders: ["Content-Type", "MCP-Protocol-Version"],
42
+ // `Deprecation` and `Link` are how a deprecated endpoint names its
43
+ // replacement; a browser client can't read either unless exposed.
44
+ exposeHeaders: [
45
+ "Content-Type",
46
+ "MCP-Protocol-Version",
47
+ "Deprecation",
48
+ "Link",
49
+ ],
43
50
  credentials: origins !== "*",
44
51
  maxAge: 86400,
45
52
  });
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Deprecated API endpoints.
3
+ *
4
+ * A deprecated endpoint keeps answering exactly as before until the major
5
+ * release that removes it, and says so on every response, errors included:
6
+ * `Deprecation` (RFC 9745) carries when it was deprecated, and `Link` with
7
+ * `rel="successor-version"` names what replaces it. The docs and the release
8
+ * notes say the same thing in words.
9
+ */
10
+
11
+ import type { MiddlewareHandler } from "hono";
12
+ import type { Bindings } from "../types.js";
13
+ import type { AppVariables } from "../types/app-context.js";
14
+ import { toPublicPath } from "../lib/url.js";
15
+
16
+ type Env = { Bindings: Bindings; Variables: AppVariables };
17
+
18
+ /**
19
+ * When 0.9 deprecated the Thread lists that `/api/public/threads` replaces:
20
+ * the `GET /api/public/posts` list and `GET /api/public/archive`.
21
+ */
22
+ export const THREAD_LIST_DEPRECATED_AT = Date.UTC(2026, 8, 27) / 1000;
23
+
24
+ /**
25
+ * Mark every response of a route as deprecated.
26
+ *
27
+ * @param deprecatedAt - Unix seconds the endpoint was deprecated
28
+ * @param successor - The replacement, as a site path (the site path prefix is
29
+ * added)
30
+ * @returns Hono middleware that sets `Deprecation` and `Link`
31
+ * @example
32
+ * ```ts
33
+ * routes.get("/", deprecated(THREAD_LIST_DEPRECATED_AT, "/api/public/threads"), handler);
34
+ * ```
35
+ */
36
+ export function deprecated(
37
+ deprecatedAt: number,
38
+ successor: string,
39
+ ): MiddlewareHandler<Env> {
40
+ return async (c, next) => {
41
+ await next();
42
+ c.header("Deprecation", `@${deprecatedAt}`);
43
+ c.header(
44
+ "Link",
45
+ `<${toPublicPath(successor, c.var.appConfig.sitePathPrefix)}>; rel="successor-version"`,
46
+ );
47
+ };
48
+ }
@@ -144,6 +144,9 @@ describe("MCP API Routes", () => {
144
144
  );
145
145
 
146
146
  expect(toolNames).toContain("jant_posts_list");
147
+ expect(toolNames).toContain("jant_threads_list");
148
+ expect(toolNames).toContain("jant_threads_get");
149
+ expect(toolNames).toContain("jant_threads_list_posts");
147
150
  expect(toolNames).toContain("jant_collections_add_thread");
148
151
  expect(toolNames).toContain("jant_collections_remove_thread");
149
152
  expect(toolNames).toContain("jant_settings_update");
@@ -213,6 +216,92 @@ describe("MCP API Routes", () => {
213
216
  expect(await services.collections.getThreadIds(collection.id)).toEqual([]);
214
217
  });
215
218
 
219
+ it("reads Threads through tools/call", async () => {
220
+ const { app, services } = createTestApp({ authenticated: true });
221
+ app.route("/api/mcp", mcpApiRoutes);
222
+
223
+ const collection = await services.collections.create({
224
+ slug: "notes",
225
+ title: "Notes",
226
+ });
227
+ const root = await services.posts.create({
228
+ format: "note",
229
+ bodyMarkdown: "Root",
230
+ publishedAt: 1000,
231
+ collectionIds: [collection.id],
232
+ });
233
+ const replies = [];
234
+ let parent = root;
235
+ for (let i = 1; i <= 7; i++) {
236
+ parent = await services.posts.create({
237
+ format: "note",
238
+ bodyMarkdown: `Reply ${i}`,
239
+ replyToId: parent.id,
240
+ publishedAt: 1000 + i,
241
+ createdAt: 1000 + i,
242
+ });
243
+ replies.push(parent);
244
+ }
245
+ const other = await services.posts.create({
246
+ format: "note",
247
+ bodyMarkdown: "Elsewhere",
248
+ publishedAt: 500,
249
+ });
250
+
251
+ const call = async (name: string, args: Record<string, unknown>) => {
252
+ const res = await postMcp(
253
+ app,
254
+ {
255
+ jsonrpc: "2.0",
256
+ id: 40,
257
+ method: "tools/call",
258
+ params: { name, arguments: args },
259
+ },
260
+ { "MCP-Protocol-Version": "2025-06-18" },
261
+ );
262
+ expect(res.status).toBe(200);
263
+ const { result } = await res.json();
264
+ expect(result.isError).toBe(false);
265
+ return result.structuredContent;
266
+ };
267
+
268
+ const all = await call("jant_threads_list", { sort: "published" });
269
+ expect(all.threads.map((thread: { id: string }) => thread.id)).toEqual([
270
+ root.id,
271
+ other.id,
272
+ ]);
273
+ expect(all.threads[0].postCount).toBe(8);
274
+ expect(all.threads[0].fold).toBeUndefined();
275
+
276
+ const inCollection = await call("jant_threads_list", {
277
+ collection: "notes",
278
+ fold: true,
279
+ });
280
+ expect(inCollection.threads).toHaveLength(1);
281
+ expect(inCollection.threads[0].fold.hidden).toBe(2);
282
+ expect(inCollection.threads[0].fold.gap).toEqual({
283
+ id: replies[2]?.id,
284
+ slug: replies[2]?.slug,
285
+ });
286
+
287
+ const thread = await call("jant_threads_get", { id: replies[4]?.id });
288
+ expect(thread).toMatchObject({ id: root.id, postCount: 8 });
289
+
290
+ const walked: string[] = [];
291
+ let cursor: string | undefined;
292
+ for (let page = 0; page < 10; page++) {
293
+ const result = await call("jant_threads_list_posts", {
294
+ id: root.id,
295
+ limit: 3,
296
+ ...(cursor ? { cursor } : {}),
297
+ });
298
+ walked.push(...result.posts.map((post: { id: string }) => post.id));
299
+ cursor = result.nextCursor ?? undefined;
300
+ if (!cursor) break;
301
+ }
302
+ expect(walked).toEqual([root.id, ...replies.map((reply) => reply.id)]);
303
+ });
304
+
216
305
  it("pages posts through tools/call with nextCursor", async () => {
217
306
  const { app, services } = createTestApp({ authenticated: true });
218
307
  app.route("/api/mcp", mcpApiRoutes);
@@ -340,6 +429,60 @@ describe("MCP API Routes", () => {
340
429
  expect(body.result.structuredContent.results[0].slug).toBeTruthy();
341
430
  });
342
431
 
432
+ it("searches private posts and says which results are private", async () => {
433
+ const { app, services } = createTestApp({ authenticated: true, fts: true });
434
+ app.route("/api/mcp", mcpApiRoutes);
435
+
436
+ const root = await services.posts.create({
437
+ format: "note",
438
+ title: "Secret diary",
439
+ body: tiptapDoc("Private root about lanterns"),
440
+ visibility: "private",
441
+ });
442
+ const reply = await services.posts.create({
443
+ format: "note",
444
+ body: tiptapDoc("Private reply about lanterns"),
445
+ replyToId: root.id,
446
+ });
447
+ const publicPost = await services.posts.create({
448
+ format: "note",
449
+ body: tiptapDoc("Public post about lanterns"),
450
+ });
451
+
452
+ const res = await postMcp(
453
+ app,
454
+ {
455
+ jsonrpc: "2.0",
456
+ id: 4,
457
+ method: "tools/call",
458
+ params: {
459
+ name: "jant_search_posts",
460
+ arguments: { query: "lanterns" },
461
+ },
462
+ },
463
+ { "MCP-Protocol-Version": "2025-06-18" },
464
+ );
465
+
466
+ expect(res.status).toBe(200);
467
+ const body = await res.json();
468
+ expect(body.result.isError).toBe(false);
469
+ const visibilityById = new Map(
470
+ (
471
+ body.result.structuredContent.results as {
472
+ id: string;
473
+ visibility: string;
474
+ }[]
475
+ ).map((result) => [result.id, result.visibility]),
476
+ );
477
+ expect(visibilityById).toEqual(
478
+ new Map([
479
+ [root.id, "private"],
480
+ [reply.id, "private"],
481
+ [publicPost.id, "public"],
482
+ ]),
483
+ );
484
+ });
485
+
343
486
  it("uploads media through tools/call", async () => {
344
487
  const storage = createMockStorage();
345
488
  const { app, services } = createTestApp({
@@ -222,6 +222,84 @@ describe("Posts API Routes", () => {
222
222
  expect((await unreadable.json()).code).toBe("VALIDATION_ERROR");
223
223
  });
224
224
 
225
+ // The failure this guards: ordered by thread activity with pins first, a
226
+ // reply lifted a long-published root to the top — past a walk's cursor,
227
+ // so the walk never returned it.
228
+ it("orders published posts by publication alone", async () => {
229
+ const { app, services } = createTestApp({ authenticated: true });
230
+ app.route("/api/posts", postsApiRoutes);
231
+
232
+ const root = await services.posts.create({
233
+ format: "note",
234
+ bodyMarkdown: "old root",
235
+ publishedAt: 1000,
236
+ });
237
+ const pinned = await services.posts.create({
238
+ format: "note",
239
+ bodyMarkdown: "pinned",
240
+ publishedAt: 2000,
241
+ pinned: true,
242
+ });
243
+ const recent = await services.posts.create({
244
+ format: "note",
245
+ bodyMarkdown: "recent",
246
+ publishedAt: 3000,
247
+ });
248
+
249
+ const first = await (await app.request("/api/posts?limit=1")).json();
250
+ expect(first.posts[0].id).toBe(recent.id);
251
+ const reply = await services.posts.create({
252
+ format: "note",
253
+ bodyMarkdown: "late reply",
254
+ replyToId: root.id,
255
+ publishedAt: 4000,
256
+ });
257
+
258
+ const rest = await walkPostPages(app, "/api/posts", 1, first.nextCursor);
259
+ expect(rest).toEqual([pinned.id, root.id]);
260
+ const all = await (await app.request("/api/posts")).json();
261
+ expect(all.posts.map((post: { id: string }) => post.id)).toEqual([
262
+ reply.id,
263
+ recent.id,
264
+ pinned.id,
265
+ root.id,
266
+ ]);
267
+ expect(
268
+ all.posts.map(
269
+ (post: { threadPostCount: number }) => post.threadPostCount,
270
+ ),
271
+ ).toEqual([2, 1, 1, 2]);
272
+ });
273
+
274
+ it("keeps drafts in last-edited order", async () => {
275
+ const { app, services } = createTestApp({ authenticated: true });
276
+ app.route("/api/posts", postsApiRoutes);
277
+
278
+ const first = await services.posts.create({
279
+ format: "note",
280
+ bodyMarkdown: "first",
281
+ status: "draft",
282
+ createdAt: 1000,
283
+ updatedAt: 1000,
284
+ });
285
+ const second = await services.posts.create({
286
+ format: "note",
287
+ bodyMarkdown: "second",
288
+ status: "draft",
289
+ createdAt: 2000,
290
+ updatedAt: 2000,
291
+ });
292
+ await services.posts.update(first.id, { bodyMarkdown: "edited" });
293
+
294
+ const res = await app.request("/api/posts?status=draft");
295
+ const body = await res.json();
296
+ expect(body.posts.map((post: { id: string }) => post.id)).toEqual([
297
+ first.id,
298
+ second.id,
299
+ ]);
300
+ expect(body.posts[0].threadPostCount).toBe(0);
301
+ });
302
+
225
303
  it("serializes quote attribution as sourceName/sourceUrl", async () => {
226
304
  const { app, services } = createTestApp({ authenticated: true });
227
305
  app.route("/api/posts", postsApiRoutes);
@@ -4,12 +4,14 @@ import { collectionsApiRoutes } from "../collections.js";
4
4
  import { navItemsApiRoutes } from "../nav-items.js";
5
5
  import { publicArchiveApiRoutes } from "../public/archive.js";
6
6
  import { publicPostsApiRoutes } from "../public/posts.js";
7
+ import { publicThreadsApiRoutes } from "../public/threads.js";
7
8
  import { searchApiRoutes } from "../search.js";
8
9
 
9
10
  function mountPublicReadRoutes(authenticated = false) {
10
11
  const testApp = createTestApp({ authenticated, fts: true });
11
12
  testApp.app.route("/api/public/posts", publicPostsApiRoutes);
12
13
  testApp.app.route("/api/public/archive", publicArchiveApiRoutes);
14
+ testApp.app.route("/api/public/threads", publicThreadsApiRoutes);
13
15
  testApp.app.route("/api/search", searchApiRoutes);
14
16
  testApp.app.route("/api/collections", collectionsApiRoutes);
15
17
  testApp.app.route("/api/nav-items", navItemsApiRoutes);
@@ -21,6 +23,9 @@ describe("public API access setting", () => {
21
23
  "/api/public/posts",
22
24
  "/api/public/posts/missing",
23
25
  "/api/public/archive",
26
+ "/api/public/threads",
27
+ "/api/public/threads/missing",
28
+ "/api/public/threads/missing/posts",
24
29
  ])("returns 404 for %s when the public API is off", async (path) => {
25
30
  const { app, services } = mountPublicReadRoutes();
26
31
  await services.settings.set("PUBLIC_API_ENABLED", "false");
@@ -102,6 +102,110 @@ describe("Search API Routes", () => {
102
102
  expect(body.count).toBe(0);
103
103
  });
104
104
 
105
+ describe("private posts", () => {
106
+ async function seedPrivateThread(
107
+ services: ReturnType<typeof createTestApp>["services"],
108
+ ) {
109
+ const root = await services.posts.create({
110
+ format: "note",
111
+ title: "Secret diary",
112
+ body: tiptapDoc("Private root about lanterns"),
113
+ visibility: "private",
114
+ });
115
+ await services.posts.create({
116
+ format: "note",
117
+ body: tiptapDoc("Private reply about lanterns"),
118
+ replyToId: root.id,
119
+ });
120
+ await services.posts.create({
121
+ format: "note",
122
+ title: "Public notes",
123
+ body: tiptapDoc("Public post about lanterns"),
124
+ });
125
+ }
126
+
127
+ it("leaves out private posts and replies in a private Thread for anonymous callers", async () => {
128
+ const { app, services } = createTestApp({
129
+ authenticated: false,
130
+ fts: true,
131
+ });
132
+ app.route("/api/search", searchApiRoutes);
133
+ await seedPrivateThread(services);
134
+
135
+ const res = await app.request("/api/search?q=lanterns");
136
+ expect(res.status).toBe(200);
137
+ const body = await res.json();
138
+ expect(body.count).toBe(1);
139
+ expect(body.results[0].title).toBe("Public notes");
140
+
141
+ const titleRes = await app.request("/api/search?q=Secret");
142
+ const titleBody = await titleRes.json();
143
+ expect(titleBody.count).toBe(0);
144
+ expect(JSON.stringify(titleBody)).not.toContain("Secret diary");
145
+ });
146
+
147
+ it("answers a signed-in caller the same way", async () => {
148
+ const { app, services } = createTestApp({
149
+ authenticated: true,
150
+ fts: true,
151
+ });
152
+ app.route("/api/search", searchApiRoutes);
153
+ await seedPrivateThread(services);
154
+
155
+ const res = await app.request("/api/search?q=lanterns");
156
+ const body = await res.json();
157
+ expect(body.count).toBe(1);
158
+ expect(body.results[0].title).toBe("Public notes");
159
+ });
160
+ });
161
+
162
+ describe("limit", () => {
163
+ async function seedMatches(
164
+ services: ReturnType<typeof createTestApp>["services"],
165
+ ) {
166
+ for (let i = 0; i < 3; i++) {
167
+ await services.posts.create({
168
+ format: "note",
169
+ body: tiptapDoc(`Lantern note number ${i}`),
170
+ });
171
+ }
172
+ }
173
+
174
+ it.each(["-1", "0", "-500"])(
175
+ "raises limit=%s to one result",
176
+ async (limit) => {
177
+ const { app, services } = createTestApp({ fts: true });
178
+ app.route("/api/search", searchApiRoutes);
179
+ await seedMatches(services);
180
+
181
+ const res = await app.request(`/api/search?q=lantern&limit=${limit}`);
182
+ expect(res.status).toBe(200);
183
+ const body = await res.json();
184
+ expect(body.count).toBe(1);
185
+ },
186
+ );
187
+
188
+ it("uses the default for a limit that isn't a number", async () => {
189
+ const { app, services } = createTestApp({ fts: true });
190
+ app.route("/api/search", searchApiRoutes);
191
+ await seedMatches(services);
192
+
193
+ const res = await app.request("/api/search?q=lantern&limit=abc");
194
+ const body = await res.json();
195
+ expect(body.count).toBe(3);
196
+ });
197
+
198
+ it("keeps a limit within range as given", async () => {
199
+ const { app, services } = createTestApp({ fts: true });
200
+ app.route("/api/search", searchApiRoutes);
201
+ await seedMatches(services);
202
+
203
+ const res = await app.request("/api/search?q=lantern&limit=2");
204
+ const body = await res.json();
205
+ expect(body.count).toBe(2);
206
+ });
207
+ });
208
+
105
209
  it("does not require authentication", async () => {
106
210
  const { app } = createTestApp({ authenticated: false, fts: true });
107
211
  app.route("/api/search", searchApiRoutes);