Public: anyone can read this; the crew can change it.
/explore has a JSON form: the same ranked rows and filters as the page, for an agent #15773
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/15744-explore-has-a-json-form-the-same-ranked → main 0 commits fork 2 threads · 2 unresolved
16 files
changed +298
−90
docs/features/explore.md +4
| @@ -128,3 +128,7 @@ than that, so a 5,000-character paste does not bloat the page. | ||
| 128 | 128 | ## A picture beside each app |
| 129 | 129 | |
| 130 | 130 | Each app row leads with a small picture of its newest public look, so you see what it is before you read about it. An app with no look, or a private one, shows a box with its initial. The terminal's explore list has no pictures. |
| 131 | ||
| 132 | ## A JSON form for an agent (#15744) | |
| 133 | ||
| 134 | `GET /explore.json` answers the page's rows for the page's one filter line (`readExploreLine`; the same words in `q`, or the separate parameters `kind`, `sort`, `updated`, `owner` and the rest). The answer is `{ query, filters, items, next_cursor }`: `filters` names what the line set (`sort` always; `kind`, `text`, `updated`, `owner`, `forks`, `ships`, `live`, `mine`, `template`, `archived` when set), and each app row carries `score_parts` (`forks`, `ships`, `likes`, `fresh`, `use`, `quiet` (0, or the drop a long-quiet app takes), each as the ranking weighs it, and `total`, their sum, within a rounding of the row's `score`). A word the explorer does not take is a 422 naming it (`unknown_filter` for a word in `q`, `invalid` with `field` for a parameter); rows are the ones this viewer may see, so a private app never appears for a stranger. `GET /api/v1/explore` is the same list without `filters` and `score_parts`. No new MCP tool: the `explore` tool already takes the same line. |
src/actions/explore.ts +39 −3
| @@ -23,8 +23,8 @@ import { appsForRepos } from "../core/apps.ts"; | ||
| 23 | 23 | import { markOf, type Mark } from "../core/marks.ts"; |
| 24 | 24 | import { |
| 25 | 25 | DEFAULT_WEIGHTS, |
| 26 | frontScore, | |
| 27 | 26 | frontSignals, |
| 27 | frontTerms, | |
| 28 | 28 | frontWeights, |
| 29 | 29 | SIGNAL_DAYS, |
| 30 | 30 | type FrontSignals, |
| @@ -598,6 +598,8 @@ export interface ExploreRow { | ||
| 598 | 598 | /** When the app was made (a person: their newest app); read only for `sort:new`. */ |
| 599 | 599 | readonly createdAt?: string; |
| 600 | 600 | readonly score: number; |
| 601 | /** An app's score, term by term, unrounded: `score` is their sum (`scoreParts` reads it). */ | |
| 602 | readonly terms?: Record<WhySignal | "quiet", number>; | |
| 601 | 603 | /** An app's repository, for "Make it yours". */ |
| 602 | 604 | readonly repo?: ExploreRepo; |
| 603 | 605 | /** A person's mark, from their account (`core/marks.ts`): the owner's, never a typed one. */ |
| @@ -713,7 +715,7 @@ export async function explore( | ||
| 713 | 715 | export function rowsWithWhy(app: App, query: ExploreQuery, items: readonly ExploreRow[]): (ExploreRow & { why?: string; figures?: string; forks?: number; ships?: number; likes?: number; updatedAt?: string | null; quiet?: string })[] { |
| 714 | 716 | const weights = frontWeights(app.db); |
| 715 | 717 | const now = Date.now(); |
| 716 | return items.map((row) => { | |
| 718 | return items.map(({ terms: _terms, ...row }) => { | |
| 717 | 719 | const why = whyOf(row, query.sort, now, weights); |
| 718 | 720 | const figures = figuresOf(row, now, query.sort); |
| 719 | 721 | // An app row says its numbers flat as well, read from the same `numbers` and `shippedAt` the |
| @@ -726,6 +728,37 @@ export function rowsWithWhy(app: App, query: ExploreQuery, items: readonly Explo | ||
| 726 | 728 | }); |
| 727 | 729 | } |
| 728 | 730 | |
| 731 | /** | |
| 732 | * The terms of an app row's score, to three places, with `total` their sum, so the parts add up | |
| 733 | * to the total exactly; `total` is within a rounding of the row's `score`, which is the same | |
| 734 | * terms unrounded. Rows that are not apps have none. | |
| 735 | */ | |
| 736 | export function scoreParts(row: ExploreRow): Record<WhySignal | "quiet" | "total", number> | undefined { | |
| 737 | if (row.terms === undefined) return undefined; | |
| 738 | const r = (x: number): number => Math.round(x * 1000) / 1000; | |
| 739 | const t = row.terms; | |
| 740 | const parts = { forks: r(t.forks), ships: r(t.ships), likes: r(t.likes), fresh: r(t.fresh), use: r(t.use), quiet: r(t.quiet) }; | |
| 741 | return { ...parts, total: r(parts.forks + parts.ships + parts.likes + parts.fresh + parts.use + parts.quiet) }; | |
| 742 | } | |
| 743 | ||
| 744 | /** | |
| 745 | * The filters the line set, by the words the line uses; those left at their default are left out. | |
| 746 | */ | |
| 747 | export function exploreFilters(q: ExploreQuery): Record<string, string | number | boolean> { | |
| 748 | const out: Record<string, string | number | boolean> = { sort: q.sort }; | |
| 749 | if (q.kind !== "all") out.kind = q.kind; | |
| 750 | if (q.text !== "") out.text = q.text; | |
| 751 | if (q.archived) out.archived = true; | |
| 752 | if (q.updated !== "all") out.updated = q.updated; | |
| 753 | if (q.owner !== undefined) out.owner = q.owner; | |
| 754 | if (q.forks !== undefined) out.forks = q.forks; | |
| 755 | if (q.ships !== undefined) out.ships = q.ships; | |
| 756 | if (q.live !== undefined) out.live = q.live; | |
| 757 | if (q.mine !== undefined) out.mine = q.mine; | |
| 758 | if (q.template !== undefined) out.template = q.template; | |
| 759 | return out; | |
| 760 | } | |
| 761 | ||
| 729 | 762 | export interface ExplorePage { |
| 730 | 763 | readonly items: readonly ExploreRow[]; |
| 731 | 764 | /** Pass back as `cursor` for the page after; null on the last. */ |
| @@ -954,6 +987,8 @@ function rank( | ||
| 954 | 987 | const s = told(repo); |
| 955 | 988 | const liked = likes.get(repo.id) ?? 0; |
| 956 | 989 | const canCopy = copyable(repo); |
| 990 | const t = frontTerms(s, now, weights); | |
| 991 | const terms = { forks: t.forks, ships: t.ships, likes: LIKE_WEIGHT * Math.log1p(liked), fresh: t.fresh, use: t.use, quiet: isQuiet(s.shippedAt, now) ? -QUIET_DROP : 0 }; | |
| 957 | 992 | return { |
| 958 | 993 | kind: "app", |
| 959 | 994 | name: `${repo.ownerName}/${repo.name}`, |
| @@ -968,7 +1003,8 @@ function rank( | ||
| 968 | 1003 | }, |
| 969 | 1004 | shippedAt: s.shippedAt, |
| 970 | 1005 | ...(dates?.get(repo.id) === undefined ? {} : { createdAt: dates.get(repo.id)!.createdAt }), |
| 971 | score: frontScore(s, now, weights) + LIKE_WEIGHT * Math.log1p(liked) - (isQuiet(s.shippedAt, now) ? QUIET_DROP : 0), | |
| 1006 | score: t.forks + t.ships + t.use + t.fresh + terms.likes + terms.quiet, | |
| 1007 | terms, | |
| 972 | 1008 | repo: { |
| 973 | 1009 | owner: repo.ownerName, |
| 974 | 1010 | name: repo.name, |
src/contract/openapi/routes/getExploreJson.ts added +3
| @@ -0,0 +1,3 @@ | ||
| 1 | import { limitTo, type Route } from "../shared.ts"; | |
| 2 | ||
| 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: { q: "string", cursor: "string", limit: limitTo(100), sort: "string", kind: "string" } }; |
src/contract/openapi/routes/index.ts +1
| @@ -265,6 +265,7 @@ export { route as getApiV1UsersUsernameRepos } from "./getApiV1UsersUsernameRepo | ||
| 265 | 265 | export { route as getApiV1UsersUsernameSignins } from "./getApiV1UsersUsernameSignins.ts"; |
| 266 | 266 | export { route as getApiV1Version } from "./getApiV1Version.ts"; |
| 267 | 267 | export { route as getContractOpenapiJson } from "./getContractOpenapiJson.ts"; |
| 268 | export { route as getExploreJson } from "./getExploreJson.ts"; | |
| 268 | 269 | export { route as getHealth } from "./getHealth.ts"; |
| 269 | 270 | export { route as getMetrics } from "./getMetrics.ts"; |
| 270 | 271 | export { route as getOembed } from "./getOembed.ts"; |
src/contract/tags.ts +1
| @@ -69,6 +69,7 @@ const ALIAS: Readonly<Record<string, string>> = { | ||
| 69 | 69 | thoughts: "feed", |
| 70 | 70 | share: "feed", |
| 71 | 71 | explore: "feed", |
| 72 | "explore.json": "feed", | |
| 72 | 73 | front: "feed", |
| 73 | 74 | search: "feed", |
| 74 | 75 | family: "forges", |
src/core/front.ts +20 −11
| @@ -183,22 +183,31 @@ export function setFrontWeights(db: Database, weights: FrontWeights, by: string) | ||
| 183 | 183 | * thousand awake hours do not drown everything else; freshness fades to |
| 184 | 184 | * nothing over the signal window. |
| 185 | 185 | */ |
| 186 | export function frontTerms( | |
| 187 | s: FrontSignals, | |
| 188 | now = Date.now(), | |
| 189 | w: FrontWeights = DEFAULT_WEIGHTS, | |
| 190 | ): { forks: number; ships: number; use: number; fresh: number } { | |
| 191 | const days = | |
| 192 | s.shippedAt === null | |
| 193 | ? Infinity | |
| 194 | : Math.max(0, (now - Date.parse(s.shippedAt)) / 86_400_000); | |
| 195 | return { | |
| 196 | forks: w.forks * Math.log1p(s.forks), | |
| 197 | ships: w.ships * Math.log1p(s.ships), | |
| 198 | use: w.use * Math.log1p(s.awakeHours), | |
| 199 | fresh: w.fresh * Math.max(0, 1 - days / SIGNAL_DAYS), | |
| 200 | }; | |
| 201 | } | |
| 202 | ||
| 203 | /** The sum of `frontTerms`: the one number the ranking sorts by. */ | |
| 186 | 204 | export function frontScore( |
| 187 | 205 | s: FrontSignals, |
| 188 | 206 | now = Date.now(), |
| 189 | 207 | w: FrontWeights = DEFAULT_WEIGHTS, |
| 190 | 208 | ): number { |
| 191 | const days = | |
| 192 | s.shippedAt === null | |
| 193 | ? Infinity | |
| 194 | : Math.max(0, (now - Date.parse(s.shippedAt)) / 86_400_000); | |
| 195 | const fresh = Math.max(0, 1 - days / SIGNAL_DAYS); | |
| 196 | return ( | |
| 197 | w.forks * Math.log1p(s.forks) + | |
| 198 | w.ships * Math.log1p(s.ships) + | |
| 199 | w.use * Math.log1p(s.awakeHours) + | |
| 200 | w.fresh * fresh | |
| 201 | ); | |
| 209 | const t = frontTerms(s, now, w); | |
| 210 | return t.forks + t.ships + t.use + t.fresh; | |
| 202 | 211 | } |
| 203 | 212 | |
| 204 | 213 | /** Near the top, at most this many of one owner's apps. */ |
src/core/reserved.ts +1
| @@ -137,6 +137,7 @@ export const SYSTEM_NAMES: readonly string[] = [ | ||
| 137 | 137 | "maintenance.json", |
| 138 | 138 | "changelog.atom", |
| 139 | 139 | "explore.atom", |
| 140 | "explore.json", | |
| 140 | 141 | "feed.json", |
| 141 | 142 | "sw.js", |
| 142 | 143 | "offline", |
src/http/api.ts +2 −74
| @@ -129,8 +129,6 @@ import { watchMilestone } from "../actions/watches.ts"; | ||
| 129 | 129 | import { THOUGHT_MAX, keepThought } from "../actions/thought.ts"; |
| 130 | 130 | import { SEARCH_LIMIT_MAX, search, searchRefusal, searchWithin, type SearchPhase } from "../actions/search.ts"; |
| 131 | 131 | import { runRepos } from "./run_gate.ts"; |
| 132 | import { writeStamp } from "../core/write_clock.ts"; | |
| 133 | import { listChildren } from "../actions/spawn.ts"; | |
| 134 | 132 | import { |
| 135 | 133 | commitToBranch, |
| 136 | 134 | createRepo, |
| @@ -357,19 +355,7 @@ import { | ||
| 357 | 355 | tryAgain, |
| 358 | 356 | retryAfterOf, |
| 359 | 357 | } from "./respond.ts"; |
| 360 | import { | |
| 361 | explorePage, | |
| 362 | rowsWithWhy, | |
| 363 | cursorFits, | |
| 364 | type ExploreRow, | |
| 365 | exploreLine, | |
| 366 | exploreNote, | |
| 367 | exploreSuggestion, | |
| 368 | readExploreLine, | |
| 369 | exploreLineFrom, | |
| 370 | badExploreParam, | |
| 371 | EXPLORE_PARAMS, | |
| 372 | } from "../actions/explore.ts"; | |
| 358 | import { exploreApi } from "./explore_json.ts"; | |
| 373 | 359 | import { frontInput, frontJson, setFront } from "../actions/front.ts"; |
| 374 | 360 | import { COPIES_PER_DAY, makeItYours } from "../actions/make_it_yours.ts"; |
| 375 | 361 | import { passportRoutes } from "./passport_edge.ts"; |
| @@ -3710,65 +3696,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo | ||
| 3710 | 3696 | }); |
| 3711 | 3697 | |
| 3712 | 3698 | // Explore (#607): the rows /explore shows, for the same one line. |
| 3713 | router.add("GET", "/api/v1/explore", async (ctx) => { | |
| 3714 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 3715 | // One rule: whatever the explorer does not take is 422, naming the field and the allowed | |
| 3716 | // values: `limit` (one refusal on every list route), a separate filter parameter, or a word | |
| 3717 | // typed in `q` (`unknown_filter`). | |
| 3718 | const limit = parseLimit(ctx.url.searchParams.get("limit"), 100, 30); | |
| 3719 | if (limit === undefined) return limitRefusal(100, { legacy_error: "invalid" }); | |
| 3720 | if (queryTooLong(ctx.url.searchParams.get("q"))) | |
| 3721 | return json({ error: "invalid", field: "q", message: QUERY_TOO_LONG }, 422); | |
| 3722 | const refused = badExploreParam((name) => ctx.url.searchParams.get(name)); | |
| 3723 | if (refused !== null) return json({ error: "invalid", field: refused.field, message: refused.message }, 422); | |
| 3724 | const line = exploreLineFrom((name) => ctx.url.searchParams.get(name)); | |
| 3725 | const { query, unknown } = readExploreLine(line); | |
| 3726 | for (const field of EXPLORE_PARAMS) { | |
| 3727 | const given = ctx.url.searchParams.get(field); | |
| 3728 | if (given !== null && given.trim() !== "" && unknown.some((w) => w.toLowerCase().startsWith(`${field}:`))) | |
| 3729 | return json({ error: "invalid", field, message: exploreNote(unknown) }, 422); | |
| 3730 | } | |
| 3731 | const suggest = exploreSuggestion(line); | |
| 3732 | if (unknown.length > 0) | |
| 3733 | return json({ error: "unknown_filter", message: exploreNote(unknown), field: "q", ...(suggest === undefined ? {} : { suggest: suggest.line }) }, 422); | |
| 3734 | const mine = runRepos(ctx.app, ctx.auth); | |
| 3735 | // A run token is shown only the rows of its own repositories; the cut | |
| 3736 | // and the cursor are made from those rows alone. | |
| 3737 | const visible = | |
| 3738 | mine === undefined | |
| 3739 | ? undefined | |
| 3740 | : (row: ExploreRow) => | |
| 3741 | row.repo !== undefined && | |
| 3742 | mine.some((r) => r.ownerName.toLowerCase() === row.repo!.owner.toLowerCase() && r.name.toLowerCase() === row.repo!.name.toLowerCase()); | |
| 3743 | // The tag names the line, the cursor, the viewer and the forge's write clock | |
| 3744 | // (which moves on any like, fork, push or visibility change), and no clock | |
| 3745 | // for the ranking, so the tag is deterministic. Freshness ranks | |
| 3746 | // drift only by age, so a repeat may keep an order a little behind until | |
| 3747 | // the next write moves the clock. A repeat is answered before the explore | |
| 3748 | // phase runs, and only for a cursor that parses (`*` must not hide a 400). | |
| 3749 | const stamp = writeStamp(ctx.app.db); | |
| 3750 | let headers: Record<string, string> = {}; | |
| 3751 | const cursor = ctx.url.searchParams.get("cursor"); | |
| 3752 | if (cursor !== null && !cursorFits(cursor, query)) | |
| 3753 | return cursorRefusal("cursor is the next_cursor of a page before"); | |
| 3754 | if (stamp !== undefined) { | |
| 3755 | const viewer = ctx.auth.user === undefined ? "anonymous" : `${ctx.auth.user.id}${ctx.auth.user.isAdmin ? ":admin" : ""}`; | |
| 3756 | const confined = mine === undefined ? "" : mine.map((r) => r.id).join(","); | |
| 3757 | const children = ctx.auth.user?.isAdmin === true ? JSON.stringify((await listChildren(ctx.app)).map((c) => [c.name, c.done])) : ""; | |
| 3758 | const etag = weakEtag( | |
| 3759 | [exploreLine(query), cursor ?? "", String(limit), viewer, confined, stamp, children].join("\n"), | |
| 3760 | ); | |
| 3761 | headers = { etag, "cache-control": "private, no-cache", vary: "authorization, cookie" }; | |
| 3762 | if (holds(ctx.request, etag)) return new Response(null, { status: 304, headers }); | |
| 3763 | } | |
| 3764 | const page = await timePhaseAsync(ctx.request, "explore", () => | |
| 3765 | explorePage(ctx.app, ctx.auth.user, query, cursor, visible, undefined, limit), | |
| 3766 | ); | |
| 3767 | if (page === null) | |
| 3768 | return cursorRefusal("cursor is the next_cursor of a page before"); | |
| 3769 | const items = rowsWithWhy(ctx.app, query, page.items); | |
| 3770 | return timePhase(ctx.request, "render", () => json({ query: exploreLine(query), ...(unknown.length === 0 ? {} : { note: exploreNote(unknown) }), ...(suggest === undefined ? {} : { suggest: suggest.line }), items, next_cursor: page.nextCursor }, 200, headers)); | |
| 3771 | }); | |
| 3699 | router.add("GET", "/api/v1/explore", (ctx) => exploreApi(ctx)); | |
| 3772 | 3700 | |
| 3773 | 3701 | // Make it yours (#606): a fork with its app, planned unless dryRun is |
| 3774 | 3702 | // false; the answer names the copy and what was and was not copied. |
src/http/explore_json.ts added +96
| @@ -0,0 +1,96 @@ | ||
| 1 | /** | |
| 2 | * GET /api/v1/explore and GET /explore.json (#15744): the page's rows for the page's one filter | |
| 3 | * line, read by the same `readExploreLine`. The `.json` form adds each row's score parts and the | |
| 4 | * filters read, so an agent ranks and filters the way a person does. | |
| 5 | */ | |
| 6 | import type { Ctx } from "./context.ts"; | |
| 7 | import { json } from "./respond.ts"; | |
| 8 | import { cursorRefusal, limitRefusal, parseLimit } from "../contract/page_query.ts"; | |
| 9 | import { queryTooLong, QUERY_TOO_LONG } from "../core/query_limit.ts"; | |
| 10 | import { runRepos } from "./run_gate.ts"; | |
| 11 | import { writeStamp } from "../core/write_clock.ts"; | |
| 12 | import { listChildren } from "../actions/spawn.ts"; | |
| 13 | import { holds, weakEtag } from "./etag.ts"; | |
| 14 | import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../core/route_timing.ts"; | |
| 15 | import { | |
| 16 | explorePage, | |
| 17 | rowsWithWhy, | |
| 18 | cursorFits, | |
| 19 | type ExploreRow, | |
| 20 | exploreLine, | |
| 21 | exploreNote, | |
| 22 | exploreSuggestion, | |
| 23 | readExploreLine, | |
| 24 | exploreLineFrom, | |
| 25 | badExploreParam, | |
| 26 | exploreFilters, | |
| 27 | scoreParts, | |
| 28 | EXPLORE_PARAMS, | |
| 29 | } from "../actions/explore.ts"; | |
| 30 | ||
| 31 | /** `GET /api/v1/explore`: the page's rows, as the API and the MCP send them. */ | |
| 32 | export const exploreApi = (ctx: Ctx): Promise<Response> => answer(ctx, "list"); | |
| 33 | ||
| 34 | /** `GET /explore.json`: the same rows with each app's score parts and the filters read. */ | |
| 35 | export const exploreJson = (ctx: Ctx): Promise<Response> => answer(ctx, "detail"); | |
| 36 | ||
| 37 | async function answer(ctx: Ctx, shape: "list" | "detail"): Promise<Response> { | |
| 38 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 39 | // One rule: whatever the explorer does not take is 422, naming the field and the allowed | |
| 40 | // values: `limit` (one refusal on every list route), a separate filter parameter, or a word | |
| 41 | // typed in `q` (`unknown_filter`). | |
| 42 | const limit = parseLimit(ctx.url.searchParams.get("limit"), 100, 30); | |
| 43 | if (limit === undefined) return limitRefusal(100, { legacy_error: "invalid" }); | |
| 44 | if (queryTooLong(ctx.url.searchParams.get("q"))) | |
| 45 | return json({ error: "invalid", field: "q", message: QUERY_TOO_LONG }, 422); | |
| 46 | const refused = badExploreParam((name) => ctx.url.searchParams.get(name)); | |
| 47 | if (refused !== null) return json({ error: "invalid", field: refused.field, message: refused.message }, 422); | |
| 48 | const line = exploreLineFrom((name) => ctx.url.searchParams.get(name)); | |
| 49 | const { query, unknown } = readExploreLine(line); | |
| 50 | for (const field of EXPLORE_PARAMS) { | |
| 51 | const given = ctx.url.searchParams.get(field); | |
| 52 | if (given !== null && given.trim() !== "" && unknown.some((w) => w.toLowerCase().startsWith(`${field}:`))) | |
| 53 | return json({ error: "invalid", field, message: exploreNote(unknown) }, 422); | |
| 54 | } | |
| 55 | const suggest = exploreSuggestion(line); | |
| 56 | if (unknown.length > 0) | |
| 57 | return json({ error: "unknown_filter", message: exploreNote(unknown), field: "q", ...(suggest === undefined ? {} : { suggest: suggest.line }) }, 422); | |
| 58 | const mine = runRepos(ctx.app, ctx.auth); | |
| 59 | // A run token is shown only the rows of its own repositories; the cut | |
| 60 | // and the cursor are made from those rows alone. | |
| 61 | const visible = | |
| 62 | mine === undefined | |
| 63 | ? undefined | |
| 64 | : (row: ExploreRow) => | |
| 65 | row.repo !== undefined && | |
| 66 | mine.some((r) => r.ownerName.toLowerCase() === row.repo!.owner.toLowerCase() && r.name.toLowerCase() === row.repo!.name.toLowerCase()); | |
| 67 | // The tag names the line, the cursor, the viewer and the forge's write clock | |
| 68 | // (which moves on any like, fork, push or visibility change), and no clock | |
| 69 | // for the ranking, so the tag is deterministic. Freshness ranks | |
| 70 | // drift only by age, so a repeat may keep an order a little behind until | |
| 71 | // the next write moves the clock. A repeat is answered before the explore | |
| 72 | // phase runs, and only for a cursor that parses (`*` must not hide a 400). | |
| 73 | const stamp = writeStamp(ctx.app.db); | |
| 74 | let headers: Record<string, string> = {}; | |
| 75 | const cursor = ctx.url.searchParams.get("cursor"); | |
| 76 | if (cursor !== null && !cursorFits(cursor, query)) | |
| 77 | return cursorRefusal("cursor is the next_cursor of a page before"); | |
| 78 | if (stamp !== undefined) { | |
| 79 | const viewer = ctx.auth.user === undefined ? "anonymous" : `${ctx.auth.user.id}${ctx.auth.user.isAdmin ? ":admin" : ""}`; | |
| 80 | const confined = mine === undefined ? "" : mine.map((r) => r.id).join(","); | |
| 81 | const children = ctx.auth.user?.isAdmin === true ? JSON.stringify((await listChildren(ctx.app)).map((c) => [c.name, c.done])) : ""; | |
| 82 | const etag = weakEtag( | |
| 83 | [shape, exploreLine(query), cursor ?? "", String(limit), viewer, confined, stamp, children].join("\n"), | |
| 84 | ); | |
| 85 | headers = { etag, "cache-control": "private, no-cache", vary: "authorization, cookie" }; | |
| 86 | if (holds(ctx.request, etag)) return new Response(null, { status: 304, headers }); | |
| 87 | } | |
| 88 | const page = await timePhaseAsync(ctx.request, "explore", () => | |
| 89 | explorePage(ctx.app, ctx.auth.user, query, cursor, visible, undefined, limit), | |
| 90 | ); | |
| 91 | if (page === null) | |
| 92 | return cursorRefusal("cursor is the next_cursor of a page before"); | |
| 93 | const rows = rowsWithWhy(ctx.app, query, page.items); | |
| 94 | const items = shape === "detail" ? rows.map((row, i) => ({ ...row, score_parts: scoreParts(page.items[i]!) })) : rows; | |
| 95 | return timePhase(ctx.request, "render", () => json({ query: exploreLine(query), ...(shape === "detail" ? { filters: exploreFilters(query) } : {}), ...(unknown.length === 0 ? {} : { note: exploreNote(unknown) }), ...(suggest === undefined ? {} : { suggest: suggest.line }), items, next_cursor: page.nextCursor }, 200, headers)); | |
| 96 | } |
src/http/marks/explore.json.json added +4
| @@ -0,0 +1,4 @@ | ||
| 1 | { | |
| 2 | "head": "/explore.json", | |
| 3 | "mark": "open" | |
| 4 | } |
src/http/server.ts +3
| @@ -360,6 +360,7 @@ import { HOME_REGIONS } from "../web/studio/home_last.ts"; | ||
| 360 | 360 | import { serviceWorker } from "../web/sw.ts"; |
| 361 | 361 | import { offlinePage } from "../web/pages/offline.ts"; |
| 362 | 362 | import { explorePage } from "../web/studio/explore.ts"; |
| 363 | import { exploreJson } from "./explore_json.ts"; | |
| 363 | 364 | import { isPacksMirror, MIRROR_PUSH_REFUSED } from "../packs/owner.ts"; |
| 364 | 365 | import { packEdit, packNew, packPage, packRepos, packsMirror, packsPage } from "../web/pages/packs.ts"; |
| 365 | 366 | import { |
| @@ -1013,6 +1014,8 @@ export function buildRouter(): Router<Handler> { | ||
| 1013 | 1014 | // Apps and people ranked by real numbers, narrowed in one line (#607). |
| 1014 | 1015 | router.add("GET", "/explore", explorePage); |
| 1015 | 1016 | router.add("GET", "/explore.atom", exploreAtom); |
| 1017 | // The page's JSON form (#15744): the same rows, with each row's score parts and the filters read. | |
| 1018 | router.add("GET", "/explore.json", (ctx) => exploreJson(ctx)); | |
| 1016 | 1019 | // Forge packs: premade forges to deploy, and the way to help build their apps. |
| 1017 | 1020 | router.add("GET", "/packs", packsPage); |
| 1018 | 1021 | router.add("POST", "/packs/mirror", packsMirror); |
test/design-audit.test.ts +1 −1
| @@ -17,7 +17,7 @@ const doc = readFileSync("docs/design/audit.md", "utf8"); | ||
| 17 | 17 | |
| 18 | 18 | /** Routes that answer a file, a fragment, a redirect hop or a callback. */ |
| 19 | 19 | const NOT_PAGES = |
| 20 | /^\/(assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|new\/issue$|events$|system\/stream$|talk\/stream$|settings\/teams\/stream$|sw\.js$|offline$|robots\.txt$|favicon\.ico$|apple-touch-icon(-precomposed)?\.png$|sitemap\.xml$|edition$|oembed$|manifest\.webmanifest$|opensearch\.xml$|llms(-full)?\.txt$|openapi\.json$|releases\.json$|templates\.json$|maintenance\.json$|changelog\.atom$|explore\.atom$|feed\.json$|docs(\/[^/]*)?$|audit\.csv$|settings\/traffic\/scrapes\/export$|fleet\/graph\/live$|fleet\/graph\.csv$|forges\/export\.csv$|settings\/origins\/callback$|broker\/origins\/start$|home\/archived\/|settings\/backups\/live$|api\/v1(\/|$))/; | |
| 20 | /^\/(assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|new\/issue$|events$|system\/stream$|talk\/stream$|settings\/teams\/stream$|sw\.js$|offline$|robots\.txt$|favicon\.ico$|apple-touch-icon(-precomposed)?\.png$|sitemap\.xml$|edition$|oembed$|manifest\.webmanifest$|opensearch\.xml$|llms(-full)?\.txt$|openapi\.json$|releases\.json$|templates\.json$|maintenance\.json$|changelog\.atom$|explore\.(atom|json)$|feed\.json$|docs(\/[^/]*)?$|audit\.csv$|settings\/traffic\/scrapes\/export$|fleet\/graph\/live$|fleet\/graph\.csv$|forges\/export\.csv$|settings\/origins\/callback$|broker\/origins\/start$|home\/archived\/|settings\/backups\/live$|api\/v1(\/|$))/; | |
| 21 | 21 | |
| 22 | 22 | const getRoutes = [ |
| 23 | 23 | ...server.matchAll(/router\.add\(\s*"GET",\s*"([^"]+)"/g), |
test/explore-json.test.ts added +121
| @@ -0,0 +1,121 @@ | ||
| 1 | /** | |
| 2 | * /explore has a JSON form (#15744): `/explore.json` answers the page's rows with each app's score | |
| 3 | * parts and the filters read; the filter line is the page's own; an unknown filter is a 422 naming | |
| 4 | * it; a private app never appears for a stranger. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { createApp, type App } from "../src/app.ts"; | |
| 11 | import { createRepo } from "../src/actions/repos.ts"; | |
| 12 | import { createApp as insertApp } from "../src/core/apps.ts"; | |
| 13 | import { createSession } from "../src/core/sessions.ts"; | |
| 14 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 15 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 16 | import { promote } from "./helpers/members.ts"; | |
| 17 | import { quietLogs } from "./helpers/globals.ts"; | |
| 18 | ||
| 19 | quietLogs(); | |
| 20 | let dir = ""; | |
| 21 | let app: App; | |
| 22 | let servers: Servers; | |
| 23 | ||
| 24 | beforeAll(async () => { | |
| 25 | dir = await mkdtemp(join(tmpdir(), "forge-explore-json-")); | |
| 26 | app = createApp({ dataDir: dir, port: 0 }); | |
| 27 | servers = await serve(app); | |
| 28 | const founder = await createUser(app.db, { origin: "seed", trusted: true, username: "founder", email: "[email protected]", password: "a-long-words-passphrase", adminIfFirst: true }); | |
| 29 | if (!founder.ok) throw new Error("founder"); | |
| 30 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "olive", email: "[email protected]", password: "a-long-words-passphrase" }); | |
| 31 | if (!made.ok) throw new Error("user"); | |
| 32 | promote(app.db, made.value); | |
| 33 | const olive = getUserByName(app.db, "olive")!; | |
| 34 | for (const [name, visibility] of [["garden", "public"], ["secretplot", "private"]] as const) { | |
| 35 | const repo = await createRepo(app, olive, { name, visibility }); | |
| 36 | if (!repo.ok) throw new Error("repo"); | |
| 37 | const rec = insertApp(app.db, { repoId: repo.value.id, slug: `olive-${name}`, access: visibility }); | |
| 38 | if (!rec.ok) throw new Error("app"); | |
| 39 | } | |
| 40 | }, 30_000); | |
| 41 | afterAll(async () => { | |
| 42 | await servers.stop(); | |
| 43 | app.close(); | |
| 44 | await rm(dir, { recursive: true, force: true }); | |
| 45 | }); | |
| 46 | ||
| 47 | const url = (qs: string) => `${servers.url}/explore.json${qs}`; | |
| 48 | ||
| 49 | test("/explore.json answers rows with score parts and the filters read", async () => { | |
| 50 | const res = await fetch(url("?kind=app&sort=forks")); | |
| 51 | expect(res.status).toBe(200); | |
| 52 | expect(res.headers.get("content-type")).toContain("application/json"); | |
| 53 | const body = (await res.json()) as any; | |
| 54 | expect(body.filters).toEqual({ sort: "forks", kind: "app" }); | |
| 55 | const row = body.items.find((r: any) => r.name === "olive/garden"); | |
| 56 | expect(row).toBeDefined(); | |
| 57 | expect(Object.keys(row.score_parts).sort()).toEqual(["forks", "fresh", "likes", "quiet", "ships", "total", "use"]); | |
| 58 | expect(Math.abs(row.score_parts.total - row.score)).toBeLessThanOrEqual(0.0025); | |
| 59 | }); | |
| 60 | ||
| 61 | test("/explore stays the page whatever Accept says, so the edge cache keeps one key", async () => { | |
| 62 | for (const accept of ["application/json", "text/html"]) { | |
| 63 | const page = await fetch(`${servers.url}/explore`, { headers: { accept } }); | |
| 64 | expect(page.headers.get("content-type")).toContain("text/html"); | |
| 65 | } | |
| 66 | expect((await fetch(url(""))).headers.get("vary")).not.toContain("Accept,"); | |
| 67 | }); | |
| 68 | ||
| 69 | test("the parts add up to the total exactly, and the total is within a rounding of the score", async () => { | |
| 70 | const body = (await (await fetch(url("?kind=app"))).json()) as any; | |
| 71 | const apps = body.items.filter((r: any) => r.score_parts !== undefined); | |
| 72 | expect(apps.length).toBeGreaterThan(0); | |
| 73 | for (const r of apps) { | |
| 74 | const p = r.score_parts; | |
| 75 | const sum = Math.round((p.forks + p.ships + p.likes + p.fresh + p.use + p.quiet) * 1000) / 1000; | |
| 76 | expect(p.total).toBe(sum); | |
| 77 | expect(Math.abs(p.total - r.score)).toBeLessThanOrEqual(0.0025); | |
| 78 | } | |
| 79 | }); | |
| 80 | ||
| 81 | test("/explore.json and /api/v1/explore never share a 304", async () => { | |
| 82 | const detail = await fetch(url("?kind=app")); | |
| 83 | const list = await fetch(`${servers.url}/api/v1/explore?kind=app`); | |
| 84 | const [d, l] = [detail.headers.get("etag"), list.headers.get("etag")]; | |
| 85 | expect(d).toBeTruthy(); | |
| 86 | expect(l).toBeTruthy(); | |
| 87 | expect(d).not.toBe(l); | |
| 88 | expect((await fetch(url("?kind=app"), { headers: { "if-none-match": d! } })).status).toBe(304); | |
| 89 | expect((await fetch(url("?kind=app"), { headers: { "if-none-match": l! } })).status).toBe(200); | |
| 90 | expect((await fetch(`${servers.url}/api/v1/explore?kind=app`, { headers: { "if-none-match": d! } })).status).toBe(200); | |
| 91 | }); | |
| 92 | ||
| 93 | test("the filter query is the page's own: q words and separate params read the same", async () => { | |
| 94 | const typed = (await (await fetch(url(`?q=${encodeURIComponent("kind:app sort:forks")}`))).json()) as any; | |
| 95 | const param = (await (await fetch(url("?kind=app&sort=forks"))).json()) as any; | |
| 96 | expect(typed.filters).toEqual(param.filters); | |
| 97 | expect(typed.query).toBe(param.query); | |
| 98 | }); | |
| 99 | ||
| 100 | test("an unknown filter is a 422 naming it", async () => { | |
| 101 | const q = await fetch(url(`?q=${encodeURIComponent("sort:zzz")}`)); | |
| 102 | expect(q.status).toBe(422); | |
| 103 | expect(JSON.stringify(await q.json())).toContain("sort:zzz"); | |
| 104 | const sort = await fetch(url("?sort=zzz")); | |
| 105 | expect(sort.status).toBe(422); | |
| 106 | expect(((await sort.json()) as any).field).toBe("sort"); | |
| 107 | }); | |
| 108 | ||
| 109 | test("a private app never appears for a stranger", async () => { | |
| 110 | const body = await (await fetch(url(""))).text(); | |
| 111 | expect(body).toContain("olive/garden"); | |
| 112 | expect(body).not.toContain("secretplot"); | |
| 113 | }); | |
| 114 | ||
| 115 | test("an owner sees their private app; a stranger does not", async () => { | |
| 116 | const olive = getUserByName(app.db, "olive")!; | |
| 117 | const cookie = `forge_session=${createSession(app.db, olive.id).token}`; | |
| 118 | const mine = await (await fetch(url(""), { headers: { cookie } })).text(); | |
| 119 | expect(mine).toContain("secretplot"); | |
| 120 | expect(await (await fetch(url(""))).text()).not.toContain("secretplot"); | |
| 121 | }); |
test/forge-looks.test.ts +1
| @@ -52,6 +52,7 @@ const NOT_A_PAGE: Record<string, string> = { | ||
| 52 | 52 | "/maintenance.json": "JSON rendering of the findings on /maintenance, which is pictured; covered by test/maintenance-json.test.ts", |
| 53 | 53 | "/changelog.atom": "Atom feed of /changelog", |
| 54 | 54 | "/explore.atom": "Atom feed of /explore", |
| 55 | "/explore.json": "JSON form of /explore", | |
| 55 | 56 | "/feed.json": "JSON Feed of /feed", |
| 56 | 57 | "/sitemap.xml": "XML for crawlers", |
| 57 | 58 | "/oembed": "JSON for other sites to build a link card; covered by test/oembed.test.ts", |
test/not-found-asset.test.ts −1
| @@ -98,7 +98,6 @@ const TABLE: [string, number, string, number][] = [ | ||
| 98 | 98 | ["/.well-known/agent.json", 404, "application/json", 400], |
| 99 | 99 | ["/oauth/nothing", 404, "application/json", 400], |
| 100 | 100 | ["/docs.atom", 404, "text/plain", 20], |
| 101 | ["/explore.json", 404, "text/plain", 20], | |
| 102 | 101 | ["/site.webmanifest", 404, "text/plain", 20], |
| 103 | 102 | ["/readme.md", 404, "text/plain", 20], |
| 104 | 103 | ["/logo.svg", 404, "text/plain", 20], |
test/openapi-drift.test.ts +1
| @@ -15,6 +15,7 @@ const NOT_ROUTED: Readonly<Record<string, string>> = { | ||
| 15 | 15 | "POST /mcp": "routed outside /api/v1 (src/http/mcp.ts); the MCP has its own card and tool list", |
| 16 | 16 | "POST /settings/account/close/options": "routed outside /api/v1 (src/http/settings_routes.ts): the close form's passkey challenge, a browser session's JSON (#15619)", |
| 17 | 17 | "GET /oembed": "routed outside /api/v1 (src/http/server.ts, web/standards.ts): the oEmbed endpoint other tools discover from a page's head", |
| 18 | "GET /explore.json": "routed outside /api/v1 (src/http/server.ts, explore_json.ts): the explore page's own JSON form (#15744)", | |
| 18 | 19 | }; |
| 19 | 20 | const NOT_DESCRIBED: Readonly<Record<string, string>> = {}; |
| 20 | 21 |
new above
offline
The body is indented 4 spaces; the repo uses 2. Also this function now serves two routes with a boolean flag. Split the shared part from the detail part, or name the flag.