Public: anyone can read this; the crew can change it.

/explore.json and /api/v1/explore are described in the OpenAPI document with their fields #16011

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/15991-explore-json-and-api-v1-explore-are-desc → main 0 commits fork

  • Merged. mason/15991-explore-json-and-api-v1-explore-are-desc was merged into main as 494c1a4.

Review

Sign in to review this change.
5 files changed +104 −16
src/contract/openapi.ts +13 −14
@@ -138,6 +138,17 @@ function shapesSchema(shapes: Readonly<Record<string, ReplyShape>>, list: boolea
138138 : one;
139139 }
140140
141 /**
142 * A success body's schema: its flat `reply` fields, with a cursor list's `items` and `next_cursor`
143 * from `replyShapes` beside them when a route declares both.
144 */
145 function replySchema(r: Route) {
146 const flat = { type: "object", properties: Object.fromEntries(Object.entries(r.reply ?? {}).map(([k, t]) => [k, schema(t)])) };
147 if (r.replyShapes === undefined) return flat;
148 const shaped = shapesSchema(r.replyShapes, pagesByCursor(r));
149 return r.reply === undefined || !("properties" in shaped) ? shaped : { ...shaped, properties: { ...flat.properties, ...shaped.properties } };
150 }
151
141152 /** The roles each role may act as: an admin is a member, a member is anonymous too. */
142153 const REACHES: Readonly<Record<Role, readonly Role[]>> = {
143154 anonymous: ["anonymous"],
@@ -211,21 +222,9 @@ export function openapi(origin: string, version: string, role: Role): Record<str
211222 responses: {
212223 [String(r.status ?? 200)]: {
213224 description: "Done",
214 ...(r.replyShapes === undefined
225 ...(r.replyShapes === undefined && r.reply === undefined
215226 ? {}
216 : { content: { "application/json": { schema: shapesSchema(r.replyShapes, pagesByCursor(r)) } } }),
217 ...(r.reply === undefined
218 ? {}
219 : {
220 content: {
221 "application/json": {
222 schema: {
223 type: "object",
224 properties: Object.fromEntries(Object.entries(r.reply).map(([k, t]) => [k, schema(t)])),
225 },
226 },
227 },
228 }),
227 : { content: { "application/json": { schema: replySchema(r) } } }),
229228 },
230229 ...Object.fromEntries((r.alsoStatus ?? []).map((c) => [String(c), c >= 400 ? sharedRef("Refused") : c === 304 ? { description: "Not modified: the If-None-Match sent is still current; no body" } : { description: "Done" }])),
231230 ...(pagesByCursor(r) ? { "400": sharedRef("PageRefused") } : readsJsonBody(r) ? { "400": sharedRef("NotJson") } : {}),
src/contract/openapi/explore_reply.ts added +54
@@ -0,0 +1,54 @@
1 /**
2 * The one answer of GET /api/v1/explore and GET /explore.json (#15991), described once so the two
3 * routes cannot drift: `http/explore_json.ts` sends both from one function, and the `.json` form
4 * only adds `filters` and each app's `score_parts`.
5 */
6 import type { ReplyShape } from "./shared.ts";
7
8 /** What every row says, whatever it is. */
9 const ROW = {
10 kind: "string",
11 name: "string",
12 url: "string",
13 description: "string",
14 numbers: "object",
15 shippedAt: "string|null",
16 score: "number",
17 figures: "string",
18 why: "string",
19 };
20
21 const APP = {
22 ...ROW,
23 lately: "object",
24 forks: "integer",
25 ships: "integer",
26 likes: "integer",
27 updatedAt: "string|null",
28 quiet: "string",
29 repo: "object",
30 copyable: "boolean",
31 action: "object",
32 createdAt: "string",
33 };
34
35 const SCORE_PARTS = { score_parts: "object" };
36
37 /** The fields at the top of the answer; `detail` adds the filters read. */
38 export const exploreReply = (detail: boolean): Readonly<Record<string, string>> => ({
39 query: "string",
40 ...(detail ? { filters: "object" } : {}),
41 note: "string",
42 suggest: "string",
43 });
44
45 /** The rows: an app, a person or another forge; `detail` adds an app's score parts. */
46 export const exploreRows = (detail: boolean): Readonly<Record<string, ReplyShape>> => ({
47 app: { says: "A listed app: its counts, shipped time and rank reasons", fields: detail ? { ...APP, ...SCORE_PARTS } : APP },
48 person: { says: "A person, by the ships and forks of their apps in the last 30 days", fields: { ...ROW, lately: "object", mark: "object", createdAt: "string" } },
49 forge: { says: "Another forge", fields: ROW },
50 });
51
52 /** The words both routes say of themselves, so each names the other. */
53 export const exploreSame = (other: string): string =>
54 ` The same answer as \`${other}\`, sent from one handler for the same filter line; \`/explore.json\` adds \`filters\` and each app's \`score_parts\`.`;
src/contract/openapi/routes/getApiV1Explore.ts +2 −1
@@ -1,3 +1,4 @@
11 import { EXPLORE_QUERY, type Route } from "../shared.ts";
2 import { exploreReply, exploreRows, exploreSame } from "../explore_reply.ts";
23
3 export const route: Route = { method: "get", path: "/api/v1/explore", summary: "Explore apps and repositories", detail: "Explore apps and repositories; `q` takes words and `kind:`/`owner:` filters; answers { query, items, next_cursor } (an app item carries forks, ships, likes and updatedAt, the time of its last ship, not of its last push, null when never shipped) (`limit` 1 to 100 rows a page, default 30; next_cursor null on the last; a bad `limit`, `sort` or `kind` is a 422 naming the field); cursor from next_cursor; a bad cursor is a 422 `invalid_cursor`; the answer carries an ETag (cache-control private, no-cache; vary authorization, cookie) that changes when anything listed changes, and a repeat sending it in If-None-Match gets 304 with no body", auth: false, role: "anonymous", alsoStatus: [304, 422], query: EXPLORE_QUERY };
4 export const route: Route = { method: "get", path: "/api/v1/explore", summary: "Explore apps and repositories", detail: "Explore apps and repositories; `q` takes words and `kind:`/`owner:` filters; answers { query, items, next_cursor } (an app item carries forks, ships, likes and updatedAt, the time of its last ship, not of its last push, null when never shipped) (`limit` 1 to 100 rows a page, default 30; next_cursor null on the last; a bad `limit`, `sort` or `kind` is a 422 naming the field); cursor from next_cursor; a bad cursor is a 422 `invalid_cursor`; the answer carries an ETag (cache-control private, no-cache; vary authorization, cookie) that changes when anything listed changes, and a repeat sending it in If-None-Match gets 304 with no body" + exploreSame("/explore.json"), auth: false, role: "anonymous", alsoStatus: [304, 422], query: EXPLORE_QUERY, reply: exploreReply(false), replyShapes: exploreRows(false) };
src/contract/openapi/routes/getExploreJson.ts +2 −1
@@ -1,3 +1,4 @@
11 import { EXPLORE_QUERY, type Route } from "../shared.ts";
2 import { exploreReply, exploreRows, exploreSame } from "../explore_reply.ts";
23
3 export const route: Route = { method: "get", path: "/explore.json", summary: "The explore page as JSON", detail: "The rows /explore shows, for the same filter line (`q` words, or `kind`, `sort`, `updated`, `owner` and the other parameters); answers { query, filters, items, next_cursor } where `filters` names what the line set and each app item carries `score_parts` (forks, ships, likes, fresh, use, quiet, total); a word the explorer does not take is a 422 naming it; a private app appears only to a viewer who may read it", auth: false, role: "anonymous", alsoStatus: [304, 422], query: EXPLORE_QUERY };
4 export const route: Route = { method: "get", path: "/explore.json", summary: "The explore page as JSON", detail: "The rows /explore shows, for the same filter line (`q` words, or `kind`, `sort`, `updated`, `owner` and the other parameters); answers { query, filters, items, next_cursor } where `filters` names what the line set and each app item carries `score_parts` (forks, ships, likes, fresh, use, quiet, total); a word the explorer does not take is a 422 naming it; a private app appears only to a viewer who may read it" + exploreSame("/api/v1/explore"), auth: false, role: "anonymous", alsoStatus: [304, 422], query: EXPLORE_QUERY, reply: exploreReply(true), replyShapes: exploreRows(true) };
test/explore-json.test.ts +33
@@ -119,3 +119,36 @@ test("an owner sees their private app; a stranger does not", async () => {
119119 expect(mine).toContain("secretplot");
120120 expect(await (await fetch(url(""))).text()).not.toContain("secretplot");
121121 });
122
123 /**
124 * A small JSON-schema check for the subset the document uses: type (or a type array), properties,
125 * items, anyOf.
126 */
127 function invalid(value: unknown, s: any, at: string): string[] {
128 if (s.anyOf !== undefined) {
129 const tries = s.anyOf.map((one: any) => invalid(value, one, at));
130 return tries.some((t: string[]) => t.length === 0) ? [] : [`${at}: matches none of ${s.anyOf.map((o: any) => o.title).join(", ")}: ${tries.flat().join("; ")}`];
131 }
132 const kind = value === null ? "null" : Array.isArray(value) ? "array" : Number.isInteger(value) ? "integer" : typeof value;
133 const allowed: string[] = [s.type].flat();
134 const fits = allowed.includes(kind) || (kind === "integer" && allowed.includes("number"));
135 if (!fits) return [`${at}: ${kind} is not ${allowed.join("|")}`];
136 if (kind === "array") return (value as unknown[]).flatMap((v, i) => invalid(v, s.items ?? {}, `${at}[${i}]`));
137 if (kind !== "object" || s.properties === undefined) return [];
138 return Object.entries(value as Record<string, unknown>).flatMap(([k, v]) => (s.properties[k] === undefined ? [`${at}.${k}: not described`] : invalid(v, s.properties[k], `${at}.${k}`)));
139 }
140
141 test("both explore paths are described as one answer, and the answers fit the described schema", async () => {
142 const doc = (await (await fetch(`${servers.url}/contract/openapi.json`)).json()) as any;
143 const schemaOf = (path: string) => doc.paths[path].get.responses["200"].content["application/json"].schema;
144 for (const [path, url, detail] of [["/explore.json", `${servers.url}/explore.json?kind=app`, true], ["/api/v1/explore", `${servers.url}/api/v1/explore?kind=app`, false]] as const) {
145 const s = schemaOf(path);
146 expect(Object.keys(s.properties)).toEqual(expect.arrayContaining(["query", "note", "suggest", "items", "next_cursor"]));
147 expect(Boolean(s.properties.filters)).toBe(detail);
148 const body = (await (await fetch(url)).json()) as any;
149 expect(body.items.length).toBeGreaterThan(0);
150 expect(invalid(body, s, "$"), JSON.stringify(body.items[0])).toEqual([]);
151 }
152 expect(doc.paths["/explore.json"].get.description).toContain("/api/v1/explore");
153 expect(doc.paths["/api/v1/explore"].get.description).toContain("/explore.json");
154 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs